Skip to content

Commit 8450402

Browse files
authored
fix: recover subagent waits after transport drops
Fix subagent recovery and session state reconciliation. Thanks @ZiPengWei.
1 parent 5376a4a commit 8450402

20 files changed

Lines changed: 1283 additions & 49 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ Docs: https://docs.openclaw.ai
115115
- Control UI/chat: keep optimistic user and assistant tail messages visible when a final history refresh briefly returns an older snapshot, preventing message cards from flash-disappearing until the next refresh. Fixes #71371. Thanks @WolvenRA.
116116
- Talk/TTS: resolve configured extension speech providers from the active runtime registry before provider-list discovery, so Talk mode no longer rejects valid plugin speech providers as unsupported.
117117
- Sessions/subagents: stop stale ended runs and old store-only child reverse links from reappearing in `childSessions`, while keeping live descendants and recently-ended children visible. Fixes #57920.
118+
- Subagents: recover child sessions after recoverable wait transport failures without exposing an extra wait state, and keep terminal lifecycle timer ordering deterministic. (#71423) Thanks @ZiPengWei.
118119
- Subagents: stop stale unended runs from counting as active or pending forever, while preserving restart-aborted recovery for recoverable child sessions. Fixes #71252. Thanks @hclsys.
119120
- Gateway/tools: allow `POST /tools/invoke` to reach plugin-backed catalog tools such as `browser` when no core implementation exists, while still preferring built-in tools for real core names. Thanks @chat2way.
120121
- Browser/security: require `operator.admin` for the `browser.request` gateway method, matching the host/browser-node control authority exposed by that route. Thanks @RichardCao.

‎extensions/feishu/src/channel.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -892,6 +892,33 @@ describe("normalizeFeishuTarget", () => {
892892
});
893893
});
894894

895+
describe("feishuPlugin.messaging.resolveDeliveryTarget", () => {
896+
it("routes direct conversations to user targets", () => {
897+
expect(
898+
feishuPlugin.messaging?.resolveDeliveryTarget?.({
899+
conversationId: "ou_123",
900+
}),
901+
).toEqual({ to: "user:ou_123" });
902+
});
903+
904+
it("routes group conversations to chat targets", () => {
905+
expect(
906+
feishuPlugin.messaging?.resolveDeliveryTarget?.({
907+
conversationId: "oc_123",
908+
}),
909+
).toEqual({ to: "chat:oc_123" });
910+
});
911+
912+
it("routes topic conversations to parent chat plus thread id", () => {
913+
expect(
914+
feishuPlugin.messaging?.resolveDeliveryTarget?.({
915+
conversationId: "oc_123:topic:omt_456",
916+
parentConversationId: "oc_123",
917+
}),
918+
).toEqual({ to: "chat:oc_123", threadId: "omt_456" });
919+
});
920+
});
921+
895922
describe("looksLikeFeishuId", () => {
896923
it("accepts provider-prefixed user targets", () => {
897924
expect(looksLikeFeishuId("feishu:user:ou_123")).toBe(true);

‎extensions/feishu/src/channel.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1134,6 +1134,20 @@ export const feishuPlugin: ChannelPlugin<ResolvedFeishuAccount, FeishuProbeResul
11341134
setupWizard: feishuSetupWizard,
11351135
messaging: {
11361136
normalizeTarget: (raw) => normalizeFeishuTarget(raw) ?? undefined,
1137+
resolveDeliveryTarget: ({ conversationId, parentConversationId }) => {
1138+
const directId = parseFeishuDirectConversationId(conversationId);
1139+
if (directId) {
1140+
return { to: `user:${directId}` };
1141+
}
1142+
const parsed = parseFeishuConversationId({ conversationId, parentConversationId });
1143+
if (parsed?.topicId) {
1144+
return {
1145+
to: `chat:${parentConversationId?.trim() || parsed.chatId}`,
1146+
threadId: parsed.topicId,
1147+
};
1148+
}
1149+
return { to: `chat:${parsed?.chatId ?? conversationId.trim()}` };
1150+
},
11371151
resolveSessionConversation: ({ kind, rawId }) =>
11381152
resolveFeishuSessionConversation({ kind, rawId }),
11391153
resolveOutboundSessionRoute: (params) => resolveFeishuOutboundSessionRoute(params),

‎src/agents/run-wait.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ vi.mock("../gateway/call.js", () => ({
77

88
import {
99
__testing,
10+
isRecoverableAgentWaitError,
1011
readLatestAssistantReply,
1112
readLatestAssistantReplySnapshot,
1213
waitForAgentRun,
@@ -151,6 +152,18 @@ describe("waitForAgentRun", () => {
151152
});
152153
});
153154

155+
it("keeps transport-close wait failures as errors for generic callers", async () => {
156+
callGatewayMock.mockRejectedValue(new Error("gateway closed (1006): transport close"));
157+
158+
const result = await waitForAgentRun({ runId: "run-interrupted", timeoutMs: 500 });
159+
160+
expect(result).toEqual({
161+
status: "error",
162+
error: "gateway closed (1006): transport close",
163+
});
164+
expect(isRecoverableAgentWaitError(result.error)).toBe(true);
165+
});
166+
154167
it("preserves pending agent.wait status", async () => {
155168
callGatewayMock.mockResolvedValue({ status: "pending" });
156169

‎src/agents/run-wait.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,28 @@ function normalizeAgentWaitResult(
4949
};
5050
}
5151

52+
const RECOVERABLE_AGENT_WAIT_ERROR_PATTERNS: readonly RegExp[] = [
53+
/gateway closed \(1006/i,
54+
/transport close/i,
55+
/connection loss/i,
56+
/connection closed/i,
57+
/gateway not connected/i,
58+
/no active .* listener/i,
59+
/socket hang up/i,
60+
/\b(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|EHOSTUNREACH|ENETUNREACH)\b/i,
61+
];
62+
63+
export function isRecoverableAgentWaitError(error: string | undefined): boolean {
64+
const message = error?.trim();
65+
if (!message) {
66+
return false;
67+
}
68+
if (message.includes("gateway timeout")) {
69+
return false;
70+
}
71+
return RECOVERABLE_AGENT_WAIT_ERROR_PATTERNS.some((pattern) => pattern.test(message));
72+
}
73+
5274
function normalizePendingRunIds(runIds: Iterable<string>): string[] {
5375
const seen = new Set<string>();
5476
for (const runId of runIds) {

‎src/agents/subagent-orphan-recovery.test.ts‎

Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
22
import * as sessions from "../config/sessions.js";
33
import * as gateway from "../gateway/call.js";
44
import * as sessionUtils from "../gateway/session-utils.fs.js";
5-
import { recoverOrphanedSubagentSessions } from "./subagent-orphan-recovery.js";
5+
import * as announceDelivery from "./subagent-announce-delivery.js";
6+
import {
7+
recoverOrphanedSubagentSessions,
8+
scheduleOrphanRecovery,
9+
} from "./subagent-orphan-recovery.js";
610
import * as subagentRegistrySteerRuntime from "./subagent-registry-steer-runtime.js";
711
import type { SubagentRunRecord } from "./subagent-registry.types.js";
812

@@ -28,8 +32,19 @@ vi.mock("../gateway/session-utils.fs.js", () => ({
2832
readSessionMessages: vi.fn(() => []),
2933
}));
3034

35+
vi.mock("./subagent-announce-delivery.js", () => ({
36+
deliverSubagentAnnouncement: vi.fn(async () => ({ delivered: true, path: "direct" })),
37+
isInternalAnnounceRequesterSession: vi.fn(() => false),
38+
loadRequesterSessionEntry: vi.fn(() => ({ entry: {} })),
39+
}));
40+
41+
vi.mock("./subagent-announce-origin.js", () => ({
42+
resolveAnnounceOrigin: vi.fn((entry, requesterOrigin) => requesterOrigin),
43+
}));
44+
3145
vi.mock("./subagent-registry-steer-runtime.js", () => ({
3246
replaceSubagentRunAfterSteer: vi.fn(() => true),
47+
finalizeInterruptedSubagentRun: vi.fn(async () => 1),
3348
}));
3449

3550
function createTestRunRecord(overrides: Partial<SubagentRunRecord> = {}): SubagentRunRecord {
@@ -84,10 +99,12 @@ function getResumeMessage() {
8499

85100
describe("subagent-orphan-recovery", () => {
86101
beforeEach(() => {
102+
vi.useFakeTimers();
87103
vi.clearAllMocks();
88104
});
89105

90106
afterEach(() => {
107+
vi.useRealTimers();
91108
vi.restoreAllMocks();
92109
});
93110

@@ -262,6 +279,13 @@ describe("subagent-orphan-recovery", () => {
262279

263280
expect(result.recovered).toBe(0);
264281
expect(result.failed).toBe(1);
282+
expect(result.failedRuns).toEqual([
283+
expect.objectContaining({
284+
runId: "run-1",
285+
childSessionKey: "agent:main:subagent:test-session-1",
286+
error: "gateway unavailable",
287+
}),
288+
]);
265289

266290
// abortedLastRun flag should NOT be cleared on failure,
267291
// so the next restart can retry the recovery
@@ -369,6 +393,38 @@ describe("subagent-orphan-recovery", () => {
369393
expect(message).toContain("config changes from your previous run were already applied");
370394
});
371395

396+
it("announces recovery-in-progress once when a later retry is attempting resume", async () => {
397+
mockSingleAbortedSession();
398+
399+
const activeRuns = createActiveRuns(createTestRunRecord());
400+
const notifiedRecoverySessionKeys = new Set<string>();
401+
402+
await recoverOrphanedSubagentSessions({
403+
getActiveRuns: () => activeRuns,
404+
attemptNumber: 2,
405+
maxAttempts: 4,
406+
notifiedRecoverySessionKeys,
407+
});
408+
409+
expect(announceDelivery.deliverSubagentAnnouncement).toHaveBeenCalledOnce();
410+
expect(announceDelivery.deliverSubagentAnnouncement).toHaveBeenCalledWith(
411+
expect.objectContaining({
412+
requesterSessionKey: "agent:main:quietchat:direct:+1234567890",
413+
triggerMessage: expect.stringContaining("Automatic recovery is already in progress"),
414+
}),
415+
);
416+
expect(notifiedRecoverySessionKeys).toEqual(new Set(["agent:main:subagent:test-session-1"]));
417+
418+
await recoverOrphanedSubagentSessions({
419+
getActiveRuns: () => activeRuns,
420+
attemptNumber: 3,
421+
maxAttempts: 4,
422+
notifiedRecoverySessionKeys,
423+
});
424+
425+
expect(announceDelivery.deliverSubagentAnnouncement).toHaveBeenCalledOnce();
426+
});
427+
372428
it("prevents duplicate resume when updateSessionStore fails", async () => {
373429
vi.mocked(gateway.callGateway).mockResolvedValue({ runId: "new-run" } as never);
374430
vi.mocked(sessions.updateSessionStore).mockRejectedValue(new Error("write failed"));
@@ -429,4 +485,41 @@ describe("subagent-orphan-recovery", () => {
429485
expect(gateway.callGateway).toHaveBeenCalledOnce();
430486
expect(sessions.updateSessionStore).toHaveBeenCalledOnce();
431487
});
488+
489+
it("finalizes interrupted runs with a readable failure after recovery retries are exhausted", async () => {
490+
vi.mocked(sessions.loadSessionStore).mockReturnValue({
491+
"agent:main:subagent:test-session-1": {
492+
sessionId: "session-abc",
493+
updatedAt: Date.now(),
494+
abortedLastRun: true,
495+
},
496+
});
497+
vi.mocked(gateway.callGateway).mockRejectedValue(new Error("service restart"));
498+
499+
const activeRuns = createActiveRuns(createTestRunRecord());
500+
501+
scheduleOrphanRecovery({
502+
getActiveRuns: () => activeRuns,
503+
delayMs: 1,
504+
maxRetries: 1,
505+
});
506+
507+
await vi.advanceTimersByTimeAsync(1);
508+
await Promise.resolve();
509+
await vi.advanceTimersByTimeAsync(2);
510+
await Promise.resolve();
511+
512+
expect(subagentRegistrySteerRuntime.finalizeInterruptedSubagentRun).toHaveBeenCalledWith(
513+
expect.objectContaining({
514+
runId: "run-1",
515+
childSessionKey: "agent:main:subagent:test-session-1",
516+
error: expect.stringContaining("Automatic recovery failed after 2 attempts"),
517+
}),
518+
);
519+
expect(subagentRegistrySteerRuntime.finalizeInterruptedSubagentRun).toHaveBeenCalledWith(
520+
expect.objectContaining({
521+
error: expect.stringContaining("service restart"),
522+
}),
523+
);
524+
});
432525
});

0 commit comments

Comments
 (0)