worktree_exit.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. """The keep / archive / discard question when an interactive ``hermes -w`` session exits with a
  2. dirty or unpushed worktree.
  3. Asked once, in the foreground, after the UI released the terminal: by the classic CLI in
  4. ``_tui_shutdown`` (before ``_run_cleanup`` arms the exit watchdog) and by the TUI launcher after
  5. the Ink child exits. The answer is applied right there, synchronously, before any exit watchdog
  6. or teardown runs: a large archive is never cut short, and a failed one keeps the tree. Only a real interactive session
  7. asks: ``-q``/``-z``/cron/gateway never reach these call sites, a missing TTY or a signal-driven
  8. shutdown skips the question, and every skip means Keep (the sweep archives the tree later).
  9. """
  10. from __future__ import annotations
  11. import logging
  12. import os
  13. import sys
  14. from typing import Optional
  15. from agent.i18n import t
  16. logger = logging.getLogger(__name__)
  17. KEEP, ARCHIVE, DISCARD = "keep", "archive", "discard"
  18. def _has_tty() -> bool:
  19. try:
  20. return sys.stdin.isatty() and sys.stdout.isatty()
  21. except (AttributeError, ValueError):
  22. return False
  23. def worktree_state(info: dict) -> Optional[str]:
  24. """``"dirty"``, ``"unpushed"`` or None (clean and pushed / gone)."""
  25. from hermes_cli.worktree_ops import _worktree_has_unpushed_commits, _worktree_is_dirty
  26. path, repo_root = info.get("path", ""), info.get("repo_root", "")
  27. if not path or not os.path.isdir(path):
  28. return None
  29. if _worktree_is_dirty(path, repo_root, timeout=10):
  30. return "dirty"
  31. if _worktree_has_unpushed_commits(path, timeout=10):
  32. return "unpushed"
  33. return None
  34. def _still_in_use(path: str, grace_s: float = 5.0) -> bool:
  35. """Whether a live process (other than this one) still works in *path* after a short grace:
  36. the TUI's own backend (``tui_gateway``) takes a moment to exit after the Ink UI closes."""
  37. import time
  38. from hermes_cli.worktree_sweep import live_process_pids
  39. deadline = time.monotonic() + grace_s
  40. while live_process_pids([path], exclude=(os.getpid(),)).get(path):
  41. if time.monotonic() >= deadline:
  42. return True
  43. time.sleep(0.25)
  44. return False
  45. def ask_exit_choice(info: Optional[dict]) -> str:
  46. """Ask what to do with a dirty/unpushed tree; records the answer in ``info["exit_choice"]``."""
  47. if not info or not _has_tty():
  48. return KEEP
  49. state = worktree_state(info)
  50. if state is None:
  51. return KEEP
  52. if _still_in_use(info["path"]):
  53. return KEEP # something still runs in there; never offer to delete it
  54. from hermes_cli.curses_ui import curses_radiolist
  55. title = t(f"cli.worktree.exit_question_{state}", path=info["path"])
  56. items = [t("cli.worktree.exit_choice_keep"), t("cli.worktree.exit_choice_archive"),
  57. t("cli.worktree.exit_choice_discard")]
  58. try: # Esc / Ctrl-C / a curses failure all resolve to Keep (index 0)
  59. idx = curses_radiolist(title, items, selected=0, cancel_returns=0)
  60. except Exception:
  61. logger.debug("worktree exit question failed; keeping the tree", exc_info=True)
  62. idx = None
  63. choice = {1: ARCHIVE, 2: DISCARD}.get(idx, KEEP) if isinstance(idx, int) else KEEP
  64. info["exit_choice"] = choice
  65. return choice
  66. def apply_exit_choice(info: dict, echo) -> bool:
  67. """Carry out an Archive/Discard answer once -> True when the tree was handled (removed or a
  68. message printed). Keep (or no answer) -> False: the caller's default keep path runs."""
  69. choice = info.pop("exit_choice", None)
  70. if choice not in (ARCHIVE, DISCARD):
  71. return False
  72. path, repo_root, branch = info["path"], info["repo_root"], info.get("branch")
  73. if choice == ARCHIVE:
  74. import subprocess
  75. from hermes_cli.worktree_archive import ArchiveError
  76. from hermes_cli.worktree_sweep import archive_then_remove, sweep_settings
  77. echo(t("cli.worktree.archiving", path=path))
  78. try:
  79. ref, _kept, removed, why = archive_then_remove(
  80. repo_root, path, reason="session exit", unlock=True, exclude_pids=(os.getpid(),),
  81. max_untracked_mb=sweep_settings()["archive_max_file_mb"])
  82. except (ArchiveError, OSError, subprocess.SubprocessError, KeyboardInterrupt) as exc:
  83. echo(f"\033[31m{t('cli.worktree.archive_failed', path=path, error=str(exc) or 'interrupted')}\033[0m")
  84. return True
  85. name = ref.rsplit("/", 1)[-1]
  86. if removed:
  87. echo(f"\033[32m{t('cli.worktree.archived', path=path, ref=ref)}\033[0m")
  88. else:
  89. echo(f"\033[33m{t('cli.worktree.archived_kept', path=path, ref=ref, reason=why or '?')}\033[0m")
  90. echo(f" {t('cli.worktree.restore_hint', name=name)}")
  91. return True
  92. from hermes_cli._subprocess_compat import noninteractive_git_env
  93. from hermes_cli.worktree_ops import _git_quiet, release_lsp_clients
  94. release_lsp_clients(path)
  95. _git_quiet(["worktree", "unlock", path], repo_root, log="git worktree unlock failed (non-fatal)")
  96. _git_quiet(["worktree", "remove", path, "--force"], repo_root, timeout=60, log="Failed to remove worktree")
  97. if branch and not os.path.isdir(path):
  98. _git_quiet(["branch", "-D", branch], repo_root, log=f"Failed to delete branch {branch}",
  99. env=noninteractive_git_env())
  100. echo(f"\033[33m{t('cli.worktree.discarded', path=path)}\033[0m")
  101. return True