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(agentic-ide): always show the branch a pane works in, with its pull request (#584)

Ruben Lütkef2937bde4436
diff --git a/jarvis/agentic_ide/github_status.py b/jarvis/agentic_ide/github_status.py
index 15d5ce1fad..201eef9ffe 100644
--- a/jarvis/agentic_ide/github_status.py
+++ b/jarvis/agentic_ide/github_status.py
@@ -1,4 +1,4 @@
-"""Read-only GitHub status for branches actually created by each coding session.
+"""Read-only GitHub status for the branch each coding session works in.
Unlike the repository overview, this queries the exact remote branch, including
its historical PR when GitHub has deleted the branch after merging. No local
@@ -21,7 +21,7 @@ from loguru import logger
from jarvis.agentic_ide import git_overview, github_link
from jarvis.agentic_ide.github_checks import CheckStatus, checks
-from jarvis.agentic_ide.session_branches import PaneBranchRecord, owned_branch
+from jarvis.agentic_ide.session_branches import PaneBranchRecord, pane_branch
_QUERY = """
query($owner: String!, $name: String!, $branch: String!, $ref: String!, $prIds: [ID!]!) {
@@ -269,7 +269,7 @@ def parse_status(target: Checkout, payload: dict[str, Any], fetched_at: float) -
def statuses(records: list[PaneBranchRecord] | dict[str, str]) -> dict[str, dict[str, Any] | None]:
- """One result per pane with ownership evidence; shared GitHub reads."""
+ """One result per pane that works in a branch; shared GitHub reads."""
result: dict[str, dict[str, Any] | None] = {}
# Old route versions supplied only folders: those carry no ownership proof.
if isinstance(records, dict):
@@ -279,7 +279,7 @@ def statuses(records: list[PaneBranchRecord] | dict[str, str]) -> dict[str, dict
credential_read = False
for record in records:
pane = record.pane
- owned = owned_branch(record)
+ owned = pane_branch(record)
if owned is None:
result[pane] = None
continue
diff --git a/jarvis/agentic_ide/session_branches.py b/jarvis/agentic_ide/session_branches.py
index d233953014..7d0328a3c9 100644
--- a/jarvis/agentic_ide/session_branches.py
+++ b/jarvis/agentic_ide/session_branches.py
@@ -1,7 +1,23 @@
-"""Attribute branches to a pane's successful creation calls, never to its CWD.
+"""Find the branch a pane's work belongs to, from its session's own record.
-The CLI transcript is used only as ownership evidence. GitHub remains the sole
-source of remote branch, PR and check status. Unrecognised commands fail closed.
+A pane's branch is, in this order (:func:`pane_branch`):
+
+1. the branch its session created or last changed a checkout of, whichever
+ is newer, and
+2. the branch checked out in the folder the pane runs in.
+
+The CLI transcript is used only as evidence of where a session worked. GitHub
+remains the sole source of remote branch, PR and check status. Unrecognised
+commands fail closed, which leaves the pane with its folder's branch.
+
+A creation call counts once it is confirmed, by either witness:
+
+* the tool result quotes Git's own "new branch" line, or
+* the repository's reflog records that branch as created while the call ran.
+
+The second witness is what makes this work for every coding CLI: a result that
+was piped through a filter, cut short, or written by a shell that reports no
+exit code still leaves the repository's own record of the creation.
"""
from __future__ import annotations
@@ -13,7 +29,7 @@ import shlex
import threading
import time
from collections.abc import Iterable
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any
@@ -41,6 +57,11 @@ class CreatedBranch:
folder: str
created_at: float = 0
silent_success: bool = False
+ # When the creating call started; with created_at it bounds the moment the
+ # repository must have recorded the branch.
+ called_at: float = 0
+ # False while only the command names the branch and its result does not.
+ confirmed: bool = True
_STRING = r"""(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')"""
@@ -82,8 +103,22 @@ def _unquote(value: str) -> str:
return value[1:-1] if len(value) > 1 and value[0] == value[-1] and value[0] in "\"'" else value
-def created_by_command(command: str, folder: str) -> list[CreatedBranch]:
- """Understand literal Git creation commands; checking out a branch is not creation."""
+_DRIVE_PATH = re.compile(r"/([A-Za-z])(/.*)?")
+
+
+def _enter(cwd: Path, target: str) -> Path:
+ """The directory a shell lands in after ``cd target`` from ``cwd``."""
+ if target == "~" or target[:2] in {"~/", "~\\"}:
+ return (Path.home() / target[2:]).resolve()
+ drive = _DRIVE_PATH.fullmatch(target) if os.name == "nt" else None
+ if drive:
+ # Git Bash on Windows spells a drive root as /c/.
+ return Path(f"{drive[1].upper()}:{drive[2] or '/'}").resolve()
+ return (cwd / target).resolve()
+
+
+def _git_calls(command: str, folder: str) -> list[tuple[Path, list[str], int]]:
+ """Every literal ``git`` call: its folder, its arguments, the chain's length."""
lexer = shlex.shlex(command, posix=False, punctuation_chars=";&|\n")
lexer.whitespace = " \t\r"
lexer.whitespace_split = True
@@ -99,12 +134,12 @@ def created_by_command(command: str, folder: str) -> list[CreatedBranch]:
else:
segments[-1].append(word)
cwd = Path(folder)
- found = []
+ calls = []
for args in segments:
if not args:
continue
if args[0].lower() in {"cd", "set-location", "pushd"} and len(args) == 2:
- cwd = (cwd / args[1]).resolve()
+ cwd = _enter(cwd, args[1])
continue
if args[0] not in {"git", "git.exe"}:
continue
@@ -112,8 +147,49 @@ def created_by_command(command: str, folder: str) -> list[CreatedBranch]:
root = cwd
while len(args) >= 2 and args[0] in {"-C", "-c"}:
if args[0] == "-C":
- root = (root / args[1]).resolve()
+ root = _enter(root, args[1])
args = args[2:]
+ calls.append((root, args, len(segments)))
+ return calls
+
+
+#: Git commands that change a checkout or publish from it. Reading a folder
+#: (``git log``, ``git diff``) is not working in it.
+_GIT_WRITES = frozenset(
+ {
+ "add",
+ "am",
+ "apply",
+ "checkout",
+ "cherry-pick",
+ "commit",
+ "merge",
+ "mv",
+ "pull",
+ "push",
+ "rebase",
+ "reset",
+ "restore",
+ "revert",
+ "rm",
+ "switch",
+ }
+)
+
+
+def written_by_command(command: str, folder: str) -> list[str]:
+ """The folders whose checkout this command line changed through Git."""
+ return [
+ str(root)
+ for root, args, _ in _git_calls(command, folder)
+ if args and args[0] in _GIT_WRITES
+ ]
+
+
+def created_by_command(command: str, folder: str) -> list[CreatedBranch]:
+ """Understand literal Git creation commands; checking out a branch is not creation."""
+ found = []
+ for root, args, chained in _git_calls(command, folder):
branch = ""
silent = False
if args[:2] == ["worktree", "add"] and "-b" in args:
@@ -127,16 +203,41 @@ def created_by_command(command: str, folder: str) -> list[CreatedBranch]:
branch = args[args.index(option) + 1]
elif len(args) >= 2 and args[0] == "branch" and not args[1].startswith("-"):
branch = args[1]
- silent = len(segments) == 1 and len(args) in {2, 3}
+ silent = chained == 1 and len(args) in {2, 3}
if branch and not branch.startswith("-"):
found.append(CreatedBranch(branch=branch, folder=str(root), silent_success=silent))
return found
+#: Shell tools across the coding CLIs, lower-cased and without a namespace.
+_SHELL_TOOLS = frozenset(
+ {
+ "exec",
+ "exec_command",
+ "bash",
+ "powershell",
+ "shell",
+ "run_shell_command",
+ "run_command",
+ "run_terminal_cmd",
+ }
+)
+
+
def created_branches(
- events: Iterable[dict[str, Any]], folder: str, *, not_before: float = 0
+ events: Iterable[dict[str, Any]],
+ folder: str,
+ *,
+ not_before: float = 0,
+ unconfirmed: bool = False,
) -> list[CreatedBranch]:
- calls: dict[str, list[CreatedBranch]] = {}
+ """Branches this session's shell calls created, oldest first.
+
+ With ``unconfirmed`` a successful creation call whose result does not name
+ the branch is returned too, marked ``confirmed=False``: the caller has to
+ find the creation in the repository before it counts.
+ """
+ calls: dict[str, tuple[float, list[CreatedBranch]]] = {}
found: list[CreatedBranch] = []
for event in events:
# A native conversation fork copies earlier tool records. Those belong
@@ -147,15 +248,7 @@ def created_branches(
identity = str(payload.get("call_id") or "")
if event.get("kind") == "tool_call":
tool = str(payload.get("name") or "").rsplit(".", 1)[-1].lower()
- if tool not in {
- "exec",
- "exec_command",
- "bash",
- "shell",
- "run_shell_command",
- "run_command",
- "run_terminal_cmd",
- }:
+ if tool not in _SHELL_TOOLS:
continue
arguments = payload.get("input") or {}
if not isinstance(arguments, dict):
@@ -167,7 +260,7 @@ def created_branches(
command, str((Path(folder) / cwd).resolve()) if cwd else folder
)
)
- calls[identity] = candidates
+ calls[identity] = ((event.get("ts_ms") or 0) / 1000, candidates)
elif event.get("kind") == "tool_result" and not payload.get("is_error"):
output = str(payload.get("output") or "")
names = set(_CREATED.findall(output))
@@ -176,19 +269,90 @@ def created_branches(
succeeded = bool(
re.search(r'(?:"exit_code"\s*:\s*0\b|Process exited with code 0\b)', output)
)
- for candidate in calls.pop(identity, []):
- if candidate.branch in names or (
+ called_at, candidates = calls.pop(identity, (0, []))
+ ended_at = (event.get("ts_ms") or 0) / 1000
+ for candidate in candidates:
+ confirmed = candidate.branch in names or (
candidate.silent_success and succeeded and not names and "fatal:" not in output
- ):
+ )
+ if confirmed or unconfirmed:
found.append(
CreatedBranch(
- candidate.branch, candidate.folder, (event.get("ts_ms") or 0) / 1000
+ candidate.branch,
+ candidate.folder,
+ ended_at,
+ called_at=called_at,
+ confirmed=confirmed,
+ )
+ )
+ return found
+
+
+#: Tools that write one file, lower-cased and without a namespace. An unknown
+#: tool is ignored: the session's Git writes still place it.
+_FILE_TOOLS = frozenset(
+ {
+ "write",
+ "edit",
+ "multiedit",
+ "notebookedit",
+ "write_file",
+ "replace",
+ "writefile",
+ "strreplacefile",
+ "write_to_file",
+ "replace_file_content",
+ "multi_replace_file_content",
+ }
+)
+_PATH_KEYS = ("file_path", "filePath", "notebook_path", "path", "TargetFile")
+
+
+def worked_folders(
+ events: Iterable[dict[str, Any]], folder: str, *, not_before: float = 0
+) -> list[tuple[str, float]]:
+ """Folders this session changed, oldest first: by a Git write or a file tool.
+
+ Only a call whose result came back without an error counts, and reading a
+ folder never does.
+ """
+ calls: dict[str, list[str]] = {}
+ found: list[tuple[str, float]] = []
+ for event in events:
+ if not_before and (event.get("ts_ms") or 0) < not_before * 1000:
+ continue
+ payload = event.get("payload") or {}
+ identity = str(payload.get("call_id") or "")
+ if event.get("kind") == "tool_call":
+ tool = str(payload.get("name") or "").rsplit(".", 1)[-1].lower()
+ arguments = payload.get("input") or {}
+ if not isinstance(arguments, dict):
+ continue
+ folders: list[str] = []
+ if tool in _SHELL_TOOLS:
+ for command, cwd in _commands(arguments):
+ folders.extend(
+ written_by_command(
+ command, str((Path(folder) / cwd).resolve()) if cwd else folder
)
)
+ elif tool in _FILE_TOOLS:
+ target = next(
+ (arguments[key] for key in _PATH_KEYS if isinstance(arguments.get(key), str)),
+ "",
+ )
+ if target:
+ folders.append(str(_enter(Path(folder), target).parent))
+ if folders:
+ calls[identity] = folders
+ elif event.get("kind") == "tool_result" and not payload.get("is_error"):
+ at = (event.get("ts_ms") or 0) / 1000
+ found.extend((written, at) for written in calls.pop(identity, []))
return found
-_cache: dict[tuple[str, str, str, float], tuple[float, list[CreatedBranch]]] = {}
+_Evidence = tuple[float, list[CreatedBranch], list[tuple[str, float]]]
+_cache: dict[tuple[str, str, str, float], _Evidence] = {}
_cache_lock = threading.Lock()
@@ -198,32 +362,189 @@ def _common(folder: str) -> str:
return os.path.normcase(str((path / value.strip()).resolve())) if value else ""
-def owned_branch(record: PaneBranchRecord) -> CreatedBranch | None:
- if record.created_branch:
- return CreatedBranch(record.created_branch, record.folder)
+_REFLOG_ENTRY = re.compile(r"@\{(\d+)\}\t(.*)")
+# Transcript and reflog clocks are the same machine's; the reflog keeps whole
+# seconds, the transcript stamps a call a moment after the model emitted it.
+_CLOCK_SLACK = 2
+
+
+_creations: dict[tuple[str, str, float, float], bool] = {}
+
+
+def _recorded_creation(folder: str, branch: str, called_at: float, ended_at: float) -> bool:
+ """Did this repository record ``branch`` as created while the call ran?
+
+ The window lies in the past and a reflog entry never changes, so an answer
+ Git actually gave stays valid; a read that failed is asked again.
+ """
+ if not called_at or not ended_at or ended_at < called_at:
+ return False
+ key = (os.path.normcase(folder), branch, called_at, ended_at)
+ with _cache_lock:
+ known = _creations.get(key)
+ if known is not None:
+ return known
+ log = git_overview._out(
+ ["log", "-g", "--date=unix", "--format=%gd%x09%gs", f"refs/heads/{branch}", "--"],
+ Path(folder),
+ )
+ if log is None:
+ return False
+ recorded = False
+ for line in log.splitlines():
+ entry = _REFLOG_ENTRY.search(line)
+ if entry is None or not entry[2].startswith("branch: Created from"):
+ continue
+ if called_at - _CLOCK_SLACK <= int(entry[1]) <= ended_at + _CLOCK_SLACK:
+ recorded = True
+ break
+ with _cache_lock:
+ if len(_creations) >= 512:
+ _creations.clear()
+ _creations[key] = recorded
+ return recorded
+
+
+def _evidence(record: PaneBranchRecord) -> tuple[list[CreatedBranch], list[tuple[str, float]]]:
+ """What this session's own record says it created and where it wrote."""
if not record.session_id or not agent_transcript.can_read(record.agent):
- return None
+ return [], []
key = (record.history_id, record.session_id, record.folder, record.started_at)
now = time.monotonic()
with _cache_lock:
cached = _cache.get(key)
- if cached is None or now - cached[0] >= 15:
- events = (
- agent_transcript.read_events(record.agent, record.session_id, home=record.home) or []
- )
- candidates = created_branches(events, record.folder, not_before=record.started_at)
- with _cache_lock:
- _cache[key] = (now, candidates)
- for expired in [key for key, (at, _) in _cache.items() if now - at > 300]:
- del _cache[expired]
- else:
- candidates = cached[1]
+ if cached is not None and now - cached[0] < 15:
+ return cached[1], cached[2]
+ events = agent_transcript.read_events(record.agent, record.session_id, home=record.home) or []
+ candidates = created_branches(
+ events, record.folder, not_before=record.started_at, unconfirmed=True
+ )
+ worked = worked_folders(events, record.folder, not_before=record.started_at)
+ with _cache_lock:
+ _cache[key] = (now, candidates, worked)
+ for expired in [key for key, entry in _cache.items() if now - entry[0] > 300]:
+ del _cache[expired]
+ return candidates, worked
+
+
+def owned_branch(record: PaneBranchRecord) -> CreatedBranch | None:
+ """The newest branch this pane demonstrably created."""
+ if record.created_branch:
+ return CreatedBranch(record.created_branch, record.folder)
+ candidates, _ = _evidence(record)
if not candidates:
return None
root = _common(record.folder)
if not root:
return None
for candidate in reversed(candidates):
- if _common(candidate.folder) == root:
+ if candidate.confirmed and _common(candidate.folder) == root:
return candidate
+ # The result did not name the branch, or the command reached this
+ # repository by a path this module cannot follow (a shell variable).
+ # The pane's own repository then has to show the creation inside the
+ # call.
+ if _recorded_creation(
+ record.folder, candidate.branch, candidate.called_at, candidate.created_at
+ ):
+ return replace(candidate, folder=record.folder, confirmed=True)
+ return None
+
+
+@dataclass(frozen=True)
+class _Repository:
+ read_at: float
+ # (folder, branch) of every checkout with a branch out, longest folder first.
+ checkouts: list[tuple[str, str]]
+ default_branch: str
+
+
+_repositories: dict[str, _Repository] = {}
+
+
+def _key(folder: str) -> str:
+ return os.path.normcase(os.path.normpath(folder))
+
+
+def _repository(folder: str, root: str) -> _Repository:
+ """The repository's checkouts and default branch; one read serves every pane."""
+ now = time.monotonic()
+ with _cache_lock:
+ known = _repositories.get(root)
+ if known is not None and now - known.read_at < 15:
+ return known
+ path = Path(folder)
+ checkouts: list[tuple[str, str]] = []
+ worktree = ""
+ for line in (git_overview._out(["worktree", "list", "--porcelain"], path) or "").splitlines():
+ if line.startswith("worktree "):
+ worktree = _key(line[len("worktree ") :])
+ elif line.startswith("branch refs/heads/") and worktree:
+ checkouts.append((worktree, line[len("branch refs/heads/") :]))
+ checkouts.sort(key=lambda entry: len(entry[0]), reverse=True)
+ head = git_overview._out(
+ ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], path
+ )
+ repository = _Repository(now, checkouts, (head or "").strip().removeprefix("origin/"))
+ with _cache_lock:
+ _repositories[root] = repository
+ return repository
+
+
+def _worked_branch(record: PaneBranchRecord) -> tuple[str, float] | None:
+ """The feature branch out in the checkout this session last changed.
+
+ The default branch does not count: a command run in the main checkout must
+ not hide the feature branch the session has been building.
+ """
+ _, worked = _evidence(record)
+ if not worked:
+ return None
+ root = _common(record.folder)
+ if not root:
+ return None
+ repository = _repository(record.folder, root)
+ default = {repository.default_branch} if repository.default_branch else {"main", "master"}
+ for folder, at in reversed(worked):
+ touched = _key(folder)
+ for checkout, branch in repository.checkouts:
+ if touched == checkout or touched.startswith(checkout + os.sep):
+ if branch not in default:
+ return branch, at
+ break
return None
+
+
+@dataclass(frozen=True)
+class PaneBranch:
+ branch: str
+ folder: str
+ # Set only for a branch the pane created: a pull request older than this
+ # belongs to an earlier branch of the same name.
+ created_at: float = 0
+
+
+def pane_branch(record: PaneBranchRecord) -> PaneBranch | None:
+ """The branch a pane's work belongs to.
+
+ In this order: the branch its session created or last changed a checkout
+ of, whichever is newer, and failing both the branch checked out where the
+ pane runs. A detached HEAD has none.
+ """
+ created = owned_branch(record)
+ if record.created_branch and created is not None:
+ return PaneBranch(created.branch, created.folder)
+ worked = _worked_branch(record)
+ if created is not None and (
+ worked is None or worked[0] == created.branch or created.created_at >= worked[1]
+ ):
+ return PaneBranch(created.branch, created.folder, created.created_at)
+ if worked is not None:
+ return PaneBranch(worked[0], record.folder)
+ path = Path(record.folder)
+ head = (
+ git_overview._out(["symbolic-ref", "--quiet", "--short", "HEAD"], path)
+ if path.is_dir()
+ else None
+ )
+ return PaneBranch(head.strip(), record.folder) if head and head.strip() else None
diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.py
index 771d63f9e9..2c628dfffa 100644
--- a/jarvis/ui/web/agentic_ide_git_routes.py
+++ b/jarvis/ui/web/agentic_ide_git_routes.py
@@ -145,7 +145,7 @@ def workspace_overview(
@router.get("/session-status", summary="Current GitHub branch, pull request and CI status per pane")
def session_github_status(workspace_id: str = Query(..., min_length=1)) -> dict:
- """Read GitHub state only for a branch this pane demonstrably created."""
+ """Read GitHub state for the branch each pane works in."""
session = get_registry().get(workspace_id)
if session is None:
raise HTTPException(status_code=404, detail="Workspace not found.")
diff --git a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.test.tsx
index d3b772f9dc..b8465776ad 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.test.tsx
@@ -20,12 +20,27 @@ function status(extra: Partial<SessionGitHubStatus> = {}): SessionGitHubStatus {
}
describe("session GitHub link", () => {
- it.each([null, status({ published: false }), status({ owned: false }),
- status({ owned: undefined as unknown as boolean })])("hides unconfirmed session branches", (value) => {
+ it.each([null, status({ owned: false }),
+ status({ owned: undefined as unknown as boolean })])("hides a pane without a branch", (value) => {
const { container } = render(<GitHubStatusBadge status={value} appearance="dark" />);
expect(container.innerHTML).toBe("");
});
+ it("shows a quiet branch symbol while the branch is only local", () => {
+ render(<GitHubStatusBadge status={status({ published: false, state: "branch", number: null })} appearance="dark" />);
+ const symbol = screen.getByTestId("session-github-status");
+ expect(symbol.getAttribute("role")).toBe("img");
+ expect(symbol.getAttribute("aria-label")).toBe("owner/repo · feature/test: Not on GitHub yet");
+ expect(symbol.title).toContain("Not on GitHub yet");
+ expect(symbol.querySelectorAll("svg")).toHaveLength(1);
+ expect(screen.queryByRole("link")).toBeNull();
+ });
+
+ it("does not claim a local branch is unpublished while GitHub cannot be read", () => {
+ render(<GitHubStatusBadge status={status({ published: false, available: false })} appearance="dark" />);
+ expect(screen.getByTestId("session-github-status").title).toContain("GitHub status unavailable");
+ });
+
it("renders just one quiet icon even with running CI and merge warnings", () => {
render(<GitHubStatusBadge status={status({ merge_status: "dirty", review: "changes_requested" })} appearance="dark" />);
const link = screen.getByRole("link");
diff --git a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
index 1092b25e70..56fb89eb7d 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
@@ -18,20 +18,30 @@ export function GitHubStatusBadge({ status, appearance }: {
appearance: TerminalAppearance;
}) {
const t = useT();
- if (!status?.owned || !status.published) return null;
+ if (!status?.owned) return null;
if (!/^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9._-]+$/.test(status.repo) || !status.branch) return null;
+ const identity = `${status.repo} · ${status.branch}`;
+ const unavailable = !status.available || Date.now() / 1000 - status.fetched_at > 60;
+ if (!status.published) {
+ // Nothing on GitHub to open yet: the pane still says which branch its work is on.
+ const label = t(unavailable ? "ide_panes.github.unavailable" : "ide_panes.github.local_only");
+ return <span data-header-control="true" data-testid="session-github-status" role="img"
+ aria-label={`${identity}: ${label}`} title={`${identity}\n${label}`}
+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center opacity-50"
+ style={{ color: PANE_BRAND[appearance].inkMuted }}>
+ <GitHubIcon name="git-branch" width={16} height={16} className="block shrink-0" />
+ </span>;
+ }
// The PR may belong to an upstream repository when this branch is a fork.
const pullRequest = /^https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9._-]+\/pull\/([1-9]\d*)$/.exec(status.url);
const url = pullRequest ? status.url : `https://github.com/${status.repo}/tree/${encodeURIComponent(status.branch)}`;
const destination = pullRequest
? fill(t("ide_panes.github.dest_pr"), { number: pullRequest[1] })
: t("ide_panes.github.dest_branch");
- const unavailable = !status.available || Date.now() / 1000 - status.fetched_at > 60;
const [icon, labelKey] = unavailable
? ["git-branch" as const, "ide_panes.github.unavailable"]
: PR[status.state] ?? ["git-branch" as const, "ide_panes.github.branch_generic"];
const label = t(labelKey);
- const identity = `${status.repo} · ${status.branch}`;
return <a data-header-control="true" data-testid="session-github-status"
href={url} target="_blank" rel="noopener noreferrer"
aria-label={fill(t("ide_panes.github.open_aria"), { destination, identity })}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts b/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
index 8d4bf72947..d675d48683 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
@@ -33,9 +33,12 @@ type Entry = {
};
const entries = new Map<string, Entry>();
const EMPTY: Panes = {};
+// A workspace's last answer outlives its listeners: a pane coming back on
+// stage shows its branch at once, and the refresh follows.
+const remembered = new Map<string, Panes>();
function start(workspaceId: string): Entry {
- const entry: Entry = { panes: EMPTY, listeners: new Set(), stop: () => {} };
+ const entry: Entry = { panes: remembered.get(workspaceId) ?? EMPTY, listeners: new Set(), stop: () => {} };
let disposed = false;
let controller: AbortController | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -121,6 +124,7 @@ export function useSessionGitHub(workspaceId?: string, pane?: string): SessionGi
return () => {
entry.listeners.delete(listener);
if (!entry.listeners.size) {
+ remembered.set(workspaceId, entry.panes);
entry.stop();
entries.delete(workspaceId);
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index c077cddd1a..d5a71b9970 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -8689,6 +8689,7 @@
"state_closed": "Ohne Merge geschlossen",
"unavailable": "GitHub-Status nicht verfügbar",
"branch_generic": "GitHub-Branch",
+ "local_only": "Noch nicht auf GitHub",
"dest_pr": "Pull Request #{number}",
"dest_branch": "Branch",
"open_aria": "GitHub {destination} öffnen: {identity}",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 5eb07a5e74..cf02940e14 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -8689,6 +8689,7 @@
"state_closed": "Closed without merging",
"unavailable": "GitHub status unavailable",
"branch_generic": "GitHub branch",
+ "local_only": "Not on GitHub yet",
"dest_pr": "pull request #{number}",
"dest_branch": "branch",
"open_aria": "Open GitHub {destination}: {identity}",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index a29045bc00..8753aafa46 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -8689,6 +8689,7 @@
"state_closed": "Cerrada sin fusionar",
"unavailable": "Estado de GitHub no disponible",
"branch_generic": "Rama de GitHub",
+ "local_only": "Aún no está en GitHub",
"dest_pr": "pull request #{number}",
"dest_branch": "rama",
"open_aria": "Abrir {destination} de GitHub: {identity}",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
index ce10fab066..55bad54858 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
@@ -8689,6 +8689,7 @@
"state_closed": "Fechado sem merge",
"unavailable": "Estado do GitHub indisponível",
"branch_generic": "Ramo do GitHub",
+ "local_only": "Ainda não está no GitHub",
"dest_pr": "pull request #{number}",
"dest_branch": "ramo",
"open_aria": "Abrir {destination} do GitHub: {identity}",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
index 7fda6646f8..30e3f526ad 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -8689,6 +8689,7 @@
"state_closed": "未合并即关闭",
"unavailable": "GitHub 状态不可用",
"branch_generic": "GitHub 分支",
+ "local_only": "尚未推送到 GitHub",
"dest_pr": "拉取请求 #{number}",
"dest_branch": "分支",
"open_aria": "打开 GitHub {destination}:{identity}",
diff --git a/tests/unit/agentic_ide/test_github_status.py b/tests/unit/agentic_ide/test_github_status.py
index c544eb48c7..7b5e0e651e 100644
--- a/tests/unit/agentic_ide/test_github_status.py
+++ b/tests/unit/agentic_ide/test_github_status.py
@@ -85,7 +85,7 @@ def test_pr_states_survive_branch_deletion(state, extra, expected):
assert value.ci.state == "success"
-def test_local_only_has_no_badge_and_green_checks_do_not_mean_merged():
+def test_local_only_is_unpublished_and_green_checks_do_not_mean_merged():
assert not status.parse_status(TARGET, payload(head=""), 1).published
value = status.parse_status(TARGET, payload(checks=rollup()), 1)
assert value.published and value.state == "branch"
@@ -213,7 +213,7 @@ def test_multiple_panes_share_requests_and_errors_are_unknown(monkeypatch):
monkeypatch.setattr(status, "checkout", local)
monkeypatch.setattr(
status,
- "owned_branch",
+ "pane_branch",
lambda record: SimpleNamespace(folder="worktree", branch=TARGET.branch, created_at=0),
)
monkeypatch.setattr(
diff --git a/tests/unit/agentic_ide/test_session_branches.py b/tests/unit/agentic_ide/test_session_branches.py
index 486267516d..052d7ffe5f 100644
--- a/tests/unit/agentic_ide/test_session_branches.py
+++ b/tests/unit/agentic_ide/test_session_branches.py
@@ -1,6 +1,8 @@
"""Ownership requires successful creation in this session's own tool record."""
import json
+import subprocess
+import time
from dataclasses import replace
import pytest
@@ -80,9 +82,7 @@ def test_code_mode_literal_arguments_and_windows_paths(tmp_path):
cwd = str(tmp_path / "a folder")
source = (
'text(await tools.exec_command({cmd: "git worktree add -b codex/fix ../fork HEAD", '
- 'workdir: '
- + json.dumps(cwd)
- + "}));"
+ "workdir: " + json.dumps(cwd) + "}));"
)
found = branches.created_branches(
[
@@ -178,3 +178,226 @@ def test_codex_item_ids_do_not_break_call_result_matching(monkeypatch, tmp_path)
]
assert paired == ["shared", "shared"]
assert branches.created_branches(events, str(tmp_path))[0].branch == "owned"
+
+
+# --- the repository as second witness: every coding CLI, not one output format ---
+
+
+def timed(command, output, *, name="Bash", started=1000.0, ended=1010.0, identity="call"):
+ return [
+ {
+ "kind": "tool_call",
+ "ts_ms": started * 1000,
+ "payload": {"call_id": identity, "name": name, "input": {"command": command}},
+ },
+ {
+ "kind": "tool_result",
+ "ts_ms": ended * 1000,
+ "payload": {"call_id": identity, "output": output, "is_error": False},
+ },
+ ]
+
+
+def _git(repo, *args):
+ subprocess.run(
+ ["git", "-C", str(repo), "-c", "[email protected]", "-c", "user.name=T", *args],
+ check=True,
+ capture_output=True,
+ )
+
+
+def repository(tmp_path, monkeypatch):
+ branches._cache.clear()
+ branches._creations.clear()
+ monkeypatch.setattr(agent_transcript, "can_read", lambda _: True)
+ _git(tmp_path, "init", "-q", "-b", "main")
+ _git(tmp_path, "commit", "-q", "--allow-empty", "--no-verify", "-m", "chore: seed")
+ return tmp_path
+
+
+def _pane(repo, monkeypatch, events, agent="claude"):
+ monkeypatch.setattr(agent_transcript, "read_events", lambda *_, **__: events)
+ return branches.PaneBranchRecord("t1", "history", str(repo), agent, "session")
+
+
+def test_result_that_does_not_name_the_branch_stays_unconfirmed(tmp_path):
+ events = timed("git worktree add -b claude/topic ../wt origin/main | tail -1", "HEAD is now")
+
+ assert branches.created_branches(events, str(tmp_path)) == []
+ (found,) = branches.created_branches(events, str(tmp_path), unconfirmed=True)
+ assert (found.branch, found.confirmed) == ("claude/topic", False)
+ assert (found.called_at, found.created_at) == (1000.0, 1010.0)
+
+
[email protected]("tool", ["Bash", "PowerShell", "shell", "run_shell_command"])
+def test_every_shell_tool_is_read(tool, tmp_path):
+ events = timed("git switch -c owned", "Switched to a new branch 'owned'", name=tool)
+
+ assert [entry.branch for entry in branches.created_branches(events, str(tmp_path))] == ["owned"]
+
+
+def test_repository_record_confirms_a_filtered_result(repository, monkeypatch):
+ started = time.time()
+ _git(repository, "branch", "claude/topic")
+ events = timed(
+ "git worktree add -b claude/topic ../wt main 2>&1 | tail -1",
+ "HEAD is now at 1234567 chore: seed",
+ started=started - 1,
+ ended=time.time() + 1,
+ )
+
+ owned = branches.owned_branch(_pane(repository, monkeypatch, events))
+
+ assert owned is not None and owned.branch == "claude/topic"
+ assert owned.folder == str(repository)
+
+
+def test_repository_record_confirms_a_path_this_module_cannot_follow(repository, monkeypatch):
+ started = time.time()
+ _git(repository, "branch", "owned")
+ events = timed(
+ 'cd "/c/somewhere/else" && git switch -c owned',
+ "Switched to a new branch 'owned'",
+ started=started - 1,
+ ended=time.time() + 1,
+ )
+
+ assert branches.owned_branch(_pane(repository, monkeypatch, events)).branch == "owned"
+
+
+def test_branch_that_existed_before_the_call_is_not_owned(repository, monkeypatch):
+ _git(repository, "branch", "claude/topic")
+ later = time.time() + 3600
+ events = timed(
+ "git worktree add -b claude/topic ../wt main | tail -1",
+ "nothing useful",
+ started=later,
+ ended=later + 5,
+ )
+
+ assert branches.owned_branch(_pane(repository, monkeypatch, events)) is None
+
+
+def test_creation_in_another_repository_is_not_owned(repository, monkeypatch):
+ now = time.time()
+ events = timed("git -C ../elsewhere switch -c owned | tail -1", "", started=now - 1, ended=now)
+
+ assert branches.owned_branch(_pane(repository, monkeypatch, events)) is None
+
+
+def test_call_without_a_clock_is_never_confirmed_by_the_repository(repository, monkeypatch):
+ _git(repository, "branch", "owned")
+ events = [call({"command": "git switch -c owned | tail -1"}, name="Bash"), result("")]
+ events[1]["ts_ms"] = time.time() * 1000
+
+ assert branches.owned_branch(_pane(repository, monkeypatch, events)) is None
+
+
+# --- the branch a pane works in: created, changed, or simply checked out ---
+
+
+def wrote(path, *, name="Edit", at=2000.0, identity="write", key="file_path"):
+ return [
+ {
+ "kind": "tool_call",
+ "ts_ms": at * 1000,
+ "payload": {"call_id": identity, "name": name, "input": {key: str(path)}},
+ },
+ {
+ "kind": "tool_result",
+ "ts_ms": at * 1000,
+ "payload": {"call_id": identity, "output": "ok", "is_error": False},
+ },
+ ]
+
+
+def test_reading_a_folder_is_not_working_in_it(tmp_path):
+ events = timed("git -C ../other log --oneline; git -C ../other diff", "abc")
+
+ assert branches.worked_folders(events, str(tmp_path)) == []
+
+
+def test_git_writes_and_file_tools_place_the_session(tmp_path):
+ events = timed("cd ../wt && git commit -m x", "", ended=1010.0) + wrote(
+ tmp_path / "pkg" / "a.py", name="Write"
+ )
+
+ assert branches.worked_folders(events, str(tmp_path)) == [
+ (str((tmp_path / ".." / "wt").resolve()), 1010.0),
+ (str(tmp_path / "pkg"), 2000.0),
+ ]
+
+
+def test_failed_write_places_nobody(tmp_path):
+ events = timed("git commit -m x", "nothing to commit")
+ events[1]["payload"]["is_error"] = True
+
+ assert branches.worked_folders(events, str(tmp_path)) == []
+
+
+def feature_checkout(repository):
+ branches._repositories.clear()
+ checkout = repository / "wt"
+ _git(repository, "worktree", "add", "-q", "-b", "feature/x", str(checkout))
+ return checkout
+
+
+ "tool, key", [("Edit", "file_path"), ("write_file", "file_path"), ("WriteFile", "path")]
+)
+def test_pane_works_in_the_branch_of_the_checkout_it_changed(
+ repository, feature_checkout, monkeypatch, tool, key
+):
+ events = wrote(feature_checkout / "pkg" / "a.py", name=tool, key=key)
+
+ found = branches.pane_branch(_pane(repository, monkeypatch, events))
+
+ assert (found.branch, found.created_at) == ("feature/x", 0)
+
+
+def test_a_commit_in_another_checkout_places_the_pane(repository, feature_checkout, monkeypatch):
+ events = timed(f'git -C "{feature_checkout}" commit --allow-empty -m x', "[feature/x 1] x")
+
+ assert branches.pane_branch(_pane(repository, monkeypatch, events)).branch == "feature/x"
+
+
+def test_default_branch_work_does_not_hide_the_feature_branch(
+ repository, feature_checkout, monkeypatch
+):
+ events = wrote(feature_checkout / "a.py", at=2000.0) + timed(
+ "git add README.md", "", started=3000.0, ended=3001.0
+ )
+
+ assert branches.pane_branch(_pane(repository, monkeypatch, events)).branch == "feature/x"
+
+
+def test_pane_without_evidence_gets_the_branch_of_its_folder(
+ repository, feature_checkout, monkeypatch
+):
+ reader = timed("git -C wt log --oneline", "abc")
+
+ assert branches.pane_branch(_pane(repository, monkeypatch, reader)).branch == "main"
+ in_checkout = branches.PaneBranchRecord("t2", "other", str(feature_checkout))
+ assert branches.pane_branch(in_checkout).branch == "feature/x"
+
+
+def test_newer_created_branch_wins_and_keeps_its_creation_time(
+ repository, feature_checkout, monkeypatch
+):
+ started = time.time()
+ _git(repository, "branch", "claude/topic")
+ events = wrote(feature_checkout / "a.py", at=started - 500) + timed(
+ "git branch claude/topic | tail -1", "", started=started - 1, ended=time.time() + 1
+ )
+
+ found = branches.pane_branch(_pane(repository, monkeypatch, events))
+
+ assert found.branch == "claude/topic" and found.created_at > 0
+
+
+def test_detached_head_has_no_branch(repository):
+ _git(repository, "checkout", "-q", "--detach", "HEAD")
+
+ assert branches.pane_branch(branches.PaneBranchRecord("t1", "h", str(repository))) is None