desktop_ui.py 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/env python3
  2. """Bridge desktop-only tools to Hermes-desktop renderer events.
  3. The desktop ``tui_gateway`` installs an emitter via :func:`set_emitter`; elsewhere it
  4. stays ``None`` and tools report "desktop only". Routing keys off ``HERMES_UI_SESSION_ID``
  5. so the event lands on the window that owns the turn (the sink is lock-guarded).
  6. Window-level events (``pane.reveal``, ``preview.open``) route by
  7. ``HERMES_UI_SESSION_ID`` — the window/socket that owns the turn.
  8. Session-scoped events (``message.reaction``) route by ``HERMES_SESSION_ID``
  9. so the renderer's gateway-event stream, keyed on the chat session, receives
  10. the frame on the correct transcript transport (#80678).
  11. """
  12. import json
  13. from typing import Callable, FrozenSet, Optional
  14. from gateway.session_context import get_session_env
  15. from tools.registry import tool_error
  16. # (sid, event, payload) sink, installed by the desktop gateway.
  17. _emit: Optional[Callable[[str, str, dict], None]] = None
  18. # Events that target a specific chat session rather than a window/socket.
  19. # The renderer's gateway-event stream is keyed on the session id, so
  20. # routing these through HERMES_UI_SESSION_ID (the window identity) means
  21. # the frame lands on a stream that doesn't own the transcript and is
  22. # never painted (#80678).
  23. _SESSION_SCOPED_EVENTS: frozenset[str] = frozenset({"message.reaction"})
  24. def set_emitter(fn: Optional[Callable[[str, str, dict], None]]) -> None:
  25. """Install (or clear) the renderer-event sink. Called by the desktop gateway."""
  26. global _emit
  27. _emit = fn
  28. def available() -> bool:
  29. """True when running under the desktop app (an emitter is wired)."""
  30. return _emit is not None
  31. def user_enabled(setting: str, default: bool) -> bool:
  32. """Read a desktop Appearance switch from ``display.<setting>``. The renderer mirrors
  33. these toggles onto the CONNECTED gateway's config, so this is the user's real answer
  34. for local/SSH/URL/cloud gateways alike; ``check_fn``s use it to withdraw a tool from
  35. the schema. Unreadable config -> ``default`` so a shipped-on feature does not vanish
  36. on a transient read error."""
  37. try:
  38. from hermes_cli.config import load_config_readonly
  39. display = load_config_readonly().get("display")
  40. except Exception:
  41. return default
  42. if not isinstance(display, dict) or setting not in display:
  43. return default
  44. return bool(display.get(setting))
  45. def emit(event: str, payload: dict) -> bool:
  46. """Route ``event`` to the window owning the current turn; False when no emitter."""
  47. if _emit is None:
  48. return False
  49. if event in _SESSION_SCOPED_EVENTS:
  50. sid = get_session_env("HERMES_SESSION_ID", "")
  51. if not sid:
  52. sid = get_session_env("HERMES_UI_SESSION_ID", "")
  53. else:
  54. sid = get_session_env("HERMES_UI_SESSION_ID", "")
  55. _emit(sid, event, payload)
  56. return True
  57. def emit_or_error(event: str, payload: dict, fail_prefix: str, desktop_only: str, result: dict) -> str:
  58. """Emit ``event``; ``tool_error`` text on failure (``fail_prefix`` + exception, or
  59. ``desktop_only`` when no emitter), else ``result`` as JSON. Calls ``emit`` via the
  60. module attribute so tests can patch it."""
  61. try:
  62. ok = emit(event, payload)
  63. except Exception as exc:
  64. return tool_error(f"{fail_prefix}{exc}")
  65. return json.dumps(result, ensure_ascii=False) if ok else tool_error(desktop_only)
  66. def passthrough_json(raw) -> str:
  67. """Desktop answers with a JSON object; pass it through, else wrap the raw text."""
  68. try:
  69. return json.dumps(json.loads(raw), ensure_ascii=False)
  70. except (TypeError, ValueError):
  71. return json.dumps({"text": str(raw)}, ensure_ascii=False)