Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ide): show the agent done gate's last verdict on each pane (#748)
Ruben Lütke8dde994cf39a
diff --git a/dodaios/agentic_ide/done_gate_status.py b/dodaios/agentic_ide/done_gate_status.pynew file mode 100644index 0000000000..f9f3e072d2--- /dev/null+++ b/dodaios/agentic_ide/done_gate_status.py@@ -0,0 +1,266 @@+"""The agent done gate's last verdict for each pane, read from its own record.++``scripts/agent_done_gate.py`` runs from each coding CLI's Stop hook and+decides whether the agent may stop yet. On every check it writes the session's+last verdict to ``<git common dir>/agent-done-gate/sessions/<session>.json``+under ``"last"``::++ {"verdict", "reason", "next", "pr", "branch", "cwd", "at"}++This module only reads those files. It never asks GitHub and never runs the+gate: the header shows what the gate itself last said.++A pane is matched to its record by (:func:`board`):++1. its agent session id, when the app knows it (Claude Code, Codex, Kimi,+ OpenCode, ... through ``agent_sessions``): that session's file and no+ other, however old;+2. otherwise by folder or branch: the newest record, at most+ :data:`FALLBACK_MAX_AGE_S` old, whose ``cwd`` is the pane's folder or whose+ ``branch`` is the pane's branch. Records of sessions another pane of the+ workspace is known to own are never borrowed.+"""++from __future__ import annotations++import json+import os+import re+import threading+import time+from collections.abc import Callable, Iterable+from dataclasses import asdict, dataclass+from datetime import datetime+from pathlib import Path+from typing import Any++from dodaios.agentic_ide import git_overview++#: The gate's folder inside the git common dir (``STATE_DIR`` in the gate).+STATE_DIR = "agent-done-gate"+#: The verdicts a header shows. NONE and HOLD stay quiet: nothing to land, or+#: a person asked for the branch to stay local.+SHOWN = frozenset({"DONE", "WAIT", "FIX", "STUCK"})+#: A record matched only by folder or branch is ignored once it is this old.+FALLBACK_MAX_AGE_S = 6 * 3600+#: How long a folder's git common dir and branch are reused before asking git again.+REPO_TTL_S = 30.0+#: Long reasons are cut; the tooltip has room for a sentence or two, not a log.+MAX_TEXT = 600+++@dataclass(frozen=True, slots=True)+class PaneGateRecord:+ """What is known about one pane: its name, its folder, its session, its branch."""++ pane: str+ folder: str+ session_id: str = ""+ #: The worktree branch Jarvis created for the pane, when it did.+ branch: str = ""+++@dataclass(frozen=True, slots=True)+class GateVerdict:+ verdict: str+ reason: str+ next: str+ pr: int | None+ branch: str+ at: str+ #: ``session``: the pane's own session wrote it; ``folder``: matched by+ #: folder or branch, so it may be a neighbouring session's word.+ matched: str++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++@dataclass(frozen=True, slots=True)+class RepoInfo:+ common_dir: Path | None+ branch: str = ""+++Locate = Callable[[str], RepoInfo]+++def safe_name(session: str) -> str:+ """The file name the gate gives a session id (``_safe`` in the gate)."""+ return re.sub(r"[^\w.-]", "_", session)[:120]+++def _norm(folder: str) -> str:+ if not folder:+ return ""+ try:+ return os.path.normcase(os.path.normpath(os.path.abspath(folder)))+ except (OSError, ValueError): # an unreadable path matches no record; the label stays empty+ return ""+++def _timestamp(value: Any) -> float | None:+ if not isinstance(value, str) or not value:+ return None+ try:+ stamp = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))+ except ValueError: # a record without a valid time is not shown, by design+ return None+ if stamp.tzinfo is None:+ return None+ return stamp.timestamp()+++def _text(value: Any) -> str:+ return value.strip()[:MAX_TEXT] if isinstance(value, str) else ""+++def parse_last(data: Any) -> dict[str, Any] | None:+ """The ``last`` record of a session file, cleaned, or None if it is not one."""+ if not isinstance(data, dict):+ return None+ last = data.get("last")+ if not isinstance(last, dict):+ return None+ verdict = _text(last.get("verdict")).upper()+ at = _text(last.get("at"))+ if not verdict or _timestamp(at) is None:+ return None+ pr = last.get("pr")+ return {+ "verdict": verdict,+ "reason": _text(last.get("reason")),+ "next": _text(last.get("next")),+ "pr": pr if isinstance(pr, int) and not isinstance(pr, bool) and pr > 0 else None,+ "branch": _text(last.get("branch")),+ "cwd": _text(last.get("cwd")),+ "at": at,+ }+++def _read(path: Path) -> dict[str, Any] | None:+ try:+ return parse_last(json.loads(path.read_text(encoding="utf-8")))+ except (OSError, ValueError): # the gate may be mid-write or absent; next poll reads it+ return None+++def _verdict(last: dict[str, Any], matched: str) -> GateVerdict | None:+ if last["verdict"] not in SHOWN:+ return None+ return GateVerdict(+ verdict=last["verdict"],+ reason=last["reason"],+ next=last["next"],+ pr=last["pr"],+ branch=last["branch"],+ at=last["at"],+ matched=matched,+ )+++# ------------------------------------------------------------------ git+++_repos: dict[str, tuple[float, RepoInfo]] = {}+_repos_lock = threading.Lock()+++def locate(folder: str) -> RepoInfo:+ """The git common dir and checked-out branch of ``folder``, briefly cached."""+ key = _norm(folder)+ now = time.monotonic()+ with _repos_lock:+ hit = _repos.get(key)+ if hit and now - hit[0] < REPO_TTL_S:+ return hit[1]+ out = (+ git_overview._out(+ ["rev-parse", "--path-format=absolute", "--git-common-dir", "--abbrev-ref", "HEAD"],+ Path(folder),+ )+ if key and Path(folder).is_dir()+ else None+ )+ lines = (out or "").splitlines()+ info = RepoInfo(+ common_dir=Path(lines[0].strip()) if lines and lines[0].strip() else None,+ branch=lines[1].strip() if len(lines) > 1 and lines[1].strip() != "HEAD" else "",+ )+ with _repos_lock:+ _repos[key] = (now, info)+ return info+++def forget_repos() -> None:+ """Drop the cached git answers; tests only."""+ with _repos_lock:+ _repos.clear()+++# ------------------------------------------------------------------ board+++def _recent(sessions: Path, now: float) -> list[tuple[str, dict[str, Any]]]:+ """Every (file stem, record) in ``sessions`` written within the fallback window."""+ found: list[tuple[str, dict[str, Any]]] = []+ try:+ entries = list(os.scandir(sessions))+ except OSError: # no sessions folder means the gate never ran in this repository+ return found+ for entry in entries:+ if not entry.name.endswith(".json"):+ continue+ try:+ if now - entry.stat().st_mtime > FALLBACK_MAX_AGE_S:+ continue+ except OSError: # a file deleted between listing and stat is simply gone+ continue+ last = _read(Path(entry.path))+ stamp = _timestamp(last["at"]) if last else None+ if last and stamp is not None and now - stamp <= FALLBACK_MAX_AGE_S:+ found.append((entry.name[: -len(".json")], last))+ return found+++def board(+ records: Iterable[PaneGateRecord],+ *,+ now: float | None = None,+ find_repo: Locate | None = None,+) -> dict[str, dict[str, Any] | None]:+ """The gate's last shown verdict per pane name (None when there is none to show)."""+ now = time.time() if now is None else now+ find_repo = find_repo or locate+ records = list(records)+ owned = {safe_name(r.session_id) for r in records if r.session_id}+ recent: dict[Path, list[tuple[str, dict[str, Any]]]] = {}+ answer: dict[str, dict[str, Any] | None] = {}+ for record in records:+ repo = find_repo(record.folder)+ if repo.common_dir is None:+ answer[record.pane] = None+ continue+ sessions = repo.common_dir / STATE_DIR / "sessions"+ if record.session_id:+ last = _read(sessions / f"{safe_name(record.session_id)}.json")+ shown = _verdict(last, "session") if last else None+ answer[record.pane] = shown.to_dict() if shown else None+ continue+ if sessions not in recent:+ recent[sessions] = _recent(sessions, now)+ folder = _norm(record.folder)+ branches = {b for b in (record.branch, repo.branch) if b}+ best: dict[str, Any] | None = None+ best_at = float("-inf")+ for stem, last in recent[sessions]:+ if stem in owned:+ continue+ if not ((folder and _norm(last["cwd"]) == folder) or last["branch"] in branches):+ continue+ stamp = _timestamp(last["at"]) or 0.0+ if stamp > best_at:+ best, best_at = last, stamp+ shown = _verdict(best, "folder") if best else None+ answer[record.pane] = shown.to_dict() if shown else None+ return answerdiff --git a/dodaios/ui/web/agentic_ide_git_routes.py b/dodaios/ui/web/agentic_ide_git_routes.pyindex e7c201d626..eb30554bc6 100644--- a/dodaios/ui/web/agentic_ide_git_routes.py+++ b/dodaios/ui/web/agentic_ide_git_routes.py@@ -6,6 +6,8 @@ Endpoints (all under ``/api/agentic-ide/git``)::GET /changes Changed files under a folder, with line countsGET /diff One file's change against the last commitGET /overview A workspace's branches with merged-into, PR and CI state+ GET /session-status GitHub branch, pull request and CI status per pane+ GET /done-gate The agent done gate's last verdict per pane (local files only)GET /branch/contents A branch's own commits and changed filesGET /branch/diff How a branch changed one fileGET /branch/editors Where a branch's checkout can be opened on this computer@@ -47,6 +49,7 @@ from pydantic import BaseModel, Fieldfrom dodaios.agentic_ide import (branch_contents,+ done_gate_status,git_changes,git_ops,git_overview,@@ -246,6 +249,30 @@ def _pane_records(session: Session) -> list[PaneBranchRecord]:][email protected]("/done-gate", summary="The agent done gate's last verdict per pane")+def pane_done_gate(workspace_id: str = Query(..., min_length=1)) -> dict:+ """What ``scripts/agent_done_gate.py`` last said about each pane's session.++ Read from the gate's own state files in the repository's git common dir,+ never from GitHub, so it is cheap enough to ask on every header poll. A+ pane whose verdict is NONE or HOLD, or that has no record, maps to null.+ """+ session = get_registry().get(workspace_id)+ if session is None:+ raise HTTPException(status_code=404, detail="Workspace not found.")+ records = [+ done_gate_status.PaneGateRecord(+ pane=pane.name,+ folder=pane.cwd(session.folder),+ session_id=pane.resume.id if pane.resume else "",+ branch=pane.branch,+ )+ for pane in session.terminals+ if not pane.computer_id+ ]+ return {"panes": done_gate_status.board(records)}++# The editors a branch's checkout is offered in, when installed._BRANCH_EDITORS = ("code", "cursor")diff --git a/dodaios/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/dodaios/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex 5a57d11e42..2345aa9835 100644--- a/dodaios/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/dodaios/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -165,6 +165,7 @@ import { useIdeSidePanelStore } from "@/store/ideSidePanel";import { prefetchPaneChanges } from "./paneChangesApi";import { WorkspaceTerminalHeader } from "./WorkspaceTerminalHeader";import { usePaneContextMenu } from "./usePaneContextMenu";+import { PaneDoneGateBadge } from "./PaneDoneGateBadge";import { SessionGitHubBadge } from "./SessionGitHubBadge";import { fill, loadLocaleChunk, translate, useT } from "@/i18n";@@ -3767,6 +3768,7 @@ function PaneHeader({)}</div>+ <PaneDoneGateBadge workspaceId={githubStatusEnabled ? workspaceId : undefined} name={name} appearance={appearance} /><SessionGitHubBadge workspaceId={githubStatusEnabled ? workspaceId : undefined} name={name} appearance={appearance} />{/* Pane actions appear where the eye already is: on the pane under thepointer, on the focused pane, and while one of their menus is open.diff --git a/dodaios/ui/web/frontend/src/components/agentic/PaneDoneGateBadge.test.tsx b/dodaios/ui/web/frontend/src/components/agentic/PaneDoneGateBadge.test.tsxnew file mode 100644index 0000000000..5408a7cc97--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentic/PaneDoneGateBadge.test.tsx@@ -0,0 +1,111 @@+import { act, cleanup, render, renderHook, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { resetConnectBudgetForTests } from "@/lib/connectBudget";+import { DoneGateLabel } from "./PaneDoneGateBadge";+import { themeFor } from "./terminalThemes";+import { POLL_MS, resetPaneDoneGateForTests, usePaneDoneGate, type PaneDoneGate } from "./usePaneDoneGate";++function gate(extra: Partial<PaneDoneGate> = {}): PaneDoneGate {+ return {+ verdict: "WAIT", reason: "CI is running on PR #12", next: "Wait for the checks.", pr: 12,+ branch: "claude/feature", at: "2026-10-19T17:10:47+00:00", matched: "session", ...extra,+ };+}++describe("done gate label", () => {+ afterEach(cleanup);++ it("shows nothing without a verdict", () => {+ const { container } = render(<DoneGateLabel gate={null} appearance="dark" name="t1" />);+ expect(container.innerHTML).toBe("");+ });++ it.each([+ ["WAIT", "waiting", "yellow"],+ ["FIX", "fix", "red"],+ ["STUCK", "stuck", "red"],+ ["DONE", "landed", "green"],+ ] as const)("words %s quietly in its own colour, in both appearances", (verdict, label, slot) => {+ for (const appearance of ["dark", "light"] as const) {+ render(<DoneGateLabel gate={gate({ verdict })} appearance={appearance} name="t1" />);+ const badge = screen.getByTestId("pane-done-gate-t1");+ expect(badge.textContent).toBe(label);+ expect(badge.dataset.verdict).toBe(verdict);+ expect(badge.getAttribute("aria-label")).toBe(`t1: done gate ${label}`);+ const color = themeFor(appearance)[slot] as string;+ const swatch = document.createElement("span");+ swatch.style.color = color;+ expect(badge.style.color).toBe(swatch.style.color);+ // Only STUCK wears an outline.+ expect(badge.style.borderColor).toBe(verdict === "STUCK" ? swatch.style.color : "transparent");+ cleanup();+ }+ });++ it("puts the reason and the next step in the tooltip", () => {+ render(<DoneGateLabel gate={gate({ verdict: "FIX", matched: "folder" })} appearance="light" name="t2" />);+ const title = screen.getByTestId("pane-done-gate-t2").title;+ expect(title).toContain("Done gate: something needs fixing before this agent may stop");+ expect(title).toContain("CI is running on PR #12");+ expect(title).toContain("Next: Wait for the checks.");+ expect(title).toContain("Pull request #12");+ expect(title).toContain("Matched by this pane's folder or branch");+ });+});++describe("done gate poll", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ resetConnectBudgetForTests();+ vi.spyOn(Math, "random").mockReturnValue(0.5);+ vi.spyOn(document, "hidden", "get").mockReturnValue(false);+ });+ afterEach(() => {+ cleanup();+ resetPaneDoneGateForTests();+ resetConnectBudgetForTests();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ it("shares one local read per workspace and drops quiet or unknown verdicts", async () => {+ const fetcher = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ panes: { t1: gate(), t2: null, t3: { ...gate(), verdict: "HOLD" } } }),+ });+ vi.stubGlobal("fetch", fetcher);+ const a = renderHook(() => usePaneDoneGate("w", "t1"));+ const b = renderHook(() => usePaneDoneGate("w", "t2"));+ const c = renderHook(() => usePaneDoneGate("w", "t3"));+ await act(() => vi.advanceTimersByTimeAsync(300));+ expect(fetcher).toHaveBeenCalledTimes(1);+ expect(String(fetcher.mock.calls[0][0])).toBe("/api/agentic-ide/git/done-gate?workspace_id=w");+ expect(a.result.current?.verdict).toBe("WAIT");+ expect(b.result.current).toBeNull();+ expect(c.result.current).toBeNull();++ fetcher.mockResolvedValue({ ok: true, json: async () => ({ panes: { t1: gate({ verdict: "DONE" }) } }) });+ await act(() => vi.advanceTimersByTimeAsync(POLL_MS * 1.5));+ expect(a.result.current?.verdict).toBe("DONE");++ // A failed read keeps the gate's last word.+ fetcher.mockRejectedValue(new Error("offline"));+ await act(() => vi.advanceTimersByTimeAsync(POLL_MS * 1.5));+ expect(a.result.current?.verdict).toBe("DONE");++ a.unmount(); b.unmount(); c.unmount();+ const calls = fetcher.mock.calls.length;+ await act(() => vi.advanceTimersByTimeAsync(POLL_MS * 4));+ expect(fetcher.mock.calls.length).toBe(calls);+ });++ it("asks nothing without a workspace", async () => {+ const fetcher = vi.fn();+ vi.stubGlobal("fetch", fetcher);+ const hook = renderHook(() => usePaneDoneGate(undefined, "t1"));+ await act(() => vi.advanceTimersByTimeAsync(POLL_MS));+ expect(fetcher).not.toHaveBeenCalled();+ expect(hook.result.current).toBeNull();+ });+});diff --git a/dodaios/ui/web/frontend/src/components/agentic/PaneDoneGateBadge.tsx b/dodaios/ui/web/frontend/src/components/agentic/PaneDoneGateBadge.tsxnew file mode 100644index 0000000000..b212d4e911--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentic/PaneDoneGateBadge.tsx@@ -0,0 +1,61 @@+import type { CSSProperties } from "react";+import { fill, useT } from "@/i18n";+import { themeFor, type TerminalAppearance } from "./terminalThemes";+import { usePaneDoneGate, type DoneGateVerdict, type PaneDoneGate } from "./usePaneDoneGate";++const KEYS: Record<DoneGateVerdict, string> = {+ DONE: "done", WAIT: "wait", FIX: "fix", STUCK: "stuck",+};++function checkedAt(at: string): string {+ const stamp = new Date(at);+ return Number.isNaN(stamp.getTime()) ? "" : stamp.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });+}++/**+ * The done gate's last word on this pane's session, as a quiet label beside+ * the pane's GitHub status: WAIT amber, FIX red, STUCK outlined in red, DONE+ * green. NONE and HOLD show nothing. The tooltip carries the reason and the+ * next step the gate gave the agent.+ */+export function DoneGateLabel({ gate, appearance, name }: {+ gate: PaneDoneGate | null;+ appearance: TerminalAppearance;+ name: string;+}) {+ const t = useT();+ if (!gate) return null;+ const theme = themeFor(appearance);+ const key = KEYS[gate.verdict];+ const label = t(`ide_panes.done_gate.label_${key}`);+ const color = gate.verdict === "DONE" ? theme.green : gate.verdict === "WAIT" ? theme.yellow : theme.red;+ const time = checkedAt(gate.at);+ const lines = [+ t(`ide_panes.done_gate.title_${key}`),+ gate.reason,+ gate.next ? fill(t("ide_panes.done_gate.next"), { next: gate.next }) : "",+ gate.pr ? fill(t("ide_panes.done_gate.pull_request"), { number: gate.pr }) : "",+ time ? fill(t("ide_panes.done_gate.checked"), { time }) : "",+ gate.matched === "folder" ? t("ide_panes.done_gate.matched_folder") : "",+ ].filter(Boolean);+ const style: CSSProperties = {+ color,+ borderColor: gate.verdict === "STUCK" ? color : "transparent",+ };+ return <span data-header-control="true" data-testid={`pane-done-gate-${name}`} data-verdict={gate.verdict}+ role="img" aria-label={fill(t("ide_panes.done_gate.aria"), { pane: name, state: label })}+ title={lines.join("\n")}+ className="inline-flex h-4 shrink-0 cursor-default items-center rounded border px-1 text-[10px] font-medium leading-none tracking-wide"+ style={style}>+ {label}+ </span>;+}++export function PaneDoneGateBadge({ workspaceId, name, appearance }: {+ workspaceId?: string;+ name: string;+ appearance: TerminalAppearance;+}) {+ const gate = usePaneDoneGate(workspaceId, name);+ return <DoneGateLabel gate={gate} appearance={appearance} name={name} />;+}diff --git a/dodaios/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx b/dodaios/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsxindex 9312c77410..06fc4bcb39 100644--- a/dodaios/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx+++ b/dodaios/ui/web/frontend/src/components/agentic/WorkspaceTerminalHeader.tsx@@ -4,6 +4,7 @@ import { Check, FileDiff, FolderGit2, FolderInput, GitBranch, Maximize2, Minimizimport { fill, loadLocaleChunk, useT } from "@/i18n";import { AgentMark } from "./AgentMark";import { BranchIcon } from "./branchIcon";+import { PaneDoneGateBadge } from "./PaneDoneGateBadge";import { SessionGitHubBadge } from "./SessionGitHubBadge";import { usePaneTitle } from "@/store/paneRecaps";import { PromptHistoryButton } from "./PromptHistoryButton";@@ -300,6 +301,7 @@ export function WorkspaceTerminalHeader({</span>}</button> : renameForm}<span id={dragHintId} className="sr-only">{t("ide_panes.header.drag_hint")}</span>+ <PaneDoneGateBadge workspaceId={githubStatusEnabled ? workspaceId : undefined} name={name} appearance={appearance} /><SessionGitHubBadge workspaceId={githubStatusEnabled ? workspaceId : undefined} name={name} appearance={appearance} /><div data-header-control="true" className="flex shrink-0 items-center gap-0.5">{onReviewChanges && <button type="button" data-testid={`pane-review-changes-${name}`} aria-label={fill(t("agentic_grid.pane.review_changes"), { pane: name })}diff --git a/dodaios/ui/web/frontend/src/components/agentic/usePaneDoneGate.ts b/dodaios/ui/web/frontend/src/components/agentic/usePaneDoneGate.tsnew file mode 100644index 0000000000..c5e4044abd--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/agentic/usePaneDoneGate.ts@@ -0,0 +1,144 @@+import { useCallback, useSyncExternalStore } from "react";+import { requestConnect, spreadDelay } from "@/lib/connectBudget";++/** The verdicts a pane header shows; NONE and HOLD arrive as null. */+export type DoneGateVerdict = "DONE" | "WAIT" | "FIX" | "STUCK";++/** What `scripts/agent_done_gate.py` last said about a pane's session. */+export interface PaneDoneGate {+ verdict: DoneGateVerdict;+ reason: string;+ next: string;+ pr: number | null;+ branch: string;+ /** ISO time of the check, UTC. */+ at: string;+ /** `folder`: matched by the pane's folder or branch, not its own session id. */+ matched: "session" | "folder";+}++type Panes = Record<string, PaneDoneGate | null>;+type Entry = { panes: Panes; listeners: Set<() => void>; stop: () => void };++/**+ * The gate writes its verdict when an agent tries to stop, so a few seconds'+ * delay is invisible; reading it is a handful of local files, never GitHub.+ */+export const POLL_MS = 15_000;+const VERDICTS: ReadonlySet<string> = new Set(["DONE", "WAIT", "FIX", "STUCK"]);+const EMPTY: Panes = {};+const entries = new Map<string, Entry>();+// A workspace's last answer outlives its listeners, so a pane coming back on+// stage shows its verdict at once and the refresh follows.+const remembered = new Map<string, Panes>();++function clean(data: unknown): Panes {+ if (!data || typeof data !== "object") return {};+ const panes: Panes = {};+ for (const [name, value] of Object.entries(data as Record<string, unknown>)) {+ const item = value as Partial<PaneDoneGate> | null;+ panes[name] = item && typeof item === "object" && VERDICTS.has(String(item.verdict))+ ? {+ verdict: item.verdict as DoneGateVerdict,+ reason: typeof item.reason === "string" ? item.reason : "",+ next: typeof item.next === "string" ? item.next : "",+ pr: typeof item.pr === "number" ? item.pr : null,+ branch: typeof item.branch === "string" ? item.branch : "",+ at: typeof item.at === "string" ? item.at : "",+ matched: item.matched === "folder" ? "folder" : "session",+ }+ : null;+ }+ return panes;+}++function start(workspaceId: string): Entry {+ const entry: Entry = { panes: remembered.get(workspaceId) ?? EMPTY, listeners: new Set(), stop: () => {} };+ let disposed = false;+ let controller: AbortController | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let cancelConnect: (() => void) | undefined;++ const schedule = (delay: number) => {+ clearTimeout(timer);+ cancelConnect?.();+ if (disposed || document.hidden) return;+ cancelConnect = requestConnect(() => { void poll(); }, delay);+ };+ const poll = async () => {+ if (disposed || controller || document.hidden) return;+ controller = new AbortController();+ const timeout = setTimeout(() => controller?.abort(), 15_000);+ try {+ const query = new URLSearchParams({ workspace_id: workspaceId });+ const response = await fetch(`/api/agentic-ide/git/done-gate?${query}`, { signal: controller.signal });+ if (response.ok) {+ const data = await response.json() as { panes?: unknown };+ const panes = clean(data.panes);+ // An unchanged answer keeps its identity, so no header redraws for it.+ if (!disposed && JSON.stringify(panes) !== JSON.stringify(entry.panes)) {+ entry.panes = panes;+ remembered.set(workspaceId, entry.panes);+ entry.listeners.forEach((listener) => listener());+ }+ }+ // A failed read keeps the last answer: the verdict is the gate's+ // last word, which a missed poll does not change.+ } catch {+ // Same: offline or aborted, the last answer stands.+ } finally {+ clearTimeout(timeout);+ controller = undefined;+ if (!disposed) timer = setTimeout(() => schedule(0), spreadDelay(POLL_MS));+ }+ };+ const resume = () => {+ if (document.hidden) {+ clearTimeout(timer);+ cancelConnect?.();+ return;+ }+ if (!controller) schedule(spreadDelay(500));+ };+ document.addEventListener("visibilitychange", resume);+ entry.stop = () => {+ disposed = true;+ clearTimeout(timer);+ cancelConnect?.();+ controller?.abort();+ document.removeEventListener("visibilitychange", resume);+ };+ schedule(spreadDelay(150));+ return entry;+}++/** The done gate's last shown verdict for one pane, or null. One poll per workspace. */+export function usePaneDoneGate(workspaceId?: string, pane?: string): PaneDoneGate | null {+ const subscribe = useCallback((listener: () => void) => {+ if (!workspaceId) return () => {};+ let entry = entries.get(workspaceId);+ if (!entry) {+ entry = start(workspaceId);+ entries.set(workspaceId, entry);+ }+ entry.listeners.add(listener);+ return () => {+ entry.listeners.delete(listener);+ if (!entry.listeners.size) {+ entry.stop();+ entries.delete(workspaceId);+ }+ };+ }, [workspaceId]);+ const snapshot = useCallback(+ () => workspaceId ? entries.get(workspaceId)?.panes ?? remembered.get(workspaceId) ?? EMPTY : EMPTY,+ [workspaceId],+ );+ const panes = useSyncExternalStore(subscribe, snapshot, () => EMPTY);+ return pane ? panes[pane] ?? null : null;+}++/** Forget every remembered answer; tests only. */+export function resetPaneDoneGateForTests() {+ remembered.clear();+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex dc5876c747..b3249a0601 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -9218,6 +9218,21 @@"refreshing": "GitHub-Status wird aktualisiert…","loading": "GitHub-Status wird gelesen…"},+ "done_gate": {+ "label_done": "gelandet",+ "label_wait": "wartet",+ "label_fix": "beheben",+ "label_stuck": "festgefahren",+ "title_done": "Done-Gate: die Arbeit ist gelandet",+ "title_wait": "Done-Gate: wartet, bevor dieser Agent aufhören darf",+ "title_fix": "Done-Gate: etwas muss behoben werden, bevor dieser Agent aufhören darf",+ "title_stuck": "Done-Gate: festgefahren, ein Mensch muss draufschauen",+ "next": "Nächster Schritt: {next}",+ "pull_request": "Pull-Request #{number}",+ "checked": "Geprüft um {time}",+ "matched_folder": "Über den Ordner oder Branch dieses Panes zugeordnet, nicht über seine eigene Sitzung",+ "aria": "{pane}: Done-Gate {state}"+ },"dock": {"swap": "Plätze tauschen","left": "Links platzieren",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 1efddeaefc..8b7b53ba5d 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -9218,6 +9218,21 @@"refreshing": "Refreshing GitHub status…","loading": "Reading the GitHub status…"},+ "done_gate": {+ "label_done": "landed",+ "label_wait": "waiting",+ "label_fix": "fix",+ "label_stuck": "stuck",+ "title_done": "Done gate: the work has landed",+ "title_wait": "Done gate: waiting before this agent may stop",+ "title_fix": "Done gate: something needs fixing before this agent may stop",+ "title_stuck": "Done gate: stuck, a person has to look",+ "next": "Next: {next}",+ "pull_request": "Pull request #{number}",+ "checked": "Checked at {time}",+ "matched_folder": "Matched by this pane's folder or branch, not its own session",+ "aria": "{pane}: done gate {state}"+ },"dock": {"swap": "Swap positions","left": "Place on the left",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex 5cfbdad115..f68d3db563 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -9218,6 +9218,21 @@"refreshing": "Actualizando el estado de GitHub…","loading": "Leyendo el estado de GitHub…"},+ "done_gate": {+ "label_done": "integrado",+ "label_wait": "esperando",+ "label_fix": "corregir",+ "label_stuck": "atascado",+ "title_done": "Done gate: el trabajo ya está integrado",+ "title_wait": "Done gate: esperando antes de que este agente pueda parar",+ "title_fix": "Done gate: hay algo que corregir antes de que este agente pueda parar",+ "title_stuck": "Done gate: atascado, una persona tiene que revisarlo",+ "next": "Siguiente: {next}",+ "pull_request": "Pull request #{number}",+ "checked": "Comprobado a las {time}",+ "matched_folder": "Asociado por la carpeta o la rama de este panel, no por su propia sesión",+ "aria": "{pane}: done gate {state}"+ },"dock": {"swap": "Intercambiar posiciones","left": "Colocar a la izquierda",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex 1f00be9ed7..6d48f92a9b 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -9218,6 +9218,21 @@"refreshing": "A atualizar o estado do GitHub…","loading": "A ler o estado do GitHub…"},+ "done_gate": {+ "label_done": "integrado",+ "label_wait": "aguardando",+ "label_fix": "corrigir",+ "label_stuck": "travado",+ "title_done": "Done gate: o trabalho já foi integrado",+ "title_wait": "Done gate: aguardando antes que este agente possa parar",+ "title_fix": "Done gate: algo precisa ser corrigido antes que este agente possa parar",+ "title_stuck": "Done gate: travado, uma pessoa precisa olhar",+ "next": "Próximo passo: {next}",+ "pull_request": "Pull request #{number}",+ "checked": "Verificado às {time}",+ "matched_folder": "Associado pela pasta ou branch deste painel, não pela própria sessão",+ "aria": "{pane}: done gate {state}"+ },"dock": {"swap": "Trocar posições","left": "Colocar à esquerda",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex ff4f7b3894..742e640f43 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -9218,6 +9218,21 @@"refreshing": "正在刷新 GitHub 状态…","loading": "正在读取 GitHub 状态…"},+ "done_gate": {+ "label_done": "已合入",+ "label_wait": "等待中",+ "label_fix": "需修复",+ "label_stuck": "卡住",+ "title_done": "完成检查:工作已合入",+ "title_wait": "完成检查:等待中,此代理暂不能停止",+ "title_fix": "完成检查:需要先修复问题,此代理才能停止",+ "title_stuck": "完成检查:卡住了,需要人工查看",+ "next": "下一步:{next}",+ "pull_request": "拉取请求 #{number}",+ "checked": "检查于 {time}",+ "matched_folder": "按此窗格的文件夹或分支匹配,而非其自身会话",+ "aria": "{pane}:完成检查 {state}"+ },"dock": {"swap": "交换位置","left": "放在左侧",diff --git a/tests/fakes/fake_done_gate.py b/tests/fakes/fake_done_gate.pynew file mode 100644index 0000000000..e4e3c349a7--- /dev/null+++ b/tests/fakes/fake_done_gate.py@@ -0,0 +1,68 @@+"""Agent done gate state on disk, and a git locator that never runs git.++``FakeRepoLocator`` stands in for ``done_gate_status.locate``: each folder maps+to the git common dir and branch a test chose, and every question is counted.+``write_session`` writes a session file the way ``scripts/agent_done_gate.py``+does, so the reader is tested against the gate's real file shape.+"""++from __future__ import annotations++import json+import os+from dataclasses import dataclass, field+from datetime import UTC, datetime+from pathlib import Path++from dodaios.agentic_ide.done_gate_status import STATE_DIR, RepoInfo, safe_name+++@dataclass+class FakeRepoLocator:+ repos: dict[str, RepoInfo] = field(default_factory=dict)+ asked: list[str] = field(default_factory=list)++ def add(self, folder: str | Path, common_dir: Path | None, branch: str = "") -> None:+ self.repos[os.path.normcase(os.path.abspath(str(folder)))] = RepoInfo(common_dir, branch)++ def __call__(self, folder: str) -> RepoInfo:+ self.asked.append(folder)+ return self.repos.get(os.path.normcase(os.path.abspath(folder)), RepoInfo(None))+++def iso(stamp: float) -> str:+ return datetime.fromtimestamp(stamp, UTC).isoformat(timespec="seconds")+++def write_session(+ common_dir: Path,+ session: str,+ *,+ verdict: str,+ at: float,+ reason: str = "",+ next_step: str = "",+ pr: int | None = None,+ branch: str = "",+ cwd: str | Path = "",+ mtime: float | None = None,+) -> Path:+ """One ``sessions/<session>.json`` with a ``last`` record, as the gate writes it."""+ path = common_dir / STATE_DIR / "sessions" / f"{safe_name(session)}.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ state = {+ "branches": [branch] if branch else [],+ "last": {+ "verdict": verdict,+ "reason": reason,+ "next": next_step,+ "pr": pr,+ "branch": branch,+ "cwd": str(cwd),+ "at": iso(at),+ },+ }+ path.write_text(json.dumps(state, indent=1), encoding="utf-8")+ if mtime is not None:+ os.utime(path, (mtime, mtime))+ return pathdiff --git a/tests/unit/agentic_ide/test_done_gate_status.py b/tests/unit/agentic_ide/test_done_gate_status.pynew file mode 100644index 0000000000..ab2d000063--- /dev/null+++ b/tests/unit/agentic_ide/test_done_gate_status.py@@ -0,0 +1,258 @@+"""The pane header's done-gate verdict, read only from the gate's own files."""++from __future__ import annotations++import subprocess+import time+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from dodaios.agentic_ide import done_gate_status as gate+from dodaios.agentic_ide.agent_sessions import ResumeHandle+from dodaios.agentic_ide.done_gate_status import PaneGateRecord+from dodaios.ui.web import agentic_ide_git_routes as routes+from tests.fakes.fake_done_gate import FakeRepoLocator, iso, write_session++# Real time: the reader skips files by their modification time before parsing them.+NOW = time.time()+++def repo(tmp_path: Path) -> SimpleNamespace:+ common = tmp_path / "main" / ".git"+ common.mkdir(parents=True)+ worktree = tmp_path / "wt"+ worktree.mkdir()+ locator = FakeRepoLocator()+ locator.add(tmp_path / "main", common, "main")+ locator.add(worktree, common, "claude/feature")+ return SimpleNamespace(common=common, main=tmp_path / "main", worktree=worktree, locate=locator)+++def test_a_pane_with_a_known_session_reads_that_sessions_file(repo) -> None:+ write_session(+ repo.common,+ "abc-123",+ verdict="WAIT",+ at=NOW - 60,+ reason="CI is running",+ next_step="Wait for CI.",+ pr=42,+ branch="claude/feature",+ cwd=repo.worktree,+ )+ answer = gate.board(+ [PaneGateRecord("t1", str(repo.worktree), session_id="abc-123")],+ now=NOW,+ find_repo=repo.locate,+ )+ assert answer["t1"] == {+ "verdict": "WAIT",+ "reason": "CI is running",+ "next": "Wait for CI.",+ "pr": 42,+ "branch": "claude/feature",+ "at": iso(NOW - 60),+ "matched": "session",+ }+++def test_session_ids_are_mapped_to_the_gates_file_names(repo) -> None:+ write_session(repo.common, "a/b:c", verdict="FIX", at=NOW)+ assert (repo.common / "agent-done-gate" / "sessions" / "a_b_c.json").exists()+ answer = gate.board(+ [PaneGateRecord("t1", str(repo.main), session_id="a/b:c")], now=NOW, find_repo=repo.locate+ )+ assert answer["t1"]["verdict"] == "FIX"++[email protected]("verdict", ["NONE", "HOLD"])+def test_quiet_verdicts_show_nothing(repo, verdict: str) -> None:+ write_session(repo.common, "s1", verdict=verdict, at=NOW)+ answer = gate.board(+ [PaneGateRecord("t1", str(repo.main), session_id="s1")], now=NOW, find_repo=repo.locate+ )+ assert answer == {"t1": None}+++def test_a_known_session_never_borrows_a_neighbours_record(repo) -> None:+ write_session(+ repo.common, "other", verdict="FIX", at=NOW, cwd=repo.worktree, branch="claude/feature"+ )+ answer = gate.board(+ [PaneGateRecord("t1", str(repo.worktree), session_id="mine")],+ now=NOW,+ find_repo=repo.locate,+ )+ assert answer == {"t1": None}+++def test_without_a_session_the_newest_record_for_the_folder_wins(repo) -> None:+ write_session(repo.common, "old", verdict="FIX", at=NOW - 600, cwd=repo.worktree)+ write_session(repo.common, "new", verdict="DONE", at=NOW - 60, cwd=repo.worktree / ".")+ write_session(repo.common, "elsewhere", verdict="STUCK", at=NOW, cwd=repo.main)+ answer = gate.board([PaneGateRecord("t1", str(repo.worktree))], now=NOW, find_repo=repo.locate)+ assert answer["t1"]["verdict"] == "DONE"+ assert answer["t1"]["matched"] == "folder"+++def test_without_a_session_a_record_for_the_panes_branch_matches(repo) -> None:+ write_session(+ repo.common,+ "s1",+ verdict="STUCK",+ at=NOW - 60,+ cwd=repo.main / "sub",+ branch="claude/feature",+ )+ by_checkout = gate.board(+ [PaneGateRecord("t1", str(repo.worktree))], now=NOW, find_repo=repo.locate+ )+ assert by_checkout["t1"]["verdict"] == "STUCK"+ by_fork_branch = gate.board(+ [PaneGateRecord("t2", str(repo.main), branch="claude/feature")],+ now=NOW,+ find_repo=repo.locate,+ )+ assert by_fork_branch["t2"]["verdict"] == "STUCK"+++def test_folder_matches_older_than_six_hours_are_ignored(repo) -> None:+ write_session(repo.common, "s1", verdict="WAIT", at=NOW - 6 * 3600 - 5, cwd=repo.worktree)+ answer = gate.board([PaneGateRecord("t1", str(repo.worktree))], now=NOW, find_repo=repo.locate)+ assert answer == {"t1": None}+++def test_folder_matches_skip_sessions_another_pane_owns(repo) -> None:+ write_session(repo.common, "owned", verdict="FIX", at=NOW, cwd=repo.main)+ answer = gate.board(+ [+ PaneGateRecord("t1", str(repo.main), session_id="owned"),+ PaneGateRecord("t2", str(repo.main)),+ ],+ now=NOW,+ find_repo=repo.locate,+ )+ assert answer["t1"]["verdict"] == "FIX"+ assert answer["t2"] is None+++def test_a_newer_quiet_verdict_hides_an_older_loud_one(repo) -> None:+ write_session(repo.common, "a", verdict="FIX", at=NOW - 300, cwd=repo.worktree)+ write_session(repo.common, "b", verdict="HOLD", at=NOW - 10, cwd=repo.worktree)+ answer = gate.board([PaneGateRecord("t1", str(repo.worktree))], now=NOW, find_repo=repo.locate)+ assert answer == {"t1": None}+++def test_broken_or_foreign_files_and_folders_outside_git_are_quiet(repo, tmp_path: Path) -> None:+ sessions = repo.common / "agent-done-gate" / "sessions"+ sessions.mkdir(parents=True)+ (sessions / "bad.json").write_text("{not json", encoding="utf-8")+ (sessions / "nolast.json").write_text('{"branches": []}', encoding="utf-8")+ (sessions / "nodate.json").write_text(+ '{"last": {"verdict": "FIX", "at": "yesterday"}}', encoding="utf-8"+ )+ answer = gate.board(+ [+ PaneGateRecord("t1", str(repo.main), session_id="bad"),+ PaneGateRecord("t2", str(repo.main), session_id="nolast"),+ PaneGateRecord("t3", str(repo.main)),+ PaneGateRecord("t4", str(tmp_path / "not-a-repo")),+ ],+ now=NOW,+ find_repo=repo.locate,+ )+ assert answer == {"t1": None, "t2": None, "t3": None, "t4": None}+++def test_an_odd_pull_request_field_is_dropped_and_long_text_is_cut(repo) -> None:+ write_session(repo.common, "s1", verdict="fix", at=NOW, reason="x" * 5000)+ path = repo.common / "agent-done-gate" / "sessions" / "s1.json"+ path.write_text(+ path.read_text(encoding="utf-8").replace('"pr": null', '"pr": true'), encoding="utf-8"+ )+ answer = gate.board(+ [PaneGateRecord("t1", str(repo.main), session_id="s1")], now=NOW, find_repo=repo.locate+ )+ assert answer["t1"]["verdict"] == "FIX"+ assert answer["t1"]["pr"] is None+ assert len(answer["t1"]["reason"]) == gate.MAX_TEXT+++def _git(cwd: Path, *args: str) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)+++def test_locate_reads_the_common_dir_and_branch_of_a_worktree(tmp_path: Path) -> None:+ main = tmp_path / "main"+ main.mkdir()+ _git(main, "init", "-q", "-b", "main")+ _git(+ main,+ "-c",+ "user.name=t",+ "-c",+ "[email protected]",+ "commit",+ "-q",+ "--allow-empty",+ "-m",+ "c",+ )+ _git(main, "worktree", "add", "-q", "-b", "claude/x", str(tmp_path / "wt"))+ gate.forget_repos()+ info = gate.locate(str(tmp_path / "wt"))+ assert info.branch == "claude/x"+ assert info.common_dir is not None and info.common_dir.resolve() == (main / ".git").resolve()+ assert gate.locate(str(tmp_path / "missing")).common_dir is None+ gate.forget_repos()+++def test_the_route_maps_each_local_pane_by_its_session(monkeypatch, repo) -> None:+ write_session(repo.common, "claude-1", verdict="WAIT", at=time.time() - 30, reason="queued")+ write_session(repo.common, "codex-2", verdict="FIX", at=time.time() - 30, cwd=repo.main)++ def pane(+ name: str, folder: str = "", resume: ResumeHandle | None = None, computer_id: str = ""+ ):+ return SimpleNamespace(+ name=name,+ folder=folder,+ branch="",+ resume=resume,+ computer_id=computer_id,+ cwd=lambda workspace, folder=folder: folder or workspace,+ )++ session = SimpleNamespace(+ id="w1",+ folder=str(repo.main),+ terminals=[+ pane("t1", str(repo.worktree), ResumeHandle("claude_session", "claude-1", 0)),+ pane("t2"),+ pane("t3", computer_id="vps"),+ ],+ )+ monkeypatch.setattr(+ routes,+ "get_registry",+ lambda: SimpleNamespace(get=lambda workspace_id: session if workspace_id == "w1" else None),+ )+ monkeypatch.setattr(gate, "locate", repo.locate)+ app = FastAPI()+ app.include_router(routes.router)+ client = TestClient(app)++ body = client.get("/api/agentic-ide/git/done-gate", params={"workspace_id": "w1"}).json()+ assert set(body["panes"]) == {"t1", "t2"}+ assert body["panes"]["t1"]["verdict"] == "WAIT"+ assert body["panes"]["t2"]["verdict"] == "FIX"+ assert body["panes"]["t2"]["matched"] == "folder"+ assert (+ client.get("/api/agentic-ide/git/done-gate", params={"workspace_id": "nope"}).status_code+ == 404+ )