open_preview_tool.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/env python3
  2. """Open a URL, dev server, or file in the Hermes desktop GUI's preview pane.
  3. Registration lives in the `desktop_preview` tool (``tools.preview_tool``); this module keeps
  4. the normalizer + open action. Emits ``preview.open`` via ``desktop_ui``: the renderer opens
  5. the pane for the window that asked and never steals focus for a background session.
  6. """
  7. import os
  8. import re
  9. from pathlib import Path
  10. from urllib.parse import unquote, urlparse
  11. from tools import desktop_ui
  12. from tools.registry import tool_error
  13. def _normalize_target(raw: str) -> str:
  14. """Coax a bare host/domain into a fetchable URL; leave paths + schemes alone.
  15. ``www.cnn.com`` -> ``https://www.cnn.com``; ``localhost:3000`` -> ``http://localhost:3000``.
  16. File paths and explicit schemes pass through for the renderer's preview normalizer.
  17. """
  18. v = raw.strip().strip("`").strip()
  19. if not v or "://" in v or v.startswith(("/", "./", "../", "~", "file:")):
  20. return v
  21. if re.match(r"^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:\d+)?(/|$)", v, re.IGNORECASE):
  22. return "http://" + v
  23. if re.match(r"^[\w.-]+\.[a-z]{2,}(:\d+)?(/.*)?$", v, re.IGNORECASE):
  24. return "https://" + v
  25. return v
  26. def _local_fs_path(target: str) -> Path | None:
  27. """Return a filesystem path for local targets; None for http(s) URLs."""
  28. raw = (target or "").strip()
  29. if not raw:
  30. return None
  31. if "://" in raw:
  32. parsed = urlparse(raw)
  33. if parsed.scheme.lower() != "file":
  34. return None
  35. path = unquote(parsed.path or "")
  36. if parsed.netloc and parsed.netloc not in {"", "localhost"}:
  37. path = f"//{parsed.netloc}{path}"
  38. elif (
  39. os.name == "nt"
  40. and len(path) >= 3
  41. and path[0] == "/"
  42. and path[2] == ":"
  43. ):
  44. path = path[1:]
  45. return Path(path) if path else None
  46. return Path(raw).expanduser()
  47. def _is_existing_directory(target: str) -> bool:
  48. path = _local_fs_path(target)
  49. if path is None:
  50. return False
  51. try:
  52. return path.is_dir()
  53. except OSError:
  54. # Stat failed (permissions, broken reparse, etc.). Do not treat that
  55. # as "this is a directory" — reject only when we positively observe
  56. # an existing directory. The renderer still sees the original target.
  57. return False
  58. def open_preview_tool(url: str, label: str = "") -> str:
  59. """Ask the desktop GUI to show ``url`` in the preview pane beside the chat."""
  60. target = _normalize_target(url or "")
  61. if not target:
  62. return tool_error(
  63. "url is required — a web URL (https://…), a localhost dev server, or a "
  64. "file path to show in the preview pane.")
  65. if _is_existing_directory(target):
  66. return tool_error(
  67. "directories are not previewable — pass a file path or a URL. "
  68. f"{target} is a directory."
  69. )
  70. label = (label or "").strip()
  71. return desktop_ui.emit_or_error(
  72. "preview.open",
  73. {"url": target, "label": label},
  74. "Failed to open the preview pane: ",
  75. "The preview pane is only available in the Hermes desktop app.",
  76. {"success": True, "url": target, "label": label})