main_desktop.py 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  1. """Desktop (Electron) app: build/stamp, stage-and-swap pack, exe integrity gate, macOS signing, Linux sandbox, launch (hermes gui/desktop).
  2. Split out of ``hermes_cli/main.py``. Names that still live in main (``PROJECT_ROOT``, ...)
  3. are imported lazily inside the functions that use them (avoids an import cycle).
  4. """
  5. import logging
  6. import contextlib
  7. import argparse
  8. import hashlib
  9. import json
  10. import os
  11. import platform
  12. import re
  13. import shlex
  14. import shutil
  15. import stat
  16. import subprocess
  17. import sys
  18. import time as _time_mod
  19. from pathlib import Path
  20. from typing import Callable, Optional
  21. from hermes_cli.desktop_console import desktop_console_output, desktop_launch_notice
  22. from hermes_platform.host import facts
  23. # Log-record parity with the origin module.
  24. logger = logging.getLogger("hermes_cli.main")
  25. _PREVIOUS_APP_KEPT = " ↩ The previous desktop app was left untouched and still works."
  26. def _desktop_dist_exists(desktop_dir: Path) -> bool:
  27. """Return True when a local desktop renderer build is present."""
  28. return (desktop_dir / "dist" / "index.html").exists()
  29. def _renderer_bundle_dir(desktop_dir: Path, *, source_mode: bool) -> Optional[Path]:
  30. """The renderer ``dist`` a launch loads: ``apps/desktop/dist`` in source mode, else the
  31. ``app.asar.unpacked/dist`` copy (the only real directory, and the one an interrupted replace tears)."""
  32. if source_mode:
  33. return desktop_dir / "dist"
  34. resources = _packaged_resources_dir(desktop_dir)
  35. return None if resources is None else resources / "app.asar.unpacked" / "dist"
  36. def _packaged_resources_dir(desktop_dir: Path) -> Optional[Path]:
  37. """The packaged app's ``resources`` dir (renderer bundle, baked ``install-stamp.json``)."""
  38. executable = _desktop_packaged_executable(desktop_dir)
  39. if executable is None:
  40. return None
  41. # macOS: …/Hermes.app/Contents/MacOS/Hermes → …/Contents/Resources
  42. return executable.parent.parent / "Resources" if sys.platform == "darwin" else executable.parent / "resources"
  43. # The module files the renderer fetches before any app code runs: Vite emits
  44. # them as `<script type="module" src>` plus `<link rel="modulepreload" href>`.
  45. _HTML_TAG_WITH_URL = re.compile(r"""<(?:script|link)\b[^>]*\b(?:src|href)=["']([^"']+)["'][^>]*>""", re.IGNORECASE)
  46. _MODULE_TAG = re.compile(r"""\btype=["']module["']|\brel=["']modulepreload["']""", re.IGNORECASE)
  47. def _renderer_bundle_torn(dist_dir: Path) -> bool:
  48. """True when ``index.html`` names hashed module chunks that aren't there.
  49. A replace interrupted by locked files leaves index and ``assets/`` from
  50. different generations; the app dies on its first lazy import while the
  51. SOURCE-tree stamp still matches, so no rebuild fixes it. Conservative: an
  52. unreadable index or one naming nothing checkable is NOT torn.
  53. """
  54. try:
  55. html = (dist_dir / "index.html").read_text(encoding="utf-8-sig", errors="replace")
  56. except OSError:
  57. return False
  58. for match in _HTML_TAG_WITH_URL.finditer(html):
  59. href = match.group(1)
  60. # Absolute/CDN URLs aren't part of this bundle's generation.
  61. if not _MODULE_TAG.search(match.group(0)) or re.match(r"^[a-z]+:|^//", href, re.IGNORECASE):
  62. continue
  63. rel = href.split("?", 1)[0].split("#", 1)[0].lstrip("./")
  64. if rel and not (dist_dir / rel).exists():
  65. return True
  66. return False
  67. def _packaged_node_pty_missing(dist_dir: Path) -> bool:
  68. """True when the packaged node-pty has no native binary for this OS.
  69. The main process requires node-pty at startup, so such a package dies
  70. before any window opens while the source stamp still matches (#62462).
  71. Same places node-pty's loader and stage-native-deps.mjs look. Conservative:
  72. a package without node-pty at all is not judged here.
  73. """
  74. root = dist_dir / "node_modules" / "node-pty"
  75. if not (root / "package.json").is_file():
  76. return False
  77. native_dirs = [root / "build" / "Release", *(root / "prebuilds").glob(f"{sys.platform}-*")]
  78. return not any(next(d.rglob("*.node"), None) for d in native_dirs if d.is_dir())
  79. def _desktop_build_needed(desktop_dir: Path, project_root: Path, *, source_mode: bool) -> bool:
  80. """True when the desktop build output is stale, missing, torn, or built in the other mode."""
  81. if source_mode:
  82. if not _desktop_dist_exists(desktop_dir):
  83. return True
  84. elif _desktop_packaged_executable(desktop_dir) is None:
  85. return True
  86. # A torn bundle is stale no matter what the stamp says: the hash describes
  87. # the intact SOURCE tree, not the half-replaced output.
  88. dist_dir = _renderer_bundle_dir(desktop_dir, source_mode=source_mode)
  89. if dist_dir is not None and _renderer_bundle_torn(dist_dir):
  90. print(f" ⚠ A previous update left the desktop bundle incomplete ({dist_dir}); rebuilding it")
  91. return True
  92. if not source_mode and dist_dir is not None and _packaged_node_pty_missing(dist_dir):
  93. print(" ⚠ The packaged desktop app has no node-pty native binary; rebuilding it")
  94. return True
  95. from hermes_cli.source_build import source_product_current
  96. return dist_dir is None or not source_product_current(project_root, "desktop", dist_dir)
  97. def _packaged_desktop_current_for_head(desktop_dir: Path, project_root: Path) -> bool:
  98. """True when the packaged app was built from HEAD and none of its inputs changed since.
  99. Freshness alone cannot answer this for an update: the baked ``install-stamp.json`` is a
  100. desktop input that only the build itself rewrites, so after a pull that touched no other
  101. desktop input the receipt still reads current while the app names the previous commit.
  102. The commit the packaged app actually ships is the missing half; anything unreadable
  103. means "build".
  104. """
  105. resources = _packaged_resources_dir(desktop_dir)
  106. if resources is None:
  107. return False
  108. from hermes_cli.steward import read_install_stamp
  109. from hermes_cli.version_info import _run_git
  110. commit = read_install_stamp(resources).get("commit")
  111. if not isinstance(commit, str) or commit != _run_git(project_root, "rev-parse", "HEAD"):
  112. return False
  113. return not _desktop_build_needed(desktop_dir, project_root, source_mode=False)
  114. def _desktop_packaged_executable(desktop_dir: Path) -> Optional[Path]:
  115. """Return the current platform's unpacked Electron app executable."""
  116. return _desktop_packaged_executable_in(desktop_dir / "release")
  117. def _desktop_packaged_executable_in(release_dir: Path) -> Optional[Path]:
  118. """The unpacked Electron app executable under *release_dir* (live ``release`` or a staging dir).
  119. *release_dir* is electron-builder's ``directories.output`` — the live ``apps/desktop/release`` or a
  120. stage-and-swap staging dir (#86443).
  121. """
  122. if sys.platform == "darwin":
  123. candidates = list(release_dir.glob("mac*/Hermes.app/Contents/MacOS/Hermes"))
  124. elif sys.platform == "win32":
  125. candidates = [
  126. release_dir / d / "Hermes.exe" for d in ("win-unpacked", "win-ia32-unpacked", "win-arm64-unpacked")
  127. ]
  128. else:
  129. candidates = [
  130. release_dir / d / n for d in ("linux-unpacked", "linux-arm64-unpacked") for n in ("hermes", "Hermes")
  131. ]
  132. existing = [p for p in candidates if p.exists()]
  133. if not existing:
  134. return None
  135. if sys.platform == "win32" and len(existing) > 1:
  136. # A stale win-arm64-unpacked next to the real win-unpacked: picking by
  137. # mtime can hand a wrong-architecture Hermes.exe to the launcher. Prefer
  138. # candidates whose PE machine matches the host; mtime when none parse.
  139. # Multiple unpacked trees can coexist (e.g. a stale win-arm64-unpacked left behind by a cross-arch
  140. # experiment next to the real win-unpacked). Picking purely by mtime can then hand a
  141. # wrong-architecture Hermes.exe to the launcher, which Windows rejects with "This app can't run on
  142. # your computer" (#69179).
  143. expected = _expected_windows_pe_machines()
  144. matching = [p for p in existing if _pe_machine_or_none(p) in expected]
  145. if matching:
  146. existing = matching
  147. return max(existing, key=lambda p: p.stat().st_mtime)
  148. # ─── Desktop stage-and-swap pack (#86443) ─────────────────────────────────── electron-builder packs IN
  149. # PLACE: before-pack.mjs wipes ``release/<platform>- unpacked`` (or the mac ``Hermes.app``) and the Electron
  150. # unpack + asar + rename then rebuild it. Any failure after that wipe — corrupt cached zip, blocked
  151. # download, missing dep, disk full — leaves the user with NO app, and ``hermes update`` used to report
  152. # "partially complete" over an empty release/. Fix the class, not the predicate: build into a STAGING output
  153. # dir next to release/, verify the staged result, and only then swap it over the live tree with renames. On
  154. # any failure the live app is untouched.
  155. _DESKTOP_STAGING_PREFIX = ".staging-"
  156. _DESKTOP_PREVIOUS_SUFFIX = ".previous"
  157. # A real-time file scanner (AV/EDR) holds a short exclusive handle on a freshly packed
  158. # release/win-unpacked tree; the promotion rename then fails with a sharing violation
  159. # (WinError 32 / 5 -> PermissionError) and succeeds a moment later on identical input (#112544).
  160. # Only PermissionError is retried: EXDEV/ENOENT-class failures are permanent.
  161. _DESKTOP_SWAP_RENAME_RETRY_DELAYS_S = (0.5, 1.0, 1.0, 1.0)
  162. def _rename_riding_out_file_lock(src: Path, dst: Path) -> None:
  163. """``os.rename`` that retries a transient PermissionError with bounded backoff; re-raises the last one."""
  164. for attempt, delay in enumerate(_DESKTOP_SWAP_RENAME_RETRY_DELAYS_S, start=1):
  165. try:
  166. os.rename(src, dst)
  167. return
  168. except PermissionError as exc:
  169. logger.warning(
  170. "desktop promotion rename %s -> %s hit a file lock (attempt %d/%d), retrying in %.1fs: %s",
  171. src.name, dst.name, attempt, len(_DESKTOP_SWAP_RENAME_RETRY_DELAYS_S) + 1, delay, exc,
  172. )
  173. _time_mod.sleep(delay)
  174. os.rename(src, dst)
  175. def _desktop_staging_dir(desktop_dir: Path) -> Path:
  176. """Fresh staging dir ``apps/desktop/.staging-<pid>-<ts>``: a sibling of ``release/`` (same fs → the
  177. swap is a rename) but not inside it, so ``release/*-unpacked`` globs never see it. Sweeps leftovers."""
  178. for stale in desktop_dir.glob(f"{_DESKTOP_STAGING_PREFIX}*"):
  179. shutil.rmtree(stale, ignore_errors=True)
  180. return desktop_dir / f"{_DESKTOP_STAGING_PREFIX}{os.getpid()}-{int(_time_mod.time())}"
  181. def _desktop_unpacked_root(exe: Path, release_dir: Path) -> Path:
  182. """The dir directly under *release_dir* holding *exe* (electron-builder's ``appOutDir``, swapped whole)."""
  183. unpacked = exe
  184. while unpacked.parent != release_dir:
  185. if unpacked.parent == unpacked:
  186. raise ValueError(f"{exe} is not under {release_dir}")
  187. unpacked = unpacked.parent
  188. return unpacked
  189. def _recover_interrupted_swap(live: Path, aside: Path) -> None:
  190. """Finish a swap that died between its two renames before starting a new one: a missing
  191. ``live`` with its ``aside`` copy present means the previous app was moved out and nothing
  192. moved in, so put it back; otherwise ``aside`` is leftover. Deleting ``aside`` first (as the
  193. swappers used to) destroyed the only remaining copy of the app."""
  194. if not live.exists() and aside.is_dir():
  195. try:
  196. aside.rename(live)
  197. logger.warning("restored %s from an interrupted desktop app swap", live)
  198. return
  199. except OSError as exc:
  200. logger.warning("could not restore %s from %s: %s", live, aside, exc)
  201. return
  202. shutil.rmtree(aside, ignore_errors=True)
  203. def _move_live_app_aside(live_root: Path, previous: Path, held_by: Optional[list], consent) -> None:
  204. """First swap rename. On Windows a refusal names the programs whose working folder is inside
  205. ``live_root``, the folder being renamed (#101789), and retries once only after the user
  206. consented to closing them. A program in a sibling folder (``win-arm64-unpacked``) does not
  207. block this rename, so it is neither named nor offered for closing."""
  208. try:
  209. _rename_riding_out_file_lock(live_root, previous)
  210. return
  211. except PermissionError:
  212. if sys.platform != "win32":
  213. raise
  214. from hermes_cli.desktop_release_holders import find_release_cwd_holders, release_after_refused_rename
  215. holders, closed = release_after_refused_rename(live_root, consent=consent)
  216. if not closed:
  217. if held_by is not None:
  218. held_by.extend(holders)
  219. raise
  220. try:
  221. _rename_riding_out_file_lock(live_root, previous)
  222. except PermissionError:
  223. if held_by is not None:
  224. held_by.extend(find_release_cwd_holders(live_root))
  225. raise
  226. def _swap_staged_desktop_app(
  227. desktop_dir: Path, staging_dir: Path, *, held_by: Optional[list] = None,
  228. ) -> Optional[Path]:
  229. """Promote a VERIFIED staged pack over ``release/`` by two renames (live → ``.previous``, staged →
  230. live); a failure between them rolls back. Returns the live exe or None (live app kept). Never raises.
  231. ``held_by`` collects the named programs that blocked the swap (Windows cwd holders)."""
  232. from hermes_cli.desktop_release_holders import take_consent
  233. from hermes_cli.update_receipt import _launcher_correlation_id
  234. release_dir = desktop_dir / "release"
  235. # A "close and retry" consent covers this one attempt of the run it was given for (#101789).
  236. consent = take_consent(release_dir, _launcher_correlation_id())
  237. staged_exe = _desktop_packaged_executable_in(staging_dir)
  238. if staged_exe is None:
  239. shutil.rmtree(staging_dir, ignore_errors=True)
  240. return None
  241. try:
  242. staged_root = _desktop_unpacked_root(staged_exe, staging_dir)
  243. live_root = release_dir / staged_root.name
  244. previous = release_dir / (staged_root.name + _DESKTOP_PREVIOUS_SUFFIX)
  245. release_dir.mkdir(parents=True, exist_ok=True)
  246. _recover_interrupted_swap(live_root, previous)
  247. moved_aside = live_root.exists()
  248. if moved_aside:
  249. # A Desktop may have reopened during the long packaging step (Windows lock) or
  250. # never exited at all (a manual `hermes update`/`hermes desktop` run does not
  251. # wait for it — only the update hand-offs do). Either way a renderer alive
  252. # past the rename below keeps fetching its old hashed chunks from disk and
  253. # dies on the next lazy import, so stop it on every platform (#109643).
  254. stopped = _stop_desktop_processes_locking_build(desktop_dir, also_posix=True)
  255. if stopped:
  256. logger.info("stopped desktop processes before staged app promotion: %s", stopped)
  257. _move_live_app_aside(live_root, previous, held_by, consent)
  258. try:
  259. _rename_riding_out_file_lock(staged_root, live_root)
  260. except OSError:
  261. if moved_aside:
  262. _rename_riding_out_file_lock(previous, live_root) # restore; live app back as it was
  263. raise
  264. if moved_aside:
  265. shutil.rmtree(previous, ignore_errors=True)
  266. except (OSError, ValueError) as exc:
  267. logger.warning("desktop stage-and-swap failed, live app kept: %s", exc)
  268. return None
  269. finally:
  270. shutil.rmtree(staging_dir, ignore_errors=True)
  271. return live_root / staged_exe.relative_to(staged_root)
  272. def _discard_desktop_staging(staging_dir: Path) -> None:
  273. shutil.rmtree(staging_dir, ignore_errors=True)
  274. # ─── Desktop exe integrity gate (#69179) ──────────────────────────────────── The desktop self-update chain
  275. # (Desktop → hermes-setup --update → `hermes update` → `hermes desktop --build-only` → relaunch) rebuilds
  276. # Hermes.exe on the end user's machine and used to verify only that the file EXISTS before declaring
  277. # success. A corrupt cached Electron zip whose extraction produced a truncated electron.exe, an interrupted
  278. # rcedit resource rewrite, a disk-full pack, or a wrong-arch unpacked tree therefore shipped a broken binary
  279. # that Windows refuses to load ("This app can't run on your computer" / 此应用无法在你的电脑上运行). These helpers parse
  280. # the PE header — no signature infrastructure required — so a structurally broken or wrong-architecture
  281. # Hermes.exe is caught BEFORE the updater replaces the working app, and the previous build can be restored
  282. # from the .bak tree that apps/desktop/scripts/before-pack.mjs now preserves.
  283. _PE_MACHINE_I386 = 0x014C
  284. _PE_MACHINE_AMD64 = 0x8664
  285. _PE_MACHINE_ARM64 = 0xAA64
  286. _PE_MACHINE_NAMES = {
  287. _PE_MACHINE_I386: "x86 (32-bit)", _PE_MACHINE_AMD64: "x64 (AMD64)", _PE_MACHINE_ARM64: "ARM64",
  288. }
  289. _PE_MACHINE_TO_NAME = {_PE_MACHINE_ARM64: "ARM64", _PE_MACHINE_AMD64: "AMD64", _PE_MACHINE_I386: "X86"}
  290. # MACHINE_ATTRIBUTES bits (processthreadsapi.h). UserEnabled means the host
  291. # can run user-mode code of that machine type — natively or under emulation.
  292. _MACHINE_ATTRIBUTE_USER_ENABLED = 0x00000001
  293. def _kernel32():
  294. import ctypes
  295. return ctypes.WinDLL("kernel32", use_last_error=True)
  296. def _windows_user_runnable_pe_machines() -> Optional[set]:
  297. """PE machines this host runs in user mode via GetMachineTypeAttributes (the only API reporting
  298. AMD64-on-ARM64 emulation); None when unavailable (pre-Win11 22000) so callers fall back."""
  299. import ctypes
  300. from ctypes import wintypes
  301. kernel32 = _kernel32()
  302. kernel32.GetMachineTypeAttributes.argtypes = [wintypes.USHORT, ctypes.POINTER(ctypes.c_int)]
  303. kernel32.GetMachineTypeAttributes.restype = ctypes.c_long
  304. runnable = set()
  305. for machine in (_PE_MACHINE_ARM64, _PE_MACHINE_AMD64, _PE_MACHINE_I386):
  306. attributes = ctypes.c_int(0)
  307. # HRESULT: zero is success, any nonzero value is a failure.
  308. if kernel32.GetMachineTypeAttributes(machine, ctypes.byref(attributes)):
  309. continue
  310. if attributes.value & _MACHINE_ATTRIBUTE_USER_ENABLED:
  311. runnable.add(machine)
  312. return runnable or None
  313. def _windows_native_machine() -> str:
  314. """Return the native Windows machine name in upper-case PE vocabulary."""
  315. if sys.platform == "win32":
  316. return {"arm64": "ARM64", "amd64": "AMD64", "x86": "X86"}.get(
  317. facts.native_arch(), (platform.machine() or "").upper()
  318. )
  319. return (platform.machine() or "").upper()
  320. def _expected_windows_pe_machines() -> set:
  321. """PE machines this Windows host can load: ``GetMachineTypeAttributes``, else by name (AMD64 → x64+x86,
  322. ARM64 → ARM64+x64, x86 → x86). Unknown hosts get the full set so the gate can never brick launch."""
  323. if sys.platform == "win32":
  324. try:
  325. runnable = _windows_user_runnable_pe_machines()
  326. except (OSError, AttributeError, TypeError, ValueError):
  327. runnable = None
  328. if runnable:
  329. return runnable
  330. machine = _windows_native_machine().upper()
  331. if machine in ("AMD64", "X86_64", "X64"):
  332. return {_PE_MACHINE_AMD64, _PE_MACHINE_I386}
  333. if machine in ("ARM64", "AARCH64"):
  334. return {_PE_MACHINE_ARM64, _PE_MACHINE_AMD64}
  335. if machine in ("X86", "I386", "I486", "I586", "I686"):
  336. return {_PE_MACHINE_I386}
  337. return {_PE_MACHINE_AMD64, _PE_MACHINE_ARM64, _PE_MACHINE_I386}
  338. def _parse_pe_machine(path: Path) -> int:
  339. """COFF machine field of the PE at ``path``; ``ValueError`` with a readable reason when it is not a
  340. structurally complete PE (bad magic, truncated header, section data past EOF). Header walk only."""
  341. import struct
  342. try:
  343. file_size = path.stat().st_size
  344. except OSError as exc:
  345. raise ValueError(f"unreadable: {exc}")
  346. if file_size < 512:
  347. raise ValueError(f"file is only {file_size} bytes — far too small to be a Windows executable")
  348. with path.open("rb") as fh:
  349. head = fh.read(64)
  350. if len(head) < 64 or head[:2] != b"MZ":
  351. raise ValueError(
  352. "missing MZ header — not a Windows executable (a truncated or non-binary file saved as .exe?)"
  353. )
  354. e_lfanew = struct.unpack_from("<I", head, 0x3C)[0]
  355. if e_lfanew <= 0 or e_lfanew + 24 > file_size:
  356. raise ValueError("corrupt DOS header: PE header offset points past end of file")
  357. fh.seek(e_lfanew)
  358. pe_head = fh.read(24)
  359. if len(pe_head) < 24 or pe_head[:4] != b"PE\x00\x00":
  360. raise ValueError("missing PE signature — corrupt executable header")
  361. machine, n_sections = struct.unpack_from("<HH", pe_head, 4)
  362. size_of_optional = struct.unpack_from("<H", pe_head, 20)[0]
  363. fh.seek(e_lfanew + 24 + size_of_optional)
  364. max_section_end = 0
  365. for _ in range(n_sections):
  366. section = fh.read(40)
  367. if len(section) < 40:
  368. raise ValueError("truncated PE section table")
  369. size_of_raw, pointer_to_raw = struct.unpack_from("<II", section, 16)
  370. max_section_end = max(max_section_end, pointer_to_raw + size_of_raw)
  371. if file_size < max_section_end:
  372. raise ValueError(
  373. f"truncated executable: file is {file_size} bytes but its PE sections extend to {max_section_end} bytes"
  374. )
  375. return machine
  376. def _pe_machine_or_none(path: Path) -> Optional[int]:
  377. try:
  378. return _parse_pe_machine(path)
  379. except ValueError:
  380. return None
  381. def _desktop_exe_integrity_error(path: Path) -> Optional[str]:
  382. """Why ``path`` cannot run on this Windows host, or None when it parses as a loadable PE."""
  383. try:
  384. machine = _parse_pe_machine(path)
  385. except ValueError as exc:
  386. return str(exc)
  387. if machine not in _expected_windows_pe_machines():
  388. got = _PE_MACHINE_NAMES.get(machine, f"unknown machine 0x{machine:04X}")
  389. return (
  390. f"architecture mismatch: built a {got} executable but this is a "
  391. f"{_windows_native_machine()} Windows host"
  392. )
  393. return None
  394. def _electron_dir(project_root: Path) -> Path:
  395. """The installed Electron package dir: workspace-local ``apps/desktop/node_modules/electron`` (where
  396. ``electronDist`` points) when present, else the root hoist npm sometimes uses instead."""
  397. desktop_local = project_root / "apps" / "desktop" / "node_modules" / "electron"
  398. if desktop_local.exists():
  399. return desktop_local
  400. return project_root / "node_modules" / "electron"
  401. def _runs_from(proc, release_dir: Path) -> bool:
  402. """True when *proc*'s executable lives inside *release_dir* (False when it cannot be read)."""
  403. try:
  404. return release_dir in Path(proc.exe()).resolve().parents
  405. except Exception:
  406. return False
  407. def _desktop_ancestor_in(desktop_dir: Path) -> Optional[int]:
  408. """PID of a Desktop from this build's ``release`` tree that is one of OUR ancestors, else None.
  409. That Desktop is running this process (its backend's launch-time update tail, or a
  410. `hermes update` it spawned). On Windows it holds the exe lock the promotion rename
  411. needs, and it cannot be stopped without killing this process first. Never raises."""
  412. try:
  413. import psutil
  414. release_dir = (desktop_dir / "release").resolve()
  415. ancestors = list(psutil.Process(os.getpid()).parents())
  416. except Exception:
  417. return None
  418. for parent in ancestors:
  419. if _runs_from(parent, release_dir):
  420. return int(parent.pid)
  421. return None
  422. def _stop_desktop_processes_locking_build(desktop_dir: Path, *, also_posix: bool = False) -> list[int]:
  423. """Terminate a running desktop app whose exe lives INSIDE this build's ``release`` tree.
  424. Windows needs it everywhere: the exe lock makes the pack die with ``Access is denied``.
  425. POSIX can rename a running app's files away, so the pack itself needs no stop — but a
  426. renderer left alive through the stage-and-swap promotion keeps fetching its OLD hashed
  427. chunks by path after the swap and dies on the next lazy import (#109643), so the swap
  428. point passes ``also_posix=True``. Never raises; returns the PIDs asked to stop."""
  429. if sys.platform != "win32" and not also_posix:
  430. return []
  431. try:
  432. import psutil
  433. release_dir = (desktop_dir / "release").resolve()
  434. except Exception:
  435. return []
  436. if not release_dir.is_dir():
  437. return []
  438. me = os.getpid()
  439. # Never stop a Desktop that is one of OUR ancestors, on any platform: this
  440. # process lives in its tree. A historical Desktop (v2026.7.1 Linux in-app
  441. # update) runs `hermes update` as a child with piped stdout/stderr and owns
  442. # the post-update rebuild and relaunch. Killing it breaks those pipes (EPIPE
  443. # fails the update) and leaves nobody to relaunch. On Windows the same holds
  444. # for the launch-time tail a Desktop's own backend runs
  445. # (venv_sync._finish_source_update): stopping that Desktop took the whole
  446. # tree down with it before the tail could clear its markers, so every
  447. # launch repeated it (#123499). The exe lock that stop was meant to free
  448. # cannot be freed by the process that holds it alive; build_prepared_desktop
  449. # skips that doomed build instead (_desktop_ancestor_in).
  450. #
  451. # Spare that Desktop's whole process tree, not just its main process. Its
  452. # zygote, renderer, GPU and network-service helpers run the same release
  453. # exe but are siblings of us, not ancestors. Stopping them leaves a main
  454. # process with no renderer. It cannot draw its update overlay, relaunch, or
  455. # quit, so it outlives the update forever. (That is the v2026.7.1 Linux
  456. # in-app update E2E: the receipt succeeds and then the app hangs.)
  457. spared: set[int] = set()
  458. try:
  459. ancestors = list(psutil.Process(me).parents())
  460. except Exception:
  461. ancestors = []
  462. for parent in ancestors:
  463. spared.add(parent.pid)
  464. # Only a Desktop ancestor's descendants. Every process descends from
  465. # init, so sparing all ancestors' trees would spare everything.
  466. if not _runs_from(parent, release_dir):
  467. continue
  468. with contextlib.suppress(Exception):
  469. spared.update(child.pid for child in parent.children(recursive=True))
  470. victims = []
  471. try:
  472. proc_iter = psutil.process_iter(["pid", "exe"])
  473. except Exception:
  474. return []
  475. for proc in proc_iter:
  476. try:
  477. info = proc.info
  478. pid = info.get("pid")
  479. exe = info.get("exe")
  480. if not exe or pid is None or pid == me or pid in spared:
  481. continue
  482. exe_path = Path(exe).resolve()
  483. except Exception:
  484. continue
  485. if release_dir in exe_path.parents:
  486. victims.append(proc)
  487. stopped: list[int] = []
  488. for proc in victims:
  489. try:
  490. proc.terminate()
  491. stopped.append(int(proc.pid))
  492. except Exception:
  493. continue
  494. if stopped:
  495. # Wait for the handles (and thus the file locks) to actually release.
  496. with contextlib.suppress(Exception):
  497. _, alive = psutil.wait_procs(victims, timeout=5)
  498. killed = []
  499. for proc in alive:
  500. try:
  501. proc.kill()
  502. killed.append(proc)
  503. except Exception:
  504. continue
  505. if killed:
  506. psutil.wait_procs(killed, timeout=5)
  507. return stopped
  508. def _desktop_macos_bundle_id(bundle: Path) -> Optional[str]:
  509. """Return a bundle/framework CFBundleIdentifier for local macOS signing."""
  510. import plistlib
  511. info = bundle / "Contents" / "Info.plist"
  512. if not info.exists() and bundle.suffix == ".framework":
  513. candidates = list(bundle.glob("Versions/*/Resources/Info.plist")) + list(
  514. bundle.glob("Resources/Info.plist"))
  515. if candidates:
  516. info = candidates[0]
  517. if not info.exists():
  518. return None
  519. try:
  520. data = plistlib.loads(info.read_bytes())
  521. except Exception:
  522. return None
  523. ident = data.get("CFBundleIdentifier")
  524. return str(ident) if ident else None
  525. def _desktop_macos_local_signing_identity() -> Optional[str]:
  526. """``desktop.macos_signing_identity`` — a persistent (even self-signed) code-signing cert anchors
  527. the Designated Requirement and keeps TCC grants stable across rebuilds. Unset → ad-hoc."""
  528. if sys.platform != "darwin":
  529. return None
  530. try:
  531. from hermes_cli.config import load_config
  532. desktop = load_config().get("desktop", {})
  533. if not isinstance(desktop, dict):
  534. return None
  535. identity = desktop.get("macos_signing_identity")
  536. if not isinstance(identity, str):
  537. return None
  538. return identity.strip() or None
  539. except Exception as exc:
  540. print(
  541. " (warning: could not load desktop.macos_signing_identity: "
  542. f"{exc}; falling back to ad-hoc signing)"
  543. )
  544. return None
  545. def _codesign_verify(codesign: str, app: Path, **kwargs) -> subprocess.CompletedProcess:
  546. return subprocess.run( # noqa: PLW1510 -- forwarding wrapper: callers pass subprocess kwargs via **kwargs (check may arrive through it); an explicit check=False would raise TypeError
  547. [codesign, "--verify", "--deep", "--strict", str(app)], capture_output=True, **kwargs)
  548. def _macos_signature_summary(codesign: str, app: Path) -> Optional[dict]:
  549. """Best-effort signing identity of a ``.app`` bundle: ``{team, identifier, verified}``.
  550. ``None`` when the bundle has no readable signature (``codesign -dv`` fails — e.g. an
  551. unsigned bundle). ``team``/``identifier`` are ``None`` when the signature lacks them
  552. (ad-hoc signatures report ``TeamIdentifier=not set``); ``verified`` is the strict
  553. ``--verify --deep --strict`` result. Never raises.
  554. """
  555. try:
  556. info = subprocess.run(
  557. [codesign, "-dv", str(app)], check=False, capture_output=True,
  558. text=True, encoding="utf-8", errors="replace")
  559. except Exception:
  560. return None
  561. output = f"{info.stdout}\n{info.stderr}"
  562. if info.returncode != 0:
  563. return None
  564. def field(key: str) -> Optional[str]:
  565. for line in output.splitlines():
  566. if line.startswith(f"{key}="):
  567. return line[len(key) + 1:].strip() or None
  568. return None
  569. team = field("TeamIdentifier")
  570. return {
  571. "team": None if team in (None, "not set") else team,
  572. "identifier": field("Identifier"),
  573. "verified": _codesign_verify(codesign, app, check=False).returncode == 0,
  574. }
  575. def _macos_signing_downgrade_error(installed: dict, rebuilt: Optional[dict]) -> Optional[str]:
  576. """Reason to refuse swapping a publisher-signed installed app for ``rebuilt``, or None.
  577. #123748: replacing a Developer ID (Team ID) installation with a locally signed or
  578. ad-hoc rebuild — or any bundle whose signing identity or bundle identifier differs —
  579. invalidates the code-hash-bound keychain ACLs the app's safeStorage credentials are
  580. encrypted under and resets TCC grants. Ad-hoc-to-ad-hoc replacement (the local
  581. development flow) is untouched. ``installed`` is a ``_macos_signature_summary`` dict;
  582. ``rebuilt`` is None when the rebuilt bundle has no readable signature.
  583. """
  584. if not installed["team"]:
  585. return None
  586. if rebuilt is None or not rebuilt["team"]:
  587. return (f"publisher-signed app (Team ID {installed['team']}) would be replaced by a "
  588. "locally signed or unreadable build; kept the existing app. To update it, "
  589. "sign the rebuild with the publisher identity (CSC_LINK / "
  590. "APPLE_SIGNING_IDENTITY) and update again.")
  591. if rebuilt["team"] != installed["team"]:
  592. return (f"publisher Team ID {installed['team']} does not match rebuilt "
  593. f"{rebuilt['team']}; kept the existing app. Check the signing identity "
  594. f"in desktop.macos_signing_identity and update again.")
  595. if (installed["identifier"] and rebuilt["identifier"]
  596. and installed["identifier"] != rebuilt["identifier"]):
  597. return (f"bundle identifier {installed['identifier']!r} does not match rebuilt "
  598. f"{rebuilt['identifier']!r}; kept the existing app. Align the build's "
  599. f"bundle identifier and update again.")
  600. if not rebuilt["verified"]:
  601. return ("rebuilt bundle failed strict signature verification; kept the existing "
  602. "app. Re-run the build; if it persists, inspect with `codesign -vvv`.")
  603. return None
  604. def _desktop_macos_has_valid_real_signature(app: Path) -> bool:
  605. """True when the bundle has an intact Team-ID signature, so the fixup never clobbers a notarized
  606. build with ad-hoc (resets TCC). A STALE real signature fails --verify → False → repairable."""
  607. codesign = shutil.which("codesign")
  608. if not codesign:
  609. return False
  610. try:
  611. info = subprocess.run(
  612. [codesign, "-dv", str(app)], check=False, capture_output=True, text=True, encoding="utf-8", errors="replace")
  613. output = f"{info.stdout}\n{info.stderr}"
  614. if info.returncode != 0 or "TeamIdentifier=" not in output or "TeamIdentifier=not set" in output:
  615. return False
  616. return _codesign_verify(codesign, app, check=False).returncode == 0
  617. except Exception:
  618. return False
  619. def _desktop_macos_local_codesign(app: Path, *, desktop_dir: Path, identity: str = "-") -> bool:
  620. """Sign a local build inside-out (Mach-O files, nested frameworks/helpers, main bundle) with the
  621. repo's entitlements and an identifier-pinned DR when ad-hoc — a plain ``--deep --sign -`` gives
  622. a cdhash-only DR (TCC re-prompts every rebuild) and strips the JIT/mic entitlements.
  623. Raises on signing failure; True after strict verification."""
  624. codesign = shutil.which("codesign")
  625. if not codesign:
  626. return False
  627. ent_main = desktop_dir / "electron" / "entitlements.mac.plist"
  628. ent_inherit = desktop_dir / "electron" / "entitlements.mac.inherit.plist"
  629. if not (ent_main.exists() and ent_inherit.exists()):
  630. # Hardened-runtime restrictions apply to ad-hoc signatures too; signing
  631. # with --options runtime but WITHOUT allow-jit would leave Electron/V8
  632. # crashing on launch. Bail so the caller falls back to the legacy sign.
  633. raise FileNotFoundError(f"desktop entitlement plists missing under {desktop_dir / 'electron'}")
  634. def sign_path(
  635. path: Path, *, entitlements: Optional[Path] = None, identifier: Optional[str] = None,
  636. runtime: bool = True) -> None:
  637. args = [codesign, "--force", "--sign", identity, "--timestamp=none"]
  638. if runtime:
  639. args += ["--options", "runtime"]
  640. if entitlements is not None and entitlements.exists():
  641. args += ["--entitlements", str(entitlements)]
  642. if identifier and identity == "-":
  643. # Ad-hoc signatures get a cdhash-only DR by default; pin an
  644. # identifier-based DR so TCC has something stable to persist.
  645. args += ["--requirements", f'=designated => identifier "{identifier}"']
  646. args.append(str(path))
  647. subprocess.run(args, check=True, capture_output=True)
  648. # 1) Standalone Mach-O files (native modules, dylibs, crashpad handler),
  649. # compared relative to the app root — the absolute path always contains
  650. # the outer Hermes.app component.
  651. contents = app / "Contents"
  652. standalone: list[Path] = []
  653. for root, _dirs, files in os.walk(contents):
  654. root_path = Path(root)
  655. if any(part.endswith(".app") for part in root_path.relative_to(app).parts):
  656. continue # nested helper apps are signed as bundles below
  657. for name in files:
  658. fp = root_path / name
  659. if name in {"chrome_crashpad_handler", "spawn-helper"} or fp.suffix in {".node", ".dylib"}:
  660. standalone.append(fp)
  661. for fp in sorted(standalone, key=lambda p: len(p.parts), reverse=True):
  662. sign_path(fp, runtime=False)
  663. # 2) Nested frameworks and helper apps, deepest first.
  664. bundles: set[Path] = set()
  665. frameworks_dir = contents / "Frameworks"
  666. if frameworks_dir.exists():
  667. for root, _dirs, _files in os.walk(frameworks_dir):
  668. p = Path(root)
  669. if p.suffix in {".framework", ".app"}:
  670. bundles.add(p)
  671. for bundle in sorted(bundles, key=lambda p: len(p.parts), reverse=True):
  672. # Every nested bundle takes the inherit plist, frameworks included: under the hardened
  673. # runtime Electron Framework needs allow-jit in its own signature, and signing it with
  674. # no entitlements strips what electron-builder's afterSign step applies in a real build.
  675. sign_path(bundle, entitlements=ent_inherit, identifier=_desktop_macos_bundle_id(bundle))
  676. # 3) The main bundle, with the app's own entitlements.
  677. sign_path(app, entitlements=ent_main, identifier=_desktop_macos_bundle_id(app))
  678. _codesign_verify(codesign, app, check=True)
  679. return True
  680. def _macos_legacy_adhoc_resign(codesign: str, app: Path) -> bool:
  681. """Legacy deep ad-hoc re-sign; NEVER deletes the safeStorage keychain item (that would orphan every
  682. credential under it, and there is no verified successor identity here — the "Always Allow"
  683. prompt is recoverable, deletion is not)."""
  684. try:
  685. result = subprocess.run(
  686. [codesign, "--force", "--deep", "--sign", "-", str(app)], check=False, capture_output=True, text=True, encoding="utf-8", errors="replace"
  687. )
  688. if result.returncode != 0:
  689. print(
  690. f" (warning: legacy ad-hoc re-sign failed (exit {result.returncode}); "
  691. "leaving safeStorage keychain item untouched)"
  692. )
  693. return False
  694. if _codesign_verify(codesign, app, check=False, text=True, encoding="utf-8", errors="replace").returncode != 0:
  695. print(
  696. " (warning: legacy ad-hoc re-sign did not pass strict verification; "
  697. "leaving safeStorage keychain item untouched)"
  698. )
  699. return False
  700. print(" → macOS desktop re-signed (legacy ad-hoc); safeStorage keychain item left untouched")
  701. return True
  702. except Exception as exc:
  703. print(f" (warning: macOS relaunch fixup skipped: {exc})")
  704. return False
  705. def _desktop_macos_relaunchable_fixup(
  706. desktop_dir: Path, *, publisher_signing_configured: Optional[bool] = None,
  707. release_dir: Optional[Path] = None) -> bool:
  708. """Re-sign a locally-built macOS app so in-place self-update doesn't reset TCC grants.
  709. A rebuilt ad-hoc bundle (new cdhash, no stable Designated Requirement) reports
  710. "Hermes is damaged" and loses every grant. Clear quarantine xattrs, then sign
  711. with ``desktop.macos_signing_identity`` or identifier-pinned ad-hoc, keeping
  712. entitlements. When a configured identity fails (#121857): over a locally-signed
  713. install, retry identifier-pinned ad-hoc before the cdhash-only legacy sign;
  714. over a publisher-signed (Team ID) install, refuse — the weaker signature would
  715. orphan the keychain ACLs and TCC grants the update was asked to preserve
  716. (#123748). No-op with a publisher identity (CSC_LINK / APPLE_SIGNING_IDENTITY;
  717. callers may pass the decision so a later dotenv load can't reverse it) or an
  718. intact Developer ID signature. ``release_dir`` signs the STAGED bundle before
  719. promotion. Never raises.
  720. """
  721. if sys.platform != "darwin":
  722. return True
  723. if publisher_signing_configured is None:
  724. publisher_signing_configured = bool(
  725. os.environ.get("CSC_LINK") or os.environ.get("APPLE_SIGNING_IDENTITY"))
  726. if publisher_signing_configured:
  727. return True
  728. # ``release_dir`` (stage-and-swap, #86443): sign the STAGED bundle before it is promoted, so the live
  729. # app is never touched mid-sign.
  730. exe = _desktop_packaged_executable_in(release_dir or (desktop_dir / "release"))
  731. if exe is None:
  732. return True
  733. # exe = .../Hermes.app/Contents/MacOS/Hermes -> app bundle = .../Hermes.app
  734. app = exe.parents[2]
  735. if not str(app).endswith(".app") or not app.is_dir():
  736. return True
  737. codesign = shutil.which("codesign")
  738. if not codesign:
  739. return False
  740. if _desktop_macos_has_valid_real_signature(app):
  741. return True
  742. subprocess.run(["xattr", "-cr", str(app)], check=False)
  743. configured = _desktop_macos_local_signing_identity()
  744. identity = configured or "-"
  745. # The existing bundle this build's new signature replaces: the live release bundle the
  746. # staged pack is promoted over (``_swap_staged_desktop_app`` swaps by the same root
  747. # name), or the bundle being re-signed in place when no staging is involved. Its signing
  748. # class decides the fallback policy below; None when this is the first build.
  749. if release_dir is None:
  750. replaces = app
  751. else:
  752. try:
  753. replaces = desktop_dir / "release" / exe.relative_to(release_dir)
  754. except ValueError:
  755. replaces = None
  756. if not str(replaces).endswith(".app") or not replaces.is_dir():
  757. replaces = None
  758. try:
  759. if _desktop_macos_local_codesign(app, desktop_dir=desktop_dir, identity=identity):
  760. label = "keychain identity" if configured else "stable ad-hoc identity"
  761. print(f" → macOS desktop signed with {label}; TCC grants persist across rebuilds")
  762. return True
  763. except Exception as exc:
  764. if configured:
  765. target_sig = _macos_signature_summary(codesign, replaces) if replaces else None
  766. if target_sig and target_sig["team"]:
  767. # #123748: a publisher-signed (Team ID) install must never be degraded to a
  768. # locally signed or ad-hoc build — the weaker signature changes the anchor
  769. # the keychain ACLs and TCC grants are bound against, orphaning safeStorage
  770. # credentials. Keep the existing bundle and name the remedy.
  771. print(
  772. f" ✗ macOS signing identity {configured!r} did not produce a verified "
  773. f"signature, and the installed app is publisher-signed (Team ID "
  774. f"{target_sig['team']}); keeping it (no ad-hoc fallback). Fix the identity "
  775. "(e.g. `hermes desktop --setup-tcc-identity` or edit "
  776. "desktop.macos_signing_identity in config.yaml) and update again."
  777. )
  778. return False
  779. # A configured cert can fail while the login keychain is locked (an SSH
  780. # update, #121857). For a locally-signed install, identifier-pinned ad-hoc
  781. # still keeps the designated requirement and entitlements — TCC re-prompts
  782. # once — where the cdhash-only ``--deep --sign -`` would reset every grant
  783. # on each rebuild.
  784. print(
  785. f" (warning: configured macOS signing identity failed: {identity!r} ({exc}); "
  786. "falling back to identifier-pinned ad-hoc — TCC grants may need one "
  787. "re-prompt; run the update from the logged-in session to keep the "
  788. "certificate anchor)"
  789. )
  790. try:
  791. if _desktop_macos_local_codesign(app, desktop_dir=desktop_dir, identity="-"):
  792. print(
  793. " → macOS desktop signed with stable ad-hoc identity; "
  794. "TCC grants persist across rebuilds"
  795. )
  796. return True
  797. except Exception as adhoc_exc:
  798. exc = adhoc_exc
  799. print(f" (warning: stable macOS signing failed ({exc}); using legacy ad-hoc sign)")
  800. return _macos_legacy_adhoc_resign(codesign, app)
  801. def _app_asar_hash(app_path: Path) -> str | None:
  802. """Return the SHA-256 hex digest of an app bundle's app.asar, or None."""
  803. asar = app_path / "Contents" / "Resources" / "app.asar"
  804. if not asar.is_file():
  805. return None
  806. h = hashlib.sha256()
  807. try:
  808. with open(asar, "rb") as f:
  809. for chunk in iter(lambda: f.read(65536), b""):
  810. h.update(chunk)
  811. return h.hexdigest()
  812. except OSError:
  813. return None
  814. def _swap_in_new_macos_bundle(tmp: Path, target: Path, old: Path) -> None:
  815. """Move a staged macOS bundle into place without losing the old bundle."""
  816. moved_old = False
  817. if target.exists():
  818. try:
  819. target.rename(old)
  820. except OSError:
  821. shutil.rmtree(tmp, ignore_errors=True)
  822. raise
  823. moved_old = True
  824. try:
  825. tmp.rename(target)
  826. except OSError as install_error:
  827. rollback_error: OSError | None = None
  828. if moved_old:
  829. try:
  830. old.rename(target)
  831. except OSError as exc:
  832. rollback_error = exc
  833. shutil.rmtree(tmp, ignore_errors=True)
  834. if rollback_error is not None:
  835. raise OSError(
  836. f"installing the staged bundle failed and rollback remains at {old}: "
  837. f"{rollback_error}"
  838. ) from install_error
  839. raise
  840. shutil.rmtree(old, ignore_errors=True)
  841. def _running_macos_app_bundles() -> set[Path]:
  842. """``.app`` bundles of every live Hermes Desktop process. A running bundle is never swapped
  843. under: Electron loads ``app.asar`` chunks and helper apps lazily, so renaming its bundle away
  844. and deleting the old tree crashes the live app (the detached updater waits for it to exit)."""
  845. import psutil
  846. bundles: set[Path] = set()
  847. for proc in psutil.process_iter(["exe"]):
  848. exe = proc.info.get("exe") or ""
  849. if exe.endswith("/Contents/MacOS/Hermes"):
  850. bundles.add(Path(exe).resolve().parents[2])
  851. return bundles
  852. def _stage_macos_bundle_copy(src: Path, dst: Path) -> None:
  853. """``ditto`` copies a bundle with its signature, xattrs and symlinks intact (``shutil`` drops
  854. the resource-fork metadata codesign verifies)."""
  855. subprocess.run(["/usr/bin/ditto", str(src), str(dst)], check=True, capture_output=True)
  856. def _install_rebuilt_desktop_app(desktop_dir: Path, candidates: list[Path]) -> tuple[list[Path], list[str]]:
  857. """Copy the rebuilt macOS bundle into every stale or missing installed ``Hermes.app`` in
  858. *candidates* (``_installed_desktop_apps()``) (#52339).
  859. ``hermes desktop --build-only`` (what ``hermes update`` runs) packages into
  860. ``apps/desktop/release/`` only. Finder, the Dock and Spotlight launch the copy in
  861. ``/Applications`` (or ``~/Applications``), so without this step every update leaves the
  862. installed shell one build behind the backend it boots. The detached Desktop updater swaps
  863. only the bundle it was launched from, so an app running from ``release/`` never refreshed
  864. the installed copy either.
  865. Returns ``(installed, problems)``: bundles that were (re)installed, and one user-facing line per
  866. bundle that could not be (running, copy or swap failure). Both empty means every installed
  867. copy was already current.
  868. """
  869. if sys.platform != "darwin":
  870. return [], []
  871. rebuilt_exe = _desktop_packaged_executable(desktop_dir)
  872. if rebuilt_exe is None:
  873. return [], []
  874. # .../Hermes.app/Contents/MacOS/Hermes -> .../Hermes.app
  875. return _install_rebuilt_macos_bundles(
  876. rebuilt_exe.parents[2], candidates, running=_running_macos_app_bundles())
  877. def _refresh_installed_desktop_apps(desktop_dir: Path) -> None:
  878. """Install the rebuilt bundle over stale or missing installed copies, report each outcome, and
  879. record which copies this update keeps current."""
  880. if not _owns_installed_desktop_apps():
  881. return
  882. owned = _installed_desktop_apps()
  883. missing = {app for app in owned if not app.exists()}
  884. installed, problems = _install_rebuilt_desktop_app(desktop_dir, owned)
  885. for app in installed:
  886. if app in missing:
  887. print(f" ✓ Reinstalled the Desktop app at {app}: it had been removed, so Finder, "
  888. "the Dock and Spotlight could not find Hermes")
  889. else:
  890. print(f" ✓ Installed the rebuilt Desktop app at {app}")
  891. for problem in problems:
  892. print(f" ⚠ {problem}")
  893. from hermes_cli.gui_uninstall import desktop_install_record
  894. from utils import atomic_json_write, read_json_or_empty
  895. # A copy that failed to reinstall stays recorded, so the next update retries it. Every
  896. # `hermes desktop` launch lands here: write only when the set changed.
  897. apps = [str(app) for app in owned]
  898. if read_json_or_empty(desktop_install_record()).get("apps", []) == apps:
  899. return
  900. try:
  901. atomic_json_write(desktop_install_record(), {"apps": apps})
  902. except OSError as exc:
  903. print(f" ⚠ Could not record the installed Desktop app ({exc})")
  904. def _update_owned_macos_bundles(candidates: list[Path]) -> list[Path]:
  905. """The existing bundles in *candidates* that only ``hermes update`` keeps current (#52339).
  906. Ownership comes from the bundle's own ``install-stamp.json``. ``updateMechanism: self`` is a
  907. bootstrap build (a local pack or the bootstrap download), and stamps older than the field
  908. predate every self-updating kind. Bundled/light releases update themselves and commit builds
  909. are external, so a local build must never be copied over them. No readable stamp, no claim.
  910. """
  911. owned = []
  912. for app in candidates:
  913. try:
  914. stamp = json.loads((app / "Contents" / "Resources" / "install-stamp.json").read_text(encoding="utf-8-sig"))
  915. except (OSError, ValueError):
  916. continue
  917. if isinstance(stamp, dict) and stamp.get("updateMechanism", "self") == "self":
  918. owned.append(app)
  919. return owned
  920. def _owns_installed_desktop_apps() -> bool:
  921. """A packaged app runs the checkout under the default Hermes home, so only that checkout (on
  922. macOS) may build for it: a bundle from any other tree (a dev worktree) would split shell from
  923. backend."""
  924. if sys.platform != "darwin":
  925. return False
  926. from hermes_cli.main import PROJECT_ROOT
  927. from hermes_constants import get_default_hermes_root
  928. return Path(PROJECT_ROOT).resolve() == (get_default_hermes_root() / "hermes-agent").resolve()
  929. def _installed_desktop_apps() -> list[Path]:
  930. """Installed macOS ``Hermes.app`` bundles this checkout's update owns.
  931. When no owned copy is left, a recorded one that has gone missing still counts: its ownership
  932. stamp left with the bundle, and without the record nothing would ever put it back (Finder, the
  933. Dock and Spotlight lose Hermes for good). A copy moved to the other Applications folder keeps
  934. its stamp, so it is found instead of doubled. Hermes' GUI uninstall deletes the record.
  935. """
  936. if not _owns_installed_desktop_apps():
  937. return []
  938. from hermes_cli.gui_uninstall import desktop_install_record, packaged_gui_app_paths
  939. from utils import read_json_or_empty
  940. candidates = packaged_gui_app_paths()
  941. if owned := _update_owned_macos_bundles(candidates):
  942. return owned
  943. recorded = read_json_or_empty(desktop_install_record()).get("apps")
  944. if not isinstance(recorded, list):
  945. return []
  946. return [app for app in candidates if str(app) in recorded and not app.exists()]
  947. def _installed_desktop_launch_target(desktop_dir: Path, packaged_executable: Path) -> Path:
  948. """The executable ``hermes desktop`` launches: the installed app once it IS the checkout build.
  949. Finder, the Dock and Spotlight open the installed ``Hermes.app``; launching the ``release/``
  950. bundle beside it ran the same app from a second path while the installed copy went stale
  951. (#52339). Refresh the installed copies, then launch the first one that matches the checkout
  952. build. The checkout bundle stays the fallback: nothing installed, or a copy that is running
  953. or could not be replaced.
  954. """
  955. if sys.platform != "darwin":
  956. return packaged_executable
  957. _refresh_installed_desktop_apps(desktop_dir)
  958. rebuilt_hash = _app_asar_hash(packaged_executable.parents[2])
  959. for app in _installed_desktop_apps():
  960. if rebuilt_hash is not None and _app_asar_hash(app) == rebuilt_hash:
  961. return app / "Contents" / "MacOS" / "Hermes"
  962. return packaged_executable
  963. def _install_rebuilt_macos_bundles(
  964. rebuilt_app: Path, candidates: list[Path], *, running: set[Path]) -> tuple[list[Path], list[str]]:
  965. """Stage-and-swap ``rebuilt_app`` into each bundle path in ``candidates`` that is missing or
  966. whose ``app.asar`` differs. The rebuilt bundle already carries the stable local signing identity and no
  967. quarantine xattr (``_desktop_macos_relaunchable_fixup``); ``ditto`` preserves both, so nothing
  968. is re-signed here and TCC grants survive. A publisher-signed (Team ID) installation is never
  969. replaced by a locally signed build or a different signing/bundle identity — the swap is
  970. refused and reported instead (#123748)."""
  971. rebuilt_hash = _app_asar_hash(rebuilt_app)
  972. if rebuilt_hash is None:
  973. return [], []
  974. codesign = shutil.which("codesign")
  975. rebuilt_sig = _macos_signature_summary(codesign, rebuilt_app) if codesign else None
  976. installed: list[Path] = []
  977. problems: list[str] = []
  978. for app in candidates:
  979. # Either swapper (this one or the Desktop hand-off's posix.sh ``.old``) may have died
  980. # between its renames; recover before judging what is installed.
  981. _recover_interrupted_swap(app, app.parent / f"{app.name}.hermes-update-old")
  982. _recover_interrupted_swap(app, app.parent / f"{app.name}.old")
  983. if app.is_dir() and _app_asar_hash(app) == rebuilt_hash:
  984. continue
  985. if app.resolve() in running:
  986. problems.append(
  987. f"{app} is running and was not refreshed; quit Hermes Desktop and run "
  988. "`hermes update` again (or update from inside the app)")
  989. continue
  990. if codesign:
  991. installed_sig = _macos_signature_summary(codesign, app)
  992. if installed_sig is not None:
  993. downgrade = _macos_signing_downgrade_error(installed_sig, rebuilt_sig)
  994. if downgrade:
  995. problems.append(f"{app} not refreshed: {downgrade}")
  996. continue
  997. tmp = app.parent / f"{app.name}.hermes-update-new"
  998. old = app.parent / f"{app.name}.hermes-update-old"
  999. shutil.rmtree(tmp, ignore_errors=True)
  1000. try:
  1001. _stage_macos_bundle_copy(rebuilt_app, tmp)
  1002. _swap_in_new_macos_bundle(tmp, app, old)
  1003. except (OSError, subprocess.CalledProcessError) as exc:
  1004. shutil.rmtree(tmp, ignore_errors=True)
  1005. kept = "; the previous app was kept" if app.exists() else ""
  1006. problems.append(f"{app} could not be installed ({exc}){kept}")
  1007. continue
  1008. installed.append(app)
  1009. return installed, problems
  1010. def _force_adhoc_macos_signing(env: dict, *, source_mode: bool) -> bool:
  1011. """Force ad-hoc signing for the local packaged rebuild: with ``CSC_IDENTITY_AUTO_DISCOVERY`` on,
  1012. electron-builder grabs any personal keychain cert and stalls the sign step or clobbers a
  1013. notarized signature. No-op for source runs, off-macOS, with a real identity, or when pinned."""
  1014. if sys.platform != "darwin" or source_mode:
  1015. return False
  1016. if env.get("CSC_LINK") or env.get("APPLE_SIGNING_IDENTITY") or "CSC_IDENTITY_AUTO_DISCOVERY" in env:
  1017. return False
  1018. env["CSC_IDENTITY_AUTO_DISCOVERY"] = "false"
  1019. return True
  1020. def _desktop_linux_needs_no_sandbox() -> bool:
  1021. """True when Electron should run ``--no-sandbox``: Ubuntu 23.10+ ``apparmor_restrict_unprivileged_userns``
  1022. breaks the userns sandbox without a root-owned 4755 helper. Deliberately NOT True for root —
  1023. Electron as root without a sandbox must stay an explicit choice."""
  1024. if os.environ.get("ELECTRON_DISABLE_SANDBOX", 0) == "1":
  1025. return True
  1026. if sys.platform != "linux":
  1027. return False
  1028. if hasattr(os, "geteuid") and os.geteuid() == 0:
  1029. return False
  1030. try:
  1031. with open("/proc/sys/kernel/apparmor_restrict_unprivileged_userns", encoding="utf-8") as f:
  1032. return f.read().strip() == "1"
  1033. except OSError:
  1034. return False
  1035. def _desktop_linux_userns_sandbox_available() -> bool:
  1036. """True when the unprivileged userns sandbox works (probed with ``unshare``, fails closed) — then
  1037. the setuid ``chrome-sandbox`` helper is never consulted and no sudo prompt is needed."""
  1038. if sys.platform != "linux":
  1039. return False
  1040. unshare = shutil.which("unshare")
  1041. if not unshare:
  1042. return False
  1043. try:
  1044. return (
  1045. subprocess.run(
  1046. [unshare, "--user", "--map-root-user", "true"],
  1047. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5, check=False,
  1048. ).returncode
  1049. == 0)
  1050. except (OSError, subprocess.TimeoutExpired):
  1051. return False
  1052. def _sandbox_helper_lstat(packaged_executable: Path) -> tuple[Path, Optional[os.stat_result]]:
  1053. """``(chrome-sandbox path, lstat or None)`` — lstat so a symlink is inspected, not followed."""
  1054. sandbox = packaged_executable.parent / "chrome-sandbox"
  1055. try:
  1056. return sandbox, sandbox.lstat()
  1057. except OSError:
  1058. return sandbox, None
  1059. def _sandbox_helper_is_setuid_root(st: os.stat_result) -> bool:
  1060. return st.st_uid == 0 and stat.S_IMODE(st.st_mode) == 0o4755
  1061. def _desktop_linux_sandbox_helper_is_regular_file(packaged_executable: Path) -> bool:
  1062. """Return True when ``chrome-sandbox`` exists as a regular file."""
  1063. if sys.platform != "linux":
  1064. return False
  1065. _sandbox, st = _sandbox_helper_lstat(packaged_executable)
  1066. return st is not None and stat.S_ISREG(st.st_mode)
  1067. def _desktop_linux_sandbox_fixup(packaged_executable: Path) -> bool:
  1068. """Configure Electron's Linux SUID sandbox helper when required."""
  1069. if sys.platform != "linux":
  1070. return True
  1071. sandbox, st = _sandbox_helper_lstat(packaged_executable)
  1072. if not sandbox.exists():
  1073. print(f"✗ Hermes Desktop is missing Electron's Linux sandbox helper: {sandbox}")
  1074. return False
  1075. # Reject symlinks — chown/chmod must not follow an attacker-controlled link.
  1076. if st is None:
  1077. print(f"✗ Cannot stat Electron's Linux sandbox helper: {sandbox}")
  1078. return False
  1079. if not stat.S_ISREG(st.st_mode):
  1080. print(f"✗ Electron's Linux sandbox helper is not a regular file: {sandbox}")
  1081. return False
  1082. if _sandbox_helper_is_setuid_root(st):
  1083. return True
  1084. from hermes_cli.main_desktop_apparmor import chromium_userns_sandbox_verdict
  1085. verdict = chromium_userns_sandbox_verdict(packaged_executable)
  1086. if verdict if verdict is not None else _desktop_linux_userns_sandbox_available():
  1087. print("✓ Using Chromium's user-namespace sandbox (setuid helper not needed).")
  1088. return True
  1089. sudo = shutil.which("sudo")
  1090. if not sudo:
  1091. print("✗ Hermes Desktop requires sudo to configure Electron's Linux sandbox helper.")
  1092. return False
  1093. print("→ Configuring Electron Linux sandbox helper (sudo required)...")
  1094. # A .desktop/autostart/detached launch has no TTY, so a sudo password prompt could never be
  1095. # answered — without -n the launch hangs indefinitely instead of failing (#123927). Terminal
  1096. # launches keep the interactive prompt.
  1097. # ponytail: fail-fast only, no GUI askpass fallback; add one if TTY-less hosts need password sudo.
  1098. # ``sys.stdin`` is None when the process has no stdin at all (detached launch, GUI spawn that
  1099. # closed it) and a closed stream raises on ``isatty()``; both are no-TTY cases and neither may
  1100. # escape as a traceback that skips the ``--no-sandbox`` fallback (#123927 review).
  1101. try:
  1102. non_interactive = sys.stdin is None or not sys.stdin.isatty()
  1103. except ValueError: # stdin closed under us
  1104. non_interactive = True
  1105. for command in ([sudo, "chown", "root:root", str(sandbox)], [sudo, "chmod", "4755", str(sandbox)]):
  1106. if non_interactive:
  1107. command.insert(1, "-n")
  1108. try:
  1109. completed = subprocess.run(
  1110. command,
  1111. stdin=subprocess.DEVNULL if non_interactive else None,
  1112. timeout=60 if non_interactive else None,
  1113. check=False,
  1114. )
  1115. ok = completed.returncode == 0
  1116. except (OSError, subprocess.SubprocessError):
  1117. ok = False
  1118. if not ok:
  1119. print(f"✗ Failed to configure Electron's Linux sandbox helper: {sandbox}")
  1120. return False
  1121. return True
  1122. def _desktop_linux_needs_disable_setuid_sandbox(packaged_executable: Path) -> bool:
  1123. """True when a present, non-setuid ``chrome-sandbox`` would make Chromium abort with
  1124. ``setuid_sandbox_host`` despite a working userns sandbox (call after the fixup's userns path)."""
  1125. if sys.platform != "linux":
  1126. return False
  1127. _sandbox, st = _sandbox_helper_lstat(packaged_executable)
  1128. return st is not None and stat.S_ISREG(st.st_mode) and not _sandbox_helper_is_setuid_root(st)
  1129. _LINUX_PASSWORD_STORES = frozenset({"gnome-libsecret", "kwallet", "kwallet5", "kwallet6", "basic"})
  1130. _GPU_FLAG_WORDS = {**dict.fromkeys(("1", "true", "yes", "on"), "1"), **dict.fromkeys(("0", "false", "no", "off"), "0")}
  1131. def _detect_linux_password_store() -> str | None:
  1132. """Chromium password-store backend for this Linux session (KDE env → GNOME Keyring socket → D-Bus
  1133. ping of org.freedesktop.secrets), or None. Chromium's own detection fails under the launcher
  1134. env, and safeStorage then reports encryption unavailable."""
  1135. kde_version = os.environ.get("KDE_SESSION_VERSION", "").strip()
  1136. if kde_version:
  1137. return {"6": "kwallet6", "5": "kwallet5"}.get(kde_version, "kwallet")
  1138. if os.environ.get("KDE_FULL_SESSION"):
  1139. return "kwallet"
  1140. if os.environ.get("GNOME_KEYRING_CONTROL"):
  1141. return "gnome-libsecret"
  1142. with contextlib.suppress(Exception):
  1143. result = subprocess.run(
  1144. [
  1145. "dbus-send", "--session", "--print-reply", "--reply-timeout=2000",
  1146. "--dest=org.freedesktop.secrets",
  1147. "/org/freedesktop/secrets",
  1148. "org.freedesktop.DBus.Peer.Ping",
  1149. ],
  1150. capture_output=True,
  1151. timeout=5, check=False)
  1152. if result.returncode == 0:
  1153. return "gnome-libsecret"
  1154. return None
  1155. _A11Y_OFF_WORDS = frozenset(("0", "false", "no", "off", "disabled"))
  1156. def _desktop_launch_options() -> tuple[list[str], str, str, str, bool]:
  1157. """``desktop.*`` launch options: ``(electron_flags, disable_gpu "auto"/"1"/"0", password_store,
  1158. ozone_hint "auto"/"x11"/"wayland", renderer_accessibility bool)``; unknown values and config
  1159. errors yield "auto"/[]/True so a malformed config never blocks the launch."""
  1160. flags: list[str] = []
  1161. disable_gpu = password_store = ozone_hint = "auto"
  1162. renderer_accessibility = True
  1163. try:
  1164. from hermes_cli.config import load_config
  1165. desktop_cfg = (load_config() or {}).get("desktop") or {}
  1166. except Exception:
  1167. return flags, disable_gpu, password_store, ozone_hint, renderer_accessibility
  1168. raw_flags = desktop_cfg.get("electron_flags")
  1169. if isinstance(raw_flags, str):
  1170. flags = shlex.split(raw_flags, posix=(os.name != "nt"))
  1171. elif isinstance(raw_flags, (list, tuple)):
  1172. flags = [str(f) for f in raw_flags if str(f).strip()]
  1173. def _choice(key: str, allowed) -> str:
  1174. raw = desktop_cfg.get(key, "auto")
  1175. low = raw.strip().lower() if isinstance(raw, str) else ""
  1176. return low if low in allowed else "auto"
  1177. raw_gpu = desktop_cfg.get("disable_gpu", "auto")
  1178. if isinstance(raw_gpu, bool):
  1179. disable_gpu = "1" if raw_gpu else "0"
  1180. elif isinstance(raw_gpu, str):
  1181. disable_gpu = _GPU_FLAG_WORDS.get(raw_gpu.strip().lower(), "auto")
  1182. password_store = _choice("password_store", _LINUX_PASSWORD_STORES)
  1183. ozone_hint = _choice("ozone_platform_hint", ("auto", "x11", "wayland"))
  1184. raw_a11y = desktop_cfg.get("renderer_accessibility", True)
  1185. if isinstance(raw_a11y, bool):
  1186. renderer_accessibility = raw_a11y
  1187. elif isinstance(raw_a11y, (int, float)):
  1188. # YAML resolves a bare `0`/`0.0` to int/float, not str — the unquoted
  1189. # off-switch a user actually writes must not silently keep the ON
  1190. # default. Checked after bool: bool is an int subclass in Python.
  1191. renderer_accessibility = bool(raw_a11y)
  1192. elif isinstance(raw_a11y, str):
  1193. renderer_accessibility = raw_a11y.strip().lower() not in _A11Y_OFF_WORDS
  1194. return flags, disable_gpu, password_store, ozone_hint, renderer_accessibility
  1195. def _register_linux_desktop_entry(defer: bool = False):
  1196. """Install the XDG desktop entry for Hermes Desktop (Linux only, best-effort).
  1197. ``Exec`` and ``Icon`` are absolute so the entry works outside a login shell.
  1198. ``hermes uninstall --gui`` removes it.
  1199. ``defer=True`` (app-grid launch) returns a ``DeferredDesktopEntryInstall`` that writes the
  1200. entry only once the Electron window is on screen (#111906); ``None`` when nothing is
  1201. pending. Terminal, detached and ``--build-only`` launches install synchronously.
  1202. """
  1203. from hermes_cli.main import PROJECT_ROOT
  1204. try:
  1205. from hermes_cli.linux_desktop_entry import DeferredDesktopEntryInstall, install_desktop_entry, is_supported
  1206. if not is_supported():
  1207. return None
  1208. if defer:
  1209. deferred = DeferredDesktopEntryInstall(PROJECT_ROOT)
  1210. deferred.start()
  1211. return deferred
  1212. entry = install_desktop_entry(PROJECT_ROOT)
  1213. if entry:
  1214. print(f"✓ Desktop launcher entry installed: {entry}")
  1215. except Exception as exc: # never block a launch on launcher plumbing
  1216. print(f"⚠ Could not install the desktop launcher entry: {exc}")
  1217. return None
  1218. def _promote_staged_desktop_app(
  1219. desktop_dir: Path, staging_dir: Path, *,
  1220. integrity_check: Optional[Callable[[Path], Optional[str]]] = None,
  1221. ) -> Path:
  1222. """Sign and verify before swapping; the default integrity check is Windows PE validation."""
  1223. staged_executable = _desktop_packaged_executable_in(staging_dir)
  1224. # Locally-built apps are ad-hoc signed; make them relaunchable after an
  1225. # in-place self-update. Signs the STAGED bundle so the live app is never
  1226. # half-signed. No-op on non-macOS and on real-identity builds.
  1227. if not _desktop_macos_relaunchable_fixup(desktop_dir, release_dir=staging_dir):
  1228. # #123748: the fixup refused to sign (configured identity failed, codesign
  1229. # missing). Promoting would replace the live app with a bundle whose
  1230. # signature was never established — fold the refusal into the same
  1231. # previous-app-kept error path the integrity check uses.
  1232. _discard_desktop_staging(staging_dir)
  1233. print("✗ The rebuilt desktop app could not be signed with a stable identity; "
  1234. "not promoting it.")
  1235. raise RuntimeError(f"Desktop signing refused the staged build. {_PREVIOUS_APP_KEPT}")
  1236. # Validate only staging. The swap owns live-app rollback; raw in-place
  1237. # pack backups are not part of this transaction.
  1238. if integrity_check is None and sys.platform == "win32":
  1239. integrity_check = _desktop_exe_integrity_error
  1240. error = (
  1241. integrity_check(staged_executable)
  1242. if staged_executable is not None and integrity_check is not None else None
  1243. )
  1244. if staged_executable is None or error is not None:
  1245. _discard_desktop_staging(staging_dir)
  1246. if staged_executable is None:
  1247. print(f"✗ Desktop build produced no launchable app in {staging_dir}")
  1248. else:
  1249. print(f"✗ The built {staged_executable.name} failed its integrity check: {error}\n"
  1250. f" at: {staged_executable}")
  1251. raise RuntimeError(f"Desktop build produced no launchable app. {_PREVIOUS_APP_KEPT}")
  1252. held_by: list = []
  1253. packaged_executable = _swap_staged_desktop_app(desktop_dir, staging_dir, held_by=held_by)
  1254. if packaged_executable is None and held_by:
  1255. from hermes_cli.desktop_release_holders import describe_block, holder_names
  1256. print(describe_block(held_by, desktop_dir / "release"))
  1257. raise RuntimeError(
  1258. f"Could not publish the desktop build: {holder_names(held_by)} is using its folder. {_PREVIOUS_APP_KEPT}")
  1259. if packaged_executable is None:
  1260. print(f"✗ Could not install the rebuilt desktop app into {desktop_dir / 'release'}")
  1261. raise RuntimeError(f"Could not publish the desktop build. {_PREVIOUS_APP_KEPT}")
  1262. return packaged_executable
  1263. def _diagnose_esbuild_ignore_scripts(output: Optional[str]) -> None:
  1264. """Print an actionable hint when a desktop build failed because esbuild's platform
  1265. binary was never staged (`ignore-scripts=true` skips esbuild's postinstall, so the
  1266. ``@esbuild/<platform>`` optional dependency is absent) — #53082. Best-effort: only
  1267. adds context, never masks the original error."""
  1268. text = output or ""
  1269. if not ("@esbuild/" in text and "could not be found" in text) and "ignore-scripts" not in text:
  1270. return
  1271. print(" ⚠ This looks like esbuild's native binary is missing — commonly caused by")
  1272. print(" `ignore-scripts=true` in your npm config, which skips esbuild's postinstall")
  1273. print(" that stages the @esbuild/<platform> package.")
  1274. print(" Fix: run `npm config get ignore-scripts` — if true, either set it to false")
  1275. print(" (`npm config set ignore-scripts false`), then reinstall: `npm ci` in the repo root,")
  1276. print(" or stage the binary directly: `node node_modules/esbuild/install.js` in apps/desktop.")
  1277. def build_prepared_desktop(desktop_dir: Path, *, source_mode: bool, npm: str, env: dict,
  1278. icons: Path | None = None) -> Optional[Path]:
  1279. """Build prepared desktop sources, then publish the verified staged app."""
  1280. from hermes_cli.source_build import run_in_custody # npm writes the checkout: update custody
  1281. if not source_mode and sys.platform == "win32" and (ancestor := _desktop_ancestor_in(desktop_dir)):
  1282. # The Desktop running this build holds the exe lock the promotion rename needs,
  1283. # and stopping it would kill this process first (#123499). Packing would only
  1284. # produce a build that cannot be installed; leave the app as it is. Its content
  1285. # stamp stays stale, so `hermes desktop` run outside the app rebuilds it
  1286. # (_desktop_build_needed), and the in-app update completes with desktop=True.
  1287. print(f" ⚠ Skipped rebuilding the desktop app: this update is running inside it (pid {ancestor}),")
  1288. print(" and Windows locks a running app's files. Quit Hermes Desktop and run `hermes desktop`")
  1289. print(" from a terminal, or use Update now in Settings → About, to rebuild and reopen it.")
  1290. return None
  1291. build_label = "source build" if source_mode else "packaged app"
  1292. build_env = dict(env)
  1293. if sys.platform == "win32":
  1294. # The installer stages pinned Git in its own PowerShell process. Product
  1295. # builds run later, often with every system git removed from PATH; the
  1296. # desktop stamp must still resolve this checkout's real HEAD.
  1297. import pm
  1298. build_env = pm.ensure("git", base_env=build_env).env
  1299. if _force_adhoc_macos_signing(build_env, source_mode=source_mode):
  1300. print(" → No Developer ID configured; ad-hoc signing this local rebuild "
  1301. "(CSC_IDENTITY_AUTO_DISCOVERY=false)")
  1302. build_args = ["--icons", str(icons)] if icons else []
  1303. build_cmd = [npm, "run", "build", "--", *build_args]
  1304. staging_dir = None if source_mode else _desktop_staging_dir(desktop_dir)
  1305. if staging_dir is not None:
  1306. # electron-builder packs in place; only the verified staging tree may
  1307. # replace the running app, never a failed or incomplete build.
  1308. stopped = _stop_desktop_processes_locking_build(desktop_dir)
  1309. if stopped:
  1310. print(f" ⚠ Stopped running desktop app to free the build output (pid {', '.join(map(str, stopped))})")
  1311. try:
  1312. run_in_custody(desktop_dir.parents[1], build_cmd, f"Building desktop {build_label}", cwd=desktop_dir, env=build_env)
  1313. if staging_dir is not None:
  1314. from hermes_cli.update_stage import publish_stage
  1315. publish_stage("Packaging the desktop app")
  1316. run_in_custody(desktop_dir.parents[1], [npm, "run", "builder", "--", "--dir", "--publish", "never",
  1317. f"-c.directories.output={staging_dir}"], "Packaging the desktop app",
  1318. cwd=desktop_dir, env=build_env)
  1319. packaged_executable = (
  1320. _promote_staged_desktop_app(desktop_dir, staging_dir) if staging_dir is not None else None
  1321. )
  1322. return packaged_executable
  1323. except subprocess.CalledProcessError as exc:
  1324. _diagnose_esbuild_ignore_scripts(exc.output)
  1325. raise
  1326. finally:
  1327. if staging_dir is not None:
  1328. _discard_desktop_staging(staging_dir)
  1329. _WSL_DXG_DEVICE = Path("/dev/dxg")
  1330. _WSL_D3D12_DRIVERS = (
  1331. Path("/usr/lib/x86_64-linux-gnu/dri/d3d12_dri.so"),
  1332. Path("/usr/lib/aarch64-linux-gnu/dri/d3d12_dri.so"),
  1333. Path("/usr/lib64/dri/d3d12_dri.so"),
  1334. Path("/usr/lib/dri/d3d12_dri.so"),
  1335. )
  1336. _MESA_DRIVER_OVERRIDES = ("GALLIUM_DRIVER", "MESA_LOADER_DRIVER_OVERRIDE", "LIBGL_ALWAYS_SOFTWARE", "LIBGL_DRIVERS_PATH")
  1337. def _prefer_wsl_d3d12(env: dict) -> None:
  1338. """Under WSLg, /dev/dxg alone does not make Mesa pick the GPU: Chromium still lands on
  1339. llvmpipe unless GALLIUM_DRIVER selects d3d12, and it must be set before Electron spawns
  1340. its GPU process (setting it from JS is too late). Explicit Mesa choices win; hosts without
  1341. the driver are left alone."""
  1342. from hermes_constants import is_wsl
  1343. if any(key in env for key in _MESA_DRIVER_OVERRIDES):
  1344. return
  1345. if is_wsl() and _WSL_DXG_DEVICE.exists() and any(driver.is_file() for driver in _WSL_D3D12_DRIVERS):
  1346. env["GALLIUM_DRIVER"] = "d3d12"
  1347. # Chromium's ProcessSingleton binds $TMPDIR/scoped_dirXXXXXX/SingletonSocket (33 bytes after
  1348. # TMPDIR, measured on Electron 40); sun_path holds 107 bytes plus the NUL.
  1349. _ELECTRON_TMPDIR_MAX_BYTES = 107 - len("/scoped_dirXXXXXX/SingletonSocket")
  1350. _DESKTOP_TMPDIR_ENV = "HERMES_DESKTOP_TMPDIR"
  1351. def _desktop_launch_env(args: argparse.Namespace) -> tuple[dict, list[str]]:
  1352. """Electron child env + config-supplied extra flags. ``desktop.*`` config is bridged to env vars
  1353. Electron already reads; an explicit env var wins over config (and over keychain detection)."""
  1354. from hermes_constants import socket_safe_tmpdir, with_hermes_node_path
  1355. # with_hermes_node_path() copies os.environ when called with no arg.
  1356. env = with_hermes_node_path()
  1357. tmpdir = env.get("TMPDIR", "")
  1358. if sys.platform == "linux" and len(os.fsencode(tmpdir)) > _ELECTRON_TMPDIR_MAX_BYTES:
  1359. # A longer TMPDIR hangs requestSingleInstanceLock(). Only Chromium's socket dir moves:
  1360. # Electron main hands the real TMPDIR back to the backend and its other children.
  1361. env[_DESKTOP_TMPDIR_ENV] = tmpdir
  1362. env["TMPDIR"] = socket_safe_tmpdir()
  1363. _prefer_wsl_d3d12(env)
  1364. for attr, key in (
  1365. ("fake_boot", "HERMES_DESKTOP_BOOT_FAKE"), ("ignore_existing", "HERMES_DESKTOP_IGNORE_EXISTING")):
  1366. if getattr(args, attr, False):
  1367. env[key] = "1"
  1368. if getattr(args, "hermes_root", None):
  1369. env["HERMES_DESKTOP_HERMES_ROOT"] = str(Path(args.hermes_root).expanduser().resolve())
  1370. cwd = getattr(args, "cwd", None)
  1371. env["HERMES_DESKTOP_CWD"] = str(Path(cwd).expanduser().resolve()) if cwd else os.getcwd()
  1372. config_electron_flags, config_disable_gpu, config_password_store, config_ozone_hint, config_renderer_a11y = (
  1373. _desktop_launch_options())
  1374. if config_disable_gpu != "auto" and "HERMES_DESKTOP_DISABLE_GPU" not in os.environ:
  1375. env["HERMES_DESKTOP_DISABLE_GPU"] = config_disable_gpu
  1376. if config_ozone_hint != "auto" and "ELECTRON_OZONE_PLATFORM_HINT" not in os.environ:
  1377. env["ELECTRON_OZONE_PLATFORM_HINT"] = config_ozone_hint
  1378. # Renderer accessibility tree (composer exposure to OS dictation/IME
  1379. # tools, #118271/#92607) defaults to ON inside the app; bridge only the
  1380. # explicit opt-out so the default never depends on the launcher path.
  1381. if not config_renderer_a11y and "HERMES_DESKTOP_RENDERER_ACCESSIBILITY" not in os.environ:
  1382. env["HERMES_DESKTOP_RENDERER_ACCESSIBILITY"] = "0"
  1383. # Without --password-store safeStorage.isEncryptionAvailable() is often
  1384. # false and the desktop app refuses to persist remote gateway tokens.
  1385. if sys.platform == "linux" and "HERMES_DESKTOP_PASSWORD_STORE" not in os.environ:
  1386. password_store = (
  1387. config_password_store if config_password_store != "auto" else _detect_linux_password_store()
  1388. )
  1389. if password_store:
  1390. env["HERMES_DESKTOP_PASSWORD_STORE"] = password_store
  1391. return env, config_electron_flags
  1392. def _check_desktop_skip_build(
  1393. desktop_dir: Path, project_root: Path, *, source_mode: bool, packaged_executable: Optional[Path]
  1394. ) -> None:
  1395. """Validate the pre-built artifact ``--skip-build`` promised; exit with a hint when it's missing."""
  1396. if source_mode:
  1397. if not _desktop_dist_exists(desktop_dir):
  1398. print(f"✗ --skip-build --source was passed but no desktop dist found at: {desktop_dir / 'dist'}")
  1399. print(" Pre-build first: cd apps/desktop && npm run build")
  1400. print(" Or drop --skip-build to install dependencies and build automatically.")
  1401. sys.exit(1)
  1402. if not (_electron_dir(project_root) / "package.json").exists():
  1403. print("✗ --skip-build --source requires existing desktop workspace dependencies.")
  1404. print(f" Install first: cd {project_root} && npm ci")
  1405. print(" Or drop --skip-build to install dependencies and build automatically.")
  1406. sys.exit(1)
  1407. print(f"→ Skipping desktop source build (--skip-build --source); using dist at {desktop_dir / 'dist'}")
  1408. elif packaged_executable is None:
  1409. print(f"✗ --skip-build was passed but no packaged desktop app was found at: {desktop_dir / 'release'}")
  1410. print(" Pre-build first: cd apps/desktop && npm run pack")
  1411. print(" Or drop --skip-build to package automatically.")
  1412. sys.exit(1)
  1413. else:
  1414. desktop_launch_notice(f"→ Skipping desktop package build (--skip-build); using {packaged_executable}")
  1415. def _packaged_desktop_launch_command(packaged_executable: Path) -> list[str]:
  1416. """``[exe, *sandbox flags]`` after the Linux sandbox fixup; exits when the sandbox can't be configured."""
  1417. from hermes_cli.main_desktop_apparmor import print_no_sandbox_fallback
  1418. launch_command = [str(packaged_executable)]
  1419. if not _desktop_linux_sandbox_fixup(packaged_executable):
  1420. if _desktop_linux_needs_no_sandbox() and _desktop_linux_sandbox_helper_is_regular_file(packaged_executable):
  1421. print_no_sandbox_fallback(packaged_executable)
  1422. launch_command.append("--no-sandbox")
  1423. else:
  1424. sys.exit(1)
  1425. elif _desktop_linux_needs_disable_setuid_sandbox(packaged_executable):
  1426. launch_command.append("--disable-setuid-sandbox")
  1427. return launch_command
  1428. def _site_packages_install_kind(project_root: Path) -> Optional[str]:
  1429. """The package manager owning a non-editable install at *project_root*, or None.
  1430. A package-manager install (Homebrew, pip, distro packaging) places this
  1431. code in a ``site-packages``/``dist-packages`` tree. Such a tree ships no
  1432. ``apps/desktop`` source, so the build ladder below can never run — the
  1433. caller must not treat it like a broken checkout. A Homebrew formula lives
  1434. under a ``Cellar`` directory; any other site-packages owner is reported
  1435. generically as pip.
  1436. """
  1437. parts = Path(project_root).parts
  1438. if "site-packages" in parts or "dist-packages" in parts:
  1439. return "homebrew" if "Cellar" in parts else "pip"
  1440. return None
  1441. def _launch_installed_macos_desktop_app() -> bool:
  1442. """Launch a separately installed ``/Applications/Hermes.app``, if present.
  1443. Returns True only when the app bundle exists and a detached launch was
  1444. started — the caller then exits without touching the build ladder.
  1445. """
  1446. if sys.platform != "darwin":
  1447. return False
  1448. executable = Path("/Applications/Hermes.app/Contents/MacOS/Hermes")
  1449. if not executable.is_file():
  1450. return False
  1451. from hermes_cli.bundled_app import launch_detached
  1452. pid = launch_detached([str(executable)], cwd=executable.parent)
  1453. print(f"→ Launched the installed Hermes Desktop app: {executable} (pid {pid})")
  1454. return True
  1455. def _run_desktop_one_shot(args: argparse.Namespace, desktop_dir: Path, *, bundled: bool) -> None:
  1456. """Run a host-setup one-shot flag, then exit without building or launching."""
  1457. # macOS: a self-signed code-signing identity so TCC grants survive rebuilds.
  1458. if getattr(args, "setup_tcc_identity", False):
  1459. from hermes_cli.main_desktop_tcc import _desktop_macos_setup_tcc_identity
  1460. identity = getattr(args, "identity", None) or "Hermes Local Signing"
  1461. sys.exit(0 if _desktop_macos_setup_tcc_identity(identity) else 1)
  1462. # Linux: the per-binary AppArmor profile for Chromium's namespace sandbox (#130177).
  1463. if getattr(args, "install_apparmor_profile", False):
  1464. from hermes_cli.bundled_app import NotBundledApp, resolve_bundle_layout
  1465. from hermes_cli.main import PROJECT_ROOT
  1466. from hermes_cli.main_desktop_apparmor import install_profile
  1467. exe = _desktop_packaged_executable(desktop_dir)
  1468. if bundled:
  1469. with contextlib.suppress(NotBundledApp):
  1470. exe = resolve_bundle_layout(PROJECT_ROOT).launcher
  1471. if exe is None:
  1472. print(f"✗ No packaged Hermes Desktop found under {desktop_dir / 'release'}; run `hermes desktop` first.")
  1473. sys.exit(0 if exe is not None and install_profile(exe) else 1)
  1474. def cmd_gui(args: argparse.Namespace):
  1475. """Build and launch the native Electron desktop GUI."""
  1476. from hermes_cli.main import PROJECT_ROOT
  1477. from hermes_cli.source_build import prepare_source_dependencies, source_build_env
  1478. desktop_dir = PROJECT_ROOT / "apps" / "desktop"
  1479. # A bundled install IS the app: no source tree, no build, and the
  1480. # launcher is a sibling of this payload rather than something we
  1481. # produce. Every rung below assembles a checkout build, so the sealed
  1482. # shape leaves here with the env it just built.
  1483. from hermes_cli.steward import is_bundled_payload
  1484. bundled = is_bundled_payload(PROJECT_ROOT)
  1485. if not bundled and not (desktop_dir / "package.json").exists():
  1486. # A package-manager install (Homebrew, pip, ...) ships no desktop
  1487. # source tree, so building here is impossible by construction (#61056).
  1488. # Prefer the separately installed desktop app; otherwise explain the
  1489. # packaging shape instead of the generic missing-source error.
  1490. install_kind = _site_packages_install_kind(PROJECT_ROOT)
  1491. if install_kind is not None and _launch_installed_macos_desktop_app():
  1492. sys.exit(0)
  1493. print(f"Desktop GUI source not found at: {desktop_dir}")
  1494. if install_kind == "homebrew":
  1495. print(
  1496. " This Hermes came from Homebrew, which does not ship the desktop app's\n"
  1497. " source tree, so it cannot be built from this install.\n"
  1498. " Install the desktop app from https://hermes-agent.nousresearch.com,\n"
  1499. " or run `hermes desktop` from a source checkout."
  1500. )
  1501. sys.exit(1)
  1502. with contextlib.suppress(Exception):
  1503. from hermes_logging import setup_logging as _setup_logging_gui
  1504. _setup_logging_gui(mode="gui")
  1505. env, config_electron_flags = _desktop_launch_env(args)
  1506. source_mode = getattr(args, "source", False)
  1507. skip_build = getattr(args, "skip_build", False)
  1508. force_build = getattr(args, "force_build", False)
  1509. _run_desktop_one_shot(args, desktop_dir, bundled=bundled)
  1510. if bundled:
  1511. _launch_bundled_desktop(args, env, config_electron_flags)
  1512. packaged_executable = _desktop_packaged_executable(desktop_dir)
  1513. # The mutable preflight (freshness check → npm install → pack) mutates
  1514. # checkout-scoped node_modules and apps/desktop/release. Serialize it
  1515. # across processes so a manual `hermes desktop` racing `hermes update`'s
  1516. # rebuild cannot corrupt either (#93940). The lock lives outside the
  1517. # checkout, keyed by the resolved checkout path.
  1518. from hermes_cli.desktop_build_lock import DesktopBuildLock
  1519. build_lock: DesktopBuildLock | None = None
  1520. if not bundled and not skip_build:
  1521. build_lock = DesktopBuildLock(PROJECT_ROOT)
  1522. try:
  1523. acquired = build_lock.acquire()
  1524. except OSError as exc:
  1525. print(f"✗ Could not create the desktop build lock: {exc}")
  1526. print(" Refusing to run npm without serialization; check the checkout permissions and retry.")
  1527. sys.exit(1)
  1528. if not acquired:
  1529. print("✗ A Hermes update or another desktop dependency install or build is already running.")
  1530. print(" Wait for it to finish, then retry.")
  1531. sys.exit(2)
  1532. needs_build = not skip_build and (
  1533. force_build or _desktop_build_needed(desktop_dir, PROJECT_ROOT, source_mode=source_mode)
  1534. )
  1535. npm = None
  1536. try:
  1537. if needs_build:
  1538. build_env = source_build_env(env, explicit=force_build or getattr(args, "build_only", False))
  1539. npm = shutil.which("npm", path=build_env["PATH"])
  1540. env["PATH"] = build_env["PATH"]
  1541. if skip_build:
  1542. _check_desktop_skip_build(
  1543. desktop_dir, PROJECT_ROOT, source_mode=source_mode, packaged_executable=packaged_executable
  1544. )
  1545. elif needs_build:
  1546. prepare_source_dependencies(PROJECT_ROOT, ("ui-tui", "web", "apps/desktop"), env=build_env,
  1547. explicit=force_build or getattr(args, "build_only", False))
  1548. built = build_prepared_desktop(desktop_dir, source_mode=source_mode, npm=npm, env=build_env)
  1549. if not source_mode:
  1550. # None only when the build was skipped under its own Desktop: reopen the app it kept.
  1551. packaged_executable = built or packaged_executable
  1552. else:
  1553. build_label = "source build" if source_mode else "packaged app"
  1554. desktop_launch_notice(f"✓ Desktop {build_label} is up to date (content stamp matches)", source_mode=source_mode)
  1555. except (OSError, subprocess.SubprocessError, RuntimeError) as exc:
  1556. print(f"✗ Desktop GUI build failed: {exc}")
  1557. if build_lock is not None:
  1558. build_lock.release()
  1559. raise SystemExit(1) from exc
  1560. # Best-effort and idempotent; a failure must never stop the app from launching.
  1561. # An app-grid launch (DESKTOP_STARTUP_ID) must not write its own entry while the
  1562. # shell still has the app in STARTING, so it defers the write until Electron
  1563. # reports the window on screen (#111906). --build-only spawns no app: write now.
  1564. from hermes_cli.linux_desktop_entry import launched_from_shell
  1565. build_only = bool(getattr(args, "build_only", False))
  1566. deferred_entry = _register_linux_desktop_entry(defer=launched_from_shell() and not build_only)
  1567. # --build-only: produce the artifact but do NOT launch. The installer's
  1568. # --update flow drives the rebuild headlessly and launches the desktop
  1569. # itself (detached, after the old exe has exited); launching here would
  1570. # block the installer. Verify the artifact exists so a silent "built
  1571. # nothing" can't slip past.
  1572. if build_only:
  1573. if source_mode:
  1574. if not _desktop_dist_exists(desktop_dir):
  1575. print(f"✗ --build-only --source produced no dist at: {desktop_dir / 'dist'}")
  1576. sys.exit(1)
  1577. print(f"✓ Desktop source build ready at {desktop_dir / 'dist'} (not launching; --build-only)")
  1578. elif packaged_executable is None:
  1579. print(f"✗ --build-only produced no launchable app at: {desktop_dir / 'release'}")
  1580. print(" Expected an unpacked Electron app for the current OS.")
  1581. sys.exit(1)
  1582. else:
  1583. print(f"✓ Desktop packaged app ready: {packaged_executable} (not launching; --build-only)")
  1584. if build_lock is not None:
  1585. build_lock.release()
  1586. return
  1587. if source_mode:
  1588. print("→ Launching Hermes Desktop from source build...")
  1589. # Launch only the prepared runtime. npm exec can provision a missing
  1590. # Electron package, including when --skip-build was requested.
  1591. electron = _electron_dir(PROJECT_ROOT)
  1592. try:
  1593. executable = electron / "dist" / (electron / "path.txt").read_text(encoding="utf-8-sig").strip()
  1594. if not executable.is_file():
  1595. raise FileNotFoundError(executable)
  1596. except OSError as exc:
  1597. print(f"✗ Prepared Electron runtime is missing: {exc}")
  1598. print(" From the project root, run: node scripts/build/electron-runtime.mjs --source .")
  1599. raise SystemExit(1) from exc
  1600. launch_command = [str(executable), "."]
  1601. else:
  1602. if packaged_executable is None:
  1603. print(f"✗ Desktop package build completed but no launchable app was found at: {desktop_dir / 'release'}")
  1604. print(" Expected an unpacked Electron app for the current OS.")
  1605. sys.exit(1)
  1606. launch_command = _packaged_desktop_launch_command(
  1607. _installed_desktop_launch_target(desktop_dir, packaged_executable))
  1608. launch_command.extend(config_electron_flags)
  1609. if getattr(args, "local", False):
  1610. launch_command.append("--local")
  1611. # Out-of-band preview escape hatch (#97213): a fullscreened preview pane
  1612. # owns all input, and Wayland has no xdotool/wmctrl to break out from a
  1613. # terminal. `hermes desktop --close-preview` rides the single-instance
  1614. # argv so a second CLI invocation unlocks the running app.
  1615. if getattr(args, "close_preview", False):
  1616. launch_command.append("--close-preview")
  1617. launch_command.extend(_explicit_profile_args())
  1618. if not source_mode:
  1619. desktop_launch_notice(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")
  1620. # The launch target is ready; the fixups above finished mutating the
  1621. # packaged tree. Electron is the long-lived handoff, so release the build
  1622. # lock now — an open Desktop window must never block a future rebuild.
  1623. if build_lock is not None:
  1624. build_lock.release()
  1625. pass_fds: tuple[int, ...] = ()
  1626. if deferred_entry is not None:
  1627. env = deferred_entry.child_env(env)
  1628. pass_fds = deferred_entry.pass_fds
  1629. if not source_mode and sys.platform == "win32":
  1630. # Windows: detach the packaged Desktop from the parent console + process
  1631. # group, then return immediately (#58275). A console-inheriting
  1632. # subprocess.run dies with the launching shell (CTRL_CLOSE_EVENT fans
  1633. # out to the process group) and floods the parent terminal — under
  1634. # cp936, mojibake — with Electron/Node stdout. Mirrors the bundled
  1635. # launcher (_launch_bundled_desktop) and gateway_windows._spawn_detached.
  1636. # macOS/Linux keep the foreground run below: those launches are
  1637. # expected to stay attached to the terminal, and the desktop_console
  1638. # drain is a Windows-only concern.
  1639. from hermes_cli._subprocess_compat import (
  1640. windows_detach_flags,
  1641. windows_detach_flags_without_breakaway,
  1642. )
  1643. popen_kwargs = dict(
  1644. cwd=desktop_dir,
  1645. env=env,
  1646. stdin=subprocess.DEVNULL,
  1647. stdout=subprocess.DEVNULL,
  1648. stderr=subprocess.DEVNULL,
  1649. close_fds=True,
  1650. )
  1651. try:
  1652. subprocess.Popen(launch_command, creationflags=windows_detach_flags(), **popen_kwargs)
  1653. except OSError as exc:
  1654. # Only recover from a denied job breakaway (the parent's job object
  1655. # lacks JOB_OBJECT_LIMIT_BREAKAWAY_OK), which surfaces as
  1656. # ERROR_ACCESS_DENIED (winerror == 5). Re-raise every other spawn
  1657. # failure (bad argv/env, missing exe) so it stays a clear, single
  1658. # error instead of being masked by a doomed second attempt.
  1659. if getattr(exc, "winerror", None) != 5:
  1660. raise
  1661. subprocess.Popen(
  1662. launch_command,
  1663. creationflags=windows_detach_flags_without_breakaway(),
  1664. **popen_kwargs,
  1665. )
  1666. if deferred_entry is not None:
  1667. deferred_entry.finish()
  1668. desktop_launch_notice("✓ Hermes Desktop launched in a detached window; you can close this shell.")
  1669. sys.exit(0)
  1670. with desktop_console_output(source_mode=source_mode) as streams:
  1671. try:
  1672. launch_result = subprocess.run(
  1673. launch_command, cwd=desktop_dir, env=env, check=False, pass_fds=pass_fds, **streams
  1674. )
  1675. except KeyboardInterrupt:
  1676. # Ctrl-C in the terminal the launcher is attached to is the user
  1677. # closing the Desktop, not a launcher crash. Exit cleanly instead
  1678. # of dumping a KeyboardInterrupt traceback from subprocess.run
  1679. # (#59848).
  1680. print("\n✓ Hermes Desktop closed.")
  1681. sys.exit(0)
  1682. if deferred_entry is not None:
  1683. deferred_entry.finish()
  1684. sys.exit(launch_result.returncode)
  1685. def _explicit_profile_args() -> list[str]:
  1686. """``--profile <name>`` for Electron when ``-p``/``--profile`` was on argv.
  1687. Explicit flag only. A bare `hermes desktop` must not forward the sticky CLI
  1688. profile — Electron would persist it over the stored desktop one.
  1689. """
  1690. from hermes_cli.main import explicit_cli_profile
  1691. profile = explicit_cli_profile()
  1692. return ["--profile", profile] if profile else []
  1693. def _launch_bundled_desktop(
  1694. args: argparse.Namespace, env: dict, electron_flags: list[str]
  1695. ) -> None:
  1696. """Start the desktop app this CLI ships inside, then exit.
  1697. A bundled install has no source tree to build: the app is a signed,
  1698. read-only artifact and this Python is a passenger in its resources.
  1699. So the whole build ladder below is skipped and the launcher is started
  1700. DETACHED — the user ran a CLI command, and the app must outlive the
  1701. terminal it was typed into. The app's own single-instance lock turns a
  1702. second run into "focus the running window".
  1703. Never returns.
  1704. """
  1705. from hermes_cli.bundled_app import NotBundledApp, launch_detached, resolve_bundle_layout
  1706. from hermes_cli.main import PROJECT_ROOT
  1707. refused = [
  1708. flag
  1709. for flag, name in (
  1710. ("--source", "source"),
  1711. ("--build-only", "build_only"),
  1712. ("--force-build", "force_build"),
  1713. )
  1714. if getattr(args, name, False)
  1715. ]
  1716. if refused:
  1717. print(f"✗ {', '.join(refused)} cannot apply to a bundled Hermes install.")
  1718. print(" This app ships prebuilt and has no desktop source tree to build.")
  1719. sys.exit(2)
  1720. try:
  1721. layout = resolve_bundle_layout(PROJECT_ROOT)
  1722. except NotBundledApp as exc:
  1723. # The stamp says bundled, so a tree that is not one is a damaged or
  1724. # mispackaged install. Report it — degrading to the build ladder
  1725. # would run npm inside the app's own resources.
  1726. print(f"✗ This Hermes is stamped as a bundled desktop install, but {exc}.")
  1727. print(" The install is damaged — reinstall Hermes from the website.")
  1728. sys.exit(1)
  1729. if layout.launcher is None:
  1730. print(f"✗ Found no Hermes Desktop launcher in {layout.app_root}.")
  1731. print(" The install is damaged — reinstall Hermes from the website.")
  1732. sys.exit(1)
  1733. launch_command = _packaged_desktop_launch_command(layout.launcher)
  1734. launch_command.extend(electron_flags)
  1735. launch_command.extend(_explicit_profile_args())
  1736. pid = launch_detached(launch_command, env=env, cwd=layout.app_root)
  1737. print(f"→ Launched Hermes Desktop: {' '.join(launch_command)} (pid {pid})")
  1738. sys.exit(0)