bundled_app.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """Where the running BUNDLED desktop app lives, and how to start it.
  2. A bundled artifact runs its agent out of ``<app>/resources/agent-payload``,
  3. so a Python process inside that payload sits at a known offset from the app
  4. the user double-clicks. This module turns that offset into the launcher path
  5. and starts it — the two things every in-bundle caller needs and each one
  6. used to work out for itself.
  7. The shape authority is the build stamp (``payload: bundled``, read through
  8. :func:`hermes_cli.steward.is_bundled_payload`), never a filesystem probe: a
  9. probe answers "is this artifact intact?", not "which shape am I?". Callers
  10. gate on the stamp, then ask here WHERE the app is. A stamp that says bundled
  11. over a tree that is not one is damage, and :func:`resolve_bundle_layout`
  12. says so instead of degrading to a checkout.
  13. Two consumers today: ``hermes desktop`` (start the app this CLI ships
  14. inside) and the sealed self-updater (stop the app, then relaunch it).
  15. """
  16. from __future__ import annotations
  17. import os
  18. import subprocess
  19. import sys
  20. from dataclasses import dataclass
  21. from pathlib import Path
  22. __all__ = [
  23. "PAYLOAD_DIR_NAME",
  24. "BundleLayout",
  25. "NotBundledApp",
  26. "launch_detached",
  27. "resolve_bundle_layout",
  28. ]
  29. #: The resources-resident payload directory every bundled artifact ships.
  30. PAYLOAD_DIR_NAME = "agent-payload"
  31. #: Executables that sit beside a Linux Electron launcher without being one.
  32. #: AppRun is the AppImage entry stub, which re-execs the launcher below.
  33. _LINUX_NON_LAUNCHERS = frozenset({"AppRun", "chrome-sandbox", "chrome_crashpad_handler"})
  34. class NotBundledApp(Exception):
  35. """Raised when a tree is not a bundled desktop payload."""
  36. @dataclass(frozen=True)
  37. class BundleLayout:
  38. """The three directories and the launcher of a bundled desktop app.
  39. ``launcher`` is None when the app directory holds no single obvious
  40. executable. That is a real state on a damaged or unusual install, and
  41. both callers would rather report it than act on a guess.
  42. """
  43. app_root: Path
  44. resources: Path
  45. payload: Path
  46. launcher: Path | None
  47. def resolve_bundle_layout(
  48. project_root: Path | str, *, platform: str | None = None
  49. ) -> BundleLayout:
  50. """Locate the desktop app that contains the payload at *project_root*.
  51. *project_root* is the payload's ``repo/`` tree — the install root a
  52. bundled backend runs from. The app sits two directories above the
  53. payload on Windows and Linux, and four above it on macOS, where the
  54. payload lands in ``Hermes.app/Contents/Resources``.
  55. The macOS offset is detected from the directory names themselves
  56. rather than from *platform*, so a layout can be resolved for any host
  57. from any host. *platform* (default :data:`sys.platform`) only decides
  58. the launcher-naming rule.
  59. Raises :class:`NotBundledApp` when the tree is not a bundled payload —
  60. a source checkout, or the docker/nix sealed shape, which has no app.
  61. """
  62. repo = Path(project_root).resolve()
  63. payload = repo.parent
  64. if payload.name != PAYLOAD_DIR_NAME:
  65. raise NotBundledApp(
  66. f"{repo} is not inside a {PAYLOAD_DIR_NAME}/ payload — no desktop app contains it"
  67. )
  68. resources = payload.parent
  69. app_root = resources.parent
  70. # macOS: .../Hermes.app/Contents/Resources/agent-payload/repo
  71. if (
  72. resources.name == "Resources"
  73. and app_root.name == "Contents"
  74. and app_root.parent.suffix == ".app"
  75. ):
  76. app_root = app_root.parent
  77. if not app_root.is_dir():
  78. raise NotBundledApp(f"no app directory above the payload at {payload}")
  79. return BundleLayout(
  80. app_root=app_root,
  81. resources=resources,
  82. payload=payload,
  83. launcher=_resolve_launcher(app_root, platform or sys.platform),
  84. )
  85. def _resolve_launcher(app_root: Path, platform: str) -> Path | None:
  86. """The executable that starts the app, or None when it is ambiguous.
  87. One rule per platform, each one "the single launcher among files that
  88. are not launchers":
  89. * macOS — the one file in ``Contents/MacOS``.
  90. * Windows — the one top-level ``.exe`` that is not the uninstaller.
  91. * Linux — the one top-level executable that is not an Electron helper
  92. or a shared library.
  93. """
  94. if platform == "darwin":
  95. return _only(_files(app_root / "Contents" / "MacOS"))
  96. if platform == "win32":
  97. return _only(
  98. [
  99. p
  100. for p in _files(app_root)
  101. if p.suffix.lower() == ".exe"
  102. and not p.name.lower().startswith("uninstall")
  103. ]
  104. )
  105. return _only(
  106. [
  107. p
  108. for p in _files(app_root)
  109. if p.name not in _LINUX_NON_LAUNCHERS
  110. and ".so" not in p.name
  111. and os.access(p, os.X_OK)
  112. ]
  113. )
  114. def _files(directory: Path) -> list[Path]:
  115. """Regular files directly in *directory*; empty when it is unreadable."""
  116. try:
  117. return sorted(p for p in directory.iterdir() if p.is_file())
  118. except OSError:
  119. return []
  120. def _only(candidates: list[Path]) -> Path | None:
  121. return candidates[0] if len(candidates) == 1 else None
  122. def launch_detached(
  123. argv: list[str], *, env: dict[str, str] | None = None, cwd: Path | str | None = None
  124. ) -> int:
  125. """Start *argv* as its own process and return its pid.
  126. The child outlives this process: it leads a new session on POSIX, and
  127. on Windows it gets the detach creation flags (new process group, own
  128. hidden console, breakaway from any job object). Its stdio goes to the
  129. null device, because the terminal that ran ``hermes desktop`` is free
  130. to close the moment this call returns.
  131. """
  132. from hermes_cli._subprocess_compat import windows_detach_popen_kwargs
  133. child = subprocess.Popen(
  134. argv,
  135. cwd=str(cwd) if cwd is not None else None,
  136. env=env,
  137. stdin=subprocess.DEVNULL,
  138. stdout=subprocess.DEVNULL,
  139. stderr=subprocess.DEVNULL,
  140. close_fds=True,
  141. # detached-spawn: ok — the desktop app launch, meant to outlive the CLI that opens it
  142. **windows_detach_popen_kwargs(),
  143. )
  144. return child.pid