Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(agents): run graph API + React Flow UI (Lane M2) (#956)
Call White59e2714d0af5
diff --git a/core/services/agent_graph.py b/core/services/agent_graph.pynew file mode 100644index 000000000..4d222fbdf--- /dev/null+++ b/core/services/agent_graph.py@@ -0,0 +1,776 @@+"""Read-only assembly of the Agents · 运行图 (run graph) payload.++This service is the single place that turns the persisted agent state into the+graph the Agents → 运行 tab renders. It is intentionally read-only: it opens a+SQLite connection, reads ``agent_sessions``/``agent_runs``/``scopes``/+``run_definitions``, and merges in liveness that the caller passes in from the+controller's running-agents snapshot. It never writes and never touches the+controller directly, so it stays pure w.r.t. its inputs and unit-testable with+fixture rows + a fake ``live_agents`` list.++Wire shape is the frozen contract in+``docs/plans/agents-run-graph-contract.md`` §3. The only addition over that doc+is the per-node ``runs`` array (recent runs for the detail-panel timeline);+it is additive and only the graph frontend consumes it.++Graph semantics (all from existing columns):++- **Node** = an ``agent_sessions`` row. ``status``/``live`` come from the+ running-agents snapshot when the session has a live process, else from the+ session's latest run outcome.+- **Spawn edge** (caller → callee): runs with ``source_kind='agent'`` and+ ``source_actor`` set, aggregated per (caller session, callee session).+- **Callback edge** (callee → report target): runs with ``callback_session_id``+ set; status from ``callback_status``.+- **Trigger edge** (definition → carrying session): runs with+ ``run_type in ('scheduled','watch')`` grouped by ``definition_id``.++Scope is joined LEFT (``scope_id`` is nullable): a NULL scope renders as the+``独立`` (standalone) bucket.+"""++from __future__ import annotations++from datetime import datetime, timedelta, timezone+from typing import Any, Iterable, Mapping, Optional, Sequence++from sqlalchemy import select+from sqlalchemy.engine import Engine++from storage.background import _status_query_values, normalize_run_status+from storage.db import create_sqlite_engine+from storage.models import agent_runs, agent_sessions, run_definitions, scope_settings, scopes++# History window → lookback seconds. ``24h`` is the default (contract §3).+WINDOW_SECONDS: dict[str, int] = {+ "1h": 3600,+ "6h": 21600,+ "24h": 86400,+ "7d": 604800,+}+DEFAULT_WINDOW = "24h"++# Server-side node cap; when exceeded we keep the most recent 300 and set+# ``truncated`` so the client can surface it (contract §3).+NODE_CAP = 300++# Recent runs embedded per node for the detail-panel timeline (contract A1:+# newest first, capped at 10).+RUNS_PER_NODE = 10++# Sort sentinel for runs whose created_at is missing/unparseable (oldest).+_EPOCH = datetime.min.replace(tzinfo=timezone.utc)++# Trigger definition types that produce a trigger chip.+_TRIGGER_RUN_TYPES = {"scheduled", "watch"}++++# ── timestamp helpers ────────────────────────────────────────────────────────+# Stored ``*_at`` strings come in two ISO-8601 flavors depending on the writer+# (``…Z`` second-granularity vs ``.isoformat()`` with ``+00:00`` microseconds).+# Parse either and re-emit the canonical ``…Z`` the contract asks for.++def _parse_iso(value: Optional[str]) -> Optional[datetime]:+ if not value:+ return None+ text = value.strip()+ if not text:+ return None+ if text.endswith("Z"):+ text = text[:-1] + "+00:00"+ try:+ dt = datetime.fromisoformat(text)+ except ValueError:+ return None+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt.astimezone(timezone.utc)+++def _iso_z(value: Any) -> Optional[str]:+ """Normalize a stored timestamp (or datetime) to ``YYYY-MM-DDTHH:MM:SSZ``."""+ if isinstance(value, datetime):+ dt: Optional[datetime] = value if value.tzinfo else value.replace(tzinfo=timezone.utc)+ else:+ dt = _parse_iso(value)+ if dt is None:+ return value if isinstance(value, str) and value else None+ return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++# ── status resolution ────────────────────────────────────────────────────────++def _node_status(live_state: Optional[str], runs: list[dict[str, Any]]) -> tuple[str, bool]:+ """Return ``(status, live)`` for a node.++ Live sessions carry the running-agents state (``active``/``idle``/+ ``orphan``). Otherwise the node reflects its runs: any non-terminal run+ (``queued``/``running`` — including a stale ``running`` with no live process,+ or an older queued/running run left behind a newer finished one on a reused+ or stuck session) surfaces as ``queued`` so the Active view keeps its pending+ work; else the latest run's terminal outcome; else ``idle``.+ """+ if live_state in ("active", "idle", "orphan"):+ return live_state, True+ for run in runs:+ if normalize_run_status(run["status"]) in ("queued", "running"):+ return "queued", False+ if runs:+ return normalize_run_status(runs[0]["status"]), False+ return "idle", False+++def _merge_live_state(states: Iterable[str]) -> str:+ """Collapse a session's per-backend live rows into one state.++ A session can appear once per backend in the snapshot; ``active`` wins over+ ``orphan`` over ``idle`` so the node reflects its most significant activity.+ """+ rank = {"active": 0, "orphan": 1, "idle": 2}+ best: Optional[str] = None+ for state in states:+ if best is None or rank.get(state, 3) < rank.get(best, 3):+ best = state+ return best or "idle"+++# ── liveness index ───────────────────────────────────────────────────────────++def _index_live_agents(live_agents: Sequence[Mapping[str, Any]]) -> dict[str, dict[str, Any]]:+ """Index running-agents rows by ``session_id``.++ Keeps the merged live ``state`` and the ``elapsed_seconds`` of the row whose+ state *won* the merge — the header shows the winning state (e.g. ``active``),+ so its elapsed must come from an ``active`` row, not from an unrelated idle+ row that happened to have a larger elapsed.+ """+ by_session: dict[str, dict[str, Any]] = {}+ grouped: dict[str, list[Mapping[str, Any]]] = {}+ for row in live_agents or ():+ session_id = row.get("session_id")+ if session_id:+ grouped.setdefault(session_id, []).append(row)+ for session_id, rows in grouped.items():+ state = _merge_live_state(str(r.get("state") or "idle") for r in rows)+ winning_elapsed = [+ r.get("elapsed_seconds")+ for r in rows+ if str(r.get("state") or "idle") == state and r.get("elapsed_seconds") is not None+ ]+ by_session[session_id] = {+ "state": state,+ "elapsed_seconds": max(winning_elapsed) if winning_elapsed else None,+ }+ return by_session+++# ── scope helpers ────────────────────────────────────────────────────────────++def _scope_label(display_name: Optional[str], native_id: Optional[str]) -> Optional[str]:+ if display_name and display_name.strip():+ return display_name+ return native_id or None+++def _project_id(platform: Optional[str], scope_type: Optional[str], native_id: Optional[str]) -> Optional[str]:+ # A "project" is an avibe scope of type project; its public id is the+ # scope's native_id (proj_<hex>). IM scopes are not projects.+ if platform == "avibe" and scope_type == "project":+ return native_id+ return None+++# ── trigger schedule label ───────────────────────────────────────────────────++def _schedule_label(row: Mapping[str, Any]) -> Optional[str]:+ if row.get("definition_type") == "scheduled":+ cron = row.get("cron")+ if cron:+ return f"cron {cron}"+ run_at = row.get("run_at")+ if run_at:+ return _iso_z(run_at)+ return None+++# ── main assembly ────────────────────────────────────────────────────────────++def build_graph(+ *,+ live_agents: Optional[Sequence[Mapping[str, Any]]] = None,+ window: str = DEFAULT_WINDOW,+ project: str = "all",+ include_ended: bool = True,+ include_background: bool = True,+ live_unreachable: bool = False,+ now: Optional[datetime] = None,+ node_cap: int = NODE_CAP,+ engine: Optional[Engine] = None,+) -> dict[str, Any]:+ """Assemble the run-graph payload (contract §3 + amendments A1/A2).++ ``live_agents`` is the controller's running-agents snapshot list (each row+ has at least ``session_id`` + ``state``); the route injects it so this stays+ testable. ``live_unreachable`` (A2) is set by the route when the controller+ is down and ``live_agents`` is empty. ``now`` is injectable for tests.+ """+ now = now or datetime.now(timezone.utc)+ if now.tzinfo is None:+ now = now.replace(tzinfo=timezone.utc)+ window = window if window in WINDOW_SECONDS else DEFAULT_WINDOW+ cutoff = now - timedelta(seconds=WINDOW_SECONDS[window])+ cutoff_iso = cutoff.isoformat()++ live_by_session = _index_live_agents(live_agents or ())+ live_ids = set(live_by_session)++ owned_engine = engine is None+ engine = engine or create_sqlite_engine()+ try:+ with engine.connect() as conn:+ # The candidate source differs by view. History (include_ended) uses+ # the window scan. Active (contract A5 = live + queued) uses the live+ # set plus every session with a non-terminal run, independent of the+ # window and of the raw status alias — so a stuck-queued job older+ # than the cutoff, or a controller-down stale ``running`` row, can't+ # disappear from the active view.+ if include_ended:+ candidate_ids = _resolve_candidates(conn, live_ids, cutoff_iso)+ else:+ candidate_ids = set(live_ids) | _active_run_session_ids(conn)+ if not candidate_ids:+ return _empty_payload(now, window, live_unreachable)++ # Bound the expensive run-history load by choosing which candidate+ # SESSIONS to load runs for (cheap — no runs) before ``_load_runs``,+ # after the session-level visibility filters (project, background,+ # archived/disabled) so hidden rows can't consume the cap and starve+ # visible ones. A busy install can have far more candidates than+ # survive the response, and the graph refetches on SSE/poll.+ candidate_rows = _load_sessions(conn, candidate_ids)+ eligible = _prefilter_candidate_rows(+ candidate_rows, project=project,+ include_background=include_background, live_ids=live_ids,+ )+ ranked = sorted(eligible, key=lambda r: _session_sort_key(r, live_ids))+ candidate_truncated = len(ranked) > node_cap+ session_by_id = {r["id"]: r for r in ranked[:node_cap]}+ loaded_ids = set(session_by_id)++ runs_by_session = _load_runs(conn, loaded_ids)+ # Pull in lineage sessions referenced by a retained run — even a+ # spawn/callback older than the window (e.g. a long-lived live+ # session's original delegation) — so the edge and its "who started+ # it / reports to" endpoints survive. Fixed point, but track attempted+ # ids in ``loaded_ids`` (monotonic): a run can point at a session id+ # with no ``agent_sessions`` row (stale source_actor/callback from+ # imported or repaired state) which never lands in ``session_by_id``,+ # so keying the loop off that alone would spin forever.+ while True:+ extra = _lineage_refs(runs_by_session) - loaded_ids+ if not extra:+ break+ loaded_ids |= extra+ runs_by_session.update(_load_runs(conn, extra))+ for row in _load_sessions(conn, extra):+ session_by_id.setdefault(row["id"], row)+ session_rows = list(session_by_id.values())+ edges, trigger_ids = _build_edges(runs_by_session, loaded_ids)+ trigger_nodes = _load_trigger_nodes(conn, trigger_ids)+ finally:+ if owned_engine:+ engine.dispose()++ nodes = _build_nodes(session_rows, runs_by_session, live_by_session)+ nodes = _filter_nodes(nodes, project=project, include_ended=include_ended,+ include_background=include_background)+ nodes, cap_truncated = _cap_nodes(nodes, node_cap)+ truncated = candidate_truncated or cap_truncated++ node_ids = {n["session_id"] for n in nodes}+ edges = _filter_edges(edges, node_ids, {t["definition_id"] for t in trigger_nodes})+ trigger_nodes = _prune_triggers(trigger_nodes, edges)++ return {+ "ok": True,+ "generated_at": _iso_z(now),+ "window": window,+ "live_unreachable": live_unreachable,+ "counts": _counts(nodes),+ "nodes": nodes,+ "trigger_nodes": trigger_nodes,+ "edges": edges,+ "truncated": truncated,+ }+++def _empty_payload(now: datetime, window: str, live_unreachable: bool) -> dict[str, Any]:+ return {+ "ok": True,+ "generated_at": _iso_z(now),+ "window": window,+ "live_unreachable": live_unreachable,+ "counts": _counts([]),+ "nodes": [],+ "trigger_nodes": [],+ "edges": [],+ "truncated": False,+ }+++def _active_run_session_ids(conn) -> set[str]:+ """Sessions with a non-terminal run — the non-live half of the active view+ (contract A5). Uses the run store's own normalized status family+ (``queued``/``running`` → raw ``pending``/``queued``/``processing``/+ ``running``) so aliases and a controller-down stale ``running`` row still+ count, and is NOT window-limited so a stuck-queued job older than the+ history cutoff can't disappear from the active view. Non-terminal runs are+ few (in-flight work drains), so the set stays small."""+ raw_statuses = _status_query_values("queued") + _status_query_values("running")+ stmt = select(agent_runs.c.session_id).where(agent_runs.c.status.in_(raw_statuses)).distinct()+ return {row[0] for row in conn.execute(stmt) if row[0]}+++def _resolve_candidates(conn, live_ids: set[str], cutoff_iso: str) -> set[str]:+ """The set of session ids that become nodes.++ Always the live sessions, plus every session with a run in the window and+ the sessions those runs reference as caller (``source_actor``) or callback+ target — so tree roots, report targets, and (per contract A5) queued work+ render. ``_filter_nodes`` then narrows to the active (non-terminal) or full+ (history) view; this stays broad so a queued-but-not-live session is a+ candidate the active filter can keep.+ """+ candidates: set[str] = set(live_ids)+ # Window match = any recent activity, not just creation: a long run created+ # before the cutoff but finished/failed/canceled inside the window must+ # still surface. ``updated_at`` alone captures all of these — it is set to+ # ``created_at`` on insert and bumped to the transition time (equal to+ # ``completed_at`` on terminal states) on every status change, so it is a+ # superset of the created/completed timestamps. Using the single column lets+ # this frequently-polled scan ride the ``ix_agent_runs_updated`` index+ # instead of a full table scan (the other agent_runs indexes all lead with a+ # non-timestamp column and cannot serve a bare range predicate).+ stmt = select(+ agent_runs.c.session_id,+ agent_runs.c.source_kind,+ agent_runs.c.source_actor,+ agent_runs.c.callback_session_id,+ agent_runs.c.callback_status,+ ).where(agent_runs.c.updated_at >= cutoff_iso)+ for row in conn.execute(stmt).mappings():+ if row["session_id"]:+ candidates.add(row["session_id"])+ if row["source_kind"] == "agent" and row["source_actor"]:+ candidates.add(row["source_actor"])+ # Only a callback target that will draw an edge (A4: non-null status) —+ # a bare return route must not promote an unconnected root node.+ if row["callback_session_id"] and row["callback_status"]:+ candidates.add(row["callback_session_id"])+ return candidates+++def _load_sessions(conn, candidate_ids: set[str]) -> list[dict[str, Any]]:+ cols = [+ agent_sessions.c.id,+ agent_sessions.c.scope_id,+ agent_sessions.c.agent_name,+ agent_sessions.c.agent_backend,+ agent_sessions.c.model,+ agent_sessions.c.reasoning_effort,+ agent_sessions.c.workdir,+ agent_sessions.c.title,+ agent_sessions.c.status,+ agent_sessions.c.visibility,+ agent_sessions.c.created_at,+ agent_sessions.c.updated_at,+ agent_sessions.c.last_active_at,+ scopes.c.display_name.label("scope_display_name"),+ scopes.c.native_id.label("scope_native_id"),+ scopes.c.platform.label("scope_platform"),+ scopes.c.scope_type.label("scope_scope_type"),+ scopes.c.native_type.label("scope_native_type"),+ scope_settings.c.enabled.label("scope_enabled"),+ ]+ stmt = (+ select(*cols)+ .select_from(+ agent_sessions+ .outerjoin(scopes, agent_sessions.c.scope_id == scopes.c.id)+ .outerjoin(scope_settings, agent_sessions.c.scope_id == scope_settings.c.scope_id)+ )+ .where(agent_sessions.c.id.in_(candidate_ids))+ )+ return [dict(row) for row in conn.execute(stmt).mappings()]+++def _load_runs(conn, candidate_ids: set[str]) -> dict[str, list[dict[str, Any]]]:+ """Every run belonging to a candidate session, newest first, grouped by+ session. Full lineage (not window-limited) so aggregates + edges are+ accurate for a session once it is in scope."""+ stmt = (+ select(+ agent_runs.c.id,+ agent_runs.c.session_id,+ agent_runs.c.status,+ agent_runs.c.run_type,+ agent_runs.c.definition_id,+ agent_runs.c.source_kind,+ agent_runs.c.source_actor,+ agent_runs.c.parent_run_id,+ agent_runs.c.callback_session_id,+ agent_runs.c.callback_status,+ agent_runs.c.callback_run_id,+ agent_runs.c.created_at,+ agent_runs.c.started_at,+ agent_runs.c.completed_at,+ )+ .where(agent_runs.c.session_id.in_(candidate_ids))+ .order_by(agent_runs.c.created_at.desc(), agent_runs.c.id.desc())+ )+ grouped: dict[str, list[dict[str, Any]]] = {}+ for row in conn.execute(stmt).mappings():+ data = dict(row)+ grouped.setdefault(data["session_id"], []).append(data)+ # Re-sort newest-first in Python: stored run times mix `...Z` (seconds) and+ # `.isoformat()` (`+00:00`, microseconds), so SQLite's text order_by can rank+ # two same-second runs wrong and leave a stale run at runs[0] — which drives+ # the node status, the recent-runs timeline, and the active-view filter.+ for runs in grouped.values():+ runs.sort(key=lambda r: (_parse_iso(r.get("created_at")) or _EPOCH, r["id"]), reverse=True)+ return grouped+++def _lineage_refs(runs_by_session: dict[str, list[dict[str, Any]]]) -> set[str]:+ """Session ids referenced as a spawn caller or callback target by any run."""+ refs: set[str] = set()+ for runs in runs_by_session.values():+ for run in runs:+ if run.get("source_kind") == "agent" and run.get("source_actor"):+ refs.add(run["source_actor"])+ # Only follow a callback target that will actually draw an edge+ # (A4: callback edges need a non-null status). A run that merely+ # recorded a return route otherwise promotes an unconnected root that+ # consumes cap/count with no report edge.+ if run.get("callback_session_id") and run.get("callback_status"):+ refs.add(run["callback_session_id"])+ return refs+++def _build_edges(+ runs_by_session: dict[str, list[dict[str, Any]]],+ candidate_ids: set[str],+) -> tuple[list[dict[str, Any]], set[str]]:+ """Aggregate spawn / callback / trigger edges from the candidate runs."""+ spawn: dict[tuple[str, str], dict[str, Any]] = {}+ callback: dict[tuple[str, str], dict[str, Any]] = {}+ trigger: dict[tuple[str, str], dict[str, Any]] = {}+ trigger_ids: set[str] = set()++ def _newer(existing: Optional[str], candidate: Optional[str]) -> bool:+ # Compare parsed instants, not raw strings: stored run times mix `...Z`+ # (second precision) and `.isoformat()` (microseconds/`+00:00`), which+ # sort wrong lexicographically within the same second.+ cand = _parse_iso(candidate)+ if cand is None:+ return False+ prev = _parse_iso(existing)+ return prev is None or prev < cand++ # Callback target per run id — an explicit callback-delivery run+ # (source_kind='agent', parent_run_id → the delegated run) reports INTO the+ # delegated run's callback session. Such a report row must NOT be counted as+ # a spawn (it would draw a misleading callee→caller edge and make the caller+ # look "started by" the callee). Detect it: the run's session equals its+ # parent run's callback target.+ callback_target_by_run: dict[str, str] = {}+ for runs in runs_by_session.values():+ for run in runs:+ if run.get("callback_session_id"):+ callback_target_by_run[run["id"]] = run["callback_session_id"]++ for session_id, runs in runs_by_session.items():+ for run in runs:+ created = run.get("created_at")+ parent = run.get("parent_run_id")+ is_callback_delivery = bool(parent) and callback_target_by_run.get(parent) == session_id+ # spawn: caller (source_actor) → this session (excluding callback-+ # delivery reports, which run in the caller's session by design)+ if run.get("source_kind") == "agent" and run.get("source_actor") and not is_callback_delivery:+ key = (run["source_actor"], session_id)+ agg = spawn.setdefault(key, {"run_count": 0, "last_run_id": None, "last_at": None})+ agg["run_count"] += 1+ if agg["last_at"] is None or _newer(agg["last_at"], created):+ agg["last_at"] = created+ agg["last_run_id"] = run.get("id")+ # callback: this session → report target+ # Contract A4: only emit a callback edge once a callback_status is+ # recorded. A run that merely routes a callback (sync-delegated,+ # null status — nothing will be delivered) produces no edge.+ if run.get("callback_session_id") and run.get("callback_status"):+ key = (session_id, run["callback_session_id"])+ agg = callback.setdefault(key, {"status": None, "last_run_id": None, "last_at": None})+ if agg["last_at"] is None or _newer(agg["last_at"], created):+ agg["last_at"] = created+ agg["last_run_id"] = run.get("callback_run_id") or run.get("id")+ agg["status"] = run.get("callback_status")+ # trigger: definition → this session+ if run.get("run_type") in _TRIGGER_RUN_TYPES and run.get("definition_id"):+ definition_id = run["definition_id"]+ trigger_ids.add(definition_id)+ key = (definition_id, session_id)+ agg = trigger.setdefault(key, {"run_count": 0, "last_at": None})+ agg["run_count"] += 1+ if agg["last_at"] is None or _newer(agg["last_at"], created):+ agg["last_at"] = created++ edges: list[dict[str, Any]] = []+ for (src, dst), agg in spawn.items():+ edges.append({+ "kind": "spawn", "from": src, "to": dst,+ "run_count": agg["run_count"],+ "last_run_id": agg["last_run_id"], "last_at": _iso_z(agg["last_at"]),+ })+ for (src, dst), agg in callback.items():+ edges.append({+ "kind": "callback", "from": src, "to": dst,+ "status": agg["status"],+ "last_run_id": agg["last_run_id"], "last_at": _iso_z(agg["last_at"]),+ })+ for (definition_id, dst), agg in trigger.items():+ edges.append({+ "kind": "trigger", "from": f"def:{definition_id}", "to": dst,+ "run_count": agg["run_count"], "last_at": _iso_z(agg["last_at"]),+ })+ return edges, trigger_ids+++def _load_trigger_nodes(conn, trigger_ids: set[str]) -> list[dict[str, Any]]:+ if not trigger_ids:+ return []+ stmt = select(+ run_definitions.c.id,+ run_definitions.c.definition_type,+ run_definitions.c.name,+ run_definitions.c.cron,+ run_definitions.c.run_at,+ run_definitions.c.enabled,+ ).where(run_definitions.c.id.in_(trigger_ids))+ nodes: list[dict[str, Any]] = []+ for row in conn.execute(stmt).mappings():+ data = dict(row)+ nodes.append({+ "definition_id": data["id"],+ "definition_type": data["definition_type"],+ "name": data.get("name"),+ "schedule_label": _schedule_label(data),+ "enabled": bool(data.get("enabled")),+ })+ return nodes+++def _build_nodes(+ session_rows: list[dict[str, Any]],+ runs_by_session: dict[str, list[dict[str, Any]]],+ live_by_session: dict[str, dict[str, Any]],+) -> list[dict[str, Any]]:+ nodes: list[dict[str, Any]] = []+ for row in session_rows:+ session_id = row["id"]+ runs = runs_by_session.get(session_id, [])+ live = live_by_session.get(session_id)+ status, is_live = _node_status(live["state"] if live else None, runs)++ # Hide user-deleted chats (archived session) and sessions under an+ # archived project (avibe project scope with scope_settings.enabled=0) —+ # other session lists hide both, so they must not reappear as non-live+ # history nodes. A live row still shows so its runtime can be ended.+ is_archived_project = row.get("scope_scope_type") == "project" and row.get("scope_enabled") == 0+ if (row.get("status") == "archived" or is_archived_project) and not is_live:+ continue++ run_count_total = len(runs)+ run_count_running = sum(1 for r in runs if normalize_run_status(r["status"]) == "running")+ recent = [+ {+ "id": r["id"],+ "status": normalize_run_status(r["status"]),+ "run_type": r.get("run_type"),+ "created_at": _iso_z(r.get("created_at")),+ "started_at": _iso_z(r.get("started_at")),+ "completed_at": _iso_z(r.get("completed_at")),+ }+ for r in runs[:RUNS_PER_NODE]+ ]++ # A private ``vibe agent run`` session hangs on the legacy+ # ``private_agent_run`` pseudo-scope (placeholder platform, no delivery).+ # Mirror the running-agents enrichment: render it as an internal run+ # (no platform/scope label/project) and not openable — never label it as+ # an IM channel session or offer a chat link. M1 re-parents sessions off+ # this pseudo-scope, so this branch is a no-op post-migration.+ is_private_run = row.get("scope_native_type") == "private_agent_run"+ platform = None if is_private_run else row.get("scope_platform")+ scope_label = None if is_private_run else _scope_label(+ row.get("scope_display_name"), row.get("scope_native_id")+ )+ project_id = None if is_private_run else _project_id(+ row.get("scope_platform"), row.get("scope_scope_type"), row.get("scope_native_id")+ )++ node: dict[str, Any] = {+ "session_id": session_id,+ "title": row.get("title"),+ "agent_name": row.get("agent_name"),+ "agent_backend": row.get("agent_backend"),+ "model": row.get("model"),+ "reasoning_effort": row.get("reasoning_effort"),+ "status": status,+ "live": is_live,+ "scope_id": row.get("scope_id"),+ "project_id": project_id,+ "scope_label": scope_label,+ "platform": platform,+ "workdir": row.get("workdir"),+ # Every persisted session is openable in chat EXCEPT the internal+ # private-agent-run pseudo-scope sessions (M1 retires those).+ "openable_in_chat": not is_private_run,+ "created_at": _iso_z(row.get("created_at")),+ "last_active_at": _iso_z(row.get("last_active_at")),+ "elapsed_seconds": (live or {}).get("elapsed_seconds") if is_live else None,+ "run_counts": {"total": run_count_total, "running": run_count_running},+ "runs": recent,+ # Legacy rows backfill to foreground (contract §1).+ "visibility": row.get("visibility") or "foreground",+ }+ nodes.append(node)+ return nodes+++def _filter_nodes(+ nodes: list[dict[str, Any]],+ *,+ project: str,+ include_ended: bool,+ include_background: bool,+) -> list[dict[str, Any]]:+ result = nodes+ if not include_ended:+ # Active view (contract A5) = non-terminal work: live sessions plus+ # queued (accepted-but-not-started) runs. Only terminal non-live nodes+ # (succeeded/failed/canceled) are dropped.+ result = [n for n in result if n["live"] or n["status"] == "queued"]+ if project and project != "all":+ if project == "standalone":+ result = [n for n in result if not n["scope_id"]]+ else:+ target = f"avibe::project::{project}"+ result = [n for n in result if n["scope_id"] == target]+ if not include_background:+ result = [n for n in result if n.get("visibility") != "background"]+ return result+++def _node_sort_key(node: dict[str, Any]) -> tuple[int, str]:+ # Live first, then most-recently-active; deterministic tie-break on id.+ activity = node.get("last_active_at") or node.get("created_at") or ""+ return (0 if node["live"] else 1, _invert_iso(activity) + node["session_id"])+++def _invert_iso(value: str) -> str:+ # Sort ISO timestamps descending under an ascending sort by inverting bytes.+ return "".join(chr(0x10FFFF - ord(c)) if ord(c) < 0x10FFFF else c for c in value)+++def _session_sort_key(row: dict[str, Any], live_ids: set[str]) -> tuple[int, str]:+ # Mirror _node_sort_key on a raw session row so candidates can be ranked (and+ # capped) before their run histories are loaded.+ activity = row.get("last_active_at") or row.get("created_at") or ""+ sid = row["id"]+ return (0 if sid in live_ids else 1, _invert_iso(activity) + sid)+++def _prefilter_candidate_rows(+ rows: list[dict[str, Any]],+ *,+ project: str,+ include_background: bool,+ live_ids: set[str],+) -> list[dict[str, Any]]:+ # The session-level visibility filters that _build_nodes / _filter_nodes also+ # apply, hoisted ahead of the run-load cap so hidden rows (archived chats,+ # sessions under a disabled project, backgrounds, other projects) can't+ # consume the cap and starve visible sessions. include_ended is deliberately+ # excluded — it needs the run-derived status, so it stays a post-load filter.+ def _hidden(r: dict[str, Any]) -> bool:+ # Mirror _build_nodes: archived chat or archived (disabled) project,+ # unless the session is live.+ if r["id"] in live_ids:+ return False+ archived_project = r.get("scope_scope_type") == "project" and r.get("scope_enabled") == 0+ return r.get("status") == "archived" or archived_project++ result = [r for r in rows if not _hidden(r)]+ if not include_background:+ result = [r for r in result if (r.get("visibility") or "foreground") != "background"]+ if project and project != "all":+ if project == "standalone":+ result = [r for r in result if not r.get("scope_id")]+ else:+ target = f"avibe::project::{project}"+ result = [r for r in result if r.get("scope_id") == target]+ return list(result)+++def _cap_nodes(nodes: list[dict[str, Any]], node_cap: int) -> tuple[list[dict[str, Any]], bool]:+ ordered = sorted(nodes, key=_node_sort_key)+ if len(ordered) > node_cap:+ return ordered[:node_cap], True+ return ordered, False+++def _filter_edges(+ edges: list[dict[str, Any]],+ node_ids: set[str],+ trigger_ids: set[str],+) -> list[dict[str, Any]]:+ kept: list[dict[str, Any]] = []+ for edge in edges:+ if edge["kind"] == "trigger":+ definition_id = edge["from"][len("def:"):]+ if definition_id in trigger_ids and edge["to"] in node_ids:+ kept.append(edge)+ else:+ if edge["from"] in node_ids and edge["to"] in node_ids:+ kept.append(edge)+ return kept+++def _prune_triggers(+ trigger_nodes: list[dict[str, Any]],+ edges: list[dict[str, Any]],+) -> list[dict[str, Any]]:+ referenced = {e["from"][len("def:"):] for e in edges if e["kind"] == "trigger"}+ return [t for t in trigger_nodes if t["definition_id"] in referenced]+++def _counts(nodes: list[dict[str, Any]]) -> dict[str, int]:+ counts = {+ "active": 0, "idle": 0, "orphan": 0, "queued": 0,+ "succeeded": 0, "failed": 0, "canceled": 0,+ "live": 0, "ended": 0, "background": 0, "foreground": 0, "total": len(nodes),+ }+ for node in nodes:+ status = node["status"]+ if status in counts:+ counts[status] += 1+ if node["live"]:+ counts["live"] += 1+ else:+ counts["ended"] += 1+ if node.get("visibility") == "background":+ counts["background"] += 1+ else:+ counts["foreground"] += 1+ return countsdiff --git a/docs/plans/agents-run-graph-contract.md b/docs/plans/agents-run-graph-contract.mdindex 3ab47ce10..bdc7277ee 100644--- a/docs/plans/agents-run-graph-contract.md+++ b/docs/plans/agents-run-graph-contract.md@@ -4,6 +4,48 @@ Frozen interface contract for the two parallel lanes of`agents-run-graph-and-session-visibility.md`. **Deviations requireorchestrator sign-off first** — do not negotiate field changes lane-to-lane.+Amendments (orchestrator-approved):++- **A1 (2026-07-23, PR #956)**: graph node gains `runs[]` (recent runs for+ the detail-panel timeline, newest first, capped at 10 — avoids an N+1+ fetch). Additive.+- **A2 (2026-07-23, PR #956)**: top-level `live_unreachable: boolean` —+ `true` when the controller/running-agents service is unreachable and the+ payload degrades to DB-only (client shows a degraded banner, mirroring the+ running list's `unreachable` pattern). Additive.+- **A3 (2026-07-23, PR #956 review r1)**: session-less orphan processes are+ **NOT synthesized as graph nodes** (nodes stay = `agent_sessions` rows;+ orphans have no session, no lineage, no chat). Capability restored via a+ client-side **orphan strip** above the canvas (and a section in the mobile+ list): rows sourced from the existing `GET /api/running-agents` payload+ (`session_id == null`), each with backend/pid/elapsed and the existing+ Kill flow (`POST /api/running-agents/end`, 2-step confirm). Graph payload+ unchanged. Session-anchored orphans keep rendering as `status:orphan`+ nodes.+- **A4 (2026-07-23, PR #956 review r1)**: callback edges are emitted **only+ when `callback_status` is non-null** (a recorded outcome/progress state).+ Sync-delegated runs that merely record a callback route (null status,+ nothing will be delivered) do not produce an edge. Supersedes the earlier+ "null → pending" mapping.+- **A5 (2026-07-23, PR #956 review r1)**: `include_ended=0` means+ **non-terminal sessions** — live (`active|idle|orphan`) **plus `queued`**+ — not "live only". Queued work is upcoming and must be visible in the+ active view; the counts object keeps `queued` populated accordingly.+- **A6 (2026-07-23, cross-lane)**: visibility reconcile **event contract**:+ backend (M1, PR #957) emits the existing `session.activity` SSE event with+ the session's current `visibility` on every PATCH/CLI visibility or scope+ change. Frontend consumption is **M2's (PR #956)**: the Inbox context+ removes a session card when an event carries `visibility='background'`+ (and refetches/re-adds on `'foreground'`); absent `visibility` field ⇒+ no-op (defensive pre-M1). M1 does not touch `ui/**` for this; the gap is+ recorded in #957's inventory as assigned to #956.+- **A7 (2026-07-23, PR #956 review)**: graph endpoint path renamed+ `/api/agents/graph` → **`/api/agents-graph`**. Rationale: `/api/agents/…`+ is the agent-resource namespace and agent names are user-creatable slugs —+ an agent literally named `graph` would shadow the route. Endpoint and its+ sole consumer live in the same PR; no migration cost. Reserving the word+ `graph` in the agent-name domain was rejected.+## 1. Visibility enum (M1 owns, M2 consumes)- `agent_sessions.visibility` ∈ `"foreground" | "background"`.@@ -31,13 +73,15 @@ CLI equivalent: `vibe session update [--visibility foreground|background]## 3. Graph endpoint (M2 owns; shape frozen for both)-`GET /api/agents/graph?window=24h&project=<project_id|all|standalone>&include_ended=1&include_background=1`+`GET /api/agents-graph?window=24h&project=<project_id|all|standalone>&include_ended=1&include_background=1`+(path per amendment A7)- `window`: `1h|6h|24h|7d` (default `24h`); bounds history lookback(`agent_runs.created_at >= now - window`, plus all currently-livesessions regardless of window).-- `include_ended=0` ⇒ live sessions only. `include_background=0` ⇒- foreground nodes only (edges to hidden nodes are dropped with them).+- `include_ended=0` ⇒ non-terminal sessions: live (`active|idle|orphan`)+ plus `queued` (amendment A5). `include_background=0` ⇒ foreground nodes+ only (edges to hidden nodes are dropped with them).Response:@@ -46,6 +90,7 @@ Response:"ok": true,"generated_at": "2026-07-23T02:00:00Z","window": "24h",+ "live_unreachable": false,"counts": { "active": 3, "idle": 1, "queued": 1, "ended": 4,"background": 5, "foreground": 3 },"nodes": [@@ -68,7 +113,11 @@ Response:"created_at": "2026-07-21T10:10:22Z","last_active_at": "2026-07-23T01:58:00Z","elapsed_seconds": 4320,- "run_counts": { "total": 6, "running": 1 }+ "run_counts": { "total": 6, "running": 1 },+ "runs": [+ { "id": "run_9f2kc1", "status": "running", "run_type": "agent_run",+ "created_at": "...", "started_at": "...", "completed_at": null }+ ]}],"trigger_nodes": [@@ -104,9 +153,10 @@ Semantics:`def:<definition_id>`.- `spawn` edges: aggregated per (caller session → callee session) from runswith `source_kind='agent'` and `source_actor` set.-- `callback` edges: emitted whenever `callback_session_id` is set (even when- it equals the spawn caller — the client decides rendering). `status` ∈- `pending|sent|failed|skipped` (from `callback_status`; null → `pending`).+- `callback` edges: emitted when `callback_session_id` is set **and**+ `callback_status` is non-null (amendment A4 — sync runs that only record a+ return route draw nothing). Target may equal the spawn caller; the client+ decides rendering. `status` ∈ `pending|sent|failed|skipped`.- `trigger` edges: runs with `run_type in ('scheduled','watch')` grouped by`definition_id`.- Cap: server may truncate to the most recent 300 nodes; setdiff --git a/storage/alembic/versions/20260723_0033_agent_runs_updated_index.py b/storage/alembic/versions/20260723_0033_agent_runs_updated_index.pynew file mode 100644index 000000000..1c601c400--- /dev/null+++ b/storage/alembic/versions/20260723_0033_agent_runs_updated_index.py@@ -0,0 +1,51 @@+"""index agent_runs.updated_at for the run-graph window scan++Revision ID: 20260723_0033+Revises: 20260723_0032+Create Date: 2026-07-23+"""++from __future__ import annotations++from alembic import op++revision = "20260723_0033"+down_revision = "20260723_0032"+branch_labels = None+depends_on = None+++def _tables(bind) -> set[str]:+ return {+ str(row[0])+ for row in bind.exec_driver_sql(+ "select name from sqlite_master where type = 'table'"+ )+ }+++def _indexes(bind, table: str) -> set[str]:+ return {+ str(row[1])+ for row in bind.exec_driver_sql(f'pragma index_list("{table}")').fetchall()+ }+++def upgrade() -> None:+ bind = op.get_bind()+ if "agent_runs" not in _tables(bind):+ return+ # The run-graph candidate scan filters agent_runs by a bare+ # ``updated_at >= cutoff`` range every poll/SSE refresh; without a+ # leading-timestamp index it scans the whole table (the other agent_runs+ # indexes all lead with a non-timestamp column).+ if "ix_agent_runs_updated" not in _indexes(bind, "agent_runs"):+ op.create_index("ix_agent_runs_updated", "agent_runs", ["updated_at"])+++def downgrade() -> None:+ bind = op.get_bind()+ if "agent_runs" not in _tables(bind):+ return+ if "ix_agent_runs_updated" in _indexes(bind, "agent_runs"):+ op.drop_index("ix_agent_runs_updated", table_name="agent_runs")diff --git a/storage/migrations.py b/storage/migrations.pyindex 3f3481c0c..5ab3cca9e 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -619,6 +619,7 @@ def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:conn.execute('create index if not exists ix_agent_runs_session_created on agent_runs (session_id, created_at)')conn.execute('create index if not exists ix_agent_runs_agent_created on agent_runs (agent_name, created_at)')conn.execute('create index if not exists ix_agent_runs_callback_status on agent_runs (callback_status, completed_at)')+ conn.execute('create index if not exists ix_agent_runs_updated on agent_runs (updated_at)')def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:diff --git a/storage/models.py b/storage/models.pyindex 2e855fc4a..eb0ab0062 100644--- a/storage/models.py+++ b/storage/models.py@@ -252,6 +252,9 @@ agent_runs = Table(Index("ix_agent_runs_session_created", "session_id", "created_at"),Index("ix_agent_runs_agent_created", "agent_name", "created_at"),Index("ix_agent_runs_callback_status", "callback_status", "completed_at"),+ # Leading-timestamp index for the run-graph window scan: updated_at bumps on+ # every state change, so it is the single column that scan filters on.+ Index("ix_agent_runs_updated", "updated_at"),)# Backwards-compatible Python aliases for legacy callers. The physical tablediff --git a/tests/test_agent_graph_service.py b/tests/test_agent_graph_service.pynew file mode 100644index 000000000..2ca1056fe--- /dev/null+++ b/tests/test_agent_graph_service.py@@ -0,0 +1,789 @@+"""Unit tests for ``core.services.agent_graph`` (the run-graph assembly).++Seeds a real SQLite state DB with a spawn chain, a callback, task/watch+triggers, a standalone session, an ended session, and an out-of-window+session, then asserts the frozen contract §3 payload+(``docs/plans/agents-run-graph-contract.md``): node status/liveness, scope vs+标准 standalone bucketing, spawn/callback/trigger edge aggregation, window+filter, project filter, live-only mode, node cap + truncation, and+visibility emission + background filtering.+"""++from __future__ import annotations++import sys+from datetime import datetime, timedelta, timezone+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.services import agent_graph+from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state+from storage.models import agent_runs, agent_sessions, run_definitions, scope_settings, scopes++NOW = datetime(2026, 7, 23, 2, 0, 0, tzinfo=timezone.utc)+PROJECT_ID = "proj_x"+PROJECT_SCOPE = f"avibe::project::{PROJECT_ID}"+++def _z(dt: datetime) -> str:+ """Session-style timestamp: ``…Z`` second granularity."""+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _run_iso(dt: datetime) -> str:+ """Run-style timestamp: ``.isoformat()`` with ``+00:00`` (mixed-format DB)."""+ return dt.isoformat()+++def isolated_state(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ yield tmp_path+++def _insert_scope(conn) -> None:+ conn.execute(+ scopes.insert().values(+ id=PROJECT_SCOPE,+ platform="avibe",+ scope_type="project",+ native_id=PROJECT_ID,+ parent_scope_id=None,+ display_name="vibe-remote",+ native_type="project",+ is_private=0,+ supports_threads=1,+ metadata_json="{}",+ first_seen_at=_z(NOW - timedelta(days=10)),+ last_seen_at=_z(NOW),+ updated_at=_z(NOW),+ )+ )+++def _insert_session(conn, session_id, *, scope_id, backend="claude", title=None,+ created=None, last_active=None, status="active",+ visibility="foreground") -> None:+ created = created or (NOW - timedelta(hours=2))+ conn.execute(+ agent_sessions.insert().values(+ id=session_id,+ scope_id=scope_id,+ agent_id=None,+ agent_name=backend,+ agent_backend=backend,+ agent_variant="default",+ model="claude-fable-5" if backend == "claude" else "gpt-5.3-codex",+ reasoning_effort="high",+ session_anchor=session_id,+ workdir=f"/tmp/{session_id}",+ native_session_id=session_id,+ title=title,+ status=status,+ agent_status="idle",+ visibility=visibility,+ metadata_json="{}",+ created_at=_z(created),+ updated_at=_z(last_active or created),+ last_active_at=_z(last_active or created),+ )+ )+++def _insert_run(conn, run_id, *, session_id, status="succeeded", run_type="agent",+ created=None, source_kind=None, source_actor=None, definition_id=None,+ callback_session_id=None, callback_status=None, started=None, completed=None,+ parent_run_id=None) -> None:+ created = created or (NOW - timedelta(hours=1))+ conn.execute(+ agent_runs.insert().values(+ id=run_id,+ definition_id=definition_id,+ run_type=run_type,+ status=status,+ source_kind=source_kind,+ source_actor=source_actor,+ parent_run_id=parent_run_id,+ agent_name=None,+ agent_id=None,+ agent_backend=None,+ model=None,+ reasoning_effort=None,+ session_policy=None,+ session_id=session_id,+ legacy_session_key=None,+ post_to=None,+ deliver_key=None,+ prompt=None,+ message=None,+ message_payload_json=None,+ result_text=None,+ result_payload_json=None,+ message_ids_json=None,+ callback_session_id=callback_session_id,+ callback_status=callback_status,+ callback_error=None,+ callback_run_id=None,+ callback_completed_at=None,+ cancel_requested=0,+ cancel_requested_at=None,+ pid=None,+ exit_code=None,+ error=None,+ stdout=None,+ stderr=None,+ created_at=_run_iso(created),+ started_at=_run_iso(started or created),+ completed_at=_run_iso(completed) if completed else None,+ # Mirror production: updated_at is bumped to the latest transition+ # time (start, then completion), never left at creation time.+ updated_at=_run_iso(completed or started or created),+ metadata_json="{}",+ )+ )+++def _insert_definition(conn, definition_id, *, definition_type="scheduled",+ name=None, cron=None, run_at=None, enabled=1) -> None:+ conn.execute(+ run_definitions.insert().values(+ id=definition_id,+ definition_type=definition_type,+ name=name,+ agent_name=None,+ session_policy=None,+ session_id=None,+ legacy_session_key=None,+ prompt=None,+ message=None,+ message_payload_json=None,+ schedule_type="cron" if cron else ("at" if run_at else None),+ cron=cron,+ run_at=run_at,+ timezone="UTC",+ command_json=None,+ shell_command=None,+ prefix=None,+ cwd=None,+ mode=None,+ timeout_seconds=None,+ lifetime_timeout_seconds=None,+ retry_exit_codes_json=None,+ retry_delay_seconds=None,+ post_to=None,+ deliver_key=None,+ enabled=enabled,+ deleted_at=None,+ created_at=_run_iso(NOW - timedelta(days=1)),+ updated_at=_run_iso(NOW - timedelta(days=1)),+ last_started_at=None,+ last_finished_at=None,+ last_event_at=None,+ last_run_at=None,+ last_error=None,+ last_exit_code=None,+ last_run_id=None,+ metadata_json="{}",+ )+ )+++def seeded(isolated_state):+ """A representative graph:++ - ses_root (project, live active) spawns ses_child_a (live idle, 2 runs)+ and ses_child_b (ended, succeeded).+ - ses_child_a reports back to ses_root (callback pending).+ - ses_standalone (scope NULL, ended failed) — a root of its own.+ - ses_triggered (project, ended) fired by scheduled task def_daily (2 runs).+ - ses_old (project) has a run 3 days ago — outside the 24h window.+ """+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _insert_scope(conn)+ _insert_session(conn, "ses_root", scope_id=PROJECT_SCOPE, backend="claude", title="Root PM")+ _insert_session(conn, "ses_child_a", scope_id=PROJECT_SCOPE, backend="codex", title="Backend lane")+ _insert_session(conn, "ses_child_b", scope_id=PROJECT_SCOPE, backend="claude", title="Frontend lane")+ _insert_session(conn, "ses_standalone", scope_id=None, backend="codex", title="Standalone")+ _insert_session(conn, "ses_triggered", scope_id=PROJECT_SCOPE, backend="claude", title="Daily draft")+ _insert_session(conn, "ses_queued", scope_id=PROJECT_SCOPE, backend="claude", title="Queued lane")+ _insert_session(conn, "ses_old", scope_id=PROJECT_SCOPE, backend="claude", title="Old",+ created=NOW - timedelta(days=3), last_active=NOW - timedelta(days=3))++ _insert_definition(conn, "def_daily", name="Daily draft", cron="17 10 * * *")++ # spawn ses_root → ses_child_a (2 runs); the latest also callbacks to root+ _insert_run(conn, "run_a1", session_id="ses_child_a", source_kind="agent",+ source_actor="ses_root", created=NOW - timedelta(minutes=40))+ _insert_run(conn, "run_a2", session_id="ses_child_a", source_kind="agent",+ source_actor="ses_root", callback_session_id="ses_root",+ callback_status="pending", created=NOW - timedelta(minutes=20))+ # spawn ses_root → ses_child_b (1 run); it also *routes* a callback to root+ # but with NULL callback_status (sync-delegated) — A4 ⇒ no callback edge.+ _insert_run(conn, "run_b1", session_id="ses_child_b", source_kind="agent",+ source_actor="ses_root", status="succeeded", callback_session_id="ses_root",+ callback_status=None, created=NOW - timedelta(minutes=30),+ completed=NOW - timedelta(minutes=18))+ # queued (accepted-but-not-started) non-live run — A5 ⇒ shows in Active.+ _insert_run(conn, "run_q1", session_id="ses_queued", status="queued",+ created=NOW - timedelta(minutes=5))+ # standalone root, its own failed run+ _insert_run(conn, "run_s1", session_id="ses_standalone", status="failed",+ created=NOW - timedelta(minutes=50))+ # scheduled trigger def_daily → ses_triggered (2 runs)+ _insert_run(conn, "run_t1", session_id="ses_triggered", run_type="scheduled",+ definition_id="def_daily", created=NOW - timedelta(hours=6))+ _insert_run(conn, "run_t2", session_id="ses_triggered", run_type="scheduled",+ definition_id="def_daily", created=NOW - timedelta(hours=2))+ # out-of-window run+ _insert_run(conn, "run_old", session_id="ses_old", created=NOW - timedelta(days=3))+ return engine+++LIVE = [+ {"session_id": "ses_root", "state": "active", "elapsed_seconds": 1560.0, "backend": "claude"},+ {"session_id": "ses_child_a", "state": "idle", "elapsed_seconds": 12.0, "backend": "codex"},+]+++def _nodes_by_id(payload):+ return {n["session_id"]: n for n in payload["nodes"]}+++def _edge(payload, kind, src, dst):+ for e in payload["edges"]:+ if e["kind"] == kind and e["from"] == src and e["to"] == dst:+ return e+ return None+++# ── happy-path assembly ──────────────────────────────────────────────────────+++def test_history_payload_shape(seeded):+ payload = agent_graph.build_graph(live_agents=LIVE, window="24h", now=NOW, engine=seeded)+ assert payload["ok"] is True+ assert payload["window"] == "24h"+ assert payload["generated_at"].endswith("Z")+ assert payload["truncated"] is False++ nodes = _nodes_by_id(payload)+ # ses_old is outside the 24h window and not live → excluded.+ assert set(nodes) == {+ "ses_root", "ses_child_a", "ses_child_b", "ses_standalone", "ses_triggered", "ses_queued",+ }+++def test_live_and_ended_status(seeded):+ nodes = _nodes_by_id(agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded))+ assert nodes["ses_root"]["live"] is True+ assert nodes["ses_root"]["status"] == "active"+ assert nodes["ses_root"]["elapsed_seconds"] == 1560.0+ assert nodes["ses_child_a"]["live"] is True+ assert nodes["ses_child_a"]["status"] == "idle"+ # ended nodes take the latest run outcome and are not live+ assert nodes["ses_child_b"]["live"] is False+ assert nodes["ses_child_b"]["status"] == "succeeded"+ assert nodes["ses_standalone"]["status"] == "failed"+ assert nodes["ses_child_b"]["elapsed_seconds"] is None+++def test_scope_vs_standalone(seeded):+ nodes = _nodes_by_id(agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded))+ assert nodes["ses_triggered"]["project_id"] == PROJECT_ID+ assert nodes["ses_triggered"]["scope_label"] == "vibe-remote"+ assert nodes["ses_triggered"]["platform"] == "avibe"+ # standalone: NULL scope ⇒ every scope field null (独立 bucket)+ assert nodes["ses_standalone"]["scope_id"] is None+ assert nodes["ses_standalone"]["project_id"] is None+ assert nodes["ses_standalone"]["scope_label"] is None+ assert nodes["ses_standalone"]["platform"] is None+++def test_every_node_openable_in_chat(seeded):+ nodes = _nodes_by_id(agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded))+ assert all(n["openable_in_chat"] for n in nodes.values())+++def test_private_agent_run_scope_is_internal(isolated_state):+ # A private ``vibe agent run`` session on the legacy private_agent_run+ # pseudo-scope must render as an internal run: no platform/scope label/+ # project, and not openable in chat (mirrors running-agents enrichment).+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ conn.execute(+ scopes.insert().values(+ id="slack::private::pv1", platform="slack", scope_type="private",+ native_id="pv1", parent_scope_id=None, display_name="internal-run",+ native_type="private_agent_run", is_private=1, supports_threads=0,+ metadata_json="{}", first_seen_at=_z(NOW), last_seen_at=_z(NOW), updated_at=_z(NOW),+ )+ )+ _insert_session(conn, "ses_priv", scope_id="slack::private::pv1", backend="codex",+ title="Internal run")+ _insert_run(conn, "run_p1", session_id="ses_priv", status="succeeded",+ created=NOW - timedelta(minutes=10))+ node = _nodes_by_id(agent_graph.build_graph(live_agents=[], now=NOW, engine=engine))["ses_priv"]+ assert node["platform"] is None+ assert node["scope_label"] is None+ assert node["project_id"] is None+ assert node["openable_in_chat"] is False+ finally:+ engine.dispose()+++def test_window_includes_recently_completed_run(isolated_state):+ # A run created before the 24h cutoff but completed inside it must keep its+ # session in the window (recent activity, not just creation time).+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ _insert_session(conn, "ses_lr", scope_id=None, backend="claude", title="Long run")+ _insert_run(conn, "run_lr", session_id="ses_lr", status="succeeded",+ created=NOW - timedelta(days=3), completed=NOW - timedelta(minutes=10))+ nodes = _nodes_by_id(agent_graph.build_graph(live_agents=[], now=NOW, engine=engine, window="24h"))+ assert "ses_lr" in nodes+ finally:+ engine.dispose()+++def test_callback_delivery_is_not_a_spawn(isolated_state):+ # A delegated run spawns callee and routes a callback to caller; the callee's+ # explicit callback-delivery run reports INTO the caller's session with+ # parent_run_id = the delegated run. That report must NOT create a backwards+ # spawn edge callee→caller (only the real spawn caller→callee + the callback).+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ _insert_session(conn, "ses_caller", scope_id=None, backend="claude", title="Caller")+ _insert_session(conn, "ses_callee", scope_id=None, backend="codex", title="Callee")+ _insert_run(conn, "run_deleg", session_id="ses_callee", source_kind="agent",+ source_actor="ses_caller", callback_session_id="ses_caller",+ callback_status="sent", created=NOW - timedelta(minutes=30))+ _insert_run(conn, "run_report", session_id="ses_caller", source_kind="agent",+ source_actor="ses_callee", parent_run_id="run_deleg",+ created=NOW - timedelta(minutes=10))+ payload = agent_graph.build_graph(live_agents=[], now=NOW, engine=engine)+ assert _edge(payload, "spawn", "ses_caller", "ses_callee") is not None+ assert _edge(payload, "spawn", "ses_callee", "ses_caller") is None+ assert _edge(payload, "callback", "ses_callee", "ses_caller") is not None+ finally:+ engine.dispose()+++def test_live_node_lineage_survives_old_window(isolated_state):+ # A live session spawned by a run OLDER than the window: the caller has no+ # in-window run, but its lineage must still be loaded so the spawn edge and+ # the caller node survive (not a human-started root).+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ _insert_session(conn, "ses_caller", scope_id=None, backend="claude", title="Caller")+ _insert_session(conn, "ses_livekid", scope_id=None, backend="codex", title="Live kid")+ _insert_run(conn, "run_oldspawn", session_id="ses_livekid", source_kind="agent",+ source_actor="ses_caller", created=NOW - timedelta(days=3))+ live = [{"session_id": "ses_livekid", "state": "active", "elapsed_seconds": 5.0}]+ payload = agent_graph.build_graph(live_agents=live, now=NOW, engine=engine, window="24h")+ nodes = _nodes_by_id(payload)+ assert "ses_livekid" in nodes and nodes["ses_livekid"]["live"] is True+ assert "ses_caller" in nodes # pulled in as lineage despite the old run+ assert _edge(payload, "spawn", "ses_caller", "ses_livekid") is not None+ finally:+ engine.dispose()+++def test_lineage_expands_to_fixed_point(isolated_state):+ # A→B→C where A and B's spawn runs are older than the window and only C is+ # live: fixed-point expansion must pull in BOTH B (1 hop) and A (2 hops).+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ for sid in ("ses_a", "ses_b", "ses_c"):+ _insert_session(conn, sid, scope_id=None, backend="claude", title=sid)+ _insert_run(conn, "run_b", session_id="ses_b", source_kind="agent",+ source_actor="ses_a", created=NOW - timedelta(days=3))+ _insert_run(conn, "run_c", session_id="ses_c", source_kind="agent",+ source_actor="ses_b", created=NOW - timedelta(days=3))+ live = [{"session_id": "ses_c", "state": "active", "elapsed_seconds": 5.0}]+ payload = agent_graph.build_graph(live_agents=live, now=NOW, engine=engine, window="24h")+ nodes = _nodes_by_id(payload)+ assert {"ses_a", "ses_b", "ses_c"} <= set(nodes)+ assert _edge(payload, "spawn", "ses_a", "ses_b") is not None+ assert _edge(payload, "spawn", "ses_b", "ses_c") is not None+ finally:+ engine.dispose()+++def test_archived_project_sessions_hidden(isolated_state):+ # A session under an archived project (avibe project scope with+ # scope_settings.enabled=0) is hidden like an archived session.+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ conn.execute(+ scopes.insert().values(+ id="avibe::project::proj_arch", platform="avibe", scope_type="project",+ native_id="proj_arch", parent_scope_id=None, display_name="Archived proj",+ native_type="project", is_private=0, supports_threads=1, metadata_json="{}",+ first_seen_at=_z(NOW), last_seen_at=_z(NOW), updated_at=_z(NOW),+ )+ )+ conn.execute(+ scope_settings.insert().values(+ scope_id="avibe::project::proj_arch", enabled=0, role=None,+ workdir="/tmp/arch", agent_name=None, agent_backend=None, agent_variant=None,+ model=None, reasoning_effort=None, require_mention=None, settings_version=1,+ settings_json="{}", created_at=_z(NOW), updated_at=_z(NOW),+ )+ )+ _insert_session(conn, "ses_ap", scope_id="avibe::project::proj_arch", backend="claude",+ title="Under archived project")+ _insert_run(conn, "run_ap", session_id="ses_ap", status="succeeded",+ created=NOW - timedelta(minutes=10))+ nodes = _nodes_by_id(agent_graph.build_graph(live_agents=[], now=NOW, engine=engine))+ assert "ses_ap" not in nodes+ finally:+ engine.dispose()+++def test_archived_non_live_session_excluded(isolated_state):+ # An archived (user-deleted) chat with a recent run must not reappear as a+ # history node.+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ _insert_session(conn, "ses_arch", scope_id=None, backend="claude", title="Archived",+ status="archived")+ _insert_run(conn, "run_arch", session_id="ses_arch", status="canceled",+ created=NOW - timedelta(minutes=10))+ nodes = _nodes_by_id(agent_graph.build_graph(live_agents=[], now=NOW, engine=engine))+ assert "ses_arch" not in nodes+ finally:+ engine.dispose()+++def test_spawn_edges_aggregate(seeded):+ payload = agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded)+ spawn_a = _edge(payload, "spawn", "ses_root", "ses_child_a")+ assert spawn_a is not None and spawn_a["run_count"] == 2+ assert spawn_a["last_run_id"] == "run_a2" # newest of the pair+ spawn_b = _edge(payload, "spawn", "ses_root", "ses_child_b")+ assert spawn_b is not None and spawn_b["run_count"] == 1+++def test_callback_edge(seeded):+ payload = agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded)+ cb = _edge(payload, "callback", "ses_child_a", "ses_root")+ assert cb is not None+ assert cb["status"] == "pending"+++def test_a4_no_callback_edge_without_status(seeded):+ # run_b1 routes a callback to ses_root but with NULL callback_status+ # (sync-delegated); A4 ⇒ no edge emitted.+ payload = agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded)+ assert _edge(payload, "callback", "ses_child_b", "ses_root") is None+++def test_trigger_edge_and_node(seeded):+ payload = agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded)+ tr = _edge(payload, "trigger", "def:def_daily", "ses_triggered")+ assert tr is not None and tr["run_count"] == 2+ triggers = {t["definition_id"]: t for t in payload["trigger_nodes"]}+ assert "def_daily" in triggers+ assert triggers["def_daily"]["definition_type"] == "scheduled"+ assert triggers["def_daily"]["schedule_label"] == "cron 17 10 * * *"+ assert triggers["def_daily"]["enabled"] is True+++def test_node_runs_timeline(seeded):+ nodes = _nodes_by_id(agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded))+ child_a = nodes["ses_child_a"]+ assert child_a["run_counts"]["total"] == 2+ # A1 run-row shape: newest first, id + status + run_type + created/started/+ # completed (Z-normalized), capped at 10.+ assert [r["id"] for r in child_a["runs"]] == ["run_a2", "run_a1"]+ assert len(child_a["runs"]) <= agent_graph.RUNS_PER_NODE == 10+ row = child_a["runs"][0]+ assert set(row) == {"id", "status", "run_type", "created_at", "started_at", "completed_at"}+ assert row["created_at"].endswith("Z") and row["started_at"].endswith("Z")+++def test_live_unreachable_flag(seeded):+ # A2: always present, default False; the route flips it True when the+ # controller is down.+ default = agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded)+ assert default["live_unreachable"] is False+ degraded = agent_graph.build_graph(live_agents=[], now=NOW, engine=seeded, live_unreachable=True)+ assert degraded["live_unreachable"] is True+++def test_counts(seeded):+ counts = agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded)["counts"]+ assert counts["live"] == 2+ assert counts["active"] == 1+ assert counts["idle"] == 1+ assert counts["queued"] == 1+ assert counts["ended"] == 4+ assert counts["total"] == 6+ # seeded sessions default to foreground (no explicit visibility set)+ assert counts["foreground"] == 6+ assert counts["background"] == 0+++# ── filters ──────────────────────────────────────────────────────────────────+++def test_active_mode_keeps_live_and_queued(seeded):+ # A5: Active view = non-terminal (live + queued). Live ses_root/ses_child_a+ # AND the queued ses_queued stay; terminal non-live nodes drop.+ payload = agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded, include_ended=False)+ nodes = _nodes_by_id(payload)+ assert set(nodes) == {"ses_root", "ses_child_a", "ses_queued"}+ assert nodes["ses_queued"]["status"] == "queued"+ # edges to dropped (terminal) nodes are gone; the live-pair callback stays+ assert _edge(payload, "callback", "ses_child_a", "ses_root") is not None+ assert _edge(payload, "spawn", "ses_root", "ses_child_b") is None+ assert _edge(payload, "trigger", "def:def_daily", "ses_triggered") is None+ assert payload["trigger_nodes"] == []+++def test_project_filter_standalone(seeded):+ nodes = _nodes_by_id(+ agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded, project="standalone")+ )+ assert set(nodes) == {"ses_standalone"}+++def test_project_filter_concrete(seeded):+ nodes = _nodes_by_id(+ agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded, project=PROJECT_ID)+ )+ assert "ses_standalone" not in nodes+ assert "ses_root" in nodes+++def test_window_widening_includes_old(seeded):+ nodes24 = _nodes_by_id(agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded, window="24h"))+ assert "ses_old" not in nodes24+ nodes7d = _nodes_by_id(agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded, window="7d"))+ assert "ses_old" in nodes7d+++def test_no_live_agents_degrades_to_db_only(seeded):+ # Controller unreachable ⇒ no liveness; every node is non-live/ended.+ payload = agent_graph.build_graph(live_agents=[], now=NOW, engine=seeded)+ assert all(n["live"] is False for n in payload["nodes"])+ assert payload["counts"]["live"] == 0+++def test_node_cap_truncates(seeded):+ payload = agent_graph.build_graph(live_agents=LIVE, now=NOW, engine=seeded, node_cap=2)+ assert payload["truncated"] is True+ assert len(payload["nodes"]) == 2+ # live sessions are the most significant → survive the cap+ assert {n["session_id"] for n in payload["nodes"]} == {"ses_root", "ses_child_a"}+++def test_cap_applies_project_filter_before_capping(isolated_state):+ # With more candidates than the cap, a project-filtered view must still+ # return that project's session even when it is older than sessions in other+ # scopes — the pre-run candidate cap applies the project/background filter+ # first, so a busy install can't crowd the selected project out of the cap+ # (and its runs are the only ones loaded).+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _insert_scope(conn)+ _insert_session(conn, "ses_proj", scope_id=PROJECT_SCOPE, title="Proj",+ last_active=NOW - timedelta(hours=3))+ _insert_run(conn, "run_proj", session_id="ses_proj", created=NOW - timedelta(hours=3))+ # Two newer standalone sessions that would win a global recency cap.+ for idx in range(2):+ sid = f"ses_free{idx}"+ _insert_session(conn, sid, scope_id=None, title=f"Free{idx}",+ last_active=NOW - timedelta(minutes=idx + 1))+ _insert_run(conn, f"run_free{idx}", session_id=sid,+ created=NOW - timedelta(minutes=idx + 1))++ payload = agent_graph.build_graph(+ live_agents=[], now=NOW, engine=engine, node_cap=1, project=PROJECT_ID+ )+ assert [n["session_id"] for n in payload["nodes"]] == ["ses_proj"]+++def test_active_view_keeps_queued_past_recency_cap(isolated_state):+ # A queued session with old last_active must still appear in the active view+ # even when newer *ended* sessions would fill a small cap — the active view+ # loads live/queued candidates directly, not a recency slice of raw sessions.+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _insert_session(conn, "ses_q", scope_id=None, title="Queued",+ last_active=NOW - timedelta(hours=5))+ _insert_run(conn, "run_q", session_id="ses_q", status="queued",+ created=NOW - timedelta(hours=5))+ for idx in range(2):+ sid = f"ses_done{idx}"+ _insert_session(conn, sid, scope_id=None, title=f"Done{idx}",+ last_active=NOW - timedelta(minutes=idx + 1))+ _insert_run(conn, f"run_done{idx}", session_id=sid, status="succeeded",+ created=NOW - timedelta(minutes=idx + 1))++ payload = agent_graph.build_graph(+ live_agents=[], now=NOW, engine=engine, node_cap=1, include_ended=False+ )+ assert [n["session_id"] for n in payload["nodes"]] == ["ses_q"]+++def test_missing_lineage_reference_terminates(isolated_state):+ # A retained run pointing at a session id with no agent_sessions row (a stale+ # source_actor/callback from imported or repaired state) must not spin the+ # lineage fixed-point loop forever: it terminates and returns a graph without+ # a node for the missing session.+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _insert_session(conn, "ses_live", scope_id=None, title="Live")+ _insert_run(conn, "run_live", session_id="ses_live", source_kind="agent",+ source_actor="ses_ghost")++ payload = agent_graph.build_graph(+ live_agents=[{"session_id": "ses_live", "state": "active"}], now=NOW, engine=engine+ )+ ids = {n["session_id"] for n in payload["nodes"]}+ assert "ses_live" in ids+ assert "ses_ghost" not in ids+++def test_active_view_captures_nonterminal_past_window_and_aliases(isolated_state):+ # Active view (A5) surfaces any session with a non-terminal run regardless of+ # the history window or the raw status alias: a stuck queued job older than+ # the cutoff and a controller-down `running` row both count, with live_agents+ # empty (controller unreachable).+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _insert_session(conn, "ses_oldq", scope_id=None, title="Old queued",+ last_active=NOW - timedelta(days=3))+ _insert_run(conn, "run_oldq", session_id="ses_oldq", status="queued",+ created=NOW - timedelta(days=3))+ _insert_session(conn, "ses_run", scope_id=None, title="Running",+ last_active=NOW - timedelta(minutes=5))+ _insert_run(conn, "run_run", session_id="ses_run", status="running",+ created=NOW - timedelta(minutes=5))++ payload = agent_graph.build_graph(+ live_agents=[], now=NOW, engine=engine, include_ended=False, window="1h"+ )+ # running (no live process) normalizes to queued; the 3-day-old queued job is+ # kept even though it is far outside the 1h window.+ assert {n["session_id"]: n["status"] for n in payload["nodes"]} == {+ "ses_oldq": "queued",+ "ses_run": "queued",+ }+++def test_null_status_callback_target_not_promoted(isolated_state):+ # A run that records a callback route but no callback_status (A4: no edge)+ # must not promote the (otherwise inactive) target into an unconnected node.+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _insert_session(conn, "ses_caller", scope_id=None, title="Caller")+ _insert_session(conn, "ses_target", scope_id=None, title="Target")+ _insert_run(conn, "run_c", session_id="ses_caller",+ callback_session_id="ses_target", callback_status=None)++ payload = agent_graph.build_graph(+ live_agents=[{"session_id": "ses_caller", "state": "active"}], now=NOW, engine=engine+ )+ assert {n["session_id"] for n in payload["nodes"]} == {"ses_caller"}+ assert not any(e["kind"] == "callback" for e in payload["edges"])+++def test_archived_sessions_excluded_before_cap(isolated_state):+ # Archived sessions must be dropped before the node cap so a burst of recent+ # archived chats can't consume the cap and starve an older visible session.+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ for idx in range(2):+ sid = f"ses_arch{idx}"+ _insert_session(conn, sid, scope_id=None, title=f"Arch{idx}",+ status="archived", last_active=NOW - timedelta(minutes=idx + 1))+ _insert_run(conn, f"run_arch{idx}", session_id=sid,+ created=NOW - timedelta(minutes=idx + 1))+ _insert_session(conn, "ses_vis", scope_id=None, title="Visible",+ last_active=NOW - timedelta(hours=2))+ _insert_run(conn, "run_vis", session_id="ses_vis", created=NOW - timedelta(hours=2))++ payload = agent_graph.build_graph(live_agents=[], now=NOW, engine=engine, node_cap=1)+ assert [n["session_id"] for n in payload["nodes"]] == ["ses_vis"]+++def test_visibility_emitted_and_filtered(isolated_state):+ # M1's ``agent_sessions.visibility`` is now a hard column: every node+ # carries it (legacy rows backfill to foreground), a background session is+ # reflected in the counts, and ``include_background=0`` drops it.+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ _insert_session(conn, "ses_fg", scope_id=None, title="Foreground")+ _insert_session(conn, "ses_bg", scope_id=None, title="Background",+ visibility="background")+ # A window run makes each session a graph candidate (bare sessions with+ # no run and no liveness are not surfaced).+ _insert_run(conn, "run_fg", session_id="ses_fg")+ _insert_run(conn, "run_bg", session_id="ses_bg")++ full = agent_graph.build_graph(live_agents=[], now=NOW, engine=engine)+ by_id = _nodes_by_id(full)+ assert by_id["ses_fg"]["visibility"] == "foreground"+ assert by_id["ses_bg"]["visibility"] == "background"+ assert full["counts"]["foreground"] == 1+ assert full["counts"]["background"] == 1++ hidden = agent_graph.build_graph(+ live_agents=[], now=NOW, engine=engine, include_background=False+ )+ assert set(_nodes_by_id(hidden)) == {"ses_fg"}+++# ── pure helpers ─────────────────────────────────────────────────────────────+++def test_iso_z_normalizes_both_formats():+ assert agent_graph._iso_z("2026-07-23T02:00:00Z") == "2026-07-23T02:00:00Z"+ assert agent_graph._iso_z("2026-07-23T02:00:00.500000+00:00") == "2026-07-23T02:00:00Z"+ assert agent_graph._iso_z(None) is None+++def test_node_status_resolution():+ assert agent_graph._node_status("active", []) == ("active", True)+ assert agent_graph._node_status(None, [{"status": "completed"}]) == ("succeeded", False)+ # a stale running row with no live process is surfaced as queued+ assert agent_graph._node_status(None, [{"status": "running"}]) == ("queued", False)+ assert agent_graph._node_status(None, []) == ("idle", False)+ # any non-terminal run keeps the node active, even behind a newer finished+ # run on a reused/stuck session (runs are newest-first)+ assert agent_graph._node_status(+ None, [{"status": "succeeded"}, {"status": "queued"}]+ ) == ("queued", False)+++def test_merge_live_state_prefers_active():+ assert agent_graph._merge_live_state(["idle", "active", "orphan"]) == "active"+ assert agent_graph._merge_live_state(["idle", "orphan"]) == "orphan"+ assert agent_graph._merge_live_state([]) == "idle"+++def test_liveness_elapsed_from_winning_state_row():+ # Two backend rows for one session: the idle row has a larger elapsed, but+ # the node shows the ACTIVE state, so it must use the active row's elapsed.+ indexed = agent_graph._index_live_agents([+ {"session_id": "s", "state": "idle", "elapsed_seconds": 9999.0},+ {"session_id": "s", "state": "active", "elapsed_seconds": 42.0},+ ])+ assert indexed["s"]["state"] == "active"+ assert indexed["s"]["elapsed_seconds"] == 42.0diff --git a/tests/test_agents_graph_route.py b/tests/test_agents_graph_route.pynew file mode 100644index 000000000..3d664e638--- /dev/null+++ b/tests/test_agents_graph_route.py@@ -0,0 +1,125 @@+"""Route tests for ``GET /api/agents-graph``.++Locks three things the service unit tests can't: (1) the endpoint lives at+``/api/agents-graph`` (contract A7), OUTSIDE ``/api/agents/<name>``, so it+neither shadows nor is shadowed by an agent named ``graph``; (2) query params+flow through; (3) when the controller is unreachable the route still returns a+DB-only graph flagged ``live_unreachable`` instead of erroring.+"""++from __future__ import annotations++import json+from datetime import datetime, timedelta, timezone++import pytest++from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state+from storage.models import agent_runs, agent_sessions+from storage.settings_service import upsert_scope+from vibe import internal_client+from vibe.ui_server import app+++def _seed(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ # The route computes its 24h cutoff from the real wall clock (it does not+ # accept an injected ``now``), so anchor the fixture to now — a fixed+ # calendar date would fall out of the default window once the suite runs+ # more than 24h later.+ now = datetime.now(timezone.utc)+ now_z = now.strftime("%Y-%m-%dT%H:%M:%SZ")+ recent_iso = (now - timedelta(minutes=30)).isoformat()+ engine = create_sqlite_engine()+ try:+ with engine.begin() as conn:+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project",+ native_id="proj_route", now=now_z)+ for sid in ("ses_live", "ses_ended"):+ conn.execute(+ agent_sessions.insert().values(+ id=sid, scope_id=scope_id, agent_backend="claude", agent_variant="default",+ session_anchor=sid, native_session_id=sid, title=sid.upper(),+ status="active", agent_status="idle", metadata_json="{}",+ created_at=now_z, updated_at=now_z, last_active_at=now_z,+ )+ )+ conn.execute(+ agent_runs.insert().values(+ id="run_e1", run_type="agent", status="succeeded", session_id="ses_ended",+ cancel_requested=0, created_at=recent_iso,+ started_at=recent_iso, updated_at=recent_iso,+ metadata_json="{}",+ )+ )+ finally:+ engine.dispose()+++def _mock_live(monkeypatch, agents):+ async def fake_list(**_kwargs):+ return {"status_code": 200, "body": {"agents": agents}}++ monkeypatch.setattr(internal_client, "list_running_agents", fake_list)+++def _get(path):+ resp = app.test_client().get(path)+ return resp.status_code, json.loads(resp.content)+++def test_graph_route_resolves_and_merges_liveness(monkeypatch, tmp_path):+ _seed(monkeypatch, tmp_path)+ _mock_live(monkeypatch, [{"session_id": "ses_live", "state": "active", "elapsed_seconds": 9.0}])++ status, body = _get("/api/agents-graph?window=24h")+ assert status == 200+ # Resolved to the graph handler (not vibe_agent_get(name="graph")).+ assert body["ok"] is True+ assert {"nodes", "edges", "trigger_nodes", "counts", "generated_at"} <= set(body)+ nodes = {n["session_id"]: n for n in body["nodes"]}+ assert nodes["ses_live"]["live"] is True and nodes["ses_live"]["status"] == "active"+ assert nodes["ses_ended"]["live"] is False and nodes["ses_ended"]["status"] == "succeeded"+++def test_include_ended_flag(monkeypatch, tmp_path):+ _seed(monkeypatch, tmp_path)+ _mock_live(monkeypatch, [{"session_id": "ses_live", "state": "active"}])++ _, body = _get("/api/agents-graph?include_ended=0")+ assert {n["session_id"] for n in body["nodes"]} == {"ses_live"}+++def test_controller_unreachable_degrades(monkeypatch, tmp_path):+ _seed(monkeypatch, tmp_path)++ async def fake_raise(**_kwargs):+ raise internal_client.InternalServerUnavailable("down")++ monkeypatch.setattr(internal_client, "list_running_agents", fake_raise)++ status, body = _get("/api/agents-graph")+ assert status == 200+ assert body["ok"] is True+ assert body.get("live_unreachable") is True+ # DB-only ⇒ nothing is live, but history still renders.+ assert all(n["live"] is False for n in body["nodes"])+ assert body["counts"]["live"] == 0+++def test_graph_endpoint_outside_agent_namespace(monkeypatch, tmp_path):+ """A7: the graph endpoint is /api/agents-graph, OUTSIDE /api/agents/<name>,+ so it neither shadows nor is shadowed by an agent literally named 'graph'."""+ _seed(monkeypatch, tmp_path)+ _mock_live(monkeypatch, [])++ _, graph_body = _get("/api/agents-graph")+ assert "nodes" in graph_body # the run-graph handler++ # /api/agents/graph now falls through to the agent-detail handler for the+ # agent named "graph" (no "nodes"), proving an agent named "graph" stays+ # reachable/editable and is not captured by the graph route.+ _, detail_body = _get("/api/agents/graph")+ assert "nodes" not in detail_bodydiff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex 07cda2358..a80178758 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -662,6 +662,32 @@ def test_inbox_and_unread_queries_exclude_background_sessions(isolated_state):assert hidden is None+def test_list_inbox_sessions_only_session_returns_row_past_window(isolated_state):+ """``only_session`` fetches one specific foreground session regardless of how+ many other sessions are more recently active — the path the Inbox foreground+ reconcile (contract A6) uses to re-add a restored session that sorts past the+ paged window."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_titled_session(conn, scope_id, "ses_old", "Old")+ _insert_msg(conn, scope_id, "ses_old", "agent", "older", "2026-05-30T09:00:00Z", read=True)+ # Two newer sessions that fill a small window ahead of ses_old.+ for idx, ts in enumerate(("2026-05-30T10:00:00Z", "2026-05-30T11:00:00Z")):+ sid = f"ses_new{idx}"+ _seed_titled_session(conn, scope_id, sid, f"New{idx}")+ _insert_msg(conn, scope_id, sid, "agent", "newer", ts, read=True)++ with engine.connect() as conn:+ windowed = messages_service.list_inbox_sessions(conn, platform="avibe", limit=1)+ targeted = messages_service.list_inbox_sessions(+ conn, platform="avibe", only_session="ses_old", limit=1+ )++ assert "ses_old" not in [row["session_id"] for row in windowed["sessions"]]+ assert [row["session_id"] for row in targeted["sessions"]] == ["ses_old"]++def test_list_inbox_sessions_includes_notify_only_failed_turn(isolated_state):"""A turn that fails before producing any ``result`` persists only a terminal``notify``; that failed conversation must still surface in the inbox (with thediff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 520bf62eb..c76d63e74 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -19,7 +19,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260723_0032"+HEAD_REVISION = "20260723_0033"def _index_sql(conn: sqlite3.Connection, name: str) -> str:diff --git a/ui/package-lock.json b/ui/package-lock.jsonindex 685113150..1707e1cde 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -8,6 +8,7 @@"name": "ui","version": "0.0.0","dependencies": {+ "@dagrejs/dagre": "^1.1.8","@hpke/core": "^1.9.0","@hpke/dhkem-x25519": "^1.8.0","@lexical/react": "^0.45.0",@@ -25,6 +26,7 @@"@xterm/addon-search": "^0.16.0","@xterm/addon-web-links": "^0.12.0","@xterm/xterm": "^6.0.0",+ "@xyflow/react": "^12.11.2","agentation": "^3.0.2","chart.js": "^4.4.0","class-variance-authority": "^0.7.1",@@ -342,6 +344,24 @@"node": ">=6.9.0"}},+ "node_modules/@dagrejs/dagre": {+ "version": "1.1.8",+ "resolved": "https://registry.npmjs.org/@dagrejs/dagre/-/dagre-1.1.8.tgz",+ "integrity": "sha512-5SEDlndt4W/LaVzPYJW+bSmSEZc9EzTf8rJ20WCKvjS5EAZAN0b+x0Yww7VMT4R3Wootkg+X9bUfUxazYw6Blw==",+ "license": "MIT",+ "dependencies": {+ "@dagrejs/graphlib": "2.2.4"+ }+ },+ "node_modules/@dagrejs/graphlib": {+ "version": "2.2.4",+ "resolved": "https://registry.npmjs.org/@dagrejs/graphlib/-/graphlib-2.2.4.tgz",+ "integrity": "sha512-mepCf/e9+SKYy1d02/UkvSy6+6MoyXhVxP8lLDfA7BPE1X1d4dR0sZznmbM8/XVJ1GPM+Svnx7Xj6ZweByWUkw==",+ "license": "MIT",+ "engines": {+ "node": ">17.0.0"+ }+ },"node_modules/@emnapi/core": {"version": "1.11.1","resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",@@ -2486,6 +2506,55 @@"assertion-error": "^2.0.1"}},+ "node_modules/@types/d3-color": {+ "version": "3.1.3",+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",+ "license": "MIT"+ },+ "node_modules/@types/d3-drag": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",+ "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-interpolate": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-color": "*"+ }+ },+ "node_modules/@types/d3-selection": {+ "version": "3.0.11",+ "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",+ "integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",+ "license": "MIT"+ },+ "node_modules/@types/d3-transition": {+ "version": "3.0.9",+ "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",+ "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-selection": "*"+ }+ },+ "node_modules/@types/d3-zoom": {+ "version": "3.0.8",+ "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",+ "integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-interpolate": "*",+ "@types/d3-selection": "*"+ }+ },"node_modules/@types/debug": {"version": "4.1.13","resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz",@@ -3057,6 +3126,48 @@"addons/*"]},+ "node_modules/@xyflow/react": {+ "version": "12.11.2",+ "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.11.2.tgz",+ "integrity": "sha512-eLAlDWJfWnQEhJwGMjlWdAXO9eYllKpliUmPQlAmOLxz6mExXuzMVDUKLMquixgkrtmMFFtug3jGKmYYld12cA==",+ "license": "MIT",+ "dependencies": {+ "@xyflow/system": "0.0.79",+ "classcat": "^5.0.3",+ "zustand": "^4.4.0"+ },+ "peerDependencies": {+ "@types/react": ">=17",+ "@types/react-dom": ">=17",+ "react": ">=17",+ "react-dom": ">=17"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "@types/react-dom": {+ "optional": true+ }+ }+ },+ "node_modules/@xyflow/system": {+ "version": "0.0.79",+ "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.79.tgz",+ "integrity": "sha512-czLyOh91NF0hIzbNzwi8I6GlqG23BHh2435OddfI6uiaLH3xdrdygO93gqgH1Bv9mhy8XPFQJOBn1FTq4LvEWA==",+ "license": "MIT",+ "dependencies": {+ "@types/d3-drag": "^3.0.7",+ "@types/d3-interpolate": "^3.0.4",+ "@types/d3-selection": "^3.0.10",+ "@types/d3-transition": "^3.0.8",+ "@types/d3-zoom": "^3.0.8",+ "d3-drag": "^3.0.0",+ "d3-interpolate": "^3.0.1",+ "d3-selection": "^3.0.0",+ "d3-zoom": "^3.0.0"+ }+ },"node_modules/acorn": {"version": "8.15.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",@@ -3404,6 +3515,12 @@"url": "https://polar.sh/cva"}},+ "node_modules/classcat": {+ "version": "5.0.5",+ "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",+ "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",+ "license": "MIT"+ },"node_modules/clsx": {"version": "2.1.1","resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",@@ -3513,6 +3630,112 @@"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==","license": "MIT"},+ "node_modules/d3-color": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-dispatch": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",+ "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-drag": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",+ "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-selection": "3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-ease": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",+ "license": "BSD-3-Clause",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-interpolate": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-selection": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",+ "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",+ "license": "ISC",+ "peer": true,+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-timer": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",+ "license": "ISC",+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/d3-transition": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",+ "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",+ "license": "ISC",+ "dependencies": {+ "d3-color": "1 - 3",+ "d3-dispatch": "1 - 3",+ "d3-ease": "1 - 3",+ "d3-interpolate": "1 - 3",+ "d3-timer": "1 - 3"+ },+ "engines": {+ "node": ">=12"+ },+ "peerDependencies": {+ "d3-selection": "2 - 3"+ }+ },+ "node_modules/d3-zoom": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",+ "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",+ "license": "ISC",+ "dependencies": {+ "d3-dispatch": "1 - 3",+ "d3-drag": "2 - 3",+ "d3-interpolate": "1 - 3",+ "d3-selection": "2 - 3",+ "d3-transition": "2 - 3"+ },+ "engines": {+ "node": ">=12"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -7642,6 +7865,34 @@"zod": "^3.25.0 || ^4.0.0"}},+ "node_modules/zustand": {+ "version": "4.5.7",+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",+ "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",+ "license": "MIT",+ "dependencies": {+ "use-sync-external-store": "^1.2.2"+ },+ "engines": {+ "node": ">=12.7.0"+ },+ "peerDependencies": {+ "@types/react": ">=16.8",+ "immer": ">=9.0.6",+ "react": ">=16.8"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ },+ "immer": {+ "optional": true+ },+ "react": {+ "optional": true+ }+ }+ },"node_modules/zwitch": {"version": "2.0.4","resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",diff --git a/ui/package.json b/ui/package.jsonindex 6ed3e5233..6ec1dd6a7 100644--- a/ui/package.json+++ b/ui/package.json@@ -15,6 +15,7 @@"validate:theme": "node scripts/validate-theme.mjs"},"dependencies": {+ "@dagrejs/dagre": "^1.1.8","@hpke/core": "^1.9.0","@hpke/dhkem-x25519": "^1.8.0","@lexical/react": "^0.45.0",@@ -32,6 +33,7 @@"@xterm/addon-search": "^0.16.0","@xterm/addon-web-links": "^0.12.0","@xterm/xterm": "^6.0.0",+ "@xyflow/react": "^12.11.2","agentation": "^3.0.2","chart.js": "^4.4.0","class-variance-authority": "^0.7.1",diff --git a/ui/src/components/workbench/AgentGraphCanvas.tsx b/ui/src/components/workbench/AgentGraphCanvas.tsxnew file mode 100644index 000000000..e0b179e19--- /dev/null+++ b/ui/src/components/workbench/AgentGraphCanvas.tsx@@ -0,0 +1,321 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import {+ Background,+ BackgroundVariant,+ Controls,+ Handle,+ MarkerType,+ Panel,+ Position,+ ReactFlow,+ ReactFlowProvider,+ useEdgesState,+ useNodesState,+ useReactFlow,+ type Edge,+ type Node,+ type NodeProps,+} from '@xyflow/react';+import '@xyflow/react/dist/style.css';+import { useTranslation } from 'react-i18next';++import { useTheme } from '../../context/ThemeContext';+import {+ type AgentGraphEdge,+ type AgentGraphNode,+ type AgentGraphTriggerNode,+ triggerRefId,+} from '../../lib/agentGraph';+import {+ SESSION_NODE_HEIGHT,+ SESSION_NODE_WIDTH,+ TRIGGER_NODE_HEIGHT,+ TRIGGER_NODE_WIDTH,+ layoutLR,+} from '../../lib/agentGraphLayout';+import { AgentGraphNodeCard } from './AgentGraphNodeCard';+import { AgentGraphTriggerChip } from './AgentGraphTriggerChip';++// ── custom node data + components ────────────────────────────────────────────++type SessionNodeData = {+ node: AgentGraphNode;+ selected: boolean;+ faded: boolean;+ onSelect: (id: string) => void;+ onOpenChat: (id: string) => void;+};+type TriggerNodeData = {+ trigger: AgentGraphTriggerNode;+ faded: boolean;+ onSelect: (definitionId: string) => void;+};++// Hidden handles anchor the edges; the card/chip fills the sized RF node box.+const HANDLE_CLASS = '!h-1 !w-1 !min-w-0 !border-0 !bg-transparent';++const SessionRFNode: React.FC<NodeProps> = ({ data }) => {+ const d = data as unknown as SessionNodeData;+ return (+ <>+ <Handle type="target" position={Position.Left} className={HANDLE_CLASS} isConnectable={false} />+ <AgentGraphNodeCard+ node={d.node}+ selected={d.selected}+ faded={d.faded}+ onClick={() => d.onSelect(d.node.session_id)}+ // Double-click opens the chat only for openable sessions (internal+ // private-agent-run nodes have none).+ onDoubleClick={() => d.node.openable_in_chat && d.onOpenChat(d.node.session_id)}+ />+ <Handle type="source" position={Position.Right} className={HANDLE_CLASS} isConnectable={false} />+ </>+ );+};++const TriggerRFNode: React.FC<NodeProps> = ({ data }) => {+ const d = data as unknown as TriggerNodeData;+ return (+ <>+ <AgentGraphTriggerChip trigger={d.trigger} faded={d.faded} onClick={() => d.onSelect(d.trigger.definition_id)} />+ <Handle type="source" position={Position.Right} className={HANDLE_CLASS} isConnectable={false} />+ </>+ );+};++// Module-const so React Flow doesn't warn about a new nodeTypes object each render.+const NODE_TYPES = { session: SessionRFNode, trigger: TriggerRFNode };++// ── edge styling ─────────────────────────────────────────────────────────────++function edgeVars(kind: AgentGraphEdge['kind']): { color: string; dashed: boolean } {+ if (kind === 'spawn') return { color: 'var(--mint)', dashed: false };+ if (kind === 'callback') return { color: 'var(--cyan)', dashed: true };+ return { color: 'var(--violet)', dashed: true }; // trigger+}++// Build an undirected adjacency map so hovering a node can highlight its whole+// up/down-stream chain (spec: "hover 节点高亮上下游链路").+function buildAdjacency(edges: AgentGraphEdge[]): Map<string, Set<string>> {+ const adj = new Map<string, Set<string>>();+ const link = (a: string, b: string) => {+ if (!adj.has(a)) adj.set(a, new Set());+ adj.get(a)!.add(b);+ };+ for (const e of edges) {+ link(e.from, e.to);+ link(e.to, e.from);+ }+ return adj;+}++function reachable(start: string, adj: Map<string, Set<string>>): Set<string> {+ const seen = new Set<string>([start]);+ const stack = [start];+ while (stack.length) {+ const cur = stack.pop()!;+ for (const next of adj.get(cur) ?? []) {+ if (!seen.has(next)) {+ seen.add(next);+ stack.push(next);+ }+ }+ }+ return seen;+}++// ── props ────────────────────────────────────────────────────────────────────++interface AgentGraphCanvasProps {+ nodes: AgentGraphNode[];+ triggerNodes: AgentGraphTriggerNode[];+ edges: AgentGraphEdge[];+ selectedId: string | null;+ // Changes when the user changes a filter; a new value re-fits the viewport to+ // the new layout. Unchanged across SSE/poll refreshes so they keep the view.+ fitKey: string;+ onSelectNode: (sessionId: string) => void;+ onSelectTrigger: (definitionId: string) => void;+ onOpenChat: (sessionId: string) => void;+}++export const AgentGraphCanvas: React.FC<AgentGraphCanvasProps> = (props) => (+ // Provider lets the inner flow call fitView once nodes are measured.+ <ReactFlowProvider>+ <Flow {...props} />+ </ReactFlowProvider>+);++const Flow: React.FC<AgentGraphCanvasProps> = ({+ nodes,+ triggerNodes,+ edges,+ selectedId,+ fitKey,+ onSelectNode,+ onSelectTrigger,+ onOpenChat,+}) => {+ const { t } = useTranslation();+ const { resolvedTheme } = useTheme();+ const [hoveredId, setHoveredId] = useState<string | null>(null);+ const [rfNodes, setRfNodes, onNodesChange] = useNodesState<Node>([]);+ const [rfEdges, setRfEdges, onEdgesChange] = useEdgesState<Edge>([]);+ const reactFlow = useReactFlow();+ const fittedRef = useRef(false);++ const adjacency = useMemo(() => buildAdjacency(edges), [edges]);+ const highlighted = useMemo(+ () => (hoveredId ? reachable(hoveredId, adjacency) : null),+ [hoveredId, adjacency],+ );++ // Layout only ranks along the call tree (spawn + trigger). Callback edges are+ // drawn but excluded from ranking so they don't fight the left→right layers.+ const layout = useMemo(() => {+ const layoutNodes = [+ ...nodes.map((n) => ({ id: n.session_id, width: SESSION_NODE_WIDTH, height: SESSION_NODE_HEIGHT })),+ ...triggerNodes.map((tr) => ({+ id: triggerRefId(tr.definition_id),+ width: TRIGGER_NODE_WIDTH,+ height: TRIGGER_NODE_HEIGHT,+ })),+ ];+ const layoutEdges = edges+ .filter((e) => e.kind === 'spawn' || e.kind === 'trigger')+ .map((e) => ({ source: e.from, target: e.to }));+ return layoutLR(layoutNodes, layoutEdges);+ }, [nodes, triggerNodes, edges]);++ // Compose the React Flow node list (sessions + trigger chips).+ const computedNodes = useMemo<Node[]>(() => {+ const out: Node[] = [];+ for (const node of nodes) {+ const pos = layout.get(node.session_id) ?? { x: 0, y: 0 };+ out.push({+ id: node.session_id,+ type: 'session',+ position: pos,+ draggable: false,+ style: { width: SESSION_NODE_WIDTH, height: SESSION_NODE_HEIGHT },+ data: {+ node,+ selected: node.session_id === selectedId,+ faded: !!highlighted && !highlighted.has(node.session_id),+ onSelect: onSelectNode,+ onOpenChat,+ } as unknown as Record<string, unknown>,+ });+ }+ for (const trigger of triggerNodes) {+ const id = triggerRefId(trigger.definition_id);+ const pos = layout.get(id) ?? { x: 0, y: 0 };+ out.push({+ id,+ type: 'trigger',+ position: pos,+ draggable: false,+ style: { width: TRIGGER_NODE_WIDTH, height: TRIGGER_NODE_HEIGHT },+ data: {+ trigger,+ faded: !!highlighted && !highlighted.has(id),+ onSelect: onSelectTrigger,+ } as unknown as Record<string, unknown>,+ });+ }+ return out;+ }, [nodes, triggerNodes, layout, selectedId, highlighted, onSelectNode, onSelectTrigger, onOpenChat]);++ const computedEdges = useMemo<Edge[]>(() => {+ return edges.map((edge) => {+ const { color, dashed } = edgeVars(edge.kind);+ const dim = !!highlighted && !(highlighted.has(edge.from) && highlighted.has(edge.to));+ return {+ id: `${edge.kind}:${edge.from}->${edge.to}`,+ source: edge.from,+ target: edge.to,+ type: 'default',+ style: {+ stroke: color,+ strokeWidth: 1.6,+ strokeDasharray: dashed ? '5 4' : undefined,+ opacity: dim ? 0.12 : 0.9,+ },+ markerEnd: { type: MarkerType.ArrowClosed, color, width: 13, height: 13 },+ } satisfies Edge;+ });+ }, [edges, highlighted]);++ useEffect(() => setRfNodes(computedNodes), [computedNodes, setRfNodes]);+ useEffect(() => setRfEdges(computedEdges), [computedEdges, setRfEdges]);++ // A deliberate filter/layout change re-arms the fit guard so the next measured+ // layout re-fits; SSE/poll refreshes keep the same fitKey and preserve the view.+ useEffect(() => {+ fittedRef.current = false;+ }, [fitKey]);++ // Fit after the first non-empty layout is measured (and again after a fitKey+ // change re-arms the guard); plain SSE refreshes keep the viewport stable.+ useEffect(() => {+ if (!fittedRef.current && rfNodes.length) {+ fittedRef.current = true;+ requestAnimationFrame(() => reactFlow.fitView({ padding: 0.22, maxZoom: 1 }));+ }+ }, [rfNodes, reactFlow]);++ return (+ <div className="h-[600px] max-h-[72vh] w-full overflow-hidden rounded-2xl border border-border-strong bg-surface-3/60">+ <ReactFlow+ nodes={rfNodes}+ edges={rfEdges}+ onNodesChange={onNodesChange}+ onEdgesChange={onEdgesChange}+ nodeTypes={NODE_TYPES}+ colorMode={resolvedTheme}+ nodesDraggable={false}+ nodesConnectable={false}+ elementsSelectable+ // Read-only graph: keep click selection but disable Delete/Backspace, or+ // the change handlers would drop a selected node/edge until next refresh.+ deleteKeyCode={null}+ proOptions={{ hideAttribution: true }}+ minZoom={0.2}+ maxZoom={1.75}+ onNodeMouseEnter={(_e, node) => setHoveredId(node.id)}+ onNodeMouseLeave={() => setHoveredId(null)}+ onPaneClick={() => setHoveredId(null)}+ >+ <Background variant={BackgroundVariant.Dots} gap={22} size={1} className="opacity-40" />+ <Controls showInteractive={false} position="bottom-right" />+ <Panel position="bottom-left">+ <Legend t={t} />+ </Panel>+ </ReactFlow>+ </div>+ );+};++const Legend: React.FC<{ t: (k: string) => string }> = ({ t }) => (+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 rounded-xl border border-border-strong bg-surface/90 px-3 py-2 text-[11px] text-muted backdrop-blur">+ <LegendItem label={t('agents.graph.legend.spawn')}>+ <span className="h-[2px] w-5" style={{ background: 'var(--mint)' }} />+ </LegendItem>+ <LegendItem label={t('agents.graph.legend.callback')}>+ <span className="h-0 w-5 border-t-2 border-dashed" style={{ borderColor: 'var(--cyan)' }} />+ </LegendItem>+ <LegendItem label={t('agents.graph.legend.trigger')}>+ <span className="h-0 w-5 border-t-2 border-dashed" style={{ borderColor: 'var(--violet)' }} />+ </LegendItem>+ <LegendItem label={t('agents.graph.legend.background')}>+ <span className="text-muted">◎</span>+ </LegendItem>+ </div>+);++const LegendItem: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (+ <span className="inline-flex items-center gap-1.5">+ <span className="inline-flex items-center">{children}</span>+ {label}+ </span>+);diff --git a/ui/src/components/workbench/AgentGraphDetail.tsx b/ui/src/components/workbench/AgentGraphDetail.tsxnew file mode 100644index 000000000..c41cb826d--- /dev/null+++ b/ui/src/components/workbench/AgentGraphDetail.tsx@@ -0,0 +1,379 @@+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Link } from 'react-router-dom';+import {+ Bot,+ CornerDownRight,+ CornerLeftUp,+ Eye,+ EyeOff,+ FolderClosed,+ Loader2,+ MessageSquare,+ Power,+ Square,+ Trash2,+ X,+} from 'lucide-react';+import clsx from 'clsx';++import { useApi } from '../../context/ApiContext';+import { useToast } from '../../context/ToastContext';+import { Button } from '../ui/button';+import { formatRelativeTime } from '../../lib/relativeTime';+import {+ type AgentGraphEdge,+ type AgentGraphNode,+ type AgentGraphStatus,+ type AgentGraphTriggerNode,+ deriveLineage,+ formatElapsed,+ isBackground,+ nodeDisplayTitle,+ runElapsedSeconds,+ statusMeta,+} from '../../lib/agentGraph';++interface AgentGraphDetailProps {+ node: AgentGraphNode;+ nodesById: Map<string, AgentGraphNode>;+ edges: AgentGraphEdge[];+ triggersById: Map<string, AgentGraphTriggerNode>;+ onClose: () => void;+ onSelectNode: (sessionId: string) => void;+ onRefresh: () => void;+}++export const AgentGraphDetail: React.FC<AgentGraphDetailProps> = ({+ node,+ nodesById,+ edges,+ triggersById,+ onClose,+ onSelectNode,+ onRefresh,+}) => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();+ const [busy, setBusy] = useState(false);+ const [armEnd, setArmEnd] = useState(false);+ const disarmRef = useRef<number | null>(null);+ const disarm = () => {+ if (disarmRef.current != null) window.clearTimeout(disarmRef.current);+ disarmRef.current = null;+ setArmEnd(false);+ };+ const arm = () => {+ if (disarmRef.current != null) window.clearTimeout(disarmRef.current);+ setArmEnd(true);+ // Auto-disarm after a few seconds: the Stop/Kill button can keep focus, so+ // blur alone would leave a destructive action armed indefinitely and a later+ // stray click could terminate an active/orphan run.+ disarmRef.current = window.setTimeout(() => {+ disarmRef.current = null;+ setArmEnd(false);+ }, 3000);+ };+ // The panel stays mounted across node switches (only the prop changes), so+ // clear a pending destructive-confirm when the selected session changes — a+ // click on the new node must not skip its first confirmation — and never let+ // the disarm timer outlive the panel.+ useEffect(() => {+ setArmEnd(false);+ return () => {+ if (disarmRef.current != null) window.clearTimeout(disarmRef.current);+ disarmRef.current = null;+ };+ }, [node.session_id]);++ const lineage = deriveLineage(node.session_id, edges, triggersById);+ const meta = statusMeta(node.status);+ const background = isBackground(node);+ const timeLabel = node.live+ ? formatElapsed(node.elapsed_seconds)+ : formatRelativeTime(node.last_active_at ?? node.created_at, t);++ const callerTitle = (sessionId: string): string => {+ const caller = nodesById.get(sessionId);+ return caller ? nodeDisplayTitle(caller) : sessionId;+ };++ // 触发 (trigger source): a Task/Watch definition, else an agent-initiated run,+ // else the human/platform origin.+ const triggerLabel = lineage.trigger+ ? `${lineage.trigger.definition_type === 'watch' ? t('agents.graph.trigger.watch') : t('agents.graph.trigger.task')} · ${lineage.trigger.name ?? lineage.trigger.definition_id}`+ : lineage.spawnedBy+ ? t('agents.graph.detail.triggerAgentRun')+ : t('agents.graph.detail.triggerHuman');++ const toggleVisibility = async () => {+ if (!node.visibility) return;+ const next = node.visibility === 'foreground' ? 'background' : 'foreground';+ setBusy(true);+ try {+ await api.setSessionVisibility(node.session_id, next);+ showToast(t(next === 'foreground' ? 'agents.graph.detail.movedForeground' : 'agents.graph.detail.movedBackground'), 'success');+ onRefresh();+ } catch (err) {+ showToast(err instanceof Error ? err.message : String(err), 'error');+ } finally {+ setBusy(false);+ }+ };++ const endRun = async () => {+ disarm();+ setBusy(true);+ try {+ // Ending a live runtime needs the backend-specific identifiers the+ // running-agents snapshot holds (Claude → composite_key, Codex/OpenCode →+ // base_session_id, orphan → pid); session_id alone can't resolve the+ // teardown. Resolve the live row for this session at click time so the+ // graph node stays free of transient process identifiers.+ const snap = await api.getRunningAgents();+ const rows = (snap.ok ? snap.agents : []).filter((a) => a.session_id === node.session_id);+ // A session can have multiple backend rows; the liveness merge picked one+ // state for the node. End the row whose state made the node live (else the+ // idle/persisted row could be targeted instead of the active one), then+ // fall back to backend match, then any row for the session.+ const row =+ rows.find((a) => a.state === node.status && a.backend === node.agent_backend) ??+ rows.find((a) => a.state === node.status) ??+ rows.find((a) => a.backend === node.agent_backend) ??+ rows[0];+ if (!row) {+ showToast(t('agents.graph.detail.endGone'), 'warning');+ onRefresh();+ return;+ }+ const result = await api.endRunningAgent({+ backend: row.backend,+ state: row.state,+ session_id: row.session_id,+ composite_key: row.composite_key,+ base_session_id: row.base_session_id,+ pid: row.pid,+ });+ if (result.ok) {+ showToast(t('agents.running.endedToast'), 'success');+ onRefresh();+ } else {+ showToast(t('agents.running.endFailedToast', { error: result.error || 'failed' }), 'error');+ }+ } catch (err) {+ showToast(err instanceof Error ? err.message : String(err), 'error');+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="flex flex-col gap-3.5">+ {/* Header: status + visibility pills + close */}+ <div className="flex items-center gap-2">+ <span+ className={clsx(+ 'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[11px] font-semibold',+ statusPillClass(meta.tone),+ )}+ >+ <span className={clsx('size-1.5 rounded-full', meta.dotClass)} />+ {t(meta.labelKey)}+ {timeLabel !== '—' && <span className="font-mono text-[10px] opacity-80">· {timeLabel}</span>}+ </span>+ {node.visibility && (+ <span className="inline-flex items-center gap-1 rounded-full border border-border-strong bg-foreground/[0.04] px-2 py-0.5 text-[10px] text-muted">+ {background ? <EyeOff className="size-3" /> : <Eye className="size-3" />}+ {t(background ? 'agents.graph.detail.background' : 'agents.graph.detail.foreground')}+ </span>+ )}+ <span className="flex-1" />+ <Button type="button" variant="ghost" size="icon" onClick={onClose} aria-label={t('common.close')} className="size-6">+ <X className="size-3.5" />+ </Button>+ </div>++ {/* Title + agent line */}+ <div className="flex flex-col gap-1">+ <div className="text-[16px] font-bold text-foreground">{nodeDisplayTitle(node)}</div>+ <div className="flex flex-wrap items-center gap-1.5 text-[11px] text-muted">+ {node.agent_name && <span className="font-medium text-foreground">{node.agent_name}</span>}+ {node.agent_backend && (+ <span className="rounded border border-border-strong bg-foreground/[0.04] px-1 font-mono text-[9px] font-bold uppercase">+ {node.agent_backend}+ </span>+ )}+ {node.model && <span className="font-mono">{node.model}</span>}+ {node.reasoning_effort && <span className="font-mono">· {node.reasoning_effort}</span>}+ </div>+ </div>++ <div className="h-px bg-border" />++ {/* Facts */}+ <div className="flex flex-col gap-2.5">+ <Fact label={t('agents.graph.detail.project')}>+ <span className="inline-flex items-center gap-1.5">+ <FolderClosed className="size-3 text-muted" />+ {node.scope_label ?? t('agents.graph.detail.standalone')}+ </span>+ </Fact>+ {node.workdir && (+ <Fact label={t('agents.graph.detail.workdir')}>+ <span className="break-all font-mono text-[11px]">{node.workdir}</span>+ </Fact>+ )}+ {node.visibility && (+ <Fact label={t('agents.graph.detail.visibility')}>+ <span className="inline-flex items-center gap-1.5">+ {background ? <EyeOff className="size-3" /> : <Eye className="size-3" />}+ {t(background ? 'agents.graph.detail.visibilityBackground' : 'agents.graph.detail.visibilityForeground')}+ </span>+ </Fact>+ )}+ <Fact label={t('agents.graph.detail.startedBy')}>+ {lineage.spawnedBy ? (+ <button+ type="button"+ onClick={() => onSelectNode(lineage.spawnedBy!)}+ className="inline-flex items-center gap-1.5 text-mint hover:underline"+ >+ <CornerLeftUp className="size-3" />+ {callerTitle(lineage.spawnedBy)}+ </button>+ ) : (+ <span className="inline-flex items-center gap-1.5 text-muted">+ <Bot className="size-3" />+ {triggerLabel}+ </span>+ )}+ </Fact>+ <Fact label={t('agents.graph.detail.reportsTo')}>+ {lineage.callbackTo ? (+ <span className="inline-flex items-center gap-1.5 text-cyan">+ <CornerDownRight className="size-3" />+ {callerTitle(lineage.callbackTo)}+ <span className="text-muted">· {t(`agents.graph.detail.callback.${lineage.callbackStatus ?? 'pending'}`)}</span>+ </span>+ ) : (+ <span className="text-muted">—</span>+ )}+ </Fact>+ <Fact label={t('agents.graph.detail.trigger')}>+ <span className="font-mono text-[11px] text-muted">{triggerLabel}</span>+ </Fact>+ </div>++ {/* Runs timeline */}+ {node.runs && node.runs.length > 0 && (+ <>+ <div className="flex items-center justify-between">+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">+ {t('agents.graph.detail.runsTitle')}+ </span>+ <Link to="/harness?tab=runs" className="text-[11px] font-medium text-cyan hover:underline">+ {t('agents.graph.detail.viewAllInHarness')}+ </Link>+ </div>+ <div className="flex flex-col gap-1">+ {node.runs.map((run) => (+ <Link+ key={run.id}+ to={`/harness?tab=runs&run=${encodeURIComponent(run.id)}`}+ className="flex items-center gap-2 rounded-lg border border-border bg-surface px-2.5 py-1.5 text-[11px] transition hover:border-border-strong"+ >+ <span className={clsx('size-1.5 shrink-0 rounded-full', statusMeta(runStatus(run.status)).dotClass)} />+ <code className="font-mono text-foreground">{run.id}</code>+ <span className="text-muted">{t(statusMeta(runStatus(run.status)).labelKey)}</span>+ <span className="flex-1" />+ <span className="font-mono text-[10px] text-muted">{formatElapsed(runElapsedSeconds(run))}</span>+ </Link>+ ))}+ </div>+ </>+ )}++ {/* Actions */}+ <div className="flex flex-col gap-2 pt-1">+ {/* Open-chat only for openable sessions — an internal private-agent-run+ session has no chat to open (openable_in_chat=false). */}+ {node.openable_in_chat && (+ <Link+ to={`/chat/${encodeURIComponent(node.session_id)}`}+ className="inline-flex h-9 items-center justify-center gap-2 rounded-lg border border-mint/40 bg-mint-soft text-[13px] font-semibold text-mint transition hover:brightness-110"+ >+ <MessageSquare className="size-3.5" />+ {t('agents.graph.detail.openChat')}+ </Link>+ )}+ <div className="flex items-center gap-2">+ {node.visibility && (+ <Button type="button" variant="outline" size="xs" onClick={toggleVisibility} disabled={busy} className="flex-1">+ {busy ? <Loader2 className="size-3 animate-spin" /> : background ? <Eye className="size-3" /> : <EyeOff className="size-3" />}+ {t(background ? 'agents.graph.detail.toForeground' : 'agents.graph.detail.toBackground')}+ </Button>+ )}+ {node.live && (() => {+ // Per-state end action (Stop / Disconnect / Kill), matching the old+ // running list: active + orphan are destructive (2-step confirm),+ // idle disconnect is non-destructive (single click).+ const meta = END_META[node.status as EndState] ?? END_META.active;+ const EndIcon = meta.Icon;+ return (+ <Button+ type="button"+ variant={armEnd ? 'destructive' : 'destructive-soft'}+ size="xs"+ onClick={() => (meta.needsConfirm && !armEnd ? arm() : endRun())}+ onBlur={() => disarm()}+ disabled={busy}+ className="flex-1"+ >+ {busy ? (+ <Loader2 className="size-3 animate-spin" />+ ) : armEnd ? null : (+ <EndIcon className="size-3" />+ )}+ {armEnd ? t('agents.running.confirmEnd') : t(meta.labelKey)}+ </Button>+ );+ })()}+ </div>+ </div>+ </div>+ );+};++// Per-state end action, matching the old running list. Idle disconnect is+// non-destructive (no confirm); active Stop and orphan Kill require a 2nd click.+type EndState = 'active' | 'idle' | 'orphan';+const END_META: Record<EndState, { labelKey: string; Icon: typeof Square; needsConfirm: boolean }> = {+ active: { labelKey: 'agents.running.endActive', Icon: Square, needsConfirm: true },+ idle: { labelKey: 'agents.running.endIdle', Icon: Power, needsConfirm: false },+ orphan: { labelKey: 'agents.running.endOrphan', Icon: Trash2, needsConfirm: true },+};++// A run row's stored status is already normalized to the run vocabulary; map it+// onto the node status vocabulary the shared statusMeta understands (a live+// run's ``running`` reuses the ``active`` dot).+function runStatus(status: string): AgentGraphStatus {+ if (status === 'running') return 'active';+ const known: AgentGraphStatus[] = ['queued', 'succeeded', 'failed', 'canceled', 'idle', 'active', 'orphan'];+ return (known as string[]).includes(status) ? (status as AgentGraphStatus) : 'idle';+}++function statusPillClass(tone: string): string {+ if (tone === 'mint') return 'border-mint/40 bg-mint-soft text-mint';+ if (tone === 'gold') return 'border-gold/40 bg-gold/10 text-gold';+ if (tone === 'cyan') return 'border-cyan/40 bg-cyan-soft text-cyan';+ if (tone === 'destructive') return 'border-destructive/40 bg-destructive/10 text-destructive';+ return 'border-border-strong bg-foreground/[0.04] text-muted';+}++const Fact: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (+ <div className="flex items-start gap-3">+ <span className="w-16 shrink-0 pt-0.5 font-mono text-[10px] font-bold uppercase tracking-wide text-muted">{label}</span>+ <div className="min-w-0 flex-1 text-[12px] text-foreground">{children}</div>+ </div>+);diff --git a/ui/src/components/workbench/AgentGraphMobileList.tsx b/ui/src/components/workbench/AgentGraphMobileList.tsxnew file mode 100644index 000000000..ed7aa4420--- /dev/null+++ b/ui/src/components/workbench/AgentGraphMobileList.tsx@@ -0,0 +1,69 @@+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { CalendarClock, CornerDownRight, Eye } from 'lucide-react';++import {+ type AgentGraphEdge,+ type AgentGraphNode,+ type AgentGraphTriggerNode,+ buildGraphForest,+} from '../../lib/agentGraph';+import { AgentGraphNodeCard } from './AgentGraphNodeCard';++interface AgentGraphMobileListProps {+ nodes: AgentGraphNode[];+ edges: AgentGraphEdge[];+ triggerNodes: AgentGraphTriggerNode[];+ selectedId: string | null;+ onSelectNode: (sessionId: string) => void;+}++// Mobile fallback: the same graph payload rendered as a spawn-tree indented+// list (no canvas). Depth comes from the spawn forest; a triggered lineage root+// shows its Task/Watch source as a small chip above the card.+export const AgentGraphMobileList: React.FC<AgentGraphMobileListProps> = ({+ nodes,+ edges,+ triggerNodes,+ selectedId,+ onSelectNode,+}) => {+ const { t } = useTranslation();+ const rows = useMemo(() => buildGraphForest(nodes, edges, triggerNodes), [nodes, edges, triggerNodes]);++ return (+ <div className="flex flex-col gap-2">+ {rows.map(({ node, depth, trigger }) => (+ <div+ key={node.session_id}+ style={{ marginLeft: depth * 18 }}+ className="flex flex-col gap-1"+ >+ {depth > 0 && (+ <span className="flex items-center gap-1 text-[10px] text-muted">+ <CornerDownRight className="size-3" />+ </span>+ )}+ {trigger && (+ <span className="inline-flex w-fit items-center gap-1 rounded-md border border-violet/40 bg-violet-soft px-1.5 py-0.5 text-[10px] font-medium text-violet">+ {trigger.definition_type === 'watch' ? <Eye className="size-2.5" /> : <CalendarClock className="size-2.5" />}+ {trigger.name ?? trigger.definition_id}+ </span>+ )}+ <div className="h-[92px]">+ <AgentGraphNodeCard+ node={node}+ selected={node.session_id === selectedId}+ onClick={() => onSelectNode(node.session_id)}+ />+ </div>+ </div>+ ))}+ {rows.length === 0 && (+ <div className="rounded-xl border border-dashed border-border bg-surface px-6 py-10 text-center text-[12px] text-muted">+ {t('agents.graph.empty')}+ </div>+ )}+ </div>+ );+};diff --git a/ui/src/components/workbench/AgentGraphNodeCard.tsx b/ui/src/components/workbench/AgentGraphNodeCard.tsxnew file mode 100644index 000000000..a81c33baa--- /dev/null+++ b/ui/src/components/workbench/AgentGraphNodeCard.tsx@@ -0,0 +1,117 @@+import { useTranslation } from 'react-i18next';+import { Check, EyeOff, FolderClosed, X } from 'lucide-react';+import clsx from 'clsx';++import { BACKEND_TEXT, type Backend } from '../../lib/backendAccent';+import { formatRelativeTime } from '../../lib/relativeTime';+import {+ type AgentGraphNode,+ formatElapsed,+ isBackground,+ nodeDisplayTitle,+ statusMeta,+} from '../../lib/agentGraph';++// Border/tint by status tone. Selected wins (mint ring + glow, per spec frame+// anu5U 选中态). Failed nodes carry a destructive tint; live-active a mint+// hint; everything else the neutral surface. Non-live nodes are dimmed by the+// caller via ``faded``.+function shellClass(node: AgentGraphNode, selected: boolean): string {+ if (selected) return 'border-mint/70 bg-mint-soft shadow-[0_0_20px_-6px_rgba(91,255,160,0.55)]';+ const tone = statusMeta(node.status).tone;+ if (tone === 'destructive') return 'border-destructive/40 bg-destructive/[0.05]';+ if (node.status === 'active') return 'border-mint/40 bg-surface';+ if (node.status === 'queued') return 'border-gold/40 bg-surface';+ return 'border-border bg-surface';+}++interface AgentGraphNodeCardProps {+ node: AgentGraphNode;+ selected?: boolean;+ // Dim when a hovered node's up/down-stream highlight excludes this one.+ faded?: boolean;+ onClick?: () => void;+ onDoubleClick?: () => void;+ className?: string;+}++// One session card — the shared visual used both as a React Flow canvas node+// and as a mobile grouped-list row. Fills its parent (the parent owns the box+// size so the dagre layout and the card stay in lockstep).+export const AgentGraphNodeCard: React.FC<AgentGraphNodeCardProps> = ({+ node,+ selected = false,+ faded = false,+ onClick,+ onDoubleClick,+ className,+}) => {+ const { t } = useTranslation();+ const backendClass = BACKEND_TEXT[node.agent_backend as Backend] ?? 'text-muted';+ const background = isBackground(node);+ const timeLabel = node.live+ ? formatElapsed(node.elapsed_seconds)+ : formatRelativeTime(node.last_active_at ?? node.created_at, t);++ return (+ <button+ type="button"+ onClick={onClick}+ onDoubleClick={onDoubleClick}+ title={nodeDisplayTitle(node)}+ className={clsx(+ 'flex h-full w-full flex-col gap-1.5 rounded-xl border px-3 py-2.5 text-left transition',+ shellClass(node, selected),+ !node.live && !selected && 'opacity-65',+ faded && 'opacity-25',+ onClick && 'hover:border-border-strong',+ className,+ )}+ >+ {/* Header: status glyph · agent · backend badge · visibility eye */}+ <div className="flex min-w-0 items-center gap-1.5">+ <StatusGlyph node={node} />+ <span className="truncate text-[12px] font-semibold text-foreground">+ {node.agent_name ?? '—'}+ </span>+ {node.agent_backend && (+ <span+ className={clsx(+ 'shrink-0 rounded border border-border-strong bg-foreground/[0.04] px-1 py-0 font-mono text-[9px] font-bold',+ backendClass,+ )}+ >+ {node.agent_backend}+ </span>+ )}+ <span className="flex-1" />+ {background && <EyeOff className="size-3 shrink-0 text-muted" aria-label={t('agents.graph.detail.background')} />}+ </div>++ {/* Title */}+ <div className="min-w-0 truncate text-[13px] font-semibold text-foreground">+ {nodeDisplayTitle(node)}+ </div>++ {/* Footer: scope (or 独立) · elapsed / relative time */}+ <div className="flex min-w-0 items-center gap-1.5 text-[11px] text-muted">+ <FolderClosed className="size-3 shrink-0" />+ <span className="min-w-0 flex-1 truncate">+ {node.scope_label ?? t('agents.graph.detail.standalone')}+ </span>+ <span className="shrink-0 font-mono text-[10px]">{timeLabel}</span>+ </div>+ </button>+ );+};++// Status glyph: colored dot (live/queued), check (succeeded), or cross+// (failed/canceled) — mirrors the spec frame node states.+const StatusGlyph: React.FC<{ node: AgentGraphNode }> = ({ node }) => {+ const meta = statusMeta(node.status);+ if (meta.glyph === 'check') return <Check className="size-3 shrink-0 text-muted" />;+ if (meta.glyph === 'cross') {+ return <X className={clsx('size-3 shrink-0', meta.tone === 'destructive' ? 'text-destructive' : 'text-muted')} />;+ }+ return <span className={clsx('size-2 shrink-0 rounded-full', meta.dotClass, node.status === 'active' && 'animate-pulse')} />;+};diff --git a/ui/src/components/workbench/AgentGraphOrphanStrip.tsx b/ui/src/components/workbench/AgentGraphOrphanStrip.tsxnew file mode 100644index 000000000..913e5f308--- /dev/null+++ b/ui/src/components/workbench/AgentGraphOrphanStrip.tsx@@ -0,0 +1,158 @@+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { AlertTriangle, Loader2, Power, Square, Trash2 } from 'lucide-react';+import clsx from 'clsx';++import type { RunningAgent } from '../../context/ApiContext';+import { Button } from '../ui/button';+import { Badge } from '../ui/badge';+import { BACKEND_LABEL, BACKEND_TEXT, type Backend } from '../../lib/backendAccent';+import { formatElapsed } from '../../lib/agentGraph';++// Contract A3 (+ review r6): the run graph is session-centric, so a live+// running-agents row with no session_id has no node. This strip above the+// canvas preserves the old flat list's ability to SEE and end EVERY such+// session-less runtime — not just orphans — with its actual state and a+// state-appropriate action. Purely client-side over the running-agents+// payload; the graph payload is unchanged.++// Per-state presentation: dot/label + end action (Stop / Disconnect / Kill).+// Idle disconnect is non-destructive (single click); active/orphan confirm.+type LiveState = 'active' | 'idle' | 'orphan';+const STATE_META: Record<+ LiveState,+ { dotClass: string; stateKey: string; endKey: string; Icon: typeof Square; needsConfirm: boolean }+> = {+ active: { dotClass: 'bg-mint', stateKey: 'agents.running.stateActive', endKey: 'agents.running.endActive', Icon: Square, needsConfirm: true },+ idle: { dotClass: 'bg-muted', stateKey: 'agents.running.stateIdle', endKey: 'agents.running.endIdle', Icon: Power, needsConfirm: false },+ orphan: { dotClass: 'bg-amber-500', stateKey: 'agents.running.stateOrphan', endKey: 'agents.running.endOrphan', Icon: Trash2, needsConfirm: true },+};+const stateMeta = (state: string) => STATE_META[(state as LiveState)] ?? STATE_META.orphan;++interface AgentGraphOrphanStripProps {+ // Session-less live rows (any state) from GET /api/running-agents.+ rows: RunningAgent[];+ onEnd: (row: RunningAgent) => Promise<void>;+}++export const AgentGraphOrphanStrip: React.FC<AgentGraphOrphanStripProps> = ({ rows, onEnd }) => {+ const { t } = useTranslation();+ if (rows.length === 0) return null;+ return (+ <div className="flex flex-col gap-2 rounded-xl border border-amber-500/40 bg-amber-500/[0.05] px-4 py-3">+ <div className="flex items-center gap-2">+ <AlertTriangle className="size-3.5 shrink-0 text-amber-500" />+ <span className="text-[12px] font-semibold text-foreground">+ {t('agents.graph.orphans.title', { count: rows.length })}+ </span>+ </div>+ <div className="text-[11px] text-muted">{t('agents.graph.orphans.description')}</div>+ <div className="flex flex-col gap-1.5">+ {rows.map((row) => (+ <OrphanRow+ // composite_key is the unique identifier when present; otherwise+ // combine every stable identifier the row carries so two session-less+ // rows from the same backend (e.g. OpenCode active rows with only a+ // base_session_id, no pid/native id) can't collide onto one React key+ // and swap OrphanRow state (a stuck/misdirected confirm or spinner).+ key={+ row.composite_key ??+ [row.backend, row.base_session_id, row.native_session_id, row.pid, row.workdir]+ .map((v) => v ?? '')+ .join('|')+ }+ row={row}+ onEnd={onEnd}+ />+ ))}+ </div>+ </div>+ );+};++const OrphanRow: React.FC<{ row: RunningAgent; onEnd: (r: RunningAgent) => Promise<void> }> = ({+ row,+ onEnd,+}) => {+ const { t } = useTranslation();+ const [armed, setArmed] = useState(false);+ const [ending, setEnding] = useState(false);+ const mounted = useRef(true);+ const disarm = useRef<number | null>(null);+ useEffect(+ () => () => {+ mounted.current = false;+ if (disarm.current != null) window.clearTimeout(disarm.current);+ },+ [],+ );++ const meta = stateMeta(row.state);+ const EndIcon = meta.Icon;+ const backendLabel = BACKEND_LABEL[row.backend as Backend] ?? row.backend;+ const backendClass = BACKEND_TEXT[row.backend as Backend] ?? 'text-muted';++ const handleClick = () => {+ if (ending) return;+ if (meta.needsConfirm && !armed) {+ setArmed(true);+ if (disarm.current != null) window.clearTimeout(disarm.current);+ disarm.current = window.setTimeout(() => {+ if (mounted.current) setArmed(false);+ }, 3000);+ return;+ }+ setArmed(false);+ if (disarm.current != null) window.clearTimeout(disarm.current);+ setEnding(true);+ void onEnd(row).finally(() => {+ if (mounted.current) setEnding(false);+ });+ };++ return (+ <div className="flex min-w-0 items-center gap-2 rounded-lg border border-border bg-surface px-3 py-2 text-[11px]">+ <Badge variant="secondary" className="font-mono text-[9px] uppercase">+ <span className={clsx('size-1.5 rounded-full', meta.dotClass)} />+ {t(meta.stateKey)}+ </Badge>+ <span className={clsx('font-mono text-[10px] font-bold uppercase tracking-wide', backendClass)}>+ {backendLabel}+ </span>+ {typeof row.pid === 'number' && (+ <span className="font-mono text-[10px] text-muted">+ pid {row.pid}+ {row.pid_shared && <span className="ml-1 text-amber-500">{t('agents.running.pidShared')}</span>}+ </span>+ )}+ {row.workdir && (+ <span className="min-w-0 flex-1 truncate font-mono text-[10px] text-muted" title={row.workdir}>+ {row.workdir}+ </span>+ )}+ <span className="flex-1" />+ {row.elapsed_seconds != null && (+ <span className="shrink-0 font-mono text-[10px] text-muted">{formatElapsed(row.elapsed_seconds)}</span>+ )}+ <Button+ type="button"+ variant={armed ? 'destructive' : 'destructive-soft'}+ size="xs"+ onClick={handleClick}+ disabled={ending}+ className="h-7 shrink-0"+ >+ {ending ? (+ <Loader2 className="size-3 animate-spin" />+ ) : armed ? (+ t('agents.running.confirmEnd')+ ) : (+ <>+ <EndIcon className="size-3" />+ {t(meta.endKey)}+ </>+ )}+ </Button>+ </div>+ );+};diff --git a/ui/src/components/workbench/AgentGraphTab.tsx b/ui/src/components/workbench/AgentGraphTab.tsxnew file mode 100644index 000000000..e4ccecbca--- /dev/null+++ b/ui/src/components/workbench/AgentGraphTab.tsx@@ -0,0 +1,479 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';+import { AlertTriangle, ChevronDown, Clock, FolderClosed, Loader2, RefreshCw, ServerCrash } from 'lucide-react';+import clsx from 'clsx';++import { useApi } from '../../context/ApiContext';+import type { RunningAgent } from '../../context/ApiContext';+import { useToast } from '../../context/ToastContext';+import { Button } from '../ui/button';+import { Switch } from '../ui/switch';+import { SegmentedRadio } from '../ui/segmented';+import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';+import {+ type AgentGraphResult,+ type GraphWindow,+ GRAPH_WINDOWS,+} from '../../lib/agentGraph';+import { AgentGraphCanvas } from './AgentGraphCanvas';+import { AgentGraphMobileList } from './AgentGraphMobileList';+import { AgentGraphDetail } from './AgentGraphDetail';+import { AgentGraphOrphanStrip } from './AgentGraphOrphanStrip';++// Degraded-mode refresh cadence while SSE is disconnected (mirrors the old+// RunningAgentsTab). SSE covers lifecycle writes when connected.+const POLL_INTERVAL_MS = 4000;+const LIVENESS_POLL_INTERVAL_MS = 30000;++type GraphPayload = AgentGraphResult & { live_unreachable?: boolean };++// Desktop ⇒ React Flow canvas; mobile ⇒ grouped list (contract §4).+function useIsDesktop(): boolean {+ const [desktop, setDesktop] = useState(+ () => typeof window !== 'undefined' && window.matchMedia?.('(min-width: 768px)').matches,+ );+ useEffect(() => {+ if (typeof window === 'undefined' || !window.matchMedia) return;+ const mql = window.matchMedia('(min-width: 768px)');+ const onChange = () => setDesktop(mql.matches);+ mql.addEventListener('change', onChange);+ return () => mql.removeEventListener('change', onChange);+ }, []);+ return !!desktop;+}++export const AgentGraphTab: React.FC = () => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();+ const navigate = useNavigate();+ const isDesktop = useIsDesktop();++ const [graph, setGraph] = useState<GraphPayload | null>(null);+ // Session-less orphan processes (contract A3) — surfaced in a strip above the+ // graph, not as nodes. Sourced from the running-agents snapshot, so they are+ // filter-independent like the badge.+ const [orphans, setOrphans] = useState<RunningAgent[]>([]);+ const [loading, setLoading] = useState(true);+ const [errored, setErrored] = useState(false);+ const [eventBridgeConnected, setEventBridgeConnected] = useState(false);+ const [projects, setProjects] = useState<{ id: string; display_name: string }[]>([]);++ // Filters (spec: 活跃/含历史 · time window · project incl. 独立 · 显示后台会话).+ const [mode, setMode] = useState<'active' | 'history'>('history');+ const [windowSel, setWindowSel] = useState<GraphWindow>('24h');+ const [projectSel, setProjectSel] = useState<string>('all');+ const [showBackground, setShowBackground] = useState(true);++ const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);++ const mountedRef = useRef(true);+ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);++ // Project dropdown options come from the authoritative project list so the+ // menu stays complete even when a filter narrows the graph.+ useEffect(() => {+ let cancelled = false;+ api+ .listProjects()+ .then((res) => {+ if (!cancelled) setProjects(res.projects.map((p) => ({ id: p.id, display_name: p.display_name })));+ })+ .catch(() => {});+ return () => {+ cancelled = true;+ };+ }, [api]);++ const seqRef = useRef(0);+ const inFlightRef = useRef(false);+ const pendingBgRef = useRef(false);+ const fetchGraph = useCallback(+ async (background = false) => {+ // Coalesce background refreshes: the poll and the SSE bus (which can burst+ // many run/turn events) both call this. While a fetch is in flight, record+ // that another was requested and run exactly one trailing refresh when it+ // settles — `seqRef` only discards stale *results*, it doesn't stop+ // concurrent scans from piling up on a slow/backgrounded tab.+ if (background && inFlightRef.current) {+ pendingBgRef.current = true;+ return;+ }+ const seq = ++seqRef.current;+ inFlightRef.current = true;+ if (!background) setLoading(true);+ try {+ // Orphans come from the (filter-independent) running-agents snapshot in+ // parallel with the filtered graph; a running-agents failure must not+ // fail the graph fetch.+ const [result, running] = await Promise.all([+ api.getAgentsGraph({+ window: windowSel,+ project: projectSel,+ includeEnded: mode === 'history',+ includeBackground: showBackground,+ }),+ api.getRunningAgents().catch(() => null),+ ]);+ // Ignore a stale response: a slower earlier request must not clobber a+ // newer one issued after a filter change.+ if (!mountedRef.current || seq !== seqRef.current) return;+ setGraph(result);+ // Every session-less live row (any state) goes to the strip — the graph+ // is session-centric so these have no node, and the old flat list let+ // users end them. The strip labels each by its actual state and offers a+ // state-appropriate action (Stop/Disconnect/Kill).+ setOrphans(running && running.ok ? running.agents.filter((a) => !a.session_id) : []);+ setErrored(false);+ } catch {+ if (mountedRef.current && seq === seqRef.current) setErrored(true);+ } finally {+ inFlightRef.current = false;+ // Always clear the spinner a foreground fetch raised — even if a newer+ // fetch superseded its result — or a superseded foreground load leaves+ // loading stuck true forever.+ if (mountedRef.current && !background) setLoading(false);+ // Run the single coalesced refresh requested while this one was in+ // flight, so bursts collapse to one trailing fetch — but only if no+ // newer fetch has started. If the user changed a filter (or any newer+ // fetch bumped seqRef) the current `fetchGraph` closure holds stale+ // params; replaying it would overwrite the graph with the old filter's+ // results. The newer in-flight fetch already covers freshness, so drop+ // the stale trailing refresh.+ if (mountedRef.current && pendingBgRef.current && seq === seqRef.current) {+ pendingBgRef.current = false;+ void fetchGraph(true);+ } else if (seq !== seqRef.current) {+ pendingBgRef.current = false;+ }+ }+ },+ [api, windowSel, projectSel, mode, showBackground],+ );++ // Kill a session-less orphan process (A3): orphan teardown resolves by pid, so+ // pass the snapshot row's identifiers straight through.+ const killOrphan = useCallback(+ async (orphan: RunningAgent) => {+ try {+ const result = await api.endRunningAgent({+ backend: orphan.backend,+ state: orphan.state,+ session_id: orphan.session_id,+ composite_key: orphan.composite_key,+ base_session_id: orphan.base_session_id,+ pid: orphan.pid,+ });+ if (result.ok) {+ showToast(t('agents.running.endedToast'), 'success');+ void fetchGraph(true);+ } else {+ showToast(t('agents.running.endFailedToast', { error: result.error || 'failed' }), 'error');+ }+ } catch (err) {+ showToast(err instanceof Error ? err.message : String(err), 'error');+ }+ },+ [api, showToast, t, fetchGraph],+ );++ useEffect(() => {+ void fetchGraph(false);+ }, [fetchGraph]);++ // Realtime: reuse the workbench SSE bus (runs/turn/session events) — no new+ // transport (contract). Refetch in the background on any signal.+ useEffect(() => {+ return api.connectWorkbenchEvents({+ onConnected: (data) => {+ if (data.source === 'controller') {+ setEventBridgeConnected(true);+ void fetchGraph(true);+ }+ },+ onEventBridgeStatus: ({ connected }) => {+ setEventBridgeConnected(connected);+ if (connected) void fetchGraph(true);+ },+ onError: () => setEventBridgeConnected(false),+ onRunsUpdated: () => void fetchGraph(true),+ onTurnStart: () => void fetchGraph(true),+ onTurnEnd: () => void fetchGraph(true),+ onSessionStatus: () => void fetchGraph(true),+ // Visibility/scope/project moves arrive as session.activity — refetch so a+ // session leaves/enters its bucket immediately instead of waiting for the+ // 30s liveness poll.+ onSessionActivity: () => void fetchGraph(true),+ });+ }, [api, fetchGraph]);++ // Low-rate reconciliation poll (orphan/liveness is a sampled snapshot).+ useEffect(() => {+ const intervalMs = eventBridgeConnected ? LIVENESS_POLL_INTERVAL_MS : POLL_INTERVAL_MS;+ let timer: number | undefined;+ let cancelled = false;+ const tick = () => {+ if (cancelled) return;+ if (document.visibilityState === 'visible') void fetchGraph(true);+ timer = window.setTimeout(tick, intervalMs);+ };+ timer = window.setTimeout(tick, intervalMs);+ return () => {+ cancelled = true;+ window.clearTimeout(timer);+ };+ }, [eventBridgeConnected, fetchGraph]);++ // Memoize so the empty-fallback arrays keep a stable identity across renders+ // (they feed downstream useMemo dependency lists).+ const nodes = useMemo(() => graph?.nodes ?? [], [graph]);+ const triggerNodes = useMemo(() => graph?.trigger_nodes ?? [], [graph]);+ const edges = useMemo(() => graph?.edges ?? [], [graph]);++ const nodesById = useMemo(() => new Map(nodes.map((n) => [n.session_id, n])), [nodes]);+ const triggersById = useMemo(+ () => new Map(triggerNodes.map((tr) => [tr.definition_id, tr])),+ [triggerNodes],+ );++ // Drop a stale selection once its node leaves the payload.+ useEffect(() => {+ if (selectedNodeId && !nodesById.has(selectedNodeId)) setSelectedNodeId(null);+ }, [selectedNodeId, nodesById]);++ const selectedNode = selectedNodeId ? nodesById.get(selectedNodeId) ?? null : null;++ const onSelectTrigger = useCallback(+ (definitionId: string) => {+ const tab = triggersById.get(definitionId)?.definition_type === 'watch' ? 'watches' : 'tasks';+ // Land on the matching Harness definitions tab (deep-select by id is a+ // follow-up once Harness supports a ?task/?watch URL anchor).+ navigate(`/harness?tab=${tab}`);+ },+ [navigate, triggersById],+ );++ const projectLabel = useMemo(() => {+ if (projectSel === 'all') return t('agents.graph.filters.projectAll');+ if (projectSel === 'standalone') return t('agents.graph.detail.standalone');+ return projects.find((p) => p.id === projectSel)?.display_name ?? projectSel;+ }, [projectSel, projects, t]);++ const counts = graph?.counts;++ return (+ <div className="flex flex-col gap-4">+ {/* Header strip: subtitle + live pill */}+ <div className="flex flex-wrap items-center gap-3">+ <p className="min-w-0 flex-1 text-[12.5px] text-muted">{t('agents.graph.subtitle')}</p>+ {counts && (+ <span className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-mint/40 bg-mint-soft px-3 py-1 text-[12px] font-semibold text-mint">+ <span className="size-1.5 rounded-full bg-mint" />+ {t('agents.graph.livePill', { active: counts.active, queued: counts.queued })}+ </span>+ )}+ </div>++ {/* Filters */}+ <div className="flex flex-wrap items-center gap-2.5">+ <SegmentedRadio+ value={mode}+ onChange={setMode}+ ariaLabel={t('agents.graph.filters.modeLabel')}+ options={[+ { id: 'active', label: t('agents.graph.filters.active') },+ { id: 'history', label: t('agents.graph.filters.withHistory') },+ ]}+ />+ <FilterDropdown+ icon={<Clock className="size-3 text-muted" />}+ label={t(`agents.graph.window.${windowSel}`)}+ >+ {(close) =>+ GRAPH_WINDOWS.map((w) => (+ <DropdownItem+ key={w}+ active={w === windowSel}+ onClick={() => {+ setWindowSel(w);+ close();+ }}+ >+ {t(`agents.graph.window.${w}`)}+ </DropdownItem>+ ))+ }+ </FilterDropdown>+ <FilterDropdown+ icon={<FolderClosed className="size-3 text-muted" />}+ label={`${t('agents.graph.filters.project')}: ${projectLabel}`}+ >+ {(close) => (+ <>+ {[+ { value: 'all', label: t('agents.graph.filters.projectAll') },+ { value: 'standalone', label: t('agents.graph.detail.standalone') },+ ...projects.map((p) => ({ value: p.id, label: p.display_name })),+ ].map((opt) => (+ <DropdownItem+ key={opt.value}+ active={opt.value === projectSel}+ onClick={() => {+ setProjectSel(opt.value);+ close();+ }}+ >+ {opt.label}+ </DropdownItem>+ ))}+ </>+ )}+ </FilterDropdown>+ <span className="flex-1" />+ <label className="inline-flex items-center gap-2 text-[12px] text-muted">+ {t('agents.graph.filters.showBackground')}+ <Switch checked={showBackground} onCheckedChange={setShowBackground} label={t('agents.graph.filters.showBackground')} />+ </label>+ <Button type="button" variant="outline" size="xs" onClick={() => fetchGraph(false)} disabled={loading}>+ <RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />+ {t('common.refresh')}+ </Button>+ </div>++ {graph?.live_unreachable && (+ <div className="flex items-center gap-2 rounded-lg border border-gold/40 bg-gold/[0.06] px-3 py-2 text-[12px] text-gold">+ <ServerCrash className="size-3.5" />+ {t('agents.graph.unreachable')}+ </div>+ )}++ {graph?.truncated && (+ <div className="flex items-center gap-2 rounded-lg border border-gold/40 bg-gold/[0.06] px-3 py-2 text-[12px] text-gold">+ <AlertTriangle className="size-3.5 shrink-0" />+ {t('agents.graph.truncated')}+ </div>+ )}++ {/* Session-less live processes strip (A3 + r6) — above the graph. */}+ <AgentGraphOrphanStrip rows={orphans} onEnd={killOrphan} />++ {loading && !graph ? (+ <div className="flex items-center justify-center py-16">+ <Loader2 className="size-5 animate-spin text-muted" />+ </div>+ ) : errored && !graph ? (+ <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-amber-500/40 bg-amber-500/[0.04] px-6 py-12 text-center">+ <ServerCrash className="size-8 text-amber-500" />+ <div className="text-[13px] text-muted">{t('agents.graph.error')}</div>+ <Button type="button" variant="outline" size="xs" onClick={() => fetchGraph(false)}>+ <RefreshCw className="size-3.5" />+ {t('common.refresh')}+ </Button>+ </div>+ ) : (+ <div+ className={clsx(+ 'grid gap-4',+ selectedNode ? 'grid-cols-1 lg:grid-cols-[minmax(0,1fr)_360px]' : 'grid-cols-1',+ )}+ >+ <div className={clsx('min-w-0', selectedNode && 'max-lg:hidden')}>+ {nodes.length === 0 ? (+ <div className="rounded-xl border border-dashed border-border bg-surface px-6 py-12 text-center text-[13px] text-muted">+ {t('agents.graph.empty')}+ </div>+ ) : isDesktop ? (+ <AgentGraphCanvas+ nodes={nodes}+ triggerNodes={triggerNodes}+ edges={edges}+ selectedId={selectedNodeId}+ // Refit the viewport when the filters change the layout (small→+ // large graph, different project/window); SSE-only refreshes keep+ // the same key and preserve the current pan/zoom.+ fitKey={`${windowSel}|${projectSel}|${mode}|${showBackground}`}+ onSelectNode={setSelectedNodeId}+ onSelectTrigger={onSelectTrigger}+ onOpenChat={(id) => navigate(`/chat/${encodeURIComponent(id)}`)}+ />+ ) : (+ <AgentGraphMobileList+ nodes={nodes}+ edges={edges}+ triggerNodes={triggerNodes}+ selectedId={selectedNodeId}+ onSelectNode={setSelectedNodeId}+ />+ )}+ </div>++ {selectedNode && (+ <div className="self-start rounded-2xl border border-border-strong bg-surface p-5">+ <AgentGraphDetail+ node={selectedNode}+ nodesById={nodesById}+ edges={edges}+ triggersById={triggersById}+ onClose={() => setSelectedNodeId(null)}+ onSelectNode={setSelectedNodeId}+ onRefresh={() => fetchGraph(true)}+ />+ </div>+ )}+ </div>+ )}+ </div>+ );+};++// ── compact filter dropdown (Popover) — mirrors AgentsPage BackendFilter ──────++interface FilterDropdownProps {+ icon: React.ReactNode;+ label: string;+ children: (close: () => void) => React.ReactNode;+}++const FilterDropdown: React.FC<FilterDropdownProps> = ({ icon, label, children }) => {+ const [open, setOpen] = useState(false);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="flex items-center gap-1.5 rounded-md border border-border-strong bg-surface px-3 py-2 text-[12px] font-medium text-foreground transition hover:bg-foreground/[0.04]"+ >+ {icon}+ <span className="max-w-[160px] truncate">{label}</span>+ <ChevronDown className="size-3 text-muted" />+ </button>+ </PopoverTrigger>+ <PopoverContent align="start" className="max-h-[280px] w-[200px] overflow-y-auto p-1">+ {children(() => setOpen(false))}+ </PopoverContent>+ </Popover>+ );+};++const DropdownItem: React.FC<{ active: boolean; onClick: () => void; children: React.ReactNode }> = ({+ active,+ onClick,+ children,+}) => (+ <button+ type="button"+ onClick={onClick}+ className={clsx(+ 'flex w-full items-center gap-2 truncate rounded px-2 py-1.5 text-left text-[12px] transition',+ active ? 'bg-cyan-soft text-cyan' : 'text-foreground hover:bg-foreground/[0.04]',+ )}+ >+ {children}+ </button>+);diff --git a/ui/src/components/workbench/AgentGraphTriggerChip.tsx b/ui/src/components/workbench/AgentGraphTriggerChip.tsxnew file mode 100644index 000000000..003cc2743--- /dev/null+++ b/ui/src/components/workbench/AgentGraphTriggerChip.tsx@@ -0,0 +1,52 @@+import { useTranslation } from 'react-i18next';+import { CalendarClock, Eye } from 'lucide-react';+import clsx from 'clsx';++import type { AgentGraphTriggerNode } from '../../lib/agentGraph';++interface AgentGraphTriggerChipProps {+ trigger: AgentGraphTriggerNode;+ faded?: boolean;+ onClick?: () => void;+ className?: string;+}++// Task/Watch trigger source — a violet chip that sits left of the session it+// fires (spec frame anu5U). Click jumps to the matching Harness definitions+// tab. Fills its parent so the canvas box + dagre layout stay in lockstep.+export const AgentGraphTriggerChip: React.FC<AgentGraphTriggerChipProps> = ({+ trigger,+ faded = false,+ onClick,+ className,+}) => {+ const { t } = useTranslation();+ const isWatch = trigger.definition_type === 'watch';+ const Icon = isWatch ? Eye : CalendarClock;+ const kindLabel = isWatch ? t('agents.graph.trigger.watch') : t('agents.graph.trigger.task');+ const name = trigger.name?.trim() || trigger.definition_id;++ return (+ <button+ type="button"+ onClick={onClick}+ title={name}+ className={clsx(+ 'flex h-full w-full items-center gap-2 rounded-xl border border-violet/40 bg-violet-soft px-3 py-2 text-left transition hover:brightness-110',+ faded && 'opacity-25',+ className,+ )}+ >+ <span className="flex size-7 shrink-0 items-center justify-center rounded-lg border border-violet/30 bg-violet/[0.12] text-violet">+ <Icon className="size-3.5" />+ </span>+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-[12px] font-semibold text-foreground">{name}</span>+ <span className="truncate font-mono text-[10px] uppercase tracking-wide text-violet">+ {kindLabel}+ {trigger.schedule_label && <span className="text-muted"> · {trigger.schedule_label}</span>}+ </span>+ </div>+ </button>+ );+};diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex faea95b8c..d63afc672 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -23,7 +23,7 @@ import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import type { VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';-import { RunningAgentsTab } from './RunningAgentsTab';+import { AgentGraphTab } from './AgentGraphTab';import { useToast } from '../../context/ToastContext';import { NewAgentDialog } from './NewAgentDialog';import { RunAgentDialog } from './RunAgentDialog';@@ -127,7 +127,11 @@ export const AgentsPage: React.FC = () => {try {const result = await api.getRunningAgents();if (result.ok && result.counts) {- setRunningActiveCount((result.counts as any).active ?? 0);+ // Badge = the true live-session count (active + idle + orphan) from the+ // running-agents snapshot. Deliberately sourced here (not from the graph+ // tab's counts) so it stays independent of the graph's project/time/+ // visibility filters — a narrowed graph must not shrink the badge.+ setRunningActiveCount(result.counts.total ?? 0);} else {setRunningActiveCount(null);}@@ -136,12 +140,13 @@ export const AgentsPage: React.FC = () => {}}, [api]);+ // Keep the badge fresh on every tab (including 运行) so it never depends on+ // the graph view's filters.useEffect(() => {- if (agentsTab !== 'running') void fetchRunningActiveCount();- }, [agentsTab, fetchRunningActiveCount]);+ void fetchRunningActiveCount();+ }, [fetchRunningActiveCount]);useEffect(() => {- if (agentsTab === 'running') return;return api.connectWorkbenchEvents({onConnected: (data) => {if (data.source === 'controller') {@@ -159,10 +164,14 @@ export const AgentsPage: React.FC = () => {onTurnEnd: () => fetchRunningActiveCount(),onSessionStatus: () => fetchRunningActiveCount(),});- }, [api, agentsTab, fetchRunningActiveCount]);+ }, [api, fetchRunningActiveCount]);useEffect(() => {- if (agentsTab === 'running' || eventBridgeConnected) return;+ // Reconcile the badge even while SSE is connected: process death / orphan /+ // reap is a sampled snapshot with no run/session SSE event, so a slow+ // liveness poll keeps the count fresh (30s connected, 8s disconnected),+ // mirroring the old running list.+ const intervalMs = eventBridgeConnected ? 30000 : 8000;let timer: number | undefined;let cancelled = false;let inFlight = false;@@ -171,7 +180,7 @@ export const AgentsPage: React.FC = () => {const tick = async () => {if (cancelled) return;if (document.visibilityState !== 'visible') {- timer = window.setTimeout(tick, 8000);+ timer = window.setTimeout(tick, intervalMs);return;}if (inFlight) {@@ -191,14 +200,14 @@ export const AgentsPage: React.FC = () => {void tick();return;}- timer = window.setTimeout(tick, 8000);+ timer = window.setTimeout(tick, intervalMs);};const refreshNow = () => {if (document.visibilityState === 'visible') void tick();};- void tick();+ timer = window.setTimeout(tick, intervalMs);document.addEventListener('visibilitychange', refreshNow);window.addEventListener('focus', refreshNow);return () => {@@ -207,7 +216,7 @@ export const AgentsPage: React.FC = () => {document.removeEventListener('visibilitychange', refreshNow);window.removeEventListener('focus', refreshNow);};- }, [eventBridgeConnected, agentsTab, fetchRunningActiveCount]);+ }, [eventBridgeConnected, fetchRunningActiveCount]);const selectAgent = useCallback(async (name: string, openDetail = false) => {@@ -254,9 +263,6 @@ export const AgentsPage: React.FC = () => {refresh().then(() => setSelected(agent));};- const handleRunningActiveCountChange = useCallback((count: number | null) => {- setRunningActiveCount(count);- }, []);const updateField = async (patch: Partial<VibeAgentFull>) => {if (!selected) return;@@ -395,8 +401,8 @@ export const AgentsPage: React.FC = () => {})}</div>- {/* Running tab body */}- {agentsTab === 'running' && <RunningAgentsTab onActiveCountChange={handleRunningActiveCountChange} />}+ {/* 运行 tab body — the run graph (replaces the old flat running list). */}+ {agentsTab === 'running' && <AgentGraphTab />}{/* Toolbar — design.pen Imduv: search + backend filter + spacer + Import + 新建 Agent */}<div className={clsx('flex flex-wrap items-center gap-2.5', agentsTab === 'running' ? 'hidden' : detailOpen && 'max-lg:hidden')}>diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsxindex 242446296..598fff51c 100644--- a/ui/src/components/workbench/HarnessPage.tsx+++ b/ui/src/components/workbench/HarnessPage.tsx@@ -1229,6 +1229,66 @@ const RunDetail: React.FC<RunDetailProps> = ({ run }) => {<code className="font-mono text-[11px] text-muted">{run.definition_id}</code></DetailField>)}+ {/* Session + lineage (Part B): the run row already carries these; surface+ them instead of hiding the who-started-whom / where-it-reports story.+ Render the id as plain text — the run payload has no openability flag,+ and a private ``vibe agent run`` session lives on the internal+ private_agent_run pseudo-scope that is intentionally NOT chat-openable,+ so an unconditional /chat link would dead-link. The openable-gated+ chat entry point lives in the Agents 运行 graph detail panel. */}+ {run.session_id && (+ <DetailField label={t('harness.detail.session')}>+ <code className="min-w-0 truncate font-mono text-[11px] text-muted">{run.session_id}</code>+ </DetailField>+ )}+ {(run.source_kind || run.source_actor) && (+ <DetailField label={t('harness.detail.source')}>+ <span className="inline-flex min-w-0 flex-wrap items-center gap-1.5 text-[12px] text-foreground">+ {run.source_kind && (+ <span className="rounded border border-border-strong bg-foreground/[0.04] px-1.5 py-0 font-mono text-[10px] uppercase text-muted">+ {run.source_kind}+ </span>+ )}+ {run.source_actor && (+ // Lineage id only — the run payload carries no openable_in_chat+ // signal, and a stale/imported or internal (non-openable) session+ // id would deep-link to a dead /chat target, so render it plain.+ <span className="font-mono text-[11px] text-muted">{run.source_actor}</span>+ )}+ </span>+ </DetailField>+ )}+ {run.parent_run_id && (+ <DetailField label={t('harness.detail.parentRun')}>+ <Link+ to={`/harness?tab=runs&run=${encodeURIComponent(run.parent_run_id)}`}+ className="inline-flex items-center gap-1 font-mono text-[11px] text-violet hover:underline"+ >+ {run.parent_run_id}+ <ArrowUpRight className="size-3" />+ </Link>+ </DetailField>+ )}+ {run.callback_session_id && (+ <DetailField label={t('harness.detail.callback')}>+ <span className="inline-flex min-w-0 flex-wrap items-center gap-1.5">+ {/* Lineage id only (see source above) — plain text, not a /chat link. */}+ <span className="min-w-0 truncate font-mono text-[11px] text-muted">+ {run.callback_session_id}+ </span>+ {run.callback_status && (+ <span className="rounded border border-border-strong bg-foreground/[0.04] px-1.5 py-0 font-mono text-[10px] uppercase text-muted">+ {run.callback_status}+ </span>+ )}+ </span>+ {run.callback_error && (+ <div className="mt-1 rounded-md border border-destructive/40 bg-destructive/[0.06] px-2 py-1 text-[11px] text-destructive">+ {run.callback_error}+ </div>+ )}+ </DetailField>+ )}{(run.message || run.prompt) && (<DetailField label={t('harness.detail.message')}><pre className="max-h-32 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">diff --git a/ui/src/components/workbench/RunningAgentsTab.tsx b/ui/src/components/workbench/RunningAgentsTab.tsxdeleted file mode 100644index 2777c771a..000000000--- a/ui/src/components/workbench/RunningAgentsTab.tsx+++ /dev/null@@ -1,577 +0,0 @@-import { useCallback, useEffect, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';-import {- Activity,- AlertTriangle,- Bot,- ExternalLink,- Loader2,- MessageSquare,- Power,- RefreshCw,- ServerCrash,- Square,- Trash2,-} from 'lucide-react';-import clsx from 'clsx';-import { Link } from 'react-router-dom';--import { useApi } from '../../context/ApiContext';-import type { RunningAgent } from '../../context/ApiContext';-import { useToast } from '../../context/ToastContext';-import { PlatformIcon } from '../visual/PlatformIcon';-import { Badge } from '../ui/badge';-import { Button } from '../ui/button';-import {- BACKEND_LABEL,- BACKEND_TEXT as BACKEND_ICON_CLASS,- type Backend,-} from '../../lib/backendAccent';--// Degraded-mode refresh cadence while SSE is disconnected.-const POLL_INTERVAL_MS = 4000;-const LIVENESS_POLL_INTERVAL_MS = 30000;-const RENDER_TICK_INTERVAL_MS = 1000;--type DisplayRunningAgent = RunningAgent & {- elapsed_observed_at: number;-};--// Humanize elapsed_seconds: 12 → "12s", 185 → "3m", 3700 → "1h"-function formatElapsed(seconds: number | null): string {- if (seconds == null) return '—';- // Clamp negatives: a malformed/clock-skewed baseline must never read "-3s".- const s = Math.max(0, seconds);- if (s < 60) return `${Math.round(s)}s`;- if (s < 3600) return `${Math.floor(s / 60)}m`;- return `${Math.floor(s / 3600)}h`;-}--// Truncate workdir for display — keep the last two path segments.-function shortWorkdir(workdir: string | null): string {- if (!workdir) return '—';- const parts = workdir.replace(/\/$/, '').split('/');- if (parts.length <= 2) return workdir;- return `…/${parts[parts.length - 2]}/${parts[parts.length - 1]}`;-}--// Stable identity for ordering — must NOT change between polls so rows don't-// visually jump. (Deliberately excludes elapsed_seconds, which ticks every poll.)-function identityKey(a: RunningAgent): string {- return (- (a.session_id ? `${a.backend}:${a.session_id}` : null) ??- a.composite_key ??- `${a.backend}:${a.base_session_id ?? ''}:${a.workdir ?? ''}:${a.pid ?? ''}:${a.native_session_id ?? ''}`- );-}--// Sort: active first, then idle, then orphan; WITHIN a state band order by a-// stable identity (not elapsed) so the list stays put across polls instead of-// reshuffling as durations tick.-function sortAgents(agents: RunningAgent[]): RunningAgent[] {- return [...agents].sort((a, b) => {- const stateRank = (s: string) => (s === 'active' ? 0 : s === 'idle' ? 1 : 2);- const sr = stateRank(a.state) - stateRank(b.state);- if (sr !== 0) return sr;- return identityKey(a).localeCompare(identityKey(b));- });-}--function currentElapsedSeconds(agent: DisplayRunningAgent, now: number): number | null {- if (agent.elapsed_seconds == null) return null;- const age = Math.max(0, (now - agent.elapsed_observed_at) / 1000);- return agent.elapsed_seconds + age;-}--// Per-state presentation, in one place: the state dot/badge AND the End button-// label/icon/confirm-policy all key off this map instead of parallel ternaries.-type RunState = 'active' | 'idle' | 'orphan';-const STATE_META: Record<- RunState,- {- dotClass: string;- badgeVariant: 'success' | 'secondary' | 'warning';- stateKey: string;- endKey: string;- EndIcon: React.ComponentType<{ className?: string }>;- needsConfirm: boolean;- }-> = {- active: { dotClass: 'bg-mint', badgeVariant: 'success', stateKey: 'agents.running.stateActive', endKey: 'agents.running.endActive', EndIcon: Square, needsConfirm: true },- idle: { dotClass: 'bg-muted', badgeVariant: 'secondary', stateKey: 'agents.running.stateIdle', endKey: 'agents.running.endIdle', EndIcon: Power, needsConfirm: false },- orphan: { dotClass: 'bg-amber-500', badgeVariant: 'warning', stateKey: 'agents.running.stateOrphan', endKey: 'agents.running.endOrphan', EndIcon: Trash2, needsConfirm: true },-};-const stateMeta = (state: string) => STATE_META[(state as RunState)] ?? STATE_META.idle;--interface RunningAgentsTabProps {- onActiveCountChange?: (count: number | null) => void;-}--export const RunningAgentsTab: React.FC<RunningAgentsTabProps> = ({ onActiveCountChange }) => {- const { t } = useTranslation();- const api = useApi();- const { showToast } = useToast();- const [agents, setAgents] = useState<DisplayRunningAgent[]>([]);- const [renderNow, setRenderNow] = useState(() => Date.now());- const [unreachable, setUnreachable] = useState(false);- const [loading, setLoading] = useState(true);- const [eventBridgeConnected, setEventBridgeConnected] = useState(false);- // Guards against setState after unmount: an in-flight poll can resolve after- // the user leaves the Running tab (the component unmounts) — without this the- // resolved fetch would call setState on an unmounted component.- const mountedRef = useRef(true);- useEffect(() => {- mountedRef.current = true;- return () => {- mountedRef.current = false;- };- }, []);-- const fetchData = useCallback(- async (isBackground = false) => {- if (!isBackground) setLoading(true);- try {- const result = await api.getRunningAgents();- if (!mountedRef.current) return;- if (!result.ok && result.unreachable) {- setUnreachable(true);- setAgents([]);- onActiveCountChange?.(null);- } else {- const observedAt = Date.now();- setUnreachable(false);- setRenderNow(observedAt);- setAgents(sortAgents(result.agents ?? []).map((agent) => ({ ...agent, elapsed_observed_at: observedAt })));- onActiveCountChange?.((result.counts as any)?.active ?? 0);- }- } catch {- // Any unexpected fetch failure (network/401/non-JSON) means we cannot- // trust the list — surface the explicit unreachable state (I1) rather- // than silently leaving stale rows with no indication.- if (mountedRef.current) {- setUnreachable(true);- setAgents([]);- onActiveCountChange?.(null);- }- } finally {- if (mountedRef.current && !isBackground) setLoading(false);- }- },- [api, onActiveCountChange],- );-- // End a running agent's live runtime, dispatched controller-side by- // backend+state (active→interrupt+disconnect, idle→disconnect, orphan→kill- // process). Best-effort: refresh right after so the row reflects the change- // (the next poll reconciles authoritatively anyway).- const endAgent = useCallback(- async (agent: RunningAgent) => {- let result: Awaited<ReturnType<typeof api.endRunningAgent>> | undefined;- try {- result = await api.endRunningAgent({- backend: agent.backend,- state: agent.state,- session_id: agent.session_id,- composite_key: agent.composite_key,- base_session_id: agent.base_session_id,- pid: agent.pid,- });- } catch (err) {- // A network failure shouldn't bubble into an unhandled rejection.- console.warn('running-agents: end failed', err);- }- // Always give the user feedback — silence reads as "nothing happened".- if (result?.ok) {- showToast(t('agents.running.endedToast'), 'success');- } else {- const reason = result?.error || (result?.unreachable ? 'unreachable' : 'failed');- showToast(t('agents.running.endFailedToast', { error: reason }), 'error');- }- if (mountedRef.current) await fetchData(true);- },- [api, fetchData, showToast, t],- );-- useEffect(() => {- fetchData(false);- }, [fetchData]);-- useEffect(() => {- return api.connectWorkbenchEvents({- onConnected: (data) => {- if (data.source === 'controller') {- setEventBridgeConnected(true);- fetchData(true);- }- },- onEventBridgeStatus: ({ connected }) => {- setEventBridgeConnected(connected);- if (connected) fetchData(true);- },- onError: () => setEventBridgeConnected(false),- onRunsUpdated: () => fetchData(true),- onTurnStart: () => fetchData(true),- onTurnEnd: () => fetchData(true),- onSessionStatus: () => fetchData(true),- });- }, [api, fetchData]);-- const hasElapsedRows = agents.some((agent) => agent.elapsed_seconds != null);- useEffect(() => {- if (!hasElapsedRows) return;- const timer = window.setInterval(() => setRenderNow(Date.now()), RENDER_TICK_INTERVAL_MS);- return () => window.clearInterval(timer);- }, [hasElapsedRows]);-- // SSE covers lifecycle writes, and the render ticker covers elapsed labels.- // External process death/orphan detection is a sampled snapshot, so keep a- // low-rate reconciliation poll only while visible rows can go stale.- useEffect(() => {- const intervalMs = eventBridgeConnected ? LIVENESS_POLL_INTERVAL_MS : POLL_INTERVAL_MS;- if (eventBridgeConnected && agents.length === 0) return;- let timer: number | undefined;- let cancelled = false;- let inFlight = false;- let pendingWake = false;-- const tick = async () => {- if (cancelled) return;- if (document.visibilityState !== 'visible') {- timer = window.setTimeout(tick, intervalMs);- return;- }- if (inFlight) {- pendingWake = true;- return;- }- inFlight = true;- window.clearTimeout(timer);- try {- await fetchData(true);- } finally {- inFlight = false;- }- if (cancelled) return;- if (pendingWake) {- pendingWake = false;- void tick();- return;- }- timer = window.setTimeout(tick, intervalMs);- };-- const refreshNow = () => {- if (document.visibilityState === 'visible') void tick();- };-- void tick();- document.addEventListener('visibilitychange', refreshNow);- window.addEventListener('focus', refreshNow);- return () => {- cancelled = true;- window.clearTimeout(timer);- document.removeEventListener('visibilitychange', refreshNow);- window.removeEventListener('focus', refreshNow);- };- }, [agents.length, eventBridgeConnected, fetchData]);-- if (loading) {- return (- <div className="flex items-center justify-center py-16">- <Loader2 className="size-5 animate-spin text-muted" />- </div>- );- }-- if (unreachable) {- return (- <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-amber/40 bg-amber/[0.04] px-6 py-12 text-center">- <ServerCrash className="size-8 text-amber-500" />- <div className="text-[14px] font-semibold text-foreground">- {t('agents.running.unreachableTitle')}- </div>- <div className="max-w-sm text-[12px] text-muted">{t('agents.running.unreachableBody')}</div>- <Button- type="button"- variant="outline"- size="xs"- onClick={() => fetchData(false)}- className="mt-2"- >- <RefreshCw className="size-3.5" />- {t('common.refresh')}- </Button>- </div>- );- }-- if (agents.length === 0) {- return (- <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-border bg-surface px-6 py-12 text-center">- <Activity className="size-8 text-muted" />- <div className="text-[13px] text-muted">{t('agents.running.empty')}</div>- <Button- type="button"- variant="outline"- size="xs"- onClick={() => fetchData(false)}- className="mt-1"- >- <RefreshCw className="size-3.5" />- {t('common.refresh')}- </Button>- </div>- );- }-- return (- <div className="flex flex-col gap-3">- {/* Header row with manual refresh */}- <div className="flex items-center justify-end">- <Button type="button" variant="outline" size="xs" onClick={() => fetchData(false)}>- <RefreshCw className="size-3.5" />- {t('common.refresh')}- </Button>- </div>-- {agents.map((agent) => (- <RunningAgentRow- // Stable identity (survives re-sorts so React doesn't remount rows) —- // same key the sort uses; no positional index.- key={identityKey(agent)}- agent={agent}- renderNow={renderNow}- onEnd={endAgent}- />- ))}- </div>- );-};--// ----------------------------------------------------------------------------// One row / card per running agent session-// -----------------------------------------------------------------------------interface RunningAgentRowProps {- agent: DisplayRunningAgent;- renderNow: number;- onEnd: (agent: RunningAgent) => Promise<void>;-}--const RunningAgentRow: React.FC<RunningAgentRowProps> = ({ agent, renderNow, onEnd }) => {- const { t } = useTranslation();- const isOrphan = agent.state === 'orphan';- const [ending, setEnding] = useState(false);- // Two-step confirm for destructive ends (active loses in-flight work; orphan- // sends SIGTERM/SIGKILL). Idle disconnect is harmless (session is re-creatable)- // so it ends on the first click.- const [armed, setArmed] = useState(false);- const rowMounted = useRef(true);- const disarmTimer = useRef<number | null>(null);- useEffect(() => () => {- rowMounted.current = false;- if (disarmTimer.current != null) window.clearTimeout(disarmTimer.current);- }, []);-- // Per-state End presentation (Stop / Disconnect / Kill) + confirm policy.- const meta = stateMeta(agent.state);- const needsConfirm = meta.needsConfirm;- const endLabel = t(meta.endKey);- const EndIcon = meta.EndIcon;-- const runEnd = async () => {- setArmed(false);- if (disarmTimer.current != null) window.clearTimeout(disarmTimer.current);- setEnding(true);- try {- await onEnd(agent);- } finally {- if (rowMounted.current) setEnding(false);- }- };-- const handleEndClick = () => {- if (ending) return;- if (needsConfirm && !armed) {- setArmed(true);- if (disarmTimer.current != null) window.clearTimeout(disarmTimer.current);- disarmTimer.current = window.setTimeout(() => {- if (rowMounted.current) setArmed(false);- }, 3000);- return;- }- void runEnd();- };-- const backendLabel =- BACKEND_LABEL[agent.backend as Backend] ?? agent.backend;- const backendClass =- BACKEND_ICON_CLASS[agent.backend as Backend] ?? 'text-muted';- const elapsedSeconds = currentElapsedSeconds(agent, renderNow);-- const canOpenChat = agent.openable_in_chat && !!agent.session_id;-- return (- <div- className={clsx(- 'flex min-w-0 flex-col gap-2 rounded-xl border px-4 py-3 transition',- isOrphan- ? 'border-amber/40 bg-amber/[0.04]'- : 'border-border bg-surface',- )}- >- {/* ── Row top: backend · state dot · elapsed · platform · chat link ── */}- <div className="flex min-w-0 flex-wrap items-center gap-2">- {/* Backend badge */}- <span className={clsx('font-mono text-[11px] font-bold uppercase tracking-wide', backendClass)}>- {backendLabel}- </span>-- {/* State indicator */}- <StateDot state={agent.state} t={t} />-- {/* Elapsed — "busy {{elapsed}}" while a turn is in flight (the backend- anchors this to the turn-start baseline, not last-chunk time), else- "idle {{elapsed}}". */}- {elapsedSeconds != null && (- <span className="font-mono text-[11px] text-muted">- {t(- agent.state === 'active'- ? 'agents.running.busy'- : 'agents.running.idleElapsed',- { elapsed: formatElapsed(elapsedSeconds) },- )}- </span>- )}-- {/* Orphan label */}- {isOrphan && (- <Badge variant="warning" className="font-mono text-[9px] uppercase">- <AlertTriangle className="size-2.5" />- {t('agents.running.orphan')}- </Badge>- )}-- {/* Spacer */}- <div className="flex-1" />-- {/* Chat link — IM (slack/discord/…) sessions included; when a row has no- openable session we render nothing at all (no "unavailable" label). */}- {canOpenChat && (- <Link- to={`/chat/${encodeURIComponent(agent.session_id ?? '')}`}- className="inline-flex shrink-0 items-center gap-1 text-[11px] font-medium text-cyan hover:underline"- >- <MessageSquare className="size-3" />- {t('agents.running.openChat')}- <ExternalLink className="size-2.5" />- </Link>- )}-- {/* Unified End — terminates this agent's live runtime, dispatched by- state: Stop (active) / Disconnect (idle) / Kill process (orphan).- Destructive ends (active/orphan) require a 2nd confirming click. */}- <Button- type="button"- variant={armed ? 'destructive' : 'destructive-soft'}- size={armed ? 'xs' : 'icon'}- onClick={handleEndClick}- disabled={ending}- aria-label={armed ? t('agents.running.confirmEnd') : endLabel}- title={armed ? t('agents.running.confirmEnd') : endLabel}- className={clsx('shrink-0', armed ? 'h-7' : 'size-7')}- >- {ending ? (- <Loader2 className="size-3.5 animate-spin" />- ) : armed ? (- t('agents.running.confirmEnd')- ) : (- <EndIcon className="size-3.5" />- )}- </Button>- </div>-- {/* ── Row bottom: title · platform/scope · workdir · model · pid ── */}- <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted">- {/* Title */}- {agent.title && (- <span className="min-w-0 max-w-[200px] truncate font-medium text-foreground" title={agent.title}>- {agent.title}- </span>- )}-- {/* Origin: agent-initiated private runs have no IM platform — label them- explicitly as "agent" + the run name; otherwise show platform/scope. */}- {agent.trigger_source === 'agent' ? (- <span className="inline-flex shrink-0 items-center gap-1 text-violet">- <Bot className="size-3" />- <span className="uppercase tracking-wide">{t('agents.running.agentInitiated')}</span>- {agent.scope_display_name && (- <span className="max-w-[140px] truncate text-muted" title={agent.scope_display_name}>- · {agent.scope_display_name}- </span>- )}- </span>- ) : agent.platform ? (- <span className="inline-flex shrink-0 items-center gap-1">- <PlatformIcon platform={agent.platform as any} size={12} />- <span className="uppercase tracking-wide">{agent.platform}</span>- {agent.scope_type && <span>·</span>}- {agent.scope_type && <span>{agent.scope_type}</span>}- {agent.scope_display_name && (- <span className="max-w-[120px] truncate" title={agent.scope_display_name}>- · {agent.scope_display_name}- </span>- )}- </span>- ) : null}-- {/* Workdir */}- {agent.workdir && (- <span- className="max-w-[180px] truncate font-mono text-[10px]"- title={agent.workdir}- >- {shortWorkdir(agent.workdir)}- </span>- )}-- {/* Model */}- {agent.model && (- <span className="max-w-[160px] shrink-0 truncate font-mono text-[10px]" title={agent.model}>- {agent.model}- </span>- )}-- {/* PID — omit for opencode, omit if null */}- {agent.backend !== 'opencode' && typeof agent.pid === 'number' && (- <span className="shrink-0 font-mono text-[10px]">- pid {agent.pid}- {agent.pid_shared && (- <span className="ml-1 text-amber-500">{t('agents.running.pidShared')}</span>- )}- </span>- )}-- {/* Agent name */}- {agent.agent_name && (- <span className="shrink-0 text-[10px]">{agent.agent_name}</span>- )}- </div>- </div>- );-};--// ----------------------------------------------------------------------------// State dot: colored circle + label-// -----------------------------------------------------------------------------const StateDot: React.FC<{ state: string; t: (k: string) => string }> = ({ state, t }) => {- const meta = stateMeta(state);- return (- <Badge variant={meta.badgeVariant} className="font-mono text-[9px] uppercase">- <span className={clsx('size-1.5 rounded-full', meta.dotClass)} />- {t(meta.stateKey)}- </Badge>- );-};diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 30443a354..2e8f30833 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';import { useToast } from './ToastContext';import { apiFetch } from '../lib/apiFetch';import type { TurnActivityGroupWire } from '../lib/agentActivity';+import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';import {WorkbenchEventReconnectLoop,@@ -609,7 +610,7 @@ export type ApiContextType = {getTurnState: (sessionId: string, options?: { handleError?: boolean }) => Promise<SessionRuntimeState>;getSessionDraft: (sessionId: string) => Promise<{ text: string }>;setSessionDraft: (sessionId: string, text: string) => Promise<{ ok: boolean }>;- listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; cache?: boolean; handleError?: boolean }) => Promise<InboxFeedResult>;+ listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; onlySession?: string; cache?: boolean; handleError?: boolean }) => Promise<InboxFeedResult>;connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;listVibeAgents: (params?: { backend?: string; includeDisabled?: boolean }) => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;getVibeAgent: (name: string) => Promise<{ ok: boolean; agent: VibeAgentFull; default_agent_name: string | null }>;@@ -676,6 +677,13 @@ export type ApiContextType = {listHarnessRuns: (params?: HarnessRunsParams) => Promise<HarnessRunsResult>;getHarnessRun: (runId: string) => Promise<{ ok: boolean; run: HarnessRun }>;getRunningAgents: () => Promise<RunningAgentsResult>;+ // Agents · 运行图 graph payload (contract §3). Realtime — refetched off SSE,+ // so it bypasses the read cache. ``live_unreachable`` is set when the+ // controller is down and the graph fell back to DB-only (history).+ getAgentsGraph: (params?: AgentGraphParams) => Promise<AgentGraphResult & { live_unreachable?: boolean }>;+ // Foreground/background toggle from the graph detail panel (contract §2,+ // M1-owned PATCH). Returns the updated session payload.+ setSessionVisibility: (sessionId: string, visibility: AgentGraphVisibility) => Promise<WorkbenchSession>;endRunningAgent: (payload: {backend?: string | null;state?: string | null;@@ -921,7 +929,16 @@ export type WorkbenchEventHandlers = {onConnectionState?: (state: WorkbenchEventConnectionState) => void;onEventBridgeStatus?: (data: { connected: boolean }) => void;onMessageNew?: (data: WorkbenchMessage) => void;- onSessionActivity?: (data: { session_id: string; scope_id: string | null; event: string; title?: string | null }) => void;+ // ``visibility`` (contract A6): the backend carries the session's current+ // foreground/background on visibility/scope changes so the Inbox can drop /+ // restore the card live. Absent on pre-M1 backends ⇒ consumers no-op.+ onSessionActivity?: (data: {+ session_id: string;+ scope_id: string | null;+ event: string;+ title?: string | null;+ visibility?: 'foreground' | 'background';+ }) => void;onInboxUnreadChanged?: (data: {session_id?: string;scope_id?: string | null;@@ -1221,6 +1238,12 @@ export type HarnessRun = {source_kind: string | null;source_actor: string | null;parent_run_id: string | null;+ // Callback (report-back) lineage — serialized by the backend run row but+ // previously unrendered; the run detail surfaces these (Part B).+ callback_session_id: string | null;+ callback_run_id: string | null;+ callback_status: string | null;+ callback_error: string | null;agent_name: string | null;agent_id: string | null;agent_backend: string | null;@@ -2625,6 +2648,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenif (params?.unreadOnly) search.set('unread_only', '1');if (params?.limit) search.set('limit', String(params.limit));if (params?.before) search.set('before', params.before);+ if (params?.onlySession) search.set('session', params.onlySession);const qs = search.toString();const path = qs ? `/api/inbox?${qs}` : '/api/inbox';const options = { handleError: params?.handleError };@@ -2841,6 +2865,17 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children}};},+ getAgentsGraph: (params) => {+ const search = new URLSearchParams();+ if (params?.window) search.set('window', params.window);+ if (params?.project) search.set('project', params.project);+ if (params?.includeEnded === false) search.set('include_ended', '0');+ if (params?.includeBackground === false) search.set('include_background', '0');+ const qs = search.toString();+ return getJson(qs ? `/api/agents-graph?${qs}` : '/api/agents-graph');+ },+ setSessionVisibility: (sessionId, visibility) =>+ patchJson(`/api/sessions/${encodeURIComponent(sessionId)}`, { visibility }),getRunningAgents: async () => {const res = await apiFetch('/api/running-agents');// 503/504 means controller is down; surface as unreachable instead of throwing.diff --git a/ui/src/context/WorkbenchInboxContext.tsx b/ui/src/context/WorkbenchInboxContext.tsxindex 1c51aee75..a2dcb42f3 100644--- a/ui/src/context/WorkbenchInboxContext.tsx+++ b/ui/src/context/WorkbenchInboxContext.tsx@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';import { useApi } from './ApiContext';import type { InboxSession } from './ApiContext';+import { sessionActivityInboxAction } from '../lib/inboxActivity';const PAGE_SIZE = 30;@@ -187,6 +188,31 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>}}, [api, applyUnreadMap]);+ // Targeted reconcile for one session (contract A6 foreground restore): fetch+ // that exact session by id and upsert its card, so a restored session+ // reappears even when its activity sorts past the windowed reconcile()'s+ // newest-N rows. The response still carries the pagination-independent+ // whole-account unread map, so refresh that too. Never touches the cursor.+ const reconcileSession = useCallback(+ async (sessionId: string) => {+ try {+ const result = await api.listInbox({+ platform: 'avibe',+ onlySession: sessionId,+ limit: 1,+ cache: false,+ handleError: false,+ });+ const row = result.sessions.find((s) => s.session_id === sessionId);+ if (row) setInboxSessions((prev) => upsertSession(prev, row));+ applyUnreadMap(result.unread_by_session ?? {});+ } catch (err) {+ console.error('[inbox] reconcileSession failed', err);+ }+ },+ [api, applyUnreadMap],+ );+useEffect(() => {// First mount loads page one; every later rerun reconciles the loaded window// instead when an ``api`` identity change rebuilds the value — so@@ -217,9 +243,19 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>}},onSessionActivity: (data) => {- // Terminal archive (here or in another tab) — drop the card + its unread- // live, instead of waiting for the next reconnect/refresh to filter it.- if (data.event !== 'archived') return;+ // Contract A6: react to visibility/scope changes carried on the event.+ // background ⇒ drop the card (like an archive); foreground ⇒ fetch that+ // exact session and upsert its card so it reappears even if it sorts past+ // the reconcile window; no visibility ⇒ no-op except an explicit archive.+ // See lib/inboxActivity.+ const action = sessionActivityInboxAction(data);+ if (action === 'reconcile') {+ void reconcileSession(data.session_id);+ return;+ }+ if (action === 'ignore') return;+ // action === 'drop': remove the card + its unread live, instead of+ // waiting for the next reconnect/refresh to filter it.setInboxSessions((prev) => prev.filter((s) => s.session_id !== data.session_id));setUnreadBySession((prev) => {if (!(data.session_id in prev)) return prev;@@ -235,7 +271,7 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>},});return disconnect;- }, [api, refresh, reconcile, applyUnreadMap]);+ }, [api, refresh, reconcile, reconcileSession, applyUnreadMap]);// Recover after the OS suspended us. A backgrounded mobile PWA has its page// frozen and its SSE socket dropped, and the broker never replays the gap;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 03522df3b..777da65a4 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1906,7 +1906,7 @@"subtitle": "{{count}} agents registered across all backends.","tabs": {"definitions": "Definitions",- "running": "Running"+ "running": "Runs"},"running": {"empty": "No agents are currently running.",@@ -1928,6 +1928,81 @@"endFailedToast": "Couldn't end ({{error}})","pidShared": "(shared)"},+ "graph": {+ "subtitle": "Who started whom, who reports back — click a node for details, double-click to open the chat.",+ "livePill": "{{active}} running · {{queued}} queued",+ "empty": "No sessions in this view yet.",+ "error": "Couldn't load the run graph.",+ "unreachable": "Runtime unreachable — showing history only.",+ "truncated": "Showing the most recent 300 sessions — narrow the filters to see the rest.",+ "orphans": {+ "title": "{{count}} unattributed process(es)",+ "description": "Live runtimes with no session — not shown as graph nodes. End them here."+ },+ "filters": {+ "modeLabel": "Time range",+ "active": "Active",+ "withHistory": "With history",+ "project": "Project",+ "projectAll": "All",+ "showBackground": "Show background sessions"+ },+ "window": {+ "1h": "Last 1h",+ "6h": "Last 6h",+ "24h": "Last 24h",+ "7d": "Last 7d"+ },+ "trigger": {+ "task": "Task",+ "watch": "Watch"+ },+ "legend": {+ "spawn": "Spawn",+ "callback": "Callback",+ "trigger": "Task / Watch",+ "background": "Background"+ },+ "status": {+ "active": "running",+ "idle": "idle",+ "orphan": "orphan",+ "queued": "queued",+ "succeeded": "done",+ "failed": "failed",+ "canceled": "canceled"+ },+ "detail": {+ "background": "Background",+ "foreground": "Foreground",+ "standalone": "Standalone",+ "project": "Project",+ "workdir": "Workdir",+ "visibility": "Visibility",+ "visibilityForeground": "Foreground",+ "visibilityBackground": "Background · hidden from lists",+ "startedBy": "Started by",+ "reportsTo": "Reports to",+ "trigger": "Trigger",+ "triggerAgentRun": "agent · vibe agent run",+ "triggerHuman": "human",+ "callback": {+ "pending": "callback pending",+ "sent": "callback sent",+ "failed": "callback failed",+ "skipped": "callback skipped"+ },+ "runsTitle": "Runs · this session",+ "viewAllInHarness": "View all in Harness",+ "openChat": "Open chat · view transcript",+ "toForeground": "Move to foreground",+ "toBackground": "Hide",+ "cancelRun": "Cancel run",+ "movedForeground": "Moved to foreground",+ "movedBackground": "Moved to background",+ "endGone": "This session is no longer live."+ }+ },"showDisabled": "Show disabled","statusEnabled": "enabled","statusDisabled": "disabled",@@ -2206,6 +2281,9 @@"openInAgents": "Open in Agents","agentInherit": "Inherits default agent","sessionNone": "No bound session",+ "source": "Source",+ "parentRun": "Parent run",+ "callback": "Callback","effort": "effort {{value}}"},"sessionPolicy": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 1e7455094..e84569f3a 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1906,7 +1906,7 @@"subtitle": "已登记 {{count}} 个 Agent。","tabs": {"definitions": "定义",- "running": "运行中"+ "running": "运行"},"running": {"empty": "当前没有正在运行的 Agent。",@@ -1928,6 +1928,81 @@"endFailedToast": "无法结束({{error}})","pidShared": "(共享)"},+ "graph": {+ "subtitle": "谁启动了谁、向谁汇报 — 点节点看详情,双击进入会话。",+ "livePill": "{{active}} 个运行中 · {{queued}} 排队",+ "empty": "该视图暂无会话。",+ "error": "无法加载运行图。",+ "unreachable": "运行时不可达 — 仅显示历史。",+ "truncated": "仅显示最近 300 个会话 — 收窄筛选条件可查看其余。",+ "orphans": {+ "title": "{{count}} 个会话外进程",+ "description": "无法归属到会话的运行时,不作为图节点显示,可在此结束。"+ },+ "filters": {+ "modeLabel": "时间范围",+ "active": "活跃",+ "withHistory": "含历史",+ "project": "项目",+ "projectAll": "全部",+ "showBackground": "显示后台会话"+ },+ "window": {+ "1h": "近 1 小时",+ "6h": "近 6 小时",+ "24h": "近 24 小时",+ "7d": "近 7 天"+ },+ "trigger": {+ "task": "TASK",+ "watch": "WATCH"+ },+ "legend": {+ "spawn": "启动",+ "callback": "汇报 / callback",+ "trigger": "Task / Watch 触发",+ "background": "后台会话"+ },+ "status": {+ "active": "运行中",+ "idle": "空闲",+ "orphan": "孤儿",+ "queued": "排队",+ "succeeded": "已完成",+ "failed": "失败",+ "canceled": "已取消"+ },+ "detail": {+ "background": "后台",+ "foreground": "前台",+ "standalone": "独立",+ "project": "项目",+ "workdir": "工作目录",+ "visibility": "可见性",+ "visibilityForeground": "前台",+ "visibilityBackground": "后台 · 不在会话列表",+ "startedBy": "启动方",+ "reportsTo": "汇报到",+ "trigger": "触发",+ "triggerAgentRun": "agent · vibe agent run",+ "triggerHuman": "人工发起",+ "callback": {+ "pending": "待回传",+ "sent": "已回传",+ "failed": "回传失败",+ "skipped": "已跳过"+ },+ "runsTitle": "RUNS · 本会话",+ "viewAllInHarness": "在 Harness 查看全部",+ "openChat": "打开会话 · 查看 Chat 记录",+ "toForeground": "移到前台",+ "toBackground": "隐藏",+ "cancelRun": "取消 Run",+ "movedForeground": "已移到前台",+ "movedBackground": "已移到后台",+ "endGone": "该会话已不在运行。"+ }+ },"showDisabled": "显示已禁用","statusEnabled": "已启用","statusDisabled": "已停用",@@ -2206,6 +2281,9 @@"openInAgents": "在 Agents 打开","agentInherit": "继承默认 Agent","sessionNone": "未绑定会话",+ "source": "来源",+ "parentRun": "父 Run",+ "callback": "回传","effort": "推理 {{value}}"},"sessionPolicy": {diff --git a/ui/src/lib/agentGraph.test.ts b/ui/src/lib/agentGraph.test.tsnew file mode 100644index 000000000..946cc8e66--- /dev/null+++ b/ui/src/lib/agentGraph.test.ts@@ -0,0 +1,150 @@+import { describe, expect, it } from 'vitest';++import {+ type AgentGraphEdge,+ type AgentGraphNode,+ type AgentGraphTriggerNode,+ buildGraphForest,+ deriveLineage,+ formatElapsed,+ isBackground,+ nodeDisplayTitle,+ statusMeta,+} from './agentGraph';++function node(id: string, over: Partial<AgentGraphNode> = {}): AgentGraphNode {+ return {+ session_id: id,+ title: null,+ agent_name: 'claude',+ agent_backend: 'claude',+ model: null,+ reasoning_effort: null,+ status: 'idle',+ live: false,+ scope_id: null,+ project_id: null,+ scope_label: null,+ platform: null,+ workdir: null,+ openable_in_chat: true,+ created_at: '2026-07-23T00:00:00Z',+ last_active_at: '2026-07-23T00:00:00Z',+ elapsed_seconds: null,+ run_counts: { total: 0, running: 0 },+ ...over,+ };+}++const trigger: AgentGraphTriggerNode = {+ definition_id: 'def_1',+ definition_type: 'scheduled',+ name: 'Daily',+ schedule_label: 'cron 10:17',+ enabled: true,+};++describe('formatElapsed', () => {+ it('humanizes seconds/minutes/hours', () => {+ expect(formatElapsed(12)).toBe('12s');+ expect(formatElapsed(185)).toBe('3m');+ expect(formatElapsed(3700)).toBe('1h');+ expect(formatElapsed(null)).toBe('—');+ expect(formatElapsed(-5)).toBe('0s');+ });+});++describe('nodeDisplayTitle', () => {+ it('prefers the title, else agent + session suffix', () => {+ expect(nodeDisplayTitle(node('ses_abc', { title: 'Root' }))).toBe('Root');+ expect(nodeDisplayTitle(node('ses_123456', { title: null, agent_name: 'pm' }))).toBe('pm · 123456');+ });+});++describe('statusMeta / isBackground', () => {+ it('maps status to tone + glyph', () => {+ expect(statusMeta('active').glyph).toBe('dot');+ expect(statusMeta('succeeded').glyph).toBe('check');+ expect(statusMeta('failed').glyph).toBe('cross');+ expect(statusMeta('failed').tone).toBe('destructive');+ });+ it('treats absent visibility as foreground', () => {+ expect(isBackground(node('a'))).toBe(false);+ expect(isBackground(node('a', { visibility: 'background' }))).toBe(true);+ });+});++describe('deriveLineage', () => {+ const edges: AgentGraphEdge[] = [+ { kind: 'spawn', from: 'root', to: 'child', run_count: 1, last_at: '2026-07-23T01:00:00Z' },+ { kind: 'spawn', from: 'root2', to: 'child', run_count: 1, last_at: '2026-07-23T02:00:00Z' },+ { kind: 'callback', from: 'child', to: 'root', status: 'pending', last_at: '2026-07-23T02:00:00Z' },+ { kind: 'trigger', from: 'def:def_1', to: 'child', run_count: 3, last_at: '2026-07-23T00:30:00Z' },+ ];+ const triggersById = new Map([[trigger.definition_id, trigger]]);++ it('picks the latest spawn caller, the callback target+status, and the trigger', () => {+ const lineage = deriveLineage('child', edges, triggersById);+ expect(lineage.spawnedBy).toBe('root2'); // newest spawn edge in+ expect(lineage.callbackTo).toBe('root');+ expect(lineage.callbackStatus).toBe('pending');+ expect(lineage.trigger?.definition_id).toBe('def_1');+ });++ it('returns nulls for an unconnected node', () => {+ const lineage = deriveLineage('orphan', edges, triggersById);+ expect(lineage).toEqual({ spawnedBy: null, callbackTo: null, callbackStatus: null, trigger: null });+ });+});++describe('buildGraphForest', () => {+ it('nests children under their spawn parent with increasing depth', () => {+ const nodes = [node('root', { live: true }), node('a'), node('b')];+ const edges: AgentGraphEdge[] = [+ { kind: 'spawn', from: 'root', to: 'a' },+ { kind: 'spawn', from: 'a', to: 'b' },+ ];+ const rows = buildGraphForest(nodes, edges);+ expect(rows.map((r) => [r.node.session_id, r.depth])).toEqual([+ ['root', 0],+ ['a', 1],+ ['b', 2],+ ]);+ });++ it('attaches a trigger to its target session', () => {+ const nodes = [node('t')];+ const edges: AgentGraphEdge[] = [{ kind: 'trigger', from: 'def:def_1', to: 't' }];+ const rows = buildGraphForest(nodes, edges, [trigger]);+ expect(rows[0].trigger?.definition_id).toBe('def_1');+ });++ it('keeps the latest trigger per session by last_at', () => {+ const nodes = [node('t')];+ const tr2: AgentGraphTriggerNode = { ...trigger, definition_id: 'def_2', name: 'Newer' };+ const edges: AgentGraphEdge[] = [+ { kind: 'trigger', from: 'def:def_1', to: 't', last_at: '2026-07-23T00:00:00Z' },+ { kind: 'trigger', from: 'def:def_2', to: 't', last_at: '2026-07-23T05:00:00Z' },+ ];+ expect(buildGraphForest(nodes, edges, [trigger, tr2])[0].trigger?.definition_id).toBe('def_2');+ // Order-independent: the newest wins regardless of edge iteration order.+ expect(buildGraphForest(nodes, [...edges].reverse(), [trigger, tr2])[0].trigger?.definition_id).toBe('def_2');+ });++ it('guards cycles so every node appears exactly once', () => {+ const nodes = [node('x'), node('y')];+ const edges: AgentGraphEdge[] = [+ { kind: 'spawn', from: 'x', to: 'y' },+ { kind: 'spawn', from: 'y', to: 'x' },+ ];+ const rows = buildGraphForest(nodes, edges);+ expect(rows).toHaveLength(2);+ expect(new Set(rows.map((r) => r.node.session_id))).toEqual(new Set(['x', 'y']));+ });++ it('orders roots live-first', () => {+ const nodes = [node('old', { live: false }), node('hot', { live: true })];+ const rows = buildGraphForest(nodes, []);+ expect(rows[0].node.session_id).toBe('hot');+ });+});diff --git a/ui/src/lib/agentGraph.ts b/ui/src/lib/agentGraph.tsnew file mode 100644index 000000000..572974e19--- /dev/null+++ b/ui/src/lib/agentGraph.ts@@ -0,0 +1,321 @@+// Shared types + pure helpers for the Agents · 运行图 (run graph).+//+// The wire shape is the frozen contract in+// `docs/plans/agents-run-graph-contract.md` §3 (GET /api/agents-graph). The+// only addition over that doc is the per-node `runs` array: the detail panel's+// "RUNS · 本会话" timeline needs the recent run rows, and the graph service is+// the one place that already has agent_runs open — embedding them avoids an+// N+1 fetch from the client. It is additive (no frozen field changes) and only+// the graph frontend consumes it.+//+// Everything here is transport/React-agnostic so the layout + forest builders+// stay unit-testable without a canvas.++// ── Wire types (frozen contract §3) ────────────────────────────────────────++// Live nodes carry a running-agents state; non-live nodes carry the latest run+// outcome. `live` on the node distinguishes the two families.+export type AgentGraphLiveStatus = 'active' | 'idle' | 'orphan';+export type AgentGraphTerminalStatus = 'queued' | 'succeeded' | 'failed' | 'canceled';+export type AgentGraphStatus = AgentGraphLiveStatus | AgentGraphTerminalStatus;++export type AgentGraphVisibility = 'foreground' | 'background';++// One recent run for a session (contract amendment A1; drives the detail-panel+// timeline). Elapsed is derived client-side from started/completed.+export type AgentGraphRunRow = {+ id: string;+ status: string;+ run_type: string | null;+ created_at: string | null;+ started_at: string | null;+ completed_at: string | null;+};++export type AgentGraphNode = {+ session_id: string;+ title: string | null;+ agent_name: string | null;+ agent_backend: string | null;+ model: string | null;+ reasoning_effort: string | null;+ status: AgentGraphStatus;+ live: boolean;+ // Absent until the M1 visibility column ships; absent ⇒ treat as foreground+ // AND hide the 移到前台/隐藏 actions (the PATCH would 400 otherwise).+ visibility?: AgentGraphVisibility;+ scope_id: string | null;+ project_id: string | null;+ scope_label: string | null;+ platform: string | null;+ workdir: string | null;+ openable_in_chat: boolean;+ created_at: string;+ last_active_at: string | null;+ elapsed_seconds: number | null;+ run_counts: { total: number; running: number };+ runs?: AgentGraphRunRow[];+};++export type AgentGraphTriggerNode = {+ definition_id: string;+ // 'scheduled' | 'watch' in practice; kept open for forward definitions.+ definition_type: string;+ name: string | null;+ schedule_label: string | null;+ enabled: boolean;+};++export type AgentGraphEdgeKind = 'spawn' | 'callback' | 'trigger';+export type AgentGraphCallbackStatus = 'pending' | 'sent' | 'failed' | 'skipped';++export type AgentGraphEdge = {+ kind: AgentGraphEdgeKind;+ // session_id, or `def:<definition_id>` for a trigger source.+ from: string;+ to: string;+ run_count?: number;+ last_run_id?: string | null;+ last_at?: string | null;+ // callback edges only.+ status?: AgentGraphCallbackStatus | null;+};++export type AgentGraphCounts = {+ active: number;+ idle: number;+ queued: number;+ ended: number;+ background: number;+ foreground: number;+ [key: string]: number;+};++export type AgentGraphResult = {+ ok: boolean;+ generated_at: string;+ window: string;+ counts: AgentGraphCounts;+ nodes: AgentGraphNode[];+ trigger_nodes: AgentGraphTriggerNode[];+ edges: AgentGraphEdge[];+ truncated: boolean;+};++// ── Query params ────────────────────────────────────────────────────────────++export type GraphWindow = '1h' | '6h' | '24h' | '7d';+export const GRAPH_WINDOWS: GraphWindow[] = ['1h', '6h', '24h', '7d'];++// `all` = every project, `standalone` = the NULL-scope (独立) bucket, else a+// concrete project_id. Mirrors the contract's `project` query param.+export type GraphProjectFilter = string; // 'all' | 'standalone' | <project_id>++export type AgentGraphParams = {+ window?: GraphWindow;+ project?: GraphProjectFilter;+ includeEnded?: boolean;+ includeBackground?: boolean;+};++// ── Presentation helpers ─────────────────────────────────────────────────────++// The trigger def id encoded on a trigger edge's `from`.+export const TRIGGER_PREFIX = 'def:';+export function triggerRefId(definitionId: string): string {+ return `${TRIGGER_PREFIX}${definitionId}`;+}+export function isTriggerRef(ref: string): boolean {+ return ref.startsWith(TRIGGER_PREFIX);+}+export function definitionIdFromRef(ref: string): string {+ return ref.startsWith(TRIGGER_PREFIX) ? ref.slice(TRIGGER_PREFIX.length) : ref;+}++// Per-status presentation, in one place (matches the spec frame anu5U). The+// dot/border tone maps to design tokens; `dim` fades ended sessions.+export type StatusTone = 'mint' | 'gold' | 'cyan' | 'muted' | 'destructive';+export type StatusMeta = {+ tone: StatusTone;+ dotClass: string;+ labelKey: string;+ dim: boolean;+ // Which glyph the node header shows: a colored dot, a check, or a cross.+ glyph: 'dot' | 'check' | 'cross';+};++const STATUS_META: Record<AgentGraphStatus, StatusMeta> = {+ active: { tone: 'mint', dotClass: 'bg-mint', labelKey: 'agents.graph.status.active', dim: false, glyph: 'dot' },+ queued: { tone: 'gold', dotClass: 'bg-gold', labelKey: 'agents.graph.status.queued', dim: false, glyph: 'dot' },+ idle: { tone: 'cyan', dotClass: 'bg-cyan', labelKey: 'agents.graph.status.idle', dim: false, glyph: 'dot' },+ orphan: { tone: 'gold', dotClass: 'bg-amber-500', labelKey: 'agents.graph.status.orphan', dim: false, glyph: 'dot' },+ succeeded: { tone: 'muted', dotClass: 'bg-muted', labelKey: 'agents.graph.status.succeeded', dim: true, glyph: 'check' },+ failed: { tone: 'destructive', dotClass: 'bg-destructive', labelKey: 'agents.graph.status.failed', dim: true, glyph: 'cross' },+ canceled: { tone: 'muted', dotClass: 'bg-muted', labelKey: 'agents.graph.status.canceled', dim: true, glyph: 'cross' },+};++export function statusMeta(status: AgentGraphStatus): StatusMeta {+ return STATUS_META[status] ?? STATUS_META.idle;+}++// A background session is dimmed/eye-off; absent visibility ⇒ foreground.+export function isBackground(node: Pick<AgentGraphNode, 'visibility'>): boolean {+ return node.visibility === 'background';+}++// Human-friendly duration: 12 → "12s", 185 → "3m", 3700 → "1h". Mirrors the+// running-list formatter so the graph and list read consistently.+export function formatElapsed(seconds: number | null | undefined): string {+ if (seconds == null) return '—';+ const s = Math.max(0, seconds);+ if (s < 60) return `${Math.round(s)}s`;+ if (s < 3600) return `${Math.floor(s / 60)}m`;+ return `${Math.floor(s / 3600)}h`;+}++// Elapsed seconds for a run row: completed − started, or now − started while+// still open. Derived client-side since A1 carries timestamps, not a duration.+export function runElapsedSeconds(+ run: Pick<AgentGraphRunRow, 'started_at' | 'completed_at'>,+): number | null {+ if (!run.started_at) return null;+ const start = Date.parse(run.started_at);+ if (Number.isNaN(start)) return null;+ const end = run.completed_at ? Date.parse(run.completed_at) : Date.now();+ return Math.max(0, (end - start) / 1000);+}++// Fallback label when a node has no title: agent name + short session suffix.+export function nodeDisplayTitle(node: Pick<AgentGraphNode, 'title' | 'agent_name' | 'session_id'>): string {+ if (node.title && node.title.trim()) return node.title;+ const suffix = node.session_id.length > 6 ? node.session_id.slice(-6) : node.session_id;+ return node.agent_name ? `${node.agent_name} · ${suffix}` : suffix;+}++// ── Lineage derivation (facts panel) ─────────────────────────────────────────++export type NodeLineage = {+ // 启动方: caller session that spawned this one (latest spawn edge in).+ spawnedBy: string | null;+ // 汇报到: callback target + status (callback edge out).+ callbackTo: string | null;+ callbackStatus: AgentGraphCallbackStatus | null;+ // 触发: originating task/watch definition (trigger edge in).+ trigger: AgentGraphTriggerNode | null;+};++// Pick the most recent of two ISO timestamps (null sorts oldest).+function laterAt(a: string | null | undefined, b: string | null | undefined): number {+ return (a ? Date.parse(a) : 0) - (b ? Date.parse(b) : 0);+}++export function deriveLineage(+ sessionId: string,+ edges: AgentGraphEdge[],+ triggersById: Map<string, AgentGraphTriggerNode>,+): NodeLineage {+ let spawnedBy: AgentGraphEdge | null = null;+ let callback: AgentGraphEdge | null = null;+ let trigger: AgentGraphEdge | null = null;+ for (const edge of edges) {+ if (edge.kind === 'spawn' && edge.to === sessionId) {+ if (!spawnedBy || laterAt(edge.last_at, spawnedBy.last_at) > 0) spawnedBy = edge;+ } else if (edge.kind === 'callback' && edge.from === sessionId) {+ if (!callback || laterAt(edge.last_at, callback.last_at) > 0) callback = edge;+ } else if (edge.kind === 'trigger' && edge.to === sessionId) {+ if (!trigger || laterAt(edge.last_at, trigger.last_at) > 0) trigger = edge;+ }+ }+ return {+ spawnedBy: spawnedBy ? spawnedBy.from : null,+ callbackTo: callback ? callback.to : null,+ callbackStatus: callback ? (callback.status ?? 'pending') : null,+ trigger: trigger ? triggersById.get(definitionIdFromRef(trigger.from)) ?? null : null,+ };+}++// ── Forest builder (mobile grouped list) ─────────────────────────────────────++// One row of the mobile tree list: a node plus its indentation depth and the+// trigger (if any) that spawned its lineage root.+export type ForestRow = {+ node: AgentGraphNode;+ depth: number;+ trigger: AgentGraphTriggerNode | null;+};++// Ranking: live sessions first, then most-recently-active. Deterministic tie+// break on session_id so the list never reshuffles between refreshes.+function nodeOrder(a: AgentGraphNode, b: AgentGraphNode): number {+ if (a.live !== b.live) return a.live ? -1 : 1;+ const at = laterAt(b.last_active_at ?? b.created_at, a.last_active_at ?? a.created_at);+ if (at !== 0) return at;+ return a.session_id.localeCompare(b.session_id);+}++// Flatten the spawn forest into indented rows. A node's parent is the latest+// spawn caller that is also present in the node set; nodes with no such parent+// are roots. Cycles and diamonds are guarded by a visited set (each node is+// emitted once, under its latest parent). Triggered roots carry their trigger+// chip so the mobile row can show the Task/Watch source.+export function buildGraphForest(+ nodes: AgentGraphNode[],+ edges: AgentGraphEdge[],+ triggerNodes: AgentGraphTriggerNode[] = [],+): ForestRow[] {+ const byId = new Map(nodes.map((n) => [n.session_id, n]));+ const triggersById = new Map(triggerNodes.map((tr) => [tr.definition_id, tr]));++ // Resolve each node's spawn parent (latest incoming spawn edge whose source+ // is a real node) and its trigger source.+ const parentOf = new Map<string, string>();+ const parentEdgeAt = new Map<string, string | null | undefined>();+ const triggerOf = new Map<string, AgentGraphTriggerNode>();+ const triggerAtOf = new Map<string, string | null | undefined>();+ const childrenOf = new Map<string, string[]>();++ for (const edge of edges) {+ if (edge.kind === 'spawn' && byId.has(edge.from) && byId.has(edge.to) && edge.from !== edge.to) {+ const prev = parentOf.get(edge.to);+ if (!prev || laterAt(edge.last_at, parentEdgeAt.get(edge.to)) > 0) {+ parentOf.set(edge.to, edge.from);+ parentEdgeAt.set(edge.to, edge.last_at);+ }+ } else if (edge.kind === 'trigger' && byId.has(edge.to)) {+ const tr = triggersById.get(definitionIdFromRef(edge.from));+ // A session reused by multiple tasks/watches gets one trigger edge per+ // definition; keep the latest by last_at so the mobile chip matches the+ // detail panel's lineage (which also picks the newest trigger).+ if (tr && (!triggerOf.has(edge.to) || laterAt(edge.last_at, triggerAtOf.get(edge.to)) > 0)) {+ triggerOf.set(edge.to, tr);+ triggerAtOf.set(edge.to, edge.last_at);+ }+ }+ }+ for (const [child, parent] of parentOf) {+ if (!childrenOf.has(parent)) childrenOf.set(parent, []);+ childrenOf.get(parent)!.push(child);+ }++ const roots = nodes.filter((n) => !parentOf.has(n.session_id)).sort(nodeOrder);+ const rows: ForestRow[] = [];+ const visited = new Set<string>();++ const walk = (node: AgentGraphNode, depth: number, rootTrigger: AgentGraphTriggerNode | null) => {+ if (visited.has(node.session_id)) return;+ visited.add(node.session_id);+ const trigger = triggerOf.get(node.session_id) ?? (depth === 0 ? rootTrigger : null);+ rows.push({ node, depth, trigger });+ const kids = (childrenOf.get(node.session_id) ?? [])+ .map((id) => byId.get(id))+ .filter((n): n is AgentGraphNode => !!n)+ .sort(nodeOrder);+ for (const kid of kids) walk(kid, depth + 1, null);+ };++ for (const root of roots) walk(root, 0, triggerOf.get(root.session_id) ?? null);+ // Any node left unvisited (a cycle with no external root) is surfaced flat so+ // it never silently disappears from the list.+ for (const node of nodes) if (!visited.has(node.session_id)) rows.push({ node, depth: 0, trigger: null });+ return rows;+}diff --git a/ui/src/lib/agentGraphLayout.ts b/ui/src/lib/agentGraphLayout.tsnew file mode 100644index 000000000..631162ad3--- /dev/null+++ b/ui/src/lib/agentGraphLayout.ts@@ -0,0 +1,71 @@+// Layered left→right layout for the run-graph canvas, backed by dagre.+//+// Why dagre (over elk): the graph is a call-tree forest — spawn + trigger edges+// form the hierarchy — which is exactly dagre's layered ("rank") model. It is+// synchronous (no async layout round-trip to reconcile against React state on+// every SSE refresh) and far lighter than the elkjs WASM/JS port, and it is the+// canonical React Flow layouting pairing. Only the desktop canvas imports this,+// so mobile never pulls dagre into its path.+//+// Only spawn + trigger edges are fed to the ranker: callback edges point back+// toward the caller and would fight the left→right layering if they influenced+// ranks. They are still drawn — just not used to place nodes.++import dagre from '@dagrejs/dagre';++// Node box sizes; shared with the node components so the layout reserves the+// right footprint. Session cards are wider; trigger chips are compact.+export const SESSION_NODE_WIDTH = 264;+export const SESSION_NODE_HEIGHT = 92;+export const TRIGGER_NODE_WIDTH = 208;+export const TRIGGER_NODE_HEIGHT = 68;++export type LayoutNode = { id: string; width: number; height: number };+export type LayoutEdge = { source: string; target: string };+export type LayoutPosition = { x: number; y: number };++export type LayoutOptions = {+ nodesep?: number;+ ranksep?: number;+ marginx?: number;+ marginy?: number;+};++// Returns top-left positions keyed by node id (dagre yields centers; React Flow+// wants top-left, so we offset by half the node box).+export function layoutLR(+ nodes: LayoutNode[],+ edges: LayoutEdge[],+ options: LayoutOptions = {},+): Map<string, LayoutPosition> {+ const graph = new dagre.graphlib.Graph();+ graph.setGraph({+ rankdir: 'LR',+ nodesep: options.nodesep ?? 26,+ ranksep: options.ranksep ?? 104,+ marginx: options.marginx ?? 28,+ marginy: options.marginy ?? 28,+ });+ graph.setDefaultEdgeLabel(() => ({}));++ for (const node of nodes) {+ graph.setNode(node.id, { width: node.width, height: node.height });+ }+ for (const edge of edges) {+ // Guard: a layout edge may reference a node that was filtered out.+ if (graph.hasNode(edge.source) && graph.hasNode(edge.target)) {+ graph.setEdge(edge.source, edge.target);+ }+ }++ dagre.layout(graph);++ const positions = new Map<string, LayoutPosition>();+ for (const node of nodes) {+ const laid = graph.node(node.id);+ if (laid) {+ positions.set(node.id, { x: laid.x - node.width / 2, y: laid.y - node.height / 2 });+ }+ }+ return positions;+}diff --git a/ui/src/lib/inboxActivity.test.ts b/ui/src/lib/inboxActivity.test.tsnew file mode 100644index 000000000..774e08a15--- /dev/null+++ b/ui/src/lib/inboxActivity.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { sessionActivityInboxAction } from './inboxActivity';++describe('sessionActivityInboxAction (contract A6)', () => {+ it('drops the card when the session moved to background', () => {+ expect(sessionActivityInboxAction({ event: 'updated', visibility: 'background' })).toBe('drop');+ });++ it('reconciles the feed when the session moved to foreground', () => {+ expect(sessionActivityInboxAction({ event: 'updated', visibility: 'foreground' })).toBe('reconcile');+ });++ it('still drops on an explicit archive event', () => {+ expect(sessionActivityInboxAction({ event: 'archived' })).toBe('drop');+ });++ it('no-ops for an ordinary activity event without visibility (defensive pre-M1)', () => {+ expect(sessionActivityInboxAction({ event: 'updated' })).toBe('ignore');+ expect(sessionActivityInboxAction({ event: 'activity', visibility: undefined })).toBe('ignore');+ });+});diff --git a/ui/src/lib/inboxActivity.ts b/ui/src/lib/inboxActivity.tsnew file mode 100644index 000000000..e2ff15c2a--- /dev/null+++ b/ui/src/lib/inboxActivity.ts@@ -0,0 +1,22 @@+// Decide what the Inbox does with a `session.activity` SSE event.+//+// Contract A6: the backend carries the session's current `visibility` on a+// visibility/scope change. Background hides the card (like an archive);+// foreground re-pulls the feed so a restored session reappears. A pre-M1+// backend never sends `visibility`, so an ordinary activity event without it+// stays a no-op (only an explicit `archived` still drops the card).+//+// Pure so it can be unit-tested without rendering the provider.++export type InboxActivityEvent = {+ event: string;+ visibility?: 'foreground' | 'background';+};++export type InboxActivityAction = 'drop' | 'reconcile' | 'ignore';++export function sessionActivityInboxAction(data: InboxActivityEvent): InboxActivityAction {+ if (data.visibility === 'foreground') return 'reconcile';+ if (data.visibility === 'background' || data.event === 'archived') return 'drop';+ return 'ignore';+}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex fb0fc9d23..5733f2d63 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3112,6 +3112,55 @@ async def running_agents_end():return jsonify(body), (result.get("status_code") or 200)+# Contract A7: the run-graph endpoint lives OUTSIDE the ``/api/agents/<name>``+# namespace (``/api/agents-graph``). ``<name>`` is a user-creatable agent slug,+# so a ``/api/agents/graph`` path would be shadowed by — or shadow — an agent+# literally named ``graph``; a distinct top-level path avoids the collision.[email protected]("/api/agents-graph", methods=["GET"])+async def agents_graph_get():+ """Read-only run-graph payload for the Agents → 运行 tab.++ Assembles ``agent_sessions`` + ``agent_runs`` + ``scopes`` into the frozen+ contract §3 shape (``docs/plans/agents-run-graph-contract.md``). Liveness is+ controller-owned, so it is fetched from the internal running-agents snapshot+ and merged in; when the controller is unreachable the graph still renders+ from the DB (all nodes non-live) with a ``live_unreachable`` hint so the tab+ can show a "runtime unreachable — history only" state instead of a+ misleading empty graph."""+ from core.services import agent_graph+ from vibe import internal_client++ def _flag(value, default: bool) -> bool:+ if value is None:+ return default+ return str(value).strip().lower() in {"1", "true", "yes", "on"}++ window = request.args.get("window") or agent_graph.DEFAULT_WINDOW+ project = request.args.get("project") or "all"+ include_ended = _flag(request.args.get("include_ended"), True)+ include_background = _flag(request.args.get("include_background"), True)++ live_agents: list = []+ live_unreachable = False+ try:+ result = await internal_client.list_running_agents()+ live_agents = (result.get("body") or {}).get("agents") or []+ except (internal_client.InternalServerUnavailable, internal_client.InternalServerTimeout):+ # Controller down: fall back to a DB-only graph (history stays visible).+ live_unreachable = True++ payload = await asyncio.to_thread(+ agent_graph.build_graph,+ live_agents=live_agents,+ window=window,+ project=project,+ include_ended=include_ended,+ include_background=include_background,+ live_unreachable=live_unreachable,+ )+ return jsonify(payload)++@app.route("/api/agents/<name>", methods=["GET"])def vibe_agent_get(name):from vibe import api@@ -7609,6 +7658,10 @@ def inbox_list():except (TypeError, ValueError):limit = 30before = request.args.get("before") or None+ # Targeted single-session fetch: lets a client (e.g. the Inbox visibility+ # reconcile) guarantee one specific session's row is (re)loaded even when its+ # activity sorts past the paged window.+ only_session = request.args.get("session") or Noneengine = _projects_engine()with engine.connect() as conn:@@ -7618,6 +7671,7 @@ def inbox_list():unread_only=unread_only,limit=limit,before=before,+ only_session=only_session,)# Pagination-independent unread map for the sidebar badges (a session# with unread may sit past the first inbox page) + header totals.