session_display.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. """Per-turn client presentation (hidden widget intents, large-paste title preview) through canonical admission.
  2. The Desktop composer types some sends ``display_kind="hidden"`` (goal control, inline-preview decisions,
  3. first-run kickoffs): model-facing text no client may render as a user bubble. A large paste carries a
  4. ``title_preview`` that only the session titler reads. Both are facts about ONE admitted turn, committed with
  5. the admission row as ``display_v1`` so a retry, a queued drain or a managed child applies exactly what
  6. was admitted, and bound to that admission's own event, never to a later turn on the same task.
  7. """
  8. from contextlib import contextmanager
  9. from contextvars import ContextVar
  10. from hermes_state_runtime import RuntimeStoreError
  11. HIDDEN = 'hidden'
  12. _TITLE_PREVIEW_LIMIT = 1000
  13. _SUBMIT_FIELDS = ('display_kind', 'title_preview')
  14. _display_turn: ContextVar[tuple | None] = ContextVar('display_turn', default=None)
  15. _submission_turn: ContextVar[tuple | None] = ContextVar('submission_turn', default=None)
  16. def submit_display_fields(params):
  17. """The raw per-turn presentation fields of a ``prompt.submit`` request, forwarded to admission."""
  18. return {key: params[key] for key in _SUBMIT_FIELDS if key in params}
  19. def admit_display(params):
  20. """Wire ``display_kind`` / ``title_preview`` -> committed ``display_v1`` (``{}`` when absent).
  21. Only ``hidden`` is a client-authorable kind; anything else is refused rather than rendered,
  22. so a typo can never turn machine text into a visible user row."""
  23. kind, preview = params.get('display_kind'), params.get('title_preview')
  24. if kind is not None and kind != HIDDEN:
  25. raise RuntimeStoreError('invalid_params')
  26. if preview is not None and not isinstance(preview, str):
  27. raise RuntimeStoreError('invalid_params')
  28. committed = {}
  29. if kind:
  30. committed['kind'] = HIDDEN
  31. if preview and preview.strip():
  32. committed['title_preview'] = preview[:_TITLE_PREVIEW_LIMIT]
  33. return {'display_v1': committed} if committed else {}
  34. def restore_display(committed):
  35. """A committed ``display_v1`` arriving across a process boundary (managed worker), re-checked by the
  36. admission validator: only an object admission itself could have committed is accepted."""
  37. if not isinstance(committed, dict) or not committed or set(committed) - {'kind', 'title_preview'}:
  38. raise RuntimeStoreError('invalid_params')
  39. wire = {'display_kind': committed.get('kind'), 'title_preview': committed.get('title_preview')}
  40. if admit_display(wire).get('display_v1') != committed:
  41. raise RuntimeStoreError('invalid_params')
  42. return committed
  43. @contextmanager
  44. def display_turn_scope(admission_id, committed):
  45. token = _display_turn.set((admission_id, committed) if committed else None)
  46. try:
  47. yield
  48. finally:
  49. _display_turn.reset(token)
  50. @contextmanager
  51. def submission_turn_scope(admission_id, submission_id):
  52. """Bind the client's ``submission_id`` (the admission's ``request_id``) to the admission's own event.
  53. The user row this turn persists carries it, so a client whose window closed before the submit ack
  54. came back can read the stored transcript and tell a send that landed from one that never did."""
  55. token = _submission_turn.set((admission_id, submission_id) if submission_id else None)
  56. try:
  57. yield
  58. finally:
  59. _submission_turn.reset(token)
  60. def admission_submission(event):
  61. """``{'submission_id': ...}`` for the admission ``event`` executes, ``{}`` for any other event."""
  62. bound = _submission_turn.get()
  63. if bound is None or event is None or getattr(event, 'message_id', None) != bound[0]:
  64. return {}
  65. return {'submission_id': bound[1]}
  66. def admission_display(event):
  67. """The committed presentation of the admission ``event`` executes (its ``message_id`` is the
  68. admission id), ``{}`` for any other event: a follow-up on the same task never inherits it."""
  69. bound = _display_turn.get()
  70. if bound is None or event is None or getattr(event, 'message_id', None) != bound[0]:
  71. return {}
  72. return bound[1]
  73. def worker_display_kwargs():
  74. """``run_conversation`` persistence kwargs of the managed child's single admitted turn."""
  75. bound = _display_turn.get()
  76. committed = bound[1] if bound is not None else {}
  77. return {**({'persist_user_display_kind': HIDDEN} if committed.get('kind') == HIDDEN else {}),
  78. **({'persist_user_display_metadata': {'title_preview': committed['title_preview']}}
  79. if committed.get('title_preview') else {})}