Skip to content

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

feat(git): source control panel in the Git tab (#727)

Ruben Lütke1d61bbc65e39
diff --git a/jarvis/agentic_ide/git_changes.py b/jarvis/agentic_ide/git_changes.py
index d7b7a7d52d..f073362b21 100644
--- a/jarvis/agentic_ide/git_changes.py
+++ b/jarvis/agentic_ide/git_changes.py
@@ -332,6 +332,8 @@ def _parse_unified(text: str) -> tuple[list[DiffHunk], int, int, bool, bool]:
return hunks, added, removed, False, truncated
+#: Names the staged copy instead of a commit.
+INDEX_REF = "index"
#: A commit id a caller may name instead of HEAD.
_COMMIT_ID = re.compile(r"^[0-9a-f]{7,64}$")
@@ -340,17 +342,19 @@ def head_text(folder: str | Path, path: str, ref: str = "") -> str | None:
"""One file's text as of the last commit, or of commit ``ref``; None when git has no copy.
``ref`` is a commit id (a pane review compares against the code before an
- agent's first change); anything else is refused.
+ agent's first change) or ``index`` for the staged copy (the Git tab's
+ working-tree diff); anything else is refused.
"""
rel = normalize_workspace_path(folder, path)
root = Path(folder).expanduser()
- if ref and not _COMMIT_ID.match(ref):
+ if ref and ref != INDEX_REF and not _COMMIT_ID.match(ref):
raise ValueError("That is not a commit id.")
- if not _has_head(root):
+ if ref != INDEX_REF and not _has_head(root):
return None
# "./" makes git read the path relative to the workspace folder, which may
# sit below the repository root.
- result = _git(["show", f"{ref or 'HEAD'}:./{rel}"], root)
+ revision = "" if ref == INDEX_REF else ref or "HEAD"
+ result = _git(["show", f"{revision}:./{rel}"], root)
if result is None or result.returncode != 0:
return None
# The editor shows a BOM file's text without its BOM; so must the diff.
diff --git a/jarvis/agentic_ide/scm.py b/jarvis/agentic_ide/scm.py
new file mode 100644
index 0000000000..38a69c646f
--- /dev/null
+++ b/jarvis/agentic_ide/scm.py
@@ -0,0 +1,1152 @@
+"""Source control for the Git tab: the working tree, the index and the history.
+
+The Git tab works on the repository of the open workspace the way a person
+works in a terminal: read what changed (staged, unstaged, untracked, in
+conflict), move files in and out of the index, throw changes away, commit,
+stash, switch and create branches and tags, and read the commit graph.
+
+Every call runs the ``git`` CLI at the repository root with prompts switched
+off and a timeout, so a credential prompt or a hook that waits never hangs the
+app. Reads never take the index lock (``GIT_OPTIONAL_LOCKS=0``): agents run
+their own git in the same checkout. Failures are :class:`GitError` with a
+sentence for the person and a ``code`` the UI can branch on.
+
+Paths in and out of this module are repository-relative POSIX paths; the route
+layer only ever hands in the folder of an open workspace.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+from dataclasses import asdict, dataclass, field
+from pathlib import Path, PurePosixPath
+from typing import Any, Literal
+
+from loguru import logger
+
+from jarvis.agentic_ide.git_ops import GitError
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+_READ_TIMEOUT_S = 15.0
+_WRITE_TIMEOUT_S = 60.0
+# A commit runs the repository's hooks; a push or fetch talks to a server.
+_COMMIT_TIMEOUT_S = 300.0
+_NETWORK_TIMEOUT_S = 180.0
+#: Most files one status answer lists (the rest is reported as ``truncated``).
+MAX_STATUS_FILES = 10_000
+#: Most commits one graph page returns.
+MAX_GRAPH_PAGE = 200
+#: Largest file text a commit diff returns per side.
+MAX_DIFF_TEXT_BYTES = 2 * 1024 * 1024
+#: A commit id, a ref name or ``stash@{n}``: what the UI may name as a revision.
+_REVISION = re.compile(r"^(?!-)[A-Za-z0-9._/@{}^~+-]{1,250}$")
+_HASH = re.compile(r"^[0-9a-f]{4,64}$")
+_UNIT = "\x1f"
+_RECORD = "\x1e"
+
+GraphScope = Literal["auto", "all", "current"]
+
+
+# ------------------------------------------------------------------ plumbing
+
+
+def _run(
+ args: list[str],
+ root: Path,
+ *,
+ timeout: float = _READ_TIMEOUT_S,
+ stdin: str | None = None,
+ read: bool = False,
+) -> subprocess.CompletedProcess[str]:
+ env = dict(os.environ)
+ # Never block on a credential or editor prompt nobody can see.
+ env["GIT_TERMINAL_PROMPT"] = "0"
+ env["GIT_EDITOR"] = "true"
+ env["GIT_SEQUENCE_EDITOR"] = "true"
+ env["GCM_INTERACTIVE"] = "never"
+ if read:
+ env["GIT_OPTIONAL_LOCKS"] = "0"
+ try:
+ return subprocess.run(
+ ["git", "-c", "core.quotePath=false", "-c", "color.ui=false", *args],
+ cwd=str(root),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=timeout,
+ check=False,
+ env=env,
+ input=stdin if stdin is not None else "",
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except FileNotFoundError as exc:
+ raise GitError("Git is not installed.", code="missing") from exc
+ except subprocess.TimeoutExpired as exc:
+ logger.info("Source control: `git {}` did not answer in time in {}", args[0], root)
+ raise GitError("Git did not answer in time.", code="timeout") from exc
+
+
+def _reason(result: subprocess.CompletedProcess[str]) -> str:
+ lines = [
+ line.strip()
+ for line in (result.stderr or result.stdout or "").splitlines()
+ if line.strip() and not line.strip().startswith("hint:")
+ ]
+ return lines[-1] if lines else f"git exited with {result.returncode}"
+
+
+def _ok(
+ args: list[str],
+ root: Path,
+ *,
+ what: str,
+ timeout: float = _WRITE_TIMEOUT_S,
+ stdin: str | None = None,
+ code: str = "failed",
+) -> str:
+ result = _run(args, root, timeout=timeout, stdin=stdin)
+ if result.returncode != 0:
+ raise GitError(f"Git could not {what}: {_reason(result)}", code=code)
+ return result.stdout
+
+
+def _read(args: list[str], root: Path, *, timeout: float = _READ_TIMEOUT_S) -> str | None:
+ result = _run(args, root, timeout=timeout, read=True)
+ return result.stdout if result.returncode == 0 else None
+
+
+def repository_root(folder: str | Path) -> Path:
+ """The top of the repository ``folder`` is in; raises when it is in none."""
+ path = Path(folder).expanduser()
+ if not path.is_dir():
+ raise GitError(f"There is no folder called {path}.", code="no_folder")
+ result = _run(["rev-parse", "--show-toplevel"], path, read=True)
+ if result.returncode != 0:
+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")
+ return Path(result.stdout.strip())
+
+
+def _prefix(folder: Path, root: Path) -> str:
+ """The workspace folder's path inside the repository, with a trailing slash."""
+ result = _run(["rev-parse", "--show-prefix"], folder, read=True)
+ return result.stdout.strip() if result.returncode == 0 else ""
+
+
+def _clean_paths(paths: list[str]) -> list[str]:
+ """Repository-relative paths, refusing anything that would leave the repository."""
+ cleaned: list[str] = []
+ for raw in paths:
+ value = (raw or "").strip().replace("\\", "/")
+ posix = PurePosixPath(value)
+ if (
+ not value
+ or posix.is_absolute()
+ or ".." in posix.parts
+ or re.match(r"^[A-Za-z]:", value)
+ ):
+ raise GitError(f"{raw!r} is not a path inside the repository.", code="invalid")
+ cleaned.append(posix.as_posix())
+ if not cleaned:
+ raise GitError("No files were named.", code="invalid")
+ return cleaned
+
+
+def _pathspec(paths: list[str]) -> str:
+ """Paths for ``--pathspec-from-file=-``: NUL separated, matched literally."""
+ return "\0".join(paths) + "\0"
+
+
+_LITERAL = ["--literal-pathspecs"]
+
+
+def _revision(value: str) -> str:
+ value = (value or "").strip()
+ if not _REVISION.match(value) or ".." in value:
+ raise GitError(f"{value!r} is not a branch, tag or commit.", code="invalid")
+ return value
+
+
+def _branch_name(root: Path, name: str) -> str:
+ value = (name or "").strip()
+ if not value or value.startswith("-"):
+ raise GitError("The branch needs a name.", code="invalid")
+ if _run(["check-ref-format", "--branch", value], root, read=True).returncode != 0:
+ raise GitError(f"{value!r} is not a valid branch name.", code="invalid")
+ return value
+
+
+def _has_head(root: Path) -> bool:
+ return _run(["rev-parse", "--verify", "--quiet", "HEAD"], root, read=True).returncode == 0
+
+
+# ------------------------------------------------------------------ status
+
+
+@dataclass(slots=True)
+class ScmFile:
+ """One changed path in one group of the Source Control list."""
+
+ #: Repository-relative path.
+ path: str
+ #: The status letter shown beside the file: M A D R C T U I or ``!``.
+ letter: str
+ #: ``index_modified`` ``modified`` ``untracked`` ``both_modified`` …
+ status: str
+ #: Where a rename or copy came from.
+ original: str = ""
+
+
+@dataclass(slots=True)
+class ScmStatus:
+ available: bool
+ reason: str = ""
+ root: str = ""
+ #: The workspace folder's path inside the repository ("" or ``sub/``).
+ prefix: str = ""
+ branch: str = ""
+ head: str = ""
+ detached: bool = False
+ unborn: bool = False
+ upstream: str = ""
+ ahead: int = 0
+ behind: int = 0
+ #: ``merge`` | ``rebase`` | ``cherry-pick`` | ``revert`` | ``bisect`` | ""
+ operation: str = ""
+ remotes: list[str] = field(default_factory=list)
+ stashes: int = 0
+ merge: list[ScmFile] = field(default_factory=list)
+ staged: list[ScmFile] = field(default_factory=list)
+ changes: list[ScmFile] = field(default_factory=list)
+ truncated: bool = False
+ #: The last commit's message, for an amend.
+ head_message: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+_INDEX_STATUS = {
+ "M": ("M", "index_modified"),
+ "T": ("T", "index_type_changed"),
+ "A": ("A", "index_added"),
+ "D": ("D", "index_deleted"),
+ "R": ("R", "index_renamed"),
+ "C": ("C", "index_copied"),
+}
+_TREE_STATUS = {
+ "M": ("M", "modified"),
+ "T": ("T", "type_changed"),
+ "D": ("D", "deleted"),
+ "A": ("A", "intent_to_add"),
+ "R": ("R", "intent_to_rename"),
+}
+_CONFLICT_STATUS = {
+ "DD": "both_deleted",
+ "AU": "added_by_us",
+ "UD": "deleted_by_them",
+ "UA": "added_by_them",
+ "DU": "deleted_by_us",
+ "AA": "both_added",
+ "UU": "both_modified",
+}
+
+
+def _operation(root: Path) -> str:
+ git_dir = _read(["rev-parse", "--git-dir"], root)
+ if not git_dir:
+ return ""
+ path = Path(git_dir.strip())
+ if not path.is_absolute():
+ path = root / path
+ if (path / "rebase-merge").exists() or (path / "rebase-apply").exists():
+ return "rebase"
+ if (path / "MERGE_HEAD").exists():
+ return "merge"
+ if (path / "CHERRY_PICK_HEAD").exists():
+ return "cherry-pick"
+ if (path / "REVERT_HEAD").exists():
+ return "revert"
+ if (path / "BISECT_LOG").exists():
+ return "bisect"
+ return ""
+
+
+def parse_status(text: str, status: ScmStatus) -> None:
+ """Fill ``status`` from ``git status --porcelain=v2 -z --branch`` output."""
+ records = text.split("\0")
+ index = 0
+ count = 0
+ while index < len(records):
+ record = records[index]
+ index += 1
+ if not record:
+ continue
+ if record.startswith("# "):
+ key, _, value = record[2:].partition(" ")
+ if key == "branch.oid":
+ status.unborn = value == "(initial)"
+ status.head = "" if status.unborn else value
+ elif key == "branch.head":
+ status.detached = value == "(detached)"
+ status.branch = "" if status.detached else value
+ elif key == "branch.upstream":
+ status.upstream = value
+ elif key == "branch.ab":
+ parts = value.split()
+ if len(parts) == 2:
+ status.ahead = int(parts[0].lstrip("+") or 0)
+ status.behind = int(parts[1].lstrip("-") or 0)
+ continue
+ if count >= MAX_STATUS_FILES:
+ status.truncated = True
+ if record[:1] == "2":
+ index += 1
+ continue
+ kind = record[:1]
+ if kind == "?":
+ status.changes.append(ScmFile(path=record[2:], letter="U", status="untracked"))
+ count += 1
+ elif kind == "!":
+ continue
+ elif kind == "u":
+ fields = record.split(" ", 10)
+ xy, path = fields[1], fields[10]
+ status.merge.append(
+ ScmFile(path=path, letter="!", status=_CONFLICT_STATUS.get(xy, "both_modified"))
+ )
+ count += 1
+ elif kind in {"1", "2"}:
+ limit = 8 if kind == "1" else 9
+ fields = record.split(" ", limit)
+ xy, path = fields[1], fields[limit]
+ original = ""
+ if kind == "2":
+ original = records[index] if index < len(records) else ""
+ index += 1
+ x, y = xy[0], xy[1]
+ if x in _INDEX_STATUS:
+ letter, word = _INDEX_STATUS[x]
+ status.staged.append(
+ ScmFile(
+ path=path,
+ letter=letter,
+ status=word,
+ original=original if x in {"R", "C"} else "",
+ )
+ )
+ count += 1
+ if y in _TREE_STATUS:
+ letter, word = _TREE_STATUS[y]
+ status.changes.append(
+ ScmFile(
+ path=path,
+ letter=letter,
+ status=word,
+ original=original if x not in {"R", "C"} and y == "R" else "",
+ )
+ )
+ count += 1
+
+
+def read_status(folder: str | Path) -> ScmStatus:
+ """The Source Control list of the repository ``folder`` is in."""
+ path = Path(folder).expanduser()
+ try:
+ root = repository_root(path)
+ except GitError as exc: # not a repository: the Git tab shows the reason instead
+ return ScmStatus(available=False, reason=str(exc))
+ status = ScmStatus(available=True, root=str(root), prefix=_prefix(path, root))
+ result = _run(
+ ["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=all", "--find-renames"],
+ root,
+ read=True,
+ timeout=30.0,
+ )
+ if result.returncode != 0:
+ return ScmStatus(
+ available=False, reason=f"Git could not read the status: {_reason(result)}"
+ )
+ parse_status(result.stdout, status)
+ status.operation = _operation(root)
+ remotes = _read(["remote"], root)
+ status.remotes = [line.strip() for line in (remotes or "").splitlines() if line.strip()]
+ stashes = _read(["stash", "list", "--format=%gd"], root)
+ status.stashes = len([line for line in (stashes or "").splitlines() if line.strip()])
+ if not status.unborn:
+ status.head_message = (_read(["log", "-1", "--format=%B"], root) or "").strip()
+ return status
+
+
+# ------------------------------------------------------------------ index
+
+
+def stage(folder: str | Path, paths: list[str]) -> None:
+ """Add the named files to the index; a deleted file is staged as deleted."""
+ root = repository_root(folder)
+ cleaned = _clean_paths(paths)
+ _ok(
+ [*_LITERAL, "add", "--all", "--pathspec-from-file=-", "--pathspec-file-nul"],
+ root,
+ what="stage the changes",
+ stdin=_pathspec(cleaned),
+ )
+
+
+def stage_all(folder: str | Path, *, tracked_only: bool = False) -> None:
+ root = repository_root(folder)
+ _ok(["add", "--update" if tracked_only else "--all"], root, what="stage the changes")
+
+
+def unstage(folder: str | Path, paths: list[str]) -> None:
+ """Take the named files out of the index; the working tree keeps them."""
+ root = repository_root(folder)
+ cleaned = _clean_paths(paths)
+ if _has_head(root):
+ args = ["restore", "--staged", "--pathspec-from-file=-", "--pathspec-file-nul"]
+ else:
+ # Nothing committed yet: there is no HEAD to restore from.
+ args = ["rm", "--cached", "-r", "--quiet", "--pathspec-from-file=-", "--pathspec-file-nul"]
+ _ok([*_LITERAL, *args], root, what="unstage the changes", stdin=_pathspec(cleaned))
+
+
+def unstage_all(folder: str | Path) -> None:
+ root = repository_root(folder)
+ if _has_head(root):
+ _ok(["reset", "--quiet"], root, what="unstage the changes")
+ else:
+ _ok(["rm", "--cached", "-r", "--quiet", "."], root, what="unstage the changes")
+
+
+def _trash(target: Path) -> bool:
+ """Move an untracked file to the system trash; False when there is none."""
+ try:
+ from send2trash import send2trash # type: ignore[import-not-found]
+ except ImportError: # no trash support on this machine: the caller deletes for good
+ return False
+ try:
+ send2trash(str(target))
+ except OSError as exc:
+ logger.info("Source control: the trash refused {}: {}", target.name, exc)
+ return False
+ return True
+
+
+def _remove_untracked(root: Path, rel: str) -> None:
+ target = (root / rel).resolve()
+ try:
+ target.relative_to(root.resolve())
+ except ValueError as exc:
+ raise GitError(f"{rel} is outside the repository.", code="invalid") from exc
+ if not (target.exists() or target.is_symlink()):
+ return
+ if _trash(target):
+ return
+ if target.is_dir() and not target.is_symlink():
+ raise GitError(f"{rel} is a folder; delete it in the Folder tab.", code="invalid")
+ target.unlink()
+
+
+def discard(folder: str | Path, paths: list[str]) -> None:
+ """Throw away the working-tree changes of the named files.
+
+ A tracked file goes back to its staged (or committed) content; an untracked
+ one goes to the system trash (deleted for good where there is no trash).
+ A file that only exists in the index stays staged.
+ """
+ root = repository_root(folder)
+ cleaned = _clean_paths(paths)
+ listed = _run(
+ [*_LITERAL, "ls-files", "-z", "--cached", "--", *cleaned], root, read=True
+ ).stdout.split("\0")
+ tracked = {entry for entry in listed if entry}
+ restore = [path for path in cleaned if path in tracked]
+ untracked = [path for path in cleaned if path not in tracked]
+ if restore:
+ _ok(
+ [*_LITERAL, "restore", "--worktree", "--pathspec-from-file=-", "--pathspec-file-nul"],
+ root,
+ what="discard the changes",
+ stdin=_pathspec(restore),
+ )
+ for rel in untracked:
+ _remove_untracked(root, rel)
+
+
+def discard_all(folder: str | Path, *, untracked: bool) -> None:
+ """Discard every working-tree change; ``untracked`` also removes new files."""
+ root = repository_root(folder)
+ if _run(["ls-files", "--cached", "-z"], root, read=True).stdout:
+ _ok(["restore", "--worktree", "."], root, what="discard the changes")
+ if untracked:
+ listed = _read(["ls-files", "-z", "--others", "--exclude-standard"], root) or ""
+ for rel in [entry for entry in listed.split("\0") if entry]:
+ _remove_untracked(root, rel)
+
+
+def ignore(folder: str | Path, paths: list[str]) -> str:
+ """Append the named files to the repository's ``.gitignore``; returns its path."""
+ root = repository_root(folder)
+ cleaned = _clean_paths(paths)
+ target = root / ".gitignore"
+ existing = target.read_text(encoding="utf-8") if target.exists() else ""
+ known = {line.strip() for line in existing.splitlines()}
+ lines = [f"/{path}" for path in cleaned if f"/{path}" not in known and path not in known]
+ if lines:
+ joiner = "" if not existing or existing.endswith("\n") else "\n"
+ with target.open("a", encoding="utf-8", newline="\n") as handle:
+ handle.write(joiner + "\n".join(lines) + "\n")
+ return ".gitignore"
+
+
+# ------------------------------------------------------------------ commit
+
+
+def commit(
+ folder: str | Path,
+ message: str,
+ *,
+ amend: bool = False,
+ all_changes: bool = False,
+ include_untracked: bool = True,
+ signoff: bool = False,
+ no_verify: bool = False,
+ allow_empty: bool = False,
+) -> str:
+ """Commit the index (or every change, with ``all_changes``). Returns the short id."""
+ root = repository_root(folder)
+ text = (message or "").strip()
+ if not text and not amend:
+ raise GitError("The commit needs a message.", code="invalid")
+ if all_changes:
+ _ok(["add", "--all" if include_untracked else "--update"], root, what="stage the changes")
+ nothing = _run(["diff", "--cached", "--quiet"], root).returncode == 0 and _has_head(root)
+ if nothing and not amend and not allow_empty:
+ raise GitError("There are no staged changes to commit.", code="clean")
+ args = ["commit", "--cleanup=strip"]
+ if amend:
+ args.append("--amend")
+ if signoff:
+ args.append("--signoff")
+ if no_verify:
+ args.append("--no-verify")
+ if allow_empty:
+ args.append("--allow-empty")
+ stdin: str | None = None
+ if text:
+ args.extend(["-F", "-"])
+ stdin = text + "\n"
+ else:
+ args.append("--no-edit")
+ _ok(args, root, what="commit", timeout=_COMMIT_TIMEOUT_S, stdin=stdin)
+ return _ok(["rev-parse", "--short", "HEAD"], root, what="read the new commit").strip()
+
+
+def undo_last_commit(folder: str | Path) -> str:
+ """Undo the last commit and keep its changes staged; returns its message."""
+ root = repository_root(folder)
+ if not _has_head(root):
+ raise GitError("There is no commit to undo.", code="invalid")
+ message = (_read(["log", "-1", "--format=%B"], root) or "").strip()
+ if _run(["rev-parse", "--verify", "--quiet", "HEAD~1"], root, read=True).returncode == 0:
+ _ok(["reset", "--soft", "HEAD~1"], root, what="undo the last commit")
+ else:
+ # The first commit has no parent: drop the branch ref, keep the index.
+ _ok(["update-ref", "-d", "HEAD"], root, what="undo the last commit")
+ return message
+
+
+def continue_operation(folder: str | Path) -> None:
+ """Finish a merge, rebase, cherry-pick or revert once every conflict is staged."""
+ root = repository_root(folder)
+ operation = _operation(root)
+ if not operation or operation == "bisect":
+ raise GitError("Nothing is in progress.", code="invalid")
+ if operation == "merge":
+ _ok(["commit", "--no-edit"], root, what="finish the merge", timeout=_COMMIT_TIMEOUT_S)
+ return
+ _ok(
+ [operation, "--continue"], root, what=f"continue the {operation}", timeout=_COMMIT_TIMEOUT_S
+ )
+
+
+def abort_operation(folder: str | Path) -> None:
+ root = repository_root(folder)
+ operation = _operation(root)
+ if not operation:
+ raise GitError("Nothing is in progress.", code="invalid")
+ if operation == "bisect":
+ _ok(["bisect", "reset"], root, what="end the bisect")
+ return
+ _ok([operation, "--abort"], root, what=f"abort the {operation}")
+
+
+# ------------------------------------------------------------------ remotes
+
+
+def _current_branch(root: Path) -> str:
+ return (_read(["symbolic-ref", "--quiet", "--short", "HEAD"], root) or "").strip()
+
+
+def _upstream(root: Path) -> str:
+ return (
+ _read(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], root) or ""
+ ).strip()
+
+
+def _remotes(root: Path) -> list[str]:
+ return [line.strip() for line in (_read(["remote"], root) or "").splitlines() if line.strip()]
+
+
+def fetch(
+ folder: str | Path, *, remote: str = "", prune: bool = False, all_remotes: bool = False
+) -> None:
+ root = repository_root(folder)
+ args = ["fetch"]
+ if prune:
+ args.append("--prune")
+ if all_remotes or not remote:
+ args.append("--all")
+ else:
+ args.append(_remote_name(root, remote))
+ _ok(args, root, what="fetch", timeout=_NETWORK_TIMEOUT_S, code="network")
+
+
+def pull(folder: str | Path, *, rebase: bool = False, remote: str = "", branch: str = "") -> None:
+ """Pull into the current branch: fast-forward or merge, or ``rebase``.
+
+ A pull that conflicts leaves the merge or rebase in progress; the conflicts
+ then show under Merge Changes, the same as in a terminal.
+ """
+ root = repository_root(folder)
+ if not _current_branch(root):
+ raise GitError("Check out a branch before pulling.", code="detached")
+ args = ["pull", "--rebase" if rebase else "--no-rebase"]
+ if remote:
+ args.append(_remote_name(root, remote))
+ if branch:
+ args.append(_revision(branch))
+ elif not _upstream(root):
+ raise GitError(
+ "This branch has no upstream to pull from. Publish it first.", code="no_upstream"
+ )
+ _ok(args, root, what="pull", timeout=_NETWORK_TIMEOUT_S, code="network")
+
+
+def push(
+ folder: str | Path,
+ *,
+ remote: str = "",
+ force: bool = False,
+ tags: bool = False,
+) -> str:
+ """Push the current branch; the first push (or ``remote``) sets the upstream."""
+ root = repository_root(folder)
+ branch = _current_branch(root)
+ if not branch:
+ raise GitError("Check out a branch before pushing.", code="detached")
+ remotes = _remotes(root)
+ if not remotes:
+ raise GitError("This repository has no remote to push to.", code="no_remote")
+ upstream = _upstream(root)
+ args = ["push"]
+ if force:
+ args.append("--force-with-lease")
+ if tags:
+ args.append("--follow-tags")
+ if upstream and not remote:
+ _ok(args, root, what="push", timeout=_NETWORK_TIMEOUT_S, code="network")
+ return upstream
+ target = (
+ _remote_name(root, remote) if remote else ("origin" if "origin" in remotes else remotes[0])
+ )
+ _ok(
+ [*args, "--set-upstream", target, branch],
+ root,
+ what="push",
+ timeout=_NETWORK_TIMEOUT_S,
+ code="network",
+ )
+ return f"{target}/{branch}"
+
+
+def push_tags(folder: str | Path, *, remote: str = "") -> None:
+ root = repository_root(folder)
+ remotes = _remotes(root)
+ if not remotes:
+ raise GitError("This repository has no remote to push to.", code="no_remote")
+ target = (
+ _remote_name(root, remote) if remote else ("origin" if "origin" in remotes else remotes[0])
+ )
+ _ok(
+ ["push", target, "--tags"],
+ root,
+ what="push the tags",
+ timeout=_NETWORK_TIMEOUT_S,
+ code="network",
+ )
+
+
+def sync(folder: str | Path, *, rebase: bool = False) -> None:
+ """Pull, then push: what the Sync Changes button does."""
+ pull(folder, rebase=rebase)
+ push(folder)
+
+
+def _remote_name(root: Path, remote: str) -> str:
+ name = (remote or "").strip()
+ if name not in _remotes(root):
+ raise GitError(f"There is no remote called {name!r}.", code="not_found")
+ return name
+
+
+def add_remote(folder: str | Path, name: str, url: str) -> None:
+ root = repository_root(folder)
+ value = (name or "").strip()
+ address = (url or "").strip()
+ if not re.match(r"^[A-Za-z0-9._-]{1,100}$", value):
+ raise GitError(
+ "The remote needs a name of letters, digits, dots or dashes.", code="invalid"
+ )
+ if not address or address.startswith("-"):
+ raise GitError("The remote needs a URL.", code="invalid")
+ _ok(["remote", "add", value, address], root, what="add the remote")
+
+
+def remove_remote(folder: str | Path, name: str) -> None:
+ root = repository_root(folder)
+ _ok(["remote", "remove", _remote_name(root, name)], root, what="remove the remote")
+
+
+# ------------------------------------------------------------------ refs
+
+
+@dataclass(slots=True)
+class Ref:
+ #: ``head`` | ``remote`` | ``tag``
+ kind: str
+ name: str
+ commit: str
+ date: int
+ subject: str
+ upstream: str = ""
+
+
+def list_refs(folder: str | Path) -> dict[str, Any]:
+ """Every local branch, remote branch and tag, newest first."""
+ root = repository_root(folder)
+ text = _read(
+ [
+ "for-each-ref",
+ "--sort=-committerdate",
+ f"--format=%(refname){_UNIT}%(objectname:short){_UNIT}%(committerdate:unix)"
+ f"{_UNIT}%(contents:subject){_UNIT}%(upstream:short)",
+ "refs/heads",
+ "refs/remotes",
+ "refs/tags",
+ ],
+ root,
+ )
+ refs: list[Ref] = []
+ for line in (text or "").splitlines():
+ parts = line.split(_UNIT)
+ if len(parts) < 5:
+ continue
+ full, commit_id, date, subject, upstream = parts[:5]
+ if full.startswith("refs/heads/"):
+ kind, name = "head", full[len("refs/heads/") :]
+ elif full.startswith("refs/remotes/"):
+ kind, name = "remote", full[len("refs/remotes/") :]
+ if name.endswith("/HEAD"):
+ continue
+ elif full.startswith("refs/tags/"):
+ kind, name = "tag", full[len("refs/tags/") :]
+ else:
+ continue
+ refs.append(
+ Ref(
+ kind=kind,
+ name=name,
+ commit=commit_id,
+ date=int(date or 0),
+ subject=subject,
+ upstream=upstream,
+ )
+ )
+ return {"current": _current_branch(root), "refs": [asdict(ref) for ref in refs]}
+
+
+def checkout(folder: str | Path, ref: str, *, detached: bool = False) -> str:
+ """Switch to a local branch, a remote branch (tracked locally) or a tag/commit."""
+ root = repository_root(folder)
+ target = _revision(ref)
+ local = _run(["show-ref", "--verify", "--quiet", f"refs/heads/{target}"], root, read=True)
+ if not detached and local.returncode == 0:
+ _ok(["switch", target], root, what=f"switch to {target}")
+ return target
+ remote = _run(["show-ref", "--verify", "--quiet", f"refs/remotes/{target}"], root, read=True)
+ if not detached and remote.returncode == 0:
+ name = target.split("/", 1)[1] if "/" in target else target
+ exists = _run(["show-ref", "--verify", "--quiet", f"refs/heads/{name}"], root, read=True)
+ if exists.returncode == 0:
+ _ok(["switch", name], root, what=f"switch to {name}")
+ else:
+ _ok(["switch", "--track", target], root, what=f"check out {target}")
+ return name
+ _ok(["switch", "--detach", target], root, what=f"check out {target}")
+ return target
+
+
+def create_branch(folder: str | Path, name: str, *, start: str = "", switch: bool = True) -> str:
+ root = repository_root(folder)
+ branch = _branch_name(root, name)
+ base = [_revision(start)] if start else []
+ if switch:
+ _ok(["switch", "-c", branch, *base], root, what="create the branch")
+ else:
+ _ok(["branch", branch, *base], root, what="create the branch")
+ return branch
+
+
+def rename_branch(folder: str | Path, name: str, *, old: str = "") -> str:
+ root = repository_root(folder)
+ branch = _branch_name(root, name)
+ args = ["branch", "-m"] + ([_revision(old)] if old else []) + [branch]
+ _ok(args, root, what="rename the branch")
+ return branch
+
+
+def delete_branch(folder: str | Path, name: str, *, force: bool = False) -> None:
+ root = repository_root(folder)
+ branch = _revision(name)
+ if branch == _current_branch(root):
+ raise GitError("The branch you are on cannot be deleted.", code="current")
+ result = _run(["branch", "-D" if force else "-d", branch], root)
+ if result.returncode != 0:
+ if not force and "not fully merged" in (result.stderr or ""):
+ raise GitError(f"{branch} has commits that are on no other branch.", code="unmerged")
+ raise GitError(f"Git could not delete the branch: {_reason(result)}")
+
+
+def merge(folder: str | Path, ref: str) -> str:
+ """Merge ``ref`` into the current branch; a conflict leaves the merge open."""
+ root = repository_root(folder)
+ result = _run(["merge", "--no-edit", _revision(ref)], root, timeout=_COMMIT_TIMEOUT_S)
+ if result.returncode != 0:
+ if _operation(root) == "merge":
+ return "conflict"
+ raise GitError(f"Git could not merge: {_reason(result)}")
+ return "merged"
+
+
+def rebase(folder: str | Path, ref: str) -> str:
+ """Rebase the current branch onto ``ref``; a conflict leaves the rebase open."""
+ root = repository_root(folder)
+ result = _run(["rebase", _revision(ref)], root, timeout=_COMMIT_TIMEOUT_S)
+ if result.returncode != 0:
+ if _operation(root) == "rebase":
+ return "conflict"
+ raise GitError(f"Git could not rebase: {_reason(result)}")
+ return "rebased"
+
+
+def create_tag(folder: str | Path, name: str, *, message: str = "", ref: str = "") -> None:
+ root = repository_root(folder)
+ tag = (name or "").strip()
+ if (
+ not tag
+ or tag.startswith("-")
+ or _run(["check-ref-format", f"refs/tags/{tag}"], root, read=True).returncode
+ ):
+ raise GitError(f"{tag!r} is not a valid tag name.", code="invalid")
+ args = ["tag"]
+ stdin = None
+ if message.strip():
+ args += ["-a", "-F", "-"]
+ stdin = message.strip() + "\n"
+ args.append(tag)
+ if ref:
+ args.append(_revision(ref))
+ _ok(args, root, what="create the tag", stdin=stdin)
+
+
+def delete_tag(folder: str | Path, name: str) -> None:
+ root = repository_root(folder)
+ _ok(["tag", "-d", _revision(name)], root, what="delete the tag")
+
+
+def cherry_pick(folder: str | Path, commit_id: str) -> str:
+ root = repository_root(folder)
+ result = _run(["cherry-pick", _revision(commit_id)], root, timeout=_COMMIT_TIMEOUT_S)
+ if result.returncode != 0:
+ if _operation(root) == "cherry-pick":
+ return "conflict"
+ raise GitError(f"Git could not cherry-pick: {_reason(result)}")
+ return "picked"
+
+
+def revert(folder: str | Path, commit_id: str) -> str:
+ root = repository_root(folder)
+ result = _run(["revert", "--no-edit", _revision(commit_id)], root, timeout=_COMMIT_TIMEOUT_S)
+ if result.returncode != 0:
+ if _operation(root) == "revert":
+ return "conflict"
+ raise GitError(f"Git could not revert: {_reason(result)}")
+ return "reverted"
+
+
+# ------------------------------------------------------------------ stash
+
+
+def list_stashes(folder: str | Path) -> list[dict[str, Any]]:
+ root = repository_root(folder)
+ text = _read(["stash", "list", f"--format=%gd{_UNIT}%gs{_UNIT}%ct"], root) or ""
+ stashes = []
+ for line in text.splitlines():
+ parts = line.split(_UNIT)
+ if len(parts) == 3:
+ stashes.append({"ref": parts[0], "message": parts[1], "date": int(parts[2] or 0)})
+ return stashes
+
+
+def _stash_ref(value: str) -> str:
+ if not re.match(r"^stash@\{\d{1,5}\}$", value or ""):
+ raise GitError(f"{value!r} is not a stash.", code="invalid")
+ return value
+
+
+def stash(
+ folder: str | Path, *, message: str = "", include_untracked: bool = False, staged: bool = False
+) -> None:
+ root = repository_root(folder)
+ args = ["stash", "push"]
+ if include_untracked:
+ args.append("--include-untracked")
+ if staged:
+ args.append("--staged")
+ if message.strip():
+ args += ["-m", message.strip()]
+ result = _run(args, root, timeout=_WRITE_TIMEOUT_S)
+ if result.returncode != 0:
+ raise GitError(f"Git could not stash: {_reason(result)}")
+ if "No local changes to save" in (result.stdout + result.stderr):
+ raise GitError("There are no local changes to stash.", code="clean")
+
+
+def stash_apply(folder: str | Path, ref: str = "", *, pop: bool = False) -> None:
+ root = repository_root(folder)
+ args = ["stash", "pop" if pop else "apply", "--index"]
+ if ref:
+ args.append(_stash_ref(ref))
+ result = _run(args, root, timeout=_WRITE_TIMEOUT_S)
+ if result.returncode == 0:
+ return
+ # --index fails when the staged part no longer applies; apply the content alone.
+ retry = [part for part in args if part != "--index"]
+ _ok(retry, root, what="apply the stash")
+
+
+def stash_drop(folder: str | Path, ref: str = "", *, everything: bool = False) -> None:
+ root = repository_root(folder)
+ if everything:
+ _ok(["stash", "clear"], root, what="drop the stashes")
+ return
+ _ok(["stash", "drop", *([_stash_ref(ref)] if ref else [])], root, what="drop the stash")
+
+
+# ------------------------------------------------------------------ history
+
+
+@dataclass(slots=True)
+class GraphCommit:
+ id: str
+ parents: list[str]
+ author: str
+ email: str
+ date: int
+ refs: list[str]
+ subject: str
+
+
+def _parse_log(text: str) -> list[GraphCommit]:
+ commits: list[GraphCommit] = []
+ for record in text.split(_RECORD):
+ record = record.strip("\n")
+ if not record:
+ continue
+ parts = record.split(_UNIT)
+ if len(parts) < 7:
+ continue
+ commit_id, parents, author, email, date, refs, subject = parts[:7]
+ commits.append(
+ GraphCommit(
+ id=commit_id,
+ parents=parents.split(),
+ author=author,
+ email=email,
+ date=int(date or 0),
+ refs=[ref.strip() for ref in refs.split(",") if ref.strip()],
+ subject=subject,
+ )
+ )
+ return commits
+
+
+_LOG_FORMAT = f"--format=%H{_UNIT}%P{_UNIT}%an{_UNIT}%ae{_UNIT}%at{_UNIT}%D{_UNIT}%s{_RECORD}"
+
+
+def graph(
+ folder: str | Path, *, scope: GraphScope = "auto", skip: int = 0, limit: int = 50
+) -> dict[str, Any]:
+ """One page of the commit graph, newest first in topological order.
+
+ ``auto`` shows the current branch with its upstream, ``current`` only the
+ branch, ``all`` every branch, remote branch and tag.
+ """
+ root = repository_root(folder)
+ if not _has_head(root):
+ return {
+ "commits": [],
+ "more": False,
+ "head": "",
+ "incoming": [],
+ "outgoing": [],
+ "upstream": "",
+ }
+ size = max(1, min(int(limit), MAX_GRAPH_PAGE))
+ upstream = _upstream(root)
+ if scope == "all":
+ revs = ["--branches", "--remotes", "--tags", "HEAD"]
+ elif scope == "current" or not upstream:
+ revs = ["HEAD"]
+ else:
+ revs = ["HEAD", upstream]
+ text = _read(
+ [
+ "log",
+ "--topo-order",
+ "--decorate=full",
+ _LOG_FORMAT,
+ f"--skip={max(0, int(skip))}",
+ f"-n{size + 1}",
+ *revs,
+ "--",
+ ],
+ root,
+ timeout=30.0,
+ )
+ commits = _parse_log(text or "")
+ head = (_read(["rev-parse", "HEAD"], root) or "").strip()
+ incoming: list[str] = []
+ outgoing: list[str] = []
+ if upstream:
+ incoming = (_read(["rev-list", "--max-count=500", f"HEAD..{upstream}"], root) or "").split()
+ outgoing = (_read(["rev-list", "--max-count=500", f"{upstream}..HEAD"], root) or "").split()
+ return {
+ "commits": [asdict(entry) for entry in commits[:size]],
+ "more": len(commits) > size,
+ "head": head,
+ "upstream": upstream,
+ "incoming": incoming,
+ "outgoing": outgoing,
+ }
+
+
+_NAME_STATUS = {"M": "M", "A": "A", "D": "D", "R": "R", "C": "C", "T": "T", "U": "!"}
+
+
+def commit_details(folder: str | Path, commit_id: str) -> dict[str, Any]:
+ """A commit's full message and the files it changed against its first parent."""
+ root = repository_root(folder)
+ rev = _revision(commit_id)
+ meta = _read(
+ [
+ "show",
+ "-s",
+ f"--format=%H{_UNIT}%P{_UNIT}%an{_UNIT}%ae{_UNIT}%at{_UNIT}%cn{_UNIT}%ct{_UNIT}%B",
+ rev,
+ ],
+ root,
+ )
+ if meta is None:
+ raise GitError(f"There is no commit {commit_id!r}.", code="not_found")
+ parts = meta.split(_UNIT, 7)
+ full, parents = parts[0], parts[1].split()
+ if parents:
+ args = ["diff-tree", "-r", "-z", "-M", "--name-status", parents[0], full]
+ else:
+ args = ["diff-tree", "--no-commit-id", "-r", "-z", "-M", "--name-status", "--root", full]
+ listed = (_read(args, root) or "").split("\0")
+ files: list[dict[str, str]] = []
+ index = 0
+ while index < len(listed):
+ code = listed[index]
+ index += 1
+ if not code:
+ continue
+ letter = _NAME_STATUS.get(code[0], code[0])
+ if letter in {"R", "C"}:
+ original, path = listed[index], listed[index + 1]
+ index += 2
+ else:
+ original, path = "", listed[index]
+ index += 1
+ files.append({"path": path, "letter": letter, "original": original})
+ stat = _read(
+ ["diff", "--shortstat", parents[0], full]
+ if parents
+ else ["show", "--shortstat", "--format=", full],
+ root,
+ )
+ return {
+ "id": full,
+ "parents": parents,
+ "author": parts[2],
+ "email": parts[3],
+ "date": int(parts[4] or 0),
+ "committer": parts[5],
+ "committer_date": int(parts[6] or 0),
+ "message": parts[7].strip() if len(parts) > 7 else "",
+ "files": files,
+ "stat": (stat or "").strip(),
+ }
+
+
+def _blob_text(root: Path, rev: str, path: str) -> tuple[str | None, bool]:
+ """A file's text at ``rev`` (None when it does not exist there) and whether it is binary."""
+ if not rev:
+ return None, False
+ size = _read(["cat-file", "-s", f"{rev}:{path}"], root)
+ if size is None:
+ return None, False
+ if int(size.strip() or 0) > MAX_DIFF_TEXT_BYTES:
+ return "", True
+ result = _run(["show", f"{rev}:{path}"], root, read=True)
+ if result.returncode != 0:
+ return None, False
+ text = result.stdout
+ if "\0" in text:
+ return "", True
+ return text.removeprefix(""), False
+
+
+def commit_file_diff(
+ folder: str | Path, commit_id: str, path: str, *, original: str = ""
+) -> dict[str, Any]:
+ """The two sides of one file in a commit: its first parent's text and the commit's."""
+ root = repository_root(folder)
+ rev = _revision(commit_id)
+ (rel,) = _clean_paths([path])
+ before_path = _clean_paths([original])[0] if original else rel
+ parents = (_read(["rev-list", "--parents", "-n1", rev], root) or "").split()[1:]
+ before, binary_before = _blob_text(root, parents[0] if parents else "", before_path)
+ after, binary_after = _blob_text(root, rev, rel)
+ return {
+ "path": rel,
+ "original_path": before_path,
+ "before": before,
+ "after": after,
+ "binary": binary_before or binary_after,
+ }
diff --git a/jarvis/ui/web/agentic_ide_scm_routes.py b/jarvis/ui/web/agentic_ide_scm_routes.py
new file mode 100644
index 0000000000..3c517d1edf
--- /dev/null
+++ b/jarvis/ui/web/agentic_ide_scm_routes.py
@@ -0,0 +1,491 @@
+"""REST routes for the Git tab's source control (``/api/agentic-ide/git/scm``).
+
+Every route names an open workspace, never a path: the repository is the one
+that workspace's folder is in, so no request can point git elsewhere on the
+machine. Paths in the bodies are repository-relative. Handlers are plain
+``def`` so git runs in the anyio threadpool, never on the event loop.
+
+A failed git call answers 422 with ``{"detail": {"message", "code"}}``, the
+same shape as the rest of the Git tab's routes.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Literal
+
+from fastapi import APIRouter, HTTPException, Query
+from pydantic import BaseModel, Field
+
+from jarvis.agentic_ide import scm
+from jarvis.agentic_ide.git_ops import GitError
+from jarvis.agentic_ide.session import get_registry
+
+router = APIRouter(prefix="/api/agentic-ide/git/scm", tags=["agentic-ide-git"])
+
+
+def _folder(workspace_id: str) -> Path:
+ session = get_registry().get(workspace_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="Workspace not found.")
+ return Path(session.folder)
+
+
+def _fail(exc: GitError) -> HTTPException:
+ return HTTPException(status_code=422, detail={"message": str(exc), "code": exc.code})
+
+
+class WorkspaceBody(BaseModel):
+ workspace_id: str = Field(..., min_length=1)
+
+
+class PathsBody(WorkspaceBody):
+ paths: list[str] = Field(..., min_length=1, max_length=20_000)
+
+
+class StageAllBody(WorkspaceBody):
+ tracked_only: bool = False
+
+
+class DiscardAllBody(WorkspaceBody):
+ untracked: bool = Field(False, description="Also remove untracked files")
+
+
+class CommitBody(WorkspaceBody):
+ message: str = Field("", max_length=20_000)
+ amend: bool = False
+ all_changes: bool = Field(False, description="Stage every change first")
+ include_untracked: bool = True
+ signoff: bool = False
+ no_verify: bool = False
+ allow_empty: bool = False
+
+
+class FetchBody(WorkspaceBody):
+ remote: str = Field("", max_length=200)
+ prune: bool = False
+ all_remotes: bool = False
+
+
+class PullBody(WorkspaceBody):
+ rebase: bool = False
+ remote: str = Field("", max_length=200)
+ branch: str = Field("", max_length=300)
+
+
+class PushBody(WorkspaceBody):
+ remote: str = Field("", max_length=200)
+ force: bool = False
+ tags: bool = False
+
+
+class SyncBody(WorkspaceBody):
+ rebase: bool = False
+
+
+class RemoteBody(WorkspaceBody):
+ name: str = Field(..., min_length=1, max_length=100)
+ url: str = Field("", max_length=2000)
+
+
+class RefBody(WorkspaceBody):
+ ref: str = Field(..., min_length=1, max_length=300)
+
+
+class CheckoutBody(RefBody):
+ detached: bool = False
+
+
+class BranchBody(WorkspaceBody):
+ name: str = Field(..., min_length=1, max_length=300)
+ start: str = Field("", max_length=300)
+ switch: bool = True
+
+
+class RenameBody(WorkspaceBody):
+ name: str = Field(..., min_length=1, max_length=300)
+ old: str = Field("", max_length=300)
+
+
+class DeleteBranchBody(WorkspaceBody):
+ name: str = Field(..., min_length=1, max_length=300)
+ force: bool = False
+
+
+class TagBody(WorkspaceBody):
+ name: str = Field(..., min_length=1, max_length=300)
+ message: str = Field("", max_length=5000)
+ ref: str = Field("", max_length=300)
+
+
+class StashBody(WorkspaceBody):
+ message: str = Field("", max_length=2000)
+ include_untracked: bool = False
+ staged: bool = False
+
+
+class StashRefBody(WorkspaceBody):
+ ref: str = Field("", max_length=40)
+ pop: bool = False
+
+
+class StashDropBody(WorkspaceBody):
+ ref: str = Field("", max_length=40)
+ everything: bool = False
+
+
+class OperationBody(WorkspaceBody):
+ action: Literal["continue", "abort"]
+
+
+def _ok(**extra: object) -> dict:
+ return {"ok": True, **extra}
+
+
[email protected]("/status", summary="Staged, unstaged, untracked and conflicting files")
+def status(workspace_id: str = Query(..., min_length=1)) -> dict:
+ return scm.read_status(_folder(workspace_id)).to_dict()
+
+
[email protected]("/refs", summary="Local branches, remote branches and tags")
+def refs(workspace_id: str = Query(..., min_length=1)) -> dict:
+ try:
+ return scm.list_refs(_folder(workspace_id))
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/graph", summary="One page of the commit graph")
+def graph(
+ workspace_id: str = Query(..., min_length=1),
+ scope: Literal["auto", "all", "current"] = "auto",
+ skip: int = Query(0, ge=0),
+ limit: int = Query(50, ge=1, le=scm.MAX_GRAPH_PAGE),
+) -> dict:
+ try:
+ return scm.graph(_folder(workspace_id), scope=scope, skip=skip, limit=limit)
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/commit", summary="A commit's message and changed files")
+def commit_details(
+ workspace_id: str = Query(..., min_length=1), commit: str = Query(..., min_length=4)
+) -> dict:
+ try:
+ return scm.commit_details(_folder(workspace_id), commit)
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/commit/file", summary="Both sides of one file in a commit")
+def commit_file(
+ workspace_id: str = Query(..., min_length=1),
+ commit: str = Query(..., min_length=4),
+ path: str = Query(..., min_length=1),
+ original: str = "",
+) -> dict:
+ try:
+ return scm.commit_file_diff(_folder(workspace_id), commit, path, original=original)
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/stashes", summary="The stash list")
+def stashes(workspace_id: str = Query(..., min_length=1)) -> dict:
+ try:
+ return {"stashes": scm.list_stashes(_folder(workspace_id))}
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/stage", summary="Stage files")
+def stage(body: PathsBody) -> dict:
+ try:
+ scm.stage(_folder(body.workspace_id), body.paths)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/stage-all", summary="Stage every change")
+def stage_all(body: StageAllBody) -> dict:
+ try:
+ scm.stage_all(_folder(body.workspace_id), tracked_only=body.tracked_only)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/unstage", summary="Unstage files")
+def unstage(body: PathsBody) -> dict:
+ try:
+ scm.unstage(_folder(body.workspace_id), body.paths)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/unstage-all", summary="Unstage every file")
+def unstage_all(body: WorkspaceBody) -> dict:
+ try:
+ scm.unstage_all(_folder(body.workspace_id))
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/discard", summary="Discard the working-tree changes of files")
+def discard(body: PathsBody) -> dict:
+ try:
+ scm.discard(_folder(body.workspace_id), body.paths)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/discard-all", summary="Discard every working-tree change")
+def discard_all(body: DiscardAllBody) -> dict:
+ try:
+ scm.discard_all(_folder(body.workspace_id), untracked=body.untracked)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/ignore", summary="Add files to .gitignore")
+def ignore(body: PathsBody) -> dict:
+ try:
+ return _ok(file=scm.ignore(_folder(body.workspace_id), body.paths))
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/commit", summary="Commit the staged changes")
+def commit(body: CommitBody) -> dict:
+ try:
+ sha = scm.commit(
+ _folder(body.workspace_id),
+ body.message,
+ amend=body.amend,
+ all_changes=body.all_changes,
+ include_untracked=body.include_untracked,
+ signoff=body.signoff,
+ no_verify=body.no_verify,
+ allow_empty=body.allow_empty,
+ )
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok(commit=sha)
+
+
[email protected]("/undo-commit", summary="Undo the last commit, keeping its changes staged")
+def undo_commit(body: WorkspaceBody) -> dict:
+ try:
+ return _ok(message=scm.undo_last_commit(_folder(body.workspace_id)))
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/operation", summary="Continue or abort a merge, rebase, cherry-pick or revert")
+def operation(body: OperationBody) -> dict:
+ try:
+ if body.action == "continue":
+ scm.continue_operation(_folder(body.workspace_id))
+ else:
+ scm.abort_operation(_folder(body.workspace_id))
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/fetch", summary="Fetch from the remotes")
+def fetch(body: FetchBody) -> dict:
+ try:
+ scm.fetch(
+ _folder(body.workspace_id),
+ remote=body.remote,
+ prune=body.prune,
+ all_remotes=body.all_remotes,
+ )
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/pull", summary="Pull into the current branch")
+def pull(body: PullBody) -> dict:
+ try:
+ scm.pull(
+ _folder(body.workspace_id), rebase=body.rebase, remote=body.remote, branch=body.branch
+ )
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/push", summary="Push the current branch")
+def push(body: PushBody) -> dict:
+ try:
+ upstream = scm.push(
+ _folder(body.workspace_id), remote=body.remote, force=body.force, tags=body.tags
+ )
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok(upstream=upstream)
+
+
[email protected]("/push-tags", summary="Push every tag")
+def push_tags(body: PushBody) -> dict:
+ try:
+ scm.push_tags(_folder(body.workspace_id), remote=body.remote)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/sync", summary="Pull, then push")
+def sync(body: SyncBody) -> dict:
+ try:
+ scm.sync(_folder(body.workspace_id), rebase=body.rebase)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/remote/add", summary="Add a remote")
+def add_remote(body: RemoteBody) -> dict:
+ try:
+ scm.add_remote(_folder(body.workspace_id), body.name, body.url)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/remote/remove", summary="Remove a remote")
+def remove_remote(body: RemoteBody) -> dict:
+ try:
+ scm.remove_remote(_folder(body.workspace_id), body.name)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/checkout", summary="Check out a branch, remote branch, tag or commit")
+def checkout(body: CheckoutBody) -> dict:
+ try:
+ return _ok(
+ branch=scm.checkout(_folder(body.workspace_id), body.ref, detached=body.detached)
+ )
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/branch/create", summary="Create a branch")
+def create_branch(body: BranchBody) -> dict:
+ try:
+ name = scm.create_branch(
+ _folder(body.workspace_id), body.name, start=body.start, switch=body.switch
+ )
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok(branch=name)
+
+
[email protected]("/branch/rename", summary="Rename a branch")
+def rename_branch(body: RenameBody) -> dict:
+ try:
+ return _ok(branch=scm.rename_branch(_folder(body.workspace_id), body.name, old=body.old))
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/branch/delete", summary="Delete a local branch")
+def delete_branch(body: DeleteBranchBody) -> dict:
+ try:
+ scm.delete_branch(_folder(body.workspace_id), body.name, force=body.force)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/merge", summary="Merge a branch into the current one")
+def merge(body: RefBody) -> dict:
+ try:
+ return _ok(result=scm.merge(_folder(body.workspace_id), body.ref))
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/rebase", summary="Rebase the current branch onto another")
+def rebase(body: RefBody) -> dict:
+ try:
+ return _ok(result=scm.rebase(_folder(body.workspace_id), body.ref))
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/cherry-pick", summary="Apply one commit onto the current branch")
+def cherry_pick(body: RefBody) -> dict:
+ try:
+ return _ok(result=scm.cherry_pick(_folder(body.workspace_id), body.ref))
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/revert", summary="Commit the inverse of one commit")
+def revert(body: RefBody) -> dict:
+ try:
+ return _ok(result=scm.revert(_folder(body.workspace_id), body.ref))
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/tag/create", summary="Create a tag")
+def create_tag(body: TagBody) -> dict:
+ try:
+ scm.create_tag(_folder(body.workspace_id), body.name, message=body.message, ref=body.ref)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/tag/delete", summary="Delete a tag")
+def delete_tag(body: TagBody) -> dict:
+ try:
+ scm.delete_tag(_folder(body.workspace_id), body.name)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/stash", summary="Stash the working-tree changes")
+def stash(body: StashBody) -> dict:
+ try:
+ scm.stash(
+ _folder(body.workspace_id),
+ message=body.message,
+ include_untracked=body.include_untracked,
+ staged=body.staged,
+ )
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/stash/apply", summary="Apply or pop a stash")
+def stash_apply(body: StashRefBody) -> dict:
+ try:
+ scm.stash_apply(_folder(body.workspace_id), body.ref, pop=body.pop)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
+
+
[email protected]("/stash/drop", summary="Drop a stash, or every stash")
+def stash_drop(body: StashDropBody) -> dict:
+ try:
+ scm.stash_drop(_folder(body.workspace_id), body.ref, everything=body.everything)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return _ok()
diff --git a/jarvis/ui/web/frontend/package-lock.json b/jarvis/ui/web/frontend/package-lock.json
index 8b0e825962..163a106cb8 100644
--- a/jarvis/ui/web/frontend/package-lock.json
+++ b/jarvis/ui/web/frontend/package-lock.json
@@ -23,6 +23,7 @@
"@react-three/drei": "^9.122.0",
"@react-three/fiber": "^8.18.0",
"@tanstack/react-query": "^5.56.0",
+ "@vscode/codicons": "0.0.40",
"@xterm/addon-canvas": "^0.7.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-search": "^0.16.0",
@@ -3063,6 +3064,12 @@
"url": "https://opencollective.com/vitest"
}
},
+ "node_modules/@vscode/codicons": {
+ "version": "0.0.40",
+ "resolved": "https://registry.npmjs.org/@vscode/codicons/-/codicons-0.0.40.tgz",
+ "integrity": "sha512-R8sEDXthD86JHsk3xERrMcTN6sMovbk1AXYB5/tGoEYCE8DWwya6al5VLrAmQYXC1bQhUHIfHALj8ijQUs11cQ==",
+ "license": "CC-BY-4.0"
+ },
"node_modules/@xterm/addon-canvas": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/@xterm/addon-canvas/-/addon-canvas-0.7.0.tgz",
diff --git a/jarvis/ui/web/frontend/package.json b/jarvis/ui/web/frontend/package.json
index f8bd173a89..0af947c154 100644
--- a/jarvis/ui/web/frontend/package.json
+++ b/jarvis/ui/web/frontend/package.json
@@ -25,6 +25,7 @@
"@react-three/drei": "^9.122.0",
"@react-three/fiber": "^8.18.0",
"@tanstack/react-query": "^5.56.0",
+ "@vscode/codicons": "0.0.40",
"@xterm/addon-canvas": "^0.7.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-search": "^0.16.0",
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx
index 4a9db425f1..4cc71e0442 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,887 +1,293 @@
-import { StrictMode } from "react";
-import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { GitOverviewTab, resetGitOverviewCache } from "./GitOverviewTab";
-import type { BranchRow, Checkout, CiStatus, PullRequest, RepoOverview } from "./gitOverviewApi";
-import { openExternalUrl } from "@/lib/openExternal";
+import type { GraphPage, ScmFile, ScmStatus } from "./scm/scmApi";
+import { useCodeEditorStore } from "@/store/codeEditor";
import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
-import { useIdeSidePanelStore } from "@/store/ideSidePanel";
-vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn(async () => true) }));
+vi.mock("./scm/MonacoDiff", () => ({ default: () => <div data-testid="scm-diff-editor" /> }));
-const noCi: CiStatus = { state: "none", url: "", total: 0, passed: 0, failed: 0, running: 0, pending: 0, commit: "", names: [] };
+const file = (path: string, letter: ScmFile["letter"], status: string): ScmFile => ({ path, letter, status, original: "" });
-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,
- };
-}
-
-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}`,
- state,
- base: "main",
- head: "x",
- head_oid: "",
- merged_at: "",
- updated_at: "",
- queue_position: state === "queued" ? 2 : null,
- ci,
- ...extra,
-});
-
-const CHECKOUT: Checkout = {
- branch: "feature/wip",
+const BASE: ScmStatus = {
+ available: true,
+ reason: "",
+ root: "/code/app",
+ prefix: "",
+ branch: "main",
+ head: "c2c2c2c2c2c2",
detached: false,
unborn: false,
- head: "abc123def456",
- upstream: "origin/feature/wip",
- ahead: 2,
+ upstream: "origin/main",
+ ahead: 0,
behind: 0,
- files: 0,
- staged: 0,
- unstaged: 0,
- untracked: 0,
- conflicted: 0,
operation: "",
+ remotes: ["origin"],
stashes: 0,
- last_fetch: Math.floor(Date.now() / 1000) - 120,
- has_remote: true,
-};
-
-const OVERVIEW: RepoOverview = {
- available: true,
- reason: "",
- root: "/code/app",
- branch: "feature/wip",
- detached: false,
- head: "abc123def456",
- default_branch: "main",
+ merge: [],
+ staged: [file("src/new.ts", "A", "index_added")],
+ changes: [file("app.py", "M", "modified"), file("notes.txt", "U", "untracked"), file("old.txt", "D", "deleted")],
truncated: false,
- github: {
- available: true,
- reason: "",
- code: "",
- repo: "o/r",
- suggested_repo: "o/r",
- source: "app",
- repo_url: "https://github.com/o/r",
- fetched_at: Date.now() / 1000,
- },
- branches: [
- branch("feature/wip", {
- current: true,
- ahead: 2,
- pull_requests: [pr(7, "open")],
- ci: { ...noCi, state: "running", url: "https://github.com/o/r/actions/runs/7", total: 3, passed: 1, running: 2, names: ["tests"] },
- }),
- branch("main", { ci: { ...noCi, state: "success", total: 4, passed: 4, url: "https://github.com/o/r/actions/runs/1" } }),
- branch("feature/done", {
- merged_into: [{ target: "main", via: "pull_request", number: 5, url: "" }],
- pull_requests: [pr(5, "merged")],
- ci: { ...noCi, state: "success", total: 2, passed: 2 },
- }),
- branch("feature/queued", { pull_requests: [pr(8, "queued")] }),
- branch("feature/draft", { pull_requests: [pr(9, "draft")] }),
- branch("feature/dropped", {
- pull_requests: [pr(4, "closed")],
- ci: { ...noCi, state: "failure", total: 2, passed: 1, failed: 1, names: ["lint"], url: "https://github.com/o/r/actions/runs/4" },
- }),
- ],
- remote_branches: [branch("only-remote", { remote_only: true, upstream: "" })],
- checkout: CHECKOUT,
- base_ref: "origin/main",
+ head_message: "feat: before",
};
-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. */
-let gate: Promise<void> | null = null;
-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",
- base: "origin/main",
+const GRAPH: GraphPage = {
commits: [
- { sha: "aaaaaaaaaaaa", subject: "Add the widget", author: "Ada", committed_at: 1_790_000_000, on_github: false },
- { sha: "bbbbbbbbbbbb", subject: "Start the widget", author: "Ada", committed_at: 1_789_000_000, on_github: true },
+ { id: "c2c2c2c2c2c2", parents: ["c1c1c1c1c1c1"], author: "Ada", email: "[email protected]", date: 1_790_000_000, refs: ["HEAD -> refs/heads/main", "refs/remotes/origin/main"], subject: "feat: second" },
+ { id: "c1c1c1c1c1c1", parents: [], author: "Ada", email: "[email protected]", date: 1_789_000_000, refs: ["tag: refs/tags/v1.0"], subject: "feat: first" },
],
- commits_truncated: false,
- files: [
- { path: "src/widget.ts", status: "added", added: 12, removed: 0 },
- { path: "README.md", status: "modified", added: 2, removed: 1 },
- ],
- files_truncated: false,
- reason: "",
-};
-const FILE_DIFF = {
- path: "src/widget.ts",
- status: "added",
- binary: false,
- added: 1,
- removed: 0,
- truncated: false,
- hunks: [{ header: "@@ -0,0 +1 @@", lines: [{ kind: "add", text: "export const widget = 1;", old_no: null, new_no: 1 }] }],
+ more: false,
+ head: "c2c2c2c2c2c2",
+ upstream: "origin/main",
+ incoming: [],
+ outgoing: [],
};
-const REPOS = {
- connected: true,
- source: "app",
- login: "octo",
- reason: "",
- repos: [
- { name: "octo/other", description: "Something else", private: true, fork: false, url: "", pushed_at: "" },
- { name: "o/r", description: "", private: false, fork: false, url: "", pushed_at: "" },
- ],
-};
-const ACTION = /\/api\/agentic-ide\/git\/(fetch|pull|commit|switch|prepare|branch\/push|branch\/pull-request|branch\/update|branch\/delete)$/;
+
+let status: ScmStatus = BASE;
+const posts: { path: string; body: Record<string, unknown> }[] = [];
+const gets: string[] = [];
beforeEach(() => {
- answer = OVERVIEW;
- status = 200;
- gate = null;
- calls.length = 0;
- puts.length = 0;
- opens.length = 0;
- diffs.length = 0;
+ status = BASE;
posts.length = 0;
- for (const key of Object.keys(refusals)) delete refusals[key];
+ gets.length = 0;
+ window.localStorage.clear();
resetGitOverviewCache();
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
- 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]);
+ const json = (body: unknown, code = 200) => new Response(JSON.stringify(body), { status: code, headers: { "Content-Type": "application/json" } });
+ if (init?.method === "POST") {
+ posts.push({ path: url.replace(/^.*\/api\/agentic-ide\/git\//, ""), body: JSON.parse(String(init.body)) });
+ return json({ ok: true, commit: "abc1234", message: "feat: before", branch: "x", upstream: "origin/main", result: "merged" });
+ }
+ gets.push(url);
+ if (url.includes("/scm/status")) return json(status);
+ if (url.includes("/scm/graph")) return json(GRAPH);
+ if (url.includes("/scm/commit?")) {
return json({
- ok: true,
- message: "Done.",
- upstream: "origin/feature/wip",
- commit: "abc1234",
- url: "https://github.com/o/r/pull/11",
- folder: "/code/app",
- branch: String(posts.at(-1)?.body.branch ?? ""),
- created: true,
+ id: "c2c2c2c2c2c2",
+ parents: ["c1c1c1c1c1c1"],
+ author: "Ada",
+ email: "",
+ date: 0,
+ committer: "Ada",
+ committer_date: 0,
+ message: "feat: second",
+ files: [{ path: "src/x.ts", letter: "M", original: "" }],
+ stat: "1 file changed, 2 insertions(+)",
});
}
- if (url.includes("/github/repos")) return json(REPOS);
- if (url.includes("/branch/contents")) return json(CONTENTS);
- if (url.includes("/branch/diff")) {
- diffs.push(url);
- return json(FILE_DIFF);
- }
- if (url.includes("/branch/editors")) return json({ file_manager: true, editors: [{ id: "code", label: "VS Code" }] });
- if (url.includes("/branch/open")) {
- opens.push(String(init?.body));
- return json({ opened: true, path: "/code/app" });
- }
- if (url.includes("/github/binding")) {
- puts.push(String(init?.body));
- answer = OVERVIEW;
- return json({ ok: true, repo: "o/r" });
+ if (url.includes("/scm/refs")) {
+ return json({
+ current: "main",
+ refs: [
+ { kind: "head", name: "main", commit: "c2c2c2c", date: 0, subject: "feat: second", upstream: "origin/main" },
+ { kind: "head", name: "feature/x", commit: "c1c1c1c", date: 0, subject: "feat: first", upstream: "" },
+ { kind: "tag", name: "v1.0", commit: "c1c1c1c", date: 0, subject: "", upstream: "" },
+ ],
+ });
}
- if (gate) await gate;
- return json(answer, status);
+ return json({ detail: "Not Found" }, 404);
}),
);
useEventStore.setState({ activeSection: "agentic-ide" });
useIdeChatStore.setState({ workspace: { id: "w1", name: "App", path: "/code/app" }, stagedPane: null });
+ useCodeEditorStore.setState({ tabs: [] });
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
- vi.mocked(openExternalUrl).mockClear();
});
-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 fileRow = (path: string, group = "changes") =>
+ screen.getAllByTestId("scm-file").find((element) => element.dataset.path === path && element.dataset.group === group)!;
const posted = (path: string) => posts.filter((post) => post.path === path).map((post) => post.body);
-describe("GitOverviewTab — the checkout at a glance", () => {
- it("says who is ahead and offers the one next step as a button", async () => {
+describe("GitOverviewTab — changes", () => {
+ it("lists staged and unstaged files in their groups with a status letter", 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));
+ expect(await screen.findByTestId("scm-group-staged")).toBeTruthy();
+ expect(within(screen.getByTestId("scm-group-staged")).getByTestId("scm-group-count").textContent).toBe("1");
+ expect(within(screen.getByTestId("scm-group-changes")).getByTestId("scm-group-count").textContent).toBe("3");
+ expect(fileRow("app.py").dataset.letter).toBe("M");
+ expect(fileRow("notes.txt").dataset.letter).toBe("U");
+ expect(fileRow("src/new.ts", "staged").dataset.letter).toBe("A");
+ expect(within(fileRow("old.txt")).getByText("old.txt").className).toContain("line-through");
+ expect(within(fileRow("app.py")).getByTestId("scm-letter").className).toContain("scm-tone-M");
+ expect(screen.getByTestId("scm-branch").textContent).toBe("main*");
});
- it("commits uncommitted work from an inline message box", async () => {
- answer = withCheckout({ ahead: 0, files: 3, unstaged: 2, untracked: 1 }, { ahead: 0 });
+ it("stages and unstages from a file's row", async () => {
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());
+ fireEvent.click(within(await screen.findByText("app.py").then(() => fileRow("app.py"))).getByTestId("scm-stage"));
+ await vi.waitFor(() => expect(posted("scm/stage")).toEqual([{ workspace_id: "w1", paths: ["app.py"] }]));
+ fireEvent.click(within(fileRow("src/new.ts", "staged")).getByTestId("scm-unstage"));
+ await vi.waitFor(() => expect(posted("scm/unstage")).toEqual([{ workspace_id: "w1", paths: ["src/new.ts"] }]));
});
- it("moves edits made on the default branch to a new branch instead of committing them there", async () => {
- answer = {
- ...withCheckout({ branch: "main", upstream: "origin/main", ahead: 0, files: 62, unstaged: 60, untracked: 2 }),
- branch: "main",
- branches: [branch("main", { current: true }), ...OVERVIEW.branches.slice(2)],
- pull_requests: [pr(7, "open")],
- };
+ it("acts on every selected file at once", async () => {
render(<GitOverviewTab />);
- const next = await screen.findByTestId("git-next");
- expect(next.dataset.step).toBe("branch_off");
- expect(next.textContent).toContain("Move 60 changed files to a branch");
- expect(next.textContent).toContain("main is the default branch");
- fireEvent.click(screen.getByTestId("git-next-action"));
- expect((screen.getByTestId("git-branch-submit") as HTMLButtonElement).disabled).toBe(true);
- fireEvent.change(screen.getByTestId("git-branch-name"), { target: { value: "feature/tidy-up" } });
- fireEvent.click(screen.getByTestId("git-branch-submit"));
- await vi.waitFor(() =>
- expect(posted("prepare")).toEqual([{ folder: "/code/app", mode: "new_branch", branch: "feature/tidy-up", base: "" }]),
- );
- await vi.waitFor(() => expect(screen.queryByTestId("git-branch-form")).toBeNull());
- // Committing on the default branch stays possible for whoever wants it, as the second choice.
- expect(posted("commit")).toEqual([]);
+ await screen.findByText("app.py");
+ fireEvent.click(fileRow("app.py"));
+ fireEvent.click(fileRow("notes.txt"), { ctrlKey: true });
+ fireEvent.click(within(fileRow("notes.txt")).getByTestId("scm-stage"));
+ await vi.waitFor(() => expect(posted("scm/stage")).toEqual([{ workspace_id: "w1", paths: ["app.py", "notes.txt"] }]));
});
- it("opens the Changes tab to review what is uncommitted", async () => {
- answer = withCheckout({ files: 1, unstaged: 1 });
+ it("commits the staged files with Ctrl+Enter and empties the box", async () => {
render(<GitOverviewTab />);
- fireEvent.click(await screen.findByTestId("git-review-changes"));
- expect(useIdeSidePanelStore.getState().active).toBe("changes");
+ const box = (await screen.findByTestId("scm-message")) as HTMLTextAreaElement;
+ expect(box.placeholder).toContain("main");
+ fireEvent.change(box, { target: { value: "feat: widget" } });
+ fireEvent.keyDown(box, { key: "Enter", ctrlKey: true });
+ await vi.waitFor(() => expect(posted("scm/commit")).toHaveLength(1));
+ expect(posted("scm/commit")[0]).toMatchObject({ message: "feat: widget", amend: false, all_changes: false });
+ await vi.waitFor(() => expect(box.value).toBe(""));
});
- 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" }]];
+ it("asks before committing every change when nothing is staged", async () => {
+ status = { ...BASE, staged: [] };
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 }]));
+ fireEvent.change(await screen.findByTestId("scm-message"), { target: { value: "fix: all" } });
+ fireEvent.click(screen.getByTestId("scm-primary"));
+ fireEvent.click(await screen.findByTestId("scm-choice-yes"));
+ await vi.waitFor(() => expect(posted("scm/commit")[0]).toMatchObject({ message: "fix: all", all_changes: 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 });
+ it("asks for a message instead of committing without one", async () => {
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();
+ fireEvent.click(await screen.findByTestId("scm-primary"));
+ expect(await screen.findByTestId("scm-message-error")).toBeTruthy();
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 });
+ it("commits and pushes from the button's menu", async () => {
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");
+ fireEvent.change(await screen.findByTestId("scm-message"), { target: { value: "feat: ship" } });
+ fireEvent.click(screen.getByTestId("scm-primary-more"));
+ fireEvent.click(await screen.findByTestId("scm-menu-commit-push"));
+ await vi.waitFor(() => expect(posted("scm/push")).toHaveLength(1));
+ expect(posted("scm/commit")[0]).toMatchObject({ message: "feat: ship" });
});
- it("opens a pull request for a pushed branch that has none", async () => {
- answer = withCheckout({ ahead: 0 }, { ahead: 0, pull_requests: [], ci: noCi });
+ it("discards a file only after a confirmation", async () => {
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"));
+ await screen.findByText("app.py");
+ fireEvent.click(within(fileRow("app.py")).getByTestId("scm-discard"));
+ expect(await screen.findByTestId("scm-choice")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("scm-choice-cancel"));
+ expect(posted("scm/discard")).toEqual([]);
+ fireEvent.click(within(fileRow("app.py")).getByTestId("scm-discard"));
+ fireEvent.click(await screen.findByTestId("scm-choice-discard"));
+ await vi.waitFor(() => expect(posted("scm/discard")).toEqual([{ workspace_id: "w1", paths: ["app.py"] }]));
});
- 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: [] };
+ it("opens a changed file's diff in the editor and an untracked file as it is", async () => {
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();
+ await screen.findByText("app.py");
+ fireEvent.click(fileRow("app.py"));
+ expect(useCodeEditorStore.getState().tabs.map((tab) => [tab.path, tab.mode])).toEqual([["app.py", "diff"]]);
+ fireEvent.click(fileRow("notes.txt"));
+ expect(useCodeEditorStore.getState().tabs.map((tab) => [tab.path, tab.mode])).toEqual([["notes.txt", "edit"]]);
});
- it("flags commits on GitHub that were not fetched yet, and fetches them", async () => {
- answer = withCheckout({ ahead: 0 }, { ahead: 0, unfetched: true });
+ it("shows folders in tree view", async () => {
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" }]));
+ await screen.findByText("app.py");
+ expect(screen.queryByTestId("scm-folder")).toBeNull();
+ fireEvent.click(screen.getByTestId("scm-view-mode"));
+ expect((await screen.findByTestId("scm-folder")).textContent).toContain("src");
});
- 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;
- });
+ it("turns the button into Sync with the counts when there is nothing to commit", async () => {
+ status = { ...BASE, staged: [], changes: [], ahead: 1, behind: 2 };
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();
+ const button = await screen.findByTestId("scm-primary");
+ expect(button.dataset.action).toBe("sync");
+ expect(button.textContent).toContain("2↓");
+ expect(button.textContent).toContain("1↑");
+ fireEvent.click(button);
+ fireEvent.click(await screen.findByTestId("scm-choice-ok"));
+ await vi.waitFor(() => expect(posted("scm/sync")).toHaveLength(1));
});
- it("shows the tab's shape while the very first answer loads", async () => {
- let release: () => void = () => {};
- gate = new Promise<void>((resolve) => {
- release = resolve;
- });
+ it("offers to publish a branch that has no upstream", async () => {
+ status = { ...BASE, staged: [], changes: [], upstream: "" };
render(<GitOverviewTab />);
- expect(screen.getByTestId("git-loading")).toBeTruthy();
- release();
- expect(await screen.findByTestId("git-status")).toBeTruthy();
+ const button = await screen.findByTestId("scm-primary");
+ expect(button.dataset.action).toBe("publish");
+ fireEvent.click(button);
+ await vi.waitFor(() => expect(posted("scm/push")).toEqual([{ workspace_id: "w1", remote: "origin" }]));
});
- it("still works against a backend from before the control center", async () => {
- const { checkout: _checkout, base_ref: _base, ...old } = OVERVIEW;
- answer = old;
+ it("switches branch from the branch name", async () => {
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");
+ fireEvent.click(await screen.findByTestId("scm-branch"));
+ const items = await screen.findAllByTestId("scm-quick-pick-item");
+ expect(items.map((item) => item.textContent)).toEqual(expect.arrayContaining([expect.stringContaining("feature/x"), expect.stringContaining("v1.0")]));
+ fireEvent.click(items.find((item) => item.textContent?.includes("feature/x"))!);
+ await vi.waitFor(() => expect(posted("scm/checkout")).toEqual([{ workspace_id: "w1", ref: "feature/x", detached: false }]));
});
-});
-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")],
- };
+ it("stashes with a message from the more menu", async () => {
render(<GitOverviewTab />);
- 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"]);
+ fireEvent.click(await screen.findByTestId("scm-more"));
+ fireEvent.mouseEnter(await screen.findByTestId("scm-menu-stash-menu"));
+ fireEvent.click(await screen.findByTestId("scm-menu-s-stash"));
+ const box = await screen.findByTestId("scm-quick-input-box");
+ fireEvent.change(box, { target: { value: "wip" } });
+ fireEvent.keyDown(box, { key: "Enter" });
+ await vi.waitFor(() => expect(posted("scm/stash")).toEqual([{ workspace_id: "w1", message: "wip" }]));
});
- 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" })],
- };
+ it("puts the message of an undone commit back into the box", async () => {
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");
+ fireEvent.click(await screen.findByTestId("scm-more"));
+ fireEvent.mouseEnter(await screen.findByTestId("scm-menu-commit-menu"));
+ fireEvent.click(await screen.findByTestId("scm-menu-c-undo"));
+ await vi.waitFor(() => expect((screen.getByTestId("scm-message") as HTMLTextAreaElement).value).toBe("feat: before"));
+ expect(posted("scm/undo-commit")).toHaveLength(1);
});
- 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 () => {
+ it("offers to initialize a folder that is no repository", async () => {
+ status = { ...BASE, available: false, reason: "app is not a git repository." };
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([]);
+ fireEvent.click(await screen.findByTestId("scm-init"));
+ await vi.waitFor(() => expect(posted("prepare")).toEqual([{ folder: "/code/app", mode: "init", branch: "", base: "" }]));
});
});
-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(calls[0]).toContain("/api/agentic-ide/git/overview?workspace_id=w1");
- });
-
- it("shows each pull request state with GitHub's colour", async () => {
- render(<GitOverviewTab />);
- await screen.findAllByTestId("git-branch-row");
- const state = (name: string) => within(row(name)).getByTestId("git-pr").querySelector("[data-pr-state]");
- expect(state("feature/wip")?.getAttribute("class")).toContain("text-success");
- expect(state("feature/done")?.getAttribute("class")).toContain("--gh-merged");
- expect(state("feature/queued")?.getAttribute("class")).toContain("text-warning");
- expect(state("feature/draft")?.getAttribute("class")).toContain("text-muted-foreground");
- expect(state("feature/dropped")?.getAttribute("class")).toContain("text-destructive");
- expect(state("feature/dropped")?.getAttribute("data-pr-state")).toBe("closed");
- });
-
- it("keeps CI apart from merging: a merged branch still shows its own green check", async () => {
- render(<GitOverviewTab />);
- await screen.findAllByTestId("git-branch-row");
- const done = row("feature/done");
- expect(within(done).getByTestId("git-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-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.
- expect(within(row("feature/queued")).queryByTestId("git-ci")).toBeNull();
- });
-
- it("opens the pull request and the CI run in the browser", async () => {
- render(<GitOverviewTab />);
- await screen.findAllByTestId("git-branch-row");
- fireEvent.click(within(row("feature/wip")).getByTestId("git-pr"));
- expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/pull/7");
- fireEvent.click(within(row("feature/dropped")).getByTestId("git-ci"));
- expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/actions/runs/4");
- });
-
- it("explains every icon in its tooltip", async () => {
- render(<GitOverviewTab />);
- await screen.findAllByTestId("git-branch-row");
- fireEvent.mouseEnter(within(row("feature/dropped")).getByTestId("git-ci").parentElement!);
- const tip = await screen.findByRole("tooltip");
- expect(tip.textContent).toContain("CI failed");
- expect(tip.textContent).toContain("lint");
- });
-
- it("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");
- 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 () => {
- const now = Math.floor(Date.now() / 1000);
- answer = {
- ...OVERVIEW,
- branches: [
- branch("fresh", { committed_at: now - 2 * 3600 }),
- branch("old", { committed_at: Date.UTC(2024, 2, 3, 12) / 1000 }),
- branch("undated"),
- ],
- };
- render(<GitOverviewTab />);
- await screen.findAllByTestId("git-branch-row");
- 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 />);
- await screen.findAllByTestId("git-branch-row");
- expect(screen.queryByTestId("git-branch-details")).toBeNull();
-
- fireEvent.click(within(row("feature/wip")).getByTestId("git-branch-toggle"));
- const details = within(row("feature/wip")).getByTestId("git-branch-details");
- await within(details).findByTestId("git-branch-commits");
- fireEvent.click(await within(details).findByTestId("git-open-folder"));
- await vi.waitFor(() => expect(opens).toHaveLength(1));
- expect(JSON.parse(opens[0])).toEqual({ workspace_id: "w1", branch: "feature/wip", target: "folder" });
- fireEvent.click(within(details).getByTestId("git-open-code"));
- await vi.waitFor(() => expect(JSON.parse(opens[1]).target).toBe("code"));
- fireEvent.click(within(details).getByTestId("git-open-github"));
- 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, 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-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.
- // A commit only on this computer gets no GitHub link (that page would be a 404).
- const commit = (sha: string) => within(details).getAllByTestId("git-branch-commit").find((el) => el.dataset.sha === sha)!;
- expect(within(commit("aaaaaaaaaaaa")).queryByTestId("git-commit-link")).toBeNull();
- expect(within(commit("aaaaaaaaaaaa")).getByTestId("git-commit-local")).toBeTruthy();
- fireEvent.click(within(commit("bbbbbbbbbbbb")).getByTestId("git-commit-link"));
- expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/commit/bbbbbbbbbbbb");
- expect(within(details).getByTestId("git-branch-commits").textContent).toContain("Add the widget");
- expect(within(details).getByTestId("git-branch-commits").textContent).toContain("2 commits not in origin/main");
- const file = within(details).getAllByTestId("git-branch-file").find((el) => el.dataset.path === "src/widget.ts")!;
- fireEvent.click(within(file).getByRole("button"));
- expect(await within(file).findByTestId("explorer-diff")).toBeTruthy();
- expect(within(file).getByTestId("explorer-diff").textContent).toContain("export const widget = 1;");
- expect(diffs[0]).toContain("path=src%2Fwidget.ts");
- expect(diffs[0]).toContain("base=main");
-
- // A second click folds it away again.
- fireEvent.click(within(row("feature/wip")).getByTestId("git-branch-toggle"));
- 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();
+describe("GitOverviewTab — graph", () => {
+ it("draws the history with branch and tag badges and opens a commit's files", async () => {
+ render(<GitOverviewTab />);
+ const commits = await screen.findAllByTestId("scm-graph-commit");
+ expect(commits.map((element) => element.textContent)).toEqual([expect.stringContaining("feat: second"), expect.stringContaining("feat: first")]);
+ expect(within(commits[0]).getAllByTestId("scm-graph-ref").map((badge) => badge.getAttribute("aria-label"))).toEqual(["main", "origin/main"]);
+ expect(within(commits[1]).getByTestId("scm-graph-ref").dataset.kind).toBe("tag");
+ fireEvent.click(commits[0]);
+ expect((await screen.findByTestId("scm-graph-file")).textContent).toContain("x.ts");
+ fireEvent.click(screen.getByTestId("scm-graph-file"));
+ expect(await screen.findByTestId("scm-diff-dialog")).toBeTruthy();
+ await act(async () => {
+ fireEvent.click(screen.getByTestId("scm-diff-close"));
+ });
+ expect(screen.queryByTestId("scm-diff-dialog")).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" }]];
+ it("creates a branch at a commit from its menu", async () => {
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"));
+ const [top] = await screen.findAllByTestId("scm-graph-commit");
+ fireEvent.contextMenu(top);
+ fireEvent.click(await screen.findByTestId("scm-menu-create-branch"));
+ const box = await screen.findByTestId("scm-quick-input-box");
+ fireEvent.change(box, { target: { value: "feature/here" } });
+ fireEvent.keyDown(box, { key: "Enter" });
await vi.waitFor(() =>
- expect(posted("branch/delete")).toEqual([{ workspace_id: "w1", branch: "feature/draft", force: false, remote: false, with_worktree: false }]),
+ expect(posted("scm/branch/create")).toEqual([{ workspace_id: "w1", name: "feature/here", start: "c2c2c2c2c2c2", switch: true }]),
);
- // 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");
- fireEvent.click(within(row("feature/queued")).getByTestId("git-branch-more"));
- const menu = await screen.findByTestId("git-branch-menu");
- expect(within(menu).getByTestId("git-menu-pr").textContent).toContain("#8");
- // A live pull request exists, so there is nothing new to create.
- expect(within(menu).queryByTestId("git-menu-create-pr")).toBeNull();
- fireEvent.click(within(menu).getByTestId("git-menu-compare"));
- expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/compare/main...feature/queued");
- expect(screen.queryByTestId("git-branch-menu")).toBeNull();
-
- fireEvent.contextMenu(row("feature/done"));
- const second = await screen.findByTestId("git-branch-menu");
- fireEvent.click(within(second).getByTestId("git-menu-create-pr"));
- expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/compare/main...feature/done?expand=1");
- });
-});
-
-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 />);
- expect((await screen.findByTestId("git-unavailable")).textContent).toContain("not a git repository");
- });
-
- it("shows the local state before a GitHub repository is picked, and connects the recommended one in a click", async () => {
- answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "" } };
- render(<GitOverviewTab />);
- // Nothing is hidden behind the question: branch, sync and branches are all there.
- expect((await screen.findByTestId("git-current-branch")).textContent).toBe("feature/wip");
- expect(screen.getByTestId("git-sync-push").dataset.count).toBe("2");
- expect(screen.getAllByTestId("git-branch-row")).toHaveLength(6);
- expect(screen.queryByTestId("git-repo-picker")).toBeNull();
- const card = screen.getByTestId("git-connect-repo");
- expect(within(card).getByTestId("git-connect-suggested").textContent).toBe("o/r");
- fireEvent.click(within(card).getByTestId("git-connect-suggested"));
- await vi.waitFor(() => expect(puts).toEqual([JSON.stringify({ workspace_id: "w1", repo: "o/r" })]));
- await vi.waitFor(() => expect(screen.queryByTestId("git-connect-repo")).toBeNull());
- expect(await screen.findByTestId("git-section-prs")).toBeTruthy();
- });
-
- it("offers the list of repositories for a folder whose remote is not on GitHub", async () => {
- answer = {
- ...OVERVIEW,
- github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "", suggested_repo: "" },
- };
- render(<GitOverviewTab />);
- const card = await screen.findByTestId("git-connect-repo");
- expect(within(card).queryByTestId("git-connect-suggested")).toBeNull();
- expect(screen.getAllByTestId("git-branch-row")).toHaveLength(6);
- fireEvent.click(within(card).getByTestId("git-connect-choose"));
- await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));
- // The list can be left again without picking; the local state comes back.
- fireEvent.click(screen.getByLabelText("Keep the current repository"));
- expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(6);
- });
-
- it("asks 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 />);
- fireEvent.click(within(await screen.findByTestId("git-connect-repo")).getByTestId("git-connect-choose"));
- // 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 />);
- fireEvent.click(within(await screen.findByTestId("git-connect-repo")).getByTestId("git-connect-choose"));
- 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 () => {
- answer = { detail: "Not Found" };
- status = 404;
- render(<GitOverviewTab />);
- expect((await screen.findByTestId("git-error")).textContent).toContain("Connect a GitHub repository");
- fireEvent.click(screen.getByTestId("git-restart"));
- await vi.waitFor(() => expect(calls).toContain("/api/settings/restart-app"));
});
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx
index 430a8c8748..f2f7bf41d9 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,506 +1,411 @@
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 { openExternalUrl } from "@/lib/openExternal";
-import { cn } from "@/lib/utils";
-import { QuickTooltip } from "@/components/ui/tooltip";
+import { useT } from "@/i18n";
+import { prepareGit } from "@/lib/gitApi";
import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
-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, ConnectRepositoryCard, GitHubRepoPicker } from "./GitHubRepoPicker";
-import { attention, canCleanUp, checkoutOf, openPullRequests, type AttentionItem, type BranchFilter } from "./gitInsights";
-import {
- bindGitHubRepo,
- 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";
+import { RepositoryOverview, RestartToConnectCard } from "./RepositoryOverview";
+import { ChangesView, IconButton, viewSortMenu, type ListSettings } from "./scm/ChangesView";
+import { Codicon } from "./scm/Codicon";
+import "./scm/scm.css";
+import { DiffDialog, type DiffSource } from "./scm/DiffDialog";
+import { GraphView } from "./scm/GraphView";
+import { useQuickInput } from "./scm/QuickInput";
+import { ScmMenu, menuPointFor, type MenuItem } from "./scm/ScmMenu";
+import { ScmViews } from "./scm/ScmViews";
+import type { GraphScope } from "./scm/scmApi";
+import { scmStorage, useChoice, useScmCommands, useScmStatus, type CommitOptions } from "./scm/useScm";
-/**
- * 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 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;
-
-/**
- * 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>();
+export { resetGitOverviewCache } from "./RepositoryOverview";
-/** 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>(() => (workspaceId ? (LAST_OVERVIEW.get(workspaceId) ?? null) : null));
- const [error, setError] = useState("");
- const [routeMissing, setRouteMissing] = useState(false);
- const [loading, setLoading] = useState(false);
- 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(() => {
- 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 = forceNext.current;
- forceNext.current = false;
- let githubLoading = false;
- const tick = async () => {
- if (useEventStore.getState().activeSection === "agentic-ide") {
- setLoading(true);
- try {
- const next = await fetchGitOverview(workspaceId, refresh);
- refresh = false;
- githubLoading = next.github?.code === "loading" || Boolean(next.github?.refreshing);
- LAST_OVERVIEW.set(workspaceId, next);
- if (alive) {
- setData(next);
- setError("");
- setRouteMissing(false);
- }
- } catch (err) {
- // Keep the last answer on screen; the next tick tries again.
- if (alive) {
- setError((err as Error).message);
- setRouteMissing(err instanceof GitOverviewError && err.routeMissing);
- }
- } finally {
- if (alive) setLoading(false);
- }
- }
- const delay = githubLoading ? POLL_LOADING_MS + Math.random() * 500 : POLL_MS + Math.random() * POLL_JITTER_MS;
- if (alive) timer = window.setTimeout(tick, delay);
- };
- void tick();
- return () => {
- alive = false;
- window.clearTimeout(timer);
- };
- }, [workspaceId, round]);
- const refresh = useCallback(() => {
- forceNext.current = true;
- setRound((value) => value + 1);
- }, []);
- return { data, error, routeMissing, loading, refresh };
-}
+type ViewId = "changes" | "graph" | "branches";
-async function restartApp(pushToast: (kind: "warning" | "error", text: string) => void, t: (key: string) => string): Promise<boolean> {
+function readJson<T>(key: string, fallback: T): T {
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;
+ const text = scmStorage.get(key);
+ return text ? { ...fallback, ...(JSON.parse(text) as T) } : fallback;
} catch {
- pushToast("error", t("permissions.restart_failed"));
- return false;
+ return fallback; // a damaged entry falls back to the defaults
}
}
-/**
- * The running backend predates this tab: the one thing to do is restart, so
- * the card says what the tab is for and restarts on a click. A click in the
- * app is the person asking; control clients can never restart it.
- */
-function RestartToConnectCard() {
- const t = useT();
- const pushToast = useEventStore((state) => state.pushToast);
- const [restarting, setRestarting] = useState(false);
- const restart = async () => {
- if (restarting) return;
- setRestarting(true);
- 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">
- <p className="text-[12.5px] font-medium text-foreground">{t("ide_side_panel.git.connect_repo_title")}</p>
- <p className="text-[11.5px] text-muted-foreground">{t("ide_side_panel.git.needs_restart")}</p>
- <button
- type="button"
- data-testid="git-restart"
- disabled={restarting}
- onClick={() => void restart()}
- className="inline-flex h-8 items-center gap-1.5 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 disabled:opacity-60"
- >
- {restarting ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <RefreshCw className="h-3.5 w-3.5" aria-hidden />}
- {t("ide_side_panel.git.restart_button")}
- </button>
- </div>
- );
-}
-
-/** 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>
- );
-}
+const VIEWS_KEY = "jarvis.git.scm.views.v1";
+const WEIGHTS_KEY = "jarvis.git.scm.weights.v1";
+const LIST_KEY = "jarvis.git.scm.list.v1";
+const SCOPE_KEY = "jarvis.git.scm.graphScope.v1";
+const MESSAGE_KEY = (workspaceId: string) => `jarvis.git.scm.message.${workspaceId}`;
/**
- * 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.
+ * The Git tab: source control for the open workspace's repository. Changes
+ * lists every staged, unstaged and conflicting file under the commit box;
+ * Graph draws the history; Branches & Pull Requests is the repository-wide
+ * overview with GitHub's pull requests and CI.
*/
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);
- // 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 [cleaning, setCleaning] = useState<BranchRow[] | null>(null);
- const [alsoRemote, setAlsoRemote] = useState(false);
- const [editors, setEditors] = useState<BranchEditors | null>(null);
- const prsRef = useRef<HTMLDivElement>(null);
- const branchesRef = useRef<HTMLDivElement>(null);
- useEffect(() => {
- let alive = true;
- fetchBranchEditors()
- .then((answer) => alive && setEditors(answer))
- // An older backend has no such route: rows then offer GitHub and copy only.
- .catch(() => alive && setEditors({ file_manager: false, editors: [] }));
- return () => {
- alive = false;
- };
- }, []);
- const openMenu = useCallback((row: BranchRow, x: number, y: number) => {
- 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.
- const [changing, setChanging] = useState(false);
- // The repository just picked. The pick is saved at once, but the GitHub
- // read it starts takes seconds (up to the request timeout); until that
- // answer lands the tab shows the choice and the local branches, never the
- // picker again — a picker that stays put reads as "the click did nothing".
- const [pickedRepo, setPickedRepo] = useState("");
- const [binding, setBinding] = useState(false);
const pushToast = useEventStore((state) => state.pushToast);
- useEffect(() => setChanging(false), [workspaceId]);
- useEffect(() => setPickedRepo(""), [data, workspaceId]);
+ const quick = useQuickInput();
+ const choice = useChoice();
+ const { status, error, refresh } = useScmStatus(workspaceId);
+ const [bump, setBump] = useState(0);
+ const onChanged = useCallback(() => setBump((value) => value + 1), []);
+ const { busy, commands } = useScmCommands({ workspaceId: workspaceId ?? "", status, refresh, quick, ask: choice.ask, onChanged });
+ const [open, setOpen] = useState<Record<ViewId, boolean>>(() => readJson(VIEWS_KEY, { changes: true, graph: true, branches: false }));
+ const [weights, setWeights] = useState<Record<string, number>>(() => readJson(WEIGHTS_KEY, { changes: 1, graph: 1, branches: 1 }));
+ const [settings, setSettings] = useState<ListSettings>(() => readJson<ListSettings>(LIST_KEY, { mode: "list", sort: "path" }));
+ const [scope, setScope] = useState<GraphScope>(() => (scmStorage.get(SCOPE_KEY) as GraphScope) || "auto");
+ const [diff, setDiff] = useState<DiffSource | null>(null);
+ const [menu, setMenu] = useState<{ items: MenuItem[]; x: number; y: number } | null>(null);
+ const [goHead, setGoHead] = useState(0);
+ const [initializing, setInitializing] = useState(false);
+ // The commit message is kept per workspace, across restarts, until it is committed.
+ const [message, setMessageState] = useState(() => (workspaceId ? scmStorage.get(MESSAGE_KEY(workspaceId)) : ""));
+ const [messageError, setMessageError] = useState("");
+ const messageRef = useRef<HTMLTextAreaElement>(null);
+ const shownWorkspace = useRef(workspaceId);
useEffect(() => {
- setFilter("all");
- setMenu(null);
- setCleaning(null);
+ if (shownWorkspace.current === workspaceId) return;
+ shownWorkspace.current = workspaceId;
+ setMessageState(workspaceId ? scmStorage.get(MESSAGE_KEY(workspaceId)) : "");
+ setMessageError("");
}, [workspaceId]);
- useEffect(() => setAlsoRemote(false), [actions.confirmation]);
+ const setMessage = useCallback(
+ (next: string) => {
+ setMessageState(next);
+ setMessageError("");
+ if (workspaceId) scmStorage.set(MESSAGE_KEY(workspaceId), next);
+ },
+ [workspaceId],
+ );
+
+ useEffect(() => scmStorage.set(VIEWS_KEY, JSON.stringify(open)), [open]);
+ useEffect(() => scmStorage.set(WEIGHTS_KEY, JSON.stringify(weights)), [weights]);
+ useEffect(() => scmStorage.set(LIST_KEY, JSON.stringify(settings)), [settings]);
+ useEffect(() => scmStorage.set(SCOPE_KEY, scope), [scope]);
- const items = useMemo(() => (data?.available ? attention(data) : []), [data]);
- const prs = useMemo(() => (data?.available ? openPullRequests(data) : []), [data]);
+ // The graph reads again when the branch, its tip or its upstream moves.
+ const revision = status ? [status.branch, status.head, status.upstream, status.ahead, status.behind, bump].join("|") : String(bump);
+
+ const toggleView = (id: ViewId) => setOpen((current) => ({ ...current, [id]: !current[id] }));
+
+ const runCommit = useCallback(
+ (options: CommitOptions) => {
+ if (!message.trim() && options.kind !== "amend") {
+ setOpen((current) => ({ ...current, changes: true }));
+ setMessageError(t("ide_side_panel.git.scm.message_required"));
+ messageRef.current?.focus();
+ return;
+ }
+ setMessageError("");
+ void commands.commit(message, options).then((made) => made && setMessage(""));
+ },
+ [commands, message, setMessage, t],
+ );
+
+ // Undo puts the commit's message back into the box, as long as nothing new was typed there.
+ const undoLastCommit = useCallback(async () => {
+ const restored = await commands.undoLastCommit();
+ if (restored !== undefined && !message.trim()) setMessage(restored);
+ }, [commands, message, setMessage]);
+
+ const moreMenu = useCallback((): MenuItem[] => {
+ const operation = status?.operation ?? "";
+ return [
+ viewSortMenu(settings, setSettings, t),
+ { kind: "separator", id: "m0" },
+ { id: "pull", label: t("ide_side_panel.git.scm.pull"), run: () => void commands.pull() },
+ { id: "push", label: t("ide_side_panel.git.scm.push"), run: () => void commands.push() },
+ { id: "checkout", label: t("ide_side_panel.git.scm.checkout_to"), run: () => void commands.checkoutTo() },
+ { id: "fetch", label: t("ide_side_panel.git.scm.fetch"), run: () => void commands.fetch() },
+ { kind: "separator", id: "m1" },
+ {
+ kind: "submenu",
+ id: "commit-menu",
+ label: t("ide_side_panel.git.scm.menu_commit"),
+ items: [
+ { id: "c-commit", label: t("ide_side_panel.git.scm.commit"), run: () => runCommit({ kind: "commit" }) },
+ { id: "c-staged", label: t("ide_side_panel.git.scm.commit_staged"), run: () => runCommit({ kind: "commit", scope: "staged" }) },
+ { id: "c-all", label: t("ide_side_panel.git.scm.commit_all"), run: () => runCommit({ kind: "commit", scope: "all" }) },
+ { id: "c-undo", label: t("ide_side_panel.git.scm.undo_last_commit"), disabled: !status?.head, run: () => void undoLastCommit() },
+ ...(operation === "rebase"
+ ? [{ id: "c-abort-rebase", label: t("ide_side_panel.git.scm.abort_rebase"), run: () => void commands.operation("abort") } as MenuItem]
+ : []),
+ { kind: "separator", id: "c1" },
+ { id: "c-amend", label: t("ide_side_panel.git.scm.commit_amend"), run: () => runCommit({ kind: "amend" }) },
+ { id: "c-staged-amend", label: t("ide_side_panel.git.scm.commit_staged_amend"), run: () => runCommit({ kind: "amend", scope: "staged" }) },
+ { id: "c-all-amend", label: t("ide_side_panel.git.scm.commit_all_amend"), run: () => runCommit({ kind: "amend", scope: "all" }) },
+ { kind: "separator", id: "c2" },
+ { id: "c-signoff", label: t("ide_side_panel.git.scm.commit_signed_off"), run: () => runCommit({ kind: "commit", signoff: true }) },
+ { id: "c-staged-signoff", label: t("ide_side_panel.git.scm.commit_staged_signed_off"), run: () => runCommit({ kind: "commit", scope: "staged", signoff: true }) },
+ { id: "c-all-signoff", label: t("ide_side_panel.git.scm.commit_all_signed_off"), run: () => runCommit({ kind: "commit", scope: "all", signoff: true }) },
+ { kind: "separator", id: "c3" },
+ { id: "c-no-verify", label: t("ide_side_panel.git.scm.commit_no_verify"), run: () => runCommit({ kind: "commit", noVerify: true }) },
+ ],
+ },
+ {
+ kind: "submenu",
+ id: "changes-menu",
+ label: t("ide_side_panel.git.scm.menu_changes"),
+ items: [
+ { id: "ch-stage-all", label: t("ide_side_panel.git.scm.stage_all"), run: () => void commands.stageAll() },
+ { id: "ch-unstage-all", label: t("ide_side_panel.git.scm.unstage_all"), run: () => void commands.unstageAll() },
+ { id: "ch-discard-all", label: t("ide_side_panel.git.scm.discard_all"), run: () => void commands.discardAll() },
+ ],
+ },
+ {
+ kind: "submenu",
+ id: "pull-push-menu",
+ label: t("ide_side_panel.git.scm.menu_pull_push"),
+ items: [
+ { id: "pp-sync", label: t("ide_side_panel.git.scm.sync"), run: () => void commands.sync() },
+ { kind: "separator", id: "p1" },
+ { id: "pp-pull", label: t("ide_side_panel.git.scm.pull"), run: () => void commands.pull() },
+ { id: "pp-pull-rebase", label: t("ide_side_panel.git.scm.pull_rebase"), run: () => void commands.pull(true) },
+ { id: "pp-pull-from", label: t("ide_side_panel.git.scm.pull_from"), run: () => void commands.pullFrom() },
+ { kind: "separator", id: "p2" },
+ { id: "pp-push", label: t("ide_side_panel.git.scm.push"), run: () => void commands.push() },
+ { id: "pp-push-to", label: t("ide_side_panel.git.scm.push_to"), run: () => void commands.pushTo() },
+ { id: "pp-push-tags", label: t("ide_side_panel.git.scm.push_tags"), run: () => void commands.pushTags() },
+ { kind: "separator", id: "p3" },
+ { id: "pp-fetch", label: t("ide_side_panel.git.scm.fetch"), run: () => void commands.fetch() },
+ { id: "pp-fetch-prune", label: t("ide_side_panel.git.scm.fetch_prune"), run: () => void commands.fetch({ prune: true }) },
+ { id: "pp-fetch-all", label: t("ide_side_panel.git.scm.fetch_all"), run: () => void commands.fetch({ all_remotes: true }) },
+ ],
+ },
+ {
+ kind: "submenu",
+ id: "branch-menu",
+ label: t("ide_side_panel.git.scm.menu_branch"),
+ items: [
+ { id: "b-merge", label: t("ide_side_panel.git.scm.merge_branch"), run: () => void commands.mergeBranch() },
+ { id: "b-rebase", label: t("ide_side_panel.git.scm.rebase_branch"), run: () => void commands.rebaseBranch() },
+ { kind: "separator", id: "b1" },
+ { id: "b-create", label: t("ide_side_panel.git.scm.create_branch"), run: () => void commands.createBranch() },
+ { id: "b-create-from", label: t("ide_side_panel.git.scm.create_branch_from"), run: () => void commands.createBranchFrom() },
+ { kind: "separator", id: "b2" },
+ { id: "b-rename", label: t("ide_side_panel.git.scm.rename_branch"), disabled: !status?.branch, run: () => void commands.renameBranch() },
+ { id: "b-delete", label: t("ide_side_panel.git.scm.delete_branch"), run: () => void commands.deleteBranch() },
+ { kind: "separator", id: "b3" },
+ { id: "b-publish", label: t("ide_side_panel.git.scm.publish_branch"), disabled: !status?.branch || Boolean(status?.upstream), run: () => void commands.publish() },
+ ],
+ },
+ {
+ kind: "submenu",
+ id: "remote-menu",
+ label: t("ide_side_panel.git.scm.menu_remote"),
+ items: [
+ { id: "r-add", label: t("ide_side_panel.git.scm.add_remote"), run: () => void commands.addRemote() },
+ { id: "r-remove", label: t("ide_side_panel.git.scm.remove_remote"), disabled: !status?.remotes.length, run: () => void commands.removeRemote() },
+ ],
+ },
+ {
+ kind: "submenu",
+ id: "stash-menu",
+ label: t("ide_side_panel.git.scm.menu_stash"),
+ items: [
+ { id: "s-stash", label: t("ide_side_panel.git.scm.stash"), run: () => void commands.stash() },
+ { id: "s-stash-untracked", label: t("ide_side_panel.git.scm.stash_untracked"), run: () => void commands.stash({ include_untracked: true }) },
+ { id: "s-stash-staged", label: t("ide_side_panel.git.scm.stash_staged"), run: () => void commands.stash({ staged: true }) },
+ { kind: "separator", id: "s1" },
+ { id: "s-apply-latest", label: t("ide_side_panel.git.scm.apply_latest_stash"), disabled: !status?.stashes, run: () => void commands.applyStash(false, true) },
+ { id: "s-apply", label: t("ide_side_panel.git.scm.apply_stash"), disabled: !status?.stashes, run: () => void commands.applyStash(false, false) },
+ { kind: "separator", id: "s2" },
+ { id: "s-pop-latest", label: t("ide_side_panel.git.scm.pop_latest_stash"), disabled: !status?.stashes, run: () => void commands.applyStash(true, true) },
+ { id: "s-pop", label: t("ide_side_panel.git.scm.pop_stash"), disabled: !status?.stashes, run: () => void commands.applyStash(true, false) },
+ { kind: "separator", id: "s3" },
+ { id: "s-drop", label: t("ide_side_panel.git.scm.drop_stash"), disabled: !status?.stashes, run: () => void commands.dropStash() },
+ { id: "s-drop-all", label: t("ide_side_panel.git.scm.drop_all_stashes"), disabled: !status?.stashes, run: () => void commands.dropAllStashes() },
+ ],
+ },
+ {
+ kind: "submenu",
+ id: "tags-menu",
+ label: t("ide_side_panel.git.scm.menu_tags"),
+ items: [
+ { id: "t-create", label: t("ide_side_panel.git.scm.create_tag"), run: () => void commands.createTag() },
+ { id: "t-delete", label: t("ide_side_panel.git.scm.delete_tag"), run: () => void commands.deleteTag() },
+ ],
+ },
+ ];
+ }, [status, settings, commands, runCommit, undoLastCommit, t]);
+
+ const scopeMenu = (): MenuItem[] =>
+ (["auto", "current", "all"] as GraphScope[]).map((value) => ({
+ id: `scope-${value}`,
+ label: t(`ide_side_panel.git.scm.scope.${value}`),
+ checked: scope === value,
+ run: () => setScope(value),
+ }));
+
+ const initRepository = async () => {
+ if (!workspace?.path || initializing) return;
+ setInitializing(true);
+ try {
+ await prepareGit(workspace.path, { mode: "init", branch: "", base: "" });
+ } catch (err) {
+ pushToast("error", (err as Error).message);
+ } finally {
+ setInitializing(false);
+ refresh();
+ }
+ };
+
+ const repoName = useMemo(
+ () => ((status?.root || workspace?.path) ?? "").replace(/\\/g, "/").split("/").filter(Boolean).pop() ?? workspace?.name ?? "",
+ [status?.root, workspace?.path, workspace?.name],
+ );
if (!workspace) {
return <p className="px-4 py-6 text-center text-xs text-muted-foreground">{t("ide_side_panel.git.no_workspace")}</p>;
}
- const github = data?.github;
- // The list of repositories only opens when asked for: a folder without a
- // repository picked still shows its local state, with a card that offers the pick.
- const picking = Boolean(data && workspaceId && !pickedRepo && changing && github?.code !== "not_connected");
- const connectRepository = (repo: string) => {
- if (!workspaceId || binding) return;
- setBinding(true);
- bindGitHubRepo(workspaceId, repo)
- .then(() => {
- setPickedRepo(repo);
- refresh();
- })
- .catch((err: Error) => pushToast("error", err.message))
- .finally(() => setBinding(false));
- };
- 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");
+ let changesBody;
+ if (!status) {
+ changesBody =
+ error?.code === "unavailable" ? (
+ <RestartToConnectCard />
+ ) : error ? (
+ <p data-testid="scm-error" className="px-[20px] py-[8px] text-[13px]" style={{ color: "var(--scm-deleted)" }}>
+ {error.message}
+ </p>
+ ) : (
+ <div className="flex justify-center py-4">
+ <Codicon name="loading" spin />
+ </div>
+ );
+ } else if (!status.available) {
+ changesBody = (
+ <div data-testid="scm-unavailable" className="space-y-[12px] px-[20px] py-[10px] text-[13px] leading-[1.4em]">
+ <p>{t("ide_side_panel.git.scm.no_repository")}</p>
+ <button
+ type="button"
+ data-testid="scm-init"
+ disabled={initializing || !workspace.path}
+ onClick={() => void initRepository()}
+ className="scm-button inline-flex h-[26px] w-full items-center justify-center gap-[4px] rounded-[2px] px-[4px] text-[13px]"
+ >
+ {initializing && <Codicon name="loading" spin />}
+ {t("ide_side_panel.git.scm.init_repository")}
+ </button>
+ </div>
+ );
+ } else {
+ changesBody = (
+ <ChangesView
+ key={workspace.id}
+ workspaceId={workspace.id}
+ repoName={repoName}
+ status={status}
+ commands={commands}
+ busy={busy}
+ settings={settings}
+ message={message}
+ onMessage={setMessage}
+ messageError={messageError}
+ messageRef={messageRef}
+ onCommit={runCommit}
+ onDiff={setDiff}
+ onRefresh={refresh}
+ moreMenu={moreMenu}
+ />
+ );
+ }
+ const repository = status?.available;
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 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>
- <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={refreshTip} side="bottom" className="inline-flex">
- <button
- type="button"
- data-testid="git-refresh"
- aria-label={t("ide_side_panel.git.refresh")}
- 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"
+ <section data-testid="ide-git-tab" aria-label={t("ide_side_panel.git.aria")} className="scm-root relative flex h-full min-h-0 flex-col">
+ <div className="flex h-[35px] shrink-0 items-center pl-[20px] pr-[8px]">
+ <span className="min-w-0 flex-1 truncate text-[13px]" style={{ color: "var(--scm-title-fg)" }}>
+ {t("ide_side_panel.git.scm.title")}
+ </span>
+ {repository && (
+ <IconButton label={t("ide_side_panel.git.scm.more_actions")} testId="scm-title-more" onClick={(event) => setMenu({ items: moreMenu(), ...menuPointFor(event.currentTarget) })}>
+ <Codicon name="ellipsis" />
+ </IconButton>
+ )}
+ </div>
+ <div className="relative h-[2px] shrink-0 overflow-hidden" aria-hidden>
+ {busy && <div data-testid="scm-progress" className="scm-progress" />}
+ </div>
+ <ScmViews
+ onWeights={(next) => setWeights((current) => ({ ...current, ...next }))}
+ views={[
+ {
+ id: "changes",
+ title: t("ide_side_panel.git.scm.view_changes"),
+ open: open.changes,
+ onToggle: () => toggleView("changes"),
+ weight: weights.changes ?? 1,
+ actions: repository ? (
+ <IconButton
+ label={settings.mode === "list" ? t("ide_side_panel.git.scm.view_tree") : t("ide_side_panel.git.scm.view_list")}
+ testId="scm-view-mode"
+ onClick={() => setSettings((current) => ({ ...current, mode: current.mode === "list" ? "tree" : "list" }))}
>
- <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 || fetched) && (
- <p data-testid="git-github-state" className="flex min-w-0 items-center gap-1.5 text-[10.5px] text-muted-foreground">
- {boundRepo && (
- <QuickTooltip content={t("ide_side_panel.git.change_repo")} side="bottom" className="inline-flex min-w-0">
+ <Codicon name={settings.mode === "list" ? "list-tree" : "list-flat"} />
+ </IconButton>
+ ) : undefined,
+ body: changesBody,
+ },
+ {
+ id: "graph",
+ title: t("ide_side_panel.git.scm.view_graph"),
+ open: open.graph,
+ onToggle: () => toggleView("graph"),
+ weight: weights.graph ?? 1,
+ actions: repository ? (
+ <>
+ <span className="mr-[4px] inline-flex min-w-0 items-center gap-[3px] text-[12px] opacity-80">
+ <Codicon name="repo" />
+ <span className="max-w-[110px] truncate">{repoName}</span>
+ </span>
<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"
+ data-testid="scm-graph-scope"
+ onClick={(event) => setMenu({ items: scopeMenu(), ...menuPointFor(event.currentTarget) })}
+ className="scm-action !w-auto gap-[3px] px-[3px] text-[12px]"
>
- <span className="truncate">{boundRepo}</span>
+ <Codicon name="git-branch" />
+ {t(`ide_side_panel.git.scm.scope.${scope}`)}
</button>
- </QuickTooltip>
- )}
- {boundRepo && <span aria-hidden>·</span>}
- <span className="min-w-0 truncate">
- {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>
-
- {picking && data && workspaceId ? (
- <GitHubRepoPicker
- key={workspaceId}
- workspaceId={workspaceId}
- current={github?.repo ?? ""}
- suggested={github?.suggested_repo ?? ""}
- onPicked={(repo) => {
- setPickedRepo(repo);
- setChanging(false);
- refresh();
- }}
- onCancel={() => setChanging(false)}
- />
- ) : (
- <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>
- )
+ <IconButton label={t("ide_side_panel.git.scm.go_to_current")} testId="scm-graph-head" onClick={() => setGoHead((value) => value + 1)}>
+ <Codicon name="target" />
+ </IconButton>
+ <IconButton label={t("ide_side_panel.git.scm.fetch")} testId="scm-graph-fetch" disabled={busy !== ""} onClick={() => void commands.fetch()}>
+ <Codicon name="repo-fetch" />
+ </IconButton>
+ <IconButton label={t("ide_side_panel.git.scm.pull")} testId="scm-graph-pull" disabled={busy !== ""} onClick={() => void commands.pull()}>
+ <Codicon name="repo-pull" />
+ </IconButton>
+ <IconButton label={t("ide_side_panel.git.scm.push")} testId="scm-graph-push" disabled={busy !== ""} onClick={() => void commands.push()}>
+ <Codicon name="repo-push" />
+ </IconButton>
+ <IconButton label={t("ide_side_panel.git.scm.refresh")} testId="scm-graph-refresh" onClick={onChanged}>
+ <Codicon name="refresh" />
+ </IconButton>
+ </>
+ ) : undefined,
+ body: repository ? (
+ <GraphView workspaceId={workspace.id} revision={revision} scope={scope} commands={commands} onDiff={setDiff} targetHead={goHead} />
) : (
- <LoadingShape />
- )
- ) : !data.available ? (
- <p data-testid="git-unavailable" className="px-4 py-6 text-center text-xs text-muted-foreground">
- {data.reason}
- </p>
- ) : (
- <>
- {!data.checkout && <OlderBackendNote />}
- <StatusPanel key={workspace.id} overview={data} actions={actions} onOpenChanges={() => useIdeSidePanelStore.getState().openTab("changes")} />
- {github?.code === "not_connected" && <ConnectGitHubCard />}
- {github?.code === "needs_repo" && !pickedRepo && (
- <ConnectRepositoryCard
- suggested={github.suggested_repo}
- busy={binding}
- onUse={connectRepository}
- onChoose={() => setChanging(true)}
- />
- )}
- <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 }))}
- >
- <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>
- )}
-
- {menu && data && (
- <BranchMenu
- row={menu.row}
- repoUrl={github?.repo_url ?? ""}
- 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();
- }}
- />
- )}
+ <p className="px-[20px] py-[4px] text-[13px] opacity-70">{t("ide_side_panel.git.scm.no_commits")}</p>
+ ),
+ },
+ {
+ id: "branches",
+ title: t("ide_side_panel.git.scm.view_branches"),
+ open: open.branches,
+ onToggle: () => toggleView("branches"),
+ weight: weights.branches ?? 1,
+ body: <RepositoryOverview onChanged={refresh} />,
+ },
+ ]}
+ />
+ {quick.element}
+ {choice.element}
+ {diff && <DiffDialog source={diff} onClose={() => setDiff(null)} />}
+ {menu && <ScmMenu items={menu.items} x={menu.x} y={menu.y} onClose={() => setMenu(null)} />}
</section>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/RepositoryOverview.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/RepositoryOverview.test.tsx
new file mode 100644
index 0000000000..f86a4b34d6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/RepositoryOverview.test.tsx
@@ -0,0 +1,712 @@
+import { StrictMode } from "react";
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RepositoryOverview, resetGitOverviewCache } from "./RepositoryOverview";
+import type { BranchRow, Checkout, CiStatus, PullRequest, RepoOverview } from "./gitOverviewApi";
+import { openExternalUrl } from "@/lib/openExternal";
+import { useEventStore } from "@/store/events";
+import { useIdeChatStore } from "@/store/ideChat";
+
+vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn(async () => true) }));
+
+const noCi: CiStatus = { state: "none", url: "", total: 0, passed: 0, failed: 0, running: 0, pending: 0, commit: "", names: [] };
+
+function branch(name: string, extra: Partial<BranchRow> = {}): BranchRow {
+ return {
+ name,
+ current: false,
+ remote_only: false,
+ upstream: `origin/${name}`,
+ ahead: 0,
+ behind: 0,
+ head: "abc123def456",
+ committed_at: 0,
+ worktree: "",
+ on_github: true,
+ merged_into: [],
+ pull_requests: [],
+ ci: noCi,
+ ci_stale: false,
+ base_ahead: 1,
+ base_behind: 0,
+ ...extra,
+ };
+}
+
+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}`,
+ state,
+ base: "main",
+ head: "x",
+ head_oid: "",
+ merged_at: "",
+ updated_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: "",
+ root: "/code/app",
+ branch: "feature/wip",
+ detached: false,
+ head: "abc123def456",
+ default_branch: "main",
+ truncated: false,
+ github: {
+ available: true,
+ reason: "",
+ code: "",
+ repo: "o/r",
+ suggested_repo: "o/r",
+ source: "app",
+ repo_url: "https://github.com/o/r",
+ fetched_at: Date.now() / 1000,
+ },
+ branches: [
+ branch("feature/wip", {
+ current: true,
+ ahead: 2,
+ pull_requests: [pr(7, "open")],
+ ci: { ...noCi, state: "running", url: "https://github.com/o/r/actions/runs/7", total: 3, passed: 1, running: 2, names: ["tests"] },
+ }),
+ branch("main", { ci: { ...noCi, state: "success", total: 4, passed: 4, url: "https://github.com/o/r/actions/runs/1" } }),
+ branch("feature/done", {
+ merged_into: [{ target: "main", via: "pull_request", number: 5, url: "" }],
+ pull_requests: [pr(5, "merged")],
+ ci: { ...noCi, state: "success", total: 2, passed: 2 },
+ }),
+ branch("feature/queued", { pull_requests: [pr(8, "queued")] }),
+ branch("feature/draft", { pull_requests: [pr(9, "draft")] }),
+ branch("feature/dropped", {
+ pull_requests: [pr(4, "closed")],
+ ci: { ...noCi, state: "failure", total: 2, passed: 1, failed: 1, names: ["lint"], url: "https://github.com/o/r/actions/runs/4" },
+ }),
+ ],
+ remote_branches: [branch("only-remote", { remote_only: true, upstream: "" })],
+ 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. */
+let gate: Promise<void> | null = null;
+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",
+ base: "origin/main",
+ commits: [
+ { sha: "aaaaaaaaaaaa", subject: "Add the widget", author: "Ada", committed_at: 1_790_000_000, on_github: false },
+ { sha: "bbbbbbbbbbbb", subject: "Start the widget", author: "Ada", committed_at: 1_789_000_000, on_github: true },
+ ],
+ commits_truncated: false,
+ files: [
+ { path: "src/widget.ts", status: "added", added: 12, removed: 0 },
+ { path: "README.md", status: "modified", added: 2, removed: 1 },
+ ],
+ files_truncated: false,
+ reason: "",
+};
+const FILE_DIFF = {
+ path: "src/widget.ts",
+ status: "added",
+ binary: false,
+ added: 1,
+ removed: 0,
+ truncated: false,
+ hunks: [{ header: "@@ -0,0 +1 @@", lines: [{ kind: "add", text: "export const widget = 1;", old_no: null, new_no: 1 }] }],
+};
+const REPOS = {
+ connected: true,
+ source: "app",
+ login: "octo",
+ reason: "",
+ repos: [
+ { name: "octo/other", description: "Something else", private: true, fork: false, url: "", pushed_at: "" },
+ { name: "o/r", description: "", private: false, fork: false, url: "", pushed_at: "" },
+ ],
+};
+const ACTION = /\/api\/agentic-ide\/git\/(fetch|pull|commit|switch|prepare|branch\/push|branch\/pull-request|branch\/update|branch\/delete)$/;
+
+beforeEach(() => {
+ answer = OVERVIEW;
+ status = 200;
+ gate = null;
+ calls.length = 0;
+ 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) => {
+ const url = String(input);
+ 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",
+ folder: "/code/app",
+ branch: String(posts.at(-1)?.body.branch ?? ""),
+ created: true,
+ });
+ }
+ if (url.includes("/github/repos")) return json(REPOS);
+ if (url.includes("/branch/contents")) return json(CONTENTS);
+ if (url.includes("/branch/diff")) {
+ diffs.push(url);
+ return json(FILE_DIFF);
+ }
+ if (url.includes("/branch/editors")) return json({ file_manager: true, editors: [{ id: "code", label: "VS Code" }] });
+ if (url.includes("/branch/open")) {
+ opens.push(String(init?.body));
+ return json({ opened: true, path: "/code/app" });
+ }
+ if (url.includes("/github/binding")) {
+ puts.push(String(init?.body));
+ answer = OVERVIEW;
+ return json({ ok: true, repo: "o/r" });
+ }
+ if (gate) await gate;
+ return json(answer, status);
+ }),
+ );
+ useEventStore.setState({ activeSection: "agentic-ide" });
+ useIdeChatStore.setState({ workspace: { id: "w1", name: "App", path: "/code/app" }, stagedPane: null });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.mocked(openExternalUrl).mockClear();
+});
+
+const row = (name: string) => screen.getAllByTestId("git-branch-row").find((el) => el.dataset.branch === name)!;
+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("RepositoryOverview — 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(<RepositoryOverview />);
+ 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(<RepositoryOverview />);
+ 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>
+ <RepositoryOverview />
+ </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(<RepositoryOverview />);
+ 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("RepositoryOverview — branches", () => {
+ it("lists the workspace's branches and marks the checked-out one", async () => {
+ render(<RepositoryOverview />);
+ 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(calls[0]).toContain("/api/agentic-ide/git/overview?workspace_id=w1");
+ });
+
+ it("shows each pull request state with GitHub's colour", async () => {
+ render(<RepositoryOverview />);
+ await screen.findAllByTestId("git-branch-row");
+ const state = (name: string) => within(row(name)).getByTestId("git-pr").querySelector("[data-pr-state]");
+ expect(state("feature/wip")?.getAttribute("class")).toContain("text-success");
+ expect(state("feature/done")?.getAttribute("class")).toContain("--gh-merged");
+ expect(state("feature/queued")?.getAttribute("class")).toContain("text-warning");
+ expect(state("feature/draft")?.getAttribute("class")).toContain("text-muted-foreground");
+ expect(state("feature/dropped")?.getAttribute("class")).toContain("text-destructive");
+ expect(state("feature/dropped")?.getAttribute("data-pr-state")).toBe("closed");
+ });
+
+ it("keeps CI apart from merging: a merged branch still shows its own green check", async () => {
+ render(<RepositoryOverview />);
+ await screen.findAllByTestId("git-branch-row");
+ const done = row("feature/done");
+ 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-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.
+ expect(within(row("feature/queued")).queryByTestId("git-ci")).toBeNull();
+ });
+
+ it("opens the pull request and the CI run in the browser", async () => {
+ render(<RepositoryOverview />);
+ await screen.findAllByTestId("git-branch-row");
+ fireEvent.click(within(row("feature/wip")).getByTestId("git-pr"));
+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/pull/7");
+ fireEvent.click(within(row("feature/dropped")).getByTestId("git-ci"));
+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/actions/runs/4");
+ });
+
+ it("explains every icon in its tooltip", async () => {
+ render(<RepositoryOverview />);
+ await screen.findAllByTestId("git-branch-row");
+ fireEvent.mouseEnter(within(row("feature/dropped")).getByTestId("git-ci").parentElement!);
+ const tip = await screen.findByRole("tooltip");
+ expect(tip.textContent).toContain("CI failed");
+ expect(tip.textContent).toContain("lint");
+ });
+
+ it("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(<RepositoryOverview />);
+ await screen.findAllByTestId("git-branch-row");
+ 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 () => {
+ const now = Math.floor(Date.now() / 1000);
+ answer = {
+ ...OVERVIEW,
+ branches: [
+ branch("fresh", { committed_at: now - 2 * 3600 }),
+ branch("old", { committed_at: Date.UTC(2024, 2, 3, 12) / 1000 }),
+ branch("undated"),
+ ],
+ };
+ render(<RepositoryOverview />);
+ await screen.findAllByTestId("git-branch-row");
+ 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(<RepositoryOverview />);
+ 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(<RepositoryOverview />);
+ 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(<RepositoryOverview />);
+ 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(<RepositoryOverview />);
+ await screen.findAllByTestId("git-branch-row");
+ expect(screen.queryByTestId("git-branch-details")).toBeNull();
+
+ fireEvent.click(within(row("feature/wip")).getByTestId("git-branch-toggle"));
+ const details = within(row("feature/wip")).getByTestId("git-branch-details");
+ await within(details).findByTestId("git-branch-commits");
+ fireEvent.click(await within(details).findByTestId("git-open-folder"));
+ await vi.waitFor(() => expect(opens).toHaveLength(1));
+ expect(JSON.parse(opens[0])).toEqual({ workspace_id: "w1", branch: "feature/wip", target: "folder" });
+ fireEvent.click(within(details).getByTestId("git-open-code"));
+ await vi.waitFor(() => expect(JSON.parse(opens[1]).target).toBe("code"));
+ fireEvent.click(within(details).getByTestId("git-open-github"));
+ 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, 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-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.
+ // A commit only on this computer gets no GitHub link (that page would be a 404).
+ const commit = (sha: string) => within(details).getAllByTestId("git-branch-commit").find((el) => el.dataset.sha === sha)!;
+ expect(within(commit("aaaaaaaaaaaa")).queryByTestId("git-commit-link")).toBeNull();
+ expect(within(commit("aaaaaaaaaaaa")).getByTestId("git-commit-local")).toBeTruthy();
+ fireEvent.click(within(commit("bbbbbbbbbbbb")).getByTestId("git-commit-link"));
+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/commit/bbbbbbbbbbbb");
+ expect(within(details).getByTestId("git-branch-commits").textContent).toContain("Add the widget");
+ expect(within(details).getByTestId("git-branch-commits").textContent).toContain("2 commits not in origin/main");
+ const file = within(details).getAllByTestId("git-branch-file").find((el) => el.dataset.path === "src/widget.ts")!;
+ fireEvent.click(within(file).getByRole("button"));
+ expect(await within(file).findByTestId("explorer-diff")).toBeTruthy();
+ expect(within(file).getByTestId("explorer-diff").textContent).toContain("export const widget = 1;");
+ expect(diffs[0]).toContain("path=src%2Fwidget.ts");
+ expect(diffs[0]).toContain("base=main");
+
+ // A second click folds it away again.
+ fireEvent.click(within(row("feature/wip")).getByTestId("git-branch-toggle"));
+ 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(<RepositoryOverview />);
+ 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(<RepositoryOverview />);
+ 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(<RepositoryOverview />);
+ 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(<RepositoryOverview />);
+ 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 an open question when another workspace is shown", async () => {
+ answer = withCheckout({ ahead: 0, files: 3, unstaged: 2, untracked: 1 }, { ahead: 0 });
+ render(<RepositoryOverview />);
+ 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"));
+ 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(posts).toEqual([]);
+ });
+
+ it("offers GitHub pages and copies from a branch's menu", async () => {
+ render(<RepositoryOverview />);
+ await screen.findAllByTestId("git-branch-row");
+ fireEvent.click(within(row("feature/queued")).getByTestId("git-branch-more"));
+ const menu = await screen.findByTestId("git-branch-menu");
+ expect(within(menu).getByTestId("git-menu-pr").textContent).toContain("#8");
+ // A live pull request exists, so there is nothing new to create.
+ expect(within(menu).queryByTestId("git-menu-create-pr")).toBeNull();
+ fireEvent.click(within(menu).getByTestId("git-menu-compare"));
+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/compare/main...feature/queued");
+ expect(screen.queryByTestId("git-branch-menu")).toBeNull();
+
+ fireEvent.contextMenu(row("feature/done"));
+ const second = await screen.findByTestId("git-branch-menu");
+ fireEvent.click(within(second).getByTestId("git-menu-create-pr"));
+ expect(openExternalUrl).toHaveBeenCalledWith("https://github.com/o/r/compare/main...feature/done?expand=1");
+ });
+});
+
+describe("RepositoryOverview — 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(<RepositoryOverview />);
+ expect((await screen.findByTestId("git-unavailable")).textContent).toContain("not a git repository");
+ });
+
+ it("shows the local state before a GitHub repository is picked, and connects the recommended one in a click", async () => {
+ answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "" } };
+ render(<RepositoryOverview />);
+ // Nothing is hidden behind the question: the branches are all there.
+ expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(6);
+ expect(screen.queryByTestId("git-repo-picker")).toBeNull();
+ const card = screen.getByTestId("git-connect-repo");
+ expect(within(card).getByTestId("git-connect-suggested").textContent).toBe("o/r");
+ fireEvent.click(within(card).getByTestId("git-connect-suggested"));
+ await vi.waitFor(() => expect(puts).toEqual([JSON.stringify({ workspace_id: "w1", repo: "o/r" })]));
+ await vi.waitFor(() => expect(screen.queryByTestId("git-connect-repo")).toBeNull());
+ expect(await screen.findByTestId("git-section-prs")).toBeTruthy();
+ });
+
+ it("offers the list of repositories for a folder whose remote is not on GitHub", async () => {
+ answer = {
+ ...OVERVIEW,
+ github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "", suggested_repo: "" },
+ };
+ render(<RepositoryOverview />);
+ const card = await screen.findByTestId("git-connect-repo");
+ expect(within(card).queryByTestId("git-connect-suggested")).toBeNull();
+ expect(screen.getAllByTestId("git-branch-row")).toHaveLength(6);
+ fireEvent.click(within(card).getByTestId("git-connect-choose"));
+ await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));
+ // The list can be left again without picking; the local state comes back.
+ fireEvent.click(screen.getByLabelText("Keep the current repository"));
+ expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(6);
+ });
+
+ it("asks which GitHub repository the folder is, recommending its remote", async () => {
+ answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "" } };
+ render(<RepositoryOverview />);
+ fireEvent.click(within(await screen.findByTestId("git-connect-repo")).getByTestId("git-connect-choose"));
+ // 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(<RepositoryOverview />);
+ fireEvent.click(within(await screen.findByTestId("git-connect-repo")).getByTestId("git-connect-choose"));
+ 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(<RepositoryOverview />);
+ 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(<RepositoryOverview />);
+ expect(await screen.findByTestId("git-connect-github")).toBeTruthy();
+ expect(screen.getAllByTestId("git-branch-row")).toHaveLength(6);
+ // 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 () => {
+ answer = { detail: "Not Found" };
+ status = 404;
+ render(<RepositoryOverview />);
+ expect((await screen.findByTestId("git-error")).textContent).toContain("Connect a GitHub repository");
+ fireEvent.click(screen.getByTestId("git-restart"));
+ await vi.waitFor(() => expect(calls).toContain("/api/settings/restart-app"));
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/RepositoryOverview.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/RepositoryOverview.tsx
new file mode 100644
index 0000000000..63efd5f8f2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/RepositoryOverview.tsx
@@ -0,0 +1,506 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { ExternalLink, Loader2, RefreshCw } 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 { useIdeChatStore } from "@/store/ideChat";
+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, ConnectRepositoryCard, GitHubRepoPicker } from "./GitHubRepoPicker";
+import { attention, canCleanUp, checkoutOf, openPullRequests, type AttentionItem, type BranchFilter } from "./gitInsights";
+import {
+ bindGitHubRepo,
+ fetchBranchEditors,
+ fetchGitOverview,
+ GitOverviewError,
+ type BranchEditors,
+ type BranchRow,
+ type RepoOverview,
+} from "./gitOverviewApi";
+import { PullRequestList } from "./PullRequestList";
+import { Section } from "./Section";
+import { useGitActions } from "./useGitActions";
+
+/**
+ * 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 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;
+
+/**
+ * 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>();
+
+/** 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>(() => (workspaceId ? (LAST_OVERVIEW.get(workspaceId) ?? null) : null));
+ const [error, setError] = useState("");
+ const [routeMissing, setRouteMissing] = useState(false);
+ const [loading, setLoading] = useState(false);
+ 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(() => {
+ 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 = forceNext.current;
+ forceNext.current = false;
+ let githubLoading = false;
+ const tick = async () => {
+ if (useEventStore.getState().activeSection === "agentic-ide") {
+ setLoading(true);
+ try {
+ const next = await fetchGitOverview(workspaceId, refresh);
+ refresh = false;
+ githubLoading = next.github?.code === "loading" || Boolean(next.github?.refreshing);
+ LAST_OVERVIEW.set(workspaceId, next);
+ if (alive) {
+ setData(next);
+ setError("");
+ setRouteMissing(false);
+ }
+ } catch (err) {
+ // Keep the last answer on screen; the next tick tries again.
+ if (alive) {
+ setError((err as Error).message);
+ setRouteMissing(err instanceof GitOverviewError && err.routeMissing);
+ }
+ } finally {
+ if (alive) setLoading(false);
+ }
+ }
+ const delay = githubLoading ? POLL_LOADING_MS + Math.random() * 500 : POLL_MS + Math.random() * POLL_JITTER_MS;
+ if (alive) timer = window.setTimeout(tick, delay);
+ };
+ void tick();
+ return () => {
+ alive = false;
+ window.clearTimeout(timer);
+ };
+ }, [workspaceId, round]);
+ const refresh = useCallback(() => {
+ forceNext.current = true;
+ setRound((value) => value + 1);
+ }, []);
+ return { data, error, routeMissing, loading, refresh };
+}
+
+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;
+ }
+}
+
+/**
+ * The running backend predates this tab: the one thing to do is restart, so
+ * the card says what the tab is for and restarts on a click. A click in the
+ * app is the person asking; control clients can never restart it.
+ */
+export function RestartToConnectCard() {
+ const t = useT();
+ const pushToast = useEventStore((state) => state.pushToast);
+ const [restarting, setRestarting] = useState(false);
+ const restart = async () => {
+ if (restarting) return;
+ setRestarting(true);
+ 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">
+ <p className="text-[12.5px] font-medium text-foreground">{t("ide_side_panel.git.connect_repo_title")}</p>
+ <p className="text-[11.5px] text-muted-foreground">{t("ide_side_panel.git.needs_restart")}</p>
+ <button
+ type="button"
+ data-testid="git-restart"
+ disabled={restarting}
+ onClick={() => void restart()}
+ className="inline-flex h-8 items-center gap-1.5 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 disabled:opacity-60"
+ >
+ {restarting ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <RefreshCw className="h-3.5 w-3.5" aria-hidden />}
+ {t("ide_side_panel.git.restart_button")}
+ </button>
+ </div>
+ );
+}
+
+/** 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's Branches view: what needs a look across the repository, every
+ * open pull request with its CI, and every branch with what it is merged into.
+ * What matters can be done here. `onChanged` tells the rest of the tab that a
+ * branch action may have moved the checkout.
+ */
+export function RepositoryOverview({ onChanged }: { onChanged?: () => void }) {
+ const t = useT();
+ const lang = useRunLocale();
+ const workspace = useIdeChatStore((state) => state.workspace);
+ const workspaceId = workspace?.id ?? null;
+ const { data, error, routeMissing, loading, refresh: reread } = useGitOverview(workspaceId);
+ const changed = useRef(onChanged);
+ changed.current = onChanged;
+ const refresh = useCallback(() => {
+ reread();
+ changed.current?.();
+ }, [reread]);
+ // 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 [cleaning, setCleaning] = useState<BranchRow[] | null>(null);
+ const [alsoRemote, setAlsoRemote] = useState(false);
+ const [editors, setEditors] = useState<BranchEditors | null>(null);
+ const prsRef = useRef<HTMLDivElement>(null);
+ const branchesRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ let alive = true;
+ fetchBranchEditors()
+ .then((answer) => alive && setEditors(answer))
+ // An older backend has no such route: rows then offer GitHub and copy only.
+ .catch(() => alive && setEditors({ file_manager: false, editors: [] }));
+ return () => {
+ alive = false;
+ };
+ }, []);
+ const openMenu = useCallback((row: BranchRow, x: number, y: number) => {
+ 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.
+ const [changing, setChanging] = useState(false);
+ // The repository just picked. The pick is saved at once, but the GitHub
+ // read it starts takes seconds (up to the request timeout); until that
+ // answer lands the tab shows the choice and the local branches, never the
+ // picker again — a picker that stays put reads as "the click did nothing".
+ const [pickedRepo, setPickedRepo] = useState("");
+ const [binding, setBinding] = useState(false);
+ const pushToast = useEventStore((state) => state.pushToast);
+ useEffect(() => setChanging(false), [workspaceId]);
+ useEffect(() => setPickedRepo(""), [data, workspaceId]);
+ useEffect(() => {
+ setFilter("all");
+ setMenu(null);
+ setCleaning(null);
+ }, [workspaceId]);
+ 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>;
+ }
+ const github = data?.github;
+ // The list of repositories only opens when asked for: a folder without a
+ // repository picked still shows its local state, with a card that offers the pick.
+ const picking = Boolean(data && workspaceId && !pickedRepo && changing && github?.code !== "not_connected");
+ const connectRepository = (repo: string) => {
+ if (!workspaceId || binding) return;
+ setBinding(true);
+ bindGitHubRepo(workspaceId, repo)
+ .then(() => {
+ setPickedRepo(repo);
+ refresh();
+ })
+ .catch((err: Error) => pushToast("error", err.message))
+ .finally(() => setBinding(false));
+ };
+ const boundRepo = pickedRepo || github?.repo || "";
+ 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="git-repository-overview" aria-label={t("ide_side_panel.git.aria")} className="flex h-full min-h-0 flex-col">
+ <div className="shrink-0 border-b border-border/60 px-3 py-1">
+ <div className="flex items-center gap-2">
+ <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={refreshTip} side="bottom" className="inline-flex">
+ <button
+ type="button"
+ data-testid="git-refresh"
+ aria-label={t("ide_side_panel.git.refresh")}
+ 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 || fetching || github?.refreshing) && "animate-spin motion-reduce:animate-none")} aria-hidden />
+ </button>
+ </QuickTooltip>
+ </span>
+ </div>
+ {(boundRepo || fetched) && (
+ <p data-testid="git-github-state" className="flex min-w-0 items-center gap-1.5 text-[10.5px] text-muted-foreground">
+ {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">
+ {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>
+
+ {picking && data && workspaceId ? (
+ <GitHubRepoPicker
+ key={workspaceId}
+ workspaceId={workspaceId}
+ current={github?.repo ?? ""}
+ suggested={github?.suggested_repo ?? ""}
+ onPicked={(repo) => {
+ setPickedRepo(repo);
+ setChanging(false);
+ refresh();
+ }}
+ onCancel={() => setChanging(false)}
+ />
+ ) : (
+ <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>
+ )
+ ) : (
+ <LoadingShape />
+ )
+ ) : !data.available ? (
+ <p data-testid="git-unavailable" className="px-4 py-6 text-center text-xs text-muted-foreground">
+ {data.reason}
+ </p>
+ ) : (
+ <>
+ {!data.checkout && <OlderBackendNote />}
+ {github?.code === "not_connected" && <ConnectGitHubCard />}
+ {github?.code === "needs_repo" && !pickedRepo && (
+ <ConnectRepositoryCard
+ suggested={github.suggested_repo}
+ busy={binding}
+ onUse={connectRepository}
+ onChoose={() => setChanging(true)}
+ />
+ )}
+ <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 }))}
+ >
+ <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>
+ )}
+
+ {menu && data && (
+ <BranchMenu
+ row={menu.row}
+ repoUrl={github?.repo_url ?? ""}
+ 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/StatusPanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/StatusPanel.tsx
deleted file mode 100644
index a85cfdad3f..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/StatusPanel.tsx
+++ /dev/null
@@ -1,417 +0,0 @@
-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 "branch_off":
- return {
- title: plural(t, "ide_side_panel.git.next.branch_off", step.count),
- reason: fill(key("branch_off_reason"), { branch: overview.default_branch }),
- action: key("branch_off_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 [naming, setNaming] = useState(false);
- const [branchName, setBranchName] = 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 "branch_off":
- return setNaming(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 startBranch = async () => {
- const name = branchName.trim();
- if (!name) return;
- if (await actions.createBranch(name)) {
- setBranchName("");
- setNaming(false);
- }
- };
- 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>
- )}
-
- {naming ? (
- <div data-testid="git-branch-form" className="mt-2.5 space-y-1.5 rounded-lg border border-border/70 bg-secondary/40 p-2">
- <input
- data-testid="git-branch-name"
- autoFocus
- value={branchName}
- onChange={(event) => setBranchName(event.target.value)}
- onKeyDown={(event) => {
- if (event.key === "Enter") void startBranch();
- if (event.key === "Escape") {
- event.stopPropagation();
- setNaming(false);
- }
- }}
- placeholder={t("ide_side_panel.git.branch.placeholder")}
- aria-label={t("ide_side_panel.git.branch.placeholder")}
- className="h-7 w-full rounded-md border border-border/70 bg-background px-2 font-mono text-[12px] text-foreground outline-none placeholder:font-sans placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"
- />
- <p className="text-[10.5px] leading-snug text-muted-foreground">{t("ide_side_panel.git.branch.scope")}</p>
- <div className="flex justify-end gap-1.5">
- <button
- type="button"
- onClick={() => setNaming(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-branch-submit"
- disabled={!branchName.trim() || actions.busy !== ""}
- onClick={() => void startBranch()}
- 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.startsWith("branch:") && <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />}
- {t("ide_side_panel.git.branch.create")}
- </button>
- </div>
- </div>
- ) : 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 && !naming && 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/scm/ChangesView.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/ChangesView.tsx
new file mode 100644
index 0000000000..2655c96e16
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/ChangesView.tsx
@@ -0,0 +1,799 @@
+import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode, type RefObject } from "react";
+import { fill, useT } from "@/i18n";
+import { isMacClient } from "@/lib/embeddedDesktop";
+import { cn } from "@/lib/utils";
+import { QuickTooltip } from "@/components/ui/tooltip";
+import { useCodeEditorStore } from "@/store/codeEditor";
+import { revealInExplorer } from "@/store/ideExplorer";
+import { useEventStore } from "@/store/events";
+import { fetchHeadText } from "../../../editor/editorApi";
+import { FileTypeIcon } from "../../explorer/FileTypeIcon";
+import type { ScmFile, ScmStatus } from "./scmApi";
+import {
+ baseName,
+ buildRows,
+ dirName,
+ groupsOf,
+ letterTone,
+ pathsOfRow,
+ primaryAction,
+ statusKey,
+ workspacePath,
+ type GroupId,
+ type Row,
+ type SortKey,
+ type ViewMode,
+} from "./scmModel";
+import { Codicon, Twistie } from "./Codicon";
+import { ScmMenu, menuPointFor, type MenuItem } from "./ScmMenu";
+import type { CommitOptions, ScmCommands } from "./useScm";
+import type { DiffSource } from "./DiffDialog";
+
+export const ROW_HEIGHT = 22;
+/** Each tree level steps in by 8 px. */
+const INDENT = 8;
+const OVERSCAN = 12;
+
+export function IconButton({
+ label,
+ testId,
+ onClick,
+ disabled,
+ children,
+ className,
+}: {
+ label: string;
+ testId: string;
+ onClick: (event: MouseEvent<HTMLButtonElement>) => void;
+ disabled?: boolean;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <QuickTooltip content={label} side="bottom" className="inline-flex shrink-0">
+ <button
+ type="button"
+ aria-label={label}
+ data-testid={testId}
+ disabled={disabled}
+ onClick={(event) => {
+ event.stopPropagation();
+ onClick(event);
+ }}
+ className={cn("scm-action", className)}
+ >
+ {children}
+ </button>
+ </QuickTooltip>
+ );
+}
+
+const modKey = () => (typeof navigator !== "undefined" && isMacClient(navigator.userAgent) ? "Cmd" : "Ctrl");
+
+/** The pane state the list and the menus share. */
+export interface ListSettings {
+ mode: ViewMode;
+ sort: SortKey;
+}
+
+const FileRow = memo(function FileRow({
+ row,
+ selected,
+ focused,
+ mode,
+ onPointer,
+ onContext,
+ onOpenFile,
+ onDiscard,
+ onStage,
+ onUnstage,
+}: {
+ row: Extract<Row, { kind: "file" }>;
+ selected: boolean;
+ focused: boolean;
+ mode: ViewMode;
+ onPointer: (row: Row, event: MouseEvent) => void;
+ onContext: (row: Row, event: MouseEvent) => void;
+ onOpenFile: (row: Extract<Row, { kind: "file" }>) => void;
+ onDiscard: (row: Row) => void;
+ onStage: (row: Row) => void;
+ onUnstage: (row: Row) => void;
+}) {
+ const t = useT();
+ const { file, group } = row;
+ const tone = letterTone(file.letter);
+ const state = t(statusKey(file.status));
+ const deleted = file.letter === "D";
+ const description = mode === "list" ? dirName(file.path) : "";
+ const tip = `${file.original ? `${file.original} → ` : ""}${file.path} • ${state}`;
+ return (
+ <div
+ role="treeitem"
+ aria-selected={selected}
+ data-focused={focused || undefined}
+ data-testid="scm-file"
+ data-path={file.path}
+ data-group={group}
+ data-letter={file.letter}
+ onClick={(event) => onPointer(row, event)}
+ onDoubleClick={(event) => onPointer(row, event)}
+ onContextMenu={(event) => onContext(row, event)}
+ style={{ height: ROW_HEIGHT, paddingLeft: (row.depth + 1) * INDENT }}
+ className="scm-row flex cursor-pointer select-none items-center"
+ >
+ <Twistie visible={false} />
+ <FileTypeIcon path={file.path} className="mr-[6px] h-4 w-4" />
+ <QuickTooltip content={tip} side="bottom" className="flex min-w-0 flex-1 items-baseline overflow-hidden whitespace-nowrap">
+ <span className={cn("truncate", tone, deleted && "line-through")}>{baseName(file.path)}</span>
+ {description && <span className="ml-[0.5em] min-w-0 truncate text-[0.9em] opacity-70">{description}</span>}
+ </QuickTooltip>
+ <span className="scm-actions shrink-0 items-center gap-[2px] pl-1">
+ {file.letter !== "D" && (
+ <IconButton label={t("ide_side_panel.git.scm.open_file")} testId="scm-open-file" onClick={() => onOpenFile(row)}>
+ <Codicon name="go-to-file" />
+ </IconButton>
+ )}
+ {group === "changes" && (
+ <IconButton label={t("ide_side_panel.git.scm.discard_changes")} testId="scm-discard" onClick={() => onDiscard(row)}>
+ <Codicon name="discard" />
+ </IconButton>
+ )}
+ {group === "staged" ? (
+ <IconButton label={t("ide_side_panel.git.scm.unstage_changes")} testId="scm-unstage" onClick={() => onUnstage(row)}>
+ <Codicon name="remove" />
+ </IconButton>
+ ) : (
+ <IconButton label={t("ide_side_panel.git.scm.stage_changes")} testId="scm-stage" onClick={() => onStage(row)}>
+ <Codicon name="add" />
+ </IconButton>
+ )}
+ </span>
+ <QuickTooltip content={state} side="bottom" className="inline-flex shrink-0">
+ <span data-testid="scm-letter" className={cn("ml-[5px] mr-[12px] w-4 text-center text-[12px] font-semibold opacity-90", tone)}>
+ {file.letter}
+ </span>
+ </QuickTooltip>
+ </div>
+ );
+});
+
+function GroupRow({
+ row,
+ focused,
+ onToggle,
+ onContext,
+ children,
+}: {
+ row: Extract<Row, { kind: "group" }>;
+ focused: boolean;
+ onToggle: () => void;
+ onContext: (event: MouseEvent) => void;
+ children: ReactNode;
+}) {
+ const t = useT();
+ return (
+ <div
+ role="treeitem"
+ aria-expanded={row.open}
+ data-focused={focused || undefined}
+ data-testid={`scm-group-${row.group}`}
+ onClick={onToggle}
+ onContextMenu={onContext}
+ style={{ height: ROW_HEIGHT, paddingLeft: INDENT }}
+ className="scm-row flex cursor-pointer select-none items-center pr-[12px]"
+ >
+ <Twistie open={row.open} />
+ <span className="min-w-0 flex-1 truncate">{t(`ide_side_panel.git.scm.group.${row.group}`)}</span>
+ <span className="scm-actions shrink-0 items-center gap-[2px] pr-1">{children}</span>
+ <span data-testid="scm-group-count" className="scm-badge ml-1 shrink-0 tabular-nums">
+ {row.count}
+ </span>
+ </div>
+ );
+}
+
+/**
+ * The upper half of the Git tab: the repository line, the commit message box
+ * with its button, and every changed file in its group — Merge Changes,
+ * Staged Changes, Changes — with the status letter beside each.
+ */
+export function ChangesView({
+ workspaceId,
+ repoName,
+ status,
+ commands,
+ busy,
+ settings,
+ message,
+ onMessage,
+ messageError,
+ messageRef,
+ onCommit,
+ onDiff,
+ onRefresh,
+ moreMenu,
+}: {
+ workspaceId: string;
+ repoName: string;
+ status: ScmStatus;
+ commands: ScmCommands;
+ busy: string;
+ settings: ListSettings;
+ message: string;
+ onMessage: (message: string) => void;
+ /** Why the last commit attempt did not start ("A message is required"). */
+ messageError: string;
+ messageRef: RefObject<HTMLTextAreaElement>;
+ onCommit: (options: CommitOptions) => void;
+ onDiff: (source: DiffSource) => void;
+ onRefresh: () => void;
+ moreMenu: () => MenuItem[];
+}) {
+ const t = useT();
+ const pushToast = useEventStore((state) => state.pushToast);
+ const [closed, setClosed] = useState<Set<string>>(() => new Set());
+ const [selection, setSelection] = useState<Set<string>>(() => new Set());
+ const [anchor, setAnchor] = useState("");
+ const [focusKey, setFocusKey] = useState("");
+ const [menu, setMenu] = useState<{ items: MenuItem[]; x: number; y: number } | null>(null);
+ const textarea = messageRef;
+ const scroller = useRef<HTMLDivElement>(null);
+ const listTop = useRef<HTMLDivElement>(null);
+ const [viewport, setViewport] = useState({ top: 0, height: 600, offset: 0 });
+
+ useEffect(() => setSelection(new Set()), [workspaceId]);
+
+ const groups = useMemo(() => groupsOf(status), [status]);
+ const rows = useMemo(() => buildRows(groups, settings.mode, settings.sort, closed), [groups, settings.mode, settings.sort, closed]);
+ const rowIndex = useMemo(() => new Map(rows.map((row, index) => [row.key, index])), [rows]);
+ const action = primaryAction(status);
+ const branchLabel = status.detached ? status.head.slice(0, 8) : status.branch || "—";
+ const dirty = status.staged.length + status.changes.length + status.merge.length > 0;
+
+ // Drop a selection whose files are gone.
+ useEffect(() => {
+ setSelection((current) => {
+ const next = new Set([...current].filter((key) => rowIndex.has(key)));
+ return next.size === current.size ? current : next;
+ });
+ }, [rowIndex]);
+
+ // The textarea grows with its text, up to ten lines.
+ useLayoutEffect(() => {
+ const element = textarea.current;
+ if (!element) return;
+ element.style.height = "auto";
+ // scrollHeight leaves out the 1 px border on each side.
+ const wanted = element.scrollHeight + 2;
+ const limit = 10 * 18 + 12;
+ element.style.height = `${Math.min(wanted, limit)}px`;
+ element.style.overflowY = wanted > limit ? "auto" : "hidden";
+ }, [message, textarea]);
+
+ const measure = useCallback(() => {
+ const element = scroller.current;
+ const top = listTop.current;
+ if (!element || !top) return;
+ setViewport({ top: element.scrollTop, height: element.clientHeight, offset: top.offsetTop });
+ }, []);
+ useLayoutEffect(() => {
+ measure();
+ const element = scroller.current;
+ if (!element || typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [measure, message, status.operation]);
+
+ const first = Math.max(0, Math.floor((viewport.top - viewport.offset) / ROW_HEIGHT) - OVERSCAN);
+ const last = Math.min(rows.length, Math.ceil((viewport.top - viewport.offset + viewport.height) / ROW_HEIGHT) + OVERSCAN);
+
+ const filesOf = useCallback(
+ (row: Row): ScmFile[] => {
+ // A row inside the selection acts for the whole selection.
+ const keys = selection.has(row.key) && selection.size > 1 ? [...selection] : [row.key];
+ const picked: ScmFile[] = [];
+ const seen = new Set<string>();
+ for (const key of keys) {
+ const target = rows[rowIndex.get(key) ?? -1];
+ if (!target) continue;
+ const group = groups.find((entry) => entry.id === target.group);
+ for (const path of pathsOfRow(target, groups)) {
+ const file = group?.files.find((entry) => entry.path === path);
+ if (file && !seen.has(`${target.group}:${path}`)) {
+ seen.add(`${target.group}:${path}`);
+ picked.push(file);
+ }
+ }
+ }
+ return picked;
+ },
+ [selection, rows, rowIndex, groups],
+ );
+
+ const openFile = useCallback(
+ (file: ScmFile, preview = true) => {
+ const path = workspacePath(file.path, status.prefix);
+ if (path === null) return pushToast("info", t("ide_side_panel.git.scm.outside_workspace"));
+ useCodeEditorStore.getState().openFile(workspaceId, path, { preview });
+ },
+ [workspaceId, status.prefix, pushToast, t],
+ );
+
+ const openChanges = useCallback(
+ (file: ScmFile, group: GroupId, preview = true) => {
+ const path = workspacePath(file.path, status.prefix);
+ if (path === null) return pushToast("info", t("ide_side_panel.git.scm.outside_workspace"));
+ if (group === "merge" || file.letter === "U") return openFile(file, preview);
+ if (file.letter === "D") {
+ const fromIndex = group === "changes";
+ return onDiff({
+ title: `${baseName(file.path)} (${t(fromIndex ? "ide_side_panel.git.scm.working_tree" : "ide_side_panel.git.scm.index")})`,
+ path: file.path,
+ load: async () => ({ before: await fetchHeadText(workspaceId, path, fromIndex ? "index" : ""), after: null, binary: false }),
+ });
+ }
+ const base =
+ group === "changes" && status.staged.some((entry) => entry.path === file.path)
+ ? { ref: "index", label: t("ide_side_panel.git.scm.diff_working_tree") }
+ : undefined;
+ useCodeEditorStore.getState().openFile(workspaceId, path, { mode: "diff", base, preview });
+ },
+ [workspaceId, status.prefix, status.staged, onDiff, openFile, pushToast, t],
+ );
+
+ const stageRow = useCallback((row: Row) => void commands.stage(filesOf(row).map((file) => file.path)), [commands, filesOf]);
+ const unstageRow = useCallback((row: Row) => void commands.unstage(filesOf(row).map((file) => file.path)), [commands, filesOf]);
+ const discardRow = useCallback((row: Row) => void commands.discardFiles(filesOf(row)), [commands, filesOf]);
+ const openFileRow = useCallback((row: Extract<Row, { kind: "file" }>) => openFile(row.file, false), [openFile]);
+
+ const toggle = useCallback((key: string) => {
+ setClosed((current) => {
+ const next = new Set(current);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ }, []);
+
+ const onPointer = useCallback(
+ (row: Row, event: MouseEvent) => {
+ setFocusKey(row.key);
+ if (event.shiftKey && anchor && rowIndex.has(anchor)) {
+ const [from, to] = [rowIndex.get(anchor)!, rowIndex.get(row.key)!].sort((a, b) => a - b);
+ setSelection(new Set(rows.slice(from, to + 1).filter((entry) => entry.kind === "file").map((entry) => entry.key)));
+ return;
+ }
+ if (event.ctrlKey || event.metaKey) {
+ setSelection((current) => {
+ const next = new Set(current);
+ if (next.has(row.key)) next.delete(row.key);
+ else next.add(row.key);
+ return next;
+ });
+ setAnchor(row.key);
+ return;
+ }
+ setSelection(new Set([row.key]));
+ setAnchor(row.key);
+ if (row.kind === "folder") return toggle(row.key);
+ if (row.kind === "file") openChanges(row.file, row.group, event.detail < 2);
+ },
+ [anchor, rowIndex, rows, toggle, openChanges],
+ );
+
+ const copy = useCallback(
+ (text: string) => {
+ void navigator.clipboard?.writeText(text).catch(() => pushToast("error", t("ide_side_panel.git.scm.copy_failed")));
+ },
+ [pushToast, t],
+ );
+
+ const fileMenu = useCallback(
+ (row: Row): MenuItem[] => {
+ const files = filesOf(row);
+ const paths = files.map((file) => file.path);
+ const single = row.kind === "file" && files.length === 1 ? row.file : null;
+ const absolute = (path: string) => `${status.root.replace(/\\/g, "/")}/${path}`;
+ const items: MenuItem[] = [];
+ if (single) {
+ items.push(
+ { id: "open-changes", label: t("ide_side_panel.git.scm.open_changes"), run: () => openChanges(single, row.group, false) },
+ { id: "open-file", label: t("ide_side_panel.git.scm.open_file"), disabled: single.letter === "D", run: () => openFile(single, false) },
+ { kind: "separator", id: "s1" },
+ );
+ }
+ if (row.group === "staged") items.push({ id: "unstage", label: t("ide_side_panel.git.scm.unstage_changes"), run: () => unstageRow(row) });
+ else items.push({ id: "stage", label: t(row.group === "merge" ? "ide_side_panel.git.scm.mark_resolved" : "ide_side_panel.git.scm.stage_changes"), run: () => stageRow(row) });
+ if (row.group === "changes") {
+ items.push({ id: "discard", label: t("ide_side_panel.git.scm.discard_changes"), run: () => discardRow(row) });
+ if (files.every((file) => file.letter === "U")) items.push({ id: "ignore", label: t("ide_side_panel.git.scm.add_to_gitignore"), run: () => void commands.ignore(paths) });
+ }
+ if (single) {
+ const path = workspacePath(single.path, status.prefix);
+ items.push(
+ { kind: "separator", id: "s2" },
+ {
+ id: "reveal",
+ label: t("ide_side_panel.git.scm.reveal_in_explorer"),
+ disabled: path === null || single.letter === "D",
+ run: () => path !== null && revealInExplorer({ workspaceId, path }),
+ },
+ { id: "copy-path", label: t("ide_side_panel.git.scm.copy_path"), run: () => copy(absolute(single.path)) },
+ { id: "copy-relative", label: t("ide_side_panel.git.scm.copy_relative_path"), run: () => copy(single.path) },
+ );
+ }
+ return items;
+ },
+ [filesOf, status.root, status.prefix, workspaceId, openChanges, openFile, stageRow, unstageRow, discardRow, commands, copy, t],
+ );
+
+ const groupMenu = useCallback(
+ (group: GroupId): MenuItem[] => {
+ if (group === "staged") return [{ id: "unstage-all", label: t("ide_side_panel.git.scm.unstage_all"), run: () => void commands.unstageAll() }];
+ if (group === "merge") return [{ id: "stage-all", label: t("ide_side_panel.git.scm.stage_all_merge"), run: () => void commands.stage(status.merge.map((file) => file.path)) }];
+ return [
+ { id: "stage-all", label: t("ide_side_panel.git.scm.stage_all"), run: () => void commands.stage(status.changes.map((file) => file.path)) },
+ { id: "discard-all", label: t("ide_side_panel.git.scm.discard_all"), run: () => void commands.discardAll() },
+ ];
+ },
+ [commands, status.merge, status.changes, t],
+ );
+
+ const onContext = useCallback(
+ (row: Row, event: MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!selection.has(row.key)) {
+ setSelection(new Set([row.key]));
+ setAnchor(row.key);
+ }
+ setFocusKey(row.key);
+ setMenu({ items: row.kind === "group" ? groupMenu(row.group) : fileMenu(row), x: event.clientX, y: event.clientY });
+ },
+ [selection, fileMenu, groupMenu],
+ );
+
+ const runCommit = onCommit;
+
+ const runPrimary = () => {
+ if (action.kind === "commit") return void runCommit({ kind: "commit" });
+ if (action.kind === "continue") return void commands.operation("continue");
+ if (action.kind === "publish") return void commands.publish();
+ return void commands.sync();
+ };
+
+ const commitMenu = (): MenuItem[] => [
+ { id: "commit", label: t("ide_side_panel.git.scm.commit"), run: () => void runCommit({ kind: "commit" }) },
+ { id: "commit-amend", label: t("ide_side_panel.git.scm.commit_amend"), run: () => void runCommit({ kind: "amend" }) },
+ { id: "commit-push", label: t("ide_side_panel.git.scm.commit_push"), run: () => void runCommit({ kind: "push" }) },
+ { id: "commit-sync", label: t("ide_side_panel.git.scm.commit_sync"), run: () => void runCommit({ kind: "sync" }) },
+ ];
+
+ const onListKey = (event: KeyboardEvent<HTMLDivElement>) => {
+ const index = rowIndex.get(focusKey) ?? -1;
+ const go = (next: number) => {
+ const target = rows[Math.max(0, Math.min(rows.length - 1, next))];
+ if (!target) return;
+ setFocusKey(target.key);
+ if (!event.shiftKey) {
+ setSelection(new Set([target.key]));
+ setAnchor(target.key);
+ }
+ const element = scroller.current;
+ if (element) {
+ const y = viewport.offset + (rows.indexOf(target)) * ROW_HEIGHT;
+ if (y < element.scrollTop) element.scrollTop = y;
+ else if (y + ROW_HEIGHT > element.scrollTop + element.clientHeight) element.scrollTop = y + ROW_HEIGHT - element.clientHeight;
+ }
+ };
+ const row = rows[index];
+ if (event.key === "ArrowDown") go(index + 1);
+ else if (event.key === "ArrowUp") go(index - 1);
+ else if (event.key === "Home") go(0);
+ else if (event.key === "End") go(rows.length - 1);
+ else if (event.key === "Enter" && row) {
+ if (row.kind === "file") openChanges(row.file, row.group, false);
+ else toggle(row.key);
+ } else if ((event.key === "ArrowLeft" || event.key === "ArrowRight") && row && row.kind !== "file") {
+ if ((event.key === "ArrowLeft") === row.open) toggle(row.key);
+ } else if (event.key === "a" && (event.ctrlKey || event.metaKey)) {
+ setSelection(new Set(rows.filter((entry) => entry.kind === "file").map((entry) => entry.key)));
+ } else return;
+ event.preventDefault();
+ };
+
+ const syncLabel =
+ status.upstream && (status.ahead || status.behind)
+ ? fill(t("ide_side_panel.git.scm.sync_tip"), { behind: status.behind, ahead: status.ahead, upstream: status.upstream })
+ : status.upstream
+ ? fill(t("ide_side_panel.git.scm.synced_tip"), { upstream: status.upstream })
+ : t("ide_side_panel.git.scm.publish_branch");
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div ref={scroller} data-testid="scm-changes-scroller" onScroll={measure} className="min-h-0 flex-1 overflow-y-auto">
+ <div data-testid="scm-repo-row" className="scm-row flex h-[22px] items-center pr-[8px]">
+ <Twistie open />
+ <Codicon name="repo" className="mr-[6px]" />
+ <span className="min-w-0 shrink truncate">{repoName}</span>
+ <QuickTooltip content={t("ide_side_panel.git.scm.checkout_tip")} side="bottom" className="inline-flex min-w-0">
+ <button
+ type="button"
+ data-testid="scm-branch"
+ onClick={() => void commands.checkoutTo()}
+ className="ml-[0.5em] inline-flex min-w-0 items-center gap-[3px] text-[0.9em] opacity-70 hover:opacity-100"
+ >
+ <Codicon name="git-branch" className="!text-[14px]" />
+ <span className="truncate">
+ {branchLabel}
+ {dirty ? "*" : ""}
+ </span>
+ </button>
+ </QuickTooltip>
+ <span className="ml-auto flex shrink-0 items-center gap-[2px] pl-1">
+ {status.remotes.length > 0 && (
+ <QuickTooltip content={syncLabel} side="bottom" className="inline-flex">
+ <button
+ type="button"
+ data-testid="scm-sync"
+ aria-label={syncLabel}
+ disabled={busy !== ""}
+ onClick={() => void commands.sync()}
+ className="scm-action !w-auto gap-[2px] px-[3px] text-[12px] tabular-nums"
+ >
+ {!status.upstream ? (
+ <Codicon name="cloud-upload" />
+ ) : status.ahead || status.behind ? (
+ <>
+ {status.behind > 0 && (
+ <>
+ {status.behind}
+ <Codicon name="arrow-down" className="!text-[14px]" />
+ </>
+ )}
+ {status.ahead > 0 && (
+ <>
+ {status.ahead}
+ <Codicon name="arrow-up" className="!text-[14px]" />
+ </>
+ )}
+ </>
+ ) : (
+ <Codicon name="sync" spin={busy === "sync"} />
+ )}
+ </button>
+ </QuickTooltip>
+ )}
+ <IconButton label={fill(t("ide_side_panel.git.scm.commit_tip"), { branch: branchLabel })} testId="scm-commit-icon" disabled={busy !== ""} onClick={() => void runCommit({ kind: "commit" })}>
+ <Codicon name="check" />
+ </IconButton>
+ <IconButton label={t("ide_side_panel.git.scm.refresh")} testId="scm-refresh" onClick={onRefresh}>
+ <Codicon name="refresh" />
+ </IconButton>
+ <IconButton
+ label={t("ide_side_panel.git.scm.more_actions")}
+ testId="scm-more"
+ onClick={(event) => setMenu({ items: moreMenu(), ...menuPointFor(event.currentTarget) })}
+ >
+ <Codicon name="ellipsis" />
+ </IconButton>
+ </span>
+ </div>
+
+ <div className="pb-[6px] pl-[20px] pr-[12px] pt-[3px]">
+ {status.operation && status.operation !== "bisect" && (
+ <div data-testid="scm-operation" className="mb-[6px] flex items-start gap-2 rounded-sm border border-[var(--scm-modified)] px-[6px] py-[2px] text-[12px] leading-[18px]">
+ <Codicon name="git-merge" className="mt-[1px]" />
+ <span className="min-w-0 flex-1">{t(`ide_side_panel.git.scm.operation.${status.operation}`)}</span>
+ <button type="button" data-testid="scm-abort" onClick={() => void commands.operation("abort")} className="shrink-0 text-[var(--scm-focus)] hover:underline">
+ {t("ide_side_panel.git.scm.abort")}
+ </button>
+ </div>
+ )}
+ <div className="relative">
+ <textarea
+ ref={textarea}
+ data-testid="scm-message"
+ rows={1}
+ value={message}
+ spellCheck={false}
+ aria-label={t("ide_side_panel.git.scm.message_label")}
+ aria-invalid={Boolean(messageError) || undefined}
+ placeholder={fill(t("ide_side_panel.git.scm.message_placeholder"), { key: modKey(), branch: branchLabel })}
+ onChange={(event) => onMessage(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault();
+ if (busy === "") void runCommit({ kind: "commit" });
+ }
+ }}
+ style={messageError ? { borderColor: "var(--scm-error-border)", outlineColor: "var(--scm-error-border)" } : undefined}
+ className="scm-input block min-h-[26px] w-full resize-none px-[6px] py-[2px] text-[13px] leading-[20px]"
+ />
+ {messageError && (
+ <p
+ data-testid="scm-message-error"
+ className="border border-t-0 px-[6px] py-[2px] text-[12px] leading-[17px]"
+ style={{ background: "var(--scm-error-bg)", borderColor: "var(--scm-error-border)" }}
+ >
+ {messageError}
+ </p>
+ )}
+ </div>
+ <div className="mt-[6px] flex h-[26px]">
+ <button
+ type="button"
+ data-testid="scm-primary"
+ data-action={action.kind}
+ disabled={busy !== "" || (action.kind === "commit" && !action.enabled)}
+ onClick={runPrimary}
+ className={cn(
+ "scm-button inline-flex min-w-0 flex-1 items-center justify-center gap-[4px] px-[4px] text-[13px] leading-[18px]",
+ action.kind === "commit" ? "rounded-l-[2px]" : "rounded-[2px]",
+ )}
+ >
+ {action.kind === "commit" && (
+ <>
+ <Codicon name="check" />
+ <span className="truncate">{t("ide_side_panel.git.scm.commit")}</span>
+ </>
+ )}
+ {action.kind === "continue" && (
+ <>
+ <Codicon name="check" />
+ <span className="truncate">{t("ide_side_panel.git.scm.continue")}</span>
+ </>
+ )}
+ {action.kind === "publish" && (
+ <>
+ <Codicon name="cloud-upload" />
+ <span className="truncate">{t("ide_side_panel.git.scm.publish_branch")}</span>
+ </>
+ )}
+ {action.kind === "sync" && (
+ <>
+ <Codicon name="sync" spin={busy === "sync"} />
+ <span className="truncate">{t("ide_side_panel.git.scm.sync_changes")}</span>
+ <span className="shrink-0 tabular-nums">
+ {action.behind > 0 && `${action.behind}↓ `}
+ {action.ahead > 0 && `${action.ahead}↑`}
+ </span>
+ </>
+ )}
+ </button>
+ {action.kind === "commit" && (
+ <>
+ <span aria-hidden className="scm-button w-px shrink-0 py-[4px]" style={{ opacity: busy !== "" || !action.enabled ? 0.4 : 1 }}>
+ <span className="block h-full w-px" style={{ background: "var(--scm-button-separator)" }} />
+ </span>
+ <button
+ type="button"
+ data-testid="scm-primary-more"
+ aria-label={t("ide_side_panel.git.scm.commit_options")}
+ disabled={busy !== "" || !action.enabled}
+ onClick={(event) => setMenu({ items: commitMenu(), ...menuPointFor(event.currentTarget) })}
+ className="scm-button inline-flex w-[26px] shrink-0 items-center justify-center rounded-r-[2px]"
+ >
+ <Codicon name="chevron-down" />
+ </button>
+ </>
+ )}
+ </div>
+ </div>
+
+ <div
+ ref={listTop}
+ role="tree"
+ aria-label={t("ide_side_panel.git.scm.changes_aria")}
+ aria-multiselectable
+ tabIndex={0}
+ onKeyDown={onListKey}
+ className="scm-list relative outline-none"
+ style={{ height: rows.length * ROW_HEIGHT }}
+ >
+ <div style={{ position: "absolute", top: first * ROW_HEIGHT, left: 0, right: 0 }}>
+ {rows.slice(first, last).map((row) => {
+ if (row.kind === "file") {
+ return (
+ <FileRow
+ key={row.key}
+ row={row}
+ selected={selection.has(row.key)}
+ focused={focusKey === row.key}
+ mode={settings.mode}
+ onPointer={onPointer}
+ onContext={onContext}
+ onOpenFile={openFileRow}
+ onDiscard={discardRow}
+ onStage={stageRow}
+ onUnstage={unstageRow}
+ />
+ );
+ }
+ if (row.kind === "folder") {
+ return (
+ <div
+ key={row.key}
+ role="treeitem"
+ aria-expanded={row.open}
+ aria-selected={selection.has(row.key)}
+ data-focused={focusKey === row.key || undefined}
+ data-testid="scm-folder"
+ onClick={(event) => onPointer(row, event)}
+ onContextMenu={(event) => onContext(row, event)}
+ style={{ height: ROW_HEIGHT, paddingLeft: (row.depth + 1) * INDENT }}
+ className="scm-row flex cursor-pointer select-none items-center pr-[12px]"
+ >
+ <Twistie open={row.open} />
+ <Codicon name={row.open ? "folder-opened" : "folder"} className="mr-[6px]" />
+ <span className="min-w-0 flex-1 truncate">{row.label}</span>
+ <span className="scm-actions shrink-0 items-center gap-[2px]">
+ {row.group === "changes" && (
+ <IconButton label={t("ide_side_panel.git.scm.discard_changes")} testId="scm-folder-discard" onClick={() => discardRow(row)}>
+ <Codicon name="discard" />
+ </IconButton>
+ )}
+ {row.group === "staged" ? (
+ <IconButton label={t("ide_side_panel.git.scm.unstage_changes")} testId="scm-folder-unstage" onClick={() => unstageRow(row)}>
+ <Codicon name="remove" />
+ </IconButton>
+ ) : (
+ <IconButton label={t("ide_side_panel.git.scm.stage_changes")} testId="scm-folder-stage" onClick={() => stageRow(row)}>
+ <Codicon name="add" />
+ </IconButton>
+ )}
+ </span>
+ </div>
+ );
+ }
+ return (
+ <GroupRow key={row.key} row={row} focused={focusKey === row.key} onToggle={() => toggle(row.key)} onContext={(event) => onContext(row, event)}>
+ {row.group === "staged" && (
+ <IconButton label={t("ide_side_panel.git.scm.unstage_all")} testId="scm-unstage-all" onClick={() => void commands.unstageAll()}>
+ <Codicon name="remove" />
+ </IconButton>
+ )}
+ {row.group === "changes" && row.count > 0 && (
+ <>
+ <IconButton label={t("ide_side_panel.git.scm.discard_all")} testId="scm-discard-all" onClick={() => void commands.discardAll()}>
+ <Codicon name="discard" />
+ </IconButton>
+ <IconButton label={t("ide_side_panel.git.scm.stage_all")} testId="scm-stage-all" onClick={() => void commands.stage(status.changes.map((file) => file.path))}>
+ <Codicon name="add" />
+ </IconButton>
+ </>
+ )}
+ {row.group === "merge" && (
+ <IconButton label={t("ide_side_panel.git.scm.stage_all_merge")} testId="scm-stage-all-merge" onClick={() => void commands.stage(status.merge.map((file) => file.path))}>
+ <Codicon name="add" />
+ </IconButton>
+ )}
+ </GroupRow>
+ );
+ })}
+ </div>
+ </div>
+ {status.truncated && <p className="px-[20px] py-[4px] text-[12px] opacity-70">{t("ide_side_panel.git.scm.truncated")}</p>}
+ </div>
+ {menu && <ScmMenu items={menu.items} x={menu.x} y={menu.y} onClose={() => setMenu(null)} />}
+ </div>
+ );
+}
+
+/** "View & Sort" for the more menu: list or tree, and the sort order. */
+export function viewSortMenu(settings: ListSettings, onSettings: (next: ListSettings) => void, t: (key: string) => string): MenuItem {
+ return {
+ kind: "submenu",
+ id: "view-sort",
+ label: t("ide_side_panel.git.scm.view_sort"),
+ items: [
+ { id: "view-list", label: t("ide_side_panel.git.scm.view_list"), checked: settings.mode === "list", run: () => onSettings({ ...settings, mode: "list" }) },
+ { id: "view-tree", label: t("ide_side_panel.git.scm.view_tree"), checked: settings.mode === "tree", run: () => onSettings({ ...settings, mode: "tree" }) },
+ { kind: "separator", id: "vs1" },
+ { id: "sort-name", label: t("ide_side_panel.git.scm.sort_name"), checked: settings.sort === "name", run: () => onSettings({ ...settings, sort: "name" }) },
+ { id: "sort-path", label: t("ide_side_panel.git.scm.sort_path"), checked: settings.sort === "path", run: () => onSettings({ ...settings, sort: "path" }) },
+ { id: "sort-status", label: t("ide_side_panel.git.scm.sort_status"), checked: settings.sort === "status", run: () => onSettings({ ...settings, sort: "status" }) },
+ ],
+ };
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/Codicon.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/Codicon.tsx
new file mode 100644
index 0000000000..fd7e05b8dc
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/Codicon.tsx
@@ -0,0 +1,15 @@
+import { cn } from "@/lib/utils";
+
+/** One glyph of the codicon font (`git-branch`, `check`, `discard`, …), 16 px. */
+export function Codicon({ name, className, spin = false }: { name: string; className?: string; spin?: boolean }) {
+ return <span aria-hidden className={cn("codicon", `codicon-${name}`, spin && "codicon-modifier-spin", className)} />;
+}
+
+/** The fold arrow in front of a tree row: 16 px wide plus 6 px before the label. */
+export function Twistie({ open, visible = true }: { open?: boolean; visible?: boolean }) {
+ return (
+ <span className="flex h-[22px] w-[22px] shrink-0 items-center pr-[6px]" aria-hidden>
+ {visible && <Codicon name={open ? "chevron-down" : "chevron-right"} />}
+ </span>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/DiffDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/DiffDialog.tsx
new file mode 100644
index 0000000000..7f456659c0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/DiffDialog.tsx
@@ -0,0 +1,92 @@
+import { lazy, Suspense, useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { Codicon } from "./Codicon";
+import { useT } from "@/i18n";
+
+const MonacoDiff = lazy(() => import("./MonacoDiff"));
+
+export interface DiffSource {
+ /** The tab title: "app.py (abc1234)". */
+ title: string;
+ path: string;
+ load: () => Promise<{ before: string | null; after: string | null; binary: boolean }>;
+}
+
+/** A large read-only diff over the app, for a commit's file or a deleted file. */
+export function DiffDialog({ source, onClose }: { source: DiffSource; onClose: () => void }) {
+ const t = useT();
+ const [state, setState] = useState<{ before: string; after: string; binary: boolean } | { error: string } | null>(null);
+ useEffect(() => {
+ let alive = true;
+ setState(null);
+ source
+ .load()
+ .then((answer) => alive && setState({ before: answer.before ?? "", after: answer.after ?? "", binary: answer.binary }))
+ .catch((error: Error) => alive && setState({ error: error.message }));
+ return () => {
+ alive = false;
+ };
+ }, [source]);
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ onClose();
+ }
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, [onClose]);
+ return createPortal(
+ <div
+ role="presentation"
+ className="scm-portal fixed inset-0 z-[110] flex items-center justify-center p-6"
+ style={{ background: "rgba(0, 0, 0, 0.3)" }}
+ onPointerDown={(event) => event.target === event.currentTarget && onClose()}
+ >
+ <section
+ role="dialog"
+ aria-modal="true"
+ aria-label={source.title}
+ data-testid="scm-diff-dialog"
+ className="flex h-full max-h-[86vh] w-full max-w-6xl flex-col overflow-hidden rounded-[6px]"
+ style={{ background: "var(--scm-bg)", color: "var(--scm-fg)", border: "1px solid var(--scm-menu-border)", boxShadow: "0 0 8px 2px rgba(0, 0, 0, 0.36)" }}
+ >
+ <header className="flex h-[35px] shrink-0 items-center gap-[6px] px-[10px]" style={{ borderBottom: "1px solid var(--scm-border)" }}>
+ <span className="min-w-0 flex-1 truncate text-[13px]">{source.title}</span>
+ <button
+ type="button"
+ aria-label={t("ide_side_panel.git.scm.close")}
+ data-testid="scm-diff-close"
+ onClick={onClose}
+ className="scm-action"
+ >
+ <Codicon name="close" />
+ </button>
+ </header>
+ <div className="relative min-h-0 flex-1">
+ {!state ? (
+ <div className="flex h-full items-center justify-center">
+ <Codicon name="loading" spin />
+ </div>
+ ) : "error" in state ? (
+ <p className="p-6 text-center text-[13px]" style={{ color: "var(--scm-deleted)" }}>{state.error}</p>
+ ) : state.binary ? (
+ <p className="p-6 text-center text-[13px] opacity-70">{t("ide_side_panel.git.scm.binary")}</p>
+ ) : (
+ <Suspense
+ fallback={
+ <div className="flex h-full items-center justify-center">
+ <Codicon name="loading" spin />
+ </div>
+ }
+ >
+ <MonacoDiff path={source.path} before={state.before} after={state.after} />
+ </Suspense>
+ )}
+ </div>
+ </section>
+ </div>,
+ document.body,
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/GraphView.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/GraphView.tsx
new file mode 100644
index 0000000000..f32f8614e6
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/GraphView.tsx
@@ -0,0 +1,366 @@
+import { memo, useCallback, useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
+import { useT } from "@/i18n";
+import { useRunLocale } from "@/components/runs/format";
+import { cn } from "@/lib/utils";
+import { QuickTooltip } from "@/components/ui/tooltip";
+import { useEventStore } from "@/store/events";
+import { FileTypeIcon } from "../../explorer/FileTypeIcon";
+import { agoLabel } from "../gitBadges";
+import { scmApi, type CommitDetails, type GraphCommit, type GraphPage, type GraphScope } from "./scmApi";
+import { baseName, dirName, laneColor, layoutGraph, letterTone, parseRefs, type GraphRow, type RefBadge } from "./scmModel";
+import { ScmMenu, type MenuItem } from "./ScmMenu";
+import { Codicon, Twistie } from "./Codicon";
+import type { ScmCommands } from "./useScm";
+import type { DiffSource } from "./DiffDialog";
+
+const ROW = 22;
+/** A commit's files sit one level in, under its subject. */
+const GRAPH_INDENT = 16;
+const LANE = 11;
+const PAGE = 50;
+
+function laneX(lane: number) {
+ return LANE / 2 + 2 + lane * LANE;
+}
+
+/** The lanes of one graph row: lines from above into the dot, lines from the dot down. */
+const GraphLanes = memo(function GraphLanes({ row, head, lanes }: { row: GraphRow; head: boolean; lanes: number }) {
+ // Every row is as wide as the widest one, so the subjects line up.
+ const width = laneX(Math.max(lanes, row.width) - 1) + LANE / 2 + 2;
+ const mid = ROW / 2;
+ const x = laneX(row.lane);
+ const paths: { d: string; color: string }[] = [];
+ row.top.forEach((value, lane) => {
+ if (value === null) return;
+ if (value === row.commit.id) {
+ const from = laneX(lane);
+ paths.push({ d: from === x ? `M${x} 0 V${mid}` : `M${from} 0 C${from} ${mid * 0.8} ${x} ${mid * 0.4} ${x} ${mid}`, color: laneColor(lane === row.lane ? row.lane : lane) });
+ } else {
+ const lx = laneX(lane);
+ // A lane passing by goes straight through, unless it was freed here and moves down.
+ if (row.bottom[lane] === value) paths.push({ d: `M${lx} 0 V${ROW}`, color: laneColor(lane) });
+ else {
+ const target = row.bottom.indexOf(value);
+ if (target >= 0) paths.push({ d: `M${lx} 0 C${lx} ${mid} ${laneX(target)} ${mid} ${laneX(target)} ${ROW}`, color: laneColor(target) });
+ }
+ }
+ });
+ if (row.bottom[row.lane] !== undefined && row.bottom[row.lane] !== null && row.commit.parents.length > 0) {
+ paths.push({ d: `M${x} ${mid} V${ROW}`, color: laneColor(row.lane) });
+ }
+ for (const lane of row.branches) {
+ const bx = laneX(lane);
+ paths.push({ d: `M${x} ${mid} C${x} ${mid + mid * 0.6} ${bx} ${mid + mid * 0.2} ${bx} ${ROW}`, color: laneColor(lane) });
+ }
+ const merge = row.commit.parents.length > 1;
+ return (
+ <svg width={width} height={ROW} className="shrink-0" aria-hidden>
+ {paths.map((path, index) => (
+ <path key={index} d={path.d} stroke={path.color} strokeWidth={1} fill="none" />
+ ))}
+ {head ? (
+ <>
+ <circle cx={x} cy={mid} r={5} fill={laneColor(row.lane)} />
+ <circle cx={x} cy={mid} r={3} fill="var(--scm-bg)" />
+ </>
+ ) : merge ? (
+ <>
+ <circle cx={x} cy={mid} r={4} fill="var(--scm-bg)" stroke={laneColor(row.lane)} strokeWidth={2} />
+ <circle cx={x} cy={mid} r={1.5} fill={laneColor(row.lane)} />
+ </>
+ ) : (
+ <circle cx={x} cy={mid} r={4} fill={laneColor(row.lane)} />
+ )}
+ </svg>
+ );
+});
+
+const REF_COLOR: Record<RefBadge["kind"], string> = {
+ head: "var(--scm-ref-local)",
+ remote: "var(--scm-ref-remote)",
+ tag: "var(--scm-ref-base)",
+};
+const REF_ICON: Record<RefBadge["kind"], string> = { head: "git-branch", remote: "cloud", tag: "tag" };
+
+/** A ref on a commit: the first one with its name, every further one as its icon only. */
+function RefChip({ badge, compact }: { badge: RefBadge; compact: boolean }) {
+ return (
+ <QuickTooltip content={badge.name} side="bottom" className="inline-flex shrink-0">
+ <span
+ data-testid="scm-graph-ref"
+ data-kind={badge.kind}
+ aria-label={badge.name}
+ style={{ background: REF_COLOR[badge.kind], color: "var(--scm-ref-fg)" }}
+ className={cn(
+ "ml-[4px] inline-flex h-[18px] max-w-[120px] items-center gap-[2px] rounded-[9px] text-[11px] leading-[18px]",
+ compact ? "w-[18px] justify-center" : "px-[5px]",
+ )}
+ >
+ <Codicon name={badge.current ? "target" : REF_ICON[badge.kind]} className="!text-[12px] !leading-[12px]" />
+ {!compact && <span className="truncate">{badge.name}</span>}
+ </span>
+ </QuickTooltip>
+ );
+}
+
+/**
+ * The commit graph under the changes: the current branch with its upstream
+ * (or every branch), lanes and merges drawn beside each commit, branch and
+ * tag badges, commits not yet pulled or pushed marked. A click opens the
+ * commit's files; a file opens its diff.
+ */
+export function GraphView({
+ workspaceId,
+ revision,
+ scope,
+ commands,
+ onDiff,
+ targetHead,
+}: {
+ workspaceId: string;
+ /** Bumped whenever history or refs may have moved. */
+ revision: string;
+ scope: GraphScope;
+ commands: ScmCommands;
+ onDiff: (source: DiffSource) => void;
+ /** Bumped to scroll the current commit into view. */
+ targetHead: number;
+}) {
+ const t = useT();
+ const lang = useRunLocale();
+ const pushToast = useEventStore((state) => state.pushToast);
+ const [page, setPage] = useState<GraphPage | null>(null);
+ const [commits, setCommits] = useState<GraphCommit[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState("");
+ const [open, setOpen] = useState<Record<string, CommitDetails | "loading">>({});
+ const [menu, setMenu] = useState<{ items: MenuItem[]; x: number; y: number } | null>(null);
+ const scroller = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ let alive = true;
+ const controller = new AbortController();
+ setLoading(true);
+ // Re-read as many commits as are on screen, so a refresh keeps the scroll.
+ const size = Math.max(PAGE, Math.min(200, commits.length || PAGE));
+ scmApi
+ .graph(workspaceId, scope, 0, size, controller.signal)
+ .then((answer) => {
+ if (!alive) return;
+ setPage(answer);
+ setCommits(answer.commits);
+ setError("");
+ })
+ .catch((err: Error) => alive && err.name !== "AbortError" && setError(err.message))
+ .finally(() => alive && setLoading(false));
+ return () => {
+ alive = false;
+ controller.abort();
+ };
+ // `commits.length` is read once per load on purpose.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [workspaceId, scope, revision]);
+
+ useEffect(() => setOpen({}), [workspaceId, scope]);
+
+ const loadMore = useCallback(() => {
+ if (loading || !page?.more) return;
+ setLoading(true);
+ scmApi
+ .graph(workspaceId, scope, commits.length, PAGE)
+ .then((answer) => {
+ setCommits((current) => [...current, ...answer.commits]);
+ setPage((current) => (current ? { ...current, more: answer.more } : answer));
+ })
+ .catch((err: Error) => pushToast("error", err.message))
+ .finally(() => setLoading(false));
+ }, [loading, page, workspaceId, scope, commits.length, pushToast]);
+
+ const rows = useMemo(() => layoutGraph(commits), [commits]);
+ const lanes = useMemo(() => Math.min(12, rows.reduce((most, row) => Math.max(most, row.width), 1)), [rows]);
+ const incoming = useMemo(() => new Set(page?.incoming ?? []), [page]);
+ const outgoing = useMemo(() => new Set(page?.outgoing ?? []), [page]);
+ const head = page?.head ?? "";
+
+ useEffect(() => {
+ if (!targetHead || !head) return;
+ scroller.current?.querySelector<HTMLElement>(`[data-commit="${head}"]`)?.scrollIntoView?.({ block: "center" });
+ }, [targetHead, head]);
+
+ const toggle = (commit: GraphCommit) => {
+ if (open[commit.id]) {
+ setOpen((current) => {
+ const next = { ...current };
+ delete next[commit.id];
+ return next;
+ });
+ return;
+ }
+ setOpen((current) => ({ ...current, [commit.id]: "loading" }));
+ scmApi
+ .commit(workspaceId, commit.id)
+ .then((details) => setOpen((current) => (current[commit.id] ? { ...current, [commit.id]: details } : current)))
+ .catch((err: Error) => {
+ pushToast("error", err.message);
+ setOpen((current) => {
+ const next = { ...current };
+ delete next[commit.id];
+ return next;
+ });
+ });
+ };
+
+ const copy = (text: string) => void navigator.clipboard?.writeText(text).catch(() => pushToast("error", t("ide_side_panel.git.scm.copy_failed")));
+
+ const commitMenu = (commit: GraphCommit): MenuItem[] => [
+ { id: "checkout-detached", label: t("ide_side_panel.git.scm.checkout_detached_here"), run: () => void commands.checkoutRef(commit.id, true) },
+ { id: "create-branch", label: t("ide_side_panel.git.scm.create_branch_here"), run: () => void commands.createBranch(commit.id) },
+ { id: "create-tag", label: t("ide_side_panel.git.scm.create_tag_here"), run: () => void commands.createTag(commit.id) },
+ { kind: "separator", id: "g1" },
+ { id: "cherry-pick", label: t("ide_side_panel.git.scm.cherry_pick"), disabled: commit.id === head, run: () => void commands.cherryPick(commit.id) },
+ { id: "revert", label: t("ide_side_panel.git.scm.revert_commit"), run: () => void commands.revert(commit.id) },
+ { kind: "separator", id: "g2" },
+ { id: "copy-id", label: t("ide_side_panel.git.scm.copy_commit_id"), run: () => copy(commit.id) },
+ { id: "copy-message", label: t("ide_side_panel.git.scm.copy_commit_message"), run: () => copy(commit.subject) },
+ ];
+
+ const onContext = (commit: GraphCommit, event: MouseEvent) => {
+ event.preventDefault();
+ setMenu({ items: commitMenu(commit), x: event.clientX, y: event.clientY });
+ };
+
+ if (error && commits.length === 0) {
+ return (
+ <p data-testid="scm-graph-error" className="px-[20px] py-[4px] text-[13px]" style={{ color: "var(--scm-deleted)" }}>
+ {error}
+ </p>
+ );
+ }
+ if (!page) {
+ return (
+ <div className="flex items-center justify-center py-[8px]">
+ <Codicon name="loading" spin />
+ </div>
+ );
+ }
+ if (commits.length === 0) {
+ return <p className="px-[20px] py-[4px] text-[13px] opacity-70">{t("ide_side_panel.git.scm.no_commits")}</p>;
+ }
+
+ return (
+ <div
+ ref={scroller}
+ data-testid="scm-graph"
+ className="h-full overflow-y-auto"
+ onScroll={(event) => {
+ const element = event.currentTarget;
+ if (element.scrollTop + element.clientHeight > element.scrollHeight - ROW * 6) loadMore();
+ }}
+ >
+ {rows.map((row) => {
+ const commit = row.commit;
+ const badges = parseRefs(commit.refs);
+ const details = open[commit.id];
+ const direction = incoming.has(commit.id) ? "incoming" : outgoing.has(commit.id) ? "outgoing" : "";
+ const date = new Date(commit.date * 1000);
+ const tip = [
+ `${commit.author} <${commit.email}>`,
+ `${agoLabel(commit.date, lang, t)} (${date.toLocaleString(lang)})`,
+ "",
+ commit.subject,
+ "",
+ commit.id.slice(0, 8),
+ ...(direction ? [t(`ide_side_panel.git.scm.${direction}`)] : []),
+ ].join("\n");
+ return (
+ <div key={commit.id}>
+ <div
+ role="button"
+ tabIndex={0}
+ data-testid="scm-graph-commit"
+ data-commit={commit.id}
+ data-direction={direction || undefined}
+ aria-expanded={Boolean(details)}
+ onClick={() => toggle(commit)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ toggle(commit);
+ }
+ }}
+ onContextMenu={(event) => onContext(commit, event)}
+ style={{ height: ROW }}
+ className="scm-row flex cursor-pointer select-none items-center pr-[8px] focus-visible:outline focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-[var(--scm-focus)]"
+ >
+ <GraphLanes row={row} head={commit.id === head} lanes={lanes} />
+ <QuickTooltip content={tip} side="bottom" className="ml-[4px] flex min-w-0 flex-1 items-baseline overflow-hidden whitespace-nowrap">
+ <span className={cn("min-w-0 truncate", commit.id === head && "font-semibold")}>{commit.subject}</span>
+ <span className="ml-[0.5em] min-w-0 shrink truncate text-[0.9em] opacity-70">{commit.author}</span>
+ </QuickTooltip>
+ {direction && (
+ <QuickTooltip content={t(`ide_side_panel.git.scm.${direction}`)} side="bottom" className="inline-flex shrink-0">
+ <span aria-label={t(`ide_side_panel.git.scm.${direction}`)} className="ml-[4px] inline-flex opacity-80">
+ <Codicon name={direction === "incoming" ? "arrow-circle-down" : "arrow-circle-up"} />
+ </span>
+ </QuickTooltip>
+ )}
+ {badges.map((badge, index) => (
+ <RefChip key={`${badge.kind}:${badge.name}`} badge={badge} compact={index > 0} />
+ ))}
+ </div>
+ {details === "loading" && (
+ <div className="flex h-[22px] items-center" style={{ paddingLeft: GRAPH_INDENT + 22 }}>
+ <Codicon name="loading" spin />
+ </div>
+ )}
+ {details && details !== "loading" && (
+ <div data-testid="scm-graph-files">
+ {details.message.includes("\n") && (
+ <p className="whitespace-pre-wrap break-words py-[2px] pr-[12px] text-[12px] leading-[18px] opacity-70" style={{ paddingLeft: GRAPH_INDENT + 22 }}>{details.message.split("\n").slice(1).join("\n").trim()}</p>
+ )}
+ {details.files.map((file) => (
+ <div
+ key={file.path}
+ role="button"
+ tabIndex={0}
+ data-testid="scm-graph-file"
+ onClick={() =>
+ onDiff({
+ title: `${baseName(file.path)} (${commit.id.slice(0, 7)})`,
+ path: file.path,
+ load: () => scmApi.commitFile(workspaceId, commit.id, file.path, file.original),
+ })
+ }
+ onKeyDown={(event) => {
+ if (event.key === "Enter") event.currentTarget.click();
+ }}
+ style={{ height: ROW, paddingLeft: GRAPH_INDENT }}
+ className="scm-row flex cursor-pointer select-none items-center"
+ >
+ <Twistie visible={false} />
+ <FileTypeIcon path={file.path} className="mr-[6px] h-4 w-4" />
+ <span className={cn("truncate", letterTone(file.letter), file.letter === "D" && "line-through")}>{baseName(file.path)}</span>
+ <span className="ml-[0.5em] min-w-0 flex-1 truncate text-[0.9em] opacity-70">{dirName(file.path)}</span>
+ <span className={cn("ml-[5px] mr-[12px] w-4 shrink-0 text-center text-[12px] font-semibold opacity-90", letterTone(file.letter))}>{file.letter}</span>
+ </div>
+ ))}
+ {details.stat && (
+ <p className="text-[12px] leading-[22px] opacity-70" style={{ paddingLeft: GRAPH_INDENT + 22 }}>
+ {details.stat}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ {page.more && (
+ <button type="button" data-testid="scm-graph-more" onClick={loadMore} className="scm-row flex h-[22px] w-full items-center gap-[6px] pl-[8px]" style={{ color: "var(--scm-focus)" }}>
+ <Codicon name={loading ? "loading" : "fold-down"} spin={loading} />
+ {t("ide_side_panel.git.scm.load_more")}
+ </button>
+ )}
+ {menu && <ScmMenu items={menu.items} x={menu.x} y={menu.y} onClose={() => setMenu(null)} />}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/MonacoDiff.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/MonacoDiff.tsx
new file mode 100644
index 0000000000..074a7d1e41
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/MonacoDiff.tsx
@@ -0,0 +1,40 @@
+import { useEffect, useRef } from "react";
+import { EDITOR_OPTIONS, applyTheme, monaco } from "../../../editor/monacoRuntime";
+import { languageFor } from "../../../editor/editorModels";
+
+/**
+ * A read-only side-by-side diff of two texts (a commit's change to one file).
+ * Loaded lazily with the editor engine, never on the app's boot path.
+ */
+export default function MonacoDiff({ path, before, after }: { path: string; before: string; after: string }) {
+ const host = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const root = document.documentElement;
+ const sync = () => applyTheme(root.classList.contains("dark"));
+ sync();
+ const observer = new MutationObserver(sync);
+ observer.observe(root, { attributes: true, attributeFilter: ["class", "style"] });
+ const language = languageFor(path);
+ const original = monaco.editor.createModel(before, language);
+ const modified = monaco.editor.createModel(after, language);
+ const diff = monaco.editor.createDiffEditor(host.current!, {
+ ...EDITOR_OPTIONS,
+ minimap: { enabled: false },
+ stickyScroll: { enabled: false },
+ readOnly: true,
+ originalEditable: false,
+ renderSideBySide: true,
+ useInlineViewWhenSpaceIsLimited: true,
+ renderSideBySideInlineBreakpoint: 700,
+ theme: "jarvis",
+ });
+ diff.setModel({ original, modified });
+ return () => {
+ observer.disconnect();
+ diff.dispose();
+ original.dispose();
+ modified.dispose();
+ };
+ }, [path, before, after]);
+ return <div ref={host} data-testid="scm-diff-editor" className="h-full w-full" />;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/QuickInput.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/QuickInput.tsx
new file mode 100644
index 0000000000..9b5ef1fe7f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/QuickInput.tsx
@@ -0,0 +1,192 @@
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+
+export interface QuickPickItem<T> {
+ label: string;
+ description?: string;
+ detail?: string;
+ icon?: ReactNode;
+ value: T;
+ /** Starts a titled block in the list ("Branches", "Tags"). */
+ group?: string;
+}
+
+interface PickRequest {
+ mode: "pick";
+ items: QuickPickItem<unknown>[];
+ placeholder: string;
+ resolve: (value: unknown) => void;
+}
+
+interface InputRequest {
+ mode: "input";
+ prompt: string;
+ placeholder: string;
+ value: string;
+ password?: boolean;
+ validate?: (value: string) => string;
+ resolve: (value: unknown) => void;
+}
+
+type Request = PickRequest | InputRequest;
+
+export interface QuickInput {
+ pick: <T>(items: QuickPickItem<T>[], placeholder: string) => Promise<T | undefined>;
+ input: (options: { prompt: string; placeholder?: string; value?: string; validate?: (value: string) => string }) => Promise<string | undefined>;
+ element: ReactNode;
+}
+
+const MAX_SHOWN = 300;
+
+function matches(item: QuickPickItem<unknown>, words: string[]): boolean {
+ const text = `${item.label} ${item.description ?? ""} ${item.detail ?? ""}`.toLowerCase();
+ return words.every((word) => text.includes(word));
+}
+
+function Widget({ request, onDone }: { request: Request; onDone: (value: unknown) => void }) {
+ const [text, setText] = useState(request.mode === "input" ? request.value : "");
+ const [active, setActive] = useState(0);
+ const input = useRef<HTMLInputElement>(null);
+ const list = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ input.current?.focus();
+ if (request.mode === "input") input.current?.select();
+ }, [request]);
+
+ const shown = useMemo(() => {
+ if (request.mode !== "pick") return [];
+ const words = text.toLowerCase().split(/\s+/).filter(Boolean);
+ return request.items.filter((item) => matches(item, words)).slice(0, MAX_SHOWN);
+ }, [request, text]);
+ useEffect(() => setActive(0), [text]);
+ useEffect(() => {
+ list.current?.querySelector<HTMLElement>(`[data-pick-index="${active}"]`)?.scrollIntoView?.({ block: "nearest" });
+ }, [active]);
+
+ const error = request.mode === "input" && request.validate ? request.validate(text) : "";
+ const accept = () => {
+ if (request.mode === "pick") {
+ const item = shown[active];
+ if (item) onDone(item.value);
+ return;
+ }
+ if (!error) onDone(text);
+ };
+
+ return (
+ <div
+ role="dialog"
+ aria-modal="true"
+ data-testid="scm-quick-input"
+ className="scm-portal absolute inset-x-[8px] top-[4px] z-[60] overflow-hidden rounded-[6px]"
+ style={{ background: "var(--scm-menu-bg)", color: "var(--scm-menu-fg)", border: "1px solid var(--scm-menu-border)", boxShadow: "0 0 8px 2px rgba(0, 0, 0, 0.36)" }}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") onDone(undefined);
+ else if (event.key === "Enter") accept();
+ else if (event.key === "ArrowDown" && shown.length) setActive((value) => (value + 1) % shown.length);
+ else if (event.key === "ArrowUp" && shown.length) setActive((value) => (value - 1 + shown.length) % shown.length);
+ else return;
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ >
+ <div className="px-[6px] pb-[6px] pt-[6px]">
+ <input
+ ref={input}
+ data-testid="scm-quick-input-box"
+ value={text}
+ type={request.mode === "input" && request.password ? "password" : "text"}
+ placeholder={request.placeholder}
+ aria-invalid={Boolean(error) || undefined}
+ onChange={(event) => setText(event.target.value)}
+ onBlur={(event) => {
+ // A click inside the widget keeps it; anywhere else cancels, as Escape does.
+ if (!event.currentTarget.closest("[data-testid=scm-quick-input]")?.contains(event.relatedTarget as Node | null)) onDone(undefined);
+ }}
+ className="scm-input h-[26px] w-full px-[6px] text-[13px]"
+ style={error ? { borderColor: "var(--scm-error-border)", outlineColor: "var(--scm-error-border)" } : undefined}
+ />
+ {request.mode === "input" && (
+ <p data-testid="scm-quick-input-prompt" className="px-[4px] pt-[6px] text-[12px] leading-[18px]" style={error ? { color: "var(--scm-deleted)" } : { opacity: 0.8 }}>
+ {error || request.prompt}
+ </p>
+ )}
+ </div>
+ {request.mode === "pick" && (
+ <div ref={list} role="listbox" className="max-h-[min(50vh,440px)] overflow-y-auto pb-[6px]">
+ {shown.map((item, index) => (
+ <div key={`${item.label}-${index}`}>
+ {item.group && (index === 0 || shown[index - 1].group !== item.group) && (
+ <div className="mx-[6px] flex h-[22px] items-center justify-end border-t px-[6px] text-[11px]" style={{ borderColor: "var(--scm-menu-separator)", color: "var(--scm-desc-fg)" }}>
+ {item.group}
+ </div>
+ )}
+ <button
+ type="button"
+ role="option"
+ tabIndex={-1}
+ aria-selected={index === active}
+ data-pick-index={index}
+ data-testid="scm-quick-pick-item"
+ onMouseMove={() => setActive(index)}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => onDone(item.value)}
+ style={index === active ? { background: "var(--scm-menu-selection)", color: "var(--scm-menu-selection-fg)" } : undefined}
+ className="mx-[6px] flex h-[22px] w-[calc(100%-12px)] min-w-0 items-center gap-[6px] rounded-[3px] px-[6px] text-left text-[13px]"
+ >
+ {item.icon && <span className="flex h-4 w-4 shrink-0 items-center justify-center">{item.icon}</span>}
+ <span className="min-w-0 flex-1">
+ <span className="flex min-w-0 items-baseline gap-2">
+ <span className="truncate">{item.label}</span>
+ {item.description && <span className="min-w-0 truncate text-[0.9em] opacity-70">{item.description}</span>}
+ </span>
+ {item.detail && <span className="block truncate text-[11px] opacity-60">{item.detail}</span>}
+ </span>
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** A filterable pick list and a one-line input box at the top of the Git tab. */
+export function useQuickInput(): QuickInput {
+ const [request, setRequest] = useState<Request | null>(null);
+ const pending = useRef<Request | null>(null);
+ const open = useCallback((next: Request) => {
+ pending.current?.resolve(undefined);
+ pending.current = next;
+ setRequest(next);
+ }, []);
+ useEffect(() => () => pending.current?.resolve(undefined), []);
+ const pick = useCallback(
+ <T,>(items: QuickPickItem<T>[], placeholder: string) =>
+ new Promise<T | undefined>((resolve) =>
+ open({ mode: "pick", items: items as QuickPickItem<unknown>[], placeholder, resolve: resolve as (value: unknown) => void }),
+ ),
+ [open],
+ );
+ const input = useCallback(
+ (options: { prompt: string; placeholder?: string; value?: string; validate?: (value: string) => string }) =>
+ new Promise<string | undefined>((resolve) =>
+ open({
+ mode: "input",
+ prompt: options.prompt,
+ placeholder: options.placeholder ?? "",
+ value: options.value ?? "",
+ validate: options.validate,
+ resolve: resolve as (value: unknown) => void,
+ }),
+ ),
+ [open],
+ );
+ const done = useCallback((value: unknown) => {
+ const current = pending.current;
+ pending.current = null;
+ setRequest(null);
+ current?.resolve(value);
+ }, []);
+ const element = request ? <Widget key={request.mode + (request.mode === "pick" ? request.placeholder : request.prompt)} request={request} onDone={done} /> : null;
+ return { pick, input, element };
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/ScmMenu.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/ScmMenu.tsx
new file mode 100644
index 0000000000..dc1f5c7569
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/ScmMenu.tsx
@@ -0,0 +1,192 @@
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { Codicon } from "./Codicon";
+
+export type MenuItem =
+ | {
+ kind?: "item";
+ id: string;
+ label: string;
+ /** Shown dimmed at the right edge ("Ctrl+Enter"). */
+ hint?: string;
+ disabled?: boolean;
+ checked?: boolean;
+ run: () => void;
+ }
+ | { kind: "submenu"; id: string; label: string; disabled?: boolean; items: MenuItem[] }
+ | { kind: "separator"; id: string };
+
+const MENU_WIDTH = 236;
+const ITEM_HEIGHT = 24;
+
+function isActionable(item: MenuItem): boolean {
+ return item.kind !== "separator" && !item.disabled;
+}
+
+function MenuPanel({
+ items,
+ x,
+ y,
+ level,
+ testId,
+ onClose,
+ onBack,
+}: {
+ items: MenuItem[];
+ x: number;
+ y: number;
+ level: number;
+ testId: string;
+ onClose: () => void;
+ /** Closes this submenu and gives the keyboard back to its parent. */
+ onBack?: () => void;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [position, setPosition] = useState({ left: x, top: y });
+ const [active, setActive] = useState(-1);
+ const [open, setOpen] = useState<{ index: number; x: number; y: number; keyboard: boolean } | null>(null);
+
+ // Keep the whole menu on screen: flip left of the anchor, lift above the bottom edge.
+ useLayoutEffect(() => {
+ const box = ref.current?.getBoundingClientRect();
+ if (!box) return;
+ const width = box.width || MENU_WIDTH;
+ const left = x + width > window.innerWidth - 4 ? Math.max(4, (level > 0 ? x - width - MENU_WIDTH + 8 : window.innerWidth - width - 4)) : x;
+ const top = y + box.height > window.innerHeight - 4 ? Math.max(4, window.innerHeight - box.height - 4) : y;
+ setPosition({ left, top });
+ }, [x, y, level, items.length]);
+
+ useEffect(() => {
+ if (level > 0 && active >= 0) ref.current?.focus();
+ }, [level, active]);
+ useEffect(() => {
+ ref.current?.focus();
+ }, []);
+
+ const openSubmenu = (index: number, keyboard: boolean) => {
+ const element = ref.current?.querySelector<HTMLElement>(`[data-menu-index="${index}"]`);
+ const box = element?.getBoundingClientRect();
+ if (!box) return;
+ setOpen({ index, x: box.right - 2, y: box.top - 4, keyboard });
+ };
+
+ const move = (step: number) => {
+ if (!items.some(isActionable)) return;
+ let next = active;
+ do {
+ next = (next + step + items.length) % items.length;
+ } while (!isActionable(items[next]));
+ setActive(next);
+ };
+
+ const activate = (index: number, keyboard: boolean) => {
+ const item = items[index];
+ if (!item || !isActionable(item)) return;
+ if (item.kind === "submenu") return openSubmenu(index, keyboard);
+ if (item.kind === "separator") return;
+ onClose();
+ item.run();
+ };
+
+ return (
+ <>
+ <div
+ ref={ref}
+ role="menu"
+ tabIndex={-1}
+ data-testid={testId}
+ className="scm-portal fixed z-[120] max-w-[320px] rounded-[5px] py-[4px] outline-none"
+ style={{ left: position.left, top: position.top, minWidth: MENU_WIDTH, background: "var(--scm-menu-bg)", color: "var(--scm-menu-fg)", border: "1px solid var(--scm-menu-border)", boxShadow: "0 2px 8px rgba(0, 0, 0, 0.36)" }}
+ onContextMenu={(event) => event.preventDefault()}
+ onKeyDown={(event) => {
+ if (open) return;
+ if (event.key === "ArrowDown") move(1);
+ else if (event.key === "ArrowUp") move(-1);
+ else if (event.key === "Enter" || event.key === " ") activate(active, true);
+ else if (event.key === "ArrowRight" && items[active]?.kind === "submenu") openSubmenu(active, true);
+ else if (event.key === "ArrowLeft" && onBack) onBack();
+ else if (event.key === "Escape") (onBack ?? onClose)();
+ else return;
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ >
+ {items.map((item, index) =>
+ item.kind === "separator" ? (
+ <div key={item.id} role="separator" className="mx-[10px] my-[4px] h-px" style={{ background: "var(--scm-menu-separator)" }} />
+ ) : (
+ <button
+ key={item.id}
+ type="button"
+ role="menuitem"
+ data-menu-index={index}
+ data-testid={`scm-menu-${item.id}`}
+ disabled={item.disabled}
+ aria-haspopup={item.kind === "submenu" || undefined}
+ onMouseEnter={() => {
+ setActive(index);
+ if (item.kind === "submenu" && !item.disabled) openSubmenu(index, false);
+ else setOpen(null);
+ }}
+ onClick={() => activate(index, false)}
+ style={{ height: ITEM_HEIGHT, ...(active === index && !item.disabled ? { background: "var(--scm-menu-selection)", color: "var(--scm-menu-selection-fg)" } : {}) }}
+ className="mx-[4px] flex w-[calc(100%-8px)] items-center rounded-[3px] pr-[8px] text-left disabled:opacity-40"
+ >
+ <span className="flex w-[26px] shrink-0 justify-center">{item.kind !== "submenu" && item.checked && <Codicon name="check" />}</span>
+ <span className="min-w-0 flex-1 truncate">{item.label}</span>
+ {item.kind === "submenu" ? (
+ <Codicon name="chevron-right" className="shrink-0" />
+ ) : (
+ item.hint && <span className="shrink-0 pl-[2em]">{item.hint}</span>
+ )}
+ </button>
+ ),
+ )}
+ </div>
+ {open && items[open.index]?.kind === "submenu" && (
+ <MenuPanel
+ key={open.index}
+ items={(items[open.index] as { items: MenuItem[] }).items}
+ x={open.x}
+ y={open.y}
+ level={level + 1}
+ testId={`${testId}-sub`}
+ onClose={onClose}
+ onBack={() => {
+ setOpen(null);
+ ref.current?.focus();
+ }}
+ />
+ )}
+ </>
+ );
+}
+
+/** A menu at a screen point, with submenus; closes on Escape, a click outside or a choice. */
+export function ScmMenu({ items, x, y, onClose, testId = "scm-menu" }: { items: MenuItem[]; x: number; y: number; onClose: () => void; testId?: string }) {
+ useEffect(() => {
+ const close = (event: PointerEvent) => {
+ if (!(event.target as HTMLElement | null)?.closest?.("[role=menu]")) onClose();
+ };
+ const blur = () => onClose();
+ window.addEventListener("pointerdown", close, true);
+ window.addEventListener("blur", blur);
+ window.addEventListener("resize", blur);
+ return () => {
+ window.removeEventListener("pointerdown", close, true);
+ window.removeEventListener("blur", blur);
+ window.removeEventListener("resize", blur);
+ };
+ }, [onClose]);
+ return createPortal(<MenuPanel items={items} x={x} y={y} level={0} testId={testId} onClose={onClose} />, document.body);
+}
+
+/** Where a menu opened from a button should appear: under its bottom edge, right-aligned. */
+export function menuPointFor(element: HTMLElement): { x: number; y: number } {
+ const box = element.getBoundingClientRect();
+ return { x: Math.max(4, box.right - MENU_WIDTH), y: box.bottom + 2 };
+}
+
+export function MenuHost({ menu, onClose }: { menu: { items: MenuItem[]; x: number; y: number } | null; onClose: () => void }): ReactNode {
+ return menu ? <ScmMenu items={menu.items} x={menu.x} y={menu.y} onClose={onClose} /> : null;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/ScmViews.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/ScmViews.tsx
new file mode 100644
index 0000000000..da30658aca
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/ScmViews.tsx
@@ -0,0 +1,99 @@
+import { useCallback, useRef, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";
+
+import { Codicon } from "./Codicon";
+
+export interface ViewSpec {
+ id: string;
+ title: string;
+ open: boolean;
+ onToggle: () => void;
+ /** Icon buttons at the header's right edge, shown while the pointer is over the view. */
+ actions?: ReactNode;
+ body: ReactNode;
+ /** Share of the free height this view takes while open. */
+ weight: number;
+}
+
+const HEADER = 22;
+const MIN_BODY = 44;
+
+/**
+ * Collapsible views stacked in one column. Open views share the height by
+ * weight; the sash between two open views moves the line between them.
+ */
+export function ScmViews({ views, onWeights }: { views: ViewSpec[]; onWeights: (weights: Record<string, number>) => void }) {
+ const bodies = useRef<Record<string, HTMLDivElement | null>>({});
+ const startDrag = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>, above: string, below: string) => {
+ event.preventDefault();
+ const open = views.filter((view) => view.open);
+ const sizes: Record<string, number> = {};
+ for (const view of open) sizes[view.id] = bodies.current[view.id]?.getBoundingClientRect().height ?? MIN_BODY;
+ const startY = event.clientY;
+ const total = sizes[above] + sizes[below];
+ const handle = event.currentTarget;
+ handle.setPointerCapture?.(event.pointerId);
+ const move = (moveEvent: PointerEvent) => {
+ const delta = moveEvent.clientY - startY;
+ const top = Math.max(MIN_BODY, Math.min(total - MIN_BODY, sizes[above] + delta));
+ onWeights({ ...sizes, [above]: top, [below]: total - top });
+ };
+ const up = () => {
+ window.removeEventListener("pointermove", move);
+ window.removeEventListener("pointerup", up);
+ };
+ window.addEventListener("pointermove", move);
+ window.addEventListener("pointerup", up);
+ },
+ [views, onWeights],
+ );
+
+ let previousOpen = "";
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {views.map((view, index) => {
+ const sashAbove = view.open && previousOpen ? previousOpen : "";
+ if (view.open) previousOpen = view.id;
+ return (
+ <section
+ key={view.id}
+ data-testid={`scm-view-${view.id}`}
+ data-open={view.open || undefined}
+ className="scm-view relative flex min-h-0 flex-col"
+ style={{ ...(view.open ? { flex: `${view.weight} 1 0px`, minHeight: HEADER + MIN_BODY } : { flex: "0 0 auto" }), borderTop: index > 0 ? "1px solid var(--scm-border)" : undefined }}
+ >
+ {sashAbove && (
+ <div
+ role="separator"
+ aria-orientation="horizontal"
+ data-testid={`scm-sash-${view.id}`}
+ onPointerDown={(event) => startDrag(event, sashAbove, view.id)}
+ className="absolute inset-x-0 -top-[3px] z-10 h-[6px] cursor-row-resize transition-colors delay-150 hover:bg-[var(--scm-focus)]"
+ />
+ )}
+ <div className="flex shrink-0 items-center pr-[8px]" style={{ height: HEADER }}>
+ <button
+ type="button"
+ data-testid={`scm-view-toggle-${view.id}`}
+ aria-expanded={view.open}
+ onClick={view.onToggle}
+ className="flex h-full min-w-0 flex-1 items-center pl-[2px] text-left focus-visible:outline focus-visible:outline-1 focus-visible:-outline-offset-1 focus-visible:outline-[var(--scm-focus)]"
+ >
+ <Codicon name={view.open ? "chevron-down" : "chevron-right"} className="mr-[2px]" />
+ <span className="truncate text-[13px]" style={{ color: "var(--scm-title-fg)" }}>
+ {view.title}
+ </span>
+ </button>
+ {view.open && view.actions && <span className="scm-view-actions shrink-0 items-center gap-[2px]">{view.actions}</span>}
+ </div>
+ {view.open && (
+ <div ref={(element) => (bodies.current[view.id] = element)} className="min-h-0 flex-1 overflow-hidden">
+ {view.body}
+ </div>
+ )}
+ </section>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scm.css b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scm.css
new file mode 100644
index 0000000000..aaa125476a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scm.css
@@ -0,0 +1,272 @@
+/*
+ * The Git tab's source control surface: its own colour table for the light
+ * and the dark appearance, the system UI font at 13 px, 22 px rows and the
+ * codicon glyphs. Every value the components use comes from a --scm-* token.
+ */
+@import "@vscode/codicons/dist/codicon.css";
+
+/* The code editor ships an older copy of the same font under the same name;
+ this surface draws its glyphs from its own copy. */
+@font-face {
+ font-family: "scm-codicon";
+ font-display: block;
+ src: url("@vscode/codicons/dist/codicon.ttf") format("truetype");
+}
+
+.scm-root,
+.scm-portal {
+ --scm-bg: #f8f8f8;
+ --scm-fg: #3b3b3b;
+ --scm-title-fg: #3b3b3b;
+ --scm-desc-fg: #717171;
+ --scm-border: #e5e5e5;
+ --scm-input-bg: #ffffff;
+ --scm-input-border: #cecece;
+ --scm-input-placeholder: #767676;
+ --scm-focus: #005fb8;
+ --scm-button-bg: #005fb8;
+ --scm-button-hover: #0258a8;
+ --scm-button-fg: #ffffff;
+ --scm-button-separator: rgba(255, 255, 255, 0.4);
+ --scm-badge-bg: #005fb8;
+ --scm-badge-fg: #ffffff;
+ --scm-hover: #f2f2f2;
+ --scm-selection: #e8e8e8;
+ --scm-selection-focus: #e8e8e8;
+ --scm-toolbar-hover: rgba(184, 184, 184, 0.31);
+ --scm-icon: #3b3b3b;
+ --scm-progress: #005fb8;
+ --scm-menu-bg: #ffffff;
+ --scm-menu-fg: #3b3b3b;
+ --scm-menu-border: #cecece;
+ --scm-menu-selection: #005fb8;
+ --scm-menu-selection-fg: #ffffff;
+ --scm-menu-separator: #cecece;
+ --scm-error-bg: #f2dede;
+ --scm-error-border: #be1100;
+ --scm-modified: #895503;
+ --scm-added: #587c0c;
+ --scm-untracked: #007100;
+ --scm-deleted: #ad0707;
+ --scm-renamed: #007100;
+ --scm-conflict: #ad0707;
+ --scm-ignored: #8e8e90;
+ --scm-ref-local: #005fb8;
+ --scm-ref-remote: #652d90;
+ --scm-ref-base: #ea5c00;
+ --scm-ref-fg: #ffffff;
+ --scm-lane-0: #ffb000;
+ --scm-lane-1: #dc267f;
+ --scm-lane-2: #994f00;
+ --scm-lane-3: #40b0a6;
+ --scm-lane-4: #b66dff;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "Ubuntu", "Droid Sans", sans-serif;
+ font-size: 13px;
+ line-height: 22px;
+ color: var(--scm-fg);
+ background: var(--scm-bg);
+}
+
+.dark .scm-root,
+.dark .scm-portal {
+ --scm-bg: #181818;
+ --scm-fg: #cccccc;
+ --scm-title-fg: #cccccc;
+ --scm-desc-fg: #9d9d9d;
+ --scm-border: #2b2b2b;
+ --scm-input-bg: #313131;
+ --scm-input-border: #3c3c3c;
+ --scm-input-placeholder: #989898;
+ --scm-focus: #0078d4;
+ --scm-button-bg: #0078d4;
+ --scm-button-hover: #026ec1;
+ --scm-button-fg: #ffffff;
+ --scm-badge-bg: #0078d4;
+ --scm-badge-fg: #ffffff;
+ --scm-hover: #2a2d2e;
+ --scm-selection: #37373d;
+ --scm-selection-focus: #04395e;
+ --scm-toolbar-hover: rgba(90, 93, 94, 0.31);
+ --scm-icon: #cccccc;
+ --scm-progress: #0078d4;
+ --scm-menu-bg: #1f1f1f;
+ --scm-menu-fg: #cccccc;
+ --scm-menu-border: #454545;
+ --scm-menu-selection: #0078d4;
+ --scm-menu-separator: #454545;
+ --scm-error-bg: #5a1d1d;
+ --scm-error-border: #be1100;
+ --scm-modified: #e2c08d;
+ --scm-added: #81b88b;
+ --scm-untracked: #73c991;
+ --scm-deleted: #c74e39;
+ --scm-renamed: #73c991;
+ --scm-conflict: #e4676b;
+ --scm-ignored: #8c8c8c;
+ --scm-ref-local: #0078d4;
+ --scm-ref-remote: #b180d7;
+ --scm-ref-base: #ea5c00;
+}
+
+/* Menus and dialogs are portalled to <body>; they carry the class themselves. */
+.scm-portal {
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "Ubuntu", "Droid Sans", sans-serif;
+ font-size: 13px;
+}
+
+.scm-root .codicon,
+.scm-portal .codicon {
+ font-family: "scm-codicon" !important;
+ font-size: 16px;
+ line-height: 16px;
+}
+
+.scm-row:hover {
+ background: var(--scm-hover);
+}
+.scm-row[aria-selected="true"] {
+ background: var(--scm-selection);
+}
+.scm-list:focus-within .scm-row[aria-selected="true"] {
+ background: var(--scm-selection-focus);
+}
+.scm-list:focus .scm-row[data-focused="true"] {
+ outline: 1px solid var(--scm-focus);
+ outline-offset: -1px;
+}
+
+/* Row actions show on hover, on the focused row and on a selected one. */
+.scm-row .scm-actions {
+ display: none;
+}
+.scm-row:hover .scm-actions,
+.scm-row[aria-selected="true"] .scm-actions,
+.scm-row[data-focused="true"] .scm-actions {
+ display: flex;
+}
+
+/* View-header actions show while the pointer or the keyboard is in the view. */
+.scm-view .scm-view-actions {
+ display: none;
+}
+.scm-view:hover .scm-view-actions,
+.scm-view:focus-within .scm-view-actions {
+ display: flex;
+}
+
+.scm-action {
+ display: inline-flex;
+ width: 22px;
+ height: 22px;
+ align-items: center;
+ justify-content: center;
+ border-radius: 5px;
+ color: var(--scm-icon);
+ background: transparent;
+ flex-shrink: 0;
+}
+.scm-action:hover {
+ background: var(--scm-toolbar-hover);
+}
+.scm-action:disabled {
+ opacity: 0.4;
+ background: transparent;
+}
+.scm-action:focus-visible {
+ outline: 1px solid var(--scm-focus);
+ outline-offset: -1px;
+}
+
+.scm-input {
+ background: var(--scm-input-bg);
+ border: 1px solid var(--scm-input-border);
+ color: var(--scm-fg);
+ border-radius: 2px;
+}
+.scm-input::placeholder {
+ color: var(--scm-input-placeholder);
+}
+.scm-input:focus {
+ outline: 1px solid var(--scm-focus);
+ outline-offset: -1px;
+ border-color: var(--scm-focus);
+}
+
+.scm-button {
+ background: var(--scm-button-bg);
+ color: var(--scm-button-fg);
+}
+.scm-button:hover:not(:disabled) {
+ background: var(--scm-button-hover);
+}
+.scm-button:disabled {
+ opacity: 0.4;
+}
+.scm-button:focus-visible {
+ outline: 1px solid var(--scm-focus);
+ outline-offset: 2px;
+}
+
+.scm-badge {
+ display: inline-block;
+ min-width: 18px;
+ height: 18px;
+ padding: 3px 6px;
+ border-radius: 11px;
+ font-size: 11px;
+ line-height: 12px;
+ font-weight: 400;
+ text-align: center;
+ box-sizing: border-box;
+ background: var(--scm-badge-bg);
+ color: var(--scm-badge-fg);
+}
+
+.scm-progress {
+ position: absolute;
+ top: 0;
+ height: 2px;
+ width: 2%;
+ background: var(--scm-progress);
+ animation: scm-progress 4s linear infinite;
+}
+@media (prefers-reduced-motion: reduce) {
+ .scm-progress {
+ animation: none;
+ width: 100%;
+ opacity: 0.6;
+ }
+}
+@keyframes scm-progress {
+ from {
+ transform: translateX(0) scaleX(1);
+ left: 0;
+ }
+ to {
+ left: 100%;
+ }
+}
+
+.scm-tone-M,
+.scm-tone-T {
+ color: var(--scm-modified);
+}
+.scm-tone-A {
+ color: var(--scm-added);
+}
+.scm-tone-U {
+ color: var(--scm-untracked);
+}
+.scm-tone-D {
+ color: var(--scm-deleted);
+}
+.scm-tone-R,
+.scm-tone-C {
+ color: var(--scm-renamed);
+}
+.scm-tone-\! {
+ color: var(--scm-conflict);
+}
+.scm-tone-I {
+ color: var(--scm-ignored);
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts
new file mode 100644
index 0000000000..cdec7dfc48
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmApi.ts
@@ -0,0 +1,208 @@
+/**
+ * Client for `/api/agentic-ide/git/scm`: the Git tab's source control.
+ *
+ * Mirrors `jarvis/agentic_ide/scm.py`. Every call names the open workspace;
+ * paths are repository-relative. A failed call rejects with a
+ * {@link GitApiError} whose `code` says which follow-up the UI can offer.
+ */
+import { GitApiError } from "@/lib/gitApi";
+import { fill, translate } from "@/i18n";
+
+/** The letter beside a file: M A D R C T U, or `!` for a conflict. */
+export type ScmLetter = "M" | "A" | "D" | "R" | "C" | "T" | "U" | "I" | "!";
+
+export interface ScmFile {
+ path: string;
+ letter: ScmLetter;
+ /** `index_modified`, `modified`, `untracked`, `both_modified`, … */
+ status: string;
+ /** Where a rename or copy came from. */
+ original: string;
+}
+
+export interface ScmStatus {
+ available: boolean;
+ reason: string;
+ root: string;
+ /** The workspace folder's path inside the repository ("" or `sub/`). */
+ prefix: string;
+ branch: string;
+ head: string;
+ detached: boolean;
+ unborn: boolean;
+ upstream: string;
+ ahead: number;
+ behind: number;
+ operation: "" | "merge" | "rebase" | "cherry-pick" | "revert" | "bisect";
+ remotes: string[];
+ stashes: number;
+ merge: ScmFile[];
+ staged: ScmFile[];
+ changes: ScmFile[];
+ truncated: boolean;
+ head_message: string;
+}
+
+export interface ScmRef {
+ kind: "head" | "remote" | "tag";
+ name: string;
+ commit: string;
+ date: number;
+ subject: string;
+ upstream: string;
+}
+
+export interface GraphCommit {
+ id: string;
+ parents: string[];
+ author: string;
+ email: string;
+ date: number;
+ /** `git log %D` decorations: `HEAD -> refs/heads/main`, `refs/remotes/origin/main`, `tag: refs/tags/v1`. */
+ refs: string[];
+ subject: string;
+}
+
+export interface GraphPage {
+ commits: GraphCommit[];
+ more: boolean;
+ head: string;
+ upstream: string;
+ incoming: string[];
+ outgoing: string[];
+}
+
+export type GraphScope = "auto" | "all" | "current";
+
+export interface CommitFile {
+ path: string;
+ letter: ScmLetter;
+ original: string;
+}
+
+export interface CommitDetails {
+ id: string;
+ parents: string[];
+ author: string;
+ email: string;
+ date: number;
+ committer: string;
+ committer_date: number;
+ message: string;
+ files: CommitFile[];
+ stat: string;
+}
+
+export interface CommitFileDiff {
+ path: string;
+ original_path: string;
+ before: string | null;
+ after: string | null;
+ binary: boolean;
+}
+
+export interface Stash {
+ ref: string;
+ message: string;
+ date: number;
+}
+
+const BASE = "/api/agentic-ide/git/scm";
+
+async function failure(res: Response): Promise<GitApiError> {
+ if (res.status === 404) {
+ // Either the workspace closed, or a backend from before these routes.
+ try {
+ const body = (await res.json()) as { detail?: unknown };
+ if (body.detail === "Not Found") return new GitApiError(translate("shell_errors.git_after_restart"), "unavailable");
+ if (typeof body.detail === "string") return new GitApiError(body.detail, "not_found");
+ } catch {
+ // Not JSON: treat it as the missing route.
+ }
+ return new GitApiError(translate("shell_errors.git_after_restart"), "unavailable");
+ }
+ try {
+ const body = (await res.json()) as { detail?: unknown };
+ const detail = body.detail;
+ if (detail && typeof detail === "object" && "message" in detail) {
+ const { message, code } = detail as { message: string; code?: string };
+ return new GitApiError(message, code ?? "failed");
+ }
+ if (typeof detail === "string") return new GitApiError(detail, "failed");
+ } catch {
+ // Not JSON (a proxy error page): the status line is all there is to say.
+ }
+ return new GitApiError(fill(translate("shell_errors.git_request_failed"), { status: res.status }), "failed");
+}
+
+async function get<T>(path: string, params: Record<string, string | number>, signal?: AbortSignal): Promise<T> {
+ const query = new URLSearchParams(Object.entries(params).map(([key, value]) => [key, String(value)])).toString();
+ const res = await fetch(`${BASE}${path}?${query}`, { signal });
+ if (!res.ok) throw await failure(res);
+ return (await res.json()) as T;
+}
+
+async function post<T = { ok: true }>(path: string, body: object): Promise<T> {
+ const res = await fetch(`${BASE}${path}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) throw await failure(res);
+ return (await res.json()) as T;
+}
+
+export const scmApi = {
+ status: (workspace_id: string, signal?: AbortSignal) => get<ScmStatus>("/status", { workspace_id }, signal),
+ refs: (workspace_id: string) => get<{ current: string; refs: ScmRef[] }>("/refs", { workspace_id }),
+ graph: (workspace_id: string, scope: GraphScope, skip: number, limit: number, signal?: AbortSignal) =>
+ get<GraphPage>("/graph", { workspace_id, scope, skip, limit }, signal),
+ commit: (workspace_id: string, commit: string) => get<CommitDetails>("/commit", { workspace_id, commit }),
+ commitFile: (workspace_id: string, commit: string, path: string, original = "") =>
+ get<CommitFileDiff>("/commit/file", { workspace_id, commit, path, original }),
+ stashes: (workspace_id: string) => get<{ stashes: Stash[] }>("/stashes", { workspace_id }),
+
+ stage: (workspace_id: string, paths: string[]) => post("/stage", { workspace_id, paths }),
+ stageAll: (workspace_id: string, tracked_only = false) => post("/stage-all", { workspace_id, tracked_only }),
+ unstage: (workspace_id: string, paths: string[]) => post("/unstage", { workspace_id, paths }),
+ unstageAll: (workspace_id: string) => post("/unstage-all", { workspace_id }),
+ discard: (workspace_id: string, paths: string[]) => post("/discard", { workspace_id, paths }),
+ discardAll: (workspace_id: string, untracked: boolean) => post("/discard-all", { workspace_id, untracked }),
+ ignore: (workspace_id: string, paths: string[]) => post("/ignore", { workspace_id, paths }),
+ commitChanges: (
+ workspace_id: string,
+ message: string,
+ options: { amend?: boolean; all_changes?: boolean; include_untracked?: boolean; signoff?: boolean; no_verify?: boolean; allow_empty?: boolean } = {},
+ ) => post<{ ok: true; commit: string }>("/commit", { workspace_id, message, ...options }),
+ undoCommit: (workspace_id: string) => post<{ ok: true; message: string }>("/undo-commit", { workspace_id }),
+ operation: (workspace_id: string, action: "continue" | "abort") => post("/operation", { workspace_id, action }),
+
+ fetch: (workspace_id: string, options: { remote?: string; prune?: boolean; all_remotes?: boolean } = {}) =>
+ post("/fetch", { workspace_id, ...options }),
+ pull: (workspace_id: string, options: { rebase?: boolean; remote?: string; branch?: string } = {}) =>
+ post("/pull", { workspace_id, ...options }),
+ push: (workspace_id: string, options: { remote?: string; force?: boolean; tags?: boolean } = {}) =>
+ post<{ ok: true; upstream: string }>("/push", { workspace_id, ...options }),
+ pushTags: (workspace_id: string, remote = "") => post("/push-tags", { workspace_id, remote }),
+ sync: (workspace_id: string, rebase = false) => post("/sync", { workspace_id, rebase }),
+ addRemote: (workspace_id: string, name: string, url: string) => post("/remote/add", { workspace_id, name, url }),
+ removeRemote: (workspace_id: string, name: string) => post("/remote/remove", { workspace_id, name }),
+
+ checkout: (workspace_id: string, ref: string, detached = false) =>
+ post<{ ok: true; branch: string }>("/checkout", { workspace_id, ref, detached }),
+ createBranch: (workspace_id: string, name: string, start = "", switchTo = true) =>
+ post<{ ok: true; branch: string }>("/branch/create", { workspace_id, name, start, switch: switchTo }),
+ renameBranch: (workspace_id: string, name: string, old = "") => post("/branch/rename", { workspace_id, name, old }),
+ deleteBranch: (workspace_id: string, name: string, force = false) => post("/branch/delete", { workspace_id, name, force }),
+ merge: (workspace_id: string, ref: string) => post<{ ok: true; result: string }>("/merge", { workspace_id, ref }),
+ rebase: (workspace_id: string, ref: string) => post<{ ok: true; result: string }>("/rebase", { workspace_id, ref }),
+ cherryPick: (workspace_id: string, ref: string) => post<{ ok: true; result: string }>("/cherry-pick", { workspace_id, ref }),
+ revert: (workspace_id: string, ref: string) => post<{ ok: true; result: string }>("/revert", { workspace_id, ref }),
+ createTag: (workspace_id: string, name: string, message = "", ref = "") => post("/tag/create", { workspace_id, name, message, ref }),
+ deleteTag: (workspace_id: string, name: string) => post("/tag/delete", { workspace_id, name }),
+
+ stash: (workspace_id: string, options: { message?: string; include_untracked?: boolean; staged?: boolean } = {}) =>
+ post("/stash", { workspace_id, ...options }),
+ stashApply: (workspace_id: string, ref = "", pop = false) => post("/stash/apply", { workspace_id, ref, pop }),
+ stashDrop: (workspace_id: string, ref = "", everything = false) => post("/stash/drop", { workspace_id, ref, everything }),
+};
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmModel.test.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmModel.test.ts
new file mode 100644
index 0000000000..e4d664433a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmModel.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from "vitest";
+import type { GraphCommit, ScmFile, ScmStatus } from "./scmApi";
+import { buildRows, groupsOf, layoutGraph, parseRefs, primaryAction, workspacePath } from "./scmModel";
+
+const file = (path: string, letter: ScmFile["letter"] = "M", status = "modified"): ScmFile => ({ path, letter, status, original: "" });
+
+const STATUS: ScmStatus = {
+ available: true,
+ reason: "",
+ root: "/code/app",
+ prefix: "",
+ branch: "main",
+ head: "abc",
+ detached: false,
+ unborn: false,
+ upstream: "origin/main",
+ ahead: 0,
+ behind: 0,
+ operation: "",
+ remotes: ["origin"],
+ stashes: 0,
+ merge: [],
+ staged: [],
+ changes: [],
+ truncated: false,
+ head_message: "",
+};
+
+describe("source control rows", () => {
+ it("lists the groups in order and always shows Changes", () => {
+ expect(groupsOf(STATUS).map((group) => group.id)).toEqual(["changes"]);
+ const busy = { ...STATUS, merge: [file("a", "!")], staged: [file("b", "A")], changes: [file("c")] };
+ expect(groupsOf(busy).map((group) => group.id)).toEqual(["merge", "staged", "changes"]);
+ });
+
+ it("draws a flat list sorted by path, name or status", () => {
+ const groups = groupsOf({ ...STATUS, changes: [file("src/b.ts"), file("a/z.ts", "U", "untracked"), file("src/a.ts", "D", "deleted")] });
+ const paths = (sort: "path" | "name" | "status") =>
+ buildRows(groups, "list", sort, new Set())
+ .filter((row) => row.kind === "file")
+ .map((row) => (row.kind === "file" ? row.file.path : ""));
+ expect(paths("path")).toEqual(["a/z.ts", "src/a.ts", "src/b.ts"]);
+ expect(paths("name")).toEqual(["src/a.ts", "src/b.ts", "a/z.ts"]);
+ expect(paths("status")).toEqual(["a/z.ts", "src/b.ts", "src/a.ts"]);
+ });
+
+ it("folds single-child folders together in tree mode and hides closed ones", () => {
+ const groups = groupsOf({ ...STATUS, changes: [file("src/components/a.ts"), file("src/components/b.ts"), file("README.md")] });
+ const rows = buildRows(groups, "tree", "path", new Set());
+ expect(rows.map((row) => (row.kind === "folder" ? `dir:${row.label}` : row.kind === "file" ? row.file.path : row.key))).toEqual([
+ "group:changes",
+ "dir:src/components",
+ "src/components/a.ts",
+ "src/components/b.ts",
+ "README.md",
+ ]);
+ const folder = rows.find((row) => row.kind === "folder")!;
+ expect(folder.kind === "folder" && folder.files).toEqual(["src/components/a.ts", "src/components/b.ts"]);
+ const closed = buildRows(groups, "tree", "path", new Set([folder.key]));
+ expect(closed.filter((row) => row.kind === "file")).toHaveLength(1);
+ expect(buildRows(groups, "tree", "path", new Set(["group:changes"]))).toHaveLength(1);
+ });
+
+ it("maps repository paths into the workspace folder", () => {
+ expect(workspacePath("app/src/x.ts", "app/")).toBe("src/x.ts");
+ expect(workspacePath("other/x.ts", "app/")).toBeNull();
+ expect(workspacePath("x.ts", "")).toBe("x.ts");
+ });
+});
+
+describe("the commit button", () => {
+ it("commits while there are changes, else publishes or syncs", () => {
+ expect(primaryAction({ ...STATUS, changes: [file("a")] })).toEqual({ kind: "commit", enabled: true });
+ expect(primaryAction({ ...STATUS, upstream: "" })).toEqual({ kind: "publish" });
+ expect(primaryAction({ ...STATUS, ahead: 2, behind: 1 })).toEqual({ kind: "sync", ahead: 2, behind: 1 });
+ expect(primaryAction(STATUS)).toEqual({ kind: "commit", enabled: false });
+ expect(primaryAction({ ...STATUS, upstream: "", remotes: [] })).toEqual({ kind: "commit", enabled: false });
+ });
+
+ it("continues a rebase once its conflicts are gone, and commits a merge", () => {
+ expect(primaryAction({ ...STATUS, operation: "rebase", staged: [file("a")] })).toEqual({ kind: "continue", operation: "rebase" });
+ expect(primaryAction({ ...STATUS, operation: "rebase", merge: [file("a", "!")] })).toEqual({ kind: "commit", enabled: true });
+ expect(primaryAction({ ...STATUS, operation: "merge" })).toEqual({ kind: "commit", enabled: true });
+ });
+});
+
+describe("refs and the graph", () => {
+ it("reads git's decorations as badges, the current branch first", () => {
+ expect(parseRefs(["refs/remotes/origin/main", "HEAD -> refs/heads/main", "tag: refs/tags/v1.0", "refs/remotes/origin/HEAD"])).toEqual([
+ { kind: "head", name: "main", current: true },
+ { kind: "remote", name: "origin/main", current: false },
+ { kind: "tag", name: "v1.0", current: false },
+ ]);
+ expect(parseRefs(["HEAD"])).toEqual([]);
+ });
+
+ const commit = (id: string, parents: string[]): GraphCommit => ({ id, parents, author: "a", email: "", date: 0, refs: [], subject: id });
+
+ it("keeps a straight history in one lane", () => {
+ const rows = layoutGraph([commit("c", ["b"]), commit("b", ["a"]), commit("a", [])]);
+ expect(rows.map((row) => row.lane)).toEqual([0, 0, 0]);
+ expect(rows[2].bottom).toEqual([]);
+ });
+
+ it("opens a lane for a merged branch and closes it where the branch started", () => {
+ // m merges f into main; f and b both come from a.
+ const rows = layoutGraph([commit("m", ["b", "f"]), commit("f", ["a"]), commit("b", ["a"]), commit("a", [])]);
+ expect(rows[0]).toMatchObject({ lane: 0, branches: [1], bottom: ["b", "f"] });
+ expect(rows[1]).toMatchObject({ lane: 1, bottom: ["b", "a"] });
+ expect(rows[2]).toMatchObject({ lane: 0, bottom: ["a", "a"] });
+ expect(rows[3]).toMatchObject({ lane: 0, joins: [1], bottom: [] });
+ });
+
+ it("gives a second branch tip its own lane", () => {
+ const rows = layoutGraph([commit("x", ["a"]), commit("y", ["a"]), commit("a", [])]);
+ expect(rows.map((row) => row.lane)).toEqual([0, 1, 0]);
+ expect(rows[2].joins).toEqual([1]);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmModel.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmModel.ts
new file mode 100644
index 0000000000..7be013f728
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/scmModel.ts
@@ -0,0 +1,291 @@
+/**
+ * The pure half of the Git tab's source control: how the status letters look,
+ * how the file groups turn into list or tree rows, how the commit graph's
+ * lanes run, and what the commit button offers. No React, so it is tested
+ * directly.
+ */
+import type { GraphCommit, ScmFile, ScmLetter, ScmStatus } from "./scmApi";
+
+export type GroupId = "merge" | "staged" | "changes";
+export type ViewMode = "list" | "tree";
+export type SortKey = "path" | "name" | "status";
+
+// ------------------------------------------------------------------ letters
+
+/** The class that colours a file's name and letter (`scm-tone-*` in scm.css). */
+export function letterTone(letter: ScmLetter): string {
+ return `scm-tone-${letter}`;
+}
+
+/** The i18n key of a file state's tooltip word ("Modified", "Index Added", …). */
+export function statusKey(status: string): string {
+ return `ide_side_panel.git.scm.state.${status}`;
+}
+
+export const FILE_STATES = [
+ "index_modified",
+ "index_type_changed",
+ "index_added",
+ "index_deleted",
+ "index_renamed",
+ "index_copied",
+ "modified",
+ "type_changed",
+ "deleted",
+ "intent_to_add",
+ "intent_to_rename",
+ "untracked",
+ "both_deleted",
+ "added_by_us",
+ "deleted_by_them",
+ "added_by_them",
+ "deleted_by_us",
+ "both_added",
+ "both_modified",
+] as const;
+
+// ------------------------------------------------------------------ paths
+
+export const baseName = (path: string) => path.split("/").filter(Boolean).pop() ?? path;
+export const dirName = (path: string) => path.split("/").slice(0, -1).join("/");
+
+/** A repository path as a path in the workspace folder; null when it lies outside it. */
+export function workspacePath(path: string, prefix: string): string | null {
+ if (!prefix) return path;
+ return path.startsWith(prefix) ? path.slice(prefix.length) : null;
+}
+
+/** The key that identifies one file row (the same path can sit in two groups). */
+export const fileKey = (group: GroupId, path: string) => `${group}:${path}`;
+
+// ------------------------------------------------------------------ rows
+
+export type Row =
+ | { kind: "group"; key: string; group: GroupId; count: number; open: boolean }
+ | { kind: "folder"; key: string; group: GroupId; path: string; label: string; depth: number; open: boolean; files: string[] }
+ | { kind: "file"; key: string; group: GroupId; file: ScmFile; depth: number };
+
+export interface Group {
+ id: GroupId;
+ files: ScmFile[];
+}
+
+/** The groups the list shows, in order; an empty group is left out (Changes always shows). */
+export function groupsOf(status: ScmStatus): Group[] {
+ const groups: Group[] = [];
+ if (status.merge.length) groups.push({ id: "merge", files: status.merge });
+ if (status.staged.length) groups.push({ id: "staged", files: status.staged });
+ groups.push({ id: "changes", files: status.changes });
+ return groups;
+}
+
+const LETTER_ORDER: Record<string, number> = { "!": 0, U: 1, A: 2, M: 3, T: 4, R: 5, C: 6, D: 7, I: 8 };
+
+function sortFiles(files: ScmFile[], sort: SortKey): ScmFile[] {
+ const byPath = (a: ScmFile, b: ScmFile) => a.path.localeCompare(b.path);
+ const copy = [...files];
+ if (sort === "name") return copy.sort((a, b) => baseName(a.path).localeCompare(baseName(b.path)) || byPath(a, b));
+ if (sort === "status") return copy.sort((a, b) => (LETTER_ORDER[a.letter] ?? 9) - (LETTER_ORDER[b.letter] ?? 9) || byPath(a, b));
+ return copy.sort(byPath);
+}
+
+interface TreeNode {
+ name: string;
+ path: string;
+ folders: Map<string, TreeNode>;
+ files: ScmFile[];
+}
+
+function buildTree(files: ScmFile[]): TreeNode {
+ const root: TreeNode = { name: "", path: "", folders: new Map(), files: [] };
+ for (const file of files) {
+ const parts = file.path.split("/");
+ let node = root;
+ for (const part of parts.slice(0, -1)) {
+ let next = node.folders.get(part);
+ if (!next) {
+ next = { name: part, path: node.path ? `${node.path}/${part}` : part, folders: new Map(), files: [] };
+ node.folders.set(part, next);
+ }
+ node = next;
+ }
+ node.files.push(file);
+ }
+ return root;
+}
+
+function filesUnder(node: TreeNode): string[] {
+ return [...node.files.map((file) => file.path), ...[...node.folders.values()].flatMap(filesUnder)];
+}
+
+/**
+ * Every row the list draws, top to bottom. `closed` holds the keys of folded
+ * groups and folders. In tree mode a folder with a single sub-folder and no
+ * files of its own folds into it ("src/components").
+ */
+export function buildRows(groups: Group[], mode: ViewMode, sort: SortKey, closed: ReadonlySet<string>): Row[] {
+ const rows: Row[] = [];
+ for (const group of groups) {
+ const groupKey = `group:${group.id}`;
+ const open = !closed.has(groupKey);
+ rows.push({ kind: "group", key: groupKey, group: group.id, count: group.files.length, open });
+ if (!open) continue;
+ if (mode === "list") {
+ for (const file of sortFiles(group.files, sort)) {
+ rows.push({ kind: "file", key: fileKey(group.id, file.path), group: group.id, file, depth: 1 });
+ }
+ continue;
+ }
+ const walk = (node: TreeNode, depth: number) => {
+ const folders = [...node.folders.values()].sort((a, b) => a.name.localeCompare(b.name));
+ for (const start of folders) {
+ let folder = start;
+ let label = folder.name;
+ while (folder.files.length === 0 && folder.folders.size === 1) {
+ folder = [...folder.folders.values()][0];
+ label = `${label}/${folder.name}`;
+ }
+ const key = `${group.id}:dir:${folder.path}`;
+ const folderOpen = !closed.has(key);
+ rows.push({ kind: "folder", key, group: group.id, path: folder.path, label, depth, open: folderOpen, files: filesUnder(folder) });
+ if (folderOpen) walk(folder, depth + 1);
+ }
+ for (const file of sortFiles(node.files, sort === "path" ? "name" : sort)) {
+ rows.push({ kind: "file", key: fileKey(group.id, file.path), group: group.id, file, depth });
+ }
+ };
+ walk(buildTree(group.files), 1);
+ }
+ return rows;
+}
+
+/** The file paths a row stands for: the file itself, or everything under a folder or group. */
+export function pathsOfRow(row: Row, groups: Group[]): string[] {
+ if (row.kind === "file") return [row.file.path];
+ if (row.kind === "folder") return row.files;
+ return groups.find((group) => group.id === row.group)?.files.map((file) => file.path) ?? [];
+}
+
+// ------------------------------------------------------------------ commit button
+
+export type PrimaryAction =
+ | { kind: "commit"; enabled: boolean }
+ | { kind: "continue"; operation: string }
+ | { kind: "publish" }
+ | { kind: "sync"; ahead: number; behind: number };
+
+/** What the big button under the message box does right now. */
+export function primaryAction(status: ScmStatus): PrimaryAction {
+ const hasChanges = status.staged.length + status.changes.length + status.merge.length > 0;
+ if (status.operation && status.operation !== "bisect" && status.merge.length === 0 && status.operation !== "merge") {
+ return { kind: "continue", operation: status.operation };
+ }
+ if (hasChanges || status.operation === "merge") return { kind: "commit", enabled: true };
+ if (status.branch && !status.upstream && status.remotes.length > 0 && !status.unborn) return { kind: "publish" };
+ if (status.upstream && (status.ahead > 0 || status.behind > 0)) return { kind: "sync", ahead: status.ahead, behind: status.behind };
+ return { kind: "commit", enabled: false };
+}
+
+// ------------------------------------------------------------------ refs
+
+export interface RefBadge {
+ kind: "head" | "remote" | "tag";
+ name: string;
+ /** The branch HEAD points at. */
+ current: boolean;
+}
+
+/** `git log %D` decorations (with `--decorate=full`) as badges; `origin/HEAD` is left out. */
+export function parseRefs(refs: string[]): RefBadge[] {
+ const badges: RefBadge[] = [];
+ for (const raw of refs) {
+ let value = raw.trim();
+ let current = false;
+ if (value === "HEAD") continue;
+ if (value.startsWith("HEAD -> ")) {
+ value = value.slice("HEAD -> ".length);
+ current = true;
+ }
+ if (value.startsWith("tag: ")) {
+ badges.push({ kind: "tag", name: value.slice("tag: refs/tags/".length), current: false });
+ } else if (value.startsWith("refs/heads/")) {
+ badges.push({ kind: "head", name: value.slice("refs/heads/".length), current });
+ } else if (value.startsWith("refs/remotes/")) {
+ const name = value.slice("refs/remotes/".length);
+ if (!name.endsWith("/HEAD")) badges.push({ kind: "remote", name, current: false });
+ }
+ }
+ // The current branch first, then branches, remotes, tags.
+ const order = { head: 1, remote: 2, tag: 3 } as const;
+ return badges.sort((a, b) => Number(b.current) - Number(a.current) || order[a.kind] - order[b.kind]);
+}
+
+// ------------------------------------------------------------------ graph
+
+export interface GraphRow {
+ commit: GraphCommit;
+ /** The lane this commit's dot sits in. */
+ lane: number;
+ /** Lanes entering the row from above: [lane, its commit] (null = empty lane). */
+ top: (string | null)[];
+ /** Lanes leaving the row downwards. */
+ bottom: (string | null)[];
+ /** Lanes the commit's second and later parents leave through. */
+ branches: number[];
+ /** Lanes that end in this commit (other children joining it). */
+ joins: number[];
+ /** Lanes this row needs to draw. */
+ width: number;
+}
+
+/**
+ * Lane layout for commits in topological order. Each lane holds the commit it
+ * is waiting for; a commit takes the first lane waiting for it (or a free one),
+ * its first parent continues in that lane, every further parent takes the lane
+ * already waiting for it or a free one.
+ */
+export function layoutGraph(commits: GraphCommit[]): GraphRow[] {
+ const lanes: (string | null)[] = [];
+ const rows: GraphRow[] = [];
+ for (const commit of commits) {
+ let lane = lanes.indexOf(commit.id);
+ const top = [...lanes];
+ if (lane < 0) {
+ lane = lanes.indexOf(null);
+ if (lane < 0) {
+ lane = lanes.length;
+ lanes.push(null);
+ }
+ }
+ const joins: number[] = [];
+ lanes.forEach((value, index) => {
+ if (value === commit.id && index !== lane) {
+ joins.push(index);
+ lanes[index] = null;
+ }
+ });
+ lanes[lane] = commit.parents[0] ?? null;
+ const branches: number[] = [];
+ for (const parent of commit.parents.slice(1)) {
+ let target = lanes.indexOf(parent);
+ if (target < 0) {
+ target = lanes.indexOf(null);
+ if (target < 0) {
+ target = lanes.length;
+ lanes.push(null);
+ }
+ lanes[target] = parent;
+ }
+ branches.push(target);
+ }
+ while (lanes.length && lanes[lanes.length - 1] === null) lanes.pop();
+ const bottom = [...lanes];
+ rows.push({ commit, lane, top, bottom, branches, joins, width: Math.max(top.length, bottom.length, lane + 1) });
+ }
+ return rows;
+}
+
+/** One of five lane colours, the same lane always the same one. */
+export const LANE_COLORS = 5;
+/** The first lane carries the checked-out branch and takes its ref colour; the others cycle. */
+export const laneColor = (lane: number) => (lane === 0 ? "var(--scm-ref-local)" : `var(--scm-lane-${(lane - 1) % LANE_COLORS})`);
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/useScm.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/useScm.tsx
new file mode 100644
index 0000000000..e1714ec052
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/scm/useScm.tsx
@@ -0,0 +1,631 @@
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { Cloud, GitBranch, Plus, Tag } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { GitApiError } from "@/lib/gitApi";
+import { useEventStore } from "@/store/events";
+import { Codicon } from "./Codicon";
+import { scmApi, type ScmRef, type ScmStatus } from "./scmApi";
+import type { QuickInput, QuickPickItem } from "./QuickInput";
+
+const POLL_MS = 5_000;
+const POLL_JITTER_MS = 1_500;
+
+/** A choice the tab asks for before something that cannot be taken back. */
+export interface Choice {
+ title: string;
+ body?: string;
+ buttons: { id: string; label: string; primary?: boolean; destructive?: boolean }[];
+}
+
+/** The open workspace's source control state, read again every few seconds while it is on screen. */
+export function useScmStatus(workspaceId: string | null) {
+ const [status, setStatus] = useState<ScmStatus | null>(null);
+ const [error, setError] = useState<GitApiError | null>(null);
+ const [round, setRound] = useState(0);
+ const last = useRef("");
+ useEffect(() => {
+ setStatus(null);
+ setError(null);
+ last.current = "";
+ }, [workspaceId]);
+ useEffect(() => {
+ if (!workspaceId) return;
+ let alive = true;
+ let timer: number | undefined;
+ let controller: AbortController | null = null;
+ const tick = async () => {
+ const visible = typeof document === "undefined" || document.visibilityState !== "hidden";
+ if (visible && useEventStore.getState().activeSection === "agentic-ide") {
+ controller = new AbortController();
+ try {
+ const next = await scmApi.status(workspaceId, controller.signal);
+ const text = JSON.stringify(next);
+ // An unchanged answer keeps the same object: the list does not redraw.
+ if (alive && text !== last.current) {
+ last.current = text;
+ setStatus(next);
+ }
+ if (alive) setError(null);
+ } catch (err) {
+ if (alive && !(err instanceof DOMException && err.name === "AbortError")) {
+ setError(err instanceof GitApiError ? err : new GitApiError((err as Error).message, "failed"));
+ }
+ }
+ }
+ if (alive) timer = window.setTimeout(tick, POLL_MS + Math.random() * POLL_JITTER_MS);
+ };
+ void tick();
+ const onFocus = () => {
+ window.clearTimeout(timer);
+ void tick();
+ };
+ window.addEventListener("focus", onFocus);
+ return () => {
+ alive = false;
+ controller?.abort();
+ window.clearTimeout(timer);
+ window.removeEventListener("focus", onFocus);
+ };
+ }, [workspaceId, round]);
+ const refresh = useCallback(() => setRound((value) => value + 1), []);
+ return { status, error, refresh };
+}
+
+function ChoiceDialog({ choice, onDone }: { choice: Choice; onDone: (id: string | undefined) => void }) {
+ const t = useT();
+ const first = useRef<HTMLButtonElement>(null);
+ useEffect(() => first.current?.focus(), []);
+ return createPortal(
+ <div
+ role="presentation"
+ className="scm-portal fixed inset-0 z-[115] flex items-start justify-center p-4 pt-[12vh]"
+ style={{ background: "rgba(0, 0, 0, 0.3)" }}
+ onPointerDown={(event) => event.target === event.currentTarget && onDone(undefined)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ onDone(undefined);
+ }
+ }}
+ >
+ <section
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby="scm-choice-title"
+ data-testid="scm-choice"
+ className="flex w-full max-w-[460px] flex-col rounded-[6px] px-[20px] pb-[18px] pt-[20px]"
+ style={{ background: "var(--scm-menu-bg)", color: "var(--scm-menu-fg)", border: "1px solid var(--scm-menu-border)", boxShadow: "0 0 8px 2px rgba(0, 0, 0, 0.36)" }}
+ >
+ <div className="flex gap-[12px]">
+ <Codicon name="warning" className="!text-[24px] !leading-[24px]" />
+ <div className="min-w-0 flex-1">
+ <h2 id="scm-choice-title" className="whitespace-pre-line break-words text-[13px] font-semibold leading-[20px]">
+ {choice.title}
+ </h2>
+ {choice.body && <p className="mt-[6px] whitespace-pre-line break-words text-[13px] leading-[20px] opacity-90">{choice.body}</p>}
+ </div>
+ </div>
+ <div className="mt-[20px] flex flex-wrap justify-end gap-[8px]">
+ {choice.buttons.map((button, index) => (
+ <button
+ key={button.id}
+ ref={index === 0 ? first : undefined}
+ type="button"
+ data-testid={`scm-choice-${button.id}`}
+ onClick={() => onDone(button.id)}
+ style={index === 0 ? undefined : { background: "var(--scm-input-bg)", color: "var(--scm-fg)", border: "1px solid var(--scm-input-border)" }}
+ className={index === 0 ? "scm-button inline-flex h-[26px] min-w-[80px] items-center justify-center rounded-[2px] px-[12px] text-[13px]" : "inline-flex h-[26px] min-w-[80px] items-center justify-center rounded-[2px] px-[12px] text-[13px] hover:opacity-90"}
+ >
+ {button.label}
+ </button>
+ ))}
+ <button
+ type="button"
+ data-testid="scm-choice-cancel"
+ onClick={() => onDone(undefined)}
+ style={{ background: "var(--scm-input-bg)", color: "var(--scm-fg)", border: "1px solid var(--scm-input-border)" }}
+ className="inline-flex h-[26px] min-w-[80px] items-center justify-center rounded-[2px] px-[12px] text-[13px] hover:opacity-90"
+ >
+ {t("ide_side_panel.git.confirm.cancel")}
+ </button>
+ </div>
+ </section>
+ </div>,
+ document.body,
+ );
+}
+
+/** `ask(choice)` resolves with the button pressed, or undefined on cancel. */
+export function useChoice(): { ask: (choice: Choice) => Promise<string | undefined>; element: ReactNode } {
+ const [current, setCurrent] = useState<{ choice: Choice; resolve: (id: string | undefined) => void } | null>(null);
+ const ask = useCallback(
+ (choice: Choice) =>
+ new Promise<string | undefined>((resolve) => {
+ setCurrent((previous) => {
+ previous?.resolve(undefined);
+ return { choice, resolve };
+ });
+ }),
+ [],
+ );
+ const element = current ? (
+ <ChoiceDialog
+ choice={current.choice}
+ onDone={(id) => {
+ current.resolve(id);
+ setCurrent(null);
+ }}
+ />
+ ) : null;
+ return { ask, element };
+}
+
+const storage = {
+ get(key: string): string {
+ try {
+ return window.localStorage.getItem(key) ?? "";
+ } catch {
+ return ""; // storage blocked: every question is asked again
+ }
+ },
+ set(key: string, value: string) {
+ try {
+ window.localStorage.setItem(key, value);
+ } catch {
+ // storage blocked: the choice lasts for this session only
+ }
+ },
+};
+export const scmStorage = storage;
+
+export type CommitKind = "commit" | "amend" | "push" | "sync";
+export interface CommitOptions {
+ kind: CommitKind;
+ /** `staged` commits the index only, `all` stages everything first; omitted = decide (smart commit). */
+ scope?: "staged" | "all";
+ signoff?: boolean;
+ noVerify?: boolean;
+}
+
+/**
+ * Every git command of the Git tab: each runs once at a time behind the
+ * progress bar, reports a failure in a toast and re-reads the status. Commands
+ * that pick a branch, a remote or a stash ask through the quick input; those
+ * that cannot be undone ask through a choice dialog first.
+ */
+export function useScmCommands({
+ workspaceId,
+ status,
+ refresh,
+ quick,
+ ask,
+ onChanged,
+}: {
+ workspaceId: string;
+ status: ScmStatus | null;
+ refresh: () => void;
+ quick: QuickInput;
+ ask: (choice: Choice) => Promise<string | undefined>;
+ /** History or refs may have moved: the graph reads again. */
+ onChanged: () => void;
+}) {
+ const t = useT();
+ const pushToast = useEventStore((state) => state.pushToast);
+ const [busy, setBusy] = useState("");
+ // Commands run one after another, in the order they were asked for: a quick
+ // second click (stage, then unstage) waits for the first instead of racing it.
+ const queue = useRef<Promise<unknown>>(Promise.resolve());
+ const pending = useRef(0);
+ const statusRef = useRef(status);
+ statusRef.current = status;
+
+ const run = useCallback(
+ <T,>(label: string, action: () => Promise<T>, { history = true }: { history?: boolean } = {}): Promise<T | undefined> => {
+ pending.current += 1;
+ const next = queue.current.then(async () => {
+ setBusy(label);
+ try {
+ return await action();
+ } catch (err) {
+ pushToast("error", (err as Error).message);
+ return undefined;
+ } finally {
+ pending.current -= 1;
+ if (pending.current === 0) setBusy("");
+ refresh();
+ if (history) onChanged();
+ }
+ });
+ queue.current = next;
+ return next;
+ },
+ [pushToast, refresh, onChanged],
+ );
+
+ const refs = useCallback(async (): Promise<ScmRef[]> => {
+ try {
+ return (await scmApi.refs(workspaceId)).refs;
+ } catch (err) {
+ pushToast("error", (err as Error).message);
+ return [];
+ }
+ }, [workspaceId, pushToast]);
+
+ const refItems = useCallback(
+ (list: ScmRef[], kinds: ScmRef["kind"][], skip = ""): QuickPickItem<string>[] =>
+ list
+ .filter((ref) => kinds.includes(ref.kind) && ref.name !== skip)
+ .map((ref) => ({
+ label: ref.name,
+ description: `${ref.commit}${ref.subject ? ` · ${ref.subject}` : ""}`,
+ icon:
+ ref.kind === "tag" ? (
+ <Tag className="h-3.5 w-3.5" aria-hidden />
+ ) : ref.kind === "remote" ? (
+ <Cloud className="h-3.5 w-3.5" aria-hidden />
+ ) : (
+ <GitBranch className="h-3.5 w-3.5" aria-hidden />
+ ),
+ group: t(`ide_side_panel.git.scm.ref_group.${ref.kind}`),
+ value: ref.name,
+ })),
+ [t],
+ );
+
+ const branchName = useCallback(
+ (prompt: string, value = "") =>
+ quick.input({
+ prompt,
+ placeholder: t("ide_side_panel.git.scm.branch_name_placeholder"),
+ value,
+ validate: (text) => (/\s|\.\.|[~^:?*[\\]|^-|^\/|\/$|\.lock$|@\{/.test(text.trim()) ? t("ide_side_panel.git.scm.branch_name_invalid") : ""),
+ }),
+ [quick, t],
+ );
+
+ const pickRemote = useCallback(
+ async (placeholder: string): Promise<string | undefined> => {
+ const remotes = statusRef.current?.remotes ?? [];
+ if (remotes.length === 0) {
+ pushToast("warning", t("ide_side_panel.git.scm.no_remotes"));
+ return undefined;
+ }
+ if (remotes.length === 1) return remotes[0];
+ return quick.pick(
+ remotes.map((name) => ({ label: name, value: name, icon: <Cloud className="h-3.5 w-3.5" aria-hidden /> })),
+ placeholder,
+ );
+ },
+ [quick, pushToast, t],
+ );
+
+ const commands = useMemo(() => {
+ const id = workspaceId;
+ const push = () => run("push", () => scmApi.push(id));
+ const publish = async () => {
+ const remote = await pickRemote(t("ide_side_panel.git.scm.pick_remote_publish"));
+ if (remote) await run("publish", () => scmApi.push(id, { remote }));
+ };
+ const sync = async () => {
+ const current = statusRef.current;
+ if (current && !current.upstream) return publish();
+ if (storage.get("jarvis.git.scm.confirmSync") !== "never") {
+ const answer = await ask({
+ title: fill(t("ide_side_panel.git.scm.sync_confirm"), { upstream: current?.upstream ?? "" }),
+ buttons: [
+ { id: "ok", label: t("ide_side_panel.git.scm.ok"), primary: true },
+ { id: "always", label: t("ide_side_panel.git.scm.ok_dont_ask") },
+ ],
+ });
+ if (!answer) return;
+ if (answer === "always") storage.set("jarvis.git.scm.confirmSync", "never");
+ }
+ await run("sync", () => scmApi.sync(id));
+ };
+
+ const commit = async (message: string, options: CommitOptions): Promise<boolean> => {
+ const current = statusRef.current;
+ if (!current) return false;
+ const amend = options.kind === "amend";
+ let scope = options.scope;
+ if (!scope) {
+ if (current.staged.length > 0 || current.operation === "merge") scope = "staged";
+ else if (current.changes.length > 0) {
+ const smart = storage.get("jarvis.git.scm.smartCommit");
+ if (smart !== "always") {
+ const answer = await ask({
+ title: t("ide_side_panel.git.scm.smart_commit_title"),
+ buttons: [
+ { id: "yes", label: t("ide_side_panel.git.scm.yes"), primary: true },
+ { id: "always", label: t("ide_side_panel.git.scm.always") },
+ ],
+ });
+ if (!answer) return false;
+ if (answer === "always") storage.set("jarvis.git.scm.smartCommit", "always");
+ }
+ scope = "all";
+ } else if (!amend) {
+ pushToast("info", t("ide_side_panel.git.scm.nothing_to_commit"));
+ return false;
+ } else scope = "staged";
+ }
+ if (amend && !message.trim()) {
+ // An amend without a new message keeps the last one.
+ } else if (!message.trim()) return false;
+ const made = await run("commit", () =>
+ scmApi.commitChanges(id, message, {
+ amend,
+ all_changes: scope === "all",
+ signoff: options.signoff,
+ no_verify: options.noVerify,
+ }),
+ );
+ if (!made) return false;
+ if (options.kind === "push") await run("push", () => scmApi.push(id));
+ if (options.kind === "sync") await run("sync", () => scmApi.sync(id));
+ return true;
+ };
+
+ const discardFiles = async (files: { path: string; letter: string }[]) => {
+ if (files.length === 0) return;
+ const untracked = files.filter((file) => file.letter === "U");
+ const name = files[0].path.split("/").pop() ?? files[0].path;
+ let title: string;
+ let label: string;
+ if (files.length === 1 && untracked.length === 1) {
+ title = fill(t("ide_side_panel.git.scm.delete_untracked_one"), { name });
+ label = t("ide_side_panel.git.scm.delete_file");
+ } else if (files.length === 1) {
+ title = fill(t("ide_side_panel.git.scm.discard_one"), { name });
+ label = t("ide_side_panel.git.scm.discard_file");
+ } else {
+ title = fill(t("ide_side_panel.git.scm.discard_many"), { n: files.length });
+ label = fill(t("ide_side_panel.git.scm.discard_n_files"), { n: files.length });
+ }
+ const answer = await ask({
+ title,
+ body: untracked.length ? t("ide_side_panel.git.scm.untracked_to_trash") : t("ide_side_panel.git.scm.cannot_undo"),
+ buttons: [{ id: "discard", label, destructive: true }],
+ });
+ if (answer === "discard") await run("discard", () => scmApi.discard(id, files.map((file) => file.path)), { history: false });
+ };
+
+ const discardAll = async () => {
+ const current = statusRef.current;
+ if (!current || current.changes.length === 0) return;
+ const untracked = current.changes.filter((file) => file.letter === "U").length;
+ const tracked = current.changes.length - untracked;
+ const buttons: Choice["buttons"] = [];
+ if (untracked > 0) buttons.push({ id: "all", label: fill(t("ide_side_panel.git.scm.discard_all_files"), { n: current.changes.length }), destructive: true });
+ if (tracked > 0) buttons.push({ id: "tracked", label: fill(t("ide_side_panel.git.scm.discard_tracked_files"), { n: tracked }), destructive: untracked === 0 });
+ const answer = await ask({
+ title: fill(t("ide_side_panel.git.scm.discard_all_title"), { n: current.changes.length }),
+ body: untracked ? fill(t("ide_side_panel.git.scm.discard_all_body"), { n: untracked }) : t("ide_side_panel.git.scm.cannot_undo"),
+ buttons,
+ });
+ if (answer) await run("discard", () => scmApi.discardAll(id, answer === "all"), { history: false });
+ };
+
+ const checkoutTo = async (detached = false) => {
+ const list = await refs();
+ type Pick = { action: "create" | "create_from" | "detached" } | { ref: string };
+ const items: QuickPickItem<Pick>[] = [
+ ...(detached
+ ? []
+ : [
+ { label: t("ide_side_panel.git.scm.create_branch"), icon: <Plus className="h-3.5 w-3.5" aria-hidden />, value: { action: "create" as const } },
+ { label: t("ide_side_panel.git.scm.create_branch_from"), icon: <Plus className="h-3.5 w-3.5" aria-hidden />, value: { action: "create_from" as const } },
+ { label: t("ide_side_panel.git.scm.checkout_detached"), icon: <GitBranch className="h-3.5 w-3.5" aria-hidden />, value: { action: "detached" as const } },
+ ]),
+ ...refItems(list, detached ? ["head", "remote", "tag"] : ["head", "remote", "tag"]).map((item) => ({ ...item, value: { ref: item.value } })),
+ ];
+ const picked = await quick.pick(items, detached ? t("ide_side_panel.git.scm.pick_detached") : t("ide_side_panel.git.scm.pick_checkout"));
+ if (!picked) return;
+ if ("ref" in picked) {
+ await run("checkout", () => scmApi.checkout(id, picked.ref, detached));
+ return;
+ }
+ if (picked.action === "detached") return checkoutTo(true);
+ if (picked.action === "create") return createBranch();
+ return createBranchFrom();
+ };
+
+ const createBranch = async (start = "") => {
+ const name = await branchName(t("ide_side_panel.git.scm.branch_name_prompt"));
+ if (name?.trim()) await run("branch", () => scmApi.createBranch(id, name.trim(), start));
+ };
+ const createBranchFrom = async () => {
+ const list = await refs();
+ const start = await quick.pick(refItems(list, ["head", "remote", "tag"]), t("ide_side_panel.git.scm.pick_branch_from"));
+ if (start) await createBranch(start);
+ };
+ const renameBranch = async () => {
+ const current = statusRef.current?.branch ?? "";
+ const name = await branchName(t("ide_side_panel.git.scm.rename_prompt"), current);
+ if (name?.trim() && name.trim() !== current) await run("rename", () => scmApi.renameBranch(id, name.trim()));
+ };
+ const deleteBranch = async () => {
+ const list = await refs();
+ const name = await quick.pick(refItems(list, ["head"], statusRef.current?.branch), t("ide_side_panel.git.scm.pick_delete_branch"));
+ if (!name) return;
+ let unmerged = false;
+ await run("delete", async () => {
+ try {
+ await scmApi.deleteBranch(id, name);
+ } catch (err) {
+ // Its commits are on no other branch: ask before deleting them for good.
+ if (!(err instanceof GitApiError && err.code === "unmerged")) throw err;
+ unmerged = true;
+ }
+ });
+ if (unmerged) await deleteBranchForce(name);
+ };
+ const deleteBranchForce = async (name: string) => {
+ const answer = await ask({
+ title: fill(t("ide_side_panel.git.scm.delete_unmerged"), { name }),
+ buttons: [{ id: "force", label: t("ide_side_panel.git.scm.delete_branch_button"), destructive: true }],
+ });
+ if (answer) await run("delete", () => scmApi.deleteBranch(id, name, true));
+ };
+ const mergeBranch = async () => {
+ const list = await refs();
+ const ref = await quick.pick(refItems(list, ["head", "remote", "tag"], statusRef.current?.branch), t("ide_side_panel.git.scm.pick_merge"));
+ if (!ref) return;
+ const answer = await run("merge", () => scmApi.merge(id, ref));
+ if (answer?.result === "conflict") pushToast("warning", t("ide_side_panel.git.scm.merge_conflicts"));
+ };
+ const rebaseBranch = async () => {
+ const list = await refs();
+ const ref = await quick.pick(refItems(list, ["head", "remote"], statusRef.current?.branch), t("ide_side_panel.git.scm.pick_rebase"));
+ if (!ref) return;
+ const answer = await run("rebase", () => scmApi.rebase(id, ref));
+ if (answer?.result === "conflict") pushToast("warning", t("ide_side_panel.git.scm.rebase_conflicts"));
+ };
+
+ const pullFrom = async () => {
+ const remote = await pickRemote(t("ide_side_panel.git.scm.pick_remote_pull"));
+ if (!remote) return;
+ const list = await refs();
+ const branch = await quick.pick(
+ refItems(list.filter((ref) => ref.kind === "remote" && ref.name.startsWith(`${remote}/`)), ["remote"]).map((item) => ({
+ ...item,
+ value: item.value.slice(remote.length + 1),
+ })),
+ t("ide_side_panel.git.scm.pick_branch_pull"),
+ );
+ if (branch) await run("pull", () => scmApi.pull(id, { remote, branch }));
+ };
+ const pushTo = async () => {
+ const remote = await pickRemote(t("ide_side_panel.git.scm.pick_remote_push"));
+ if (remote) await run("push", () => scmApi.push(id, { remote }));
+ };
+
+ const addRemote = async () => {
+ const name = await quick.input({
+ prompt: t("ide_side_panel.git.scm.remote_name_prompt"),
+ validate: (text) => (/^[A-Za-z0-9._-]+$/.test(text.trim()) || !text ? "" : t("ide_side_panel.git.scm.remote_name_invalid")),
+ });
+ if (!name?.trim()) return;
+ const url = await quick.input({ prompt: t("ide_side_panel.git.scm.remote_url_prompt"), placeholder: "https://github.com/owner/repo.git" });
+ if (url?.trim()) await run("remote", () => scmApi.addRemote(id, name.trim(), url.trim()));
+ };
+ const removeRemote = async () => {
+ const remotes = statusRef.current?.remotes ?? [];
+ const name = await quick.pick(
+ remotes.map((remote) => ({ label: remote, value: remote, icon: <Cloud className="h-3.5 w-3.5" aria-hidden /> })),
+ t("ide_side_panel.git.scm.pick_remote_remove"),
+ );
+ if (name) await run("remote", () => scmApi.removeRemote(id, name));
+ };
+
+ const stash = async (options: { include_untracked?: boolean; staged?: boolean } = {}) => {
+ const message = await quick.input({ prompt: t("ide_side_panel.git.scm.stash_message_prompt"), placeholder: t("ide_side_panel.git.scm.stash_message_placeholder") });
+ if (message === undefined) return;
+ await run("stash", () => scmApi.stash(id, { message, ...options }), { history: false });
+ };
+ const pickStash = async (placeholder: string) => {
+ let stashes: { ref: string; message: string }[] = [];
+ try {
+ stashes = (await scmApi.stashes(id)).stashes;
+ } catch (err) {
+ pushToast("error", (err as Error).message);
+ return undefined;
+ }
+ if (stashes.length === 0) {
+ pushToast("info", t("ide_side_panel.git.scm.no_stashes"));
+ return undefined;
+ }
+ return quick.pick(stashes.map((entry) => ({ label: entry.message, description: entry.ref, value: entry.ref })), placeholder);
+ };
+ const applyStash = async (pop: boolean, latest: boolean) => {
+ const ref = latest ? "" : await pickStash(pop ? t("ide_side_panel.git.scm.pick_stash_pop") : t("ide_side_panel.git.scm.pick_stash_apply"));
+ if (ref === undefined) return;
+ await run("stash", () => scmApi.stashApply(id, ref, pop), { history: false });
+ };
+ const dropStash = async () => {
+ const ref = await pickStash(t("ide_side_panel.git.scm.pick_stash_drop"));
+ if (!ref) return;
+ const answer = await ask({
+ title: fill(t("ide_side_panel.git.scm.drop_stash_confirm"), { ref }),
+ buttons: [{ id: "drop", label: t("ide_side_panel.git.scm.drop"), destructive: true }],
+ });
+ if (answer) await run("stash", () => scmApi.stashDrop(id, ref), { history: false });
+ };
+ const dropAllStashes = async () => {
+ const answer = await ask({
+ title: fill(t("ide_side_panel.git.scm.drop_all_confirm"), { n: statusRef.current?.stashes ?? 0 }),
+ buttons: [{ id: "drop", label: t("ide_side_panel.git.scm.drop_all"), destructive: true }],
+ });
+ if (answer) await run("stash", () => scmApi.stashDrop(id, "", true), { history: false });
+ };
+
+ const createTag = async (ref = "") => {
+ const name = await quick.input({ prompt: t("ide_side_panel.git.scm.tag_name_prompt"), placeholder: "v1.0.0" });
+ if (!name?.trim()) return;
+ const message = await quick.input({ prompt: t("ide_side_panel.git.scm.tag_message_prompt"), placeholder: t("ide_side_panel.git.scm.tag_message_placeholder") });
+ if (message === undefined) return;
+ await run("tag", () => scmApi.createTag(id, name.trim(), message, ref));
+ };
+ const deleteTag = async () => {
+ const list = await refs();
+ const name = await quick.pick(refItems(list, ["tag"]), t("ide_side_panel.git.scm.pick_tag_delete"));
+ if (name) await run("tag", () => scmApi.deleteTag(id, name));
+ };
+
+ const undoLastCommit = async (): Promise<string | undefined> => {
+ const answer = await run("undo", () => scmApi.undoCommit(id));
+ return answer?.message;
+ };
+
+ return {
+ push,
+ publish,
+ sync,
+ commit,
+ pull: (rebase = false) => run("pull", () => scmApi.pull(id, { rebase })),
+ pullFrom,
+ pushTo,
+ pushTags: () => run("push", () => scmApi.pushTags(id)),
+ fetch: (options: { prune?: boolean; all_remotes?: boolean } = {}) => run("fetch", () => scmApi.fetch(id, options)),
+ stage: (paths: string[]) => run("stage", () => scmApi.stage(id, paths), { history: false }),
+ stageAll: () => run("stage", () => scmApi.stageAll(id), { history: false }),
+ unstage: (paths: string[]) => run("unstage", () => scmApi.unstage(id, paths), { history: false }),
+ unstageAll: () => run("unstage", () => scmApi.unstageAll(id), { history: false }),
+ discardFiles,
+ discardAll,
+ ignore: (paths: string[]) => run("ignore", () => scmApi.ignore(id, paths), { history: false }),
+ checkoutTo,
+ checkoutRef: (ref: string, detached = false) => run("checkout", () => scmApi.checkout(id, ref, detached)),
+ createBranch,
+ createBranchFrom,
+ renameBranch,
+ deleteBranch,
+ deleteBranchForce,
+ mergeBranch,
+ rebaseBranch,
+ addRemote,
+ removeRemote,
+ stash,
+ applyStash,
+ dropStash,
+ dropAllStashes,
+ createTag,
+ deleteTag,
+ undoLastCommit,
+ operation: (action: "continue" | "abort") => run(action, () => scmApi.operation(id, action)),
+ cherryPick: async (commitId: string) => {
+ const answer = await run("cherry-pick", () => scmApi.cherryPick(id, commitId));
+ if (answer?.result === "conflict") pushToast("warning", t("ide_side_panel.git.scm.cherry_pick_conflicts"));
+ },
+ revert: async (commitId: string) => {
+ const answer = await run("revert", () => scmApi.revert(id, commitId));
+ if (answer?.result === "conflict") pushToast("warning", t("ide_side_panel.git.scm.revert_conflicts"));
+ },
+ };
+ }, [workspaceId, run, refs, refItems, branchName, pickRemote, quick, ask, pushToast, t]);
+
+ return { busy, commands };
+}
+
+export type ScmCommands = ReturnType<typeof useScmCommands>["commands"];
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index b348279c8b..c86e3172b2 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -8022,7 +8022,222 @@
},
"connect_repo_body": "Wähle das GitHub-Repository dieses Ordners, um hier Pull Requests und CI zu sehen.",
"connect_repo_other": "Anderes …",
- "connect_repo_choose": "Repository wählen …"
+ "connect_repo_choose": "Repository wählen …",
+ "scm": {
+ "title": "Quellcodeverwaltung",
+ "view_changes": "Änderungen",
+ "view_graph": "Graph",
+ "view_branches": "Branches & Pull Requests",
+ "group": {
+ "merge": "Merge-Änderungen",
+ "staged": "Bereitgestellte Änderungen",
+ "changes": "Änderungen"
+ },
+ "state": {
+ "index_modified": "Index geändert",
+ "index_type_changed": "Index: Typ geändert",
+ "index_added": "Index hinzugefügt",
+ "index_deleted": "Index gelöscht",
+ "index_renamed": "Index umbenannt",
+ "index_copied": "Index kopiert",
+ "modified": "Geändert",
+ "type_changed": "Typ geändert",
+ "deleted": "Gelöscht",
+ "intent_to_add": "Zum Hinzufügen vorgemerkt",
+ "intent_to_rename": "Zum Umbenennen vorgemerkt",
+ "untracked": "Nicht verfolgt",
+ "both_deleted": "Konflikt: von beiden gelöscht",
+ "added_by_us": "Konflikt: von uns hinzugefügt",
+ "deleted_by_them": "Konflikt: von ihnen gelöscht",
+ "added_by_them": "Konflikt: von ihnen hinzugefügt",
+ "deleted_by_us": "Konflikt: von uns gelöscht",
+ "both_added": "Konflikt: von beiden hinzugefügt",
+ "both_modified": "Konflikt: von beiden geändert"
+ },
+ "operation": {
+ "merge": "Merge läuft: Konflikte lösen, bereitstellen, dann committen.",
+ "rebase": "Rebase läuft: Konflikte lösen, bereitstellen, dann fortsetzen.",
+ "cherry-pick": "Cherry-Pick läuft: Konflikte lösen, bereitstellen, dann fortsetzen.",
+ "revert": "Revert läuft: Konflikte lösen, bereitstellen, dann fortsetzen."
+ },
+ "scope": {
+ "auto": "Automatisch",
+ "current": "Aktueller Branch",
+ "all": "Alle Branches"
+ },
+ "ref_group": {
+ "head": "Branches",
+ "remote": "Remote-Branches",
+ "tag": "Tags"
+ },
+ "abort": "Abbrechen",
+ "abort_rebase": "Rebase abbrechen",
+ "add_remote": "Remote hinzufügen…",
+ "add_to_gitignore": "Zu .gitignore hinzufügen",
+ "always": "Immer",
+ "apply_latest_stash": "Neuesten Stash anwenden",
+ "apply_stash": "Stash anwenden…",
+ "binary": "Diese Datei ist binär oder zu groß für einen Vergleich.",
+ "branch_name_invalid": "Ein Branch-Name darf keine Leerzeichen, '..', '~', '^', ':', '?', '*', '[' oder '\\' enthalten.",
+ "branch_name_placeholder": "Branch-Name",
+ "branch_name_prompt": "Bitte einen Namen für den neuen Branch angeben",
+ "cannot_undo": "Das lässt sich nicht rückgängig machen.",
+ "changes_aria": "Geänderte Dateien",
+ "checkout_detached": "Losgelöst auschecken…",
+ "checkout_detached_here": "Auschecken (losgelöst)",
+ "checkout_tip": "Branch/Tag auschecken…",
+ "checkout_to": "Auschecken nach…",
+ "cherry_pick": "Cherry-Pick",
+ "cherry_pick_conflicts": "Der Cherry-Pick hat Konflikte. Löse sie unter Merge-Änderungen.",
+ "close": "Schließen",
+ "commit": "Commit",
+ "commit_all": "Alles committen",
+ "commit_all_amend": "Alles committen (ändern)",
+ "commit_all_signed_off": "Alles committen (abgezeichnet)",
+ "commit_amend": "Commit (ändern)",
+ "commit_no_verify": "Commit (ohne Prüfung)",
+ "commit_options": "Weitere Commit-Aktionen",
+ "commit_push": "Commit & Push",
+ "commit_signed_off": "Commit (abgezeichnet)",
+ "commit_staged": "Bereitgestellte committen",
+ "commit_staged_amend": "Bereitgestellte committen (ändern)",
+ "commit_staged_signed_off": "Bereitgestellte committen (abgezeichnet)",
+ "commit_sync": "Commit & Synchronisieren",
+ "commit_tip": "Änderungen auf „{branch}“ committen",
+ "continue": "Fortsetzen",
+ "copy_commit_id": "Commit-ID kopieren",
+ "copy_commit_message": "Commit-Nachricht kopieren",
+ "copy_failed": "Kopieren in die Zwischenablage fehlgeschlagen.",
+ "copy_path": "Pfad kopieren",
+ "copy_relative_path": "Relativen Pfad kopieren",
+ "create_branch": "Neuen Branch erstellen…",
+ "create_branch_from": "Neuen Branch erstellen von…",
+ "create_branch_here": "Branch erstellen…",
+ "create_tag": "Tag erstellen",
+ "create_tag_here": "Tag erstellen…",
+ "delete_branch": "Branch löschen…",
+ "delete_branch_button": "Branch löschen",
+ "delete_file": "In den Papierkorb",
+ "delete_tag": "Tag löschen",
+ "delete_unmerged": "Der Branch „{name}“ hat Commits, die auf keinem anderen Branch liegen. Trotzdem löschen?",
+ "delete_untracked_one": "„{name}“ löschen?",
+ "diff_working_tree": "Bereitgestellt ↔ Arbeitsverzeichnis",
+ "discard_all": "Alle Änderungen verwerfen",
+ "discard_all_body": "{n} davon sind nicht verfolgt und kommen in den Papierkorb. Der Rest lässt sich nicht rückgängig machen.",
+ "discard_all_files": "Alle {n} Dateien verwerfen",
+ "discard_all_title": "Alle Änderungen in {n} Dateien verwerfen?",
+ "discard_changes": "Änderungen verwerfen",
+ "discard_file": "Datei verwerfen",
+ "discard_many": "Änderungen in {n} Dateien verwerfen?",
+ "discard_n_files": "{n} Dateien verwerfen",
+ "discard_one": "Änderungen in „{name}“ verwerfen?",
+ "discard_tracked_files": "{n} verfolgte Dateien verwerfen",
+ "drop": "Verwerfen",
+ "drop_all": "Alle verwerfen",
+ "drop_all_confirm": "Alle {n} Stashes verwerfen? Das lässt sich nicht rückgängig machen.",
+ "drop_all_stashes": "Alle Stashes verwerfen…",
+ "drop_stash": "Stash verwerfen…",
+ "drop_stash_confirm": "{ref} verwerfen? Das lässt sich nicht rückgängig machen.",
+ "fetch": "Abrufen",
+ "fetch_all": "Von allen Remotes abrufen",
+ "fetch_prune": "Abrufen (bereinigen)",
+ "go_to_current": "Zum aktuellen Commit",
+ "incoming": "Eingehend: noch nicht gepullt",
+ "index": "Index",
+ "init_repository": "Repository initialisieren",
+ "load_more": "Mehr laden",
+ "mark_resolved": "Bereitstellen (als gelöst markieren)",
+ "menu_branch": "Branch",
+ "menu_changes": "Änderungen",
+ "menu_commit": "Commit",
+ "menu_pull_push": "Pull, Push",
+ "menu_remote": "Remote",
+ "menu_stash": "Stash",
+ "menu_tags": "Tags",
+ "merge_branch": "Mergen…",
+ "merge_conflicts": "Der Merge hat Konflikte. Löse sie unter Merge-Änderungen.",
+ "message_label": "Commit-Nachricht",
+ "message_placeholder": "Nachricht ({key}+Enter für Commit auf „{branch}“)",
+ "message_required": "Bitte zuerst eine Commit-Nachricht eingeben.",
+ "more_actions": "Weitere Aktionen…",
+ "no_commits": "Noch keine Commits.",
+ "no_remotes": "Dieses Repository hat keine Remotes.",
+ "no_repository": "Der Ordner dieses Workspaces ist noch kein Git-Repository.",
+ "no_stashes": "Es gibt keine Stashes.",
+ "nothing_to_commit": "Es gibt keine Änderungen zum Committen.",
+ "ok": "OK",
+ "ok_dont_ask": "OK, nicht mehr fragen",
+ "open_changes": "Änderungen öffnen",
+ "open_file": "Datei öffnen",
+ "outgoing": "Ausgehend: noch nicht gepusht",
+ "outside_workspace": "Diese Datei liegt außerhalb des Workspace-Ordners.",
+ "pick_branch_from": "Ref auswählen, von dem der Branch erstellt wird",
+ "pick_branch_pull": "Branch zum Pullen auswählen",
+ "pick_checkout": "Branch oder Tag zum Auschecken auswählen",
+ "pick_delete_branch": "Branch zum Löschen auswählen",
+ "pick_detached": "Ref zum losgelösten Auschecken auswählen",
+ "pick_merge": "Branch oder Tag zum Mergen auswählen",
+ "pick_rebase": "Branch für den Rebase auswählen",
+ "pick_remote_publish": "Remote zum Veröffentlichen des Branches auswählen",
+ "pick_remote_pull": "Remote zum Pullen auswählen",
+ "pick_remote_push": "Remote zum Pushen auswählen",
+ "pick_remote_remove": "Remote zum Entfernen auswählen",
+ "pick_stash_apply": "Stash zum Anwenden auswählen",
+ "pick_stash_drop": "Stash zum Verwerfen auswählen",
+ "pick_stash_pop": "Stash zum Anwenden und Entfernen auswählen",
+ "pick_tag_delete": "Tag zum Löschen auswählen",
+ "pop_latest_stash": "Neuesten Stash anwenden und entfernen",
+ "pop_stash": "Stash anwenden und entfernen…",
+ "publish_branch": "Branch veröffentlichen",
+ "pull": "Pull",
+ "pull_from": "Pull von…",
+ "pull_rebase": "Pull (Rebase)",
+ "push": "Push",
+ "push_tags": "Tags pushen",
+ "push_to": "Push nach…",
+ "rebase_branch": "Branch rebasen…",
+ "rebase_conflicts": "Der Rebase hat Konflikte. Löse sie unter Merge-Änderungen und setze dann fort.",
+ "refresh": "Aktualisieren",
+ "remote_name_invalid": "Nur Buchstaben, Ziffern, Punkte, Unterstriche oder Bindestriche.",
+ "remote_name_prompt": "Bitte einen Namen für das Remote angeben",
+ "remote_url_prompt": "Bitte die URL des Remotes angeben",
+ "remove_remote": "Remote entfernen",
+ "rename_branch": "Branch umbenennen…",
+ "rename_prompt": "Bitte einen neuen Namen für den Branch angeben",
+ "reveal_in_explorer": "Im Ordner-Tab anzeigen",
+ "revert_commit": "Commit zurücknehmen",
+ "revert_conflicts": "Das Zurücknehmen hat Konflikte. Löse sie unter Merge-Änderungen und setze dann fort.",
+ "smart_commit_title": "Es gibt keine bereitgestellten Änderungen zum Committen.\n\nAlle Änderungen bereitstellen und direkt committen?",
+ "sort_name": "Nach Name sortieren",
+ "sort_path": "Nach Pfad sortieren",
+ "sort_status": "Nach Status sortieren",
+ "stage_all": "Alle Änderungen bereitstellen",
+ "stage_all_merge": "Alle Merge-Änderungen bereitstellen",
+ "stage_changes": "Änderungen bereitstellen",
+ "stash": "Stash",
+ "stash_message_placeholder": "Nachricht (optional)",
+ "stash_message_prompt": "Optional eine Nachricht für den Stash angeben",
+ "stash_staged": "Bereitgestellte stashen",
+ "stash_untracked": "Stash (inklusive nicht verfolgter)",
+ "sync": "Synchronisieren",
+ "sync_changes": "Änderungen synchronisieren",
+ "sync_confirm": "Damit werden Commits von und nach „{upstream}“ gepullt und gepusht.",
+ "sync_tip": "Änderungen synchronisieren: {behind}↓ {ahead}↑ mit {upstream}",
+ "synced_tip": "Synchron mit {upstream}",
+ "tag_message_placeholder": "Nachricht (optional)",
+ "tag_message_prompt": "Optional eine Nachricht für das Tag angeben",
+ "tag_name_prompt": "Bitte einen Namen für das Tag angeben",
+ "truncated": "Es wurden mehr Dateien geändert, als die Liste zeigt.",
+ "undo_last_commit": "Letzten Commit rückgängig machen",
+ "unstage_all": "Bereitstellung aller Änderungen aufheben",
+ "unstage_changes": "Bereitstellung aufheben",
+ "untracked_to_trash": "Nicht verfolgte Dateien kommen in den Papierkorb.",
+ "view_list": "Als Liste anzeigen",
+ "view_tree": "Als Baum anzeigen",
+ "view_sort": "Ansicht & Sortierung",
+ "working_tree": "Arbeitsverzeichnis",
+ "yes": "Ja"
+ }
},
"skills": {
"subtitle": "Auf ein Terminal ziehen, um ihn einzufügen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 968b2aba94..720bbcd9dc 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -8022,7 +8022,222 @@
},
"connect_repo_body": "Pick this folder's GitHub repository to see pull requests and CI here.",
"connect_repo_other": "Another…",
- "connect_repo_choose": "Choose a repository…"
+ "connect_repo_choose": "Choose a repository…",
+ "scm": {
+ "title": "Source Control",
+ "view_changes": "Changes",
+ "view_graph": "Graph",
+ "view_branches": "Branches & Pull Requests",
+ "group": {
+ "merge": "Merge Changes",
+ "staged": "Staged Changes",
+ "changes": "Changes"
+ },
+ "state": {
+ "index_modified": "Index Modified",
+ "index_type_changed": "Index Type Changed",
+ "index_added": "Index Added",
+ "index_deleted": "Index Deleted",
+ "index_renamed": "Index Renamed",
+ "index_copied": "Index Copied",
+ "modified": "Modified",
+ "type_changed": "Type Changed",
+ "deleted": "Deleted",
+ "intent_to_add": "Intent to Add",
+ "intent_to_rename": "Intent to Rename",
+ "untracked": "Untracked",
+ "both_deleted": "Conflict: Both Deleted",
+ "added_by_us": "Conflict: Added by Us",
+ "deleted_by_them": "Conflict: Deleted by Them",
+ "added_by_them": "Conflict: Added by Them",
+ "deleted_by_us": "Conflict: Deleted by Us",
+ "both_added": "Conflict: Both Added",
+ "both_modified": "Conflict: Both Modified"
+ },
+ "operation": {
+ "merge": "Merging: resolve the conflicts, stage them, then commit.",
+ "rebase": "Rebasing: resolve the conflicts, stage them, then continue.",
+ "cherry-pick": "Cherry-picking: resolve the conflicts, stage them, then continue.",
+ "revert": "Reverting: resolve the conflicts, stage them, then continue."
+ },
+ "scope": {
+ "auto": "Auto",
+ "current": "Current Branch",
+ "all": "All Branches"
+ },
+ "ref_group": {
+ "head": "Branches",
+ "remote": "Remote Branches",
+ "tag": "Tags"
+ },
+ "abort": "Abort",
+ "abort_rebase": "Abort Rebase",
+ "add_remote": "Add Remote…",
+ "add_to_gitignore": "Add to .gitignore",
+ "always": "Always",
+ "apply_latest_stash": "Apply Latest Stash",
+ "apply_stash": "Apply Stash…",
+ "binary": "This file is binary or too large to compare.",
+ "branch_name_invalid": "A branch name cannot contain spaces, '..', '~', '^', ':', '?', '*', '[' or '\\'.",
+ "branch_name_placeholder": "Branch name",
+ "branch_name_prompt": "Please provide a new branch name",
+ "cannot_undo": "This cannot be undone.",
+ "changes_aria": "Changed files",
+ "checkout_detached": "Checkout detached…",
+ "checkout_detached_here": "Checkout (Detached)",
+ "checkout_tip": "Checkout Branch/Tag…",
+ "checkout_to": "Checkout to…",
+ "cherry_pick": "Cherry Pick",
+ "cherry_pick_conflicts": "The cherry-pick has conflicts. Resolve them under Merge Changes.",
+ "close": "Close",
+ "commit": "Commit",
+ "commit_all": "Commit All",
+ "commit_all_amend": "Commit All (Amend)",
+ "commit_all_signed_off": "Commit All (Signed Off)",
+ "commit_amend": "Commit (Amend)",
+ "commit_no_verify": "Commit (No Verify)",
+ "commit_options": "More commit actions",
+ "commit_push": "Commit & Push",
+ "commit_signed_off": "Commit (Signed Off)",
+ "commit_staged": "Commit Staged",
+ "commit_staged_amend": "Commit Staged (Amend)",
+ "commit_staged_signed_off": "Commit Staged (Signed Off)",
+ "commit_sync": "Commit & Sync",
+ "commit_tip": "Commit Changes on \"{branch}\"",
+ "continue": "Continue",
+ "copy_commit_id": "Copy Commit ID",
+ "copy_commit_message": "Copy Commit Message",
+ "copy_failed": "Could not copy to the clipboard.",
+ "copy_path": "Copy Path",
+ "copy_relative_path": "Copy Relative Path",
+ "create_branch": "Create new branch…",
+ "create_branch_from": "Create new branch from…",
+ "create_branch_here": "Create Branch…",
+ "create_tag": "Create Tag",
+ "create_tag_here": "Create Tag…",
+ "delete_branch": "Delete Branch…",
+ "delete_branch_button": "Delete Branch",
+ "delete_file": "Move to Trash",
+ "delete_tag": "Delete Tag",
+ "delete_unmerged": "The branch \"{name}\" has commits that are on no other branch. Delete it anyway?",
+ "delete_untracked_one": "Delete \"{name}\"?",
+ "diff_working_tree": "Staged ↔ Working Tree",
+ "discard_all": "Discard All Changes",
+ "discard_all_body": "{n} of them are untracked and go to the trash. The rest cannot be undone.",
+ "discard_all_files": "Discard All {n} Files",
+ "discard_all_title": "Discard all changes in {n} files?",
+ "discard_changes": "Discard Changes",
+ "discard_file": "Discard File",
+ "discard_many": "Discard changes in {n} files?",
+ "discard_n_files": "Discard {n} Files",
+ "discard_one": "Discard changes in \"{name}\"?",
+ "discard_tracked_files": "Discard {n} Tracked Files",
+ "drop": "Drop",
+ "drop_all": "Drop All",
+ "drop_all_confirm": "Drop all {n} stashes? This cannot be undone.",
+ "drop_all_stashes": "Drop All Stashes…",
+ "drop_stash": "Drop Stash…",
+ "drop_stash_confirm": "Drop {ref}? This cannot be undone.",
+ "fetch": "Fetch",
+ "fetch_all": "Fetch From All Remotes",
+ "fetch_prune": "Fetch (Prune)",
+ "go_to_current": "Go to Current Commit",
+ "incoming": "Incoming: not pulled yet",
+ "index": "Index",
+ "init_repository": "Initialize Repository",
+ "load_more": "Load more",
+ "mark_resolved": "Stage (Mark Resolved)",
+ "menu_branch": "Branch",
+ "menu_changes": "Changes",
+ "menu_commit": "Commit",
+ "menu_pull_push": "Pull, Push",
+ "menu_remote": "Remote",
+ "menu_stash": "Stash",
+ "menu_tags": "Tags",
+ "merge_branch": "Merge…",
+ "merge_conflicts": "The merge has conflicts. Resolve them under Merge Changes.",
+ "message_label": "Commit message",
+ "message_placeholder": "Message ({key}+Enter to commit on \"{branch}\")",
+ "message_required": "Type a commit message first.",
+ "more_actions": "More Actions…",
+ "no_commits": "No commits yet.",
+ "no_remotes": "This repository has no remotes.",
+ "no_repository": "The folder of this workspace is not a git repository yet.",
+ "no_stashes": "There are no stashes.",
+ "nothing_to_commit": "There are no changes to commit.",
+ "ok": "OK",
+ "ok_dont_ask": "OK, Don't Ask Again",
+ "open_changes": "Open Changes",
+ "open_file": "Open File",
+ "outgoing": "Outgoing: not pushed yet",
+ "outside_workspace": "This file is outside the workspace folder.",
+ "pick_branch_from": "Select a ref to create the branch from",
+ "pick_branch_pull": "Pick a branch to pull from",
+ "pick_checkout": "Select a branch or tag to checkout",
+ "pick_delete_branch": "Select a branch to delete",
+ "pick_detached": "Select a ref to checkout in detached mode",
+ "pick_merge": "Select a branch or tag to merge from",
+ "pick_rebase": "Select a branch to rebase onto",
+ "pick_remote_publish": "Pick a remote to publish the branch to",
+ "pick_remote_pull": "Pick a remote to pull from",
+ "pick_remote_push": "Pick a remote to push to",
+ "pick_remote_remove": "Pick a remote to remove",
+ "pick_stash_apply": "Pick a stash to apply",
+ "pick_stash_drop": "Pick a stash to drop",
+ "pick_stash_pop": "Pick a stash to pop",
+ "pick_tag_delete": "Select a tag to delete",
+ "pop_latest_stash": "Pop Latest Stash",
+ "pop_stash": "Pop Stash…",
+ "publish_branch": "Publish Branch",
+ "pull": "Pull",
+ "pull_from": "Pull from…",
+ "pull_rebase": "Pull (Rebase)",
+ "push": "Push",
+ "push_tags": "Push Tags",
+ "push_to": "Push to…",
+ "rebase_branch": "Rebase Branch…",
+ "rebase_conflicts": "The rebase has conflicts. Resolve them under Merge Changes, then continue.",
+ "refresh": "Refresh",
+ "remote_name_invalid": "Use letters, digits, dots, underscores or dashes.",
+ "remote_name_prompt": "Please provide a remote name",
+ "remote_url_prompt": "Please provide the remote URL",
+ "remove_remote": "Remove Remote",
+ "rename_branch": "Rename Branch…",
+ "rename_prompt": "Please provide a new name for the branch",
+ "reveal_in_explorer": "Reveal in Folder Tab",
+ "revert_commit": "Revert Commit",
+ "revert_conflicts": "The revert has conflicts. Resolve them under Merge Changes, then continue.",
+ "smart_commit_title": "There are no staged changes to commit.\n\nWould you like to stage all your changes and commit them directly?",
+ "sort_name": "Sort by Name",
+ "sort_path": "Sort by Path",
+ "sort_status": "Sort by Status",
+ "stage_all": "Stage All Changes",
+ "stage_all_merge": "Stage All Merge Changes",
+ "stage_changes": "Stage Changes",
+ "stash": "Stash",
+ "stash_message_placeholder": "Message (optional)",
+ "stash_message_prompt": "Optionally provide a stash message",
+ "stash_staged": "Stash Staged",
+ "stash_untracked": "Stash (Include Untracked)",
+ "sync": "Sync",
+ "sync_changes": "Sync Changes",
+ "sync_confirm": "This will pull and push commits from and to \"{upstream}\".",
+ "sync_tip": "Synchronize Changes: {behind}↓ {ahead}↑ with {upstream}",
+ "synced_tip": "In sync with {upstream}",
+ "tag_message_placeholder": "Message (optional)",
+ "tag_message_prompt": "Optionally provide a message to annotate the tag",
+ "tag_name_prompt": "Please provide a tag name",
+ "truncated": "More files changed than the list shows.",
+ "undo_last_commit": "Undo Last Commit",
+ "unstage_all": "Unstage All Changes",
+ "unstage_changes": "Unstage Changes",
+ "untracked_to_trash": "Untracked files are moved to the trash.",
+ "view_list": "View as List",
+ "view_tree": "View as Tree",
+ "view_sort": "View & Sort",
+ "working_tree": "Working Tree",
+ "yes": "Yes"
+ }
},
"skills": {
"subtitle": "Drag one onto a terminal to paste it",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 19b8d7f6e2..d65770d865 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -8022,7 +8022,222 @@
},
"connect_repo_body": "Elige el repositorio de GitHub de esta carpeta para ver aquí las pull requests y la CI.",
"connect_repo_other": "Otro…",
- "connect_repo_choose": "Elegir un repositorio…"
+ "connect_repo_choose": "Elegir un repositorio…",
+ "scm": {
+ "title": "Control de código fuente",
+ "view_changes": "Cambios",
+ "view_graph": "Gráfico",
+ "view_branches": "Ramas y pull requests",
+ "group": {
+ "merge": "Cambios de fusión",
+ "staged": "Cambios preparados",
+ "changes": "Cambios"
+ },
+ "state": {
+ "index_modified": "Índice modificado",
+ "index_type_changed": "Índice: tipo cambiado",
+ "index_added": "Índice agregado",
+ "index_deleted": "Índice eliminado",
+ "index_renamed": "Índice renombrado",
+ "index_copied": "Índice copiado",
+ "modified": "Modificado",
+ "type_changed": "Tipo cambiado",
+ "deleted": "Eliminado",
+ "intent_to_add": "Pendiente de agregar",
+ "intent_to_rename": "Pendiente de renombrar",
+ "untracked": "Sin seguimiento",
+ "both_deleted": "Conflicto: eliminado por ambos",
+ "added_by_us": "Conflicto: agregado por nosotros",
+ "deleted_by_them": "Conflicto: eliminado por ellos",
+ "added_by_them": "Conflicto: agregado por ellos",
+ "deleted_by_us": "Conflicto: eliminado por nosotros",
+ "both_added": "Conflicto: agregado por ambos",
+ "both_modified": "Conflicto: modificado por ambos"
+ },
+ "operation": {
+ "merge": "Fusión en curso: resuelve los conflictos, prepáralos y confirma.",
+ "rebase": "Rebase en curso: resuelve los conflictos, prepáralos y continúa.",
+ "cherry-pick": "Cherry-pick en curso: resuelve los conflictos, prepáralos y continúa.",
+ "revert": "Reversión en curso: resuelve los conflictos, prepáralos y continúa."
+ },
+ "scope": {
+ "auto": "Automático",
+ "current": "Rama actual",
+ "all": "Todas las ramas"
+ },
+ "ref_group": {
+ "head": "Ramas",
+ "remote": "Ramas remotas",
+ "tag": "Etiquetas"
+ },
+ "abort": "Cancelar",
+ "abort_rebase": "Cancelar rebase",
+ "add_remote": "Agregar remoto…",
+ "add_to_gitignore": "Agregar a .gitignore",
+ "always": "Siempre",
+ "apply_latest_stash": "Aplicar el último stash",
+ "apply_stash": "Aplicar stash…",
+ "binary": "Este archivo es binario o demasiado grande para compararlo.",
+ "branch_name_invalid": "Un nombre de rama no puede contener espacios, '..', '~', '^', ':', '?', '*', '[' ni '\\'.",
+ "branch_name_placeholder": "Nombre de la rama",
+ "branch_name_prompt": "Indica el nombre de la nueva rama",
+ "cannot_undo": "Esto no se puede deshacer.",
+ "changes_aria": "Archivos cambiados",
+ "checkout_detached": "Extraer en modo separado…",
+ "checkout_detached_here": "Extraer (separado)",
+ "checkout_tip": "Extraer rama/etiqueta…",
+ "checkout_to": "Extraer en…",
+ "cherry_pick": "Cherry-pick",
+ "cherry_pick_conflicts": "El cherry-pick tiene conflictos. Resuélvelos en Cambios de fusión.",
+ "close": "Cerrar",
+ "commit": "Confirmar",
+ "commit_all": "Confirmar todo",
+ "commit_all_amend": "Confirmar todo (enmendar)",
+ "commit_all_signed_off": "Confirmar todo (firmado)",
+ "commit_amend": "Confirmar (enmendar)",
+ "commit_no_verify": "Confirmar (sin verificar)",
+ "commit_options": "Más acciones de confirmación",
+ "commit_push": "Confirmar e insertar",
+ "commit_signed_off": "Confirmar (firmado)",
+ "commit_staged": "Confirmar preparados",
+ "commit_staged_amend": "Confirmar preparados (enmendar)",
+ "commit_staged_signed_off": "Confirmar preparados (firmado)",
+ "commit_sync": "Confirmar y sincronizar",
+ "commit_tip": "Confirmar cambios en \"{branch}\"",
+ "continue": "Continuar",
+ "copy_commit_id": "Copiar ID del commit",
+ "copy_commit_message": "Copiar mensaje del commit",
+ "copy_failed": "No se pudo copiar al portapapeles.",
+ "copy_path": "Copiar ruta",
+ "copy_relative_path": "Copiar ruta relativa",
+ "create_branch": "Crear rama nueva…",
+ "create_branch_from": "Crear rama nueva desde…",
+ "create_branch_here": "Crear rama…",
+ "create_tag": "Crear etiqueta",
+ "create_tag_here": "Crear etiqueta…",
+ "delete_branch": "Eliminar rama…",
+ "delete_branch_button": "Eliminar rama",
+ "delete_file": "Mover a la papelera",
+ "delete_tag": "Eliminar etiqueta",
+ "delete_unmerged": "La rama \"{name}\" tiene commits que no están en ninguna otra rama. ¿Eliminarla igualmente?",
+ "delete_untracked_one": "¿Eliminar \"{name}\"?",
+ "diff_working_tree": "Preparado ↔ Árbol de trabajo",
+ "discard_all": "Descartar todos los cambios",
+ "discard_all_body": "{n} de ellos no tienen seguimiento y van a la papelera. El resto no se puede deshacer.",
+ "discard_all_files": "Descartar los {n} archivos",
+ "discard_all_title": "¿Descartar todos los cambios en {n} archivos?",
+ "discard_changes": "Descartar cambios",
+ "discard_file": "Descartar archivo",
+ "discard_many": "¿Descartar los cambios en {n} archivos?",
+ "discard_n_files": "Descartar {n} archivos",
+ "discard_one": "¿Descartar los cambios en \"{name}\"?",
+ "discard_tracked_files": "Descartar {n} archivos con seguimiento",
+ "drop": "Eliminar",
+ "drop_all": "Eliminar todos",
+ "drop_all_confirm": "¿Eliminar los {n} stashes? Esto no se puede deshacer.",
+ "drop_all_stashes": "Eliminar todos los stashes…",
+ "drop_stash": "Eliminar stash…",
+ "drop_stash_confirm": "¿Eliminar {ref}? Esto no se puede deshacer.",
+ "fetch": "Recuperar",
+ "fetch_all": "Recuperar de todos los remotos",
+ "fetch_prune": "Recuperar (limpiar)",
+ "go_to_current": "Ir al commit actual",
+ "incoming": "Entrante: aún sin traer",
+ "index": "Índice",
+ "init_repository": "Inicializar repositorio",
+ "load_more": "Cargar más",
+ "mark_resolved": "Preparar (marcar como resuelto)",
+ "menu_branch": "Rama",
+ "menu_changes": "Cambios",
+ "menu_commit": "Confirmar",
+ "menu_pull_push": "Pull, Push",
+ "menu_remote": "Remoto",
+ "menu_stash": "Stash",
+ "menu_tags": "Etiquetas",
+ "merge_branch": "Fusionar…",
+ "merge_conflicts": "La fusión tiene conflictos. Resuélvelos en Cambios de fusión.",
+ "message_label": "Mensaje del commit",
+ "message_placeholder": "Mensaje ({key}+Intro para confirmar en \"{branch}\")",
+ "message_required": "Escribe primero un mensaje de commit.",
+ "more_actions": "Más acciones…",
+ "no_commits": "Todavía no hay commits.",
+ "no_remotes": "Este repositorio no tiene remotos.",
+ "no_repository": "La carpeta de este espacio de trabajo todavía no es un repositorio git.",
+ "no_stashes": "No hay stashes.",
+ "nothing_to_commit": "No hay cambios que confirmar.",
+ "ok": "Aceptar",
+ "ok_dont_ask": "Aceptar y no volver a preguntar",
+ "open_changes": "Abrir cambios",
+ "open_file": "Abrir archivo",
+ "outgoing": "Saliente: aún sin enviar",
+ "outside_workspace": "Este archivo está fuera de la carpeta del espacio de trabajo.",
+ "pick_branch_from": "Selecciona una referencia desde la que crear la rama",
+ "pick_branch_pull": "Elige una rama de la que traer",
+ "pick_checkout": "Selecciona una rama o etiqueta para extraer",
+ "pick_delete_branch": "Selecciona una rama para eliminar",
+ "pick_detached": "Selecciona una referencia para extraer en modo separado",
+ "pick_merge": "Selecciona una rama o etiqueta para fusionar",
+ "pick_rebase": "Selecciona una rama sobre la que hacer rebase",
+ "pick_remote_publish": "Elige un remoto en el que publicar la rama",
+ "pick_remote_pull": "Elige un remoto del que traer",
+ "pick_remote_push": "Elige un remoto al que enviar",
+ "pick_remote_remove": "Elige un remoto para quitar",
+ "pick_stash_apply": "Elige un stash para aplicar",
+ "pick_stash_drop": "Elige un stash para eliminar",
+ "pick_stash_pop": "Elige un stash para aplicar y quitar",
+ "pick_tag_delete": "Selecciona una etiqueta para eliminar",
+ "pop_latest_stash": "Aplicar y quitar el último stash",
+ "pop_stash": "Aplicar y quitar stash…",
+ "publish_branch": "Publicar rama",
+ "pull": "Pull",
+ "pull_from": "Pull desde…",
+ "pull_rebase": "Pull (rebase)",
+ "push": "Push",
+ "push_tags": "Enviar etiquetas",
+ "push_to": "Push a…",
+ "rebase_branch": "Hacer rebase de la rama…",
+ "rebase_conflicts": "El rebase tiene conflictos. Resuélvelos en Cambios de fusión y continúa.",
+ "refresh": "Actualizar",
+ "remote_name_invalid": "Usa letras, dígitos, puntos, guiones bajos o guiones.",
+ "remote_name_prompt": "Indica un nombre para el remoto",
+ "remote_url_prompt": "Indica la URL del remoto",
+ "remove_remote": "Quitar remoto",
+ "rename_branch": "Renombrar rama…",
+ "rename_prompt": "Indica un nombre nuevo para la rama",
+ "reveal_in_explorer": "Mostrar en la pestaña Carpeta",
+ "revert_commit": "Revertir commit",
+ "revert_conflicts": "La reversión tiene conflictos. Resuélvelos en Cambios de fusión y continúa.",
+ "smart_commit_title": "No hay cambios preparados que confirmar.\n\n¿Quieres preparar todos tus cambios y confirmarlos directamente?",
+ "sort_name": "Ordenar por nombre",
+ "sort_path": "Ordenar por ruta",
+ "sort_status": "Ordenar por estado",
+ "stage_all": "Preparar todos los cambios",
+ "stage_all_merge": "Preparar todos los cambios de fusión",
+ "stage_changes": "Preparar cambios",
+ "stash": "Stash",
+ "stash_message_placeholder": "Mensaje (opcional)",
+ "stash_message_prompt": "Opcionalmente, indica un mensaje para el stash",
+ "stash_staged": "Stash de preparados",
+ "stash_untracked": "Stash (incluir sin seguimiento)",
+ "sync": "Sincronizar",
+ "sync_changes": "Sincronizar cambios",
+ "sync_confirm": "Se traerán y enviarán commits desde y hacia \"{upstream}\".",
+ "sync_tip": "Sincronizar cambios: {behind}↓ {ahead}↑ con {upstream}",
+ "synced_tip": "Sincronizado con {upstream}",
+ "tag_message_placeholder": "Mensaje (opcional)",
+ "tag_message_prompt": "Opcionalmente, indica un mensaje para anotar la etiqueta",
+ "tag_name_prompt": "Indica un nombre para la etiqueta",
+ "truncated": "Cambiaron más archivos de los que muestra la lista.",
+ "undo_last_commit": "Deshacer el último commit",
+ "unstage_all": "Quitar todos los cambios preparados",
+ "unstage_changes": "Quitar de preparados",
+ "untracked_to_trash": "Los archivos sin seguimiento se mueven a la papelera.",
+ "view_list": "Ver como lista",
+ "view_tree": "Ver como árbol",
+ "view_sort": "Vista y orden",
+ "working_tree": "Árbol de trabajo",
+ "yes": "Sí"
+ }
},
"skills": {
"subtitle": "Arrástralo a un terminal para pegarlo",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
index 5fee80dc07..3f888a688b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
@@ -8022,7 +8022,222 @@
},
"connect_repo_body": "Escolha o repositório GitHub desta pasta para ver aqui os pull requests e a CI.",
"connect_repo_other": "Outro…",
- "connect_repo_choose": "Escolher um repositório…"
+ "connect_repo_choose": "Escolher um repositório…",
+ "scm": {
+ "title": "Controle do código-fonte",
+ "view_changes": "Alterações",
+ "view_graph": "Gráfico",
+ "view_branches": "Branches e pull requests",
+ "group": {
+ "merge": "Alterações de mesclagem",
+ "staged": "Alterações preparadas",
+ "changes": "Alterações"
+ },
+ "state": {
+ "index_modified": "Índice modificado",
+ "index_type_changed": "Índice: tipo alterado",
+ "index_added": "Índice adicionado",
+ "index_deleted": "Índice excluído",
+ "index_renamed": "Índice renomeado",
+ "index_copied": "Índice copiado",
+ "modified": "Modificado",
+ "type_changed": "Tipo alterado",
+ "deleted": "Excluído",
+ "intent_to_add": "Marcado para adicionar",
+ "intent_to_rename": "Marcado para renomear",
+ "untracked": "Não rastreado",
+ "both_deleted": "Conflito: excluído por ambos",
+ "added_by_us": "Conflito: adicionado por nós",
+ "deleted_by_them": "Conflito: excluído por eles",
+ "added_by_them": "Conflito: adicionado por eles",
+ "deleted_by_us": "Conflito: excluído por nós",
+ "both_added": "Conflito: adicionado por ambos",
+ "both_modified": "Conflito: modificado por ambos"
+ },
+ "operation": {
+ "merge": "Mesclagem em andamento: resolva os conflitos, prepare-os e faça o commit.",
+ "rebase": "Rebase em andamento: resolva os conflitos, prepare-os e continue.",
+ "cherry-pick": "Cherry-pick em andamento: resolva os conflitos, prepare-os e continue.",
+ "revert": "Reversão em andamento: resolva os conflitos, prepare-os e continue."
+ },
+ "scope": {
+ "auto": "Automático",
+ "current": "Branch atual",
+ "all": "Todos os branches"
+ },
+ "ref_group": {
+ "head": "Branches",
+ "remote": "Branches remotos",
+ "tag": "Tags"
+ },
+ "abort": "Anular",
+ "abort_rebase": "Anular rebase",
+ "add_remote": "Adicionar remoto…",
+ "add_to_gitignore": "Adicionar ao .gitignore",
+ "always": "Sempre",
+ "apply_latest_stash": "Aplicar o stash mais recente",
+ "apply_stash": "Aplicar stash…",
+ "binary": "Este arquivo é binário ou grande demais para comparar.",
+ "branch_name_invalid": "Um nome de branch não pode conter espaços, '..', '~', '^', ':', '?', '*', '[' ou '\\'.",
+ "branch_name_placeholder": "Nome do branch",
+ "branch_name_prompt": "Informe o nome do novo branch",
+ "cannot_undo": "Isso não pode ser desfeito.",
+ "changes_aria": "Arquivos alterados",
+ "checkout_detached": "Fazer checkout desanexado…",
+ "checkout_detached_here": "Checkout (desanexado)",
+ "checkout_tip": "Fazer checkout de branch/tag…",
+ "checkout_to": "Fazer checkout para…",
+ "cherry_pick": "Cherry-pick",
+ "cherry_pick_conflicts": "O cherry-pick tem conflitos. Resolva-os em Alterações de mesclagem.",
+ "close": "Fechar",
+ "commit": "Commit",
+ "commit_all": "Commit de tudo",
+ "commit_all_amend": "Commit de tudo (corrigir)",
+ "commit_all_signed_off": "Commit de tudo (assinado)",
+ "commit_amend": "Commit (corrigir)",
+ "commit_no_verify": "Commit (sem verificação)",
+ "commit_options": "Mais ações de commit",
+ "commit_push": "Commit e push",
+ "commit_signed_off": "Commit (assinado)",
+ "commit_staged": "Commit dos preparados",
+ "commit_staged_amend": "Commit dos preparados (corrigir)",
+ "commit_staged_signed_off": "Commit dos preparados (assinado)",
+ "commit_sync": "Commit e sincronizar",
+ "commit_tip": "Fazer commit das alterações em \"{branch}\"",
+ "continue": "Continuar",
+ "copy_commit_id": "Copiar ID do commit",
+ "copy_commit_message": "Copiar mensagem do commit",
+ "copy_failed": "Não foi possível copiar para a área de transferência.",
+ "copy_path": "Copiar caminho",
+ "copy_relative_path": "Copiar caminho relativo",
+ "create_branch": "Criar novo branch…",
+ "create_branch_from": "Criar novo branch a partir de…",
+ "create_branch_here": "Criar branch…",
+ "create_tag": "Criar tag",
+ "create_tag_here": "Criar tag…",
+ "delete_branch": "Excluir branch…",
+ "delete_branch_button": "Excluir branch",
+ "delete_file": "Mover para a lixeira",
+ "delete_tag": "Excluir tag",
+ "delete_unmerged": "O branch \"{name}\" tem commits que não estão em nenhum outro branch. Excluir mesmo assim?",
+ "delete_untracked_one": "Excluir \"{name}\"?",
+ "diff_working_tree": "Preparado ↔ Árvore de trabalho",
+ "discard_all": "Descartar todas as alterações",
+ "discard_all_body": "{n} deles não são rastreados e vão para a lixeira. O resto não pode ser desfeito.",
+ "discard_all_files": "Descartar todos os {n} arquivos",
+ "discard_all_title": "Descartar todas as alterações em {n} arquivos?",
+ "discard_changes": "Descartar alterações",
+ "discard_file": "Descartar arquivo",
+ "discard_many": "Descartar as alterações em {n} arquivos?",
+ "discard_n_files": "Descartar {n} arquivos",
+ "discard_one": "Descartar as alterações em \"{name}\"?",
+ "discard_tracked_files": "Descartar {n} arquivos rastreados",
+ "drop": "Descartar",
+ "drop_all": "Descartar todos",
+ "drop_all_confirm": "Descartar todos os {n} stashes? Isso não pode ser desfeito.",
+ "drop_all_stashes": "Descartar todos os stashes…",
+ "drop_stash": "Descartar stash…",
+ "drop_stash_confirm": "Descartar {ref}? Isso não pode ser desfeito.",
+ "fetch": "Buscar",
+ "fetch_all": "Buscar de todos os remotos",
+ "fetch_prune": "Buscar (limpar)",
+ "go_to_current": "Ir para o commit atual",
+ "incoming": "Entrada: ainda não puxado",
+ "index": "Índice",
+ "init_repository": "Inicializar repositório",
+ "load_more": "Carregar mais",
+ "mark_resolved": "Preparar (marcar como resolvido)",
+ "menu_branch": "Branch",
+ "menu_changes": "Alterações",
+ "menu_commit": "Commit",
+ "menu_pull_push": "Pull, Push",
+ "menu_remote": "Remoto",
+ "menu_stash": "Stash",
+ "menu_tags": "Tags",
+ "merge_branch": "Mesclar…",
+ "merge_conflicts": "A mesclagem tem conflitos. Resolva-os em Alterações de mesclagem.",
+ "message_label": "Mensagem do commit",
+ "message_placeholder": "Mensagem ({key}+Enter para fazer commit em \"{branch}\")",
+ "message_required": "Digite primeiro uma mensagem de commit.",
+ "more_actions": "Mais ações…",
+ "no_commits": "Ainda não há commits.",
+ "no_remotes": "Este repositório não tem remotos.",
+ "no_repository": "A pasta deste espaço de trabalho ainda não é um repositório git.",
+ "no_stashes": "Não há stashes.",
+ "nothing_to_commit": "Não há alterações para fazer commit.",
+ "ok": "OK",
+ "ok_dont_ask": "OK, não perguntar de novo",
+ "open_changes": "Abrir alterações",
+ "open_file": "Abrir arquivo",
+ "outgoing": "Saída: ainda não enviado",
+ "outside_workspace": "Este arquivo está fora da pasta do espaço de trabalho.",
+ "pick_branch_from": "Selecione uma referência para criar o branch",
+ "pick_branch_pull": "Escolha um branch para puxar",
+ "pick_checkout": "Selecione um branch ou tag para fazer checkout",
+ "pick_delete_branch": "Selecione um branch para excluir",
+ "pick_detached": "Selecione uma referência para checkout desanexado",
+ "pick_merge": "Selecione um branch ou tag para mesclar",
+ "pick_rebase": "Selecione um branch para o rebase",
+ "pick_remote_publish": "Escolha um remoto para publicar o branch",
+ "pick_remote_pull": "Escolha um remoto para puxar",
+ "pick_remote_push": "Escolha um remoto para enviar",
+ "pick_remote_remove": "Escolha um remoto para remover",
+ "pick_stash_apply": "Escolha um stash para aplicar",
+ "pick_stash_drop": "Escolha um stash para descartar",
+ "pick_stash_pop": "Escolha um stash para aplicar e remover",
+ "pick_tag_delete": "Selecione uma tag para excluir",
+ "pop_latest_stash": "Aplicar e remover o stash mais recente",
+ "pop_stash": "Aplicar e remover stash…",
+ "publish_branch": "Publicar branch",
+ "pull": "Pull",
+ "pull_from": "Pull de…",
+ "pull_rebase": "Pull (rebase)",
+ "push": "Push",
+ "push_tags": "Enviar tags",
+ "push_to": "Push para…",
+ "rebase_branch": "Fazer rebase do branch…",
+ "rebase_conflicts": "O rebase tem conflitos. Resolva-os em Alterações de mesclagem e continue.",
+ "refresh": "Atualizar",
+ "remote_name_invalid": "Use letras, dígitos, pontos, sublinhados ou hífens.",
+ "remote_name_prompt": "Informe um nome para o remoto",
+ "remote_url_prompt": "Informe a URL do remoto",
+ "remove_remote": "Remover remoto",
+ "rename_branch": "Renomear branch…",
+ "rename_prompt": "Informe um novo nome para o branch",
+ "reveal_in_explorer": "Mostrar na aba Pasta",
+ "revert_commit": "Reverter commit",
+ "revert_conflicts": "A reversão tem conflitos. Resolva-os em Alterações de mesclagem e continue.",
+ "smart_commit_title": "Não há alterações preparadas para fazer commit.\n\nDeseja preparar todas as alterações e fazer o commit diretamente?",
+ "sort_name": "Ordenar por nome",
+ "sort_path": "Ordenar por caminho",
+ "sort_status": "Ordenar por status",
+ "stage_all": "Preparar todas as alterações",
+ "stage_all_merge": "Preparar todas as alterações de mesclagem",
+ "stage_changes": "Preparar alterações",
+ "stash": "Stash",
+ "stash_message_placeholder": "Mensagem (opcional)",
+ "stash_message_prompt": "Opcionalmente, informe uma mensagem para o stash",
+ "stash_staged": "Stash dos preparados",
+ "stash_untracked": "Stash (incluir não rastreados)",
+ "sync": "Sincronizar",
+ "sync_changes": "Sincronizar alterações",
+ "sync_confirm": "Isso vai puxar e enviar commits de e para \"{upstream}\".",
+ "sync_tip": "Sincronizar alterações: {behind}↓ {ahead}↑ com {upstream}",
+ "synced_tip": "Sincronizado com {upstream}",
+ "tag_message_placeholder": "Mensagem (opcional)",
+ "tag_message_prompt": "Opcionalmente, informe uma mensagem para anotar a tag",
+ "tag_name_prompt": "Informe um nome para a tag",
+ "truncated": "Mais arquivos foram alterados do que a lista mostra.",
+ "undo_last_commit": "Desfazer o último commit",
+ "unstage_all": "Remover todas as alterações preparadas",
+ "unstage_changes": "Remover da preparação",
+ "untracked_to_trash": "Arquivos não rastreados vão para a lixeira.",
+ "view_list": "Ver como lista",
+ "view_tree": "Ver como árvore",
+ "view_sort": "Exibição e ordem",
+ "working_tree": "Árvore de trabalho",
+ "yes": "Sim"
+ }
},
"skills": {
"subtitle": "Arrasta uma para um terminal para a colar",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
index bb90a8718a..d31a9d6a5a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -8022,7 +8022,222 @@
},
"connect_repo_body": "为此文件夹选择 GitHub 仓库,即可在这里查看拉取请求和 CI。",
"connect_repo_other": "其他…",
- "connect_repo_choose": "选择仓库…"
+ "connect_repo_choose": "选择仓库…",
+ "scm": {
+ "title": "源代码管理",
+ "view_changes": "更改",
+ "view_graph": "图形",
+ "view_branches": "分支和拉取请求",
+ "group": {
+ "merge": "合并更改",
+ "staged": "暂存的更改",
+ "changes": "更改"
+ },
+ "state": {
+ "index_modified": "索引已修改",
+ "index_type_changed": "索引类型已更改",
+ "index_added": "索引已添加",
+ "index_deleted": "索引已删除",
+ "index_renamed": "索引已重命名",
+ "index_copied": "索引已复制",
+ "modified": "已修改",
+ "type_changed": "类型已更改",
+ "deleted": "已删除",
+ "intent_to_add": "计划添加",
+ "intent_to_rename": "计划重命名",
+ "untracked": "未跟踪",
+ "both_deleted": "冲突:双方都已删除",
+ "added_by_us": "冲突:我方添加",
+ "deleted_by_them": "冲突:对方删除",
+ "added_by_them": "冲突:对方添加",
+ "deleted_by_us": "冲突:我方删除",
+ "both_added": "冲突:双方都已添加",
+ "both_modified": "冲突:双方都已修改"
+ },
+ "operation": {
+ "merge": "正在合并:解决冲突并暂存,然后提交。",
+ "rebase": "正在变基:解决冲突并暂存,然后继续。",
+ "cherry-pick": "正在拣选:解决冲突并暂存,然后继续。",
+ "revert": "正在还原:解决冲突并暂存,然后继续。"
+ },
+ "scope": {
+ "auto": "自动",
+ "current": "当前分支",
+ "all": "所有分支"
+ },
+ "ref_group": {
+ "head": "分支",
+ "remote": "远程分支",
+ "tag": "标签"
+ },
+ "abort": "中止",
+ "abort_rebase": "中止变基",
+ "add_remote": "添加远程…",
+ "add_to_gitignore": "添加到 .gitignore",
+ "always": "始终",
+ "apply_latest_stash": "应用最新储藏",
+ "apply_stash": "应用储藏…",
+ "binary": "此文件是二进制文件或过大,无法比较。",
+ "branch_name_invalid": "分支名称不能包含空格、'..'、'~'、'^'、':'、'?'、'*'、'[' 或 '\\'。",
+ "branch_name_placeholder": "分支名称",
+ "branch_name_prompt": "请输入新分支的名称",
+ "cannot_undo": "此操作无法撤消。",
+ "changes_aria": "已更改的文件",
+ "checkout_detached": "以分离模式签出…",
+ "checkout_detached_here": "签出(分离)",
+ "checkout_tip": "签出分支/标签…",
+ "checkout_to": "签出到…",
+ "cherry_pick": "拣选",
+ "cherry_pick_conflicts": "拣选存在冲突。请在“合并更改”中解决。",
+ "close": "关闭",
+ "commit": "提交",
+ "commit_all": "全部提交",
+ "commit_all_amend": "全部提交(修正)",
+ "commit_all_signed_off": "全部提交(签名)",
+ "commit_amend": "提交(修正)",
+ "commit_no_verify": "提交(不验证)",
+ "commit_options": "更多提交操作",
+ "commit_push": "提交并推送",
+ "commit_signed_off": "提交(签名)",
+ "commit_staged": "提交已暂存",
+ "commit_staged_amend": "提交已暂存(修正)",
+ "commit_staged_signed_off": "提交已暂存(签名)",
+ "commit_sync": "提交并同步",
+ "commit_tip": "在“{branch}”上提交更改",
+ "continue": "继续",
+ "copy_commit_id": "复制提交 ID",
+ "copy_commit_message": "复制提交消息",
+ "copy_failed": "无法复制到剪贴板。",
+ "copy_path": "复制路径",
+ "copy_relative_path": "复制相对路径",
+ "create_branch": "创建新分支…",
+ "create_branch_from": "从…创建新分支",
+ "create_branch_here": "创建分支…",
+ "create_tag": "创建标签",
+ "create_tag_here": "创建标签…",
+ "delete_branch": "删除分支…",
+ "delete_branch_button": "删除分支",
+ "delete_file": "移到回收站",
+ "delete_tag": "删除标签",
+ "delete_unmerged": "分支“{name}”包含不在其他任何分支上的提交。仍要删除吗?",
+ "delete_untracked_one": "删除“{name}”?",
+ "diff_working_tree": "已暂存 ↔ 工作树",
+ "discard_all": "放弃所有更改",
+ "discard_all_body": "其中 {n} 个未跟踪,将移到回收站。其余无法撤消。",
+ "discard_all_files": "放弃全部 {n} 个文件",
+ "discard_all_title": "放弃 {n} 个文件中的所有更改?",
+ "discard_changes": "放弃更改",
+ "discard_file": "放弃文件",
+ "discard_many": "放弃 {n} 个文件中的更改?",
+ "discard_n_files": "放弃 {n} 个文件",
+ "discard_one": "放弃“{name}”中的更改?",
+ "discard_tracked_files": "放弃 {n} 个已跟踪文件",
+ "drop": "删除",
+ "drop_all": "全部删除",
+ "drop_all_confirm": "删除全部 {n} 个储藏?此操作无法撤消。",
+ "drop_all_stashes": "删除所有储藏…",
+ "drop_stash": "删除储藏…",
+ "drop_stash_confirm": "删除 {ref}?此操作无法撤消。",
+ "fetch": "抓取",
+ "fetch_all": "从所有远程抓取",
+ "fetch_prune": "抓取(修剪)",
+ "go_to_current": "转到当前提交",
+ "incoming": "传入:尚未拉取",
+ "index": "索引",
+ "init_repository": "初始化仓库",
+ "load_more": "加载更多",
+ "mark_resolved": "暂存(标记为已解决)",
+ "menu_branch": "分支",
+ "menu_changes": "更改",
+ "menu_commit": "提交",
+ "menu_pull_push": "拉取、推送",
+ "menu_remote": "远程",
+ "menu_stash": "储藏",
+ "menu_tags": "标签",
+ "merge_branch": "合并…",
+ "merge_conflicts": "合并存在冲突。请在“合并更改”中解决。",
+ "message_label": "提交消息",
+ "message_placeholder": "消息(按 {key}+Enter 在“{branch}”上提交)",
+ "message_required": "请先输入提交消息。",
+ "more_actions": "更多操作…",
+ "no_commits": "还没有提交。",
+ "no_remotes": "此仓库没有远程。",
+ "no_repository": "此工作区的文件夹还不是 git 仓库。",
+ "no_stashes": "没有储藏。",
+ "nothing_to_commit": "没有可提交的更改。",
+ "ok": "确定",
+ "ok_dont_ask": "确定,不再询问",
+ "open_changes": "打开更改",
+ "open_file": "打开文件",
+ "outgoing": "传出:尚未推送",
+ "outside_workspace": "此文件位于工作区文件夹之外。",
+ "pick_branch_from": "选择用于创建分支的引用",
+ "pick_branch_pull": "选择要拉取的分支",
+ "pick_checkout": "选择要签出的分支或标签",
+ "pick_delete_branch": "选择要删除的分支",
+ "pick_detached": "选择要以分离模式签出的引用",
+ "pick_merge": "选择要合并的分支或标签",
+ "pick_rebase": "选择要变基到的分支",
+ "pick_remote_publish": "选择要发布分支的远程",
+ "pick_remote_pull": "选择要拉取的远程",
+ "pick_remote_push": "选择要推送到的远程",
+ "pick_remote_remove": "选择要移除的远程",
+ "pick_stash_apply": "选择要应用的储藏",
+ "pick_stash_drop": "选择要删除的储藏",
+ "pick_stash_pop": "选择要弹出的储藏",
+ "pick_tag_delete": "选择要删除的标签",
+ "pop_latest_stash": "弹出最新储藏",
+ "pop_stash": "弹出储藏…",
+ "publish_branch": "发布分支",
+ "pull": "拉取",
+ "pull_from": "从…拉取",
+ "pull_rebase": "拉取(变基)",
+ "push": "推送",
+ "push_tags": "推送标签",
+ "push_to": "推送到…",
+ "rebase_branch": "变基分支…",
+ "rebase_conflicts": "变基存在冲突。请在“合并更改”中解决,然后继续。",
+ "refresh": "刷新",
+ "remote_name_invalid": "请使用字母、数字、点、下划线或连字符。",
+ "remote_name_prompt": "请输入远程名称",
+ "remote_url_prompt": "请输入远程 URL",
+ "remove_remote": "移除远程",
+ "rename_branch": "重命名分支…",
+ "rename_prompt": "请输入分支的新名称",
+ "reveal_in_explorer": "在文件夹标签页中显示",
+ "revert_commit": "还原提交",
+ "revert_conflicts": "还原存在冲突。请在“合并更改”中解决,然后继续。",
+ "smart_commit_title": "没有可提交的暂存更改。\n\n是否要暂存所有更改并直接提交?",
+ "sort_name": "按名称排序",
+ "sort_path": "按路径排序",
+ "sort_status": "按状态排序",
+ "stage_all": "暂存所有更改",
+ "stage_all_merge": "暂存所有合并更改",
+ "stage_changes": "暂存更改",
+ "stash": "储藏",
+ "stash_message_placeholder": "消息(可选)",
+ "stash_message_prompt": "可选:输入储藏消息",
+ "stash_staged": "储藏已暂存",
+ "stash_untracked": "储藏(包括未跟踪)",
+ "sync": "同步",
+ "sync_changes": "同步更改",
+ "sync_confirm": "这将从“{upstream}”拉取提交并推送到该处。",
+ "sync_tip": "同步更改:与 {upstream} {behind}↓ {ahead}↑",
+ "synced_tip": "已与 {upstream} 同步",
+ "tag_message_placeholder": "消息(可选)",
+ "tag_message_prompt": "可选:输入用于注释标签的消息",
+ "tag_name_prompt": "请输入标签名称",
+ "truncated": "更改的文件比列表显示的更多。",
+ "undo_last_commit": "撤消上次提交",
+ "unstage_all": "取消暂存所有更改",
+ "unstage_changes": "取消暂存更改",
+ "untracked_to_trash": "未跟踪的文件将移到回收站。",
+ "view_list": "以列表形式查看",
+ "view_tree": "以树形式查看",
+ "view_sort": "视图和排序",
+ "working_tree": "工作树",
+ "yes": "是"
+ }
},
"skills": {
"subtitle": "拖到终端上即可粘贴",
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 17ed829546..8d976ca395 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -484,6 +484,7 @@ class WebServer:
from .agent_mcp_routes import router as agent_mcp_router
from .agent_runtime_routes import router as agent_runtime_router
from .agentic_ide_git_routes import router as agentic_ide_git_router
+ from .agentic_ide_scm_routes import router as agentic_ide_scm_router
from .agentic_ide_routes import router as agentic_ide_router
from .antigravity_routes import router as antigravity_router
from .app_actions_routes import router as app_actions_router
@@ -697,6 +698,7 @@ class WebServer:
# workspace above; adds the folder picker, call-signs, transcripts, and
# the focused coding mode.
# Before the IDE router, so its /{…} paths never shadow /git/….
+ app.include_router(agentic_ide_scm_router)
app.include_router(agentic_ide_git_router)
app.state.team_threads = None
app.include_router(team_thread_router)
diff --git a/tests/unit/agentic_ide/test_scm.py b/tests/unit/agentic_ide/test_scm.py
new file mode 100644
index 0000000000..eeff55e488
--- /dev/null
+++ b/tests/unit/agentic_ide/test_scm.py
@@ -0,0 +1,323 @@
+"""Source control for the Git tab, against a real ``git``."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import git_changes, scm
+from jarvis.agentic_ide.git_ops import GitError
+
+pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")
+
+
[email protected](autouse=True)
+def _identity(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"))
+ # Untracked files go away for good in tests, never into the real trash.
+ monkeypatch.setattr(scm, "_trash", lambda target: False)
+
+
+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 repo(tmp_path: Path) -> Path:
+ root = tmp_path / "project"
+ root.mkdir()
+ _git(root, "init", "-q", "-b", "main")
+ (root / "app.py").write_text("print('hi')\n", encoding="utf-8")
+ (root / "old.txt").write_text("old\n", encoding="utf-8")
+ _git(root, "add", ".")
+ _git(root, "commit", "-q", "-m", "feat: app")
+ return root
+
+
+def cloned(tmp_path: Path, repo: Path) -> tuple[Path, Path]:
+ """A bare remote, the repo pushed to it, and a second clone that can push more."""
+ remote = tmp_path / "remote.git"
+ _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(remote))
+ _git(repo, "remote", "add", "origin", str(remote))
+ _git(repo, "push", "-q", "-u", "origin", "main")
+ other = tmp_path / "other"
+ _git(tmp_path, "clone", "-q", str(remote), str(other))
+ return remote, other
+
+
+def _letters(files: list[scm.ScmFile]) -> dict[str, str]:
+ return {entry.path: entry.letter for entry in files}
+
+
+def test_status_groups_staged_unstaged_untracked_and_renames(repo: Path) -> None:
+ (repo / "app.py").write_text("print('changed')\n", encoding="utf-8")
+ (repo / "new.txt").write_text("new\n", encoding="utf-8")
+ (repo / "staged.txt").write_text("s\n", encoding="utf-8")
+ _git(repo, "add", "staged.txt")
+ _git(repo, "mv", "old.txt", "renamed.txt")
+ (repo / "dir").mkdir()
+ (repo / "dir" / "deep.txt").write_text("d\n", encoding="utf-8")
+
+ status = scm.read_status(repo)
+
+ assert status.available and status.branch == "main" and not status.detached
+ assert _letters(status.changes) == {"app.py": "M", "new.txt": "U", "dir/deep.txt": "U"}
+ assert _letters(status.staged) == {"staged.txt": "A", "renamed.txt": "R"}
+ renamed = next(entry for entry in status.staged if entry.path == "renamed.txt")
+ assert renamed.original == "old.txt" and renamed.status == "index_renamed"
+ assert status.head_message == "feat: app"
+
+
+def test_status_outside_a_repository_is_unavailable(tmp_path: Path) -> None:
+ status = scm.read_status(tmp_path)
+ assert not status.available and status.reason
+
+
+def test_stage_unstage_and_discard(repo: Path) -> None:
+ (repo / "app.py").write_text("print('changed')\n", encoding="utf-8")
+ (repo / "new file.txt").write_text("n\n", encoding="utf-8")
+ (repo / "old.txt").unlink()
+
+ scm.stage(repo, ["app.py", "new file.txt", "old.txt"])
+ status = scm.read_status(repo)
+ assert _letters(status.staged) == {"app.py": "M", "new file.txt": "A", "old.txt": "D"}
+ assert status.changes == []
+
+ scm.unstage(repo, ["app.py"])
+ status = scm.read_status(repo)
+ assert _letters(status.changes) == {"app.py": "M"}
+
+ scm.discard(repo, ["app.py"])
+ assert (repo / "app.py").read_text(encoding="utf-8") == "print('hi')\n"
+
+ scm.unstage_all(repo)
+ scm.discard(repo, ["new file.txt", "old.txt"])
+ assert not (repo / "new file.txt").exists()
+ assert (repo / "old.txt").exists()
+ assert scm.read_status(repo).changes == []
+
+
+def test_paths_outside_the_repository_are_refused(repo: Path) -> None:
+ for bad in ["../escape.txt", "/etc/passwd", "C:/Windows/x", ""]:
+ with pytest.raises(GitError) as exc:
+ scm.stage(repo, [bad])
+ assert exc.value.code == "invalid"
+
+
+def test_discard_all_keeps_untracked_unless_asked(repo: Path) -> None:
+ (repo / "app.py").write_text("x\n", encoding="utf-8")
+ (repo / "new.txt").write_text("n\n", encoding="utf-8")
+ scm.discard_all(repo, untracked=False)
+ assert _letters(scm.read_status(repo).changes) == {"new.txt": "U"}
+ scm.discard_all(repo, untracked=True)
+ assert scm.read_status(repo).changes == []
+
+
+def test_commit_amend_all_and_undo(repo: Path) -> None:
+ (repo / "app.py").write_text("print('two')\n", encoding="utf-8")
+ with pytest.raises(GitError) as exc:
+ scm.commit(repo, "fix: nothing staged")
+ assert exc.value.code == "clean"
+
+ scm.commit(repo, "fix: two\n\nbody line", all_changes=True)
+ assert _git(repo, "log", "-1", "--format=%B").strip() == "fix: two\n\nbody line"
+
+ (repo / "more.txt").write_text("m\n", encoding="utf-8")
+ scm.stage(repo, ["more.txt"])
+ scm.commit(repo, "", amend=True)
+ assert _git(repo, "rev-list", "--count", "HEAD") == "2"
+ assert "more.txt" in _git(repo, "show", "--name-only", "--format=", "HEAD")
+
+ message = scm.undo_last_commit(repo)
+ assert message.startswith("fix: two")
+ status = scm.read_status(repo)
+ assert {"app.py", "more.txt"} <= {entry.path for entry in status.staged}
+ assert _git(repo, "rev-list", "--count", "HEAD") == "1"
+
+
+def test_undo_the_first_commit_keeps_the_files_staged(tmp_path: Path) -> None:
+ root = tmp_path / "fresh"
+ root.mkdir()
+ _git(root, "init", "-q", "-b", "main")
+ (root / "a.txt").write_text("a\n", encoding="utf-8")
+ scm.stage(root, ["a.txt"])
+ scm.commit(root, "first")
+ scm.undo_last_commit(root)
+ status = scm.read_status(root)
+ assert status.unborn and _letters(status.staged) == {"a.txt": "A"}
+ scm.unstage(root, ["a.txt"])
+ assert _letters(scm.read_status(root).changes) == {"a.txt": "U"}
+
+
+def test_ignore_appends_once(repo: Path) -> None:
+ (repo / "build.log").write_text("x\n", encoding="utf-8")
+ scm.ignore(repo, ["build.log"])
+ scm.ignore(repo, ["build.log"])
+ assert (repo / ".gitignore").read_text(encoding="utf-8") == "/build.log\n"
+ assert "build.log" not in {entry.path for entry in scm.read_status(repo).changes}
+
+
+def test_branches_tags_checkout_and_merge_conflict(repo: Path) -> None:
+ scm.create_branch(repo, "feature/x")
+ assert scm.read_status(repo).branch == "feature/x"
+ (repo / "app.py").write_text("print('feature')\n", encoding="utf-8")
+ scm.commit(repo, "feat: feature", all_changes=True)
+ scm.create_tag(repo, "v1.0", message="first release")
+ refs = scm.list_refs(repo)
+ names = {(ref["kind"], ref["name"]) for ref in refs["refs"]}
+ assert {("head", "main"), ("head", "feature/x"), ("tag", "v1.0")} <= names
+ assert refs["current"] == "feature/x"
+
+ scm.checkout(repo, "main")
+ (repo / "app.py").write_text("print('main')\n", encoding="utf-8")
+ scm.commit(repo, "feat: main", all_changes=True)
+ assert scm.merge(repo, "feature/x") == "conflict"
+ status = scm.read_status(repo)
+ assert status.operation == "merge"
+ assert [(entry.path, entry.letter) for entry in status.merge] == [("app.py", "!")]
+
+ scm.abort_operation(repo)
+ assert scm.read_status(repo).operation == ""
+
+ with pytest.raises(GitError) as exc:
+ scm.delete_branch(repo, "feature/x")
+ assert exc.value.code == "unmerged"
+ scm.delete_branch(repo, "feature/x", force=True)
+ scm.delete_tag(repo, "v1.0")
+ assert {ref["name"] for ref in scm.list_refs(repo)["refs"]} == {"main"}
+
+ with pytest.raises(GitError):
+ scm.create_branch(repo, "bad..name")
+ with pytest.raises(GitError):
+ scm.checkout(repo, "--orphan")
+
+
+def test_stash_round_trip(repo: Path) -> None:
+ (repo / "app.py").write_text("stashed\n", encoding="utf-8")
+ (repo / "new.txt").write_text("n\n", encoding="utf-8")
+ scm.stash(repo, message="wip", include_untracked=True)
+ assert scm.read_status(repo).changes == []
+ stashes = scm.list_stashes(repo)
+ assert len(stashes) == 1 and "wip" in stashes[0]["message"]
+ assert scm.read_status(repo).stashes == 1
+
+ scm.stash_apply(repo, stashes[0]["ref"])
+ assert (repo / "app.py").read_text(encoding="utf-8") == "stashed\n"
+ scm.discard_all(repo, untracked=True)
+ scm.stash_apply(repo, pop=True)
+ assert scm.list_stashes(repo) == []
+ with pytest.raises(GitError):
+ scm.stash_drop(repo, "HEAD")
+
+
+def test_graph_commit_details_and_file_diff(repo: Path) -> None:
+ (repo / "app.py").write_text("print('v2')\n", encoding="utf-8")
+ _git(repo, "mv", "old.txt", "moved.txt")
+ scm.commit(repo, "feat: v2", all_changes=True)
+
+ page = scm.graph(repo, limit=1)
+ assert len(page["commits"]) == 1 and page["more"]
+ top = page["commits"][0]
+ assert top["subject"] == "feat: v2" and top["id"] == page["head"]
+ assert any("HEAD" in ref for ref in top["refs"])
+ rest = scm.graph(repo, skip=1, limit=10)
+ assert [entry["subject"] for entry in rest["commits"]] == ["feat: app"]
+ assert rest["commits"][0]["parents"] == [] and not rest["more"]
+
+ details = scm.commit_details(repo, top["id"])
+ assert details["message"] == "feat: v2"
+ files = {entry["path"]: entry for entry in details["files"]}
+ assert files["app.py"]["letter"] == "M"
+ assert files["moved.txt"]["letter"] == "R" and files["moved.txt"]["original"] == "old.txt"
+
+ diff = scm.commit_file_diff(repo, top["id"], "app.py")
+ assert diff["before"] == "print('hi')\n" and diff["after"] == "print('v2')\n"
+ first = scm.commit_details(repo, rest["commits"][0]["id"])
+ assert {entry["letter"] for entry in first["files"]} == {"A"}
+ added = scm.commit_file_diff(repo, rest["commits"][0]["id"], "app.py")
+ assert added["before"] is None and added["after"] == "print('hi')\n"
+
+
+def test_index_text_reads_the_staged_copy(repo: Path) -> None:
+ (repo / "app.py").write_text("staged\n", encoding="utf-8")
+ scm.stage(repo, ["app.py"])
+ (repo / "app.py").write_text("worktree\n", encoding="utf-8")
+ assert git_changes.head_text(repo, "app.py", git_changes.INDEX_REF) == "staged\n"
+ assert git_changes.head_text(repo, "app.py") == "print('hi')\n"
+ assert git_changes.head_text(repo, "missing.txt", git_changes.INDEX_REF) is None
+
+
+def test_remote_sync_publish_and_incoming(repo: Path, cloned: tuple[Path, Path]) -> None:
+ _, other = cloned
+ (other / "remote.txt").write_text("r\n", encoding="utf-8")
+ _git(other, "add", ".")
+ _git(other, "commit", "-q", "-m", "feat: from elsewhere")
+ _git(other, "push", "-q")
+
+ scm.fetch(repo)
+ status = scm.read_status(repo)
+ assert status.upstream == "origin/main" and status.behind == 1 and status.ahead == 0
+ page = scm.graph(repo)
+ assert len(page["incoming"]) == 1
+ assert page["commits"][0]["subject"] == "feat: from elsewhere"
+
+ (repo / "local.txt").write_text("l\n", encoding="utf-8")
+ scm.commit(repo, "feat: local", all_changes=True)
+ scm.sync(repo)
+ status = scm.read_status(repo)
+ assert status.ahead == 0 and status.behind == 0
+ assert (repo / "remote.txt").exists()
+
+ scm.create_branch(repo, "topic")
+ assert scm.read_status(repo).upstream == ""
+ assert scm.push(repo) == "origin/topic"
+ assert scm.read_status(repo).upstream == "origin/topic"
+
+ scm.checkout(repo, "main")
+ scm.delete_branch(repo, "topic", force=True)
+ scm.fetch(repo, prune=True)
+ assert scm.checkout(repo, "origin/topic") == "topic"
+ assert scm.read_status(repo).upstream == "origin/topic"
+
+ scm.add_remote(repo, "mirror", str(cloned[0]))
+ assert "mirror" in scm.read_status(repo).remotes
+ scm.remove_remote(repo, "mirror")
+ with pytest.raises(GitError):
+ scm.remove_remote(repo, "mirror")
+
+
+def test_status_parser_reads_conflicts_and_branch_headers() -> None:
+ text = "\0".join(
+ [
+ "# branch.oid 1234567890abcdef1234567890abcdef12345678",
+ "# branch.head topic",
+ "# branch.upstream origin/topic",
+ "# branch.ab +2 -3",
+ "u UU N... 100644 100644 100644 100644 a b c both.txt",
+ "1 .D N... 100644 100644 000000 a a gone.txt",
+ "1 MM N... 100644 100644 100644 a b both sides.txt",
+ "2 R. N... 100644 100644 100644 a a R100 new name.txt",
+ "old name.txt",
+ "? fresh.txt",
+ "",
+ ]
+ )
+ status = scm.ScmStatus(available=True)
+ scm.parse_status(text, status)
+ assert status.branch == "topic" and status.upstream == "origin/topic"
+ assert (status.ahead, status.behind) == (2, 3)
+ assert [(entry.path, entry.status) for entry in status.merge] == [("both.txt", "both_modified")]
+ assert _letters(status.staged) == {"both sides.txt": "M", "new name.txt": "R"}
+ assert status.staged[1].original == "old name.txt"
+ assert _letters(status.changes) == {"gone.txt": "D", "both sides.txt": "M", "fresh.txt": "U"}