Skip to content

Commit bcaec0c

Browse files
authored
fix: resume main sessions after gateway restarts (#121969)
* 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
1 parent 63bba28 commit bcaec0c

35 files changed

Lines changed: 826 additions & 1509 deletions

‎docs/gateway/restart-recovery.md‎

Lines changed: 33 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ Restarting the gateway does not lose agent state. Conversations, transcripts,
1111
scheduled jobs, background task records, and queued outbound messages all live
1212
on disk, and work that was interrupted mid-turn is detected and resumed
1313
automatically after the gateway comes back up. Recovery is always on and
14-
normally needs no manual intervention. Repeatedly failing recovery is bounded
15-
and may quarantine one session until you inspect or replace it.
14+
normally needs no manual intervention. Exhausted infrastructure retries, or a
15+
missing durable message-action authority claim, may quarantine one session
16+
until you inspect or replace it.
1617

1718
This page describes what survives a restart, how interrupted work is detected,
1819
and what the automatic resume looks like.
@@ -54,19 +55,12 @@ Three complementary mechanisms mark sessions whose turn did not finish:
5455
Commands, attachments, per-turn overrides, pending deliveries, prior abort
5556
hints, plugin-owned sessions, and turns with execution hooks keep their
5657
specialized admission paths.
57-
If a `before_agent_reply` hook is installed, admission also records its phase.
58-
Recovery never replays a hook interrupted mid-call. Once an unhandled hook
59-
finishes, its checkpoint records that result, but recovery still fails closed
60-
while that hook remains active: a checkpoint cannot prove that the same
61-
plugin code and configuration loaded after the restart. A
62-
`before_agent_reply` hook may declare a host-enforced
63-
`eligibleTriggers` scope; a hook limited to scheduled `heartbeat` or `cron`
64-
turns is not active for a recovered user turn and therefore does not block
65-
it. Unscoped or invalid registrations remain active for this safety check.
66-
Handled text and silent results are checkpointed separately for deterministic
67-
settlement.
68-
Durable recovery claims written by older versions have no source-ownership
69-
marker, so they receive the same fail-closed hook check during an upgrade.
58+
If a `before_agent_reply` hook is installed, admission records enough phase
59+
state to distinguish a completed silent result from an ambiguous side-effect
60+
window. Recovery dispatches an ordinary user-triggered agent turn, so the
61+
currently loaded `before_agent_reply` hooks run under their normal trigger
62+
rules. Ambiguous prior hook outcomes resume with restart-safe tools rather
63+
than replaying unrestricted side effects.
7064
- **At shutdown:** during the restart drain, every session with an active run
7165
is stamped with a recovery marker in the session store before the run is
7266
aborted.
@@ -98,17 +92,18 @@ replacement. `openclaw doctor --fix` can repair a stale aborted flag that
9892
conflicts with a tombstone, but it does not re-enable that recovery cycle.
9993

10094
Every retry reuses one durable dispatch identifier, so an ambiguous connection
101-
failure cannot start the same recovery twice. Completed and unresumable Control
102-
UI turns also retain bounded durable idempotency tombstones, allowing a
103-
reconnecting outbox to retire them without re-executing the request.
95+
failure cannot start the same recovery twice. Completed Control UI turns also
96+
retain bounded durable idempotency tombstones, allowing a reconnecting outbox
97+
to retire them without re-executing the request.
10498

10599
Message-tool-only replies use a second durable correlation. Before a terminal
106100
same-conversation send reaches the channel, the gateway records an unresolved
107101
delivery intent on the exact session and source turn. A confirmed provider
108102
success resolves it to a durable delivered receipt; a confirmed failure clears
109103
it. Recovery completes a delivered receipt without rerunning tools. If a crash
110-
leaves the provider outcome unknown, recovery fails closed instead of replaying
111-
an external effect.
104+
leaves the provider outcome unknown, recovery resumes with restart-safe tools
105+
so the model can inspect and report the ambiguity without replaying the
106+
external effect.
112107

113108
The delivered reply is also mirrored into the transcript with its source
114109
message ID. Terminal mirrors use a distinct receipt key, so a progress send with
@@ -118,20 +113,21 @@ durable channel-ingress claims can restore message-action authority. A resumed
118113
run keeps the original source-delivery mode and source correlation, including
119114
requester identity and any same-channel/thread restriction, so the same receipt
120115
remains authoritative even if another restart happens during recovery. A
121-
message-tool-only turn without reconstructable channel authority is failed
122-
closed and receives the one-time resend notice.
123-
124-
Before resuming, the gateway checks that the transcript tail is safe to
125-
continue from. An aborted turn is the interruption itself, so it resumes on a
126-
best-effort basis whatever abort detail the provider or worker recorded with it:
116+
message-tool-only turn without reconstructable channel authority is tombstoned
117+
because OpenClaw cannot safely mint message-action authority without the
118+
original channel-ingress claim. The terminal notice directs the user to start a
119+
replacement with `/new` or `/reset`.
120+
121+
Before resuming, the gateway classifies the transcript tail to choose the tool
122+
restriction for the continuation. An aborted turn is the interruption itself,
123+
so it resumes on a best-effort basis whatever abort detail the provider or worker recorded with it:
127124
partial streamed text stays in the transcript and the continuation picks up from
128125
the message beneath it, while a tool call left dangling is dropped from the next
129126
provider payload and restricted to restart-safe tools unless it is audited
130-
replay-safe. If the tail is genuinely unsafe (for example a provider failure, or
131-
a turn that ended on a stale pending approval), the session is not blindly
132-
re-run; the agent instead posts a short notice asking the user to resend the
133-
last request. For WebChat, that notice is written directly to the session
134-
history so it remains visible after reconnect.
127+
replay-safe. Provider failures, completed assistant tails, empty transcripts,
128+
and stale pending approvals also continue from the existing transcript. States
129+
with ambiguous side effects use restart-safe tools; otherwise the model decides
130+
what completed and what remains and can report any uncertainty to the user.
135131

136132
OpenClaw can also reconstruct interrupted read-only [Code Mode](/tools/code-mode)
137133
work. Code Mode marks these runs as restart-safe and rejects side-effecting
@@ -140,8 +136,9 @@ the `wait` control, the new gateway reconstructs the turn from its transcript
140136
and forces the reconstructed execution to remain restart-safe even if the
141137
model omits or clears that flag. The host filters the entire reconstructed
142138
turn to audited read-only core tools and explicitly replay-safe plugin tools,
143-
including when Code Mode is disabled after the restart. Side-effecting work
144-
remains guarded by the resend notice rather than risking a duplicate write.
139+
including when Code Mode is disabled after the restart. A non-replay-safe or
140+
unmatched Code Mode checkpoint still resumes for model reconciliation, but
141+
without Code Mode controls and with the restart-safe tool restriction.
145142

146143
### Subagents
147144

@@ -234,8 +231,9 @@ channels.start --params '{"channel":"<id>"}'`
234231
- **Logs:** recovery decisions are logged under the
235232
`main-session-restart-recovery` and `subagent-interrupted-resume`
236233
subsystems.
237-
- **Reply hooks:** automatically delivered replies from resumed main-session
238-
turns run the normal `reply_payload_sending` hook before channel delivery,
234+
- **Reply hooks:** resumed turns run currently loaded `before_agent_reply`
235+
hooks under the normal user-trigger rules. Automatically delivered replies
236+
also run the normal `reply_payload_sending` hook before channel delivery,
239237
with the recovered session, run, account, and conversation context.
240238

241239
## What is not resumed
@@ -244,8 +242,6 @@ channels.start --params '{"channel":"<id>"}'`
244242
handles them: subagent sessions (subagent recovery), cron sessions (the
245243
scheduler re-runs on schedule), and ACP-managed sessions (the connected IDE
246244
or client owns the resume).
247-
- Sessions whose transcript tail cannot be safely continued; these get the
248-
resend notice described above instead of a silent re-run.
249245
- Work that was never admitted: messages arriving during the drain window are
250246
rejected with an explicit restart error rather than silently queued into a
251247
dying process.

‎docs/plugins/hooks.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,9 @@ observation side effects.
6767

6868
Trigger eligibility is enforced by the host before it invokes the handler. A
6969
hook registered with `eligibleTriggers: ["heartbeat", "cron"]` is therefore
70-
inactive for user turns and does not block recovery of an interrupted user
71-
turn. Omitted, empty, malformed, or partly unknown lists remain unrestricted
72-
so dispatch and recovery fail closed. Other hook kinds do not accept this
73-
option.
70+
inactive for user turns, including a recovered user turn. Omitted, empty,
71+
malformed, or partly unknown lists remain unrestricted, so the hook runs for
72+
those turns. Other hook kinds do not accept this option.
7473

7574
Operators can set hook budgets without patching plugin code:
7675

‎src/agents/main-session-recovery/main-session-recovery-state.ts‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import type {
77
MainRestartRecoveryState,
88
RestartRecoveryRun,
99
} from "../../config/sessions.js";
10-
import { buildRestartRecoveryClaimCleanupPatch } from "../../config/sessions/restart-recovery-state.js";
1110
import {
1211
isAcpSessionKey,
1312
isCronSessionKey,
@@ -632,28 +631,6 @@ export function transitionMainSessionRecovery(
632631
entry.updatedAt = command.now;
633632
return { kind: "tombstoned" };
634633
}
635-
case "fail_recovery": {
636-
const conflict = matchesObservation(entry, command.observation);
637-
if (conflict) {
638-
return { kind: "rejected", reason: conflict };
639-
}
640-
const noticeEntry = structuredClone(entry);
641-
entry.status = "failed";
642-
entry.lifecycleRunId = undefined;
643-
entry.abortedLastRun = true;
644-
entry.endedAt = command.now;
645-
entry.updatedAt = command.now;
646-
Object.assign(entry, PENDING_FINAL_DELIVERY_CLEAR_PATCH);
647-
Object.assign(
648-
entry,
649-
buildRestartRecoveryClaimCleanupPatch({
650-
entry,
651-
recordTerminalSource: true,
652-
}),
653-
);
654-
entry.mainRestartRecovery = undefined;
655-
return { kind: "failed", noticeEntry };
656-
}
657634
case "doctor_repair": {
658635
if (!entry.mainRestartRecovery?.tombstone || entry.abortedLastRun !== true) {
659636
return { kind: "no_change" };

‎src/agents/main-session-recovery/main-session-recovery-types.ts‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
import type {
2-
InternalSessionEntry as SessionEntry,
3-
MainRestartRecoveryState,
4-
RestartRecoveryRun,
5-
} from "../../config/sessions.js";
1+
import type { MainRestartRecoveryState, RestartRecoveryRun } from "../../config/sessions.js";
62

73
type MainSessionRecoveryExecutionIdentity = NonNullable<
84
MainRestartRecoveryState["executionIdentity"]
@@ -130,11 +126,6 @@ export type MainSessionRecoveryCommand =
130126
observation: MainSessionRecoveryObservation;
131127
reason: string;
132128
}
133-
| {
134-
kind: "fail_recovery";
135-
now: number;
136-
observation: MainSessionRecoveryObservation;
137-
}
138129
| { kind: "doctor_repair"; now: number }
139130
| { kind: "clear" };
140131

@@ -149,7 +140,6 @@ export type MainSessionRecoveryTransitionResult =
149140
| "recovery_validated"
150141
| "tombstoned";
151142
}
152-
| { kind: "failed"; noticeEntry: SessionEntry }
153143
| { kind: "foreground_claimed"; claim: MainSessionRecoveryOwnerClaim }
154144
| { kind: "observed"; view: MainSessionRecoveryView }
155145
| { kind: "rejected"; reason: MainSessionRecoveryConflict }

‎src/agents/main-session-recovery/main-session-restart-claim.ts‎

Lines changed: 0 additions & 49 deletions
This file was deleted.

‎src/agents/main-session-recovery/main-session-restart-dispatch.ts‎

Lines changed: 0 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@ import type { GatewayRecoveryRuntime } from "../../gateway/server-instance-runti
1616
import type { AgentRunRequest } from "../../gateway/server-methods/agent-request-types.js";
1717
import { getAgentEventLifecycleGeneration } from "../../infra/agent-events.js";
1818
import { createSubsystemLogger } from "../../logging/subsystem.js";
19-
import { findRestartRecoveryUnsafeReplyHook } from "../../plugins/restart-recovery-hook-safety.js";
20-
import { withPluginRuntimeRegistryScope } from "../../plugins/runtime/gateway-request-scope.js";
2119
import { CommandLane } from "../../process/lanes.js";
22-
import { resolveAgentIdFromSessionKey } from "../../routing/session-key.js";
2320
import { MAIN_SESSION_RESTART_RECOVERY_SOURCE_TOOL } from "../../sessions/input-provenance.js";
2421
import { resolveSendPolicy } from "../../sessions/send-policy.js";
2522
import {
@@ -28,8 +25,6 @@ import {
2825
type DeliveryContext,
2926
} from "../../utils/delivery-context.shared.js";
3027
import { isDeliverableMessageChannel } from "../../utils/message-channel.js";
31-
import { resolveAgentWorkspaceDir, resolveDefaultAgentId } from "../agent-scope.js";
32-
import { loadAgentRuntimePluginRegistryHandle } from "../runtime-plugins.js";
3328
import { buildMainSessionRecoveryClearPatch } from "./main-session-recovery-clear.js";
3429
import {
3530
repairMainSessionRecoveryMutation,
@@ -69,58 +64,6 @@ export function requiresRestartRecoveryMessageActionAuthority(entry: SessionEntr
6964
);
7065
}
7166

72-
export function resolveRestartRecoveryResumeBlockReason(params: {
73-
cfg?: OpenClawConfig;
74-
entry: SessionEntry;
75-
sessionKey: string;
76-
}): string | undefined {
77-
const beforeAgentReplyState = params.entry.restartRecoveryBeforeAgentReplyState;
78-
const sourceIngress = params.entry.restartRecoverySourceIngress;
79-
const hasLegacyClaimWithoutOwnership =
80-
sourceIngress === undefined &&
81-
normalizeOptionalString(params.entry.restartRecoveryDeliveryRunId) !== undefined;
82-
// Durable claims written before source ownership existed may have entered
83-
// through a channel or Control UI. Treat those claims as external so an
84-
// upgrade cannot bypass a newly active policy or side-effect hook.
85-
const requiresHookSafetyProof =
86-
hasLegacyClaimWithoutOwnership ||
87-
beforeAgentReplyState === "admitted" ||
88-
beforeAgentReplyState === "continue" ||
89-
beforeAgentReplyState === "handled-reply" ||
90-
sourceIngress === "channel" ||
91-
sourceIngress === "control-ui";
92-
if (!requiresHookSafetyProof) {
93-
return undefined;
94-
}
95-
if (!params.cfg) {
96-
return "pre-hook recovery runtime config is unavailable";
97-
}
98-
let pluginRegistry: ReturnType<typeof loadAgentRuntimePluginRegistryHandle>;
99-
try {
100-
const agentId = resolveAgentIdFromSessionKey(
101-
params.sessionKey,
102-
resolveDefaultAgentId(params.cfg),
103-
);
104-
pluginRegistry = loadAgentRuntimePluginRegistryHandle({
105-
config: params.cfg,
106-
workspaceDir: resolveAgentWorkspaceDir(params.cfg, agentId),
107-
allowGatewaySubagentBinding: true,
108-
});
109-
} catch {
110-
return "pre-hook recovery runtime plugins could not be loaded";
111-
}
112-
if (!pluginRegistry) {
113-
return "pre-hook recovery runtime plugins could not be loaded";
114-
}
115-
// A stored hook result proves that invocation completed, but not that the
116-
// same plugin code and config are still loaded after restart. Fail closed
117-
// until hook activation owns a stable cross-process implementation digest.
118-
const unsafeHook = withPluginRuntimeRegistryScope(pluginRegistry, () =>
119-
findRestartRecoveryUnsafeReplyHook({ trigger: "user" }),
120-
);
121-
return unsafeHook ? `pre-hook recovery cannot bypass the active ${unsafeHook} hook` : undefined;
122-
}
123-
12467
function buildResumeMessage(pendingFinalDeliveryText?: string | null): string {
12568
const sanitizedPendingText =
12669
typeof pendingFinalDeliveryText === "string"

0 commit comments

Comments
 (0)