Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(events): account for every stream gap instead of hiding it behind refetching (#1597)
Call Whiteff528804d816
diff --git a/core/inbox_events.py b/core/inbox_events.pyindex 84ebc39fc..9205b7adb 100644--- a/core/inbox_events.py+++ b/core/inbox_events.py@@ -36,9 +36,29 @@ def is_controller_process() -> bool:return _CONTROLLER_PROCESS+class _Subscription:+ """One subscriber's queue, plus what this bus failed to hand it.++ Same shape and same reason as ``vibe/sse_broker.py``: a bounded queue makes+ "slow subscriber" and "lost events" one condition, and the loss is invisible+ from both ends. This is the first of the two queues on the controller →+ browser path, so a discard here never reaches the UI server's broker at all:+ ids stay contiguous, the browser socket keeps heartbeating, and nothing+ downstream can tell that a gap exists. Counting it is what lets the feed's+ owner end the subscription and make the reconnect announce the gap.+ """++ __slots__ = ("loop", "queue", "dropped")++ def __init__(self, loop: asyncio.AbstractEventLoop, queue: asyncio.Queue) -> None:+ self.loop = loop+ self.queue = queue+ self.dropped = 0++class InboxEventBus:def __init__(self) -> None:- self._subscribers: dict[int, tuple[asyncio.AbstractEventLoop, asyncio.Queue]] = {}+ self._subscribers: dict[int, _Subscription] = {}self._callbacks: dict[int, Callable[[str, Any], None]] = {}self._next_id = 0self._lock = threading.Lock()@@ -49,9 +69,22 @@ class InboxEventBus:with self._lock:sub_id = self._next_idself._next_id += 1- self._subscribers[sub_id] = (loop, queue)+ self._subscribers[sub_id] = _Subscription(loop, queue)return sub_id, queue+ def dropped_count(self, sub_id: int) -> int:+ """How many events this bus discarded for one subscriber, ever.++ Monotonic for the life of the subscription so a caller compares it+ against its own last reading, never resetting it out from under another+ reader. Returns 0 for an unknown ``sub_id``: a subscription that no+ longer exists has no continuity left to speak for.+ """++ with self._lock:+ subscription = self._subscribers.get(sub_id)+ return subscription.dropped if subscription is not None else 0+def subscribe_callback(self, callback: Callable[[str, Any], None]) -> int:"""Register an in-process callback run synchronously before queue fan-out.@@ -85,18 +118,28 @@ class InboxEventBus:callback(event_type, data)except Exception:logger.exception("inbox event callback failed for %s", event_type)- for loop, queue in subs:+ for subscription in subs:try:- loop.call_soon_threadsafe(self._put_nowait, queue, event_type, data)+ subscription.loop.call_soon_threadsafe(+ self._put_nowait, subscription, event_type, data+ )except RuntimeError:# Loop closed mid-publish; drop silently.pass@staticmethod- def _put_nowait(queue: asyncio.Queue, event_type: str, data: Any) -> None:+ def _put_nowait(subscription: _Subscription, event_type: str, data: Any) -> None:+ """Hand one event to one subscriber, and record it if that fails.++ Every path here that does not enqueue is a lost event and must count as+ one. Runs on the subscriber's loop thread via ``call_soon_threadsafe``,+ same as the feed that reads the count, so the counter needs no lock.+ """+try:- queue.put_nowait((event_type, data))+ subscription.queue.put_nowait((event_type, data))except asyncio.QueueFull:+ subscription.dropped += 1logger.warning("inbox event bus subscriber queue full; dropping %s", event_type)diff --git a/core/internal_server.py b/core/internal_server.pyindex 497bf6599..909e86123 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -2016,19 +2016,41 @@ def create_app(from core.inbox_events import bussub_id, queue = bus.subscribe()+ # Baselined before the handshake below, because that yield reaches the+ # bridge and a discard after it is a hole in what this feed promised.+ last_dropped = bus.dropped_count(sub_id)async def _stream():try:- # A REAL ``connected`` event (not a ``:`` comment, which the- # internal_client parser swallows) so it flows bridge → broker →- # browser. The UI sidebar refetches on this, which reconciles- # agent-status dots after a CONTROLLER restart while the UI server- # + browser SSE stay up: only this bridge reconnects, so the- # browser's own ``connected`` never fires and the crash-recovery- # ``running → idle`` reset (broadcast to no subscriber) would- # otherwise be invisible until a manual reload (Codex P2).+ # A REAL ``connected`` event, not a ``:`` comment, which the+ # internal_client parser swallows: the bridge has to be able to+ # observe this handshake. It consumes the frame rather than+ # relaying it, and publishes the bridge-status transition that+ # browsers actually key off. Either way the UI reconciles after a+ # CONTROLLER restart that leaves the UI server + browser SSE up:+ # only this bridge reconnects, so the browser's own ``connected``+ # never fires and the crash-recovery ``running → idle`` reset+ # (broadcast to no subscriber) would otherwise stay invisible+ # until a manual reload (Codex P2).yield _sse_event("connected", {})while True:+ # Same rule as the UI server's browser feed: a subscriber+ # that lost an event is not a subscriber any more. Ending it+ # makes the bridge reconnect, and a reconnect flips the+ # bridge status, which is what tells browsers to reconcile.+ # Announcing the hole down this stream instead cannot work --+ # the queue is still full, so the next iteration finds+ # another discard and announces again. Checked before+ # ``get()`` so no event is relayed as if it followed the+ # previous one when it does not.+ dropped = bus.dropped_count(sub_id)+ if dropped > last_dropped:+ logger.warning(+ "internal events: ending subscriber %s after %s dropped event(s)",+ sub_id,+ dropped - last_dropped,+ )+ returnevent_type, data = await queue.get()yield _sse_event(event_type, data)finally:diff --git a/tests/test_event_loss_is_never_silent.py b/tests/test_event_loss_is_never_silent.pynew file mode 100644index 000000000..9de1004dd--- /dev/null+++ b/tests/test_event_loss_is_never_silent.py@@ -0,0 +1,107 @@+"""Every queue that can discard an event must be able to admit it.++The browser suppresses its reconnect catch-up when the event stream can prove it+lost nothing (see ``ui/src/lib/workbenchEventConnection.ts``). That proof is only+as good as the path's willingness to report a hole, and the path is a chain of+bounded fan-out queues: a full one discards, the publisher's exception has+nowhere to report to, and the subscriber's socket stays open and healthy. Loss+looks exactly like quiet.++Enumerating those queues by hand does not work -- it was asserted complete twice+and was wrong twice, once per review round. So this states the property instead+of the list: wherever a queue drops an event, that drop is counted, and the+module owning it exposes the count. A new bounded fan-out queue added anywhere+under ``core/`` or ``vibe/`` fails this test rather than silently becoming the+next hole in a proof that claims to cover the whole path.++What the count is *for* belongs to each feed's own tests: ``tests/test_sse_broker.py``+and ``tests/test_inbox_events.py`` cover the counters, and+``tests/test_ui_server_fastapi.py`` / ``tests/test_internal_server.py`` cover the+readers ending a subscription whose view has a hole in it.+"""++from __future__ import annotations++import ast+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+SEARCH_ROOTS = ("core", "vibe")+++def _is_queue_full(node: ast.expr | None) -> bool:+ """Match ``asyncio.QueueFull`` and a bare/aliased ``QueueFull``."""++ if isinstance(node, ast.Attribute):+ return node.attr == "QueueFull"+ if isinstance(node, ast.Name):+ return node.id == "QueueFull"+ if isinstance(node, ast.Tuple):+ return any(_is_queue_full(element) for element in node.elts)+ return False+++def _counts_a_drop(handler: ast.ExceptHandler) -> bool:+ """True when the handler increments something named ``dropped``."""++ for node in ast.walk(handler):+ if not isinstance(node, ast.AugAssign):+ continue+ target = node.target+ if isinstance(target, ast.Attribute) and target.attr == "dropped":+ return True+ if isinstance(target, ast.Name) and target.id == "dropped":+ return True+ return False+++def _python_sources() -> list[Path]:+ return sorted(+ path+ for root in SEARCH_ROOTS+ for path in (REPO_ROOT / root).rglob("*.py")+ )+++def test_every_discarded_event_is_counted():+ sources = _python_sources()+ assert sources, "found no sources to scan; the search roots moved"++ silent: list[str] = []+ uncountable: list[str] = []+ found = 0++ for path in sources:+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))+ handlers = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.ExceptHandler) and _is_queue_full(node.type)+ ]+ if not handlers:+ continue+ found += len(handlers)+ relative = path.relative_to(REPO_ROOT)+ for handler in handlers:+ if not _counts_a_drop(handler):+ silent.append(f"{relative}:{handler.lineno}")+ # Counting a drop nobody can read is the same hole one step later.+ exposes_count = any(+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ and node.name == "dropped_count"+ for node in ast.walk(tree)+ )+ if not exposes_count:+ uncountable.append(str(relative))++ assert not silent, (+ "a full queue discards an event without counting it, so no subscriber "+ f"can ever learn its view has a hole: {silent}"+ )+ assert not uncountable, (+ "a module discards events but exposes no dropped_count, so the count "+ f"cannot reach whoever owns the subscriber's stream: {uncountable}"+ )+ # A guard against the scan silently matching nothing (an import rename, a+ # moved module): the property above is vacuous if it inspected no handlers.+ assert found >= 2, f"expected the known fan-out queues to be scanned, saw {found}"diff --git a/tests/test_inbox_bridge.py b/tests/test_inbox_bridge.pyindex f58b09250..dcce5d2ca 100644--- a/tests/test_inbox_bridge.py+++ b/tests/test_inbox_bridge.py@@ -26,9 +26,11 @@ def test_inbox_bridge_publishes_controller_bridge_status(monkeypatch):asyncio.run(inbox_bridge.run_inbox_bridge())assert inbox_bridge.is_bridge_connected() is False+ # The internal feed's own handshake is consumed, not relayed: the status+ # frame beside it is the browser-facing expression of the same fact, and one+ # fact announced twice made every controller recovery cost two catch-ups.assert published == [("workbench.events.bridge.status", {"connected": True}),- ("connected", {}),("runs.updated", {"run_id": "run_1", "status": "queued"}),("workbench.events.bridge.status", {"connected": False}),]diff --git a/tests/test_inbox_events.py b/tests/test_inbox_events.pyindex 30aa302cf..7f2c8889a 100644--- a/tests/test_inbox_events.py+++ b/tests/test_inbox_events.py@@ -260,3 +260,42 @@ def test_sqlite_background_store_does_not_bridge_controller_self_updates(tmp_patstore.close()assert bridged == []+++def test_dropped_count_records_what_a_full_bus_queue_discarded():+ """The first of the two queues between the controller and a browser.++ A discard here never reaches the UI server's broker at all, so nothing+ downstream can infer it: the bridge keeps relaying, the browser socket keeps+ heartbeating, and a proof built on those would vouch for continuity it does+ not have. The count is what lets ``/internal/events`` end the subscription+ and make the reconnect announce the gap instead.+ """+ import asyncio++ from core.inbox_events import InboxEventBus++ async def scenario():+ bus = InboxEventBus()+ sub_id, queue = bus.subscribe()+ assert bus.dropped_count(sub_id) == 0++ for index in range(queue.maxsize + 3):+ bus.publish("runs.updated", {"run_id": f"run_{index}"})+ # publish() hands off via call_soon_threadsafe, so let the loop run it.+ await asyncio.sleep(0)++ assert queue.qsize() == queue.maxsize+ assert bus.dropped_count(sub_id) == 3+ # Monotonic: reading it must not consume another reader's evidence.+ assert bus.dropped_count(sub_id) == 3++ bus.publish("runs.updated", {"run_id": "run_overflow"})+ await asyncio.sleep(0)+ assert bus.dropped_count(sub_id) == 4++ # A subscription that no longer exists has no continuity to speak for.+ bus.unsubscribe(sub_id)+ assert bus.dropped_count(sub_id) == 0++ asyncio.run(scenario())diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 7d85f7b08..7194bba48 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -1796,6 +1796,96 @@ def test_publish_event_endpoint_emits_allowlisted_bus_event():]+def test_internal_events_end_a_subscriber_whose_queue_overflowed(monkeypatch):+ """The controller feed drops its reader rather than serving it a hole.++ This is the first bounded queue on the controller → UI-server → browser+ path, and a discard here is the most invisible of the three: the UI server's+ broker never sees the event, so every id downstream stays contiguous and+ every socket keeps heartbeating. Ending the stream is what turns the loss+ into a signal -- the bridge reconnects, the reconnect flips+ ``workbench.events.bridge.status``, and browsers reconcile once. Announcing+ the hole down this same stream cannot work: the queue is still full, so the+ next iteration finds another discard and announces again, starving the+ payload frames the warning was about.+ """++ from core import inbox_events++ subscriptions: list[tuple[int, asyncio.Queue]] = []+ real_subscribe = inbox_events.bus.subscribe++ def tracking_subscribe():+ # The controller handshake carries no sub_id (the browser feed's does),+ # so the test learns it the only other way available to a caller.+ subscription = real_subscribe()+ subscriptions.append(subscription)+ return subscription++ monkeypatch.setattr(inbox_events.bus, "subscribe", tracking_subscribe)+ baseline_subscribers = inbox_events.bus.subscriber_count()++ def decode(chunk) -> str:+ return chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk++ async def collect_until_end() -> tuple[str, int, list[str], bool, int]:+ app = internal_server.create_app(_build_controller_double())+ route = next(+ candidate+ for candidate in app.routes+ if getattr(candidate, "path", None) == "/internal/events"+ and "GET" in (getattr(candidate, "methods", None) or set())+ )+ response = await route.endpoint()+ iterator = response.body_iterator.__aiter__()+ frames: list[str] = []+ ended = False+ try:+ handshake = decode(await iterator.__anext__())+ sub_id, queue = subscriptions[-1]+ # Park the stream inside its read loop before overflowing the queue,+ # so what this asserts is a discard the reader has to notice on a+ # later iteration -- not one already covered by the handshake it+ # just delivered.+ pending = asyncio.create_task(iterator.__anext__())+ await asyncio.sleep(0)++ for index in range(queue.maxsize + 3):+ inbox_events.bus.publish("runs.updated", {"run_id": f"run_{index}"})+ # One yield runs the whole batch of ``call_soon_threadsafe``+ # handoffs, so every discard has happened by the time the count is+ # read.+ await asyncio.sleep(0)+ dropped = inbox_events.bus.dropped_count(sub_id)++ # Bounded well below the ``maxsize`` frames still sitting in the+ # queue: a stream that kept serving them would run out of the budget+ # rather than end, which is the failure this asserts against.+ for _ in range(5):+ awaitable = pending if pending is not None else iterator.__anext__()+ pending = None+ try:+ frames.append(decode(await asyncio.wait_for(awaitable, timeout=2)))+ except StopAsyncIteration:+ ended = True+ break+ finally:+ await iterator.aclose()+ # Read after the generator has exited: its ``finally`` unsubscribes, and+ # a subscription that no longer exists is owed nothing.+ return handshake, dropped, frames, ended, inbox_events.bus.subscriber_count()++ handshake, dropped, frames, ended, subscribers_after = asyncio.run(collect_until_end())++ assert "event: connected" in handshake+ assert dropped == 3+ assert ended is True+ # The queue still held ``maxsize`` events, so anything but a short tail here+ # means the reader kept relaying frames across the gap.+ assert len(frames) <= 1+ assert subscribers_after == baseline_subscribers++def test_reconcile_platforms_endpoint_calls_controller(monkeypatch):controller = _build_controller_double()calls = []diff --git a/tests/test_sse_broker.py b/tests/test_sse_broker.pyindex d9749bfcf..996a58581 100644--- a/tests/test_sse_broker.py+++ b/tests/test_sse_broker.py@@ -54,6 +54,53 @@ def test_publish_preserves_repeated_payloads_and_omits_ts():assert third_payload == {"type": "queue.updated", "data": {"session_id": "ses2"}}+def test_dropped_count_records_what_a_full_queue_discarded():+ """A subscriber that cannot keep up is a subscriber losing events.++ The queue is bounded, so ``put_nowait`` raises somewhere it cannot report+ while the subscriber's socket stays perfectly healthy. Unless the broker+ counts the discard, nobody ever finds out it happened.+ """++ broker = SSEBroker()++ async def scenario():+ sub_id, queue = broker.subscribe()+ overflow = 3+ for index in range(queue.maxsize + overflow):+ broker.publish("queue.updated", {"n": index})+ # ``publish`` hands each event over with ``call_soon_threadsafe``, so+ # none of them have been enqueued yet; one yield runs the whole batch.+ await asyncio.sleep(0)+ first_reading = broker.dropped_count(sub_id)+ # Monotonic, never reset: whoever acts on the count compares it against+ # its own last reading, so reading it must not consume it.+ repeat_reading = broker.dropped_count(sub_id)++ broker.publish("queue.updated", {"n": "one more"})+ await asyncio.sleep(0)+ second_reading = broker.dropped_count(sub_id)++ broker.unsubscribe(sub_id)+ return (+ queue.maxsize,+ queue.qsize(),+ first_reading,+ repeat_reading,+ second_reading,+ broker.dropped_count(sub_id),+ )++ maxsize, queued, first_reading, repeat_reading, second_reading, after_unsubscribe = asyncio.run(scenario())++ assert queued == maxsize+ assert first_reading == 3+ assert repeat_reading == 3+ assert second_reading == 4+ # A subscription that no longer exists has no continuity left to speak for.+ assert after_unsubscribe == 0++def test_publish_survives_concurrent_subscribe_churn():broker = SSEBroker()diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 0d4830e83..6f7487bd1 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -2613,6 +2613,137 @@ def test_workbench_events_filter_privileged_events_for_viewers(monkeypatch, tmp_assert "hidden-secret" not in body+def test_workbench_events_heartbeat_proves_liveness_on_its_own_clock(monkeypatch, tmp_path):+ """A browser must be able to tell a quiet stream from a dead one.++ The keep-alive comment cannot say it -- ``EventSource`` never surfaces a+ comment -- so the stream emits an observable frame on a wall-clock cadence+ that no amount of traffic can suppress.+ """+ from vibe.authorization import AuthorizationContext+ from vibe.sse_broker import broker+ from vibe.ui_compat import g++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ # Only to keep the test quick. The client reads the cadence off the frame+ # rather than assuming the shipped value.+ monkeypatch.setattr(ui_server, "WORKBENCH_EVENT_HEARTBEAT_INTERVAL_S", 0.05)++ def decode(chunk) -> str:+ return chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk++ async def collect_heartbeats() -> tuple[str, str, str]:+ with app.test_request_context("/api/events"):+ g.authorization_context = AuthorizationContext(instance_role="viewer", is_remote=True)+ response = await ui_server.workbench_events()+ iterator = response.body_iterator.__aiter__()+ try:+ handshake = [decode(await iterator.__anext__()) for _ in range(3)]+ idle = await asyncio.wait_for(iterator.__anext__(), timeout=2)+ # A stream carrying events this viewer may not see is silent+ # from the browser's side while being anything but idle, so a+ # cadence measured from the last delivered frame would leave+ # exactly this subscriber unable to prove its stream alive.+ broker.publish("vaults.updated", {"secret_name": "hidden-secret"})+ busy = await asyncio.wait_for(iterator.__anext__(), timeout=2)+ finally:+ await iterator.aclose()+ return handshake[1], decode(idle), decode(busy)++ connected, idle, busy = asyncio.run(collect_heartbeats())++ # The handshake declares the cadence before anything proves it. That promise+ # is what lets a client hold a brand-new stream to a deadline: without it, a+ # stream that opens and then goes silent has nothing to have broken, and the+ # client's only options are to trust it for a whole window or to watchdog+ # servers that never promised anything.+ assert "event: connected" in connected+ assert '"interval_ms":50' in connected++ assert "event: heartbeat" in idle+ # The cadence rides along here too, because only a heartbeat is proof, and+ # proof is what the staleness window is measured from.+ assert '"interval_ms":50' in idle+ assert "event: heartbeat" in busy+ assert "hidden-secret" not in busy+++def test_workbench_events_end_a_subscriber_whose_queue_overflowed(monkeypatch, tmp_path):+ """A subscriber that lost an event is not a subscriber any more.++ The broker's per-subscriber queue is bounded, so "slow subscriber" and "lost+ events" are one condition -- and nothing else on the wire betrays it: the+ socket stays open and the heartbeats keep proving it alive. Ending the stream+ is the repair, because the client's reconnect path gets a fresh empty queue+ and catches consumers up exactly once, with backoff if the load that+ overflowed the queue is still going. Announcing the hole on this stream+ instead keeps a full queue full: the next iteration finds another discard and+ announces again, starving the payload frames it was warning about.+ """+ from vibe.authorization import AuthorizationContext+ from vibe.sse_broker import broker+ from vibe.ui_compat import g++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()++ def decode(chunk) -> str:+ return chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk++ async def collect_until_end() -> tuple[int, list[str], bool, int]:+ with app.test_request_context("/api/events"):+ g.authorization_context = AuthorizationContext(instance_role="owner", is_remote=True)+ response = await ui_server.workbench_events()+ iterator = response.body_iterator.__aiter__()+ frames: list[str] = []+ ended = False+ try:+ handshake = [decode(await iterator.__anext__()) for _ in range(3)]+ sub_id = int(json.loads(handshake[1].split("data: ", 1)[1])["sub_id"])+ # Park the stream inside its read loop before overflowing the+ # queue. A discard from before the loop started is already+ # covered by the handshake the client just received, so only a+ # later one is worth acting on.+ pending = asyncio.create_task(iterator.__anext__())+ await asyncio.sleep(0)++ for index in range(400):+ broker.publish("session.activity", {"session_id": f"ses{index}"})+ # One yield runs the whole batch of ``call_soon_threadsafe``+ # handoffs, so every discard has happened by the time the count+ # is read.+ await asyncio.sleep(0)+ dropped = broker.dropped_count(sub_id)++ # Bounded well below the ~200 frames still sitting in the queue:+ # a stream that kept serving them would run out of the budget+ # rather than end, which is the failure this asserts against.+ for _ in range(5):+ awaitable = pending if pending is not None else iterator.__anext__()+ pending = None+ try:+ frames.append(decode(await asyncio.wait_for(awaitable, timeout=2)))+ except StopAsyncIteration:+ ended = True+ break+ finally:+ await iterator.aclose()+ # Read after the generator has exited: its ``finally`` releases the+ # subscription, so the client's reconnect starts from a clean slate+ # rather than inheriting a count that would end the new stream too.+ return dropped, frames, ended, broker.dropped_count(sub_id)++ dropped, frames, ended, dropped_after_release = asyncio.run(collect_until_end())++ assert dropped > 0+ assert ended+ assert dropped_after_release == 0+ # Not by announcing the hole on the stream that has it: nothing about a+ # subscriber whose view is incomplete is worth another frame.+ assert not [frame for frame in frames if "workbench.events.gap" in frame]++def test_workbench_events_allow_show_events_when_show_page_acl_allows(monkeypatch, tmp_path) -> None:from vibe.authorization import AuthorizationContextfrom vibe.sse_broker import brokerdiff --git a/ui/src/components/workbench/AgentGraphTab.tsx b/ui/src/components/workbench/AgentGraphTab.tsxindex 139fc949e..0dc450c27 100644--- a/ui/src/components/workbench/AgentGraphTab.tsx+++ b/ui/src/components/workbench/AgentGraphTab.tsx@@ -315,16 +315,11 @@ export const AgentGraphTab: React.FC = () => {// transport (contract). Refetch in the background on any signal.useEffect(() => {return api.connectWorkbenchEvents({- onConnected: (data) => {- if (data.source === 'controller') {- setEventBridgeConnected(true);- void fetchGraph(true);- }- },- onEventBridgeStatus: ({ connected }) => {- setEventBridgeConnected(connected);- if (connected) void fetchGraph(true);- },+ // Every gap ends here, whichever leg it was on, so this is the catch-up.+ // The bridge report is only the indicator's level: it comes with its own+ // `onConnected`, and refetching from both would pay twice for one gap.+ onConnected: () => void fetchGraph(true),+ onEventBridgeStatus: ({ connected }) => setEventBridgeConnected(connected),onError: () => setEventBridgeConnected(false),onRunsUpdated: () => void fetchGraph(true),onTurnStart: () => void fetchGraph(true),diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex c45ed5a34..6a62f8c06 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -215,16 +215,11 @@ export const AgentsPage: React.FC = () => {return;}return api.connectWorkbenchEvents({- onConnected: (data) => {- if (data.source === 'controller') {- setEventBridgeConnected(true);- fetchRunningActiveCount();- }- },- onEventBridgeStatus: ({ connected }) => {- setEventBridgeConnected(connected);- if (connected) fetchRunningActiveCount();- },+ // Every gap ends here, whichever leg it was on, so this is the catch-up.+ // The bridge report is only the indicator's level: it comes with its own+ // `onConnected`, and refetching from both would pay twice for one gap.+ onConnected: () => fetchRunningActiveCount(),+ onEventBridgeStatus: ({ connected }) => setEventBridgeConnected(connected),onError: () => setEventBridgeConnected(false),onRunsUpdated: () => fetchRunningActiveCount(),onTurnStart: () => fetchRunningActiveCount(),diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex eff04f585..7d3983432 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -38,7 +38,7 @@ import { isEditableFile, isEditableMeta, previewOverlayKind } from '../../lib/fiimport { recentPathLabel } from '../../lib/editorRecents';import type { LocalFileLinkTarget } from '../../lib/localFileLinks';import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';-import { canMarkConversationRead, onPageReactivated, usePageActive } from '../../lib/pageActivity';+import { canMarkConversationRead, usePageActive } from '../../lib/pageActivity';import { isDesktopViewport, useIsDesktop } from '../../lib/useIsDesktop';import { resultFooterParts } from '../../lib/resultFooter';import {@@ -1504,6 +1504,16 @@ export const ChatPage: React.FC = () => {// appear without the user having sent anything.useEffect(() => {if (!sessionId) return;+ // Whatever the stream could not deliver, read back from durable storage:+ // dropped message rows, the queue, whether a turn is still running, and a+ // native bind whose turn.end went missing. Both gap edges want exactly+ // this, so they share it rather than each keeping their own copy.+ const catchUpAfterGap = () => {+ void reconcile({ force: true });+ void refreshQueue();+ void syncTurnState({ quiet: true });+ void refreshSessionRow();+ };const disconnect = api.connectWorkbenchEvents({// NB: match against sessionIdRef.current (the CURRENT route), NOT the// captured ``sessionId`` — there is a window after a chat switch before@@ -1621,15 +1631,12 @@ export const ChatPage: React.FC = () => {// invalidation and converge on the complete committed row.void refreshSessionRow();},- onConnected: () => {- // Every (re)connect recovers any state missed while the socket was down:- // dropped message rows, the queue, whether a turn is still running, and- // a native bind whose turn.end we missed.- void reconcile({ force: true });- void refreshQueue();- void syncTurnState({ quiet: true });- void refreshSessionRow();- },+ // A socket that was down missed whatever happened while it was. This+ // covers every way a stream can break, including a mobile tab suspended+ // without a clean reconnect: ApiContext recycles a stream that cannot+ // prove it survived, so the recovery arrives here (Codex P2). A stream+ // that did prove it fires nothing — it already delivered them.+ onConnected: catchUpAfterGap,onAuthorizationChanged: (data) => {const currentSessionId = sessionIdRef.current;if (!currentSessionId) return;@@ -1657,30 +1664,6 @@ export const ChatPage: React.FC = () => {return disconnect;}, [api, sessionId, appendMessage, reconcile, refresh, refreshQueue, syncTurnState, refreshSessionRow, markWorking, goBack, ingestActivityRow, scheduleActivityRefresh, dispatchLive, probeShowPageAccess, installServerSession]);- // Mobile tabs (the common case for IM users) get backgrounded mid-turn; the- // SSE feed can be suspended without a clean reconnect, dropping the reply.- // Reconcile when the page comes back so the answer + working state catch up- // to durable storage.- useEffect(() => {- if (!sessionId) return;- const resync = () => {- if (document.visibilityState !== 'visible') return;- // A suspended tab can drop the reply AND the turn.end, so recover all- // three: missed rows, the queue, and the working/Stop state (Codex P2).- void reconcile({ force: true });- void refreshQueue();- void syncTurnState({ quiet: true });- void refreshSessionRow();- };- // Regaining the network is its own gap, independent of the page coming back.- const stopReactivation = onPageReactivated(resync);- window.addEventListener('online', resync);- return () => {- stopReactivation();- window.removeEventListener('online', resync);- };- }, [sessionId, reconcile, refreshQueue, syncTurnState, refreshSessionRow]);-useEffect(() => {setRuntimeState((current) => ({ ...current, pending_input_count: queue.length }));}, [queue.length]);diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex 12314f214..296fd29cb 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -552,16 +552,11 @@ export const VaultsPage: React.FC = () => {useEffect(() => {return api.connectWorkbenchEvents({- onConnected: (data) => {- if (data.source === 'controller') {- setEventBridgeConnected(true);- refresh();- }- },- onEventBridgeStatus: ({ connected }) => {- setEventBridgeConnected(connected);- if (connected) refresh();- },+ // Every gap ends here, whichever leg it was on, so this is the catch-up.+ // The bridge report is only the indicator's level: it comes with its own+ // `onConnected`, and refetching from both would pay twice for one gap.+ onConnected: () => refresh(),+ onEventBridgeStatus: ({ connected }) => setEventBridgeConnected(connected),onError: () => setEventBridgeConnected(false),onVaultsUpdated: () => refresh(),onAuthorizationChanged: () => refresh(),diff --git a/ui/src/context/ApiContext.streamLiveness.test.tsx b/ui/src/context/ApiContext.streamLiveness.test.tsxnew file mode 100644index 000000000..06cc6df4e--- /dev/null+++ b/ui/src/context/ApiContext.streamLiveness.test.tsx@@ -0,0 +1,462 @@+/* @vitest-environment jsdom */++import { cleanup, render } from '@testing-library/react';+import { useEffect } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const apiFetch = vi.hoisted(() => vi.fn());+const showToast = vi.hoisted(() => vi.fn());++vi.mock('../lib/apiFetch', () => ({ apiFetch }));+vi.mock('./ToastContext', () => ({ useToast: () => ({ showToast }) }));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++import {+ WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS,+ WORKBENCH_EVENT_RETRY_INITIAL_MS,+ workbenchEventStaleAfterMs,+} from '../lib/workbenchEventConnection';+import { ApiProvider, useApi } from './ApiContext';++const STALE_AFTER_MS = workbenchEventStaleAfterMs(WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS);++/**+ * Enough of EventSource to be inspected and fed frames. jsdom ships none, and+ * the behavior under test is precisely what the real one cannot express: a+ * socket that died while the page was suspended, still reporting `OPEN`.+ */+class FakeEventSource {+ static readonly OPEN = 1;+ static instances: FakeEventSource[] = [];++ readyState = FakeEventSource.OPEN;+ closed = false;+ onerror: ((event: Event) => void) | null = null;+ private readonly listeners = new Map<string, Set<(event: MessageEvent) => void>>();++ constructor(readonly url: string) {+ FakeEventSource.instances.push(this);+ }++ addEventListener(type: string, listener: (event: MessageEvent) => void): void {+ const bucket = this.listeners.get(type) ?? new Set();+ bucket.add(listener);+ this.listeners.set(type, bucket);+ }++ removeEventListener(type: string, listener: (event: MessageEvent) => void): void {+ this.listeners.get(type)?.delete(listener);+ }++ close(): void {+ this.closed = true;+ this.readyState = 2;+ }++ emit(type: string, data: unknown): void {+ const event = { data: JSON.stringify(data) } as MessageEvent;+ for (const listener of [...(this.listeners.get(type) ?? [])]) listener(event);+ }++ static latest(): FakeEventSource {+ const source = FakeEventSource.instances.at(-1);+ if (!source) throw new Error('no EventSource was opened');+ return source;+ }+}++/**+ * The one signal consumers catch up on. Every gap has to arrive here, and a+ * stream that never broke must not produce it a second time.+ */+const onConnected = vi.fn();++const Subscriber = () => {+ const api = useApi();+ useEffect(() => api.connectWorkbenchEvents({ onConnected }), [api]);+ return null;+};++/** A heartbeat, which is also the server declaring the cadence it owes. */+const emitHeartbeat = () => {+ FakeEventSource.latest().emit('heartbeat', {+ interval_ms: WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS,+ });+};++/**+ * What the UI server reports about its own leg to the controller. It sends one+ * of these immediately after the handshake on every stream it opens, which is+ * why every mount below sends one too: a fixture that skipped it would be+ * testing a client talking to a server that does not exist.+ */+const emitControllerLeg = (connected: boolean) => {+ FakeEventSource.latest().emit('workbench.events.bridge.status', {+ type: 'workbench.events.bridge.status',+ data: { connected },+ });+};++/** A handshake from a server that declares the cadence it owes. */+const emitHandshake = (subId: number) => {+ FakeEventSource.latest().emit('connected', {+ sub_id: subId,+ interval_ms: WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS,+ });+};++/** A handshake from a server too old to declare one: nothing to enforce. */+const emitUndeclaredHandshake = (subId: number) => {+ FakeEventSource.latest().emit('connected', { sub_id: subId });+};++/** Open a stream and complete its handshake, as a real connect would. */+const mountStream = () => {+ render(<ApiProvider><Subscriber /></ApiProvider>);+ emitHandshake(1);+ emitControllerLeg(true);+};++/** The same, against a server that never declares a cadence. */+const mountUndeclaredStream = () => {+ render(<ApiProvider><Subscriber /></ApiProvider>);+ emitUndeclaredHandshake(1);+ emitControllerLeg(true);+};++/**+ * The ordinary case: a stream that handshook and then proved itself. A handshake+ * is a promise about the future, not evidence about the past, so anything that+ * expects a stream to vouch for a gap has to start here rather than at the+ * handshake.+ */+const mountConnectedStream = () => {+ mountStream();+ emitHeartbeat();+};++const setVisibility = (state: 'visible' | 'hidden') => {+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: state });+ document.dispatchEvent(new Event('visibilitychange'));+};++/**+ * The page leaving and coming back: the gap the gate is asked to account for.+ * `beat` is whether the stream spoke while the page was away, which is the only+ * evidence that can cover an interval -- a heartbeat from before it was away+ * says nothing about what happened during it.+ */+const awayAndBack = ({ beat = false, awayMs = 1_000 } = {}) => {+ setVisibility('hidden');+ vi.advanceTimersByTime(awayMs);+ if (beat) emitHeartbeat();+ setVisibility('visible');+};++/** Regaining the network: a gap nothing here watched open, so an undated one. */+const networkBack = () => {+ window.dispatchEvent(new Event('online'));+};++beforeEach(() => {+ vi.useFakeTimers();+ // jsdom reports no window focus, and a page that never counts as active never+ // counts as coming back either. These tests are about what happens when it+ // does, so give it the focus a real browser tab has.+ document.hasFocus = () => true;+ apiFetch.mockReset();+ apiFetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });+ showToast.mockReset();+ onConnected.mockReset();+ FakeEventSource.instances = [];+ vi.stubGlobal('EventSource', FakeEventSource);+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+});++afterEach(() => {+ cleanup();+ Reflect.deleteProperty(document, 'hasFocus');+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe('ApiProvider workbench stream liveness', () => {+ it('leaves a stream that keeps proving itself alone across reactivations', () => {+ mountConnectedStream();+ expect(onConnected).toHaveBeenCalledTimes(1);++ // The whole optimization: returning to a page whose stream kept running+ // through the gap must not recycle it, and so must not make consumers+ // re-read what it has already delivered.+ awayAndBack({ beat: true });+ expect(FakeEventSource.instances).toHaveLength(1);+ expect(onConnected).toHaveBeenCalledTimes(1);++ // Heartbeats keep proving it well past the stale window, which also shows+ // the watchdog re-arming on each one: without that, the deadline armed at+ // the handshake would have killed this stream during the second pass.+ for (let pass = 0; pass < 3; pass += 1) {+ vi.advanceTimersByTime(STALE_AFTER_MS - 1_000);+ emitHeartbeat();+ awayAndBack({ beat: true });+ }+ expect(FakeEventSource.instances).toHaveLength(1);+ expect(FakeEventSource.latest().closed).toBe(false);+ expect(onConnected).toHaveBeenCalledTimes(1);+ });++ it('recycles a stream that stopped proving itself while nothing else noticed', () => {+ mountConnectedStream();+ const zombie = FakeEventSource.latest();+ expect(onConnected).toHaveBeenCalledTimes(1);++ // No heartbeat for longer than the stale window, with no page event and no+ // `error` -- a socket dropped by a proxy that the browser keeps reporting+ // `OPEN`. Nobody would ever ask about it, so the watchdog has to.+ vi.advanceTimersByTime(STALE_AFTER_MS);+ expect(zombie.closed).toBe(true);+ // Not a moment earlier than that: the catch-up is worth nothing until a+ // stream is actually carrying events again.+ expect(onConnected).toHaveBeenCalledTimes(1);++ vi.advanceTimersByTime(WORKBENCH_EVENT_RETRY_INITIAL_MS);+ expect(FakeEventSource.instances).toHaveLength(2);+ emitHandshake(2);+ expect(onConnected).toHaveBeenCalledTimes(2);+ });++ it('defers to the reactivation edge while the page is hidden', () => {+ mountConnectedStream();+ const zombie = FakeEventSource.latest();++ // A hidden page cannot hold a stream open and its timers are throttled or+ // frozen, so the watchdog declines to judge -- reopening from there is the+ // burst of hidden-tab reconnects this whole design exists to avoid.+ setVisibility('hidden');+ vi.advanceTimersByTime(STALE_AFTER_MS * 2);+ expect(zombie.closed).toBe(false);+ expect(zombie.readyState).toBe(FakeEventSource.OPEN);+ expect(onConnected).toHaveBeenCalledTimes(1);++ // Coming back is where that stream is asked to account for the gap. It+ // cannot, so it is replaced -- and the edge itself carries the catch-up,+ // because the replacement may be several backoff windows away.+ setVisibility('visible');+ expect(zombie.closed).toBe(true);+ expect(onConnected).toHaveBeenCalledTimes(2);++ emitHandshake(2);+ expect(onConnected).toHaveBeenCalledTimes(3);+ });++ it('catches consumers up on the wake edge, not on the stream it is replacing', () => {+ mountConnectedStream();+ expect(onConnected).toHaveBeenCalledTimes(1);++ awayAndBack({ awayMs: STALE_AFTER_MS });++ // Recovery must not depend on the thing being recovered. The stale stream is+ // gone and its replacement has not handshaken -- and against a stopped+ // server or an offline network it never will -- so waiting for that+ // handshake would leave a returning page showing what it had before it was+ // hidden, with nothing on the way.+ expect(onConnected).toHaveBeenCalledTimes(2);+ // And it is the edge's own catch-up: the stale stream is closed and its+ // replacement has not reported in, so nothing else could have produced it.+ expect(FakeEventSource.instances).toHaveLength(2);++ // Repeated edges on a stream that still cannot prove itself each pay for+ // themselves, exactly as the unconditional refetch did before this change.+ awayAndBack();+ expect(onConnected).toHaveBeenCalledTimes(3);+ });++ it('does not let a heartbeat from before the gap speak for it', () => {+ mountConnectedStream();+ expect(onConnected).toHaveBeenCalledTimes(1);++ // A suspension shorter than the freshness window. The newest heartbeat is+ // still fresh by the clock, but it arrived before the page left: a frozen+ // tab receives nothing, so a window with no heartbeat in it is not the+ // scheduling jitter that tolerance exists for. It is silence.+ awayAndBack({ awayMs: 5_000 });+ expect(onConnected).toHaveBeenCalledTimes(2);++ // The socket itself is still plausible, so it is kept: recycling on every+ // short tab switch would cost more than the read it saves, and the watchdog+ // is already watching for the heartbeat this stream now owes.+ expect(FakeEventSource.instances).toHaveLength(1);+ expect(FakeEventSource.latest().closed).toBe(false);+ });++ it('treats a network return as a gap nothing can vouch for', () => {+ mountConnectedStream();+ expect(onConnected).toHaveBeenCalledTimes(1);++ // Nothing here watched the connection drop, so no heartbeat can be placed+ // inside the gap and the catch-up is the only safe reading -- what the+ // unconditional refetch did before this change, on an event that fires when+ // the network actually changes rather than on every focus move.+ networkBack();+ expect(onConnected).toHaveBeenCalledTimes(2);+ expect(FakeEventSource.instances).toHaveLength(1);+ });++ it('does not let a replacement stream inherit the old one as proof of life', () => {+ mountConnectedStream();+ const first = FakeEventSource.latest();++ awayAndBack({ awayMs: STALE_AFTER_MS });+ expect(first.closed).toBe(true);++ // The stale stream was recycled; until the replacement proves itself there+ // is nothing vouching for it, so a second return is another gap rather than+ // a stream that accounted for one.+ const replacement = FakeEventSource.latest();+ expect(replacement).not.toBe(first);+ awayAndBack();+ expect(replacement.closed).toBe(true);++ // Once a stream proves itself across the gap, it speaks for itself again --+ // and the return is free, which is the entire point of the design. Both legs+ // report in, because a replacement stream inherits nothing: the old one's+ // controller-leg report went with it.+ emitHandshake(2);+ emitControllerLeg(true);+ emitHeartbeat();+ const proven = FakeEventSource.latest();+ const catchUps = onConnected.mock.calls.length;+ awayAndBack({ beat: true });+ expect(FakeEventSource.latest()).toBe(proven);+ expect(proven.closed).toBe(false);+ expect(onConnected).toHaveBeenCalledTimes(catchUps);+ });++ it('ends a controller-leg gap in place, without recycling the browser leg', () => {+ mountConnectedStream();++ // A report of the level it is already at is not a recovery, any more than+ // the opening one the mount already sent was. A stream that just dispatched+ // its handshake catch-up must not be charged a second one, or every connect+ // would cost double what it saves.+ emitControllerLeg(true);+ expect(onConnected).toHaveBeenCalledTimes(1);++ // While that leg is down the controller publishes into a severed bridge and+ // nothing replays it, so this is a real gap -- one the browser socket sails+ // straight through, heartbeating, with no error to report.+ emitControllerLeg(false);+ vi.advanceTimersByTime(STALE_AFTER_MS - 1_000);+ emitHeartbeat();+ expect(onConnected).toHaveBeenCalledTimes(1);++ emitControllerLeg(true);+ expect(onConnected).toHaveBeenCalledTimes(2);+ // Reopening this socket would have inherited the same severed bridge, so the+ // recovery is announced on the stream that stayed up rather than by making a+ // new one.+ expect(FakeEventSource.instances).toHaveLength(1);+ expect(FakeEventSource.latest().closed).toBe(false);++ // And it is the transition that carries the meaning, every time it happens.+ emitControllerLeg(false);+ emitControllerLeg(true);+ expect(onConnected).toHaveBeenCalledTimes(3);+ });++ it('does not let a live socket vouch for a gap the controller leg was down for', () => {+ mountConnectedStream();+ emitControllerLeg(false);+ const socket = FakeEventSource.latest();+ const catchUps = onConnected.mock.calls.length;++ // The two rulings meet here, and each keeps its own scope. The socket+ // heartbeats through the whole gap, so the transport has nothing to repair+ // and is left alone -- reopening it would inherit the same severed bridge.+ // But what it carried across that gap came from a bridge that was down, so+ // the interval is not accounted for and the returning page reads.+ awayAndBack({ beat: true });+ expect(onConnected).toHaveBeenCalledTimes(catchUps + 1);+ expect(FakeEventSource.latest()).toBe(socket);+ expect(socket.closed).toBe(false);++ // Every return during the outage pays, exactly as an unconditional refetch+ // would: nothing here can shorten a gap that is still open.+ awayAndBack({ beat: true });+ expect(onConnected).toHaveBeenCalledTimes(catchUps + 2);++ // And once both legs are carrying again, returns are free again -- the+ // recovery itself is the last catch-up the outage costs.+ emitControllerLeg(true);+ const settled = onConnected.mock.calls.length;+ awayAndBack({ beat: true });+ expect(onConnected).toHaveBeenCalledTimes(settled);+ });++ it('never holds a server to a cadence it did not declare', () => {+ mountUndeclaredStream();+ const legacy = FakeEventSource.latest();++ // An older server -- a rollback under a tab that stayed open -- completes+ // the handshake and then says nothing more. A deadline is a claim about a+ // cadence, and this server made none, so there is nothing to enforce:+ // closing it on a timer would recycle a healthy stream every stale window,+ // forever, charging every consumer a catch-up each round.+ vi.advanceTimersByTime(STALE_AFTER_MS * 4);+ expect(legacy.closed).toBe(false);+ expect(FakeEventSource.instances).toHaveLength(1);+ expect(onConnected).toHaveBeenCalledTimes(1);++ // But it never counts as proven either, not even for one cadence: the+ // handshake says this stream is alive now, which is not the question. So the+ // reactivation edge recycles it immediately and pays for the catch-up -- the+ // pre-heartbeat behavior this optimization replaces, and no worse than it.+ awayAndBack();+ expect(legacy.closed).toBe(true);+ expect(onConnected).toHaveBeenCalledTimes(2);+ });++ it('holds a stream to the cadence its handshake promised, heartbeat or not', () => {+ mountStream();+ const silent = FakeEventSource.latest();++ // The hole a stamp-only clock cannot express: this stream opened, promised a+ // cadence, and then went quiet without ever sending a first heartbeat. There+ // is nothing to stamp, so the promise itself has to start the clock -- or a+ // stream that dies this way is watched by nobody, and the browser will keep+ // reporting the dead socket `OPEN`.+ vi.advanceTimersByTime(STALE_AFTER_MS);+ expect(silent.closed).toBe(true);++ // A heartbeat then restarts that same clock rather than replacing the+ // mechanism, so a stream that keeps proving itself is never recycled.+ vi.advanceTimersByTime(WORKBENCH_EVENT_RETRY_INITIAL_MS);+ emitHandshake(2);+ const proven = FakeEventSource.latest();+ for (let pass = 0; pass < 3; pass += 1) {+ vi.advanceTimersByTime(STALE_AFTER_MS - 1_000);+ emitHeartbeat();+ }+ expect(proven.closed).toBe(false);+ });++ it('keeps a declared cadence when a later handshake carries none', () => {+ mountStream();+ const declared = FakeEventSource.latest();++ // Only a frame carrying a cadence may speak for one. A `connected` without+ // one is either an older UI server's handshake or some future producer of+ // the same event name; arriving late in the window, one allowed to speak+ // would either retire the deadline this server promised or push it out by a+ // full window -- and this stream is already dead, having never sent a+ // heartbeat. (The controller relay that first motivated this rule is gone:+ // its frame is consumed by the bridge, which publishes the leg's status+ // instead.)+ vi.advanceTimersByTime(STALE_AFTER_MS - 1_000);+ FakeEventSource.latest().emit('connected', { type: 'connected' });+ vi.advanceTimersByTime(1_000);+ expect(declared.closed).toBe(true);+ });+});diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex c7c03e7a6..3e3b454ab 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -6,7 +6,7 @@ import { apiFetch, recoverRemoteAuthFromSessionProbe } from '../lib/apiFetch';import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';import type { TurnActivityGroupWire } from '../lib/agentActivity';import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';-import { onPageReactivated } from '../lib/pageActivity';+import { onPageReactivated, type PageReactivationListener } from '../lib/pageActivity';import type { ShowPagePayload } from '../lib/showPageLinks';import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';@@ -21,6 +21,13 @@ import {} from '../lib/showPageAccess';import {WorkbenchEventReconnectLoop,+ WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS,+ declaredWorkbenchHeartbeatInterval,+ isWorkbenchHeartbeatFresh,+ parseWorkbenchHeartbeatInterval,+ streamCoveredGap,+ workbenchEventStaleAfterMs,+ type WorkbenchControllerLegState,type WorkbenchEventConnectionState,} from '../lib/workbenchEventConnection';import type { DockDoc } from './dockDoc';@@ -1162,7 +1169,35 @@ export type WorkbenchEventEnvelope<T = unknown> = {};export type WorkbenchEventHandlers = {- onConnected?: (data: { sub_id: number; source?: 'browser' | 'controller' }) => void;+ /**+ * A stream is live and reaching this consumer, and any gap before now is+ * over. Every gap ends here, on either of the two legs a stream is carried+ * over: the browser socket breaking (an error, a page that came back to a+ * stream that could not prove it survived, a heartbeat that stopped arriving)+ * is recovered by reconnecting, and this fires once the new subscription+ * exists; the UI server's controller bridge dropping and coming back is+ * recovered in place, and this fires when it does. Nothing replays either+ * gap, so this is also the one place to re-read whatever this consumer keeps+ * live off the stream — including the window between its own first read and+ * this subscription.+ *+ * Consumers must not re-derive when a gap happened. Neither the reactivation+ * edge nor `onEventBridgeStatus` is that signal: a returning page whose stream+ * never broke has missed nothing, and a bridge report is a level rather than+ * an edge. Both verdicts are made in one place, and a consumer recomputing+ * them will drift from it.+ *+ * It carries no payload, deliberately. Which leg came back, and whether any+ * handshake stands behind this edge at all -- a page returning onto a stream+ * that could not prove it survived says to catch up now, rather than wait for+ * a replacement several backoff windows away -- are distinctions a catch-up+ * cannot branch on without silently skipping the gaps it does not recognise.+ * So there is nothing here to branch on. `onEventBridgeStatus` stays the level+ * a bridge indicator renders from, and is not a second catch-up trigger: every+ * bridge recovery arrives here too, so refetching from both would charge each+ * one twice.+ */+ onConnected?: () => void;onConnectionState?: (state: WorkbenchEventConnectionState) => void;onEventBridgeStatus?: (data: { connected: boolean }) => void;onAuthorizationChanged?: (data: {@@ -2610,10 +2645,36 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst eventSourceRef = useRef<EventSource | null>(null);const eventHandlersRef = useRef(new Set<WorkbenchEventHandlers>());const eventConnectionRef = useRef<{ sub_id: number; source?: 'browser' | 'controller' } | null>(null);- const eventBridgeConnectedRef = useRef(false);+ // The controller leg of this stream, which is the second thing that can break:+ // the browser socket stays open and heartbeating while the UI server loses+ // `/internal/events`, and `vibe/inbox_bridge.py` resumes the live feed without+ // replaying what the controller published in between. `unknown` is not a third+ // kind of outage -- it is a stream that has not heard from the leg yet, which+ // is what keeps its first "connected" report from reading as a recovery.+ const eventControllerLegRef = useRef<WorkbenchControllerLegState>('unknown');+ // When the active stream last proved it was alive, and the cadence the server+ // said it would prove it at. Null whenever there is no stream to speak for --+ // including a stream that has connected but not yet been heard from, because a+ // heartbeat is the only thing that proves continuity and nothing else may+ // stand in for one. A server too old to send them therefore never reads as+ // proven, which is the pre-heartbeat behavior this optimization replaces.+ const eventHeartbeatAtRef = useRef<number | null>(null);+ const eventHeartbeatIntervalRef = useRef(WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS);+ // When the deadline the current stream is being held to started running, or+ // null when this server never promised a cadence and so cannot be held to one.+ // Deliberately separate from the stamp above: a promise is what makes a+ // deadline enforceable, and only a heartbeat is proof the stream is carrying+ // events. Collapsing them either lets a handshake vouch for a stream or leaves+ // a stream that dies before its first heartbeat with no deadline at all.+ const eventHeartbeatClockAtRef = useRef<number | null>(null);+ // Fires when the next heartbeat is overdue. A heartbeat is a continuous clock,+ // so whoever trusts it has to keep watching it: sampling only at the moment a+ // page returns would leave a stream that dies one second later unquestioned+ // until the next return, which may never come while the tab stays open.+ const eventHeartbeatWatchdogRef = useRef<ReturnType<typeof setTimeout> | null>(null);const eventConnectionStateRef = useRef<WorkbenchEventConnectionState>('reconnecting');const eventReconnectLoopRef = useRef<WorkbenchEventReconnectLoop | null>(null);- const wakeWorkbenchEventsRef = useRef<() => void>(() => {});+ const resumeWorkbenchEventsRef = useRef<PageReactivationListener>(() => {});const syncSessionDraftsRef = useRef<() => void>(() => {});const stopWorkbenchEventsRef = useRef<() => void>(() => {});const sessionArchivedHandlersRef = useRef(new Set<(sessionId: string) => void>());@@ -2791,38 +2852,149 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children}};+ const clearWorkbenchHeartbeatWatchdog = () => {+ if (eventHeartbeatWatchdogRef.current === null) return;+ clearTimeout(eventHeartbeatWatchdogRef.current);+ eventHeartbeatWatchdogRef.current = null;+ };+const closeActiveWorkbenchEventSource = () => {const source = eventSourceRef.current;eventSourceRef.current = null;source?.close();eventConnectionRef.current = null;- eventBridgeConnectedRef.current = false;+ eventControllerLegRef.current = 'unknown';+ // The stamp and the cadence both speak for one socket only; a later stream+ // must earn its own, including the right to be watched on a timer.+ eventHeartbeatAtRef.current = null;+ eventHeartbeatClockAtRef.current = null;+ clearWorkbenchHeartbeatWatchdog();};/*** The stream's own handshake, or null while events cannot reach handlers. A- * controller-sourced stream also needs its bridge up: the browser leg being- * open says nothing about the controller leg behind it.+ * controller-sourced stream is itself the controller leg, so it is down when+ * that leg reports down.*/const workbenchEventHandshake = () => {const connection = eventConnectionRef.current;if (!connection) return null;- if (connection.source === 'controller' && !eventBridgeConnectedRef.current) return null;+ if (connection.source === 'controller' && eventControllerLegRef.current !== 'connected') return null;return connection;};/**- * Events are flowing end to end right now, so a reconnect would close no gap.+ * Reconnecting this socket would close no gap, because it is carrying+ * everything it can carry right now.*- * Transport liveness is the browser's to own: it errors the stream on network- * changes and on HTTP/2 ping timeouts, which is what `readyState` reports. The- * server's own keep-alive is an SSE comment plus it only fires after 15s of- * silence on the timeout branch, so it is invisible to EventSource and absent- * from a stream busy delivering events this context filters out -- a- * last-frame staleness check built on it would call healthy streams dead.+ * Scoped to this socket on purpose: a stream reaches the browser over two legs+ * that fail independently, and each one is judged by whoever can see it. This+ * is the browser leg. Reopening it cannot repair the controller leg behind the+ * UI server -- the replacement would inherit the same severed bridge -- so the+ * controller leg is not a term here; it announces its own recovery instead, in+ * the `workbench.events.bridge.status` listener below.+ *+ * That makes this the answer to one question only: whether recycling this+ * socket would close anything. It is not a verdict on the stream, and asking+ * it as one is how a controller-leg outage came to read as a gap-free resume.+ * `streamCoveredGap` is where every leg is accounted for.+ *+ * All three terms are needed for this leg. `readyState` is the browser's own+ * transport verdict, which it revises on network changes and HTTP/2 ping+ * timeouts. The handshake says a stream that is open can also reach handlers.+ * Neither survives suspension: a backgrounded tab can have its socket dropped+ * and be resumed with the connection still reported `OPEN` and no `error` ever+ * delivered, so only a recent heartbeat distinguishes a quiet stream from that+ * zombie.+ */+ const isWorkbenchBrowserLegLive = () =>+ eventSourceRef.current?.readyState === EventSource.OPEN &&+ workbenchEventHandshake() !== null &&+ isWorkbenchHeartbeatFresh(+ eventHeartbeatAtRef.current,+ eventHeartbeatIntervalRef.current,+ Date.now(),+ );++ /**+ * This stream is over: drop it, say so, and let the loop schedule the next+ * attempt. One owner for the transition, because a stream that dies silently+ * has to end up in exactly the same state as one that reports `error` --+ * consumers recover through the reconnect's `connected`, so a path that+ * skipped any of these steps would strand them.*/- const isWorkbenchEventStreamLive = () =>- eventSourceRef.current?.readyState === EventSource.OPEN && workbenchEventHandshake() !== null;+ const failWorkbenchEventStream = () => {+ closeActiveWorkbenchEventSource();+ setWorkbenchEventConnectionState('reconnecting');+ dispatchToWorkbenchHandlers((handlers) => handlers.onEventBridgeStatus?.({ connected: false }));+ getWorkbenchEventReconnectLoop().failed();+ };++ /**+ * Watch for the heartbeat the current stream owes us. A stream that stops+ * proving itself is dead whether or not the browser ever says so, and the+ * only way a consumer learns that is if someone is still looking.+ */+ const armWorkbenchHeartbeatWatchdog = () => {+ clearWorkbenchHeartbeatWatchdog();+ // Only a stream whose server promised a cadence owes a heartbeat. A deadline+ // is a claim about a cadence, so a server that never declared one cannot be+ // held to it: against an older server -- a rollback under a tab that stayed+ // open -- this would otherwise close a healthy stream every stale window+ // forever, charging every consumer a catch-up each round. A modern server+ // makes that promise in its handshake, which is what puts a stream that dies+ // before its first heartbeat on a deadline too.+ const clockAt = eventHeartbeatClockAtRef.current;+ if (clockAt === null) return;+ const staleAt = clockAt + workbenchEventStaleAfterMs(eventHeartbeatIntervalRef.current);+ eventHeartbeatWatchdogRef.current = setTimeout(() => {+ eventHeartbeatWatchdogRef.current = null;+ // A hidden page cannot hold a stream open anyway, and its timers are+ // throttled or frozen: the reactivation edge is the honest check there.+ if (document.visibilityState !== 'visible') return;+ // A heartbeat may have landed since this timer was set, in which case the+ // stream is proving itself and only the deadline moved.+ if (isWorkbenchBrowserLegLive()) {+ armWorkbenchHeartbeatWatchdog();+ return;+ }+ failWorkbenchEventStream();+ }, Math.max(0, staleAt - Date.now()));+ };++ /**+ * Start this stream's clock from its server's promise. Called from the+ * handshake, so a stream that opens and never sends a heartbeat still has a+ * deadline to miss -- the case a stamp-only clock cannot express, because+ * there is nothing to stamp.+ *+ * Sticky per stream: only a frame that carries a cadence is allowed to speak+ * for one, so a controller-relayed handshake (no cadence of its own) never+ * clears a clock the UI server's own handshake started.+ */+ const declareWorkbenchHeartbeatCadence = (intervalMs: number) => {+ eventHeartbeatIntervalRef.current = intervalMs;+ eventHeartbeatClockAtRef.current = Date.now();+ armWorkbenchHeartbeatWatchdog();+ };++ /**+ * Record proof of life and keep watching for the next one. Stamping and+ * watching are one action on purpose: a stamp nobody watches expires+ * unnoticed, and a watchdog armed off a stale stamp fires against the wrong+ * deadline.+ *+ * A heartbeat also restarts the clock, and does so even from a server that+ * never declared a cadence: whatever the deadline was measured from, the+ * newest proof is now the honest starting point.+ */+ const stampWorkbenchHeartbeat = (intervalMs?: number) => {+ const now = Date.now();+ eventHeartbeatAtRef.current = now;+ eventHeartbeatClockAtRef.current = now;+ if (intervalMs !== undefined) eventHeartbeatIntervalRef.current = intervalMs;+ armWorkbenchHeartbeatWatchdog();+ };function reconnectWorkbenchEventSource(): void {if (eventHandlersRef.current.size === 0) return;@@ -2835,7 +3007,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childreneventReconnectLoopRef.current = new WorkbenchEventReconnectLoop({reconnect: reconnectWorkbenchEventSource,isVisible: () => document.visibilityState === 'visible',- isStreamLive: isWorkbenchEventStreamLive,+ isBrowserLegLive: isWorkbenchBrowserLegLive,});}return eventReconnectLoopRef.current;@@ -2864,15 +3036,34 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrengetWorkbenchEventReconnectLoop().attemptStarted();source.addEventListener('connected', (e: MessageEvent) => {if (eventSourceRef.current !== source) return;+ // Deliberately no stamp here. This frame proves the stream is alive now,+ // which is not the question: the question is whether it will still be+ // proving that in a minute, and only a heartbeat answers it. Seeding from+ // the handshake would hand a stream up to one stale window of unearned+ // trust -- enough for a suspended tab to return, be believed, and skip the+ // catch-up for a gap it did have.+ //+ // What it may do is start the clock: the frame's `interval_ms` is the+ // server declaring the cadence it owes, which is a promise, not proof.+ // That is what puts a stream that opens and then goes silent on a+ // deadline, while a server too old to declare one is still never+ // watchdogged and still never believed without a heartbeat.try {- const parsed = JSON.parse(e.data) as { sub_id?: number; type?: string; data?: unknown };+ const parsed = JSON.parse(e.data) as {+ sub_id?: number;+ interval_ms?: unknown;+ 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,};+ const declaredIntervalMs = declaredWorkbenchHeartbeatInterval(parsed.interval_ms);+ if (declaredIntervalMs !== undefined) declareWorkbenchHeartbeatCadence(declaredIntervalMs);if (sourceKind === 'controller') {- eventBridgeConnectedRef.current = true;+ eventControllerLegRef.current = 'connected';setWorkbenchEventConnectionState('connected');dispatchToWorkbenchHandlers((handlers) => handlers.onEventBridgeStatus?.({ connected: true }));}@@ -2882,10 +3073,26 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children}if (eventConnectionRef.current) {getWorkbenchEventReconnectLoop().streamOpened();- const connected = eventConnectionRef.current;- dispatchToWorkbenchHandlers((handlers) => handlers.onConnected?.(connected));+ dispatchToWorkbenchHandlers((handlers) => handlers.onConnected?.());}});+ // The server's proof of life. It carries no news, so nothing is dispatched+ // to handlers -- the arrival itself is the whole payload, and the declared+ // cadence lets the staleness window be sized by the side that sets it.+ source.addEventListener('heartbeat', (e: MessageEvent) => {+ if (eventSourceRef.current !== source) return;+ let intervalMs: number | undefined;+ try {+ const payload = JSON.parse(e.data) as { interval_ms?: unknown };+ intervalMs = parseWorkbenchHeartbeatInterval(payload.interval_ms);+ } catch {+ // The frame arrived, which is what matters; keep the current cadence.+ }+ // The only place a stream is ever stamped, which is what lets a null stamp+ // mean "nothing has proved this stream yet" even on a stream already+ // running against a declared deadline.+ stampWorkbenchHeartbeat(intervalMs);+ });source.addEventListener('authorization.changed', (e: MessageEvent) => {const envelope = parseWorkbenchEnvelope<{project_ids?: string[];@@ -3039,26 +3246,33 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst envelope = parseWorkbenchEnvelope<{ connected: boolean }>(e.data);if (!envelope) return;getWorkbenchEventReconnectLoop().streamOpened();- eventBridgeConnectedRef.current = envelope.data.connected;+ const previousLeg = eventControllerLegRef.current;+ eventControllerLegRef.current = envelope.data.connected ? 'connected' : 'disconnected';setWorkbenchEventConnectionState(envelope.data.connected ? 'connected' : 'reconnecting');dispatchToWorkbenchHandlers((handlers) => {handlers.onAny?.(envelope);handlers.onEventBridgeStatus?.(envelope.data);});+ // A leg that was down and is now up is a gap that just ended. The browser+ // socket stayed open across it, so no reconnect will announce this one --+ // but the meaning is identical, so it arrives through the same signal, and+ // consumers need no second concept to handle it. Only from `disconnected`:+ // a new stream's opening report is the leg's state, not a recovery, and+ // treating it as one would charge every connect a duplicate catch-up.+ if (previousLeg === 'disconnected' && envelope.data.connected) {+ dispatchToWorkbenchHandlers((handlers) => handlers.onConnected?.());+ }});source.onerror = (err) => {if (eventSourceRef.current !== source) return;- closeActiveWorkbenchEventSource();+ failWorkbenchEventStream();// EventSource does not expose a failed response's status or JSON body.// Probe through apiFetch, then inspect the successful /api/session form;// both 401s and the 200 refresh payload enter the shared login recovery.void apiFetch('/api/session', { cache: 'no-store' }).then(recoverRemoteAuthFromSessionProbe).catch(() => undefined);- setWorkbenchEventConnectionState('reconnecting');- dispatchToWorkbenchHandlers((handlers) => handlers.onEventBridgeStatus?.({ connected: false }));dispatchToWorkbenchHandlers((handlers) => handlers.onError?.(err));- getWorkbenchEventReconnectLoop().failed();};}@@ -3075,28 +3289,80 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children};stopWorkbenchEventsRef.current = stopWorkbenchEventSource;- const wakeWorkbenchEvents = () => {+ /**+ * The page or the network came back. Catch the transport up; the stream then+ * tells consumers whether anything was missed, by reconnecting or not.+ *+ * One owner, deliberately. Every consumer used to subscribe to the raw+ * reactivation edge and refetch unconditionally, which is why returning to a+ * tab cost a burst of reads that a healthy stream had already delivered. Now+ * only a stream that cannot prove it survived the gap costs a catch-up, and+ * consumers hear about it through the same `connected` signal an ordinary+ * mid-session reconnect already used.+ *+ * `awaySince` is when the gap being recovered from opened, or null for one+ * nothing can date -- a network return, or a page back from an away period+ * the sampler never saw begin.+ */+ const wakeWorkbenchEvents: PageReactivationListener = (awaySince) => {if (eventHandlersRef.current.size === 0 || document.visibilityState !== 'visible') return;+ // Read before waking, because waking is what changes the answer.+ //+ // Two questions, asked separately because they have different subjects. The+ // transport one -- is this socket worth keeping -- is about the browser leg,+ // and is the reconnect loop's. This one is about the whole path across an+ // interval, so it is asked of every leg, by the one function that knows what+ // the legs are; the browser leg's own verdict goes in as a term rather than+ // standing in for the answer.+ const survivedTheGap = streamCoveredGap({+ browserLegLive: isWorkbenchBrowserLegLive(),+ lastHeartbeatAt: eventHeartbeatAtRef.current,+ controllerLeg: eventControllerLegRef.current,+ awaySince,+ intervalMs: eventHeartbeatIntervalRef.current,+ now: Date.now(),+ });// The indicator belongs to whoever opens a stream: openWorkbenchEventSource// marks it reconnecting on every attempt. Announcing it here instead made a// wake that keeps a live stream flash "reconnecting" over a healthy one.getWorkbenchEventReconnectLoop().wake();+ // Timers are not trustworthy across a hidden period -- throttled, frozen,+ // or fired while hidden and declined -- so re-establish the watch on a+ // stream that was kept rather than reasoning about which of those happened.+ // Idempotent: it re-arms off the surviving clock, and declines for a stream+ // that was recycled or never declared a cadence.+ armWorkbenchHeartbeatWatchdog();+ // This edge owns its own catch-up. Deferring it to the replacement stream's+ // handshake would make recovery depend on the thing being recovered: a+ // server that is down, an offline network, or a backoff wait leaves the+ // reconnect pending for as long as it takes, and until then a returning page+ // shows whatever it had before it was hidden with nothing on the way. Paying+ // it here is what the unconditional refetch did before this change, so a+ // reactivation onto a broken stream costs no more than it used to; the+ // replacement's later `connected` is a second catch-up in exactly the case+ // that already paid for two.+ if (!survivedTheGap) {+ dispatchToWorkbenchHandlers((handlers) => handlers.onConnected?.());+ }};- wakeWorkbenchEventsRef.current = wakeWorkbenchEvents;+ resumeWorkbenchEventsRef.current = wakeWorkbenchEvents;useEffect(() => {- const wakeIfVisible = () => {+ const wakeIfVisible: PageReactivationListener = (awaySince) => {if (document.visibilityState !== 'visible') return;- wakeWorkbenchEventsRef.current();+ resumeWorkbenchEventsRef.current(awaySince);syncSessionDraftsRef.current();};- // Regaining the network is its own gap, independent of the page coming back.+ // Regaining the network is its own gap, independent of the page coming back,+ // and an undated one: nothing here watched the connection drop, so no+ // heartbeat can be placed inside it.+ const wakeFromNetwork = () => wakeIfVisible(null);const stopReactivation = onPageReactivated(wakeIfVisible);- window.addEventListener('online', wakeIfVisible);+ window.addEventListener('online', wakeFromNetwork);if (document.visibilityState === 'visible') syncSessionDraftsRef.current();return () => {stopReactivation();- window.removeEventListener('online', wakeIfVisible);+ window.removeEventListener('online', wakeFromNetwork);stopWorkbenchEventsRef.current();};}, []);@@ -4018,13 +4284,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children});if (workbenchEventHandshake()) {queueMicrotask(() => {- const connected = workbenchEventHandshake();- if (eventHandlersRef.current.has(handlers) && connected) {- handlers.onConnected?.(connected);+ if (eventHandlersRef.current.has(handlers) && workbenchEventHandshake()) {+ handlers.onConnected?.();}});}- if (eventBridgeConnectedRef.current) {+ if (eventControllerLegRef.current === 'connected') {queueMicrotask(() => {if (eventHandlersRef.current.has(handlers)) {handlers.onEventBridgeStatus?.({ connected: true });diff --git a/ui/src/context/WorkbenchInboxProvider.tsx b/ui/src/context/WorkbenchInboxProvider.tsxindex 4ea7d0434..9d9471427 100644--- a/ui/src/context/WorkbenchInboxProvider.tsx+++ b/ui/src/context/WorkbenchInboxProvider.tsx@@ -7,7 +7,6 @@ import { WorkbenchInboxContext, type InboxState } from './WorkbenchInboxContext'import { sessionActivityInboxAction } from '../lib/inboxActivity';import { syncFaviconBadge } from '../lib/faviconBadge';import { useConsumerActivation } from '../lib/useConsumerActivation';-import { onPageReactivated } from '../lib/pageActivity';import {createWorkbenchSessionReadOwnership,type WorkbenchSessionReadStamp,@@ -867,6 +866,18 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>return next;});},+ // A live stream is reaching us again, so anything it missed has to come+ // from durable storage. This is the recovery for every gap, including the+ // OS suspending us: a backgrounded mobile PWA has its page frozen and its+ // SSE socket dropped, the broker never replays the gap, and iOS can leave+ // EventSource in a zombie OPEN state without onerror. ApiContext recycles+ // a stream that cannot prove it survived, so that case arrives here too —+ // while a returning page whose stream did prove it fires nothing, having+ // already delivered the events.+ onConnected: () => {+ if (isFeedActive()) void reconcile();+ else void refreshUnread();+ },onError: (err) => {// ApiContext owns the explicit reconnect loop. Keep this a log, not a// crash, so the workbench stays usable during the HTTP fallback.@@ -883,29 +894,11 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>isFeedActive,oweWholeUnread,readFeedForActiveConsumer,+ reconcile,reconcileSession,+ refreshUnread,]);- // Recover after the OS suspended us. A backgrounded mobile PWA has its page- // frozen and its SSE socket dropped, and the broker never replays the gap;- // iOS can leave EventSource in a zombie OPEN state without onerror. ApiContext- // reopens the shared stream when the page comes back and when the network- // returns; independently reconcile the durable feed here so missed events- // never gate data freshness.- useEffect(() => {- const resync = () => {- if (document.visibilityState !== 'visible') return;- if (isFeedActive()) void reconcile();- else void refreshUnread();- };- const stopReactivation = onPageReactivated(resync);- window.addEventListener('online', resync);- return () => {- stopReactivation();- window.removeEventListener('online', resync);- };- }, [isFeedActive, reconcile, refreshUnread]);-const totalUnread = useMemo(() => Object.values(unreadBySession).reduce((sum, n) => sum + (n || 0), 0),[unreadBySession],diff --git a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx b/ui/src/context/WorkbenchSessionReadOrdering.test.tsxindex d8a57cf9f..e2fdca8a5 100644--- a/ui/src/context/WorkbenchSessionReadOrdering.test.tsx+++ b/ui/src/context/WorkbenchSessionReadOrdering.test.tsx@@ -94,9 +94,45 @@ type FakeApi = {const apiRef = { current: null as FakeApi | null };+type StreamConnectHandler = NonNullable<WorkbenchEventHandlers['onConnected']>;++const streamConnectHandlers = new Set<StreamConnectHandler>();+const wrappedApis = new WeakMap<FakeApi, FakeApi>();++/**+ * Supply the half of the resume edge the real ApiContext owns. Consumers no+ * longer watch page activity themselves: ApiContext decides whether the shared+ * event stream can vouch for the gap the page spent away, recycles the ones that+ * cannot, and announces the replacement through `onConnected`. These fakes stand+ * in for that context, so the signal has to come from here rather than from every+ * fake in the file.+ */+function withStreamConnect(api: FakeApi | null): FakeApi | null {+ if (!api) return null;+ // Consumers key their subscription effect on the api object, so a fresh+ // wrapper per render would resubscribe forever.+ const cached = wrappedApis.get(api);+ if (cached) return cached;+ const wrapped: FakeApi = {+ ...api,+ connectWorkbenchEvents: (handlers) => {+ const disconnect = api.connectWorkbenchEvents(handlers);+ const onConnected = handlers.onConnected;+ if (!onConnected) return disconnect;+ streamConnectHandlers.add(onConnected);+ return () => {+ streamConnectHandlers.delete(onConnected);+ disconnect();+ };+ },+ };+ wrappedApis.set(api, wrapped);+ return wrapped;+}+vi.mock('./ApiContext', async () => {const actual = await vi.importActual<typeof import('./ApiContext')>('./ApiContext');- return { ...actual, useApi: () => apiRef.current };+ return { ...actual, useApi: () => withStreamConnect(apiRef.current) };});// The provider reports its one never-sent refusal through the toast surface, which@@ -111,26 +147,19 @@ function settle() {});}-// The inbox reconciles when the page comes back, which is an edge rather than a-// level: the shared page-activity sampler ignores a `focus` event on a page that-// never left. Simulate a real gap by hiding the document and revealing it again.+// The inbox reconciles when a stream starts reaching it. That covers coming back+// to a page whose stream could not prove it stayed connected -- ApiContext+// recycles it, and the replacement's handshake is the signal here. It is not the+// raw visibility edge, which a page whose stream never dropped also sees.function simulatePageResume() {- const setVisibility = (state: DocumentVisibilityState) => {- Object.defineProperty(document, 'visibilityState', { value: state, configurable: true });- document.dispatchEvent(new Event('visibilitychange'));- };- setVisibility('hidden');- setVisibility('visible');- // Drop the shadowing property so the rest of the suite reads jsdom's own getter.- Reflect.deleteProperty(document, 'visibilityState');+ for (const handler of [...streamConnectHandlers]) handler({ sub_id: 1, source: 'browser' });}describe('Workbench session read ownership', () => {beforeEach(() => {apiRef.current = null;// jsdom never reports window focus, so no reading would ever count as "the- // page is presented". Model a focused window and let visibility carry the- // transitions `simulatePageResume` needs.+ // page is presented" and nothing would ever be marked read.document.hasFocus = () => true;});@@ -169,7 +198,7 @@ describe('Workbench session read ownership', () => {await settle();act(() => {- handlers?.onConnected?.({ sub_id: 1, source: 'browser' });+ handlers?.onConnected?.();});await settle();act(() => {@@ -264,7 +293,7 @@ describe('Workbench session read ownership', () => {);await settle();act(() => {- handlers?.onConnected?.({ sub_id: 2, source: 'browser' });+ handlers?.onConnected?.();});await settle();expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(1);@@ -373,7 +402,7 @@ describe('Workbench session read ownership', () => {);await settle();act(() => {- handlers?.onConnected?.({ sub_id: 3, source: 'browser' });+ handlers?.onConnected?.();});await settle();expect(getWorkbenchProjectsBootstrap).toHaveBeenCalledTimes(2);@@ -528,7 +557,7 @@ describe('Workbench session read ownership', () => {);await settle();act(() => {- handlers?.onConnected?.({ sub_id: 2, source: 'browser' });+ handlers?.onConnected?.();});await settle();act(() => {@@ -737,7 +766,7 @@ describe('Workbench session read ownership', () => {);await settle();act(() => {- handlers?.onConnected?.({ sub_id: 3, source: 'browser' });+ handlers?.onConnected?.();});await settle();act(() => {diff --git a/ui/src/context/shellBootstrapDemand.test.tsx b/ui/src/context/shellBootstrapDemand.test.tsxindex 411065833..e2bbe073c 100644--- a/ui/src/context/shellBootstrapDemand.test.tsx+++ b/ui/src/context/shellBootstrapDemand.test.tsx@@ -96,9 +96,45 @@ type FakeApi = {const apiRef = { current: null as FakeApi | null };+type StreamConnectHandler = NonNullable<WorkbenchEventHandlers['onConnected']>;++const streamConnectHandlers = new Set<StreamConnectHandler>();+const wrappedApis = new WeakMap<FakeApi, FakeApi>();++/**+ * Supply the half of the resume edge the real ApiContext owns. Consumers no+ * longer watch page activity themselves: ApiContext decides whether the shared+ * event stream can vouch for the gap the page spent away, recycles the ones that+ * cannot, and announces the replacement through `onConnected`. These fakes stand+ * in for that context, so the signal has to come from here rather than from every+ * fake in the file.+ */+function withStreamConnect(api: FakeApi | null): FakeApi | null {+ if (!api) return null;+ // Consumers key their subscription effect on the api object, so a fresh+ // wrapper per render would resubscribe forever.+ const cached = wrappedApis.get(api);+ if (cached) return cached;+ const wrapped: FakeApi = {+ ...api,+ connectWorkbenchEvents: (handlers) => {+ const disconnect = api.connectWorkbenchEvents(handlers);+ const onConnected = handlers.onConnected;+ if (!onConnected) return disconnect;+ streamConnectHandlers.add(onConnected);+ return () => {+ streamConnectHandlers.delete(onConnected);+ disconnect();+ };+ },+ };+ wrappedApis.set(api, wrapped);+ return wrapped;+}+vi.mock('./ApiContext', async () => {const actual = await vi.importActual<typeof import('./ApiContext')>('./ApiContext');- return { ...actual, useApi: () => apiRef.current };+ return { ...actual, useApi: () => withStreamConnect(apiRef.current) };});// The provider reports its one never-sent refusal through the toast surface, which@@ -163,17 +199,14 @@ const InboxProbe = ({return null;};-// A resume is an EDGE, and ``onPageReactivated`` deliberately refuses to read a-// bare ``focus`` as one: focus moving between elements of a page that never left-// is the common case, and treating it as a return is what made the old listener-// over-fire. So drive the transition the sampler actually reads — system focus-// lost, then regained — rather than the event that used to stand in for it.+// A resume only concerns the feed when the shared event stream cannot vouch for+// the gap the page spent away. That verdict belongs to ApiContext, which recycles+// such a stream and announces the replacement -- so drive that signal rather than+// the raw activity edge, which a page whose stream never dropped also sees and+// which no longer reaches these consumers.const resumePage = async () => {await act(async () => {- document.hasFocus = () => false;- window.dispatchEvent(new Event('blur'));- document.hasFocus = () => true;- window.dispatchEvent(new Event('focus'));+ for (const handler of [...streamConnectHandlers]) handler({ sub_id: 1, source: 'browser' });});};@@ -185,9 +218,6 @@ describe('Demand-driven shell bootstrap', () => {afterEach(() => {cleanup();apiRef.current = null;- // Own property, so the prototype's real implementation comes back for tests- // that never resume.- Reflect.deleteProperty(document, 'hasFocus');});describe('projects tree', () => {@@ -951,7 +981,7 @@ describe('Demand-driven shell bootstrap', () => {const before = reads();await act(async () => {- handlers?.onConnected?.({ sub_id: 1 });+ handlers?.onConnected?.();handlers?.onSessionActivity?.({session_id: session.id,scope_id: session.scope_id,@@ -1393,7 +1423,7 @@ describe('Demand-driven shell bootstrap', () => {expect(bootstrap).toHaveBeenCalledTimes(1);await act(async () => {- handlers?.onConnected?.({ sub_id: 1 });+ handlers?.onConnected?.();});expect(bootstrap).toHaveBeenCalledTimes(2);expect(bootstrap.mock.calls[1][0]).toMatchObject({ projectIds: [project.id] });@@ -1726,7 +1756,7 @@ describe('Demand-driven shell bootstrap', () => {// reach the minimum and does not get to clear it either: the reconnect// still asks for eleven. Paying part of a debt is not paying it.await act(async () => {- handlers?.onConnected?.({ sub_id: 1 });+ handlers?.onConnected?.();});await settle();expect(bootstrap).toHaveBeenCalledTimes(3);@@ -1737,7 +1767,7 @@ describe('Demand-driven shell bootstrap', () => {// that produces it — otherwise a restore later undone would widen every// rebuild of this project forever.await act(async () => {- handlers?.onConnected?.({ sub_id: 1 });+ handlers?.onConnected?.();});await settle();expect(bootstrap).toHaveBeenCalledTimes(4);@@ -1917,7 +1947,7 @@ describe('Demand-driven shell bootstrap', () => {// The debt is untouched, so the next trigger asks for eleven rows: the// failure declined to pay it, exactly as a refusal does.await act(async () => {- handlers?.onConnected?.({ sub_id: 1 });+ handlers?.onConnected?.();});await settle();expect(bootstrap).toHaveBeenCalledTimes(2);diff --git a/ui/src/context/workbenchEventOwnership.test.ts b/ui/src/context/workbenchEventOwnership.test.tsnew file mode 100644index 000000000..2540855e4--- /dev/null+++ b/ui/src/context/workbenchEventOwnership.test.ts@@ -0,0 +1,112 @@+import { readFileSync, readdirSync } from 'node:fs';+import { join } from 'node:path';+import ts from 'typescript';+import { describe, expect, it } from 'vitest';++/**+ * The catch-up edge has exactly one owner, stated as a property of every+ * subscription in the tree rather than as a list of the consumers that got it+ * wrong.+ *+ * Three rounds of review found the same defect at four call sites: a consumer+ * decided for itself whether a signal applied to it. Twice it was keyed to call+ * order, once to the signal's payload -- which round 8 deleted, so that form is+ * now untypeable. What a type cannot express is the remaining form: reading the+ * *level* (`onEventBridgeStatus`) as if it were the edge. A consumer that+ * refetches there pays twice for a controller bounce, because that recovery also+ * arrives as `onConnected`; a consumer that only listens there never catches up+ * on a resume, because a returning page has no bridge transition to report.+ *+ * So the level may move state and nothing else, and anything reading it must+ * also subscribe to the edge. A fifth consumer written the old way fails here+ * instead of costing a review round.+ */++const SRC = join(__dirname, '..');++const sourceFiles = () =>+ readdirSync(SRC, { recursive: true, encoding: 'utf8' })+ .filter((file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file))+ .map((file) => join(SRC, file));++const rightmostName = (expression: ts.Expression): string | undefined => {+ if (ts.isIdentifier(expression)) return expression.text;+ if (ts.isPropertyAccessExpression(expression)) return expression.name.text;+ return undefined;+};++type Subscription = { file: string; handlers: Map<string, ts.Expression> };++const subscriptions = (): Subscription[] => {+ const found: Subscription[] = [];+ for (const path of sourceFiles()) {+ const text = readFileSync(path, 'utf8');+ if (!text.includes('connectWorkbenchEvents')) continue;+ const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);+ const visit = (node: ts.Node) => {+ if (+ ts.isCallExpression(node) &&+ rightmostName(node.expression) === 'connectWorkbenchEvents' &&+ node.arguments.length > 0 &&+ ts.isObjectLiteralExpression(node.arguments[0])+ ) {+ const handlers = new Map<string, ts.Expression>();+ for (const property of node.arguments[0].properties) {+ if (!ts.isPropertyAssignment(property) || !property.name) continue;+ const name = ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)+ ? property.name.text+ : undefined;+ if (name) handlers.set(name, property.initializer);+ }+ found.push({ file: path.slice(SRC.length + 1), handlers });+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ }+ return found;+};++describe('workbench event ownership', () => {+ const all = subscriptions();++ // Vacuity guard: the scan is only a property if it is actually reaching the+ // consumers. Bounds rather than exact counts, so adding a consumer does not+ // edit this test -- but deleting the whole call, renaming the method, or+ // breaking the parse does.+ it('reaches every subscription in the tree', () => {+ expect(all.length).toBeGreaterThanOrEqual(12);+ expect(all.filter(({ handlers }) => handlers.has('onConnected')).length)+ .toBeGreaterThanOrEqual(5);+ expect(all.filter(({ handlers }) => handlers.has('onEventBridgeStatus')).length)+ .toBeGreaterThanOrEqual(4);+ });++ it('never reads the bridge level without the catch-up edge', () => {+ const missing = all+ .filter(({ handlers }) => handlers.has('onEventBridgeStatus') && !handlers.has('onConnected'))+ .map(({ file }) => file);+ expect(missing, 'a bridge-status subscriber must also catch up on onConnected').toEqual([]);+ });++ it('calls nothing but state setters from the bridge level', () => {+ const offenders: string[] = [];+ for (const { file, handlers } of all) {+ const handler = handlers.get('onEventBridgeStatus');+ if (!handler) continue;+ const visit = (node: ts.Node) => {+ if (ts.isCallExpression(node)) {+ const called = rightmostName(node.expression) ?? '<expression>';+ if (!/^set[A-Z]/.test(called)) offenders.push(`${file}: ${called}()`);+ }+ ts.forEachChild(node, visit);+ };+ visit(handler);+ }+ // A read here is the defect: the level is not an edge, so it either pays+ // twice for a bounce that already dispatched `onConnected`, or stands in for+ // an edge it cannot see. Whitelisting setters rather than blacklisting the+ // reads keeps a newly named read from slipping through.+ expect(offenders, 'the bridge level moves state; the catch-up belongs on onConnected').toEqual([]);+ });+});diff --git a/ui/src/lib/pageActivity.test.ts b/ui/src/lib/pageActivity.test.tsindex ab30ad0f6..537a0d85e 100644--- a/ui/src/lib/pageActivity.test.ts+++ b/ui/src/lib/pageActivity.test.ts@@ -3,10 +3,12 @@import { afterEach, describe, expect, it, vi } from 'vitest';import {+ AWAY_REASONS,canMarkConversationRead,createPageActivityTracker,isPageActive,onPageReactivated,+ type AwayReason,type PageActivitySnapshot,} from './pageActivity';@@ -132,10 +134,46 @@ describe('onPageReactivated', () => {for (const root of shadowed) Reflect.deleteProperty(root, 'activeElement');shadowed.length = 0;Reflect.deleteProperty(document, 'hasFocus');+ Reflect.deleteProperty(document, 'visibilityState');for (const element of created) element.remove();created.length = 0;});+ it('dates the gap from when the page left, once per away period', () => {+ vi.useFakeTimers();+ try {+ document.hasFocus = () => true;+ const reactivated = listen();++ const leftAt = Date.now();+ document.hasFocus = () => false;+ window.dispatchEvent(new Event('blur'));+ // Time passing while away must not move the stamp: a listener revalidating+ // across the gap needs when it opened, and "now" is its other end.+ vi.advanceTimersByTime(30_000);+ document.hasFocus = () => true;+ window.dispatchEvent(new Event('focus'));++ expect(reactivated).toHaveBeenCalledTimes(1);+ expect(reactivated).toHaveBeenLastCalledWith(leftAt);++ // The next gap is its own interval, not a continuation of the last one.+ vi.advanceTimersByTime(5_000);+ const leftAgainAt = Date.now();+ document.hasFocus = () => false;+ window.dispatchEvent(new Event('blur'));+ vi.advanceTimersByTime(1_000);+ document.hasFocus = () => true;+ window.dispatchEvent(new Event('focus'));++ expect(reactivated).toHaveBeenCalledTimes(2);+ expect(reactivated).toHaveBeenLastCalledWith(leftAgainAt);+ expect(leftAgainAt).toBeGreaterThan(leftAt);+ } finally {+ vi.useRealTimers();+ }+ });+it('reports a system focus loss that arrived at the frame holding focus', () => {document.hasFocus = () => true;@@ -275,6 +313,83 @@ describe('onPageReactivated', () => {expect(reactivated).not.toHaveBeenCalled();});+ // One entry per member of `AWAY_REASONS`, so a reason added to the module has+ // to be answered here rather than inheriting whatever the untested case does.+ type AwayTransition = { reason: AwayReason; enter: () => void; leave: () => void };++ const setVisibility = (visibilityState: DocumentVisibilityState) => {+ Object.defineProperty(document, 'visibilityState', {+ value: visibilityState,+ configurable: true,+ });+ document.dispatchEvent(new Event('visibilitychange'));+ };++ const awayTransitions = (): AwayTransition[] => [+ {+ reason: 'hidden',+ enter: () => setVisibility('hidden'),+ leave: () => setVisibility('visible'),+ },+ {+ reason: 'blurred',+ enter: () => {+ document.hasFocus = () => false;+ window.dispatchEvent(new Event('blur'));+ },+ leave: () => {+ document.hasFocus = () => true;+ window.dispatchEvent(new Event('focus'));+ },+ },+ {+ reason: 'out-of-sight',+ enter: () => void focusCrossOriginFrame(),+ leave: () => {+ focusParent();+ window.dispatchEvent(new Event('focus'));+ },+ },+ ];++ it('dates the gap from the last step further away, not the first', () => {+ const transitions = awayTransitions();+ // The property is over every way of being away, so the list must be the+ // whole partition -- an unanswered reason would silently drop out of it.+ expect(transitions.map((transition) => transition.reason).sort()).toEqual(+ [...AWAY_REASONS].sort(),+ );++ vi.useFakeTimers();+ try {+ for (const first of transitions) {+ for (const second of transitions) {+ if (first === second) continue;+ const step = `${first.reason} then ${second.reason}`;+ document.hasFocus = () => true;+ const reactivated = listen();++ // Out of sight is not out of action: a page whose focus moved into an+ // embedded frame keeps executing, so whatever it received then cannot+ // vouch for the interval that opens when it is hidden or blurred next.+ first.enter();+ vi.advanceTimersByTime(20_000);+ expect(reactivated, step).not.toHaveBeenCalled();+ const steppedAt = Date.now();+ second.enter();+ vi.advanceTimersByTime(20_000);+ second.leave();+ first.leave();++ expect(reactivated, step).toHaveBeenCalled();+ expect(reactivated.mock.calls[0], step).toEqual([steppedAt]);+ }+ }+ } finally {+ vi.useRealTimers();+ }+ });+it('treats coming back from a cross-origin frame as coming back', () => {document.hasFocus = () => true;diff --git a/ui/src/lib/pageActivity.ts b/ui/src/lib/pageActivity.tsindex 2053c5741..6db6110db 100644--- a/ui/src/lib/pageActivity.ts+++ b/ui/src/lib/pageActivity.ts@@ -35,12 +35,16 @@ export function canMarkConversationRead({);}-export function readPageActivity(): boolean {- if (typeof document === 'undefined') return false;- return isPageActive({+export function readPageActivitySnapshot(): PageActivitySnapshot {+ if (typeof document === 'undefined') return { visibilityState: 'hidden', hasFocus: false };+ return {visibilityState: document.visibilityState,hasFocus: typeof document.hasFocus !== 'function' || document.hasFocus(),- });+ };+}++export function readPageActivity(): boolean {+ return isPageActive(readPageActivitySnapshot());}export type PageActivityTracker = {@@ -78,22 +82,64 @@ export function createPageActivityTracker(initialActive: boolean): PageActivityT// "the page is active" and "the page just came back" — rather than each binding// its own focus/visibility listeners and re-deriving them.+/**+ * Told when the page came back, and when it left. A gap has two ends, and a+ * listener revalidating across it needs both: evidence that it was away is only+ * evidence about the gap if it is dated inside it.+ *+ * `null` means the page is back from an away period this sampler never saw+ * begin, which nothing can be dated against. Listeners must read it as the+ * gap being unaccounted for rather than absent.+ */+export type PageReactivationListener = (awaySince: number | null) => void;+const activeListeners = new Set<() => void>();-const reactivationListeners = new Set<() => void>();+const reactivationListeners = new Set<PageReactivationListener>();++/**+ * The ways a page stops being presented, each a different thing the browser+ * stops doing for it. Declared as a list rather than a bare union so a reason+ * added here has to be answered in the tests that walk it.+ */+export const AWAY_REASONS = ['hidden', 'blurred', 'out-of-sight'] as const;++export type AwayReason = (typeof AWAY_REASONS)[number];++const readAwayReasons = (+ snapshot: PageActivitySnapshot,+ outOfSight: boolean,+): Set<AwayReason> => {+ const reasons = new Set<AwayReason>();+ if (snapshot.visibilityState !== 'visible') reasons.add('hidden');+ if (!snapshot.hasFocus) reasons.add('blurred');+ if (outOfSight) reasons.add('out-of-sight');+ return reasons;+};let tracker: PageActivityTracker | null = null;let detach: (() => void) | null = null;+// When the current away period began, or null while the page is here. Only this+// sampler watches the page leave, so only it can date that end of the gap.+let awaySince: number | null = null;+// Why it was away as of the last reading, which is what makes a later reading a+// step further away rather than more of the same.+let awayReasons: Set<AwayReason> = new Set();// Copy first: a listener may unsubscribe while the set is being walked.const notify = (listeners: Set<() => void>) => {for (const listener of [...listeners]) listener();};+const notifyReactivated = (gapStart: number | null) => {+ for (const listener of [...reactivationListeners]) listener(gapStart);+};+const sample = () => {if (!tracker) return;const wasActive = tracker.isActive();const wasOutOfSight = focusOutOfSight;- const active = readPageActivity();+ const snapshot = readPageActivitySnapshot();+ const active = isPageActive(snapshot);// Re-walk before deciding: what makes an unobservable gap a return is// regaining sight of the page, not merely having lost it. An out-of-sight// frame reloading itself samples too, and it never left.@@ -102,8 +148,30 @@ const sample = () => {// Either edge is a return: one this document watched happen, or one it could// only have missed while focus sat where it cannot look.const reactivated = tracker.observe(active) || (active && regainedSight);+ // Date the away period from the *latest* step further away, not the first sign+ // of it. Each new reason is the browser taking something else away, so it+ // opens an interval of its own that earlier evidence cannot speak for: a page+ // whose focus sits in an embedded frame is out of sight yet still executing,+ // and the heartbeats it keeps receiving there say nothing about the suspension+ // that begins when its tab is hidden afterwards. A reason merely going away+ // leaves the stamp alone, because evidence dated after it was collected in a+ // state at least this degraded. The stamp is when this sampler *saw* the step,+ // which is no earlier than the step itself -- a listener attaching mid-gap can+ // only date it from the reading it took.+ const reasons = readAwayReasons(snapshot, focusOutOfSight);+ const wentFurtherAway = [...reasons].some((reason) => !awayReasons.has(reason));+ awayReasons = reasons;if (tracker.isActive() !== wasActive) notify(activeListeners);- if (reactivated) notify(reactivationListeners);+ if (reactivated) {+ const gapStart = awaySince;+ // A return ends the interval, and starts a new one only if this very reading+ // still shows a reason -- coming back to the page while focus stays inside+ // an embedded frame is proof of receiving now, and out of sight from now on.+ awaySince = reasons.size > 0 ? Date.now() : null;+ notifyReactivated(gapStart);+ } else if (wentFurtherAway) {+ awaySince = Date.now();+ }};// Focus events go to the window that holds focus, and Chrome hands focus to an@@ -247,6 +315,10 @@ const attach = () => {releaseFocusChain();tracker = null;detach = null;+ // Nobody is watching the page leave any more, so the next attach cannot+ // date a gap from before it started looking.+ awaySince = null;+ awayReasons = new Set();};// Fold the current reading in once, so a page that mounts while an embedded// frame already holds focus starts watching that chain without waiting for an@@ -254,7 +326,7 @@ const attach = () => {sample();};-const subscribe = (listeners: Set<() => void>, listener: () => void): (() => void) => {+const subscribe = <Listener>(listeners: Set<Listener>, listener: Listener): (() => void) => {if (typeof document === 'undefined' || typeof window === 'undefined') return () => {};listeners.add(listener);if (!detach) attach();@@ -275,8 +347,12 @@ const subscribePageActive = (listener: () => void): (() => void) =>* revalidating data that may have gone stale during the gap; a bare `focus`* listener over-fires because it cannot tell a return from a focus move that* never left the page.+ *+ * The listener is handed when the page left, for revalidation that can be+ * skipped on evidence: see `PageReactivationListener`. A listener that+ * revalidates unconditionally can keep ignoring it.*/-export function onPageReactivated(listener: () => void): () => void {+export function onPageReactivated(listener: PageReactivationListener): () => void {return subscribe(reactivationListeners, listener);}diff --git a/ui/src/lib/showPagesStore.test.ts b/ui/src/lib/showPagesStore.test.tsindex 43705dc07..837ca97f2 100644--- a/ui/src/lib/showPagesStore.test.ts+++ b/ui/src/lib/showPagesStore.test.ts@@ -94,13 +94,12 @@ describe('ShowPagesInventoryStore', () => {const close = store.activate();await store.reload();- handlers?.onConnected?.({ sub_id: 1, source: 'browser' });expect(store.getSnapshot().pages).toHaveLength(1);close();// Still subscribed, but invalidation-only: a reconnect or a session event// with nobody reading must not put a request on a route that renders none.- handlers?.onConnected?.({ sub_id: 2, source: 'browser' });+ handlers?.onConnected?.();handlers?.onSessionActivity?.({session_id: 'session-1',scope_id: null,@@ -229,7 +228,15 @@ describe('ShowPagesInventoryStore', () => {expect(connectWorkbenchEvents).toHaveBeenCalledTimes(1);});- it('does not refetch when the initial events connection arrives after the activation read', async () => {+ // The property rather than a list of cases: with a consumer reading, every+ // `onConnected` is followed by a read issued after it. No call is exempt, and+ // none can be singled out either -- the edge says only that a gap needs+ // closing, so there is nothing on it to tell a first subscription from one+ // replacing a stream that could not prove it survived. What makes a read+ // authoritative for a subscription is having started after that subscription+ // announced itself, and activate()'s read is issued before. Any run of edges+ // therefore costs its own length in reads.+ it('reads again after every catch-up edge', async () => {let handlers: EventHandlers | undefined;const getShowPages = vi.fn().mockResolvedValue({ pages: [page()] });const store = new ShowPagesInventoryStore({@@ -242,16 +249,42 @@ describe('ShowPagesInventoryStore', () => {const release = store.activate();await store.reload();- handlers?.onConnected?.({ sub_id: 1, source: 'browser' });- await Promise.resolve();expect(getShowPages).toHaveBeenCalledTimes(1);- handlers?.onConnected?.({ sub_id: 2, source: 'browser' });- await store.reload();- expect(getShowPages).toHaveBeenCalledTimes(2);+ for (let expected = 2; expected <= 4; expected += 1) {+ handlers?.onConnected?.();+ // Asserted before any await: the edge issues the read synchronously, so+ // a test that awaited `reload()` first would manufacture the very request+ // it is checking for and pass against a handler that skipped the edge.+ expect(getShowPages).toHaveBeenCalledTimes(expected);+ await store.reload();+ }release();});+ it('reads nothing for an established subscription with nobody reading', async () => {+ let handlers: EventHandlers | undefined;+ const getShowPages = vi.fn().mockResolvedValue({ pages: [page()] });+ const store = new ShowPagesInventoryStore({+ getShowPages,+ connectWorkbenchEvents: vi.fn((next) => {+ handlers = next;+ return vi.fn();+ }),+ });++ store.activate()();+ await store.reload();+ expect(getShowPages).toHaveBeenCalledTimes(1);++ // Revalidation waits for demand: the subscription stays open to hear+ // invalidation, and reactivation re-reads anyway.+ handlers?.onConnected?.();+ handlers?.onConnected?.();+ await Promise.resolve();+ expect(getShowPages).toHaveBeenCalledTimes(1);+ });+it('withdraws a retained page immediately when access is lost', async () => {const store = new ShowPagesInventoryStore({getShowPages: vi.fn().mockResolvedValue({ pages: [page()] }),diff --git a/ui/src/lib/showPagesStore.ts b/ui/src/lib/showPagesStore.tsindex 538920370..13602ae24 100644--- a/ui/src/lib/showPagesStore.ts+++ b/ui/src/lib/showPagesStore.ts@@ -258,15 +258,21 @@ export class ShowPagesInventoryStore {private connectEvents(): void {if (this.disconnectEvents) return;- let connected = false;this.disconnectEvents = this.api.connectWorkbenchEvents({+ // Re-read after EVERY established subscription -- no exempt call, which is+ // the rule ``WindowLayer``, ``WorkbenchProjectsProvider`` and+ // ``WorkbenchInboxProvider`` already follow. The exemption this store used+ // to carry was that activate() had just read, so the first handshake was+ // covered. It is not: that read is issued in the same tick the EventSource+ // is created, so the server can answer it before it registers the+ // subscription, and a mutation in between reaches neither. What makes a+ // read authoritative for a subscription is having been issued AFTER that+ // subscription announced itself, and no count of calls can establish it.+ //+ // The cost is one extra inventory read per subscription established, not+ // per handshake: ``invalidateAndReload`` fences the read already in+ // flight, so activate()'s retries as this one instead of overlapping it.onConnected: () => {- // activate() already revalidates this subscription's initial connection.- // Only later callbacks are reconnects that may cover a missed event gap.- if (!connected) {- connected = true;- return;- }// Revalidation, so it may wait for a consumer: activation re-reads// anyway. Only invalidation has to act with nobody reading.if (this.activeConsumers === 0) return;diff --git a/ui/src/lib/useVaultRequestRefresh.ts b/ui/src/lib/useVaultRequestRefresh.tsindex 704044526..c57dce857 100644--- a/ui/src/lib/useVaultRequestRefresh.ts+++ b/ui/src/lib/useVaultRequestRefresh.ts@@ -12,8 +12,9 @@ export function shouldPollVaultRequests(eventBridgeConnected: boolean): boolean/*** Refresh pending Vault requests from `vaults.updated` while the controller- * event bridge is healthy, with visibility-aware polling only as a degraded- * fallback. The immediate fallback tick also supplies the initial snapshot.+ * event bridge is healthy, catching up on `onConnected` for whatever the stream+ * could not deliver, with visibility-aware polling only as a degraded fallback.+ * The immediate fallback tick also supplies the initial snapshot.*/export function useVaultRequestRefresh(refresh: () => void | Promise<void>): void {const api = useApi();@@ -21,10 +22,11 @@ export function useVaultRequestRefresh(refresh: () => void | Promise<void>): voiuseEffect(() => {return api.connectWorkbenchEvents({- onEventBridgeStatus: ({ connected }) => {- setEventBridgeConnected(connected);- if (connected) void refresh();- },+ // Every gap ends here, whichever leg it was on, so this is the catch-up.+ // The bridge report is only the poll fallback's level: its recovery comes+ // with its own `onConnected`, and refetching from both would pay twice.+ onConnected: () => void refresh(),+ onEventBridgeStatus: ({ connected }) => setEventBridgeConnected(connected),onError: () => setEventBridgeConnected(false),onVaultsUpdated: () => void refresh(),});diff --git a/ui/src/lib/workbenchEventConnection.test.ts b/ui/src/lib/workbenchEventConnection.test.tsindex c2bcd67e4..ce5fcd513 100644--- a/ui/src/lib/workbenchEventConnection.test.ts+++ b/ui/src/lib/workbenchEventConnection.test.ts@@ -2,7 +2,15 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import {WorkbenchEventReconnectLoop,+ WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS,WORKBENCH_EVENT_OPEN_TIMEOUT_MS,+ declaredWorkbenchHeartbeatInterval,+ heartbeatCoversGap,+ isWorkbenchHeartbeatFresh,+ parseWorkbenchHeartbeatInterval,+ streamCoveredGap,+ workbenchEventStaleAfterMs,+ type WorkbenchControllerLegState,} from './workbenchEventConnection';describe('WorkbenchEventReconnectLoop', () => {@@ -16,7 +24,7 @@ describe('WorkbenchEventReconnectLoop', () => {const loop = new WorkbenchEventReconnectLoop({reconnect,isVisible: () => true,- isStreamLive: () => false,+ isBrowserLegLive: () => false,});for (const delayMs of [1_000, 2_000, 4_000, 8_000, 15_000, 15_000]) {@@ -43,7 +51,7 @@ describe('WorkbenchEventReconnectLoop', () => {const loop = new WorkbenchEventReconnectLoop({reconnect,isVisible: () => visible,- isStreamLive: () => false,+ isBrowserLegLive: () => false,});loop.attemptStarted();@@ -68,14 +76,14 @@ describe('WorkbenchEventReconnectLoop', () => {expect(reconnect).toHaveBeenCalledTimes(2);});- it('leaves a live stream alone on wake while still dropping the backoff', () => {+ it('leaves a live browser leg alone on wake while still dropping the backoff', () => {vi.useFakeTimers();- let streamLive = false;+ let browserLegLive = false;const reconnect = vi.fn();const loop = new WorkbenchEventReconnectLoop({reconnect,isVisible: () => true,- isStreamLive: () => streamLive,+ isBrowserLegLive: () => browserLegLive,});for (const delayMs of [1_000, 2_000, 4_000, 8_000, 15_000]) {@@ -85,19 +93,19 @@ describe('WorkbenchEventReconnectLoop', () => {expect(reconnect).toHaveBeenCalledTimes(5);reconnect.mockClear();- // A retry is waiting out the ceiling when the stream comes back up.+ // A retry is waiting out the ceiling when the socket comes back up.loop.failed();- streamLive = true;+ browserLegLive = true;loop.wake();vi.advanceTimersByTime(60_000);- // A stream that never dropped missed nothing, so waking must not recycle+ // A socket that never dropped missed nothing, so waking must not recycle// it -- every consumer refetches on reconnect to close a gap that a live- // stream does not have. The queued retry is cancelled, not deferred.+ // socket does not have. The queued retry is cancelled, not deferred.expect(reconnect).not.toHaveBeenCalled();// Clearing the backoff is the other half of waking: the next real drop// retries from the shortest delay instead of resuming at the ceiling.- streamLive = false;+ browserLegLive = false;loop.failed();vi.advanceTimersByTime(999);expect(reconnect).not.toHaveBeenCalled();@@ -105,3 +113,192 @@ describe('WorkbenchEventReconnectLoop', () => {expect(reconnect).toHaveBeenCalledTimes(1);});});++describe('workbench event stream liveness', () => {+ const now = 1_700_000_000_000;++ it('only vouches for a stream inside its own staleness window', () => {+ const interval = WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS;+ const staleAfter = workbenchEventStaleAfterMs(interval);++ // A server too old to send heartbeats never stamps one, so its streams+ // never speak for a gap -- the pre-heartbeat behavior, unchanged.+ expect(isWorkbenchHeartbeatFresh(null, interval, now)).toBe(false);+ expect(isWorkbenchHeartbeatFresh(now, interval, now)).toBe(true);+ // A few missed beats are jitter, not an outage.+ expect(isWorkbenchHeartbeatFresh(now - interval, interval, now)).toBe(true);+ expect(isWorkbenchHeartbeatFresh(now - (staleAfter - 1), interval, now)).toBe(true);+ expect(isWorkbenchHeartbeatFresh(now - staleAfter, interval, now)).toBe(false);+ // A clock that moved backwards cannot date the stamp; unproven is the safe+ // reading, because it costs one redundant read rather than a missed one.+ expect(isWorkbenchHeartbeatFresh(now + 1, interval, now)).toBe(false);+ });++ it('sizes the window from the server cadence but bounds what it will believe', () => {+ // The point of shipping the cadence: a slower server widens the tolerance+ // instead of the client hardcoding a guess about the interval.+ expect(workbenchEventStaleAfterMs(60_000)).toBeGreaterThan(+ workbenchEventStaleAfterMs(WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS),+ );+ // ...and a floor keeps a fast cadence from making jitter look like death.+ expect(workbenchEventStaleAfterMs(1_000)).toBe(+ workbenchEventStaleAfterMs(WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS),+ );++ expect(parseWorkbenchHeartbeatInterval(20_000)).toBe(20_000);+ for (const unusable of [undefined, null, 'soon', NaN, Infinity, {}]) {+ expect(parseWorkbenchHeartbeatInterval(unusable)).toBe(+ WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS,+ );+ }+ // A window no real gap could exceed would switch the check off, so a+ // declared cadence is clamped rather than trusted.+ const clamped = parseWorkbenchHeartbeatInterval(Number.MAX_SAFE_INTEGER);+ expect(isWorkbenchHeartbeatFresh(now - 3_600_000, clamped, now)).toBe(false);+ expect(parseWorkbenchHeartbeatInterval(-5)).toBeGreaterThan(0);+ });++ it('separates a cadence the server declared from one the client assumed', () => {+ // The two readers differ only in what they do with an unusable field, and+ // that difference is the whole point: a heartbeat is proof of life whatever+ // it says about cadence, while a handshake that declares nothing must not be+ // held to a deadline it never agreed to.+ for (const undeclared of [undefined, null, 'soon', NaN, Infinity, {}]) {+ expect(declaredWorkbenchHeartbeatInterval(undeclared)).toBeUndefined();+ expect(parseWorkbenchHeartbeatInterval(undeclared)).toBe(+ WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS,+ );+ }+ // A declaration is honored, and bounded by the same clamp, so a nonsense+ // promise cannot buy a window no real outage could exceed.+ expect(declaredWorkbenchHeartbeatInterval(20_000)).toBe(20_000);+ expect(declaredWorkbenchHeartbeatInterval(Number.MAX_SAFE_INTEGER)).toBe(+ parseWorkbenchHeartbeatInterval(Number.MAX_SAFE_INTEGER),+ );+ expect(declaredWorkbenchHeartbeatInterval(-5)).toBeGreaterThan(0);+ });++ const interval = WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS;+ const staleAfter = workbenchEventStaleAfterMs(interval);++ it('covers a gap only when a heartbeat lands inside it and still holds at its end', () => {+ // Stated as containment rather than as a list of scenarios. The gap is+ // [awaySince, now]; one heartbeat vouches for [beat, beat + staleAfter).+ // Coverage is that window reaching the gap's end while the beat itself falls+ // after the gap's start -- both ends, spelled independently of how the+ // implementation spells them, so dropping either one fails here.+ const covered = (awaySince: number, beat: number) =>+ awaySince < beat && beat <= now && now < beat + staleAfter;++ const offsets = [0, 1, 500, interval, staleAfter - 1, staleAfter, staleAfter + 1, staleAfter * 3];+ // A beat dated in the future is included: an unusable clock is not evidence.+ for (const awayAgo of offsets) {+ for (const beatAgo of [...offsets, -1]) {+ const awaySince = now - awayAgo;+ const lastHeartbeatAt = now - beatAgo;+ expect(+ heartbeatCoversGap({ lastHeartbeatAt, awaySince, intervalMs: interval, now }),+ `away ${awayAgo}ms ago, heartbeat ${beatAgo}ms ago`,+ ).toBe(covered(awaySince, lastHeartbeatAt));+ }+ }+ });++ it('reads an interval missing an end as uncovered', () => {+ // Both nulls say the same thing -- one end of the interval is missing, and a+ // comparison against a missing end has no answer. Unproven is the safe+ // reading: it costs a redundant read instead of silently stale data.+ for (const awaySince of [null, now - 1_000]) {+ for (const lastHeartbeatAt of [null, now]) {+ if (awaySince !== null && lastHeartbeatAt !== null) continue;+ expect(heartbeatCoversGap({ lastHeartbeatAt, awaySince, intervalMs: interval, now })).toBe(+ false,+ );+ }+ }+ });++ it('shrinks the untestable tail to one cadence without pretending to remove it', () => {+ // What this costs: a gap too short to contain a heartbeat is not covered, so+ // it pays the catch-up read that freshness alone would have skipped.+ expect(+ heartbeatCoversGap({+ lastHeartbeatAt: now - 1_000,+ awaySince: now - 500,+ intervalMs: interval,+ now,+ }),+ ).toBe(false);+ // What it cannot fix, recorded rather than patched: silence is not evidence,+ // so a stream that dies after its last heartbeat still reads as covering the+ // rest of a long gap. Only the watchdog closes that, by waiting for the+ // stream to speak again.+ expect(+ heartbeatCoversGap({+ lastHeartbeatAt: now - (staleAfter - 1),+ awaySince: now - staleAfter * 10,+ intervalMs: interval,+ now,+ }),+ ).toBe(true);+ });+});++describe('streamCoveredGap', () => {+ const now = 1_700_000_000_000;+ const interval = WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS;+ const staleAfter = workbenchEventStaleAfterMs(interval);+ const legs: WorkbenchControllerLegState[] = ['unknown', 'connected', 'disconnected'];++ it('holds only when every leg accounts for the interval', () => {+ // Stated as the conjunction it claims to be, spelled independently of how+ // the implementation spells each term -- a comparison here against a record+ // lookup there -- so dropping any one leg fails this.+ const carrying = (leg: WorkbenchControllerLegState) => leg === 'connected';++ for (const browserLegLive of [true, false]) {+ for (const controllerLeg of legs) {+ for (const lastHeartbeatAt of [now, now - 1_000, now - staleAfter, null]) {+ for (const awaySince of [now - 2_000, now - staleAfter * 10, null]) {+ expect(+ streamCoveredGap({+ browserLegLive,+ lastHeartbeatAt,+ controllerLeg,+ awaySince,+ intervalMs: interval,+ now,+ }),+ `browser ${browserLegLive}, controller ${controllerLeg}, beat ${lastHeartbeatAt}, away ${awaySince}`,+ ).toBe(+ browserLegLive &&+ carrying(controllerLeg) &&+ heartbeatCoversGap({ lastHeartbeatAt, awaySince, intervalMs: interval, now }),+ );+ }+ }+ }+ }+ });++ it('reads an unreported controller leg as unproven rather than healthy', () => {+ // The case the socket cannot see: it is open, heartbeating, and carrying+ // nothing, because the link behind the server is down. Every term about the+ // browser leg says covered, and the answer must still be no -- otherwise a+ // returning page skips its catch-up read and stays stale for as long as the+ // outage lasts.+ const provenBrowserLeg = {+ browserLegLive: true,+ lastHeartbeatAt: now - 1_000,+ awaySince: now - 2_000,+ intervalMs: interval,+ now,+ };+ expect(heartbeatCoversGap(provenBrowserLeg)).toBe(true);+ expect(streamCoveredGap({ ...provenBrowserLeg, controllerLeg: 'connected' })).toBe(true);+ expect(streamCoveredGap({ ...provenBrowserLeg, controllerLeg: 'disconnected' })).toBe(false);+ // And no report is not a report of health: a leg nobody has spoken about+ // cannot vouch for an interval either.+ expect(streamCoveredGap({ ...provenBrowserLeg, controllerLeg: 'unknown' })).toBe(false);+ });+});diff --git a/ui/src/lib/workbenchEventConnection.ts b/ui/src/lib/workbenchEventConnection.tsindex 846b66162..19ad122d8 100644--- a/ui/src/lib/workbenchEventConnection.ts+++ b/ui/src/lib/workbenchEventConnection.ts@@ -4,20 +4,201 @@ export const WORKBENCH_EVENT_RETRY_INITIAL_MS = 1_000;export const WORKBENCH_EVENT_RETRY_MAX_MS = 15_000;export const WORKBENCH_EVENT_OPEN_TIMEOUT_MS = 20_000;+/**+ * Heartbeat cadence to assume when the server has not declared a usable one.+ * Only ever sizes the window around a heartbeat that did arrive: a stream is+ * unproven until one does, so a server too old to send them never reads as+ * proven no matter what this says.+ */+export const WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS = 15_000;++// How many heartbeats a stream may miss before it stops speaking for itself.+// Lower turns one dropped frame or a long GC pause into a phantom outage, and+// the only cost of waiting is one catch-up read arriving late.+const WORKBENCH_EVENT_HEARTBEAT_MISSES = 3;+// Floor, so a fast cadence still tolerates ordinary scheduling jitter.+const WORKBENCH_EVENT_HEARTBEAT_STALE_FLOOR_MS = 45_000;+// Bounds on a cadence the server declares. A nonsense value must not be able to+// switch the staleness check off by claiming an interval no gap could exceed.+const WORKBENCH_EVENT_HEARTBEAT_MIN_MS = 1_000;+const WORKBENCH_EVENT_HEARTBEAT_MAX_MS = 120_000;++/**+ * A cadence the server actually declared, or undefined when it declared none.+ *+ * The distinction carries real weight: a declaration is what makes a deadline+ * enforceable, so a server that never made one must not be held to a default it+ * never agreed to. Substituting the fallback here would put every stream from a+ * server too old to declare a cadence on a deadline it cannot meet, and recycle+ * it every stale window forever.+ */+export function declaredWorkbenchHeartbeatInterval(raw: unknown): number | undefined {+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return undefined;+ return Math.min(+ WORKBENCH_EVENT_HEARTBEAT_MAX_MS,+ Math.max(WORKBENCH_EVENT_HEARTBEAT_MIN_MS, raw),+ );+}++/**+ * Read a server-declared cadence, falling back on anything unusable. For a+ * frame that is itself proof of life -- a heartbeat -- an unreadable cadence is+ * not worth discarding the proof over, so the fallback sizes the next window.+ */+export function parseWorkbenchHeartbeatInterval(raw: unknown): number {+ return declaredWorkbenchHeartbeatInterval(raw) ?? WORKBENCH_EVENT_HEARTBEAT_FALLBACK_MS;+}++/** How long a stream's last proof of life stays good. */+export function workbenchEventStaleAfterMs(intervalMs: number): number {+ return Math.max(+ WORKBENCH_EVENT_HEARTBEAT_STALE_FLOOR_MS,+ intervalMs * WORKBENCH_EVENT_HEARTBEAT_MISSES,+ );+}++/**+ * Whether a stream has proved itself alive recently enough to account for a gap+ * the page spent away. `readyState === OPEN` cannot: a suspended tab's socket+ * can die with the connection left in a zombie `OPEN` state and no `error`+ * event, which is precisely the case a returning page must not trust.+ */+export function isWorkbenchHeartbeatFresh(+ lastHeartbeatAt: number | null,+ intervalMs: number,+ now: number,+): boolean {+ if (lastHeartbeatAt === null) return false;+ const age = now - lastHeartbeatAt;+ // An age outside the window in either direction is unusable: the clock moved+ // backwards, so the stamp cannot be dated. Read that as unproven, which costs+ // one redundant read instead of trusting a stream that may be dead.+ return age >= 0 && age < workbenchEventStaleAfterMs(intervalMs);+}++/**+ * Whether heartbeat evidence covers the gap a page spent away.+ *+ * The claim a returning page makes is about an interval -- nothing was missed+ * between leaving and coming back -- so it takes evidence dated inside that+ * interval. An interval is covered by two comparisons and there is no third:+ * the newest heartbeat has to postdate the gap's start, and it has to still be+ * fresh at its end. Freshness alone was the whole test, which let a heartbeat+ * from *before* a short suspension speak for a socket that died during it: a+ * page that is not executing receives nothing, so a heartbeat missing from the+ * time it was away is not the scheduling jitter the freshness window exists to+ * absorb. It is no evidence at all.+ *+ * `awaySince === null` is a gap that cannot be dated, and an undated interval+ * is never covered. A stamp that lags the real departure -- all a listener that+ * attached mid-gap can offer -- cannot manufacture coverage either: a heartbeat+ * dated after it is traffic this page received while executing, on a socket+ * that was therefore still alive.+ *+ * What this cannot cover is the tail after the newest heartbeat, and no+ * comparison can: absence of traffic is never evidence of continuity, so a+ * stream that dies late in a long gap still reads as covered here. The+ * heartbeat watchdog is what closes that -- it is the only check that can wait+ * for the stream to speak again. This term shrinks the untestable tail from the+ * whole away period down to one cadence; it cannot remove it.+ */+export function heartbeatCoversGap({+ lastHeartbeatAt,+ awaySince,+ intervalMs,+ now,+}: {+ lastHeartbeatAt: number | null;+ awaySince: number | null;+ intervalMs: number;+ now: number;+}): boolean {+ if (awaySince === null || lastHeartbeatAt === null) return false;+ return lastHeartbeatAt > awaySince && isWorkbenchHeartbeatFresh(lastHeartbeatAt, intervalMs, now);+}++/**+ * How far the controller leg has been observed from this client. `unknown` is+ * not a third kind of outage: it is a leg nobody has reported on yet.+ */+export type WorkbenchControllerLegState = 'unknown' | 'connected' | 'disconnected';++/**+ * Whether each state means the controller leg is carrying events. A record keyed+ * by the union rather than a comparison against `'connected'`, so a state added+ * later cannot compile until this answer is decided for it -- and the answer+ * that is easy to get wrong is already here: `unknown` is a leg nobody has+ * reported on, and no report is not a report of health.+ */+const CONTROLLER_LEG_CARRYING: Record<WorkbenchControllerLegState, boolean> = {+ unknown: false,+ connected: true,+ disconnected: false,+};++/**+ * Whether the stream as a whole can vouch for the interval a page spent away.+ *+ * Every leg, every time. An event crosses two links that fail independently to+ * reach a handler -- controller to UI server, UI server to browser -- so a+ * verdict about the stream is a verdict about both, and one assembled from a+ * single leg is a sound answer to a different question. That substitution is+ * what this function exists to make unavailable: the browser leg is deliberately+ * the whole of the *transport* question, because reopening that socket cannot+ * repair the link behind the server, and reading the transport verdict here+ * imported that deliberate scope into a claim about the whole path.+ *+ * The legs prove themselves differently, and the asymmetry is structural rather+ * than an omission. The browser leg is sampled, so only its own periodic proof,+ * dated inside the interval, separates a quiet socket from a dead one. The+ * controller leg is reported -- and reported *over* the browser leg -- so a+ * browser leg proven continuous across the interval is what makes the+ * controller leg's present level an account of the whole interval: every+ * transition it made was delivered, and a recovery among them already announced+ * itself as the gap it was. A leg whose reports travelled some other way would+ * need its own term dated inside the interval, exactly as the browser leg has.+ */+export function streamCoveredGap({+ browserLegLive,+ lastHeartbeatAt,+ controllerLeg,+ awaySince,+ intervalMs,+ now,+}: {+ browserLegLive: boolean;+ lastHeartbeatAt: number | null;+ controllerLeg: WorkbenchControllerLegState;+ awaySince: number | null;+ intervalMs: number;+ now: number;+}): boolean {+ return (+ browserLegLive &&+ CONTROLLER_LEG_CARRYING[controllerLeg] &&+ heartbeatCoversGap({ lastHeartbeatAt, awaySince, intervalMs, now })+ );+}+type TimerHandle = ReturnType<typeof setTimeout>;interface WorkbenchEventReconnectLoopOptions {reconnect: () => void;isVisible: () => boolean;- /** Whether events are flowing end to end right now, so no gap needs closing. */- isStreamLive: () => boolean;+ /**+ * Whether the leg this loop owns -- the browser's socket -- is carrying right+ * now, so reopening it would close nothing. Scoped to that leg on purpose: it+ * is the only one a reconnect can repair. Not a verdict on the whole stream,+ * and not usable as one.+ */+ isBrowserLegLive: () => boolean;}/** Owns the retry policy; EventSource wiring stays in ApiContext. */export class WorkbenchEventReconnectLoop {private readonly reconnect: () => void;private readonly isVisible: () => boolean;- private readonly isStreamLive: () => boolean;+ private readonly isBrowserLegLive: () => boolean;private retryTimer: TimerHandle | null = null;private openTimer: TimerHandle | null = null;private retryAttempt = 0;@@ -26,7 +207,7 @@ export class WorkbenchEventReconnectLoop {constructor(options: WorkbenchEventReconnectLoopOptions) {this.reconnect = options.reconnect;this.isVisible = options.isVisible;- this.isStreamLive = options.isStreamLive;+ this.isBrowserLegLive = options.isBrowserLegLive;}attemptStarted(): void {@@ -72,7 +253,7 @@ export class WorkbenchEventReconnectLoop {// consumer runs on reconnect -- that waking exists to recover from.// Checked before clearOpenTimer() so a stream that is open at the transport// but has not completed its handshake keeps its watchdog armed.- if (this.isStreamLive()) return;+ if (this.isBrowserLegLive()) return;this.clearOpenTimer();this.reconnect();}diff --git a/vibe/inbox_bridge.py b/vibe/inbox_bridge.pyindex 023eaa8f8..0a22bdc8e 100644--- a/vibe/inbox_bridge.py+++ b/vibe/inbox_bridge.py@@ -96,7 +96,18 @@ async def run_inbox_bridge() -> None:# the next genuine drop reconnects promptly.backoff = _BACKOFF_INITIALif event_type == "connected":+ # The internal feed's handshake, consumed here and not+ # relayed. ``_set_bridge_connected`` already published the+ # browser-facing expression of this exact fact, and the+ # client turns that leg transition into one gap-ended+ # signal. Forwarding this frame too made every controller+ # recovery announce twice, because ``connected`` on the+ # browser stream is a different claim -- "your subscription+ # is established", carrying a sub_id and a heartbeat+ # cadence this frame has never had. One fact, one owner,+ # and the leg's owner is the side that tracks the leg._set_bridge_connected(True)+ continueevent_id = (str(data.get("_event_id") or "")if isinstance(data, dict)diff --git a/vibe/sse_broker.py b/vibe/sse_broker.pyindex ae4e13682..7a8ce2d92 100644--- a/vibe/sse_broker.py+++ b/vibe/sse_broker.py@@ -30,9 +30,26 @@ from typing import Anylogger = logging.getLogger(__name__)+class _Subscription:+ """One subscriber's queue, plus what this broker failed to hand it.++ A bounded queue means "slow subscriber" and "lost events" are the same+ condition, and the loss is invisible from both ends: the publisher's+ ``put_nowait`` raised somewhere it cannot report, and the subscriber's socket+ stays perfectly healthy. Counting the discards here is what lets whoever owns+ that subscriber's stream tell it that its view has a hole in it.+ """++ __slots__ = ("queue", "dropped")++ def __init__(self, queue: asyncio.Queue) -> None:+ self.queue = queue+ self.dropped = 0++class SSEBroker:def __init__(self) -> None:- self._subscribers: dict[int, asyncio.Queue] = {}+ self._subscribers: dict[int, _Subscription] = {}self._next_id = 0self._loop: asyncio.AbstractEventLoop | None = None# ``subscribe`` / ``unsubscribe`` run on the event loop thread while@@ -50,7 +67,7 @@ class SSEBroker:with self._lock:sub_id = self._next_idself._next_id += 1- self._subscribers[sub_id] = queue+ self._subscribers[sub_id] = _Subscription(queue)total = len(self._subscribers)logger.debug("SSE subscriber %s connected (total=%s)", sub_id, total)return sub_id, queue@@ -66,6 +83,20 @@ class SSEBroker:with self._lock:return len(self._subscribers)+ def dropped_count(self, sub_id: int) -> int:+ """How many events this broker discarded for one subscriber, ever.++ Monotonic for the life of the subscription, so a caller compares it+ against its own last reading rather than resetting it: two readers of the+ same subscription must not be able to consume each other's evidence.+ Returns 0 for an unknown ``sub_id`` -- a subscription that no longer+ exists has no continuity left to speak for.+ """++ with self._lock:+ subscription = self._subscribers.get(sub_id)+ return subscription.dropped if subscription is not None else 0+def publish(self, event_type: str, data: Any) -> None:"""Fan a JSON event out to every subscriber.@@ -82,20 +113,30 @@ class SSEBroker:with self._lock:if not self._subscribers:return- queues = list(self._subscribers.values())- for queue in queues:+ subscriptions = list(self._subscribers.values())+ for subscription in subscriptions:try:- loop.call_soon_threadsafe(self._put_nowait, queue, event_type, payload)+ loop.call_soon_threadsafe(self._put_nowait, subscription, event_type, payload)except RuntimeError:# Loop was closed; skip silently — next subscribe will# capture a fresh loop.pass@staticmethod- def _put_nowait(queue: asyncio.Queue, event_type: str, payload: str) -> None:+ def _put_nowait(subscription: _Subscription, event_type: str, payload: str) -> None:+ """Hand one event to one subscriber, and record it if that fails.++ Every path here that does not enqueue is a lost event and must count as+ one: the subscriber has no other way to find out, and a discard nobody+ counted is a hole in its view that reads exactly like quiet. Runs on the+ event loop thread via ``call_soon_threadsafe``, same as the generator+ that reads the count, so the counter needs no lock of its own.+ """+try:- queue.put_nowait((event_type, payload))+ subscription.queue.put_nowait((event_type, payload))except asyncio.QueueFull:+ subscription.dropped += 1logger.warning("SSE subscriber queue full; dropping %s event", event_type)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 5a984c6ee..3cacf5000 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -170,6 +170,10 @@ _AUTHORIZATION_REVOKED_WEBSOCKET_CLOSE_CODE = 4403_AUTHORIZATION_UNAVAILABLE_WEBSOCKET_CLOSE_CODE = 4503_AUTHORIZATION_CHANGED_WEBSOCKET_CLOSE_CODE = 1012_AUTHORIZATION_REVISION_RECHECK_SECONDS = 1.0+# How often ``GET /api/events`` proves the stream is alive. It doubles as the+# proxy keep-alive -- Cloudflare Tunnel's default idle is well below 100s, and+# mid-tier proxies are happier still with something this short.+WORKBENCH_EVENT_HEARTBEAT_INTERVAL_S = 15.0_TRUE_BOOL_STRINGS = {"1", "true", "yes", "on"}STRUCTURED_LOG_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$")@@ -11556,6 +11560,42 @@ def _workbench_event_data(payload: str) -> dict[str, Any] | None:return data if isinstance(data, dict) else None+def _workbench_event_heartbeat_interval_ms() -> int:+ return int(WORKBENCH_EVENT_HEARTBEAT_INTERVAL_S * 1000)+++def _workbench_event_connected_frame(sub_id: int) -> str:+ """The handshake: this subscription's id, and the cadence it is owed.++ Carrying the cadence here is what lets a client hold a brand-new stream to a+ deadline. The promise arrives before the first heartbeat does, so a stream+ that opens and then goes silent has something to have broken -- without it,+ the client's only options are to trust an unproven stream for a whole window+ or to watchdog servers that never promised anything.++ A declaration, never proof: a server too old to send this field is simply+ never held to a cadence, and a client must still wait for a heartbeat before+ believing the stream is carrying events.+ """+ interval_ms = _workbench_event_heartbeat_interval_ms()+ return f'event: connected\ndata: {{"sub_id":{sub_id},"interval_ms":{interval_ms}}}\n\n'+++def _workbench_event_heartbeat_frame() -> str:+ """A frame whose only job is to be seen.++ An SSE comment keeps proxies awake but never reaches ``EventSource``, so a+ client watching a quiet stream cannot distinguish it from a socket that died+ while the tab was suspended -- iOS in particular leaves such a stream in a+ zombie ``OPEN`` state with no ``error``. Carrying the cadence lets the client+ size its own staleness tolerance from the server that sets it, rather than+ duplicating the interval on both sides -- which is also why the interval+ belongs in the payload even though nothing else here needs a body.+ """+ interval_ms = _workbench_event_heartbeat_interval_ms()+ return f'event: heartbeat\ndata: {{"interval_ms":{interval_ms}}}\n\n'++def _workbench_event_visible_to_context(context, event_type: str, payload: str) -> bool:if context is None:return True@@ -11678,9 +11718,10 @@ async def workbench_events():Browsers open this once and keep it open; the route streams JSONevents (message.new, session.activity, inbox.unread.changed) as- they happen elsewhere in the app, plus a 15-second keep-alive- comment line so Cloudflare-style proxies don't kill the idle TCP- connection.+ they happen elsewhere in the app, plus a ``heartbeat`` event every+ ``WORKBENCH_EVENT_HEARTBEAT_INTERVAL_S`` so Cloudflare-style proxies+ don't kill the idle TCP connection and the client can tell a quiet+ stream from a dead one.Native FastAPI ``StreamingResponse`` so the loop stays async andeach browser only costs one task, not one OS thread.@@ -11722,6 +11763,14 @@ async def workbench_events():async def generate():sub_id, queue = broker.subscribe()+ # Baselined here, before anything can suspend or reach the client. A+ # fresh subscription is owed everything from this instant on, so the+ # count is 0 by construction -- reading it late looked equivalent and is+ # not: the authorization await and the handshake below are suspension+ # points, and the client can finish its connect catch-up while this+ # generator is parked between them. A burst discarded in that window+ # would then become the baseline and never be reported.+ last_dropped = broker.dropped_count(sub_id)try:state = await authorization_state()if state != "current":@@ -11730,7 +11779,7 @@ async def workbench_events():# First chunk = handshake + sub_id so the client can include it in# 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"+ yield _workbench_event_connected_frame(sub_id)payload = json.dumps({"type": WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT,@@ -11740,13 +11789,50 @@ async def workbench_events():separators=(",", ":"),)yield f"event: {WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT}\ndata: {payload}\n\n"+ last_heartbeat_at = time.monotonic()while True:state = await authorization_state()if state != "current":yield _remote_authorization_sse_frame(state)return+ # A subscriber that lost an event is not a subscriber any more,+ # so end its stream and let it reconnect: the fresh subscription+ # gets an empty queue and the client's reconnect path already+ # catches consumers up exactly once, with backoff if the load+ # that overflowed the queue is still going. Announcing the hole+ # on this stream instead looks cheaper and is not -- the queue+ # stays full, so the next iteration finds another discard and+ # announces again, starving the payload frames it was warning+ # about. Reopening is the actual repair here, unlike the+ # controller leg, which announces in place because a new socket+ # would inherit the same severed bridge.+ #+ # Checked before the heartbeat: a heartbeat claims this stream is+ # worth trusting, which stopped being true.+ dropped = broker.dropped_count(sub_id)+ if dropped > last_dropped:+ logger.warning(+ "workbench events: ending subscriber %s after %s dropped event(s)",+ sub_id,+ dropped - last_dropped,+ )+ return+ # A fixed cadence, deliberately not "only when the queue went+ # quiet". Data frames are no proof of life to a client that may+ # be filtered out of all of them, and one unconditional clock+ # means each side has exactly one thing to stamp.+ since_heartbeat = time.monotonic() - last_heartbeat_at+ if since_heartbeat >= WORKBENCH_EVENT_HEARTBEAT_INTERVAL_S:+ yield _workbench_event_heartbeat_frame()+ last_heartbeat_at = time.monotonic()+ continuetry:- event_type, payload = await asyncio.wait_for(queue.get(), timeout=15.0)+ # Floored so an event arriving just short of the deadline+ # cannot spin this loop; the heartbeat is at most that late.+ event_type, payload = await asyncio.wait_for(+ queue.get(),+ timeout=max(0.25, WORKBENCH_EVENT_HEARTBEAT_INTERVAL_S - since_heartbeat),+ )state = await authorization_state()if state != "current":yield _remote_authorization_sse_frame(state)@@ -11783,13 +11869,9 @@ async def workbench_events():)yield f"event: {event_type}\ndata: {payload}\n\n"except asyncio.TimeoutError:- state = await authorization_state()- if state != "current":- yield _remote_authorization_sse_frame(state)- return- # 15s keep-alive — Cloudflare Tunnel default idle is well- # below 100s but this still keeps mid-tier proxies happy.- yield ": ping\n\n"+ # Nothing to forward. Loop round so the heartbeat is emitted+ # by the one branch that owns it, after a fresh auth check.+ continueexcept asyncio.CancelledError:raisefinally: