Skip to content

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

feat(ide): git options for new workspaces and agents, plus a Git panel

rubenluetke10-beep499a7dfaea9b
diff --git a/jarvis/agentic_ide/folders.py b/jarvis/agentic_ide/folders.py
index 67b7a8ebc9..727e055567 100644
--- a/jarvis/agentic_ide/folders.py
+++ b/jarvis/agentic_ide/folders.py
@@ -516,8 +516,22 @@ def create_folder(parent: str | Path | None, name: str) -> tuple[FolderEntry | N
def _git_branch(root: Path) -> str | None:
- """Current branch from ``.git/HEAD`` — no subprocess, no git required."""
- head = root / ".git" / "HEAD"
+ """Current branch from ``.git/HEAD`` — no subprocess, no git required.
+
+ In a linked worktree ``.git`` is a FILE (``gitdir: <path>``) pointing at the
+ worktree's own git directory, which holds its HEAD.
+ """
+ dot_git = root / ".git"
+ head = dot_git / "HEAD"
+ if dot_git.is_file():
+ try:
+ pointer = dot_git.read_text(encoding="utf-8", errors="replace").strip()
+ except OSError: # unreadable pointer: no branch shown, like a missing HEAD
+ return None
+ if not pointer.startswith("gitdir:"):
+ return None
+ gitdir = Path(pointer[len("gitdir:") :].strip())
+ head = (gitdir if gitdir.is_absolute() else root / gitdir) / "HEAD"
try:
text = head.read_text(encoding="utf-8", errors="replace").strip()
except OSError:
diff --git a/jarvis/agentic_ide/git_ops.py b/jarvis/agentic_ide/git_ops.py
new file mode 100644
index 0000000000..9246f9a912
--- /dev/null
+++ b/jarvis/agentic_ide/git_ops.py
@@ -0,0 +1,825 @@
+"""Git for the Agentic IDE: where a workspace's agents work, and what they changed.
+
+The IDE runs several coding agents at once. Git decides whether they share one
+checkout or each get their own, so this module is the one place that answers:
+
+* **Inspect** — which branch a folder is on, what is uncommitted, how far it is
+ ahead of / behind its upstream, which branches and worktrees exist.
+* **Prepare** — the git half of opening a workspace or an agent: keep the
+ current checkout, ``git init`` a new repository, create or switch a branch in
+ place, or give the agents a fresh ``git worktree`` of their own.
+* **Finish** — commit everything, push, open a pull request (``gh``), merge a
+ worktree's branch back, and remove a worktree safely.
+
+Where worktrees go: ``<repo>/.worktrees/<name>`` — beside the code they belong
+to, and listed in the repository's LOCAL ``.git/info/exclude`` so they never
+show up as untracked files. Nothing in the committed ``.gitignore`` is changed
+on the user's behalf.
+
+Every function blocks (``git`` subprocesses) — callers run them in a worker
+thread. Cross-platform: plain ``git`` on PATH, ``pathlib`` paths, UTF-8, and
+``NO_WINDOW_CREATIONFLAGS`` so no console window flashes on Windows. A machine
+without git gets ``git_available=False`` from :func:`inspect` and a readable
+:class:`GitError` from everything else — never a crash.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import secrets
+import shutil
+import subprocess
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any, Literal
+
+from loguru import logger
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+#: The folder under the repository root that holds agent worktrees.
+WORKTREE_DIR = ".worktrees"
+
+#: Prefix of generated branch names, so agent branches sort together.
+BRANCH_PREFIX = "agent/"
+
+_GIT_TIMEOUT_S = 60
+# Network operations (push, fetch, PR creation) get longer: a first push of a
+# big branch over a slow link legitimately takes a while.
+_NETWORK_TIMEOUT_S = 180
+# Caps on what one inspection returns — the UI lists, it does not page.
+_MAX_BRANCHES = 200
+_MAX_CHANGES = 200
+
+PrepareMode = Literal[
+ "current", "init", "new_branch", "switch_branch", "new_worktree", "open_worktree"
+]
+
+_ADJECTIVES = tuple(
+ "amber brave bright calm clever cosmic crisp daring eager gentle golden happy keen"
+ " lively lucky mellow nimble quiet rapid silver steady swift tidy vivid witty".split()
+)
+_NOUNS = tuple(
+ "anchor aurora breeze canyon comet delta ember falcon forest glacier harbor lagoon"
+ " meadow meteor orbit otter pine prairie river summit tide valley willow zenith lynx".split()
+)
+
+
+class GitError(RuntimeError):
+ """A git operation that failed, worded for the person who asked for it.
+
+ ``code`` lets the UI react to the failures it has a follow-up for (``dirty``
+ asks "remove anyway?") without parsing the sentence.
+ """
+
+ def __init__(self, message: str, *, code: str = "failed") -> None:
+ super().__init__(message)
+ self.code = code
+
+
+# ----------------------------------------------------------------- plumbing
+
+
+def git_available() -> bool:
+ return shutil.which("git") is not None
+
+
+def gh_available() -> bool:
+ """The GitHub CLI, which opens pull requests. Optional — only PRs need it."""
+ return shutil.which("gh") is not None
+
+
+def _run(
+ args: list[str], cwd: Path, *, timeout: float = _GIT_TIMEOUT_S, program: str = "git"
+) -> subprocess.CompletedProcess[str]:
+ env = dict(os.environ)
+ # Never block on a credential or editor prompt nobody can see.
+ env["GIT_TERMINAL_PROMPT"] = "0"
+ env.setdefault("GIT_EDITOR", "true")
+ env["GH_PROMPT_DISABLED"] = "1"
+ command = [program, *args] if program != "git" else ["git", "-c", "core.quotepath=off", *args]
+ try:
+ return subprocess.run(
+ command,
+ cwd=str(cwd),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=timeout,
+ check=False,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except FileNotFoundError as exc:
+ name = "Git" if program == "git" else "The GitHub CLI (gh)"
+ raise GitError(f"{name} is not installed.", code="missing") from exc
+ except subprocess.TimeoutExpired as exc:
+ raise GitError(f"{program} did not answer in time.", code="timeout") from exc
+
+
+def _reason(result: subprocess.CompletedProcess[str]) -> str:
+ """The last meaningful line git printed — usually the one that says why."""
+ 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"exited with {result.returncode}"
+
+
+def _ok(args: list[str], cwd: Path, *, timeout: float = _GIT_TIMEOUT_S, what: str = "") -> str:
+ result = _run(args, cwd, timeout=timeout)
+ if result.returncode != 0:
+ prefix = f"Git could not {what}: " if what else "Git: "
+ raise GitError(prefix + _reason(result))
+ return result.stdout
+
+
+def _folder(folder: str | Path) -> Path:
+ path = Path(folder).expanduser()
+ if not path.is_dir():
+ raise GitError(f"There is no folder called {path}.", code="no_folder")
+ return path
+
+
+def _same_path(a: str | Path, b: str | Path) -> bool:
+ try:
+ return os.path.normcase(str(Path(a).resolve())) == os.path.normcase(str(Path(b).resolve()))
+ except OSError: # unresolvable path: compare the spelling instead
+ return os.path.normcase(str(a)) == os.path.normcase(str(b))
+
+
+def _inside(child: Path, parent: Path) -> bool:
+ try:
+ relative = Path(os.path.relpath(child.resolve(), parent.resolve()))
+ except ValueError: # different drives on Windows: not inside
+ return False
+ return not relative.parts or relative.parts[0] != ".."
+
+
+# ------------------------------------------------------------------ inspect
+
+
+@dataclass(slots=True)
+class Change:
+ path: str
+ # One letter per side, git's own: M modified, A added, D deleted, R renamed,
+ # ? untracked, U conflicted, . unchanged on that side.
+ index: str
+ worktree: str
+
+
+@dataclass(slots=True)
+class Branch:
+ name: str
+ current: bool = False
+ upstream: str = ""
+ committed_at: int = 0
+ # The checkout this branch is open in, if any — a branch can be checked out
+ # in only one worktree at a time.
+ worktree: str = ""
+
+
+@dataclass(slots=True)
+class Worktree:
+ path: str
+ branch: str = ""
+ head: str = ""
+ main: bool = False
+ detached: bool = False
+ locked: bool = False
+ prunable: bool = False
+ # The worktree the inspected folder is in.
+ current: bool = False
+
+
+@dataclass(slots=True)
+class RepoInfo:
+ folder: str
+ git_available: bool = True
+ gh_available: bool = False
+ is_repo: bool = False
+ root: str = ""
+ # The main checkout (the one that owns ``.git``) — equal to ``root`` unless
+ # the folder is inside a linked worktree.
+ main_root: str = ""
+ is_worktree: bool = False
+ branch: str = ""
+ detached: bool = False
+ # No commit yet (fresh ``git init``): nothing to branch from.
+ unborn: bool = False
+ head: str = ""
+ upstream: str = ""
+ ahead: int = 0
+ behind: int = 0
+ staged: int = 0
+ unstaged: int = 0
+ untracked: int = 0
+ conflicted: int = 0
+ insertions: int = 0
+ deletions: int = 0
+ default_branch: str = ""
+ remotes: list[str] = field(default_factory=list)
+ branches: list[Branch] = field(default_factory=list)
+ remote_branches: list[str] = field(default_factory=list)
+ worktrees: list[Worktree] = field(default_factory=list)
+ changes: list[Change] = field(default_factory=list)
+ suggested_branch: str = ""
+ # Where :func:`prepare` would put a worktree for ``suggested_branch``.
+ worktree_dir: str = ""
+
+ @property
+ def dirty(self) -> bool:
+ return bool(self.staged or self.unstaged or self.untracked or self.conflicted)
+
+ def to_dict(self) -> dict[str, Any]:
+ data = asdict(self)
+ data["dirty"] = self.dirty
+ return data
+
+
+def repo_root(folder: str | Path) -> Path | None:
+ """The top of the git checkout ``folder`` is in, or None if it is not one."""
+ path = Path(folder).expanduser()
+ if not path.is_dir() or not git_available():
+ return None
+ try:
+ result = _run(["rev-parse", "--show-toplevel"], path)
+ except GitError: # git missing or hung: treated as "not a repository"
+ return None
+ top = result.stdout.strip()
+ return Path(top) if result.returncode == 0 and top else None
+
+
+def _common_dir(folder: Path) -> Path | None:
+ try:
+ result = _run(["rev-parse", "--path-format=absolute", "--git-common-dir"], folder)
+ except GitError: # git missing or hung: no common dir to compare
+ return None
+ text = result.stdout.strip()
+ return Path(text) if result.returncode == 0 and text else None
+
+
+def same_repository(folder: str | Path, other: str | Path) -> bool:
+ """True when both folders are checkouts of ONE repository (e.g. a worktree of it)."""
+ a, b = Path(folder).expanduser(), Path(other).expanduser()
+ if not a.is_dir() or not b.is_dir() or not git_available():
+ return False
+ common_a, common_b = _common_dir(a), _common_dir(b)
+ return common_a is not None and common_b is not None and _same_path(common_a, common_b)
+
+
+def _parse_status(text: str, info: RepoInfo) -> None:
+ """Fill branch/ahead/behind/counts from ``git status --porcelain=v2 --branch``."""
+ for line in text.splitlines():
+ if line.startswith("# branch.oid "):
+ oid = line[len("# branch.oid ") :].strip()
+ info.unborn = oid == "(initial)"
+ info.head = "" if info.unborn else oid[:12]
+ elif line.startswith("# branch.head "):
+ head = line[len("# branch.head ") :].strip()
+ info.detached = head == "(detached)"
+ info.branch = "" if info.detached else head
+ elif line.startswith("# branch.upstream "):
+ info.upstream = line[len("# branch.upstream ") :].strip()
+ elif line.startswith("# branch.ab "):
+ match = re.match(r"# branch\.ab \+(\d+) -(\d+)", line)
+ if match:
+ info.ahead, info.behind = int(match.group(1)), int(match.group(2))
+ elif line.startswith(("1 ", "2 ")):
+ parts = line.split(" ")
+ xy = parts[1] if len(parts) > 1 else ".."
+ # Ordinary entries have 8 fields before the path, renames 9 (the
+ # score) plus "<path>\t<orig>".
+ path = " ".join(parts[8 if line.startswith("1 ") else 9 :]).split("\t")[0]
+ if xy[0] != ".":
+ info.staged += 1
+ if xy[1] != ".":
+ info.unstaged += 1
+ if len(info.changes) < _MAX_CHANGES:
+ info.changes.append(Change(path=path, index=xy[0], worktree=xy[1]))
+ elif line.startswith("u "):
+ info.conflicted += 1
+ path = " ".join(line.split(" ")[10:])
+ if len(info.changes) < _MAX_CHANGES:
+ info.changes.append(Change(path=path, index="U", worktree="U"))
+ elif line.startswith("? "):
+ info.untracked += 1
+ if len(info.changes) < _MAX_CHANGES:
+ info.changes.append(Change(path=line[2:], index="?", worktree="?"))
+
+
+def _parse_worktrees(text: str, current_root: Path) -> list[Worktree]:
+ trees: list[Worktree] = []
+ entry: Worktree | None = None
+ for line in [*text.splitlines(), ""]:
+ if not line.strip():
+ if entry is not None:
+ trees.append(entry)
+ entry = None
+ continue
+ key, _, value = line.partition(" ")
+ if key == "worktree":
+ entry = Worktree(path=str(Path(value)), main=not trees and entry is None)
+ entry.current = _same_path(value, current_root)
+ elif entry is None:
+ continue
+ elif key == "HEAD":
+ entry.head = value[:12]
+ elif key == "branch":
+ entry.branch = value.removeprefix("refs/heads/")
+ elif key == "detached":
+ entry.detached = True
+ elif key == "locked":
+ entry.locked = True
+ elif key == "prunable":
+ entry.prunable = True
+ elif key == "bare":
+ entry.main = False
+ return trees
+
+
+def _default_branch(root: Path, branches: list[Branch], current: str) -> str:
+ result = _run(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], root)
+ if result.returncode == 0 and result.stdout.strip():
+ return result.stdout.strip().split("/", 1)[-1]
+ names = {branch.name for branch in branches}
+ for candidate in ("main", "master", "trunk", "develop"):
+ if candidate in names:
+ return candidate
+ return current
+
+
+def inspect(folder: str | Path) -> RepoInfo:
+ """Everything the Git panel shows about ``folder``, in a handful of git calls."""
+ path = Path(folder).expanduser()
+ info = RepoInfo(folder=str(path), gh_available=gh_available())
+ if not git_available():
+ info.git_available = False
+ return info
+ if not path.is_dir():
+ raise GitError(f"There is no folder called {path}.", code="no_folder")
+ root = repo_root(path)
+ if root is None:
+ info.suggested_branch = suggest_branch_name()
+ return info
+ info.is_repo = True
+ info.root = str(root)
+
+ status = _run(["status", "--porcelain=v2", "--branch", "--untracked-files=normal"], root)
+ if status.returncode == 0:
+ _parse_status(status.stdout, info)
+ if not info.unborn:
+ shortstat = _run(["diff", "--shortstat", "HEAD"], root)
+ if shortstat.returncode == 0:
+ plus = re.search(r"(\d+) insertion", shortstat.stdout)
+ minus = re.search(r"(\d+) deletion", shortstat.stdout)
+ info.insertions = int(plus.group(1)) if plus else 0
+ info.deletions = int(minus.group(1)) if minus else 0
+
+ refs = _run(
+ [
+ "for-each-ref",
+ "--sort=-committerdate",
+ f"--count={_MAX_BRANCHES}",
+ "--format=%(refname:short)%09%(upstream:short)%09%(committerdate:unix)%09%(worktreepath)",
+ "refs/heads",
+ ],
+ root,
+ )
+ if refs.returncode == 0:
+ for line in refs.stdout.splitlines():
+ name, upstream, stamp, tree = ([*line.split("\t"), "", "", ""])[:4]
+ if not name:
+ continue
+ info.branches.append(
+ Branch(
+ name=name,
+ current=name == info.branch,
+ upstream=upstream,
+ committed_at=int(stamp) if stamp.isdigit() else 0,
+ worktree=str(Path(tree)) if tree else "",
+ )
+ )
+ remote_refs = _run(
+ ["for-each-ref", f"--count={_MAX_BRANCHES}", "--format=%(refname:short)", "refs/remotes"],
+ root,
+ )
+ if remote_refs.returncode == 0:
+ info.remote_branches = [
+ ref
+ for ref in remote_refs.stdout.split()
+ if ref and not ref.endswith("/HEAD") and "/" in ref
+ ]
+ remotes = _run(["remote"], root)
+ if remotes.returncode == 0:
+ info.remotes = remotes.stdout.split()
+
+ trees = _run(["worktree", "list", "--porcelain"], root)
+ if trees.returncode == 0:
+ info.worktrees = _parse_worktrees(trees.stdout, root)
+ main = next((tree for tree in info.worktrees if tree.main), None)
+ info.main_root = main.path if main else str(root)
+ info.is_worktree = main is not None and not _same_path(main.path, root)
+ info.default_branch = _default_branch(root, info.branches, info.branch)
+ info.suggested_branch = suggest_branch_name(root)
+ info.worktree_dir = str(worktree_path(Path(info.main_root), info.suggested_branch))
+ return info
+
+
+# ------------------------------------------------------------------ naming
+
+
+def suggest_branch_name(root: Path | None = None) -> str:
+ """A readable, free branch name such as ``agent/brave-river-1a2f``."""
+ for _ in range(20):
+ words = f"{secrets.choice(_ADJECTIVES)}-{secrets.choice(_NOUNS)}"
+ name = f"{BRANCH_PREFIX}{words}-{secrets.token_hex(2)}"
+ if root is None or not _branch_exists(root, name):
+ return name
+ return f"{BRANCH_PREFIX}{secrets.token_hex(4)}"
+
+
+def normalize_branch(name: str) -> str:
+ """The typed name as a branch name: trimmed, inner whitespace to dashes."""
+ return re.sub(r"\s+", "-", (name or "").strip())
+
+
+def _branch_exists(root: Path, branch: str) -> bool:
+ try:
+ result = _run(["show-ref", "--verify", "--quiet", f"refs/heads/{branch}"], root)
+ except GitError: # git missing or hung: the name counts as free
+ return False
+ return result.returncode == 0
+
+
+def _valid_branch(root: Path, branch: str) -> str:
+ branch = normalize_branch(branch)
+ if not branch:
+ raise GitError("The branch needs a name.", code="invalid")
+ if _run(["check-ref-format", "--branch", branch], root).returncode != 0:
+ raise GitError(f"{branch!r} is not a valid git branch name.", code="invalid")
+ return branch
+
+
+def worktree_path(main_root: Path, branch: str) -> Path:
+ """``<repo>/.worktrees/<branch with / as ->`` — one level, never nested."""
+ return main_root / WORKTREE_DIR / normalize_branch(branch).replace("/", "-")
+
+
+def _exclude_worktree_dir(root: Path) -> None:
+ """List ``.worktrees/`` in the repository's LOCAL exclude file, once."""
+ result = _run(["rev-parse", "--path-format=absolute", "--git-path", "info/exclude"], root)
+ if result.returncode != 0 or not result.stdout.strip():
+ return
+ exclude = Path(result.stdout.strip())
+ line = f"/{WORKTREE_DIR}/"
+ try:
+ existing = exclude.read_text(encoding="utf-8") if exclude.exists() else ""
+ if line in existing.splitlines():
+ return
+ exclude.parent.mkdir(parents=True, exist_ok=True)
+ prefix = "" if not existing or existing.endswith("\n") else "\n"
+ with exclude.open("a", encoding="utf-8") as handle:
+ handle.write(f"{prefix}{line}\n")
+ except OSError as exc:
+ # Only cosmetic: the worktree works, `git status` just lists the folder.
+ logger.warning("Agentic IDE git: could not exclude {} in {}: {}", line, exclude, exc)
+
+
+# ------------------------------------------------------------------ prepare
+
+
+@dataclass(slots=True)
+class Prepared:
+ """Where the workspace/agent should run after :func:`prepare`."""
+
+ folder: str
+ branch: str = ""
+ created: bool = False
+ message: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+def init_repository(folder: str | Path) -> Prepared:
+ """``git init`` on ``main`` plus an EMPTY first commit, so branches work at once.
+
+ Only an empty commit — the user's files are never committed on their
+ behalf (a folder may hold secrets that belong in ``.gitignore`` first).
+ """
+ path = _folder(folder)
+ if repo_root(path) is not None:
+ raise GitError(f"{path.name} is already inside a git repository.", code="exists")
+ result = _run(["init", "--initial-branch=main"], path)
+ if result.returncode != 0: # git older than 2.28
+ _ok(["init"], path, what="create the repository")
+ _ok(["symbolic-ref", "HEAD", "refs/heads/main"], path, what="name the first branch")
+ message = ["commit", "--allow-empty", "-m", "chore: initialize repository"]
+ first = _run(message, path)
+ if first.returncode != 0:
+ # No git identity configured on this machine yet: sign only this empty
+ # root commit with a neutral local identity rather than failing the init.
+ fallback = [
+ "-c",
+ "user.name=Personal Jarvis",
+ "-c",
+ "user.email=jarvis@localhost",
+ *message,
+ ]
+ _ok(fallback, path, what="create the first commit")
+ logger.info("Agentic IDE git: initialized {}", path)
+ return Prepared(
+ folder=str(path),
+ branch="main",
+ created=True,
+ message="Initialized a new repository on main.",
+ )
+
+
+def _sub_folder(source: Path, root: Path, target: Path) -> Path:
+ """The same place inside ``target`` that ``source`` has inside ``root``."""
+ try:
+ relative = Path(os.path.relpath(source.resolve(), root.resolve()))
+ except ValueError: # different drives on Windows: use the worktree root
+ return target
+ if not relative.parts or relative.parts[0] == ".." or str(relative) == ".":
+ return target
+ candidate = target / relative
+ return candidate if candidate.is_dir() else target
+
+
+def _require_commit(root: Path) -> None:
+ if _run(["rev-parse", "--verify", "--quiet", "HEAD"], root).returncode != 0:
+ raise GitError(
+ "This repository has no commit yet, so there is nothing to branch from. "
+ "Make a first commit, then try again.",
+ code="unborn",
+ )
+
+
+def prepare(folder: str | Path, mode: PrepareMode, *, branch: str = "", base: str = "") -> Prepared:
+ """Do the git half of opening a workspace/agent in ``folder``; say where to run it."""
+ path = _folder(folder)
+ if mode == "current":
+ root = repo_root(path)
+ current = inspect(path).branch if root is not None else ""
+ return Prepared(folder=str(path), branch=current)
+ if mode == "init":
+ return init_repository(path)
+
+ root = repo_root(path)
+ if root is None:
+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")
+
+ if mode == "open_worktree":
+ # `branch` names the worktree's branch, or `base` its path.
+ info = inspect(root)
+ wanted = normalize_branch(branch)
+ for tree in info.worktrees:
+ if (wanted and tree.branch == wanted) or (base and _same_path(tree.path, base)):
+ if tree.prunable or not Path(tree.path).is_dir():
+ raise GitError(
+ f"The worktree {tree.path} no longer exists — prune it.", code="prunable"
+ )
+ target = Path(tree.path)
+ return Prepared(folder=str(_sub_folder(path, root, target)), branch=tree.branch)
+ raise GitError("That worktree does not exist.", code="not_found")
+
+ name = _valid_branch(root, branch or suggest_branch_name(root))
+ base_ref = (base or "").strip()
+ if (
+ base_ref
+ and _run(["rev-parse", "--verify", "--quiet", f"{base_ref}^{{commit}}"], root).returncode
+ != 0
+ ):
+ raise GitError(f"There is no branch or commit called {base_ref!r}.", code="invalid")
+
+ if mode == "switch_branch":
+ _ok(["switch", name], root, what=f"switch to {name}")
+ return Prepared(folder=str(path), branch=name, message=f"Switched to {name}.")
+
+ if mode == "new_branch":
+ if _branch_exists(root, name):
+ _ok(["switch", name], root, what=f"switch to {name}")
+ return Prepared(
+ folder=str(path), branch=name, message=f"Switched to the existing branch {name}."
+ )
+ _require_commit(root)
+ _ok(["switch", "-c", name, *([base_ref] if base_ref else [])], root, what=f"create {name}")
+ return Prepared(
+ folder=str(path), branch=name, created=True, message=f"Created and switched to {name}."
+ )
+
+ if mode == "new_worktree":
+ _require_commit(root)
+ info = inspect(root)
+ main_root = Path(info.main_root or root)
+ existing = next((b for b in info.branches if b.name == name), None)
+ if existing and existing.worktree:
+ # Already checked out somewhere: open that checkout instead of failing.
+ target = Path(existing.worktree)
+ return Prepared(
+ folder=str(_sub_folder(path, root, target)),
+ branch=name,
+ message=f"{name} is already checked out in {target} — opened that.",
+ )
+ target = worktree_path(main_root, name)
+ if target.exists():
+ raise GitError(
+ f"The folder {target} already exists — pick another name.", code="exists"
+ )
+ _exclude_worktree_dir(main_root)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if existing:
+ args = ["worktree", "add", str(target), name]
+ else:
+ args = ["worktree", "add", "-b", name, str(target), base_ref or "HEAD"]
+ _ok(args, main_root, what="create the worktree")
+ logger.info("Agentic IDE git: created worktree {} on {}", target, name)
+ return Prepared(
+ folder=str(_sub_folder(path, root, target)),
+ branch=name,
+ created=True,
+ message=f"Created a worktree for {name}.",
+ )
+ raise GitError(f"Unknown git option {mode!r}.", code="invalid")
+
+
+# ------------------------------------------------------------------- finish
+
+
+def commit_all(folder: str | Path, message: str) -> str:
+ """Stage everything (respecting ``.gitignore``) and commit it. Returns the short sha."""
+ path = _folder(folder)
+ root = repo_root(path)
+ if root is None:
+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")
+ text = (message or "").strip()
+ if not text:
+ raise GitError("The commit needs a message.", code="invalid")
+ _ok(["add", "--all"], root, what="stage the changes")
+ if _run(["diff", "--cached", "--quiet"], root).returncode == 0:
+ raise GitError("There is nothing to commit.", code="clean")
+ _ok(["commit", "-m", text], root, what="commit")
+ return _ok(["rev-parse", "--short", "HEAD"], root).strip()
+
+
+def push(folder: str | Path) -> str:
+ """Push the current branch, setting its upstream on the first push."""
+ path = _folder(folder)
+ info = inspect(path)
+ if not info.is_repo:
+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")
+ if info.detached or not info.branch:
+ raise GitError("Check out a branch before pushing.", code="detached")
+ root = Path(info.root)
+ if info.upstream:
+ _ok(["push"], root, timeout=_NETWORK_TIMEOUT_S, what="push")
+ return info.upstream
+ if not info.remotes:
+ raise GitError("This repository has no remote to push to.", code="no_remote")
+ remote = "origin" if "origin" in info.remotes else info.remotes[0]
+ _ok(
+ ["push", "--set-upstream", remote, info.branch],
+ root,
+ timeout=_NETWORK_TIMEOUT_S,
+ what="push",
+ )
+ return f"{remote}/{info.branch}"
+
+
+def fetch(folder: str | Path) -> None:
+ path = _folder(folder)
+ root = repo_root(path)
+ if root is None:
+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")
+ _ok(["fetch", "--all", "--prune"], root, timeout=_NETWORK_TIMEOUT_S, what="fetch")
+
+
+def create_pull_request(folder: str | Path, *, title: str = "", draft: bool = False) -> str:
+ """Push if needed, then open a PR with the GitHub CLI. Returns its URL."""
+ if not gh_available():
+ raise GitError(
+ "Install the GitHub CLI (gh) to open pull requests from here.", code="missing"
+ )
+ path = _folder(folder)
+ info = inspect(path)
+ if not info.is_repo or not info.branch:
+ raise GitError("Check out a branch before opening a pull request.", code="detached")
+ if info.branch == info.default_branch:
+ raise GitError(
+ f"You are on {info.branch} itself — open the PR from a feature branch.", code="invalid"
+ )
+ if not info.upstream or info.ahead:
+ push(path)
+ args = ["pr", "create", "--base", info.default_branch, "--head", info.branch]
+ args += ["--title", title.strip(), "--body", ""] if title.strip() else ["--fill"]
+ if draft:
+ args.append("--draft")
+ result = _run(args, Path(info.root), timeout=_NETWORK_TIMEOUT_S, program="gh")
+ if result.returncode != 0:
+ raise GitError(f"The pull request could not be opened: {_reason(result)}")
+ urls = re.findall(r"https?://\S+", result.stdout)
+ return urls[-1] if urls else result.stdout.strip()
+
+
+def merge_back(folder: str | Path, *, into: str = "") -> str:
+ """Merge the branch checked out in ``folder`` into ``into`` (default branch).
+
+ Runs in the checkout where ``into`` is checked out, which must have no
+ uncommitted changes. A conflicting merge is aborted, never left half-done.
+ """
+ path = _folder(folder)
+ info = inspect(path)
+ if not info.is_repo or not info.branch:
+ raise GitError("Check out a branch before merging it back.", code="detached")
+ if info.staged or info.unstaged or info.conflicted:
+ raise GitError("Commit this branch's changes first, then merge it back.", code="dirty")
+ target = (into or info.default_branch).strip()
+ if not target or target == info.branch:
+ raise GitError("Pick a different branch to merge into.", code="invalid")
+ holder = next((tree for tree in info.worktrees if tree.branch == target), None)
+ if holder is None:
+ raise GitError(
+ f"{target} is not checked out anywhere. Check it out in the main folder first.",
+ code="not_checked_out",
+ )
+ where = Path(holder.path)
+ clean = _run(["status", "--porcelain", "--untracked-files=no"], where)
+ if clean.returncode != 0 or clean.stdout.strip():
+ raise GitError(
+ f"{where} has uncommitted changes on {target} — commit them first.", code="dirty"
+ )
+ result = _run(["merge", "--no-ff", "--no-edit", info.branch], where)
+ if result.returncode != 0:
+ conflicts = _run(["diff", "--name-only", "--diff-filter=U"], where).stdout.split()
+ _run(["merge", "--abort"], where)
+ if conflicts:
+ shown = ", ".join(conflicts[:5]) + (" …" if len(conflicts) > 5 else "")
+ raise GitError(
+ f"Merging {info.branch} into {target} conflicts in {shown}. Nothing was changed — "
+ "ask the agent to rebase onto the target branch, then merge again.",
+ code="conflict",
+ )
+ raise GitError(f"Git could not merge: {_reason(result)}")
+ return _ok(["rev-parse", "--short", "HEAD"], where).strip()
+
+
+def remove_worktree(
+ folder: str | Path, worktree: str | Path, *, force: bool = False, delete_branch: bool = False
+) -> str:
+ """Remove a linked worktree of ``folder``'s repository. Returns a summary.
+
+ Refuses the main checkout. Uncommitted work raises ``code="dirty"`` unless
+ ``force`` — the UI asks a second, explicit question first. The branch is
+ deleted only when asked AND fully merged (``git branch -d``, never ``-D``).
+ """
+ path = _folder(folder)
+ info = inspect(path)
+ if not info.is_repo:
+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")
+ tree = next((entry for entry in info.worktrees if _same_path(entry.path, worktree)), None)
+ if tree is None:
+ raise GitError("That worktree does not belong to this repository.", code="not_found")
+ if tree.main:
+ raise GitError("The main checkout cannot be removed.", code="invalid")
+ main_root = Path(info.main_root)
+ if Path(tree.path).is_dir() and not force:
+ dirty = _run(["status", "--porcelain"], Path(tree.path))
+ if dirty.returncode == 0 and dirty.stdout.strip():
+ count = len(dirty.stdout.strip().splitlines())
+ plural = "s" if count != 1 else ""
+ raise GitError(
+ f"{Path(tree.path).name} has {count} uncommitted change{plural}. Remove it anyway?",
+ code="dirty",
+ )
+ args = ["worktree", "remove", *(["--force"] if force else []), tree.path]
+ _ok(args, main_root, what="remove the worktree")
+ summary = f"Removed {Path(tree.path).name}."
+ if delete_branch and tree.branch:
+ result = _run(["branch", "-d", tree.branch], main_root)
+ if result.returncode == 0:
+ summary += f" Deleted branch {tree.branch}."
+ else:
+ summary += f" Kept branch {tree.branch} — it is not merged yet."
+ logger.info("Agentic IDE git: {}", summary)
+ return summary
+
+
+def prune_worktrees(folder: str | Path) -> None:
+ """Forget worktrees whose folders were deleted by hand."""
+ path = _folder(folder)
+ root = repo_root(path)
+ if root is None:
+ raise GitError(f"{path.name} is not a git repository.", code="not_repo")
+ _ok(["worktree", "prune"], root, what="prune worktrees")
+
+
+def worktree_in_use(worktree: str | Path, open_folders: list[str]) -> bool:
+ """True when an open workspace runs inside ``worktree`` (its files may be locked)."""
+ target = Path(worktree)
+ return any(_inside(Path(folder), target) for folder in open_folders if folder)
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index 47e32e8853..44908908d8 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -2384,10 +2384,19 @@ class Registry:
raise SessionError(f"Cannot open {root}: {exc}") from exc
if project_id:
+ # Local: git is needed only for this one check.
+ from .git_ops import same_repository
+
project = await asyncio.to_thread(library.get_project, project_id)
if project is None and project_id != library.project_id_for(root):
raise SessionError("That project does not exist.")
- if project and library.project_id_for(root) != library.project_id_for(project.path):
+ if (
+ project
+ and library.project_id_for(root) != library.project_id_for(project.path)
+ # A git worktree of the project's repository belongs to it
+ # too: that is how a workspace gets a checkout of its own.
+ and not await asyncio.to_thread(same_repository, root, project.path)
+ ):
raise SessionError("The workspace folder must belong to its project.")
unknown = {
diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.py
new file mode 100644
index 0000000000..1e9012aa8d
--- /dev/null
+++ b/jarvis/ui/web/agentic_ide_git_routes.py
@@ -0,0 +1,159 @@
+"""REST routes for the Agentic IDE's Git panel.
+
+Endpoints (all under ``/api/agentic-ide/git``)::
+
+ GET /inspect Branch, changes, ahead/behind, branches, worktrees
+ POST /prepare Git half of opening a workspace or an agent
+ POST /commit Stage everything and commit
+ POST /push Push the current branch (sets upstream once)
+ POST /fetch Fetch every remote
+ POST /pull-request Open a PR with the GitHub CLI
+ POST /merge Merge a branch back into its target
+ POST /worktrees/remove Remove a linked worktree (asks again when dirty)
+ POST /worktrees/prune Forget worktrees deleted by hand
+
+Every route takes the folder it works on — a workspace folder, a project path
+or a worktree — and runs git in the anyio threadpool (plain ``def`` handlers),
+never on the event loop. Loopback-only like the rest of the IDE API.
+
+A failed git call answers 422 with ``{"detail": {"message", "code"}}`` so the
+UI can offer the follow-up it has for that code (``dirty`` → "remove anyway?").
+"""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, HTTPException, Query
+from pydantic import BaseModel, Field
+
+from jarvis.agentic_ide import git_ops
+from jarvis.agentic_ide.git_ops import GitError, PrepareMode
+from jarvis.agentic_ide.session import get_registry
+
+router = APIRouter(prefix="/api/agentic-ide/git", tags=["agentic-ide-git"])
+
+
+def _fail(exc: GitError) -> HTTPException:
+ return HTTPException(status_code=422, detail={"message": str(exc), "code": exc.code})
+
+
+class FolderRequest(BaseModel):
+ folder: str = Field(..., min_length=1, description="Folder inside the repository")
+
+
+class PrepareRequest(FolderRequest):
+ mode: PrepareMode = "current"
+ branch: str = Field("", max_length=200)
+ base: str = Field("", max_length=400, description="Base branch/commit, or worktree path")
+
+
+class CommitRequest(FolderRequest):
+ message: str = Field(..., min_length=1, max_length=5000)
+
+
+class PullRequestRequest(FolderRequest):
+ title: str = Field("", max_length=300)
+ draft: bool = False
+
+
+class MergeRequest(FolderRequest):
+ into: str = Field("", max_length=200, description="Target branch; default branch if empty")
+
+
+class RemoveWorktreeRequest(FolderRequest):
+ worktree: str = Field(..., min_length=1)
+ force: bool = False
+ delete_branch: bool = False
+
+
[email protected]("/inspect", summary="Git status, branches and worktrees of a folder")
+def inspect_folder(folder: str = Query(..., min_length=1)) -> dict:
+ try:
+ return git_ops.inspect(folder).to_dict()
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/prepare", summary="Prepare a checkout for a new workspace or agent")
+def prepare_checkout(req: PrepareRequest) -> dict:
+ try:
+ return git_ops.prepare(req.folder, req.mode, branch=req.branch, base=req.base).to_dict()
+ except GitError as exc:
+ raise _fail(exc) from exc
+
+
[email protected]("/commit", summary="Stage every change and commit it")
+def commit_changes(req: CommitRequest) -> dict:
+ try:
+ sha = git_ops.commit_all(req.folder, req.message)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return {"ok": True, "commit": sha}
+
+
[email protected]("/push", summary="Push the current branch")
+def push_branch(req: FolderRequest) -> dict:
+ try:
+ upstream = git_ops.push(req.folder)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return {"ok": True, "upstream": upstream}
+
+
[email protected]("/fetch", summary="Fetch every remote")
+def fetch_remotes(req: FolderRequest) -> dict:
+ try:
+ git_ops.fetch(req.folder)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return {"ok": True}
+
+
[email protected]("/pull-request", summary="Open a pull request for the current branch")
+def open_pull_request(req: PullRequestRequest) -> dict:
+ try:
+ url = git_ops.create_pull_request(req.folder, title=req.title, draft=req.draft)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return {"ok": True, "url": url}
+
+
[email protected]("/merge", summary="Merge the current branch back into its target")
+def merge_branch(req: MergeRequest) -> dict:
+ try:
+ sha = git_ops.merge_back(req.folder, into=req.into)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return {"ok": True, "commit": sha}
+
+
+ "/worktrees/remove",
+ summary="Remove a linked git worktree",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+def remove_worktree(req: RemoveWorktreeRequest) -> dict:
+ open_folders = [session.folder for session in get_registry().sessions]
+ if git_ops.worktree_in_use(req.worktree, open_folders):
+ raise HTTPException(
+ status_code=422,
+ detail={
+ "message": "A workspace is still open in this worktree. Close it first.",
+ "code": "in_use",
+ },
+ )
+ try:
+ summary = git_ops.remove_worktree(
+ req.folder, req.worktree, force=req.force, delete_branch=req.delete_branch
+ )
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return {"ok": True, "message": summary}
+
+
[email protected]("/worktrees/prune", summary="Forget worktrees whose folders are gone")
+def prune_worktrees(req: FolderRequest) -> dict:
+ try:
+ git_ops.prune_worktrees(req.folder)
+ except GitError as exc:
+ raise _fail(exc) from exc
+ return {"ok": True}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.test.tsx
index c44d1d80c6..b4c15fee2b 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.test.tsx
@@ -5,7 +5,7 @@ import { WorkspaceOptionsDialog } from "./WorkspaceOptionsDialog";
afterEach(cleanup);
const setup = () => ({
open: true, onOpenChange: vi.fn(), workspace: "Installer", count: 6, busy: false, canAdd: true,
- maxPanes: 16, onAdd: vi.fn(), onBalance: vi.fn(), onRename: vi.fn(), onClose: vi.fn(),
+ maxPanes: 16, onAdd: vi.fn(), onBalance: vi.fn(), onRename: vi.fn(), onClose: vi.fn(), onGit: vi.fn(),
appearance: null, onAppearance: vi.fn(),
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.tsx
index 1aa84b0cd3..f6ef4404df 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceOptionsDialog.tsx
@@ -1,5 +1,5 @@
import * as Dialog from "@radix-ui/react-dialog";
-import { Columns2, X } from "lucide-react";
+import { Columns2, GitBranch, X } from "lucide-react";
import { cn } from "@/lib/utils";
interface Props {
@@ -15,6 +15,8 @@ interface Props {
onBalance: () => void;
onRename: () => void;
onClose: () => void;
+ /** Opens the workspace's Git panel. */
+ onGit: () => void;
appearance: "light" | "dark" | null;
onAppearance: (appearance: "light" | "dark" | null) => void;
}
@@ -48,6 +50,7 @@ export function WorkspaceOptionsDialog(props: Props) {
</section>
<div className="border-t border-border pt-2">
<button type="button" disabled={props.busy || !props.canAdd || props.count >= props.maxPanes} onClick={() => choose(props.onAdd)} className="block w-full rounded-lg px-2 py-2.5 text-left text-sm hover:bg-muted disabled:opacity-40">Add coding agent</button>
+ <button type="button" disabled={props.busy} onClick={() => choose(props.onGit)} className="flex w-full items-center gap-2 rounded-lg px-2 py-2.5 text-left text-sm hover:bg-muted disabled:opacity-40"><GitBranch className="h-4 w-4 text-muted-foreground" />Git: branches, commits, worktrees</button>
<button type="button" disabled={props.busy} onClick={() => choose(props.onRename)} className="block w-full rounded-lg px-2 py-2.5 text-left text-sm hover:bg-muted disabled:opacity-40">Rename workspace</button>
<button type="button" disabled={props.busy} onClick={() => choose(props.onClose)} className="block w-full rounded-lg px-2 py-2.5 text-left text-sm text-destructive hover:bg-muted disabled:opacity-40">Close workspace</button>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/git/GitCheckoutPicker.tsx b/jarvis/ui/web/frontend/src/components/agentic/git/GitCheckoutPicker.tsx
new file mode 100644
index 0000000000..7a1440fd8a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/git/GitCheckoutPicker.tsx
@@ -0,0 +1,165 @@
+import { useEffect, useMemo, useState } from "react";
+import { Dices, FolderGit2, FolderTree, GitBranch, GitBranchPlus, GitFork, Loader2, Sparkles } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { folderName, inspectGit, type GitPlan, type GitPrepareMode, type GitRepoInfo } from "@/lib/gitApi";
+import { GitStatusLine } from "./GitStatusLine";
+
+interface Props {
+ /** The folder the workspace/agent would open in. */
+ folder: string;
+ value: GitPlan;
+ onChange: (plan: GitPlan) => void;
+ disabled?: boolean;
+ /**
+ * `workspace`: every option, including changing the branch in place.
+ * `agent`: share the workspace's checkout, or give the agent a worktree of
+ * its own — which opens as its own workspace tab.
+ */
+ context: "workspace" | "agent";
+ /** Receives the inspection, so the caller can label its submit button. */
+ onInfo?: (info: GitRepoInfo | null) => void;
+}
+
+interface Option { mode: GitPrepareMode; title: string; hint: string; Icon: typeof GitBranch; recommended?: boolean }
+
+/** A fresh suggestion that is not the one already offered. */
+function reroll(current: string): string {
+ const adjectives = ["amber", "brave", "calm", "cosmic", "eager", "golden", "keen", "lucky", "nimble", "swift", "vivid"];
+ const nouns = ["comet", "delta", "ember", "falcon", "harbor", "meadow", "orbit", "otter", "river", "summit", "willow"];
+ for (;;) {
+ const pick = (list: string[]) => list[Math.floor(Math.random() * list.length)];
+ const hex = Math.floor(Math.random() * 0xffff).toString(16).padStart(4, "0");
+ const name = `agent/${pick(adjectives)}-${pick(nouns)}-${hex}`;
+ if (name !== current) return name;
+ }
+}
+
+/**
+ * The git half of "New workspace" and "Add coding agent": keep the checkout,
+ * branch, or give the agents a worktree of their own. Reads the folder once
+ * and shows where things stand (branch, changes, ahead/behind) beside the choice.
+ */
+export function GitCheckoutPicker({ folder, value, onChange, disabled, context, onInfo }: Props) {
+ const [info, setInfo] = useState<GitRepoInfo | null>(null);
+ const [error, setError] = useState("");
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ setLoading(true); setError("");
+ inspectGit(folder, controller.signal)
+ .then((next) => { setInfo(next); onInfo?.(next); })
+ .catch((reason: Error) => { if (!controller.signal.aborted) { setInfo(null); onInfo?.(null); setError(reason.message); } })
+ .finally(() => { if (!controller.signal.aborted) setLoading(false); });
+ return () => controller.abort();
+ // onInfo is a callback prop; re-inspecting when it changes identity would loop.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [folder]);
+
+ const linked = useMemo(() => (info?.worktrees ?? []).filter((tree) => !tree.main && !tree.prunable && !tree.current), [info]);
+ const switchable = useMemo(() => (info?.branches ?? []).filter((branch) => !branch.current && !branch.worktree), [info]);
+ const bases = useMemo(() => {
+ if (!info) return [];
+ const local = info.branches.map((branch) => branch.name);
+ const ordered = [info.branch, info.default_branch, ...local].filter(Boolean);
+ return [...new Set([...ordered, ...info.remote_branches])];
+ }, [info]);
+
+ const options: Option[] = !info?.is_repo
+ ? [
+ { mode: "current", title: "Without git", hint: "Open the folder as it is", Icon: FolderTree, recommended: true },
+ { mode: "init", title: "Initialize git", hint: "New repository on main, ready for branches", Icon: Sparkles },
+ ]
+ : [
+ context === "agent"
+ ? { mode: "current", title: "Share this checkout", hint: `Same folder as the other agents${info.branch ? ` · ${info.branch}` : ""}`, Icon: FolderTree, recommended: true }
+ : { mode: "current", title: "Current checkout", hint: info.branch ? `Work on ${info.branch} in the project folder` : "Work in the project folder", Icon: FolderTree, recommended: true },
+ { mode: "new_worktree", title: "New worktree", hint: context === "agent" ? "Own folder and branch, opens as its own tab" : "Own folder and branch, agents never collide", Icon: GitFork },
+ ...(context === "workspace" ? [
+ { mode: "new_branch" as const, title: "New branch", hint: "Branch off here, in the project folder", Icon: GitBranchPlus },
+ ...(switchable.length ? [{ mode: "switch_branch" as const, title: "Existing branch", hint: "Check out another branch here", Icon: GitBranch }] : []),
+ ] : []),
+ ...(linked.length ? [{ mode: "open_worktree" as const, title: "Existing worktree", hint: "Open a worktree that is already there", Icon: FolderGit2 }] : []),
+ ];
+
+ const choose = (mode: GitPrepareMode) => {
+ if (mode === value.mode) return;
+ if (mode === "new_worktree" || mode === "new_branch") onChange({ mode, branch: info?.suggested_branch || reroll(""), base: info?.branch ?? "" });
+ else if (mode === "switch_branch") onChange({ mode, branch: switchable[0]?.name ?? "", base: "" });
+ else if (mode === "open_worktree") onChange({ mode, branch: linked[0]?.branch ?? "", base: linked[0]?.path ?? "" });
+ else onChange({ mode, branch: "", base: "" });
+ };
+
+ const field = "h-9 w-full rounded-lg border border-input bg-background/60 px-3 text-sm text-foreground outline-none focus:border-ring focus:ring-1 focus:ring-ring/30 disabled:opacity-50";
+ const creating = value.mode === "new_worktree" || value.mode === "new_branch";
+ const preview = value.mode === "new_worktree" && info?.main_root
+ ? `${folderName(info.main_root)}/.worktrees/${value.branch.trim().replace(/\s+/g, "-").replace(/\//g, "-") || "…"}` : "";
+
+ return <section aria-label="Git" data-testid="git-checkout-picker" className="space-y-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="text-xs font-medium text-muted-foreground">Git</span>
+ {loading ? <span className="flex items-center gap-1.5 text-xs text-muted-foreground"><Loader2 className="h-3 w-3 animate-spin" />Reading repository…</span>
+ : info?.is_repo ? <GitStatusLine info={info} /> : null}
+ </div>
+ {error && <p role="alert" className="text-xs text-destructive">{error}</p>}
+ {!loading && info && !info.git_available && <p className="rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
+ Git is not installed on this computer. Install it from git-scm.com to use branches and worktrees.</p>}
+
+ {!loading && info?.git_available && <div className="grid grid-cols-1 gap-2 sm:grid-cols-2" role="radiogroup" aria-label="Git checkout">
+ {options.map((option) => {
+ const checked = value.mode === option.mode;
+ return <button key={option.mode} type="button" role="radio" aria-checked={checked} disabled={disabled}
+ onClick={() => choose(option.mode)}
+ className={cn("flex items-start gap-2.5 rounded-lg border px-3 py-2.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
+ checked ? "border-primary bg-primary/10 ring-1 ring-primary/40" : "border-border bg-background hover:bg-muted")}>
+ <option.Icon className={cn("mt-0.5 h-4 w-4 shrink-0", checked ? "text-primary" : "text-muted-foreground")} aria-hidden />
+ <span className="min-w-0">
+ <span className="flex items-center gap-1.5 text-sm font-medium text-foreground">{option.title}
+ {option.recommended && <span className="rounded-full bg-muted px-1.5 py-px text-[10px] font-medium text-muted-foreground">Recommended</span>}</span>
+ <span className="mt-0.5 block text-xs leading-snug text-muted-foreground">{option.hint}</span>
+ </span>
+ </button>;
+ })}
+ </div>}
+
+ {info?.is_repo && creating && <div className="grid grid-cols-1 gap-2 rounded-xl border border-border bg-muted/30 p-3 sm:grid-cols-2">
+ <label className="block text-xs text-muted-foreground">Branch name
+ <span className="mt-1 flex gap-1.5">
+ <input value={value.branch} disabled={disabled} spellCheck={false} aria-label="Branch name"
+ onChange={(event) => onChange({ ...value, branch: event.target.value })}
+ placeholder={info.suggested_branch} className={cn(field, "font-mono text-xs")} />
+ <button type="button" disabled={disabled} aria-label="Suggest another name" title="Suggest another name"
+ onClick={() => onChange({ ...value, branch: reroll(value.branch) })}
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50"><Dices className="h-4 w-4" /></button>
+ </span>
+ </label>
+ <label className="block text-xs text-muted-foreground">Based on
+ <select value={value.base} disabled={disabled || info.unborn} aria-label="Base branch"
+ onChange={(event) => onChange({ ...value, base: event.target.value })} className={cn(field, "mt-1")}>
+ {bases.map((name) => <option key={name} value={name}>{name}{name === info.branch ? " (current)" : name === info.default_branch ? " (default)" : ""}</option>)}
+ </select>
+ </label>
+ <p className="text-xs text-muted-foreground sm:col-span-2">
+ {info.unborn ? "This repository has no commit yet — make a first commit before branching."
+ : value.mode === "new_worktree" ? <>Creates <span className="font-mono text-foreground">{preview}</span>. Only committed work is copied; an existing branch is reused.</>
+ : info.dirty ? "Your uncommitted changes move along to the new branch." : "The project folder switches to the new branch for every agent in it."}
+ </p>
+ </div>}
+
+ {info?.is_repo && value.mode === "switch_branch" && <label className="block text-xs text-muted-foreground">Branch
+ <select value={value.branch} disabled={disabled} aria-label="Existing branch" onChange={(event) => onChange({ ...value, branch: event.target.value })} className={cn(field, "mt-1")}>
+ {switchable.map((branch) => <option key={branch.name} value={branch.name}>{branch.name}</option>)}
+ </select>
+ </label>}
+
+ {info?.is_repo && value.mode === "open_worktree" && <label className="block text-xs text-muted-foreground">Worktree
+ <select value={value.base} disabled={disabled} aria-label="Existing worktree"
+ onChange={(event) => { const tree = linked.find((entry) => entry.path === event.target.value); onChange({ ...value, base: event.target.value, branch: tree?.branch ?? "" }); }}
+ className={cn(field, "mt-1")}>
+ {linked.map((tree) => <option key={tree.path} value={tree.path}>{folderName(tree.path)} · {tree.branch || "detached"}</option>)}
+ </select>
+ </label>}
+
+ {value.mode === "init" && <p className="text-xs text-muted-foreground">Creates a repository on <span className="font-mono">main</span> with an empty first commit. Your files are not committed — you decide what goes in.</p>}
+ </section>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/git/GitPanelDialog.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/git/GitPanelDialog.test.tsx
new file mode 100644
index 0000000000..bccbe643f4
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/git/GitPanelDialog.test.tsx
@@ -0,0 +1,103 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { GitPanelDialog } from "./GitPanelDialog";
+import { GitCheckoutPicker } from "./GitCheckoutPicker";
+import { GitApiError, KEEP_CHECKOUT, type GitRepoInfo } from "@/lib/gitApi";
+
+const git = vi.hoisted(() => ({
+ inspectGit: vi.fn(), commitAll: vi.fn(), pushBranch: vi.fn(), fetchRemotes: vi.fn(), openPullRequest: vi.fn(),
+ mergeBack: vi.fn(), removeWorktree: vi.fn(), pruneWorktrees: vi.fn(), prepareGit: vi.fn(),
+}));
+vi.mock("@/lib/gitApi", async (importOriginal) => ({ ...(await importOriginal<object>()), ...git }));
+vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn() }));
+
+const worktree = { path: "/code/app/.worktrees/agent-x", branch: "agent/x", head: "def", main: false, detached: false, locked: false, prunable: false, current: false };
+const info: GitRepoInfo = {
+ folder: "/code/app", git_available: true, gh_available: true, is_repo: true, root: "/code/app", main_root: "/code/app",
+ is_worktree: false, branch: "feature/login", detached: false, unborn: false, head: "abc", upstream: "origin/feature/login",
+ ahead: 2, behind: 1, staged: 0, unstaged: 1, untracked: 1, conflicted: 0, insertions: 12, deletions: 3, dirty: true,
+ default_branch: "main", remotes: ["origin"],
+ branches: [
+ { name: "feature/login", current: true, upstream: "origin/feature/login", committed_at: 0, worktree: "/code/app" },
+ { name: "main", current: false, upstream: "origin/main", committed_at: 0, worktree: "" },
+ { name: "agent/x", current: false, upstream: "", committed_at: 0, worktree: worktree.path },
+ ],
+ remote_branches: ["origin/main"],
+ worktrees: [{ ...worktree, path: "/code/app", branch: "feature/login", main: true, current: true }, worktree],
+ changes: [{ path: "src/app.ts", index: ".", worktree: "M" }, { path: "notes.md", index: "?", worktree: "?" }],
+ suggested_branch: "agent/brave-river-0001", worktree_dir: "/code/app/.worktrees/agent-brave-river-0001",
+};
+
+beforeEach(() => { vi.clearAllMocks(); git.inspectGit.mockResolvedValue(info); });
+afterEach(cleanup);
+
+function panel(overrides: Partial<Parameters<typeof GitPanelDialog>[0]> = {}) {
+ return render(<GitPanelDialog open onOpenChange={vi.fn()} folder="/code/app" workspace="App"
+ onOpenWorktree={vi.fn()} onNewWorktree={vi.fn()} {...overrides} />);
+}
+
+describe("GitPanelDialog", () => {
+ it("shows branch, changes and ahead/behind", async () => {
+ panel();
+ expect(await screen.findByText("feature/login", { selector: "span" })).toBeTruthy();
+ expect(screen.getByText("2 changes")).toBeTruthy();
+ expect(screen.getByText("src/app.ts")).toBeTruthy();
+ expect(screen.getByText("+12")).toBeTruthy();
+ });
+
+ it("commits everything with the typed message", async () => {
+ git.commitAll.mockResolvedValue({ commit: "1234abc" });
+ panel();
+ fireEvent.change(await screen.findByLabelText("Commit message"), { target: { value: "feat: login" } });
+ fireEvent.click(screen.getByRole("button", { name: "Commit all" }));
+ await waitFor(() => expect(git.commitAll).toHaveBeenCalledWith("/code/app", "feat: login"));
+ expect(await screen.findByText("Committed 1234abc.")).toBeTruthy();
+ });
+
+ it("opens a draft pull request and offers its link", async () => {
+ git.openPullRequest.mockResolvedValue({ url: "https://example.invalid/pr/1" });
+ panel();
+ fireEvent.click(await screen.findByLabelText("Open pull requests as drafts"));
+ fireEvent.click(screen.getByRole("button", { name: "Pull request" }));
+ await waitFor(() => expect(git.openPullRequest).toHaveBeenCalledWith("/code/app", { draft: true }));
+ expect(await screen.findByRole("button", { name: "Open link" })).toBeTruthy();
+ });
+
+ it("asks a second time before removing a worktree with uncommitted work", async () => {
+ git.removeWorktree.mockRejectedValueOnce(new GitApiError("agent-x has 1 uncommitted change. Remove anyway?", "dirty"))
+ .mockResolvedValueOnce({ message: "Removed agent-x." });
+ panel();
+ fireEvent.click(await screen.findByRole("button", { name: "Remove agent-x" }));
+ fireEvent.click(screen.getByRole("button", { name: "Remove worktree" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Remove anyway" }));
+ await waitFor(() => expect(git.removeWorktree).toHaveBeenLastCalledWith("/code/app", worktree.path, { force: true, deleteBranch: false }));
+ expect(await screen.findByText("Removed agent-x.")).toBeTruthy();
+ });
+
+ it("offers to initialize a folder that is not a repository", async () => {
+ git.inspectGit.mockResolvedValue({ ...info, is_repo: false });
+ git.prepareGit.mockResolvedValue({ folder: "/code/app", branch: "main", created: true, message: "" });
+ panel();
+ fireEvent.click(await screen.findByRole("button", { name: "Initialize git" }));
+ await waitFor(() => expect(git.prepareGit).toHaveBeenCalledWith("/code/app", { mode: "init", branch: "", base: "" }));
+ });
+});
+
+describe("GitCheckoutPicker", () => {
+ it("offers an agent its own worktree but never an in-place branch switch", async () => {
+ const onChange = vi.fn();
+ render(<GitCheckoutPicker folder="/code/app" value={KEEP_CHECKOUT} onChange={onChange} context="agent" />);
+ fireEvent.click(await screen.findByRole("radio", { name: /New worktree/ }));
+ expect(onChange).toHaveBeenCalledWith({ mode: "new_worktree", branch: "agent/brave-river-0001", base: "feature/login" });
+ expect(screen.queryByRole("radio", { name: /New branch/ })).toBeNull();
+ expect(screen.getByRole("radio", { name: /Existing worktree/ })).toBeTruthy();
+ });
+
+ it("offers git init for a plain folder", async () => {
+ git.inspectGit.mockResolvedValue({ ...info, is_repo: false });
+ const onChange = vi.fn();
+ render(<GitCheckoutPicker folder="/code/app" value={KEEP_CHECKOUT} onChange={onChange} context="workspace" />);
+ fireEvent.click(await screen.findByRole("radio", { name: /Initialize git/ }));
+ expect(onChange).toHaveBeenCalledWith({ mode: "init", branch: "", base: "" });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/git/GitPanelDialog.tsx b/jarvis/ui/web/frontend/src/components/agentic/git/GitPanelDialog.tsx
new file mode 100644
index 0000000000..1b9b3bcb46
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/git/GitPanelDialog.tsx
@@ -0,0 +1,226 @@
+import { useCallback, useEffect, useState } from "react";
+import * as Dialog from "@radix-ui/react-dialog";
+import {
+ CloudDownload, ExternalLink, FolderGit2, GitCommitHorizontal, GitFork, GitMerge, GitPullRequest,
+ Loader2, RefreshCw, Sparkles, Trash2, Upload, X,
+} from "lucide-react";
+import { cn } from "@/lib/utils";
+import { openExternalUrl } from "@/lib/openExternal";
+import {
+ GitApiError, commitAll, fetchRemotes, folderName, inspectGit, mergeBack, openPullRequest, prepareGit,
+ pruneWorktrees, pushBranch, removeWorktree, type GitRepoInfo, type GitWorktree,
+} from "@/lib/gitApi";
+import { GitStatusLine } from "./GitStatusLine";
+
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** The workspace folder the panel works on. */
+ folder: string;
+ workspace: string;
+ /** Open an existing worktree as a workspace tab of its own. */
+ onOpenWorktree: (tree: GitWorktree) => void;
+ /** Start the "New workspace" flow preset to a fresh worktree. */
+ onNewWorktree: () => void;
+}
+
+/** Git letters → a short, readable tag for the change list. */
+function changeTag(index: string, worktree: string): string {
+ const letter = index === "?" ? "?" : index !== "." ? index : worktree;
+ return ({ M: "modified", A: "added", D: "deleted", R: "renamed", C: "copied", U: "conflict", "?": "new" } as Record<string, string>)[letter] ?? letter;
+}
+
+type Busy = "" | "refresh" | "commit" | "push" | "fetch" | "pr" | "merge" | "prune" | "init" | `remove:${string}`;
+
+/**
+ * The workspace's Git panel: where the checkout stands, and the few actions
+ * that finish an agent's work — commit, push, pull request, merge back — plus
+ * worktree housekeeping. Every result is said in the panel itself.
+ */
+export function GitPanelDialog({ open, onOpenChange, folder, workspace, onOpenWorktree, onNewWorktree }: Props) {
+ const [info, setInfo] = useState<GitRepoInfo | null>(null);
+ const [busy, setBusy] = useState<Busy>("");
+ const [notice, setNotice] = useState<{ tone: "ok" | "error"; text: string; url?: string } | null>(null);
+ const [message, setMessage] = useState("");
+ const [draft, setDraft] = useState(false);
+ const [removing, setRemoving] = useState<{ tree: GitWorktree; deleteBranch: boolean; dirty: string } | null>(null);
+
+ const refresh = useCallback(async () => {
+ try { setInfo(await inspectGit(folder)); }
+ catch (error) { setNotice({ tone: "error", text: (error as Error).message }); }
+ }, [folder]);
+
+ useEffect(() => {
+ if (!open) return;
+ setNotice(null); setRemoving(null);
+ setBusy("refresh");
+ void refresh().finally(() => setBusy(""));
+ }, [open, refresh]);
+
+ const act = async (kind: Busy, work: () => Promise<string | { text: string; url?: string } | void>) => {
+ setBusy(kind); setNotice(null);
+ try {
+ const result = await work();
+ if (typeof result === "string") setNotice({ tone: "ok", text: result });
+ else if (result) setNotice({ tone: "ok", ...result });
+ await refresh();
+ } catch (error) {
+ setNotice({ tone: "error", text: (error as Error).message });
+ } finally { setBusy(""); }
+ };
+
+ const commit = () => act("commit", async () => {
+ const { commit: sha } = await commitAll(folder, message.trim());
+ setMessage("");
+ return `Committed ${sha}.`;
+ });
+ const push = () => act("push", async () => `Pushed to ${(await pushBranch(folder)).upstream}.`);
+ const fetchAll = () => act("fetch", async () => { await fetchRemotes(folder); return "Fetched every remote."; });
+ const pr = () => act("pr", async () => {
+ const { url } = await openPullRequest(folder, { draft });
+ return { text: draft ? "Draft pull request opened." : "Pull request opened.", url };
+ });
+ const merge = () => act("merge", async () => {
+ const { commit: sha } = await mergeBack(folder);
+ return `Merged ${info?.branch} into ${info?.default_branch} (${sha}).`;
+ });
+ const prune = () => act("prune", async () => { await pruneWorktrees(folder); return "Forgot worktrees whose folders are gone."; });
+ const init = () => act("init", async () => { await prepareGit(folder, { mode: "init", branch: "", base: "" }); return "Initialized a repository on main."; });
+ const remove = (force: boolean) => {
+ if (!removing) return;
+ const { tree, deleteBranch } = removing;
+ void act(`remove:${tree.path}`, async () => {
+ try {
+ const { message: summary } = await removeWorktree(folder, tree.path, { force, deleteBranch });
+ setRemoving(null);
+ return summary;
+ } catch (error) {
+ // Uncommitted work: ask once more, explicitly, instead of failing.
+ if (error instanceof GitApiError && error.code === "dirty") { setRemoving({ ...removing, dirty: error.message }); return; }
+ throw error;
+ }
+ });
+ };
+
+ const linked = (info?.worktrees ?? []).filter((tree) => !tree.main);
+ const prunable = linked.some((tree) => tree.prunable);
+ const onFeatureBranch = Boolean(info?.branch && info.default_branch && info.branch !== info.default_branch);
+ const button = "flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-sm hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-40";
+ const spin = (kind: Busy, Icon: typeof Upload) => busy === kind ? <Loader2 className="h-4 w-4 animate-spin" /> : <Icon className="h-4 w-4" />;
+ const locked = busy !== "";
+
+ return <Dialog.Root open={open} onOpenChange={(next) => { if (!locked || next) onOpenChange(next); }}>
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[80] bg-background/70 backdrop-blur-sm" />
+ <Dialog.Content data-testid="git-panel" aria-busy={locked}
+ className="fixed left-1/2 top-1/2 z-[90] flex max-h-[88vh] w-[min(560px,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-2xl border border-border bg-popover text-popover-foreground shadow-2xl">
+ <header className="flex items-start justify-between gap-3 border-b border-border px-6 py-4">
+ <div className="min-w-0">
+ <Dialog.Title className="text-lg font-semibold">Git</Dialog.Title>
+ <Dialog.Description className="mt-0.5 truncate text-sm text-muted-foreground" title={folder}>{workspace} · {folderName(folder)}</Dialog.Description>
+ </div>
+ <div className="flex items-center gap-1">
+ <button type="button" aria-label="Refresh" title="Refresh" disabled={locked} onClick={() => { setBusy("refresh"); void refresh().finally(() => setBusy("")); }}
+ className="rounded-lg p-2 text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-40"><RefreshCw className={cn("h-4 w-4", busy === "refresh" && "animate-spin")} /></button>
+ <Dialog.Close aria-label="Close Git panel" className="rounded-lg p-2 text-muted-foreground hover:bg-muted hover:text-foreground"><X className="h-4 w-4" /></Dialog.Close>
+ </div>
+ </header>
+
+ <div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
+ {notice && <div role={notice.tone === "error" ? "alert" : "status"}
+ className={cn("rounded-lg border px-3 py-2 text-sm", notice.tone === "error" ? "border-destructive/40 bg-destructive/10 text-destructive" : "border-border bg-muted/40")}>
+ {notice.text}
+ {notice.url && <button type="button" aria-label="Open link" onClick={() => void openExternalUrl(notice.url!)} className="ml-2 inline-flex items-center gap-1 font-medium underline underline-offset-2">Open <ExternalLink className="h-3 w-3" /></button>}
+ </div>}
+
+ {!info ? <p className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />Reading repository…</p>
+ : !info.git_available ? <p className="text-sm text-muted-foreground">Git is not installed on this computer. Install it from git-scm.com, then refresh.</p>
+ : !info.is_repo ? <div className="space-y-3">
+ <p className="text-sm text-muted-foreground">This folder is not a git repository yet. Initialize one to give agents branches and worktrees.</p>
+ <button type="button" disabled={locked} onClick={init} className={button}>{spin("init", Sparkles)}Initialize git</button>
+ </div>
+ : <>
+ <section aria-label="Status" className="space-y-2">
+ <GitStatusLine info={info} className="text-sm" />
+ {info.is_worktree && <p className="text-xs text-muted-foreground">A worktree of <span className="font-mono">{folderName(info.main_root)}</span>. Its agents work on their own branch without touching the main folder.</p>}
+ </section>
+
+ <section aria-label="Changes" className="space-y-2.5">
+ <h3 className="text-sm font-medium">Changes</h3>
+ {info.changes.length === 0 ? <p className="text-xs text-muted-foreground">Nothing uncommitted.</p>
+ : <ul className="max-h-40 space-y-0.5 overflow-y-auto rounded-lg border border-border bg-muted/30 p-2">
+ {info.changes.map((change) => <li key={`${change.path}-${change.index}${change.worktree}`} className="flex items-center gap-2 text-xs">
+ <span className={cn("w-16 shrink-0 text-[10px] uppercase tracking-wide", change.index === "U" ? "text-destructive" : "text-muted-foreground")}>{changeTag(change.index, change.worktree)}</span>
+ <span className="truncate font-mono" title={change.path}>{change.path}</span>
+ </li>)}
+ </ul>}
+ <form className="flex gap-2" onSubmit={(event) => { event.preventDefault(); void commit(); }}>
+ <input value={message} onChange={(event) => setMessage(event.target.value)} disabled={locked || !info.dirty} aria-label="Commit message"
+ placeholder={info.dirty ? "Commit message, e.g. feat: add login form" : "No changes to commit"}
+ className="h-9 min-w-0 flex-1 rounded-lg border border-input bg-background px-3 text-sm outline-none focus:border-ring focus:ring-1 focus:ring-ring/30 disabled:opacity-50" />
+ <button type="submit" disabled={locked || !info.dirty || !message.trim()} className={button}>{spin("commit", GitCommitHorizontal)}Commit all</button>
+ </form>
+ </section>
+
+ <section aria-label="Share" className="space-y-2.5">
+ <h3 className="text-sm font-medium">Share</h3>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
+ <button type="button" disabled={locked || !info.branch || info.remotes.length === 0} onClick={push} className={button}
+ title={info.remotes.length === 0 ? "This repository has no remote" : undefined}>{spin("push", Upload)}{info.upstream ? "Push" : "Publish branch"}</button>
+ <button type="button" disabled={locked || info.remotes.length === 0} onClick={fetchAll} className={button}>{spin("fetch", CloudDownload)}Fetch</button>
+ <button type="button" disabled={locked || !info.gh_available || !onFeatureBranch || info.remotes.length === 0} onClick={pr} className={button}
+ title={!info.gh_available ? "Install the GitHub CLI (gh) to open pull requests" : !onFeatureBranch ? "Switch to a feature branch first" : undefined}>{spin("pr", GitPullRequest)}Pull request</button>
+ </div>
+ <label className="flex items-center gap-2 text-xs text-muted-foreground">
+ <input type="checkbox" checked={draft} onChange={(event) => setDraft(event.target.checked)} className="accent-primary" />Open pull requests as drafts
+ </label>
+ {onFeatureBranch && <button type="button" disabled={locked || info.dirty} onClick={merge} className={cn(button, "w-full")}
+ title={info.dirty ? "Commit the changes first" : undefined}>{spin("merge", GitMerge)}Merge {info.branch} into {info.default_branch}</button>}
+ </section>
+
+ <section aria-label="Worktrees" className="space-y-2.5">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-sm font-medium">Worktrees</h3>
+ <div className="flex gap-1.5">
+ {prunable && <button type="button" disabled={locked} onClick={prune} className="rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-muted">{busy === "prune" ? "Pruning…" : "Prune missing"}</button>}
+ <button type="button" disabled={locked || info.unborn} onClick={() => { onOpenChange(false); onNewWorktree(); }}
+ className="flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium hover:bg-muted disabled:opacity-40"><GitFork className="h-3.5 w-3.5" />New worktree</button>
+ </div>
+ </div>
+ {linked.length === 0 ? <p className="text-xs text-muted-foreground">No worktrees yet. A worktree gives agents their own folder and branch, so several can change code at once.</p>
+ : <ul className="space-y-1.5">
+ {linked.map((tree) => <li key={tree.path} className="rounded-lg border border-border px-3 py-2">
+ <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 flex-1">
+ <span className="block truncate font-mono text-xs text-foreground">{tree.branch || `detached ${tree.head}`}</span>
+ <span className="block truncate text-[11px] text-muted-foreground" title={tree.path}>{folderName(tree.path)}
+ {tree.current && " · this workspace"}{tree.prunable && " · folder missing"}{tree.locked && " · locked"}</span>
+ </span>
+ {!tree.current && !tree.prunable && <button type="button" disabled={locked} onClick={() => { onOpenChange(false); onOpenWorktree(tree); }}
+ className="rounded-md px-2 py-1 text-xs hover:bg-muted">Open</button>}
+ {!tree.current && <button type="button" disabled={locked} aria-label={`Remove ${folderName(tree.path)}`}
+ onClick={() => setRemoving({ tree, deleteBranch: false, dirty: "" })}
+ className="rounded-md p-1.5 text-muted-foreground hover:bg-muted hover:text-destructive"><Trash2 className="h-3.5 w-3.5" /></button>}
+ </div>
+ {removing?.tree.path === tree.path && <div role="group" aria-label="Confirm removal" className="mt-2 space-y-2 border-t border-border pt-2">
+ <p className="text-xs text-muted-foreground">{removing.dirty || "The folder is deleted. Committed work stays on its branch."}</p>
+ {tree.branch && <label className="flex items-center gap-2 text-xs text-muted-foreground">
+ <input type="checkbox" checked={removing.deleteBranch} onChange={(event) => setRemoving({ ...removing, deleteBranch: event.target.checked })} className="accent-primary" />
+ Also delete branch <span className="font-mono">{tree.branch}</span> if it is merged</label>}
+ <div className="flex justify-end gap-2">
+ <button type="button" onClick={() => setRemoving(null)} className="rounded-md px-2.5 py-1 text-xs text-muted-foreground hover:bg-muted">Cancel</button>
+ <button type="button" disabled={locked} onClick={() => remove(Boolean(removing.dirty))}
+ className="rounded-md bg-destructive px-2.5 py-1 text-xs font-medium text-destructive-foreground disabled:opacity-50">
+ {busy === `remove:${tree.path}` ? "Removing…" : removing.dirty ? "Remove anyway" : "Remove worktree"}</button>
+ </div>
+ </div>}
+ </li>)}
+ </ul>}
+ </section>
+ </>}
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/git/GitStatusLine.tsx b/jarvis/ui/web/frontend/src/components/agentic/git/GitStatusLine.tsx
new file mode 100644
index 0000000000..73f33c54a1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/git/GitStatusLine.tsx
@@ -0,0 +1,25 @@
+import { ArrowDown, ArrowUp, GitBranch } from "lucide-react";
+import { cn } from "@/lib/utils";
+import type { GitRepoInfo } from "@/lib/gitApi";
+
+/** Branch · changes · ahead/behind · +/- lines, in one compact row. */
+export function GitStatusLine({ info, className }: { info: GitRepoInfo; className?: string }) {
+ const changes = info.staged + info.unstaged + info.untracked + info.conflicted;
+ return <span data-testid="git-status-line" className={cn("flex flex-wrap items-center gap-x-2.5 gap-y-1 text-xs text-muted-foreground", className)}>
+ <span className="flex items-center gap-1 font-mono text-foreground" title={info.detached ? `Detached at ${info.head}` : "Current branch"}>
+ <GitBranch className="h-3.5 w-3.5" aria-hidden />{info.detached ? info.head : info.branch || "—"}
+ </span>
+ {info.is_worktree && <span className="rounded-full border border-border px-1.5 text-[10px]">worktree</span>}
+ <span className="flex items-center gap-1" title={changes ? `${changes} uncommitted` : "Nothing uncommitted"}>
+ <span className={cn("h-1.5 w-1.5 rounded-full", info.conflicted ? "bg-destructive" : changes ? "bg-warning" : "bg-success")} aria-hidden />
+ {changes ? `${changes} ${changes === 1 ? "change" : "changes"}` : "clean"}
+ </span>
+ {(info.insertions > 0 || info.deletions > 0) && <span className="font-mono">
+ <span className="text-success">+{info.insertions}</span>{" "}
+ <span className="text-destructive">−{info.deletions}</span>
+ </span>}
+ {info.upstream ? <span className="flex items-center gap-0.5 font-mono" title={`Compared with ${info.upstream}`}>
+ <ArrowUp className="h-3 w-3" aria-label="ahead" />{info.ahead}<ArrowDown className="ml-1 h-3 w-3" aria-label="behind" />{info.behind}
+ </span> : info.branch && <span title="This branch has not been pushed yet">not pushed</span>}
+ </span>;
+}
diff --git a/jarvis/ui/web/frontend/src/lib/gitApi.ts b/jarvis/ui/web/frontend/src/lib/gitApi.ts
new file mode 100644
index 0000000000..7060269184
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/gitApi.ts
@@ -0,0 +1,176 @@
+/**
+ * Client for `/api/agentic-ide/git` — the Agentic IDE's Git panel and the
+ * git options offered when a workspace or an agent is opened.
+ *
+ * Every call names the folder it works on (a workspace folder, a project path
+ * or a worktree). A failed git call rejects with a {@link GitApiError} whose
+ * `code` tells the UI which follow-up it can offer (`dirty` → "remove anyway?").
+ */
+
+export type GitPrepareMode =
+ | "current"
+ | "init"
+ | "new_branch"
+ | "switch_branch"
+ | "new_worktree"
+ | "open_worktree";
+
+export interface GitChange {
+ path: string;
+ /** Git's own letters: M modified, A added, D deleted, R renamed, ? untracked, U conflicted, . unchanged. */
+ index: string;
+ worktree: string;
+}
+
+export interface GitBranch {
+ name: string;
+ current: boolean;
+ upstream: string;
+ committed_at: number;
+ /** The checkout this branch is open in, if any. */
+ worktree: string;
+}
+
+export interface GitWorktree {
+ path: string;
+ branch: string;
+ head: string;
+ main: boolean;
+ detached: boolean;
+ locked: boolean;
+ prunable: boolean;
+ current: boolean;
+}
+
+export interface GitRepoInfo {
+ folder: string;
+ git_available: boolean;
+ gh_available: boolean;
+ is_repo: boolean;
+ root: string;
+ main_root: string;
+ is_worktree: boolean;
+ branch: string;
+ detached: boolean;
+ unborn: boolean;
+ head: string;
+ upstream: string;
+ ahead: number;
+ behind: number;
+ staged: number;
+ unstaged: number;
+ untracked: number;
+ conflicted: number;
+ insertions: number;
+ deletions: number;
+ dirty: boolean;
+ default_branch: string;
+ remotes: string[];
+ branches: GitBranch[];
+ remote_branches: string[];
+ worktrees: GitWorktree[];
+ changes: GitChange[];
+ suggested_branch: string;
+ worktree_dir: string;
+}
+
+/** What a workspace or agent should do with git before it starts. */
+export interface GitPlan {
+ mode: GitPrepareMode;
+ branch: string;
+ /** Base branch/commit for a new branch or worktree; the worktree path for `open_worktree`. */
+ base: string;
+}
+
+export interface GitPrepared {
+ folder: string;
+ branch: string;
+ created: boolean;
+ message: string;
+}
+
+export class GitApiError extends Error {
+ constructor(message: string, readonly code: string) {
+ super(message);
+ this.name = "GitApiError";
+ }
+}
+
+const BASE = "/api/agentic-ide/git";
+
+async function failure(res: Response): Promise<GitApiError> {
+ 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(`Git request failed (${res.status})`, "failed");
+}
+
+async function post<T>(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 async function inspectGit(folder: string, signal?: AbortSignal): Promise<GitRepoInfo> {
+ const res = await fetch(`${BASE}/inspect?folder=${encodeURIComponent(folder)}`, { signal });
+ if (!res.ok) throw await failure(res);
+ return (await res.json()) as GitRepoInfo;
+}
+
+export function prepareGit(folder: string, plan: GitPlan): Promise<GitPrepared> {
+ return post<GitPrepared>("/prepare", { folder, mode: plan.mode, branch: plan.branch, base: plan.base });
+}
+
+export function commitAll(folder: string, message: string): Promise<{ commit: string }> {
+ return post("/commit", { folder, message });
+}
+
+export function pushBranch(folder: string): Promise<{ upstream: string }> {
+ return post("/push", { folder });
+}
+
+export function fetchRemotes(folder: string): Promise<{ ok: boolean }> {
+ return post("/fetch", { folder });
+}
+
+export function openPullRequest(folder: string, options: { title?: string; draft?: boolean } = {}): Promise<{ url: string }> {
+ return post("/pull-request", { folder, title: options.title ?? "", draft: options.draft ?? false });
+}
+
+export function mergeBack(folder: string, into = ""): Promise<{ commit: string }> {
+ return post("/merge", { folder, into });
+}
+
+export function removeWorktree(
+ folder: string,
+ worktree: string,
+ options: { force?: boolean; deleteBranch?: boolean } = {},
+): Promise<{ message: string }> {
+ return post("/worktrees/remove", {
+ folder, worktree, force: options.force ?? false, delete_branch: options.deleteBranch ?? false,
+ });
+}
+
+export function pruneWorktrees(folder: string): Promise<{ ok: boolean }> {
+ return post("/worktrees/prune", { folder });
+}
+
+/** The plan that changes nothing: run in the folder as it is. */
+export const KEEP_CHECKOUT: GitPlan = { mode: "current", branch: "", base: "" };
+
+/** The last path segment, for labels ("…/.worktrees/agent-x" → "agent-x"). */
+export function folderName(path: string): string {
+ return path.split(/[\\/]/).filter(Boolean).at(-1) ?? path;
+}
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
index 8a643bc300..87c179a933 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
@@ -12,6 +12,8 @@ const api = vi.hoisted(() => ({
syncAgenticIdeSurface: vi.fn(() => Promise.resolve()),
}));
const openProject = vi.hoisted(() => vi.fn());
+const git = vi.hoisted(() => ({ inspectGit: vi.fn(), prepareGit: vi.fn() }));
+vi.mock("@/lib/gitApi", async (importOriginal) => ({ ...(await importOriginal<object>()), ...git }));
vi.mock("@/lib/agenticIdeApi", () => api);
vi.mock("@/lib/chatLibraryApi", () => ({ openProject }));
vi.mock("@/store/events", () => ({ useEventStore: (select: (value: unknown) => unknown) => select({ pushToast: api.pushToast }) }));
@@ -22,6 +24,14 @@ vi.mock("@/components/agentic/WorkspaceTerminalGrid", () => ({ WorkspaceTerminal
const emptyState = { active: false, session: null, max_terminals: 8, workspaces: [], active_id: null };
const project = { id: "p1", path: "/code/app", name: "App", color: null, pinned: false, archived: false,
created_at: 0, last_opened_at: 0, exists: true, chats: 0, scratch: false, workspaces: [] };
+const repoInfo = {
+ folder: "/code/app", git_available: true, gh_available: false, is_repo: true, root: "/code/app", main_root: "/code/app",
+ is_worktree: false, branch: "main", detached: false, unborn: false, head: "abc", upstream: "", ahead: 0, behind: 0,
+ staged: 0, unstaged: 0, untracked: 0, conflicted: 0, insertions: 0, deletions: 0, dirty: false, default_branch: "main",
+ remotes: [], branches: [{ name: "main", current: true, upstream: "", committed_at: 0, worktree: "/code/app" }],
+ remote_branches: [], worktrees: [{ path: "/code/app", branch: "main", head: "abc", main: true, detached: false, locked: false, prunable: false, current: true }],
+ changes: [], suggested_branch: "agent/brave-river-0001", worktree_dir: "/code/app/.worktrees/agent-brave-river-0001",
+};
const agent = { name: "codex", display_name: "Codex", installed: true, version: "1", install_command: null };
beforeEach(() => {
@@ -30,6 +40,7 @@ beforeEach(() => {
api.fetchIdeProjects.mockResolvedValue({ projects: [], active_project_id: null, active_workspace_id: null, max_terminals: 8 });
api.fetchIdeAgents.mockResolvedValue({ terminal_available: true, max_terminals: 8, suggested_names: [], agents: [agent] });
useIdeProjectsStore.setState({ projects: [], activeWorkspaceId: null, pendingWorkspaceId: null, refreshRequest: null, action: null });
+ git.inspectGit.mockResolvedValue(repoInfo);
});
afterEach(cleanup);
@@ -68,6 +79,21 @@ describe("Agentic IDE project flow", () => {
await waitFor(() => expect(screen.queryByRole("dialog", { name: "New workspace" })).toBeNull());
});
+ it("opens a new workspace in a fresh git worktree", async () => {
+ api.fetchIdeProjects.mockResolvedValue({ projects: [project], active_project_id: null, active_workspace_id: null, max_terminals: 8 });
+ api.startIdeSession.mockResolvedValue(emptyState);
+ git.prepareGit.mockResolvedValue({ folder: "/code/app/.worktrees/agent-brave-river-0001", branch: "agent/brave-river-0001", created: true, message: "" });
+ render(<AgenticIdeView />);
+ await screen.findByText("Choose a workspace");
+ act(() => useIdeProjectsStore.getState().newWorkspace("p1"));
+ const dialog = await screen.findByRole("dialog", { name: "New workspace" });
+ fireEvent.click(await within(dialog).findByRole("radio", { name: /New worktree/ }));
+ expect((within(dialog).getByLabelText("Branch name") as HTMLInputElement).value).toBe("agent/brave-river-0001");
+ fireEvent.click(screen.getByRole("button", { name: "Create workspace" }));
+ await waitFor(() => expect(git.prepareGit).toHaveBeenCalledWith("/code/app", { mode: "new_worktree", branch: "agent/brave-river-0001", base: "main" }));
+ expect(api.startIdeSession).toHaveBeenCalledWith("/code/app/.worktrees/agent-brave-river-0001", [{ agent: "codex" }], { projectId: "p1", name: "agent/brave-river-0001" });
+ });
+
it("keeps the launch dialog open while creation is in flight", async () => {
api.fetchIdeProjects.mockResolvedValue({ projects: [project], active_project_id: null, active_workspace_id: null, max_terminals: 8 });
let finish!: (state: typeof emptyState) => void;
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
index 1b1d443d98..880c190bc6 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -9,6 +9,9 @@ import { IdeSidePanelFrame } from "@/components/agentic/sidePanel/IdeSidePanel";
import { GRID_LIMIT_HINT, MAX_WORKSPACE_PANES, canSplitFit, fitsWorkspace, isBalancedWorkspace } from "@/components/agentic/workspaceDocking";
import { AgentMark } from "@/components/agentic/AgentMark";
import { CloseAgentDialog, type CloseTarget } from "@/components/agentic/CloseAgentDialog";
+import { GitCheckoutPicker } from "@/components/agentic/git/GitCheckoutPicker";
+import { GitPanelDialog } from "@/components/agentic/git/GitPanelDialog";
+import { KEEP_CHECKOUT, prepareGit, type GitPlan } from "@/lib/gitApi";
import { SplitRightIcon, SplitBelowIcon, SplitLeftIcon, SplitAboveIcon } from "@/components/agentic/splitIcons";
import type { PaneSplitDirection } from "@/components/agentic/WorkspaceTerminalHeader";
import { cn } from "@/lib/utils";
@@ -68,6 +71,11 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
const [workspaceProject, setWorkspaceProject] = useState<IdeProject | null>(null);
const [workspaceName, setWorkspaceName] = useState("");
const [workspaceAgents, setWorkspaceAgents] = useState<string[]>([]);
+ // The git half of "New workspace" and "Add coding agent": keep the checkout,
+ // branch, or give the agents a worktree of their own.
+ const [workspaceGit, setWorkspaceGit] = useState<GitPlan>(KEEP_CHECKOUT);
+ const [agentGit, setAgentGit] = useState<GitPlan>(KEEP_CHECKOUT);
+ const [gitOpen, setGitOpen] = useState(false);
const [selected, setSelected] = useState("");
const [agentPicker, setAgentPicker] = useState<{ id: string; name: string } | null>(null);
// Where the next agent opens: split off `splitAnchor` (a pane call-sign) in
@@ -259,7 +267,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
}
if (action.kind === "new-workspace") {
const project = projects.find((entry) => entry.id === action.projectId);
- if (project) { setWorkspaceProject(project); setWorkspaceName(""); setWorkspaceAgents([installed[0]?.name ?? ""]); }
+ if (project) { setWorkspaceProject(project); setWorkspaceName(""); setWorkspaceAgents([installed[0]?.name ?? ""]); setWorkspaceGit(KEEP_CHECKOUT); }
return;
}
void activateFromTree(action.workspaceId);
@@ -273,18 +281,45 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
setProjects(listing.projects);
publishProjects(listing.projects, listing.active_workspace_id);
const found = listing.projects.find((entry) => entry.id === project.id);
- if (found) { setWorkspaceProject(found); setWorkspaceAgents([installed[0]?.name ?? ""]); }
+ if (found) { setWorkspaceProject(found); setWorkspaceAgents([installed[0]?.name ?? ""]); setWorkspaceGit(KEEP_CHECKOUT); }
});
const createWorkspace = () => void run(async () => {
if (!workspaceProject || workspaceAgents.length === 0 || workspaceAgents.some((agent) => !agent)) throw new Error("Choose an installed coding agent for every session.");
- const next = await startIdeSession(workspaceProject.path, workspaceAgents.map((agent) => ({ agent })), {
- projectId: workspaceProject.id, name: workspaceName.trim() || undefined,
+ // Git first: a new branch or worktree decides WHICH folder the agents start in.
+ const prepared = workspaceGit.mode === "current" ? null : await prepareGit(workspaceProject.path, workspaceGit);
+ const ownCheckout = workspaceGit.mode === "new_worktree" || workspaceGit.mode === "open_worktree";
+ const next = await startIdeSession(prepared?.folder ?? workspaceProject.path, workspaceAgents.map((agent) => ({ agent })), {
+ projectId: workspaceProject.id, name: workspaceName.trim() || (ownCheckout && prepared?.branch ? prepared.branch : undefined),
});
setState(next);
setWorkspaceProject(null);
+ if (prepared?.message) pushToast("success", prepared.message);
});
+ // An agent with a worktree of its own opens as its own workspace tab in that
+ // worktree, grouped under the same project, so its files never collide with
+ // the agents sharing the original checkout.
+ const addAgentInWorktree = (agentName: string, plan: GitPlan) => void run(async () => {
+ if (!session) return;
+ const prepared = await prepareGit(session.folder, plan);
+ setState(await startIdeSession(prepared.folder, [{ agent: agentName }], {
+ projectId: session.project_id ?? undefined, name: prepared.branch || undefined,
+ }));
+ if (prepared.message) pushToast("success", prepared.message);
+ });
+ const openWorktreeWorkspace = (path: string, branch: string) => void run(async () => {
+ const agent = installed[0]?.name;
+ if (!agent) throw new Error("Connect a coding agent in CLIs to continue.");
+ setState(await startIdeSession(path, [{ agent }], { projectId: session?.project_id ?? undefined, name: branch || undefined }));
+ });
+ const newWorktreeWorkspace = () => {
+ const project = projects.find((entry) => entry.id === session?.project_id);
+ if (!project) { pushToast("error", "This workspace belongs to no connected project."); return; }
+ setWorkspaceProject(project); setWorkspaceName(""); setWorkspaceAgents([installed[0]?.name ?? ""]);
+ setWorkspaceGit({ mode: "new_worktree", branch: "", base: "" });
+ };
+
const addAgent = (
agentName: string,
workspaceId: string,
@@ -342,6 +377,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
const pane = named || (isBalancedWorkspace(session.layout, session.terminals) ? "" : selected);
setSplitAnchor(session.terminals.some((terminal) => terminal.name === pane) ? pane : "");
setSplitDirection(isSplitDirection(direction) ? direction : storedSplitDirection());
+ setAgentGit(KEEP_CHECKOUT);
setAgentPicker({ id: session.id, name: session.name ?? session.project.name });
}, [session, selected]);
// The chosen direction when it fits; otherwise the first that does; null
@@ -386,8 +422,10 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
<WorkspaceOptionsDialog open={optionsOpen && !!session} onOpenChange={setOptionsOpen} workspace={session?.name ?? session?.project.name ?? ""}
count={session?.terminals.length ?? 0} maxPanes={maxPanes} busy={busy} canAdd={installed.length > 0}
onAdd={openAgentPicker} onBalance={balanceLayout} onRename={() => { setRenameValue(session?.name ?? session?.project.name ?? ""); setRenameOpen(true); }}
- onClose={stopWorkspace} fontSize={fontSize} onFontSize={saveFont} appearance={appearance} onAppearance={saveAppearance}
+ onClose={stopWorkspace} onGit={() => setGitOpen(true)} fontSize={fontSize} onFontSize={saveFont} appearance={appearance} onAppearance={saveAppearance}
/>
+ {session && <GitPanelDialog open={gitOpen} onOpenChange={setGitOpen} folder={session.folder} workspace={session.name ?? session.project.name}
+ onOpenWorktree={(tree) => openWorktreeWorkspace(tree.path, tree.branch)} onNewWorktree={newWorktreeWorkspace} />}
<CloseAgentDialog target={closeTarget} busy={busy} onCancel={() => setCloseRequest(null)} onConfirm={confirmClose} />
<main className="min-h-0 flex-1">
@@ -415,7 +453,9 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
<button type="button" aria-label="Close" onClick={() => setAgentPicker(null)} className="rounded-md p-1.5 hover:bg-muted"><X className="h-4 w-4" /></button>
</div>
- {session && session.terminals.length > 0 && (() => {
+ {session && <div className="mb-4"><GitCheckoutPicker folder={session.folder} value={agentGit} onChange={setAgentGit} disabled={busy} context="agent" /></div>}
+
+ {session && session.terminals.length > 0 && agentGit.mode === "current" && (() => {
const anchorTerminal = session.terminals.find((terminal) => terminal.name === splitAnchor);
return <div className="mb-4 space-y-2.5 rounded-xl border border-border bg-muted/40 p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
@@ -447,10 +487,14 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
})()}
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
- {workspaceFull && <p role="status" className="col-span-full rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
+ {workspaceFull && agentGit.mode === "current" && <p role="status" className="col-span-full rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground">
This workspace is full ({maxPanes} agents). Close a pane, or open another workspace for more agents.</p>}
- {installed.map((agent) => <button key={agent.name} type="button" disabled={busy || workspaceFull}
- onClick={() => { const owner = agentPicker.id; setAgentPicker(null); addAgent(agent.name, owner, effectiveDirection ? splitAnchor : undefined, effectiveDirection ?? "down"); }}
+ {installed.map((agent) => <button key={agent.name} type="button" disabled={busy || (workspaceFull && agentGit.mode === "current")}
+ onClick={() => {
+ const owner = agentPicker.id; setAgentPicker(null);
+ if (agentGit.mode !== "current") addAgentInWorktree(agent.name, agentGit);
+ else addAgent(agent.name, owner, effectiveDirection ? splitAnchor : undefined, effectiveDirection ?? "down");
+ }}
className="flex min-h-12 items-center gap-3 rounded-lg border border-border px-3 py-2 text-left text-sm font-medium hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<AgentMark agent={agent.name} label={agent.display_name} logoUrl={agent.logo_url} variant="plain" />{agent.display_name}
</button>)}
@@ -488,6 +532,7 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {
placeholder="Workspace" className="mt-2 h-11 w-full rounded-lg border border-input bg-background/60 px-3 text-sm text-foreground outline-none focus:border-ring focus:ring-1 focus:ring-ring/30" />
</label>
<WorkspaceAgentSetup agents={installed} sessions={workspaceAgents} onChange={setWorkspaceAgents} disabled={busy} maxSessions={maxPanes} />
+ <GitCheckoutPicker folder={workspaceProject.path} value={workspaceGit} onChange={setWorkspaceGit} disabled={busy} context="workspace" />
</div>
<footer className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-t border-border bg-muted/20 px-6 py-4 sm:px-8">
<span className="text-xs text-muted-foreground" aria-live="polite">{workspaceAgents.length} {workspaceAgents.length === 1 ? "session" : "sessions"} · {new Set(workspaceAgents.filter(Boolean)).size} {new Set(workspaceAgents.filter(Boolean)).size === 1 ? "agent" : "agents"}</span>
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index d093db8c16..36eae721ab 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -333,6 +333,7 @@ class WebServer:
from .agent_accounts_routes import router as agent_accounts_router
from .agent_chat_routes import router as agent_chat_router
from .agent_mcp_routes import router as agent_mcp_router
+ from .agentic_ide_git_routes import router as agentic_ide_git_router
from .agentic_ide_routes import router as agentic_ide_router
from .antigravity_routes import router as antigravity_router
from .board_routes import (
@@ -526,6 +527,8 @@ class WebServer:
# doing?") and promptable from Jarvis. Reuses the same PTY stack as the
# 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_git_router)
app.include_router(agentic_ide_router)
# The pane-activity sweep has no bus of its own (the registry is a plain
# holder by design); this is the one place that holds one, so the sweep
diff --git a/tests/unit/agentic_ide/test_git_ops.py b/tests/unit/agentic_ide/test_git_ops.py
new file mode 100644
index 0000000000..7ca732a221
--- /dev/null
+++ b/tests/unit/agentic_ide/test_git_ops.py
@@ -0,0 +1,263 @@
+"""Git for the Agentic IDE: inspect, prepare, finish — against a real ``git``."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import folders, git_ops
+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:
+ # A reproducible identity and no user/system config leaking into the test.
+ 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"))
+
+
+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_ops.init_repository(root)
+ (root / "app.py").write_text("print('hi')\n", encoding="utf-8")
+ _git(root, "add", "app.py")
+ _git(root, "commit", "-m", "feat: app")
+ return root
+
+
+def test_inspect_plain_folder_is_not_a_repo(tmp_path: Path) -> None:
+ info = git_ops.inspect(tmp_path)
+ assert info.git_available
+ assert not info.is_repo
+ assert info.suggested_branch.startswith(git_ops.BRANCH_PREFIX)
+
+
+def test_init_creates_main_with_an_empty_first_commit(tmp_path: Path) -> None:
+ (tmp_path / "secret.env").write_text("TOKEN=x\n", encoding="utf-8")
+ result = git_ops.init_repository(tmp_path)
+ assert result.branch == "main" and result.created
+ info = git_ops.inspect(tmp_path)
+ assert info.branch == "main" and not info.unborn
+ # The user's files are never committed on their behalf.
+ assert info.untracked == 1
+ with pytest.raises(GitError) as exc:
+ git_ops.init_repository(tmp_path)
+ assert exc.value.code == "exists"
+
+
+def test_inspect_counts_changes_and_line_stats(repo: Path) -> None:
+ (repo / "app.py").write_text("print('hi')\nprint('more')\n", encoding="utf-8")
+ (repo / "new.txt").write_text("x\n", encoding="utf-8")
+ info = git_ops.inspect(repo)
+ assert info.branch == "main"
+ assert info.unstaged == 1 and info.untracked == 1 and info.dirty
+ assert info.insertions == 1
+ assert {change.path for change in info.changes} == {"app.py", "new.txt"}
+ assert info.default_branch == "main"
+ assert [branch.name for branch in info.branches] == ["main"]
+ assert info.to_dict()["dirty"] is True
+
+
+def test_new_branch_in_place_and_reuse(repo: Path) -> None:
+ made = git_ops.prepare(repo, "new_branch", branch="feature/login")
+ assert made.created and made.folder == str(repo)
+ assert git_ops.inspect(repo).branch == "feature/login"
+ git_ops.prepare(repo, "switch_branch", branch="main")
+ again = git_ops.prepare(repo, "new_branch", branch="feature/login")
+ assert not again.created
+ assert git_ops.inspect(repo).branch == "feature/login"
+
+
+def test_invalid_branch_name_is_refused(repo: Path) -> None:
+ with pytest.raises(GitError) as exc:
+ git_ops.prepare(repo, "new_branch", branch="bad..name")
+ assert exc.value.code == "invalid"
+
+
+def test_new_worktree_lands_under_dot_worktrees_and_is_excluded(repo: Path) -> None:
+ made = git_ops.prepare(repo, "new_worktree", branch="agent/brave-river-0001")
+ target = repo / ".worktrees" / "agent-brave-river-0001"
+ assert Path(made.folder) == target and made.created
+ assert (target / "app.py").is_file()
+ main = git_ops.inspect(repo)
+ # The worktree folder never shows up as untracked in the main checkout.
+ assert not main.dirty
+ assert any(tree.branch == "agent/brave-river-0001" for tree in main.worktrees)
+ linked = git_ops.inspect(target)
+ assert linked.is_worktree and linked.branch == "agent/brave-river-0001"
+ assert Path(linked.main_root) == Path(_git(repo, "rev-parse", "--show-toplevel"))
+ # The sidebar's cheap branch reader understands a worktree's `.git` file.
+ assert folders._git_branch(target) == "agent/brave-river-0001"
+ assert git_ops.same_repository(target, repo)
+
+
+def test_new_worktree_for_a_checked_out_branch_opens_that_checkout(repo: Path) -> None:
+ first = git_ops.prepare(repo, "new_worktree", branch="agent/one")
+ second = git_ops.prepare(repo, "new_worktree", branch="agent/one")
+ assert second.folder == first.folder and not second.created
+
+
+def test_worktree_keeps_the_sub_folder(repo: Path) -> None:
+ (repo / "web").mkdir()
+ (repo / "web" / "index.ts").write_text("export {}\n", encoding="utf-8")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-m", "feat: web")
+ made = git_ops.prepare(repo / "web", "new_worktree", branch="agent/web")
+ assert Path(made.folder) == repo / ".worktrees" / "agent-web" / "web"
+
+
+def test_unborn_repository_cannot_branch(tmp_path: Path) -> None:
+ _git(tmp_path, "init")
+ with pytest.raises(GitError) as exc:
+ git_ops.prepare(tmp_path, "new_worktree", branch="agent/x")
+ assert exc.value.code == "unborn"
+
+
+def test_commit_all_and_nothing_to_commit(repo: Path) -> None:
+ (repo / "new.txt").write_text("x\n", encoding="utf-8")
+ sha = git_ops.commit_all(repo, "feat: add new")
+ assert sha and not git_ops.inspect(repo).dirty
+ with pytest.raises(GitError) as exc:
+ git_ops.commit_all(repo, "feat: again")
+ assert exc.value.code == "clean"
+
+
+def test_push_without_remote_says_so(repo: Path) -> None:
+ with pytest.raises(GitError) as exc:
+ git_ops.push(repo)
+ assert exc.value.code == "no_remote"
+
+
+def test_push_sets_upstream_then_tracks_ahead(repo: Path, tmp_path: Path) -> None:
+ remote = tmp_path / "remote.git"
+ _git(tmp_path, "init", "--bare", str(remote))
+ _git(repo, "remote", "add", "origin", str(remote))
+ assert git_ops.push(repo) == "origin/main"
+ (repo / "b.txt").write_text("b\n", encoding="utf-8")
+ git_ops.commit_all(repo, "feat: b")
+ info = git_ops.inspect(repo)
+ assert info.upstream == "origin/main" and info.ahead == 1 and info.behind == 0
+
+
+def test_merge_back_from_worktree(repo: Path) -> None:
+ made = git_ops.prepare(repo, "new_worktree", branch="agent/feature")
+ tree = Path(made.folder)
+ (tree / "feature.txt").write_text("done\n", encoding="utf-8")
+ git_ops.commit_all(tree, "feat: feature")
+ git_ops.merge_back(tree)
+ assert (repo / "feature.txt").is_file()
+
+
+def test_merge_back_refuses_uncommitted_work(repo: Path) -> None:
+ tree = Path(git_ops.prepare(repo, "new_worktree", branch="agent/dirty").folder)
+ (tree / "app.py").write_text("changed\n", encoding="utf-8")
+ with pytest.raises(GitError) as exc:
+ git_ops.merge_back(tree)
+ assert exc.value.code == "dirty"
+
+
+def test_merge_conflict_is_aborted(repo: Path) -> None:
+ tree = Path(git_ops.prepare(repo, "new_worktree", branch="agent/clash").folder)
+ (tree / "app.py").write_text("theirs\n", encoding="utf-8")
+ git_ops.commit_all(tree, "feat: theirs")
+ (repo / "app.py").write_text("ours\n", encoding="utf-8")
+ git_ops.commit_all(repo, "feat: ours")
+ with pytest.raises(GitError) as exc:
+ git_ops.merge_back(tree)
+ assert exc.value.code == "conflict"
+ # Nothing half-merged is left behind.
+ assert not git_ops.inspect(repo).dirty
+ assert (repo / "app.py").read_text(encoding="utf-8") == "ours\n"
+
+
+def test_remove_worktree_asks_again_when_dirty(repo: Path) -> None:
+ tree = Path(git_ops.prepare(repo, "new_worktree", branch="agent/tmp").folder)
+ (tree / "scratch.txt").write_text("wip\n", encoding="utf-8")
+ with pytest.raises(GitError) as exc:
+ git_ops.remove_worktree(repo, tree)
+ assert exc.value.code == "dirty"
+ summary = git_ops.remove_worktree(repo, tree, force=True, delete_branch=True)
+ assert not tree.exists()
+ # Unmerged work is never thrown away with the branch: `-d`, not `-D`.
+ assert "Deleted branch" in summary
+ assert "agent/tmp" not in _git(repo, "branch")
+
+
+def test_remove_refuses_main_checkout(repo: Path) -> None:
+ with pytest.raises(GitError) as exc:
+ git_ops.remove_worktree(repo, repo)
+ assert exc.value.code == "invalid"
+
+
+def test_open_worktree_by_branch(repo: Path) -> None:
+ made = git_ops.prepare(repo, "new_worktree", branch="agent/open-me")
+ opened = git_ops.prepare(repo, "open_worktree", branch="agent/open-me")
+ assert opened.folder == made.folder
+
+
+def test_worktree_in_use() -> None:
+ base = Path("/work/repo/.worktrees/agent-x")
+ assert git_ops.worktree_in_use(base, [str(base / "web")])
+ assert not git_ops.worktree_in_use(base, [str(Path("/work/repo"))])
+
+
+def test_pull_request_without_gh(monkeypatch: pytest.MonkeyPatch, repo: Path) -> None:
+ monkeypatch.setattr(git_ops, "gh_available", lambda: False)
+ with pytest.raises(GitError) as exc:
+ git_ops.create_pull_request(repo)
+ assert exc.value.code == "missing"
+
+
+def test_no_git_installed(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(git_ops, "git_available", lambda: False)
+ info = git_ops.inspect(tmp_path)
+ assert not info.git_available and not info.is_repo
+
+
+async def test_workspace_may_open_in_a_worktree_of_its_project(
+ monkeypatch: pytest.MonkeyPatch, repo: Path
+) -> None:
+ from jarvis.agentic_ide import library, session
+ from tests.fakes.fake_pty_manager import FakePtyManager
+
+ monkeypatch.setattr(session, "agent_argv", lambda agent: (f"/usr/bin/{agent}",))
+ registry = session.Registry(pty_manager=FakePtyManager())
+ project = library.ensure_project(repo, name="Project")
+ tree = git_ops.prepare(repo, "new_worktree", branch="agent/tab").folder
+ opened = await registry.start(tree, [{"agent": "claude"}], project_id=project.id)
+ assert opened.folder == tree
+ assert opened.project_id == project.id
+
+
+def test_routes_report_git_errors_with_a_code(repo: Path) -> None:
+ from fastapi import HTTPException
+
+ from jarvis.ui.web import agentic_ide_git_routes as routes
+
+ made = routes.prepare_checkout(
+ routes.PrepareRequest(folder=str(repo), mode="new_worktree", branch="agent/api")
+ )
+ assert made["branch"] == "agent/api" and made["created"]
+ info = routes.inspect_folder(folder=made["folder"])
+ assert info["is_worktree"] and info["branch"] == "agent/api"
+ with pytest.raises(HTTPException) as exc:
+ routes.push_branch(routes.FolderRequest(folder=str(repo)))
+ assert exc.value.status_code == 422
+ assert exc.value.detail["code"] == "no_remote"