Skip to content

The agent that grows with you

fix(tui): legacy WS fallback can no longer write an authority-owned session

Teknium5d228dde7256
diff --git a/tests/tui_gateway/test_tui_gateway_ws.py b/tests/tui_gateway/test_tui_gateway_ws.py
index 67c5db187af..de97039f72b 100644
--- a/tests/tui_gateway/test_tui_gateway_ws.py
+++ b/tests/tui_gateway/test_tui_gateway_ws.py
@@ -1,9 +1,12 @@
import asyncio
import concurrent.futures
+import contextlib
import datetime
import json
import threading
+import pytest
+
from tui_gateway import server
from tui_gateway import ws as ws_mod
@@ -469,3 +472,51 @@ def test_legacy_fallback_keeps_the_ticket_profile_for_sessionless_scoped_handler
reply = _drive_authority_fallback(monkeypatch, capabilities=_INTERACTIVE, profile_id=str(secondary),
method="probe.scoped")
assert reply["result"]["home"] == str(secondary)
+
+
[email protected]("method,params", [
+ ("session.delete", {"session_id": "owned"}),
+ ("session.archive", {"session_id": "owned", "archived": True}),
+])
+def test_legacy_fallback_never_writes_an_authority_owned_session(monkeypatch, tmp_path, method, params):
+ """A session write the authority answers -32601 for must not reach the legacy writer: it would
+ change the authority's state.db behind its receipts and revision fence (and a delete would leave
+ the authority holding a live session whose row is gone)."""
+ from types import SimpleNamespace
+ from gateway.session_authority import LiveSession, SessionAuthority
+ from hermes_state import SessionDB
+ from hermes_state_runtime import begin_runtime_epoch
+
+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)
+ with SessionDB(db_path=tmp_path / "state.db") as db:
+ db.create_session("owned", source="tui")
+ revision = db.get_session("owned")["runtime_revision"]
+ authority = SessionAuthority(SimpleNamespace(_draining=False), profile_id=str(tmp_path),
+ instance_id="current", db=db, epoch=begin_runtime_epoch(db, instance_id="current"))
+ authority.sessions["owned"] = LiveSession(None, "route")
+ monkeypatch.setattr(server, "_profile_db", lambda *_a, **_k: contextlib.nullcontext(db))
+ sent, inbound = [], [json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})]
+
+ class FakeWS:
+ scope = {"hermes.session_authority": authority}
+
+ async def accept(self, **_kw):
+ pass
+
+ async def send_text(self, line):
+ sent.extend(json.loads(part) for part in line.splitlines() if part.strip())
+
+ async def receive_text(self):
+ if inbound:
+ return inbound.pop()
+ raise ws_mod._WebSocketDisconnect()
+
+ async def close(self, **_kw):
+ pass
+
+ asyncio.run(ws_mod.handle_ws(FakeWS(), auth_identity={"user_id": "owner", "instance_id": "current"}))
+ reply = next(frame for frame in sent if frame.get("id") == 1)
+ assert reply["error"]["code"] == -32601, reply
+ row = db.get_session("owned")
+ assert row is not None and not row.get("archived") and row["runtime_revision"] == revision
+ assert "owned" in authority.sessions
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 356ef9cf1f5..63089f9c0a0 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -311,11 +311,12 @@ async def _dispatch_request(authority_connection: Any, req: Any, req_method: Any
return await asyncio.to_thread(server.dispatch, req, transport)
resp = await authority_connection.dispatch(req)
actor = authority_connection.actor
- if _is_unknown_method(resp) and req_method in server._methods and legacy_fallback_allowed(actor):
+ if (_is_unknown_method(resp) and req_method in server._methods
+ and legacy_fallback_allowed(actor, req_method)):
# Session verbs live on the authority; everything else the sidecar still
- # registers (pet, wake word, active-session list, connectors) keeps its
- # legacy handler. A real -32601 reaches the client only for methods
- # neither side knows, which is what its version-skew notice keys on.
+ # registers (pet, wake word, connectors) keeps its legacy handler. A legacy
+ # session writer keeps the authority's -32601 (ws_legacy_fallback), as does a
+ # method neither side knows, which is what the client's version-skew notice keys on.
resp = await asyncio.to_thread(dispatch_legacy, server, req, transport, actor)
return resp
diff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.py
index 235e2d98174..5f8580b5ce3 100644
--- a/tui_gateway/ws_legacy_fallback.py
+++ b/tui_gateway/ws_legacy_fallback.py
@@ -22,10 +22,27 @@ _connection_profile_home: contextvars.ContextVar[str | None] = contextvars.Conte
"hermes_ws_connection_profile_home", default=None)
-def legacy_fallback_allowed(actor: Any) -> bool:
+# The authority owns every session, its transcript and its admissions: a legacy handler in these
+# namespaces would write the same state.db behind its receipts and revision fence (a legacy
+# ``session.delete`` dropped a row the authority still held live; ``session.branch_stored`` built a
+# second, legacy-owned runtime). Kept: store-wide reads, foreign-history import (new rows only), and
+# Desktop's project move (``session.workspace.move``), which rewrites only the row's cwd/git grouping
+# and has no authority verb yet.
+_SESSION_NAMESPACES = ("session.", "prompt.", "message.")
+_SESSION_FALLBACK_ALLOWED = frozenset({
+ "session.most_recent", "session.active_list", "session.events.stats",
+ "session.foreign.list", "session.foreign.preview", "session.foreign.import",
+ "session.workspace.move",
+})
+
+
+def legacy_fallback_allowed(actor: Any, method: str) -> bool:
"""True when the connection's grant covers the interactive purpose (the authority's own
- capability map; never a second list that could drift)."""
+ capability map; never a second list that could drift) and *method* is not a session verb
+ the authority owns."""
from gateway.runtime_bootstrap import _PURPOSE_CAPABILITIES
+ if method.startswith(_SESSION_NAMESPACES) and method not in _SESSION_FALLBACK_ALLOWED:
+ return False
return _PURPOSE_CAPABILITIES["interactive"] <= frozenset(getattr(actor, "capabilities", ()) or ())