π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent-runtime): harden async sub-agent suspend/resume against missed wakeups (#15855)
Arvin Xuf362dcb5dbdb
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 63a0599f40c..e8edfc01f71 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -1696,7 +1696,7 @@ describe('AgentRuntimeService', () => {expect(casSpy).not.toHaveBeenCalled();});- it('arms a one-shot verify when the parent has not parked yet and scheduleVerifyOnHold is set', async () => {+ it('arms the first verify (attempt 1, 15s) when the parent has not parked yet and scheduleVerifyOnHold is set', async () => {// Child completed before the parent's parking step persisted its state.mockCoordinator.loadAgentState.mockResolvedValue({pendingToolsCalling: [],@@ -1712,14 +1712,15 @@ describe('AgentRuntimeService', () => {expect(won).toBe(false);expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(expect.objectContaining({+ delay: 15_000,operationId: parentOpId,- payload: { verifyAsyncToolBarrier: true },+ payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },stepIndex: 2,}),);});- it('arms a one-shot verify when the barrier is unsatisfied and scheduleVerifyOnHold is set', async () => {+ it('arms a verify when the barrier is unsatisfied and scheduleVerifyOnHold is set', async () => {mockCoordinator.loadAgentState.mockResolvedValue({pendingToolsCalling: [{ id: 'tc1' }],status: 'waiting_for_async_tool',@@ -1736,7 +1737,104 @@ describe('AgentRuntimeService', () => {expect(won).toBe(false);expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(- expect.objectContaining({ payload: { verifyAsyncToolBarrier: true } }),+ expect.objectContaining({+ payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },+ }),+ );+ });++ it('re-arms the next verify with exponential backoff while the barrier holds', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 1,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },+ };++ // A verify handler running as attempt 2 re-arms attempt 3 (60s).+ await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true, verifyAttempt: 3 },+ );++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ delay: 60_000,+ payload: { asyncToolVerifyAttempt: 3, verifyAsyncToolBarrier: true },+ }),+ );+ });++ it('stops re-arming once the bounded attempts are exhausted', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 1,+ });+ (service as any).serverDB.query = {+ messagePlugins: { findFirst: vi.fn().mockResolvedValue(null) },+ };++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true, verifyAttempt: 6 },+ );++ expect(won).toBe(false);+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('trusts a just-backfilled message id without re-reading it (read-your-writes)', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [{ id: 'tc1' }],+ status: 'waiting_for_async_tool',+ stepCount: 3,+ });+ // Plugin row exists (created at park) but its state still reads stale.+ const findById = vi.fn().mockResolvedValue({ content: '' });+ (service as any).serverDB.query = {+ messagePlugins: {+ findFirst: vi.fn().mockResolvedValue({ id: 'msg-tc1', state: null, toolCallId: 'tc1' }),+ },+ };+ (service as any).messageModel.findById = findById;+ const casSpy = vi+ .spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool')+ .mockResolvedValue(true);++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { knownFulfilledMessageId: 'msg-tc1' },+ );++ expect(won).toBe(true);+ expect(casSpy).toHaveBeenCalledWith(parentOpId);+ // The stale read must be skipped β barrier trusted the local backfill.+ expect(findById).not.toHaveBeenCalled();+ });++ it('arms a fallback verify when a parked op has no pending tools', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ pendingToolsCalling: [],+ status: 'waiting_for_async_tool',+ stepCount: 4,+ });+ const casSpy = vi.spyOn(AgentOperationModel.prototype, 'tryResumeFromAsyncTool');++ const won = await service.tryResumeParentFromAsyncTool(+ { parentOperationId: parentOpId },+ { scheduleVerifyOnHold: true },+ );++ expect(won).toBe(false);+ expect(casSpy).not.toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: { asyncToolVerifyAttempt: 1, verifyAsyncToolBarrier: true },+ stepIndex: 4,+ }),);});@@ -1805,7 +1903,7 @@ describe('AgentRuntimeService', () => {});expect(resumeSpy).toHaveBeenCalledWith({ parentOperationId: 'parent-op-1' },- { scheduleVerifyOnHold: true },+ { knownFulfilledMessageId: 'tool-msg-1', scheduleVerifyOnHold: true },);});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex f9e69a52705..1062be444f3 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -20,6 +20,7 @@ import {trace as otelTrace,} from '@lobechat/observability-otel/api';import {+ asyncToolResumeCounter,buildInvokeAgentAttributes,buildInvokeAgentResultAttributes,invokeAgentSpanName,@@ -84,13 +85,37 @@ if (process.env.VERCEL) {const log = debug('lobe-server:agent-runtime-service');/**- * Delay before a one-shot `verifyAsyncToolBarrier` re-check fires after a+ * Base delay before the first `verifyAsyncToolBarrier` re-check fires after a* sub-agent completion found the parent not yet resumable. Long enough for* the parent's parking step to finish persisting, short enough that a lost- * resume is recovered promptly.+ * resume is recovered promptly. Subsequent attempts back off exponentially β+ * see {@link asyncToolVerifyDelayMs}.*/const ASYNC_TOOL_VERIFY_DELAY_MS = 15_000;+/**+ * Maximum number of bounded watchdog re-checks armed per parked parent. The+ * watchdog re-arms after each unsatisfied check (instead of the old single+ * shot) so a transient miss β a read-replica lag, a sibling dying between+ * backfill and resume β is retried rather than leaving the parent stuck in+ * `waiting_for_async_tool` forever. With exponential backoff from a 15s base,+ * 5 attempts span ~15s β ~7.75min total before giving up. See LOBE-10385.+ */+const ASYNC_TOOL_VERIFY_MAX_ATTEMPTS = 5;++/** Hard ceiling on a single backoff delay so late attempts don't overshoot. */+const ASYNC_TOOL_VERIFY_MAX_DELAY_MS = 240_000;++/**+ * Exponential backoff delay for the Nth (1-based) watchdog re-check:+ * 15s, 30s, 60s, 120s, 240s, capped at {@link ASYNC_TOOL_VERIFY_MAX_DELAY_MS}.+ */+const asyncToolVerifyDelayMs = (attempt: number): number =>+ Math.min(+ ASYNC_TOOL_VERIFY_DELAY_MS * 2 ** (Math.max(1, attempt) - 1),+ ASYNC_TOOL_VERIFY_MAX_DELAY_MS,+ );+/*** Format error for storage in message pluginError metadata.* Handles Error objects which don't serialize properly with JSON.stringify.@@ -590,15 +615,28 @@ export class AgentRuntimeService {resumeAsyncTool,toolMessageId,verifyAsyncToolBarrier,+ asyncToolVerifyAttempt,externalRetryCount = 0,} = params;// Watchdog re-check for a parked async-tool wait: re-run the barrier + CAS// without claiming the step lock or executing anything. Idempotent β the// CAS guarantees at most one real resume regardless of how many checks run.+ // Opt back into `scheduleVerifyOnHold` with the next attempt so an+ // unsatisfied barrier re-arms (bounded backoff) instead of giving up after+ // a single shot β the core LOBE-10385 fix.if (verifyAsyncToolBarrier) {- log('[%s][%d] Running async-tool barrier verify', operationId, stepIndex);- const resumed = await this.tryResumeParentFromAsyncTool({ parentOperationId: operationId });+ const attempt = asyncToolVerifyAttempt ?? 1;+ log(+ '[%s][%d] Running async-tool barrier verify (attempt %d)',+ operationId,+ stepIndex,+ attempt,+ );+ const resumed = await this.tryResumeParentFromAsyncTool(+ { parentOperationId: operationId },+ { scheduleVerifyOnHold: true, verifyAttempt: attempt + 1 },+ );return {nextStepScheduled: resumed,state: {},@@ -1627,12 +1665,30 @@ export class AgentRuntimeService {*/async tryResumeParentFromAsyncTool(params: { parentOperationId: string },- options?: { scheduleVerifyOnHold?: boolean },+ options?: {+ /**+ * Message id of a tool placeholder the caller just backfilled to a+ * terminal state. Trusted by the barrier as fulfilled without re-reading+ * `message_plugins` β closes the read-your-writes gap where the barrier+ * query hits a read replica that hasn't seen the just-committed write.+ */+ knownFulfilledMessageId?: string;+ scheduleVerifyOnHold?: boolean;+ /** 1-based watchdog attempt to arm when the parent isn't resumable yet. */+ verifyAttempt?: number;+ },): Promise<boolean> {const { parentOperationId } = params;const state = await this.coordinator.loadAgentState(parentOperationId);- if (!state) return false;+ if (!state) {+ // State expired (Redis TTL) or never persisted β nothing left to resume.+ // Surface it: a missing state at completion time is how a parent silently+ // strands. There is no stepCount/status to arm a verify against.+ log('[%s] async-tool resume: parent state missing/expired, cannot resume', parentOperationId);+ asyncToolResumeCounter.add(1, { outcome: 'no_state' });+ return false;+ }if (state.status !== 'waiting_for_async_tool') {// Not parked (yet). Either the op already resumed/finished β nothing to@@ -1643,12 +1699,27 @@ export class AgentRuntimeService {}const pending = (state.pendingToolsCalling ?? []) as ChatToolPayload[];- if (pending.length === 0) return false;+ if (pending.length === 0) {+ // Parked but no pending tools recorded β usually the parked snapshot's+ // `pendingToolsCalling` hasn't finished persisting yet. Warn, report, and+ // arm a fallback re-check rather than returning silently (the old bug).+ log(+ '[%s] async-tool resume: parked op has no pending tools, arming fallback',+ parentOperationId,+ );+ asyncToolResumeCounter.add(1, { outcome: 'no_pending' });+ await this.maybeScheduleAsyncToolVerify(parentOperationId, state, options);+ return false;+ }// Barrier: every pending tool must have a fulfilled tool_result message.- const allFulfilled = await this.allPendingToolsFulfilled(pending);+ const allFulfilled = await this.allPendingToolsFulfilled(+ pending,+ options?.knownFulfilledMessageId,+ );if (!allFulfilled) {log('[%s] async-tool barrier not yet satisfied, holding', parentOperationId);+ asyncToolResumeCounter.add(1, { outcome: 'barrier_held' });await this.maybeScheduleAsyncToolVerify(parentOperationId, state, options);return false;}@@ -1659,9 +1730,12 @@ export class AgentRuntimeService {);if (!won) {log('[%s] lost async-tool resume CAS, no-op', parentOperationId);+ asyncToolResumeCounter.add(1, { outcome: 'lost_cas' });return false;}+ asyncToolResumeCounter.add(1, { outcome: 'resumed' });+log('[%s] won async-tool resume CAS, scheduling step %d', parentOperationId, state.stepCount);if (this.queueService) {@@ -1682,36 +1756,60 @@ export class AgentRuntimeService {}/**- * Arm a one-shot delayed `verifyAsyncToolBarrier` re-check for a parent op- * whose resume attempt found it not yet resumable. Skipped for terminal- * states (nothing left to resume) and when the caller didn't opt in β the- * verify execution itself never re-arms, keeping retries bounded to one- * per completion event.+ * Arm the next bounded `verifyAsyncToolBarrier` re-check for a parent op whose+ * resume attempt found it not yet resumable. Skipped for terminal states+ * (nothing left to resume) and when the caller didn't opt in.+ *+ * Unlike the original single shot, the watchdog re-arms after each unsatisfied+ * check: the verify handler re-enters here with `verifyAttempt + 1`, backing+ * off exponentially up to {@link ASYNC_TOOL_VERIFY_MAX_ATTEMPTS}. A transient+ * miss (read-replica lag, a sibling dying between backfill and resume) is thus+ * retried instead of permanently stranding the parent. Once attempts are+ * exhausted the chain stops and the `verify_exhausted` metric fires so the+ * orphan is observable. See LOBE-10385.*/private async maybeScheduleAsyncToolVerify(parentOperationId: string,state: AgentState,- options?: { scheduleVerifyOnHold?: boolean },+ options?: { scheduleVerifyOnHold?: boolean; verifyAttempt?: number },): Promise<void> {if (!options?.scheduleVerifyOnHold || !this.queueService) return;const status = state.status as string;if (status === 'done' || status === 'error' || status === 'interrupted') return;+ const attempt = options.verifyAttempt ?? 1;+ if (attempt > ASYNC_TOOL_VERIFY_MAX_ATTEMPTS) {+ // Bounded retries spent and the parent is still not resumable β give up+ // re-arming and report so the stuck wait can be detected, not silently+ // accumulated.+ log(+ '[%s] async-tool barrier verify exhausted after %d attempts, giving up (status: %s)',+ parentOperationId,+ ASYNC_TOOL_VERIFY_MAX_ATTEMPTS,+ status,+ );+ asyncToolResumeCounter.add(1, { outcome: 'verify_exhausted' });+ return;+ }++ const delay = asyncToolVerifyDelayMs(attempt);log(- '[%s] scheduling async-tool barrier verify in %dms (status: %s)',+ '[%s] scheduling async-tool barrier verify attempt %d/%d in %dms (status: %s)',parentOperationId,- ASYNC_TOOL_VERIFY_DELAY_MS,+ attempt,+ ASYNC_TOOL_VERIFY_MAX_ATTEMPTS,+ delay,status,);try {await this.queueService.scheduleMessage({context: undefined,- delay: ASYNC_TOOL_VERIFY_DELAY_MS,+ delay,endpoint: `${this.baseURL}/run`,operationId: parentOperationId,- payload: { verifyAsyncToolBarrier: true },+ payload: { asyncToolVerifyAttempt: attempt, verifyAsyncToolBarrier: true },priority: 'high',stepIndex: state.stepCount,});@@ -1792,22 +1890,40 @@ export class AgentRuntimeService {);}- // 2. Barrier + CAS + resume the parent op (infra errors propagate too)- return this.tryResumeParentFromAsyncTool({ parentOperationId }, { scheduleVerifyOnHold: true });+ // 2. Barrier + CAS + resume the parent op (infra errors propagate too).+ // Pass the just-backfilled message id so the barrier trusts this write+ // instead of re-reading a possibly-stale replica.+ return this.tryResumeParentFromAsyncTool(+ { parentOperationId },+ { knownFulfilledMessageId: toolMessageId, scheduleVerifyOnHold: true },+ );}/*** Whether every pending tool call has a fulfilled tool_result message β i.e.* a tool message exists for its `tool_call_id` with non-empty content or a* terminal pluginState. Looks up by `tool_call_id` (plugin id === message id).+ *+ * `knownFulfilledMessageId` short-circuits the per-tool content/state read for+ * a placeholder the caller just backfilled in the same request: its terminal+ * write is a local fact, so re-reading it (possibly from a lagging read+ * replica) would only risk a false negative that strands the parent. The+ * plugin row itself predates the park, so the `tool_call_id β plugin.id`+ * lookup still resolves; only the freshly written content/state is trusted.*/- private async allPendingToolsFulfilled(pending: ChatToolPayload[]): Promise<boolean> {+ private async allPendingToolsFulfilled(+ pending: ChatToolPayload[],+ knownFulfilledMessageId?: string,+ ): Promise<boolean> {for (const tc of pending) {const plugin = await this.serverDB.query.messagePlugins.findFirst({where: (mp, { eq }) => eq(mp.toolCallId, tc.id),});if (!plugin) return false;+ // Trust the caller's own just-committed backfill (read-your-writes).+ if (knownFulfilledMessageId && plugin.id === knownFulfilledMessageId) continue;+const message = await this.messageModel.findById(plugin.id);const pluginState = plugin.state as { status?: string } | null;const fulfilled =diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex f962ad32a4f..a8e0ca5a469 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -121,6 +121,12 @@ export type StepCompletionReason =export interface AgentExecutionParams {approvedToolCall?: any;+ /**+ * 1-based attempt number carried by a `verifyAsyncToolBarrier` re-check so the+ * bounded watchdog can back off and stop after a fixed number of tries. Absent+ * (treated as attempt 1) on the first re-check armed by a completion bridge.+ */+ asyncToolVerifyAttempt?: number;context?: AgentRuntimeContext;externalRetryCount?: number;humanInput?: any;@@ -144,10 +150,13 @@ export interface AgentExecutionParams {/*** Watchdog re-check for a parked `waiting_for_async_tool` op: re-runs the* resume barrier + CAS without claiming the step lock or executing a step.- * A no-op when the op already resumed or the barrier is still unsatisfied.- * Scheduled one-shot by `tryResumeParentFromAsyncTool` when a sub-agent- * completion found the parent not yet resumable (covers the- * child-finishes-before-parent-parks race and transient barrier failures).+ * A no-op when the op already resumed. While the barrier is still unsatisfied+ * it re-arms the next check with exponential backoff (see+ * `asyncToolVerifyAttempt`) up to a bounded number of attempts, so a transient+ * miss is retried rather than permanently stranding the parent. First armed by+ * `tryResumeParentFromAsyncTool` when a sub-agent completion found the parent+ * not yet resumable (covers the child-finishes-before-parent-parks race and+ * transient barrier failures).*/verifyAsyncToolBarrier?: boolean;}@@ -221,6 +230,9 @@ export interface OperationCreationParams {deviceAccessPolicy?: { canUseDevice: boolean; reason: DeviceAccessReason };/** Device system info for placeholder variable replacement in Local System systemRole */deviceSystemInfo?: Record<string, string>;+ /** Discord context for injecting channel/guild info into agent system message */+ discordContext?: any;+ evalContext?: any;/*** Resolved execution plan for the run (see `resolveExecutionPlan`).* Forwarded into `state.metadata.executionPlan` so step-level layers (the@@ -228,9 +240,6 @@ export interface OperationCreationParams {* device capability from raw config.*/executionPlan?: ExecutionPlan;- /** Discord context for injecting channel/guild info into agent system message */- discordContext?: any;- evalContext?: any;/*** External lifecycle hooks* Registered once, auto-adapt to local (in-memory) or production (webhook) modediff --git a/packages/observability-otel/src/modules/agent-runtime/index.ts b/packages/observability-otel/src/modules/agent-runtime/index.tsindex 43c39eff78f..3f2bbc7885c 100644--- a/packages/observability-otel/src/modules/agent-runtime/index.ts+++ b/packages/observability-otel/src/modules/agent-runtime/index.ts@@ -1,4 +1,6 @@-import { trace } from '@opentelemetry/api';+import { metrics, trace } from '@opentelemetry/api';++const meter = metrics.getMeter('server-services-agent-runtime');/*** Tracer for Agent Runtime semantic spans (invoke_agent / chat / execute_tool /@@ -10,5 +12,23 @@ import { trace } from '@opentelemetry/api';*/export const tracer = trace.getTracer('@lobechat/agent-runtime', '0.0.1');+/**+ * Count of async sub-agent parent resume attempts grouped by `outcome`:+ * - `resumed` β won the resume CAS and scheduled the parent's next step+ * - `barrier_held` β pending tools not all fulfilled yet, re-check armed+ * - `no_pending` β parked op had no pending tools (snapshot lag), fallback armed+ * - `no_state` β parent state missing/expired in Redis, cannot resume+ * - `lost_cas` β another completion won the resume CAS first+ * - `verify_exhausted`β bounded watchdog retries exhausted while still not resumable+ *+ * Lets orphaned `waiting_for_async_tool` parents be detected via the+ * `barrier_held` / `no_pending` / `verify_exhausted` series instead of+ * accumulating silently. See LOBE-10385.+ */+export const asyncToolResumeCounter = meter.createCounter('agent_runtime_async_tool_resume_total', {+ description: 'Count of async sub-agent parent resume attempts grouped by outcome.',+ unit: '{resume}',+});+export * from './attributes';export * from './semconv';diff --git a/src/server/agent-hono/handlers/runStep.ts b/src/server/agent-hono/handlers/runStep.tsindex a4797cde5f6..1d1817a8694 100644--- a/src/server/agent-hono/handlers/runStep.ts+++ b/src/server/agent-hono/handlers/runStep.ts@@ -42,6 +42,7 @@ export async function runStep(c: Context): Promise<Response> {resumeAsyncTool,toolMessageId,verifyAsyncToolBarrier,+ asyncToolVerifyAttempt,} = { ...body, ...body.payload };if (!operationId) {@@ -74,6 +75,7 @@ export async function runStep(c: Context): Promise<Response> {const result = await aiAgentService.executeStep({approvedToolCall,+ asyncToolVerifyAttempt,context,externalRetryCount,humanInput,diff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.tsindex 0a25a793d31..ec1baea93ac 100644--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts@@ -40,7 +40,7 @@ import { resolveNotificationNavigatePath } from '@/store/chat/utils/desktopNotifimport { markdownToTxt } from '@/utils/markdownToTxt';import { messageMapKey } from '../../../utils/messageMapKey';-import { mergeQueuedMessages } from '../../operation/types';+import { mergeQueuedMessages, reconstructUploadFilesFromQueue } from '../../operation/types';import { createGatewayEventHandler } from './gatewayEventHandler';/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */@@ -1470,7 +1470,11 @@ export const executeHeterogeneousAgent = async (const merged = mergeQueuedMessages(remainingQueued);const mergedFiles =- merged.files.length > 0 ? merged.files.map((id) => ({ id }) as any) : undefined;+ merged.filesPreview.length > 0+ ? reconstructUploadFilesFromQueue(merged.filesPreview)+ : merged.files.length > 0+ ? (merged.files.map((id) => ({ id })) as any)+ : undefined;setTimeout(() => {useChatStore