Skip to content

The agent that grows with you

fix(gateway): a reconnecting viewer gets the owner's waiting server requests again

alt-glitch36a9d412b318
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 4ea5cbeed91..35567c74c39 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4979,6 +4979,7 @@ export interface CanonicalSnapshot {
info: CanonicalSnapshotInfo
pending_connection?: ConnectionRequestPayload | null
todo_state?: TodoState | null
+ open_requests?: OpenRequestEntry[] | null
}
export interface CanonicalPendingAdmission {
admission_id: string
@@ -5129,6 +5130,7 @@ export interface CanonicalEventsResult {
truncated: boolean
snapshot_required: boolean
count: number
+ open_requests?: OpenRequestEntry[] | null
}
export interface CanonicalReplayEvent {
type: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 21701deb5e7..3d64ed20c0c 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -8696,6 +8696,21 @@
"count": {
"title": "Count",
"type": "integer"
+ },
+ "open_requests": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/OpenRequestEntry"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Open Requests"
}
},
"required": [
@@ -10386,6 +10401,21 @@
}
],
"default": null
+ },
+ "open_requests": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/OpenRequestEntry"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Open Requests"
}
},
"required": [
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 65887575dec..bd50e305884 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -626,6 +626,7 @@ class AuthorityConnection:
await asyncio.to_thread(refresh_profile_hooks, policy_for_source(self.authority.runner, source))
info = await snapshot_info(self.authority, snapshot.handle.ref)
from gateway.session_connections import pending_connection
+ from gateway.session_server_requests import open_requests
# Its home module, not tui_gateway.server: importing the stdio sidecar points sys.stdout at stderr.
from tui_gateway.tool_progress import _todo_state_from_history
history, display = list(snapshot.history), {}
@@ -643,6 +644,9 @@ class AuthorityConnection:
'pending': [asdict(r) for r in snapshot.pending],
'prompts': list(snapshot.prompts), 'info': info,
'pending_connection': pending_connection(self.authority, ref.session_id),
+ # Still-waiting server→client requests: the event ring cannot say "still open".
+ 'open_requests': open_requests(self.authority.sessions[snapshot.handle.ref.session_id].event_stream,
+ snapshot.handle.ref.session_id),
# The newest todo result in the transcript, the snapshot the session's agent hydrates
# from and its ``todo.updated`` frames carried: a viewer attaching shows the plan now.
'todo_state': _todo_state_from_history(history)}
@@ -685,7 +689,9 @@ class AuthorityConnection:
epoch = params.get('replay_epoch')
if type(sequence) is not int or sequence < 0 or (epoch is not None and not isinstance(epoch, str)):
raise RuntimeStoreError('invalid_params')
- return self.authority.sessions[ref.session_id].event_stream.since(epoch, sequence)
+ from gateway.session_server_requests import open_requests
+ stream = self.authority.sessions[ref.session_id].event_stream
+ return {**stream.since(epoch, sequence), 'open_requests': open_requests(stream, ref.session_id)}
async def submit(self, ref, params):
if self._voice_stop_replay(ref, params) or await self._typed_voice_stop(ref, params):
diff --git a/gateway/session_server_requests.py b/gateway/session_server_requests.py
index 56ad7791159..64d31eaefa6 100644
--- a/gateway/session_server_requests.py
+++ b/gateway/session_server_requests.py
@@ -22,12 +22,14 @@ _POLL_S = 0.25
class _Pending:
- __slots__ = ("event", "events", "locked", "method", "qids", "result", "session_id", "value")
+ __slots__ = ("event", "events", "locked", "method", "params", "qids", "result", "session_id", "value")
- def __init__(self, session_id, qids=None, events=None, method=None):
+ def __init__(self, session_id, qids=None, events=None, method=None, params=None):
self.event = threading.Event()
self.session_id = session_id
self.method = method
+ # The frame's params as sent, so a viewer that reconnects gets the request again.
+ self.params = params or {}
# The live session's own event stream the request went out on: one per authority (profile) and
# session mount, so a viewer of another profile's same-named session can never settle it.
self.events = events
@@ -116,6 +118,17 @@ def waiting(events, session_id, method) -> bool:
return any(p.session_id == session_id and p.events is events and p.method == method for p in _open.values())
+def open_requests(events, session_id) -> list[dict]:
+ """The requests still waiting on this live session's stream, oldest first, as their frames
+ carried them (plus a batch's answers locked so far): what ``session.resume`` and
+ ``session.events.since`` hand a reconnecting viewer to re-render (``OpenRequestEntry``)."""
+ with _lock:
+ waiting_now = [(rid, p) for rid, p in _open.items() if p.session_id == session_id and p.events is events]
+ return [{"id": rid, "method": p.method,
+ "params": {**p.params, "answers": dict(p.locked)} if p.locked else dict(p.params)}
+ for rid, p in waiting_now]
+
+
def withdraw(events, session_id, method) -> int:
"""Settle every open *method* request on this live session's stream with no answer, the way a
viewer that answered would: the asker reads None and every renderer gets ``request.cancel
@@ -154,11 +167,10 @@ def _ask(events, session_id, method, params, *, cancelled, timeout, qids=None):
if not events.fanout.transports():
return None
request_id = f"srq-{uuid.uuid4().hex[:12]}"
- pending = _Pending(session_id, qids, events, method)
+ pending = _Pending(session_id, qids, events, method, {"session_id": session_id, **params})
with _lock:
_open[request_id] = pending
- events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": method,
- "params": {"session_id": session_id, **params}})
+ events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": method, "params": pending.params})
waited = 0.0
reason = "timeout"
while not pending.event.wait(_POLL_S):
diff --git a/tests/gateway/test_server_request_resume_replay.py b/tests/gateway/test_server_request_resume_replay.py
new file mode 100644
index 00000000000..7a15e512177
--- /dev/null
+++ b/tests/gateway/test_server_request_resume_replay.py
@@ -0,0 +1,55 @@
+"""A viewer that reconnects while the owner's server→client request waits gets that request again.
+
+The canonical side of the sidecar's ``open_requests`` replay (``tui_gateway/server_requests.py``):
+a Desktop reload mid-onboarding re-renders the waiting ``setup_beat`` card, and answering it there
+unblocks the turn instead of leaving it parked until ``CARD_TIMEOUT_S``.
+"""
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from tests.gateway.test_onboarding_on_the_authority import _desktop, _request, _Transport
+from tests.waiting import async_wait_until
+
+
+async def _reload(desktop):
+ """The renderer reloads: its socket closes and a new one connects and resumes."""
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_local_migration import bind_native_transport
+ await desktop.connection.close()
+ identity = {"user_id": "uid:1", "provider": "local", "profile_id": desktop.authority.profile_id,
+ "instance_id": "owner", "native_bootstrap": True}
+ desktop.transport = _Transport()
+ desktop.transport.desktop_local = True
+ desktop.connection = AuthorityConnection(desktop.authority, desktop.transport, identity)
+ bind_native_transport(desktop.authority, desktop.connection.actor, identity)
+
+
+async def test_a_resumed_viewer_gets_the_waiting_setup_card_and_its_answer_unblocks_the_turn(tmp_path, monkeypatch):
+ from gateway.session_server_requests import ask_viewer_result, waiting
+ desktop = await _desktop(tmp_path, monkeypatch, [])
+ try:
+ stored = (await _request(desktop, 1, "onboarding.start", {"rerun": True}))["result"]["stored_session_id"]
+ assert "result" in await _request(desktop, 2, "session.resume", {"session_id": stored})
+ live = desktop.authority.sessions[stored]
+ params = {"beat": "name", "tool_call_id": "call-1", "card": {"suggested": "Sid"}}
+ answer = asyncio.get_running_loop().run_in_executor(None, lambda: ask_viewer_result(
+ live.event_stream, stored, "setup_beat", params, timeout=20))
+ await async_wait_until(lambda: waiting(live.event_stream, stored, "setup_beat"), timeout=5)
+
+ await _reload(desktop)
+ resumed = await _request(desktop, 3, "session.resume", {"session_id": stored})
+
+ assert "result" in resumed, resumed
+ [entry] = resumed["result"]["open_requests"]
+ assert entry["method"] == "setup_beat" and entry["params"] == {"session_id": stored, **params}
+ reply = await desktop.connection.dispatch({"jsonrpc": "2.0", "id": entry["id"],
+ "result": {"answer": {"name": "Sid"}}})
+ assert reply is None
+ assert await asyncio.wait_for(answer, 10) == {"answer": {"name": "Sid"}}
+ assert not waiting(live.event_stream, stored, "setup_beat")
+ finally:
+ await desktop.connection.close()
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index db394b039bc..8ba38f8d295 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -9,7 +9,7 @@ from pydantic import RootModel
from .base import JsonValue, Params, Result
from .common import ProfileParams, TranscriptMessage
from .connectors_operation import ConnectionRequestPayload
-from .sessions import TodoState
+from .sessions import OpenRequestEntry, TodoState
from .canonical import AdmissionStatus, CanonicalSessionRef, PromptResponseResult, SessionInventoryFields
from .registry import canonical_method
@@ -155,6 +155,8 @@ class CanonicalSnapshot(Result):
pending_connection: ConnectionRequestPayload | None = None
# The session's todo snapshot (its transcript's newest todo result); null when it has none.
todo_state: TodoState | None = None
+ # The owner's server→client requests still unanswered (``session_server_requests.open_requests``).
+ open_requests: list[OpenRequestEntry] | None = None
class CanonicalListParams(ProfileParams):
@@ -314,6 +316,7 @@ class CanonicalEventsResult(Result):
truncated: bool
snapshot_required: bool
count: int
+ open_requests: list[OpenRequestEntry] | None = None
for _name, _params, _result in (