Skip to content

The agent that grows with you

refactor(gateway): move the owner's server-request registry out of session_sudo_prompt

Teknium433046b39989
diff --git a/gateway/local_desktop_ui.py b/gateway/local_desktop_ui.py
index f4b36566606..81e13d41bf3 100644
--- a/gateway/local_desktop_ui.py
+++ b/gateway/local_desktop_ui.py
@@ -132,7 +132,7 @@ def _install_process_sinks() -> None:
def _ask_result(turn, agent, method, params, timeout):
"""One structured server request; the viewer's ``result`` dict, or None when none answered."""
- from gateway.session_sudo_prompt import ask_viewer_result
+ from gateway.session_server_requests import ask_viewer_result
authority, session_id, _generation = turn._approval_owner
live = authority.sessions.get(session_id)
if live is None:
@@ -185,7 +185,7 @@ def _setup_beat(turn, agent, payload):
def _ask(turn, agent, method, params, timeout):
"""One ``ValueResult`` server request to the session's attached viewers; "" when none answered."""
- from gateway.session_sudo_prompt import ask_viewer
+ from gateway.session_server_requests import ask_viewer
authority, session_id, _generation = turn._approval_owner
live = authority.sessions.get(session_id)
if live is None:
diff --git a/gateway/session_clarify_batch.py b/gateway/session_clarify_batch.py
index abd48e475f5..cca7bbdb4a7 100644
--- a/gateway/session_clarify_batch.py
+++ b/gateway/session_clarify_batch.py
@@ -14,7 +14,7 @@ _QUESTION_KEYS = ("qid", "question", "choices", "multi_select")
def ask_clarify_batch(turn, questions) -> dict:
- from gateway.session_sudo_prompt import ask_viewer_result
+ from gateway.session_server_requests import ask_viewer_result
from tools.clarify_gateway import get_clarify_timeout
authority, session_id, _generation = turn._approval_owner
live = authority.sessions.get(session_id)
@@ -36,7 +36,7 @@ def ask_clarify_batch(turn, questions) -> dict:
return {"answers": {}, "outcome": "cancelled"}
known = {entry["qid"] for entry in questions}
clean = {qid: (value if isinstance(value, str) else None) for qid, value in answers.items() if qid in known}
- # ``session_sudo_prompt`` settles a batch with its terminal outcome (an absent outcome on a frame
+ # ``session_server_requests`` settles a batch with its terminal outcome (an absent outcome on a frame
# that carried answers is ``submitted``; a cancel-all or error is ``cancelled``).
outcome = result.get("outcome") if result.get("outcome") in ("submitted", "timed_out", "cancelled") else "cancelled"
return {"answers": clean, "outcome": outcome}
diff --git a/gateway/session_clarify_lock.py b/gateway/session_clarify_lock.py
index 8725234c6e3..38b8f3c9e8c 100644
--- a/gateway/session_clarify_lock.py
+++ b/gateway/session_clarify_lock.py
@@ -13,7 +13,7 @@ from hermes_state_runtime import RuntimeStoreError
async def clarify_lock(connection, ref, params):
- from gateway.session_sudo_prompt import lock_answer, may_settle
+ from gateway.session_server_requests import lock_answer, may_settle
# The dispatcher already refused unknown keys and mistyped fields against the declared
# ``ClarifyLockParams`` (``tui_gateway/contracts/canonical.py``); a missing or empty id is ours to refuse.
# ``profile`` naming another served profile was routed to its owner by ``dispatch``.
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index d079a7347fd..ea3cdba48eb 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -195,7 +195,7 @@ class AuthorityConnection:
return handlers
async def dispatch(self, request):
- from gateway.session_sudo_prompt import is_response_frame
+ from gateway.session_server_requests import is_response_frame
if is_response_frame(request):
# A viewer answering one of the owner's server→client requests (the sudo prompt): a
# response gets no reply (JSON-RPC), and only a viewer entitled to respond on that
@@ -694,7 +694,7 @@ class AuthorityConnection:
return asdict(await self.authority.interrupt(self.actor, ref, params.get('execution_generation')))
def _resolve_response(self, frame):
- from gateway.session_sudo_prompt import may_settle, resolve
+ from gateway.session_server_requests import may_settle, resolve
def entitled(session_id, events):
# The same rule ``clarify.lock`` applies to the same request id (attached + respond).
diff --git a/gateway/session_secret_prompt.py b/gateway/session_secret_prompt.py
index c413f8475cf..9bf70242f34 100644
--- a/gateway/session_secret_prompt.py
+++ b/gateway/session_secret_prompt.py
@@ -35,7 +35,7 @@ def secret_prompt_scope(turn, agent):
authority, session_id, _generation = turn._approval_owner
def callback(var_name, prompt, metadata=None):
- from gateway.session_sudo_prompt import ask_viewer
+ from gateway.session_server_requests import ask_viewer
live = authority.sessions.get(session_id)
if live is None:
return _skipped(var_name, "cancelled", "Secret setup was skipped.")
diff --git a/gateway/session_server_requests.py b/gateway/session_server_requests.py
new file mode 100644
index 00000000000..87c75542094
--- /dev/null
+++ b/gateway/session_server_requests.py
@@ -0,0 +1,173 @@
+"""The session owner's server→client requests to a local viewer, and who may settle them.
+
+The owner sends a request frame (``tui_gateway/contracts/server_requests.py``: ``sudo``, ``secret``,
+``clarify``, the Desktop UI requests) to the viewers attached to a session's event stream and blocks the
+agent thread until one answers, the turn is interrupted, or it times out: the canonical side of main's
+sidecar ``tui_gateway/server_requests.py``. A viewer answers with a JSON-RPC response frame
+(:func:`resolve`) or, for a batch clarify, per question with ``clarify.lock`` (:func:`lock_answer`); both go
+through :func:`may_settle`, and a batch's terminal result comes from ``tools.clarify_batch.settle_batch``,
+the rule the sidecar uses too. Values are never published, journaled or logged: they travel only in the
+viewer's response frame.
+"""
+from __future__ import annotations
+
+import contextlib
+import threading
+import uuid
+
+from tools.clarify_batch import settle_batch
+
+REQUEST_TIMEOUT_S = 120 # main: ``_ask("sudo", ..., timeout=120)``
+_POLL_S = 0.25
+
+
+class _Pending:
+ __slots__ = ("event", "events", "locked", "qids", "result", "session_id", "value")
+
+ def __init__(self, session_id, qids=None, events=None):
+ self.event = threading.Event()
+ self.session_id = session_id
+ # 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
+ self.value = ""
+ self.result = None
+ # A batch clarify: its question ids and the answers ``clarify.lock`` has locked so far.
+ self.qids = tuple(qids) if qids else None
+ self.locked = {}
+
+
+_lock = threading.Lock()
+_open: dict[str, _Pending] = {}
+
+
+def owned_by(authority, session_id, events) -> bool:
+ """True when *authority*'s live *session_id* is the very stream a request was sent on."""
+ live = authority.sessions.get(session_id)
+ return live is not None and events is not None and live.event_stream is events
+
+
+def may_settle(authority, actor, session_id, events) -> bool:
+ """The one rule for who may settle an owner request (a response frame or ``clarify.lock``): the
+ request went out on *authority*'s own live stream for that session (session ids repeat across
+ profiles and ``_open`` is process-wide), *actor* holds ``session:respond`` there, and *actor* is
+ attached to that session, the same set of connections the request frame was written to."""
+ from gateway.session_contract import SessionRef
+ from hermes_state_runtime import RuntimeStoreError
+ if not owned_by(authority, session_id, events):
+ return False
+ try:
+ authority.authorize(actor, SessionRef(authority.profile_id, session_id), "session:respond")
+ except RuntimeStoreError:
+ return False
+ live = authority.sessions.get(session_id)
+ return live is not None and actor in live.subscribers.values()
+
+
+def is_response_frame(frame) -> bool:
+ """A viewer's answer to one of the owner's requests: a string ``srq-`` id, a result/error, no method."""
+ return (isinstance(frame, dict) and "method" not in frame and isinstance(frame.get("id"), str)
+ and frame["id"].startswith("srq-") and ("result" in frame or "error" in frame))
+
+
+def resolve(frame, *, session_ok=lambda session_id, events: True) -> bool:
+ """Settle the open request *frame* answers; False when nothing (here) waits for that id.
+ ``session_ok(session_id, events)`` lets the caller refuse an answer from a connection not entitled
+ to that session: the caller's own authority must own ``events``, the stream the request was sent on
+ (session ids are only unique per profile, and ``_open`` is process-wide)."""
+ with _lock:
+ pending = _open.get(frame["id"])
+ if pending is None or not session_ok(pending.session_id, pending.events):
+ return False
+ _open.pop(frame["id"], None)
+ locked = dict(pending.locked) if pending.qids is not None else None
+ result = frame.get("result") if "error" not in frame else None
+ if locked is not None:
+ # One rule with main's sidecar registry: the frame's answers over the locks, or a cancel-all.
+ result = settle_batch(locked, result)
+ value = result.get("value") if isinstance(result, dict) else ""
+ pending.value = value if isinstance(value, str) else ""
+ pending.result = result if isinstance(result, dict) else None
+ pending.event.set()
+ return True
+
+
+def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, timeout=REQUEST_TIMEOUT_S) -> str:
+ """Send one one-string server→client request (``sudo``, ``secret``: ``ValueResult``) to the
+ session's attached viewers and wait for its ``value``; "" on skip, interrupt, timeout or no viewer."""
+ pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout)
+ return pending.value if pending is not None else ""
+
+
+def ask_viewer_result(events, session_id, method, params, *, cancelled=lambda: False, timeout=REQUEST_TIMEOUT_S,
+ qids=None):
+ """The same round trip for a structured answer (``clarify``: ``ClarifyResult``): the viewer's
+ ``result`` dict, or None on interrupt, timeout, an error response or no attached viewer.
+ ``qids`` makes it a batch, which always ends with ``{answers: <locked so far>, outcome}`` once
+ asked: ``lock_answer`` (the ``clarify.lock`` verb) answers it per question."""
+ pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout, qids=qids)
+ return pending.result if pending is not None else None
+
+
+def lock_answer(request_id, question_id, answer, *, session_ok=lambda session_id, events: False):
+ """Lock one answer of an open batch request (``clarify.lock``; editable until the last lock;
+ ``None`` = skipped). Returns the question ids still unanswered; the lock that empties it settles
+ the request with ``{answers, outcome: submitted}``. ``None`` when no open batch has that id or the
+ caller may not answer its session (expired, or another profile's / session's request: see
+ :func:`resolve`); ``ValueError`` for an unknown question id."""
+ with _lock:
+ pending = _open.get(request_id)
+ if pending is None or pending.qids is None or not session_ok(pending.session_id, pending.events):
+ return None
+ if question_id not in pending.qids:
+ raise ValueError(question_id)
+ pending.locked[question_id] = answer
+ remaining = [qid for qid in pending.qids if qid not in pending.locked]
+ if not remaining:
+ _open.pop(request_id, None)
+ pending.result = settle_batch(pending.locked, ended="submitted")
+ if not remaining:
+ pending.event.set()
+ return remaining
+
+
+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)
+ with _lock:
+ _open[request_id] = pending
+ events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": method,
+ "params": {"session_id": session_id, **params}})
+ waited = 0.0
+ reason = "timeout"
+ while not pending.event.wait(_POLL_S):
+ waited += _POLL_S
+ if cancelled():
+ reason = "interrupted"
+ break
+ if timeout is not None and waited >= timeout:
+ break
+ with _lock:
+ still_open = _open.pop(request_id, None) is pending
+ if still_open and pending.qids is not None:
+ # A batch keeps every answer locked before the wait ended (main's sidecar: "locked
+ # answers survive a timeout"); sudo/secret have no question ids and stay unanswered.
+ pending.result = settle_batch(pending.locked,
+ ended="cancelled" if reason == "interrupted" else "timed_out")
+ if still_open:
+ # The same teardown main's renderers key on (``request.cancel``): the card closes and a
+ # timed-out password prompt says so.
+ with contextlib.suppress(Exception):
+ events.publish(session_id, {"id": request_id, "method": method, "reason": reason},
+ event_type="request.cancel")
+ return pending if pending.qids is not None else None
+ # Settled by a viewer (a response frame or the last ``clarify.lock``): every OTHER viewer still
+ # shows the card, and a classic CLI is parked inside its modal callback. Withdraw it everywhere
+ # with ``reason: resolved`` (``RequestCancelReason``) so each renderer closes the matching card and
+ # the CLI's connection thread releases its modal (``hermes_cli.gateway_agent``). No answer rides it.
+ with contextlib.suppress(Exception):
+ events.publish(session_id, {"id": request_id, "method": method, "reason": "resolved"},
+ event_type="request.cancel")
+ return pending
diff --git a/gateway/session_sudo_prompt.py b/gateway/session_sudo_prompt.py
index 701f2ed6f59..d6c9837b639 100644
--- a/gateway/session_sudo_prompt.py
+++ b/gateway/session_sudo_prompt.py
@@ -7,180 +7,25 @@ took the headless path (``sudo: a terminal is required``). Here the owner sends
request frame (``tui_gateway/contracts/server_requests.py``) to the viewers attached to the session's
event stream and blocks the agent thread until one answers, the turn is interrupted, or it times out.
The password is never published, journaled or logged: it travels only in the viewer's response frame.
+The request registry itself is ``gateway/session_server_requests.py``.
"""
from __future__ import annotations
import contextlib
import logging
-import threading
-import uuid
-
-from tools.clarify_batch import settle_batch
logger = logging.getLogger(__name__)
SUDO_TIMEOUT_S = 120 # main: ``_ask("sudo", ..., timeout=120)``
-_POLL_S = 0.25
-
-
-class _Pending:
- __slots__ = ("event", "events", "locked", "qids", "result", "session_id", "value")
-
- def __init__(self, session_id, qids=None, events=None):
- self.event = threading.Event()
- self.session_id = session_id
- # 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
- self.value = ""
- self.result = None
- # A batch clarify: its question ids and the answers ``clarify.lock`` has locked so far.
- self.qids = tuple(qids) if qids else None
- self.locked = {}
-
-
-_lock = threading.Lock()
-_open: dict[str, _Pending] = {}
-
-
-def owned_by(authority, session_id, events) -> bool:
- """True when *authority*'s live *session_id* is the very stream a request was sent on."""
- live = authority.sessions.get(session_id)
- return live is not None and events is not None and live.event_stream is events
-
-
-def may_settle(authority, actor, session_id, events) -> bool:
- """The one rule for who may settle an owner request (a response frame or ``clarify.lock``): the
- request went out on *authority*'s own live stream for that session (session ids repeat across
- profiles and ``_open`` is process-wide), *actor* holds ``session:respond`` there, and *actor* is
- attached to that session, the same set of connections the request frame was written to."""
- from gateway.session_contract import SessionRef
- from hermes_state_runtime import RuntimeStoreError
- if not owned_by(authority, session_id, events):
- return False
- try:
- authority.authorize(actor, SessionRef(authority.profile_id, session_id), "session:respond")
- except RuntimeStoreError:
- return False
- live = authority.sessions.get(session_id)
- return live is not None and actor in live.subscribers.values()
-
-
-def is_response_frame(frame) -> bool:
- """A viewer's answer to one of the owner's requests: a string ``srq-`` id, a result/error, no method."""
- return (isinstance(frame, dict) and "method" not in frame and isinstance(frame.get("id"), str)
- and frame["id"].startswith("srq-") and ("result" in frame or "error" in frame))
-
-
-def resolve(frame, *, session_ok=lambda session_id, events: True) -> bool:
- """Settle the open request *frame* answers; False when nothing (here) waits for that id.
- ``session_ok(session_id, events)`` lets the caller refuse an answer from a connection not entitled
- to that session: the caller's own authority must own ``events``, the stream the request was sent on
- (session ids are only unique per profile, and ``_open`` is process-wide)."""
- with _lock:
- pending = _open.get(frame["id"])
- if pending is None or not session_ok(pending.session_id, pending.events):
- return False
- _open.pop(frame["id"], None)
- locked = dict(pending.locked) if pending.qids is not None else None
- result = frame.get("result") if "error" not in frame else None
- if locked is not None:
- # One rule with main's sidecar registry: the frame's answers over the locks, or a cancel-all.
- result = settle_batch(locked, result)
- value = result.get("value") if isinstance(result, dict) else ""
- pending.value = value if isinstance(value, str) else ""
- pending.result = result if isinstance(result, dict) else None
- pending.event.set()
- return True
def ask_sudo(events, session_id, command, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S) -> str:
"""Send one ``sudo`` request to the session's attached viewers and wait for its ``value``.
"" when nobody is attached, the viewer skipped, the turn was interrupted, or it timed out."""
+ from gateway.session_server_requests import ask_viewer
return ask_viewer(events, session_id, "sudo", {"command": command}, cancelled=cancelled, timeout=timeout)
-def ask_viewer(events, session_id, method, params, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S) -> str:
- """Send one one-string server→client request (``sudo``, ``secret``: ``ValueResult``) to the
- session's attached viewers and wait for its ``value``; "" on skip, interrupt, timeout or no viewer."""
- pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout)
- return pending.value if pending is not None else ""
-
-
-def ask_viewer_result(events, session_id, method, params, *, cancelled=lambda: False, timeout=SUDO_TIMEOUT_S,
- qids=None):
- """The same round trip for a structured answer (``clarify``: ``ClarifyResult``): the viewer's
- ``result`` dict, or None on interrupt, timeout, an error response or no attached viewer.
- ``qids`` makes it a batch, which always ends with ``{answers: <locked so far>, outcome}`` once
- asked: ``lock_answer`` (the ``clarify.lock`` verb) answers it per question."""
- pending = _ask(events, session_id, method, params, cancelled=cancelled, timeout=timeout, qids=qids)
- return pending.result if pending is not None else None
-
-
-def lock_answer(request_id, question_id, answer, *, session_ok=lambda session_id, events: False):
- """Lock one answer of an open batch request (``clarify.lock``; editable until the last lock;
- ``None`` = skipped). Returns the question ids still unanswered; the lock that empties it settles
- the request with ``{answers, outcome: submitted}``. ``None`` when no open batch has that id or the
- caller may not answer its session (expired, or another profile's / session's request: see
- :func:`resolve`); ``ValueError`` for an unknown question id."""
- with _lock:
- pending = _open.get(request_id)
- if pending is None or pending.qids is None or not session_ok(pending.session_id, pending.events):
- return None
- if question_id not in pending.qids:
- raise ValueError(question_id)
- pending.locked[question_id] = answer
- remaining = [qid for qid in pending.qids if qid not in pending.locked]
- if not remaining:
- _open.pop(request_id, None)
- pending.result = settle_batch(pending.locked, ended="submitted")
- if not remaining:
- pending.event.set()
- return remaining
-
-
-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)
- with _lock:
- _open[request_id] = pending
- events.fanout.write({"jsonrpc": "2.0", "id": request_id, "method": method,
- "params": {"session_id": session_id, **params}})
- waited = 0.0
- reason = "timeout"
- while not pending.event.wait(_POLL_S):
- waited += _POLL_S
- if cancelled():
- reason = "interrupted"
- break
- if timeout is not None and waited >= timeout:
- break
- with _lock:
- still_open = _open.pop(request_id, None) is pending
- if still_open and pending.qids is not None:
- # A batch keeps every answer locked before the wait ended (main's sidecar: "locked
- # answers survive a timeout"); sudo/secret have no question ids and stay unanswered.
- pending.result = settle_batch(pending.locked,
- ended="cancelled" if reason == "interrupted" else "timed_out")
- if still_open:
- # The same teardown main's renderers key on (``request.cancel``): the card closes and a
- # timed-out password prompt says so.
- with contextlib.suppress(Exception):
- events.publish(session_id, {"id": request_id, "method": method, "reason": reason},
- event_type="request.cancel")
- return pending if pending.qids is not None else None
- # Settled by a viewer (a response frame or the last ``clarify.lock``): every OTHER viewer still
- # shows the card, and a classic CLI is parked inside its modal callback. Withdraw it everywhere
- # with ``reason: resolved`` (``RequestCancelReason``) so each renderer closes the matching card and
- # the CLI's connection thread releases its modal (``hermes_cli.gateway_agent``). No answer rides it.
- with contextlib.suppress(Exception):
- events.publish(session_id, {"id": request_id, "method": method, "reason": "resolved"},
- event_type="request.cancel")
- return pending
-
-
@contextlib.contextmanager
def sudo_prompt_scope(turn, agent):
"""Install the sudo callback on this (agent) thread for a local viewer's turn; restore after."""
diff --git a/tests/gateway/test_clarify_batch_settlement_parity.py b/tests/gateway/test_clarify_batch_settlement_parity.py
index 01759263410..f632ff7f83d 100644
--- a/tests/gateway/test_clarify_batch_settlement_parity.py
+++ b/tests/gateway/test_clarify_batch_settlement_parity.py
@@ -1,6 +1,6 @@
"""One settlement rule for a batch clarify, whichever registry holds it.
-Main's sidecar (``tui_gateway/server_requests.py``) and the session owner (``gateway/session_sudo_prompt.py``)
+Main's sidecar (``tui_gateway/server_requests.py``) and the session owner (``gateway/session_server_requests.py``)
each keep open server→client requests, and each used to compute a batch's terminal ``{answers, outcome}``
in its own code, which drifted twice (#140472 review). Both now call ``tools.clarify_batch.settle_batch``.
These cases drive each real registry through the same ending, one ``clarify.lock`` on ``q0`` first, and
@@ -67,7 +67,7 @@ def _sidecar(monkeypatch, ending):
def _owner(ending):
from gateway.session_events import SessionEvents
- from gateway.session_sudo_prompt import ask_viewer_result, lock_answer, resolve
+ from gateway.session_server_requests import ask_viewer_result, lock_answer, resolve
class Peer:
frames = []
diff --git a/tests/gateway/test_clarify_lock_owner.py b/tests/gateway/test_clarify_lock_owner.py
index 8a561659037..b21d7ef7e24 100644
--- a/tests/gateway/test_clarify_lock_owner.py
+++ b/tests/gateway/test_clarify_lock_owner.py
@@ -97,7 +97,7 @@ async def test_clarify_lock_answers_the_owner_batch_request(tmp_path, monkeypatc
@pytest.mark.asyncio
async def test_a_viewer_without_the_session_cannot_lock_its_answers(tmp_path, monkeypatch):
from gateway.session_controls import AuthorityConnection
- from gateway.session_sudo_prompt import resolve
+ from gateway.session_server_requests import resolve
async def answer(event):
return 'ok'
@@ -138,7 +138,7 @@ async def test_another_profiles_viewer_of_the_same_session_id_cannot_answer(tmp_
with ``session:respond`` must not lock or answer profile A's request, through ``clarify.lock`` or a
raw response frame."""
from gateway.session_controls import AuthorityConnection
- from gateway.session_sudo_prompt import _open
+ from gateway.session_server_requests import _open
async def answer(event):
return 'ok'
@@ -200,7 +200,7 @@ async def test_clarify_lock_params_are_checked_by_the_declared_canonical_contrac
@pytest.mark.asyncio
async def test_an_unattached_connection_cannot_settle_the_batch_with_a_raw_response_frame(tmp_path, monkeypatch):
"""``clarify.lock`` and the closing response frame are two ways to settle the same request id: both go
- through one entitlement rule (``session_sudo_prompt.may_settle``), so a same-profile connection that
+ through one entitlement rule (``session_server_requests.may_settle``), so a same-profile connection that
never attached the session can no more close the batch with a frame than lock one of its answers."""
from gateway.session_controls import AuthorityConnection
@@ -214,7 +214,7 @@ async def test_an_unattached_connection_cannot_settle_the_batch_with_a_raw_respo
peer, worker, out = _start_batch(authority)
await _wait_for(lambda: any(f.get('method') == 'clarify' for f in peer.frames))
rid = next(f['id'] for f in peer.frames if f.get('method') == 'clarify')
- from gateway.session_sudo_prompt import _open
+ from gateway.session_server_requests import _open
# ``dispatch`` settles a response frame synchronously: still open afterwards means refused.
await outsider.dispatch({'jsonrpc': '2.0', 'id': rid, 'result': {'answers': {'q0': 'X', 'q1': 'X'}}})
assert rid in _open and not _open[rid].event.is_set() and out == {}, out
diff --git a/tests/gateway/test_local_desktop_ui.py b/tests/gateway/test_local_desktop_ui.py
index c765c7a4bcf..4d5aedf5e1c 100644
--- a/tests/gateway/test_local_desktop_ui.py
+++ b/tests/gateway/test_local_desktop_ui.py
@@ -10,7 +10,7 @@ from types import SimpleNamespace
import pytest
-from gateway import local_desktop_ui, local_viewer_events, session_sudo_prompt
+from gateway import local_desktop_ui, local_viewer_events, session_server_requests
from gateway.session_context import clear_session_vars, set_session_vars
from tools import desktop_ui
from tools.process_registry import process_registry
@@ -39,7 +39,7 @@ class _Fanout:
def write(self, frame, **_kw):
self.requests.append(frame)
if frame.get("method") in _ANSWERS and frame["method"] not in self.silent:
- session_sudo_prompt.resolve({"id": frame["id"], "result": _ANSWERS[frame["method"]]})
+ session_server_requests.resolve({"id": frame["id"], "result": _ANSWERS[frame["method"]]})
return True
diff --git a/tests/gateway/test_local_viewer_clarify_batch.py b/tests/gateway/test_local_viewer_clarify_batch.py
index 9019109215e..9271dffbc9b 100644
--- a/tests/gateway/test_local_viewer_clarify_batch.py
+++ b/tests/gateway/test_local_viewer_clarify_batch.py
@@ -42,7 +42,7 @@ QUESTIONS = [{'qid': 'q0', 'question': 'colour?', 'choices': ['red', 'blue'], 'm
def test_batch_is_one_request_and_the_panels_answers_return(monkeypatch):
from gateway.session_clarify_batch import ask_clarify_batch
- from gateway.session_sudo_prompt import resolve
+ from gateway.session_server_requests import resolve
turn, peer = _turn()
out = {}
worker = threading.Thread(target=lambda: out.update(ask_clarify_batch(turn, QUESTIONS)))
diff --git a/tests/gateway/test_local_viewer_secret_prompt.py b/tests/gateway/test_local_viewer_secret_prompt.py
index ccbe52c3b2f..b26d6595a6e 100644
--- a/tests/gateway/test_local_viewer_secret_prompt.py
+++ b/tests/gateway/test_local_viewer_secret_prompt.py
@@ -40,7 +40,7 @@ def _wait_for(predicate, timeout=5.0):
def _answer_when_asked(peer, value):
- from gateway.session_sudo_prompt import resolve
+ from gateway.session_server_requests import resolve
_wait_for(lambda: any(f.get('method') == 'secret' for f in peer.frames))
request = next(f for f in peer.frames if f.get('method') == 'secret')
resolve({'jsonrpc': '2.0', 'id': request['id'], 'result': {'value': value}})
diff --git a/tests/gateway/test_local_viewer_sudo_prompt.py b/tests/gateway/test_local_viewer_sudo_prompt.py
index b4e79e857d6..843469d8c00 100644
--- a/tests/gateway/test_local_viewer_sudo_prompt.py
+++ b/tests/gateway/test_local_viewer_sudo_prompt.py
@@ -37,7 +37,8 @@ def _wait_for(predicate, timeout=5.0):
def test_sudo_request_reaches_the_viewer_and_its_answer_returns():
- from gateway.session_sudo_prompt import ask_sudo, is_response_frame, resolve
+ from gateway.session_server_requests import is_response_frame, resolve
+ from gateway.session_sudo_prompt import ask_sudo
events, peer = _events()
out = {}
worker = threading.Thread(target=lambda: out.setdefault('value', ask_sudo(events, 's1', 'sudo true')))
@@ -92,7 +93,7 @@ def test_scope_installs_the_callback_only_for_local_viewer_turns(platform, insta
@pytest.mark.asyncio
async def test_the_viewer_response_frame_is_routed_by_the_authority_connection(tmp_path, monkeypatch):
- from gateway import session_sudo_prompt
+ from gateway import session_server_requests
from gateway.session_controls import AuthorityConnection
from tests.gateway.test_surface_admission import _authority
@@ -102,12 +103,12 @@ async def test_the_viewer_response_frame_is_routed_by_the_authority_connection(t
connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
# Only a viewer attached to the session gets the request frame, and only it may answer.
await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})
- pending = session_sudo_prompt._Pending('s', events=authority.sessions['s'].event_stream)
- session_sudo_prompt._open['srq-abc'] = pending
+ pending = session_server_requests._Pending('s', events=authority.sessions['s'].event_stream)
+ session_server_requests._open['srq-abc'] = pending
try:
reply = await connection.dispatch({'jsonrpc': '2.0', 'id': 'srq-abc', 'result': {'value': 'pw'}})
assert reply is None
assert pending.event.is_set() and pending.value == 'pw'
finally:
- session_sudo_prompt._open.pop('srq-abc', None)
+ session_server_requests._open.pop('srq-abc', None)
await connection.close()
diff --git a/tools/clarify_batch.py b/tools/clarify_batch.py
index 0cb8edf495e..6b5e52804f7 100644
--- a/tools/clarify_batch.py
+++ b/tools/clarify_batch.py
@@ -3,7 +3,7 @@
A batch (``clarify`` server request with question ids) is answered per question with ``clarify.lock``
and ends one of four ways: the last lock, a closing response frame, a timeout, or an interrupt/cancel.
Main's TUI sidecar (``tui_gateway/server_requests.py``) and the session owner
-(``gateway/session_sudo_prompt.py``) both settle batches; each used to compute ``{answers, outcome}``
+(``gateway/session_server_requests.py``) both settle batches; each used to compute ``{answers, outcome}``
itself and they drifted. Both call :func:`settle_batch`, so the model is told the same thing on every
surface.
"""