session_listing.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """Read-only native picker history; enumeration never adopts a transcript."""
  2. from hermes_state_local_migration import client_history_row, validate_legacy_row
  3. from hermes_state_mutation_binding import authorize_history
  4. from hermes_state_runtime import RuntimeStoreError
  5. from gateway.owner_identity import same_owner
  6. from gateway.session_route_recovery import _messaging_platform, mountable
  7. # Local labels (a cron run is a canonical local session whose last viewer is its own fire).
  8. _LOCAL_SOURCES = ('cli', 'tui', 'gui', 'desktop', 'local', 'cron')
  9. def _excluded_sources():
  10. """Main's picker listed every source but the internal ones; the API transport has its own restore.
  11. Plugin platforms are ``Platform`` pseudo-members enum iteration never yields, so the query
  12. excludes rather than enumerates, and each messaging row is judged by the cold mount's own check."""
  13. from hermes_state_sessions import INTERNAL_LISTING_SOURCES
  14. return [*INTERNAL_LISTING_SOURCES, 'api_server']
  15. def _picker_row(row, tip, sid):
  16. return {'id': row['id'], 'session_id': sid, 'resolved_id': sid, 'title': row.get('title') or '',
  17. 'source': tip['source'], 'started_at': row.get('started_at'),
  18. 'message_count': row.get('message_count', 0), 'model': tip.get('model'), 'running': False}
  19. def stored_picker_sessions(authority, actor, *, limit, include_hidden=False):
  20. """Offer legacy local rows only to the same native transport that may resume them.
  21. Canonical sessions are already in the live feed. Old local rows have no policy
  22. receipt until explicit resume; listing them must not claim or restore anything.
  23. """
  24. if actor.profile_id != authority.profile_id:
  25. raise RuntimeStoreError('profile_mismatch')
  26. if (getattr(authority, '_native_legacy_transports', {}).get(actor.transport_id) != actor
  27. or not {'session:read', 'session:create'} <= actor.capabilities):
  28. return {'sessions': [], 'scope': 'stored'}
  29. db = authority.db
  30. own_profile = db._own_profile_name() or 'default'
  31. sessions, offset, seen = [], 0, set()
  32. while len(sessions) < limit:
  33. rows = db.list_sessions_rich(exclude_sources=_excluded_sources(), limit=200, offset=offset,
  34. order_by_last_active=True, compact_rows=True, include_hidden=include_hidden)
  35. for row in rows:
  36. local = row['source'] in _LOCAL_SOURCES or client_history_row(row)
  37. if not local and _messaging_platform(row['source']) is None:
  38. continue # neither a local nor a messaging label (acp, unknown, ...): nothing this picker resumes
  39. sid = db.get_compression_tip(row['id']) or row['id']
  40. tip = db.get_session(sid)
  41. if tip is None:
  42. continue
  43. if not local:
  44. # A messaging conversation, under its lineage root (the cold mount; the listing
  45. # projects a compressed lineage onto its tip): this profile's rows the mount opens.
  46. root = row.get('_lineage_root_id') or row['id']
  47. if (row.get('profile_name') in (None, '', own_profile) and mountable(authority, root)
  48. and root not in seen):
  49. seen.add(root)
  50. sessions.append(_picker_row({**row, 'id': root}, tip, root))
  51. if len(sessions) == limit:
  52. break
  53. continue
  54. closed = _closed_local_session(authority, actor, row, tip)
  55. if closed is not None:
  56. if closed['id'] not in seen:
  57. seen.add(closed['id'])
  58. sessions.append(closed)
  59. if len(sessions) == limit:
  60. break
  61. continue
  62. try:
  63. validate_legacy_row(db, tip, subject=actor.subject)
  64. with db._read_ctx() as conn:
  65. if not authorize_history(conn, actor, sid):
  66. continue
  67. except RuntimeStoreError as exc:
  68. if exc.reason not in {'not_found', 'permission_denied'}:
  69. raise
  70. continue
  71. sessions.append(_picker_row(row, tip, sid))
  72. if len(sessions) == limit:
  73. break
  74. if len(rows) < 200:
  75. break
  76. offset += len(rows)
  77. return {'sessions': sessions, 'scope': 'stored'}
  78. def _closed_local_session(authority, actor, row, tip):
  79. """A canonical local session (created here, or adopted from main) its last viewer closed: main's
  80. picker listed it as resumable. None for anything else, including a session another principal owns."""
  81. from gateway.session_contract import SessionRef
  82. from gateway.session_local_close import closed_and_unviewed
  83. owner = tip.get('chat_id')
  84. live = authority.sessions.get(owner) if owner else None
  85. if live is None:
  86. if not owner or not _stored_closed(authority, actor, owner):
  87. return None
  88. else:
  89. try:
  90. handle = authority._handle(SessionRef(authority.profile_id, owner))
  91. authority.authorize(actor, handle.ref, 'session:read')
  92. except RuntimeStoreError:
  93. return None
  94. if not closed_and_unviewed(authority, owner, handle):
  95. return None
  96. return {'id': owner, 'session_id': owner, 'resolved_id': owner, 'title': tip.get('title') or row.get('title') or '',
  97. 'source': tip['source'], 'started_at': row.get('started_at'),
  98. 'message_count': row.get('message_count', 0), 'model': tip.get('model'), 'running': False}
  99. def _stored_closed(authority, actor, owner):
  100. """Boot leaves an ended session unrestored and a listing never restores one (a worker thread): judge
  101. its stored receipt as ``authorize`` and ``closed_and_unviewed`` would after a restore. No viewer."""
  102. from hermes_state_local import local_receipt
  103. from hermes_state_runtime import list_session_admissions
  104. if actor.profile_id != authority.profile_id or 'session:read' not in actor.capabilities:
  105. return False
  106. try:
  107. receipt = local_receipt(authority.db, owner)
  108. row = authority.db.get_session(receipt['entry']['session_id'])
  109. except (RuntimeStoreError, KeyError, TypeError):
  110. return False
  111. return (receipt.get('profile_id') == authority.profile_id
  112. and (same_owner(receipt.get('principal_id'), actor.subject) or 'session:operator' in actor.capabilities)
  113. and row is not None and row['ended_at'] is not None
  114. and not list_session_admissions(authority.db, session_id=owner))