The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(groups): a disbanded Group Chat stays gone, the startup window strands nothing, and no profile view hides a room
Teknium6ed94e3f6dc7
diff --git a/gateway/hosted_rooms_gateway_import.py b/gateway/hosted_rooms_gateway_import.pyindex a0a78802df7..03f40abb51b 100644--- a/gateway/hosted_rooms_gateway_import.py+++ b/gateway/hosted_rooms_gateway_import.py@@ -18,11 +18,19 @@ Each room moves in two crash-safe steps, so it is driven by exactly one process:owner, the subject native Desktop and a signed-in Webapp tab both act as.Re-running is a no-op: step 1 only takes rooms still on the local authority, step 2 only copies-fenced rooms the target lacks. A crash between them is finished by the next start.+fenced rooms the target has never known (neither held nor reserved in ``hosted_room_retired_ids``),+so a room the user disbanded in the gateway never comes back once its tombstone is pruned. After+the copy commits, each handed room is recorded in the source's :data:`HANDOFF_TABLE`, which step 2+never reads again. A crash between the steps is finished by the next start.``shared-state.db`` is one root file with no profile column, so only the root home's gateway (the-default profile, whose ``state.db`` sits beside it) imports; a named profile's standalone rooms stay-where they are for gateway-less use.+default profile, whose ``state.db`` sits beside it) imports. A standalone room that was not imported+stays listed and driven by the standalone backend from every profile's view, and a named profile's+view reaches the imported ones on the root gateway (``tui_gateway/methods_groups_forward.py``), so+no view loses a room it showed before.++The import runs when the gateway builds its room service (before ``ready``) and once more right+after ``ready`` (:func:`import_after_ready`), covering a room written in between."""from __future__ import annotations@@ -33,6 +41,8 @@ from pathlib import Pathlogger = logging.getLogger(__name__)SOURCE_NAME = "shared-state.db"+#: Source-side record of every room the gateway store took over: never offered again.+HANDOFF_TABLE = "hosted_room_gateway_handoffs"_OWNER = "gateway.hosted.owner.v1:"@@ -66,12 +76,34 @@ def _fence_source(source: Path, local_id: str, handoff_id: str) -> int:def _fenced_ids(source: Path, handoff_id: str) -> set[str]:+ """Fenced live rooms not yet recorded as handed over."""+ from gateway.hosted_rooms import _transaction+ with _transaction(source, immediate=True) as conn:+ _ensure_handoff_table(conn)+ return {str(row[0]) for row in conn.execute(+ f"SELECT room_id FROM hosted_rooms WHERE authority_gateway_id=? AND disbanded_at IS NULL"+ f" AND room_id NOT IN (SELECT room_id FROM {HANDOFF_TABLE})", (handoff_id,))}+++def _ensure_handoff_table(conn) -> None:+ conn.execute(f"CREATE TABLE IF NOT EXISTS {HANDOFF_TABLE} (room_id TEXT PRIMARY KEY, handed_at REAL NOT NULL)")+++def _record_handoff(source: Path, room_ids: set[str], now: float) -> None:+ from gateway.hosted_rooms import _transaction+ with _transaction(source, immediate=True) as conn:+ _ensure_handoff_table(conn)+ conn.executemany(f"INSERT OR IGNORE INTO {HANDOFF_TABLE} (room_id, handed_at) VALUES (?, ?)",+ [(room_id, now) for room_id in sorted(room_ids)])+++def handed_room_ids(source: Path) -> set[str]:+ """Every room ``source`` handed to the gateway store (recorded or still only fenced)."""from contextlib import closingfrom gateway.hosted_rooms import _read_connectionwith closing(_read_connection(source)) as conn:return {str(row[0]) for row in conn.execute(- "SELECT room_id FROM hosted_rooms WHERE authority_gateway_id=? AND disbanded_at IS NULL",- (handoff_id,))}+ "SELECT room_id FROM hosted_rooms WHERE authority_gateway_id=?", (handoff_gateway_id(),))}def _claim(conn, room_id: str, local_id: str, handoff_id: str, owner: str, now: float) -> None:@@ -112,16 +144,41 @@ def import_standalone_rooms(target_db: Path, *, runtime_epoch: int | None = Nonewith _transaction(target_db, immediate=True) as conn:if runtime_epoch is not None:_epoch(conn, runtime_epoch)- held = {str(row[0]) for row in conn.execute("SELECT room_id FROM hosted_rooms")}- missing = frozenset(fenced - held)- if not missing:- return 0- copied = _copy_rows(conn, source, only=missing)+ # Every id this store has ever known: a disbanded room's row is pruned later, its id stays.+ known = {str(row[0]) for row in conn.execute(+ "SELECT room_id FROM hosted_rooms UNION SELECT room_id FROM hosted_room_retired_ids")}+ missing = frozenset(fenced - known)+ copied = _copy_rows(conn, source, only=missing) if missing else 0for room_id in sorted(missing):_claim(conn, room_id, local_id, handoff_id, owner, now)+ _record_handoff(source, fenced, now)except (OSError, sqlite3.Error, HostedRoomError, RuntimeStoreError) as exc:logger.warning("hosted rooms: could not import the standalone Group Chats from %s (%s); ""will retry on the next start", source, exc)return 0- logger.info("hosted rooms: imported %d standalone Group Chat(s) from %s", copied, source)+ if copied:+ logger.info("hosted rooms: imported %d standalone Group Chat(s) from %s", copied, source)return copied+++def import_after_ready(authorities) -> None:+ """Import once more after the gateway published ``ready``, off the event loop.++ The start-up import runs before readiness; a standalone backend that saw no gateway yet may+ still write a room in between. Once ready, that backend forwards every call (or waits while+ the gateway is starting), so this second pass leaves nothing stranded until the next restart.+ The service's driver re-reads its bindings each tick and is woken for the claimed rooms."""+ import threading+ for authority in authorities:+ service = getattr(authority, "hosted_room_service", None)+ if service is None or getattr(service, "_ready_import_started", False):+ continue+ service._ready_import_started = True+ target, epoch = Path(authority.db.db_path), authority.epoch++ def run(target=target, epoch=epoch, service=service, authority=authority):+ from gateway.session_authorities import owner_scope+ with owner_scope(authority): # a new thread holds the launch profile's scope otherwise+ if import_standalone_rooms(target, runtime_epoch=epoch):+ service.wakeup()+ threading.Thread(target=run, name="hosted-rooms-ready-import", daemon=True).start()diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.pyindex 15e131ee9a4..f6b17e9ea8a 100644--- a/gateway/session_hosted_service.py+++ b/gateway/session_hosted_service.py@@ -274,6 +274,8 @@ def start_ready_hosted_services(runner):for service in services:# start() only releases its thread; preparation and disk access happened above.service.start()+ from gateway.hosted_rooms_gateway_import import import_after_ready+ import_after_ready(serving_authorities(runner))async def stop_hosted_service(runner, timeout=5):diff --git a/tests/gateway/test_hosted_rooms_gateway_import.py b/tests/gateway/test_hosted_rooms_gateway_import.pyindex 1b5662f7ae7..adb26dade96 100644--- a/tests/gateway/test_hosted_rooms_gateway_import.py+++ b/tests/gateway/test_hosted_rooms_gateway_import.py@@ -65,3 +65,35 @@ def test_a_named_profile_store_imports_nothing(tmp_path):assert import_standalone_rooms(named) == 0assert hosted_rooms.list_rooms(source)[0]["authority_gateway_id"] == hosted_rooms.local_authority_gateway_id()+++def test_a_room_disbanded_in_the_gateway_never_comes_back(tmp_path):+ import time+ source, target = _stores(tmp_path)+ _standalone_room(source, "room-desk")+ import_standalone_rooms(target)+ [room] = hosted_rooms.list_rooms(target)+ hosted_rooms.disband_room(target, room_id="room-desk", expected_gateway_id=room["authority_gateway_id"],+ expected_epoch=room["authority_epoch"])+ # The tombstone is pruned later (retention, count or byte cap); only the reserved id remains.+ later = time.time() + hosted_rooms.DISBANDED_ROOM_RETENTION_SECONDS + 10+ assert hosted_rooms.prune_disbanded_rooms(target, now=later) == 1++ assert import_standalone_rooms(target) == 0 # next gateway start+ assert hosted_rooms.list_rooms(target, include_disbanded=True) == []+++def test_the_gateway_imports_again_once_ready(tmp_path):+ import threading+ from types import SimpleNamespace+ from gateway.hosted_rooms_gateway_import import import_after_ready+ source, target = _stores(tmp_path)+ woke = threading.Event()+ authority = SimpleNamespace(db=SimpleNamespace(db_path=str(target)), epoch=None,+ hosted_room_service=SimpleNamespace(wakeup=woke.set))+ _standalone_room(source, "room-window") # written by a standalone backend before `ready`++ import_after_ready([authority])++ assert woke.wait(10)+ assert [r["room_id"] for r in hosted_rooms.list_rooms(target)] == ["room-window"]diff --git a/tests/tui_gateway/test_groups_owner_forward.py b/tests/tui_gateway/test_groups_owner_forward.pyindex f6aa6790e7e..2618aa5cd2e 100644--- a/tests/tui_gateway/test_groups_owner_forward.py+++ b/tests/tui_gateway/test_groups_owner_forward.py@@ -23,12 +23,26 @@ def home(tmp_path, monkeypatch):methods_groups.stop_hosted_room_service(timeout=1.0)+ENDPOINT = object()+++def _discovery(monkeypatch, *states):+ """Gateway discovery answers the given states in turn (the last one repeats)."""+ from hermes_cli import gateway_runtime+ seen = list(states)++ def discover(home, *, timeout=2.0):+ state = seen.pop(0) if len(seen) > 1 else seen[0]+ return gateway_runtime.GatewayDiscovery(state, endpoint=ENDPOINT if state == "ready" else None)+ monkeypatch.setattr(gateway_runtime, "discover_gateway_endpoint", discover)++@pytest.fixturedef owner(monkeypatch):"""A ready gateway serving the home; records what reached it."""calls = []- endpoint = object()- monkeypatch.setattr(owner_forward, "discover_owner", lambda home: endpoint)+ endpoint = ENDPOINT+ _discovery(monkeypatch, "ready")def forward_rpc(home, seen_endpoint, method, params):assert seen_endpoint is endpoint@@ -60,7 +74,7 @@ def test_capabilities_advertise_only_what_this_wire_carries(home, owner):def test_owner_refusal_is_returned_not_run_locally(home, monkeypatch):from hermes_cli.gateway_client import GatewayRPCError- monkeypatch.setattr(owner_forward, "discover_owner", lambda home: object())+ _discovery(monkeypatch, "ready")def refuse(*_args):raise GatewayRPCError("permission_denied", code=4030, data={"reason": "permission_denied"})@@ -91,3 +105,29 @@ def test_gateway_less_list_hides_rooms_handed_to_the_gateway(home):assert srv._methods["groups.list"](2, {})["result"]["rooms"] == []refused = srv._methods["groups.send"](3, {"room_id": "room-desk", "event_id": "e1", "payload": {"text": "hi"}})assert "error" in refused # the standalone copy is fenced: one driver per room+++def test_a_starting_gateway_is_waited_for_and_nothing_lands_locally(home, owner, monkeypatch):+ from tui_gateway import methods_groups_forward+ monkeypatch.setattr(methods_groups_forward, "_READY_POLL_S", 0.0, raising=False)+ _discovery(monkeypatch, "starting", "starting", "ready")++ created = srv._methods["groups.create"](1, {"room_id": "room-desk", "name": "Desk", "members": MEMBERS})++ assert created["result"]["room"]["room_id"] == "room-desk"+ assert [method for method, _ in owner] == ["groups.create"]+ from gateway.hosted_rooms import default_db_path, list_rooms+ assert list_rooms(default_db_path()) == [] # never a room the gateway's list would not show+++def test_a_named_profile_gateway_never_hides_the_standalone_rooms(home, owner, monkeypatch):+ _discovery(monkeypatch, "absent") # Desktop on its own first+ srv._methods["groups.create"](1, {"room_id": "room-desk", "name": "Desk", "members": MEMBERS})+ _discovery(monkeypatch, "ready") # then `hermes -p ops gateway` serves the selected profile++ listed = srv._methods["groups.list"](2, {"profile": "ops"})["result"]["rooms"]+ state = srv._methods["groups.state"](3, {"profile": "ops", "room_id": "room-desk"})++ assert [room["room_id"] for room in listed] == ["room-webapp", "room-desk"]+ assert state["result"]["room"]["name"] == "Desk" # served by the store that holds it+ assert [method for method, _ in owner] == ["groups.list"]diff --git a/tui_gateway/methods_groups_forward.py b/tui_gateway/methods_groups_forward.pyindex b4b91187022..15c956d9e6b 100644--- a/tui_gateway/methods_groups_forward.py+++ b/tui_gateway/methods_groups_forward.py@@ -7,8 +7,18 @@ the room calls a Desktop makes go to it instead (the owner-forward path prompts``tui_gateway/owner_forward.py``). The gateway imports the rooms this backend already hosts once(``gateway/hosted_rooms_gateway_import.py``) and fences them here, so each room has one driver.-With no gateway running, the calls run locally exactly as before. RoomLink's gateway-to-gateway-methods (``groups.peer.*``, replication, promote/demote) are not Desktop calls and stay local.+Routing, so no view ever loses a room it listed before:++- a room only the standalone store holds runs locally (a gateway cannot have it);+- a room handed to the gateway goes to the ROOT home's gateway, the only one that imports;+- anything else (``groups.create``, rooms the gateway made) goes to the selected profile's gateway;+- ``groups.list`` is that gateway's list plus the standalone rooms not handed over, plus, for a+ named profile, its handed rooms read from the root gateway.++The call runs locally only when no gateway serves the profile (``absent``, or an ``incompatible``+one that never imports). A ``starting``/``draining`` gateway is waited for and any other present+one is a retryable refusal: a local write then would be hidden from the gateway's list. RoomLink's+gateway-to-gateway methods (``groups.peer.*``, replication, promote/demote) stay local."""from __future__ import annotations@@ -24,6 +34,19 @@ FORWARDED = frozenset({"groups.approve"})#: 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.+#: ``incompatible`` is an older gateway without the session authority; it never imports, and the+#: first current gateway imports what was written here on its start.+_LOCAL_STATES = frozenset({"absent", "incompatible"})+#: States on the way to (or back to) a ready owner: wait for it, never write locally meanwhile.+_TRANSIENT_STATES = frozenset({"starting", "draining"})+#: How long one call waits for a starting or restarting gateway before refusing (retryable).+READY_WAIT_S = 20.0+_READY_POLL_S = 0.25+++class _OwnerBusy(Exception):+ """A gateway serves (or is about to serve) the home but cannot answer now."""def _home(server, params: dict):@@ -38,20 +61,66 @@ def _home(server, params: dict):return Path(get_hermes_home())-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 no ready- gateway serves the profile (the caller runs it locally)."""- from tui_gateway import owner_forward- if method not in FORWARDED:+def _root_home():+ from pathlib import Path+ from gateway.hosted_rooms import default_db_path+ return Path(default_db_path()).parent # the home whose gateway imports the standalone rooms+++def _discover(home):+ from hermes_cli.gateway_runtime import discover_gateway_endpoint+ return discover_gateway_endpoint(home, timeout=5)+++def owner_endpoint(home):+ """The ready gateway's endpoint for ``home``, or ``None`` when none serves it (run locally).++ A gateway that is starting or restarting is waited for (bounded by :data:`READY_WAIT_S`); one+ that is present but unreachable (slow identify, conflict) raises :class:`_OwnerBusy`. Either way+ nothing is written to the standalone store while a gateway may import from it."""+ import time+ deadline = time.monotonic() + READY_WAIT_S+ while True:+ discovery = _discover(home)+ if discovery.state == "ready" and discovery.endpoint is not None:+ return discovery.endpoint+ if discovery.state in _LOCAL_STATES:+ return None+ if discovery.state not in _TRANSIENT_STATES or time.monotonic() >= deadline:+ raise _OwnerBusy(discovery.reason_code or discovery.state)+ time.sleep(_READY_POLL_S)+++def _standalone_holder(room_id: str) -> str | None:+ """Where the standalone store says ``room_id`` lives: ``"gateway"`` (handed to the root+ gateway's store), ``"local"`` (any other room it holds: only this backend drives or mirrors+ it) or ``None`` (not a standalone room)."""+ from contextlib import closing+ from gateway.hosted_rooms import _read_connection, default_db_path+ from gateway.hosted_rooms_gateway_import import handoff_gateway_id+ source = default_db_path()+ if not source.is_file():return None- try:- home = _home(server, params)- endpoint = owner_forward.discover_owner(home)- except owner_forward.OwnerNotRunning:+ with closing(_read_connection(source)) as conn:+ row = conn.execute("SELECT authority_gateway_id FROM hosted_rooms WHERE room_id=?",+ (room_id,)).fetchone()+ if row is None:return None- except ValueError as exc:- return server._err(rid, 4000, str(exc))+ return "gateway" if str(row[0]) == handoff_gateway_id() else "local"+++def _standalone_rooms(params: dict | None = None) -> list[dict]:+ """The standalone store's rooms that were not handed to the gateway (the gateway-less list)."""+ from gateway.hosted_rooms import MAX_ROOM_LIST_LIMIT, default_db_path, list_rooms+ if not default_db_path().is_file():+ return []+ return local_rooms(list_rooms(default_db_path(), limit=MAX_ROOM_LIST_LIMIT,+ include_disbanded=bool(params and params.get("include_disbanded") is True)))+++def _call(server, rid, home, endpoint, method: str, params: dict) -> dict:from hermes_cli.gateway_client import GatewayRPCError+ from tui_gateway import owner_forwardtry:result = owner_forward.forward_rpc(home, endpoint, method, params)except GatewayRPCError as exc:@@ -66,6 +135,71 @@ def forward(server, rid, method: str, params: dict) -> dict | None:return server._ok(rid, result)+def _busy(server, rid, why) -> dict:+ return server._err(rid, OWNER_LOST_CODE,+ f"The Hermes gateway is not ready yet ({why}). Try again in a moment.")+++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:+ return None+ try:+ home = _home(server, params)+ room_id = str(params.get("room_id") or "")+ holder = _standalone_holder(room_id) if room_id else None+ if holder == "local":+ return None # only this backend holds it: never ask a gateway that cannot have it+ if holder == "gateway":+ home = _root_home() # the room was handed to the root gateway's store, whichever view asks+ if method == "groups.list":+ return _list(server, rid, home, params)+ endpoint = owner_endpoint(home)+ except _OwnerBusy as exc:+ return _busy(server, rid, exc)+ except ValueError as exc:+ return server._err(rid, 4000, str(exc))+ if endpoint is None:+ return None+ return _call(server, rid, home, endpoint, method, params)+++def _list(server, rid, home, params: dict) -> dict | None:+ """One Group Chat list that hides no existing room: the profile's gateway rooms, plus (on the+ first page) the rooms only the standalone store holds and, for a named profile, the standalone+ rooms already handed to the root gateway."""+ from gateway.hosted_rooms import MAX_ROOM_LIST_LIMIT, default_db_path+ from gateway.hosted_rooms_gateway_import import handed_room_ids+ endpoint = owner_endpoint(home)+ root = _root_home()+ handed = handed_room_ids(default_db_path()) if default_db_path().is_file() else set()+ root_endpoint = owner_endpoint(root) if handed and home.resolve() != root.resolve() else None+ if endpoint is None and root_endpoint is None:+ return None # the local listing (gateway-less) is the whole list+ if endpoint is None:+ reply = server._ok(rid, {"rooms": [], "next_offset": None})+ else:+ reply = _call(server, rid, home, endpoint, "groups.list", params)+ if "error" in reply or int(params.get("offset") or 0) != 0:+ return reply+ rooms = list(reply["result"].get("rooms") or [])+ extra = _standalone_rooms(params)+ if root_endpoint is not None:+ page = _call(server, rid, root, root_endpoint, "groups.list",+ {"include_disbanded": params.get("include_disbanded") is True,+ "limit": MAX_ROOM_LIST_LIMIT})+ if "error" in page:+ return page+ extra += [room for room in page["result"].get("rooms") or [] if str(room.get("room_id")) in handed]+ seen = {str(room.get("room_id")) for room in rooms}+ for room in extra:+ if str(room.get("room_id")) not in seen:+ seen.add(str(room.get("room_id")))+ rooms.append(room)+ return server._ok(rid, {**reply["result"], "rooms": rooms})++def forward_bound(rid, method: str, params: dict) -> dict | None:""":func:`forward` on the server ``methods_groups`` is bound to (``None``: none bound yet)."""from tui_gateway import methods_groups