desktop_plugin_install.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. """Install a desktop plugin from Git onto the host that serves the Webapp.
  2. Native Desktop clones one in Electron (``apps/desktop/electron/desktop-plugin-install.ts``,
  3. ``installDesktopPluginFromGit``). A browser-hosted tab has no disk of its own, so until now the install
  4. dialog could only *read* a repository through the gateway (``plugins_cmd_inspect``) and then had
  5. nothing to install with: a desktop-only package answered "nothing to install here", and the desktop
  6. half of a mixed one was reported skipped. This is the missing half of the trip — the same inspection,
  7. held to the commit it read, the same folder name and package-marker rules as Electron, published
  8. atomically into the app-level root that ``/api/desktop-plugins`` serves.
  9. The install is a clone, a staged copy and a rename: no code is imported or run here. The plugin loads
  10. the way any other installed plugin does, on the next scan of ``desktop-plugins/``.
  11. """
  12. from __future__ import annotations
  13. import re
  14. import tempfile
  15. from pathlib import Path
  16. from typing import Any, Optional
  17. from hermes_cli import desktop_plugin_halves as halves
  18. from hermes_constants import get_default_hermes_root
  19. from utils import rmtree_readonly
  20. DESKTOP_PLUGINS_DIR = "desktop-plugins"
  21. _COMMIT = re.compile(r"[0-9a-f]{40}")
  22. #: Windows device names: a folder called one of these (whatever its extension) opens the device instead.
  23. _WINDOWS_DEVICE = re.compile(r"(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|CLOCK\$|COM[0-9¹²³]|LPT[0-9¹²³])", re.IGNORECASE)
  24. def desktop_plugins_root() -> Path:
  25. """The app-level root ``desktop-plugins/``, created on demand and resolved, exactly as Electron's
  26. ``desktopPluginsRoot`` and the Webapp's read routes resolve it: one folder whichever profile the
  27. caller names."""
  28. root = get_default_hermes_root() / DESKTOP_PLUGINS_DIR
  29. root.mkdir(parents=True, exist_ok=True)
  30. return root.resolve()
  31. def _pc():
  32. """The facade, read at call time: tests patch ``plugins_cmd.<name>`` and sibling calls must see it."""
  33. from hermes_cli import plugins_cmd
  34. return plugins_cmd
  35. def _failure(error: str) -> dict[str, Any]:
  36. return {"ok": False, "error": error}
  37. def _checked_name(name: Optional[str]) -> str:
  38. """*name* when it can be one folder under the root, else raise: the name comes from a repository
  39. (a subdirectory's last segment, a manifest's ``name``) and must never reach a path unresolved. A
  40. leading dot is refused too — the root's staging folders use that prefix. So are the names Windows
  41. reads as something else: a colon makes ``C:..`` a drive-relative path, a device name opens the
  42. device, and a trailing dot is dropped."""
  43. candidate = (name or "").strip()
  44. if (not candidate or candidate.startswith(".") or candidate.endswith(".")
  45. or any(char in candidate for char in "/\\:\0") or any(ord(char) < 32 for char in candidate)
  46. or len(candidate) > 128 or _WINDOWS_DEVICE.fullmatch(candidate.split(".", 1)[0].rstrip(" "))):
  47. raise _pc().PluginOperationError(
  48. f"'{name}' is not a desktop plugin folder name: it must be a plain folder name, not a path."
  49. )
  50. return candidate
  51. def _resolve_source(identifier: str, catalog_name: Optional[str]) -> tuple[str, Optional[str], Optional[str]]:
  52. """``(git_url, subdir, catalog_sha)`` through the installer's own resolution and kill list, with the
  53. catalog's reviewed pin when *catalog_name* is given (its repository replaces *identifier*).
  54. Every scheme the CLI installs from is accepted (``git@``/``ssh://`` for private plugins, ``file://``,
  55. ``http://``): the Webapp opens only for the signed-in owner of this host, whose keys and disk these are."""
  56. pc = _pc()
  57. revision = None
  58. if catalog_name:
  59. from hermes_cli import plugins_cmd_catalog as catalog
  60. entry = catalog.get_live_catalog_entry(catalog_name)
  61. if entry is None:
  62. raise pc.PluginOperationError(f"'{catalog_name}' is not in the Hermes plugin catalog.")
  63. identifier, revision = entry.install_identifier, entry.sha or None
  64. try:
  65. git_url, subdir = pc._resolve_git_url(identifier)
  66. except ValueError as exc:
  67. raise pc.PluginOperationError(str(exc)) from exc
  68. from hermes_cli.plugins_cmd_catalog import raise_if_removed
  69. raise_if_removed(identifier, git_url, *((catalog_name,) if catalog_name else ()))
  70. return git_url, subdir, revision
  71. def install_desktop_plugin(identifier: str, *, ref: Optional[str], catalog_name: Optional[str] = None,
  72. force: bool = False) -> dict[str, Any]:
  73. """Clone a repository's desktop half into ``desktop-plugins/<name>`` on this host.
  74. *ref* is the commit the install dialog showed (``inspect``'s ``sha``): the clone is checked out at
  75. exactly that commit, so a repository that moved after review is refused rather than installed. The
  76. halves are read from that same checkout. Returns ``{ok, plugin_name, path, sha, paired_with_agent,
  77. warnings}``, or ``ok: False`` with ``error``. A package carrying both halves lands under its *agent*
  78. name with the package marker Electron writes, so the Plugins page pairs the two rows; a desktop-only
  79. repository keeps its Git-derived folder name and carries no marker.
  80. """
  81. from hermes_cli.plugins_cmd_inspect import _desktop_folder_name, detect_components
  82. pc = _pc()
  83. sha = (ref or "").strip().lower()
  84. try:
  85. if not _COMMIT.fullmatch(sha):
  86. raise pc.PluginOperationError("Installing a desktop plugin needs the commit the install dialog reviewed.")
  87. git_url, subdir, catalog_sha = _resolve_source(identifier, catalog_name)
  88. root = desktop_plugins_root()
  89. with tempfile.TemporaryDirectory(prefix="hermes-plugin-install-") as tmp:
  90. clone = Path(tmp) / "plugin"
  91. # A catalog entry is fetched at its own pin, as the agent installer fetches it: an
  92. # annotated-tag pin names the tag object, and only its peeled commit is what the dialog read.
  93. head = pc._clone_plugin_repo(clone, git_url, catalog_sha or sha, subdir)
  94. if head != sha:
  95. raise pc.PluginSourceMoved(
  96. "The catalog's reviewed commit changed since the dialog read it; inspect it again.")
  97. # Nothing reads a plugin's Git metadata, and Git's read-only object files would make the
  98. # published folder one that Windows cannot delete.
  99. rmtree_readonly(clone / ".git")
  100. plugin_root = pc._resolve_subdir_within(clone, subdir) if subdir else clone
  101. fallback = subdir.rstrip("/").rsplit("/", 1)[-1] if subdir else pc._repo_name_from_url(git_url)
  102. found = detect_components(plugin_root, fallback)
  103. if not found["desktop"]:
  104. return _failure("This package ships no desktop plugin to install here.")
  105. package_name = _checked_name(found["agent_name"]) if found["agent"] else None
  106. folder = package_name or _checked_name(_desktop_folder_name(git_url, subdir))
  107. source_dir = _desktop_tree(plugin_root)
  108. target = root / folder
  109. # A package's half keeps the marker Electron writes (the Plugins page pairs it to the agent
  110. # row); a standalone plugin carries none.
  111. marker = {"package": package_name, "repo": git_url, "source": str(target),
  112. "sourceMtimeMs": halves.mtime_ms((source_dir / "plugin.js").stat())} if package_name else None
  113. # The exists check and the publish must not interleave with a reconcile pass.
  114. with halves.ROOT_WRITER:
  115. if (halves._is_link(target) or target.exists()) and not force:
  116. return _failure(f"Desktop plugin '{folder}' already exists. Enable force reinstall to replace it.")
  117. halves.publish_desktop_tree(source_dir, target, marker)
  118. except pc.PluginOperationError as exc:
  119. return {**_failure(str(exc)), **({"source_moved": True} if isinstance(exc, pc.PluginSourceMoved) else {})}
  120. except OSError as exc:
  121. return _failure(f"Could not install the desktop plugin: {exc}")
  122. return {"ok": True, "plugin_name": folder, "path": str(target), "sha": sha,
  123. "paired_with_agent": bool(package_name), "warnings": []}
  124. def _desktop_tree(plugin_root: Path) -> Path:
  125. """The folder that is the desktop plugin (:func:`halves.desktop_source`, the rule the host's
  126. reconcile applies to an installed package too). It must be a plain tree inside the clone."""
  127. source = halves.desktop_source(plugin_root) or plugin_root / "desktop"
  128. refused = halves.check_desktop_tree(source, plugin_root)
  129. if refused:
  130. raise _pc().PluginOperationError(refused)
  131. return source
  132. def remove_desktop_plugin(name: str, *, force: bool = False) -> dict[str, Any]:
  133. """Delete one installed desktop plugin folder from this host.
  134. A folder carrying the package marker is the desktop half of an installed agent plugin: removing it
  135. alone would leave the Plugins page pairing a row with nothing behind it, and the next reconcile
  136. would copy it straight back, so it is refused unless *force* says the caller means it.
  137. """
  138. try:
  139. folder = _checked_name(name)
  140. except _pc().PluginOperationError as exc:
  141. return _failure(str(exc))
  142. target = desktop_plugins_root() / folder
  143. if halves._is_link(target):
  144. return _failure(
  145. f"'{folder}' is linked from somewhere else on this host; remove that link where it lives."
  146. )
  147. if not target.is_dir():
  148. return _failure(f"No desktop plugin named '{folder}' is installed.")
  149. with halves.ROOT_WRITER:
  150. marker = halves.read_package_marker(target)
  151. if marker and not force:
  152. return _failure(
  153. f"'{folder}' is the desktop half of an agent plugin — uninstall that plugin instead."
  154. )
  155. try:
  156. rmtree_readonly(target)
  157. except OSError as exc:
  158. return _failure(f"Could not remove the desktop plugin: {exc}")
  159. return {"ok": True, "plugin_name": folder, "path": str(target), "unpaired_from": (marker or {}).get("package")}