Skip to content

The agent that grows with you

fix(gateway): a chat's old conversation stays usable from the apps, and its replies stop reaching the chat

Teknium29abd7046417
diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py
index 5dea0e6401f..7f45c8fc1d7 100644
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@ -307,6 +307,14 @@ class GatewayAuthorizationMixin:
"""
if source is None:
return None
+ from gateway.session_detached import detached_route_of
+ if detached_route_of(source):
+ # A conversation its chat moved past answers its app viewers only, through the local
+ # adapter's event-stream delivery (gateway/session_detached.py), never the chat.
+ from gateway.session_identity import identity_of
+ identity = identity_of(source)
+ profile = identity.runtime_profile if identity is not None else getattr(source, "profile", None)
+ return self._adapters_for_profile(profile).get(Platform.LOCAL)
adapter = self._intake_adapter_for(source)
if adapter is not None:
return adapter
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.py
index 6200c3367ae..467205acf5b 100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@ -1009,9 +1009,11 @@ class GatewayTurnProgressMixin:
def local_viewer_turn(runner) -> bool:
"""A local route's viewers read the canonical event stream; ``LocalSessionAdapter.send``
- publishes nothing, so status and notices go to that stream instead."""
- return (getattr(runner, "_approval_owner", None) is not None
- and getattr(getattr(runner._ctx, "source", None), "platform", None) == Platform.LOCAL)
+ publishes nothing, so status and notices go to that stream instead. So does a conversation its
+ chat moved past (gateway/session_detached.py): it delivers through that same adapter."""
+ source = getattr(runner._ctx, "source", None) if getattr(runner, "_approval_owner", None) is not None else None
+ from gateway.session_detached import detached_route_of
+ return getattr(source, "platform", None) == Platform.LOCAL or detached_route_of(source) is not None
def _viewer_status_kind(kind, text):
diff --git a/gateway/session.py b/gateway/session.py
index 7626b1880dd..fbc9a4e738b 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -14,6 +14,7 @@ from typing import Dict, List, Optional, Any
from .config import Platform, GatewayConfig, HomeChannel
from .whatsapp_identity import canonical_whatsapp_identifier
+from gateway.session_detached import detached_route_of
from gateway.session_identity import transport_profile_of
from gateway.session_persistence import SessionPersistenceMixin, _DB_UNPINNED
from gateway.session_prompt_pin import SessionPromptPinMixin, sanitize_prompt_pin
@@ -100,6 +101,10 @@ class SessionSource:
# over the authenticated relay WebSocket. ``platform`` is the UNDERLYING platform, not
# ``relay``, so authz must key upstream trust off THIS flag.
delivered_via_upstream_relay: bool = False
+ # Wire-INVISIBLE: the key of a conversation its chat moved past, still run from the apps
+ # (gateway/session_detached.py). It replaces the chat's key, so nothing keyed by route reaches
+ # the chat's current conversation, and delivery goes nowhere.
+ detached_route: Optional[str] = field(default=None, repr=False, compare=False)
def __post_init__(self) -> None:
# Mirror scope_id/guild_id onto each other (scope_id wins) so readers of EITHER agree.
@@ -695,6 +700,8 @@ def build_session_key(
session per platform. Groups add the participant id only when ``group_sessions_per_user`` and
not in a thread (threads are shared unless ``thread_sessions_per_user``).
"""
+ if detached := detached_route_of(source):
+ return detached
is_dm = source.chat_type == "dm"
chat_id = source.chat_id
if is_dm and source.platform == Platform.WHATSAPP:
@@ -901,6 +908,9 @@ class SessionStore(
"""Single-flight session lookup/create per routing key: overlapping calls for one key (even
concurrent ``force_new``) share the owner's result so only one transition and SQLite row is
created. ``touch_activity=False`` (internal events) preserves the user-activity clock."""
+ if detached_route_of(source):
+ from gateway.session_detached import detached_entry
+ return detached_entry(self, source)
session_key = self._generate_session_key(source)
inflight_lock = self._lazy("_inflight_lock", threading.Lock)
self._lazy("_inflight_sessions", dict)
diff --git a/gateway/session_api.py b/gateway/session_api.py
index d69898f6005..7e0ecdac5bc 100644
--- a/gateway/session_api.py
+++ b/gateway/session_api.py
@@ -339,5 +339,5 @@ def restore_api_session(authority, session_id):
elif is_history_mount(live):
# A read-only view opened while the row had no binding becomes the bound conversation in place,
# so its viewers keep their subscriptions and event stream.
- live.source, live.route, live.superseded, live.history_mount = source, entry.session_key, False, False
+ live.source, live.route = source, entry.session_key
return SessionRef(authority.profile_id, session_id)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index fdea81c9fc4..3077cd64fc2 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -72,19 +72,6 @@ class LiveSession:
# (principal, effort) of a ``/reasoning`` command that arrived while a turn ran: applied in memory at
# once, committed to the policy at the next boundary (gateway/session_setting_commands.py).
pending_reasoning: tuple | None = None
- # A historic messaging row mounted for reading after its lane moved on (``/new``): ``route`` is
- # the lane's CURRENT key, which names another conversation, so nothing route-keyed (agent, Stop,
- # turns, eviction) may act through it (gateway/session_route_recovery.py). The lane publishing
- # this row again clears it.
- superseded: bool = False
- # Mounted by that cold path (not published by its lane): the lane publishing ANOTHER conversation
- # on the same route later supersedes it too.
- history_mount: bool = False
- # A local conversation a messaging lane took over (``/handoff``, a platform ``/resume``): its
- # viewers follow it onto the lane, and once that lane publishes another conversation (``/new``,
- # another handoff) it is superseded like a history mount, whatever the lane published since.
- # Set from the row (``moved_local``) on every mount of it, however constructed (#143286).
- handed_off: bool = False
# The background-review guard of a cold ``/refine`` (gateway/session_refine.py): its side agent is
# per call, so the run token lives here; a second /refine joins it and the next turn cancels it.
review: SimpleNamespace = field(default_factory=SimpleNamespace)
@@ -99,6 +86,13 @@ class LiveSession:
def __post_init__(self):
self.controls = PendingControls(self.event_stream)
+ @property
+ def detached(self):
+ """A messaging conversation its chat moved past (``name_lane``): its turns and Stop act on
+ it alone, on its own key, and reach its app viewers only (gateway/session_detached.py)."""
+ from gateway.session_detached import detached_route_of
+ return detached_route_of(self.source) is not None
+
def _log_drain_failure(task):
"""A dead pump is the one failure this module must never swallow."""
@@ -220,11 +214,6 @@ class SessionAuthority:
if is_history_mount(self.sessions[ref.session_id]):
require_history_access(self, actor, ref.session_id, capability)
from gateway.config import Platform
- if self.sessions[ref.session_id].superseded and capability != 'session:read':
- # One gateway owns every session and never crosses them: the lane's route now belongs to
- # its newer conversation, so a write here would land there. Named, so a viewer can say so.
- raise RuntimeStoreError('session_superseded', field='session_id',
- detail='this conversation\'s chat has moved on to a newer session; it is read-only')
source = self.sessions[ref.session_id].source
if (source is not None and source.platform == Platform.LOCAL
and source.user_id != actor.subject and 'session:operator' not in actor.capabilities):
@@ -277,39 +266,29 @@ class SessionAuthority:
return sid, entry.session_key
def _publish_route(self, source, sid, route):
- from gateway.config import Platform
self._require_admission_open()
- live = self.sessions.get(sid)
- # *sid* takes the route over: new here, moved onto it, or back after another conversation had it.
- took_over = live is None or live.route != route or live.superseded
- if live is None:
- from gateway.session_route_recovery import mount
- live = self.sessions[sid] = mount(self, sid, source, route)
- elif live.route != route:
- # *sid* moved lanes: ``/handoff`` or a platform ``/resume`` took a local conversation over
- # (its repoint retired the local receipt), or a ``/resume`` moved it on to another chat.
- # Its open viewers follow it, so a turn or a Stop through this mount reaches the lane that
- # holds it now, never the conversation that replaced it on the old one (#143286).
- from gateway.session_route_recovery import moved_local
- left_local = live.source is not None and live.source.platform == Platform.LOCAL
- live.handed_off = (live.handed_off or (left_local and source.platform != Platform.LOCAL)
- or moved_local(self, sid, source))
- live.source, live.route = source, route
- if took_over:
- # The lane moved on to *sid*: a cold history mount or a chat handed off earlier that is
- # still on its route is now another conversation's, so it goes read-only
- # (gateway/session_route_recovery.py): a Stop or turn through it would act on *sid*.
- for other in self.sessions.values():
- if (other.history_mount or other.handed_off) and other.route == route and other is not live:
- other.superseded = True
- # The lane itself names *sid* (again): a historic mount becomes its live session.
- live.superseded = live.history_mount = False
+ if sid not in self.sessions:
+ self.sessions[sid] = LiveSession(source, route)
+ self.name_lane(route, sid, source)
return SessionRef(self.profile_id, sid)
+ def name_lane(self, route, sid, source):
+ """The messaging chat on *route* (*source*) now names conversation *sid* (its next inbound,
+ ``/new``, ``/resume``, ``/branch``, ``/handoff``). Every other live session on the route (a
+ view kept open, a cold mount, a local chat handed off earlier) detaches onto its own key: its
+ app viewers keep using it, and nothing of it reaches the chat (gateway/session_detached.py).
+ *sid*'s own mount moves onto the route: a detached one comes back, a local one ``/handoff``
+ took over or one another chat held (a cross-chat ``/resume``) follows it, so its open viewers'
+ turns and Stops reach the chat that holds it now (#143286)."""
+ from gateway.session_detached import detach
+ for other_sid, other in self.sessions.items():
+ if other.route == route and other_sid != sid:
+ detach(self, other, other_sid)
+ if (live := self.sessions.get(sid)) is not None and live.route != route:
+ live.source, live.route = source, route
+
def agent(self, ref):
live = self.sessions[ref.session_id]
- if live.superseded:
- return None # the route's agent is the newer conversation's
lookup = getattr(self.runner, '_resident_agent_for', None) or self.runner._cached_agent_for
return lookup(live.route)
@@ -671,9 +650,7 @@ class SessionAuthority:
check_local_input(
self, SessionRef(self.profile_id, sid), row, source=source)
self._require_admission_open()
- if sid not in self.sessions: # ``mount``: a moved local chat keeps ``handed_off`` here too
- from gateway.session_route_recovery import mount
- self.sessions[sid] = mount(self, sid, source, route)
+ self.sessions.setdefault(sid, LiveSession(source, route))
if any(row['status'] == 'unknown' for row in rows):
raise RuntimeStoreError('unknown_execution')
self._schedule(SessionRef(self.profile_id, sid))
@@ -963,8 +940,6 @@ class SessionAuthority:
Stop above reached the turn's own agent, not a cached one it may still replace."""
from gateway.run import _AGENT_PENDING_SENTINEL
live = self.sessions[ref.session_id]
- if live.superseded:
- return False
running = getattr(self.runner, '_running_agents', None) or {}
agent = running.get(live.route)
return agent is not None and agent is not _AGENT_PENDING_SENTINEL
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index 33beaeab36c..f47a6b7b4f1 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -485,6 +485,7 @@ async def admit_automation(authority, adapter, event, identity, replaces=None):
own transaction, so neither lands without the other."""
authority._require_admission_open()
payload, entry = snapshot_automation(authority, adapter, event, identity)
+ from gateway.session_authority import LiveSession
sid = (payload.get('local_automation_v1') or payload['native_text_v1']['automation'])['owner']
ref = SessionRef(authority.profile_id, sid)
source, envelope = event.source, payload.get('native_text_v1')
@@ -493,9 +494,7 @@ async def admit_automation(authority, adapter, event, identity, replaces=None):
# drain resolves no adapter for this session after a restart.
from gateway.session_envelope import restore_native_source
source = restore_native_source(payload, authority.runner)
- if ref.session_id not in authority.sessions: # the route's conversation may be a moved local chat
- from gateway.session_route_recovery import mount
- authority.sessions[ref.session_id] = mount(authority, ref.session_id, source, entry.session_key)
+ authority.sessions.setdefault(ref.session_id, LiveSession(source, entry.session_key))
from functools import partial
from gateway.session_runtime_workers import tracked_write
admitted, replaced = partial(authority._admitted, ref, event), []
diff --git a/gateway/session_detached.py b/gateway/session_detached.py
new file mode 100644
index 00000000000..674cafb0a64
--- /dev/null
+++ b/gateway/session_detached.py
@@ -0,0 +1,73 @@
+"""A messaging conversation its chat moved past stays usable from the apps (Teknium's ruling).
+
+When a messaging chat names another conversation (``/new``, ``/resume``, ``/branch``, a handoff,
+its next inbound naming another one), a Desktop / Webapp / mobile view still open on the previous
+conversation keeps working: its turns, Stop and controls act on that conversation alone, and its
+replies reach its viewers only, never the chat, which now gets only its new conversation's replies.
+
+``detach`` moves the live session off the chat's route onto a key that names the conversation
+(``agent:<ns>:detached:<session id>``) and pins that key on a copy of its source
+(``SessionSource.detached_route``). From there the turn runs on the ordinary messaging path:
+
+* ``build_session_key`` answers the pinned key, so the runner's per-route state (running slot,
+ agent cache, busy guard, the agent a Stop reaches) is the conversation's own, never the chat's;
+* ``SessionStore.get_or_create_session`` resolves the key to the conversation itself
+ (``detached_entry``), and never creates or persists a route for it;
+* delivery goes through the profile's ``LocalSessionAdapter`` (gateway/session_local.py), as a local
+ session's does: its sends publish nothing, viewers read the canonical event stream.
+
+The key carries no platform slot, so a reader that parses a chat out of a session key
+(``gateway.run._parse_session_key``) finds none and delivers nowhere. The chat naming the
+conversation again (``/resume``) moves it back onto the chat's route (``SessionAuthority.name_lane``).
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta
+
+_SLOT = 'detached'
+
+
+def detached_route_of(source) -> str | None:
+ """*source*'s pinned detached key; None for any other source (duck-typed test sources too)."""
+ route = getattr(source, 'detached_route', None)
+ return route if isinstance(route, str) else None
+
+
+def detached_key(route: str, session_id: str) -> str:
+ """The detached key of *session_id*, in the profile namespace of its chat's *route*."""
+ parts = route.split(':')
+ namespace = ':'.join(parts[:2]) if len(parts) > 1 and parts[0] == 'agent' else 'agent:main'
+ return f'{namespace}:{_SLOT}:{session_id}'
+
+
+def detached_session_id(key: str) -> str | None:
+ parts = key.split(':')
+ return parts[3] if len(parts) == 4 and parts[0] == 'agent' and parts[2] == _SLOT else None
+
+
+def detach(authority, live, session_id) -> None:
+ """Move *live* (a messaging conversation its chat no longer names) off the chat's route. A
+ history mount (no source) has no route to leave, and a detached one has left it already."""
+ if live.source is None or detached_route_of(live.source):
+ return
+ from gateway.session_identity import replace_source
+ from gateway.session_local_recovery import local_adapter
+ local_adapter(authority) # its delivery; a messaging-only gateway has none yet
+ live.route = detached_key(live.route, session_id)
+ live.source = replace_source(live.source, detached_route=live.route)
+
+
+def detached_entry(store, source):
+ """The routing entry a detached *source* resolves to: its own conversation, at the compression
+ tip a turn writes to. Never stored: the chat's route stays the only one this conversation has."""
+ from gateway.session import SessionEntry
+ key = source.detached_route
+ session_id = str(detached_session_id(key))
+ db = store._db_for_key(key)
+ row = db.get_session(session_id) if db is not None else None
+ tip = (db.get_compression_tip(session_id) if db is not None else None) or session_id
+ now = datetime.now()
+ # Never a new conversation (that would fire session:start and first-contact notes).
+ started = datetime.fromtimestamp(row['started_at']) if row and row.get('started_at') else now - timedelta(seconds=1)
+ return SessionEntry(session_key=key, session_id=tip, created_at=started, updated_at=now, origin=source,
+ platform=source.platform, chat_type=source.chat_type)
diff --git a/gateway/session_history_mount.py b/gateway/session_history_mount.py
index 54811572341..187e4a27ca4 100644
--- a/gateway/session_history_mount.py
+++ b/gateway/session_history_mount.py
@@ -4,7 +4,7 @@ Pre-authority cron runs, subagent transcripts, API rows without a binding, and r
WebUI or the foreign-session importer wrote: before #106742 a viewer opened any of them straight
from ``state.db``. Nothing can run them (no frozen policy, no lane, and adopting a WebUI row as
writable would legitimise its second writer), so the owner mounts them for reading only. The mount
-is ``superseded``, so nothing route-keyed acts through it, and every capability but
+is keyed by no lane's route, so nothing route-keyed acts through it, and every capability but
``session:read`` is refused by name. Archive, pin and delete still work as for any read-only mount
(gateway/session_mutations.py), but only a leaf row deletes. Old local CLI/TUI/Desktop rows are not mounted
here: resume adopts them as writable conversations (gateway/session_local_migration.py).
@@ -43,7 +43,7 @@ def mount_history(authority, actor, sid):
return False # restore_api_session's
authority._require_admission_open()
from gateway.session_authority import LiveSession
- authority.sessions.setdefault(sid, LiveSession(None, _ROUTE_PREFIX + sid, superseded=True, history_mount=True))
+ authority.sessions.setdefault(sid, LiveSession(None, _ROUTE_PREFIX + sid))
return True
diff --git a/gateway/session_local_close.py b/gateway/session_local_close.py
index d8643d836e1..9ae3bbbc690 100644
--- a/gateway/session_local_close.py
+++ b/gateway/session_local_close.py
@@ -5,6 +5,7 @@ session row it owned; pickers then listed it as resumable. The stamp itself is t
``session.detach {end_reason}`` (``session_acp_lifecycle.end_idle_viewer_session``); this module only
decides which live rows read as closed.
"""
+from gateway.session_history_mount import is_history_mount
from hermes_state_local import local_receipt
from hermes_state_runtime import RuntimeStoreError
@@ -21,8 +22,8 @@ def closed_idle_unviewed(live, execution_state, target_ended_at):
in one off-loop query (``gateway/session_live_listing``)."""
if live is None or live.subscribers or execution_state != 'idle':
return False
- if live.superseded:
- return True # an old messaging conversation opened read-only: history once no one views it
+ if live.detached or is_history_mount(live):
+ return True # an old messaging conversation or a stored one: history once no one views it
return target_ended_at is not None
@@ -31,7 +32,7 @@ def closed_and_unviewed(authority, session_id, handle):
live = authority.sessions.get(session_id)
if live is None or live.subscribers or handle.execution_state != 'idle':
return False
- if live.superseded:
+ if live.detached or is_history_mount(live):
return True
target = _local_target(authority, session_id)
row = authority.db.get_session_list_row(target) if target else None
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index e9eeaea5678..94651e61f37 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -28,6 +28,16 @@ def local_adapter_map(authority):
return profile_adapters.setdefault(name, {})
+def local_adapter(authority):
+ """The LOCAL adapter *authority*'s local sessions, and the conversations its chats moved past
+ (gateway/session_detached.py), deliver through: created on first use."""
+ adapters = local_adapter_map(authority)
+ if (adapter := adapters.get(Platform.LOCAL)) is None:
+ from gateway.session_local import LocalSessionAdapter
+ adapter = adapters[Platform.LOCAL] = LocalSessionAdapter(authority)
+ return adapter
+
+
def local_source(authority, chat_id, user_id):
"""LOCAL SessionSource for a session owned by *authority*. A served secondary's local sessions
carry its profile so ``build_session_key`` namespaces them (``agent:<name>:local:...``) and the
@@ -164,11 +174,7 @@ def restore_local_session(authority, sid):
if isinstance(exc, RuntimeStoreError):
raise _ReceiptRefused(exc.reason, field=exc.field, detail=exc.detail) from exc
raise _ReceiptRefused('storage_unavailable') from exc
- adapters = local_adapter_map(authority)
- adapter = adapters.get(Platform.LOCAL)
- if adapter is None:
- adapter = LocalSessionAdapter(authority)
- adapters[Platform.LOCAL] = adapter
+ adapter = local_adapter(authority)
if not isinstance(adapter, LocalSessionAdapter) or adapter.authority is not authority:
raise RuntimeStoreError('runtime_draining')
live = authority.sessions.get(sid)
diff --git a/gateway/session_mutations.py b/gateway/session_mutations.py
index 16a16c2712c..4cd3176fb66 100644
--- a/gateway/session_mutations.py
+++ b/gateway/session_mutations.py
@@ -61,13 +61,13 @@ def _authorize_control(authority, actor, ref, params, owner=None):
if operation in {'delete', 'archive', 'sidebar'}:
# The read gate mounts a cold row first, so the checks below see what it is.
authority.authorize(actor, ref, 'session:read')
+ from gateway.session_history_mount import is_history_mount
if operation == 'delete':
from gateway.session_history_mount import require_history_leaf
require_history_leaf(authority, ref.session_id)
- if not (operation in {'delete', 'archive', 'sidebar'} and authority.sessions[ref.session_id].superseded):
- # An old conversation its chat moved past is read-only, but deleting it retires its
- # own lineage only (retirement never evicts a read-only mount's route), and archiving
- # or pinning it flags that lineage's rows only, never the route's newer conversation.
+ if not (operation in {'delete', 'archive', 'sidebar'} and is_history_mount(authority.sessions[ref.session_id])):
+ # Stored history is read-only, but deleting it retires its own lineage only, and
+ # archiving or pinning it flags that lineage's rows only.
authority.authorize(actor, ref, 'session:control')
return cold_history
@@ -423,7 +423,7 @@ def retire_live_sessions(authority, session_ids, *, require_fence=False):
# So do the password managers it unlocked: this path never reaches the viewer-close settle.
release_unlocks(sid)
candidate = authority.sessions.pop(sid, None)
- if candidate is not None and not candidate.superseded: # its route is the newer session's
+ if candidate is not None: # a detached conversation's route is its own key
evict = getattr(authority.runner, '_evict_cached_agent', None)
if callable(evict):
evict(candidate.route)
diff --git a/gateway/session_route_recovery.py b/gateway/session_route_recovery.py
index 6839fd576af..26b733a0efa 100644
--- a/gateway/session_route_recovery.py
+++ b/gateway/session_route_recovery.py
@@ -12,11 +12,10 @@ every cold row of this profile that carries a ``session_key`` and a messaging-pl
else its columns, rebuild the source.
Either way the source is revived through ``_restored_source``, so delivery stays pinned to the
-persisted receiving bot. A row the lane moved past mounts READ-ONLY (``LiveSession.superseded``): its
-only route is the lane's current key, which names the newer conversation, so a Stop, an agent lookup
-or a turn through it would act on that conversation. One gateway owns every session and never
-crosses them, so writes are refused by name (``session_superseded``) rather than given a private
-route that no adapter would deliver to (#140183 review F2). A compression continuation is never
+persisted receiving bot. A row the lane moved past mounts DETACHED (gateway/session_detached.py): the
+lane's current key names the newer conversation, so the row runs on a key of its own instead, its
+turns and Stop act on it alone and its replies reach its app viewers only, never the chat
+(Teknium's ruling: a chat's ``/new`` never locks the apps out of its old conversation). A compression continuation is never
mounted under its physical id: the lane's turns publish to the lineage root (``logical_owner``), so
``session.resume`` maps it to that root, as normal admission does. Rows without a ``session_key`` (subagents) have nothing to rebuild a lane
from. LOCAL rows (cron, CLI, TUI) restore from their private receipt and API rows from their binding
@@ -110,41 +109,24 @@ def _mount_plan(authority, sid):
def restore_routed_session(authority, sid):
"""Publish *sid* as its lane would after a restart; None when this row is not one a route or a
messaging-platform row can stand for."""
+ from gateway.session_authority import LiveSession
from gateway.session_contract import SessionRef
plan = _mount_plan(authority, sid)
if plan is None:
return None
route, entry, routed = plan
- superseded = routed is None and _names_another_conversation(authority, sid, route)
authority._require_admission_open()
# Re-pin the persisted receiving bot so delivery after a restart goes through it or nowhere,
# never the default bot by heuristic (gateway/AGENTS.md § Identity survives the process).
source = authority.runner._restored_source(entry)
- authority.sessions.setdefault(sid, mount(authority, sid, source, route, superseded=superseded,
- history_mount=True))
+ if sid not in authority.sessions:
+ live = authority.sessions[sid] = LiveSession(source, route)
+ if routed is None and _names_another_conversation(authority, sid, route):
+ from gateway.session_detached import detach
+ detach(authority, live, sid) # the lane moved past it: its turns stay off the chat
return SessionRef(authority.profile_id, sid)
-def mount(authority, sid, source, route, **flags):
- """The live entry of *sid* on *route*, however it is mounted (the lane's inbound, startup recovery
- of its queued input, a cold open, an automation wake): ``handed_off`` comes from the row
- (``moved_local``), so a moved local conversation goes read-only once its lane takes up another
- one, whichever path mounted it first (#143286)."""
- from gateway.session_authority import LiveSession
- return LiveSession(source, route, handed_off=moved_local(authority, sid, source), **flags)
-
-
-def moved_local(authority, sid, source):
- """*sid* is a local conversation (created by a local surface) published on a messaging lane:
- ``/handoff`` or a platform ``/resume`` moved it there. That provenance is the row's, not the
- path that mounts it (the Desktop that followed it, the lane's inbound, a cold open), so every
- mount of it goes read-only once the lane takes up another conversation (#143286)."""
- from hermes_state_local_migration import LEGACY_LOCAL_SOURCES
- if source is None or source.platform == Platform.LOCAL:
- return False
- return (authority.db.get_session(sid) or {}).get('created_source') in LEGACY_LOCAL_SOURCES
-
-
def mountable(authority, sid):
"""``restore_routed_session`` would mount *sid* (this profile's messaging lineage root)."""
return _mount_plan(authority, sid) is not None
@@ -182,7 +164,7 @@ def superseded_hand_off(authority, ref):
route = (authority.db.get_session(ref.session_id) or {}).get('session_key')
# The routing entry moves at the platform's /new; the lane publishes its new conversation (and so
# supersedes a mounted one) only at its next inbound.
- return bool(live is not None and live.superseded) or _names_another_conversation(authority, ref.session_id, route)
+ return bool(live is not None and live.detached) or _names_another_conversation(authority, ref.session_id, route)
async def conversation_head(runner, session_id):
@@ -209,6 +191,6 @@ def follow_hand_off(authority, source, route, owner, local_owner):
if held is None or held.source is None or held.source.platform != Platform.LOCAL:
held = None
elif local_owner != owner:
- held.source, held.route, held.handed_off = source, route, True
+ held.source, held.route = source, route
if held is not None or owner in authority.sessions:
authority._publish_route(source, owner, route)
diff --git a/gateway/session_viewer_close.py b/gateway/session_viewer_close.py
index 725c2349911..3e052c7dcb0 100644
--- a/gateway/session_viewer_close.py
+++ b/gateway/session_viewer_close.py
@@ -22,6 +22,7 @@ import uuid
from functools import partial
from pathlib import Path
+from gateway.session_history_mount import is_history_mount
from hermes_state_local import local_receipt
from hermes_state_mutation_retirement import VIEWER_CLOSE_PREFIX
from hermes_state_runtime import RuntimeStoreError
@@ -83,8 +84,8 @@ async def close_viewer_session(authority, session_id, reason):
live = authority.sessions[session_id]
if live.subscribers:
return # a viewer attached while the detach was off the loop: nothing closes or ends
- if live.superseded:
- return # a read-only historic mount: its route's delegations and agent are the newer session's
+ if is_history_mount(live):
+ return # stored history: no route, agent or delegation of its own
from tools.async_delegation import interrupt_for_session, refuse_for_session
route = live.route
parents = tuple(dict.fromkeys((session_id, _physical_target(authority, session_id))))
@@ -155,7 +156,7 @@ def rearm_persisted_closes(authority):
for key, record in stored:
session_id = key[len(CLOSE_PREFIX):]
live = authority.sessions.get(session_id)
- if live is None or live.superseded:
+ if live is None or is_history_mount(live):
continue # not restored (paused, retired): left stored for a later recovery
if live.subscribers:
forget_persisted_close(authority, session_id, record)
@@ -221,7 +222,7 @@ def arm_orphan_close(authority, session_id, reason, grace):
close it as a viewer would, without stopping its turn or its async delegations (#106742). A
stopping owner arms nothing; the next boot does (``recover_local_sessions``)."""
live = authority.sessions.get(session_id)
- if not grace or live is None or live.subscribers or live.superseded or _stopping(authority):
+ if not grace or live is None or live.subscribers or is_history_mount(live) or _stopping(authority):
return
cancel_orphan_close(authority, session_id)
authority.orphan_closes[session_id] = _call_later(
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index 02c2f7c6e70..33d0e6b830d 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -176,6 +176,14 @@ class GatewaySessionCommandsMixin:
await self.hooks.emit("session:end", dict(hook_payload))
await self.hooks.emit("session:reset", dict(hook_payload))
+ def _name_lane(self, source, session_key: str, session_id: str) -> None:
+ """The chat now names another conversation: a view still open on its previous one detaches
+ at once, not at the chat's next message (``SessionAuthority.name_lane``)."""
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self)
+ if authority is not None:
+ authority.name_lane(session_key, authority.logical_owner(session_id), source)
+
async def _handle_discard_command(self, event: MessageEvent) -> str:
"""``/discard``: drop this chat's turn lost in a gateway restart so its queue runs again."""
from gateway.session_authorities import active_authority
@@ -227,6 +235,8 @@ class GatewaySessionCommandsMixin:
async with route_owner_lock(self, _old_sid):
new_entry = await self.async_session_store.reset_session(session_key)
await move_route_wakes(self, session_key, _old_sid) # main #114456: a parked wake survives /new
+ if new_entry:
+ self._name_lane(source, session_key, new_entry.session_id)
await self._fire_session_reset_hooks(source, session_key, _old_sid,
new_entry.session_id if new_entry else None)
# Scoped to the profile serving this source so a multiplexed /new banner reports the
@@ -1096,6 +1106,7 @@ class GatewaySessionCommandsMixin:
return t("gateway.resume.switch_failed")
if local_owner is not None and authority is not None: # a Desktop still viewing it follows it
follow_hand_off(authority, source, session_key, authority.logical_owner(target_id), local_owner)
+ self._name_lane(source, session_key, target_id)
# Conversation boundary: all conversation-scoped state + security state in one funnel call.
# Conversation boundary: clear ALL conversation-scoped per-session state (model/reasoning overrides
# #10702, one-turn restores, model notes, last-resolved cache #58403, /queue overflow) + security
@@ -1276,6 +1287,7 @@ class GatewaySessionCommandsMixin:
new_entry = await self.async_session_store.switch_session(dest_key, new_session_id)
if not new_entry:
return t("gateway.branch.switch_failed")
+ self._name_lane(dest_source, dest_key, new_session_id)
self._clear_session_boundary_security_state(dest_key)
self._evict_cached_agent(dest_key)
msg_count = len([m for m in history if m.get("role") == "user"])
diff --git a/tests/gateway/test_authority_cold_route_recovery.py b/tests/gateway/test_authority_cold_route_recovery.py
index 17989f379b1..32b7dae946e 100644
--- a/tests/gateway/test_authority_cold_route_recovery.py
+++ b/tests/gateway/test_authority_cold_route_recovery.py
@@ -28,6 +28,9 @@ class _Runner(GatewayAuthorizationMixin):
self.adapters = {}
self._draining = False
+ def _cached_agent_for(self, route): # no turn ran in these fixtures: no route holds an agent
+ return None
+
def _source(platform='telegram', chat_id='4242', profile=None, chat_name=None):
from gateway.config import Platform
@@ -140,8 +143,9 @@ async def test_a_row_its_route_moved_past_mounts_from_its_own_origin(tmp_path):
cold.authority.authorize(cold.actor, _ref('old'), 'session:read')
live = cold.authority.sessions['old']
+ # Teknium's ruling: off the chat's route, on a key of its own (gateway/session_detached.py).
assert (live.route, live.source.platform, live.source.chat_id, live.source.chat_name) == (
- cold.store._generate_session_key(_source()), Platform.TELEGRAM, '4242', 'from-row')
+ 'agent:main:detached:old', Platform.TELEGRAM, '4242', 'from-row')
@pytest.mark.asyncio
@@ -269,31 +273,27 @@ async def _superseded(tmp_path):
@pytest.mark.asyncio
-async def test_a_row_its_route_moved_past_is_read_only(tmp_path):
- """#140183 review F2: the old row's only route is the lane's CURRENT key, so a Stop, an agent
- lookup or a turn on it reached the successor conversation. One gateway owns every session and
- never crosses them: the historic row reads (its own transcript) and refuses every write by name."""
- from hermes_state_runtime import RuntimeStoreError
- from gateway.session_contract import Principal, Submission
+async def test_a_row_its_route_moved_past_stays_writable_on_its_own_key(tmp_path):
+ """#140183 review F2: the old row's only route was the lane's CURRENT key, so a Stop, an agent
+ lookup or a turn on it reached the successor conversation. Teknium's ruling reverses the
+ read-only answer: the row detaches onto a key of its own, so every write is accepted and acts on
+ it alone; the successor's agent is never resolved through it."""
+ from gateway.session_contract import Principal
cold, _successor = await _superseded(tmp_path)
cold.authority.authorize(cold.actor, _ref('old'), 'session:read')
caps = frozenset({'session:read', 'session:submit', 'session:control', 'session:approve',
'session:respond'})
writer = Principal('viewer', 'fixture', caps, 'socket')
for capability in sorted(caps - {'session:read'}):
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- cold.authority.authorize(writer, _ref('old'), capability)
- # The successor's running agent sits under the shared route; the old row never resolves it.
- route = cold.authority.sessions['old'].route
- cold.authority.runner._running_agents = {route: object()}
+ cold.authority.authorize(writer, _ref('old'), capability)
+ # The successor's running agent sits under the lane's route; the old row never resolves it.
+ lane = cold.store._generate_session_key(_source())
+ assert cold.authority.sessions['old'].route == 'agent:main:detached:old'
+ cold.authority.runner._running_agents = {lane: object()}
cold.authority.runner._cached_agent_for = lambda key: cold.authority.runner._running_agents.get(key)
assert cold.authority.agent(_ref('old')) is None
assert cold.authority._runs_own_agent(_ref('old')) is False
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- await cold.authority.interrupt(writer, _ref('old'), 0)
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- await cold.authority.submit(writer, Submission('r1', _ref('old'), {'text': 'hi'}, 'queue'))
- assert cold.authority.db.get_session('old')['message_count'] == 0
+ await cold.authority.interrupt(writer, _ref('old'), 0)
@pytest.mark.asyncio
@@ -311,7 +311,9 @@ async def test_closing_or_deleting_a_superseded_row_leaves_the_successor_route_a
cold.authority.runner._evict_cached_agent = lambda key, **kw: touched.append(('evict', key))
await close_viewer_session(cold.authority, 'old', 'tui_close')
retire_live_sessions(cold.authority, ['old'])
- assert touched == []
+ # Teknium's ruling: the row acts on its own detached key, never the successor's route.
+ keys = {kw.get('session_key') if kind != 'evict' else kw for kind, kw in touched}
+ assert keys == {'agent:main:detached:old'}, touched
assert 'old' not in cold.authority.sessions
@@ -322,8 +324,9 @@ async def test_the_lane_reopening_the_row_makes_it_live_again(tmp_path):
cold, _successor = await _superseded(tmp_path)
cold.authority.authorize(cold.actor, _ref('old'), 'session:read')
live = cold.authority.sessions['old']
- cold.authority._publish_route(live.source, 'old', live.route)
- assert cold.authority.sessions['old'] is live and live.superseded is False
+ lane = cold.store._generate_session_key(_source())
+ cold.authority._publish_route(_source(), 'old', lane)
+ assert cold.authority.sessions['old'] is live and (live.route, live.detached) == (lane, False)
@pytest.mark.asyncio
@@ -334,7 +337,7 @@ async def test_a_row_whose_lane_has_no_entry_mounts_live(tmp_path):
cold = await _cold(tmp_path)
writer = Principal('viewer', 'fixture', frozenset({'session:read', 'session:submit'}), 'socket')
cold.authority.authorize(writer, _ref('unrouted'), 'session:submit')
- assert cold.authority.sessions['unrouted'].superseded is False
+ assert cold.authority.sessions['unrouted'].detached is False
def _compressed_lane(tmp_path):
@@ -376,7 +379,7 @@ async def test_resume_of_a_compression_child_attaches_to_its_logical_owner(tmp_p
'params': {'session_id': 'lane-tip'}})
assert resumed.get('result', {}).get('session_id') == 'lane-root', resumed
assert 'lane-tip' not in cold.authority.sessions
- assert cold.authority.sessions['lane-root'].superseded is False
+ assert cold.authority.sessions['lane-root'].detached is False
@pytest.mark.asyncio
@@ -413,14 +416,13 @@ async def test_resume_by_a_messaging_segment_shares_the_lanes_next_inbound_mount
mounted = sorted(sid for sid, live in cold.authority.sessions.items() if live.route == route)
assert resumed.get('result', {}).get('session_id') == inbound == root, (resumed, inbound, mounted)
assert mounted == [root]
- assert cold.authority.sessions[root].superseded is False
+ assert cold.authority.sessions[root].detached is False
@pytest.mark.asyncio
-async def test_a_live_mount_goes_read_only_when_its_lane_publishes_another_conversation(tmp_path):
+async def test_a_live_mount_detaches_when_its_lane_publishes_another_conversation(tmp_path):
"""Mounted while nothing named another conversation, then the lane's next inbound starts a fresh
- session on the same route: from then on the old mount's route is the newer session's."""
- from hermes_state_runtime import RuntimeStoreError
+ session on the same route: from then on the old mount runs on a key of its own."""
from gateway.session_contract import Principal
_seed(tmp_path, 'unrouted', _source(), routed=False)
cold = await _cold(tmp_path)
@@ -428,6 +430,7 @@ async def test_a_live_mount_goes_read_only_when_its_lane_publishes_another_conve
cold.authority.authorize(writer, _ref('unrouted'), 'session:submit')
fresh = cold.store.get_or_create_session(_source(), force_new=True)
cold.authority._publish_route(_source(), fresh.session_id, fresh.session_key)
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- cold.authority.authorize(writer, _ref('unrouted'), 'session:submit')
+ # Teknium's ruling: it stays writable, detached onto its own key.
+ cold.authority.authorize(writer, _ref('unrouted'), 'session:submit')
+ assert cold.authority.sessions['unrouted'].route == 'agent:main:detached:unrouted'
cold.authority.authorize(writer, _ref(fresh.session_id), 'session:submit')
diff --git a/tests/gateway/test_authority_lane_moves_on.py b/tests/gateway/test_authority_lane_moves_on.py
new file mode 100644
index 00000000000..9fd7f9bce36
--- /dev/null
+++ b/tests/gateway/test_authority_lane_moves_on.py
@@ -0,0 +1,133 @@
+"""After a chat moves to a new conversation, an app view of its old one keeps working, off the chat.
+
+Teknium's ruling: a messaging chat's ``/new`` must not lock Desktop / Webapp / mobile users out of
+the conversation they have open, and the chat must not get that conversation's replies once it is on
+another one. A Discord chat's conversation A is open in an app; the chat sends ``/new`` and then a
+message, which runs in its new conversation B. The app's prompt on A runs in A on A's own key, and
+the chat adapter receives nothing from it; B's turns and the chat's replies are untouched. A
+``/resume`` of A on the chat brings A's replies back to the chat. Real GatewayRunner, DiscordAdapter
+(its ``send`` recorded), SessionAuthority, drain and session resolver over a real SessionDB; the
+agent run is a stand-in that answers with the session and route it was given.
+"""
+import asyncio
+
+import pytest
+
+from tests.waiting import async_wait_until
+
+
+async def _gateway(monkeypatch):
+ from gateway.config import GatewayConfig, Platform, PlatformConfig
+ from gateway.platforms.base import SendResult
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_results import execution_result
+ from plugins.platforms.discord.adapter import DiscordAdapter
+
+ monkeypatch.setenv('DISCORD_ALLOWED_USERS', '42')
+ runner = GatewayRunner(GatewayConfig())
+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token='fixture-token', typing_indicator=False))
+ sent = []
+
+ async def send(chat_id, content, reply_to=None, metadata=None):
+ sent.append(content)
+ return SendResult(success=True, message_id='s')
+ monkeypatch.setattr(adapter, 'send', send)
+ runner.adapters = {Platform.DISCORD: adapter}
+ monkeypatch.setattr(runner, '_read_user_config', lambda: {'approvals': {'destructive_slash_confirm': False}})
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')
+ runner._wire_adapter_handlers(adapter)
+ ran, gates = [], {}
+
+ async def agent_turn(event, source, session_entry, session_key, *args):
+ # The stand-in agent: it answers with where it ran, so a reply in the chat names its source.
+ ran.append((event.text, session_entry.session_id, session_key))
+ if event.text in gates:
+ await gates[event.text].wait()
+ reply = f'reply to {event.text!r} from {session_entry.session_id}'
+ execution_result.get()['result'] = {'final_response': reply, 'messages': []}
+ return reply, None
+ monkeypatch.setattr(runner, '_hmwa_prepare_turn', agent_turn)
+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')
+ return runner, adapter, authority, source, sent, ran, gates
+
+
+async def _chat(adapter, source, sent, text):
+ from gateway.platforms.event import MessageEvent
+ before = len(sent)
+ await adapter.handle_message(MessageEvent(text=text, source=source, message_id=text))
+ await async_wait_until(lambda: len(sent) > before, what=f'the reply to {text!r}')
+
+
+def _app():
+ from gateway.session_contract import Principal
+ return Principal('app-viewer', 'default', frozenset(
+ {'session:read', 'session:submit', 'session:control', 'session:approve', 'session:respond'}), 'viewer')
+
+
+async def _app_turn(authority, ref, text):
+ """The app's prompt, settled: ``(status, outcome)`` of its admission."""
+ from gateway.session_contract import Submission
+ from hermes_state_runtime import list_session_admissions
+ receipt = await authority.submit(_app(), Submission(text, ref, {'text': text}, 'queue'))
+
+ def settled():
+ rows = [row for row in list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)
+ if row['admission_id'] == receipt.admission_id and row['status'] == 'terminal']
+ return rows and rows[0]
+ row = await async_wait_until(settled, timeout=10, what=f'the app turn {text!r}')
+ await asyncio.wait_for(authority.sessions[ref.session_id].task, 10) # its delivery runs after the settlement
+ return row['status'], row['outcome']
+
+
+async def test_the_app_keeps_its_old_conversation_and_the_chat_gets_none_of_its_replies(monkeypatch):
+ runner, adapter, authority, source, sent, ran, _gates = await _gateway(monkeypatch)
+ lane = runner.session_store._generate_session_key(source)
+ await _chat(adapter, source, sent, 'hello')
+ a = runner.session_store.peek_session_id(lane)
+ ref_a = authority.register(source)
+ await _chat(adapter, source, sent, '/new')
+ await _chat(adapter, source, sent, 'hello again')
+ b = runner.session_store.peek_session_id(lane)
+ assert b != a
+ chat_replies = len(sent)
+
+ assert await _app_turn(authority, ref_a, 'from the app') == ('terminal', 'completed')
+ text, ran_in, key = ran[-1]
+ assert (text, ran_in) == ('from the app', a) # in A, on A's own key, not the chat's
+ assert key != lane and runner.session_store.peek_session_id(lane) == b
+ assert len(sent) == chat_replies, f'the chat got the old conversation\'s reply: {sent[chat_replies:]}'
+
+ await _chat(adapter, source, sent, 'still here') # the chat keeps its new conversation
+ assert ran[-1][1:] == (b, lane) and sent[-1] == f"reply to 'still here' from {b}"
+
+
+async def test_the_old_conversation_runs_beside_the_chats_turn_and_resume_brings_its_replies_back(monkeypatch):
+ runner, adapter, authority, source, sent, ran, gates = await _gateway(monkeypatch)
+ lane = runner.session_store._generate_session_key(source)
+ await _chat(adapter, source, sent, 'hello')
+ a = runner.session_store.peek_session_id(lane)
+ ref_a = authority.register(source)
+ authority.db.set_session_title(a, 'First chat')
+ await _chat(adapter, source, sent, '/new')
+
+ from gateway.platforms.event import MessageEvent
+ gates['long chat turn'] = asyncio.Event()
+ await adapter.handle_message(MessageEvent(text='long chat turn', source=source, message_id='long'))
+ await async_wait_until(lambda: ran and ran[-1][0] == 'long chat turn', what="B's turn to start")
+ b = ran[-1][1]
+ # While B's turn runs, the app's prompt and Stop on A act on A alone.
+ assert await _app_turn(authority, ref_a, 'meanwhile') == ('terminal', 'completed')
+ assert ran[-1][:2] == ('meanwhile', a)
+ await authority.interrupt(_app(), ref_a, authority._handle(ref_a).execution_generation)
+ gates['long chat turn'].set()
+ await async_wait_until(lambda: sent and sent[-1] == f"reply to 'long chat turn' from {b}", what="B's reply")
+ assert not any('meanwhile' in text for text in sent)
+
+ await _chat(adapter, source, sent, '/resume First chat')
+ chat_replies = len(sent)
+ assert await _app_turn(authority, ref_a, 'after resume') == ('terminal', 'completed')
+ assert ran[-1] == ('after resume', a, lane) # back on the chat's route
+ assert sent[chat_replies:] == [f"reply to 'after resume' from {a}"]
diff --git a/tests/gateway/test_handoff_local_receipt.py b/tests/gateway/test_handoff_local_receipt.py
index 7c8511e5fe7..b1e5d6a9b9f 100644
--- a/tests/gateway/test_handoff_local_receipt.py
+++ b/tests/gateway/test_handoff_local_receipt.py
@@ -59,7 +59,7 @@ def _as_an_older_build(monkeypatch):
async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path, monkeypatch, handed_off_by, history):
"""``reset``: a local ``/new`` moved the chat to a new segment and its receipt names that one. A
handoff carries the conversation the user is looking at: the lane continues the post-``/new``
- segment (the title follows it), and the earlier segment is that lane's read-only history, never a
+ segment (the title follows it), and the earlier segment is that lane's (detached) history, never a
local row no receipt restores."""
from gateway.config import Platform
from gateway.session_authority import initialize_session_authority
@@ -69,7 +69,6 @@ async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path,
from gateway.session_local_title import resolve_titled_session
from hermes_state_local import POLICY_PREFIX, local_receipt
from hermes_state_local_migration import LEGACY_PREFIX
- from hermes_state_runtime import RuntimeStoreError
runner = _Runner(tmp_path)
warm = await initialize_session_authority(runner, profile_id='fixture', instance_id='warm')
@@ -103,8 +102,7 @@ async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path,
# The Desktop that ran /handoff still holds the chat open.
warm.authorize(owner, ref, 'session:read')
if history == 'reset': # its pre-/new segment is the lane's history now
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- warm.authorize(owner, ref, 'session:control')
+ warm.authorize(owner, ref, 'session:control') # Teknium's ruling: writable, detached off the lane
else:
warm.authorize(owner, ref, 'session:control')
assert transcript_target(warm, ref) == warm.physical_target(ref)
@@ -121,11 +119,10 @@ async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path,
assert conn.execute('SELECT 1 FROM state_meta WHERE key IN (?,?)', keys).fetchone() is None
tip = cold.db.get_session(cold.physical_target(head))
assert json.loads(tip['origin_json'])['platform'] == 'telegram'
- if history == 'reset': # the earlier segment opens read-only on that lane
+ if history == 'reset': # the earlier segment opens off that lane
cold.authorize(webapp, ref, 'session:read')
- assert cold.sessions[ref.session_id].route == route
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- cold.authorize(webapp, ref, 'session:control')
+ assert cold.sessions[ref.session_id].detached # Teknium's ruling: off that lane, on its own key
+ cold.authorize(webapp, ref, 'session:control') # Teknium's ruling: writable, detached off the lane
@pytest.mark.asyncio
@@ -215,20 +212,18 @@ async def test_a_handed_off_bot_chat_whose_lane_moved_on_is_moved_aside(tmp_path
"""After the platform's own ``/new`` the handed-off chat is that lane's history: the canonical
title moves aside at once, so the Bots row's roster and its registry lookup agree at every step
(warm, cold) and its click mints a fresh Bot Chat; the Desktop still viewing the old one is
- read-only (its route names the new conversation)."""
+ detached onto its own key (Teknium's ruling: still writable, never reaching the chat)."""
from gateway.session_authority import initialize_session_authority
from gateway.session_bot import _target
from gateway.session_controls import AuthorityConnection
- from hermes_state_runtime import RuntimeStoreError
runner, warm, owner, ref, telegram, route = await _handed_off_bot_chat(tmp_path)
assert await _bot_row(warm, owner) == ref.session_id
runner.session_store.reset_session(route) # Telegram's /new
assert await _bot_row(warm, owner) is None
newer = warm.register(telegram)
assert newer != ref and warm.sessions[newer.session_id].route == route
- assert warm.sessions[ref.session_id].superseded and warm.agent(ref) is None
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- warm.authorize(owner, ref, 'session:control')
+ assert warm.sessions[ref.session_id].detached and warm.agent(ref) is None
+ warm.authorize(owner, ref, 'session:control') # Teknium's ruling: writable, detached off the lane
cold_runner = _Runner(tmp_path)
cold = await initialize_session_authority(cold_runner, profile_id='fixture', instance_id='cold')
@@ -253,11 +248,10 @@ async def test_a_handed_off_bot_chat_whose_lane_moved_on_is_moved_aside(tmp_path
@pytest.mark.asyncio
async def test_a_second_chat_handed_off_to_the_same_home_chat_supersedes_the_first(tmp_path):
"""Desktop A handed off its Bot Chat H to the Telegram home chat; Desktop B then hands off its
- own open chat Y there. The lane names Y now: H is history, read-only for the Desktop still
+ own open chat Y there. The lane names Y now: H is history, detached for the Desktop still
viewing it (a Stop or turn through it would act on Y), and its canonical title moves aside."""
from gateway.session_authority import initialize_session_authority
from gateway.session_local import create_local_session
- from hermes_state_runtime import RuntimeStoreError
runner, warm, owner, ref, telegram, route = await _handed_off_bot_chat(tmp_path)
other = create_local_session(warm, owner, {'request_id': 'other-chat', 'source': 'gui', 'cwd': str(tmp_path),
'model': 'frozen', 'toolsets': []})
@@ -265,22 +259,19 @@ async def test_a_second_chat_handed_off_to_the_same_home_chat_supersedes_the_fir
assert await _handoff(runner, warm, other.session_id, telegram) == route
assert warm.logical_owner(runner.session_store.lookup_by_session_key(route).session_id) == other.session_id
warm.authorize(owner, other, 'session:submit')
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- warm.authorize(owner, ref, 'session:submit')
+ warm.authorize(owner, ref, 'session:submit') # Teknium's ruling: writable, detached off the lane
assert warm.agent(ref) is None
assert await _bot_row(warm, owner) is None
# H handed off there again: the lane names H once more, and Y is the one that is history now.
await _handoff(runner, warm, ref.session_id, telegram)
warm.authorize(owner, ref, 'session:submit')
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- warm.authorize(owner, other, 'session:submit')
+ warm.authorize(owner, other, 'session:submit') # Teknium's ruling: writable, detached off the lane
cold = await initialize_session_authority(_Runner(tmp_path), profile_id='fixture', instance_id='cold')
cold.authorize(owner, ref, 'session:control')
cold.authorize(owner, other, 'session:read')
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- cold.authorize(owner, other, 'session:control')
+ cold.authorize(owner, other, 'session:control') # Teknium's ruling: writable, detached off the lane
@pytest.mark.asyncio
@@ -390,20 +381,19 @@ async def test_a_platform_resume_of_a_local_conversation_continues_its_current_h
@pytest.mark.parametrize('takeover', ['another chat handed off', "the platform's /new"])
@pytest.mark.parametrize('door', ['/handoff', 'platform /resume'])
@pytest.mark.parametrize('history', ['plain', 'reset'])
-async def test_a_moved_conversation_is_read_only_once_its_lane_is_taken_over(tmp_path, history, door, takeover,
+async def test_a_moved_conversation_stays_writable_once_its_lane_is_taken_over(tmp_path, history, door, takeover,
opened):
"""Bot Chat X (``reset``: a local ``/new`` moved it to X2) moves onto a Telegram lane, which
continues its head, writable there. Once that lane is taken over (another chat handed off to
it, or the platform's ``/new`` and its next inbound) the head is the lane's history, however it
was mounted: the Desktop that followed it, a viewer or the lane's inbound after a restart. Its
- only route is the lane's, so a turn or a Stop through it would act on the new conversation:
- read stays open, submit and control are refused, warm and after a restart."""
+ route was the lane's, so it detaches onto its own key (Teknium's ruling): read, submit and control
+ stay open and act on it alone, warm and after a restart."""
from gateway.platforms.event import MessageEvent
from gateway.session_authority import initialize_session_authority
from gateway.session_contract import Principal, SessionRef
from gateway.session_local import create_local_session
from hermes_state_local import local_receipt
- from hermes_state_runtime import RuntimeStoreError
runner = _Runner(tmp_path)
warm = await initialize_session_authority(runner, profile_id='fixture', instance_id='warm')
owner = Principal('owner', 'fixture', frozenset({'session:create', 'session:read', 'session:control',
@@ -443,18 +433,17 @@ async def test_a_moved_conversation_is_read_only_once_its_lane_is_taken_over(tmp
for authority in (warm, cold):
authority.authorize(owner, head, 'session:read')
for capability in ('session:submit', 'session:control'):
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- authority.authorize(owner, head, capability)
+ authority.authorize(owner, head, capability) # Teknium's ruling: writable, detached off the lane
assert authority.agent(head) is None # never the lane's running agent
@pytest.mark.asyncio
-async def test_a_moved_conversation_mounted_by_startup_recovery_is_read_only_once_its_lane_is_taken_over(
+async def test_a_moved_conversation_mounted_by_startup_recovery_stays_writable_once_its_lane_is_taken_over(
tmp_path, monkeypatch):
"""Bot Chat A moves onto a Telegram chat and stays there for months: its idle local routing entry
is pruned (``session_store_max_age_days``). A restart finds the lane's input still queued, so
startup recovery is what mounts A, and the lane's next inbound reuses that mount. Once another
- chat is handed off to the lane, A is its history: a viewer's turn would run as that chat's."""
+ chat is handed off to the lane, A is its history, detached: a viewer's turn runs on A alone."""
from datetime import datetime, timedelta
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.platforms.event import MessageEvent
@@ -464,7 +453,6 @@ async def test_a_moved_conversation_mounted_by_startup_recovery_is_read_only_onc
from gateway.session_contract import Principal
from gateway.session_ingress_context import native_callback, register_transport_home
from gateway.session_local import create_local_session
- from hermes_state_runtime import RuntimeStoreError
from tests.gateway.test_command_bypass_active_session import _StubAdapter
monkeypatch.setenv('TELEGRAM_ALLOWED_USERS', '42')
monkeypatch.setattr('gateway.run._hermes_home', tmp_path)
@@ -510,8 +498,7 @@ async def test_a_moved_conversation_mounted_by_startup_recovery_is_read_only_onc
await _handoff(runner, cold, chat(cold, 'Chat B').session_id, telegram)
cold.authorize(owner, a, 'session:read')
for capability in ('session:submit', 'session:control'):
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- cold.authorize(owner, a, capability)
+ cold.authorize(owner, a, capability) # Teknium's ruling: writable, detached off the lane
finally:
runner.session_store.close_all_db_handles()
@@ -521,12 +508,11 @@ async def test_a_moved_conversation_resumed_on_another_chat_moves_there(tmp_path
"""Bot Chat A moves onto Telegram chat 4242, chat B is handed off there in turn (A is that chat's
history now), then an admin's ``/resume --all Chat A`` brings A to chat 77. Its mount follows it:
a turn or a Stop through it acts on chat 77, never on B, which holds 4242; and once chat 77 moves
- on (its ``/new``) A is that chat's history, read-only again."""
+ on (its ``/new``) A is that chat's history, detached again."""
from gateway.platforms.event import MessageEvent
from gateway.session_authority import initialize_session_authority
from gateway.session_contract import Principal
from gateway.session_local import create_local_session
- from hermes_state_runtime import RuntimeStoreError
runner = _Runner(tmp_path)
warm = await initialize_session_authority(runner, profile_id='fixture', instance_id='warm')
owner = Principal('owner', 'fixture', frozenset({'session:create', 'session:read', 'session:control',
@@ -542,8 +528,7 @@ async def test_a_moved_conversation_resumed_on_another_chat_moves_there(tmp_path
a = chat('Chat A')
await _handoff(runner, warm, a.session_id, first)
await _handoff(runner, warm, chat('Chat B').session_id, first)
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- warm.authorize(owner, a, 'session:submit')
+ warm.authorize(owner, a, 'session:submit') # Teknium's ruling: writable, detached off the lane
await _resume_gateway(runner, warm)._handle_resume_command(
MessageEvent(text='/resume --all Chat A', source=second))
route = runner.session_store._generate_session_key(second)
@@ -556,8 +541,7 @@ async def test_a_moved_conversation_resumed_on_another_chat_moves_there(tmp_path
runner.session_store.reset_session(route)
warm.register(second)
for capability in ('session:submit', 'session:control'):
- with pytest.raises(RuntimeStoreError, match='session_superseded'):
- warm.authorize(owner, a, capability)
+ warm.authorize(owner, a, capability) # Teknium's ruling: writable, detached off the lane
@pytest.mark.asyncio
diff --git a/tests/gateway/test_messaging_session_moved_on.py b/tests/gateway/test_messaging_session_moved_on.py
index 4b49bc81b19..60339f3fc2d 100644
--- a/tests/gateway/test_messaging_session_moved_on.py
+++ b/tests/gateway/test_messaging_session_moved_on.py
@@ -38,7 +38,7 @@ async def test_an_unviewed_superseded_mount_is_not_listed_live(tmp_path):
'provider': 'local', 'user_id': 'viewer', 'profile_id': 'fixture', 'instance_id': 'cold',
'capabilities': ['session:read']})
resumed = await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 'old'}})
- assert cold.authority.sessions['old'].superseded, resumed
+ assert cold.authority.sessions['old'].detached, resumed
listed = await connection.dispatch({'id': 2, 'method': 'session.list', 'params': {}})
assert 'old' in {row['id'] for row in listed['result']['sessions']}, 'a viewed historic mount stays listed'
@@ -61,8 +61,9 @@ async def test_an_old_messaging_conversation_can_be_deleted_from_the_picker(tmp_
'provider': 'local', 'user_id': 'viewer', 'profile_id': 'fixture', 'instance_id': 'cold',
'capabilities': ['session:read', 'session:control']})
resumed = await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 'old'}})
- assert cold.authority.sessions['old'].superseded, resumed
- cold.authority.runner._evict_cached_agent = lambda key, **kw: pytest.fail('evicted the chat route')
+ assert cold.authority.sessions['old'].detached, resumed
+ lane = cold.store._generate_session_key(successor.origin)
+ cold.authority.runner._evict_cached_agent = lambda key, **kw: key != lane or pytest.fail('evicted the chat route')
deleted = await connection.dispatch({'id': 2, 'method': 'session.mutate', 'params': {
'session_id': 'old', 'request_id': 'delete-old', 'operation': 'delete', 'payload': {},
@@ -76,7 +77,7 @@ async def test_an_old_messaging_conversation_can_be_deleted_from_the_picker(tmp_
@pytest.mark.asyncio
-async def test_an_old_messaging_conversation_still_refuses_every_other_write(tmp_path):
+async def test_an_old_messaging_conversation_takes_every_other_write(tmp_path):
from gateway.session_controls import AuthorityConnection
cold, _successor = await _superseded(tmp_path)
connection = AuthorityConnection(cold.authority, object(), {
@@ -86,7 +87,7 @@ async def test_an_old_messaging_conversation_still_refuses_every_other_write(tmp
renamed = await connection.dispatch({'id': 2, 'method': 'session.mutate', 'params': {
'session_id': 'old', 'request_id': 'rename-old', 'operation': 'rename', 'payload': {'title': 'x'},
'expected_revision': resumed['result']['revision']}})
- assert renamed.get('error', {}).get('message') == 'session_superseded', renamed
+ assert 'result' in renamed, renamed # Teknium's ruling: the apps keep a chat's old conversation
@pytest.mark.asyncio
diff --git a/tests/gateway/test_native_fifo_context_exhaustion.py b/tests/gateway/test_native_fifo_context_exhaustion.py
index f8ec0808203..382d626688c 100644
--- a/tests/gateway/test_native_fifo_context_exhaustion.py
+++ b/tests/gateway/test_native_fifo_context_exhaustion.py
@@ -204,7 +204,7 @@ async def test_no_scheduler_starts_the_fresh_fifo_before_reset_cleanup_finishes(
if len(executed) == 3:
break
await asyncio.sleep(0.02)
- new = runner.session_store.lookup_by_session_key(authority.sessions[old.session_id].route).session_id
+ new = runner.session_store.lookup_by_session_key(runner.session_store._generate_session_key(native.source)).session_id
assert executed == [("A", old.session_id), ("B", new), ("C", new)]
assert events.index("sync:done") < events.index("turn:B")
diff --git a/tests/gateway/test_stored_history_mount.py b/tests/gateway/test_stored_history_mount.py
index fb9b7eae0d7..e69e050681b 100644
--- a/tests/gateway/test_stored_history_mount.py
+++ b/tests/gateway/test_stored_history_mount.py
@@ -179,7 +179,7 @@ async def test_an_api_chat_opened_read_only_still_continues_through_the_api(tmp_
assert bind_api_session(conn.authority, 'api-1', caller_key='agent:main:api_server:dm:api-1') == ref
live = conn.authority.sessions['api-1']
- assert live.source.platform == Platform.API_SERVER and not live.superseded
+ assert live.source.platform == Platform.API_SERVER and not live.detached
live.event_stream.publish('api-1', {'text': 'bound'})
frame = await asyncio.to_thread(frames.get, True, 5)
assert frame['params']['payload'] == {'text': 'bound'}
diff --git a/tests/hermes_cli/test_foreign_sessions.py b/tests/hermes_cli/test_foreign_sessions.py
index 8b7efa66051..ed94896ac30 100644
--- a/tests/hermes_cli/test_foreign_sessions.py
+++ b/tests/hermes_cli/test_foreign_sessions.py
@@ -341,7 +341,7 @@ async def test_imported_chat_resumes_writable_as_cli(tmp_path, monkeypatch):
opened = await conn.resume(ref, {})
assert len(opened["messages"]) == 4
- assert not authority.sessions[session_id].superseded
+ assert not authority.sessions[session_id].detached
authority.authorize(conn.actor, ref, "session:submit")
diff --git a/tui_gateway/owner_forward.py b/tui_gateway/owner_forward.py
index 3ecc9851641..77d9d4347cb 100644
--- a/tui_gateway/owner_forward.py
+++ b/tui_gateway/owner_forward.py
@@ -50,7 +50,7 @@ _RELAYED = frozenset({"message.start", "message.complete"})
#: session row is deleted only with its admissions (``ON DELETE RESTRICT``), so that one never runs.
_REFUSED_BEFORE_COMMIT = frozenset({
"invalid_params", "runtime_draining", "runtime_retired", "profile_mismatch", "permission_denied",
- "not_found", "session_superseded", "stale_epoch", "admission_conflict", "queue_full"})
+ "not_found", "stale_epoch", "admission_conflict", "queue_full"})
class OwnerUnavailable(RuntimeError):