Repository navigation
fix: resume main sessions after gateway restarts - #121969
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: found issues before merge. Reviewed August 11, 2026, 5:53 AM ET / 09:53 UTC. ClawSweeper reviewWhat this changesThis PR resumes interrupted main sessions through the normal agent pipeline after Gateway restart and renders internal continuation prompts as System notices in Control UI. Regression provenancePossible regression — probable (reviewed change; reproduction). No predecessor PR is attributed. Merge readiness⛔ Blocked by patch quality or review findings - 7 items remain Keep open. The prior P1 remains: an interrupted reply hook can be invoked again after restart before restart-safe tool filtering applies. The Control UI update also leaves live recovery stream/tool placement attached to the prior turn under clock skew. Priority: P1 Review scores
Verification
How this fits togetherGateway restart recovery reads persisted session state, decides whether to resume or tombstone a turn, then dispatches an internal continuation through the agent pipeline. Control UI projects that persisted continuation and its live output into chat rows. flowchart LR
A[Gateway restart] --> B[Persisted main session]
B --> C[Recovery policy]
C -->|resume| D[Agent pipeline]
C -->|tombstone| E[Terminal notice]
D --> F[Transcript and live output]
F --> G[Control UI chat rows]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource -236, Tests -442, Docs -5. Total -683 across 35 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Mantis proof suggestionA redacted web chat proof would directly show that restart recovery is displayed as a System row and that subsequent continuation output is associated with it. A maintainer can ask Mantis to capture proof by posting this exact PR comment: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Retain terminal settlement for ambiguous pending hooks until durable per-hook idempotency exists, and preserve recovery-run identity when using System notices as live insertion boundaries. Do we have a high-confidence way to reproduce the issue? Yes. A persisted Is this the best way to solve the issue? No. Restart-safe model tools do not make a previously started plugin callback idempotent, and the UI boundary must also participate in live insertion bounds. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 4b08d9aa75c1. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
6d87ab8 to
c79cb97
Compare
|
Response to the ClawSweeper review (findings addressed at head P2 — turn boundaries in every chat projection: fixed. One canonical predicate ( P1 — ambiguous
Recovery turns now run currently loaded hooks under normal trigger rules. Stored data model: no persisted-shape change. The flagged serialized state is test fixtures; retired hook-state literals ( Rebase note: the branch was rebased over #121833 preserving its complete-with-durable-debt behavior for ambiguous claimed final sends; resume-first applies only to the remaining genuinely-unfinished states. |
|
CI note for the ui-e2e lane failures on this PR (evidence that they are unrelated to this change):
A follow-up task to stabilize the lane has been filed with the same evidence. Re-firing CI for a green exact-head run. |
|
Merged via squash.
|
* fix(agents): always resume main sessions after restart * fix(ui): render internal messages as system rows * docs: update gateway restart recovery semantics * refactor(sessions): simplify restart hook checkpoints * refactor(agents): consolidate restart recovery claims * test(agents): update delivery recovery revision guard * fix(plugin-sdk): preserve restart hook state contract * fix(ui): localize system row label * test(agents): remove obsolete recovery import * test(agents): align abort-code propagation with always-resume recovery * fix(ui): share notice-aware turn boundaries * test(agents): reconcile restart recovery ownership * fix(ci): reconcile rebased recovery and UI checks
…session runs) Upstream PR openclaw#75662 (head 990fca0) was amittell-authored, closed unmerged; never in main. Symptom verified live at branch HEAD: a main session ended via sessions_yield persists status "running" (no explicit paused projection, no pauseReason), so dashboards, restart recovery, and follow-up turns cannot distinguish a queued continuation from an active model turn and race it. Re-derived for the beta.2 layout (key adaptations vs the old upstream main): - SessionRunStatus now derives from the gateway-protocol TypeBox SessionRowSchema (sessions-row.ts): added Type.Literal("paused") to status + optional pauseReason ("sessions_yield"); the derived type cascades to SessionEntry.status, sessions-helpers, session-utils.types, and the UI re-export — no per-file union edits needed - protocol artifacts regenerated (pnpm protocol:gen[:swift|:kotlin]): GatewayModels.swift gains the pausereason field exactly as upstream - src/gateway/session-lifecycle-state.ts: yieldedWaiting terminal events now project status "paused" + pauseReason "sessions_yield" (error/aborted ends still resolve terminally; the marker is gated on the derived status so it cannot leak into failed rows); start events clear pauseReason - broadcast/row plumbing: server-chat.ts snapshotSource.pauseReason, session-event-payload.ts pauseReason field, session-utils-row.ts buildGatewaySessionRow entry.pauseReason, session-utils.types.ts row type - src/config/sessions/types.ts: SessionEntry.pauseReason + isTerminalSessionStatus now excludes "paused" (nonterminal) - src/config/sessions/lifecycle.ts: resolveTerminalMainSessionTranscriptRegistryCheck skips paused main sessions (even with a positive endedAt) so transcript freshness/rotation cannot run while the continuation is pending - src/agents/main-session-recovery/main-session-recovery-state.ts: isMainRestartRecoveryCandidate rejects pauseReason "sessions_yield" so restart recovery does not force a "[System] previous turn interrupted" resume that races the queued continuation - sessions-list-tool readSessionRunStatus accepts "paused" - session-entry-slot-keys.ts reserves pauseReason - UI: isSessionRunActive treats paused as active (nonterminal); session-run-state/reconcile status parsing; workboard lifecycle + card-actions route through isSessionRunActive; sessions view badge shows the explicit Paused label (idle tone, not live); lobster pet outcome skips paused rows; en.ts statusPaused + pnpm ui:i18n:sync catalog artifacts (statusPaused already in translation memory) - Superseded upstream pieces NOT re-derived: main-session-restart-recovery.ts markRestartAbortedMainSessionsFromLocks second test (function retired by the openclaw#121969 re-architecture; isMainRestartRecoveryCandidate now gates the marking path), ui i18n meta fallbackKeys/totalKeys edits (beta.2 uses generated catalog baseline files instead), CHANGELOG.md (frozen convention) Tests: session-lifecycle-state.test.ts (yielded -> paused + no pauseReason leak on terminals + start clears marker), main-session-restart-recovery.test.ts (+skip for sessions_yield-paused entries; cleaned-locks variant superseded), lifecycle.test.ts (+paused transcript-registry-check skips), session-run-state/reconcile/workboard UI tests (+paused cases). Verification: 632/632 main-session-recovery suite; 121 lifecycle-state+ lifecycle; 210 UI session-run-state/reconcile/workboard; 487 server-methods/sessions-list/sessions; 922 session utils+message events; 122 chat run-lifecycle; i18n check clean. tsgo core: 5 errors, ALL pre-existing at HEAD (auth-profiles log + terminal-resolution, recovered openclaw#57137 stack) — error set byte-identical before/after this change (DIFF=0); this change adds zero new type errors.
What Problem This Solves
Fixes an issue where users with an in-flight main-session turn could lose automatic continuity after a Gateway restart when the transcript, delivery receipt, approval, Code Mode checkpoint, or reply-hook checkpoint was ambiguous. OpenClaw marked the session failed and asked the user to resend the request even though the model still had the transcript and could safely reconcile what remained.
It also fixes the Control UI attributing the internal restart continuation to the signed-in human, including their avatar and name, because the persisted continuation is a user-role transcript row with internal-system provenance.
Why This Change Was Made
The recovery policy now has only
completeandresumeoutcomes. Delivered terminal replies and handled-silent hooks still complete without dispatch. Every former ordinary fail shape resumes; ambiguous side-effect states useforceRestartSafeTools, while Code Mode controls are enabled only for an exact replay-safe checkpoint. The continuation prompt and pending-text note remain byte-identical.The normal reply-hook pre-resume gate was removed. Restart recovery dispatches an ordinary Gateway agent turn: embedded and CLI runtimes classify it as a user trigger, so currently loaded
before_agent_replyhooks run, along with normal agent-run, transcript-write, and outbound-delivery hooks. Ingress-onlybefore_dispatchandreply_dispatchhooks are not re-run on the internal continuation. The deleted direct resend notice bypassed the agent pipeline entirely, so it was a worse hook boundary.The one hard security boundary remains: a
message_tool_onlyrecovery without a durable channel-ingress authority claim is tombstoned through the existing terminal flow. Exact pending delivery-queue owners also remain authoritative and defer a second dispatch. The terminal notice accurately directs the user to/newor/reset, which is required for tombstoned sessions.Removed paths and state-machine surface:
action: "fail"fromMainSessionResumePolicyfail_recovery,failUnresumableMainSession, andUNRESUMABLE_SESSION_NOTICEmain-session-restart-recovery-notice.tsadmitted,continue, andhandled-unrecoverablehook phases; their published type literals remain read-compatible because they are transitively exposed by the Plugin SDK Agent Harness contractThe bounded legacy abort-text window remains because
v2026.7.2-beta.5shipped restart recovery before coded abort tails; a direct upgrade can still surface that transcript.Accepted tradeoffs:
Production LOC: +200/-436 (net -236). Tests: +462/-961 (net -499). Docs: +36/-41 (net -5).
AI-assisted implementation; all changes were reviewed with the repository autoreview workflow.
User Impact
Main sessions now continue automatically after a Gateway restart instead of demanding a manual resend for transcript ambiguity. If previous delivery or tool side effects are uncertain, the agent can inspect the transcript and explain where things stand without receiving unsafe mutation tools.
In the Control UI, visible
provenance.kind === "internal_system"user-role rows render as subdued System notices with no operator avatar or name. Existing message visibility, ordering, timestamps, search filtering, and user-turn grouping remain intact. Other hidden internal-system sources remain hidden.Control UI before and after
Evidence
Pre-fix regressions failed for 14 former terminal policy shapes and for the Control UI internal-system projection. They pass after the owner-boundary repair.
Focused and full proof:
node scripts/run-vitest.mjs src/agents/main-session-recovery/— 12 files, 619 tests passednode scripts/run-vitest.mjs ui/src/pages/chat/chat-thread.test.ts ui/src/pages/chat/components/chat-message.test.ts— 2 files, 353 tests passednode scripts/run-vitest.mjs src/auto-reply/reply/agent-runner.runreplyagent.e2e.test.ts— 1 file, 141 tests passednode scripts/check-changed.mjs— passed all selected core, core-test, UI, and docs lanes after remote routing was unavailable and the wrapper fell back to local executionMock-Gateway QA Lab verdict from the exact PR head:
{ "scenario": "gateway-restart-inflight-run", "status": "pass", "step": { "name": "completes one in-flight run across restart", "status": "pass", "details": "session=agent:qa:main plannedTool=wait persistedTail=assistant/toolUse/wait recoveredTail=assistant/stop/text recoveredMarkers=1 resendNotices=0 restartSafePolicy=true recoveryPromptHeartbeat=false\nRESTART-CODE-MODE-WAIT-OK" }, "counts": { "total": 1, "passed": 1, "failed": 0, "skipped": 0 }, "providerMode": "mock-openai", "model": "mock-openai/gpt-5.6-luna" }Command: