session_route_recovery.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. """Mount a cold messaging-platform session into the authority for a local viewer (TUI-8).
  2. A messaging session (Telegram, Weixin, Discord, ...) is published into the authority only when its
  3. lane's first post-restart inbound runs ``_publish_route``, so ``session.resume`` of its row answered
  4. ``not_found`` until someone wrote to the lane again, on every gateway restart. Before the canonical
  5. authority (#106742) a viewer opened any such row straight from ``state.db``; this restores that for
  6. every cold row of this profile that carries a ``session_key`` and a messaging-platform source:
  7. * the lane's routing entry still names the row: its persisted ``origin`` is the highest-fidelity
  8. source, exactly what that first inbound would have published;
  9. * the route is gone or moved on (``/new``, reset, a pruned entry): the row's own ``origin_json``,
  10. else its columns, rebuild the source.
  11. Either way the source is revived through ``_restored_source``, so delivery stays pinned to the
  12. persisted receiving bot. A row the lane moved past mounts DETACHED (gateway/session_detached.py): the
  13. lane's current key names the newer conversation, so the row runs on a key of its own instead, its
  14. turns and Stop act on it alone and its replies reach its app viewers only, never the chat
  15. (Teknium's ruling: a chat's ``/new`` never locks the apps out of its old conversation). A compression continuation is never
  16. mounted under its physical id: the lane's turns publish to the lineage root (``logical_owner``), so
  17. ``session.resume`` maps it to that root, as normal admission does. Rows without a ``session_key`` (subagents) have nothing to rebuild a lane
  18. from. LOCAL rows (cron, CLI, TUI) restore from their private receipt and API rows from their binding
  19. (``restore_api_session``); neither is ever mounted here. The mount semantics are the first inbound's
  20. ``_publish_route``: a row that ended for a recoverable reason (``agent_close``, ``ws_orphan_reap``,
  21. ...) is mounted live too, as the lane's next message would reopen it.
  22. """
  23. import json
  24. from datetime import datetime
  25. from gateway.config import Platform
  26. def _messaging_platform(label):
  27. """The messaging ``Platform`` a row's ``source`` label names; None for the API transport (its
  28. own restore) and for labels no platform answers to (the CLI/TUI/cron local labels)."""
  29. try:
  30. platform = Platform(label)
  31. except ValueError:
  32. return None
  33. return None if platform in (Platform.LOCAL, Platform.API_SERVER) else platform
  34. def _routed_entry(authority, sid, route):
  35. """The routing entry that still names *sid* under *route*, else None."""
  36. store = authority.runner.session_store
  37. with store._lock:
  38. entry = store._entry_locked(route)
  39. if (entry is None or entry.origin is None or entry.session_key != route
  40. or authority.logical_owner(entry.session_id) != sid):
  41. return None
  42. return entry
  43. def _row_source(row, platform, profile):
  44. """The row's persisted origin, else its columns (``channel_directory`` reads rows the same way)."""
  45. from gateway.session import SessionSource
  46. try:
  47. return SessionSource.from_dict(json.loads(row['origin_json']))
  48. except (TypeError, ValueError, KeyError):
  49. pass
  50. if row.get('chat_id') is None:
  51. return None
  52. source = SessionSource(
  53. platform=platform, chat_id=str(row['chat_id']), user_id=row.get('user_id'),
  54. chat_type=row.get('chat_type') or 'dm', thread_id=row.get('thread_id'),
  55. chat_name=row.get('display_name'))
  56. if profile is not None:
  57. source.profile = profile
  58. return source
  59. def _names_another_conversation(authority, sid, route):
  60. """The lane's current routing entry names a conversation other than *sid* (``/new``, reset)."""
  61. store = authority.runner.session_store
  62. with store._lock:
  63. entry = store._entry_locked(route)
  64. return entry is not None and authority.logical_owner(entry.session_id) != sid
  65. def _row_entry(row, platform, route, profile):
  66. """A routing entry rebuilt from the row alone (the route no longer vouches for it)."""
  67. from gateway.session import SessionEntry
  68. source = _row_source(row, platform, profile)
  69. if source is None or source.platform != platform:
  70. return None
  71. started = datetime.fromtimestamp(row['started_at']) if row.get('started_at') else datetime.now()
  72. return SessionEntry(session_key=route, session_id=row['id'], created_at=started, updated_at=started,
  73. origin=source, platform=platform, chat_type=source.chat_type,
  74. transport_profile=row.get('transport_profile'))
  75. def _mount_plan(authority, sid):
  76. """``(route, entry, routed)`` for a row a route or a messaging-platform row can stand for, else
  77. None. Reads only: ``restore_routed_session`` mounts it, the stored picker lists it."""
  78. row = authority.db.get_session(sid)
  79. route = row.get('session_key') if row is not None else None
  80. platform = _messaging_platform(row['source']) if route else None
  81. if platform is None or authority.logical_owner(sid) != sid:
  82. return None # a compression continuation: its lineage root is the mount (session.resume maps it)
  83. store = authority.runner.session_store
  84. registry = getattr(authority.runner, 'session_authorities', None)
  85. profile = store._named_profile_for_key(route)
  86. if profile != (registry.profile_name(authority) if registry is not None else None):
  87. return None
  88. routed = _routed_entry(authority, sid, route)
  89. entry = routed or _row_entry(row, platform, route, profile)
  90. return None if entry is None else (route, entry, routed)
  91. def restore_routed_session(authority, sid):
  92. """Publish *sid* as its lane would after a restart; None when this row is not one a route or a
  93. messaging-platform row can stand for."""
  94. from gateway.session_authority import LiveSession
  95. from gateway.session_contract import SessionRef
  96. plan = _mount_plan(authority, sid)
  97. if plan is None:
  98. return None
  99. route, entry, routed = plan
  100. authority._require_admission_open()
  101. # Re-pin the persisted receiving bot so delivery after a restart goes through it or nowhere,
  102. # never the default bot by heuristic (gateway/AGENTS.md § Identity survives the process).
  103. source = authority.runner._restored_source(entry)
  104. if sid not in authority.sessions:
  105. live = authority.sessions[sid] = LiveSession(source, route)
  106. if routed is None and _names_another_conversation(authority, sid, route):
  107. from gateway.session_detached import detach
  108. detach(authority, live, sid) # the lane moved past it: its turns stay off the chat
  109. return SessionRef(authority.profile_id, sid)
  110. def mountable(authority, sid):
  111. """``restore_routed_session`` would mount *sid* (this profile's messaging lineage root)."""
  112. return _mount_plan(authority, sid) is not None
  113. def messaging_owner_ref(authority, ref):
  114. """The mount a messaging row resumes on: its compression lineage root, where the lane's turns
  115. publish their events (``logical_owner``). Any other row keeps *ref*."""
  116. row = authority.db.get_session(ref.session_id)
  117. if row is None or not row.get('session_key') or _messaging_platform(row['source']) is None:
  118. return ref
  119. from gateway.session_contract import SessionRef
  120. owner = authority.logical_owner(ref.session_id)
  121. return ref if owner == ref.session_id else SessionRef(ref.profile_id, owner)
  122. def handed_off_ref(authority, session_id):
  123. """The mount of *session_id* when it is a local conversation a messaging lane took over
  124. (``/handoff``, a platform ``/resume``): created by a local surface, now routed on a lane this
  125. authority mounts. Its title stays the conversation's, so ``/resume <title>`` and the Bots roster's
  126. registry lookup open it on that lane (#143286). None for any other row."""
  127. from gateway.session_contract import SessionRef
  128. from hermes_state_local_migration import LEGACY_LOCAL_SOURCES, client_label
  129. ref = messaging_owner_ref(authority, SessionRef(authority.profile_id, session_id))
  130. row = authority.db.get_session(ref.session_id) or {}
  131. created = row.get('created_source')
  132. # An adopted phone-app chat keeps the app's label as its created_source (bind_legacy_target).
  133. if (created not in LEGACY_LOCAL_SOURCES and not client_label(created)) or not mountable(authority, ref.session_id):
  134. return None
  135. return ref
  136. def superseded_hand_off(authority, ref):
  137. """Whether the lane that took over *ref* (a ``handed_off_ref``) has since moved on to another
  138. conversation (``/new``, a reset): the chat is history now, read-only on that lane."""
  139. live = authority.sessions.get(ref.session_id)
  140. route = (authority.db.get_session(ref.session_id) or {}).get('session_key')
  141. # The routing entry moves at the platform's /new; the lane publishes its new conversation (and so
  142. # supersedes a mounted one) only at its next inbound.
  143. return bool(live is not None and live.detached) or _names_another_conversation(authority, ref.session_id, route)
  144. async def conversation_head(runner, session_id):
  145. """``(authority, local owner or None, row id)`` a repoint of *session_id* onto a messaging lane
  146. carries (``/handoff``, a platform ``/resume``): a local conversation's current head
  147. (``hermes_state_local.handoff_head``), never an earlier ``/new`` segment, which would move that
  148. history onto the lane while the live conversation stays local, its receipt released (#143286)."""
  149. import asyncio
  150. from gateway.session_authorities import active_authority
  151. from hermes_state_local import handoff_head
  152. authority = active_authority(runner)
  153. db = authority.db if authority is not None else getattr(runner._session_db, '_db', runner._session_db)
  154. if db is None:
  155. return authority, None, session_id
  156. return (authority, *await asyncio.to_thread(handoff_head, db, session_id))
  157. def follow_hand_off(authority, source, route, owner, local_owner):
  158. """After ``/handoff`` repointed *route* at *owner* (the lane's logical id of the conversation's
  159. head): the local mount a viewer still holds (*local_owner*, the Desktop that ran it) moves onto
  160. the lane, as its receipt did. When the head is a later ``/new`` segment, that mount is the
  161. conversation's earlier history there, superseded once the head publishes (#143286)."""
  162. held = authority.sessions.get(local_owner) if local_owner else None
  163. if held is None or held.source is None or held.source.platform != Platform.LOCAL:
  164. held = None
  165. elif local_owner != owner:
  166. held.source, held.route = source, route
  167. if held is not None or owner in authority.sessions:
  168. authority._publish_route(source, owner, route)