Skip to content

The agent that grows with you

fix(groups): the standalone backend forwards every room method the gateway serves

Teknium95762e286ddb
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 41613fa880c..7304508a7f9 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4599,6 +4599,17 @@ export interface RoomAttachmentBytes {
data_base64: string
[key: string]: unknown
}
+export interface GroupsDiscardParams {
+ profile?: string | null
+ room_id: string
+ member_id: string
+ task_id: string
+ execution_generation: number
+}
+export interface GroupsDiscardResult {
+ discarded?: boolean
+ task: RoomTaskReceipt
+}
export interface CanonicalShellExecParams {
session_id: string
command: string
@@ -4940,17 +4951,6 @@ export interface WorkerPersistParams {
}
/** The operation's durable receipt (``message_id`` for an append, delegation results, …). */
export type WorkerPersistResult = Record<string, unknown>
-export interface GroupsDiscardParams {
- profile?: string | null
- room_id: string
- member_id: string
- task_id: string
- execution_generation: number
-}
-export interface GroupsDiscardResult {
- discarded?: boolean
- task: RoomTaskReceipt
-}
export interface CanonicalCreateParams {
profile?: string | null
request_id?: string | null
@@ -6165,6 +6165,8 @@ export interface RpcMethods {
'groups.demote': { params: GroupsDemoteParams; result: GroupsDemoteResult }
/** Permanently tombstone a hosted room id after stopping its work and revoking peer routes. */
'groups.disband': { params: GroupsDisbandParams; result: GroupsDisbandResult }
+ /** Discard one indeterminate room task after explicit user confirmation. */
+ 'groups.discard': { params: GroupsDiscardParams; result: GroupsDiscardResult }
/** List rooms hosted by this gateway, most recently changed first. */
'groups.list': { params: GroupsListParams; result: GroupsListResult }
/** A monotonic room-log delta after since_seq, bounded by count and page bytes. */
@@ -6614,6 +6616,7 @@ export const RPC_METHODS = [
'groups.create',
'groups.demote',
'groups.disband',
+ 'groups.discard',
'groups.list',
'groups.log',
'groups.peer.invite',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 5fd45a6dcb9..034adb4d690 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -1194,6 +1194,24 @@
}
}
},
+ {
+ "name": "groups.discard",
+ "summary": "Discard one indeterminate room task after explicit user confirmation.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsDiscardParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsDiscardResult"
+ }
+ }
+ },
{
"name": "groups.list",
"summary": "List rooms hosted by this gateway, most recently changed first.",
diff --git a/tests/tui_gateway/test_groups_forward_parity.py b/tests/tui_gateway/test_groups_forward_parity.py
new file mode 100644
index 00000000000..7a967780b55
--- /dev/null
+++ b/tests/tui_gateway/test_groups_forward_parity.py
@@ -0,0 +1,113 @@
+"""The standalone route reaches every room method the gateway route serves (#145960).
+
+A room handed to the gateway is fenced in the standalone store, so a room call this wire does
+not forward runs against the frozen copy and is refused ("managed by another gateway"). The
+forwarded set therefore follows the gateway route's own method table, never a hand list.
+"""
+
+from __future__ import annotations
+
+import base64
+import sqlite3
+from types import SimpleNamespace
+
+import pytest
+
+import tui_gateway.server as srv
+from tui_gateway import methods_groups, owner_forward
+
+MEMBERS = [{"member_id": "default", "profile": "default", "handle": "hermes"},
+ {"member_id": "ops", "profile": "ops", "handle": "ops"}]
+ENDPOINT = object()
+
+
+def home(tmp_path, monkeypatch):
+ path = tmp_path / ".hermes"
+ (path / "profiles" / "ops").mkdir(parents=True)
+ (path / "profiles" / "ops" / "config.yaml").write_text("{}\n")
+ monkeypatch.setenv("HERMES_HOME", str(path))
+ methods_groups.stop_hosted_room_service(timeout=1.0)
+ methods_groups.start_hosted_room_service()
+ yield path
+ methods_groups.stop_hosted_room_service(timeout=1.0)
+
+
+def _gateway(monkeypatch, state: str) -> None:
+ from hermes_cli import gateway_runtime
+
+ def discover(home, *, timeout=2.0):
+ return gateway_runtime.GatewayDiscovery(state, endpoint=ENDPOINT if state == "ready" else None)
+ monkeypatch.setattr(gateway_runtime, "discover_gateway_endpoint", discover)
+
+
+def _hand_room_to_gateway(monkeypatch):
+ """A Group Chat created on the standalone backend, then imported (and fenced) by the gateway."""
+ from gateway.hosted_rooms import default_db_path
+ from gateway.hosted_rooms_gateway_import import import_standalone_rooms
+ _gateway(monkeypatch, "absent")
+ created = srv._methods["groups.create"](1, {"room_id": "room-desk", "name": "Desk", "members": MEMBERS})
+ assert "error" not in created, created
+ target = default_db_path().with_name("state.db")
+ with sqlite3.connect(target) as conn:
+ conn.execute("CREATE TABLE IF NOT EXISTS state_meta (key TEXT PRIMARY KEY, value TEXT)")
+ assert import_standalone_rooms(target) == 1
+ _gateway(monkeypatch, "ready")
+ return target
+
+
+def test_every_gateway_room_method_reaches_the_owning_gateway(home, monkeypatch):
+ from gateway.session_group_controls import GROUP_METHODS
+ from tui_gateway.contracts.registry import METHODS
+ _hand_room_to_gateway(monkeypatch)
+ reached = []
+
+ def forward_rpc(home, endpoint, method, params):
+ reached.append(method)
+ return {"methods": list(GROUP_METHODS)} if method == "groups.capabilities" else {}
+ monkeypatch.setattr(owner_forward, "forward_rpc", forward_rpc)
+
+ for method in GROUP_METHODS:
+ assert method in METHODS, f"{method}: no contract on the standalone wire"
+ reply = srv._methods[method](1, {"room_id": "room-desk"})
+ assert "error" not in reply, (method, reply)
+ capabilities = srv._methods["groups.capabilities"](2, {})["result"]
+
+ assert reached[:len(GROUP_METHODS)] == list(GROUP_METHODS)
+ assert capabilities["methods"] == list(GROUP_METHODS) # what reaches the owner is advertised
+
+
+def test_a_file_attached_to_a_handed_room_lands_in_the_gateway_copy(home, monkeypatch):
+ from gateway.hosted_room_attachments import HostedRoomAttachmentStore
+ from gateway.hosted_rooms import default_db_path
+ from gateway.session_hosted_attachments import store_upload
+ target = _hand_room_to_gateway(monkeypatch)
+ calls = []
+
+ def forward_rpc(home, endpoint, method, params):
+ calls.append(method)
+ assert method == "groups.attachment.upload"
+ return store_upload(SimpleNamespace(db_path=target), params["room_id"], params) # the owner's store
+ monkeypatch.setattr(owner_forward, "forward_rpc", forward_rpc)
+
+ data = b"exact composer bytes"
+ reply = srv._methods["groups.attachment.upload"](1, {
+ "room_id": "room-desk", "upload_id": "upload-1", "kind": "file", "name": "note.txt",
+ "mime": "text/plain", "data_base64": base64.b64encode(data).decode("ascii")})
+
+ assert "error" not in reply, reply # main: "This Group Chat is managed by another gateway."
+ assert calls == ["groups.attachment.upload"]
+ held = HostedRoomAttachmentStore(target).find_upload(room_id="room-desk", upload_id="upload-1")
+ assert held is not None and held["attachment_id"] == reply["result"]["attachment_id"]
+ fenced = HostedRoomAttachmentStore(default_db_path()).find_upload(room_id="room-desk", upload_id="upload-1")
+ assert fenced is None # nothing was written to the frozen standalone copy
+
+
+def test_discard_on_a_room_this_backend_drives_is_refused_locally(home, monkeypatch):
+ _gateway(monkeypatch, "absent")
+ srv._methods["groups.create"](1, {"room_id": "room-desk", "name": "Desk", "members": MEMBERS})
+
+ reply = srv._methods["groups.discard"](2, {
+ "room_id": "room-desk", "member_id": "ops", "task_id": "task-1", "execution_generation": 1})
+
+ assert reply["error"]["code"] == 4127, reply
diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.py
index 43a5ce4a339..b4059786689 100644
--- a/tui_gateway/contracts/canonical.py
+++ b/tui_gateway/contracts/canonical.py
@@ -569,8 +569,10 @@ class GroupsDiscardResult(Result):
task: RoomTaskReceipt
-canonical_method("groups.discard", params=GroupsDiscardParams, result=GroupsDiscardResult,
- doc="Discard one indeterminate room task after explicit user confirmation.")
+_DISCARD_DOC = "Discard one indeterminate room task after explicit user confirmation."
+canonical_method("groups.discard", params=GroupsDiscardParams, result=GroupsDiscardResult, doc=_DISCARD_DOC)
+# The standalone route forwards it to the room's owning gateway (#145960), like the byte verbs.
+method("groups.discard", params=GroupsDiscardParams, result=GroupsDiscardResult, doc=_DISCARD_DOC)
# Shared-name overrides load after the authority-only value shapes above.
diff --git a/tui_gateway/methods_groups.py b/tui_gateway/methods_groups.py
index 9cc11e61c6c..b7922e58378 100644
--- a/tui_gateway/methods_groups.py
+++ b/tui_gateway/methods_groups.py
@@ -24,7 +24,8 @@ _METHODS = (
"groups.promote", "groups.demote", "groups.stop", "groups.retry", "groups.approve",
"groups.peer.invite", "groups.peer.revoke", "groups.peer.register", "groups.attachment.upload",
"groups.attachment.download")
-LONG_HANDLERS = frozenset(_METHODS)
+#: ``groups.discard`` is forwarded to an owning gateway only, so local capabilities never list it.
+LONG_HANDLERS = frozenset(_METHODS) | {"groups.discard"}
_service_lock = threading.Lock()
_run_store_lock = threading.Lock()
@@ -494,6 +495,13 @@ def _(rid, params: dict, service) -> dict:
return _ok(rid, {"retried": True, "task": receipt})
+@_room_method("groups.discard", code=5125)
+def _(rid, params: dict) -> dict:
+ """Discard one indeterminate room task: forwarded to the gateway that owns the room, the only
+ runtime that offers Discard; a room this backend drives itself never shows the action."""
+ return _err(rid, 4127, "Only the Hermes gateway that owns this Group Chat can discard its work.")
+
+
def _passthrough(
name: str, module: str, fn_name: str, doc: str, *, code: int, room_code: int,
params: tuple, replica_only: bool = False, wrap: str | None = None) -> None:
diff --git a/tui_gateway/methods_groups_forward.py b/tui_gateway/methods_groups_forward.py
index 5a96c7c03aa..63adf70d6d2 100644
--- a/tui_gateway/methods_groups_forward.py
+++ b/tui_gateway/methods_groups_forward.py
@@ -28,11 +28,13 @@ import logging
logger = logging.getLogger(__name__)
-#: The Desktop's room calls this wire serves; the gateway route serves each (GROUP_METHODS).
-FORWARDED = frozenset({
- "groups.capabilities", "groups.list", "groups.create", "groups.state", "groups.log",
- "groups.send", "groups.rename", "groups.disband", "groups.stop", "groups.retry",
- "groups.approve"})
+
+def forwarded() -> frozenset[str]:
+ """Every room method the gateway route serves (its ``GROUP_METHODS``), so a room the gateway
+ owns answers the same calls on this wire; a hand list here fell behind each new verb (#145960)."""
+ from gateway.session_group_controls import GROUP_METHODS
+ return frozenset(GROUP_METHODS)
+
#: The owner was found but did not answer: a verdict for this call, never a local write instead.
OWNER_LOST_CODE = 5124
#: Gateway states with no owner that will import rooms written here later: run the call locally.
@@ -131,8 +133,9 @@ def _call(server, rid, home, endpoint, method: str, params: dict) -> dict:
return server._err(rid, OWNER_LOST_CODE, "The Hermes gateway did not answer. Try again.")
result = result if isinstance(result, dict) else {}
if method == "groups.capabilities" and isinstance(result.get("methods"), list):
- # Advertise only what this wire can carry (attachments and Discard have no contract here).
- result = {**result, "methods": [name for name in result["methods"] if name in FORWARDED]}
+ # Advertise only what this wire can carry: the room methods it forwards.
+ carried = forwarded()
+ result = {**result, "methods": [name for name in result["methods"] if name in carried]}
return server._ok(rid, result)
@@ -144,7 +147,7 @@ def _busy(server, rid, why) -> dict:
def forward(server, rid, method: str, params: dict) -> dict | None:
"""The owning gateway's answer to ``method`` as this wire's envelope, or ``None`` when the call
runs locally: no gateway serves the profile, or the room lives only in the standalone store."""
- if method not in FORWARDED:
+ if method not in forwarded():
return None
try:
home = _home(server, params)
diff --git a/tui_gateway/owner_forward.py b/tui_gateway/owner_forward.py
index afbc6729016..17ffecb4186 100644
--- a/tui_gateway/owner_forward.py
+++ b/tui_gateway/owner_forward.py
@@ -76,16 +76,17 @@ def discover_owner(home: Path):
@contextlib.asynccontextmanager
-async def connect_owner(home: Path, endpoint, *, scope=None):
+async def connect_owner(home: Path, endpoint, *, scope=None, max_size: int = 2 ** 20):
"""A ``GatewayClient`` on ``endpoint``, the ready gateway serving ``home``; ``scope``: the
- ticket's profile scope (``"host"``: the one native Desktop holds)."""
+ ticket's profile scope (``"host"``: the one native Desktop holds); ``max_size``: the largest
+ answer frame accepted (websockets' 1 MiB default)."""
from hermes_cli.gateway_client import GATEWAY_WS_PROTOCOL, GatewayClient, _session_ticket, gateway_ws_target
from websockets.asyncio.client import connect
ticket = await asyncio.to_thread(_session_ticket, home, endpoint, scope=scope)
url, protocols = gateway_ws_target(endpoint, ticket)
# Loopback owner dial: never through HTTP(S)_PROXY (websockets>=14 honours it by default).
- async with connect(url, subprotocols=protocols, open_timeout=10, proxy=None) as ws:
+ async with connect(url, subprotocols=protocols, open_timeout=10, proxy=None, max_size=max_size) as ws:
if ws.subprotocol != GATEWAY_WS_PROTOCOL:
raise OwnerUnavailable("the gateway answered with another protocol")
async with GatewayClient(ws) as client:
@@ -220,8 +221,13 @@ class _Relay:
def forward_rpc(home: Path, endpoint, method: str, params: dict) -> Any:
"""One request/answer RPC on the owner serving ``home`` (Group Chat calls, WA-19), on the
host-scoped grant native Desktop itself holds, so a room may seat the served sibling profiles."""
+ from gateway.hosted_room_attachments import MAX_ATTACHMENT_BYTES
+ # A groups.attachment.download answer carries a whole file as base64: room for the largest
+ # one the room store accepts, plus its JSON-RPC envelope.
+ frame = (MAX_ATTACHMENT_BYTES + 2) // 3 * 4 + 2 ** 20
+
async def call():
- async with connect_owner(home, endpoint, scope="host") as client:
+ async with connect_owner(home, endpoint, scope="host", max_size=frame) as client:
return await client.rpc(method, **params)
return asyncio.run(call())