🤯 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): close sub-agent threads when their run ends in queue mode (#22606)
Arvin Xu013dd6b01a91
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.tsindex d3d8efe27aa..66e8d2db590 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts@@ -27,7 +27,7 @@ import {} from './intervention';import { buildLifecycleEvent, extractErrorMessage } from './lifecycleEvent';import { extractOutboundAttachments, extractTextFromMessageContent } from './messageContent';-import { persistCompletion } from './persistence';+import { persistCompletion, settleRunThread } from './persistence';import { recallUserOnCompletion } from './recall';import { emitSignalEvents, isAgentShareRun } from './signals';import type {@@ -399,6 +399,9 @@ export class CompletionLifecycle {if (isAsyncToolPark) return;+ // Before the hooks, so a parent resumed by the bridge reads a closed thread.+ await settleRunThread(this.deps(), operationId, state, reason);+// The run tree no longer works, so its concurrency slot frees now rather// than when the lease lapses. A run parked on a human decision frees it// too; its continuation takes a slot of its own.diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.threadSettlement.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.threadSettlement.test.tsnew file mode 100644index 00000000000..cd4b9d782fe--- /dev/null+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.threadSettlement.test.ts@@ -0,0 +1,129 @@+// @vitest-environment node+import { ThreadStatus } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { settleRunThread } from './persistence';++const { mockFindById, mockSettleRun } = vi.hoisted(() => ({+ mockFindById: vi.fn(),+ mockSettleRun: vi.fn(),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn(function () {+ return { findById: mockFindById, settleRun: mockSettleRun };+ }),+}));++const deps = { serverDB: {}, userId: 'user-1' } as any;+const origin = { threadId: 'thd-1', userId: 'user-1' };++describe('settleRunThread', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockFindById.mockResolvedValue({+ metadata: {+ operationId: 'op-1',+ sourceToolCallId: 'call-1',+ runUsageBaseline: { totalTokens: 100 },+ startedAt: '2026-10-01T00:00:00.000Z',+ totalTokens: 130,+ },+ });+ mockSettleRun.mockResolvedValue(true);+ });++ it.each([+ ['done', ThreadStatus.Completed],+ ['max_steps', ThreadStatus.Completed],+ ['error', ThreadStatus.Failed],+ ['interrupted', ThreadStatus.Cancel],+ ])('maps %s to %s', async (reason, status) => {+ await settleRunThread(deps, 'op-1', { origin }, reason);++ expect(mockSettleRun).toHaveBeenCalledWith(+ 'thd-1',+ 'op-1',+ expect.objectContaining({ status }),+ );+ });++ it('keeps earlier metadata and adds this run on top of earlier usage', async () => {+ await settleRunThread(+ deps,+ 'op-1',+ { origin, usage: { llm: { tokens: { total: 50 } } } },+ 'done',+ );++ expect(mockSettleRun.mock.calls[0][2].metadata).toMatchObject({+ completedAt: expect.any(String),+ operationId: 'op-1',+ sourceToolCallId: 'call-1',+ startedAt: '2026-10-01T00:00:00.000Z',+ totalTokens: 150,+ });+ });++ it('ignores usage that polling wrote for the same run', async () => {+ mockFindById.mockResolvedValue({+ metadata: { operationId: 'op-1', startedAt: '2026-10-01T00:00:00.000Z', totalTokens: 100 },+ });++ await settleRunThread(+ deps,+ 'op-1',+ { origin, usage: { llm: { tokens: { total: 150 } } } },+ 'done',+ );++ expect(mockSettleRun.mock.calls[0][2].metadata.totalTokens).toBe(150);+ });++ it('settles a run that ends before its operation id is written', async () => {+ mockFindById.mockResolvedValue({ metadata: { startedAt: '2026-10-01T00:00:00.000Z' } });++ await settleRunThread(deps, 'op-1', { createdAt: '2026-10-01T00:00:01.000Z', origin }, 'done');++ expect(mockSettleRun).toHaveBeenCalled();+ });++ it('does not settle a follow-up claim that started after this run', async () => {+ mockFindById.mockResolvedValue({ metadata: { startedAt: '2026-10-01T00:05:00.000Z' } });++ await settleRunThread(deps, 'op-1', { createdAt: '2026-10-01T00:00:01.000Z', origin }, 'done');++ expect(mockSettleRun).not.toHaveBeenCalled();+ });++ it('does not settle a thread owned by another run', async () => {+ mockFindById.mockResolvedValue({+ metadata: { operationId: 'op-2', startedAt: '2026-10-01T00:00:00.000Z' },+ });++ await settleRunThread(deps, 'op-1', { origin }, 'done');++ expect(mockSettleRun).not.toHaveBeenCalled();+ });++ it('records the run error on the thread', async () => {+ await settleRunThread(deps, 'op-1', { error: new Error('boom'), origin }, 'error');++ expect(mockSettleRun.mock.calls[0][2].metadata.error).toMatchObject({ message: 'boom' });+ });++ it('skips runs without a thread and runs parked for approval', async () => {+ await settleRunThread(deps, 'op-1', { origin: {} }, 'done');+ await settleRunThread(deps, 'op-1', { origin }, 'waiting_for_human');++ expect(mockFindById).not.toHaveBeenCalled();+ });++ it('does not throw when the thread write fails', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ mockSettleRun.mockRejectedValue(new Error('db down'));++ await expect(settleRunThread(deps, 'op-1', { origin }, 'done')).resolves.toBeUndefined();+ consoleError.mockRestore();+ });+});diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.tsindex 9a63761e784..9114f7d69e9 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/persistence.ts@@ -3,14 +3,16 @@* running mark, and the topic usage rollup.*/import { getLlmCallCount, isParkedStatus } from '@lobechat/agent-runtime';-import { type AgentOperationStatus, isAgentOperationInFlight } from '@lobechat/types';+import { type AgentOperationStatus, isAgentOperationInFlight, ThreadStatus } from '@lobechat/types';import debug from 'debug';import type { ChildUsageRollup } from '@/database/models/agentOperation';+import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';import { recomputeTopicUsage } from '@/database/models/topicUsage';import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';+import { formatErrorForMetadata } from '../AgentRuntimeService/utils';import type { CompletionLifecycleDeps } from './types';const log = debug('lobe-server:completion-lifecycle');@@ -66,6 +68,75 @@ export function statusForReason(}}+const addUsage = (earlier?: number, run?: number): number | undefined =>+ earlier === undefined ? run : earlier + (run ?? 0);++const threadStatusForReason = (reason: string): ThreadStatus => {+ if (reason === 'error') return ThreadStatus.Failed;+ if (reason === 'interrupted') return ThreadStatus.Cancel;+ return ThreadStatus.Completed;+};++/**+ * Close the isolation thread of a run that reached its end.+ *+ * The in-memory thread hooks never run in queue mode, so without this write the+ * thread stays `processing` and its task card spins forever. A run parked for+ * approval is not over and keeps its thread open. Best-effort: a failed write+ * must not cost the run its completion hooks.+ */+export async function settleRunThread(+ deps: CompletionLifecycleDeps,+ operationId: string,+ state: any,+ reason: string,+): Promise<void> {+ const threadId = state?.origin?.threadId;+ if (!threadId || reason === 'waiting_for_human') return;++ try {+ const threadModel = new ThreadModel(+ deps.serverDB,+ state.origin.userId || deps.userId,+ deps.workspaceId,+ );+ const thread = await threadModel.findById(threadId);+ if (!thread) return;++ const metadata = thread.metadata ?? {};+ const startedAt = metadata.startedAt;++ // A claim clears the operation id until the new run has one. An empty id+ // only belongs to this run if the run began after the thread was claimed.+ const ownsThread = metadata.operationId+ ? metadata.operationId === operationId+ : !!startedAt && !!state.createdAt && new Date(state.createdAt) >= new Date(startedAt);+ if (!ownsThread) return;++ const baseline = metadata.runUsageBaseline ?? {};+ const llmCalls = getLlmCallCount(state);++ await threadModel.settleRun(threadId, operationId, {+ metadata: {+ ...metadata,+ completedAt: new Date().toISOString(),+ duration: startedAt ? Date.now() - new Date(startedAt).getTime() : undefined,+ error: formatErrorForMetadata(state.error),+ operationId,+ totalCost: addUsage(baseline.totalCost, state.cost?.total),+ totalLlmCalls: addUsage(baseline.totalLlmCalls, llmCalls),+ totalMessages: state.messages?.length ?? metadata.totalMessages,+ totalSteps: addUsage(baseline.totalLlmCalls, llmCalls),+ totalTokens: addUsage(baseline.totalTokens, state.usage?.llm?.tokens?.total),+ totalToolCalls: addUsage(baseline.totalToolCalls, state.usage?.tools?.totalCalls),+ },+ status: threadStatusForReason(reason),+ });+ } catch (error) {+ console.error('[CompletionLifecycle] settleRunThread failed', { error, operationId, threadId });+ }+}+/*** Persist terminal state to `agent_operations`. Fire-and-forget: a DB* outage must never block hook dispatch or the executor's terminaldiff --git a/apps/server/src/services/aiAgent/__tests__/execGroupMember.test.ts b/apps/server/src/services/aiAgent/__tests__/execGroupMember.test.tsindex f7c8696af78..5bf6de3f8f2 100644--- a/apps/server/src/services/aiAgent/__tests__/execGroupMember.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execGroupMember.test.ts@@ -14,6 +14,7 @@ vi.mock('@/libs/trusted-client', () => ({// Mock ThreadModelconst mockThreadModel = {+ attachRunOperation: vi.fn(),claimForRun: vi.fn(),create: vi.fn(),findById: vi.fn(),diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.tsindex a494f8b5ba3..4fbf30a02b5 100644--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts@@ -13,6 +13,7 @@ vi.mock('@/libs/trusted-client', () => ({// Mock ThreadModelconst mockThreadModel = {+ attachRunOperation: vi.fn(),claimForRun: vi.fn(),create: vi.fn(),findById: vi.fn(),@@ -345,8 +346,9 @@ describe('AiAgentService.execSubAgent', () => {await service.execSubAgent(createSubAgentParams());// Second update call should be storing operationId and startedAt in metadata- expect(mockThreadModel.update).toHaveBeenCalledWith('thread-123', {- metadata: { operationId: 'op-123', startedAt: expect.any(String) },+ expect(mockThreadModel.attachRunOperation).toHaveBeenCalledWith('thread-123', {+ operationId: 'op-123',+ startedAt: expect.any(String),});});@@ -522,7 +524,7 @@ describe('AiAgentService.execSubAgent', () => {expect(mockThreadModel.claimForRun).toHaveBeenCalledWith('thread-old',{ operationId: 'op-old', status: ThreadStatus.Failed },- { startedAt: expect.any(String) },+ { runUsageBaseline: {}, startedAt: expect.any(String) },);expect(execAgentSpy).toHaveBeenCalledWith(expect.objectContaining({@@ -655,9 +657,10 @@ describe('AiAgentService.execSubAgent', () => {expect.anything(),expect.objectContaining(carried),);- expect(mockThreadModel.update).toHaveBeenCalledWith('thread-old', {- metadata: expect.objectContaining({ ...carried, operationId: 'op-new' }),- });+ expect(mockThreadModel.attachRunOperation).toHaveBeenCalledWith(+ 'thread-old',+ expect.objectContaining({ ...carried, operationId: 'op-new' }),+ );const completion = execAgentSpy.mock.calls[0][0].hooks?.find((h) => h.id === 'thread-completion',diff --git a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts b/apps/server/src/services/aiAgent/hooks/threadRunHooks.tsindex 77e512eb28d..66a097b4638 100644--- a/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts+++ b/apps/server/src/services/aiAgent/hooks/threadRunHooks.ts@@ -33,6 +33,7 @@ export function calculateTotalTokens(usage?: AgentState['usage']): number | unde*/export type ThreadCarryOver = Pick<ThreadMetadata,+ | 'runUsageBaseline'| 'sourceToolCallId'| 'totalCost'| 'totalLlmCalls'@@ -42,6 +43,12 @@ export type ThreadCarryOver = Pick<>;export const pickThreadCarryOver = (metadata?: ThreadMetadata | null): ThreadCarryOver => ({+ runUsageBaseline: {+ totalCost: metadata?.totalCost,+ totalLlmCalls: metadata?.totalLlmCalls,+ totalTokens: metadata?.totalTokens,+ totalToolCalls: metadata?.totalToolCalls,+ },sourceToolCallId: metadata?.sourceToolCallId,totalCost: metadata?.totalCost,totalMessages: metadata?.totalMessages,diff --git a/apps/server/src/services/aiAgent/subAgentRuns.ts b/apps/server/src/services/aiAgent/subAgentRuns.tsindex 4bd7348c064..08b3a086f35 100644--- a/apps/server/src/services/aiAgent/subAgentRuns.ts+++ b/apps/server/src/services/aiAgent/subAgentRuns.ts@@ -427,8 +427,10 @@ export const execAgentThreadRun = async ();// 5. Store operationId in Thread metadata- await deps.threadModel.update(thread.id, {- metadata: { ...carryOver, operationId: result.operationId, startedAt },+ await deps.threadModel.attachRunOperation(thread.id, {+ ...carryOver,+ operationId: result.operationId,+ startedAt,});// 6. If operation failed to start, update thread statusdiff --git a/packages/database/src/models/__tests__/thread.coverage.test.ts b/packages/database/src/models/__tests__/thread.coverage.test.tsindex 38fec9315bf..08b9885334c 100644--- a/packages/database/src/models/__tests__/thread.coverage.test.ts+++ b/packages/database/src/models/__tests__/thread.coverage.test.ts@@ -28,6 +28,92 @@ afterEach(async () => {const findThread = (id: string) => serverDB.query.threads.findFirst({ where: eq(threads.id, id) });describe('ThreadModel coverage', () => {+ describe('attachRunOperation', () => {+ const insertThread = (id: string, status: ThreadStatus) =>+ serverDB.insert(threads).values({+ id,+ metadata: { completedAt: '2026-10-01T00:01:00.000Z', totalTokens: 15 },+ status,+ topicId,+ type: ThreadType.Isolation,+ userId,+ });++ it('records the operation id on a processing thread', async () => {+ await insertThread('thread-attach-live', ThreadStatus.Processing);++ await threadModel.attachRunOperation('thread-attach-live', { operationId: 'op-1' });++ expect((await findThread('thread-attach-live'))?.metadata).toEqual({ operationId: 'op-1' });+ });++ it('keeps the metadata of a run that already settled', async () => {+ await insertThread('thread-attach-settled', ThreadStatus.Completed);++ await threadModel.attachRunOperation('thread-attach-settled', { operationId: 'op-1' });++ expect((await findThread('thread-attach-settled'))?.metadata).toMatchObject({+ completedAt: '2026-10-01T00:01:00.000Z',+ totalTokens: 15,+ });+ });+ });++ describe('settleRun', () => {+ const insertThread = (id: string, status: ThreadStatus, operationId?: string) =>+ serverDB.insert(threads).values({+ id,+ metadata: { operationId, startedAt: '2026-10-01T00:00:00.000Z' },+ status,+ topicId,+ type: ThreadType.Isolation,+ userId,+ });+ const value = {+ metadata: {+ completedAt: '2026-10-01T00:01:00.000Z',+ operationId: 'op-1',+ startedAt: '2026-10-01T00:00:00.000Z',+ },+ status: ThreadStatus.Completed,+ };++ it('settles a processing thread owned by the run', async () => {+ await insertThread('thread-settle-own', ThreadStatus.Processing, 'op-1');++ expect(await threadModel.settleRun('thread-settle-own', 'op-1', value)).toBe(true);+ expect(await findThread('thread-settle-own')).toMatchObject(value);+ });++ it('settles a processing thread whose operation id is not written yet', async () => {+ await insertThread('thread-settle-early', ThreadStatus.Processing);++ expect(await threadModel.settleRun('thread-settle-early', 'op-1', value)).toBe(true);+ });++ it('leaves a thread claimed by a later run open', async () => {+ await insertThread('thread-settle-later', ThreadStatus.Processing, 'op-2');++ expect(await threadModel.settleRun('thread-settle-later', 'op-1', value)).toBe(false);+ expect((await findThread('thread-settle-later'))?.status).toBe(ThreadStatus.Processing);+ });++ it('refuses when a follow-up claimed the thread after the caller read it', async () => {+ await insertThread('thread-settle-claimed', ThreadStatus.Processing);++ const stale = { ...value, metadata: { ...value.metadata, startedAt: 'earlier-claim' } };+ expect(await threadModel.settleRun('thread-settle-claimed', 'op-1', stale)).toBe(false);+ expect((await findThread('thread-settle-claimed'))?.status).toBe(ThreadStatus.Processing);+ });++ it('does not overwrite a thread that is no longer processing', async () => {+ await insertThread('thread-settle-cancelled', ThreadStatus.Cancel, 'op-1');++ expect(await threadModel.settleRun('thread-settle-cancelled', 'op-1', value)).toBe(false);+ expect((await findThread('thread-settle-cancelled'))?.status).toBe(ThreadStatus.Cancel);+ });+ });+describe('claimForRun', () => {it('claims a thread that has no status yet when no status is expected', async () => {await serverDB.insert(threads).values({diff --git a/packages/database/src/models/thread.ts b/packages/database/src/models/thread.tsindex af16cfe0b1a..d4b148d7492 100644--- a/packages/database/src/models/thread.ts+++ b/packages/database/src/models/thread.ts@@ -203,6 +203,52 @@ export class ThreadModel {return rows.length > 0;};+ /**+ * Record the operation id of a run that just started. The run is scheduled+ * before its id is known here, so it may already have settled the thread;+ * that metadata holds its final usage and error and must not be replaced.+ */+ attachRunOperation = async (id: string, metadata: ThreadMetadata) => {+ return this.db+ .update(threads)+ .set({ metadata, updatedAt: new Date() })+ .where(+ and(eq(threads.id, id), this.ownership(), eq(threads.status, ThreadStatus.Processing)),+ );+ };++ /**+ * Compare-and-set a `processing` thread into the terminal status of its run.+ *+ * `value.metadata.startedAt` must be the value the caller read: every claim+ * rewrites it, so an earlier run cannot close a follow-up that claimed the+ * thread after that read. The operation id is written after the run starts,+ * so it may still be empty; the caller decides whether an empty id is its own.+ *+ * @returns whether this caller settled the thread+ */+ settleRun = async (+ id: string,+ operationId: string,+ value: { metadata: ThreadMetadata; status: ThreadStatus },+ ): Promise<boolean> => {+ const rows = await this.db+ .update(threads)+ .set({ ...value, updatedAt: new Date() })+ .where(+ and(+ eq(threads.id, id),+ this.ownership(),+ eq(threads.status, ThreadStatus.Processing),+ sql`COALESCE(${threads.metadata} ->> 'operationId', '') IN ('', ${operationId})`,+ sql`COALESCE(${threads.metadata} ->> 'startedAt', '') = ${value.metadata.startedAt ?? ''}`,+ ),+ )+ .returning({ id: threads.id });++ return rows.length > 0;+ };+update = async (id: string, value: Partial<ThreadItem>) => {return this.db.update(threads)diff --git a/packages/types/src/topic/thread.ts b/packages/types/src/topic/thread.tsindex 6799d46d82c..fa85f34c457 100644--- a/packages/types/src/topic/thread.ts+++ b/packages/types/src/topic/thread.ts@@ -54,6 +54,15 @@ export interface ThreadMetadata {onboardingUnderstanding?: OnboardingUnderstandingThreadMarker;/** Operation ID for tracking */operationId?: string;+ /**+ * Usage of the runs before the current one, fixed when the run claims the+ * thread. The `total*` fields can't serve as this baseline: status polling+ * rewrites them while the run is live.+ */+ runUsageBaseline?: Pick<+ ThreadMetadata,+ 'totalCost' | 'totalLlmCalls' | 'totalTokens' | 'totalToolCalls'+ >;/*** The specific tool_use id within `sourceMessageId` that spawned this thread.* Used to position the thread inline as a `task` block within the parent