Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(workbench): Running agents tab — live snapshot, Open Chat, unified End (#649)

Qi Qi322e8db83d38
diff --git a/core/controller.py b/core/controller.py
index 5ae97dd10..be48ffbba 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -177,6 +177,12 @@ class Controller:
self.receiver_tasks: Dict[str, asyncio.Task] = {}
self.stored_session_mappings: Dict[str, str] = {}
self.session_last_activity: Dict[str, float] = {}
+ # Monotonic baseline of when each session's CURRENT turn went active
+ # (idle→active transition). Unlike ``session_last_activity`` — which is
+ # bumped on every streamed event — this is NOT touched mid-turn, so the
+ # Running tab can report an accurate "busy for" duration instead of
+ # seconds-since-last-chunk.
+ self.session_turn_started: Dict[str, float] = {}
self.claude_active_sessions: set[str] = set()
# The live streaming turn-sink registry now lives on the turn owner
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 2742866c3..04634c1ac 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -66,10 +66,12 @@ class SessionHandler(BaseHandler):
self.receiver_tasks = controller.receiver_tasks
self.stored_session_mappings = controller.stored_session_mappings
self.session_last_activity = getattr(controller, "session_last_activity", {})
+ self.session_turn_started = getattr(controller, "session_turn_started", {})
self.active_sessions = getattr(controller, "claude_active_sessions", set())
self.claude_system_prompts = getattr(controller, "claude_system_prompts", {})
self.claude_session_creates = getattr(controller, "claude_session_creates", {})
controller.session_last_activity = self.session_last_activity
+ controller.session_turn_started = self.session_turn_started
controller.claude_active_sessions = self.active_sessions
controller.claude_system_prompts = self.claude_system_prompts
controller.claude_session_creates = self.claude_session_creates
@@ -81,6 +83,11 @@ class SessionHandler(BaseHandler):
def mark_session_active(self, composite_key: str) -> None:
if not composite_key:
return
+ # Stamp the turn-start baseline only on the idle→active transition, so a
+ # second queued request on an already-active session does not reset the
+ # "busy for" clock (it stays anchored to the first in-flight request).
+ if composite_key not in self.active_sessions:
+ self.session_turn_started[composite_key] = time.monotonic()
self.active_sessions.add(composite_key)
self.touch_session_activity(composite_key)
@@ -88,6 +95,7 @@ class SessionHandler(BaseHandler):
if not composite_key:
return
self.active_sessions.discard(composite_key)
+ self.session_turn_started.pop(composite_key, None)
if composite_key in self.claude_sessions:
self.touch_session_activity(composite_key)
@@ -96,6 +104,7 @@ class SessionHandler(BaseHandler):
return
self.active_sessions.discard(composite_key)
self.session_last_activity.pop(composite_key, None)
+ self.session_turn_started.pop(composite_key, None)
self.claude_system_prompts.pop(composite_key, None)
def bind_claude_runtime_session(
@@ -1288,6 +1297,7 @@ class SessionHandler(BaseHandler):
for composite_key, last_activity in list(self.session_last_activity.items()):
if composite_key not in self.claude_sessions:
self.session_last_activity.pop(composite_key, None)
+ self.session_turn_started.pop(composite_key, None)
self.active_sessions.discard(composite_key)
continue
idle_for = now - last_activity
@@ -1304,6 +1314,7 @@ class SessionHandler(BaseHandler):
current_last_activity = self.session_last_activity.get(composite_key)
if composite_key not in self.claude_sessions:
self.session_last_activity.pop(composite_key, None)
+ self.session_turn_started.pop(composite_key, None)
self.active_sessions.discard(composite_key)
continue
if current_last_activity is None:
diff --git a/core/internal_server.py b/core/internal_server.py
index 4578ce46d..8929a987a 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -187,6 +187,50 @@ def create_app(controller: "Controller") -> FastAPI:
(FSM, Phase 1b). A reconnected Chat page asks this to restore working/Stop."""
return manager.turn_state(session_id)
+ @app.get("/internal/running-agents")
+ async def _running_agents() -> Any:
+ """Read-only snapshot of currently-running agent instances across all
+ backends. Lives here because every liveness source is controller
+ in-memory state the UI process cannot see; the web ``/api/running-agents``
+ route proxies this. Never mutates sessions/transports/eviction state.
+
+ Offloaded to a worker thread: the snapshot does a synchronous SQLite read
+ (and, when live orphan candidates survive, ``ps`` probes), which must not
+ block the controller's event loop that also serves IM/dispatch/SSE. The
+ aggregator tolerates concurrent registry mutation (``_safe_items``)."""
+ from core.services.running_agents import snapshot_running_agents
+
+ return await asyncio.to_thread(snapshot_running_agents, controller)
+
+ @app.post("/internal/running-agents/end")
+ async def _running_agents_end(request: Request) -> Any:
+ """Terminate one running agent's live runtime (Stop turn / disconnect /
+ kill orphan process), dispatched by backend+state. Runs ON the loop (it
+ awaits backend interrupts and mutates loop-owned registries — must NOT be
+ offloaded). Deliberately has no self-kill guard."""
+ from core.services.running_agents import end_running_agent
+
+ payload = await _safe_json(request)
+ if not isinstance(payload, dict):
+ return JSONResponse(status_code=400, content={"ok": False, "error": "invalid_payload"})
+ raw_pid = payload.get("pid")
+ try:
+ pid = int(raw_pid) if raw_pid is not None else None
+ except (TypeError, ValueError):
+ pid = None
+ result = await end_running_agent(
+ controller,
+ backend=(str(payload.get("backend")).strip() or None) if payload.get("backend") else None,
+ state=(str(payload.get("state")).strip() or None) if payload.get("state") else None,
+ session_id=payload.get("session_id") or None,
+ composite_key=payload.get("composite_key") or None,
+ base_session_id=payload.get("base_session_id") or None,
+ pid=pid,
+ )
+ if not result.get("ok"):
+ return JSONResponse(status_code=409, content=result)
+ return result
+
@app.post("/internal/dispatch")
async def _dispatch(request: Request) -> Any:
"""Streaming turn dispatch: runs a turn and proxies its notify/result
diff --git a/core/services/running_agents.py b/core/services/running_agents.py
new file mode 100644
index 000000000..ae7e02447
--- /dev/null
+++ b/core/services/running_agents.py
@@ -0,0 +1,1123 @@
+"""Read-only snapshot of currently-running agent instances.
+
+This aggregator runs INSIDE the controller process (reachable only from the
+controller's asyncio loop via ``core/internal_server.py``) because every
+liveness source it reads is controller in-memory state:
+
+- Claude: ``controller.claude_sessions`` (composite_key -> SDK client),
+ ``claude_active_sessions`` (active turn set), ``session_last_activity``.
+- Codex: ``CodexAgent._session_mgr`` / ``_turn_registry`` / ``_transports``
+ (one transport/pid per working dir, shared by many sessions).
+- OpenCode: ``OpenCodeAgent._active_requests`` (no OS subprocess / pid).
+- Orphans: the persisted Claude process registry (``claude_processes.json``)
+ for ``owner == "session"`` processes that no longer have a live SDK client.
+
+Durations are computed HERE (the controller owns the ``time.monotonic()``
+baselines; raw monotonic values are meaningless in the UI process).
+
+Display metadata (platform / scope / title / workdir) is enriched from the
+SQLite ``agent_sessions`` + ``scopes`` tables, joined by
+``session_anchor == base_session_id``. ``agent_sessions.agent_status`` is NOT
+trusted as a liveness source: it is only written for workbench sessions, so IM
+truth comes solely from the in-memory registries above.
+
+The snapshot is strictly read-only; it never mutates sessions, transports, the
+process registry, or eviction state.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import time
+from typing import TYPE_CHECKING, Any, Optional
+
+if TYPE_CHECKING:
+ from core.controller import Controller
+
+logger = logging.getLogger(__name__)
+
+
+def _safe_call(fn, default):
+ """Call ``fn`` tolerating ``RuntimeError`` from concurrent mutation.
+
+ Like ``_safe_items`` but for callables that iterate live registries
+ internally (e.g. ``CodexSessionManager.all_base_sessions`` unions three
+ lock-free dicts that the controller loop may mutate while we run in a worker
+ thread). Retries a few times, then returns ``default``.
+ """
+ for _ in range(3):
+ try:
+ return fn()
+ except RuntimeError:
+ continue
+ return default
+
+
+def _safe_items(mapping: Any) -> list:
+ """``list(mapping.items())`` tolerant of concurrent mutation.
+
+ The snapshot runs in a worker thread (``asyncio.to_thread``) while the
+ controller loop may still mutate these registries, so a plain
+ ``list(d.items())`` can raise ``RuntimeError: dictionary changed size during
+ iteration``. Reuses ``_safe_call``'s retry-then-default behavior.
+ """
+ if not hasattr(mapping, "items"):
+ return []
+ return _safe_call(lambda: list(mapping.items()), [])
+
+
+def _base_from_composite(composite_key: str) -> str:
+ """Recover ``base_session_id`` from a Claude composite key.
+
+ Composite keys are ``f"{base_session_id}:{working_path}"``; subagent bases
+ themselves contain a colon (``{platform}_{thread}:{agent_name}``), so a
+ naive ``split(":")[0]`` is wrong. ``working_path`` is an absolute path with
+ no colon, so the base is everything before the LAST colon.
+ """
+ base, sep, _workdir = composite_key.rpartition(":")
+ return base if sep else composite_key
+
+
+def _split_scope_id(scope_id: Optional[str]) -> tuple[Optional[str], Optional[str]]:
+ """Parse ``<platform>::<scope_type>::<native_id>`` (see make_scope_id) into
+ ``(platform, scope_type)``; either may be ``None`` when absent."""
+ if not scope_id:
+ return None, None
+ parts = scope_id.split("::")
+ platform = parts[0] or None
+ scope_type = parts[1] if len(parts) >= 2 else None
+ return platform, scope_type
+
+
+def _make_row(
+ *,
+ backend: str,
+ state: str,
+ base_session_id: Optional[str] = None,
+ composite_key: Optional[str] = None,
+ workdir: Optional[str] = None,
+ pid: Optional[int] = None,
+ pid_shared: bool = False,
+ native_session_id: Optional[str] = None,
+ model: Optional[str] = None,
+ elapsed_seconds: Optional[float] = None,
+) -> dict[str, Any]:
+ """Build one normalized running-agent row.
+
+ ``state`` is one of ``active`` (turn in flight), ``idle`` (connected but no
+ active turn), ``orphan`` (process in registry with no live session).
+ ``elapsed_seconds`` reads as "busy for" on active rows (seconds since the
+ current turn went active) and "idle for" on idle/orphan rows (seconds since
+ the last activity); ``None`` when the baseline is unknown.
+ """
+ return {
+ "backend": backend,
+ "state": state,
+ "base_session_id": base_session_id,
+ "composite_key": composite_key,
+ "workdir": workdir,
+ "pid": pid,
+ "pid_shared": pid_shared,
+ "native_session_id": native_session_id,
+ "model": model,
+ "elapsed_seconds": (round(elapsed_seconds, 1) if isinstance(elapsed_seconds, (int, float)) else None),
+ # Filled by _enrich_from_db when a matching agent_sessions row exists.
+ "session_id": None,
+ "title": None,
+ "platform": None,
+ "scope_type": None,
+ "scope_display_name": None,
+ "trigger_source": None,
+ "agent_name": None,
+ "openable_in_chat": False,
+ }
+
+
+def _collect_claude(
+ controller: "Controller", now: float, seen_native: dict[str, Optional[int]], seen_pids: set[int]
+) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ try:
+ from modules.agents.claude_process_reaper import get_claude_client_pid
+ except Exception: # noqa: BLE001
+ get_claude_client_pid = lambda _client: None # type: ignore[assignment]
+
+ sessions = getattr(controller, "claude_sessions", {}) or {}
+ active = getattr(controller, "claude_active_sessions", set()) or set()
+ last_activity = getattr(controller, "session_last_activity", {}) or {}
+ turn_started = getattr(controller, "session_turn_started", {}) or {}
+
+ for composite_key, client in _safe_items(sessions):
+ # composite_key is ``{base}:{abs_workdir}``; split once for both halves.
+ ck_base, ck_sep, ck_workdir = composite_key.rpartition(":")
+ base = getattr(client, "_vibe_runtime_base_session_id", None) or (ck_base if ck_sep else composite_key)
+ native = getattr(client, "_vibe_native_session_id", None)
+ model = getattr(client, "_vibe_current_model", None)
+ pid = get_claude_client_pid(client)
+ is_active = composite_key in active
+ # Active rows report turn duration from the idle→active baseline (NOT
+ # ``session_last_activity``, which is bumped on every streamed event and
+ # would read as seconds-since-last-chunk); idle rows report idle time from
+ # last activity. Fall back to last-activity if the turn baseline is missing.
+ if is_active:
+ ts = turn_started.get(composite_key)
+ if not isinstance(ts, (int, float)):
+ ts = last_activity.get(composite_key)
+ elapsed = (now - ts) if isinstance(ts, (int, float)) else None
+ else:
+ la = last_activity.get(composite_key)
+ elapsed = (now - la) if isinstance(la, (int, float)) else None
+ rows.append(
+ _make_row(
+ backend="claude",
+ state="active" if is_active else "idle",
+ base_session_id=base,
+ composite_key=composite_key,
+ workdir=(ck_workdir or None) if ck_sep else None,
+ pid=pid,
+ native_session_id=native,
+ model=model,
+ elapsed_seconds=elapsed,
+ )
+ )
+ if native:
+ # Map native id → the live client's pid (None when unresolved) so the
+ # orphan scan can tell this live process apart from an older one that
+ # leaked on reconnect (same native id, different pid). A known pid wins
+ # over a None so an unresolved duplicate can't mask it.
+ key = str(native)
+ if isinstance(pid, int):
+ seen_native[key] = pid
+ else:
+ seen_native.setdefault(key, None)
+ if isinstance(pid, int):
+ seen_pids.add(pid)
+ return rows
+
+
+def _collect_codex(controller: "Controller") -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ agent = _get_agent(controller, "codex")
+ if agent is None:
+ return rows
+ session_mgr = getattr(agent, "_session_mgr", None)
+ turn_registry = getattr(agent, "_turn_registry", None)
+ transports = getattr(agent, "_transports", {}) or {}
+ if session_mgr is None:
+ return rows
+
+ # ``all_base_sessions`` unions three lock-free dicts internally, so guard it
+ # against concurrent mutation (we run in a worker thread, §to_thread).
+ base_ids = list(_safe_call(session_mgr.all_base_sessions, []))
+ # Resolve each base's cwd once, then count sessions per cwd (so the UI can
+ # flag a pid shared across sessions) — avoids a second get_cwd pass.
+ entries: list[tuple[str, Optional[str], bool, Any]] = []
+ cwd_session_count: dict[str, int] = {}
+ for base in base_ids:
+ cwd = session_mgr.get_cwd(base)
+ active_turn = turn_registry.get_active_turn(base) if turn_registry is not None else None
+ # A request already holds the Workbench/runtime turn while ``turn/start`` is
+ # in flight, but ``get_active_turn`` stays empty until the turn id finalizes.
+ # Treat that pending-start window as active too — otherwise the UI offers
+ # Disconnect and the idle ``_end_codex`` path bypasses the canonical stop /
+ # terminal-result release and can leave the runtime gate stuck.
+ has_pending = (
+ bool(turn_registry.has_pending_turn_start(base))
+ if turn_registry is not None and hasattr(turn_registry, "has_pending_turn_start")
+ else False
+ )
+ is_active = bool(active_turn) or has_pending
+ transport = transports.get(cwd) if cwd else None
+ # A transport object can outlive its app-server when the process exits out
+ # of band (crash / reader-task failure): it lingers in ``_transports`` with
+ # ``is_alive`` False until a later cleanup removes it. Treat a dead transport
+ # as no live transport so it can't surface as a phantom idle row.
+ if transport is not None and not getattr(transport, "is_alive", True):
+ transport = None
+ # Idle eviction drops the app-server transport but preserves cwd/session
+ # mappings for resume bookkeeping. Such bases are not live and must not
+ # appear as phantom idle rows; keep only a transport-backed base or a still
+ # active (or pending-start) turn that needs to remain visible.
+ if transport is None and not is_active:
+ continue
+ entries.append((base, cwd, is_active, transport))
+ if cwd and transport is not None:
+ cwd_session_count[cwd] = cwd_session_count.get(cwd, 0) + 1
+
+ for base, cwd, is_active, transport in entries:
+ pid = getattr(transport, "pid", None) if transport is not None else None
+ # No per-session elapsed for codex: ``_transport_last_activity`` is keyed
+ # by cwd (shared across every session on that transport) and is touched on
+ # every streaming event, so it reflects neither this session's turn
+ # duration nor its idle time. Report ``None`` rather than a misleading
+ # value; the row still shows backend / state / pid_shared.
+ rows.append(
+ _make_row(
+ backend="codex",
+ state="active" if is_active else "idle",
+ base_session_id=base,
+ workdir=cwd,
+ pid=pid,
+ pid_shared=bool(cwd and transport is not None and cwd_session_count.get(cwd, 0) > 1),
+ elapsed_seconds=None,
+ )
+ )
+ return rows
+
+
+def _collect_opencode(controller: "Controller") -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ agent = _get_agent(controller, "opencode")
+ if agent is None:
+ return rows
+ # OpenCode has no owned subprocess (HTTP server + poll loop), so no pid.
+ # ``_active_requests`` only holds IN-FLIGHT turn tasks (popped in a finally
+ # once the turn settles), so OpenCode only ever surfaces as ``active`` here —
+ # connected-but-idle OpenCode sessions are not represented (D2 is honored for
+ # claude/codex; OpenCode has no idle-session registry to enumerate).
+ active_requests = getattr(agent, "_active_requests", {}) or {}
+ for base, task in _safe_items(active_requests):
+ if bool(getattr(task, "done", lambda: False)()):
+ continue # finishing — being popped; not a live turn
+ rows.append(
+ _make_row(
+ backend="opencode",
+ state="active",
+ base_session_id=base,
+ )
+ )
+ return rows
+
+
+def _collect_orphans(seen_native: dict[str, Optional[int]], seen_pids: set[int]) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ try:
+ from modules.agents.claude_process_reaper import (
+ AVIBE_CLAUDE_SESSION_OWNER,
+ _load_owned_process_registry,
+ _process_ages,
+ _process_start_time,
+ )
+ except Exception: # noqa: BLE001
+ return rows
+ try:
+ registry = _load_owned_process_registry()
+ except Exception: # noqa: BLE001
+ logger.debug("running_agents: failed to read process registry", exc_info=True)
+ return rows
+
+ # Filter to session-owned registry rows not already backed by a live client.
+ # The registry accumulates stale rows (the reaper prunes lazily), so an entry
+ # alone proves nothing — we must verify the process is genuinely alive. A
+ # missing/non-numeric ``started_at`` means we cannot prove identity, so we
+ # skip it rather than risk a false orphan from pid reuse.
+ candidates: list[tuple[Any, int, Optional[str], float]] = []
+ for record in registry:
+ if getattr(record, "owner", None) != AVIBE_CLAUDE_SESSION_OWNER:
+ continue
+ native = getattr(record, "native_session_id", None)
+ record_pid = getattr(record, "pid", None)
+ if native and str(native) in seen_native:
+ owner_pid = seen_native[str(native)]
+ # Skip only when this record IS the live client's own process, or its
+ # pid is unresolved so we can't tell them apart. A live client with the
+ # same native id but a DIFFERENT pid means an older process leaked on
+ # reconnect — let it fall through to the pid/start-time verification so
+ # it can still surface (and be killed) as an orphan.
+ if owner_pid is None or owner_pid == record_pid:
+ continue
+ if not isinstance(record_pid, int) or record_pid in seen_pids:
+ continue
+ recorded = getattr(record, "started_at", None)
+ if not isinstance(recorded, (int, float)):
+ continue # identity unprovable — don't risk a false orphan
+ candidates.append((record, record_pid, native, float(recorded)))
+
+ if not candidates:
+ return rows
+
+ # ONE batched ``ps`` to drop dead/stale pids (the common case: e.g. 88 stale
+ # dead entries collapse to zero here with a single subprocess call). Only the
+ # few survivors get the precise per-pid start-time identity check below, so
+ # we never fan out N blocking ``ps`` calls on the controller loop.
+ ages = _process_ages({pid for _, pid, _, _ in candidates})
+ for record, record_pid, native, recorded in candidates:
+ if record_pid not in ages:
+ continue # not alive — stale registry entry, not a leak
+ current_started_at = _process_start_time(record_pid)
+ if current_started_at is None:
+ continue
+ if abs(current_started_at - recorded) >= 1.0:
+ continue # pid was reused by a different process
+ rows.append(
+ _make_row(
+ backend="claude",
+ state="orphan",
+ pid=record_pid,
+ native_session_id=native,
+ elapsed_seconds=ages.get(record_pid),
+ )
+ )
+ return rows
+
+
+def _get_agent(controller: "Controller", name: str):
+ service = getattr(controller, "agent_service", None)
+ if service is None:
+ return None
+ agents = getattr(service, "agents", {}) or {}
+ return agents.get(name)
+
+
+def _enrich_from_db(rows: list[dict[str, Any]]) -> None:
+ """Best-effort: fill platform/scope/title/session_id from agent_sessions.
+
+ Joins by ``session_anchor == base_session_id``. Failure is non-fatal: rows
+ keep their in-memory truth and just lack display metadata.
+ """
+ anchors = sorted({r["base_session_id"] for r in rows if r.get("base_session_id")})
+ if not anchors:
+ return
+ try:
+ from sqlalchemy import select
+
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions, scopes
+ except Exception: # noqa: BLE001
+ return
+
+ meta_by_anchor: dict[str, list[dict[str, Any]]] = {}
+ try:
+ # Runs controller-side (this aggregator is only reached from the
+ # controller's internal server), so ``create_sqlite_engine()`` resolves
+ # the same DB the controller writes. Outer-join ``scopes`` so platform /
+ # scope_type / display_name come from the canonical columns rather than
+ # only string-splitting ``scope_id``.
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ result = conn.execute(
+ select(
+ agent_sessions.c.id,
+ agent_sessions.c.session_anchor,
+ agent_sessions.c.scope_id,
+ agent_sessions.c.agent_backend,
+ agent_sessions.c.title,
+ agent_sessions.c.workdir,
+ agent_sessions.c.agent_name,
+ agent_sessions.c.last_active_at,
+ scopes.c.platform.label("scope_platform"),
+ scopes.c.scope_type.label("scope_scope_type"),
+ scopes.c.display_name.label("scope_display_name"),
+ scopes.c.native_type.label("scope_native_type"),
+ )
+ .select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id))
+ .where(agent_sessions.c.session_anchor.in_(anchors))
+ ).mappings()
+ for row in result:
+ anchor = row["session_anchor"]
+ meta_by_anchor.setdefault(anchor, []).append(dict(row))
+ except Exception: # noqa: BLE001
+ logger.debug("running_agents: db enrichment failed", exc_info=True)
+ return
+
+ for r in rows:
+ meta = _choose_session_meta(r, meta_by_anchor.get(r.get("base_session_id")) or [])
+ if meta:
+ _apply_session_meta(r, meta)
+
+
+def _choose_session_meta(r: dict[str, Any], candidates: list[dict[str, Any]]) -> Optional[dict[str, Any]]:
+ """Pick display metadata for one running row.
+
+ ``agent_sessions`` may contain separate rows for the same anchor under
+ different backends. Prefer the row matching the live backend; fall back to the
+ most recent row only when no backend match exists.
+ """
+ if not candidates:
+ return None
+ ordered = sorted(
+ candidates,
+ key=lambda row: (row.get("last_active_at") or "", row.get("id") or ""),
+ reverse=True,
+ )
+ backend = str(r.get("backend") or "").strip()
+ if backend:
+ for row in ordered:
+ if str(row.get("agent_backend") or "").strip() == backend:
+ return row
+ return ordered[0]
+
+
+def _apply_session_meta(r: dict[str, Any], meta: dict[str, Any]) -> None:
+ """Fold one ``agent_sessions``⟕``scopes`` row into a running-agent row.
+
+ Pure (no I/O) so it can be unit-tested without a DB.
+ """
+ scope_id = meta.get("scope_id")
+ # Canonical scopes columns win; fall back to splitting scope_id when the
+ # scope row is missing (FK is nullable / SET NULL).
+ split_platform, split_scope_type = _split_scope_id(scope_id)
+ platform = meta.get("scope_platform") or split_platform
+ # Private agent runs (``vibe agent run`` / one agent invoking another) are
+ # NOT IM sessions: ``reserve_private_agent_session`` stamps the scope with a
+ # PLACEHOLDER platform (the configured primary platform — slack/discord/…,
+ # only "slack" when config is unreadable) but marks it
+ # ``native_type="private_agent_run"``. So keying off ``native_type`` (not the
+ # platform) catches these uniformly on every install. Without this guard the
+ # row would be mislabeled as a real IM session. Treat it as an agent-initiated
+ # internal run: no IM platform, ``trigger_source="agent"``, not chat-openable.
+ is_private_run = meta.get("scope_native_type") == "private_agent_run"
+ r["session_id"] = meta.get("id")
+ r["title"] = meta.get("title")
+ r["platform"] = None if is_private_run else platform
+ r["scope_type"] = meta.get("scope_scope_type") or split_scope_type
+ r["scope_display_name"] = meta.get("scope_display_name")
+ r["agent_name"] = meta.get("agent_name")
+ if not r.get("workdir"):
+ r["workdir"] = meta.get("workdir")
+ # Trigger source: agent-initiated for private agent runs; otherwise human.
+ # (scheduled/watch/webhook/callback are only asserted when a harness run
+ # reliably links them, which is not modeled here.)
+ r["trigger_source"] = "agent" if is_private_run else "human"
+ # Private agent runs are internal (``no_delivery``) — not user chat sessions —
+ # so they are not openable. Any other persisted session IS openable in the
+ # workbench Chat by its id, IM sessions included (mirrors how the Inbox /
+ # sidebar navigate to ``/chat/<session_id>``).
+ r["openable_in_chat"] = bool(meta.get("id")) and not is_private_run
+
+
+async def _end_orphan_pid(pid: int) -> dict[str, Any]:
+ """SIGTERM→SIGKILL a leaked Claude process, but ONLY after re-verifying it is
+ an avibe-owned, still-alive, identity-matching registry entry — so a bogus or
+ reused pid from the client can never make us kill an unrelated process."""
+ try:
+ from modules.agents.claude_process_reaper import (
+ AVIBE_CLAUDE_SESSION_OWNER,
+ _build_children_map,
+ _descendant_pids,
+ _load_owned_process_registry,
+ _parse_ps_rows,
+ _process_start_time,
+ _reap_pid_set,
+ _run_ps,
+ )
+ except Exception: # noqa: BLE001
+ return {"ok": False, "error": "reaper_unavailable"}
+ registry = list(_load_owned_process_registry())
+ record = None
+ for r in registry:
+ if getattr(r, "pid", None) == pid and getattr(r, "owner", None) == AVIBE_CLAUDE_SESSION_OWNER:
+ record = r
+ break
+ if record is None:
+ return {"ok": False, "error": "not_an_owned_process", "pid": pid}
+ current = _process_start_time(pid)
+ if current is None:
+ return {"ok": False, "error": "process_not_alive", "pid": pid}
+ recorded = getattr(record, "started_at", None)
+ # FAIL CLOSED: refuse to kill unless identity is provable. A record with a
+ # missing/non-numeric ``started_at`` (e.g. the registration-time ``ps`` failed)
+ # cannot be distinguished from a reused pid, so we never SIGKILL it — matching
+ # the read path's conservatism (``_collect_orphans`` skips such records too).
+ if not isinstance(recorded, (int, float)):
+ return {"ok": False, "error": "identity_unprovable", "pid": pid}
+ if abs(current - recorded) >= 1.0:
+ return {"ok": False, "error": "pid_reused", "pid": pid}
+ # NOTE: a microscopic TOCTOU remains between this check and the signal (the pid
+ # could exit + be reused in the gap); it's inherent to pid-based signaling and
+ # negligible vs. the registration→kill window the start-time match already covers.
+ #
+ # Reap the orphan root TOGETHER WITH its descendants (e.g. node helper
+ # processes), mirroring the background orphan sweep — otherwise killing only
+ # the registered root makes the Running tab row disappear while surviving
+ # children leak with no registry root a later kill could target. Apply the
+ # SAME safety subtractions as the sweep so we never signal the avibe service
+ # (or its tree) or a process owned by a DIFFERENT registered session. The
+ # blocking ``ps`` read is offloaded so we don't stall the controller loop. If
+ # it fails, fall back to the verified root pid alone (better than nothing).
+ target_pids = {pid}
+ try:
+ loop = asyncio.get_running_loop()
+ rows = _parse_ps_rows(await loop.run_in_executor(None, _run_ps))
+ children = _build_children_map(rows)
+ target_pids |= _descendant_pids(rows, pid, children)
+ # Never reap the avibe service itself or anything under it.
+ service_pid = os.getpid()
+ target_pids -= {service_pid} | _descendant_pids(rows, service_pid, children)
+ # Never reap a pid owned by a DIFFERENT registry entry (or its descendants):
+ # only this verified orphan root + its own helpers are in scope.
+ for other in registry:
+ other_pid = getattr(other, "pid", None)
+ if isinstance(other_pid, int) and other_pid > 0 and other_pid != pid:
+ target_pids.discard(other_pid)
+ target_pids -= _descendant_pids(rows, other_pid, children)
+ # The verified root is always in scope regardless of the subtractions above.
+ target_pids.add(pid)
+ except Exception: # noqa: BLE001
+ logger.debug("end: orphan descendant expansion failed for %s", pid, exc_info=True)
+ target_pids = {pid}
+ killed = await _reap_pid_set(target_pids, terminate_timeout=2.0, logger=logger)
+ return {"ok": killed > 0, "action": "killed_process", "pid": pid, "reaped_pids": sorted(target_pids)}
+
+
+def _find_claude_composite_for_base(session_handler: Any, base_session_id: Optional[str]) -> Optional[str]:
+ if not base_session_id:
+ return None
+ sessions = getattr(session_handler, "claude_sessions", {}) or {}
+ for composite_key, client in _safe_items(sessions):
+ client_base = getattr(client, "_vibe_runtime_base_session_id", None) or _base_from_composite(composite_key)
+ if client_base == base_session_id:
+ return composite_key
+ return None
+
+
+def _claude_pid_for(
+ controller: "Controller", composite_key: Optional[str], base_session_id: Optional[str]
+) -> Optional[int]:
+ """Resolve the OS pid of a live Claude session (by composite key, else base), or
+ ``None``. Used to reap the lingering CLI subprocess after the canonical stop
+ disconnects the client — the pid is unresolvable once the client is gone."""
+ session_handler = getattr(controller, "session_handler", None)
+ if session_handler is None:
+ return None
+ ck = composite_key or _find_claude_composite_for_base(session_handler, base_session_id)
+ sessions = getattr(session_handler, "claude_sessions", {}) or {}
+ client = sessions.get(ck) if ck else None
+ if client is None:
+ return None
+ try:
+ from modules.agents.claude_process_reaper import get_claude_client_pid
+
+ return get_claude_client_pid(client)
+ except Exception: # noqa: BLE001
+ return None
+
+
+async def _end_claude(controller: "Controller", composite_key: Optional[str], base_session_id: Optional[str]) -> dict[str, Any]:
+ session_handler = getattr(controller, "session_handler", None)
+ if session_handler is None:
+ return {"ok": False, "error": "session_handler_unavailable"}
+ ck = composite_key or _find_claude_composite_for_base(session_handler, base_session_id)
+ sessions = getattr(session_handler, "claude_sessions", {}) or {}
+ client = sessions.get(ck) if ck else None
+ if client is None:
+ return {"ok": False, "error": "session_not_live"}
+ # Capture the OS pid BEFORE teardown — once the client disconnects its
+ # transport is gone and the pid is no longer resolvable.
+ pid: Optional[int] = None
+ try:
+ from modules.agents.claude_process_reaper import get_claude_client_pid
+
+ pid = get_claude_client_pid(client)
+ except Exception: # noqa: BLE001
+ pid = None
+ # Interrupt any in-flight turn first (best-effort), then disconnect + free the
+ # SDK client / subprocess via the same path idle-eviction uses.
+ try:
+ if hasattr(client, "interrupt"):
+ await client.interrupt()
+ except Exception: # noqa: BLE001
+ logger.debug("end: claude interrupt failed for %s", ck, exc_info=True)
+ try:
+ await session_handler.cleanup_session(ck)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("end: claude cleanup_session failed for %s: %s", ck, exc)
+ return {"ok": False, "error": "cleanup_failed", "detail": str(exc)}
+ # ``disconnect`` only closes the SDK transport; the Claude CLI subprocess can
+ # linger (becoming an orphan the reaper would only collect on a later sweep),
+ # so "End" wouldn't actually free the process. Reap it promptly if still alive.
+ process_killed = False
+ if isinstance(pid, int):
+ try:
+ from modules.agents.claude_process_reaper import _reap_pid_set
+
+ process_killed = (await _reap_pid_set({pid}, terminate_timeout=2.0, logger=logger)) > 0
+ except Exception: # noqa: BLE001
+ logger.debug("end: claude pid reap failed for %s", pid, exc_info=True)
+ return {"ok": True, "action": "ended", "backend": "claude", "pid": pid, "process_killed": process_killed}
+
+
+async def _end_codex(controller: "Controller", base_session_id: Optional[str]) -> dict[str, Any]:
+ if not base_session_id:
+ return {"ok": False, "error": "base_session_id_required"}
+ agent = _get_agent(controller, "codex")
+ if agent is None:
+ return {"ok": False, "error": "codex_unavailable"}
+ session_mgr = getattr(agent, "_session_mgr", None)
+ turn_registry = getattr(agent, "_turn_registry", None)
+ transports = getattr(agent, "_transports", {}) or {}
+ if session_mgr is None or turn_registry is None:
+ return {"ok": False, "error": "codex_registries_unavailable"}
+ cwd = session_mgr.get_cwd(base_session_id)
+ thread_id = session_mgr.get_thread_id(base_session_id)
+ turn_id = turn_registry.get_active_turn(base_session_id)
+ transport = transports.get(cwd) if cwd else None
+ # Interrupt the active turn (the shared app-server transport stays up for
+ # other sessions on the same cwd); then clear THIS session's thread/turn state.
+ interrupted = False
+ if turn_id and thread_id and transport is not None:
+ try:
+ await transport.send_request("turn/interrupt", {"threadId": thread_id, "turnId": turn_id})
+ interrupted = True
+ except Exception: # noqa: BLE001
+ logger.debug("end: codex turn/interrupt failed for %s", base_session_id, exc_info=True)
+ try:
+ # Fully remove the session's mappings (thread + cwd + session_key), not
+ # just ``invalidate_thread`` (which preserves cwd/session_key) — otherwise
+ # ``_collect_codex``'s ``all_base_sessions()`` still enumerates it and the
+ # row never disappears from the Running tab.
+ session_mgr.clear(base_session_id)
+ turn_registry.clear_session(base_session_id)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("end: codex clear failed for %s: %s", base_session_id, exc)
+ return {"ok": False, "error": "clear_failed", "detail": str(exc)}
+ # The app-server transport is shared per cwd. If THIS was the last session on
+ # that cwd, stop it too so the codex process is actually freed (otherwise it
+ # lingers with zero sessions); if other sessions still use it, leave it up.
+ process_killed = False
+ if cwd and transport is not None:
+ remaining: list = []
+ try:
+ remaining = session_mgr.sessions_for_cwd(cwd)
+ except Exception: # noqa: BLE001
+ remaining = []
+ if not remaining:
+ try:
+ await transport.stop()
+ transports.pop(cwd, None)
+ last_activity = getattr(agent, "_transport_last_activity", None)
+ if isinstance(last_activity, dict):
+ last_activity.pop(cwd, None)
+ process_killed = True
+ except Exception: # noqa: BLE001
+ logger.debug("end: codex transport stop failed for %s", cwd, exc_info=True)
+ # ``interrupted`` is False when there was no active turn to stop (idle/stale):
+ # the session state is still cleared, but the caller can tell nothing was
+ # actively interrupted.
+ return {
+ "ok": True,
+ "action": "ended",
+ "backend": "codex",
+ "interrupted": interrupted,
+ "process_killed": process_killed,
+ }
+
+
+async def _end_opencode(controller: "Controller", base_session_id: Optional[str]) -> dict[str, Any]:
+ if not base_session_id:
+ return {"ok": False, "error": "base_session_id_required"}
+ agent = _get_agent(controller, "opencode")
+ if agent is None:
+ return {"ok": False, "error": "opencode_unavailable"}
+ active_requests = getattr(agent, "_active_requests", {}) or {}
+ task = active_requests.get(base_session_id)
+ # Best-effort remote abort (so the OpenCode server stops the run too), then
+ # cancel the local polling task.
+ session_mgr = getattr(agent, "_session_manager", None)
+ try:
+ get_req = getattr(session_mgr, "get_request_session", None)
+ req_info = get_req(base_session_id) if callable(get_req) else None
+ if req_info:
+ server = await agent._get_server()
+ await server.abort_session(req_info[0], req_info[1])
+ except Exception: # noqa: BLE001
+ logger.debug("end: opencode remote abort failed for %s", base_session_id, exc_info=True)
+ if task is not None and not task.done():
+ task.cancel()
+ return {"ok": True, "action": "ended", "backend": "opencode"}
+
+
+async def _settle_workbench_turn(controller: "Controller", session_id: Optional[str]) -> Optional[dict[str, Any]]:
+ """If a Workbench/chat turn is in flight for ``session_id``, stop it through
+ ``SessionTurnManager.cancel`` so the turn FSM settles: it interrupts the
+ backend, emits the terminal result, AND cancels the ``dispatch_turn`` task the
+ Chat page is awaiting. Skipping this (and only doing the backend teardown
+ below) would leave the chat session stuck "running" with sends queued.
+
+ Returns a success/failure result when the Workbench manager owned the turn;
+ returns ``None`` for IM/agent-run turns and when there is no turn owner.
+ """
+ if not session_id:
+ return None
+ manager = getattr(controller, "session_turns", None)
+ if manager is None or not getattr(manager, "is_in_flight", None):
+ return None
+ try:
+ if not manager.is_in_flight(session_id):
+ return None
+ result = await manager.cancel(session_id)
+ if isinstance(result, dict) and result.get("ok"):
+ return {
+ "ok": True,
+ "action": "stopped",
+ "turn_settled": True,
+ "stop_status": result.get("status"),
+ "backend": result.get("backend"),
+ }
+ return {
+ "ok": False,
+ "error": (result or {}).get("code") or "stop_failed",
+ "turn_settled": False,
+ "detail": result,
+ }
+ except Exception: # noqa: BLE001
+ logger.debug("end: workbench turn cancel failed for %s", session_id, exc_info=True)
+ return {"ok": False, "error": "stop_failed", "turn_settled": False}
+
+
+def _workdir_from_composite(composite_key: Optional[str]) -> Optional[str]:
+ if not composite_key:
+ return None
+ _base, sep, workdir = composite_key.rpartition(":")
+ return workdir if sep and workdir else None
+
+
+def _live_workdir_for_backend(
+ controller: "Controller",
+ backend: Optional[str],
+ base_session_id: Optional[str],
+ composite_key: Optional[str],
+) -> Optional[str]:
+ workdir = _workdir_from_composite(composite_key)
+ if workdir or not base_session_id:
+ return workdir
+ if backend == "codex":
+ agent = _get_agent(controller, "codex")
+ session_mgr = getattr(agent, "_session_mgr", None)
+ get_cwd = getattr(session_mgr, "get_cwd", None)
+ if callable(get_cwd):
+ try:
+ return get_cwd(base_session_id)
+ except Exception: # noqa: BLE001
+ logger.debug("end: failed to resolve codex cwd for %s", base_session_id, exc_info=True)
+ elif backend == "opencode":
+ agent = _get_agent(controller, "opencode")
+ session_mgr = getattr(agent, "_session_manager", None)
+ get_req = getattr(session_mgr, "get_request_session", None)
+ if callable(get_req):
+ try:
+ req_info = get_req(base_session_id)
+ except Exception: # noqa: BLE001
+ req_info = None
+ if req_info and len(req_info) >= 2:
+ return req_info[1]
+ return None
+
+
+def _build_stop_context(
+ controller: "Controller",
+ *,
+ backend: Optional[str],
+ session_id: Optional[str],
+ composite_key: Optional[str],
+ base_session_id: Optional[str],
+) -> Any:
+ manager = getattr(controller, "session_turns", None)
+ build_context = getattr(manager, "_build_context", None)
+ context = None
+ if session_id and callable(build_context):
+ try:
+ context = build_context(session_id)
+ except Exception: # noqa: BLE001
+ logger.debug("end: failed to rebuild stop context for %s", session_id, exc_info=True)
+ if context is None:
+ try:
+ from modules.im import MessageContext
+ except Exception: # noqa: BLE001
+ return None
+ channel_id = session_id or base_session_id or composite_key or "running-agent"
+ context = MessageContext(user_id="workbench", channel_id=str(channel_id), platform="avibe")
+ if getattr(context, "platform_specific", None) is None:
+ context.platform_specific = {}
+ payload = context.platform_specific
+ payload["suppress_stop_no_active_notice"] = True
+ effective_base_session_id = base_session_id or (_base_from_composite(composite_key) if composite_key else None)
+ if effective_base_session_id:
+ payload["backend_base_session_id"] = effective_base_session_id
+ if composite_key:
+ payload["backend_composite_session_id"] = composite_key
+ target = payload.get("agent_session_target")
+ if not isinstance(target, dict):
+ target = {}
+ payload["agent_session_target"] = target
+ if session_id and not target.get("id"):
+ target["id"] = session_id
+ if backend and not target.get("agent_backend"):
+ target["agent_backend"] = backend
+ if effective_base_session_id and not target.get("session_anchor"):
+ target["session_anchor"] = effective_base_session_id
+ workdir = _live_workdir_for_backend(controller, backend, effective_base_session_id, composite_key)
+ if workdir and not target.get("workdir"):
+ target["workdir"] = workdir
+ return context
+
+
+async def _stop_active_agent(
+ controller: "Controller",
+ *,
+ backend: Optional[str],
+ session_id: Optional[str],
+ composite_key: Optional[str],
+ base_session_id: Optional[str],
+) -> dict[str, Any]:
+ settled = await _settle_workbench_turn(controller, session_id)
+ if settled is not None:
+ if settled.get("backend") is None and backend:
+ settled["backend"] = backend
+ return settled
+
+ handler = getattr(controller, "command_handler", None)
+ handle_stop = getattr(handler, "handle_stop", None)
+ if not callable(handle_stop):
+ return {"ok": False, "error": "stop_unavailable"}
+ context = _build_stop_context(
+ controller,
+ backend=backend,
+ session_id=session_id,
+ composite_key=composite_key,
+ base_session_id=base_session_id,
+ )
+ if context is None:
+ return {"ok": False, "error": "context_unavailable"}
+ try:
+ handled = bool(await handle_stop(context))
+ except Exception: # noqa: BLE001
+ logger.debug("end: canonical stop failed for %s", base_session_id or session_id, exc_info=True)
+ return {"ok": False, "error": "stop_failed"}
+ if handled:
+ return {"ok": True, "action": "stopped", "backend": backend, "turn_settled": False}
+ payload = getattr(context, "platform_specific", None) or {}
+ return {"ok": False, "error": str(payload.get("stop_failure_reason") or "stop_failed")}
+
+
+def _resolve_live_state(
+ controller: "Controller",
+ *,
+ backend: Optional[str],
+ session_id: Optional[str],
+ composite_key: Optional[str],
+ base_session_id: Optional[str],
+) -> Optional[str]:
+ """Recompute a target's CURRENT ``active``/``idle`` state from live registries.
+
+ The browser sends the ``state`` it last polled, but a row can flip
+ idle→active (or active→idle) before the user clicks End. Trusting the stale
+ value would route an active turn down the idle teardown — which interrupts
+ the turn without releasing the Workbench/AgentService runtime gate or
+ emitting the terminal result, leaving the chat stuck. Re-deriving the state
+ here lets ``end_running_agent`` always pick the correct path.
+
+ Returns ``"active"``/``"idle"``, or ``None`` when the live state can't be
+ determined (caller then falls back to the client-supplied ``state``).
+ """
+ # A Workbench/chat turn in flight is authoritative for any backend.
+ manager = getattr(controller, "session_turns", None)
+ is_in_flight = getattr(manager, "is_in_flight", None)
+ if session_id and callable(is_in_flight):
+ try:
+ if is_in_flight(session_id):
+ return "active"
+ except Exception: # noqa: BLE001
+ logger.debug("end: is_in_flight check failed for %s", session_id, exc_info=True)
+
+ if backend == "claude":
+ active = getattr(controller, "claude_active_sessions", set()) or set()
+ session_handler = getattr(controller, "session_handler", None)
+ ck = composite_key or _find_claude_composite_for_base(session_handler, base_session_id)
+ if ck is None:
+ return None
+ return "active" if ck in active else "idle"
+
+ if backend == "codex":
+ agent = _get_agent(controller, "codex")
+ registry = getattr(agent, "_turn_registry", None)
+ if registry is None or not base_session_id:
+ return None
+ try:
+ if registry.get_active_turn(base_session_id):
+ return "active"
+ if hasattr(registry, "has_pending_turn_start") and registry.has_pending_turn_start(base_session_id):
+ return "active"
+ except Exception: # noqa: BLE001
+ logger.debug("end: codex live-state check failed for %s", base_session_id, exc_info=True)
+ return None
+ return "idle"
+
+ if backend == "opencode":
+ agent = _get_agent(controller, "opencode")
+ active_requests = getattr(agent, "_active_requests", {}) or {}
+ task = active_requests.get(base_session_id) if base_session_id else None
+ if task is None:
+ return "idle"
+ try:
+ return "idle" if bool(task.done()) else "active"
+ except Exception: # noqa: BLE001
+ return "active"
+
+ return None
+
+
+async def end_running_agent(
+ controller: "Controller",
+ *,
+ backend: Optional[str] = None,
+ state: Optional[str] = None,
+ session_id: Optional[str] = None,
+ composite_key: Optional[str] = None,
+ base_session_id: Optional[str] = None,
+ pid: Optional[int] = None,
+) -> dict[str, Any]:
+ """Terminate a running agent's LIVE runtime, dispatched by backend + state.
+
+ - orphan → SIGTERM/SIGKILL the leaked (verified, avibe-owned) process.
+ - claude → interrupt the turn + disconnect the SDK client + reap the subprocess.
+ - codex → interrupt the turn + clear the session mappings (+ stop the shared
+ app-server when this was its last session).
+ - opencode → abort the remote run + cancel the local polling task.
+
+ For an ACTIVE turn, the stop goes through the canonical per-backend stop path
+ (Workbench turns via ``SessionTurnManager.cancel``; IM / agent-run turns via
+ ``command_handler.handle_stop``) so the runtime gate / pending requests /
+ terminal result are released, then the leftover runtime is freed (codex session
+ + transport, opencode task, claude subprocess) so the row clears instead of
+ forcing a second Disconnect.
+
+ Runs on the controller event loop (mutates loop-owned registries / awaits
+ backend coroutines). There is deliberately NO self-protection: ending the
+ current session / avibe's own runtime is allowed by design.
+ """
+ if state == "orphan":
+ if not isinstance(pid, int):
+ return {"ok": False, "error": "pid_required_for_orphan"}
+ return await _end_orphan_pid(pid)
+
+ # Re-derive the live active/idle state server-side: the client's ``state`` is
+ # from its last poll and may be stale (a row can flip idle→active before the
+ # user clicks End). The recomputed value decides the teardown path so an
+ # active turn never falls through to the idle path (which would skip the
+ # canonical stop / gate + terminal-result release).
+ live_state = _resolve_live_state(
+ controller,
+ backend=backend,
+ session_id=session_id,
+ composite_key=composite_key,
+ base_session_id=base_session_id,
+ )
+ if live_state is not None:
+ state = live_state
+
+ if state == "active":
+ # Capture the Claude OS pid BEFORE the stop disconnects the client — once
+ # the SDK client is gone the pid is no longer resolvable.
+ claude_pid = (
+ _claude_pid_for(controller, composite_key, base_session_id) if backend == "claude" else None
+ )
+ stop_result = await _stop_active_agent(
+ controller,
+ backend=backend,
+ session_id=session_id,
+ composite_key=composite_key,
+ base_session_id=base_session_id,
+ )
+ stop_ok = bool(stop_result.get("ok"))
+ # The canonical stop interrupts the turn (and releases its runtime gate via
+ # the turn's own context — verified in Incus) but does NOT free the rest of
+ # the runtime. Finish the teardown so the row clears instead of forcing a
+ # second Disconnect.
+ if backend == "codex":
+ # Tear down even when the stop FAILED: a stale-active row whose turn can
+ # no longer be interrupted (app-server died) must still be clearable via
+ # End, otherwise it sticks in the tab forever.
+ teardown = await _end_codex(controller, base_session_id)
+ if isinstance(teardown, dict) and teardown.get("ok"):
+ result = dict(stop_result) if stop_ok else {"ok": True, "action": "ended", "backend": "codex"}
+ if teardown.get("process_killed"):
+ result["process_killed"] = True
+ return result
+ return stop_result if stop_ok else (teardown if isinstance(teardown, dict) else stop_result)
+
+ if not stop_ok:
+ return stop_result
+ if backend == "opencode":
+ await _end_opencode(controller, base_session_id)
+ elif backend == "claude" and isinstance(claude_pid, int):
+ # Claude's client is already removed by the stop path (so its row clears,
+ # and calling _end_claude here would wrongly report ``session_not_live``);
+ # only the leftover CLI subprocess needs reaping.
+ try:
+ from modules.agents.claude_process_reaper import _reap_pid_set
+
+ if (await _reap_pid_set({claude_pid}, terminate_timeout=2.0, logger=logger)) > 0:
+ stop_result["process_killed"] = True
+ except Exception: # noqa: BLE001
+ logger.debug("end: claude reap after stop failed for %s", claude_pid, exc_info=True)
+ return stop_result
+
+ if backend == "claude":
+ result = await _end_claude(controller, composite_key, base_session_id)
+ elif backend == "codex":
+ result = await _end_codex(controller, base_session_id)
+ elif backend == "opencode":
+ result = await _end_opencode(controller, base_session_id)
+ elif isinstance(pid, int):
+ # Fallback: a pid-only target with no backend is treated as an orphan kill.
+ return await _end_orphan_pid(pid)
+ else:
+ return {"ok": False, "error": "unknown_target"}
+
+ return result
+
+
+def snapshot_running_agents(controller: "Controller") -> dict[str, Any]:
+ """Return a read-only snapshot of all currently-running agent instances.
+
+ Shape::
+
+ {
+ "ok": True,
+ "agents": [ { backend, state, base_session_id, platform, scope_type,
+ scope_display_name, title, workdir, pid, pid_shared,
+ native_session_id, model, elapsed_seconds, trigger_source,
+ session_id, agent_name, openable_in_chat }, ... ],
+ "counts": { "total", "active", "idle", "orphan",
+ "by_backend": {claude, codex, opencode} },
+ }
+
+ One row per live SESSION (F1): a Codex pid shared by several sessions yields
+ one row per session, each flagged ``pid_shared``.
+ """
+ # ``now`` is MONOTONIC: only valid against the controller's monotonic
+ # activity baselines (claude/codex). The orphan path deliberately uses a
+ # separate wall-clock baseline (``time.time()`` vs ``ps`` start time) — do
+ # NOT feed this ``now`` into orphan elapsed math.
+ now = time.monotonic()
+ seen_native: dict[str, Optional[int]] = {}
+ seen_pids: set[int] = set()
+ rows: list[dict[str, Any]] = []
+ rows.extend(_collect_claude(controller, now, seen_native, seen_pids))
+ rows.extend(_collect_codex(controller))
+ rows.extend(_collect_opencode(controller))
+ rows.extend(_collect_orphans(seen_native, seen_pids))
+
+ _enrich_from_db(rows)
+
+ # Single pass over rows for both the state tallies and the per-backend counts.
+ states: dict[str, int] = {"active": 0, "idle": 0, "orphan": 0}
+ by_backend: dict[str, int] = {}
+ for r in rows:
+ states[r["state"]] = states.get(r["state"], 0) + 1
+ by_backend[r["backend"]] = by_backend.get(r["backend"], 0) + 1
+
+ return {
+ "ok": True,
+ "agents": rows,
+ "counts": {
+ "total": len(rows),
+ "active": states["active"],
+ "idle": states["idle"],
+ "orphan": states["orphan"],
+ "by_backend": by_backend,
+ },
+ }
diff --git a/docs/plans/running-agents-activity-tab.md b/docs/plans/running-agents-activity-tab.md
new file mode 100644
index 000000000..5f7835380
--- /dev/null
+++ b/docs/plans/running-agents-activity-tab.md
@@ -0,0 +1,166 @@
+# 运行中 Agent 视图(Agents → Running)— 需求设计稿 v3
+
+> 状态:**已定稿(需求层面)**。两轮评审收敛(opus 4.8:feasible-with-changes → minor-fixes-then-done);§8 全部分叉已拍板。可据此进入实现规划(接口签名/落点)。
+> **已锁决策**:A4(Agents 页内 `Definitions | Running` 子 Tab,A2 顶层 Activity 作兜底)· B1 轮询 · C1 只读 · D2 含 idle · E1 覆盖 IM · F1 session 中心 · G1 含 OpenCode · H1 orphan 单独成行 · I1 不可达明确态 · **J1 默认进 Definitions** · **K2 Running badge 仅计 active**。
+> 范围:**需求 / 产品层面**。不含实现代码;定义"要什么、长什么样、数据从哪来、有哪些待拍板分叉"。
+
+## 1. 背景与问题
+
+avibe 现在能看到 agent **定义**(Workbench → Agents)、定时与触发 **Harness**(Tasks/Watches/Webhooks/Runs 历史),但**看不到"此刻正在运行的 Agent"**:
+
+- 我现在有哪些 Claude Code / Codex / OpenCode 进程或会话在跑?
+- 每个挂在哪个 session 上?这个 session 是 slack / discord / web / 定时触发哪种来源?挂在哪个 channel/thread/项目、哪个 workdir?
+- 想点进去看它、跳到对应会话、(可选)停它怎么办?
+
+数据基本都已存在,但分散在三层且跨进程,从未被聚合成一个"运行时视图"。
+
+## 2. 目标 / 非目标
+
+**目标**
+1. 一眼看清"当前正在运行/活跃"的所有 agent 实例,**覆盖全部三个活后端:claude / codex / opencode**(含未来后端,靠统一抽象自动纳入)。
+2. 每行能看到关键上下文:来源平台、触发源、所属 session、scope、workdir、模型、运行时长、状态。
+3. 每行提供可点击链接/操作:跳 Chat session、查看关联 Harness run、查看 scope、(可选)停止/驱逐。
+4. 嵌入现有 Web IA,移动端可用,且在 controller 不可达时优雅降级(不报 500、不假报"0 在跑")。
+
+**非目标(本期不做)**:历史分析/图表(Runs 已有);改 eviction/reaper 回收逻辑(只读快照);token/费用统计。
+
+## 3. 信息架构:放哪?(§8-A 待拍板,评审倾向已变)
+
+现有结构:Workbench `CapabilityTabs`:`Agents | Skills | Harness | Vaults`;`HarnessPage` 内部 Tab:`Tasks | Watches | Webhooks | Runs`。
+
+**已定(A4)**:在 **`AgentsPage` 内新增子 Tab `Definitions | Running`**。心智模型是"定义 vs 运行实例"(类比 镜像/容器、Deployment/Pod):`Definitions` = 现有 agent 配置(claude/codex/opencode 后端、系统提示、模型),`Running` = 此刻活着的 session/进程,通过 `agent_sessions.agent_backend` 关联回所用后端。
+
+实现注意:
+- AgentsPage 现仅用顶层 `CapabilityTabs` + `WorkbenchPageHeader`,**没有内部子 Tab 机制**,需照 `HarnessPage` 的 `TabKey`/`TAB_ORDER`/counts/refresh/icon 模式新加一层子 Tab。
+- **无需任何路由改动**:`/agents` 仍是单一 route,子 Tab 纯属组件内部 `useState`(与 `HarnessPage.tsx:67-90` 的 `TabKey`/`TAB_ORDER` 完全同构);把现有 AgentsPage 主体抽成 `<DefinitionsTab>`,新增 `<RunningTab>`,外面套 HarnessPage 式 tab row 即可。
+- `Running` 行是 **session 中心**(非"某定义的严格实例");可按 backend/agent 分组与筛选,但不强行把每行绑回某条定义。
+- 评审曾倾向顶层 `Activity` Tab(理由:运行视图还含从不进 harness 的交互式会话,语义更宽)。**该理由不否决 A4**(一切在跑的都是"agent 在跑",放 Agents 自洽),故 A4 成立;仅当深评审发现子 Tab 机制或定义↔实例映射出现 blocker 时回退 **A2 顶层 Activity Tab**。
+
+## 4. 实体模型:一行 = 一个"运行中单元"
+
+行的粒度本身是一个**待拍板分叉(§8-F)**:session 中心 vs 进程/transport 中心。下表按"session 中心、pid 作为属性"的推荐口径给出字段:
+
+| 字段 | 含义 | 来源与注意 |
+| --- | --- | --- |
+| backend | claude / codex / opencode | 内存 registry。opencode 无自有子进程(HTTP server + poll loop),**无 pid** |
+| state | `active`(在途轮次) / `idle`(已连接空转) / `orphan`(脱钩进程) | 每后端 liveness 源不同,须各自明确定义(§7) |
+| busy_for / idle_for | 当前轮次时长 / 空转时长 | **必须在 controller 内算成"已过秒数"再传**;`monotonic()` 不可跨进程 |
+| **platform** | slack / discord / telegram / feishu / wechat / avibe(web) | `scopes.platform`;**"cron"不是 platform** |
+| **trigger source** | human / scheduled / watch / webhook / callback | harness 的 `source_kind`(与 platform 正交,单列)。**兜底**:无可靠关联 Harness run 时默认 `human`;scheduled/watch/webhook/callback 仅在能可靠关联到 run 时显示 |
+| scope | channel / thread / dm / project + 显示名 | `scopes.scope_type` + `display_name`;cron/web 可能 `scope_id=NULL`,则平台回退用 anchor 前缀 |
+| session | base_session_id + 标题 | composite_key 拆分(注意 subagent key 为 `{platform}_{thread}:{agent}:{cwd}` 三段,须按最后一段绝对路径切分)+ `agent_sessions.title` |
+| workdir | 工作目录 | composite_key / `agent_sessions.workdir`(展示可缩略,见安全 §7) |
+| model | 当前模型(**可选/best-effort**) | claude `client._vibe_current_model` 可能为 None;不保证有值 |
+| pid | OS 进程号 + 墙钟运行时长(**可选**) | claude:reaper `ClaudeOwnedProcess`,**仅 `owner=="session"`**(排除 auth 进程);codex:**一个 pid 对应一个 cwd,多 session 共享**;opencode:无 pid |
+| links | 见 §5 | 组合 |
+
+**"活"的口径(关键)**:以**内存 registry + 实际进程**为准(此刻真在跑)。`agent_sessions.agent_status` **只对 workbench/web session 写入**,IM session 不写,故 DB 不能作可靠兜底——IM 在跑的真相只能来自 controller 内存快照。
+
+## 5. 关联上下文 & 链接(每行可点)
+
+- **→ 打开 Chat**:跳 `/chat/:sessionId`。**链接可用性规则(v4 修订)**:只要有持久化 `session_id` 就提供 Open Chat——**IM(slack/discord/…)session 同样可用**,与 Inbox/侧栏既有的 `/chat/<session_id>` 导航一致。无 `session_id`(如 orphan)时**直接不渲染链接,不显示 "unavailable" 占位**。
+- **→ 查看 Scope**:IM → channel/thread;web → 项目。
+- **→ 关联 Harness**:若来自某 task/watch(`agent_runs.definition_id` / `source_kind`),链到定义与该次 run。
+- **→ 进程详情**:pid、墙钟启动时间、native_session_id、是否 orphan。
+- **操作(可选,§8-C,C1 默认不做)**:Stop 轮次(复用 `POST /internal/cancel/{session_id}` 即 `internal_client.cancel_dispatch`)/ Evict 空闲 session / Reveal workdir。
+
+## 6. 交互与状态
+
+- **实时刷新**:轮询 3–5s(B1)。计数 badge **只数 active(在途轮次,K2)**,idle 不计;**socket 不可达时 badge 显示 "—" 而非 "0"**。
+- **排序/筛选(v4 修订:稳定排序)**:先按 state(active→idle→orphan),**band 内按稳定标识排序(非 elapsed)**,避免时长每轮跳动导致行乱跳;可按 backend / platform / source / state 筛选。
+- **状态机**:加载态 / 空态("当前没有 Agent 在运行")/ **controller 不可达态("运行时不可达",区别于空态)** / orphan 高亮(只提示不自动回收)。
+- **移动端**:行卡片化,`backend·platform·state·busy_for` 优先,其余折叠。
+
+## 7. 数据来源 & 跨进程取数(佐证可行性 + 实现骨架)
+
+**架构前提(第 1 轮评审硬伤修正)**:UI 服务(`vibe/ui_server.py`,FastAPI)与 controller 是**两个进程**;活 registry 都在 controller 内存,UI 的 `/api/...` 读不到。唯一跨进程通道是 controller 的本地 Unix socket(`core/internal_server.py`,已有 `/internal/turn-state`、`/internal/cancel` 等,`0o600` 仅本机)。
+
+**取数链路(实现骨架)**:
+1. controller 侧新增 `GET /internal/running-agents`(与 controller 同 asyncio loop,直接读内存;在此处完成 DB join 与时长计算后再返回):
+ - claude:扫 `session_handler.claude_sessions.values()`,读 `_vibe_runtime_base_session_id` / `_vibe_native_session_id` / `get_claude_client_pid(client)`;**注意 `active_sessions`、`session_last_activity` 以 `composite_key` 为键(非 anchor)**,须先经 client 的 `_vibe_runtime_session_key`/`_vibe_runtime_base_session_id` 把 composite_key 解析到 base_session_id 再做 DB join(`session_anchor=base_session_id`);与 reaper `claude_processes.json` 对账标 orphan(仅 `owner=="session"`,排除 auth 进程)。
+ - codex:`_session_mgr.all_base_sessions()` 遍历 → `get_cwd(bid)` → `get_thread_id(bid)`、`_turn_registry.get_active_turn(bid)`;pid 经 `_transports[cwd]` 取。**`CodexTransport` 目前只有 `is_alive`/`is_initialized` 公开,`_process` 私有——需新增公开 pid 访问器**;pid 是 cwd 级、多对一(多 session 共享)。
+ - opencode:状态来自 `OpenCodeAgent.runtime_turn_keys()` 与 `_active_requests` 任务(HTTP server + poll,**无子进程 pid**)。
+ - 跨后端在途轮次:`core/session_turns.py` 的 `in_flight`(键为 workbench `session_id` UUID)。
+ - 显示元数据 join:SQLite `agent_sessions`(backend / workdir / title / scope_id,按 `session_anchor=base_session_id` 关联)+ `scopes`(platform / scope_type / display_name)。
+2. `vibe/internal_client.py` 新增 `list_running_agents()`,捕获 `InternalServerUnavailable`。
+3. `vibe/ui_server.py` 新增 `GET /api/running-agents` 薄代理(沿用现有 AuthGuard 鉴权;controller 不可达时返回明确的 unreachable 而非 500)。
+4. UI 侧(已定 A4):在 `AgentsPage.tsx` 内照 `HarnessPage.tsx:67` 的 `TabKey`/`TAB_ORDER`/`useState` 模式新增 `Definitions | Running` 子 Tab——把现有主体抽成 `<DefinitionsTab>`、新增 `<RunningTab>`,无路由改动。
+5. CLI 侧可加 `vibe ps` 复用同一 `/internal/running-agents`。
+
+**registry 路径修正**:`{config.paths.get_runtime_dir()}/claude_processes.json`(解析到 `~/.avibe/` 下),**非** `~/.vibe-remote/`。
+
+**安全**:pid / 绝对 workdir / native_session_id 经浏览器 API 暴露需明确沿用 `/api` 现有鉴权;workdir 是否全量展示见 §8。
+
+## 8. 偏好分叉 — 已决策(2026-06-24)
+
+> 全部已拍板:**A4**(兜底 A2)· **B1** · **C1** · **D2** · **E1** · **F1** · **G1** · **H1** · **I1** · **J1** · **K2**。下列保留选项与理由备查。
+
+### 8-A. 视图落点(IA)
+- A1:`Harness → Live` 子 Tab(改动最小)。
+- **A2(评审倾向)**:新增顶层 Capability Tab `Activity`(语义最贴切:覆盖交互式 + 自动化全部来源)。
+- A3:放进 `Admin → Dashboard` 运维小部件。
+- A4:`Agents` 页内 `Definitions | Running` 两子 Tab。
+
+### 8-B. 刷新机制
+- B1:轮询 3–5s(简单够用)。
+- B2:SSE 实时推送(更实时、成本更高)。
+
+### 8-C. 操作能力(v6 修订:统一 End)
+- ~~C1:纯只读~~ → ~~C2:仅 Stop~~ → **C3(已采纳):每行统一 "End"**,按 state 分派后端拆除:
+ - **active** → 中断在途轮次 + 断开 client(claude `client.interrupt()`+`cleanup_session`;codex `turn/interrupt`+清 thread/turn;opencode abort+cancel task)。文案 "Stop"。
+ - **idle** → 断开释放 client/transport。文案 "Disconnect"(无损可重建,免确认)。
+ - **orphan** → SIGTERM→SIGKILL 泄漏进程(**先复用 reaper 校验:owner==session + 存活 + 启动时间匹配**,绝不杀非 avibe-owned/复用 pid)。文案 "Kill process"。
+- 链路:`POST /api/running-agents/end` → `/internal/running-agents/end`(**在事件循环上跑**,因要 await 后端中断 + 改 loop 拥有的 registry,不能 to_thread)→ `end_running_agent(controller, target)` 分派。
+- **破坏性二次确认**:active/orphan 首点 arm(按钮变 "确认",3s 自动解除),再点执行;idle 立即。
+- **无自杀护栏**(产品决策):可终止当前会话 / avibe 自身;误杀手动重启。
+
+### 8-D. "运行中"纳入范围
+- D1:只显示真正持有活进程/在途轮次的实例。
+- D2:也显示"已连接但空闲(idle)"的 session,便于了解资源占用。
+
+### 8-E. IM session 可见性(评审新增)
+IM(slack/discord…)的 `agent_status` 不写 DB,要显示其"在跑"必须完全依赖 controller 内存快照(实现更重)。
+- E1:完整覆盖 IM 在跑 session(实现更重,但满足 Goal 1)。
+- E2:暂不覆盖 IM(更轻,但与 Goal 1 矛盾)。
+
+### 8-F. 行粒度(评审新增,核心建模分叉)
+Codex 一个 transport(pid)对应一个 cwd、服务多 session。
+- F1(推荐):**session 中心**——一行一个活 session,pid 作属性;多 session 共享同一 codex pid 时各自成行并注明。
+- F2:**进程/transport 中心**——一行一个 OS 进程/transport,pid 维度聚合。
+
+### 8-G. OpenCode 是否纳入 v1(评审新增)
+OpenCode 已是一等活后端(进程模型不同、无 pid)。
+- G1(推荐):v1 纳入,pid 列对 opencode 留空。
+- G2:v1 显式延后,仅 claude/codex(须在 Goal 1 注明缺口)。
+
+### 8-H. orphan 进程展示策略(已定 H1 + v4 存活校验修订)
+- H1(已定):脱钩进程单独成行标 orphan。
+- **v4 关键修订**:orphan **必须做存活+身份校验**——只展示 pid **当前确实存活**且启动时间与注册表 `started_at` 匹配(±1s,防 pid 复用)的进程。原实现只读 `claude_processes.json`(累积大量历史死 pid),会把早已退出的死 pid 当 orphan 刷屏;现复用 reaper 的 `_process_start_time` 过滤死/复用 pid。修订后多数时候 orphan 为 0,仅真有存活泄漏时出现。
+
+### 8-I. controller 不可达时的 UX(评审新增)
+- I1:显示"运行时不可达"明确态(推荐)。
+- I2:显示上次已知 + 过期横幅。
+- I3:显示空。
+
+### 8-J. 子 Tab 默认落地(已定 J1)
+点 `/agents` 默认进 **`Definitions`**(保留现有肌肉记忆);`Running` 为并列项。
+
+### 8-K. Running 子 Tab 计数 badge 口径(已定 K2)
+Running 子 Tab 的 badge **仅计 `active`(在途轮次)**;idle 实例仍在列表中可见但不计入 badge。须与 §6 口径统一:列表含 idle(D2),但所有"在跑计数"badge 一律只数 active。
+
+## 9. 验收标准(草案)
+1. 有真实运行的 claude/codex/opencode 时,Tab 内列出对应行,platform/source/session/workdir/pid(如有)正确。
+2. 点击链接正确跳 Chat / Harness run / scope。
+3. 进程结束后该行在一个刷新周期内消失。**只读观察口径**:stuck-active 被既有 eviction 驱逐后,其行随之消失——视图只观察既有驱逐结果,不自行驱逐(C1)。
+3b. 多个 codex session 共享同一 app-server pid 时(F1),各 session 各自成行、显示相同 pid 并标"共享进程"。
+3c. controller 重启后"仅 reaper registry 有进程、内存 session 丢失"时,按 H1 显示为 **orphan 行**,其 session/scope/Chat 链接为空或 best-effort;badge 仍只统计 active。
+4. controller 不可达时显示明确"运行时不可达"态、不报 500、badge 显示 "—"。
+5. 移动端可读可用;空态/加载态/出错态完整。
+
+## 附:评审日志
+- **Round 1**(opus 4.8 + codex-expert\*):双方均 feasible-with-changes。已折入:两进程取数链路、registry 路径、platform/source 拆分、monotonic→时长、codex pid 语义、agent_status 不可靠、OpenCode 纳入、安全与降级。新增分叉 8-E~8-I。
+- **Round 2**(opus 4.8):**minor-fixes-then-done**,A4 可行无需回退。已折入:composite_key 与 base_session_id 解析、CodexTransport 需公开 pid 访问器、opencode 状态源(runtime_turn_keys/_active_requests,无 pid)、子 Tab 无需路由改动、codex 共享 pid 验收项。新增微分叉 8-J/8-K(已定 J1/K2)。
+- **Round 3a**(opus 4.8):**minor-fixes-then-done,无新分叉**。修:§7 step4 去除 A1/A2 死代码改为 A4 目标、`/internal/cancel/{session_id}` 路径精确化。
+- **Round 3b**(codex 后端,小上下文):**minor-fixes-then-done,NEW_HUMAN_FORKS=none**。修:§5 链接可用性规则(失效链接置灰/隐藏)、§4 trigger source 兜底(无关联默认 human)、§9 stuck-active 改为只读观察口径、controller 重启残留进程按 orphan 显示。
+- **✅ 收敛定稿**:codex + opus **双评审一致 minor-fixes-then-done / 无遗留 blocker / 无新人工分叉**,全部修正已折入。需求设计完成。
+ - \* codex 评审取数过程:`codex-expert`(OpenAI Codex) 本区域不可用;用户配置的 codex 后端偶发 **403 直连 api.openai.com(HKG)**,且**读多文件的大型评审会触发 remote-compact,被中转上游以 `403 This account only allows Codex official clients` 拒绝**。最终改用「不读文件、doc 正文内联」的小上下文单回合评审成功跑通。**附带发现**:上述 403(偶发直连 OpenAI + compact 被禁)很可能也是用户 codex 后端反复失败/"授权失效"的根因,建议单列排查 `model_provider`/`base_url` 路由与 compact 行为。
diff --git a/modules/agents/codex/transport.py b/modules/agents/codex/transport.py
index f0a1747ee..ed2441df0 100644
--- a/modules/agents/codex/transport.py
+++ b/modules/agents/codex/transport.py
@@ -167,6 +167,18 @@ class CodexTransport:
def is_initialized(self) -> bool:
return self._initialized and self.is_alive
+ @property
+ def pid(self) -> Optional[int]:
+ """OS pid of the codex app-server subprocess, or ``None`` if not running.
+
+ Read-only accessor for observability (the running-agents snapshot). One
+ transport (hence one pid) serves every session sharing its working dir.
+ """
+ proc = self._process
+ if proc is None or proc.returncode is not None:
+ return None
+ return proc.pid
+
# ------------------------------------------------------------------
# Callbacks
# ------------------------------------------------------------------
diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.py
new file mode 100644
index 000000000..9abbab433
--- /dev/null
+++ b/tests/test_running_agents_service.py
@@ -0,0 +1,1012 @@
+"""Unit tests for the read-only running-agents snapshot aggregator.
+
+Hermetic: the DB enrichment and the on-disk Claude process registry are
+monkeypatched out, so the test exercises only the in-memory aggregation logic
+against fake controller registries — it never touches real state.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import types
+
+import pytest
+
+from core.services import running_agents
+
+
+class _AsyncFlag:
+ """Awaitable mock that records it was called and returns a fixed value."""
+
+ def __init__(self, ret=None):
+ self.called = False
+ self.ret = ret
+
+ async def __call__(self, *args, **kwargs):
+ self.called = True
+ return self.ret
+
+
+class _FakeClaudeClient:
+ def __init__(self, base, native, model):
+ self._vibe_runtime_base_session_id = base
+ self._vibe_native_session_id = native
+ self._vibe_current_model = model
+
+
+class _FakeSessionMgr:
+ def __init__(self, cwd_by_base):
+ self._cwd_by_base = cwd_by_base
+
+ def all_base_sessions(self):
+ return list(self._cwd_by_base.keys())
+
+ def get_cwd(self, base):
+ return self._cwd_by_base.get(base)
+
+ def get_sessions_by_session_key(self, _session_key):
+ return list(self._cwd_by_base.keys())
+
+
+class _FakeTurnRegistry:
+ def __init__(self, active_by_base, pending=None):
+ self._active = active_by_base
+ self._pending = set(pending or ())
+
+ def get_active_turn(self, base):
+ return self._active.get(base)
+
+ def has_pending_turn_start(self, base):
+ return base in self._pending
+
+
+class _FakeTransport:
+ def __init__(self, pid, is_alive=True):
+ self.pid = pid
+ self.is_alive = is_alive
+
+
+class _FakeTask:
+ def __init__(self, done):
+ self._done = done
+
+ def done(self):
+ return self._done
+
+
+def _make_controller(*, claude=None, codex=None, opencode=None):
+ agents = {}
+ if codex is not None:
+ agents["codex"] = codex
+ if opencode is not None:
+ agents["opencode"] = opencode
+ controller = types.SimpleNamespace()
+ controller.agent_service = types.SimpleNamespace(agents=agents)
+ controller.claude_sessions = (claude or {}).get("sessions", {})
+ controller.claude_active_sessions = (claude or {}).get("active", set())
+ controller.session_last_activity = (claude or {}).get("last_activity", {})
+ return controller
+
+
[email protected](autouse=True)
+def _no_db_no_registry(monkeypatch):
+ # Keep the aggregator hermetic: never read the real DB or process registry.
+ monkeypatch.setattr(running_agents, "_enrich_from_db", lambda rows: None)
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper._load_owned_process_registry",
+ lambda *a, **k: [],
+ )
+ # Claude pid resolution reads client._transport._process.pid; force a stable value.
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper.get_claude_client_pid",
+ lambda client: getattr(client, "_fake_pid", None),
+ )
+ # Orphan liveness: by default every probed pid is "alive" (batched ages) with
+ # a start time that matches the record (so identity passes). Tests exercising
+ # the dead/reused-pid filter override these per-pid.
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper._process_ages",
+ lambda pids: {p: 1.0 for p in pids},
+ )
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper._process_start_time",
+ lambda pid: 1000.0,
+ )
+
+
+def test_safe_items_tolerates_concurrent_mutation():
+ # Normal dict round-trips.
+ assert dict(running_agents._safe_items({"a": 1, "b": 2})) == {"a": 1, "b": 2}
+
+ # A mapping whose first ``.items()`` raises (dict-changed-size) then succeeds
+ # must be retried, not propagated.
+ class _FlakyMapping:
+ def __init__(self):
+ self._calls = 0
+ self._data = {"x": 1}
+
+ def items(self):
+ self._calls += 1
+ if self._calls == 1:
+ raise RuntimeError("dictionary changed size during iteration")
+ return self._data.items()
+
+ assert dict(running_agents._safe_items(_FlakyMapping())) == {"x": 1}
+ # Non-mapping input is handled gracefully.
+ assert running_agents._safe_items(None) == []
+
+
+def test_safe_call_retries_runtime_error_then_falls_back():
+ calls = {"n": 0}
+
+ def _flaky():
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise RuntimeError("changed size during iteration")
+ return ["a", "b"]
+
+ assert running_agents._safe_call(_flaky, []) == ["a", "b"]
+
+ # Always-raising callable falls back to the default rather than propagating.
+ def _always():
+ raise RuntimeError("boom")
+
+ assert running_agents._safe_call(_always, []) == []
+
+
+def test_claude_active_and_idle_rows():
+ c_active = _FakeClaudeClient("slack_111", "nat-a", "opus")
+ c_active._fake_pid = 4242
+ c_idle = _FakeClaudeClient("slack_222", "nat-b", None)
+ controller = _make_controller(
+ claude={
+ "sessions": {
+ "slack_111:/home/u/proj": c_active,
+ "slack_222:/home/u/other": c_idle,
+ },
+ "active": {"slack_111:/home/u/proj"},
+ "last_activity": {"slack_111:/home/u/proj": 0.0, "slack_222:/home/u/other": 0.0},
+ }
+ )
+ snap = running_agents.snapshot_running_agents(controller)
+ rows = {r["base_session_id"]: r for r in snap["agents"]}
+
+ assert rows["slack_111"]["state"] == "active"
+ assert rows["slack_111"]["pid"] == 4242
+ assert rows["slack_111"]["workdir"] == "/home/u/proj"
+ assert rows["slack_111"]["model"] == "opus"
+ assert rows["slack_222"]["state"] == "idle"
+ assert rows["slack_222"]["pid"] is None
+ assert snap["counts"]["active"] == 1
+ assert snap["counts"]["idle"] == 1
+ assert snap["counts"]["by_backend"]["claude"] == 2
+
+
+def test_subagent_composite_key_base_parsing():
+ # Subagent composite keys are `{platform}_{thread}:{agent}:{workdir}` — the
+ # base must be everything before the LAST colon (the abs workdir).
+ client = _FakeClaudeClient("slack_999:reviewer", "nat-x", None)
+ controller = _make_controller(
+ claude={
+ "sessions": {"slack_999:reviewer:/srv/app": client},
+ "active": set(),
+ "last_activity": {},
+ }
+ )
+ snap = running_agents.snapshot_running_agents(controller)
+ row = snap["agents"][0]
+ assert row["base_session_id"] == "slack_999:reviewer"
+ assert row["workdir"] == "/srv/app"
+
+
+def test_codex_shared_pid_one_row_per_session():
+ mgr = _FakeSessionMgr({"base-1": "/work/x", "base-2": "/work/x", "base-3": "/work/y"})
+ turns = _FakeTurnRegistry({"base-1": "turn-1"}) # base-1 active, others idle
+ codex = types.SimpleNamespace(
+ _session_mgr=mgr,
+ _turn_registry=turns,
+ _transports={"/work/x": _FakeTransport(7001), "/work/y": _FakeTransport(7002)},
+ _transport_last_activity={"/work/x": 0.0, "/work/y": 0.0},
+ )
+ controller = _make_controller(codex=codex)
+ snap = running_agents.snapshot_running_agents(controller)
+ by_base = {r["base_session_id"]: r for r in snap["agents"]}
+
+ assert by_base["base-1"]["pid"] == 7001 and by_base["base-1"]["pid_shared"] is True
+ assert by_base["base-2"]["pid"] == 7001 and by_base["base-2"]["pid_shared"] is True
+ assert by_base["base-3"]["pid"] == 7002 and by_base["base-3"]["pid_shared"] is False
+ assert by_base["base-1"]["state"] == "active"
+ assert by_base["base-2"]["state"] == "idle"
+ assert snap["counts"]["by_backend"]["codex"] == 3
+
+
+def test_codex_skips_evicted_idle_base_without_transport():
+ mgr = _FakeSessionMgr({"live": "/work/live", "evicted": "/work/gone", "active": "/work/active"})
+ turns = _FakeTurnRegistry({"active": "turn-1"})
+ codex = types.SimpleNamespace(
+ _session_mgr=mgr,
+ _turn_registry=turns,
+ _transports={"/work/live": _FakeTransport(7001)},
+ )
+ controller = _make_controller(codex=codex)
+ snap = running_agents.snapshot_running_agents(controller)
+ by_base = {r["base_session_id"]: r for r in snap["agents"]}
+
+ assert set(by_base) == {"live", "active"}
+ assert by_base["live"]["state"] == "idle"
+ assert by_base["active"]["state"] == "active"
+ assert by_base["active"]["pid"] is None
+
+
+def test_codex_skips_dead_transport_object():
+ # A transport whose app-server already exited (is_alive False) can linger in
+ # _transports; such a base must not surface as a phantom idle row, nor count
+ # toward pid_shared for a sibling on the same cwd.
+ mgr = _FakeSessionMgr({"dead": "/work/x", "alive": "/work/y"})
+ turns = _FakeTurnRegistry({})
+ codex = types.SimpleNamespace(
+ _session_mgr=mgr,
+ _turn_registry=turns,
+ _transports={"/work/x": _FakeTransport(8001, is_alive=False), "/work/y": _FakeTransport(8002)},
+ )
+ controller = _make_controller(codex=codex)
+ snap = running_agents.snapshot_running_agents(controller)
+ by_base = {r["base_session_id"]: r for r in snap["agents"]}
+
+ assert set(by_base) == {"alive"} # the dead-transport base is dropped
+ assert by_base["alive"]["pid"] == 8002
+
+
+def test_claude_active_elapsed_uses_turn_start_baseline():
+ # Active "busy for" must be measured from the turn-start baseline, NOT
+ # session_last_activity (which is bumped on every streamed chunk and would
+ # read as seconds-since-last-chunk). Idle rows still use last activity.
+ now = 1_000.0
+ c_active = _FakeClaudeClient("slack_a", "nat-a", "opus")
+ c_idle = _FakeClaudeClient("slack_b", "nat-b", None)
+ controller = _make_controller(
+ claude={
+ "sessions": {"slack_a:/w1": c_active, "slack_b:/w2": c_idle},
+ "active": {"slack_a:/w1"},
+ "last_activity": {"slack_a:/w1": now - 2.0, "slack_b:/w2": now - 90.0},
+ }
+ )
+ # Turn started long before the last chunk: busy time must reflect the turn
+ # baseline (120s), not the 2s since the last streamed event.
+ controller.session_turn_started = {"slack_a:/w1": now - 120.0}
+
+ import time as _time
+
+ orig = _time.monotonic
+ _time.monotonic = lambda: now
+ try:
+ snap = running_agents.snapshot_running_agents(controller)
+ finally:
+ _time.monotonic = orig
+
+ rows = {r["base_session_id"]: r for r in snap["agents"]}
+ assert rows["slack_a"]["state"] == "active"
+ assert rows["slack_a"]["elapsed_seconds"] == 120.0 # turn baseline, not 2s
+ assert rows["slack_b"]["elapsed_seconds"] == 90.0 # idle uses last activity
+
+
+def test_claude_active_elapsed_falls_back_to_last_activity_without_baseline():
+ # When no turn baseline is recorded (e.g. activated before this build), the
+ # active row degrades gracefully to last-activity rather than dropping elapsed.
+ now = 500.0
+ client = _FakeClaudeClient("slack_c", "nat-c", None)
+ controller = _make_controller(
+ claude={
+ "sessions": {"slack_c:/w": client},
+ "active": {"slack_c:/w"},
+ "last_activity": {"slack_c:/w": now - 5.0},
+ }
+ )
+ controller.session_turn_started = {} # no baseline
+
+ import time as _time
+
+ orig = _time.monotonic
+ _time.monotonic = lambda: now
+ try:
+ snap = running_agents.snapshot_running_agents(controller)
+ finally:
+ _time.monotonic = orig
+ row = snap["agents"][0]
+ assert row["state"] == "active"
+ assert row["elapsed_seconds"] == 5.0
+
+
+def test_codex_pending_turn_start_counts_as_active():
+ # While turn/start is in flight, get_active_turn is still empty but the request
+ # already holds the runtime turn. Such a base must report active (not idle), so
+ # the UI offers Stop and End takes the canonical active path.
+ mgr = _FakeSessionMgr({"starting": "/work/p"})
+ turns = _FakeTurnRegistry({}, pending={"starting"}) # no active turn yet, pending start
+ codex = types.SimpleNamespace(
+ _session_mgr=mgr,
+ _turn_registry=turns,
+ _transports={"/work/p": _FakeTransport(9100)},
+ )
+ controller = _make_controller(codex=codex)
+ snap = running_agents.snapshot_running_agents(controller)
+ by_base = {r["base_session_id"]: r for r in snap["agents"]}
+ assert by_base["starting"]["state"] == "active"
+
+
+def test_opencode_active_requests_have_no_pid():
+ oc = types.SimpleNamespace(_active_requests={"base-oc": _FakeTask(done=False)})
+ controller = _make_controller(opencode=oc)
+ snap = running_agents.snapshot_running_agents(controller)
+ row = snap["agents"][0]
+ assert row["backend"] == "opencode"
+ assert row["state"] == "active"
+ assert row["pid"] is None
+
+
+def test_orphan_only_when_native_not_owned(monkeypatch):
+ from modules.agents.claude_process_reaper import AVIBE_CLAUDE_SESSION_OWNER
+
+ live = _FakeClaudeClient("slack_live", "nat-live", None)
+ owned = types.SimpleNamespace(pid=100, native_session_id="nat-live", owner=AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ leaked = types.SimpleNamespace(pid=200, native_session_id="nat-gone", owner=AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ auth_proc = types.SimpleNamespace(pid=300, native_session_id="nat-auth", owner="auth", started_at=1000.0)
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper._load_owned_process_registry",
+ lambda *a, **k: [owned, leaked, auth_proc],
+ )
+ controller = _make_controller(
+ claude={"sessions": {"slack_live:/w": live}, "active": set(), "last_activity": {}}
+ )
+ snap = running_agents.snapshot_running_agents(controller)
+ orphans = [r for r in snap["agents"] if r["state"] == "orphan"]
+
+ # Only the leaked session-owned process becomes an orphan: the owned one is
+ # still backed by a live client (native matches), the auth process is excluded.
+ assert len(orphans) == 1
+ assert orphans[0]["pid"] == 200
+ assert orphans[0]["native_session_id"] == "nat-gone"
+ assert snap["counts"]["orphan"] == 1
+
+
+def test_orphan_dedup_by_pid_when_live_client_lacks_native(monkeypatch):
+ from modules.agents.claude_process_reaper import AVIBE_CLAUDE_SESSION_OWNER
+
+ # Live client with NO native id but a resolvable pid (e.g. SDK build that
+ # exposes the pid but Avibe hasn't captured the native session id yet).
+ live = _FakeClaudeClient("slack_live", None, None)
+ live._fake_pid = 555
+ same_pid = types.SimpleNamespace(pid=555, native_session_id="nat-x", owner=AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ leaked = types.SimpleNamespace(pid=999, native_session_id="nat-y", owner=AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper._load_owned_process_registry",
+ lambda *a, **k: [same_pid, leaked],
+ )
+ controller = _make_controller(
+ claude={"sessions": {"slack_live:/w": live}, "active": set(), "last_activity": {}}
+ )
+ snap = running_agents.snapshot_running_agents(controller)
+ orphans = [r for r in snap["agents"] if r["state"] == "orphan"]
+
+ # ``same_pid`` is NOT an orphan: its pid still backs the live client even
+ # though native ids don't match. Only the genuinely leaked pid is an orphan.
+ assert {o["pid"] for o in orphans} == {999}
+
+
+def test_private_agent_run_not_labeled_slack():
+ # ``reserve_private_agent_session`` stores private agent runs with a
+ # placeholder ``platform="slack"`` but ``native_type="private_agent_run"``.
+ # Such a row must NOT be shown as a Slack session.
+ row = running_agents._make_row(backend="codex", state="idle", base_session_id="b1")
+ meta = {
+ "id": "ses0000priv",
+ "scope_id": "slack::channel::private-agent-run-abc123",
+ "scope_platform": "slack",
+ "scope_scope_type": "channel",
+ "scope_display_name": "Private Agent Run",
+ "scope_native_type": "private_agent_run",
+ "title": "[Current Task] review",
+ "agent_name": "codex",
+ "workdir": None,
+ }
+ running_agents._apply_session_meta(row, meta)
+
+ assert row["platform"] is None # not "slack"
+ assert row["trigger_source"] == "agent"
+ assert row["openable_in_chat"] is False
+ assert row["scope_display_name"] == "Private Agent Run"
+
+
+def test_real_slack_session_labeled_and_openable():
+ row = running_agents._make_row(backend="claude", state="idle", base_session_id="slack_x")
+ meta = {
+ "id": "ses0000slack",
+ "scope_id": "slack::user::U123",
+ "scope_platform": "slack",
+ "scope_scope_type": "user",
+ "scope_display_name": "qiqi",
+ "scope_native_type": "im",
+ "title": None,
+ "agent_name": "claude",
+ "workdir": "/home/u/cc/slack",
+ }
+ running_agents._apply_session_meta(row, meta)
+
+ assert row["platform"] == "slack"
+ assert row["trigger_source"] == "human"
+ assert row["openable_in_chat"] is True # real IM session is openable
+
+
+def test_session_meta_prefers_matching_backend_before_recent_fallback():
+ candidates = [
+ {"id": "ses-claude", "agent_backend": "claude", "last_active_at": "2026-01-01T00:00:00"},
+ {"id": "ses-codex", "agent_backend": "codex", "last_active_at": "2026-01-02T00:00:00"},
+ ]
+ claude_row = running_agents._make_row(backend="claude", state="idle", base_session_id="same-anchor")
+ unknown_row = running_agents._make_row(backend="opencode", state="idle", base_session_id="same-anchor")
+
+ assert running_agents._choose_session_meta(claude_row, candidates)["id"] == "ses-claude"
+ assert running_agents._choose_session_meta(unknown_row, candidates)["id"] == "ses-codex"
+
+
+def test_orphan_surfaces_duplicate_native_with_different_pid(monkeypatch):
+ from modules.agents.claude_process_reaper import AVIBE_CLAUDE_SESSION_OWNER
+
+ # A live client reconnected as pid 100 (native nat-dup); an OLDER process with
+ # the SAME native id but pid 200 leaked. The native match must NOT hide it.
+ live = _FakeClaudeClient("slack_dup", "nat-dup", None)
+ live._fake_pid = 100
+ leaked_old = types.SimpleNamespace(
+ pid=200, native_session_id="nat-dup", owner=AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0
+ )
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper._load_owned_process_registry",
+ lambda *a, **k: [leaked_old],
+ )
+ controller = _make_controller(
+ claude={"sessions": {"slack_dup:/w": live}, "active": set(), "last_activity": {}}
+ )
+ snap = running_agents.snapshot_running_agents(controller)
+ orphans = [r for r in snap["agents"] if r["state"] == "orphan"]
+
+ # The leaked old process surfaces as a killable orphan; the live client's own
+ # pid 100 is still excluded (by seen_pids).
+ assert {o["pid"] for o in orphans} == {200}
+
+
+def test_orphan_skips_dead_and_reused_pids(monkeypatch):
+ from modules.agents.claude_process_reaper import AVIBE_CLAUDE_SESSION_OWNER
+
+ alive = types.SimpleNamespace(pid=10, native_session_id="nat-alive", owner=AVIBE_CLAUDE_SESSION_OWNER, started_at=5000.0)
+ dead = types.SimpleNamespace(pid=20, native_session_id="nat-dead", owner=AVIBE_CLAUDE_SESSION_OWNER, started_at=5000.0)
+ reused = types.SimpleNamespace(pid=30, native_session_id="nat-reused", owner=AVIBE_CLAUDE_SESSION_OWNER, started_at=5000.0)
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper._load_owned_process_registry",
+ lambda *a, **k: [alive, dead, reused],
+ )
+
+ # pid 20 is not alive (absent from batched ages → stale); pid 30 is alive but
+ # started far from the recorded time (reused by an unrelated process); pid 10
+ # is a real leak (alive + start matches the record within 1s).
+ monkeypatch.setattr(
+ "modules.agents.claude_process_reaper._process_ages",
+ lambda pids: {p: 1.0 for p in pids if p in {10, 30}},
+ )
+
+ def _start(pid):
+ return {10: 5000.4, 30: 9999.0}.get(pid)
+
+ monkeypatch.setattr("modules.agents.claude_process_reaper._process_start_time", _start)
+
+ snap = running_agents.snapshot_running_agents(_make_controller())
+ orphans = [r for r in snap["agents"] if r["state"] == "orphan"]
+
+ # Only the genuinely-alive, identity-matching pid 10 is shown; the dead pid
+ # 20 and the reused pid 30 are filtered out (no stale/false orphans).
+ assert {o["pid"] for o in orphans} == {10}
+
+
+# ---------------------------------------------------------------------------
+# end_running_agent dispatch (unified End)
+# ---------------------------------------------------------------------------
+
+
+def test_end_orphan_kills_verified_owned_pid(monkeypatch):
+ from modules.agents import claude_process_reaper as reaper
+
+ rec = types.SimpleNamespace(pid=10, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [rec])
+ monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)
+ reap = _AsyncFlag(ret=1)
+ monkeypatch.setattr(reaper, "_reap_pid_set", reap)
+
+ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=10))
+ assert res["ok"] is True
+ assert res["action"] == "killed_process"
+ assert reap.called
+
+
+def test_end_orphan_reaps_root_plus_descendants(monkeypatch):
+ # Killing a leaked Claude orphan must also reap its descendants (node helpers),
+ # mirroring the background sweep — otherwise the row disappears while children
+ # leak with no registry root a later kill could target.
+ from modules.agents import claude_process_reaper as reaper
+
+ rec = types.SimpleNamespace(pid=100, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [rec])
+ monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)
+ # Tree: 100(root) -> 200(child) -> 300(grandchild); 999 is unrelated.
+ ps_rows = [
+ reaper.ClaudeProcessRow(pid=100, ppid=1, command="claude"),
+ reaper.ClaudeProcessRow(pid=200, ppid=100, command="node helper"),
+ reaper.ClaudeProcessRow(pid=300, ppid=200, command="node helper2"),
+ reaper.ClaudeProcessRow(pid=999, ppid=1, command="unrelated"),
+ ]
+ monkeypatch.setattr(reaper, "_run_ps", lambda: "ignored")
+ monkeypatch.setattr(reaper, "_parse_ps_rows", lambda _out: ps_rows)
+ captured = {}
+
+ async def _reap(target_pids, *, terminate_timeout, logger):
+ captured["pids"] = set(target_pids)
+ return len(target_pids)
+
+ monkeypatch.setattr(reaper, "_reap_pid_set", _reap)
+
+ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=100))
+ assert res["ok"] is True
+ assert captured["pids"] == {100, 200, 300} # root + descendants, NOT the unrelated 999
+
+
+def test_end_orphan_falls_back_to_root_when_ps_unreadable(monkeypatch):
+ # If the ps read fails during descendant expansion, still reap the verified
+ # root pid (better than reaping nothing).
+ from modules.agents import claude_process_reaper as reaper
+
+ rec = types.SimpleNamespace(pid=55, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [rec])
+ monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)
+
+ def _boom():
+ raise RuntimeError("ps unavailable")
+
+ monkeypatch.setattr(reaper, "_run_ps", _boom)
+ captured = {}
+
+ async def _reap(target_pids, *, terminate_timeout, logger):
+ captured["pids"] = set(target_pids)
+ return len(target_pids)
+
+ monkeypatch.setattr(reaper, "_reap_pid_set", _reap)
+
+ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=55))
+ assert res["ok"] is True
+ assert captured["pids"] == {55}
+
+
+def test_end_orphan_excludes_other_registered_session_pids(monkeypatch):
+ # A descendant that belongs to a DIFFERENT registered session (or its own
+ # children) must NOT be reaped when ending one orphan — mirror the sweep's
+ # owned-pid subtraction so we don't kill another live session's process.
+ from modules.agents import claude_process_reaper as reaper
+
+ root = types.SimpleNamespace(pid=100, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ other = types.SimpleNamespace(pid=200, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [root, other])
+ monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)
+ # 100(root) -> 200(other owned) -> 300(other's child)
+ ps_rows = [
+ reaper.ClaudeProcessRow(pid=100, ppid=1, command="claude"),
+ reaper.ClaudeProcessRow(pid=200, ppid=100, command="claude"),
+ reaper.ClaudeProcessRow(pid=300, ppid=200, command="node helper"),
+ ]
+ monkeypatch.setattr(reaper, "_run_ps", lambda: "ignored")
+ monkeypatch.setattr(reaper, "_parse_ps_rows", lambda _out: ps_rows)
+ captured = {}
+
+ async def _reap(target_pids, *, terminate_timeout, logger):
+ captured["pids"] = set(target_pids)
+ return len(target_pids)
+
+ monkeypatch.setattr(reaper, "_reap_pid_set", _reap)
+
+ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=100))
+ assert res["ok"] is True
+ # 200 (other owned) and its child 300 are excluded; only the verified root remains.
+ assert captured["pids"] == {100}
+
+
+def test_end_orphan_never_reaps_the_service_tree(monkeypatch):
+ # If the avibe service pid (or its descendants) somehow appears under the
+ # orphan root, it must never be signalled.
+ from modules.agents import claude_process_reaper as reaper
+
+ root = types.SimpleNamespace(pid=100, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=1000.0)
+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [root])
+ monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)
+ # 100(root) -> 200(== service pid) -> 300(service child)
+ ps_rows = [
+ reaper.ClaudeProcessRow(pid=100, ppid=1, command="claude"),
+ reaper.ClaudeProcessRow(pid=200, ppid=100, command="python avibe"),
+ reaper.ClaudeProcessRow(pid=300, ppid=200, command="python worker"),
+ ]
+ monkeypatch.setattr(reaper, "_run_ps", lambda: "ignored")
+ monkeypatch.setattr(reaper, "_parse_ps_rows", lambda _out: ps_rows)
+ monkeypatch.setattr(running_agents.os, "getpid", lambda: 200) # avibe service is pid 200
+ captured = {}
+
+ async def _reap(target_pids, *, terminate_timeout, logger):
+ captured["pids"] = set(target_pids)
+ return len(target_pids)
+
+ monkeypatch.setattr(reaper, "_reap_pid_set", _reap)
+
+ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=100))
+ assert res["ok"] is True
+ assert 200 not in captured["pids"] and 300 not in captured["pids"]
+ assert captured["pids"] == {100}
+
+
+def test_end_orphan_refuses_unowned_pid(monkeypatch):
+ from modules.agents import claude_process_reaper as reaper
+
+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [])
+ reap = _AsyncFlag(ret=1)
+ monkeypatch.setattr(reaper, "_reap_pid_set", reap)
+
+ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=999))
+ assert res["ok"] is False
+ assert reap.called is False # never kills a pid avibe doesn't own
+
+
+def test_end_orphan_refuses_when_identity_unprovable(monkeypatch):
+ # An avibe-owned record with NO recorded start time cannot be distinguished
+ # from a reused pid → fail closed (never kill), matching the read path.
+ from modules.agents import claude_process_reaper as reaper
+
+ rec = types.SimpleNamespace(pid=10, owner=reaper.AVIBE_CLAUDE_SESSION_OWNER, started_at=None)
+ monkeypatch.setattr(reaper, "_load_owned_process_registry", lambda *a, **k: [rec])
+ monkeypatch.setattr(reaper, "_process_start_time", lambda pid: 1000.0)
+ reap = _AsyncFlag(ret=1)
+ monkeypatch.setattr(reaper, "_reap_pid_set", reap)
+
+ res = asyncio.run(running_agents.end_running_agent(_make_controller(), state="orphan", pid=10))
+ assert res["ok"] is False
+ assert res["error"] == "identity_unprovable"
+ assert reap.called is False
+
+
+def test_end_claude_interrupts_disconnects_and_reaps_subprocess(monkeypatch):
+ interrupt = _AsyncFlag()
+ cleanup = _AsyncFlag()
+ client = types.SimpleNamespace(interrupt=interrupt, _fake_pid=4321)
+ session_handler = types.SimpleNamespace(claude_sessions={"slack_1:/w": client}, cleanup_session=cleanup)
+ controller = _make_controller()
+ controller.session_handler = session_handler
+ reap = _AsyncFlag(ret=1)
+ monkeypatch.setattr("modules.agents.claude_process_reaper._reap_pid_set", reap)
+
+ res = asyncio.run(
+ running_agents.end_running_agent(controller, backend="claude", composite_key="slack_1:/w")
+ )
+ assert res["ok"] is True
+ assert interrupt.called and cleanup.called
+ # The subprocess is reaped promptly (not left as an orphan for the sweeper).
+ assert reap.called and res["process_killed"] is True and res["pid"] == 4321
+
+
+def test_end_claude_session_not_live():
+ session_handler = types.SimpleNamespace(claude_sessions={}, cleanup_session=_AsyncFlag())
+ controller = _make_controller()
+ controller.session_handler = session_handler
+ res = asyncio.run(running_agents.end_running_agent(controller, backend="claude", composite_key="missing:/w"))
+ assert res["ok"] is False
+ assert res["error"] == "session_not_live"
+
+
+def test_end_codex_interrupts_clears_and_stops_last_transport():
+ send = _AsyncFlag()
+ stop = _AsyncFlag()
+ transport = types.SimpleNamespace(send_request=send, stop=stop)
+ cleared = {}
+ transports = {"/w": transport}
+ mgr = types.SimpleNamespace(
+ get_cwd=lambda b: "/w",
+ get_thread_id=lambda b: "th1",
+ clear=lambda b: cleared.__setitem__("inv", b),
+ sessions_for_cwd=lambda cwd: [], # this was the last session on the cwd
+ )
+ treg = types.SimpleNamespace(
+ get_active_turn=lambda b: "turn1",
+ clear_session=lambda b: cleared.__setitem__("clr", b),
+ )
+ codex = types.SimpleNamespace(
+ _session_mgr=mgr, _turn_registry=treg, _transports=transports, _transport_last_activity={"/w": 0.0}
+ )
+ res = asyncio.run(
+ running_agents.end_running_agent(_make_controller(codex=codex), backend="codex", base_session_id="b1")
+ )
+ assert res["ok"] is True
+ assert send.called # turn/interrupt RPC sent
+ assert cleared.get("inv") == "b1" and cleared.get("clr") == "b1"
+ # Last session on the cwd → the shared app-server transport is stopped + dropped.
+ assert stop.called and res["process_killed"] is True and "/w" not in transports
+
+
+def test_end_codex_keeps_transport_when_other_sessions_share_cwd():
+ transport = types.SimpleNamespace(send_request=_AsyncFlag(), stop=_AsyncFlag())
+ transports = {"/w": transport}
+ mgr = types.SimpleNamespace(
+ get_cwd=lambda b: "/w",
+ get_thread_id=lambda b: "th1",
+ clear=lambda b: None,
+ sessions_for_cwd=lambda cwd: ["other-base"], # another session still uses it
+ )
+ treg = types.SimpleNamespace(get_active_turn=lambda b: None, clear_session=lambda b: None)
+ codex = types.SimpleNamespace(_session_mgr=mgr, _turn_registry=treg, _transports=transports)
+ res = asyncio.run(
+ running_agents.end_running_agent(_make_controller(codex=codex), backend="codex", base_session_id="b1")
+ )
+ assert res["ok"] is True
+ # Shared transport stays up; not stopped, still registered.
+ assert res["process_killed"] is False and "/w" in transports
+
+
+def test_end_opencode_cancels_active_task():
+ class _Task:
+ def __init__(self):
+ self.cancelled = False
+
+ def done(self):
+ return False
+
+ def cancel(self):
+ self.cancelled = True
+
+ task = _Task()
+ oc = types.SimpleNamespace(
+ _active_requests={"b1": task},
+ _session_manager=types.SimpleNamespace(get_request_session=lambda b: None),
+ )
+ # OpenCode rows are inherently in-flight (an active request task), so the live
+ # recheck classifies this as active: End runs the canonical stop, then
+ # _end_opencode cancels the local polling task.
+ async def _handle_stop(_context):
+ return True
+
+ controller = _make_controller(opencode=oc)
+ controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False)
+ controller.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+ res = asyncio.run(
+ running_agents.end_running_agent(
+ controller, backend="opencode", state="active", session_id="oc-s", base_session_id="b1"
+ )
+ )
+ assert res["ok"] is True
+ assert task.cancelled
+
+
+def test_end_active_workbench_turn_settles_via_manager(monkeypatch):
+ # An active turn owned by the Workbench FSM must be stopped through
+ # SessionTurnManager.cancel. The real Claude stop path pops the SDK client
+ # during cancel; End must still return success and must not run a duplicate
+ # backend teardown that would now report session_not_live.
+ sessions = {"slack_x:/w": types.SimpleNamespace(interrupt=_AsyncFlag())}
+
+ class _WorkbenchCancel:
+ def __init__(self):
+ self.called = False
+
+ async def __call__(self, _session_id):
+ self.called = True
+ sessions.pop("slack_x:/w", None)
+ return {"ok": True, "status": "cancel_requested", "backend": "claude"}
+
+ cancel = _WorkbenchCancel()
+ manager = types.SimpleNamespace(is_in_flight=lambda sid: sid == "ses-wb", cancel=cancel)
+ cleanup = _AsyncFlag()
+ controller = _make_controller()
+ controller.session_turns = manager
+ controller.session_handler = types.SimpleNamespace(claude_sessions=sessions, cleanup_session=cleanup)
+ monkeypatch.setattr("modules.agents.claude_process_reaper._reap_pid_set", _AsyncFlag(ret=0))
+
+ res = asyncio.run(
+ running_agents.end_running_agent(
+ controller, backend="claude", state="active", session_id="ses-wb", composite_key="slack_x:/w"
+ )
+ )
+ assert res["ok"] is True
+ assert cancel.called and res.get("turn_settled") is True
+ assert cleanup.called is False
+ assert sessions == {}
+
+
+def test_end_active_im_turn_uses_canonical_stop_path(monkeypatch):
+ # IM turns never enter Workbench in_flight, but active End must still use the
+ # canonical /stop path so backend adapters release pending requests, runtime
+ # gates, and terminal silent results before their registries change.
+ cancel = _AsyncFlag()
+ manager = types.SimpleNamespace(is_in_flight=lambda sid: False, cancel=cancel)
+ seen = {}
+
+ async def _handle_stop(context):
+ seen["context"] = context
+ return True
+
+ command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+ cleanup = _AsyncFlag()
+ controller = _make_controller()
+ # A genuinely-active IM turn is registered in claude_active_sessions; the
+ # server-side live-state recheck reads this to confirm the active path.
+ controller.claude_active_sessions = {"slack_y:/w"}
+ controller.session_turns = manager
+ controller.command_handler = command_handler
+ controller.session_handler = types.SimpleNamespace(claude_sessions={"slack_y:/w": object()}, cleanup_session=cleanup)
+ monkeypatch.setattr("modules.agents.claude_process_reaper._reap_pid_set", _AsyncFlag(ret=0))
+
+ res = asyncio.run(
+ running_agents.end_running_agent(
+ controller, backend="claude", state="active", session_id="slack-im", composite_key="slack_y:/w"
+ )
+ )
+ assert res["ok"] is True
+ assert cancel.called is False
+ assert res["action"] == "stopped"
+ assert res["turn_settled"] is False
+ assert cleanup.called is False
+ payload = seen["context"].platform_specific
+ assert payload["backend_base_session_id"] == "slack_y"
+ assert payload["backend_composite_session_id"] == "slack_y:/w"
+ assert payload["agent_session_target"]["agent_backend"] == "claude"
+ assert payload["suppress_stop_no_active_notice"] is True
+
+
+def test_end_active_codex_frees_runtime_after_stop():
+ # Active Codex End must FREE the runtime after the canonical stop (which only
+ # interrupts the turn): clear the session mappings + stop the now-unused shared
+ # transport so the row disappears instead of forcing a second Disconnect.
+ async def _handle_stop(context):
+ return True
+
+ cleared = {}
+ transport = types.SimpleNamespace(send_request=_AsyncFlag(), stop=_AsyncFlag())
+ transports = {"/w": transport}
+ mgr = types.SimpleNamespace(
+ get_cwd=lambda b: "/w",
+ get_thread_id=lambda b: "th1",
+ clear=lambda b: cleared.__setitem__("clr", b),
+ sessions_for_cwd=lambda cwd: [], # this was the last session on the cwd
+ )
+ treg = types.SimpleNamespace(
+ get_active_turn=lambda b: "turn1", # genuinely active per the live registry
+ clear_session=lambda b: cleared.__setitem__("treg", b),
+ )
+ codex = types.SimpleNamespace(
+ _session_mgr=mgr,
+ _turn_registry=treg,
+ _transports=transports,
+ _transport_last_activity={"/w": 0.0},
+ _runtime_turn_key_for_base_session=lambda b: f"{b}:/w",
+ )
+ controller = _make_controller(codex=codex)
+ controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False, cancel=_AsyncFlag())
+ controller.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+
+ res = asyncio.run(
+ running_agents.end_running_agent(
+ controller, backend="codex", state="active", session_id="ses-im", base_session_id="b1"
+ )
+ )
+ assert res["ok"] is True
+ # Canonical stop ran, THEN teardown cleared mappings + stopped the shared transport.
+ assert cleared.get("clr") == "b1" and cleared.get("treg") == "b1"
+ assert transport.stop.called and "/w" not in transports
+ assert res["process_killed"] is True
+
+
+def test_end_active_codex_clears_stale_row_even_when_stop_fails():
+ # A stale-active codex row (turn still in the registry but the app-server died)
+ # makes the canonical stop fail; End must still tear it down + release the gate
+ # so the row clears instead of sticking forever.
+ async def _handle_stop(context):
+ return False
+
+ cleared = {}
+ mgr = types.SimpleNamespace(
+ get_cwd=lambda b: "/w",
+ get_thread_id=lambda b: None,
+ clear=lambda b: cleared.__setitem__("clr", b),
+ sessions_for_cwd=lambda cwd: [],
+ )
+ treg = types.SimpleNamespace(
+ get_active_turn=lambda b: "stale-turn",
+ clear_session=lambda b: cleared.__setitem__("treg", b),
+ )
+ codex = types.SimpleNamespace(
+ _session_mgr=mgr,
+ _turn_registry=treg,
+ _transports={}, # app-server already gone
+ _transport_last_activity={},
+ _runtime_turn_key_for_base_session=lambda b: f"{b}:/w",
+ )
+ controller = _make_controller(codex=codex)
+ controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False, cancel=_AsyncFlag())
+ controller.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+
+ res = asyncio.run(
+ running_agents.end_running_agent(
+ controller, backend="codex", state="active", session_id="s", base_session_id="b1"
+ )
+ )
+ assert res["ok"] is True # teardown cleared the stale row despite the failed stop
+ assert cleared.get("clr") == "b1" and cleared.get("treg") == "b1"
+
+
+def test_end_unknown_target():
+ res = asyncio.run(running_agents.end_running_agent(_make_controller(), backend="mystery"))
+ assert res["ok"] is False
+ assert res["error"] == "unknown_target"
+
+
+def test_end_rechecks_live_state_idle_to_active(monkeypatch):
+ # The browser polled this Claude row as idle, but it went active before the
+ # user clicked Disconnect. End must re-derive the live state server-side and
+ # route through the canonical stop path (NOT the idle _end_claude teardown,
+ # which would skip the runtime-gate / terminal-result release).
+ seen = {}
+
+ async def _handle_stop(context):
+ seen["stopped"] = True
+ return True
+
+ cleanup = _AsyncFlag()
+ controller = _make_controller()
+ controller.claude_active_sessions = {"slack_z:/w"} # live registry says ACTIVE now
+ controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False, cancel=_AsyncFlag())
+ controller.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+ controller.session_handler = types.SimpleNamespace(
+ claude_sessions={"slack_z:/w": object()}, cleanup_session=cleanup
+ )
+ monkeypatch.setattr("modules.agents.claude_process_reaper._reap_pid_set", _AsyncFlag(ret=0))
+
+ res = asyncio.run(
+ running_agents.end_running_agent(
+ controller,
+ backend="claude",
+ state="idle", # stale client state
+ session_id="slack-im",
+ composite_key="slack_z:/w",
+ )
+ )
+ assert res["ok"] is True
+ assert seen.get("stopped") is True # canonical active stop path was taken
+ assert res["action"] == "stopped"
+ assert cleanup.called is False # idle _end_claude teardown was NOT used
+
+
+def test_end_rechecks_live_state_active_to_idle():
+ # The browser polled this Codex row as active, but the turn finished before
+ # End. With no live active/pending turn, End re-derives idle and runs the idle
+ # teardown directly (no canonical stop needed).
+ cleared = {}
+ transport = types.SimpleNamespace(send_request=_AsyncFlag(), stop=_AsyncFlag())
+ mgr = types.SimpleNamespace(
+ get_cwd=lambda b: "/w",
+ get_thread_id=lambda b: None,
+ clear=lambda b: cleared.__setitem__("clr", b),
+ sessions_for_cwd=lambda cwd: [],
+ )
+ treg = _FakeTurnRegistry({}, pending=set()) # no active turn, no pending start
+ treg.clear_session = lambda b: cleared.__setitem__("treg", b)
+ codex = types.SimpleNamespace(
+ _session_mgr=mgr, _turn_registry=treg, _transports={"/w": transport}, _transport_last_activity={"/w": 0.0}
+ )
+ controller = _make_controller(codex=codex)
+ controller.session_turns = types.SimpleNamespace(is_in_flight=lambda sid: False)
+
+ res = asyncio.run(
+ running_agents.end_running_agent(
+ controller, backend="codex", state="active", session_id="s", base_session_id="b1"
+ )
+ )
+ assert res["ok"] is True
+ assert cleared.get("clr") == "b1" and cleared.get("treg") == "b1"
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index ba5391772..50fadbdd7 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -16,11 +16,14 @@ import {
Star,
Trash2,
Upload,
+ Activity,
+ Layers,
} from 'lucide-react';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import type { VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';
+import { RunningAgentsTab } from './RunningAgentsTab';
import { useToast } from '../../context/ToastContext';
import { NewAgentDialog } from './NewAgentDialog';
import { RunAgentDialog } from './RunAgentDialog';
@@ -51,6 +54,9 @@ import {
// (a combobox can't submit an empty value, so this is the explicit clear path).
const MODEL_DEFAULT_OPTION = '__default__';
+type AgentsTabKey = 'definitions' | 'running';
+const AGENTS_TAB_ORDER: AgentsTabKey[] = ['definitions', 'running'];
+
function isSystemAgent(agent: { source: string }): boolean {
return agent.source === 'builtin' || agent.source === 'system';
}
@@ -59,6 +65,8 @@ export const AgentsPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
+ const [agentsTab, setAgentsTab] = useState<AgentsTabKey>('definitions');
+ const [runningActiveCount, setRunningActiveCount] = useState<number | null>(null);
const [agents, setAgents] = useState<VibeAgentBrief[]>([]);
const [defaultName, setDefaultName] = useState<string | null>(null);
const [selected, setSelected] = useState<VibeAgentFull | null>(null);
@@ -114,6 +122,37 @@ export const AgentsPage: React.FC = () => {
if (!selected) setDetailOpen(false);
}, [selected]);
+ // Fetch the active-count for the Running tab badge. Runs once on mount
+ // and polls every 8s so the pill reflects live state without hammering the server.
+ useEffect(() => {
+ let cancelled = false;
+ const fetchCount = async () => {
+ try {
+ const result = await api.getRunningAgents();
+ if (!cancelled) {
+ if (result.ok && result.counts) {
+ setRunningActiveCount((result.counts as any).active ?? 0);
+ } else {
+ setRunningActiveCount(null); // unreachable → show "—"
+ }
+ }
+ } catch {
+ // Any fetch failure (unreachable/401/500): show "—" rather than a stale
+ // count, matching the tab body's explicit unreachable handling.
+ if (!cancelled) setRunningActiveCount(null);
+ }
+ };
+ fetchCount();
+ // While the Running tab is open it already polls the same endpoint (4s), so
+ // skip the redundant badge poll then; one fetch on tab-switch keeps the pill
+ // fresh enough (it re-runs on the next switch back to Definitions).
+ const id = agentsTab === 'running' ? null : window.setInterval(fetchCount, 8000);
+ return () => {
+ cancelled = true;
+ if (id != null) window.clearInterval(id);
+ };
+ }, [api, agentsTab]);
+
const selectAgent = useCallback(
async (name: string, openDetail = false) => {
try {
@@ -159,6 +198,10 @@ 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;
try {
@@ -257,8 +300,50 @@ export const AgentsPage: React.FC = () => {
}
/>
+ {/* Sub-tab row: Definitions | Running */}
+ <div className="flex items-center gap-0 overflow-x-auto border-b border-border">
+ {AGENTS_TAB_ORDER.map((key) => {
+ const active = agentsTab === key;
+ return (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setAgentsTab(key)}
+ className={clsx(
+ 'flex shrink-0 items-center gap-2 whitespace-nowrap px-4 py-3 text-[13px] transition',
+ active
+ ? 'border-b-2 border-violet font-bold text-violet'
+ : 'font-medium text-muted hover:text-foreground',
+ )}
+ >
+ {key === 'definitions' ? (
+ <Layers className={clsx('size-3.5', active ? 'text-violet' : 'text-muted')} />
+ ) : (
+ <Activity className={clsx('size-3.5', active ? 'text-violet' : 'text-muted')} />
+ )}
+ {t(`agents.tabs.${key}`)}
+ {key === 'running' && (
+ <span
+ className={clsx(
+ 'rounded-full border px-1.5 py-0 font-mono text-[9px] font-bold',
+ active
+ ? 'border-violet/30 bg-violet/[0.10] text-violet'
+ : 'border-border-strong bg-foreground/[0.04] text-muted',
+ )}
+ >
+ {runningActiveCount === null ? '—' : runningActiveCount}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Running tab body */}
+ {agentsTab === 'running' && <RunningAgentsTab onActiveCountChange={handleRunningActiveCountChange} />}
+
{/* Toolbar — design.pen Imduv: search + backend filter + spacer + Import + 新建 Agent */}
- <div className={clsx('flex flex-wrap items-center gap-2.5', detailOpen && 'max-lg:hidden')}>
+ <div className={clsx('flex flex-wrap items-center gap-2.5', agentsTab === 'running' ? 'hidden' : detailOpen && 'max-lg:hidden')}>
<div className="flex h-9 w-full items-center gap-2 rounded-md border border-input bg-background px-3 transition-colors focus-within:border-ring focus-within:ring-2 focus-within:ring-ring sm:w-[320px]">
<Search className="size-3.5 shrink-0 text-muted" />
<input
@@ -281,7 +366,7 @@ export const AgentsPage: React.FC = () => {
</Button>
</div>
- {error && (
+ {agentsTab === 'definitions' && error && (
<div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive">
{error}
</div>
@@ -291,10 +376,12 @@ export const AgentsPage: React.FC = () => {
is selected; the empty "select an agent" placeholder used to
dominate the right side of a fresh page. With auto-select on
mount it's rarely needed; when it is empty we just collapse
- back to a single column. */}
+ back to a single column.
+ Hidden when Running tab is active; all hooks stay mounted. */}
<div
className={clsx(
'grid gap-5',
+ agentsTab === 'running' && 'hidden',
// `minmax(0,1fr)` + `min-w-0` keep the list column shrinkable; bare
// `1fr` would let a long agent row push the fixed detail card off-screen.
selected ? 'grid-cols-1 lg:grid-cols-[minmax(0,1fr)_420px]' : 'grid-cols-1',
diff --git a/ui/src/components/workbench/RunningAgentsTab.tsx b/ui/src/components/workbench/RunningAgentsTab.tsx
new file mode 100644
index 000000000..fd83b1824
--- /dev/null
+++ b/ui/src/components/workbench/RunningAgentsTab.tsx
@@ -0,0 +1,486 @@
+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';
+
+// How often to refresh while mounted (ms)
+const POLL_INTERVAL_MS = 4000;
+
+// 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));
+ });
+}
+
+// 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<RunningAgent[]>([]);
+ const [unreachable, setUnreachable] = useState(false);
+ const [loading, setLoading] = useState(true);
+ // 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 {
+ setUnreachable(false);
+ setAgents(sortAgents(result.agents ?? []));
+ 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],
+ );
+
+ // Initial fetch
+ useEffect(() => {
+ fetchData(false);
+ }, [fetchData]);
+
+ // Polling interval
+ useEffect(() => {
+ const id = window.setInterval(() => fetchData(true), POLL_INTERVAL_MS);
+ return () => window.clearInterval(id);
+ }, [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}
+ onEnd={endAgent}
+ />
+ ))}
+ </div>
+ );
+};
+
+// ---------------------------------------------------------------------------
+// One row / card per running agent session
+// ---------------------------------------------------------------------------
+
+interface RunningAgentRowProps {
+ agent: RunningAgent;
+ onEnd: (agent: RunningAgent) => Promise<void>;
+}
+
+const RunningAgentRow: React.FC<RunningAgentRowProps> = ({ agent, 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 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}}". */}
+ {agent.elapsed_seconds != null && (
+ <span className="font-mono text-[11px] text-muted">
+ {t(
+ agent.state === 'active'
+ ? 'agents.running.busy'
+ : 'agents.running.idleElapsed',
+ { elapsed: formatElapsed(agent.elapsed_seconds) },
+ )}
+ </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.tsx
index 42bfecf22..7ce523118 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -269,6 +269,15 @@ export type ApiContextType = {
deleteHarnessWatch: (watchId: string) => Promise<{ ok: boolean; id?: string }>;
listHarnessRuns: (params?: HarnessRunsParams) => Promise<HarnessRunsResult>;
getHarnessRun: (runId: string) => Promise<{ ok: boolean; run: HarnessRun }>;
+ getRunningAgents: () => Promise<RunningAgentsResult>;
+ endRunningAgent: (payload: {
+ backend?: string | null;
+ state?: string | null;
+ session_id?: string | null;
+ composite_key?: string | null;
+ base_session_id?: string | null;
+ pid?: number | null;
+ }) => Promise<{ ok: boolean; unreachable?: boolean; error?: string; action?: string }>;
remoteAccessStatus: () => Promise<any>;
pairVibeCloudRemoteAccess: (payload: { backend_url: string; pairing_key: string; device_name?: string }) => Promise<any>;
startRemoteAccess: () => Promise<any>;
@@ -836,6 +845,45 @@ export type HarnessBootstrapResult = {
page: HarnessTasksResult | HarnessWatchesResult | HarnessRunsResult;
};
+// =============================================================================
+// Running agents (live process view)
+// =============================================================================
+
+export type RunningAgentState = 'active' | 'idle' | 'orphan';
+
+export type RunningAgent = {
+ backend: string;
+ state: RunningAgentState;
+ base_session_id: string | null;
+ composite_key: string | null;
+ workdir: string | null;
+ pid: number | null;
+ pid_shared: boolean;
+ native_session_id: string | null;
+ model: string | null;
+ elapsed_seconds: number | null;
+ session_id: string | null;
+ title: string | null;
+ platform: string | null;
+ scope_type: string | null;
+ scope_display_name: string | null;
+ trigger_source: 'human' | 'agent' | 'scheduled' | 'watch' | 'webhook' | 'callback' | null;
+ agent_name: string | null;
+ openable_in_chat: boolean;
+};
+
+export type RunningAgentCounts = {
+ total: number;
+ active: number;
+ idle: number;
+ orphan: number;
+ by_backend: Record<string, number>;
+};
+
+export type RunningAgentsResult =
+ | { ok: true; agents: RunningAgent[]; counts: RunningAgentCounts; unreachable?: false }
+ | { ok: false; unreachable: true; agents: RunningAgent[]; counts: Partial<RunningAgentCounts> };
+
export type SessionInfo =
| { remote: false }
| { remote: true; authenticated: false }
@@ -2020,6 +2068,29 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}
};
},
+ getRunningAgents: async () => {
+ const res = await apiFetch('/api/running-agents');
+ // 503/504 means controller is down; surface as unreachable instead of throwing.
+ if (res.status === 503 || res.status === 504) {
+ return { ok: false as const, unreachable: true as const, agents: [], counts: {} };
+ }
+ if (!res.ok) {
+ await handleApiError(res, '/api/running-agents');
+ }
+ return res.json();
+ },
+ endRunningAgent: async (payload) => {
+ const res = await apiFetch('/api/running-agents/end', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ if (res.status === 503) {
+ return { ok: false, unreachable: true };
+ }
+ // 409 (couldn't end) returns a body with ok:false + error; surface it.
+ return res.json().catch(() => ({ ok: res.ok }));
+ },
remoteAccessStatus: () => getJson('/api/remote-access/status'),
pairVibeCloudRemoteAccess: (payload) => postJson('/api/remote-access/vibe-cloud/pair', payload),
startRemoteAccess: () => postJson('/api/remote-access/start', {}),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 949256a3c..39af18a27 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1537,6 +1537,30 @@
"agents": {
"title": "Agents",
"subtitle": "{{count}} agents registered across all backends.",
+ "tabs": {
+ "definitions": "Definitions",
+ "running": "Running"
+ },
+ "running": {
+ "empty": "No agents are currently running.",
+ "unreachableTitle": "Runtime unreachable",
+ "unreachableBody": "The Avibe controller is not responding. Start the service and try again.",
+ "stateActive": "active",
+ "stateIdle": "idle",
+ "stateOrphan": "orphan",
+ "orphan": "orphan process",
+ "busy": "busy {{elapsed}}",
+ "idleElapsed": "idle {{elapsed}}",
+ "openChat": "Open chat",
+ "agentInitiated": "agent",
+ "endActive": "Stop",
+ "endIdle": "Disconnect",
+ "endOrphan": "Kill process",
+ "confirmEnd": "Confirm",
+ "endedToast": "Ended",
+ "endFailedToast": "Couldn't end ({{error}})",
+ "pidShared": "(shared)"
+ },
"showDisabled": "Show disabled",
"statusEnabled": "enabled",
"statusDisabled": "disabled",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 4b5263b40..1a95f8d1c 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1537,6 +1537,30 @@
"agents": {
"title": "Agents",
"subtitle": "已登记 {{count}} 个 Agent。",
+ "tabs": {
+ "definitions": "定义",
+ "running": "运行中"
+ },
+ "running": {
+ "empty": "当前没有正在运行的 Agent。",
+ "unreachableTitle": "运行时不可达",
+ "unreachableBody": "Avibe 控制器无响应,请启动服务后重试。",
+ "stateActive": "运行中",
+ "stateIdle": "空闲",
+ "stateOrphan": "孤儿进程",
+ "orphan": "孤儿进程",
+ "busy": "忙碌 {{elapsed}}",
+ "idleElapsed": "空闲 {{elapsed}}",
+ "openChat": "打开会话",
+ "agentInitiated": "agent 发起",
+ "endActive": "停止",
+ "endIdle": "断开",
+ "endOrphan": "杀进程",
+ "confirmEnd": "确认",
+ "endedToast": "已结束",
+ "endFailedToast": "无法结束({{error}})",
+ "pidShared": "(共享)"
+ },
"showDisabled": "显示已禁用",
"statusEnabled": "已启用",
"statusDisabled": "已停用",
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 0fbf454ef..572aa337b 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -268,6 +268,31 @@ async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def end_running_agent(payload: dict[str, Any], *, socket_path: Optional[Path] = None) -> dict[str, Any]:
+ """Ask the controller to terminate one running agent's live runtime.
+
+ ``payload`` identifies the target (backend/state/composite_key/base_session_id
+ /pid). Returns ``{status_code, body}``; raises ``InternalServerUnavailable``
+ on socket failure. A Claude interrupt / OpenCode abort can take a few seconds,
+ so the timeout matches ``cancel_dispatch``.
+ """
+
+ target = (socket_path or default_socket_path()).expanduser().resolve()
+ if not target.exists():
+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")
+ transport = httpx.AsyncHTTPTransport(uds=str(target))
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(30.0, connect=1.0),
+ ) as client:
+ resp = await client.post("/internal/running-agents/end", json=payload)
+ except _SOCKET_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+
+
async def send_now(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:
"""Ask the controller to run a session's send-while-busy queue immediately
("立即发送"): interrupt any running turn + flush the queue. Returns
@@ -318,6 +343,34 @@ async def turn_state(session_id: str, *, socket_path: Optional[Path] = None) ->
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def list_running_agents(*, socket_path: Optional[Path] = None) -> dict[str, Any]:
+ """Fetch the controller's read-only running-agents snapshot.
+
+ Returns ``{status_code, body}``; raises ``InternalServerUnavailable`` on
+ socket failure so the web route can render an explicit "runtime unreachable"
+ state instead of a misleading "0 running". The snapshot reads in-memory
+ registries plus a small DB enrichment, so the read timeout is a touch longer
+ than ``turn_state``.
+ """
+
+ target = (socket_path or default_socket_path()).expanduser().resolve()
+ if not target.exists():
+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")
+ transport = httpx.AsyncHTTPTransport(uds=str(target))
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(3.0, connect=0.5),
+ ) as client:
+ resp = await client.get("/internal/running-agents")
+ except httpx.ReadTimeout as exc:
+ raise InternalServerTimeout(str(exc)) from exc
+ except _SOCKET_CONNECT_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+
+
async def health(socket_path: Optional[Path] = None) -> bool:
"""Probe ``GET /internal/health``. Returns False on any failure.
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index ac83c766f..3749c72b0 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2337,6 +2337,42 @@ def vibe_agents_get():
return _vibe_agent_error_response(exc)
[email protected]("/api/running-agents", methods=["GET"])
+async def running_agents_get():
+ """Proxy the controller's read-only running-agents snapshot to the workbench.
+
+ Every liveness source lives in the controller process, so this awaits the
+ internal Unix-socket snapshot and degrades to an explicit ``unreachable``
+ payload (never a misleading empty/0 list) when the controller is down, so the
+ Running tab can render a distinct "runtime unreachable" state (I1)."""
+ from vibe import internal_client
+
+ try:
+ result = await internal_client.list_running_agents()
+ except internal_client.InternalServerUnavailable:
+ return jsonify({"ok": False, "unreachable": True, "agents": [], "counts": {}}), 503
+ except internal_client.InternalServerTimeout:
+ return jsonify({"ok": False, "unreachable": True, "timeout": True, "agents": [], "counts": {}}), 504
+ return jsonify(result.get("body") or {})
+
+
[email protected]("/api/running-agents/end", methods=["POST"])
+async def running_agents_end():
+ """Terminate one running agent's live runtime (Stop turn / disconnect / kill
+ orphan), dispatched controller-side by backend+state. Proxies the internal
+ socket; degrades to 503 when the controller is down."""
+ from vibe import internal_client
+
+ payload = request.json or {}
+ try:
+ result = await internal_client.end_running_agent(payload)
+ except internal_client.InternalServerUnavailable:
+ return jsonify({"ok": False, "unreachable": True}), 503
+ body = result.get("body") or {}
+ # Surface the controller's status (409 when the target couldn't be ended).
+ return jsonify(body), (result.get("status_code") or 200)
+
+
@app.route("/api/agents/<name>", methods=["GET"])
def vibe_agent_get(name):
from vibe import api