Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ide): read a branch in place and list branches before GitHub answers
rubenluetke10-beep5d807b6d22e7
diff --git a/jarvis/agentic_ide/branch_contents.py b/jarvis/agentic_ide/branch_contents.pynew file mode 100644index 0000000000..ade0e75942--- /dev/null+++ b/jarvis/agentic_ide/branch_contents.py@@ -0,0 +1,221 @@+"""What one branch holds: its own commits and the files it changes.++Backs the IDE Git tab's folded-open branch row, so a branch can be read in+place instead of in an editor. A branch is compared with the default branch+the way a pull request is: commits reachable from the branch but not from the+base, and files changed since the two split (``base...branch``). The base is+``origin/<default>`` when this clone has it, since the local default branch+may have drifted from what GitHub merges into.++Everything is read-only git on refs this clone already has; a GitHub-only+branch is readable once fetched.+"""++from __future__ import annotations++from dataclasses import asdict, dataclass, field+from pathlib import Path, PurePosixPath+from typing import Any++from jarvis.agentic_ide.git_changes import FileDiff, _git, _parse_unified++#: Most commits listed for one branch; ``commits_truncated`` says when more exist.+MAX_COMMITS = 30+#: Most changed files listed for one branch.+MAX_FILES = 300++_STATUS = {"A": "added", "D": "deleted", "M": "modified", "T": "modified"}+++@dataclass(slots=True)+class BranchCommit:+ sha: str+ subject: str+ author: str+ committed_at: int+++@dataclass(slots=True)+class BranchFile:+ path: str+ #: ``added`` | ``deleted`` | ``modified``+ status: str+ #: None for a binary file.+ added: int | None = None+ removed: int | None = None+++@dataclass(slots=True)+class BranchContents:+ available: bool+ branch: str+ #: The ref compared against (``origin/main``), "" for the default branch itself.+ base: str = ""+ commits: list[BranchCommit] = field(default_factory=list)+ commits_truncated: bool = False+ files: list[BranchFile] = field(default_factory=list)+ files_truncated: bool = False+ #: Why ``available`` is false, in one plain sentence.+ reason: str = ""++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++def _valid_name(name: str) -> bool:+ return bool(name) and not name.startswith("-") and ".." not in name and "\0" not in name+++def _verify(root: Path, ref: str) -> bool:+ result = _git(["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"], root)+ return result is not None and result.returncode == 0+++def _branch_ref(root: Path, branch: str, remote: bool) -> str | None:+ if not _valid_name(branch):+ return None+ ref = f"refs/remotes/origin/{branch}" if remote else f"refs/heads/{branch}"+ return ref if _verify(root, ref) else None+++def _base_ref(root: Path, default_branch: str) -> str | None:+ if not _valid_name(default_branch):+ return None+ for ref in (f"refs/remotes/origin/{default_branch}", f"refs/heads/{default_branch}"):+ if _verify(root, ref):+ return ref+ return None+++def _short(ref: str) -> str:+ return ref.removeprefix("refs/heads/").removeprefix("refs/remotes/")+++def _commits(root: Path, spec: str) -> tuple[list[BranchCommit], bool]:+ result = _git(+ [+ "log",+ f"--max-count={MAX_COMMITS + 1}",+ "--format=%H%x1f%s%x1f%an%x1f%ct%x1e",+ spec,+ "--",+ ],+ root,+ )+ commits: list[BranchCommit] = []+ for record in (result.stdout if result and result.returncode == 0 else "").split("\x1e"):+ parts = record.strip("\n").split("\x1f")+ if len(parts) != 4 or not parts[0]:+ continue+ sha, subject, author, stamp = parts+ commits.append(+ BranchCommit(+ sha=sha[:12],+ subject=subject,+ author=author,+ committed_at=int(stamp) if stamp.isdigit() else 0,+ )+ )+ return commits[:MAX_COMMITS], len(commits) > MAX_COMMITS+++def _files(root: Path, spec: str) -> tuple[list[BranchFile], bool]:+ status = _git(["diff", "--name-status", "-z", "--no-renames", spec, "--"], root)+ numstat = _git(["diff", "--numstat", "-z", "--no-renames", spec, "--"], root)+ counts: dict[str, tuple[int | None, int | None]] = {}+ for record in (numstat.stdout if numstat and numstat.returncode == 0 else "").split("\0"):+ added, _, rest = record.partition("\t")+ removed, _, path = rest.partition("\t")+ if path:+ counts[path] = (+ int(added) if added.isdigit() else None,+ int(removed) if removed.isdigit() else None,+ )+ tokens = (status.stdout if status and status.returncode == 0 else "").split("\0")+ files: list[BranchFile] = []+ for code, path in zip(tokens[0::2], tokens[1::2], strict=False):+ if not path:+ continue+ added, removed = counts.get(path, (None, None))+ files.append(+ BranchFile(+ path=path,+ status=_STATUS.get(code[:1], "modified"),+ added=added,+ removed=removed,+ )+ )+ return files[:MAX_FILES], len(files) > MAX_FILES+++def branch_contents(+ folder: str | Path, branch: str, default_branch: str, *, remote: bool = False+) -> BranchContents:+ """The commits ``branch`` adds over the default branch, and the files it changes."""+ root = Path(folder).expanduser()+ out = BranchContents(available=False, branch=branch)+ if not root.is_dir():+ out.reason = "The workspace folder is missing."+ return out+ ref = _branch_ref(root, branch, remote)+ if ref is None:+ out.reason = (+ "This branch is only on GitHub and not fetched yet; fetch to read it here."+ if remote+ else "This branch is not in this repository."+ )+ return out+ out.available = True+ base = _base_ref(root, default_branch)+ if base is None or _short(base) in {branch, f"origin/{branch}"}:+ # The default branch itself (or no base at all): its latest commits.+ out.commits, out.commits_truncated = _commits(root, ref)+ return out+ out.base = _short(base)+ out.commits, out.commits_truncated = _commits(root, f"{base}..{ref}")+ out.files, out.files_truncated = _files(root, f"{base}...{ref}")+ return out+++def branch_file_diff(+ folder: str | Path, branch: str, default_branch: str, path: str, *, remote: bool = False+) -> FileDiff:+ """How ``branch`` changed one file since it split from the default branch."""+ root = Path(folder).expanduser()+ rel = path.strip().replace("\\", "/")+ posix = PurePosixPath(rel)+ if not rel or posix.is_absolute() or ".." in posix.parts or rel.startswith("-"):+ raise ValueError("That path is not a file in this repository.")+ ref = _branch_ref(root, branch, remote)+ base = _base_ref(root, default_branch)+ if ref is None or base is None:+ raise ValueError("This branch cannot be compared here.")+ result = _git(+ [+ "diff",+ "--no-color",+ "--no-ext-diff",+ "--no-renames",+ "-U3",+ f"{base}...{ref}",+ "--",+ rel,+ ],+ root,+ )+ text = result.stdout if result and result.returncode == 0 else ""+ hunks, added, removed, binary, truncated = _parse_unified(text)+ status = "modified"+ if "\nnew file mode" in f"\n{text}":+ status = "added"+ elif "\ndeleted file mode" in f"\n{text}":+ status = "deleted"+ return FileDiff(+ path=rel,+ status=status,+ binary=binary,+ hunks=hunks,+ added=added,+ removed=removed,+ truncated=truncated,+ )diff --git a/jarvis/agentic_ide/git_overview.py b/jarvis/agentic_ide/git_overview.pyindex ba97c420c4..65c9cf2ab0 100644--- a/jarvis/agentic_ide/git_overview.py+++ b/jarvis/agentic_ide/git_overview.py@@ -493,13 +493,29 @@ class _GitHubCache:self._entries[key] = snapreturn snap- def get(self, key: str, token: str, *, force: bool = False) -> _GitHubSnapshot:- """``key`` is the repository (``owner/name``)."""+ def get(+ self, key: str, token: str, *, force: bool = False, wait: bool = True+ ) -> _GitHubSnapshot | None:+ """``key`` is the repository (``owner/name``).++ With ``wait=False`` a repository read for the first time answers None at+ once and loads in the background: the first GitHub read takes seconds,+ and the local branches should not wait for it.+ """with self._guard:lock = self._locks.setdefault(key, threading.Lock())snap = self._entries.get(key)- if snap is None or force:+ if force or (snap is None and wait):return self._load(key, token, lock, force)+ if snap is None:+ if not lock.locked():+ threading.Thread(+ target=self._load,+ args=(key, token, lock, False),+ name="git-overview-github",+ daemon=True,+ ).start()+ return Noneif not self._fresh(snap, time.time(), False) and not lock.locked():# Stale-while-revalidate: a poll never waits seconds for GitHub;# it gets the last answer now and the new one on its next tick.@@ -642,7 +658,9 @@ def _attach_github(row: BranchRow, remote: str, snap: _GitHubSnapshot) -> None:)-def _github_for(root: Path, info: RepoOverview, refresh: bool) -> _GitHubSnapshot | None:+def _github_for(+ root: Path, info: RepoOverview, refresh: bool, wait: bool = True+) -> _GitHubSnapshot | None:"""GitHub's answer for the repository picked for ``root``, or None with``info.github`` saying what is missing (a connection, or the choice)."""state = info.github@@ -658,7 +676,12 @@ def _github_for(root: Path, info: RepoOverview, refresh: bool) -> _GitHubSnapshostate.reason = "Pick which GitHub repository this folder is."state.suggested_repo = github_link.remote_repository(root)return None- snap = _CACHE.get(state.repo, cred.token, force=refresh)+ snap = _CACHE.get(state.repo, cred.token, force=refresh, wait=wait)+ if snap is None:+ state.code = "loading"+ state.reason = "Reading pull requests and CI from GitHub…"+ state.repo_url = f"https://github.com/{state.repo}"+ return Nonestate.available = snap.okstate.reason = snap.reasonstate.code = snap.code@@ -688,8 +711,18 @@ def branch_checkout(folder: str | Path, branch: str) -> Path | None:return None-def overview(folder: str | Path, *, refresh: bool = False, github: bool = True) -> RepoOverview:- """Branches of the repository ``folder`` is in, with merge, PR and CI state."""+def overview(+ folder: str | Path,+ *,+ refresh: bool = False,+ github: bool = True,+ wait_for_github: bool = True,+) -> RepoOverview:+ """Branches of the repository ``folder`` is in, with merge, PR and CI state.++ ``wait_for_github=False`` answers a repository's very first read with the+ local branches only (``github.code == "loading"``) while GitHub loads.+ """path = Path(folder).expanduser()if not path.is_dir():return RepoOverview(available=False, reason="The workspace folder is missing.")@@ -712,7 +745,7 @@ def overview(folder: str | Path, *, refresh: bool = False, github: bool = True)snap: _GitHubSnapshot | None = Noneif github:- snap = _github_for(root, info, refresh)+ snap = _github_for(root, info, refresh, wait_for_github)# Current and default branch always make the list, however old they are.keep = {head, info.default_branch}diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.pyindex 22c62c193c..61a57013b3 100644--- a/jarvis/ui/web/agentic_ide_git_routes.py+++ b/jarvis/ui/web/agentic_ide_git_routes.py@@ -6,6 +6,8 @@ Endpoints (all under ``/api/agentic-ide/git``)::GET /changes Changed files under a folder, with line countsGET /diff One file's change against the last commitGET /overview A workspace's branches with merged-into, PR and CI state+ GET /branch/contents A branch's own commits and changed files+ GET /branch/diff How a branch changed one fileGET /branch/editors Where a branch's checkout can be opened on this computerPOST /branch/open Open a branch's checkout in the file manager or an editorGET /github/repos The person's GitHub repositories, for the one-time pick@@ -35,7 +37,14 @@ from pathlib import Pathfrom fastapi import APIRouter, HTTPException, Query, Requestfrom pydantic import BaseModel, Field-from jarvis.agentic_ide import git_changes, git_ops, git_overview, github_link, github_status+from jarvis.agentic_ide import (+ branch_contents,+ git_changes,+ git_ops,+ git_overview,+ github_link,+ github_status,+)from jarvis.agentic_ide.git_ops import GitError, PrepareModefrom jarvis.agentic_ide.session import account_home, get_registryfrom jarvis.agentic_ide.session_branches import PaneBranchRecord@@ -130,7 +139,8 @@ def workspace_overview(session = get_registry().get(workspace_id)if session is None:raise HTTPException(status_code=404, detail="Workspace not found.")- return git_overview.overview(session.folder, refresh=refresh).to_dict()+ # The tab polls again soon while GitHub's first read is still loading.+ return git_overview.overview(session.folder, refresh=refresh, wait_for_github=False).to_dict()@router.get("/session-status", summary="Current GitHub branch, pull request and CI status per pane")@@ -167,6 +177,41 @@ def _native_actions(request: Request) -> bool:)+def _workspace_folder(workspace_id: str) -> Path:+ session = get_registry().get(workspace_id)+ if session is None:+ raise HTTPException(status_code=404, detail="Workspace not found.")+ return Path(session.folder)++[email protected]("/branch/contents", summary="A branch's own commits and changed files")+def branch_contents_route(+ workspace_id: str = Query(..., min_length=1),+ branch: str = Query(..., min_length=1, max_length=300),+ base: str = Query("", max_length=300, description="The default branch to compare with"),+ remote: bool = Query(False, description="Read origin/<branch> (a GitHub-only branch)"),+) -> dict:+ """What the Git tab shows when a branch row is folded open."""+ folder = _workspace_folder(workspace_id)+ return branch_contents.branch_contents(folder, branch, base, remote=remote).to_dict()++[email protected]("/branch/diff", summary="How a branch changed one file")+def branch_diff_route(+ workspace_id: str = Query(..., min_length=1),+ branch: str = Query(..., min_length=1, max_length=300),+ path: str = Query(..., min_length=1, max_length=1000),+ base: str = Query("", max_length=300),+ remote: bool = Query(False),+) -> dict:+ folder = _workspace_folder(workspace_id)+ try:+ diff = branch_contents.branch_file_diff(folder, branch, base, path, remote=remote)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from None+ return asdict(diff)++@router.get("/branch/editors", summary="Where a branch's checkout can be opened")def branch_editors(request: Request) -> dict:"""The file manager and the installed editors; empty on a headless host."""diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsxindex b9acebdab8..aa04d0309a 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx@@ -93,6 +93,32 @@ let gate: Promise<void> | null = null;const calls: string[] = [];const puts: string[] = [];const opens: string[] = [];+const diffs: string[] = [];+const CONTENTS = {+ available: true,+ branch: "feature/wip",+ base: "origin/main",+ commits: [+ { sha: "aaaaaaaaaaaa", subject: "Add the widget", author: "Ada", committed_at: 1_790_000_000 },+ { sha: "bbbbbbbbbbbb", subject: "Start the widget", author: "Ada", committed_at: 1_789_000_000 },+ ],+ commits_truncated: false,+ files: [+ { path: "src/widget.ts", status: "added", added: 12, removed: 0 },+ { path: "README.md", status: "modified", added: 2, removed: 1 },+ ],+ files_truncated: false,+ reason: "",+};+const FILE_DIFF = {+ path: "src/widget.ts",+ status: "added",+ binary: false,+ added: 1,+ removed: 0,+ truncated: false,+ hunks: [{ header: "@@ -0,0 +1 @@", lines: [{ kind: "add", text: "export const widget = 1;", old_no: null, new_no: 1 }] }],+};const REPOS = {connected: true,source: "app",@@ -111,6 +137,7 @@ beforeEach(() => {calls.length = 0;puts.length = 0;opens.length = 0;+ diffs.length = 0;vi.stubGlobal("fetch",vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {@@ -119,6 +146,11 @@ beforeEach(() => {const json = (body: unknown, code = 200) =>new Response(JSON.stringify(body), { status: code, headers: { "Content-Type": "application/json" } });if (url.includes("/github/repos")) return json(REPOS);+ if (url.includes("/branch/contents")) return json(CONTENTS);+ if (url.includes("/branch/diff")) {+ diffs.push(url);+ return json(FILE_DIFF);+ }if (url.includes("/branch/editors")) return json({ file_manager: true, editors: [{ id: "code", label: "VS Code" }] });if (url.includes("/branch/open")) {opens.push(String(init?.body));@@ -321,6 +353,7 @@ describe("GitOverviewTab", () => {fireEvent.click(within(row("feature/wip")).getByTestId("git-branch-toggle"));const details = within(row("feature/wip")).getByTestId("git-branch-details");+ await within(details).findByTestId("git-branch-commits");fireEvent.click(await within(details).findByTestId("git-open-folder"));await vi.waitFor(() => expect(opens).toHaveLength(1));expect(JSON.parse(opens[0])).toEqual({ workspace_id: "w1", branch: "feature/wip", target: "folder" });@@ -334,10 +367,21 @@ describe("GitOverviewTab", () => {// Not checked out anywhere: nothing local to open, the switch command instead; not on GitHub either.fireEvent.click(within(row("wip/local")).getByTestId("git-branch-toggle"));const local = within(row("wip/local")).getByTestId("git-branch-details");+ await within(local).findByTestId("git-branch-commits");expect(within(local).queryByTestId("git-open-folder")).toBeNull();expect(within(local).getByTestId("git-copy-switch")).toBeTruthy();expect(within(local).queryByTestId("git-open-github")).toBeNull();+ // The branch is readable in place: its commits and files, each file's diff one click away.+ expect(within(details).getByTestId("git-branch-commits").textContent).toContain("Add the widget");+ expect(within(details).getByTestId("git-branch-commits").textContent).toContain("2 commits not in origin/main");+ const file = within(details).getAllByTestId("git-branch-file").find((el) => el.dataset.path === "src/widget.ts")!;+ fireEvent.click(within(file).getByRole("button"));+ expect(await within(file).findByTestId("explorer-diff")).toBeTruthy();+ expect(within(file).getByTestId("explorer-diff").textContent).toContain("export const widget = 1;");+ expect(diffs[0]).toContain("path=src%2Fwidget.ts");+ expect(diffs[0]).toContain("base=main");+// A second click folds it away again.fireEvent.click(within(row("feature/wip")).getByTestId("git-branch-toggle"));expect(within(row("feature/wip")).queryByTestId("git-branch-details")).toBeNull();diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsxindex 27ba45edc8..4dc19959bc 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx@@ -14,7 +14,6 @@ import {FolderGit2,FolderOpen,GitBranch,- GitCompareArrows,GitMerge,GitPullRequest,GitPullRequestClosed,@@ -35,14 +34,20 @@ import { cn } from "@/lib/utils";import { QuickTooltip } from "@/components/ui/tooltip";import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";-import { BranchMenu, branchPath, branchUrl } from "./BranchMenu";+import { BranchMenu, branchUrl } from "./BranchMenu";+import { DiffView } from "../explorer/DiffView";import { ConnectGitHubCard, GitHubRepoPicker } from "./GitHubRepoPicker";import {fetchBranchEditors,fetchGitOverview,GitOverviewError,openBranchCheckout,+ fetchBranchContents,+ fetchBranchFileDiff,+ type BranchContents,type BranchEditors,+ type BranchFile,+ type BranchFileDiff,type BranchRow,type CiState,type CiStatus,@@ -58,6 +63,8 @@ import {*/const POLL_MS = 15_000;const POLL_JITTER_MS = 3_000;+/** While GitHub's first read is still loading, the local branches are already shown and this re-asks soon. */+const POLL_LOADING_MS = 1_500;// GitHub's pull request colours: open green, merged purple, closed red, the// merge queue amber, a draft grey. Each maps to a theme token that has a light@@ -132,12 +139,14 @@ function useGitOverview(workspaceId: string | null) {let alive = true;let timer: number | undefined;let refresh = force > 0;+ let githubLoading = false;const tick = async () => {if (useEventStore.getState().activeSection === "agentic-ide") {setLoading(true);try {const next = await fetchGitOverview(workspaceId, refresh);refresh = false;+ githubLoading = next.github?.code === "loading";if (alive) {setData(next);setError("");@@ -153,7 +162,8 @@ function useGitOverview(workspaceId: string | null) {if (alive) setLoading(false);}}- if (alive) timer = window.setTimeout(tick, POLL_MS + Math.random() * POLL_JITTER_MS);+ const delay = githubLoading ? POLL_LOADING_MS + Math.random() * 500 : POLL_MS + Math.random() * POLL_JITTER_MS;+ if (alive) timer = window.setTimeout(tick, delay);};void tick();return () => {@@ -376,21 +386,92 @@ function DetailButton({);}-function DetailSection({ icon: Icon, title, testId, children }: { icon: LucideIcon; title: string; testId: string; children: ReactNode }) {+/** A file's change as one coloured letter, like the Explorer's change list. */+const FILE_STATUS: Record<BranchFile["status"], { letter: string; tone: string }> = {+ added: { letter: "A", tone: "text-success" },+ deleted: { letter: "D", tone: "text-destructive" },+ modified: { letter: "M", tone: "text-warning" },+};++function BranchFileRow({+ file,+ workspaceId,+ branch,+ base,+ remote,+}: {+ file: BranchFile;+ workspaceId: string;+ branch: string;+ base: string;+ remote: boolean;+}) {+ const t = useT();+ const [open, setOpen] = useState(false);+ const [diff, setDiff] = useState<BranchFileDiff | null>(null);+ const [error, setError] = useState("");+ useEffect(() => {+ if (!open || diff) return;+ let alive = true;+ fetchBranchFileDiff(workspaceId, branch, base, remote, file.path)+ .then((answer) => alive && setDiff(answer))+ .catch((err: Error) => alive && setError(err.message));+ return () => {+ alive = false;+ };+ }, [open, diff, workspaceId, branch, base, remote, file.path]);+ const status = FILE_STATUS[file.status];+ const slash = file.path.lastIndexOf("/");return (- <section data-testid={testId} className="space-y-1.5">- <h4 className="flex items-center gap-1.5 text-[10.5px] font-semibold uppercase tracking-wide text-muted-foreground">- <Icon className="h-3.5 w-3.5" aria-hidden />- {title}- </h4>- {children}- </section>+ <li data-testid="git-branch-file" data-path={file.path}>+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ className="flex w-full min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-left hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <ChevronRight className={cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform", open && "rotate-90")} aria-hidden />+ <span className={cn("w-3 shrink-0 text-center font-mono text-[10.5px] font-semibold", status.tone)}>{status.letter}</span>+ <span className="min-w-0 flex-1 truncate font-mono text-[11px]">+ <span className="text-foreground">{file.path.slice(slash + 1)}</span>+ {slash > 0 && <span className="ml-1.5 text-muted-foreground">{file.path.slice(0, slash)}</span>}+ </span>+ {file.added === null ? (+ <span className="shrink-0 text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.binary")}</span>+ ) : (+ <span className="shrink-0 font-mono text-[10.5px] tabular-nums">+ <span className="text-success">+{file.added}</span> <span className="text-destructive">−{file.removed}</span>+ </span>+ )}+ </button>+ {open && (+ <div data-testid="git-branch-file-diff" className="my-1 max-h-96 overflow-auto rounded-md border border-border/60 bg-background">+ {error ? (+ <p className="px-3 py-2 text-[11px] text-destructive">{error}</p>+ ) : !diff ? (+ <p className="flex items-center gap-1.5 px-3 py-2 text-[11px] text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />+ {t("ide_side_panel.git.details.loading")}+ </p>+ ) : diff.binary ? (+ <p className="px-3 py-2 text-[11px] text-muted-foreground">{t("ide_side_panel.git.details.binary")}</p>+ ) : (+ <DiffView hunks={diff.hunks} />+ )}+ </div>+ )}+ </li>);}+function DetailHeading({ children }: { children: ReactNode }) {+ return <h4 className="text-[10.5px] font-semibold uppercase tracking-wide text-muted-foreground">{children}</h4>;+}+/**- * What a clicked branch row folds open: where the branch lives on this- * computer (with a way to open that folder) and on GitHub (with a way there).+ * What a clicked branch row folds open: the branch itself — its own commits+ * and the files it changes, each file's diff one click away — plus one row of+ * ways out (an editor, the folder, GitHub, the pull request).*/function BranchDetails({row,@@ -408,6 +489,19 @@ function BranchDetails({const t = useT();const lang = useUiLanguage();const pushToast = useEventStore((state) => state.pushToast);+ const [contents, setContents] = useState<BranchContents | null>(null);+ const [error, setError] = useState("");+ useEffect(() => {+ let alive = true;+ fetchBranchContents(workspaceId, row.name, defaultBranch, row.remote_only)+ .then((answer) => alive && setContents(answer))+ .catch((err: Error) => alive && setError(err.message));+ return () => {+ alive = false;+ };+ // Re-read when the branch tip moves, not on every overview poll.+ }, [workspaceId, row.name, row.head, row.remote_only, defaultBranch]);+const url = branchUrl(repoUrl, row);const checkedOut = !row.remote_only && (row.current || Boolean(row.worktree));const pr = row.pull_requests[0];@@ -426,85 +520,123 @@ function BranchDetails({);};- const localState = row.remote_only+ const where = row.remote_only? t("ide_side_panel.git.details.local_absent"): row.current? t("ide_side_panel.git.current"): row.worktree- ? t("ide_side_panel.git.details.local_worktree")+ ? `${t("ide_side_panel.git.details.local_worktree")} ${row.worktree}`: t("ide_side_panel.git.details.local_branch_only");- const commitLine =- row.head && row.committed_at- ? `${row.head.slice(0, 7)} · ${new Intl.DateTimeFormat(lang, { dateStyle: "medium", timeStyle: "short" }).format(new Date(row.committed_at * 1000))}`- : row.head.slice(0, 7);+ const dateOf = (seconds: number) =>+ seconds ? new Intl.DateTimeFormat(lang, { dateStyle: "medium", timeStyle: "short" }).format(new Date(seconds * 1000)) : "";return (- <div data-testid="git-branch-details" className="grid gap-3 border-t border-border/50 pb-3 pl-9 pr-3 pt-2.5 text-[11.5px]">- <DetailSection icon={Laptop} title={t("ide_side_panel.git.details.local_title")} testId="git-details-local">- <p className="text-foreground">{localState}</p>- {row.worktree && <p className="break-all font-mono text-[10.5px] text-muted-foreground">{row.worktree}</p>}- {!row.remote_only && commitLine && (- <p className="font-mono text-[10.5px] text-muted-foreground">{fill(t("ide_side_panel.git.last_commit"), { date: commitLine })}</p>+ <div data-testid="git-branch-details" className="space-y-3 border-t border-border/50 pb-3 pl-8 pr-3 pt-2.5 text-[11.5px]">+ <div className="flex flex-wrap gap-1.5">+ {canOpen &&+ editors?.editors.map((editor) => (+ <DetailButton+ key={editor.id}+ icon={SquareTerminal}+ label={fill(t("ide_side_panel.git.details.open_in"), { editor: editor.label })}+ testId={`git-open-${editor.id}`}+ onClick={() => openLocal(editor.id)}+ />+ ))}+ {canOpen && (+ <DetailButton icon={FolderOpen} label={t("ide_side_panel.git.details.open_folder")} testId="git-open-folder" onClick={() => openLocal("folder")} />)}- {row.upstream && (- <p className="text-[10.5px] text-muted-foreground">- {fill(t("ide_side_panel.git.tracks"), { upstream: row.upstream, ahead: row.ahead, behind: row.behind })}- </p>+ {!checkedOut && !row.remote_only && (+ <DetailButton icon={Copy} label={t("ide_side_panel.git.menu.copy_switch")} testId="git-copy-switch" onClick={() => copy(`git switch ${row.name}`)} />)}- <div className="flex flex-wrap gap-1.5 pt-0.5">- {canOpen && (- <>- <DetailButton icon={FolderOpen} label={t("ide_side_panel.git.details.open_folder")} testId="git-open-folder" primary onClick={() => openLocal("folder")} />- {editors?.editors.map((editor) => (- <DetailButton- key={editor.id}- icon={SquareTerminal}- label={fill(t("ide_side_panel.git.details.open_in"), { editor: editor.label })}- testId={`git-open-${editor.id}`}- onClick={() => openLocal(editor.id)}- />- ))}- </>- )}- {!checkedOut && (- <DetailButton icon={Copy} label={t("ide_side_panel.git.menu.copy_switch")} testId="git-copy-switch" onClick={() => copy(`git switch ${row.name}`)} />- )}- </div>- </DetailSection>- <DetailSection icon={Globe} title={t("ide_side_panel.git.details.github_title")} testId="git-details-github">- <p className="text-foreground">- {url ? t("ide_side_panel.git.details.github_present") : repoUrl ? t("ide_side_panel.git.not_pushed") : t("ide_side_panel.git.menu.no_repo")}- </p>+ {url && <DetailButton icon={Globe} label={t("ide_side_panel.git.details.open_github")} testId="git-open-github" onClick={() => void openExternalUrl(url)} />}{pr && (- <p className="truncate text-[10.5px] text-muted-foreground">- #{pr.number} · {prStateLabel(t, pr)} · {pr.title}- </p>+ <DetailButton+ icon={PR_ICON[pr.state]}+ label={fill(t("ide_side_panel.git.menu.open_pr"), { number: pr.number })}+ testId="git-open-pr"+ onClick={() => void openExternalUrl(pr.url)}+ />)}- <div className="flex flex-wrap gap-1.5 pt-0.5">- {url && (- <DetailButton icon={ExternalLink} label={t("ide_side_panel.git.details.open_github")} testId="git-open-github" primary onClick={() => void openExternalUrl(url)} />- )}- {pr && (- <DetailButton- icon={PR_ICON[pr.state]}- label={fill(t("ide_side_panel.git.menu.open_pr"), { number: pr.number })}- testId="git-open-pr"- onClick={() => void openExternalUrl(pr.url)}- />- )}- {url && !pr && defaultBranch && row.name !== defaultBranch && (- <DetailButton- icon={GitCompareArrows}- label={fill(t("ide_side_panel.git.menu.compare"), { target: defaultBranch })}- testId="git-open-compare"- onClick={() => void openExternalUrl(`${repoUrl}/compare/${branchPath(defaultBranch)}...${branchPath(row.name)}`)}- />- )}- {row.ci.url && (- <DetailButton icon={CirclePlay} label={t("ide_side_panel.git.menu.open_ci")} testId="git-open-ci" onClick={() => void openExternalUrl(row.ci.url)} />+ {row.ci.url && (+ <DetailButton icon={CirclePlay} label={t("ide_side_panel.git.menu.open_ci")} testId="git-open-ci" onClick={() => void openExternalUrl(row.ci.url)} />+ )}+ </div>++ <p className="text-[11px] text-muted-foreground">+ <Laptop className="mr-1 inline h-3 w-3 align-[-2px]" aria-hidden />+ <span className="break-all">{where}</span>+ {row.upstream && (+ <span className="block pl-4">{fill(t("ide_side_panel.git.tracks"), { upstream: row.upstream, ahead: row.ahead, behind: row.behind })}</span>+ )}+ </p>++ {error ? (+ <p className="text-[11px] text-destructive">{error}</p>+ ) : !contents ? (+ <p data-testid="git-branch-loading" className="flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />+ {t("ide_side_panel.git.details.loading")}+ </p>+ ) : !contents.available ? (+ <p className="text-[11px] text-muted-foreground">{contents.reason}</p>+ ) : (+ <>+ <section data-testid="git-branch-commits" className="space-y-1">+ <DetailHeading>+ {contents.base+ ? fill(t("ide_side_panel.git.details.commits_vs"), { n: contents.commits.length, base: contents.base })+ : fill(t("ide_side_panel.git.details.commits_latest"), { n: contents.commits.length })}+ </DetailHeading>+ {contents.commits.length === 0 ? (+ <p className="text-[11px] text-muted-foreground">{fill(t("ide_side_panel.git.details.no_commits"), { base: contents.base })}</p>+ ) : (+ <ol className="space-y-0.5">+ {contents.commits.map((commit) => (+ <li key={commit.sha} className="flex min-w-0 items-baseline gap-2">+ {url ? (+ <button+ type="button"+ onClick={() => void openExternalUrl(`${repoUrl}/commit/${encodeURIComponent(commit.sha)}`)}+ className="shrink-0 font-mono text-[10.5px] text-info hover:underline"+ >+ {commit.sha.slice(0, 7)}+ </button>+ ) : (+ <span className="shrink-0 font-mono text-[10.5px] text-muted-foreground">{commit.sha.slice(0, 7)}</span>+ )}+ <QuickTooltip content={`${commit.subject}\n${commit.author} · ${dateOf(commit.committed_at)}`} side="bottom" className="flex min-w-0 flex-1">+ <span className="truncate text-foreground">{commit.subject}</span>+ </QuickTooltip>+ <span className="shrink-0 text-[10.5px] tabular-nums text-muted-foreground">+ {commit.committed_at ? commitDateLabel(commit.committed_at, lang) : ""}+ </span>+ </li>+ ))}+ </ol>+ )}+ {contents.commits_truncated && <p className="text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.more_commits")}</p>}+ </section>+ {contents.base && (+ <section data-testid="git-branch-files" className="space-y-1">+ <DetailHeading>{fill(t("ide_side_panel.git.details.files"), { n: contents.files.length })}</DetailHeading>+ <ul>+ {contents.files.map((file) => (+ <BranchFileRow+ key={file.path}+ file={file}+ workspaceId={workspaceId}+ branch={row.name}+ base={defaultBranch}+ remote={row.remote_only}+ />+ ))}+ </ul>+ {contents.files_truncated && <p className="text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.details.more_files")}</p>}+ </section>)}- </div>- </DetailSection>+ </>+ )}</div>);}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.tsindex 1c4316b4ae..6d5ef6c51e 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts@@ -6,6 +6,8 @@* are three separate facts on purpose — passing checks never mean "merged".*/+import type { DiffHunk } from "../explorer/explorerApi";+export type PullRequestState = "draft" | "open" | "queued" | "merged" | "closed";export type CiState = "none" | "pending" | "running" | "success" | "failure";@@ -179,3 +181,54 @@ export function openBranchCheckout(workspaceId: string, branch: string, target:body: JSON.stringify({ workspace_id: workspaceId, branch, target }),});}++export interface BranchCommit {+ sha: string;+ subject: string;+ author: string;+ committed_at: number;+}++export interface BranchFile {+ path: string;+ status: "added" | "deleted" | "modified";+ /** null for a binary file. */+ added: number | null;+ removed: number | null;+}++export interface BranchContents {+ available: boolean;+ branch: string;+ /** What the branch is compared with (`origin/main`); "" for the default branch itself. */+ base: string;+ commits: BranchCommit[];+ commits_truncated: boolean;+ files: BranchFile[];+ files_truncated: boolean;+ reason: string;+}++export interface BranchFileDiff {+ path: string;+ status: string;+ binary: boolean;+ added: number;+ removed: number;+ hunks: DiffHunk[];+ truncated: boolean;+}++function branchQuery(workspaceId: string, branch: string, base: string, remote: boolean, extra: Record<string, string> = {}): string {+ const query = new URLSearchParams({ workspace_id: workspaceId, branch, base, ...extra });+ if (remote) query.set("remote", "true");+ return query.toString();+}++export function fetchBranchContents(workspaceId: string, branch: string, base: string, remote: boolean): Promise<BranchContents> {+ return call<BranchContents>(`/api/agentic-ide/git/branch/contents?${branchQuery(workspaceId, branch, base, remote)}`);+}++export function fetchBranchFileDiff(workspaceId: string, branch: string, base: string, remote: boolean, path: string): Promise<BranchFileDiff> {+ return call<BranchFileDiff>(`/api/agentic-ide/git/branch/diff?${branchQuery(workspaceId, branch, base, remote, { path })}`);+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex c522ac10fc..415af1ceb4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -6234,16 +6234,21 @@"github_only_tip": "Nur auf GitHub, nicht auf diesem Rechner.","last_commit": "Letzter Commit: {date}","details": {- "local_title": "Dieser Rechner",- "github_title": "GitHub",- "local_absent": "Nicht auf diesem Rechner.",- "local_worktree": "In einem anderen Ordner ausgecheckt:",- "local_branch_only": "Auf diesem Rechner, aber in keinem Ordner ausgecheckt.",- "github_present": "Auf GitHub.",+ "local_absent": "Nur auf GitHub, nicht auf diesem Rechner.",+ "local_worktree": "Ausgecheckt in",+ "local_branch_only": "Auf diesem Rechner, in keinem Ordner ausgecheckt.","open_folder": "Ordner öffnen","open_in": "In {editor} öffnen","open_github": "Auf GitHub öffnen",- "open_failed": "Der Ordner konnte nicht geöffnet werden."+ "open_failed": "Der Ordner konnte nicht geöffnet werden.",+ "loading": "Branch wird gelesen…",+ "binary": "binär",+ "commits_vs": "{n} Commits, die nicht in {base} sind",+ "commits_latest": "Letzte {n} Commits",+ "no_commits": "Keine Commits über {base} hinaus.",+ "more_commits": "Ältere Commits werden nicht gezeigt.",+ "files": "{n} Dateien geändert",+ "more_files": "Es wurden mehr Dateien geändert, als hier stehen."},"merged_short": "in {target}","merged_git": "In {target} gemergt: Jeder Commit dieses Branches ist in {target} enthalten.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 148429211b..a2de358f99 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -6267,16 +6267,21 @@"github_only_tip": "Only on GitHub, not on this computer.","last_commit": "Last commit: {date}","details": {- "local_title": "This computer",- "github_title": "GitHub",- "local_absent": "Not on this computer.",- "local_worktree": "Checked out in another folder:",- "local_branch_only": "On this computer, but not checked out in any folder.",- "github_present": "On GitHub.",+ "local_absent": "Only on GitHub, not on this computer.",+ "local_worktree": "Checked out in",+ "local_branch_only": "On this computer, not checked out in any folder.","open_folder": "Open folder","open_in": "Open in {editor}","open_github": "Open on GitHub",- "open_failed": "The folder could not be opened."+ "open_failed": "The folder could not be opened.",+ "loading": "Reading the branch…",+ "binary": "binary",+ "commits_vs": "{n} commits not in {base}",+ "commits_latest": "Latest {n} commits",+ "no_commits": "No commits beyond {base}.",+ "more_commits": "Older commits are not listed.",+ "files": "{n} files changed",+ "more_files": "More files changed than are listed."},"merged_short": "in {target}","merged_git": "Merged into {target}: every commit of this branch is in {target}.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 5065a01a57..9c170a8fbf 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -6234,16 +6234,21 @@"github_only_tip": "Solo en GitHub, no está en este ordenador.","last_commit": "Último commit: {date}","details": {- "local_title": "Este ordenador",- "github_title": "GitHub",- "local_absent": "No está en este ordenador.",- "local_worktree": "Activa en otra carpeta:",- "local_branch_only": "En este ordenador, pero no está activa en ninguna carpeta.",- "github_present": "En GitHub.",+ "local_absent": "Solo en GitHub, no en este ordenador.",+ "local_worktree": "Activa en",+ "local_branch_only": "En este ordenador, no activa en ninguna carpeta.","open_folder": "Abrir carpeta","open_in": "Abrir en {editor}","open_github": "Abrir en GitHub",- "open_failed": "No se pudo abrir la carpeta."+ "open_failed": "No se pudo abrir la carpeta.",+ "loading": "Leyendo la rama…",+ "binary": "binario",+ "commits_vs": "{n} commits que no están en {base}",+ "commits_latest": "Últimos {n} commits",+ "no_commits": "Ningún commit más allá de {base}.",+ "more_commits": "Los commits más antiguos no se muestran.",+ "files": "{n} archivos cambiados",+ "more_files": "Hay más archivos cambiados de los que se muestran."},"merged_short": "en {target}","merged_git": "Fusionada en {target}: todos los commits de esta rama están en {target}.",diff --git a/tests/unit/agentic_ide/test_branch_contents.py b/tests/unit/agentic_ide/test_branch_contents.pynew file mode 100644index 0000000000..8fc82ff0cd--- /dev/null+++ b/tests/unit/agentic_ide/test_branch_contents.py@@ -0,0 +1,95 @@+"""Tests for jarvis.agentic_ide.branch_contents — reading a branch in place."""++from __future__ import annotations++import shutil+import subprocess+from pathlib import Path++import pytest++from jarvis.agentic_ide.branch_contents import branch_contents, branch_file_diff++needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")++[email protected](autouse=True)+def _isolated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ # The host's git config (signing, hooks, default branch) must not decide these tests.+ 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 _commit(root: Path, name: str, text: str, message: str) -> None:+ (root / name).write_text(text, encoding="utf-8")+ _git(root, "add", name)+ _git(+ root,+ "-c",+ "user.name=Test",+ "-c",+ "[email protected]",+ "commit",+ "-q",+ "-m",+ message,+ )+++def repo(tmp_path: Path) -> Path:+ root = tmp_path / "project"+ root.mkdir()+ _git(root, "init", "-q", "-b", "main")+ _commit(root, "a.txt", "one\ntwo\n", "start")+ _git(root, "switch", "-q", "-c", "feature/x")+ _commit(root, "a.txt", "one\nTWO\n", "change a")+ _commit(root, "b.txt", "new\n", "add b")+ _git(root, "switch", "-q", "main")+ # main moves on after the split; the branch's view must not include this.+ _commit(root, "c.txt", "main only\n", "main work")+ return root+++@needs_git+def test_a_branch_lists_its_own_commits_and_files(repo: Path) -> None:+ contents = branch_contents(repo, "feature/x", "main")+ assert contents.available and contents.base == "main"+ assert [c.subject for c in contents.commits] == ["add b", "change a"]+ assert contents.commits[0].author == "Test" and contents.commits[0].committed_at > 0+ files = {f.path: (f.status, f.added, f.removed) for f in contents.files}+ assert files == {"a.txt": ("modified", 1, 1), "b.txt": ("added", 1, 0)}+++@needs_git+def test_the_default_branch_shows_its_latest_commits(repo: Path) -> None:+ contents = branch_contents(repo, "main", "main")+ assert contents.base == ""+ assert [c.subject for c in contents.commits] == ["main work", "start"]+ assert contents.files == []+++@needs_git+def test_a_file_diff_shows_the_branch_change(repo: Path) -> None:+ diff = branch_file_diff(repo, "feature/x", "main", "a.txt")+ assert (diff.status, diff.added, diff.removed) == ("modified", 1, 1)+ kinds = [(line.kind, line.text) for hunk in diff.hunks for line in hunk.lines]+ assert ("del", "two") in kinds and ("add", "TWO") in kinds+ assert branch_file_diff(repo, "feature/x", "main", "b.txt").status == "added"+++@needs_git+def test_unknown_or_unsafe_input_is_refused(repo: Path) -> None:+ assert not branch_contents(repo, "no/such", "main").available+ assert not branch_contents(repo, "--output=x", "main").available+ gone = branch_contents(repo, "feature/x", "main", remote=True)+ assert not gone.available and "fetch" in gone.reason+ for bad in ("../outside.txt", "/etc/passwd", "--output=x"):+ with pytest.raises(ValueError):+ branch_file_diff(repo, "feature/x", "main", bad)diff --git a/tests/unit/agentic_ide/test_git_overview.py b/tests/unit/agentic_ide/test_git_overview.pyindex 6be5ecc476..a0791c6645 100644--- a/tests/unit/agentic_ide/test_git_overview.py+++ b/tests/unit/agentic_ide/test_git_overview.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport shutilimport subprocess+import threadingfrom pathlib import Pathimport pytest@@ -350,6 +351,33 @@ def test_overview_joins_pull_requests_ci_and_squash_merges(assert len(calls) == 1+@needs_git+def test_a_first_read_lists_local_branches_without_waiting_for_github(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ release = threading.Event()++ def slow_fetch(repo_name: str, token: str) -> git_overview._GitHubSnapshot:+ release.wait(5)+ return parse_github(_payload([]), fetched_at=git_overview.time.time())++ monkeypatch.setattr(git_overview, "_fetch_github", slow_fetch)+ monkeypatch.setattr(github_link, "credential", lambda: github_link.Credential("t", "app"))+ monkeypatch.setattr(github_link, "bound_repository", lambda folder: "o/slow")+ git_overview._CACHE.clear()+ info = git_overview.overview(repo, wait_for_github=False)+ assert info.github.code == "loading" and not info.github.available+ assert {row.name for row in info.branches} >= {"main", "feature/wip"}+ release.set()+ deadline = git_overview.time.time() + 5+ while git_overview.time.time() < deadline:+ later = git_overview.overview(repo, wait_for_github=False)+ if later.github.available:+ break+ git_overview.time.sleep(0.05)+ assert later.github.available++# ------------------------------------------------------------------ the one-time pick