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.

fix(agentic-ide): show a pane's branch status at once and spin while it is confirmed (#668)

Ruben Lütke94140ee2e6b4
diff --git a/jarvis/agentic_ide/agent_transcript.py b/jarvis/agentic_ide/agent_transcript.py
index f91e6b2aa3..b11a7b7853 100644
--- a/jarvis/agentic_ide/agent_transcript.py
+++ b/jarvis/agentic_ide/agent_transcript.py
@@ -1248,6 +1248,34 @@ def read_timeline(
)
+def stamp(agent: str, session_id: str, *, home: Path | None = None) -> tuple[int, int] | None:
+ """Size and modification time of a session's record: has it grown since?
+
+ A record is tens of megabytes after a day's work, and reading it whole to
+ learn that nothing was added is the expensive way to ask. ``None`` when the
+ record is not one file this module can name, or is not there: the caller
+ has no cheap answer then and reads it.
+ """
+ key = _agent_key(agent)
+ session = str(session_id or "").strip()
+ if not session:
+ return None
+ try:
+ if key == "claude":
+ path = _claude_file(session, home)
+ elif key == "codex":
+ path = _codex_file(session, home)
+ else:
+ return None
+ if path is None:
+ return None
+ info = path.stat()
+ except OSError:
+ # Unreadable for a moment (the CLI is rotating it): reading it decides.
+ return None
+ return info.st_size, info.st_mtime_ns
+
+
def read_events(
agent: str,
session_id: str,
@@ -2054,4 +2082,5 @@ __all__ = [
"read",
"read_events",
"read_timeline",
+ "stamp",
]
diff --git a/jarvis/agentic_ide/github_status.py b/jarvis/agentic_ide/github_status.py
index f8a896fe02..155eb7ebc9 100644
--- a/jarvis/agentic_ide/github_status.py
+++ b/jarvis/agentic_ide/github_status.py
@@ -11,6 +11,8 @@ import hashlib
import re
import threading
import time
+from collections.abc import Callable, Sequence
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict, dataclass, field
from functools import lru_cache
from pathlib import Path
@@ -69,6 +71,43 @@ def _git(folder: Path, *args: str) -> str:
return (git_overview._out(list(args), folder) or "").strip()
+_settings: dict[tuple[str, tuple[str, ...]], tuple[float, str]] = {}
+_settings_lock = threading.Lock()
+# A repository's remotes change when someone edits its configuration, not from
+# one read to the next.
+_SETTINGS_TTL = 60
+
+
+def _setting(folder: Path, *args: str) -> str:
+ """A remote's name or address, asked of git once a minute.
+
+ Each git call is a process of its own, and three of them per branch were
+ most of the git time a read spent. Only an answer git gave is kept: a
+ call that failed (locked, timed out) is asked again on the next read.
+ """
+ key = (str(folder), args)
+ now = time.monotonic()
+ with _settings_lock:
+ known = _settings.get(key)
+ if known is not None and now - known[0] < _SETTINGS_TTL:
+ return known[1]
+ result = git_overview._run(list(args), folder)
+ if result is None:
+ return ""
+ if result.returncode == 0:
+ value = str(result.stdout).strip()
+ elif args[0] == "config" and result.returncode == 1:
+ # `git config --get` exits 1 for an option that is not set: an answer.
+ value = ""
+ else:
+ return ""
+ with _settings_lock:
+ if len(_settings) >= 512:
+ _settings.clear()
+ _settings[key] = (now, value)
+ return value
+
+
def _repository(url: str) -> str:
"""Accept GitHub hosts exactly, never a hostname containing github.com."""
match = re.fullmatch(r"git@github\.com:([^/]+/[^/]+?)(?:\.git)?/?", url)
@@ -104,12 +143,12 @@ def checkout(folder: str | Path, branch: str = "", created_at: float = 0) -> Che
if full_ref != f"refs/heads/{branch}":
head = upstream = ref = ""
# A configured push remote takes precedence in triangular fork workflows.
- push = _git(path, "config", "--get", f"branch.{branch}.pushRemote")
- push = push or _git(path, "config", "--get", "remote.pushDefault")
+ push = _setting(path, "config", "--get", f"branch.{branch}.pushRemote")
+ push = push or _setting(path, "config", "--get", "remote.pushDefault")
remote = push or upstream or "origin"
if remote == ".":
return None
- url = _git(path, "remote", "get-url", remote)
+ url = _setting(path, "remote", "get-url", remote)
repo = _repository(url)
if not repo:
return None
@@ -170,10 +209,16 @@ def _slot(repo: str, branch: str, credential_id: str) -> _Snapshot:
return _Snapshot()
-def _snapshot(target: Checkout, token: str) -> _Snapshot:
- cached = _slot(target.repo, target.branch, hashlib.sha256(token.encode()).hexdigest())
+_slot_lock = threading.Lock()
+
+
+def _snapshot(target: Checkout, token: str, live_ttl: float = _LIVE_TTL) -> _Snapshot:
+ # Reads run side by side: two of them must find the same slot, never make
+ # one each and ask GitHub twice.
+ with _slot_lock:
+ cached = _slot(target.repo, target.branch, hashlib.sha256(token.encode()).hexdigest())
with cached.lock:
- ttl = _SETTLED_TTL if cached.settled and not cached.reason else _LIVE_TTL
+ 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)
@@ -286,6 +331,37 @@ def parse_status(target: Checkout, payload: dict[str, Any], fetched_at: float) -
return status
+#: Git and GitHub calls one read of a workspace makes side by side.
+_PARALLEL_READS = 6
+
+
+def _each(function: Callable[[Any], Any], items: Sequence[Any]) -> list[Any]:
+ """``function`` over ``items`` in order; side by side when there are several."""
+ if len(items) <= 1:
+ return [function(item) for item in items]
+ with ThreadPoolExecutor(
+ max_workers=min(_PARALLEL_READS, len(items)), thread_name_prefix="pane-github-read"
+ ) as pool:
+ return list(pool.map(function, items))
+
+
+def _tolerant(function: Callable[[Any], Any], fallback: Any, what: str) -> Callable[[Any], Any]:
+ """``function``, answering ``fallback`` where it fails for one item.
+
+ One pane whose record or checkout cannot be read must not cost every other
+ pane of the workspace its status.
+ """
+
+ def run(item: Any) -> Any:
+ try:
+ return function(item)
+ except Exception: # noqa: BLE001 - logged; the other panes still get read
+ logger.opt(exception=True).warning("Session GitHub status: {} failed", what)
+ return fallback
+
+ return run
+
+
def _foreground(listed: list[BranchStatus]) -> BranchStatus:
"""The branch a header shows: unfinished work before finished work.
@@ -296,38 +372,57 @@ def _foreground(listed: list[BranchStatus]) -> BranchStatus:
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]:
+def statuses(
+ records: list[PaneBranchRecord] | dict[str, str], *, live_ttl: float = _LIVE_TTL
+) -> dict[str, dict[str, Any] | None]:
"""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.
+ ``others``, newest first. GitHub is asked again about an unfinished
+ branch whose last answer is older than ``live_ttl`` seconds.
"""
result: dict[str, dict[str, Any] | None] = {}
# Old route versions supplied only folders: those carry no ownership proof.
if isinstance(records, dict):
return {pane: None for pane in records}
- targets: dict[tuple[str, str, float], Checkout | None] = {}
- credential: github_link.Credential | None = None
- credential_read = False
+ # Every step asks git or GitHub once per pane or branch and waits for the
+ # answer. Asked one after another, a workspace with eight branches took
+ # ten seconds; side by side it takes about as long as the slowest answer.
+ owned_by_pane = _each(_tolerant(pane_branches, [], "reading a pane's branches"), records)
+ keys = list(
+ dict.fromkeys(
+ (owned.folder, owned.branch, owned.created_at)
+ for owned_branches in owned_by_pane
+ for owned in owned_branches
+ )
+ )
+ resolve = _tolerant(lambda key: checkout(*key), None, "resolving a branch's remote")
+ targets = dict(zip(keys, _each(resolve, keys), strict=True))
+ wanted = list(dict.fromkeys(target for target in targets.values() if target is not None))
+ credential = github_link.credential() if wanted else None
+ snapshots: dict[Checkout, _Snapshot] = {}
+ if credential is not None:
+ token = credential.token
+ snapshots = dict(
+ zip(
+ wanted,
+ _each(lambda target: _snapshot(target, token, live_ttl), wanted),
+ strict=True,
+ )
+ )
now = time.time()
- for record in records:
+ for record, owned_branches in zip(records, owned_by_pane, strict=True):
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]
+ for owned in owned_branches:
+ target = targets[(owned.folder, owned.branch, owned.created_at)]
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)
+ snapshot = snapshots[target]
# 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
@@ -346,3 +441,217 @@ def statuses(records: list[PaneBranchRecord] | dict[str, str]) -> dict[str, dict
shown.others = [status for status in listed if status is not shown]
result[record.pane] = shown.to_dict()
return result
+
+
+# --------------------------------------------------------------- the board
+#
+# Reading a workspace takes seconds: every session's record, git in every
+# checkout, then GitHub. A header that waited for that showed nothing, or an
+# outdated symbol, for as long. So nothing waits: `board` answers with the last
+# read at once and brings an outdated one up to date in the background.
+
+
+@dataclass
+class _Board:
+ """A workspace's last answer, and whether a newer one is being read."""
+
+ panes: dict[str, dict[str, Any] | None] = field(default_factory=dict)
+ # The pane each answer was read for (see `_identity`): a pane that is
+ # someone else now is never shown its predecessor's branch.
+ read_for: dict[str, str] = field(default_factory=dict)
+ # Wall clock of the last read that finished; None before the first.
+ read_at: float | None = None
+ reading: bool = False
+ # The last read failed: what is on the board is no longer being kept current.
+ failed: bool = False
+ # Monotonic: when the last read started, and when the board was last asked for.
+ tried_at: float = float("-inf")
+ used_at: float = 0
+
+
+#: A board this old is read again when it is asked for.
+_BOARD_TTL = 10
+#: A board whose panes changed, or that has no answer yet, waits only this long
+#: between attempts, so a read that fails is not retried on every request.
+_RETRY_S = 1
+#: A tab behind the front one is read again once its answer is this old, so a
+#: switch to it finds an answer recent enough to show without a spinner.
+_WARM_S = 50
+#: How old GitHub's answer about an unfinished branch may get in a tab behind
+#: the front one: it keeps the hourly GitHub budget for the tab in front.
+_WARM_GITHUB_TTL = 60
+#: The longest a request that asked to wait holds on for a running read.
+_MAX_WAIT_S = 15
+_MAX_BOARDS = 64
+_boards: dict[str, _Board] = {}
+_boards_lock = threading.Lock()
+# Notified whenever a read finishes, for the requests that wait for one.
+_boards_read = threading.Condition(_boards_lock)
+# Workspaces in background tabs, queued to be read one after another.
+_ahead: dict[str, list[PaneBranchRecord]] = {}
+_ahead_running = False
+# Set while no read for a tab in front is running: reads ahead wait for it, so
+# they never take the machine from the tab someone is looking at.
+_front_reads = 0
+_front_idle = threading.Event()
+_front_idle.set()
+
+
+def _identity(record: PaneBranchRecord) -> str:
+ return "\n".join((record.pane, record.history_id, record.folder, record.created_branch))
+
+
+def _entry(key: str) -> _Board:
+ """The board for ``key``, made on first use; holds ``_boards_lock``."""
+ entry = _boards.get(key)
+ if entry is None:
+ if len(_boards) >= _MAX_BOARDS:
+ idle = sorted(
+ (name for name, old in _boards.items() if not old.reading),
+ key=lambda name: _boards[name].used_at,
+ )
+ for name in idle[: max(1, len(idle) // 2)]:
+ del _boards[name]
+ entry = _boards[key] = _Board()
+ entry.used_at = time.monotonic()
+ return entry
+
+
+def _read(entry: _Board, records: list[PaneBranchRecord], *, front: bool) -> None:
+ global _front_reads
+ panes: dict[str, dict[str, Any] | None] | None = None
+ try:
+ panes = statuses(records, live_ttl=_LIVE_TTL if front else _WARM_GITHUB_TTL)
+ except Exception: # noqa: BLE001 - nothing may leave a board "reading" for good
+ logger.opt(exception=True).warning("Session GitHub status: a background read failed")
+ finally:
+ with _boards_lock:
+ if panes is not None:
+ entry.panes = panes
+ entry.read_for = {record.pane: _identity(record) for record in records}
+ entry.read_at = time.time()
+ entry.failed = panes is None
+ entry.reading = False
+ if front:
+ _front_reads -= 1
+ if not _front_reads:
+ _front_idle.set()
+ _boards_read.notify_all()
+
+
+def _start(target: Callable[[], None], name: str) -> bool:
+ try:
+ threading.Thread(target=target, name=name, daemon=True).start()
+ except RuntimeError:
+ # No thread to be had: the read did not start, so nothing may wait for it.
+ logger.warning("Session GitHub status: a background read could not start")
+ return False
+ return True
+
+
+def board(key: str, records: list[PaneBranchRecord], *, wait: float = 0) -> dict[str, Any]:
+ """What is known about a workspace's panes, at once.
+
+ ``refreshing`` says a newer answer is being read and worth asking for again;
+ ``age`` is how many seconds ago the answer was read (None before the first
+ read); ``waiting`` names the panes that have no answer yet; ``failed`` says
+ the last read failed, so the answer is not being kept current.
+
+ With ``wait`` the answer waits up to that many seconds for a running read
+ to finish, so the caller learns of it the moment it lands instead of on
+ its next poll.
+ """
+ global _front_reads
+ with _boards_lock:
+ entry = _entry(key)
+ # A read for the tab in front replaces its read ahead, if that has not begun.
+ _ahead.pop(key, None)
+ current = {record.pane: _identity(record) for record in records}
+ changed = any(entry.read_for.get(pane) != identity for pane, identity in current.items())
+ pause = _RETRY_S if changed or entry.read_at is None else _BOARD_TTL
+ start = not entry.reading and time.monotonic() - entry.tried_at >= pause
+ if start:
+ entry.reading = True
+ entry.tried_at = time.monotonic()
+ _front_reads += 1
+ _front_idle.clear()
+ if start and not _start(lambda: _read(entry, records, front=True), "pane-github-status"):
+ with _boards_lock:
+ entry.reading = False
+ _front_reads -= 1
+ if not _front_reads:
+ _front_idle.set()
+ with _boards_lock:
+ deadline = time.monotonic() + min(max(wait, 0), _MAX_WAIT_S)
+ while entry.reading and (left := deadline - time.monotonic()) > 0:
+ _boards_read.wait(left)
+ panes = {
+ pane: entry.panes[pane]
+ for pane, identity in current.items()
+ if pane in entry.panes and entry.read_for.get(pane) == identity
+ }
+ reading = entry.reading
+ failed = entry.failed and not reading
+ age = None if entry.read_at is None else max(0.0, time.time() - entry.read_at)
+ return {
+ "panes": panes,
+ "refreshing": reading,
+ "age": age,
+ "waiting": [pane for pane in current if pane not in panes] if reading else [],
+ "failed": failed,
+ }
+
+
+def _due(entry: _Board | None) -> bool:
+ """Is a board behind the front one worth reading now? Holds ``_boards_lock``."""
+ if entry is None:
+ return True
+ if entry.reading or time.monotonic() - entry.tried_at < _WARM_S:
+ return False
+ return entry.read_at is None or time.time() - entry.read_at >= _WARM_S
+
+
+def due(key: str) -> bool:
+ """Should the tab ``key``, behind the front one, be read ahead now?"""
+ with _boards_lock:
+ return key not in _ahead and _due(_boards.get(key))
+
+
+def _drain_ahead() -> None:
+ global _ahead_running
+ while True:
+ _front_idle.wait(timeout=30)
+ with _boards_lock:
+ if not _ahead:
+ _ahead_running = False
+ return
+ key = next(iter(_ahead))
+ records = _ahead.pop(key)
+ entry = _boards.get(key)
+ if entry is None or not _due(entry):
+ continue
+ entry.reading = True
+ entry.tried_at = time.monotonic()
+ _read(entry, records, front=False)
+
+
+def read_ahead(key: str, records: list[PaneBranchRecord]) -> None:
+ """Read a tab nobody is looking at, one after another with the others.
+
+ A tab is read before its first visit, and again whenever its answer is
+ older than ``_WARM_S``, for as long as a tab in front is being shown. Its
+ header then has a recent answer the moment someone switches to it.
+ """
+ global _ahead_running
+ with _boards_lock:
+ if key in _ahead or not _due(_boards.get(key)):
+ return
+ _entry(key)
+ _ahead[key] = records
+ if _ahead_running:
+ return
+ _ahead_running = True
+ if not _start(_drain_ahead, "pane-github-ahead"):
+ with _boards_lock:
+ _ahead_running = False
+ _ahead.clear()
diff --git a/jarvis/agentic_ide/session_branches.py b/jarvis/agentic_ide/session_branches.py
index 0ec55208f9..d619df2665 100644
--- a/jarvis/agentic_ide/session_branches.py
+++ b/jarvis/agentic_ide/session_branches.py
@@ -366,15 +366,40 @@ def worked_folders(
return found
-_Evidence = tuple[float, list[CreatedBranch], list[tuple[str, float]]]
+@dataclass
+class _Evidence:
+ read_at: float
+ used_at: float
+ # The record's size and modification time when it was read; None when the
+ # record is not one file whose growth can be seen.
+ stamp: tuple[int, int] | None
+ candidates: list[CreatedBranch]
+ worked: list[tuple[str, float]]
+
+
_cache: dict[tuple[str, str, str, float], _Evidence] = {}
_cache_lock = threading.Lock()
+_commons: dict[str, tuple[float, str]] = {}
def _common(folder: str) -> str:
+ """The repository ``folder`` belongs to; asked of git once a minute."""
+ now = time.monotonic()
+ with _cache_lock:
+ known = _commons.get(folder)
+ if known is not None and now - known[0] < 60:
+ return known[1]
path = Path(folder)
value = git_overview._out(["rev-parse", "--git-common-dir"], path) if path.is_dir() else None
- return os.path.normcase(str((path / value.strip()).resolve())) if value else ""
+ common = os.path.normcase(str((path / value.strip()).resolve())) if value else ""
+ if not common:
+ # No answer (git locked or busy, or no repository yet): asked again next time.
+ return ""
+ with _cache_lock:
+ if len(_commons) >= 512:
+ _commons.clear()
+ _commons[folder] = (now, common)
+ return common
_REFLOG_ENTRY = re.compile(r"@\{(\d+)\}\t(.*)")
@@ -428,16 +453,28 @@ def _evidence(record: PaneBranchRecord) -> tuple[list[CreatedBranch], list[tuple
now = time.monotonic()
with _cache_lock:
cached = _cache.get(key)
- 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 []
+ if cached is not None and now - cached.read_at < 15:
+ cached.used_at = now
+ return cached.candidates, cached.worked
+ # A record that has not grown says what it said before. Reading one costs
+ # seconds once it is tens of megabytes, and a session waiting for its next
+ # prompt, in a tab nobody is looking at, adds nothing to it.
+ stamp = agent_transcript.stamp(record.agent, record.session_id, home=record.home)
+ if cached is not None and stamp is not None and stamp == cached.stamp:
+ cached.used_at = now
+ return cached.candidates, cached.worked
+ events = agent_transcript.read_events(record.agent, record.session_id, home=record.home)
+ if events is None:
+ # Not read (locked, being rotated): that is no evidence about the
+ # record, so it is not kept beyond the short window either.
+ events, stamp = [], None
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]:
+ _cache[key] = _Evidence(now, now, stamp, candidates, worked)
+ for expired in [key for key, entry in _cache.items() if now - entry.used_at > 1800]:
del _cache[expired]
return candidates, worked
diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.py
index 823476c536..2597c79152 100644
--- a/jarvis/ui/web/agentic_ide_git_routes.py
+++ b/jarvis/ui/web/agentic_ide_git_routes.py
@@ -55,7 +55,7 @@ from jarvis.agentic_ide import (
github_status,
)
from jarvis.agentic_ide.git_ops import GitError, PrepareMode
-from jarvis.agentic_ide.session import account_home, get_registry
+from jarvis.agentic_ide.session import Session, account_home, get_registry
from jarvis.agentic_ide.session_branches import PaneBranchRecord
from jarvis.agentic_ide.thread_folders import allowed_thread_folder
from jarvis.ui.web.surface_security import is_loopback_request
@@ -191,12 +191,46 @@ 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 for the branch each pane works in."""
- session = get_registry().get(workspace_id)
+def session_github_status(
+ workspace_id: str = Query(..., min_length=1),
+ wait: float = Query(
+ 0, ge=0, le=5, description="Seconds to wait for a read already running to finish"
+ ),
+ instant: bool = Query(
+ False, description="Answer from the last read at once; the caller asks again"
+ ),
+) -> dict:
+ """GitHub state for the branch each pane works in, as last read.
+
+ With ``instant`` it answers at once from the last read (see
+ ``github_status.board``); ``refreshing`` says a newer answer is on its
+ way, and ``wait`` holds the answer until that read lands, for at most that
+ many seconds. A caller that does not ask for ``instant`` gets the answer
+ once a running read has landed, as before: it neither knows to ask again
+ soon nor shows an empty answer as "still loading".
+ """
+ if not instant:
+ wait = _LEGACY_WAIT_S
+ registry = get_registry()
+ session = registry.get(workspace_id)
if session is None:
raise HTTPException(status_code=404, detail="Workspace not found.")
- records = [
+ # The tabs behind this one are read ahead, and kept recent while this one
+ # is shown, so a header there has its branch the moment someone switches.
+ for other in registry.sessions:
+ if other.id != workspace_id and github_status.due(other.id):
+ github_status.read_ahead(other.id, _pane_records(other))
+ return github_status.board(workspace_id, _pane_records(session), wait=wait)
+
+
+#: How long an answer for a caller that does not ask for ``instant`` waits
+#: for a running read: longer than a cold read of a large workspace takes.
+_LEGACY_WAIT_S = 15
+
+
+def _pane_records(session: Session) -> list[PaneBranchRecord]:
+ """One record per pane whose checkout is on this computer."""
+ return [
PaneBranchRecord(
pane=pane.name,
history_id=pane.history_id,
@@ -210,7 +244,6 @@ def session_github_status(workspace_id: str = Query(..., min_length=1)) -> dict:
for pane in session.terminals
if not pane.computer_id
]
- return {"panes": github_status.statuses(records)}
# The editors a branch's checkout is offered in, when installed.
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 7811a42e71..3be93a7aa8 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.test.tsx
@@ -202,3 +202,47 @@ describe("a session with several branches", () => {
expect(menu.style.color).toBe(reference.style.color);
});
});
+
+describe("a status that is still being confirmed", () => {
+ it("holds the branch's place with a spinner before anything is known", () => {
+ render(<GitHubStatusBadge status={null} pending appearance="dark" />);
+ const place = screen.getByRole("status");
+ expect(place.getAttribute("aria-label")).toBe("Reading the GitHub status…");
+ expect(place.getAttribute("data-state")).toBe("loading");
+ expect(screen.getByTestId("session-github-pending").querySelector("svg")?.getAttribute("class")).toContain("animate-spin");
+ expect(screen.queryByRole("link")).toBeNull();
+ });
+
+ it("keeps an old answer's symbol inside the spinner instead of calling it unavailable", () => {
+ const old = status({ state: "queued", fetched_at: Date.now() / 1000 - 600 });
+ render(<GitHubStatusBadge status={old} pending appearance="dark" />);
+ const link = screen.getByRole("link");
+ expect(link.title).toContain("In the merge queue");
+ expect(link.title).toContain("Refreshing GitHub status…");
+ expect(link.title).not.toContain("GitHub status unavailable");
+ expect(screen.getByTestId("session-github-pending")).toBeTruthy();
+ expect(link.querySelector("svg")?.getAttribute("width")).toBe("10");
+ });
+
+ it("calls the same old answer unavailable once nothing newer is coming", () => {
+ render(<GitHubStatusBadge status={status({ fetched_at: Date.now() / 1000 - 600 })} appearance="dark" />);
+ expect(screen.getByRole("link").title).toContain("GitHub status unavailable");
+ expect(screen.queryByTestId("session-github-pending")).toBeNull();
+ });
+
+ it("spins round the symbol of a session with several branches", () => {
+ const shown = status({ others: [status({ branch: "feature/other", state: "merged" })] });
+ render(<GitHubStatusBadge status={shown} pending appearance="light" />);
+ const button = screen.getByTestId("session-github-status");
+ expect(button.tagName).toBe("BUTTON");
+ expect(button.textContent).toBe("2");
+ expect(button.title).toContain("Refreshing GitHub status…");
+ expect(screen.getByTestId("session-github-pending").style.color).toBe("rgb(139, 87, 0)");
+ });
+
+ it.each(["light", "dark"] as const)("takes the pending hue from the %s pane appearance", (appearance) => {
+ render(<GitHubStatusBadge status={null} pending appearance={appearance} />);
+ const ring = screen.getByTestId("session-github-pending");
+ expect(ring.style.color).toBe(appearance === "light" ? "rgb(139, 87, 0)" : "rgb(210, 148, 62)");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
index 5191b858f1..a1b82fec03 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/SessionGitHubBadge.tsx
@@ -3,8 +3,8 @@ import { createPortal } from "react-dom";
import { fill, useT } from "@/i18n";
import { openExternalUrl } from "@/lib/openExternal";
import { GitHubIcon, type GitHubIconName } from "./GitHubIcon";
-import { PANE_BRAND, PANE_CHROME, type TerminalAppearance } from "./terminalThemes";
-import { useSessionGitHub, type SessionGitHubStatus } from "./useSessionGitHub";
+import { PANE_BRAND, PANE_CHROME, themeFor, type TerminalAppearance } from "./terminalThemes";
+import { FRESH_MS, useSessionGitHubPane, type SessionGitHubStatus } from "./useSessionGitHub";
const PR: Record<SessionGitHubStatus["state"], [GitHubIconName, string]> = {
branch: ["git-branch", "ide_panes.github.state_branch"],
@@ -33,11 +33,13 @@ interface BranchRow {
settled: boolean;
}
-function describe(status: SessionGitHubStatus, t: (key: string) => string): BranchRow | null {
+function describe(status: SessionGitHubStatus, t: (key: string) => string, pending = false): 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;
+ // An old answer that a newer one is being read for keeps its state and
+ // spins; it turns "unavailable" only when nothing newer is on its way.
+ const unavailable = !status.available || (!pending && Date.now() - status.fetched_at * 1000 > FRESH_MS);
if (!status.published) {
// Nothing on GitHub to open yet: the pane still says which branch its work is on.
return {
@@ -61,8 +63,39 @@ function describe(status: SessionGitHubStatus, t: (key: string) => string): Bran
};
}
+/**
+ * The spinner a check that is still running wears: a quiet track and a turning
+ * arc in the pending hue, drawn round the symbol without taking room of its own.
+ */
+function PendingRing({ appearance }: { appearance: TerminalAppearance }) {
+ return <span aria-hidden="true" data-testid="session-github-pending"
+ className="pointer-events-none absolute -inset-0.5" style={{ color: themeFor(appearance).yellow }}>
+ <svg viewBox="0 0 20 20" className="block h-full w-full animate-spin motion-reduce:animate-none">
+ <circle cx="10" cy="10" r="8.5" fill="none" stroke="currentColor" strokeOpacity="0.25" strokeWidth="1.5" />
+ <path d="M10 1.5a8.5 8.5 0 0 1 8.5 8.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
+ </svg>
+ </span>;
+}
+
+/** The header's symbol; while its status is being confirmed it sits inside the spinner. */
+function Glyph({ icon, pending, appearance }: {
+ icon: GitHubIconName | null;
+ pending: boolean;
+ appearance: TerminalAppearance;
+}) {
+ const size = pending ? 10 : 16;
+ return <span className="relative inline-flex h-4 w-4 shrink-0 items-center justify-center">
+ {icon && <GitHubIcon name={icon} width={size} height={size} className="block shrink-0" />}
+ {pending && <PendingRing appearance={appearance} />}
+ </span>;
+}
+
/** A session that worked on several branches: one symbol, the rest one click away. */
-function BranchList({ rows, appearance }: { rows: BranchRow[]; appearance: TerminalAppearance }) {
+function BranchList({ rows, appearance, pending }: {
+ rows: BranchRow[];
+ appearance: TerminalAppearance;
+ pending: boolean;
+}) {
const t = useT();
const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
@@ -148,42 +181,55 @@ function BranchList({ rows, appearance }: { rows: BranchRow[]; appearance: Termi
<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}`}
+ title={`${shown.identity}\n${shown.label}\n${t("ide_panes.github.branches_title")}: ${rows.length}${pending ? `\n${t("ide_panes.github.refreshing")}` : ""}`}
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" />
+ <Glyph icon={shown.icon} pending={pending} appearance={appearance} />
<span className="text-[10px] leading-none tabular-nums" aria-hidden="true">{rows.length}</span>
</button>
{menu}
</>;
}
-export function GitHubStatusBadge({ status, appearance }: {
+export function GitHubStatusBadge({ status, appearance, pending = false }: {
status: SessionGitHubStatus | null;
appearance: TerminalAppearance;
+ /** The status is still being read, or confirmed after it went old: it spins meanwhile. */
+ pending?: boolean;
}) {
const t = useT();
- const shown = status ? describe(status, t) : null;
- if (!shown) return null;
- const others = (status?.others ?? []).map((other) => describe(other, t))
+ const shown = status ? describe(status, t, pending) : null;
+ if (!shown) {
+ if (!pending) return null;
+ // Nothing known yet: the spinner holds the place the branch will take.
+ const label = t(status === null ? "ide_panes.github.loading" : "ide_panes.github.refreshing");
+ return <span data-header-control="true" data-testid="session-github-status" data-state="loading"
+ role="status" aria-label={label} title={label}
+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center"
+ style={{ color: PANE_BRAND[appearance].inkMuted }}>
+ <Glyph icon={null} pending appearance={appearance} />
+ </span>;
+ }
+ const others = (status?.others ?? []).map((other) => describe(other, t, pending))
.filter((row): row is BranchRow => row !== null && row.identity !== shown.identity);
- if (others.length) return <BranchList rows={[shown, ...others]} appearance={appearance} />;
+ if (others.length) return <BranchList rows={[shown, ...others]} appearance={appearance} pending={pending} />;
+ const note = pending ? `\n${t("ide_panes.github.refreshing")}` : "";
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"
+ aria-label={`${shown.identity}: ${shown.label}`} title={`${shown.identity}\n${shown.label}${note}`}
+ className={`inline-flex h-6 w-6 shrink-0 items-center justify-center ${pending ? "opacity-75" : "opacity-50"}`}
style={{ color: PANE_BRAND[appearance].inkMuted }}>
- <GitHubIcon name="git-branch" width={16} height={16} className="block shrink-0" />
+ <Glyph icon="git-branch" pending={pending} appearance={appearance} />
</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: shown.destination, identity: shown.identity })}
- title={`${shown.identity}\n${shown.label}\n${fill(t("ide_panes.github.open_title"), { destination: shown.destination })}`}
+ title={`${shown.identity}\n${shown.label}\n${fill(t("ide_panes.github.open_title"), { destination: shown.destination })}${note}`}
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()}
@@ -193,7 +239,7 @@ export function GitHubStatusBadge({ status, appearance }: {
// WebView2 drops target=_blank: use the desktop's real-browser bridge.
void openExternalUrl(url);
}}>
- <GitHubIcon name={shown.icon} width={16} height={16} className="block shrink-0" />
+ <Glyph icon={shown.icon} pending={pending} appearance={appearance} />
</a>;
}
@@ -202,6 +248,6 @@ export function SessionGitHubBadge({ workspaceId, name, appearance }: {
name: string;
appearance: TerminalAppearance;
}) {
- const status = useSessionGitHub(workspaceId, name);
- return <GitHubStatusBadge status={status} appearance={appearance} />;
+ const { status, pending } = useSessionGitHubPane(workspaceId, name);
+ return <GitHubStatusBadge status={status} pending={pending} appearance={appearance} />;
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.test.tsx
index 63b0b065ca..c7fb656f0f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.test.tsx
@@ -1,6 +1,8 @@
import { act, cleanup, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { useSessionGitHub, type SessionGitHubStatus } from "./useSessionGitHub";
+import {
+ resetSessionGitHubForTests, useSessionGitHub, useSessionGitHubPane, type SessionGitHubStatus,
+} from "./useSessionGitHub";
import { resetConnectBudgetForTests } from "@/lib/connectBudget";
const value: SessionGitHubStatus = {
@@ -11,12 +13,15 @@ const value: SessionGitHubStatus = {
beforeEach(() => {
vi.useFakeTimers();
+ // GitHub's answer is as recent as the test's clock.
+ value.fetched_at = Date.now() / 1000;
resetConnectBudgetForTests();
vi.spyOn(Math, "random").mockReturnValue(0.5);
vi.spyOn(document, "hidden", "get").mockReturnValue(false);
});
afterEach(() => {
cleanup();
+ resetSessionGitHubForTests();
resetConnectBudgetForTests();
vi.unstubAllGlobals();
vi.restoreAllMocks();
@@ -76,3 +81,137 @@ it("aborts an in-flight poll when its last subscriber unmounts", async () => {
hook.unmount();
expect(signal.aborted).toBe(true);
});
+
+const answer = (body: object) => ({ ok: true, json: async () => body });
+
+it("spins before the first answer and while the backend reads it, then shows it", async () => {
+ const fetcher = vi.fn()
+ .mockResolvedValueOnce(answer({ panes: {}, refreshing: true, age: null, waiting: ["t1"] }))
+ .mockResolvedValue(answer({ panes: { t1: value }, refreshing: false, age: 0, waiting: [] }));
+ vi.stubGlobal("fetch", fetcher);
+ const hook = renderHook(() => useSessionGitHubPane("w", "t1"));
+ expect(hook.result.current).toEqual({ status: null, pending: true });
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(hook.result.current).toEqual({ status: null, pending: true });
+ // A read on its way is asked about again within about a second.
+ await act(() => vi.advanceTimersByTimeAsync(1_500));
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(hook.result.current).toEqual({ status: value, pending: false });
+});
+
+it("stops spinning for a pane the backend reads nothing for", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(answer({ panes: { t1: value }, refreshing: false, age: 0 })));
+ const remote = renderHook(() => useSessionGitHubPane("w", "remote"));
+ expect(remote.result.current.pending).toBe(true);
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(remote.result.current).toEqual({ status: null, pending: false });
+});
+
+it("shows a tab's last answer the moment it is visited again", async () => {
+ const fetcher = vi.fn().mockResolvedValue(answer({ panes: { t1: value }, refreshing: false, age: 0 }));
+ vi.stubGlobal("fetch", fetcher);
+ const first = renderHook(() => useSessionGitHubPane("w", "t1"));
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ first.unmount();
+ await act(() => vi.advanceTimersByTimeAsync(5_000));
+ fetcher.mockClear();
+ const again = renderHook(() => useSessionGitHubPane("w", "t1"));
+ // Painted from memory before any request: no spinner for a recent answer.
+ expect(fetcher).not.toHaveBeenCalled();
+ expect(again.result.current).toEqual({ status: value, pending: false });
+});
+
+it("keeps an old answer on screen and spins until the backend confirms it", async () => {
+ const fetcher = vi.fn().mockResolvedValue(answer({ panes: { t1: value }, refreshing: false, age: 0 }));
+ vi.stubGlobal("fetch", fetcher);
+ const first = renderHook(() => useSessionGitHubPane("w", "t1"));
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ first.unmount();
+ await act(() => vi.advanceTimersByTimeAsync(120_000));
+ const merged = { ...value, state: "merged" as const, fetched_at: Date.now() / 1000 };
+ fetcher
+ .mockResolvedValueOnce(answer({ panes: { t1: value }, refreshing: true, age: 125, waiting: [] }))
+ .mockResolvedValue(answer({ panes: { t1: merged }, refreshing: false, age: 0, waiting: [] }));
+ const again = renderHook(() => useSessionGitHubPane("w", "t1"));
+ expect(again.result.current).toEqual({ status: value, pending: true });
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(again.result.current).toEqual({ status: value, pending: true });
+ await act(() => vi.advanceTimersByTimeAsync(1_500));
+ expect(again.result.current).toEqual({ status: merged, pending: false });
+});
+
+it("does not spin while a recent answer is merely being refreshed", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(answer({ panes: { t1: value }, refreshing: true, age: 20, waiting: [] })));
+ const hook = renderHook(() => useSessionGitHubPane("w", "t1"));
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(hook.result.current).toEqual({ status: value, pending: false });
+});
+
+it("stops spinning when the status cannot be read", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("offline")));
+ const hook = renderHook(() => useSessionGitHubPane("w", "t1"));
+ expect(hook.result.current.pending).toBe(true);
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(hook.result.current).toEqual({ status: null, pending: false });
+});
+
+it("follows a slow read up less often after a while, then returns to its rhythm", async () => {
+ const fetcher = vi.fn().mockResolvedValue(answer({ panes: {}, refreshing: true, age: null, waiting: ["t1"] }));
+ vi.stubGlobal("fetch", fetcher);
+ renderHook(() => useSessionGitHubPane("w", "t1"));
+ await act(() => vi.advanceTimersByTimeAsync(60_000));
+ // Thirty quick follow-ups, then one every five seconds or so.
+ expect(fetcher.mock.calls.length).toBeGreaterThan(30);
+ expect(fetcher.mock.calls.length).toBeLessThan(45);
+ fetcher.mockClear();
+ fetcher.mockResolvedValue(answer({ panes: {}, refreshing: false, age: 0 }));
+ await act(() => vi.advanceTimersByTimeAsync(10_000));
+ const settled = fetcher.mock.calls.length;
+ await act(() => vi.advanceTimersByTimeAsync(9_000));
+ expect(fetcher.mock.calls.length).toBe(settled);
+});
+
+it("stops spinning and says unavailable when the backend's reads keep failing", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(answer({
+ panes: { t1: value }, refreshing: false, age: 600, waiting: [], failed: true,
+ })));
+ const hook = renderHook(() => useSessionGitHubPane("w", "t1"));
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(hook.result.current.pending).toBe(false);
+ expect(hook.result.current.status?.available).toBe(false);
+});
+
+it("asks at once when a pane joins a workspace that is already being polled", async () => {
+ const fetcher = vi.fn().mockResolvedValue(answer({ panes: { t1: value }, refreshing: false, age: 0 }));
+ vi.stubGlobal("fetch", fetcher);
+ renderHook(() => useSessionGitHubPane("w", "t1"));
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ // A new pane may reuse a closed pane's name: the backend is asked well
+ // before the next regular poll.
+ renderHook(() => useSessionGitHubPane("w", "t2"));
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(fetcher).toHaveBeenCalledTimes(2);
+});
+
+it("spins when GitHub's own answer is old, even on a board read moments ago", async () => {
+ const stale = { ...value, fetched_at: Date.now() / 1000 - 300 };
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(answer({ panes: { t1: stale }, refreshing: true, age: 1, waiting: [] })));
+ const hook = renderHook(() => useSessionGitHubPane("w", "t1"));
+ await act(() => vi.advanceTimersByTimeAsync(200));
+ expect(hook.result.current).toEqual({ status: stale, pending: true });
+});
+
+it("asks the backend to hold a follow-up until its read lands", async () => {
+ const fetcher = vi.fn()
+ .mockResolvedValueOnce(answer({ panes: {}, refreshing: true, age: null, waiting: ["t1"] }))
+ .mockResolvedValue(answer({ panes: { t1: value }, refreshing: false, age: 0, waiting: [] }));
+ vi.stubGlobal("fetch", fetcher);
+ renderHook(() => useSessionGitHubPane("w", "t1"));
+ await act(() => vi.advanceTimersByTimeAsync(400));
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(String(fetcher.mock.calls[0][0])).not.toContain("wait=");
+ expect(String(fetcher.mock.calls[0][0])).toContain("instant=1");
+ expect(String(fetcher.mock.calls[1][0])).toContain("wait=4");
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts b/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
index 3a39d9b1db..928e26bb1b 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/useSessionGitHub.ts
@@ -27,34 +27,86 @@ export type SessionCiState = CiStatus["state"] | "cancelled" | "neutral" | "skip
| "action_required" | "timed_out" | "startup_failure" | "stale" | "unknown"
| "waiting" | "requested" | "expected" | "error";
+/** What a pane header shows: the last answer, and whether it is still being confirmed. */
+export interface PaneGitHub {
+ status: SessionGitHubStatus | null;
+ /**
+ * The status is being read, or read again because the one on screen is old.
+ * The header shows a spinner meanwhile instead of passing it off as current.
+ */
+ pending: boolean;
+}
+
type Panes = Record<string, SessionGitHubStatus | null>;
-type Entry = {
+interface Board {
panes: Panes;
- listeners: Set<() => void>;
- stop: () => void;
-};
+ /**
+ * This window's clock when the backend last read the answer, or when a
+ * failed refresh marked it unavailable; null before any answer. An answer
+ * older than {@link FRESH_MS} spins until a newer one replaces it.
+ */
+ readAt: number | null;
+ /** Panes without an answer that one is being read for; null before the backend answered. */
+ waiting: ReadonlySet<string> | null;
+}
+type Entry = { board: Board; listeners: Set<() => void>; refresh: () => void; stop: () => void };
+
+/**
+ * An answer younger than this is shown as current while a newer one is read.
+ * The backend keeps the tabs behind the front one younger than this.
+ */
+export const FRESH_MS = 120_000;
+/**
+ * While the backend reads a newer answer, the next request asks it to hold on
+ * for that read this long, so the answer lands the moment the read does.
+ */
+const WAIT_S = 4;
+/** After this many follow-ups a read that does not land is asked about less often. */
+const MAX_FOLLOW_UPS = 30;
+const POLL_MS = 20_000;
+
+const UNKNOWN: Board = { panes: {}, readAt: null, waiting: null };
+const NONE: ReadonlySet<string> = new Set();
+const IDLE: PaneGitHub = { status: null, pending: false };
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>();
+const remembered = new Map<string, Board>();
+
+const old = (readAt: number | null) => readAt === null || Date.now() - readAt > FRESH_MS;
+/** GitHub's own answer about the branch is older than {@link FRESH_MS}. */
+const outdated = (status: SessionGitHubStatus | null) =>
+ status !== null && Date.now() - status.fetched_at * 1000 > FRESH_MS;
function start(workspaceId: string): Entry {
- const entry: Entry = { panes: remembered.get(workspaceId) ?? EMPTY, listeners: new Set(), stop: () => {} };
+ // What this window saw last is shown at once; once it is old it spins until
+ // the backend has confirmed or replaced it.
+ const entry: Entry = {
+ board: remembered.get(workspaceId) ?? UNKNOWN, listeners: new Set(), refresh: () => {}, stop: () => {},
+ };
let disposed = false;
+ let followUps = 0;
let controller: AbortController | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
let cancelConnect: (() => void) | undefined;
- const notify = () => entry.listeners.forEach((listener) => listener());
+ const publish = (board: Board) => {
+ entry.board = board;
+ remembered.set(workspaceId, board);
+ 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,
- others: status.others?.map((other) => ({ ...other, available: false, reason })),
- } : null,
- ]));
- notify();
+ publish({
+ // Nothing is on its way any more: no header may keep spinning.
+ readAt: Date.now(),
+ waiting: NONE,
+ panes: Object.fromEntries(Object.entries(entry.board.panes).map(([name, status]) => [
+ name, status ? {
+ ...status, available: false, reason,
+ others: status.others?.map((other) => ({ ...other, available: false, reason })),
+ } : null,
+ ])),
+ });
};
const schedule = (delay: number) => {
clearTimeout(timer);
@@ -64,31 +116,48 @@ function start(workspaceId: string): Entry {
};
const poll = async () => {
if (disposed || controller || document.hidden) return;
+ let refreshing = false;
controller = new AbortController();
const timeout = setTimeout(() => controller?.abort(), 30_000);
try {
- const query = new URLSearchParams({ workspace_id: workspaceId });
+ // `instant`: answer from the last read at once; this header asks again.
+ const query = new URLSearchParams({ workspace_id: workspaceId, instant: "1" });
+ if (followUps) query.set("wait", String(WAIT_S));
const response = await fetch(`/api/agentic-ide/git/session-status?${query}`, { signal: controller.signal });
if (!response.ok) throw new Error("GitHub status could not be refreshed.");
- const data = await response.json() as { panes: Panes };
+ const data = await response.json() as {
+ panes: Panes; refreshing?: boolean; age?: number | null; waiting?: string[]; failed?: boolean;
+ };
if (disposed) return;
+ // The backend answers with what it last read and reads on in the
+ // background; an older backend answers only once it has read.
+ refreshing = data.refreshing === true;
+ const readAt = data.refreshing === undefined ? Date.now()
+ : typeof data.age === "number" ? Date.now() - data.age * 1000 : null;
+ const previous = entry.board.panes;
// After logout/offline, keep a previously confirmed branch visible with
// an unknown status. Never borrow identity across a checkout change.
- entry.panes = Object.fromEntries(Object.entries(data.panes).map(([name, status]) => {
- const previous = entry.panes[name];
- if (status?.owned && !status.available && previous?.owned && previous.published
- && status.repo === previous.repo && status.branch === previous.branch) {
+ const panes = Object.fromEntries(Object.entries(data.panes).map(([name, status]) => {
+ const before = previous[name];
+ if (status?.owned && !status.available && before?.owned && before.published
+ && status.repo === before.repo && status.branch === before.branch) {
return [name, { ...status, published: true }];
}
return [name, status];
}));
- notify();
+ publish({ panes, readAt, waiting: refreshing ? new Set(data.waiting ?? []) : NONE });
+ // The backend's last read failed and nothing newer is being read: what
+ // it holds is old, and says so instead of spinning.
+ if (data.failed && !refreshing) unavailable(translate("ide_panes.github.refresh_failed"));
} catch {
if (!disposed) unavailable(translate("ide_panes.github.refresh_failed"));
} finally {
clearTimeout(timeout);
controller = undefined;
- if (!disposed) timer = setTimeout(() => schedule(0), spreadDelay(20_000));
+ followUps = refreshing ? followUps + 1 : 0;
+ // A follow-up waits on the backend for the read, so it is sent at once.
+ const delay = !refreshing ? POLL_MS : followUps <= MAX_FOLLOW_UPS ? 100 : 5_000;
+ if (!disposed) timer = setTimeout(() => schedule(0), spreadDelay(delay));
}
};
const resume = () => {
@@ -97,14 +166,16 @@ function start(workspaceId: string): Entry {
cancelConnect?.();
return;
}
- // A suspended window must not present its last green badge as live data.
- if (Object.values(entry.panes).some((value) => value && Date.now() / 1000 - value.fetched_at > 60)) {
- unavailable(translate("ide_panes.github.refreshing"));
- }
+ // A suspended window must not present its last badge as live data: drawn
+ // again now, an old one spins until the backend has confirmed it.
+ if (old(entry.board.readAt)) publish({ ...entry.board });
if (!controller) schedule(spreadDelay(500));
};
document.addEventListener("visibilitychange", resume);
window.addEventListener("online", resume);
+ entry.refresh = () => {
+ if (!controller) schedule(spreadDelay(120));
+ };
entry.stop = () => {
disposed = true;
clearTimeout(timer);
@@ -113,29 +184,57 @@ function start(workspaceId: string): Entry {
document.removeEventListener("visibilitychange", resume);
window.removeEventListener("online", resume);
};
- schedule(spreadDelay(250));
+ // The backend answers from what it last read, so asking at once is cheap.
+ schedule(spreadDelay(120));
return entry;
}
-export function useSessionGitHub(workspaceId?: string, pane?: string): SessionGitHubStatus | null {
+function paneOf(board: Board, pane: string): PaneGitHub {
+ if (pane in board.panes) {
+ const status = board.panes[pane];
+ // A status that could not be read says so instead of spinning.
+ return { status, pending: old(board.readAt) || (outdated(status) && status?.available !== false) };
+ }
+ const pending = board.waiting === null || board.waiting.has(pane);
+ return pending ? { status: null, pending } : IDLE;
+}
+
+export function useSessionGitHubPane(workspaceId?: string, pane?: string): PaneGitHub {
const subscribe = useCallback((listener: () => void) => {
if (!workspaceId) return () => {};
let entry = entries.get(workspaceId);
if (!entry) {
entry = start(workspaceId);
entries.set(workspaceId, entry);
+ } else {
+ // A pane that joins a running workspace may reuse a closed pane's name;
+ // the backend tells them apart, so it is asked at once rather than in
+ // twenty seconds.
+ entry.refresh();
}
entry.listeners.add(listener);
return () => {
entry.listeners.delete(listener);
if (!entry.listeners.size) {
- remembered.set(workspaceId, entry.panes);
entry.stop();
entries.delete(workspaceId);
}
};
}, [workspaceId]);
- const snapshot = useCallback(() => workspaceId ? entries.get(workspaceId)?.panes ?? EMPTY : EMPTY, [workspaceId]);
- const panes = useSyncExternalStore(subscribe, snapshot, () => EMPTY);
- return pane ? panes[pane] ?? null : null;
+ // Before the first subscription, what this window saw last already paints.
+ const snapshot = useCallback(
+ () => workspaceId ? entries.get(workspaceId)?.board ?? remembered.get(workspaceId) ?? UNKNOWN : null,
+ [workspaceId],
+ );
+ const board = useSyncExternalStore(subscribe, snapshot, () => null);
+ return board && pane ? paneOf(board, pane) : IDLE;
+}
+
+export function useSessionGitHub(workspaceId?: string, pane?: string): SessionGitHubStatus | null {
+ return useSessionGitHubPane(workspaceId, pane).status;
+}
+
+/** Forget every remembered answer; tests only. */
+export function resetSessionGitHubForTests() {
+ remembered.clear();
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 295b72c287..91efa26d21 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -8971,7 +8971,8 @@
"open_aria": "GitHub {destination} öffnen: {identity}",
"open_title": "{destination} öffnen",
"refresh_failed": "GitHub-Status konnte nicht aktualisiert werden.",
- "refreshing": "GitHub-Status wird aktualisiert…"
+ "refreshing": "GitHub-Status wird aktualisiert…",
+ "loading": "GitHub-Status wird gelesen…"
},
"dock": {
"swap": "Plätze tauschen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index fd42c2e1a8..7ab83be843 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -8971,7 +8971,8 @@
"open_aria": "Open GitHub {destination}: {identity}",
"open_title": "Open {destination}",
"refresh_failed": "GitHub status could not be refreshed.",
- "refreshing": "Refreshing GitHub status…"
+ "refreshing": "Refreshing GitHub status…",
+ "loading": "Reading the GitHub status…"
},
"dock": {
"swap": "Swap positions",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 1dd70118d3..2f8fa76c25 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -8971,7 +8971,8 @@
"open_aria": "Abrir {destination} de GitHub: {identity}",
"open_title": "Abrir {destination}",
"refresh_failed": "No se pudo actualizar el estado de GitHub.",
- "refreshing": "Actualizando el estado de GitHub…"
+ "refreshing": "Actualizando el estado de GitHub…",
+ "loading": "Leyendo el estado de GitHub…"
},
"dock": {
"swap": "Intercambiar posiciones",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
index 8565c31b92..ee70e52643 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
@@ -8971,7 +8971,8 @@
"open_aria": "Abrir {destination} do GitHub: {identity}",
"open_title": "Abrir {destination}",
"refresh_failed": "Não foi possível atualizar o estado do GitHub.",
- "refreshing": "A atualizar o estado do GitHub…"
+ "refreshing": "A atualizar o estado do GitHub…",
+ "loading": "A ler o estado do GitHub…"
},
"dock": {
"swap": "Trocar posições",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
index 9e673c757b..c4f98a19ea 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -8971,7 +8971,8 @@
"open_aria": "打开 GitHub {destination}:{identity}",
"open_title": "打开{destination}",
"refresh_failed": "无法刷新 GitHub 状态。",
- "refreshing": "正在刷新 GitHub 状态…"
+ "refreshing": "正在刷新 GitHub 状态…",
+ "loading": "正在读取 GitHub 状态…"
},
"dock": {
"swap": "交换位置",
diff --git a/tests/unit/agentic_ide/test_github_status.py b/tests/unit/agentic_ide/test_github_status.py
index b78b66c209..a62a489a98 100644
--- a/tests/unit/agentic_ide/test_github_status.py
+++ b/tests/unit/agentic_ide/test_github_status.py
@@ -189,6 +189,7 @@ def test_checkout_reads_worktree_head_and_custom_upstream(monkeypatch, tmp_path)
return ""
monkeypatch.setattr(status, "_git", git)
+ monkeypatch.setattr(status, "_setting", git)
assert status.checkout(tmp_path, "local-name") == TARGET
@@ -197,6 +198,36 @@ def test_detached_head_never_gets_branch_status(monkeypatch, tmp_path):
assert status.checkout(tmp_path) is None
+def test_remote_settings_are_asked_of_git_once_a_minute(monkeypatch, tmp_path):
+ status._settings.clear()
+ asked = []
+
+ def run(args, cwd):
+ asked.append(args)
+ # `git config --get` answers an unset option with exit code 1.
+ return SimpleNamespace(returncode=1, stdout="")
+
+ monkeypatch.setattr(status.git_overview, "_run", run)
+ assert status._setting(tmp_path, "config", "--get", "remote.pushDefault") == ""
+ assert status._setting(tmp_path, "config", "--get", "remote.pushDefault") == ""
+ assert len(asked) == 1
+
+
+def test_a_setting_git_gave_no_answer_for_is_asked_again(monkeypatch, tmp_path):
+ status._settings.clear()
+ answers = [
+ None,
+ SimpleNamespace(returncode=128, stdout=""),
+ SimpleNamespace(returncode=0, stdout="url\n"),
+ ]
+ monkeypatch.setattr(status.git_overview, "_run", lambda args, cwd: answers.pop(0))
+ assert status._setting(tmp_path, "remote", "get-url", "origin") == ""
+ assert status._setting(tmp_path, "remote", "get-url", "origin") == ""
+ assert status._setting(tmp_path, "remote", "get-url", "origin") == "url"
+ assert status._setting(tmp_path, "remote", "get-url", "origin") == "url"
+ assert not answers
+
+
def test_multiple_panes_share_requests_and_errors_are_unknown(monkeypatch):
status._slot.cache_clear()
reads, requests = [], []
@@ -320,7 +351,9 @@ def test_finished_branch_is_read_rarely_and_never_looks_stale(monkeypatch):
pane = status.statuses(records)["t1"]
- assert requests == ["claude/open", "claude/merged", "claude/open"]
+ # Both read at first (side by side, in any order); then only the open one.
+ assert sorted(requests[:2]) == ["claude/merged", "claude/open"]
+ assert requests[2:] == ["claude/open"]
(merged,) = pane["others"]
assert merged["state"] == "merged" and merged["available"]
assert time.time() - merged["fetched_at"] < 5
@@ -369,16 +402,244 @@ def test_route_uses_pane_cwd_and_excludes_remote_computers(monkeypatch):
branch="owned",
)
remote = SimpleNamespace(name="t2", computer_id="server")
- session = SimpleNamespace(folder="workspace", terminals=[pane, remote])
+ session = SimpleNamespace(id="w", folder="workspace", terminals=[pane, remote])
+ other = SimpleNamespace(id="behind", folder="other", terminals=[])
monkeypatch.setattr(
routes,
"get_registry",
- lambda: SimpleNamespace(get=lambda key: session if key == "w" else None),
+ lambda: SimpleNamespace(
+ get=lambda key: session if key == "w" else None, sessions=[session, other]
+ ),
)
- monkeypatch.setattr(status, "statuses", lambda folders: calls.append(folders) or {})
- assert routes.session_github_status("w") == {"panes": {}}
+ ahead = []
+ monkeypatch.setattr(
+ status,
+ "board",
+ lambda key, records, wait: calls.append((records, wait)) or {"panes": {}},
+ )
+ monkeypatch.setattr(status, "due", lambda key: True)
+ monkeypatch.setattr(status, "read_ahead", lambda key, records: ahead.append(key))
+ assert routes.session_github_status("w", wait=2, instant=True) == {"panes": {}}
+ assert calls[0][1] == 2
+ # A caller that does not know `instant` gets the answer once the read lands.
+ routes.session_github_status("w", wait=0, instant=False)
+ assert calls[1][1] == routes._LEGACY_WAIT_S
+ calls[:] = [records for records, _ in calls]
+ assert [record.pane for record in calls[0]] == ["t1"]
assert calls[0][0].folder == "fork-folder"
assert calls[0][0].created_branch == "owned"
+ # The tab behind is read ahead of its first visit; the one in front is not.
+ assert set(ahead) == {"behind"}
with pytest.raises(HTTPException) as error:
routes.session_github_status("missing")
assert error.value.status_code == 404
+
+
+# ------------------------------------------------------------------- board
+
+
+def boards(monkeypatch):
+ """Empty boards, and a `statuses` the test opens and closes by hand."""
+ monkeypatch.setattr(status, "_boards", {})
+ monkeypatch.setattr(status, "_ahead", {})
+ monkeypatch.setattr(status, "_ahead_running", False)
+ monkeypatch.setattr(status, "_front_reads", 0)
+ status._front_idle.set()
+ gate = SimpleNamespace(
+ release=__import__("threading").Event(),
+ reads=[],
+ ttls=[],
+ answer=lambda records: {record.pane: {"branch": record.history_id} for record in records},
+ )
+
+ def statuses(records, live_ttl=status._LIVE_TTL):
+ gate.reads.append([record.pane for record in records])
+ gate.ttls.append(live_ttl)
+ assert gate.release.wait(5)
+ return gate.answer(records)
+
+ monkeypatch.setattr(status, "statuses", statuses)
+ return gate
+
+
+def _settle(predicate):
+ deadline = time.monotonic() + 5
+ while not predicate():
+ assert time.monotonic() < deadline, "the background read did not finish"
+ time.sleep(0.01)
+
+
+def _records(*panes, history="h"):
+ return [status.PaneBranchRecord(pane, f"{history}-{pane}", "folder") for pane in panes]
+
+
+def test_board_answers_at_once_and_reads_in_the_background(boards):
+ first = status.board("w", _records("t1"))
+ # Nothing read yet: no answer, and the pane is named as waiting for one.
+ assert first == {
+ "panes": {},
+ "refreshing": True,
+ "age": None,
+ "waiting": ["t1"],
+ "failed": False,
+ }
+ boards.release.set()
+ _settle(lambda: not status.board("w", _records("t1"))["refreshing"])
+ answer = status.board("w", _records("t1"))
+ assert answer["panes"] == {"t1": {"branch": "h-t1"}}
+ assert answer["waiting"] == [] and answer["age"] < 5
+
+
+def test_board_reads_once_while_a_read_runs_and_again_once_it_is_old(boards):
+ status.board("w", _records("t1"))
+ status.board("w", _records("t1"))
+ assert len(boards.reads) == 1
+ boards.release.set()
+ _settle(lambda: not status._boards["w"].reading)
+ status.board("w", _records("t1"))
+ assert len(boards.reads) == 1 # Still fresh.
+ boards.release.clear()
+ status._boards["w"].tried_at -= status._BOARD_TTL
+ status._boards["w"].read_at -= status._BOARD_TTL
+ answer = status.board("w", _records("t1"))
+ # The old answer is served while the newer one is read.
+ assert answer["refreshing"] and answer["panes"] == {"t1": {"branch": "h-t1"}}
+ assert answer["waiting"] == [] and answer["age"] >= status._BOARD_TTL
+ boards.release.set()
+ _settle(lambda: len(boards.reads) == 2 and not status._boards["w"].reading)
+
+
+def test_board_never_shows_a_pane_its_predecessors_answer(boards):
+ boards.release.set()
+ status.board("w", _records("t1", "t2"))
+ _settle(lambda: not status._boards["w"].reading)
+ boards.release.clear()
+ # T2 now runs another conversation: its old answer is withheld, T1's kept.
+ records = _records("t1") + _records("t2", history="new")
+ status._boards["w"].tried_at -= status._RETRY_S
+ answer = status.board("w", records)
+ assert answer["panes"] == {"t1": {"branch": "h-t1"}}
+ assert answer["refreshing"] and answer["waiting"] == ["t2"]
+ boards.release.set()
+ _settle(lambda: not status._boards["w"].reading)
+ assert status.board("w", records)["panes"]["t2"] == {"branch": "new-t2"}
+
+
+def test_a_failed_read_keeps_the_last_answer_and_is_not_retried_at_once(boards):
+ boards.release.set()
+ status.board("w", _records("t1"))
+ _settle(lambda: not status._boards["w"].reading)
+ read_at = status._boards["w"].read_at
+
+ def broken(records):
+ raise RuntimeError("git vanished")
+
+ boards.answer = broken
+ status._boards["w"].tried_at -= status._BOARD_TTL
+ status._boards["w"].read_at -= status._BOARD_TTL
+ status.board("w", _records("t1"))
+ _settle(lambda: not status._boards["w"].reading)
+ answer = status.board("w", _records("t1"))
+ assert answer["panes"] == {"t1": {"branch": "h-t1"}}
+ # Nothing newer is coming: the answer says so instead of looking current.
+ assert not answer["refreshing"] and answer["failed"]
+ assert status._boards["w"].read_at == read_at - status._BOARD_TTL
+ assert len(boards.reads) == 2
+
+
+def test_a_read_that_cannot_start_leaves_nothing_waiting(boards, monkeypatch):
+ def no_thread(*_, **__):
+ raise RuntimeError("can't start new thread")
+
+ monkeypatch.setattr(status.threading, "Thread", no_thread)
+ answer = status.board("w", _records("t1"))
+ assert not answer["refreshing"] and answer["waiting"] == []
+ assert status._front_reads == 0 and status._front_idle.is_set()
+
+
+def test_tabs_behind_are_read_once_one_after_another_after_the_front(boards):
+ status.board("front", _records("t1"))
+ status.read_ahead("a", _records("t1"))
+ status.read_ahead("b", _records("t1"))
+ status.read_ahead("a", _records("t1"))
+ assert not status.due("a") and not status.due("b")
+ # The read for the tab in front runs alone; the reads ahead wait for it.
+ time.sleep(0.05)
+ assert len(boards.reads) == 1
+ boards.release.set()
+ _settle(lambda: len(boards.reads) == 3 and not status._ahead_running)
+ assert status.board("a", _records("t1"))["panes"] == {"t1": {"branch": "h-t1"}}
+
+
+def test_a_visit_takes_over_a_read_ahead_that_has_not_begun(boards):
+ status.board("front", _records("t1"))
+ status.read_ahead("behind", _records("t1"))
+ # Someone switches to the tab behind before its turn came.
+ answer = status.board("behind", _records("t1"))
+ assert answer["refreshing"] and "behind" not in status._ahead
+ boards.release.set()
+ _settle(lambda: not status._ahead_running and not status._front_reads)
+ assert len(boards.reads) == 2
+
+
+def test_one_pane_that_cannot_be_read_does_not_cost_the_others_their_status(monkeypatch):
+ answers = {"claude/fine": _answer("claude/fine", 6, "OPEN")}
+ _session(monkeypatch, list(answers), answers)
+ working = status.pane_branches
+
+ def pane_branches(record):
+ if record.pane == "broken":
+ raise OSError("record vanished mid-read")
+ return working(record)
+
+ monkeypatch.setattr(status, "pane_branches", pane_branches)
+ records = [
+ status.PaneBranchRecord("broken", "broken", "worktree"),
+ status.PaneBranchRecord("t1", "t1", "worktree"),
+ ]
+ panes = status.statuses(records)
+ assert panes["broken"] is None
+ assert panes["t1"]["number"] == 6
+
+
+def test_a_tab_behind_is_kept_recent_with_a_slower_github_rhythm(boards):
+ boards.release.set()
+ status.read_ahead("behind", _records("t1"))
+ _settle(lambda: not status._ahead_running)
+ assert boards.ttls == [status._WARM_GITHUB_TTL]
+ # Recent: not read again.
+ assert not status.due("behind")
+ status.read_ahead("behind", _records("t1"))
+ assert len(boards.reads) == 1
+ # Once older than the warm interval, it is read again ahead of a visit.
+ status._boards["behind"].read_at -= status._WARM_S
+ status._boards["behind"].tried_at -= status._WARM_S
+ assert status.due("behind")
+ status.read_ahead("behind", _records("t1"))
+ _settle(lambda: len(boards.reads) == 2 and not status._ahead_running)
+ # The tab in front still asks GitHub on its own, quicker rhythm.
+ status.board("front", _records("t1"))
+ _settle(lambda: len(boards.reads) == 3 and not status._front_reads)
+ assert boards.ttls[-1] == status._LIVE_TTL
+
+
+def test_a_request_that_waits_gets_the_read_the_moment_it_lands(boards):
+ status.board("w", _records("t1"))
+ threading = __import__("threading")
+ threading.Timer(0.2, boards.release.set).start()
+ started = time.monotonic()
+ answer = status.board("w", _records("t1"), wait=3)
+ assert time.monotonic() - started < 2
+ assert not answer["refreshing"] and answer["panes"] == {"t1": {"branch": "h-t1"}}
+
+
+def test_a_wait_is_bounded_when_the_read_is_slow(boards, monkeypatch):
+ monkeypatch.setattr(status, "_MAX_WAIT_S", 0.2)
+ status.board("w", _records("t1"))
+ started = time.monotonic()
+ answer = status.board("w", _records("t1"), wait=5)
+ assert 0.15 < time.monotonic() - started < 2
+ assert answer["refreshing"] and answer["waiting"] == ["t1"]
+ boards.release.set()
+ _settle(lambda: not status._front_reads)
diff --git a/tests/unit/agentic_ide/test_session_branches.py b/tests/unit/agentic_ide/test_session_branches.py
index 715bc337ac..205656d31d 100644
--- a/tests/unit/agentic_ide/test_session_branches.py
+++ b/tests/unit/agentic_ide/test_session_branches.py
@@ -518,3 +518,101 @@ def test_deleted_branch_is_passed_on_unconfirmed_and_a_foreign_one_never(reposit
assert found == [("deleted", False)]
assert branches.owned_branch(record) is None
+
+
+def test_a_record_that_has_not_grown_is_not_read_again(tmp_path, monkeypatch):
+ branches._cache.clear()
+ monkeypatch.setattr(agent_transcript, "can_read", lambda _: True)
+ reads = []
+ stamps = [(100, 1)]
+
+ def read(*_, **__):
+ reads.append(1)
+ return [call({"cmd": "git switch -c owned"}), result("Switched to a new branch 'owned'")]
+
+ monkeypatch.setattr(agent_transcript, "read_events", read)
+ monkeypatch.setattr(agent_transcript, "stamp", lambda *_, **__: stamps[-1])
+ record = branches.PaneBranchRecord("t1", "history", str(tmp_path), "claude", "session")
+
+ def later():
+ # Past the short window in which nothing is asked at all.
+ for entry in branches._cache.values():
+ entry.read_at -= 60
+
+ assert [found.branch for found in branches._evidence(record)[0]] == ["owned"]
+ later()
+ assert [found.branch for found in branches._evidence(record)[0]] == ["owned"]
+ assert len(reads) == 1
+ stamps.append((180, 2))
+ later()
+ branches._evidence(record)
+ assert len(reads) == 2
+
+
+def test_a_record_whose_growth_cannot_be_seen_is_read_again(tmp_path, monkeypatch):
+ branches._cache.clear()
+ monkeypatch.setattr(agent_transcript, "can_read", lambda _: True)
+ reads = []
+ monkeypatch.setattr(agent_transcript, "read_events", lambda *_, **__: reads.append(1) or [])
+ monkeypatch.setattr(agent_transcript, "stamp", lambda *_, **__: None)
+ record = branches.PaneBranchRecord("t1", "history", str(tmp_path), "grok", "session")
+
+ branches._evidence(record)
+ branches._evidence(record)
+ assert len(reads) == 1
+ for entry in branches._cache.values():
+ entry.read_at -= 60
+ branches._evidence(record)
+ assert len(reads) == 2
+
+
+def test_a_record_that_could_not_be_read_is_not_kept_as_empty(tmp_path, monkeypatch):
+ branches._cache.clear()
+ monkeypatch.setattr(agent_transcript, "can_read", lambda _: True)
+ answers = [None, [call({"cmd": "git switch -c owned"}), result("new branch 'owned'")]]
+ monkeypatch.setattr(agent_transcript, "read_events", lambda *_, **__: answers.pop(0))
+ monkeypatch.setattr(agent_transcript, "stamp", lambda *_, **__: (100, 1))
+ record = branches.PaneBranchRecord("t1", "history", str(tmp_path), "claude", "session")
+
+ assert branches._evidence(record) == ([], [])
+ for entry in branches._cache.values():
+ entry.read_at -= 60
+ # The record itself did not change; the failed read is still not its answer.
+ assert [found.branch for found in branches._evidence(record)[0]] == ["owned"]
+
+
+def test_stamp_follows_the_record_file(tmp_path, monkeypatch):
+ path = tmp_path / "session.jsonl"
+ path.write_text("{}\n", encoding="utf-8")
+ monkeypatch.setattr(agent_transcript, "_codex_file", lambda *_: path)
+ monkeypatch.setattr(agent_transcript, "_claude_file", lambda *_: None)
+
+ first = agent_transcript.stamp("codex", "session")
+ assert first is not None and first[0] == path.stat().st_size
+ path.write_text("{}\n{}\n", encoding="utf-8")
+ assert agent_transcript.stamp("codex", "session") != first
+ assert agent_transcript.stamp("claude", "session") is None
+ assert agent_transcript.stamp("codex", "") is None
+ assert agent_transcript.stamp("unknown-cli", "session") is None
+
+
+def test_repository_of_a_folder_is_asked_of_git_once(tmp_path, monkeypatch):
+ branches._commons.clear()
+ asked = []
+
+ def out(args, cwd):
+ asked.append(args)
+ return ".git\n"
+
+ monkeypatch.setattr(branches.git_overview, "_out", out)
+ assert branches._common(str(tmp_path)) == branches._common(str(tmp_path)) != ""
+ assert len(asked) == 1
+
+
+def test_a_folder_git_gave_no_answer_for_is_asked_again(tmp_path, monkeypatch):
+ branches._commons.clear()
+ answers = [None, ".git\n"]
+ monkeypatch.setattr(branches.git_overview, "_out", lambda args, cwd: answers.pop(0))
+
+ assert branches._common(str(tmp_path)) == ""
+ assert branches._common(str(tmp_path)) != ""