Skip to content

The agent that grows with you

fix(gateway): refuse a hosted room file on a route that cannot carry it

unsupportedpastelsb97ac0415f8c
diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.py
index da9c8e13693..5ada51e5fc3 100644
--- a/gateway/session_hosted_rpc.py
+++ b/gateway/session_hosted_rpc.py
@@ -21,6 +21,8 @@ _RESULTS_BUDGET_BYTES = 384 * 1024
class HostedRoomAuthorityRPC:
+ accepts_attachments = True # submit resolves event-bound bytes per member
+
def __init__(self, authority, loop, *, room_id, member_id, profile, principal,
authorize, authorize_write=None, timeout=30):
self.authority, self.loop = authority, loop
diff --git a/tests/gateway/test_hosted_room_runtime_attachments.py b/tests/gateway/test_hosted_room_runtime_attachments.py
new file mode 100644
index 00000000000..b821af2f52c
--- /dev/null
+++ b/tests/gateway/test_hosted_room_runtime_attachments.py
@@ -0,0 +1,72 @@
+"""The canonical authority route still carries a member turn's bound file end to end."""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+from gateway import hosted_room_driver as state
+from gateway import hosted_rooms
+from gateway.hosted_room_attachments import HostedRoomAttachmentStore
+from gateway.session_hosted_rpc import HostedRoomAuthorityRPC
+from hermes_state_runtime import list_session_admissions
+from tui_gateway.hosted_room_driver import HostedRoomBinding, HostedRoomRuntime
+
+
+def _wait_for(predicate, *, timeout: float = 10.0) -> None:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if predicate():
+ return
+ time.sleep(0.01)
+ raise AssertionError("condition was not reached before timeout")
+
+
+def test_authority_route_admits_a_member_turn_with_its_file(hosted_owner, tmp_path):
+ authority, loop, principal, _ = hosted_owner
+ binding = HostedRoomBinding(room_id="room", gateway_id="gateway-a", authority_epoch=1)
+ room_db = tmp_path / "rooms.db"
+ hosted_rooms.create_room(
+ room_db, room_id="room", name="Release room",
+ members=[{"profile": "default", "handle": "default"}],
+ authority_gateway_id=binding.gateway_id, now=time.time())
+ store = HostedRoomAttachmentStore(authority.db.db_path)
+ saved = store.put(room_id="room", upload_id="upload", kind="file", name="note.txt",
+ mime="text/plain", data=b"exact bytes")
+ manifest = [{k: saved[k] for k in ("attachment_id", "kind", "name", "size", "mime")}]
+ store.commit_message(room_id="room", event_id="event", manifest=manifest,
+ recipient_member_ids=["member"])
+ identity = state.TaskIdentity("room", "task", "thread", "turn")
+ state.admit_task(room_db, identity, payload={
+ "target_profile": "default", "target_member_id": "member", "prompt": "read",
+ "source_event_seq": 1, "attachments": [{**manifest[0], "event_id": "event"}]},
+ clock=time.time)
+ rpc = HostedRoomAuthorityRPC(authority, loop, room_id="room", member_id="member",
+ profile="default", principal=principal,
+ authorize=lambda *args: True)
+ runtime = HostedRoomRuntime(
+ db_path=room_db, rooms=[binding], rpc=rpc, turn_lock=lambda _profile: _NullLock(),
+ lease_ttl_seconds=0.4, poll_interval_seconds=0.01)
+
+ runtime.start()
+ try:
+ _wait_for(lambda: rpc.callbacks or runtime.status()["last_error"] is not None)
+ finally:
+ assert runtime.stop(timeout=5.0)
+
+ # Admitted with the bytes resolved, and still running: no refusal on this route.
+ assert runtime.status()["last_error"] is None
+ assert state.get_task(room_db, identity)["status"] == "running"
+ sid = rpc.resolve_exact(profile="default", title="Group: room", source="bot_room")["session_id"]
+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)
+ assert len(rows) == 1
+ path = Path(rows[0]["payload"]["text"].split("file: ")[1].split("\n")[0])
+ assert path.read_bytes() == b"exact bytes"
+
+
+class _NullLock:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
diff --git a/tests/tui_gateway/test_hosted_room_attachment_routes.py b/tests/tui_gateway/test_hosted_room_attachment_routes.py
new file mode 100644
index 00000000000..9b7492a421b
--- /dev/null
+++ b/tests/tui_gateway/test_hosted_room_attachment_routes.py
@@ -0,0 +1,207 @@
+"""A member turn with a bound file must not reach a route that cannot carry it.
+
+Only the canonical authority route resolves event-bound attachment bytes. The legacy
+in-process route (`HostedRoomServerRPC`) and the peer route (`PeerHostedRoomTransport`)
+never declared `attachments`, so the driver's submit raised `TypeError` after it had
+marked the attempt submitted: the task was booked ambiguous and stayed `running`.
+The driver now refuses such a turn before submitting, as a proven failure.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import hosted_room_driver as state
+from gateway import hosted_rooms
+from tests.tui_gateway.test_hosted_room_driver_runtime import (
+ BINDING,
+ PROFILE,
+ ROOM_ID,
+ RecordingTurnLocks,
+ _identity,
+ _wait_for,
+)
+from tui_gateway.hosted_room_driver import HostedRoomRuntime
+from tui_gateway.hosted_room_peer_transport import PeerHostedRoomTransport, PeerMemberRoute
+from tui_gateway.hosted_room_server_rpc import HostedRoomServerRPC
+
+
+ATTACHMENTS = [{
+ "attachment_id": "att_" + "0" * 32,
+ "kind": "file",
+ "name": "note.txt",
+ "size": 11,
+ "mime": "text/plain",
+ "event_id": "event-1",
+}]
+
+
+def db(tmp_path: Path) -> Path:
+ path = tmp_path / "state.db"
+ hosted_rooms.create_room(
+ path,
+ room_id=ROOM_ID,
+ name="Release room",
+ members=[{"profile": PROFILE, "handle": PROFILE}],
+ authority_gateway_id=BINDING.gateway_id,
+ now=time.time(),
+ )
+ return path
+
+
+def _admit(db: Path, *, attachments=None) -> state.TaskIdentity:
+ identity = _identity()
+ payload = {
+ "target_profile": PROFILE,
+ "target_member_id": "member-ops",
+ "prompt": "Read the attached note.",
+ "source_event_seq": 1,
+ }
+ if attachments is not None:
+ payload["attachments"] = attachments
+ state.admit_task(db, identity, payload=payload, clock=time.time)
+ return identity
+
+
+def _run_until_settled_or_error(runtime: HostedRoomRuntime, db: Path, identity) -> dict:
+ runtime.start()
+ try:
+ _wait_for(lambda: (
+ state.get_task(db, identity)["status"] in state.TERMINAL_STATUSES
+ or runtime.status()["last_error"] is not None))
+ finally:
+ assert runtime.stop(timeout=5.0)
+ return state.get_task(db, identity)
+
+
+def _server_module():
+ """The installed server surface `HostedRoomServerRPC` normalizes; turns finish at once."""
+ submits = []
+
+ def ok(result):
+ return lambda rid, params: {"id": rid, "result": result}
+
+ def prompt_submit(rid, params):
+ submits.append(params)
+ params["_hosted_terminal_callback"]({"status": "settled", "text": "Read it."})
+ return {"id": rid, "result": {"status": "streaming"}}
+
+ server = SimpleNamespace(
+ _methods={
+ "session.list": ok({"sessions": []}),
+ "session.create": ok({"session_id": "runtime"}),
+ "session.resume": ok({"session_id": "runtime"}),
+ "session.history": ok({"messages": []}),
+ "prompt.submit": prompt_submit,
+ },
+ _sessions={},
+ _sessions_lock=threading.Lock(),
+ _pending_approval_request_payload=lambda _session_key: None,
+ )
+ return server, submits
+
+
+def _legacy_runtime(db: Path, rpc: HostedRoomServerRPC) -> HostedRoomRuntime:
+ return HostedRoomRuntime(
+ db_path=db, rooms=[BINDING], rpc=rpc, turn_lock=RecordingTurnLocks(),
+ lease_ttl_seconds=0.4, poll_interval_seconds=0.01)
+
+
+class DispatchingPeerClient:
+ """Peer client whose member settles every dispatched turn immediately."""
+
+ def __init__(self) -> None:
+ self.dispatches = []
+
+ def prepare(self, **_kwargs):
+ return {"session_id": "peer-session"}
+
+ def dispatch(self, *, dispatch, grant):
+ self.dispatches.append(dispatch)
+ return {"status": "settled", "text": "Read it."}
+
+ def status(self, **_kwargs):
+ return {"active": False}
+
+ def history(self, **_kwargs):
+ return []
+
+ def stop(self, **_kwargs):
+ return {"status": "stopping"}
+
+
+def _peer_runtime(db: Path, client: DispatchingPeerClient) -> HostedRoomRuntime:
+ route = PeerMemberRoute(
+ home_install_id="install-home", member_id="member-ops", target_install_id="install-peer",
+ target_profile=PROFILE, capability_digest="a" * 64, execution_policy_digest="b" * 64,
+ cancellation_scope_id="cancel-peer", trace_id="trace-peer", grant="signed-room-grant")
+
+ def resolve(binding, task):
+ return PeerHostedRoomTransport(
+ binding=binding, route=route, client=client,
+ source_event_seq=int(task["payload"]["source_event_seq"]),
+ task_id=task["identity"].task_id,
+ execution_generation=int(task["execution_generation"]))
+
+ return HostedRoomRuntime(
+ db_path=db, rooms=[BINDING], transport_resolver=resolve, turn_lock=RecordingTurnLocks(),
+ lease_ttl_seconds=0.4, poll_interval_seconds=0.01)
+
+
+def _assert_refused_as_proven_failure(task: dict, runtime: HostedRoomRuntime) -> None:
+ assert task["status"] == "failed", (task["status"], runtime.status()["last_error"])
+ assert task["result"]["error"].startswith("attachments_unsupported_on_route")
+ assert "attachments_unsupported_on_route" in runtime.status()["last_error"]
+ assert runtime.status()["blocked_rooms"] == ()
+
+
+def test_legacy_route_refuses_a_turn_with_a_file_before_submitting(db: Path):
+ identity = _admit(db, attachments=ATTACHMENTS)
+ server, submits = _server_module()
+ runtime = _legacy_runtime(db, HostedRoomServerRPC(server))
+
+ task = _run_until_settled_or_error(runtime, db, identity)
+
+ _assert_refused_as_proven_failure(task, runtime)
+ assert submits == []
+
+
+def test_legacy_route_still_runs_a_turn_without_a_file(db: Path):
+ identity = _admit(db)
+ server, submits = _server_module()
+ runtime = _legacy_runtime(db, HostedRoomServerRPC(server))
+
+ task = _run_until_settled_or_error(runtime, db, identity)
+
+ assert task["status"] == "settled", runtime.status()["last_error"]
+ assert task["result"]["text"] == "Read it."
+ assert [s["_hosted_task"]["member_id"] for s in submits] == ["member-ops"]
+
+
+def test_peer_route_refuses_a_turn_with_a_file_before_dispatching(db: Path):
+ identity = _admit(db, attachments=ATTACHMENTS)
+ client = DispatchingPeerClient()
+ runtime = _peer_runtime(db, client)
+
+ task = _run_until_settled_or_error(runtime, db, identity)
+
+ _assert_refused_as_proven_failure(task, runtime)
+ assert client.dispatches == []
+
+
+def test_peer_route_still_runs_a_turn_without_a_file(db: Path):
+ identity = _admit(db)
+ client = DispatchingPeerClient()
+ runtime = _peer_runtime(db, client)
+
+ task = _run_until_settled_or_error(runtime, db, identity)
+
+ assert task["status"] == "settled", runtime.status()["last_error"]
+ assert task["result"]["text"] == "Read it."
+ assert len(client.dispatches) == 1
diff --git a/tui_gateway/hosted_room_driver.py b/tui_gateway/hosted_room_driver.py
index 07fba67ea6d..1ceb1046eb4 100644
--- a/tui_gateway/hosted_room_driver.py
+++ b/tui_gateway/hosted_room_driver.py
@@ -30,13 +30,20 @@ _TERMINAL_TRUNCATION_NOTICE = (
_STOP_PENDING = "stop retry remains pending: {exc}"
+class AttachmentsUnsupportedError(RuntimeError):
+ """The member's route cannot carry the turn's files; refused before submit."""
+
+
class InternalSessionRPC(Protocol):
"""Normalized in-process session operations required by the room driver.
``submit`` durably reports one fenced turn's terminal result via ``on_terminal``;
``interrupt`` acts only while the current turn still matches ``expected_task_id``.
+ Only a transport with ``accepts_attachments`` is handed a turn's bound files.
"""
+ accepts_attachments: bool = False
+
def resolve_exact(
self, *, profile: str, title: str, source: str) -> Mapping[str, Any] | None: ...
def create(self, *, profile: str, title: str, source: str) -> Mapping[str, Any]: ...
@@ -44,6 +51,7 @@ class InternalSessionRPC(Protocol):
def submit(
self, *, profile: str, session_id: str, prompt: str, source: str, task: state.TaskIdentity,
execution_generation: int, on_terminal: Callable[[Mapping[str, Any]], None], member_id: str,
+ attachments: Sequence[Mapping[str, Any]] | None = None,
) -> Mapping[str, Any]: ...
def history(
self, *, profile: str, session_id: str, source: str) -> Sequence[Mapping[str, Any]]: ...
@@ -580,10 +588,17 @@ class HostedRoomRuntime:
self, binding: HostedRoomBinding, task: Mapping[str, Any], attempt: state.TaskAttempt
) -> None:
profile, submit_attempted = task["payload"]["target_profile"], False
+ attachments = task["payload"].get("attachments")
transport = self._transport_for(binding, task)
with self._status_lock:
self._current_tasks[binding.room_id] = attempt.identity
try:
+ if attachments and not getattr(transport, "accepts_attachments", False):
+ # A route that cannot carry the files would answer without them, and a
+ # retry cannot change the route: settle a proven failure before submit.
+ raise AttachmentsUnsupportedError(
+ "attachments_unsupported_on_route: this member's route cannot carry "
+ "attached files")
with self.turn_lock(profile):
session = self._resolve_or_create(transport, profile, binding.room_id)
# A submit should fail before admission or return after it; an unexpected
@@ -593,7 +608,7 @@ class HostedRoomRuntime:
transport.submit(
**_session_kw(profile, session_id), prompt=task["payload"]["prompt"],
task=attempt.identity, execution_generation=attempt.execution_generation,
- **({"attachments": task["payload"]["attachments"]} if task["payload"].get("attachments") else {}),
+ **({"attachments": attachments} if attachments else {}),
member_id=_member_id(task),
on_terminal=lambda receipt: self._on_terminal(binding, attempt, receipt))
self._unavailable_route_retries.pop(
diff --git a/tui_gateway/hosted_room_peer_transport.py b/tui_gateway/hosted_room_peer_transport.py
index c352e6c9856..b0319c46107 100644
--- a/tui_gateway/hosted_room_peer_transport.py
+++ b/tui_gateway/hosted_room_peer_transport.py
@@ -136,6 +136,8 @@ def build_member_dispatch(
class PeerHostedRoomTransport(InternalSessionRPC):
"""Translate runtime session operations into recipient-validated peer RPC."""
+ accepts_attachments = False # a member dispatch has no field for files
+
def __init__(
self, *, binding: HostedRoomBinding, route: PeerMemberRoute,
client: HostedRoomPeerClient, source_event_seq: int = 1, task_id: str | None = None,
diff --git a/tui_gateway/hosted_room_server_rpc.py b/tui_gateway/hosted_room_server_rpc.py
index 38578592a36..a0f9b68d625 100644
--- a/tui_gateway/hosted_room_server_rpc.py
+++ b/tui_gateway/hosted_room_server_rpc.py
@@ -27,6 +27,8 @@ class HostedRoomSessionError(RuntimeError):
class HostedRoomServerRPC:
"""Normalize the installed server handlers for :class:`HostedRoomRuntime`."""
+ accepts_attachments = False # prompt.submit here has no event-bound file resolution
+
def __init__(self, server: ModuleType) -> None:
self.server = server
self._ids = itertools.count(1)