π€― 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): settle orphaned runs on metadata-missing step delivery (#20035)
YuTengjingc829462873ab
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/resumeAbandonedParent.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/resumeAbandonedParent.test.tsnew file mode 100644index 00000000000..79e0fd9fd2f--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/__tests__/resumeAbandonedParent.test.ts@@ -0,0 +1,76 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { resumeAbandonedParent } from '../resumeAbandonedParent';++const mockDeliverWebhook = vi.hoisted(() => vi.fn());+const mockCompleteSubAgentBridge = vi.hoisted(() => vi.fn());+const mockAiAgentService = vi.hoisted(() => vi.fn());++vi.mock('@/server/services/agentRuntime/hooks/HookDispatcher', () => ({+ deliverWebhook: mockDeliverWebhook,+}));++vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn().mockImplementation(function (...args: any[]) {+ mockAiAgentService(...args);+ return { completeSubAgentBridge: mockCompleteSubAgentBridge };+ }),+}));++const resume = {+ errorMessage: 'abandoned',+ parentOperationId: 'op-parent',+ streamOwnerUserId: 'visitor-1',+ threadId: 'thd-1',+ toolMessageId: 'msg-tool',+ userId: 'user-1',+ workspaceId: 'ws-1',+};+const bridgeBody = {+ errorMessage: 'abandoned',+ operationId: 'op-child',+ parentOperationId: 'op-parent',+ reason: 'error',+ threadId: 'thd-1',+ toolMessageId: 'msg-tool',+};++describe('resumeAbandonedParent', () => {+ const db = {} as any;++ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('queues the durable callback with the visitor marker in queue mode', async () => {+ // The callback may find the child's metadata gone (runStep orphan+ // recovery), so the marker must ride along in the body.+ vi.stubEnv('QSTASH_TOKEN', 'token');++ await resumeAbandonedParent(db, 'op-child', resume);++ expect(mockDeliverWebhook).toHaveBeenCalledWith(+ { delivery: 'qstash', fallback: 'none', url: '/api/agent/webhooks/subagent-callback' },+ { ...bridgeBody, streamOwnerUserId: 'visitor-1' },+ );+ expect(mockCompleteSubAgentBridge).not.toHaveBeenCalled();+ });++ it('runs the bridge inline without a queue', async () => {+ vi.stubEnv('QSTASH_TOKEN', '');++ await resumeAbandonedParent(db, 'op-child', resume);++ expect(mockDeliverWebhook).not.toHaveBeenCalled();+ expect(mockAiAgentService).toHaveBeenCalledWith(db, 'user-1', {+ includeShareVisitor: true,+ workspaceId: 'ws-1',+ });+ expect(mockCompleteSubAgentBridge).toHaveBeenCalledWith(bridgeBody);+ });+});diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.tsindex f2c84fc47d5..5a0b57f3bef 100644--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts@@ -14,6 +14,9 @@ const mockExecuteStep = vi.fn();const mockScheduleContinuation = vi.fn();const mockReleaseOperationLock = vi.fn();const mockGetServerDB = vi.hoisted(() => vi.fn());+const mockFinalizeAbandoned = vi.hoisted(() => vi.fn());+const mockSettleStaleRunning = vi.hoisted(() => vi.fn());+const mockResumeAbandonedParent = vi.hoisted(() => vi.fn());// Lets a test force the step-boundary flush to report a timeout; undefined// means use the real implementation.const flushOverride = vi.hoisted(() => ({ settled: undefined as boolean | undefined }));@@ -50,10 +53,26 @@ vi.mock('@/server/services/aiAgent', () => ({}),}));+vi.mock('@/server/services/agentRuntime', () => ({+ AbandonOperationService: vi.fn().mockImplementation(function () {+ return { finalizeAbandoned: mockFinalizeAbandoned };+ }),+}));+vi.mock('@/database/core/db-adaptor', () => ({getServerDB: mockGetServerDB,}));+vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(function () {+ return { settleStaleRunning: mockSettleStaleRunning };+ }),+}));++vi.mock('../resumeAbandonedParent', () => ({+ resumeAbandonedParent: mockResumeAbandonedParent,+}));+function buildOperationDiagnosticDB(row?: any) {return {select: vi.fn(function () {@@ -113,6 +132,11 @@ describe('runStep handler', () => {mockScheduleContinuation.mockReset();mockReleaseOperationLock.mockReset();mockGetServerDB.mockResolvedValue({} as any);+ mockFinalizeAbandoned.mockReset();+ mockFinalizeAbandoned.mockResolvedValue({ abandoned: true, found: false });+ mockSettleStaleRunning.mockReset();+ mockSettleStaleRunning.mockResolvedValue(true);+ mockResumeAbandonedParent.mockReset();});afterEach(() => {@@ -170,6 +194,87 @@ describe('runStep handler', () => {warnSpy.mockRestore();});+ describe('orphaned operation settle', () => {+ const orphanRow = (overrides: Record<string, unknown> = {}) =>+ buildOperationDiagnosticDB({+ completedAt: null,+ startedAt: new Date(Date.now() - 2 * 60 * 60 * 1000),+ status: 'running',+ stepCount: null,+ traceS3Key: null,+ updatedAt: new Date(Date.now() - 20 * 60 * 1000),+ userId: 'user-1',+ workspaceId: 'ws-1',+ ...overrides,+ });++ let warnSpy: ReturnType<typeof vi.spyOn>;+ beforeEach(() => {+ mockGetOperationMetadata.mockResolvedValue(null);+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(function () {});+ });+ afterEach(() => {+ warnSpy.mockRestore();+ });++ it('claims the expired lease, then abandons onto the claimed row', async () => {+ mockGetServerDB.mockResolvedValue(orphanRow());+ const { ctx } = buildContext({ body: validBody });++ const res = await runStep(ctx);++ expect(res.status).toBe(401);+ const staleBefore = mockSettleStaleRunning.mock.calls[0][1] as Date;+ expect(mockSettleStaleRunning).toHaveBeenCalledWith('op-1', expect.any(Date));+ expect(Date.now() - staleBefore.getTime()).toBeGreaterThanOrEqual(10 * 60 * 1000 - 1000);+ expect(mockFinalizeAbandoned).toHaveBeenCalledWith('op-1', 'operation_metadata_missing', {+ settledAsAbandoned: true,+ });+ expect(mockResumeAbandonedParent).not.toHaveBeenCalled();+ });++ it('leaves the run alone when a heartbeat wins the lease claim', async () => {+ mockGetServerDB.mockResolvedValue(orphanRow({ updatedAt: new Date() }));+ mockSettleStaleRunning.mockResolvedValue(false);+ const { ctx } = buildContext({ body: validBody });++ await runStep(ctx);++ expect(mockFinalizeAbandoned).not.toHaveBeenCalled();+ });++ it('does not touch an operation that already reached a terminal status', async () => {+ mockGetServerDB.mockResolvedValue(orphanRow({ status: 'error' }));+ const { ctx } = buildContext({ body: validBody });++ await runStep(ctx);++ expect(mockSettleStaleRunning).not.toHaveBeenCalled();+ expect(mockFinalizeAbandoned).not.toHaveBeenCalled();+ });++ it('resumes the parent when the abandoned run was a sub-agent', async () => {+ // Regression: state and metadata are separate Redis keys, so a sub-agent+ // child can reach the with-state abandon branch here. Dropping its+ // `subAgentResume` left the parent parked in `waiting_for_async_tool`.+ const db = orphanRow();+ mockGetServerDB.mockResolvedValue(db);+ const subAgentResume = {+ errorMessage: 'abandoned',+ parentOperationId: 'op-parent',+ threadId: 'thd-1',+ toolMessageId: 'msg-tool',+ userId: 'user-1',+ };+ mockFinalizeAbandoned.mockResolvedValue({ found: true, subAgentResume });+ const { ctx } = buildContext({ body: validBody });++ await runStep(ctx);++ expect(mockResumeAbandonedParent).toHaveBeenCalledWith(db, 'op-1', subAgentResume);+ });+ });+it('includes QStash retry and message IDs in missing metadata diagnostics', async () => {mockGetOperationMetadata.mockResolvedValue({});mockGetServerDB.mockResolvedValue(buildOperationDiagnosticDB());diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/subAgentCallback.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/subAgentCallback.test.tsindex d4e2a7cb3fe..93ecfa2e58d 100644--- a/apps/server/src/router-hono/agent/handlers/__tests__/subAgentCallback.test.ts+++ b/apps/server/src/router-hono/agent/handlers/__tests__/subAgentCallback.test.ts@@ -6,6 +6,12 @@ import { subAgentCallback } from '../subAgentCallback';const mockCompleteSubAgentBridge = vi.fn();const mockGetOperationMetadata = vi.fn();const mockAiAgentService = vi.fn();+const mockOperationRows = vi.hoisted(() => ({ rows: [] as any[] }));+const mockServerDB = vi.hoisted(() => ({+ select: () => ({+ from: () => ({ where: () => ({ limit: async () => mockOperationRows.rows }) }),+ }),+}));vi.mock('@/server/services/aiAgent', () => ({AiAgentService: vi.fn().mockImplementation(function (...args: any[]) {@@ -23,7 +29,7 @@ vi.mock('@/server/modules/AgentRuntime', () => ({}));vi.mock('@/database/core/db-adaptor', () => ({- getServerDB: vi.fn().mockResolvedValue({} as any),+ getServerDB: vi.fn().mockResolvedValue(mockServerDB),}));function buildContext(opts: { body?: unknown; jsonThrows?: boolean }) {@@ -58,6 +64,7 @@ describe('subAgentCallback handler', () => {mockGetOperationMetadata.mockReset();mockAiAgentService.mockReset();mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1', workspaceId: 'ws-1' });+ mockOperationRows.rows = [];});afterEach(() => {@@ -83,6 +90,25 @@ describe('subAgentCallback handler', () => {expect(mockCompleteSubAgentBridge).not.toHaveBeenCalled();});+ it('falls back to the durable operation row when the child metadata is gone', async () => {+ // Regression (LOBE-14161): runStep's orphan recovery resumes the parent+ // precisely because the child's coordinator metadata expired, so a+ // metadata-only lookup 401'd every redelivery and stranded the parent.+ mockGetOperationMetadata.mockResolvedValue(null);+ mockOperationRows.rows = [{ userId: 'user-row', workspaceId: 'ws-row' }];+ mockCompleteSubAgentBridge.mockResolvedValue(true);+ const { ctx } = buildContext({ body: { ...validBody, streamOwnerUserId: 'visitor-1' } });++ const res = await subAgentCallback(ctx);++ expect(res.status).toBe(200);+ expect(mockAiAgentService).toHaveBeenCalledWith(mockServerDB, 'user-row', {+ includeShareVisitor: true,+ workspaceId: 'ws-row',+ });+ expect(mockCompleteSubAgentBridge).toHaveBeenCalledTimes(1);+ });+it('returns 401 when the child operation has no userId', async () => {mockGetOperationMetadata.mockResolvedValue(undefined);const { ctx } = buildContext({ body: validBody });diff --git a/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts b/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.tsindex 7ae36238c7b..aa3c3357a2b 100644--- a/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts+++ b/apps/server/src/router-hono/agent/handlers/finalizeAbandoned.ts@@ -3,8 +3,8 @@ import type { Context } from 'hono';import { getServerDB } from '@/database/core/db-adaptor';import { AbandonOperationService } from '@/server/services/agentRuntime';-import { deliverWebhook } from '@/server/services/agentRuntime/hooks/HookDispatcher';-import { AiAgentService } from '@/server/services/aiAgent';++import { resumeAbandonedParent } from './resumeAbandonedParent';const log = debug('lobe-server:agent:finalize-abandoned');@@ -34,70 +34,13 @@ export async function finalizeAbandoned(c: Context): Promise<Response> {const service = new AbandonOperationService(serverDB);const result = await service.finalizeAbandoned(operationId, reason);- // If the abandoned op was a sub-agent, resume its parent: the watchdog- // killed the child without firing its onComplete bridge, so the parent- // stays parked in `waiting_for_async_tool` until this runs.- //- // This endpoint is called by the DO inactivity watchdog EXACTLY ONCE and is- // never retried, so the resume must carry its own durability. A transient- // DB/Redis failure mid-bridge (the backfill in particular) cannot be- // recovered by the parent's async-tool verify watchdog β that only re-reads- // the barrier, it can't recreate the missing tool-message backfill. So in- // queue mode we hand off to the same QStash-backed `/subagent-callback` the- // normal completion path uses: QStash redelivers on non-2xx until the- // backfill + CAS-resume land (the callback re-resolves userId from the- // coordinator metadata, which `finalizeAbandoned` deliberately keeps alive- // for sub-agent ops). In local/dev (no queue) we run the bridge inline.- //+ // If the abandoned op was a sub-agent, resume its parent. This endpoint is+ // called by the DO inactivity watchdog EXACTLY ONCE and is never retried.// Failures intentionally propagate to the outer catch (β non-2xx) instead of// being swallowed behind a 200: a 200 here would falsely report the parent// as handled while it stays parked forever.if (result.subAgentResume) {- const {- errorMessage,- parentOperationId,- streamOwnerUserId,- threadId,- toolMessageId,- userId,- workspaceId,- } = result.subAgentResume;- // Child reached a terminal failure (watchdog kill) β the bridge backfills- // the parent's tool slot with an error note rather than a stub answer.- const bridgeBody = {- errorMessage,- operationId,- parentOperationId,- reason: 'error',- threadId,- toolMessageId,- };- if (process.env.QSTASH_TOKEN) {- await deliverWebhook(- { delivery: 'qstash', fallback: 'none', url: '/api/agent/webhooks/subagent-callback' },- bridgeBody,- );- log('[%s] queued durable parent-resume for %s', operationId, parentOperationId);- } else {- // No durable queue configured: run the CAS-guarded, idempotent bridge- // inline through AiAgentService so the runtime's models stay- // workspace-scoped.- // Mirror the queue-mode `subagent-callback`: opt into visitor rows only- // when the parent op is a shared-agent visitor run (surfaced via- // `streamOwnerUserId`). Ordinary creator runs keep the default- // exclusion.- const aiAgentService = new AiAgentService(serverDB, userId, {- includeShareVisitor: Boolean(streamOwnerUserId),- workspaceId,- });- const won = await aiAgentService.completeSubAgentBridge(bridgeBody);- log(- '[%s] resumed parent %s inline (local mode, won=%s)',- operationId,- parentOperationId,- won,- );- }+ await resumeAbandonedParent(serverDB, operationId, result.subAgentResume);}const executionTime = Date.now() - startTime;diff --git a/apps/server/src/router-hono/agent/handlers/resumeAbandonedParent.ts b/apps/server/src/router-hono/agent/handlers/resumeAbandonedParent.tsnew file mode 100644index 00000000000..eb3ab5af34f--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/resumeAbandonedParent.ts@@ -0,0 +1,76 @@+import debug from 'debug';++import type { LobeChatDatabase } from '@/database/type';+import type { AbandonedSubAgentResume } from '@/server/services/agentRuntime';+import { deliverWebhook } from '@/server/services/agentRuntime/hooks/HookDispatcher';+import { AiAgentService } from '@/server/services/aiAgent';++const log = debug('lobe-server:agent:resume-abandoned-parent');++/**+ * Resume the parent of an abandoned sub-agent. Whoever abandoned the child+ * killed it without firing its onComplete bridge, so the parent stays parked in+ * `waiting_for_async_tool` until this runs. Every caller that receives+ * `subAgentResume` from `finalizeAbandoned` must hand it here.+ *+ * Callers may fire exactly once and never retry, so the resume carries its own+ * durability. A transient DB/Redis failure mid-bridge (the backfill in+ * particular) cannot be recovered by the parent's async-tool verify watchdog β+ * that only re-reads the barrier, it can't recreate the missing tool-message+ * backfill. So in queue mode we hand off to the same QStash-backed+ * `/subagent-callback` the normal completion path uses: QStash redelivers on+ * non-2xx until the backfill + CAS-resume land (the callback re-resolves userId+ * from the coordinator metadata, which `finalizeAbandoned` deliberately keeps+ * alive for sub-agent ops). In local/dev (no queue) we run the bridge inline.+ *+ * Failures propagate so the caller can surface them instead of reporting the+ * parent as handled while it stays parked forever.+ */+export async function resumeAbandonedParent(+ serverDB: LobeChatDatabase,+ operationId: string,+ resume: AbandonedSubAgentResume,+): Promise<void> {+ const {+ errorMessage,+ parentOperationId,+ streamOwnerUserId,+ threadId,+ toolMessageId,+ userId,+ workspaceId,+ } = resume;+ // Child reached a terminal failure β the bridge backfills the parent's tool+ // slot with an error note rather than a stub answer.+ const bridgeBody = {+ errorMessage,+ operationId,+ parentOperationId,+ reason: 'error',+ threadId,+ toolMessageId,+ };++ if (process.env.QSTASH_TOKEN) {+ // `streamOwnerUserId` lets the callback keep visitor rows visible when the+ // child's coordinator metadata (its usual source) is already gone.+ await deliverWebhook(+ { delivery: 'qstash', fallback: 'none', url: '/api/agent/webhooks/subagent-callback' },+ { ...bridgeBody, streamOwnerUserId },+ );+ log('[%s] queued durable parent-resume for %s', operationId, parentOperationId);+ return;+ }++ // No durable queue configured: run the CAS-guarded, idempotent bridge inline+ // through AiAgentService so the runtime's models stay workspace-scoped.+ // Mirror the queue-mode `subagent-callback`: opt into visitor rows only when+ // the parent op is a shared-agent visitor run (surfaced via+ // `streamOwnerUserId`). Ordinary creator runs keep the default exclusion.+ const aiAgentService = new AiAgentService(serverDB, userId, {+ includeShareVisitor: Boolean(streamOwnerUserId),+ workspaceId,+ });+ const won = await aiAgentService.completeSubAgentBridge(bridgeBody);+ log('[%s] resumed parent %s inline (local mode, won=%s)', operationId, parentOperationId, won);+}diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.tsindex 1221f3e72c9..913c810e74d 100644--- a/apps/server/src/router-hono/agent/handlers/runStep.ts+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts@@ -3,15 +3,22 @@ import { eq } from 'drizzle-orm';import type { Context } from 'hono';import { getServerDB } from '@/database/core/db-adaptor';+import { AgentOperationModel } from '@/database/models/agentOperation';import { agentOperations } from '@/database/schemas/agentOperations';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';-import type { AgentExecutionResult, AgentStepContinuation } from '@/server/services/agentRuntime';+import {+ AbandonOperationService,+ type AgentExecutionResult,+ type AgentStepContinuation,+} from '@/server/services/agentRuntime';import { AiAgentService } from '@/server/services/aiAgent';import {flushScheduledWork,runWithScheduledWorkScope,} from '@/server/utils/scheduleAfterResponse';+import { resumeAbandonedParent } from './resumeAbandonedParent';+const log = debug('lobe-server:agent:run-step');/**@@ -72,6 +79,7 @@ async function getOperationRowDiagnostic(operationId: string) {status: agentOperations.status,stepCount: agentOperations.stepCount,traceS3Key: agentOperations.traceS3Key,+ updatedAt: agentOperations.updatedAt,}).from(agentOperations).where(eq(agentOperations.id, operationId))@@ -84,6 +92,7 @@ async function getOperationRowDiagnostic(operationId: string) {status: row?.status ?? null,stepCount: row?.stepCount ?? null,traceS3KeyPresent: Boolean(row?.traceS3Key),+ updatedAt: toIsoString(row?.updatedAt),};} catch (error) {return {@@ -94,6 +103,67 @@ async function getOperationRowDiagnostic(operationId: string) {}}+/**+ * How long a `running` row may go without a lease refresh before a delivery+ * that finds no coordinator metadata treats the run as dead. A live step+ * refreshes the lease every 90s (see `touchRunning`), and this matches the+ * agent-gateway idle watchdog window.+ */+const ORPHANED_RUNNING_LEASE_MS = 10 * 60 * 1000;++/**+ * Settle a run that can never make progress again: its row still claims+ * `running`, but the coordinator metadata every step needs is gone.+ *+ * Returning 401 alone leaves the row `running` and the assistant placeholder+ * loading forever: the stale-operation reaper skips runs without coordinator+ * state, and the gateway watchdog may never have armed or may already have+ * fired. The metadata read also returns null on a Redis error, so the claim is+ * the same lease CAS the reaper uses (`settleStaleRunning`) β a heartbeat that+ * lands first wins and the run is left alone.+ */+async function settleOrphanedRunningOperation(+ operationId: string,+ dbRow: Awaited<ReturnType<typeof getOperationRowDiagnostic>>,+): Promise<void> {+ if (dbRow.status !== 'running') return;++ try {+ const serverDB = await getServerDB();+ const [owner] = await serverDB+ .select({ userId: agentOperations.userId, workspaceId: agentOperations.workspaceId })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);+ if (!owner) return;++ const claimed = await new AgentOperationModel(+ serverDB,+ owner.userId,+ owner.workspaceId ?? undefined,+ ).settleStaleRunning(operationId, new Date(Date.now() - ORPHANED_RUNNING_LEASE_MS));+ if (!claimed) return;++ // The claim already moved the row to `abandoned`; tell the lifecycle so it+ // persists onto that status instead of refusing it as a conflicting owner.+ const result = await new AbandonOperationService(serverDB).finalizeAbandoned(+ operationId,+ 'operation_metadata_missing',+ { settledAsAbandoned: true },+ );+ // State and metadata are separate Redis keys, so a sub-agent child can+ // still reach the with-state branch here; its parent needs the resume.+ if (result.subAgentResume) {+ await resumeAbandonedParent(serverDB, operationId, result.subAgentResume);+ }+ console.warn(+ JSON.stringify({ event: 'agent.run_step.orphaned_operation_settled', operationId, result }),+ );+ } catch (error) {+ console.error('[run-step] failed to settle orphaned operation %s: %O', operationId, error);+ }+}+/*** Execute a single agent step. Invoked by QStash with the body* `{ operationId, stepIndex, context, humanInput?, approvedToolCall?, ... }`.@@ -160,6 +230,8 @@ export async function runStep(c: Context): Promise<Response> {log(`[${operationId}] Invalid operation or no userId found: %O`, diagnostic);console.warn(JSON.stringify(diagnostic));++ await settleOrphanedRunningOperation(operationId, dbRow);return c.json({ error: 'Invalid operation or unauthorized' }, 401);}diff --git a/apps/server/src/router-hono/agent/handlers/subAgentCallback.ts b/apps/server/src/router-hono/agent/handlers/subAgentCallback.tsindex f4fa03c5074..1ec9430e773 100644--- a/apps/server/src/router-hono/agent/handlers/subAgentCallback.ts+++ b/apps/server/src/router-hono/agent/handlers/subAgentCallback.ts@@ -1,7 +1,9 @@import debug from 'debug';+import { eq } from 'drizzle-orm';import type { Context } from 'hono';import { getServerDB } from '@/database/core/db-adaptor';+import { agentOperations } from '@/database/schemas/agentOperations';import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';import { AiAgentService } from '@/server/services/aiAgent';@@ -20,7 +22,8 @@ const log = debug('lobe-server:agent:subagent-callback');* β event fields from the hook dispatch plus the bridge params from* `webhook.body`. `errorMessage` is set by the watchdog abandon path, whose* child state never records the failure; without it the parent reads a bare- * "Sub-agent did not complete (error).".+ * "Sub-agent did not complete (error).". `streamOwnerUserId` is forwarded by+ * the abandon paths for when the child's coordinator metadata is gone.** Auth: `qstashAuth` on the route β QStash signature required.*/@@ -32,7 +35,15 @@ export async function subAgentCallback(c: Context): Promise<Response> {return c.json({ error: 'Invalid JSON body' }, 400);}- const { errorMessage, operationId, parentOperationId, reason, threadId, toolMessageId } = body;+ const {+ errorMessage,+ operationId,+ parentOperationId,+ reason,+ streamOwnerUserId,+ threadId,+ toolMessageId,+ } = body;log('subagent-callback: operationId=%s, parentOperationId=%s, reason=%s, toolMessageId=%s',@@ -50,17 +61,43 @@ export async function subAgentCallback(c: Context): Promise<Response> {}try {- // Resolve userId from the child operation's metadata β same trust chain as- // /run: the body is QStash-signature-verified, the operation must exist.+ // Resolve the owner from the child operation's metadata β same trust chain+ // as /run: the body is QStash-signature-verified, the operation must exist.+ // An abandon path can resume the parent precisely because the child's+ // metadata is gone (runStep's orphan recovery), so fall back to the durable+ // operation row; otherwise every redelivery 401s and the parent stays+ // parked in `waiting_for_async_tool` forever.const coordinator = new AgentRuntimeCoordinator();const metadata = await coordinator.getOperationMetadata(operationId);+ const serverDB = await getServerDB();++ let owner: { streamOwnerUserId?: string; userId: string; workspaceId?: string } | undefined;+ if (metadata?.userId) {+ owner = {+ streamOwnerUserId: metadata.streamOwnerUserId,+ userId: metadata.userId,+ workspaceId: metadata.workspaceId,+ };+ } else {+ const [row] = await serverDB+ .select({ userId: agentOperations.userId, workspaceId: agentOperations.workspaceId })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);+ if (row) {+ owner = {+ streamOwnerUserId: typeof streamOwnerUserId === 'string' ? streamOwnerUserId : undefined,+ userId: row.userId,+ workspaceId: row.workspaceId ?? undefined,+ };+ }+ }- if (!metadata?.userId) {+ if (!owner) {log('subagent-callback: invalid operation or no userId found for %s', operationId);return c.json({ error: 'Invalid operation or unauthorized' }, 401);}- const serverDB = await getServerDB();// Bridge through AiAgentService (like the /run step worker) so the// runtime's models stay workspace-scoped β a bare AgentRuntimeService// would be personal-scoped and the tool-message backfill / resume@@ -69,10 +106,9 @@ export async function subAgentCallback(c: Context): Promise<Response> {// carries `streamOwnerUserId` when the operation executes as the creator// but the visitor owns the stream. Ordinary creator ops keep the default// exclusion.- const includeShareVisitor = Boolean(metadata.streamOwnerUserId);- const aiAgentService = new AiAgentService(serverDB, metadata.userId, {- includeShareVisitor,- workspaceId: metadata.workspaceId,+ const aiAgentService = new AiAgentService(serverDB, owner.userId, {+ includeShareVisitor: Boolean(owner.streamOwnerUserId),+ workspaceId: owner.workspaceId,});const resumed = await aiAgentService.completeSubAgentBridge({diff --git a/apps/server/src/services/agentRuntime/AbandonOperationService.ts b/apps/server/src/services/agentRuntime/AbandonOperationService.tsindex de949759d64..48c032dc93e 100644--- a/apps/server/src/services/agentRuntime/AbandonOperationService.ts+++ b/apps/server/src/services/agentRuntime/AbandonOperationService.ts@@ -124,7 +124,12 @@ export class AbandonOperationService {const state = await this.coordinator.loadAgentState(operationId);if (!state) {log('[%s] no agent state in coordinator β already cleaned up', operationId);- await this.finalizeRunningOperationWithoutState(operationId, reason, result);+ await this.finalizeRunningOperationWithoutState(+ operationId,+ reason,+ result,+ options?.settledAsAbandoned,+ );return result;}result.found = true;@@ -261,16 +266,18 @@ export class AbandonOperationService {// silently, and a throw inside it is swallowed as non-fatal. Any of those// used to leave the operation `running` forever β nothing else retires a// non-Goal op, so it stayed live on the dashboard and blocked its own- // recovery. `settleRunning` is idempotent and only matches rows still in- // `running`, so it cannot overwrite the richer outcome when the dispatch- // did happen.+ // recovery. `settleLive` is idempotent and only matches rows still live, so+ // it cannot overwrite the richer outcome when the dispatch did happen. It+ // also covers a parked row (`waiting_for_human` / `waiting_for_async_tool`):+ // a sub-agent child parked on its own nested call skips the dispatch above,+ // and once abandoned nothing can ever resume it.if (origin.userId) {try {const settled = await new AgentOperationModel(this.db,origin.userId,origin.workspaceId,- ).settleRunning(operationId, 'error');+ ).settleLive(operationId, 'error');if (settled) {log('[%s] durable row settled by abandon safety net', operationId);}@@ -365,9 +372,19 @@ export class AbandonOperationService {operationId: string,reason: string,result: FinalizeAbandonedResult,+ settledAsAbandoned?: boolean,): Promise<void> {const op = await this.findOperationRow(operationId);- if (!op || !['running', 'waiting_for_human', 'waiting_for_async_tool'].includes(op.status)) {+ // A caller that already claimed the row (`settleStaleRunning`) has moved it+ // to `abandoned`, so that status still needs the topic / placeholder /+ // hook side effects below β otherwise the row retires while the turn keeps+ // loading.+ const preClaimed = settledAsAbandoned === true && op?.status === 'abandoned';+ if (+ !op ||+ (!preClaimed &&+ !['running', 'waiting_for_human', 'waiting_for_async_tool'].includes(op.status))+ ) {return;}@@ -380,24 +397,27 @@ export class AbandonOperationService {type: AgentRuntimeErrorType.AgentRuntimeError,};- try {- await new AgentOperationModel(- this.db,- op.userId,- op.workspaceId ?? undefined,- ).recordCompletion(operationId, {- completedAt: new Date(),- completionReason: 'error',- error: { message, type: String(error.type) },- llmCalls: 0,- processingTimeMs: op.startedAt ? Date.now() - new Date(op.startedAt).getTime() : null,- status: 'error',- stepCount: 0,- toolCalls: 0,- totalTokens: 0,- });- } catch (e) {- log('[%s] no-state abandon: recordCompletion failed (non-fatal): %O', operationId, e);+ // The pre-claim already wrote the terminal row; do not overwrite it.+ if (!preClaimed) {+ try {+ await new AgentOperationModel(+ this.db,+ op.userId,+ op.workspaceId ?? undefined,+ ).recordCompletion(operationId, {+ completedAt: new Date(),+ completionReason: 'error',+ error: { message, type: String(error.type) },+ llmCalls: 0,+ processingTimeMs: op.startedAt ? Date.now() - new Date(op.startedAt).getTime() : null,+ status: 'error',+ stepCount: 0,+ toolCalls: 0,+ totalTokens: 0,+ });+ } catch (e) {+ log('[%s] no-state abandon: recordCompletion failed (non-fatal): %O', operationId, e);+ }}const settled = await this.settleOperationTopic(op, operationId);@@ -453,7 +473,11 @@ export class AbandonOperationService {userId: op.userId,},'error',- { skipErrorMessageWrite: true },+ // Persist onto the pre-claimed `abandoned` row instead of being refused+ // as a conflicting terminal owner, which would skip the hooks.+ preClaimed+ ? { settledAsAbandoned: true, skipErrorMessageWrite: true }+ : { skipErrorMessageWrite: true },);} catch (e) {log('[%s] no-state abandon: lifecycle dispatch failed (non-fatal): %O', operationId, e);diff --git a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.tsindex 84246bbce2f..d71cd5db69c 100644--- a/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/AbandonOperationService.test.ts@@ -44,13 +44,13 @@ vi.mock('@/database/models/message', () => ({const findOperationMock = vi.fn().mockResolvedValue(null);const recordCompletionMock = vi.fn().mockResolvedValue(undefined);-const settleRunningMock = vi.fn().mockResolvedValue(true);+const settleLiveMock = vi.fn().mockResolvedValue(true);vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn().mockImplementation(function () {return {findById: findOperationMock,recordCompletion: recordCompletionMock,- settleRunning: settleRunningMock,+ settleLive: settleLiveMock,};}),}));@@ -126,7 +126,7 @@ describe('AbandonOperationService', () => {findOperationMock.mockReset().mockResolvedValue(null);recordCompletionMock.mockClear();findThreadMock.mockReset().mockResolvedValue(null);- settleRunningMock.mockReset().mockResolvedValue(true);+ settleLiveMock.mockReset().mockResolvedValue(true);latestSpineMessageIdMock.mockReset().mockResolvedValue(undefined);messageCreateMock.mockReset().mockResolvedValue({ id: 'msg_new_failure' });topicSettleRunningOperationMock@@ -293,6 +293,59 @@ describe('AbandonOperationService', () => {});});+ describe('no-state row pre-claimed by the caller', () => {+ // Regression (LOBE-14161): runStep claims the expired lease with+ // `settleStaleRunning` (row β `abandoned`) before abandoning. With both+ // state and metadata gone, the no-state guard used to accept only live+ // statuses, so the row retired while the turn kept loading.+ const abandonedRow = {+ agentId: 'agt_x',+ id: 'op_x',+ metadata: { _hooks: [{ id: 'h1', type: 'onComplete', webhook: { url: '/hook' } }] },+ startedAt: new Date('2026-09-24T17:30:02.000Z'),+ status: 'abandoned',+ topicId: 'tpc_x',+ userId: 'user_x',+ workspaceId: 'ws_x',+ };+ const abandon = (options?: { settledAsAbandoned?: boolean }) =>+ new AbandonOperationService(buildDb({ operationRow: abandonedRow }), {+ coordinator: buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) }) as any,+ snapshotStore: buildStore() as any,+ }).finalizeAbandoned('op_x', 'operation_metadata_missing', options);++ it('still settles the topic, errors the placeholder and fires hooks', async () => {+ topicSettleRunningOperationMock.mockResolvedValue({+ assistantMessageId: 'msg_assist_1',+ status: 'settled',+ });++ const result = await abandon({ settledAsAbandoned: true });++ expect(result).toMatchObject({ abandoned: true, assistantMessageUpdated: true });+ expect(recordCompletionMock).not.toHaveBeenCalled();+ expect(topicSettleRunningOperationMock).toHaveBeenCalledWith('tpc_x', 'op_x');+ expect(messageUpdateMock).toHaveBeenCalledWith('msg_assist_1', {+ content: '',+ error: expect.objectContaining({+ message: expect.stringContaining('operation_metadata_missing'),+ }),+ });+ expect(completeOperationMock).toHaveBeenCalledWith(expect.anything(), 'error', {+ settledAsAbandoned: true,+ skipErrorMessageWrite: true,+ });+ });++ it('leaves an abandoned row alone without the pre-claim flag', async () => {+ const result = await abandon();++ expect(result.abandoned).toBeUndefined();+ expect(topicSettleRunningOperationMock).not.toHaveBeenCalled();+ expect(messageUpdateMock).not.toHaveBeenCalled();+ });+ });+it('keeps no-state terminal operations classified as completed phantom timeouts', async () => {const coord = buildCoordinator({ loadAgentState: vi.fn().mockResolvedValue(null) });const store = buildStore();@@ -847,7 +900,7 @@ describe('AbandonOperationService', () => {snapshotStore: store as any,}).finalizeAbandoned('op_x', 'inactivity_watchdog');- expect(settleRunningMock).toHaveBeenCalledWith('op_x', 'error');+ expect(settleLiveMock).toHaveBeenCalledWith('op_x', 'error');});it('still settles the durable row when the lifecycle dispatch is skipped', async () => {@@ -864,7 +917,29 @@ describe('AbandonOperationService', () => {}).finalizeAbandoned('op_idle', 'stale_lease');expect(dispatchHooksMock).not.toHaveBeenCalled();- expect(settleRunningMock).toHaveBeenCalledWith('op_idle', 'error');+ expect(settleLiveMock).toHaveBeenCalledWith('op_idle', 'error');+ });++ it('settles a parked sub-agent row that the lifecycle dispatch skips', async () => {+ // Regression (LOBE-14161): a sub-agent child parked on its own nested call+ // skips `dispatchHooks`, and a `running`-only safety net left its row in+ // `waiting_for_async_tool` forever.+ const coord = buildCoordinator({+ loadAgentState: vi.fn().mockResolvedValue(+ stateWith({+ origin: { lineage: { isSubAgent: true }, topicId: 'tpc_x', userId: 'user_x' },+ status: 'waiting_for_async_tool',+ }),+ ),+ });++ await new AbandonOperationService(buildDb(), {+ coordinator: coord as any,+ snapshotStore: buildPartiallessStore() as any,+ }).finalizeAbandoned('op_parked_child', 'inactivity_watchdog');++ expect(dispatchHooksMock).not.toHaveBeenCalled();+ expect(settleLiveMock).toHaveBeenCalledWith('op_parked_child', 'error');});it('creates an assistant failure row when the dying step never made a placeholder', async () => {@@ -928,7 +1003,7 @@ describe('AbandonOperationService', () => {expect(messageCreateMock).not.toHaveBeenCalled();expect(result.assistantMessageUpdated).toBe(false);// The durable row still settles, so the run is not left running.- expect(settleRunningMock).toHaveBeenCalledWith('op_no_placeholder', 'error');+ expect(settleLiveMock).toHaveBeenCalledWith('op_no_placeholder', 'error');});it('marks the existing placeholder rather than creating a row when the step made one', async () => {diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.tsindex 927b763a767..bae29a119bd 100644--- a/packages/database/src/models/__tests__/agentOperation.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.test.ts@@ -610,6 +610,60 @@ describe('AgentOperationModel', () => {});});+ describe('settleLive', () => {+ it('retires running and parked rows but never rewrites a terminal one', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId: 'op-live-running' });+ await model.recordStart({ operationId: 'op-live-human' });+ await model.recordCompletion('op-live-human', {+ completionReason: 'waiting_for_human',+ status: 'waiting_for_human',+ });+ await model.recordStart({ operationId: 'op-live-async' });+ await model.recordCompletion('op-live-async', {+ completionReason: 'waiting_for_async_tool',+ status: 'waiting_for_async_tool',+ });+ await model.recordStart({ operationId: 'op-live-done' });+ await model.settleRunning('op-live-done', 'done');++ expect(await model.settleLive('op-live-running', 'error')).toBe(true);+ expect(await model.settleLive('op-live-human', 'error')).toBe(true);+ expect(await model.settleLive('op-live-async', 'error')).toBe(true);+ expect(await model.settleLive('op-live-done', 'error')).toBe(false);++ for (const id of ['op-live-running', 'op-live-human', 'op-live-async']) {+ expect(await model.findById(id)).toMatchObject({+ completionReason: 'error',+ status: 'error',+ });+ }+ expect((await model.findById('op-live-done'))?.status).toBe('done');+ });++ it('leaves parked rows alone through settleRunning', async () => {+ const model = new AgentOperationModel(serverDB, userId);+ await model.recordStart({ operationId: 'op-parked-kept' });+ await model.recordCompletion('op-parked-kept', {+ completionReason: 'waiting_for_human',+ status: 'waiting_for_human',+ });++ expect(await model.settleRunning('op-parked-kept', 'error')).toBe(false);+ expect((await model.findById('op-parked-kept'))?.status).toBe('waiting_for_human');+ });++ it("does not settle another user's row", async () => {+ await new AgentOperationModel(serverDB, userId).recordStart({+ operationId: 'op-live-foreign',+ });++ expect(+ await new AgentOperationModel(serverDB, otherUserId).settleLive('op-live-foreign', 'error'),+ ).toBe(false);+ });+ });+describe('claimStaleRedrive', () => {const makeStale = async (operationId: string) =>serverDBdiff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.tsindex 18f252d885e..a9a31660827 100644--- a/packages/database/src/models/agentOperation.ts+++ b/packages/database/src/models/agentOperation.ts@@ -350,6 +350,31 @@ export class AgentOperationModel {async settleRunning(operationId: string,status: 'done' | 'error' | 'interrupted',+ ): Promise<boolean> {+ return this.settleFrom(operationId, status, ['running']);+ }++ /**+ * Like {@link settleRunning}, but also retires a row parked in+ * `waiting_for_human` / `waiting_for_async_tool`. For callers that already+ * know the run is dead: a parked row whose runtime was abandoned has nothing+ * left that could ever resume it.+ */+ async settleLive(+ operationId: string,+ status: 'done' | 'error' | 'interrupted',+ ): Promise<boolean> {+ return this.settleFrom(operationId, status, [+ 'running',+ 'waiting_for_human',+ 'waiting_for_async_tool',+ ]);+ }++ private async settleFrom(+ operationId: string,+ status: 'done' | 'error' | 'interrupted',+ fromStatuses: AgentOperationStatus[],): Promise<boolean> {const [row] = await this.db.update(agentOperations)@@ -361,7 +386,7 @@ export class AgentOperationModel {.where(and(eq(agentOperations.id, operationId),- eq(agentOperations.status, 'running'),+ inArray(agentOperations.status, fromStatuses),this.ownership(),),)