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.

claude/pane branch list (#607)

Ruben Lütkeeeabe3b8c9b0
diff --git a/jarvis/agentic_ide/github_status.py b/jarvis/agentic_ide/github_status.py
index 201eef9ffe..f8a896fe02 100644
--- a/jarvis/agentic_ide/github_status.py
+++ b/jarvis/agentic_ide/github_status.py
@@ -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, pane_branch
+from jarvis.agentic_ide.session_branches import PaneBranchRecord, pane_branches
_QUERY = """
query($owner: String!, $name: String!, $branch: String!, $ref: String!, $prIds: [ID!]!) {
@@ -137,6 +137,8 @@ class BranchStatus:
merge_status: str = ""
review: str = ""
locked: bool = False
+ # The session's other branches, newest first; set on the one a header shows.
+ others: list[BranchStatus] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@@ -149,6 +151,17 @@ class _Snapshot:
fetched_at: float = 0
reason: str = ""
pr_ids: list[str] = field(default_factory=list)
+ # The pull request is merged or closed: that verdict is read again rarely.
+ settled: bool = False
+
+
+#: States a pull request does not leave by itself.
+SETTLED_STATES = frozenset({"merged", "closed"})
+_LIVE_TTL = 20
+# A session's finished branches are listed beside its current one. Reading each
+# of them every 20 seconds would spend the hourly GitHub budget on answers that
+# no longer change; a reopened or reused branch shows up after this long.
+_SETTLED_TTL = 300
@lru_cache(maxsize=256)
@@ -160,7 +173,8 @@ def _slot(repo: str, branch: str, credential_id: str) -> _Snapshot:
def _snapshot(target: Checkout, token: str) -> _Snapshot:
cached = _slot(target.repo, target.branch, hashlib.sha256(token.encode()).hexdigest())
with cached.lock:
- if time.time() - cached.fetched_at < 20:
+ ttl = _SETTLED_TTL if cached.settled and not cached.reason else _LIVE_TTL
+ if time.time() - cached.fetched_at < ttl:
return cached
owner, name = target.repo.split("/", 1)
try:
@@ -183,6 +197,10 @@ def _snapshot(target: Checkout, token: str) -> _Snapshot:
matching.sort(key=lambda pr: (pr.get("state") != "OPEN", -int(pr.get("number") or 0)))
cached.pr_ids = [str(matching[0]["id"])] if matching else cached.pr_ids
cached.reason = ""
+ read = parse_status(target, payload, 0)
+ # Neither a finished pull request nor a branch that exists nowhere
+ # changes from one poll to the next.
+ cached.settled = read.state in SETTLED_STATES or not (read.published or target.head)
except github_link.GitHubError as exc:
# Retain only identity evidence on failure. The UI suppresses all
# previous success/merge colours while available is false.
@@ -268,8 +286,22 @@ def parse_status(target: Checkout, payload: dict[str, Any], fetched_at: float) -
return status
+def _foreground(listed: list[BranchStatus]) -> BranchStatus:
+ """The branch a header shows: unfinished work before finished work.
+
+ ``listed`` leads with the branch the pane works in now. It stays in front
+ unless its pull request is merged or closed while another branch of the
+ session is still open; then the open one is what the pane still owes.
+ """
+ return next((status for status in listed if status.state not in SETTLED_STATES), listed[0])
+
+
def statuses(records: list[PaneBranchRecord] | dict[str, str]) -> dict[str, dict[str, Any] | None]:
- """One result per pane that works in a branch; shared GitHub reads."""
+ """One result per pane that works in a branch; shared GitHub reads.
+
+ A session that worked on several branches gets the others under
+ ``others``, newest first.
+ """
result: dict[str, dict[str, Any] | None] = {}
# Old route versions supplied only folders: those carry no ownership proof.
if isinstance(records, dict):
@@ -277,30 +309,40 @@ def statuses(records: list[PaneBranchRecord] | dict[str, str]) -> dict[str, dict
targets: dict[tuple[str, str, float], Checkout | None] = {}
credential: github_link.Credential | None = None
credential_read = False
+ now = time.time()
for record in records:
- pane = record.pane
- owned = pane_branch(record)
- if owned is None:
- result[pane] = None
- continue
- key = (owned.folder, owned.branch, owned.created_at)
- if key not in targets:
- targets[key] = checkout(*key)
- target = targets[key]
- if target is None:
- result[pane] = None
+ listed: list[BranchStatus] = []
+ for owned in pane_branches(record):
+ key = (owned.folder, owned.branch, owned.created_at)
+ if key not in targets:
+ targets[key] = checkout(*key)
+ target = targets[key]
+ if target is None:
+ continue
+ if not credential_read:
+ credential = github_link.credential()
+ credential_read = True
+ if credential is None:
+ status = parse_status(target, {}, 0)
+ status.available = False
+ status.reason = "GitHub is not connected."
+ else:
+ snapshot = _snapshot(target, credential.token)
+ # A settled verdict is served from a longer cache and does not
+ # go stale the way a running check does.
+ read_at = now if snapshot.settled else snapshot.fetched_at
+ status = parse_status(target, snapshot.payload, read_at)
+ status.available = not snapshot.reason
+ status.reason = snapshot.reason
+ # A branch that is gone locally belongs to this pane only if GitHub
+ # shows a pull request opened from it after the pane created it.
+ if owned.unproven and (status.number is None or not status.available):
+ continue
+ listed.append(status)
+ if not listed:
+ result[record.pane] = None
continue
- if not credential_read:
- credential = github_link.credential()
- credential_read = True
- if credential is None:
- status = parse_status(target, {}, 0)
- status.available = False
- status.reason = "GitHub is not connected."
- else:
- snapshot = _snapshot(target, credential.token)
- status = parse_status(target, snapshot.payload, snapshot.fetched_at)
- status.available = not snapshot.reason
- status.reason = snapshot.reason
- result[pane] = status.to_dict()
+ shown = _foreground(listed)
+ shown.others = [status for status in listed if status is not shown]
+ result[record.pane] = shown.to_dict()
return result
diff --git a/jarvis/agentic_ide/session_branches.py b/jarvis/agentic_ide/session_branches.py
index 7d0328a3c9..0ec55208f9 100644
--- a/jarvis/agentic_ide/session_branches.py
+++ b/jarvis/agentic_ide/session_branches.py
@@ -28,7 +28,7 @@ import re
import shlex
import threading
import time
-from collections.abc import Iterable
+from collections.abc import Iterable, Iterator
from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any
@@ -117,16 +117,31 @@ def _enter(cwd: Path, target: str) -> Path:
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")
+def _lex(text: str) -> list[str] | None:
+ lexer = shlex.shlex(text, posix=False, punctuation_chars=";&|\n")
lexer.whitespace = " \t\r"
lexer.whitespace_split = True
try:
- words = [_unquote(word) for word in lexer]
+ return [_unquote(word) for word in lexer]
except ValueError:
- logger.debug("Session branch: incomplete quoted command")
- return []
+ logger.debug("Session branch: unbalanced quotes, this text is not read as one command")
+ return None
+
+
+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."""
+ words = _lex(command)
+ if words is None:
+ # A heredoc body or a quote that spans lines breaks the whole command.
+ # The lines that stand on their own are still commands.
+ words = []
+ for line in command.splitlines():
+ part = _lex(line)
+ if part:
+ words.extend([*part, "\n"])
+ if not words:
+ logger.debug("Session branch: incomplete quoted command")
+ return []
segments: list[list[str]] = [[]]
for word in words:
if word and all(character in ";&|\n" for character in word):
@@ -427,28 +442,74 @@ def _evidence(record: PaneBranchRecord) -> tuple[list[CreatedBranch], list[tuple
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)
+_absent: dict[tuple[str, str], tuple[float, bool]] = {}
+
+
+def _gone(folder: str, root: str, branch: str) -> bool:
+ """Is ``branch`` no longer a local branch of this repository?"""
+ key = (root, branch)
+ now = time.monotonic()
+ with _cache_lock:
+ known = _absent.get(key)
+ if known is not None and now - known[0] < 60:
+ return known[1]
+ listed = git_overview._out(
+ ["for-each-ref", "--count=1", "--format=%(refname)", f"refs/heads/{branch}"], Path(folder)
+ )
+ if listed is None:
+ return False
+ gone = not listed.strip()
+ with _cache_lock:
+ if len(_absent) >= 512:
+ _absent.clear()
+ _absent[key] = (now, gone)
+ return gone
+
+
+def _creations_of(record: PaneBranchRecord) -> Iterator[CreatedBranch]:
+ """The branches this pane's creation calls account for, newest first.
+
+ ``confirmed`` is true for a creation this machine can still prove. A
+ finished branch is usually deleted, and its worktree with it: the reflog
+ that proved it is gone then. Such a branch is passed on unconfirmed, for
+ the caller to accept only once GitHub shows a pull request from it that
+ was opened after the call. A branch that still exists and was created at
+ some other time belongs to another session and is never passed on.
+ """
candidates, _ = _evidence(record)
if not candidates:
- return None
+ return
root = _common(record.folder)
if not root:
- return None
+ return
+ folders: dict[str, str] = {}
for candidate in reversed(candidates):
- if candidate.confirmed and _common(candidate.folder) == root:
- return candidate
+ if candidate.folder not in folders:
+ folders[candidate.folder] = _common(candidate.folder)
+ if candidate.confirmed and folders[candidate.folder] == root:
+ yield 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(
+ elif _recorded_creation(
record.folder, candidate.branch, candidate.called_at, candidate.created_at
):
- return replace(candidate, folder=record.folder, confirmed=True)
- return None
+ yield replace(candidate, folder=record.folder, confirmed=True)
+ elif candidate.created_at and _gone(record.folder, root, candidate.branch):
+ yield replace(candidate, folder=record.folder, confirmed=False)
+
+
+def _created(record: PaneBranchRecord) -> Iterator[CreatedBranch]:
+ """Every branch this pane demonstrably created, newest first."""
+ return (created for created in _creations_of(record) if created.confirmed)
+
+
+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)
+ return next(_created(record), None)
@dataclass(frozen=True)
@@ -491,28 +552,43 @@ def _repository(folder: str, root: str) -> _Repository:
return repository
-def _worked_branch(record: PaneBranchRecord) -> tuple[str, float] | None:
- """The feature branch out in the checkout this session last changed.
+def _worked(record: PaneBranchRecord) -> Iterator[tuple[str, float]]:
+ """The feature branches out in the checkouts this session changed, newest first.
The default branch does not count: a command run in the main checkout must
- not hide the feature branch the session has been building.
+ not hide the feature branch the session has been building. Each branch is
+ named once, at its latest change.
"""
_, worked = _evidence(record)
if not worked:
- return None
+ return
root = _common(record.folder)
if not root:
- return None
+ return
repository = _repository(record.folder, root)
default = {repository.default_branch} if repository.default_branch else {"main", "master"}
+ named: set[str] = set()
+ resolved: dict[str, str] = {}
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
+ if touched not in resolved:
+ resolved[touched] = next(
+ (
+ branch
+ for checkout, branch in repository.checkouts
+ if touched == checkout or touched.startswith(checkout + os.sep)
+ ),
+ "",
+ )
+ branch = resolved[touched]
+ if branch and branch not in default and branch not in named:
+ named.add(branch)
+ yield branch, at
+
+
+def _worked_branch(record: PaneBranchRecord) -> tuple[str, float] | None:
+ """The feature branch out in the checkout this session last changed."""
+ return next(_worked(record), None)
@dataclass(frozen=True)
@@ -522,15 +598,22 @@ class PaneBranch:
# 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
+ # The local branch is gone, so only a pull request opened after
+ # ``created_at`` can still tie it to this pane.
+ unproven: bool = False
-def pane_branch(record: PaneBranchRecord) -> PaneBranch | None:
- """The branch a pane's work belongs to.
+def _since(created: CreatedBranch) -> float:
+ """From when a pull request can belong to this creation.
- 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.
+ The call's start, not its end: one command may create the branch, push it
+ and open the pull request before its result is written.
"""
+ return created.called_at or created.created_at
+
+
+def _own_branch(record: PaneBranchRecord) -> PaneBranch | None:
+ """The branch this session created or last changed a checkout of, whichever is newer."""
created = owned_branch(record)
if record.created_branch and created is not None:
return PaneBranch(created.branch, created.folder)
@@ -538,9 +621,13 @@ def pane_branch(record: PaneBranchRecord) -> PaneBranch | None:
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)
+ return PaneBranch(created.branch, created.folder, _since(created))
if worked is not None:
return PaneBranch(worked[0], record.folder)
+ return None
+
+
+def _checked_out(record: PaneBranchRecord) -> PaneBranch | None:
path = Path(record.folder)
head = (
git_overview._out(["symbolic-ref", "--quiet", "--short", "HEAD"], path)
@@ -548,3 +635,59 @@ def pane_branch(record: PaneBranchRecord) -> PaneBranch | None:
else None
)
return PaneBranch(head.strip(), record.folder) if head and head.strip() else None
+
+
+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.
+ """
+ return _own_branch(record) or _checked_out(record)
+
+
+#: A pane header lists this many branches of one session at most.
+MAX_PANE_BRANCHES = 8
+
+
+def pane_branches(record: PaneBranchRecord) -> list[PaneBranch]:
+ """Every branch a pane's session has worked on.
+
+ The branch it works in now comes first, then the others it created or
+ changed a checkout of, newest first. A branch that is gone locally is
+ listed ``unproven``. The branch that merely happens to be checked out
+ where the pane runs is the answer only for a session with no branch of
+ its own.
+ """
+ current = _own_branch(record)
+ others: dict[str, tuple[float, PaneBranch]] = {}
+ for created in _creations_of(record):
+ if current is not None and created.branch == current.branch:
+ continue
+ if created.branch not in others:
+ others[created.branch] = (
+ created.created_at,
+ PaneBranch(
+ created.branch,
+ created.folder,
+ _since(created),
+ unproven=not created.confirmed,
+ ),
+ )
+ for branch, at in _worked(record):
+ if current is not None and branch == current.branch:
+ continue
+ known = others.get(branch)
+ # A created branch keeps its creation time: it tells its pull request
+ # from an older one of the same name. Work in a checkout proves it.
+ others[branch] = (
+ max(at, known[0]) if known else at,
+ replace(known[1], unproven=False) if known else PaneBranch(branch, record.folder),
+ )
+ ranked = [branch for _, branch in sorted(others.values(), key=lambda e: e[0], reverse=True)]
+ listed = [current, *ranked] if current is not None else ranked
+ if not listed:
+ fallback = _checked_out(record)
+ return [fallback] if fallback is not None else []
+ return listed[:MAX_PANE_BRANCHES]
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 b8465776ad..7811a42e71 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.test.tsx
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { openExternalUrl } from "@/lib/openExternal";
import { GitHubStatusBadge } from "./SessionGitHubBadge";
import type { SessionGitHubStatus } from "./useSessionGitHub";
-import { PANE_BRAND } from "./terminalThemes";
+import { PANE_BRAND, PANE_CHROME } from "./terminalThemes";
vi.mock("@/lib/openExternal", () => ({ openExternalUrl: vi.fn().mockResolvedValue(true) }));
afterEach(() => { cleanup(); vi.clearAllMocks(); });
@@ -119,3 +119,86 @@ describe("session GitHub link", () => {
expect(container.innerHTML).toBe("");
});
});
+
+describe("a session with several branches", () => {
+ const several = () => status({
+ branch: "claude/still-open", url: "https://github.com/owner/repo/pull/9", number: 9, state: "open",
+ others: [
+ status({ branch: "claude/merged", url: "https://github.com/owner/repo/pull/8", number: 8, state: "merged" }),
+ status({ branch: "claude/closed", url: "https://github.com/owner/repo/pull/7", number: 7, state: "closed" }),
+ status({ branch: "claude/local", published: false, state: "branch", number: null }),
+ ],
+ });
+
+ it("shows one symbol with the number of branches and keeps the list closed", () => {
+ render(<GitHubStatusBadge status={several()} appearance="dark" />);
+ const button = screen.getByRole("button", { name: /4 branches of this session, now owner\/repo · claude\/still-open/ });
+ expect(button.textContent).toBe("4");
+ expect(button.querySelectorAll("svg")).toHaveLength(1);
+ expect(button.getAttribute("aria-expanded")).toBe("false");
+ expect(screen.getByTestId("session-github-branches").hidden).toBe(true);
+ });
+
+ it("lists every branch with its state, the shown one first", () => {
+ render(<GitHubStatusBadge status={several()} appearance="dark" />);
+ fireEvent.click(screen.getByTestId("session-github-status"));
+ const menu = screen.getByTestId("session-github-branches");
+ expect(menu.hidden).toBe(false);
+ const rows = Array.from(menu.querySelectorAll("[role=menuitem]"));
+ expect(rows.map((row) => row.textContent)).toEqual([
+ "claude/still-open#9 · Open pull request",
+ "claude/merged#8 · Pull request merged",
+ "claude/closed#7 · Closed without merging",
+ "claude/localNot on GitHub yet",
+ ]);
+ expect(rows[1].className).toContain("opacity-60");
+ expect(rows[0].className).not.toContain("opacity-60");
+ });
+
+ it("opens the chosen pull request and closes the list", () => {
+ const drag = vi.fn();
+ render(<div onPointerDown={drag} onClick={drag}><GitHubStatusBadge status={several()} appearance="dark" /></div>);
+ fireEvent.pointerDown(screen.getByTestId("session-github-status"));
+ fireEvent.click(screen.getByTestId("session-github-status"));
+ fireEvent.click(screen.getByRole("menuitem", { name: /Open GitHub pull request #8/ }));
+ expect(openExternalUrl).toHaveBeenCalledExactlyOnceWith("https://github.com/owner/repo/pull/8");
+ expect(screen.getByTestId("session-github-branches").hidden).toBe(true);
+ expect(drag).not.toHaveBeenCalled();
+ });
+
+ it("does not link a branch that is not on GitHub", () => {
+ render(<GitHubStatusBadge status={several()} appearance="dark" />);
+ fireEvent.click(screen.getByTestId("session-github-status"));
+ const local = screen.getByText("claude/local").closest("[role=menuitem]") as HTMLElement;
+ expect(local.tagName).toBe("DIV");
+ expect(local.getAttribute("aria-disabled")).toBe("true");
+ });
+
+ it("closes on Escape and on a press outside", () => {
+ render(<GitHubStatusBadge status={several()} appearance="dark" />);
+ const button = screen.getByTestId("session-github-status");
+ const menu = screen.getByTestId("session-github-branches");
+ fireEvent.click(button);
+ fireEvent.keyDown(menu, { key: "Escape" });
+ expect(menu.hidden).toBe(true);
+ fireEvent.click(button);
+ fireEvent.pointerDown(document.body);
+ expect(menu.hidden).toBe(true);
+ });
+
+ it("drops a listed branch with invalid repository metadata", () => {
+ render(<GitHubStatusBadge status={status({ others: [status({ repo: "evil.invalid/a/b", branch: "x" })] })} appearance="dark" />);
+ expect(screen.getByRole("link")).toBeTruthy();
+ expect(screen.queryByTestId("session-github-branches")).toBeNull();
+ });
+
+ it.each(["light", "dark"] as const)("draws the list on the %s float step", (appearance) => {
+ render(<GitHubStatusBadge status={several()} appearance={appearance} />);
+ const reference = document.createElement("div");
+ reference.style.background = PANE_CHROME[appearance].float;
+ reference.style.color = PANE_BRAND[appearance].ink;
+ const menu = screen.getByTestId("session-github-branches");
+ expect(menu.style.background).toBe(reference.style.background);
+ expect(menu.style.color).toBe(reference.style.color);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
index 56fb89eb7d..29e7f767ac 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
@@ -1,7 +1,9 @@
+import { useEffect, useId, useRef, useState, type CSSProperties } from "react";
+import { createPortal } from "react-dom";
import { fill, useT } from "@/i18n";
import { openExternalUrl } from "@/lib/openExternal";
import { GitHubIcon, type GitHubIconName } from "./GitHubIcon";
-import { PANE_BRAND, type TerminalAppearance } from "./terminalThemes";
+import { PANE_BRAND, PANE_CHROME, type TerminalAppearance } from "./terminalThemes";
import { useSessionGitHub, type SessionGitHubStatus } from "./useSessionGitHub";
const PR: Record<SessionGitHubStatus["state"], [GitHubIconName, string]> = {
@@ -13,24 +15,34 @@ const PR: Record<SessionGitHubStatus["state"], [GitHubIconName, string]> = {
closed: ["git-pull-request-closed", "ide_panes.github.state_closed"],
};
-export function GitHubStatusBadge({ status, appearance }: {
- status: SessionGitHubStatus | null;
- appearance: TerminalAppearance;
-}) {
- const t = useT();
+const MENU_WIDTH = 320;
+
+/** One branch as the header words it: where it leads, and what state it is in. */
+interface BranchRow {
+ branch: string;
+ identity: string;
+ icon: GitHubIconName;
+ label: string;
+ /** Null while nothing is on GitHub to open. */
+ url: string | null;
+ destination: string;
+ /** The pull request number, when the link leads to one. */
+ pullRequest: string | null;
+ /** Merged or closed: listed, but no longer the pane's open work. */
+ settled: boolean;
+}
+
+function describe(status: SessionGitHubStatus, t: (key: string) => string): BranchRow | 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>;
+ return {
+ branch: status.branch, identity, icon: "git-branch", url: null, destination: "", pullRequest: null, settled: false,
+ label: t(unavailable ? "ide_panes.github.unavailable" : "ide_panes.github.local_only"),
+ };
}
// 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);
@@ -41,11 +53,136 @@ export function GitHubStatusBadge({ status, appearance }: {
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);
+ return {
+ branch: status.branch, identity, icon, label: t(labelKey), url, destination,
+ pullRequest: pullRequest ? pullRequest[1] : null,
+ settled: !unavailable && (status.state === "merged" || status.state === "closed"),
+ };
+}
+
+/** A session that worked on several branches: one symbol, the rest one click away. */
+function BranchList({ rows, appearance }: { rows: BranchRow[]; appearance: TerminalAppearance }) {
+ const t = useT();
+ const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+ const menuRef = useRef<HTMLDivElement>(null);
+ const menuId = useId();
+ const open = position !== null;
+ const brand = PANE_BRAND[appearance];
+ const chrome = PANE_CHROME[appearance];
+ const shown = rows[0];
+
+ useEffect(() => {
+ if (!open) return;
+ const away = (event: PointerEvent) => {
+ if (event.target instanceof Node && !menuRef.current?.contains(event.target)
+ && !buttonRef.current?.contains(event.target)) setPosition(null);
+ };
+ const dismiss = () => setPosition(null);
+ document.addEventListener("pointerdown", away, true);
+ window.addEventListener("resize", dismiss);
+ window.addEventListener("blur", dismiss);
+ return () => {
+ document.removeEventListener("pointerdown", away, true);
+ window.removeEventListener("resize", dismiss);
+ window.removeEventListener("blur", dismiss);
+ };
+ }, [open]);
+
+ const toggle = () => {
+ const rect = buttonRef.current?.getBoundingClientRect();
+ if (!rect) return;
+ const left = Math.max(8, Math.min(rect.right - MENU_WIDTH, window.innerWidth - MENU_WIDTH - 8));
+ setPosition((current) => current ? null : { left, top: rect.bottom + 4 });
+ };
+ const close = () => { setPosition(null); buttonRef.current?.focus(); };
+
+ const menu = createPortal(<div ref={menuRef} id={menuId} role="menu" hidden={!open}
+ data-testid="session-github-branches" aria-label={t("ide_panes.github.branches_title")}
+ className="fixed z-[90] max-w-[calc(100vw-16px)] rounded-lg border p-1 shadow-lg"
+ style={{ ...(position ?? { left: 0, top: 0 }), width: MENU_WIDTH, borderColor: chrome.border,
+ background: chrome.float, color: brand.ink, "--pane-chip": brand.chip } as CSSProperties}
+ onPointerDown={(event) => event.stopPropagation()}
+ onMouseDown={(event) => event.stopPropagation()}
+ onKeyDown={(event) => {
+ if (event.key === "Escape" || event.key === "Tab") { event.preventDefault(); event.stopPropagation(); close(); return; }
+ if (!["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) return;
+ event.preventDefault();
+ const items = Array.from(menuRef.current?.querySelectorAll<HTMLElement>("a[role=menuitem]") ?? []);
+ const at = items.indexOf(document.activeElement as HTMLElement);
+ const index = event.key === "Home" ? 0 : event.key === "End" ? items.length - 1
+ : (at + (event.key === "ArrowDown" ? 1 : -1) + items.length) % items.length;
+ items[index]?.focus();
+ }}>
+ <div className="px-2.5 pb-1 pt-1.5 text-[11px]" style={{ color: brand.inkFaint }}>{t("ide_panes.github.branches_title")}</div>
+ {rows.map((row) => {
+ const line = <>
+ <GitHubIcon name={row.icon} width={16} height={16} className="block shrink-0" aria-hidden="true" />
+ <span className="min-w-0 flex-1 truncate font-mono text-xs">{row.branch}</span>
+ <span className="shrink-0 text-[11px]" style={{ color: brand.inkFaint }}>
+ {row.pullRequest ? `#${row.pullRequest} · ` : ""}{row.label}
+ </span>
+ </>;
+ const layout = `flex w-full items-center gap-2 rounded px-2.5 py-1.5 text-left ${row.settled ? "opacity-60" : ""}`;
+ if (!row.url) {
+ return <div key={row.identity} role="menuitem" aria-disabled="true" title={`${row.identity}\n${row.label}`}
+ className={layout}>{line}</div>;
+ }
+ const url = row.url;
+ return <a key={row.identity} role="menuitem" href={url} target="_blank" rel="noopener noreferrer"
+ aria-label={fill(t("ide_panes.github.open_aria"), { destination: row.destination, identity: row.identity })}
+ title={`${row.identity}\n${row.label}\n${fill(t("ide_panes.github.open_title"), { destination: row.destination })}`}
+ className={`${layout} hover:bg-[color:var(--pane-chip)] hover:opacity-100 focus:bg-[color:var(--pane-chip)] focus:opacity-100 focus:outline-none`}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setPosition(null);
+ // WebView2 drops target=_blank: use the desktop's real-browser bridge.
+ void openExternalUrl(url);
+ }}>{line}</a>;
+ })}
+ </div>, document.body);
+
+ return <>
+ <button ref={buttonRef} type="button" data-header-control="true" data-testid="session-github-status"
+ aria-haspopup="menu" aria-expanded={open} aria-controls={open ? menuId : undefined}
+ aria-label={fill(t("ide_panes.github.branches_aria"), { count: rows.length, identity: shown.identity })}
+ title={`${shown.identity}\n${shown.label}\n${t("ide_panes.github.branches_title")}: ${rows.length}`}
+ className={`inline-flex h-6 shrink-0 items-center justify-center gap-0.5 rounded px-1 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-current ${shown.url ? "opacity-75" : "opacity-50"}`}
+ style={{ color: brand.inkMuted }}
+ onPointerDown={(event) => event.stopPropagation()}
+ onKeyDown={(event) => { if (event.key === "ArrowDown" && !open) { event.preventDefault(); toggle(); } }}
+ onClick={(event) => { event.stopPropagation(); toggle(); }}>
+ <GitHubIcon name={shown.icon} width={16} height={16} className="block shrink-0" />
+ <span className="text-[10px] leading-none tabular-nums" aria-hidden="true">{rows.length}</span>
+ </button>
+ {menu}
+ </>;
+}
+
+export function GitHubStatusBadge({ status, appearance }: {
+ status: SessionGitHubStatus | null;
+ appearance: TerminalAppearance;
+}) {
+ const t = useT();
+ const shown = status ? describe(status, t) : null;
+ if (!shown) return null;
+ const others = (status?.others ?? []).map((other) => describe(other, t))
+ .filter((row): row is BranchRow => row !== null && row.identity !== shown.identity);
+ if (others.length) return <BranchList rows={[shown, ...others]} appearance={appearance} />;
+ if (!shown.url) {
+ return <span data-header-control="true" data-testid="session-github-status" role="img"
+ aria-label={`${shown.identity}: ${shown.label}`} title={`${shown.identity}\n${shown.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>;
+ }
+ const url = shown.url;
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 })}
- title={`${identity}\n${label}\n${fill(t("ide_panes.github.open_title"), { destination })}`}
+ aria-label={fill(t("ide_panes.github.open_aria"), { destination: shown.destination, identity: shown.identity })}
+ title={`${shown.identity}\n${shown.label}\n${fill(t("ide_panes.github.open_title"), { destination: shown.destination })}`}
className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded opacity-75 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-current"
style={{ color: PANE_BRAND[appearance].inkMuted }}
onPointerDown={(event) => event.stopPropagation()}
@@ -55,7 +192,7 @@ export function GitHubStatusBadge({ status, appearance }: {
// WebView2 drops target=_blank: use the desktop's real-browser bridge.
void openExternalUrl(url);
}}>
- <GitHubIcon name={icon} width={16} height={16} className="block shrink-0" />
+ <GitHubIcon name={shown.icon} width={16} height={16} className="block shrink-0" />
</a>;
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts b/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
index d675d48683..3a39d9b1db 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
@@ -19,6 +19,8 @@ export interface SessionGitHubStatus {
merge_status?: string;
review?: string;
locked?: boolean;
+ /** The session's other branches, newest first. Absent from an older backend. */
+ others?: SessionGitHubStatus[];
}
export type SessionCiState = CiStatus["state"] | "cancelled" | "neutral" | "skipped"
@@ -47,7 +49,10 @@ function start(workspaceId: string): Entry {
const notify = () => entry.listeners.forEach((listener) => listener());
const unavailable = (reason: string) => {
entry.panes = Object.fromEntries(Object.entries(entry.panes).map(([name, status]) => [
- name, status ? { ...status, available: false, reason } : null,
+ name, status ? {
+ ...status, available: false, reason,
+ others: status.others?.map((other) => ({ ...other, available: false, reason })),
+ } : null,
]));
notify();
};
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index d5a71b9970..5b25997172 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -8690,6 +8690,8 @@
"unavailable": "GitHub-Status nicht verfügbar",
"branch_generic": "GitHub-Branch",
"local_only": "Noch nicht auf GitHub",
+ "branches_title": "Branches dieser Sitzung",
+ "branches_aria": "{count} Branches dieser Sitzung, aktuell {identity}",
"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 cf02940e14..4dab474254 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -8690,6 +8690,8 @@
"unavailable": "GitHub status unavailable",
"branch_generic": "GitHub branch",
"local_only": "Not on GitHub yet",
+ "branches_title": "Branches of this session",
+ "branches_aria": "{count} branches of this session, now {identity}",
"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 8753aafa46..18673f411c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -8690,6 +8690,8 @@
"unavailable": "Estado de GitHub no disponible",
"branch_generic": "Rama de GitHub",
"local_only": "Aún no está en GitHub",
+ "branches_title": "Ramas de esta sesión",
+ "branches_aria": "{count} ramas de esta sesión, ahora {identity}",
"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 55bad54858..a2e432b720 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
@@ -8690,6 +8690,8 @@
"unavailable": "Estado do GitHub indisponível",
"branch_generic": "Ramo do GitHub",
"local_only": "Ainda não está no GitHub",
+ "branches_title": "Ramos desta sessão",
+ "branches_aria": "{count} ramos desta sessão, agora {identity}",
"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 30e3f526ad..740c021d89 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -8690,6 +8690,8 @@
"unavailable": "GitHub 状态不可用",
"branch_generic": "GitHub 分支",
"local_only": "尚未推送到 GitHub",
+ "branches_title": "此会话的分支",
+ "branches_aria": "此会话的 {count} 个分支,当前 {identity}",
"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 7b5e0e651e..b78b66c209 100644
--- a/tests/unit/agentic_ide/test_github_status.py
+++ b/tests/unit/agentic_ide/test_github_status.py
@@ -1,5 +1,6 @@
"""Session badges must describe the exact GitHub branch and pushed commit."""
+import time
from types import SimpleNamespace
import pytest
@@ -213,8 +214,10 @@ def test_multiple_panes_share_requests_and_errors_are_unknown(monkeypatch):
monkeypatch.setattr(status, "checkout", local)
monkeypatch.setattr(
status,
- "pane_branch",
- lambda record: SimpleNamespace(folder="worktree", branch=TARGET.branch, created_at=0),
+ "pane_branches",
+ lambda record: [
+ SimpleNamespace(folder="worktree", branch=TARGET.branch, created_at=0, unproven=False)
+ ],
)
monkeypatch.setattr(
github_link, "credential", lambda: github_link.Credential("test-token", "gh")
@@ -230,6 +233,125 @@ def test_multiple_panes_share_requests_and_errors_are_unknown(monkeypatch):
assert failed["published"] and not failed["available"]
+def _session(monkeypatch, branches, answers, unproven=()):
+ """One pane whose session worked on ``branches``; GitHub answers per branch."""
+ status._slot.cache_clear()
+ requests: list[str] = []
+
+ def graphql(_token, _query, variables):
+ requests.append(variables["branch"])
+ return answers[variables["branch"]]
+
+ monkeypatch.setattr(
+ status,
+ "checkout",
+ lambda folder, branch, created_at: status.Checkout(TARGET.repo, branch, HEAD),
+ )
+ monkeypatch.setattr(
+ status,
+ "pane_branches",
+ lambda record: [
+ SimpleNamespace(
+ folder="worktree", branch=branch, created_at=0, unproven=branch in unproven
+ )
+ for branch in branches
+ ],
+ )
+ monkeypatch.setattr(
+ github_link, "credential", lambda: github_link.Credential("test-token", "gh")
+ )
+ monkeypatch.setattr(github_link, "graphql", graphql)
+ return requests
+
+
+def _answer(branch, number, state):
+ return payload(pr(number, state, headRefName=branch))
+
+
+def test_open_work_is_shown_before_a_finished_branch_and_the_rest_is_listed(monkeypatch):
+ answers = {
+ "claude/merged-last": _answer("claude/merged-last", 3, "MERGED"),
+ "claude/still-open": _answer("claude/still-open", 2, "OPEN"),
+ "claude/closed-first": _answer("claude/closed-first", 1, "CLOSED"),
+ }
+ _session(monkeypatch, list(answers), answers)
+
+ pane = status.statuses([status.PaneBranchRecord("t1", "t1", "worktree")])["t1"]
+
+ assert (pane["branch"], pane["state"], pane["number"]) == ("claude/still-open", "open", 2)
+ assert [(other["branch"], other["state"]) for other in pane["others"]] == [
+ ("claude/merged-last", "merged"),
+ ("claude/closed-first", "closed"),
+ ]
+
+
+def test_current_branch_stays_in_front_when_nothing_is_open(monkeypatch):
+ answers = {
+ "claude/merged-last": _answer("claude/merged-last", 3, "MERGED"),
+ "claude/closed-first": _answer("claude/closed-first", 1, "CLOSED"),
+ }
+ _session(monkeypatch, list(answers), answers)
+
+ pane = status.statuses([status.PaneBranchRecord("t1", "t1", "worktree")])["t1"]
+
+ assert pane["branch"] == "claude/merged-last"
+ assert [other["branch"] for other in pane["others"]] == ["claude/closed-first"]
+
+
+def test_single_branch_has_no_others(monkeypatch):
+ answers = {"claude/only": _answer("claude/only", 4, "OPEN")}
+ _session(monkeypatch, list(answers), answers)
+
+ pane = status.statuses([status.PaneBranchRecord("t1", "t1", "worktree")])["t1"]
+
+ assert pane["branch"] == "claude/only" and pane["others"] == []
+
+
+def test_finished_branch_is_read_rarely_and_never_looks_stale(monkeypatch):
+ answers = {
+ "claude/open": _answer("claude/open", 2, "OPEN"),
+ "claude/merged": _answer("claude/merged", 3, "MERGED"),
+ }
+ requests = _session(monkeypatch, list(answers), answers)
+ records = [status.PaneBranchRecord("t1", "t1", "worktree")]
+ status.statuses(records)
+ for branch in answers:
+ status._snapshot(status.Checkout(TARGET.repo, branch, HEAD), "test-token").fetched_at -= 60
+
+ pane = status.statuses(records)["t1"]
+
+ assert requests == ["claude/open", "claude/merged", "claude/open"]
+ (merged,) = pane["others"]
+ assert merged["state"] == "merged" and merged["available"]
+ assert time.time() - merged["fetched_at"] < 5
+
+
+def test_deleted_branch_needs_its_pull_request_to_count(monkeypatch):
+ answers = {
+ "claude/current": _answer("claude/current", 5, "OPEN"),
+ "claude/deleted-merged": _answer("claude/deleted-merged", 4, "MERGED"),
+ "claude/deleted-never-pushed": payload(head=""),
+ }
+ _session(
+ monkeypatch,
+ list(answers),
+ answers,
+ unproven={"claude/deleted-merged", "claude/deleted-never-pushed"},
+ )
+
+ pane = status.statuses([status.PaneBranchRecord("t1", "t1", "worktree")])["t1"]
+
+ assert pane["branch"] == "claude/current"
+ assert [other["branch"] for other in pane["others"]] == ["claude/deleted-merged"]
+
+
+def test_pane_whose_only_branch_is_unconfirmed_shows_nothing(monkeypatch):
+ answers = {"claude/deleted-never-pushed": payload(head="")}
+ _session(monkeypatch, list(answers), answers, unproven=set(answers))
+
+ assert status.statuses([status.PaneBranchRecord("t1", "t1", "worktree")]) == {"t1": None}
+
+
def test_route_uses_pane_cwd_and_excludes_remote_computers(monkeypatch):
from fastapi import HTTPException
diff --git a/tests/unit/agentic_ide/test_session_branches.py b/tests/unit/agentic_ide/test_session_branches.py
index 052d7ffe5f..715bc337ac 100644
--- a/tests/unit/agentic_ide/test_session_branches.py
+++ b/tests/unit/agentic_ide/test_session_branches.py
@@ -401,3 +401,120 @@ 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
+
+
+# --- a session that worked on several branches ---
+
+
+def _listed(monkeypatch, tmp_path, created, worked, current="current", gone=()):
+ folder = str(tmp_path)
+ monkeypatch.setattr(
+ branches,
+ "_own_branch",
+ lambda _: branches.PaneBranch(current, folder, 30) if current else None,
+ )
+ monkeypatch.setattr(
+ branches,
+ "_creations_of",
+ lambda _: iter(
+ [
+ branches.CreatedBranch(name, folder, at, confirmed=name not in gone)
+ for name, at in created
+ ]
+ ),
+ )
+ monkeypatch.setattr(branches, "_worked", lambda _: iter(worked))
+ monkeypatch.setattr(branches, "_checked_out", lambda _: branches.PaneBranch("main", folder))
+ return branches.pane_branches(branches.PaneBranchRecord("t1", "history", folder))
+
+
+def test_session_lists_its_other_branches_newest_first(monkeypatch, tmp_path):
+ listed = _listed(
+ monkeypatch,
+ tmp_path,
+ created=[("current", 30), ("created-early", 10)],
+ worked=[("current", 40), ("created-early", 25), ("only-worked", 20)],
+ )
+
+ assert [entry.branch for entry in listed] == ["current", "created-early", "only-worked"]
+ # The creation time survives: it tells this branch's pull request from an older one.
+ assert listed[1].created_at == 10
+ assert listed[2].created_at == 0
+
+
+def test_branch_list_is_capped(monkeypatch, tmp_path):
+ created = [(f"branch-{index}", index) for index in reversed(range(20))]
+
+ listed = _listed(monkeypatch, tmp_path, created=created, worked=[])
+
+ assert len(listed) == branches.MAX_PANE_BRANCHES
+ assert [entry.branch for entry in listed[:3]] == ["current", "branch-19", "branch-18"]
+
+
+def test_deleted_branch_is_listed_as_unproven(monkeypatch, tmp_path):
+ listed = _listed(monkeypatch, tmp_path, created=[("deleted", 10)], worked=[], gone={"deleted"})
+
+ assert [(entry.branch, entry.unproven) for entry in listed] == [
+ ("current", False),
+ ("deleted", True),
+ ]
+
+
+def test_finished_branches_stand_in_front_of_the_checked_out_default(monkeypatch, tmp_path):
+ listed = _listed(
+ monkeypatch, tmp_path, created=[("deleted", 10)], worked=[], current="", gone={"deleted"}
+ )
+
+ assert [entry.branch for entry in listed] == ["deleted"]
+
+
+def test_session_without_a_branch_of_its_own_gets_the_checked_out_one(monkeypatch, tmp_path):
+ listed = _listed(monkeypatch, tmp_path, created=[], worked=[], current="")
+
+ assert [entry.branch for entry in listed] == ["main"]
+
+
+def test_pull_request_opened_inside_the_creating_call_still_counts(monkeypatch, tmp_path):
+ folder = str(tmp_path)
+ monkeypatch.setattr(branches, "_own_branch", lambda _: None)
+ monkeypatch.setattr(
+ branches,
+ "_creations_of",
+ lambda _: iter([branches.CreatedBranch("one-call", folder, 90, called_at=50)]),
+ )
+ monkeypatch.setattr(branches, "_worked", lambda _: iter([]))
+
+ (listed,) = branches.pane_branches(branches.PaneBranchRecord("t1", "history", folder))
+
+ assert listed.created_at == 50
+
+
+def test_heredoc_does_not_hide_the_branch_creation_before_it(tmp_path):
+ command = (
+ "git switch -c claude/topic origin/main\ncat >> notes.md <<'EOF'\nthe pane's note\nEOF"
+ )
+
+ found = branches.created_by_command(command, str(tmp_path))
+
+ assert [entry.branch for entry in found] == ["claude/topic"]
+
+
+def test_deleted_branch_is_passed_on_unconfirmed_and_a_foreign_one_never(repository, monkeypatch):
+ now = time.time()
+ _git(repository, "branch", "foreign")
+ events = [
+ *timed("git switch -c deleted | tail -1", "", started=now - 20, ended=now - 19),
+ *timed(
+ "git switch -c foreign | tail -1",
+ "",
+ started=now + 3600,
+ ended=now + 3601,
+ identity="later",
+ ),
+ ]
+ record = _pane(repository, monkeypatch, events)
+
+ found = [(entry.branch, entry.confirmed) for entry in branches._creations_of(record)]
+
+ assert found == [("deleted", False)]
+ assert branches.owned_branch(record) is None