gateway_windows_legacy.py 4.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """Pre-suffix Windows gateway launchers: the objects the current per-profile names cannot reach.
  2. Before task/launcher names carried ``_profile_suffix()``, an install wrote the Scheduled Task
  3. ``Hermes_Gateway``, the Startup entry ``Hermes_Gateway.vbs``/``.cmd`` and the launcher pair
  4. ``gateway-service\\Hermes_Gateway.{vbs,cmd}``. Every operation in ``gateway_windows`` is keyed on
  5. ``get_task_name()`` → ``Hermes_Gateway_<suffix>``, so those strays are never queried, rewritten,
  6. reported or removed: they keep launching a second gateway at logon, never pick up launcher
  7. fixes, and ``hermes gateway status`` prints ✓ while they do (#116157). This module enumerates
  8. them once; ``status`` warns, ``uninstall`` and ``install --force`` remove.
  9. """
  10. from __future__ import annotations
  11. from pathlib import Path
  12. def _w():
  13. from hermes_cli import gateway_windows # facade binding is the seam for tests
  14. return gateway_windows
  15. def _targets_this_home(text: str) -> bool:
  16. """A bare-named launcher is OURS only when its action points into THIS home's ``gateway-service``
  17. dir. The bare name is also the live identity of the default ``~/.hermes`` profile, so a secondary
  18. profile that classified every ``Hermes_Gateway`` object as its own stray would delete the default
  19. profile's gateway autostart on ``uninstall`` / ``install --force``."""
  20. w = _w()
  21. marker = w._normalize_windows_path(str(w._hermes_home() / "gateway-service"))
  22. return marker in w._normalize_windows_path(text)
  23. def legacy_launcher_artifacts() -> list[tuple[str, str, Path | str]]:
  24. """``(kind, label, target)`` for every pre-suffix launcher of THIS home still present; ``kind`` is
  25. ``"file"`` or ``"task"``. Empty when this home owns the bare name (its current objects ARE the bare
  26. ones). Bare-named objects belonging to another home (a sibling install) are left alone."""
  27. w = _w()
  28. bare = w._TASK_NAME_DEFAULT
  29. if w.get_task_name() == bare:
  30. return []
  31. found: list[tuple[str, str, Path | str]] = []
  32. startup = w._startup_dir()
  33. service_dir = w._hermes_home() / "gateway-service"
  34. for path, label in (
  35. (startup / f"{bare}.vbs", "legacy pre-suffix Windows login item"),
  36. (startup / f"{bare}.cmd", "legacy pre-suffix Windows login item"),
  37. ):
  38. try:
  39. if _targets_this_home(path.read_text(encoding="utf-8-sig", errors="replace")):
  40. found.append(("file", label, path))
  41. except OSError:
  42. continue
  43. for path, label in (
  44. (service_dir / f"{bare}.vbs", "legacy pre-suffix task launcher"),
  45. (service_dir / f"{bare}.cmd", "legacy pre-suffix task script"),
  46. ):
  47. if path.exists(): # inside this home by construction
  48. found.append(("file", label, path))
  49. code, out, _err = w._exec_schtasks(["/Query", "/TN", bare, "/XML"])
  50. if code == 0 and _targets_this_home(out):
  51. found.append(("task", "legacy pre-suffix Scheduled Task", bare))
  52. return found
  53. def warn_legacy_launchers() -> bool:
  54. """``hermes gateway status``: name every stray so nobody has to do file-mtime archaeology."""
  55. artifacts = legacy_launcher_artifacts()
  56. for _kind, label, target in artifacts:
  57. print(f"⚠ {label} still installed: {target}")
  58. if artifacts:
  59. print(" These predate per-profile launcher names and also start the gateway at logon.")
  60. print(" Remove them with: hermes gateway uninstall (then: hermes gateway install)")
  61. return bool(artifacts)
  62. def remove_legacy_launchers() -> None:
  63. """``uninstall`` / ``install --force``: delete the strays; a task that needs elevation is named
  64. with the exact elevated command instead of being silently left behind."""
  65. w = _w()
  66. for kind, label, target in legacy_launcher_artifacts():
  67. if kind == "file":
  68. try:
  69. Path(target).unlink()
  70. print(f"✓ Removed {label}: {target}")
  71. except OSError as exc:
  72. print(f"⚠ Could not remove {label} {target}: {exc}")
  73. continue
  74. code, _out, err = w._exec_schtasks(["/Delete", "/F", "/TN", str(target)])
  75. if code == 0:
  76. print(f"✓ Removed {label} {str(target)!r}")
  77. elif w._is_access_denied(err.strip()):
  78. print(f"⚠ {label} {str(target)!r} needs an elevated shell to remove; run as administrator:")
  79. print(f" schtasks /Delete /F /TN {target}")
  80. else:
  81. print(f"⚠ schtasks /Delete {str(target)!r} returned code {code}: {err.strip()}")