From e2be46b65105134b9599cb0df91ebd48bf560a4f Mon Sep 17 00:00:00 2001 From: Brenner Spear Date: Fri, 17 Apr 2026 16:19:14 -0700 Subject: [PATCH 1/4] docs: add restart auto-resume PR spec --- .../auto-resume-after-restart-pr-spec.md | 589 ++++++++++++++++++ 1 file changed, 589 insertions(+) create mode 100644 docs/specs/auto-resume-after-restart-pr-spec.md diff --git a/docs/specs/auto-resume-after-restart-pr-spec.md b/docs/specs/auto-resume-after-restart-pr-spec.md new file mode 100644 index 0000000000000..7b63e15d25a2e --- /dev/null +++ b/docs/specs/auto-resume-after-restart-pr-spec.md @@ -0,0 +1,589 @@ +# PR Spec: Automatic Session Resume After Gateway Restart + +**Date:** 2026-04-17 + +> **Intent:** Fix the terrible current UX where Hermes says an interrupted task will resume after restart, but a forced/interrupted restart often converts that thread into a fresh session and tells the user to `/resume` manually. + +## TL;DR + +Hermes should treat **restart interruption** as a **resumable session state**, not as a **session reset**. + +Today, when gateway shutdown cannot drain active work within `agent.restart_drain_timeout`, startup falls back to `suspend_recently_active()`. That marks recently-active sessions as `suspended`, and the next message in the same thread causes `SessionStore.get_or_create_session()` to create a **new session ID** with `auto_reset_reason="suspended"`. The user sees: + +- shutdown banner: "Send any message after restart to resume where it left off." +- then next-turn banner: "Session automatically reset (previous session was stopped or interrupted). Use /resume..." + +That is the exact wrong behavior for the common case of **same thread, same user, same restart, still wants same task**. + +**Recommendation:** introduce a distinct persisted state like `resume_pending` / `interrupted_by_restart` and keep the existing `session_id` on the next message in the same thread. Reuse the existing transcript reload and auto-continue logic in `gateway/run.py` instead of creating a new session. Only escalate to `suspended` / clean-slate behavior after repeated failed restart-resume attempts or explicit stuck-loop detection. + +--- + +## Problem statement + +### Current user experience + +Current behavior is incoherent: + +1. Hermes sends an optimistic restart notice. +2. Gateway restart times out draining active agents. +3. Startup suspends recently-active sessions. +4. The user's next message in the same thread lands in a fresh session. +5. Hermes tells the user to browse `/resume` manually. + +This is a terrible experience because: + +- the product promises one behavior and delivers the opposite, +- the user is forced to understand internal session mechanics, +- the resume path is thread-local and obvious to the system but not automatic, +- the current fallback destroys continuity even though transcript history still exists. + +### Root cause in current code + +Relevant current behavior: + +- shutdown banner text in `gateway/run.py` + - `_notify_active_sessions_of_shutdown()` + - says: `Send any message after restart to resume where it left off.` +- forced-interrupt path in `gateway/run.py` + - if drain times out, gateway interrupts active agents + - skips `.clean_shutdown` marker so next startup treats the prior run as unsafe +- startup recovery in `gateway/run.py` + - calls `self.session_store.suspend_recently_active()` when `.clean_shutdown` is absent +- session reset behavior in `gateway/session.py` + - `get_or_create_session()` checks `entry.suspended` + - suspended sessions are turned into a **new session ID** with `auto_reset_reason="suspended"` +- reset notice in `gateway/run.py` + - emits: `Session automatically reset (previous session was stopped or interrupted)...` +- transcript continuation logic already exists in `gateway/run.py` + - if loaded history ends with a `tool` message, Hermes prepends a system note telling the model to finish the interrupted work + +**Important observation:** Hermes already has part of the resume mechanism. The main thing preventing automatic resume is that forced restart currently turns the session into a fresh session instead of preserving the old one. + +--- + +## Product goal + +When a user restarts Hermes and then sends the next message in the **same chat/thread/topic**, Hermes should, by default: + +1. preserve the same conversation lane, +2. preserve the same `session_id`, +3. reload the same transcript, +4. inform the model that the previous turn was interrupted by restart, +5. continue/resume automatically, +6. avoid making the user manually browse `/resume` unless recovery has actually failed. + +### Desired UX + +For the normal case: + +- user starts a long task in thread X +- gateway restarts +- user returns to thread X and says anything +- Hermes continues from the interrupted session in thread X + +For the pathological case: + +- same session repeatedly hangs across multiple restarts +- Hermes eventually abandons auto-resume for that session and gives the user a clean slate + +--- + +## Non-goals + +This PR should **not** try to: + +- implement fully autonomous resume with **no** user follow-up message, +- merge different threads/chats/topics into one session, +- auto-resume across a different thread than the one that was interrupted, +- invent a generic distributed job recovery layer, +- remove existing stuck-loop safety mechanisms entirely, +- change normal idle/daily `session_reset` policy semantics. + +This is specifically about **same-lane restart continuity** after gateway interruption. + +--- + +## Design principles + +1. **Restart interruption is not the same as intentional reset.** +2. **Same thread should keep same session unless proven unsafe.** +3. **Safety escalation should be progressive, not immediate.** +4. **User-visible messages must describe the actual recovery semantics.** +5. **Reuse existing transcript + auto-continue machinery instead of inventing new prompt plumbing.** + +--- + +## Recommendation + +## Introduce a resumable restart-interruption state + +Add a persisted session state that is distinct from `suspended`. + +### New state + +Recommended `SessionEntry` fields in `gateway/session.py`: + +```python +resume_pending: bool = False +resume_reason: Optional[str] = None # e.g. "restart_timeout", "crash_recovery" +resume_attempts: int = 0 +last_resume_marked_at: Optional[datetime] = None +``` + +### Meaning of states + +- `suspended=True` + - do **not** resume automatically + - next access should create a fresh session + - used for known-poisoned sessions / explicit stuck-loop protection +- `resume_pending=True` + - user should stay on the same session + - next access should preserve the existing session ID + - used when a restart interrupted in-flight work but we still expect same-thread continuation to succeed + +This is the key architectural distinction missing today. + +--- + +## High-level behavior change + +### Current behavior + +```text +restart timed out + -> skip .clean_shutdown + -> startup: suspend_recently_active() + -> session.suspended = True + -> next message => new session_id + -> user gets reset notice + /resume guidance +``` + +### Proposed behavior + +```text +restart timed out + -> mark active session(s) as resume_pending=True + -> next startup preserves mapping + -> next message in same thread returns existing session entry + -> transcript reloads from same session_id + -> model gets interruption note + -> Hermes continues automatically +``` + +### Escalation path + +```text +restart timed out repeatedly for same session + -> increment resume_attempts / stuck-loop counter + -> once threshold exceeded, convert to suspended=True + -> only then force fresh-session fallback +``` + +--- + +## Detailed design + +## 1) Persist `resume_pending` on interrupted restart + +### Where to mark it + +During shutdown in `gateway/run.py`, after drain timeout is detected and the gateway force-interrupts active agents, mark the active session keys as `resume_pending=True`. + +This should happen **instead of** relying on the startup-wide "recently active means suspend" fallback for these sessions. + +### Why here + +At shutdown time, the gateway knows: + +- which sessions were actually running, +- that the interruption came from restart/shutdown, +- that this is not an idle/daily reset, +- that the user did not ask for `/new`. + +That is the correct moment to record resumable interruption state. + +### Proposed helper + +Add a method to `SessionStore` in `gateway/session.py`: + +```python +def mark_resume_pending( + self, + session_key: str, + *, + reason: str = "restart_timeout", + increment_attempts: bool = True, +) -> bool: + ... +``` + +Responsibilities: + +- set `resume_pending=True` +- set `resume_reason` +- bump `resume_attempts` if requested +- persist metadata in `sessions.json` + +--- + +## 2) Do not auto-reset `resume_pending` sessions on next access + +### Current bad behavior + +`SessionStore.get_or_create_session()` currently treats `suspended` as "auto-reset on next access". + +### Proposed behavior + +Extend `get_or_create_session()` logic: + +- if `entry.suspended` → current reset behavior stays +- if `entry.resume_pending` → **return the existing entry** and clear or downgrade the resume marker once the resume turn begins successfully + +Pseudo-shape: + +```python +if entry.suspended: + reset_reason = "suspended" +elif entry.resume_pending: + entry.updated_at = now + self._save() + return entry +else: + reset_reason = self._should_reset(entry, source) +``` + +This is the core functional fix. + +--- + +## 3) Reuse existing transcript reload and auto-continue logic + +This PR should explicitly lean on behavior that already exists. + +### Existing asset + +`gateway/run.py` already prepends an interruption note when the loaded history ends in a `tool` result: + +- if transcript ends with role `tool`, Hermes tells the model to finish processing interrupted tool results before addressing the new user message. + +### Extend the system note behavior + +If `session_entry.resume_pending` is set, prepend a stronger note such as: + +> `[System note: Your previous turn in this same session was interrupted by a gateway restart. Continue from the existing transcript. If there are unfinished tool results, process them first, summarize what was accomplished, then answer the user's new message.]` + +This should work whether the transcript ended with: + +- a `tool` message, +- an interrupted assistant turn, +- or a partially completed tool-heavy exchange. + +### Why this is enough for v1 + +We do **not** need a brand-new recovery engine for the first version. + +Preserving the same session ID plus transcript reload plus better interruption note gets the common case back to a sane product experience. + +--- + +## 4) Keep stuck-loop protection, but move it to an escalation policy + +We should not regress the original safety intent behind the stuck-loop work. + +### Proposed rule + +- first interrupted restart for a session → auto-resume +- second interrupted restart for same session within recovery window → still auto-resume, but warn internally / increment counter +- third interrupted restart (or configurable threshold) → convert session to `suspended=True` + +This keeps safety without making the default path destructive. + +### Practical implementation options + +Option A: reuse existing stuck-loop tracking files/logic in `GatewayRunner` +- keep the existing consecutive restart accounting +- when threshold is exceeded, switch `resume_pending` -> `suspended` + +Option B: track directly in `SessionEntry` +- increment `resume_attempts` +- clear it after a successful resumed turn +- if `resume_attempts >= threshold`, set `suspended=True` + +**Recommendation:** use `SessionEntry` fields for session-local semantics and let existing gateway-level stuck-loop tracking continue to exist if needed. That makes the persisted reason visible and easier to test. + +--- + +## 5) Narrow the role of `suspend_recently_active()` + +`suspend_recently_active()` is too blunt as the generic fallback for restart interruption. + +### Current role + +It treats "recently active at startup after unclean shutdown" as a reason to force clean-slate behavior. + +### Proposed role after this PR + +Reserve it for narrower cases, such as: + +- startup crash recovery when explicit `resume_pending` metadata is absent, +- legacy upgrade path / backward compatibility, +- emergency fallback for clearly unsafe sessions, +- repeated failed recovery loops. + +### Important outcome + +This means **restart interruption should no longer immediately flow through the same code path as 'known stuck session'.** + +That separation is the real product fix. + +--- + +## 6) Fix user-facing messaging + +### Current messaging is misleading + +#### Shutdown banner +Current wording: + +> `Send any message after restart to resume where it left off.` + +This is too absolute. + +#### Reset notice +Current wording points users to `session_reset` config even when the real cause is startup suspension after interrupted restart. + +### Proposed messaging + +#### Shutdown banner +For resumable restart: + +- non-threaded chat: + - `Gateway restarting — I'll try to resume this session after restart. Send a message in this chat to continue.` +- threaded/topic chat: + - `Gateway restarting — I'll try to resume this session after restart. Send a message in this thread/topic to continue.` + +#### If the system escalates to forced clean slate +Only after repeated failure should the user see something like: + +- `This session was interrupted repeatedly during restart recovery, so Hermes started a fresh session to avoid getting stuck. Use /resume if you want the old transcript.` + +### Message principle + +Only mention `/resume` when Hermes has actually decided **not** to auto-resume. + +--- + +## State machine + +```text +ACTIVE + -> clean restart/shutdown drains successfully + -> ACTIVE (same session preserved) + +ACTIVE + -> restart/crash interrupts in-flight work + -> RESUME_PENDING + +RESUME_PENDING + -> next message in same thread/topic + -> ACTIVE (same session_id, transcript reloaded) + +RESUME_PENDING + -> repeated interrupted restarts exceed threshold + -> SUSPENDED + +SUSPENDED + -> next message + -> NEW_SESSION (fresh session_id, old transcript still available via /resume) +``` + +--- + +## File-level implementation plan + +## Primary files + +### `gateway/session.py` + +Add persisted session fields and APIs: + +- new `SessionEntry` fields: + - `resume_pending` + - `resume_reason` + - `resume_attempts` + - `last_resume_marked_at` +- serialization/deserialization support in `to_dict()` / `from_dict()` +- helper methods: + - `mark_resume_pending(...)` + - `clear_resume_pending(...)` + - maybe `escalate_to_suspended(...)` +- update `get_or_create_session()` so `resume_pending` returns existing session instead of resetting + +### `gateway/run.py` + +Update gateway behavior: + +- after drain timeout, mark active sessions `resume_pending=True` +- on resumed turn, inject restart-interruption system note when `session_entry.resume_pending` +- clear `resume_pending` after a successful resumed turn begins or completes +- update shutdown banner wording to promise attempted recovery, not guaranteed recovery +- stop routing normal interrupted restart recovery through immediate clean-slate semantics + +### `tests/gateway/` + +Add or update tests for: + +- same-session resume after interrupted restart +- transcript preserved across restart timeout +- tool-result auto-continue still works on resumed session +- repeated recovery failure escalates to suspended/new session +- shutdown banner wording is no longer misleading +- `/resume` guidance only appears when clean-slate fallback actually occurs + +--- + +## Test plan + +## Unit tests + +### `tests/gateway/test_restart_resume_pending.py` (new) + +Suggested cases: + +1. **mark resume pending persists state** + - create session + - call `mark_resume_pending()` + - reload store + - assert flags persisted + +2. **resume_pending does not create new session id** + - create session + - mark `resume_pending=True` + - call `get_or_create_session()` + - assert returned `session_id` is unchanged + +3. **suspended still creates new session id** + - existing current behavior regression guard + +4. **clear resume pending after success** + - mark resumable + - simulate successful turn start or completion + - assert `resume_pending=False` + +### `tests/gateway/test_restart_recovery_flow.py` (new) + +Suggested cases: + +1. **interrupted restart in same thread resumes existing session** + - transcript exists under original session id + - next message in same thread loads same transcript + - no auto-reset notice + +2. **tool-tail transcript triggers auto-continue note on resumed session** + - transcript ends with `tool` + - resumed run prepends correct system note + +3. **repeated restart failures escalate to suspended** + - simulate threshold crossings + - assert fresh-session fallback only after threshold + +4. **clean restart remains unchanged** + - `.clean_shutdown` path still preserves session as before + +### Message-copy tests + +Add assertions for the updated shutdown banner and fallback text. + +--- + +## Backward compatibility + +This change should be backward-compatible with existing stored sessions. + +### Migration behavior + +- old `sessions.json` entries simply deserialize with default values for new fields +- no database migration should be required if session metadata remains file-backed +- existing `suspended=True` entries should keep current semantics + +### Important safety note + +Do **not** silently reinterpret existing `suspended=True` as resumable. That would change meaning for users who explicitly relied on the current clean-slate escape hatch. + +--- + +## Risks + +### 1. Resume loop risk +If resume is attempted too aggressively, a truly poisoned session could keep re-entering the same bad state. + +**Mitigation:** keep thresholded escalation to `suspended`. + +### 2. Partial transcript ambiguity +If a turn was interrupted mid-assistant generation, the last messages may not be perfectly shaped. + +**Mitigation:** keep the recovery note explicit and rely on existing transcript loading behavior. Tests should cover common partial-tail shapes. + +### 3. Messaging confusion during rollout +If message copy changes before semantics change, UX could still be misleading. + +**Mitigation:** land copy changes in the same PR as behavior changes. + +--- + +## Open questions + +1. Should `resume_pending` clear at turn start or only after a successful completed turn? + - **Recommendation:** clear after successful completion, but protect against duplicate recovery attempts with an in-memory guard during the running turn. + +2. Should recovery be attempted only in the same thread/topic, or also same parent chat? + - **Recommendation:** same session key only. Do not cross lanes. + +3. Should startup still run `suspend_recently_active()` at all when explicit `resume_pending` markers were written during shutdown? + - **Recommendation:** no, not for those specific session keys. + +4. Should the user get an explicit "resuming interrupted work" notice? + - **Recommendation:** probably no extra chat spam in v1. Keep it as an internal system note unless debugging is enabled. + +--- + +## Recommended implementation order + +1. Add `SessionEntry` resume-pending fields + serialization +2. Add `SessionStore.mark_resume_pending()` / `clear_resume_pending()` +3. Change `get_or_create_session()` to preserve same session for `resume_pending` +4. Mark active sessions resume-pending on drain-timeout shutdown +5. Inject restart-resume system note in `gateway/run.py` +6. Clear pending state after successful resume +7. Add escalation threshold behavior +8. Update shutdown/fallback copy +9. Add regression tests + +--- + +## Success criteria + +This PR is successful if all of the following are true: + +1. A long-running task interrupted by gateway restart in a Discord/Telegram thread resumes automatically on the next message in the same thread. +2. The resumed thread keeps the same `session_id` and transcript history. +3. Hermes no longer tells the user to `/resume` for the normal restart-recovery case. +4. Existing clean restart behavior is preserved. +5. Truly stuck sessions still have a safety escape hatch after repeated failures. +6. User-facing restart copy accurately describes attempted recovery rather than promising impossible behavior. + +--- + +## Strong opinion + +Hermes should **default to continuity** after restart and only fall back to clean-slate reset when recovery is actually failing. + +Right now the system is optimized for protecting itself from stuck loops at the cost of making ordinary restart recovery feel broken. That tradeoff is backwards for user experience. + +The correct product stance is: + +- **same thread + same user + immediate post-restart message = continue automatically** +- **repeated failed recovery = fresh session as safety fallback** + +That gets the common case right without giving up the escape hatch. From 5619fa07620a9dd2cf95da93f3591c8d7235c89b Mon Sep 17 00:00:00 2001 From: Brenner Spear Date: Fri, 17 Apr 2026 22:23:47 -0700 Subject: [PATCH 2/4] fix(gateway): auto-resume interrupted restart sessions --- gateway/run.py | 135 +++++++++++++++----- gateway/session.py | 77 ++++++++++- tests/gateway/test_auto_continue.py | 33 +++++ tests/gateway/test_clean_shutdown_marker.py | 61 +++++++++ tests/gateway/test_restart_drain.py | 5 +- tests/gateway/test_session.py | 82 ++++++++++++ tests/gateway/test_session_reset_notify.py | 96 +++++++++++++- tests/gateway/test_stuck_loop.py | 2 + 8 files changed, 456 insertions(+), 35 deletions(-) diff --git a/gateway/run.py b/gateway/run.py index ea747321f95af..4fd81bf8a46e3 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -533,6 +533,43 @@ def _parse_session_key(session_key: str) -> "dict | None": return None +def _prepend_restart_recovery_note( + message: str, + agent_history: list[dict], + *, + resume_pending: bool, +) -> str: + """Prepend the appropriate interrupted-turn recovery note.""" + has_tool_tail = bool(agent_history and agent_history[-1].get("role") == "tool") + if resume_pending: + if has_tool_tail: + note = ( + "[System note: Your previous turn in this same session was interrupted by " + "a gateway restart. Continue from the existing transcript. There are " + "unfinished tool results in the conversation history, so process those " + "results first, summarize what was accomplished, then answer the user's " + "new message below.]" + ) + else: + note = ( + "[System note: Your previous turn in this same session was interrupted by " + "a gateway restart. Continue from the existing transcript and preserve " + "session continuity when answering the user's new message below.]" + ) + return note + "\n\n" + message + + if has_tool_tail: + return ( + "[System note: Your previous turn was interrupted before you could " + "process the last tool result(s). The conversation history contains " + "tool outputs you haven't responded to yet. Please finish processing " + "those results and summarize what was accomplished, then address the " + "user's new message below.]\n\n" + + message + ) + return message + + def _format_gateway_process_notification(evt: dict) -> "str | None": """Format a watch pattern event from completion_queue into a [SYSTEM:] message.""" evt_type = evt.get("type", "completion") @@ -1537,13 +1574,6 @@ async def _notify_active_sessions_of_shutdown(self) -> None: return action = "restarting" if self._restart_requested else "shutting down" - hint = ( - "Your current task will be interrupted. " - "Send any message after restart to resume where it left off." - if self._restart_requested - else "Your current task will be interrupted." - ) - msg = f"⚠️ Gateway {action} — {hint}" notified: set = set() for session_key in active: @@ -1571,6 +1601,19 @@ async def _notify_active_sessions_of_shutdown(self) -> None: thread_id = _parsed.get("thread_id") metadata = {"thread_id": thread_id} if thread_id else None + if self._restart_requested: + lane_hint = ( + "Send a message in this thread/topic to continue." + if thread_id + else "Send a message in this chat to continue." + ) + msg = ( + f"⚠️ Gateway {action} — I'll try to resume this session " + f"after restart. {lane_hint}" + ) + else: + msg = f"⚠️ Gateway {action} — Your current task will be interrupted." + await adapter.send(chat_id, msg, metadata=metadata) notified.add(dedup_key) logger.info( @@ -1670,6 +1713,8 @@ def _suspend_stuck_loop_sessions(self) -> int: entry = self.session_store._entries.get(session_key) if entry and not entry.suspended: entry.suspended = True + entry.resume_pending = False + entry.resume_reason = None suspended += 1 logger.warning( "Auto-suspended stuck session %s (active across %d " @@ -2368,11 +2413,25 @@ async def _stop_impl() -> None: timeout = self._restart_drain_timeout active_agents, timed_out = await self._drain_active_agents(timeout) if timed_out: + timed_out_session_keys = set(self._running_agents.keys()) logger.warning( "Gateway drain timed out after %.1fs with %d active agent(s); interrupting remaining work.", timeout, self._running_agent_count(), ) + if timed_out_session_keys: + for session_key in timed_out_session_keys: + try: + self.session_store.mark_resume_pending( + session_key, + reason="restart_timeout" if self._restart_requested else "shutdown_timeout", + ) + except Exception as e: + logger.debug( + "Failed to mark session %s resume-pending during shutdown: %s", + session_key[:30], + e, + ) self._interrupt_running_agents( "Gateway restarting" if self._restart_requested else "Gateway shutting down" ) @@ -2466,8 +2525,8 @@ async def _stop_impl() -> None: else: logger.info( "Skipping .clean_shutdown marker — drain timed out with " - "interrupted agents; next startup will suspend recently " - "active sessions." + "interrupted agents; resumable recovery metadata was " + "persisted for those sessions." ) # Track sessions that were active at shutdown for stuck-loop @@ -3611,7 +3670,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): if getattr(session_entry, 'was_auto_reset', False): reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'idle' if reset_reason == "suspended": - context_note = "[System note: The user's previous session was stopped and suspended. This is a fresh conversation with no prior context.]" + context_note = "[System note: The user's previous session was interrupted repeatedly during restart recovery, so Hermes started a fresh conversation to avoid getting stuck. This is a fresh conversation with no prior context.]" elif reset_reason == "daily": context_note = "[System note: The user's session was automatically reset by the daily schedule. This is a fresh conversation with no prior context.]" else: @@ -3640,20 +3699,30 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): adapter = self.adapters.get(source.platform) if adapter: if reset_reason == "suspended": - reason_text = "previous session was stopped or interrupted" + notice = ( + "◐ This session was interrupted repeatedly during restart " + "recovery, so Hermes started a fresh session to avoid " + "getting stuck. Use /resume if you want the old transcript." + ) elif reset_reason == "daily": reason_text = f"daily schedule at {policy.at_hour}:00" + notice = ( + f"◐ Session automatically reset ({reason_text}). " + f"Conversation history cleared.\n" + f"Use /resume to browse and restore a previous session.\n" + f"Adjust reset timing in config.yaml under session_reset." + ) else: hours = policy.idle_minutes // 60 mins = policy.idle_minutes % 60 duration = f"{hours}h" if not mins else f"{hours}h {mins}m" if hours else f"{mins}m" reason_text = f"inactive for {duration}" - notice = ( - f"◐ Session automatically reset ({reason_text}). " - f"Conversation history cleared.\n" - f"Use /resume to browse and restore a previous session.\n" - f"Adjust reset timing in config.yaml under session_reset." - ) + notice = ( + f"◐ Session automatically reset ({reason_text}). " + f"Conversation history cleared.\n" + f"Use /resume to browse and restore a previous session.\n" + f"Adjust reset timing in config.yaml under session_reset." + ) try: session_info = self._format_session_info() if session_info: @@ -4034,6 +4103,7 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): source=source, session_id=session_entry.session_id, session_key=session_key, + session_entry=session_entry, event_message_id=event.message_id, channel_prompt=event.channel_prompt, ) @@ -4074,6 +4144,16 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): # restarts where the session was active (never completed). if session_key: self._clear_restart_failure_count(session_key) + if getattr(session_entry, "resume_pending", False): + try: + if not agent_result.get("failed") and not agent_result.get("interrupted"): + self.session_store.clear_resume_pending(session_key) + session_entry.resume_pending = False + session_entry.resume_reason = None + session_entry.resume_attempts = 0 + session_entry.last_resume_marked_at = None + except Exception as e: + logger.debug("Failed to clear resume-pending state for %s: %s", session_key[:30], e) # Surface error details when the agent failed silently (final_response=None) if not response and agent_result.get("failed"): @@ -8492,6 +8572,7 @@ async def _run_agent( source: SessionSource, session_id: str, session_key: str = None, + session_entry: Any = None, _interrupt_depth: int = 0, event_message_id: Optional[str] = None, channel_prompt: Optional[str] = None, @@ -9251,20 +9332,11 @@ def _approval_notify_sync(approval_data: dict) -> None: if _msn: message = _msn + "\n\n" + message - # Auto-continue: if the loaded history ends with a tool result, - # the previous agent turn was interrupted mid-work (gateway - # restart, crash, SIGTERM). Prepend a system note so the model - # finishes processing the pending tool results before addressing - # the user's new message. (#4493) - if agent_history and agent_history[-1].get("role") == "tool": - message = ( - "[System note: Your previous turn was interrupted before you could " - "process the last tool result(s). The conversation history contains " - "tool outputs you haven't responded to yet. Please finish processing " - "those results and summarize what was accomplished, then address the " - "user's new message below.]\n\n" - + message - ) + message = _prepend_restart_recovery_note( + message, + agent_history, + resume_pending=bool(getattr(session_entry, "resume_pending", False)), + ) _approval_session_key = session_key or "" _approval_session_token = set_current_session_key(_approval_session_key) @@ -9881,6 +9953,7 @@ async def _notify_long_running(): source=next_source, session_id=session_id, session_key=session_key, + session_entry=session_entry, _interrupt_depth=_interrupt_depth + 1, event_message_id=next_message_id, channel_prompt=next_channel_prompt, diff --git a/gateway/session.py b/gateway/session.py index 4cb623128c7b0..fe526310dc6c6 100644 --- a/gateway/session.py +++ b/gateway/session.py @@ -377,6 +377,14 @@ class SessionEntry: # this session (create a new session_id) so the user starts fresh. # Set by /stop to break stuck-resume loops (#7536). suspended: bool = False + + # Restart/crash recovery state. Unlike `suspended`, this keeps the user + # on the same session_id for the next same-lane message so transcript + # reload and continuation can resume in place. + resume_pending: bool = False + resume_reason: Optional[str] = None + resume_attempts: int = 0 + last_resume_marked_at: Optional[datetime] = None def to_dict(self) -> Dict[str, Any]: result = { @@ -397,6 +405,14 @@ def to_dict(self) -> Dict[str, Any]: "cost_status": self.cost_status, "memory_flushed": self.memory_flushed, "suspended": self.suspended, + "resume_pending": self.resume_pending, + "resume_reason": self.resume_reason, + "resume_attempts": self.resume_attempts, + "last_resume_marked_at": ( + self.last_resume_marked_at.isoformat() + if self.last_resume_marked_at + else None + ), } if self.origin: result["origin"] = self.origin.to_dict() @@ -434,6 +450,14 @@ def from_dict(cls, data: Dict[str, Any]) -> "SessionEntry": cost_status=data.get("cost_status", "unknown"), memory_flushed=data.get("memory_flushed", False), suspended=data.get("suspended", False), + resume_pending=data.get("resume_pending", False), + resume_reason=data.get("resume_reason"), + resume_attempts=data.get("resume_attempts", 0), + last_resume_marked_at=( + datetime.fromisoformat(data["last_resume_marked_at"]) + if data.get("last_resume_marked_at") + else None + ), ) @@ -713,6 +737,10 @@ def get_or_create_session( # broke a stuck loop — #7536). if entry.suspended: reset_reason = "suspended" + elif entry.resume_pending: + entry.updated_at = now + self._save() + return entry else: reset_reason = self._should_reset(entry, source) if not reset_reason: @@ -798,10 +826,53 @@ def suspend_session(self, session_key: str) -> bool: self._ensure_loaded_locked() if session_key in self._entries: self._entries[session_key].suspended = True + self._entries[session_key].resume_pending = False + self._entries[session_key].resume_reason = None self._save() return True return False + def mark_resume_pending( + self, + session_key: str, + *, + reason: str = "restart_timeout", + increment_attempts: bool = True, + ) -> bool: + """Mark a session as resumable after restart interruption.""" + with self._lock: + self._ensure_loaded_locked() + entry = self._entries.get(session_key) + if not entry: + return False + entry.resume_pending = True + entry.resume_reason = reason + entry.last_resume_marked_at = _now() + if increment_attempts: + entry.resume_attempts += 1 + self._save() + return True + + def clear_resume_pending( + self, + session_key: str, + *, + reset_attempts: bool = True, + ) -> bool: + """Clear resumable restart state after recovery succeeds.""" + with self._lock: + self._ensure_loaded_locked() + entry = self._entries.get(session_key) + if not entry: + return False + entry.resume_pending = False + entry.resume_reason = None + entry.last_resume_marked_at = None + if reset_attempts: + entry.resume_attempts = 0 + self._save() + return True + def prune_old_entries(self, max_age_days: int) -> int: """Drop SessionEntry records older than max_age_days. @@ -869,7 +940,11 @@ def suspend_recently_active(self, max_age_seconds: int = 120) -> int: with self._lock: self._ensure_loaded_locked() for entry in self._entries.values(): - if not entry.suspended and entry.updated_at >= cutoff: + if ( + not entry.suspended + and not entry.resume_pending + and entry.updated_at >= cutoff + ): entry.suspended = True count += 1 if count: diff --git a/tests/gateway/test_auto_continue.py b/tests/gateway/test_auto_continue.py index 1f44fa6ab1d37..25df852ae01d8 100644 --- a/tests/gateway/test_auto_continue.py +++ b/tests/gateway/test_auto_continue.py @@ -8,6 +8,8 @@ import pytest +import gateway.run as gateway_run + def _simulate_auto_continue(agent_history: list, user_message: str) -> str: """Reproduce the auto-continue injection logic from _run_agent(). @@ -93,3 +95,34 @@ def test_original_message_preserved_after_note(self): note_end = result.index("]\n\n") user_msg_start = result.index("now do X") assert user_msg_start > note_end + + +class TestRestartRecoveryNote: + def test_resume_pending_prepends_restart_note_even_without_tool_tail(self): + result = gateway_run._prepend_restart_recovery_note( + "pick up where you left off", + [], + resume_pending=True, + ) + + assert result.startswith("[System note:") + assert "gateway restart" in result + assert "pick up where you left off" in result + + def test_resume_pending_with_tool_tail_uses_restart_specific_guidance(self): + history = [ + {"role": "assistant", "content": None, "tool_calls": [ + {"id": "call_1", "function": {"name": "terminal", "arguments": "{}"}} + ]}, + {"role": "tool", "tool_call_id": "call_1", "content": "done"}, + ] + + result = gateway_run._prepend_restart_recovery_note( + "continue", + history, + resume_pending=True, + ) + + assert "gateway restart" in result + assert "unfinished tool results" in result or "finish processing" in result + assert result.endswith("continue") diff --git a/tests/gateway/test_clean_shutdown_marker.py b/tests/gateway/test_clean_shutdown_marker.py index 1a476bc49a575..c101da3c218a6 100644 --- a/tests/gateway/test_clean_shutdown_marker.py +++ b/tests/gateway/test_clean_shutdown_marker.py @@ -224,3 +224,64 @@ def test_marker_written_on_restart_stop(self, tmp_path, monkeypatch): asyncio.get_event_loop().run_until_complete(runner.stop(restart=True)) assert marker.exists(), ".clean_shutdown marker should exist after restart-stop too" + + def test_timed_out_restart_marks_resume_pending_without_clean_marker(self, tmp_path, monkeypatch): + """Timed-out restart should preserve resumable state instead of immediate suspension.""" + monkeypatch.setattr("gateway.run._hermes_home", tmp_path) + marker = tmp_path / ".clean_shutdown" + + store = _make_store(tmp_path) + source = _make_source() + entry = store.get_or_create_session(source) + completed_source = _make_source(chat_id="completed") + completed_entry = store.get_or_create_session(completed_source) + + from gateway.run import GatewayRunner + + runner = object.__new__(GatewayRunner) + runner._restart_requested = False + runner._restart_detached = False + runner._restart_via_service = False + runner._restart_task_started = False + runner._running = True + runner._draining = False + runner._stop_task = None + runner._running_agents = {entry.session_key: MagicMock()} + runner._running_agents_ts = {} + runner._pending_messages = {} + runner._pending_approvals = {} + runner._background_tasks = set() + runner._shutdown_event = MagicMock() + runner._restart_drain_timeout = 5 + runner._exit_code = None + runner._exit_reason = None + runner.adapters = {} + runner.config = GatewayConfig() + runner.session_store = store + + active_agents = { + entry.session_key: MagicMock(), + completed_entry.session_key: MagicMock(), + } + + with patch("gateway.run.GatewayRunner._drain_active_agents", new_callable=AsyncMock, return_value=(active_agents, True)), \ + patch("gateway.run.GatewayRunner._finalize_shutdown_agents"), \ + patch("gateway.run.GatewayRunner._update_runtime_status"), \ + patch("gateway.status.remove_pid_file"), \ + patch("tools.process_registry.process_registry") as mock_proc_reg, \ + patch("tools.terminal_tool.cleanup_all_environments"), \ + patch("tools.browser_tool.cleanup_all_browsers"): + mock_proc_reg.kill_all = MagicMock() + + import asyncio + asyncio.get_event_loop().run_until_complete(runner.stop(restart=True)) + + refreshed = store.get_or_create_session(source) + completed_refreshed = store.get_or_create_session(completed_source) + assert marker.exists() is False + assert refreshed.session_id == entry.session_id + assert refreshed.resume_pending is True + assert refreshed.resume_reason == "restart_timeout" + assert refreshed.suspended is False + assert completed_refreshed.session_id == completed_entry.session_id + assert completed_refreshed.resume_pending is False diff --git a/tests/gateway/test_restart_drain.py b/tests/gateway/test_restart_drain.py index 3607b1e39192a..b83eed301eb91 100644 --- a/tests/gateway/test_restart_drain.py +++ b/tests/gateway/test_restart_drain.py @@ -183,7 +183,7 @@ async def test_shutdown_notification_sent_to_active_sessions(): @pytest.mark.asyncio async def test_shutdown_notification_says_restarting_when_restart_requested(): - """When _restart_requested is True, the message says 'restarting' and mentions /retry.""" + """Restart copy should promise attempted recovery, not guaranteed resume.""" runner, adapter = make_restart_runner() runner._restart_requested = True session_key = "agent:main:telegram:dm:999" @@ -193,7 +193,8 @@ async def test_shutdown_notification_says_restarting_when_restart_requested(): assert len(adapter.sent) == 1 assert "restarting" in adapter.sent[0] - assert "resume" in adapter.sent[0] + assert "I'll try to resume this session after restart." in adapter.sent[0] + assert "Send a message in this chat to continue." in adapter.sent[0] @pytest.mark.asyncio diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.py index 39e4aad3d6524..79d559a1f1583 100644 --- a/tests/gateway/test_session.py +++ b/tests/gateway/test_session.py @@ -604,6 +604,88 @@ def test_switch_session_reopens_target_session_in_db(self, tmp_path): db.close() +class TestSessionStoreResumePending: + """Restart recovery state should preserve the current session lane.""" + + @pytest.fixture() + def store(self, tmp_path): + config = GatewayConfig() + with patch("gateway.session.SessionStore._ensure_loaded"): + s = SessionStore(sessions_dir=tmp_path, config=config) + s._db = None + s._loaded = True + return s + + def test_mark_resume_pending_persists_across_reload(self, store): + source = SessionSource( + platform=Platform.TELEGRAM, + chat_id="123", + chat_type="dm", + user_id="u1", + ) + entry = store.get_or_create_session(source) + + assert store.mark_resume_pending(entry.session_key, reason="restart_timeout") is True + + reloaded = SessionStore(sessions_dir=store.sessions_dir, config=store.config) + resumed = reloaded.get_or_create_session(source) + assert resumed.session_id == entry.session_id + assert resumed.resume_pending is True + assert resumed.resume_reason == "restart_timeout" + assert resumed.resume_attempts == 1 + + def test_resume_pending_reuses_same_session_id(self, store): + source = SessionSource( + platform=Platform.TELEGRAM, + chat_id="456", + chat_type="dm", + user_id="u2", + ) + entry = store.get_or_create_session(source) + store.mark_resume_pending(entry.session_key, reason="restart_timeout") + + resumed = store.get_or_create_session(source) + + assert resumed.session_id == entry.session_id + assert resumed.was_auto_reset is False + assert resumed.auto_reset_reason is None + + def test_clear_resume_pending_keeps_session_active(self, store): + source = SessionSource( + platform=Platform.TELEGRAM, + chat_id="789", + chat_type="dm", + user_id="u3", + ) + entry = store.get_or_create_session(source) + store.mark_resume_pending(entry.session_key, reason="restart_timeout") + + assert store.clear_resume_pending(entry.session_key) is True + + refreshed = store.get_or_create_session(source) + assert refreshed.session_id == entry.session_id + assert refreshed.resume_pending is False + assert refreshed.resume_reason is None + + def test_suspend_recently_active_skips_resume_pending_sessions(self, store): + source = SessionSource( + platform=Platform.TELEGRAM, + chat_id="999", + chat_type="dm", + user_id="u4", + ) + entry = store.get_or_create_session(source) + store.mark_resume_pending(entry.session_key, reason="restart_timeout") + + count = store.suspend_recently_active() + + assert count == 0 + resumed = store.get_or_create_session(source) + assert resumed.session_id == entry.session_id + assert resumed.resume_pending is True + assert resumed.suspended is False + + class TestWhatsAppDMSessionKeyConsistency: """Regression: all session-key construction must go through build_session_key so DMs are isolated by chat_id across platforms.""" diff --git a/tests/gateway/test_session_reset_notify.py b/tests/gateway/test_session_reset_notify.py index 87903921fbda8..06ee83a626de7 100644 --- a/tests/gateway/test_session_reset_notify.py +++ b/tests/gateway/test_session_reset_notify.py @@ -8,7 +8,7 @@ """ from datetime import datetime, timedelta -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import pytest @@ -18,6 +18,7 @@ PlatformConfig, SessionResetPolicy, ) +from gateway.platforms.base import MessageEvent, MessageType from gateway.session import SessionEntry, SessionSource, SessionStore @@ -205,3 +206,96 @@ def test_to_dict_roundtrip(self): assert restored.notify == original.notify assert restored.notify_exclude_platforms == original.notify_exclude_platforms assert restored.mode == original.mode + + +def _make_notify_runner(session_entry: SessionEntry): + from types import SimpleNamespace + + from gateway.run import GatewayRunner + + runner = object.__new__(GatewayRunner) + runner.config = GatewayConfig( + platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")} + ) + adapter = MagicMock() + adapter.send = AsyncMock() + runner.adapters = {Platform.TELEGRAM: adapter} + runner._voice_mode = {} + runner.hooks = SimpleNamespace(emit=AsyncMock(), loaded_hooks=False) + runner.session_store = MagicMock() + runner.session_store.config = runner.config + runner.session_store.get_or_create_session.return_value = session_entry + runner.session_store.load_transcript.return_value = [] + runner.session_store.has_any_sessions.return_value = True + runner.session_store.append_to_transcript = MagicMock() + runner.session_store.rewrite_transcript = MagicMock() + runner.session_store.update_session = MagicMock() + runner._running_agents = {} + runner._pending_messages = {} + runner._pending_approvals = {} + runner._session_db = MagicMock() + runner._session_db.get_session_title.return_value = None + runner._reasoning_config = None + runner._provider_routing = {} + runner._fallback_model = None + runner._show_reasoning = False + runner._is_user_authorized = lambda _source: True + runner._set_session_env = lambda _context: None + runner._should_send_voice_reply = lambda *_args, **_kwargs: False + runner._send_voice_reply = AsyncMock() + runner._capture_gateway_honcho_if_configured = lambda *args, **kwargs: None + runner._emit_gateway_run_progress = AsyncMock() + runner._run_agent = AsyncMock( + return_value={ + "final_response": "ok", + "messages": [], + "tools": [], + "history_offset": 0, + "last_prompt_tokens": 0, + "input_tokens": 0, + "output_tokens": 0, + "model": "openai/test-model", + } + ) + return runner, adapter + + +@pytest.mark.asyncio +async def test_suspended_fallback_notice_mentions_repeated_restart_recovery(monkeypatch): + import gateway.run as gateway_run + + source = _make_source() + session_entry = SessionEntry( + session_key=source.chat_id, + session_id="sess-1", + created_at=datetime.now(), + updated_at=datetime.now(), + platform=Platform.TELEGRAM, + chat_type="dm", + was_auto_reset=True, + auto_reset_reason="suspended", + reset_had_activity=True, + ) + runner, adapter = _make_notify_runner(session_entry) + + event = MessageEvent( + text="hello", + message_type=MessageType.TEXT, + source=source, + message_id="m1", + ) + + monkeypatch.setattr(gateway_run, "_resolve_runtime_agent_kwargs", lambda: {"api_key": "***"}) + monkeypatch.setattr( + "agent.model_metadata.get_model_context_length", + lambda *_args, **_kwargs: 100000, + ) + + result = await runner._handle_message(event) + + assert result == "ok" + adapter.send.assert_awaited_once() + notice = adapter.send.await_args.args[1] + assert "interrupted repeatedly during restart recovery" in notice + assert "Use /resume if you want the old transcript." in notice + assert "session_reset" not in notice diff --git a/tests/gateway/test_stuck_loop.py b/tests/gateway/test_stuck_loop.py index a26f29a2b573b..6a91edf53533a 100644 --- a/tests/gateway/test_stuck_loop.py +++ b/tests/gateway/test_stuck_loop.py @@ -58,12 +58,14 @@ def test_suspend_at_threshold(self, runner_with_home): # Create a mock session entry mock_entry = MagicMock() mock_entry.suspended = False + mock_entry.resume_pending = True runner.session_store._entries = {"session:a": mock_entry} runner.session_store._save = MagicMock() suspended = runner._suspend_stuck_loop_sessions() assert suspended == 1 assert mock_entry.suspended is True + assert mock_entry.resume_pending is False def test_no_suspend_below_threshold(self, runner_with_home): runner, home = runner_with_home From 75c1d438e5b62632abeed480535fbf6f50d75669 Mon Sep 17 00:00:00 2001 From: Brenner Spear Date: Sat, 18 Apr 2026 01:23:37 -0700 Subject: [PATCH 3/4] fix(gateway): handle auto-resume edge cases --- gateway/run.py | 9 +- gateway/session.py | 36 +++++- .../gateway/test_auto_resume_review_fixes.py | 113 ++++++++++++++++++ tests/gateway/test_clean_shutdown_marker.py | 1 - 4 files changed, 149 insertions(+), 10 deletions(-) create mode 100644 tests/gateway/test_auto_resume_review_fixes.py diff --git a/gateway/run.py b/gateway/run.py index 4fd81bf8a46e3..1fb38c98c8129 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -538,14 +538,16 @@ def _prepend_restart_recovery_note( agent_history: list[dict], *, resume_pending: bool, + resume_reason: str | None = None, ) -> str: """Prepend the appropriate interrupted-turn recovery note.""" has_tool_tail = bool(agent_history and agent_history[-1].get("role") == "tool") if resume_pending: + interruption = "a gateway shutdown" if resume_reason == "shutdown_timeout" else "a gateway restart" if has_tool_tail: note = ( "[System note: Your previous turn in this same session was interrupted by " - "a gateway restart. Continue from the existing transcript. There are " + f"{interruption}. Continue from the existing transcript. There are " "unfinished tool results in the conversation history, so process those " "results first, summarize what was accomplished, then answer the user's " "new message below.]" @@ -553,7 +555,7 @@ def _prepend_restart_recovery_note( else: note = ( "[System note: Your previous turn in this same session was interrupted by " - "a gateway restart. Continue from the existing transcript and preserve " + f"{interruption}. Continue from the existing transcript and preserve " "session continuity when answering the user's new message below.]" ) return note + "\n\n" + message @@ -2413,7 +2415,7 @@ async def _stop_impl() -> None: timeout = self._restart_drain_timeout active_agents, timed_out = await self._drain_active_agents(timeout) if timed_out: - timed_out_session_keys = set(self._running_agents.keys()) + timed_out_session_keys = set(active_agents.keys()) logger.warning( "Gateway drain timed out after %.1fs with %d active agent(s); interrupting remaining work.", timeout, @@ -9336,6 +9338,7 @@ def _approval_notify_sync(approval_data: dict) -> None: message, agent_history, resume_pending=bool(getattr(session_entry, "resume_pending", False)), + resume_reason=getattr(session_entry, "resume_reason", None), ) _approval_session_key = session_key or "" diff --git a/gateway/session.py b/gateway/session.py index fe526310dc6c6..ad3cc65cfe4e2 100644 --- a/gateway/session.py +++ b/gateway/session.py @@ -27,6 +27,10 @@ def _now() -> datetime: return datetime.now() +_RESUME_RECOVERY_WINDOW = timedelta(minutes=5) +_RESUME_ATTEMPT_SUSPEND_THRESHOLD = 3 + + # --------------------------------------------------------------------------- # PII redaction helpers # --------------------------------------------------------------------------- @@ -685,6 +689,14 @@ def _should_reset(self, entry: SessionEntry, source: SessionSource) -> Optional[ return "daily" return None + + def _resume_pending_is_active( + self, entry: SessionEntry, now: datetime + ) -> bool: + """Return True while a restart-recovery handoff is still fresh.""" + if not entry.last_resume_marked_at: + return False + return (now - entry.last_resume_marked_at) <= _RESUME_RECOVERY_WINDOW def has_any_sessions(self) -> bool: """Check if any sessions have ever been created (across all platforms). @@ -738,9 +750,14 @@ def get_or_create_session( if entry.suspended: reset_reason = "suspended" elif entry.resume_pending: - entry.updated_at = now - self._save() - return entry + if self._resume_pending_is_active(entry, now): + entry.updated_at = now + self._save() + return entry + entry.resume_pending = False + entry.resume_reason = None + entry.last_resume_marked_at = None + reset_reason = self._should_reset(entry, source) else: reset_reason = self._should_reset(entry, source) if not reset_reason: @@ -845,11 +862,18 @@ def mark_resume_pending( entry = self._entries.get(session_key) if not entry: return False - entry.resume_pending = True - entry.resume_reason = reason - entry.last_resume_marked_at = _now() + marked_at = _now() if increment_attempts: entry.resume_attempts += 1 + if entry.resume_attempts >= _RESUME_ATTEMPT_SUSPEND_THRESHOLD: + entry.suspended = True + entry.resume_pending = False + entry.resume_reason = None + entry.last_resume_marked_at = None + else: + entry.resume_pending = True + entry.resume_reason = reason + entry.last_resume_marked_at = marked_at self._save() return True diff --git a/tests/gateway/test_auto_resume_review_fixes.py b/tests/gateway/test_auto_resume_review_fixes.py new file mode 100644 index 0000000000000..223f5ff977a94 --- /dev/null +++ b/tests/gateway/test_auto_resume_review_fixes.py @@ -0,0 +1,113 @@ +from unittest.mock import AsyncMock, MagicMock, patch + +import gateway.run as gateway_run +from gateway.config import GatewayConfig +from tests.gateway.test_clean_shutdown_marker import _make_source, _make_store + + +class TestShutdownTimeoutSnapshot: + def test_timeout_marks_returned_timed_out_snapshot_not_mutated_running_agents(self, tmp_path, monkeypatch): + monkeypatch.setattr("gateway.run._hermes_home", tmp_path) + + store = _make_store(tmp_path) + timed_out_source = _make_source(chat_id="timed-out") + timed_out_entry = store.get_or_create_session(timed_out_source) + other_source = _make_source(chat_id="other") + other_entry = store.get_or_create_session(other_source) + + from gateway.run import GatewayRunner + + runner = object.__new__(GatewayRunner) + runner._restart_requested = True + runner._restart_detached = False + runner._restart_via_service = False + runner._restart_task_started = False + runner._running = True + runner._draining = False + runner._stop_task = None + runner._running_agents = {other_entry.session_key: MagicMock()} + runner._running_agents_ts = {} + runner._pending_messages = {} + runner._pending_approvals = {} + runner._background_tasks = set() + runner._shutdown_event = MagicMock() + runner._restart_drain_timeout = 5 + runner._exit_code = None + runner._exit_reason = None + runner.adapters = {} + runner.config = GatewayConfig() + runner.session_store = store + + timed_out_snapshot = {timed_out_entry.session_key: MagicMock()} + + with patch("gateway.run.GatewayRunner._drain_active_agents", new_callable=AsyncMock, return_value=(timed_out_snapshot, True)), \ + patch("gateway.run.GatewayRunner._notify_active_sessions_of_shutdown", new_callable=AsyncMock), \ + patch("gateway.run.GatewayRunner._finalize_shutdown_agents"), \ + patch("gateway.run.GatewayRunner._interrupt_running_agents"), \ + patch("gateway.run.GatewayRunner._update_runtime_status"), \ + patch("gateway.status.remove_pid_file"), \ + patch("tools.process_registry.process_registry") as mock_proc_reg, \ + patch("tools.terminal_tool.cleanup_all_environments"), \ + patch("tools.browser_tool.cleanup_all_browsers"): + mock_proc_reg.kill_all = MagicMock() + + import asyncio + asyncio.get_event_loop().run_until_complete(runner.stop(restart=True)) + + timed_out_refreshed = store.get_or_create_session(timed_out_source) + other_refreshed = store.get_or_create_session(other_source) + assert timed_out_refreshed.resume_pending is True + assert timed_out_refreshed.resume_reason == "restart_timeout" + assert other_refreshed.resume_pending is False + + +class TestShutdownTimeoutCopy: + def test_shutdown_timeout_note_mentions_shutdown_not_restart(self): + result = gateway_run._prepend_restart_recovery_note( + "continue", + [], + resume_pending=True, + resume_reason="shutdown_timeout", + ) + + assert "gateway shutdown" in result + assert "gateway restart" not in result + +class TestResumePendingRecoveryWindow: + def test_expired_resume_pending_falls_back_to_normal_reset_policy(self, tmp_path, monkeypatch): + from datetime import datetime, timedelta + + import gateway.session as gateway_session + from gateway.config import SessionResetPolicy + + base_time = datetime(2026, 4, 17, 12, 0, 0) + monkeypatch.setattr(gateway_session, "_now", lambda: base_time) + + policy = SessionResetPolicy(mode="idle", idle_minutes=1) + store = _make_store(tmp_path, policy=policy) + source = _make_source(chat_id="resume-window") + entry = store.get_or_create_session(source) + store.mark_resume_pending(entry.session_key, reason="restart_timeout") + + monkeypatch.setattr(gateway_session, "_now", lambda: base_time + timedelta(minutes=10)) + resumed = store.get_or_create_session(source) + + assert resumed.session_id != entry.session_id + assert resumed.was_auto_reset is True + assert resumed.auto_reset_reason == "idle" + + +class TestResumePendingEscalation: + def test_repeated_resume_marking_escalates_to_suspended_session(self, tmp_path): + store = _make_store(tmp_path) + source = _make_source(chat_id="escalate") + entry = store.get_or_create_session(source) + + assert store.mark_resume_pending(entry.session_key, reason="restart_timeout") is True + assert store.mark_resume_pending(entry.session_key, reason="restart_timeout") is True + assert store.mark_resume_pending(entry.session_key, reason="restart_timeout") is True + + refreshed = store.get_or_create_session(source) + assert refreshed.session_id != entry.session_id + assert refreshed.was_auto_reset is True + assert refreshed.auto_reset_reason == "suspended" diff --git a/tests/gateway/test_clean_shutdown_marker.py b/tests/gateway/test_clean_shutdown_marker.py index c101da3c218a6..3ed92ca4c891d 100644 --- a/tests/gateway/test_clean_shutdown_marker.py +++ b/tests/gateway/test_clean_shutdown_marker.py @@ -261,7 +261,6 @@ def test_timed_out_restart_marks_resume_pending_without_clean_marker(self, tmp_p active_agents = { entry.session_key: MagicMock(), - completed_entry.session_key: MagicMock(), } with patch("gateway.run.GatewayRunner._drain_active_agents", new_callable=AsyncMock, return_value=(active_agents, True)), \ From 4861e0429f7c1f643bd5d7aa1919c73d2e047f39 Mon Sep 17 00:00:00 2001 From: Brenner Spear Date: Sat, 18 Apr 2026 11:17:40 -0700 Subject: [PATCH 4/4] fix(gateway): reuse stuck-loop recovery path --- .../auto-resume-after-restart-pr-spec.md | 84 ++++++++----------- gateway/run.py | 1 - gateway/session.py | 24 +----- .../gateway/test_auto_resume_review_fixes.py | 9 +- tests/gateway/test_session.py | 2 +- 5 files changed, 45 insertions(+), 75 deletions(-) diff --git a/docs/specs/auto-resume-after-restart-pr-spec.md b/docs/specs/auto-resume-after-restart-pr-spec.md index 7b63e15d25a2e..2edf821bb3ee1 100644 --- a/docs/specs/auto-resume-after-restart-pr-spec.md +++ b/docs/specs/auto-resume-after-restart-pr-spec.md @@ -15,7 +15,7 @@ Today, when gateway shutdown cannot drain active work within `agent.restart_drai That is the exact wrong behavior for the common case of **same thread, same user, same restart, still wants same task**. -**Recommendation:** introduce a distinct persisted state like `resume_pending` / `interrupted_by_restart` and keep the existing `session_id` on the next message in the same thread. Reuse the existing transcript reload and auto-continue logic in `gateway/run.py` instead of creating a new session. Only escalate to `suspended` / clean-slate behavior after repeated failed restart-resume attempts or explicit stuck-loop detection. +**Recommendation:** introduce a distinct persisted state like `resume_pending` / `interrupted_by_restart` and keep the existing `session_id` on the next message with the same `session_key`. Reuse the existing transcript reload and auto-continue logic in `gateway/run.py` instead of creating a new session. Escalation should reuse the existing `.restart_failure_counts` / stuck-loop detection path rather than adding a parallel counter on `SessionEntry`. --- @@ -28,7 +28,7 @@ Current behavior is incoherent: 1. Hermes sends an optimistic restart notice. 2. Gateway restart times out draining active agents. 3. Startup suspends recently-active sessions. -4. The user's next message in the same thread lands in a fresh session. +4. The user's next message on the same `session_key` lands in a fresh session. 5. Hermes tells the user to browse `/resume` manually. This is a terrible experience because: @@ -64,7 +64,7 @@ Relevant current behavior: ## Product goal -When a user restarts Hermes and then sends the next message in the **same chat/thread/topic**, Hermes should, by default: +When a user restarts Hermes and then sends the next message that resolves to the **same `session_key`** (same chat/thread/topic lane), Hermes should, by default: 1. preserve the same conversation lane, 2. preserve the same `session_id`, @@ -79,8 +79,8 @@ For the normal case: - user starts a long task in thread X - gateway restarts -- user returns to thread X and says anything -- Hermes continues from the interrupted session in thread X +- user returns to the same lane and says anything +- Hermes continues from the interrupted session on that same `session_key` For the pathological case: @@ -127,7 +127,6 @@ Recommended `SessionEntry` fields in `gateway/session.py`: ```python resume_pending: bool = False resume_reason: Optional[str] = None # e.g. "restart_timeout", "crash_recovery" -resume_attempts: int = 0 last_resume_marked_at: Optional[datetime] = None ``` @@ -165,7 +164,7 @@ restart timed out restart timed out -> mark active session(s) as resume_pending=True -> next startup preserves mapping - -> next message in same thread returns existing session entry + -> next message on the same `session_key` returns existing session entry -> transcript reloads from same session_id -> model gets interruption note -> Hermes continues automatically @@ -175,8 +174,8 @@ restart timed out ```text restart timed out repeatedly for same session - -> increment resume_attempts / stuck-loop counter - -> once threshold exceeded, convert to suspended=True + -> increment existing .restart_failure_counts counter + -> _suspend_stuck_loop_sessions() suspends once threshold is exceeded -> only then force fresh-session fallback ``` @@ -213,7 +212,6 @@ def mark_resume_pending( session_key: str, *, reason: str = "restart_timeout", - increment_attempts: bool = True, ) -> bool: ... ``` @@ -222,7 +220,7 @@ Responsibilities: - set `resume_pending=True` - set `resume_reason` -- bump `resume_attempts` if requested +- set `last_resume_marked_at` - persist metadata in `sessions.json` --- @@ -238,7 +236,7 @@ Responsibilities: Extend `get_or_create_session()` logic: - if `entry.suspended` → current reset behavior stays -- if `entry.resume_pending` → **return the existing entry** and clear or downgrade the resume marker once the resume turn begins successfully +- if `entry.resume_pending` → **return the existing entry** while the recovery window is still fresh, and only clear the marker after a successful turn completes Pseudo-shape: @@ -287,30 +285,28 @@ Preserving the same session ID plus transcript reload plus better interruption n --- -## 4) Keep stuck-loop protection, but move it to an escalation policy +## 4) Keep stuck-loop protection, but reuse the existing restart-failure mechanism We should not regress the original safety intent behind the stuck-loop work. ### Proposed rule - first interrupted restart for a session → auto-resume -- second interrupted restart for same session within recovery window → still auto-resume, but warn internally / increment counter -- third interrupted restart (or configurable threshold) → convert session to `suspended=True` +- second interrupted restart for the same `session_key` → still auto-resume +- third interrupted restart for the same `session_key` → let the existing stuck-loop path suspend it This keeps safety without making the default path destructive. -### Practical implementation options +### Recommended implementation -Option A: reuse existing stuck-loop tracking files/logic in `GatewayRunner` -- keep the existing consecutive restart accounting -- when threshold is exceeded, switch `resume_pending` -> `suspended` +Reuse the existing gateway-level `.restart_failure_counts` file and `_suspend_stuck_loop_sessions()` flow: -Option B: track directly in `SessionEntry` -- increment `resume_attempts` -- clear it after a successful resumed turn -- if `resume_attempts >= threshold`, set `suspended=True` +- shutdown-time drain timeout still calls `mark_resume_pending(...)` for the interrupted `session_key`s +- successful turn completion clears the restart-failure count for that `session_key` +- repeated interrupted restarts are counted in `.restart_failure_counts` +- `_suspend_stuck_loop_sessions()` flips the session to `suspended=True` once the existing threshold is exceeded -**Recommendation:** use `SessionEntry` fields for session-local semantics and let existing gateway-level stuck-loop tracking continue to exist if needed. That makes the persisted reason visible and easier to test. +Do **not** add or maintain a parallel `resume_attempts` counter on `SessionEntry`. --- @@ -328,8 +324,9 @@ Reserve it for narrower cases, such as: - startup crash recovery when explicit `resume_pending` metadata is absent, - legacy upgrade path / backward compatibility, -- emergency fallback for clearly unsafe sessions, -- repeated failed recovery loops. +- emergency fallback for clearly unsafe sessions. + +Normal interrupted-restart recovery with explicit `resume_pending` metadata should not be suspended by this helper. ### Important outcome @@ -411,13 +408,11 @@ Add persisted session fields and APIs: - new `SessionEntry` fields: - `resume_pending` - `resume_reason` - - `resume_attempts` - `last_resume_marked_at` - serialization/deserialization support in `to_dict()` / `from_dict()` - helper methods: - `mark_resume_pending(...)` - `clear_resume_pending(...)` - - maybe `escalate_to_suspended(...)` - update `get_or_create_session()` so `resume_pending` returns existing session instead of resetting ### `gateway/run.py` @@ -426,7 +421,7 @@ Update gateway behavior: - after drain timeout, mark active sessions `resume_pending=True` - on resumed turn, inject restart-interruption system note when `session_entry.resume_pending` -- clear `resume_pending` after a successful resumed turn begins or completes +- clear `resume_pending` only after a successful resumed turn completes - update shutdown banner wording to promise attempted recovery, not guaranteed recovery - stop routing normal interrupted restart recovery through immediate clean-slate semantics @@ -437,7 +432,7 @@ Add or update tests for: - same-session resume after interrupted restart - transcript preserved across restart timeout - tool-result auto-continue still works on resumed session -- repeated recovery failure escalates to suspended/new session +- repeated recovery failure escalates through `.restart_failure_counts` / `_suspend_stuck_loop_sessions()` - shutdown banner wording is no longer misleading - `/resume` guidance only appears when clean-slate fallback actually occurs @@ -475,9 +470,9 @@ Suggested cases: Suggested cases: -1. **interrupted restart in same thread resumes existing session** +1. **interrupted restart on same session key resumes existing session** - transcript exists under original session id - - next message in same thread loads same transcript + - next message on the same `session_key` loads the same transcript - no auto-reset notice 2. **tool-tail transcript triggers auto-continue note on resumed session** @@ -518,7 +513,7 @@ Do **not** silently reinterpret existing `suspended=True` as resumable. That wou ### 1. Resume loop risk If resume is attempted too aggressively, a truly poisoned session could keep re-entering the same bad state. -**Mitigation:** keep thresholded escalation to `suspended`. +**Mitigation:** keep thresholded escalation in the existing `.restart_failure_counts` / `_suspend_stuck_loop_sessions()` flow. ### 2. Partial transcript ambiguity If a turn was interrupted mid-assistant generation, the last messages may not be perfectly shaped. @@ -534,17 +529,10 @@ If message copy changes before semantics change, UX could still be misleading. ## Open questions -1. Should `resume_pending` clear at turn start or only after a successful completed turn? - - **Recommendation:** clear after successful completion, but protect against duplicate recovery attempts with an in-memory guard during the running turn. - -2. Should recovery be attempted only in the same thread/topic, or also same parent chat? - - **Recommendation:** same session key only. Do not cross lanes. - -3. Should startup still run `suspend_recently_active()` at all when explicit `resume_pending` markers were written during shutdown? - - **Recommendation:** no, not for those specific session keys. - -4. Should the user get an explicit "resuming interrupted work" notice? - - **Recommendation:** probably no extra chat spam in v1. Keep it as an internal system note unless debugging is enabled. +1. `resume_pending` should clear only after a successful completed turn, not at turn start. +2. Recovery should only be attempted on the same `session_key`. Do not cross lanes. +3. `suspend_recently_active()` should remain only as a narrower crash-recovery fallback and should not suspend explicit `resume_pending` sessions. +4. User-facing recovery should stay as an internal system note in v1 unless debugging is enabled. --- @@ -555,8 +543,8 @@ If message copy changes before semantics change, UX could still be misleading. 3. Change `get_or_create_session()` to preserve same session for `resume_pending` 4. Mark active sessions resume-pending on drain-timeout shutdown 5. Inject restart-resume system note in `gateway/run.py` -6. Clear pending state after successful resume -7. Add escalation threshold behavior +6. Clear pending state after successful completion +7. Reuse existing `.restart_failure_counts` / `_suspend_stuck_loop_sessions()` escalation 8. Update shutdown/fallback copy 9. Add regression tests @@ -566,7 +554,7 @@ If message copy changes before semantics change, UX could still be misleading. This PR is successful if all of the following are true: -1. A long-running task interrupted by gateway restart in a Discord/Telegram thread resumes automatically on the next message in the same thread. +1. A long-running task interrupted by gateway restart in a Discord/Telegram lane resumes automatically on the next message with the same `session_key`. 2. The resumed thread keeps the same `session_id` and transcript history. 3. Hermes no longer tells the user to `/resume` for the normal restart-recovery case. 4. Existing clean restart behavior is preserved. @@ -583,7 +571,7 @@ Right now the system is optimized for protecting itself from stuck loops at the The correct product stance is: -- **same thread + same user + immediate post-restart message = continue automatically** +- **same session_key + immediate post-restart message = continue automatically** - **repeated failed recovery = fresh session as safety fallback** That gets the common case right without giving up the escape hatch. diff --git a/gateway/run.py b/gateway/run.py index 1fb38c98c8129..b12a6c54b8412 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -4152,7 +4152,6 @@ async def _handle_message_with_agent(self, event, source, _quick_key: str): self.session_store.clear_resume_pending(session_key) session_entry.resume_pending = False session_entry.resume_reason = None - session_entry.resume_attempts = 0 session_entry.last_resume_marked_at = None except Exception as e: logger.debug("Failed to clear resume-pending state for %s: %s", session_key[:30], e) diff --git a/gateway/session.py b/gateway/session.py index ad3cc65cfe4e2..cb9293f926dc8 100644 --- a/gateway/session.py +++ b/gateway/session.py @@ -28,7 +28,6 @@ def _now() -> datetime: _RESUME_RECOVERY_WINDOW = timedelta(minutes=5) -_RESUME_ATTEMPT_SUSPEND_THRESHOLD = 3 # --------------------------------------------------------------------------- @@ -387,7 +386,6 @@ class SessionEntry: # reload and continuation can resume in place. resume_pending: bool = False resume_reason: Optional[str] = None - resume_attempts: int = 0 last_resume_marked_at: Optional[datetime] = None def to_dict(self) -> Dict[str, Any]: @@ -411,7 +409,6 @@ def to_dict(self) -> Dict[str, Any]: "suspended": self.suspended, "resume_pending": self.resume_pending, "resume_reason": self.resume_reason, - "resume_attempts": self.resume_attempts, "last_resume_marked_at": ( self.last_resume_marked_at.isoformat() if self.last_resume_marked_at @@ -456,7 +453,6 @@ def from_dict(cls, data: Dict[str, Any]) -> "SessionEntry": suspended=data.get("suspended", False), resume_pending=data.get("resume_pending", False), resume_reason=data.get("resume_reason"), - resume_attempts=data.get("resume_attempts", 0), last_resume_marked_at=( datetime.fromisoformat(data["last_resume_marked_at"]) if data.get("last_resume_marked_at") @@ -854,7 +850,6 @@ def mark_resume_pending( session_key: str, *, reason: str = "restart_timeout", - increment_attempts: bool = True, ) -> bool: """Mark a session as resumable after restart interruption.""" with self._lock: @@ -862,26 +857,15 @@ def mark_resume_pending( entry = self._entries.get(session_key) if not entry: return False - marked_at = _now() - if increment_attempts: - entry.resume_attempts += 1 - if entry.resume_attempts >= _RESUME_ATTEMPT_SUSPEND_THRESHOLD: - entry.suspended = True - entry.resume_pending = False - entry.resume_reason = None - entry.last_resume_marked_at = None - else: - entry.resume_pending = True - entry.resume_reason = reason - entry.last_resume_marked_at = marked_at + entry.resume_pending = True + entry.resume_reason = reason + entry.last_resume_marked_at = _now() self._save() return True def clear_resume_pending( self, session_key: str, - *, - reset_attempts: bool = True, ) -> bool: """Clear resumable restart state after recovery succeeds.""" with self._lock: @@ -892,8 +876,6 @@ def clear_resume_pending( entry.resume_pending = False entry.resume_reason = None entry.last_resume_marked_at = None - if reset_attempts: - entry.resume_attempts = 0 self._save() return True diff --git a/tests/gateway/test_auto_resume_review_fixes.py b/tests/gateway/test_auto_resume_review_fixes.py index 223f5ff977a94..27cfdf82c32f2 100644 --- a/tests/gateway/test_auto_resume_review_fixes.py +++ b/tests/gateway/test_auto_resume_review_fixes.py @@ -98,7 +98,7 @@ def test_expired_resume_pending_falls_back_to_normal_reset_policy(self, tmp_path class TestResumePendingEscalation: - def test_repeated_resume_marking_escalates_to_suspended_session(self, tmp_path): + def test_repeated_resume_marking_does_not_suspend_without_stuck_loop_counter(self, tmp_path): store = _make_store(tmp_path) source = _make_source(chat_id="escalate") entry = store.get_or_create_session(source) @@ -108,6 +108,7 @@ def test_repeated_resume_marking_escalates_to_suspended_session(self, tmp_path): assert store.mark_resume_pending(entry.session_key, reason="restart_timeout") is True refreshed = store.get_or_create_session(source) - assert refreshed.session_id != entry.session_id - assert refreshed.was_auto_reset is True - assert refreshed.auto_reset_reason == "suspended" + assert refreshed.session_id == entry.session_id + assert refreshed.resume_pending is True + assert refreshed.suspended is False + assert not hasattr(refreshed, "resume_attempts") diff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.py index 79d559a1f1583..a31bf91addec1 100644 --- a/tests/gateway/test_session.py +++ b/tests/gateway/test_session.py @@ -632,7 +632,7 @@ def test_mark_resume_pending_persists_across_reload(self, store): assert resumed.session_id == entry.session_id assert resumed.resume_pending is True assert resumed.resume_reason == "restart_timeout" - assert resumed.resume_attempts == 1 + assert not hasattr(resumed, "resume_attempts") def test_resume_pending_reuses_same_session_id(self, store): source = SessionSource(