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.

perf(ui): drive workbench updates from SSE (#765)

Call White6b243b9005c2
diff --git a/core/inbox_events.py b/core/inbox_events.py
index 860d8bc23..aba59622b 100644
--- a/core/inbox_events.py
+++ b/core/inbox_events.py
@@ -19,6 +19,20 @@ from typing import Any
logger = logging.getLogger(__name__)
+RUNS_UPDATED_EVENT = "runs.updated"
+VAULTS_UPDATED_EVENT = "vaults.updated"
+WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT = "workbench.events.bridge.status"
+_CONTROLLER_PROCESS = False
+
+
+def mark_controller_process() -> None:
+ global _CONTROLLER_PROCESS
+ _CONTROLLER_PROCESS = True
+
+
+def is_controller_process() -> bool:
+ return _CONTROLLER_PROCESS
+
class InboxEventBus:
def __init__(self) -> None:
@@ -39,6 +53,10 @@ class InboxEventBus:
with self._lock:
self._subscribers.pop(sub_id, None)
+ def subscriber_count(self) -> int:
+ with self._lock:
+ return len(self._subscribers)
+
def publish(self, event_type: str, data: Any) -> None:
"""Fan ``(event_type, data)`` out to every subscriber. No-op when none."""
with self._lock:
@@ -63,3 +81,58 @@ class InboxEventBus:
# Process-wide singleton (Controller process). ``message_mirror`` publishes;
# ``internal_server`` subscribes.
bus = InboxEventBus()
+
+
+def run_updated_payload(
+ *,
+ run_id: str,
+ status: str,
+ run_type: str | None = None,
+ session_id: str | None = None,
+ definition_id: str | None = None,
+ updated_at: str | None = None,
+ cancel_requested: bool | None = None,
+) -> dict[str, Any]:
+ """Minimal run-lifecycle payload for browser refetch-on-event consumers."""
+
+ payload: dict[str, Any] = {"run_id": run_id, "status": status}
+ if run_type:
+ payload["run_type"] = run_type
+ if session_id:
+ payload["session_id"] = session_id
+ if definition_id:
+ payload["definition_id"] = definition_id
+ if updated_at:
+ payload["updated_at"] = updated_at
+ if cancel_requested is not None:
+ payload["cancel_requested"] = cancel_requested
+ return payload
+
+
+def vaults_updated_payload(
+ *,
+ scope: str,
+ request_id: str | None = None,
+ request_status: str | None = None,
+ grant_id: str | None = None,
+ grant_status: str | None = None,
+ secret_name: str | None = None,
+) -> dict[str, Any]:
+ """Minimal vault-state payload for browser refetch-on-event consumers."""
+
+ payload: dict[str, Any] = {"scope": scope}
+ if request_id:
+ payload["request_id"] = request_id
+ if request_status:
+ payload["request_status"] = request_status
+ if grant_id:
+ payload["grant_id"] = grant_id
+ if grant_status:
+ payload["grant_status"] = grant_status
+ if secret_name:
+ payload["secret_name"] = secret_name
+ return payload
+
+
+def publish_run_updated(**kwargs: Any) -> None:
+ bus.publish(RUNS_UPDATED_EVENT, run_updated_payload(**kwargs))
diff --git a/core/internal_server.py b/core/internal_server.py
index 8929a987a..7db58161f 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -71,6 +71,9 @@ def create_app(controller: "Controller") -> FastAPI:
Factored out so tests can mount the same routes against a fake
controller without spinning up uvicorn.
"""
+ from core.inbox_events import mark_controller_process
+
+ mark_controller_process()
app = FastAPI(
title="avibe internal dispatch",
@@ -430,6 +433,28 @@ def create_app(controller: "Controller") -> FastAPI:
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
)
+ @app.post("/internal/events")
+ async def _publish_event(request: Request) -> Any:
+ """Publish an allowlisted notification into the Controller event bus.
+
+ Local child processes cannot share ``core.inbox_events.bus`` directly,
+ but they can reach this permission-restricted Unix socket and reuse the
+ same Controller -> UI-server -> browser SSE path.
+ """
+ from core.inbox_events import RUNS_UPDATED_EVENT, VAULTS_UPDATED_EVENT, bus
+
+ payload = await _safe_json(request)
+ if not isinstance(payload, dict):
+ return JSONResponse(status_code=400, content={"ok": False, "error": "invalid_payload"})
+ event_type = str(payload.get("type") or "").strip()
+ data = payload.get("data")
+ if event_type not in {RUNS_UPDATED_EVENT, VAULTS_UPDATED_EVENT}:
+ return JSONResponse(status_code=400, content={"ok": False, "error": "unsupported_event_type"})
+ if not isinstance(data, dict):
+ return JSONResponse(status_code=400, content={"ok": False, "error": "invalid_event_data"})
+ bus.publish(event_type, data)
+ return {"ok": True}
+
@app.post("/internal/cancel/{session_id}")
async def _cancel(session_id: str) -> Any:
"""HTTP adapter: delegate Stop to the turn owner (FSM, Phase 1b) and map its
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index ce1515813..d494340f3 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -1382,9 +1382,12 @@ class TaskExecutionStore:
error: Optional[str] = None,
) -> None:
if self._sqlite is not None:
- from storage.background import complete_coalesced_agent_runs_for_workbench_in_connection
+ from storage.background import (
+ complete_coalesced_agent_runs_for_workbench_in_connection,
+ run_update_event_transaction,
+ )
- with self._sqlite.engine.begin() as conn:
+ with run_update_event_transaction(self._sqlite.engine) as conn:
complete_coalesced_agent_runs_for_workbench_in_connection(
conn,
run_ids,
diff --git a/core/session_turns.py b/core/session_turns.py
index c6b8202f9..6911be1b0 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -748,6 +748,7 @@ class SessionTurnManager:
from core.inbox_events import bus
from core.workbench_media import file_attachments_from_specs, resolve_attachment_specs
from storage import messages_service
+ from storage.background import run_update_event_transaction
from storage.db import create_sqlite_engine
if not session_id:
@@ -767,7 +768,7 @@ class SessionTurnManager:
claimed_agent_run_ids: list[str] = []
try:
engine = create_sqlite_engine()
- with engine.begin() as conn:
+ with run_update_event_transaction(engine) as conn:
rows = messages_service.list_queued(conn, session_id)
if not rows:
return False
@@ -949,7 +950,7 @@ class SessionTurnManager:
retry_agent_run_flush = False
try:
engine = create_sqlite_engine()
- with engine.begin() as conn:
+ with run_update_event_transaction(engine) as conn:
claimed_run_ids = _claim_agent_run_segment_and_retire_queue(
conn,
run_ids=pending_agent_run_ids,
@@ -995,7 +996,7 @@ class SessionTurnManager:
from storage.background import reset_workbench_claimed_runs_in_connection
engine = create_sqlite_engine()
- with engine.begin() as conn:
+ with run_update_event_transaction(engine) as conn:
reset_workbench_claimed_runs_in_connection(conn, claimed_agent_run_ids)
_restore_queued_rows(conn, pending_scheduled_segment)
except Exception:
diff --git a/storage/background.py b/storage/background.py
index 559684207..bd9171abe 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
import logging
+from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
@@ -94,6 +95,7 @@ RUN_STATUS_ALIASES: dict[str, str] = {
_LIKE_ESCAPE = "\\"
DEFINITION_STATUS_COUNTS = ("all", "enabled", "disabled")
RUN_STATUS_COUNTS = ("all", "queued", "running", "succeeded", "failed", "canceled")
+_DEFERRED_RUN_EVENT_ROWS_KEY = "avibe.deferred_run_event_rows"
def normalize_run_status(status: Any) -> str:
@@ -106,6 +108,96 @@ def _status_query_values(status: str) -> list[str]:
return values or [normalized]
+def _publish_run_rows_updated(rows: list[Any]) -> None:
+ if not rows:
+ return
+ try:
+ from core.inbox_events import RUNS_UPDATED_EVENT, bus, is_controller_process, run_updated_payload
+ except Exception:
+ logger.debug("failed to import run event publisher", exc_info=True)
+ return
+ for raw_row in rows:
+ if raw_row is None:
+ continue
+ row = dict(raw_row)
+ run_id = str(row.get("id") or "").strip()
+ if not run_id:
+ continue
+ try:
+ payload = run_updated_payload(
+ run_id=run_id,
+ status=normalize_run_status(row.get("status")),
+ run_type=row.get("run_type"),
+ session_id=row.get("session_id"),
+ definition_id=row.get("definition_id"),
+ updated_at=row.get("updated_at"),
+ cancel_requested=bool(row.get("cancel_requested")),
+ )
+ bus.publish(RUNS_UPDATED_EVENT, payload)
+ if bus.subscriber_count() == 0 and not is_controller_process():
+ try:
+ from vibe import internal_client
+
+ internal_client.publish_event_sync(RUNS_UPDATED_EVENT, payload, timeout=1.5)
+ except Exception:
+ logger.debug("failed to bridge runs.updated for %s", run_id, exc_info=True)
+ except Exception:
+ logger.debug("failed to publish runs.updated for %s", run_id, exc_info=True)
+
+
+def _defer_run_rows_updated_from_connection(conn: Any, rows: list[Any]) -> None:
+ if not rows:
+ return
+ pending = conn.info.setdefault(_DEFERRED_RUN_EVENT_ROWS_KEY, {})
+ for raw_row in rows:
+ if raw_row is None:
+ continue
+ row = dict(raw_row)
+ run_id = str(row.get("id") or "").strip()
+ if run_id:
+ pending[run_id] = row
+
+
+def pop_deferred_run_event_rows_from_connection(conn: Any) -> list[dict[str, Any]]:
+ pending = conn.info.pop(_DEFERRED_RUN_EVENT_ROWS_KEY, {})
+ if not isinstance(pending, dict):
+ return []
+ return [dict(row) for row in pending.values() if row is not None]
+
+
+@contextmanager
+def run_update_event_transaction(engine: Any):
+ """Commit DB writes before publishing deferred ``runs.updated`` snapshots."""
+
+ pending_rows: list[dict[str, Any]] = []
+ with engine.begin() as conn:
+ try:
+ yield conn
+ pending_rows = pop_deferred_run_event_rows_from_connection(conn)
+ except Exception:
+ conn.info.pop(_DEFERRED_RUN_EVENT_ROWS_KEY, None)
+ raise
+ _publish_run_rows_updated(pending_rows)
+
+
+def _run_rows_for_ids(conn: Any, run_ids: list[str]) -> list[Any]:
+ normalized_ids: list[str] = []
+ seen: set[str] = set()
+ for raw_run_id in run_ids:
+ run_id = str(raw_run_id or "").strip()
+ if not run_id or run_id in seen:
+ continue
+ seen.add(run_id)
+ normalized_ids.append(run_id)
+ if not normalized_ids:
+ return []
+ return list(conn.execute(select(agent_runs).where(agent_runs.c.id.in_(normalized_ids))).mappings())
+
+
+def _defer_run_ids_updated_from_connection(conn: Any, run_ids: list[str]) -> None:
+ _defer_run_rows_updated_from_connection(conn, _run_rows_for_ids(conn, run_ids))
+
+
def _like_contains_pattern(value: str) -> str:
escaped = (
value.replace(_LIKE_ESCAPE, _LIKE_ESCAPE + _LIKE_ESCAPE)
@@ -174,6 +266,7 @@ def complete_coalesced_agent_runs_for_workbench_in_connection(
result = conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
if result.rowcount:
completed_ids.append(run_id)
+ _defer_run_ids_updated_from_connection(conn, completed_ids)
return completed_ids
@@ -238,6 +331,7 @@ def claim_queued_runs_for_workbench_in_connection(
)
if not result.rowcount:
raise RuntimeError(f"failed to claim queued agent run {run_id}")
+ _defer_run_ids_updated_from_connection(conn, normalized_run_ids)
return normalized_run_ids
@@ -352,12 +446,14 @@ def inspect_queued_runs_for_workbench_in_connection(conn: Any, run_ids: list[str
.where(agent_runs.c.status.in_(_status_query_values("queued")))
.values(status="canceled", completed_at=now, updated_at=now)
)
+ _defer_run_ids_updated_from_connection(conn, cancel_requested_run_ids)
return queued_run_ids, stale_run_ids
def reset_workbench_claimed_runs_in_connection(conn: Any, run_ids: list[str]) -> None:
now = _utc_now_iso()
seen: set[str] = set()
+ changed_ids: list[str] = []
for raw_run_id in run_ids:
run_id = str(raw_run_id or "").strip()
if not run_id or run_id in seen:
@@ -384,6 +480,8 @@ def reset_workbench_claimed_runs_in_connection(conn: Any, run_ids: list[str]) ->
.where(agent_runs.c.id == run_id)
.values(**values)
)
+ changed_ids.append(run_id)
+ _defer_run_ids_updated_from_connection(conn, changed_ids)
class SQLiteBackgroundTaskStore:
@@ -563,6 +661,7 @@ class SQLiteBackgroundTaskStore:
def enqueue_run(self, payload: dict[str, Any]) -> None:
values = self._run_values(payload)
+ row_to_publish = None
with self.engine.begin() as conn:
existing = conn.execute(
select(agent_runs.c.id).where(agent_runs.c.id == values["id"]).limit(1)
@@ -571,6 +670,10 @@ class SQLiteBackgroundTaskStore:
conn.execute(update(agent_runs).where(agent_runs.c.id == values["id"]).values(**values))
else:
conn.execute(insert(agent_runs).values(**values))
+ row_to_publish = dict(
+ conn.execute(select(agent_runs).where(agent_runs.c.id == values["id"]).limit(1)).mappings().one()
+ )
+ _publish_run_rows_updated([row_to_publish])
def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:
stmt = self._runs_query(status=status).order_by(agent_runs.c.created_at, agent_runs.c.id)
@@ -820,6 +923,7 @@ class SQLiteBackgroundTaskStore:
def cancel_run(self, run_id: str, *, requested_at: Optional[str] = None) -> bool:
now = requested_at or _utc_now_iso()
+ row_to_publish = None
with self.engine.begin() as conn:
row = conn.execute(select(agent_runs.c.status).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
if not row:
@@ -838,9 +942,16 @@ class SQLiteBackgroundTaskStore:
.where(agent_runs.c.id == run_id)
.values(**values)
)
- return bool(result.rowcount)
+ if result.rowcount:
+ row_to_publish = dict(
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().one()
+ )
+ _publish_run_rows_updated([row_to_publish])
+ return row_to_publish is not None
def claim_pending_run(self, run_id: str, *, started_at: str) -> Optional[dict[str, Any]]:
+ row_to_publish = None
+ payload = None
with self.engine.begin() as conn:
row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
if not row:
@@ -851,17 +962,25 @@ class SQLiteBackgroundTaskStore:
.where(agent_runs.c.id == run_id)
.values(status="canceled", completed_at=started_at, updated_at=started_at)
)
- return None
- result = conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == run_id)
- .where(agent_runs.c.status.in_(_status_query_values("queued")))
- .values(status="running", started_at=started_at, updated_at=started_at)
- )
- if not result.rowcount:
- return None
- row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
- return self._run_from_row(row) if row else None
+ row_to_publish = dict(
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().one()
+ )
+ payload = None
+ else:
+ result = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .where(agent_runs.c.status.in_(_status_query_values("queued")))
+ .values(status="running", started_at=started_at, updated_at=started_at)
+ )
+ if not result.rowcount:
+ return None
+ row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
+ if row:
+ row_to_publish = dict(row)
+ payload = self._run_from_row(row)
+ _publish_run_rows_updated([row_to_publish])
+ return payload
def update_run_status(
self,
@@ -939,8 +1058,14 @@ class SQLiteBackgroundTaskStore:
values["callback_run_id"] = callback_run_id
if callback_completed_at is not None:
values["callback_completed_at"] = callback_completed_at
+ row_to_publish = None
with self.engine.begin() as conn:
- conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
+ result = conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
+ if result.rowcount:
+ row_to_publish = dict(
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().one()
+ )
+ _publish_run_rows_updated([row_to_publish])
def update_callback_status(
self,
@@ -992,6 +1117,7 @@ class SQLiteBackgroundTaskStore:
merged = dict(existing.get("metadata") or {})
merged.update(metadata)
values["metadata_json"] = _json_dumps(merged)
+ row_to_publish = None
with self.engine.begin() as conn:
result = conn.execute(
update(agent_runs)
@@ -999,7 +1125,12 @@ class SQLiteBackgroundTaskStore:
.where(agent_runs.c.status.in_(_status_query_values("running")))
.values(**values)
)
- return bool(result.rowcount)
+ if result.rowcount:
+ row_to_publish = dict(
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().one()
+ )
+ _publish_run_rows_updated([row_to_publish])
+ return row_to_publish is not None
def claim_queued_run_for_workbench(
self,
@@ -1015,11 +1146,11 @@ class SQLiteBackgroundTaskStore:
*,
started_at: Optional[str] = None,
) -> list[str]:
- with self.engine.begin() as conn:
+ with run_update_event_transaction(self.engine) as conn:
return claim_queued_runs_for_workbench_in_connection(conn, run_ids, started_at=started_at)
def inspect_queued_runs_for_workbench(self, run_ids: list[str]) -> tuple[list[str], list[str]]:
- with self.engine.begin() as conn:
+ with run_update_event_transaction(self.engine) as conn:
return inspect_queued_runs_for_workbench_in_connection(conn, run_ids)
def record_run_message(
@@ -1032,6 +1163,7 @@ class SQLiteBackgroundTaskStore:
updated_at: Optional[str] = None,
) -> None:
now = updated_at or _utc_now_iso()
+ row_to_publish = None
with self.engine.begin() as conn:
row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
if not row:
@@ -1053,15 +1185,28 @@ class SQLiteBackgroundTaskStore:
if terminal_status:
values["status"] = normalize_run_status(terminal_status)
values["completed_at"] = now
- conn.execute(
+ result = conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
.values(**values)
)
+ if terminal_status and result.rowcount:
+ row_to_publish = dict(
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().one()
+ )
+ _publish_run_rows_updated([row_to_publish])
def recover_processing_runs(self) -> None:
- with self.engine.begin() as conn:
+ with run_update_event_transaction(self.engine) as conn:
now = _utc_now_iso()
+ rows = list(
+ conn.execute(
+ select(agent_runs.c.id)
+ .where(agent_runs.c.status.in_(_status_query_values("running")))
+ .where(agent_runs.c.run_type != "watch_runtime")
+ ).mappings()
+ )
+ recovered_ids = [str(row["id"]) for row in rows]
conn.execute(
update(agent_runs)
.where(agent_runs.c.status.in_(_status_query_values("running")))
@@ -1069,6 +1214,7 @@ class SQLiteBackgroundTaskStore:
.values(status="queued", started_at=None, pid=None, updated_at=now)
)
_refresh_recovered_coalesced_workbench_runs_in_connection(conn, now=now)
+ _defer_run_ids_updated_from_connection(conn, recovered_ids)
def write_watch_runtime(self, payload: dict[str, Any], *, updated_at: str) -> None:
watches = payload.get("watches", {}) if isinstance(payload, dict) else {}
diff --git a/storage/vault_service.py b/storage/vault_service.py
index a743086d7..3c08796bc 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -996,8 +996,8 @@ def fulfill_pending_provision_requests_for_secret(
name: str,
*,
decided_at: str | None = None,
-) -> None:
- conn.execute(
+) -> int:
+ result = conn.execute(
vault_requests.update()
.where(
vault_requests.c.request_type == "provision",
@@ -1006,6 +1006,7 @@ def fulfill_pending_provision_requests_for_secret(
)
.values(status="fulfilled", decided_at=decided_at or _now())
)
+ return int(result.rowcount or 0)
def create_secret(
diff --git a/tests/test_inbox_bridge.py b/tests/test_inbox_bridge.py
new file mode 100644
index 000000000..e2a4d2c23
--- /dev/null
+++ b/tests/test_inbox_bridge.py
@@ -0,0 +1,54 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+
+def test_inbox_bridge_publishes_controller_bridge_status(monkeypatch):
+ from vibe import inbox_bridge
+
+ published = []
+ inbox_bridge._bridge_connected = False
+
+ async def stream_events():
+ yield "connected", {}
+ yield "runs.updated", {"run_id": "run_1", "status": "queued"}
+
+ async def stop_after_disconnect(_delay):
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(inbox_bridge.internal_client, "stream_events", stream_events)
+ monkeypatch.setattr(inbox_bridge.broker, "publish", lambda event_type, data: published.append((event_type, data)))
+ monkeypatch.setattr(inbox_bridge.asyncio, "sleep", stop_after_disconnect)
+
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(inbox_bridge.run_inbox_bridge())
+
+ assert inbox_bridge.is_bridge_connected() is False
+ assert published == [
+ ("workbench.events.bridge.status", {"connected": True}),
+ ("connected", {}),
+ ("runs.updated", {"run_id": "run_1", "status": "queued"}),
+ ("workbench.events.bridge.status", {"connected": False}),
+ ]
+
+
+def test_inbox_bridge_tracks_current_status(monkeypatch):
+ from vibe import inbox_bridge
+
+ published = []
+ inbox_bridge._bridge_connected = False
+ monkeypatch.setattr(inbox_bridge.broker, "publish", lambda event_type, data: published.append((event_type, data)))
+
+ inbox_bridge._set_bridge_connected(True)
+ assert inbox_bridge.is_bridge_connected() is True
+
+ inbox_bridge._set_bridge_connected(True)
+ inbox_bridge._set_bridge_connected(False)
+
+ assert inbox_bridge.is_bridge_connected() is False
+ assert published == [
+ ("workbench.events.bridge.status", {"connected": True}),
+ ("workbench.events.bridge.status", {"connected": False}),
+ ]
diff --git a/tests/test_inbox_events.py b/tests/test_inbox_events.py
index d0aa118f4..c2efe4029 100644
--- a/tests/test_inbox_events.py
+++ b/tests/test_inbox_events.py
@@ -71,3 +71,129 @@ def test_unsubscribe_stops_delivery():
def test_publish_without_subscribers_is_noop():
# No loop captured, no subscribers — must not raise (boot / headless path).
InboxEventBus().publish("inbox.session.updated", {"x": 1})
+
+
+def test_sqlite_background_store_publishes_run_updates(tmp_path):
+ async def scenario():
+ from core import inbox_events
+ from storage.background import SQLiteBackgroundTaskStore
+
+ sub_id, queue = inbox_events.bus.subscribe()
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ store.enqueue_run(
+ {
+ "id": "run_evt_1",
+ "request_type": "agent_run",
+ "status": "queued",
+ "message": "hello",
+ "created_at": "2026-07-04T00:00:00+00:00",
+ "updated_at": "2026-07-04T00:00:00+00:00",
+ "session_id": "ses_evt",
+ }
+ )
+ queued = await asyncio.wait_for(queue.get(), timeout=1.0)
+
+ claimed = store.claim_pending_run("run_evt_1", started_at="2026-07-04T00:00:01+00:00")
+ assert claimed is not None
+ running = await asyncio.wait_for(queue.get(), timeout=1.0)
+
+ store.update_run_status(
+ "run_evt_1",
+ status="failed",
+ updated_at="2026-07-04T00:00:02+00:00",
+ completed_at="2026-07-04T00:00:02+00:00",
+ error="boom",
+ )
+ failed = await asyncio.wait_for(queue.get(), timeout=1.0)
+ return queued, running, failed
+ finally:
+ store.close()
+ inbox_events.bus.unsubscribe(sub_id)
+
+ queued, running, failed = asyncio.run(scenario())
+ assert queued == (
+ "runs.updated",
+ {
+ "run_id": "run_evt_1",
+ "status": "queued",
+ "run_type": "agent_run",
+ "session_id": "ses_evt",
+ "updated_at": "2026-07-04T00:00:00+00:00",
+ "cancel_requested": False,
+ },
+ )
+ assert running[0] == "runs.updated"
+ assert running[1]["run_id"] == "run_evt_1"
+ assert running[1]["status"] == "running"
+ assert failed[0] == "runs.updated"
+ assert failed[1]["run_id"] == "run_evt_1"
+ assert failed[1]["status"] == "failed"
+
+
+def test_sqlite_background_store_bridges_run_updates_without_local_subscribers(tmp_path, monkeypatch):
+ from core import inbox_events
+ from storage.background import SQLiteBackgroundTaskStore
+
+ bridged = []
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", False)
+ monkeypatch.setattr(
+ "vibe.internal_client.publish_event_sync",
+ lambda event_type, data, **kwargs: bridged.append((event_type, data, kwargs)),
+ )
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ store.enqueue_run(
+ {
+ "id": "run_evt_bridge",
+ "request_type": "agent_run",
+ "status": "queued",
+ "message": "hello",
+ "created_at": "2026-07-04T00:00:00+00:00",
+ "updated_at": "2026-07-04T00:00:00+00:00",
+ }
+ )
+ finally:
+ store.close()
+
+ assert bridged == [
+ (
+ "runs.updated",
+ {
+ "run_id": "run_evt_bridge",
+ "status": "queued",
+ "run_type": "agent_run",
+ "updated_at": "2026-07-04T00:00:00+00:00",
+ "cancel_requested": False,
+ },
+ {"timeout": 1.5},
+ )
+ ]
+
+
+def test_sqlite_background_store_does_not_bridge_controller_self_updates(tmp_path, monkeypatch):
+ from core import inbox_events
+ from storage.background import SQLiteBackgroundTaskStore
+
+ bridged = []
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", True)
+ monkeypatch.setattr(
+ "vibe.internal_client.publish_event_sync",
+ lambda event_type, data, **kwargs: bridged.append((event_type, data, kwargs)),
+ )
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ store.enqueue_run(
+ {
+ "id": "run_evt_controller",
+ "request_type": "agent_run",
+ "status": "queued",
+ "message": "hello",
+ "created_at": "2026-07-04T00:00:00+00:00",
+ "updated_at": "2026-07-04T00:00:00+00:00",
+ }
+ )
+ finally:
+ store.close()
+
+ assert bridged == []
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 6cc6d85f7..1af1be30d 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -160,6 +160,8 @@ def test_create_app_exposes_minimal_endpoints():
assert ("/internal/reconcile-platforms", ("POST",)) in routes
assert ("/internal/cancel/{session_id}", ("POST",)) in routes
assert ("/internal/dispatch", ("POST",)) in routes
+ assert ("/internal/events", ("GET",)) in routes
+ assert ("/internal/events", ("POST",)) in routes
# ---------------------------------------------------------------------
@@ -181,6 +183,39 @@ def test_health_endpoint():
assert resp.json() == {"ok": True, "service": "vibe-remote-internal", "version": 1}
+async def _publish_event_round_trip():
+ from core import inbox_events
+
+ app = internal_server.create_app(_build_controller_double())
+ transport = httpx.ASGITransport(app=app)
+ sub_id, queue = inbox_events.bus.subscribe()
+ try:
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.post(
+ "/internal/events",
+ json={
+ "type": "vaults.updated",
+ "data": {"scope": "request", "request_id": "vreq_1", "request_status": "pending"},
+ },
+ )
+ bad_resp = await client.post("/internal/events", json={"type": "unsupported", "data": {}})
+ event = await asyncio.wait_for(queue.get(), timeout=1.0)
+ return resp, bad_resp, event
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+
+
+def test_publish_event_endpoint_emits_allowlisted_bus_event():
+ resp, bad_resp, event = asyncio.run(_publish_event_round_trip())
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": True}
+ assert bad_resp.status_code == 400
+ assert event == (
+ "vaults.updated",
+ {"scope": "request", "request_id": "vreq_1", "request_status": "pending"},
+ )
+
+
def test_reconcile_platforms_endpoint_calls_controller(monkeypatch):
controller = _build_controller_double()
calls = []
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 3b45a97f5..cb6940900 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -2342,6 +2342,32 @@ def test_inspect_queued_runs_finalizes_cancel_requested_queued_agent_run(monkeyp
assert stored["completed_at"] is not None
+def test_claim_queued_runs_publishes_after_commit(monkeypatch, tmp_path) -> None:
+ import storage.background as background_module
+
+ _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id="placeholder",
+ message="queued run",
+ agent_name="codex",
+ metadata={"workbench_queue_holds_run": True},
+ )
+ bg = request_store._sqlite
+ assert bg is not None
+
+ observed_statuses: list[str | None] = []
+
+ def capture_publish(_rows):
+ stored = bg.get_run(request.id)
+ observed_statuses.append(stored["status"] if stored else None)
+
+ monkeypatch.setattr(background_module, "_publish_run_rows_updated", capture_publish)
+
+ assert bg.claim_queued_runs_for_workbench([request.id]) == [request.id]
+ assert observed_statuses == ["running"]
+
+
def test_drain_requests_reserves_watch_create_per_run_before_session_validation(tmp_path: Path) -> None:
request_store = TaskExecutionStore(tmp_path / "task_requests")
request = request_store.enqueue_definition_run(
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
index 27cfa710a..c5fa189ca 100644
--- a/tests/test_vault_api.py
+++ b/tests/test_vault_api.py
@@ -110,6 +110,25 @@ def test_create_list_delete_roundtrip(monkeypatch):
assert api.get_vault_secrets()["secrets"] == []
+def test_create_vault_secret_publishes_update_event(monkeypatch):
+ published = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ monkeypatch.setattr("vibe.internal_client.publish_event_sync", lambda *args, **kwargs: None)
+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
+
+ api.create_vault_secret(
+ {
+ "name": "EVENT_KEY",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ }
+ )
+
+ assert ("vaults.updated", {"scope": "secret", "secret_name": "EVENT_KEY"}) in published
+
+
def test_standard_rest_create_rejects_plaintext_value(monkeypatch):
from unittest.mock import Mock
@@ -364,6 +383,36 @@ def test_secret_exists_response_commits_stale_pending_provision_cleanup(monkeypa
assert stale_status == "fulfilled"
+def test_secret_exists_response_publishes_when_fulfilling_stale_provisions(monkeypatch):
+ published = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ monkeypatch.setattr("vibe.internal_client.publish_event_sync", lambda *args, **kwargs: None)
+ seal = Mock(side_effect=[_sealed("first"), _sealed("second")])
+ monkeypatch.setattr(api, "avault_seal_blind_box", seal)
+ with api._vault_engine().begin() as conn:
+ req = vault_service.create_provision_request(conn, "GH_TOKEN")
+
+ payload = {
+ "name": "GH_TOKEN",
+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},
+ "provision_request_id": req["id"],
+ }
+ api.create_vault_secret(payload)
+ published.clear()
+ with api._vault_engine().begin() as conn:
+ stale = vault_service.create_provision_request(conn, "GH_TOKEN")
+ conn.execute(vault_requests.update().where(vault_requests.c.id == stale["id"]).values(status="pending"))
+
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_secret({**payload, "blind_box": {**payload["blind_box"], "enc": "enc2", "ct": "ct2"}})
+
+ assert exc.value.code == "secret_exists"
+ assert ("vaults.updated", {"scope": "secret", "request_status": "fulfilled", "secret_name": "GH_TOKEN"}) in published
+
+
def test_duplicate_name_conflict(monkeypatch):
from unittest.mock import Mock
@@ -1563,6 +1612,12 @@ def test_revoke_grant_releases_only_that_grant_id(monkeypatch):
def test_consume_one_shot_releases_only_that_grant_id(monkeypatch):
+ published = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ monkeypatch.setattr("vibe.internal_client.publish_event_sync", lambda *args, **kwargs: None)
monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))
agent_release = Mock(return_value={"released": True})
monkeypatch.setattr(api, "avault_agent_release", agent_release)
@@ -1590,9 +1645,19 @@ def test_consume_one_shot_releases_only_that_grant_id(monkeypatch):
)
grant_2 = _grant_from_request(conn, req_2)
+ published.clear()
api.consume_one_shot_grants([grant_1], reason="test")
agent_release.assert_called_once_with(grant_id=grant_1["id"])
+ assert (
+ "vaults.updated",
+ {
+ "scope": "grant",
+ "request_id": grant_1["request_id"],
+ "grant_id": grant_1["id"],
+ "grant_status": "expired",
+ },
+ ) in published
with api._vault_engine().connect() as conn:
statuses = {
row["id"]: row["status"]
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
index bc379b1d7..651890ffb 100644
--- a/tests/test_vault_cli.py
+++ b/tests/test_vault_cli.py
@@ -1635,6 +1635,56 @@ def test_inject_reopens_session_bound_approval_when_agent_cache_is_missing(tmp_p
assert requests[0]["card"]["grant_options"][0]["purpose"] == "inject"
+def test_fetch_resolver_publishes_pending_request_when_approval_required(monkeypatch):
+ published = []
+ monkeypatch.setattr(cli, "_publish_cli_vaults_updated", lambda **kwargs: published.append(kwargs))
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(conn, name="PROTECTED_KEY", protection="protected", sealed=_sealed("protected"))
+
+ with pytest.raises(cli.TaskCliError) as exc_info:
+ cli._resolve_single_vault_delivery(
+ cli._open_vault_engine(),
+ "PROTECTED_KEY",
+ requester={"source": "cli", "session_id": "ses_cli"},
+ delivery={"session_id": "ses_cli", "mode": "fetch"},
+ purpose="fetch",
+ )
+
+ assert exc_info.value.code == "approval_required"
+ assert len(published) == 1
+ request = published[0]["request"]
+ assert published[0]["scope"] == "request"
+ assert request["status"] == "pending"
+ assert request["secret_name"] == "PROTECTED_KEY"
+ assert request["delivery"]["session_id"] == "ses_cli"
+ assert request["card"]["grant_options"][0]["purpose"] == "fetch"
+
+
+def test_inject_resolver_publishes_pending_request_when_approval_required(tmp_path, monkeypatch):
+ published = []
+ monkeypatch.setattr(cli, "_publish_cli_vaults_updated", lambda **kwargs: published.append(kwargs))
+ with cli._open_vault_engine().begin() as conn:
+ vault_service.create_secret(conn, name="PROTECTED_KEY", protection="protected", sealed=_sealed("protected"))
+
+ with pytest.raises(cli.TaskCliError) as exc_info:
+ cli._resolve_vault_inject_delivery(
+ cli._open_vault_engine(),
+ ["PROTECTED_KEY"],
+ path=str(tmp_path / "out.env"),
+ fmt="dotenv",
+ args=_ns(session_id="ses_cli"),
+ )
+
+ assert exc_info.value.code == "approval_required"
+ assert len(published) == 1
+ request = published[0]["request"]
+ assert published[0]["scope"] == "request"
+ assert request["status"] == "pending"
+ assert request["secret_name"] == "PROTECTED_KEY"
+ assert request["delivery"]["session_id"] == "ses_cli"
+ assert request["card"]["grant_options"][0]["purpose"] == "inject"
+
+
def test_run_persists_protected_approval_request_without_grant(capfd):
with cli._open_vault_engine().begin() as conn:
vault_service.create_secret(conn, name="PROTECTED_KEY", protection="protected", sealed=_sealed("protected"))
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 50fadbdd7..1e35d6d4a 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -67,6 +67,7 @@ export const AgentsPage: React.FC = () => {
const { showToast } = useToast();
const [agentsTab, setAgentsTab] = useState<AgentsTabKey>('definitions');
const [runningActiveCount, setRunningActiveCount] = useState<number | null>(null);
+ const [eventBridgeConnected, setEventBridgeConnected] = useState(false);
const [agents, setAgents] = useState<VibeAgentBrief[]>([]);
const [defaultName, setDefaultName] = useState<string | null>(null);
const [selected, setSelected] = useState<VibeAgentFull | null>(null);
@@ -122,36 +123,91 @@ 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.
+ const fetchRunningActiveCount = useCallback(async () => {
+ try {
+ const result = await api.getRunningAgents();
+ if (result.ok && result.counts) {
+ setRunningActiveCount((result.counts as any).active ?? 0);
+ } else {
+ setRunningActiveCount(null);
+ }
+ } catch {
+ setRunningActiveCount(null);
+ }
+ }, [api]);
+
+ useEffect(() => {
+ if (agentsTab !== 'running') void fetchRunningActiveCount();
+ }, [agentsTab, fetchRunningActiveCount]);
+
+ useEffect(() => {
+ if (agentsTab === 'running') return;
+ return api.connectWorkbenchEvents({
+ onConnected: (data) => {
+ if (data.source === 'controller') {
+ setEventBridgeConnected(true);
+ fetchRunningActiveCount();
+ }
+ },
+ onEventBridgeStatus: ({ connected }) => {
+ setEventBridgeConnected(connected);
+ if (connected) fetchRunningActiveCount();
+ },
+ onError: () => setEventBridgeConnected(false),
+ onRunsUpdated: () => fetchRunningActiveCount(),
+ onTurnStart: () => fetchRunningActiveCount(),
+ onTurnEnd: () => fetchRunningActiveCount(),
+ onSessionStatus: () => fetchRunningActiveCount(),
+ });
+ }, [api, agentsTab, fetchRunningActiveCount]);
+
useEffect(() => {
+ if (agentsTab === 'running' || eventBridgeConnected) return;
+ let timer: number | undefined;
let cancelled = false;
- const fetchCount = async () => {
+ let inFlight = false;
+ let pendingWake = false;
+
+ const tick = async () => {
+ if (cancelled) return;
+ if (document.visibilityState !== 'visible') {
+ timer = window.setTimeout(tick, 8000);
+ return;
+ }
+ if (inFlight) {
+ pendingWake = true;
+ return;
+ }
+ inFlight = true;
+ window.clearTimeout(timer);
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);
+ await fetchRunningActiveCount();
+ } finally {
+ inFlight = false;
+ }
+ if (cancelled) return;
+ if (pendingWake) {
+ pendingWake = false;
+ void tick();
+ return;
}
+ timer = window.setTimeout(tick, 8000);
};
- 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);
+
+ const refreshNow = () => {
+ if (document.visibilityState === 'visible') void tick();
+ };
+
+ void tick();
+ document.addEventListener('visibilitychange', refreshNow);
+ window.addEventListener('focus', refreshNow);
return () => {
cancelled = true;
- if (id != null) window.clearInterval(id);
+ window.clearTimeout(timer);
+ document.removeEventListener('visibilitychange', refreshNow);
+ window.removeEventListener('focus', refreshNow);
};
- }, [api, agentsTab]);
+ }, [eventBridgeConnected, agentsTab, fetchRunningActiveCount]);
const selectAgent = useCallback(
async (name: string, openDetail = false) => {
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index 3e8e71292..d0111eecd 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -181,6 +181,14 @@ export const HarnessPage: React.FC = () => {
refresh();
}, [refresh]);
+ useEffect(() => {
+ return api.connectWorkbenchEvents({
+ onRunsUpdated: () => {
+ void refresh();
+ },
+ });
+ }, [api, refresh]);
+
// Resolve agent_name → backend/model/effort for the detail panels: the
// task/watch payload stores only the name. Fetched once on mount.
const [agentsByName, setAgentsByName] = useState<Record<string, VibeAgentBrief>>({});
diff --git a/ui/src/components/workbench/RunningAgentsTab.tsx b/ui/src/components/workbench/RunningAgentsTab.tsx
index fd83b1824..2777c771a 100644
--- a/ui/src/components/workbench/RunningAgentsTab.tsx
+++ b/ui/src/components/workbench/RunningAgentsTab.tsx
@@ -28,8 +28,14 @@ import {
type Backend,
} from '../../lib/backendAccent';
-// How often to refresh while mounted (ms)
+// Degraded-mode refresh cadence while SSE is disconnected.
const POLL_INTERVAL_MS = 4000;
+const LIVENESS_POLL_INTERVAL_MS = 30000;
+const RENDER_TICK_INTERVAL_MS = 1000;
+
+type DisplayRunningAgent = RunningAgent & {
+ elapsed_observed_at: number;
+};
// Humanize elapsed_seconds: 12 → "12s", 185 → "3m", 3700 → "1h"
function formatElapsed(seconds: number | null): string {
@@ -71,6 +77,12 @@ function sortAgents(agents: RunningAgent[]): RunningAgent[] {
});
}
+function currentElapsedSeconds(agent: DisplayRunningAgent, now: number): number | null {
+ if (agent.elapsed_seconds == null) return null;
+ const age = Math.max(0, (now - agent.elapsed_observed_at) / 1000);
+ return agent.elapsed_seconds + age;
+}
+
// Per-state presentation, in one place: the state dot/badge AND the End button
// label/icon/confirm-policy all key off this map instead of parallel ternaries.
type RunState = 'active' | 'idle' | 'orphan';
@@ -99,9 +111,11 @@ export const RunningAgentsTab: React.FC<RunningAgentsTabProps> = ({ onActiveCoun
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
- const [agents, setAgents] = useState<RunningAgent[]>([]);
+ const [agents, setAgents] = useState<DisplayRunningAgent[]>([]);
+ const [renderNow, setRenderNow] = useState(() => Date.now());
const [unreachable, setUnreachable] = useState(false);
const [loading, setLoading] = useState(true);
+ const [eventBridgeConnected, setEventBridgeConnected] = useState(false);
// Guards against setState after unmount: an in-flight poll can resolve after
// the user leaves the Running tab (the component unmounts) — without this the
// resolved fetch would call setState on an unmounted component.
@@ -124,8 +138,10 @@ export const RunningAgentsTab: React.FC<RunningAgentsTabProps> = ({ onActiveCoun
setAgents([]);
onActiveCountChange?.(null);
} else {
+ const observedAt = Date.now();
setUnreachable(false);
- setAgents(sortAgents(result.agents ?? []));
+ setRenderNow(observedAt);
+ setAgents(sortAgents(result.agents ?? []).map((agent) => ({ ...agent, elapsed_observed_at: observedAt })));
onActiveCountChange?.((result.counts as any)?.active ?? 0);
}
} catch {
@@ -176,16 +192,88 @@ export const RunningAgentsTab: React.FC<RunningAgentsTabProps> = ({ onActiveCoun
[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]);
+ return api.connectWorkbenchEvents({
+ onConnected: (data) => {
+ if (data.source === 'controller') {
+ setEventBridgeConnected(true);
+ fetchData(true);
+ }
+ },
+ onEventBridgeStatus: ({ connected }) => {
+ setEventBridgeConnected(connected);
+ if (connected) fetchData(true);
+ },
+ onError: () => setEventBridgeConnected(false),
+ onRunsUpdated: () => fetchData(true),
+ onTurnStart: () => fetchData(true),
+ onTurnEnd: () => fetchData(true),
+ onSessionStatus: () => fetchData(true),
+ });
+ }, [api, fetchData]);
+
+ const hasElapsedRows = agents.some((agent) => agent.elapsed_seconds != null);
+ useEffect(() => {
+ if (!hasElapsedRows) return;
+ const timer = window.setInterval(() => setRenderNow(Date.now()), RENDER_TICK_INTERVAL_MS);
+ return () => window.clearInterval(timer);
+ }, [hasElapsedRows]);
+
+ // SSE covers lifecycle writes, and the render ticker covers elapsed labels.
+ // External process death/orphan detection is a sampled snapshot, so keep a
+ // low-rate reconciliation poll only while visible rows can go stale.
+ useEffect(() => {
+ const intervalMs = eventBridgeConnected ? LIVENESS_POLL_INTERVAL_MS : POLL_INTERVAL_MS;
+ if (eventBridgeConnected && agents.length === 0) return;
+ let timer: number | undefined;
+ let cancelled = false;
+ let inFlight = false;
+ let pendingWake = false;
+
+ const tick = async () => {
+ if (cancelled) return;
+ if (document.visibilityState !== 'visible') {
+ timer = window.setTimeout(tick, intervalMs);
+ return;
+ }
+ if (inFlight) {
+ pendingWake = true;
+ return;
+ }
+ inFlight = true;
+ window.clearTimeout(timer);
+ try {
+ await fetchData(true);
+ } finally {
+ inFlight = false;
+ }
+ if (cancelled) return;
+ if (pendingWake) {
+ pendingWake = false;
+ void tick();
+ return;
+ }
+ timer = window.setTimeout(tick, intervalMs);
+ };
+
+ const refreshNow = () => {
+ if (document.visibilityState === 'visible') void tick();
+ };
+
+ void tick();
+ document.addEventListener('visibilitychange', refreshNow);
+ window.addEventListener('focus', refreshNow);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ document.removeEventListener('visibilitychange', refreshNow);
+ window.removeEventListener('focus', refreshNow);
+ };
+ }, [agents.length, eventBridgeConnected, fetchData]);
if (loading) {
return (
@@ -252,6 +340,7 @@ export const RunningAgentsTab: React.FC<RunningAgentsTabProps> = ({ onActiveCoun
// same key the sort uses; no positional index.
key={identityKey(agent)}
agent={agent}
+ renderNow={renderNow}
onEnd={endAgent}
/>
))}
@@ -264,11 +353,12 @@ export const RunningAgentsTab: React.FC<RunningAgentsTabProps> = ({ onActiveCoun
// ---------------------------------------------------------------------------
interface RunningAgentRowProps {
- agent: RunningAgent;
+ agent: DisplayRunningAgent;
+ renderNow: number;
onEnd: (agent: RunningAgent) => Promise<void>;
}
-const RunningAgentRow: React.FC<RunningAgentRowProps> = ({ agent, onEnd }) => {
+const RunningAgentRow: React.FC<RunningAgentRowProps> = ({ agent, renderNow, onEnd }) => {
const { t } = useTranslation();
const isOrphan = agent.state === 'orphan';
const [ending, setEnding] = useState(false);
@@ -317,6 +407,7 @@ const RunningAgentRow: React.FC<RunningAgentRowProps> = ({ agent, onEnd }) => {
BACKEND_LABEL[agent.backend as Backend] ?? agent.backend;
const backendClass =
BACKEND_ICON_CLASS[agent.backend as Backend] ?? 'text-muted';
+ const elapsedSeconds = currentElapsedSeconds(agent, renderNow);
const canOpenChat = agent.openable_in_chat && !!agent.session_id;
@@ -342,13 +433,13 @@ const RunningAgentRow: React.FC<RunningAgentRowProps> = ({ agent, onEnd }) => {
{/* 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 && (
+ {elapsedSeconds != null && (
<span className="font-mono text-[11px] text-muted">
{t(
agent.state === 'active'
? 'agents.running.busy'
: 'agents.running.idleElapsed',
- { elapsed: formatElapsed(agent.elapsed_seconds) },
+ { elapsed: formatElapsed(elapsedSeconds) },
)}
</span>
)}
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index df65083f7..6ebeb799f 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -14,6 +14,10 @@ import { useToast } from '../../context/ToastContext';
import { VaultApprovalCard, type ApprovalOutcome } from '../ui/vault-approval-card';
import { VaultSecretForm } from '../ui/vault-secret-form';
+const PENDING_REQUEST_POLL_INTERVAL_MS = 5000;
+const PENDING_REQUEST_EXPIRY_GRACE_MS = 100;
+const MAX_BROWSER_TIMEOUT_MS = 2_147_483_647;
+
const AddSecretDialog: React.FC<{
onClose: () => void;
onCreated: (name: string, reason?: 'created' | 'already_exists') => void;
@@ -152,6 +156,17 @@ function isExpired(expiresAt: string, now: number): boolean {
return !Number.isNaN(end) && end <= now;
}
+function earliestRequestExpiry(requests: VaultRequest[]): number | null {
+ let earliest: number | null = null;
+ for (const request of requests) {
+ if (!request.expires_at) continue;
+ const expiresAt = Date.parse(request.expires_at);
+ if (Number.isNaN(expiresAt)) continue;
+ earliest = earliest == null ? expiresAt : Math.min(earliest, expiresAt);
+ }
+ return earliest;
+}
+
/** Compact mm:ss / h:mm:ss countdown for a grant chip (design.pen `y4rw5Q` shows `12:34`). */
function chipCountdown(rem: { h: number; m: number; s: number }): string {
const pad = (n: number) => n.toString().padStart(2, '0');
@@ -286,6 +301,7 @@ const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolv
const [requests, setRequests] = useState<VaultRequest[]>([]);
const [reviewing, setReviewing] = useState<VaultRequest | null>(null);
const [provisioning, setProvisioning] = useState<VaultRequest | null>(null);
+ const [eventBridgeConnected, setEventBridgeConnected] = useState(false);
const load = useCallback(async () => {
try {
@@ -302,13 +318,88 @@ const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolv
}
}, [api]);
- // Poll so a request an agent raises while the hub is open appears without a manual refresh.
useEffect(() => {
load();
- const id = setInterval(load, 5000);
- return () => clearInterval(id);
}, [load]);
+ useEffect(() => {
+ return api.connectWorkbenchEvents({
+ onConnected: (data) => {
+ if (data.source === 'controller') {
+ setEventBridgeConnected(true);
+ load();
+ }
+ },
+ onEventBridgeStatus: ({ connected }) => {
+ setEventBridgeConnected(connected);
+ if (connected) load();
+ },
+ onError: () => setEventBridgeConnected(false),
+ onVaultsUpdated: () => load(),
+ });
+ }, [api, load]);
+
+ useEffect(() => {
+ if (eventBridgeConnected) return;
+ let timer: number | undefined;
+ let cancelled = false;
+ let inFlight = false;
+ let pendingWake = false;
+
+ const tick = async () => {
+ if (cancelled) return;
+ if (document.visibilityState !== 'visible') {
+ timer = window.setTimeout(tick, PENDING_REQUEST_POLL_INTERVAL_MS);
+ return;
+ }
+ if (inFlight) {
+ pendingWake = true;
+ return;
+ }
+ inFlight = true;
+ window.clearTimeout(timer);
+ try {
+ await load();
+ } finally {
+ inFlight = false;
+ }
+ if (cancelled) return;
+ if (pendingWake) {
+ pendingWake = false;
+ void tick();
+ return;
+ }
+ timer = window.setTimeout(tick, PENDING_REQUEST_POLL_INTERVAL_MS);
+ };
+
+ const refreshNow = () => {
+ if (document.visibilityState === 'visible') void tick();
+ };
+
+ void tick();
+ document.addEventListener('visibilitychange', refreshNow);
+ window.addEventListener('focus', refreshNow);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ document.removeEventListener('visibilitychange', refreshNow);
+ window.removeEventListener('focus', refreshNow);
+ };
+ }, [eventBridgeConnected, load]);
+
+ useEffect(() => {
+ const expiresAt = earliestRequestExpiry(requests);
+ if (expiresAt == null) return;
+ const delay = Math.min(
+ Math.max(0, expiresAt - Date.now() + PENDING_REQUEST_EXPIRY_GRACE_MS),
+ MAX_BROWSER_TIMEOUT_MS,
+ );
+ const timer = window.setTimeout(() => {
+ void load();
+ }, delay);
+ return () => window.clearTimeout(timer);
+ }, [requests, load]);
+
const handleOutcome = useCallback(
(outcome: ApprovalOutcome) => {
// Drop the row immediately so it doesn't linger behind the poll; the next load
@@ -415,6 +506,7 @@ export const VaultsPage: React.FC = () => {
const [activeTags, setActiveTags] = useState<string[]>([]);
const [activeSkills, setActiveSkills] = useState<string[]>([]);
const [now, setNow] = useState(() => Date.now());
+ const [eventBridgeConnected, setEventBridgeConnected] = useState(false);
const refresh = useCallback(async () => {
setLoading(true);
@@ -442,6 +534,71 @@ export const VaultsPage: React.FC = () => {
refresh();
}, [refresh]);
+ useEffect(() => {
+ return api.connectWorkbenchEvents({
+ onConnected: (data) => {
+ if (data.source === 'controller') {
+ setEventBridgeConnected(true);
+ refresh();
+ }
+ },
+ onEventBridgeStatus: ({ connected }) => {
+ setEventBridgeConnected(connected);
+ if (connected) refresh();
+ },
+ onError: () => setEventBridgeConnected(false),
+ onVaultsUpdated: () => refresh(),
+ });
+ }, [api, refresh]);
+
+ useEffect(() => {
+ if (eventBridgeConnected) return;
+ let timer: number | undefined;
+ let cancelled = false;
+ let inFlight = false;
+ let pendingWake = false;
+
+ const tick = async () => {
+ if (cancelled) return;
+ if (document.visibilityState !== 'visible') {
+ timer = window.setTimeout(tick, 5000);
+ return;
+ }
+ if (inFlight) {
+ pendingWake = true;
+ return;
+ }
+ inFlight = true;
+ window.clearTimeout(timer);
+ try {
+ await refresh();
+ } finally {
+ inFlight = false;
+ }
+ if (cancelled) return;
+ if (pendingWake) {
+ pendingWake = false;
+ void tick();
+ return;
+ }
+ timer = window.setTimeout(tick, 5000);
+ };
+
+ const refreshNow = () => {
+ if (document.visibilityState === 'visible') void tick();
+ };
+
+ void tick();
+ document.addEventListener('visibilitychange', refreshNow);
+ window.addEventListener('focus', refreshNow);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ document.removeEventListener('visibilitychange', refreshNow);
+ window.removeEventListener('focus', refreshNow);
+ };
+ }, [eventBridgeConnected, refresh]);
+
// Tick once a second while there are live grants: advance the countdown and
// drop any grant that has reached its expiry. The backend's status=active
// filter only applies at fetch time, so without this the "Active access"
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index fca8e5602..c2a984802 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -641,7 +641,8 @@ export type WorkbenchEventEnvelope<T = unknown> = {
};
export type WorkbenchEventHandlers = {
- onConnected?: (data: { sub_id: number }) => void;
+ onConnected?: (data: { sub_id: number; source?: 'browser' | 'controller' }) => void;
+ onEventBridgeStatus?: (data: { connected: boolean }) => void;
onMessageNew?: (data: WorkbenchMessage) => void;
onSessionActivity?: (data: { session_id: string; scope_id: string | null; event: string; title?: string | null }) => void;
onInboxUnreadChanged?: (data: {
@@ -666,6 +667,23 @@ export type WorkbenchEventHandlers = {
onSessionStatus?: (data: { session_id: string; agent_status: 'idle' | 'running' | 'failed' }) => void;
// The send-while-busy queue for a session changed (enqueue / flush / remove).
onQueueUpdated?: (data: { session_id: string }) => void;
+ onRunsUpdated?: (data: {
+ run_id: string;
+ status: HarnessRunStatus;
+ run_type?: string;
+ session_id?: string;
+ definition_id?: string;
+ updated_at?: string;
+ cancel_requested?: boolean;
+ }) => void;
+ onVaultsUpdated?: (data: {
+ scope: string;
+ request_id?: string;
+ request_status?: string;
+ grant_id?: string;
+ grant_status?: string;
+ secret_name?: string;
+ }) => void;
onAny?: (event: WorkbenchEventEnvelope) => void;
onError?: (err: Event) => void;
};
@@ -1418,7 +1436,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const readCacheRef = useRef(new Map<string, { expiresAt: number; promise: Promise<any> }>());
const eventSourceRef = useRef<EventSource | null>(null);
const eventHandlersRef = useRef(new Set<WorkbenchEventHandlers>());
- const eventConnectionRef = useRef<{ sub_id: number } | null>(null);
+ const eventConnectionRef = useRef<{ sub_id: number; source?: 'browser' | 'controller' } | null>(null);
+ const eventBridgeConnectedRef = useRef(false);
const handleApiError = async (res: Response, path: string) => {
let errorMessage = `Request failed: ${path} (${res.status})`;
@@ -1531,6 +1550,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
eventSourceRef.current?.close();
eventSourceRef.current = null;
eventConnectionRef.current = null;
+ eventBridgeConnectedRef.current = false;
};
const ensureWorkbenchEventSource = (options?: { reconnect?: boolean }) => {
@@ -1543,7 +1563,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
eventSourceRef.current = source;
source.addEventListener('connected', (e: MessageEvent) => {
try {
- eventConnectionRef.current = JSON.parse(e.data) as { sub_id: number };
+ const parsed = JSON.parse(e.data) as { sub_id?: number; type?: string; data?: unknown };
+ const sourceKind = typeof parsed.sub_id === 'number' ? 'browser' : 'controller';
+ eventConnectionRef.current = {
+ sub_id: typeof parsed.sub_id === 'number' ? parsed.sub_id : -1,
+ source: sourceKind,
+ };
+ if (sourceKind === 'controller') {
+ eventBridgeConnectedRef.current = true;
+ dispatchToWorkbenchHandlers((handlers) => handlers.onEventBridgeStatus?.({ connected: true }));
+ }
} catch (err) {
console.error('[workbench-events] connected parse failed', err, e.data);
eventConnectionRef.current = null;
@@ -1636,7 +1665,52 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
handlers.onQueueUpdated?.(envelope.data);
});
});
+ source.addEventListener('runs.updated', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{
+ run_id: string;
+ status: HarnessRunStatus;
+ run_type?: string;
+ session_id?: string;
+ definition_id?: string;
+ updated_at?: string;
+ cancel_requested?: boolean;
+ }>(e.data);
+ if (!envelope) return;
+ clearReadCacheMatching((path) => path.startsWith('/api/harness'));
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onRunsUpdated?.(envelope.data);
+ });
+ });
+ source.addEventListener('vaults.updated', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{
+ scope: string;
+ request_id?: string;
+ request_status?: string;
+ grant_id?: string;
+ grant_status?: string;
+ secret_name?: string;
+ }>(e.data);
+ if (!envelope) return;
+ clearReadCacheMatching((path) => path.startsWith('/api/vault/'));
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onVaultsUpdated?.(envelope.data);
+ });
+ });
+ source.addEventListener('workbench.events.bridge.status', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<{ connected: boolean }>(e.data);
+ if (!envelope) return;
+ eventBridgeConnectedRef.current = envelope.data.connected;
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onEventBridgeStatus?.(envelope.data);
+ });
+ });
source.onerror = (err) => {
+ eventConnectionRef.current = null;
+ eventBridgeConnectedRef.current = false;
+ dispatchToWorkbenchHandlers((handlers) => handlers.onEventBridgeStatus?.({ connected: false }));
dispatchToWorkbenchHandlers((handlers) => handlers.onError?.(err));
};
};
@@ -2218,13 +2292,27 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
connectWorkbenchEvents: (handlers, options) => {
eventHandlersRef.current.add(handlers);
ensureWorkbenchEventSource(options);
- if (eventConnectionRef.current) {
+ if (
+ eventConnectionRef.current &&
+ (eventConnectionRef.current.source !== 'controller' || eventBridgeConnectedRef.current)
+ ) {
queueMicrotask(() => {
- if (eventHandlersRef.current.has(handlers) && eventConnectionRef.current) {
+ if (
+ eventHandlersRef.current.has(handlers) &&
+ eventConnectionRef.current &&
+ (eventConnectionRef.current.source !== 'controller' || eventBridgeConnectedRef.current)
+ ) {
handlers.onConnected?.(eventConnectionRef.current);
}
});
}
+ if (eventBridgeConnectedRef.current) {
+ queueMicrotask(() => {
+ if (eventHandlersRef.current.has(handlers)) {
+ handlers.onEventBridgeStatus?.({ connected: true });
+ }
+ });
+ }
return () => {
eventHandlersRef.current.delete(handlers);
if (eventHandlersRef.current.size === 0) {
diff --git a/vibe/api.py b/vibe/api.py
index 34be9a566..68197ca95 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1314,6 +1314,41 @@ class VaultApiError(ValueError):
self.status = status
+def _publish_vaults_updated(
+ *,
+ scope: str,
+ request_id: str | None = None,
+ request_status: str | None = None,
+ grant_id: str | None = None,
+ grant_status: str | None = None,
+ secret_name: str | None = None,
+) -> None:
+ """Publish a UI-server-local vault update event for refetch-on-event pages."""
+
+ try:
+ from core.inbox_events import VAULTS_UPDATED_EVENT, vaults_updated_payload
+ from vibe.sse_broker import broker
+
+ payload = vaults_updated_payload(
+ scope=scope,
+ request_id=request_id,
+ request_status=request_status,
+ grant_id=grant_id,
+ grant_status=grant_status,
+ secret_name=secret_name,
+ )
+ broker.publish(VAULTS_UPDATED_EVENT, payload)
+ if broker.subscriber_count() == 0:
+ try:
+ from vibe import internal_client
+
+ internal_client.publish_event_sync(VAULTS_UPDATED_EVENT, payload, timeout=1.5)
+ except Exception:
+ logger.debug("vaults.updated bridge publish failed", exc_info=True)
+ except Exception:
+ logger.debug("vaults.updated publish failed", exc_info=True)
+
+
def _vault_api_error_from_avault(exc: "AvaultError", *, prefix: str) -> VaultApiError:
message = str(exc)
if "requires avault >=" in message:
@@ -1465,16 +1500,25 @@ def create_vault_secret(payload: dict) -> dict:
except vault_service.InvalidSecretNameError as exc:
raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name") from exc
except vault_service.SecretExistsError as exc:
+ fulfilled_count = 0
try:
with engine.begin() as conn:
- vault_service.fulfill_pending_provision_requests_for_secret(conn, name)
+ fulfilled_count = vault_service.fulfill_pending_provision_requests_for_secret(conn, name)
except Exception:
logger.warning("failed to settle pending provision requests for existing secret %s", name, exc_info=True)
+ if fulfilled_count > 0:
+ _publish_vaults_updated(scope="secret", secret_name=name, request_status="fulfilled")
raise VaultApiError(f"secret '{name}' already exists", code="secret_exists", status=409) from exc
except vault_service.VaultAlreadyInitializedError as exc:
raise VaultApiError(str(exc), code="vault_already_initialized", status=409) from exc
except vault_service.VaultServiceError as exc:
raise VaultApiError(str(exc), code="vault_error") from exc
+ _publish_vaults_updated(
+ scope="secret",
+ secret_name=meta.get("name") or name,
+ request_id=str(payload.get("provision_request_id") or "") or None,
+ request_status="fulfilled" if payload.get("provision_request_id") else None,
+ )
return {"ok": True, "secret": meta}
@@ -1491,6 +1535,7 @@ def delete_vault_secret(name: str) -> dict:
except vault_service.SecretNotFoundError as exc:
raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc
release_vault_agent_scopes(release_scopes, reason="delete_vault_secret")
+ _publish_vaults_updated(scope="secret", secret_name=name)
return {"ok": True, "removed": True, "name": name}
@@ -1684,6 +1729,12 @@ def request_vault_access(payload: dict) -> dict:
raise VaultApiError(str(exc), code="invalid_request", status=409) from exc
except vault_service.VaultServiceError as exc:
raise VaultApiError(str(exc), code="invalid_request", status=409) from exc
+ _publish_vaults_updated(
+ scope="request",
+ request_id=request.get("id"),
+ request_status=request.get("status"),
+ secret_name=request.get("secret_name"),
+ )
return {"ok": True, "request": request}
@@ -1726,6 +1777,12 @@ def request_vault_sign(payload: dict) -> dict:
raise VaultApiError(str(exc), code="invalid_request", status=409) from exc
except vault_service.VaultServiceError as exc:
raise VaultApiError(str(exc), code="vault_error") from exc
+ _publish_vaults_updated(
+ scope="request",
+ request_id=request.get("id"),
+ request_status=request.get("status"),
+ secret_name=request.get("secret_name"),
+ )
return {"ok": True, "request": request}
@@ -1746,6 +1803,12 @@ def deny_vault_request(request_id: str, payload: dict | None = None) -> dict:
raise VaultApiError(f"request '{request_id}' not found", code="request_not_found", status=404) from exc
except vault_service.InvalidRequestError as exc:
raise VaultApiError(str(exc), code="invalid_request", status=409) from exc
+ _publish_vaults_updated(
+ scope="request",
+ request_id=request.get("id") or str(request_id),
+ request_status=request.get("status"),
+ secret_name=request.get("secret_name"),
+ )
return {"ok": True, "request": request}
@@ -1795,6 +1858,7 @@ def consume_one_shot_grants(grants: list[dict] | tuple[dict, ...] | None, *, rea
return
seen: set[str] = set()
release_scopes: list[dict[str, str]] = []
+ consumed_grants: list[dict[str, str | None]] = []
engine = _vault_engine()
with engine.begin() as conn:
for grant in grants:
@@ -1806,7 +1870,15 @@ def consume_one_shot_grants(grants: list[dict] | tuple[dict, ...] | None, *, rea
seen.add(grant_id)
with contextlib.suppress(vault_service.GrantNotActiveError, vault_service.GrantNotFoundError):
release_scopes.extend(vault_service.consume_one_shot_grant(conn, grant_id))
+ consumed_grants.append({"id": grant_id, "request_id": str(grant.get("request_id") or "") or None})
release_vault_agent_scopes(release_scopes, reason=reason)
+ for grant in consumed_grants:
+ _publish_vaults_updated(
+ scope="grant",
+ grant_id=grant["id"],
+ grant_status="expired",
+ request_id=grant.get("request_id"),
+ )
def _agent_grant_cached_all(result: dict, expected_count: int) -> bool:
@@ -2108,6 +2180,13 @@ def create_vault_grant(payload: dict) -> dict:
except vault_service.InvalidGrantError as exc:
raise VaultApiError(str(exc), code="invalid_grant") from exc
if not needs_agent_deks:
+ _publish_vaults_updated(
+ scope="grant",
+ request_id=request_id,
+ request_status="approved",
+ grant_id=grant.get("id"),
+ grant_status=grant.get("status"),
+ )
return {"ok": True, "grant": grant}
agent_relayed = False
try:
@@ -2165,6 +2244,13 @@ def create_vault_grant(payload: dict) -> dict:
force_release_scope=True,
)
raise
+ _publish_vaults_updated(
+ scope="grant",
+ request_id=request_id,
+ request_status="approved",
+ grant_id=grant.get("id"),
+ grant_status=grant.get("status"),
+ )
return {"ok": True, "grant": grant}
@@ -2487,6 +2573,12 @@ def revoke_vault_grant(grant_id: str) -> dict:
except vault_service.GrantNotActiveError as exc:
raise VaultApiError(f"grant '{grant_id}' is not active", code="grant_not_active", status=409) from exc
release_vault_agent_scopes(release_scopes, reason=f"revoke_vault_grant:{grant_id}")
+ _publish_vaults_updated(
+ scope="grant",
+ grant_id=grant.get("id") or grant_id,
+ grant_status=grant.get("status"),
+ request_id=grant.get("request_id"),
+ )
return {"ok": True, "grant": grant}
@@ -2508,6 +2600,8 @@ def vault_sign(payload: dict) -> dict:
if not vault_crypto.is_valid_secret_name(name):
raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name")
engine = _vault_engine()
+ protected_response: dict | None = None
+ protected_event: dict | None = None
try:
with engine.begin() as conn:
meta = vault_service.get_secret_meta(conn, name)
@@ -2531,27 +2625,41 @@ def vault_sign(payload: dict) -> dict:
requester=payload.get("requester") if isinstance(payload.get("requester"), dict) else None,
delivery=payload.get("delivery") if isinstance(payload.get("delivery"), dict) else None,
)
- return {"ok": False, "code": "browser_signature_required", "request": request}
+ protected_event = {
+ "scope": "request",
+ "request_id": request.get("id"),
+ "request_status": request.get("status"),
+ "secret_name": request.get("secret_name"),
+ }
+ protected_response = {"ok": False, "code": "browser_signature_required", "request": request}
+ else:
+ request_id = str(payload.get("request_id") or "")
+ if not request_id:
+ raise VaultApiError("request_id is required to complete protected signing", code="missing_request_id")
+ vault_service.validate_sign_request(conn, request_id, name=name, digest=digest, scheme=scheme)
+ signature = _normalized_protected_signature(signature)
+ _verify_protected_browser_signature(meta, digest=digest, scheme=scheme, signature=signature)
+ request = vault_service.complete_sign_request(
+ conn,
+ request_id,
+ name=name,
+ digest=digest,
+ scheme=scheme,
+ signature=signature,
+ requester=payload.get("requester") if isinstance(payload.get("requester"), dict) else None,
+ )
+ protected_event = {
+ "scope": "request",
+ "request_id": request.get("id") or request_id,
+ "request_status": request.get("status"),
+ "secret_name": request.get("secret_name"),
+ }
+ protected_response = {"ok": True, "signature": signature, "request": request}
+ else:
request_id = str(payload.get("request_id") or "")
- if not request_id:
- raise VaultApiError("request_id is required to complete protected signing", code="missing_request_id")
- vault_service.validate_sign_request(conn, request_id, name=name, digest=digest, scheme=scheme)
- signature = _normalized_protected_signature(signature)
- _verify_protected_browser_signature(meta, digest=digest, scheme=scheme, signature=signature)
- request = vault_service.complete_sign_request(
- conn,
- request_id,
- name=name,
- digest=digest,
- scheme=scheme,
- signature=signature,
- requester=payload.get("requester") if isinstance(payload.get("requester"), dict) else None,
- )
- return {"ok": True, "signature": signature, "request": request}
- request_id = str(payload.get("request_id") or "")
- if request_id:
- vault_service.claim_sign_request(conn, request_id, name=name, digest=digest, scheme=scheme)
- key_envelope = vault_service.get_key_envelope(conn, name)
+ if request_id:
+ vault_service.claim_sign_request(conn, request_id, name=name, digest=digest, scheme=scheme)
+ key_envelope = vault_service.get_key_envelope(conn, name)
except vault_service.SecretNotFoundError as exc:
raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc
except vault_service.RequestNotFoundError as exc:
@@ -2561,13 +2669,24 @@ def vault_sign(payload: dict) -> dict:
except vault_service.VaultServiceError as exc:
raise VaultApiError(str(exc), code="vault_error") from exc
+ if protected_response is not None:
+ if protected_event is not None:
+ _publish_vaults_updated(**protected_event)
+ return protected_response
+
def _fail_claimed_request(reason: str) -> None:
request_id = str(payload.get("request_id") or "")
if not request_id:
return
with contextlib.suppress(Exception):
with engine.begin() as conn:
- vault_service.fail_sign_request(conn, request_id, reason=reason)
+ request = vault_service.fail_sign_request(conn, request_id, reason=reason)
+ _publish_vaults_updated(
+ scope="request",
+ request_id=request.get("id") or request_id,
+ request_status=request.get("status"),
+ secret_name=request.get("secret_name"),
+ )
try:
signature = avault_sign(key_envelope, digest, scheme, name=name)
@@ -2592,6 +2711,12 @@ def vault_sign(payload: dict) -> dict:
except vault_service.InvalidRequestError as exc:
_fail_claimed_request("signature_rejected")
raise VaultApiError(str(exc), code="invalid_request", status=409) from exc
+ _publish_vaults_updated(
+ scope="request",
+ request_id=request.get("id") or request_id,
+ request_status=request.get("status"),
+ secret_name=request.get("secret_name"),
+ )
return {"ok": True, "signature": signature, "request": request}
try:
with engine.begin() as conn:
@@ -2622,6 +2747,7 @@ def store_vault_pubkey_pin(payload: dict) -> dict:
meta = vault_service.store_pubkey_pin(conn, name, pin)
except vault_service.SecretNotFoundError as exc:
raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc
+ _publish_vaults_updated(scope="secret", secret_name=meta.get("name") or name)
return {"ok": True, "secret": meta}
diff --git a/vibe/cli.py b/vibe/cli.py
index 69db8f574..25cfcd796 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -4678,6 +4678,37 @@ def _vault_cli_delivery(args, **fields) -> dict:
return delivery
+def _publish_cli_vaults_updated(
+ *,
+ scope: str,
+ request: dict | None = None,
+ grant: dict | None = None,
+ secret_name: str | None = None,
+) -> None:
+ """Best-effort bridge for CLI/agent vault writes into browser SSE."""
+
+ if request is None and grant is None and not secret_name:
+ return
+ try:
+ from core.inbox_events import VAULTS_UPDATED_EVENT, vaults_updated_payload
+ from vibe import internal_client
+
+ internal_client.publish_event_sync(
+ VAULTS_UPDATED_EVENT,
+ vaults_updated_payload(
+ scope=scope,
+ request_id=str(request.get("id") or "") if request else None,
+ request_status=str(request.get("status") or "") if request else None,
+ grant_id=str(grant.get("id") or "") if grant else None,
+ grant_status=str(grant.get("status") or "") if grant else None,
+ secret_name=secret_name or (str(request.get("secret_name") or "") if request else None),
+ ),
+ timeout=1.5,
+ )
+ except Exception:
+ logger.debug("failed to publish CLI vault update event", exc_info=True)
+
+
def _is_env_name(name: str) -> bool:
"""ASCII shell/env identifier: a letter or underscore, then letters/digits/underscores."""
if not name or not name[0].isascii() or not (name[0].isalpha() or name[0] == "_"):
@@ -4899,6 +4930,7 @@ def cmd_vault_rm(args):
vault_service.delete_secret(conn, args.name)
release_scopes = vault_service.agent_release_scopes_after_rows(conn, grant_rows)
api.release_vault_agent_scopes(release_scopes, reason="vault_rm")
+ _publish_cli_vaults_updated(scope="secret", secret_name=args.name)
_print_cli_payload("vault_secret", removed=True, name=args.name)
return 0
except vault_service.SecretNotFoundError:
@@ -4926,6 +4958,7 @@ def cmd_vault_access(args):
requester=_vault_cli_requester(args),
delivery=_vault_cli_delivery(args, mode="access"),
)
+ _publish_cli_vaults_updated(scope="request", request=request)
_print_cli_payload(
"vault_access_request",
request_id=request["id"],
@@ -4966,7 +4999,7 @@ def _expire_agent_grant_after_missing(
source_selector = delivery_payload.get("source_selector")
if isinstance(source_selector, dict):
try:
- return vault_service.create_access_request(
+ first_request = vault_service.create_access_request(
conn,
source_selector=source_selector,
requester=requester or {"source": "cli", "pid": os.getpid()},
@@ -4975,19 +5008,23 @@ def _expire_agent_grant_after_missing(
)
except vault_service.NotGrantableError:
pass
- for name in names:
- resolved = vault_service.resolve_secret_access(
- conn,
- name,
- requester=requester or {"source": "cli", "pid": os.getpid()},
- delivery=delivery or {},
- purpose=purpose,
- )
- if first_request is None and isinstance(resolved.get("request"), dict):
- first_request = resolved["request"]
- break
+ if first_request is None:
+ for name in names:
+ resolved = vault_service.resolve_secret_access(
+ conn,
+ name,
+ requester=requester or {"source": "cli", "pid": os.getpid()},
+ delivery=delivery or {},
+ purpose=purpose,
+ )
+ if first_request is None and isinstance(resolved.get("request"), dict):
+ first_request = resolved["request"]
+ break
except Exception:
pass
+ else:
+ _publish_cli_vaults_updated(scope="grant", grant={"id": grant_id, "status": "expired"})
+ _publish_cli_vaults_updated(scope="request", request=first_request)
return first_request
@@ -5426,6 +5463,7 @@ def _resolve_vault_run_delivery(
if str(metas[name].get("protection") or "standard") == "protected"
]
standard_approval_error: TaskCliError | None = None
+ approval_request_to_publish: dict | None = None
if metas and not protected_names:
with engine.begin() as conn:
standard_names = list(dict.fromkeys(mapping.values()))
@@ -5451,12 +5489,14 @@ def _resolve_vault_run_delivery(
delivery=delivery,
purpose="run",
)
+ approval_request_to_publish = req
standard_approval_error = TaskCliError(
"standard always_ask secrets need approval before vault run delivery",
code="approval_required",
details={"request_id": req.get("id"), "secret_names": approval_names},
)
if standard_approval_error is not None:
+ _publish_cli_vaults_updated(scope="request", request=approval_request_to_publish)
raise standard_approval_error
secrets = []
grant: dict | None = None
@@ -5527,6 +5567,7 @@ def _resolve_vault_run_delivery(
delivery=request_delivery,
purpose="run",
)
+ approval_request_to_publish = req
approval_error = TaskCliError(
"protected secrets need approval before vault run delivery",
code="approval_required",
@@ -5560,6 +5601,8 @@ def _resolve_vault_run_delivery(
resolved_by_name[vault_name] = resolved
if resolved["status"] == "approval_required":
req = resolved.get("request") or {}
+ if isinstance(req, dict):
+ approval_request_to_publish = req
approval_error = TaskCliError(
f"secret '{vault_name}' needs approval before protected delivery",
code="approval_required",
@@ -5581,6 +5624,7 @@ def _resolve_vault_run_delivery(
except Exception as exc:
_raise_after_releasing_one_shot_reservations(engine, one_shot_grants, exc)
if approval_error is not None:
+ _publish_cli_vaults_updated(scope="request", request=approval_request_to_publish)
_release_one_shot_reservations(engine, one_shot_grants)
raise approval_error
return grant, one_shot_grants, secrets
@@ -5607,6 +5651,8 @@ def _resolve_single_vault_delivery(
)
if resolved["status"] == "approval_required":
req = resolved.get("request") or {}
+ if isinstance(req, dict):
+ _publish_cli_vaults_updated(scope="request", request=req)
raise TaskCliError(
f"secret '{name}' needs approval before protected delivery",
code="approval_required",
@@ -5660,6 +5706,7 @@ def _resolve_vault_inject_delivery(engine, names: list[str], *, path: str, fmt:
grant: dict | None = None
one_shot_grants: list[dict] = []
approval_error: TaskCliError | None = None
+ approval_request_to_publish: dict | None = None
pre_delivery_error: TaskCliError | None = None
resolved_by_name: dict[str, dict] = {}
try:
@@ -5678,6 +5725,8 @@ def _resolve_vault_inject_delivery(engine, names: list[str], *, path: str, fmt:
resolved_by_name[name] = resolved
if resolved["status"] == "approval_required":
req = resolved.get("request") or {}
+ if isinstance(req, dict):
+ approval_request_to_publish = req
approval_error = TaskCliError(
f"secret '{name}' needs approval before protected delivery",
code="approval_required",
@@ -5709,6 +5758,7 @@ def _resolve_vault_inject_delivery(engine, names: list[str], *, path: str, fmt:
except Exception as exc:
_raise_after_releasing_one_shot_reservations(engine, one_shot_grants, exc)
if approval_error is not None:
+ _publish_cli_vaults_updated(scope="request", request=approval_request_to_publish)
_release_one_shot_reservations(engine, one_shot_grants)
raise approval_error
if pre_delivery_error is not None:
@@ -5935,6 +5985,7 @@ def cmd_vault_request(args):
spec=spec,
requester={"source": "cli", "pid": os.getpid()},
)
+ _publish_cli_vaults_updated(scope="request", request=req, secret_name=name)
if req.get("status") == "fulfilled":
# Secret already existed — no point waiting.
_print_cli_payload(
@@ -6017,6 +6068,7 @@ def cmd_vault_sign(args):
requester=_vault_cli_requester(args),
delivery=_vault_cli_delivery(args, mode="sign"),
)
+ _publish_cli_vaults_updated(scope="request", request=request)
_print_cli_payload(
"vault_sign_request",
request_id=request["id"],
diff --git a/vibe/inbox_bridge.py b/vibe/inbox_bridge.py
index 757102aa4..ddd81f34f 100644
--- a/vibe/inbox_bridge.py
+++ b/vibe/inbox_bridge.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import asyncio
import logging
+from core.inbox_events import WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT
from vibe import internal_client
from vibe.sse_broker import broker
@@ -30,6 +31,19 @@ logger = logging.getLogger(__name__)
# it so a long-down controller doesn't busy-spin.
_BACKOFF_INITIAL = 1.0
_BACKOFF_MAX = 15.0
+_bridge_connected = False
+
+
+def is_bridge_connected() -> bool:
+ return _bridge_connected
+
+
+def _set_bridge_connected(connected: bool) -> None:
+ global _bridge_connected
+ if _bridge_connected == connected:
+ return
+ _bridge_connected = connected
+ broker.publish(WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT, {"connected": connected})
async def run_inbox_bridge() -> None:
@@ -47,8 +61,11 @@ async def run_inbox_bridge() -> None:
# A flowing event proves the link is healthy → reset backoff so
# the next genuine drop reconnects promptly.
backoff = _BACKOFF_INITIAL
+ if event_type == "connected":
+ _set_bridge_connected(True)
broker.publish(event_type, data)
except asyncio.CancelledError:
+ _set_bridge_connected(False)
raise
except internal_client.InternalServerUnavailable:
logger.debug("inbox bridge: controller socket unavailable; retry in %.1fs", backoff)
@@ -56,5 +73,6 @@ async def run_inbox_bridge() -> None:
logger.warning("inbox bridge: stream error; retry in %.1fs", backoff, exc_info=True)
else:
logger.debug("inbox bridge: controller feed closed; reconnect in %.1fs", backoff)
+ _set_bridge_connected(False)
await asyncio.sleep(backoff)
backoff = min(backoff * 2, _BACKOFF_MAX)
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 572aa337b..1706b841b 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -184,6 +184,69 @@ async def stream_events(
raise InternalServerUnavailable(str(exc)) from exc
+async def publish_event(
+ event_type: str,
+ data: dict[str, Any],
+ *,
+ socket_path: Optional[Path] = None,
+ timeout: float = 5.0,
+) -> dict[str, Any]:
+ """Ask the Controller process to publish an allowlisted SSE notification."""
+
+ 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(timeout, connect=2.0),
+ ) as client:
+ resp = await client.post("/internal/events", json={"type": event_type, "data": data})
+ if resp.status_code >= 400:
+ detail = await resp.aread()
+ raise InternalServerUnavailable(f"events publish returned {resp.status_code}: {detail!r}")
+ return resp.json()
+ except InternalServerUnavailable:
+ raise
+ except _SOCKET_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+
+
+def publish_event_sync(
+ event_type: str,
+ data: dict[str, Any],
+ *,
+ socket_path: Optional[Path] = None,
+ timeout: float = 5.0,
+) -> dict[str, Any]:
+ """Synchronous wrapper for CLI/child-process notification publishers."""
+
+ target = (socket_path or default_socket_path()).expanduser().resolve()
+ if not target.exists():
+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")
+
+ transport = httpx.HTTPTransport(uds=str(target))
+ try:
+ with httpx.Client(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(timeout, connect=2.0),
+ ) as client:
+ resp = client.post("/internal/events", json={"type": event_type, "data": data})
+ if resp.status_code >= 400:
+ raise InternalServerUnavailable(
+ f"events publish returned {resp.status_code}: {resp.content!r}"
+ )
+ return resp.json()
+ except InternalServerUnavailable:
+ raise
+ except _SOCKET_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+
+
async def dispatch_async(
payload: dict[str, Any],
*,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 569182292..a67defec0 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6277,6 +6277,8 @@ async def workbench_events():
from fastapi.responses import StreamingResponse
+ from core.inbox_events import WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT
+ from vibe.inbox_bridge import is_bridge_connected
from vibe.sse_broker import broker
async def generate():
@@ -6286,6 +6288,15 @@ async def workbench_events():
# subsequent debug logs / cancel calls if we ever need them.
yield ": stream connected\n\n"
yield f"event: connected\ndata: {{\"sub_id\": {sub_id}}}\n\n"
+ payload = json.dumps(
+ {
+ "type": WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT,
+ "data": {"connected": is_bridge_connected()},
+ },
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ yield f"event: {WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT}\ndata: {payload}\n\n"
while True:
try:
event_type, payload = await asyncio.wait_for(queue.get(), timeout=15.0)