From 01a3a6ab0d2d8e0e8644f85ff2c650d2cecd0821 Mon Sep 17 00:00:00 2001 From: teknium1 Date: Mon, 16 Feb 2026 02:43:45 -0800 Subject: [PATCH] Implement cleanup guard to prevent multiple executions on exit - Introduced a new cleanup function that ensures terminal and browser sessions are cleaned up only once during application exit. - Updated atexit registration to use the new cleanup function, enhancing resource management and preventing potential issues from multiple cleanup calls. - Modified terminal cleanup messaging to only display when environments are cleaned, improving user feedback. --- cli.py | 35 +++++++++++++++++++++-------------- tools/terminal_tool.py | 3 ++- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/cli.py b/cli.py index 3f8227d16..8427f08a8 100755 --- a/cli.py +++ b/cli.py @@ -237,6 +237,24 @@ from cron import create_job, list_jobs, remove_job, get_job, run_daemon as run_c from tools.terminal_tool import cleanup_all_environments as _cleanup_all_terminals from tools.browser_tool import _emergency_cleanup_all_sessions as _cleanup_all_browsers +# Guard to prevent cleanup from running multiple times on exit +_cleanup_done = False + +def _run_cleanup(): + """Run resource cleanup exactly once.""" + global _cleanup_done + if _cleanup_done: + return + _cleanup_done = True + try: + _cleanup_all_terminals() + except Exception: + pass + try: + _cleanup_all_browsers() + except Exception: + pass + # ============================================================================ # ASCII Art & Branding # ============================================================================ @@ -1606,9 +1624,7 @@ class HermesCLI: process_thread.start() # Register atexit cleanup so resources are freed even on unexpected exit - # (terminal VMs, browser sessions, etc.) - atexit.register(_cleanup_all_browsers) - atexit.register(_cleanup_all_terminals) + atexit.register(_run_cleanup) # Run the application with patch_stdout for proper output handling try: @@ -1618,15 +1634,7 @@ class HermesCLI: pass finally: self._should_exit = True - # Explicitly clean up resources before exit - try: - _cleanup_all_terminals() - except Exception: - pass - try: - _cleanup_all_browsers() - except Exception: - pass + _run_cleanup() print("\nGoodbye! ⚕") @@ -1747,8 +1755,7 @@ def main( sys.exit(0) # Register cleanup for single-query mode (interactive mode registers in run()) - atexit.register(_cleanup_all_browsers) - atexit.register(_cleanup_all_terminals) + atexit.register(_run_cleanup) # Handle single query mode if query: diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index bd6504595..43b21f8e4 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -1406,7 +1406,8 @@ def cleanup_all_environments(): except: pass - print(f"[Terminal Cleanup] Cleaned {cleaned} environments") + if not os.getenv("HERMES_QUIET") and cleaned > 0: + print(f"[Terminal Cleanup] Cleaned {cleaned} environments") return cleaned