π€― 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(task): serialize task callback delivery (#17668)
Arvin Xu51e24a0e9a26
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex 3f4fdae68df..c6217918dfc 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -10,6 +10,21 @@ in feature specifications or historical field notes, not in this living checklis## Evidence and publication+### L-E5 β Treating historical branch rendering as proof that conversation can continue++**Wrong approach:** render a recovered historical `taskCallback` card beside the+active tool continuation, then call the message-loss regression verified without+sending another user message.++**Why it fails:** read-path recovery proves only that existing rows are visible.+The next user turn exercises a separate write/parent-selection path and can still+attach to the wrong branch, disappear after reconciliation, or vanish after reload.++**Correct approach:** for every conversation-branch regression, continue from the+fixture through the real composer. Assert the new user row in the database, its+parent on the active spine, its rendered presence before and after a cold reload,+and the resulting assistant continuation when the environment supports it.+### L-E1 β Publishing a replacement as a second Acceptance row**Wrong approach:** assign a replacement check a new id without `supersedes`, ordiff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 3c0c665b371..9ba78384c53 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -565,6 +565,21 @@ agent-browser --session "$RUN_SESSION" \Then assert `get url` and `app-probe.sh auth` on that exact session beforecapturing evidence.+### Agent-browser navigation hangs after an orphaned Next child keeps the port++**Situation:** an isolated full-stack dev launcher exits, but its Next child+continues listening without returning HTTP responses. `agent-browser open`,+`get url`, and even session close can then appear to hang because navigation+never settles.++**Doesn't work:** repeatedly recreating browser sessions or assuming the+browser daemon is the root cause while `curl --max-time` to the target route+also receives zero bytes.++**Works:** inspect the exact listener with `lsof`, confirm its command and+working tree, terminate only that run-owned process tree, then restart through+`init-dev-env.sh dev` and reseed the isolated browser auth. A successful HTTP+probe must precede browser assertions.### Leftover React Scan instrumentation poisons every screenshotdiff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.tsindex 5dcca47fa1f..2f6350ed419 100644--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts@@ -33,6 +33,7 @@ describe('aiChatRouter', () => {// spine head returned by the server-authoritative parentId resolution;// undefined keeps the client-provided parentId unchangedlatestSpineMessageId?: string,+ resolvedHeadDescendsFromClient = true,) => {const mockCreateUserAndAssistantMessages = vi.fn(async (@@ -62,6 +63,7 @@ describe('aiChatRouter', () => {createUserAndAssistantMessages: mockCreateUserAndAssistantMessages,// server-authoritative parentId resolution for existing-topic appendsgetLatestSpineMessageId: vi.fn().mockResolvedValue(latestSpineMessageId),+ isMessageDescendantOf: vi.fn().mockResolvedValue(resolvedHeadDescendsFromClient),}) as any,);@@ -272,6 +274,34 @@ describe('aiChatRouter', () => {);});+ it('should keep the client branch when the newest spine row belongs to a callback sibling', async () => {+ const mockCreateMessage = vi+ .fn()+ .mockResolvedValueOnce({ id: 'm-user' })+ .mockResolvedValueOnce({ id: 'm-assistant' });+ const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: undefined });++ mockMessageModel(mockCreateMessage, 'callback-branch-head', false);+ vi.mocked(AiChatService).mockImplementation(() => ({ getMessagesAndTopics: mockGet }) as any);++ const caller = aiChatRouter.createCaller(mockCtx as any);++ await caller.sendMessageInServer({+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },+ newUserMessage: { content: 'hi', parentId: 'active-main-head' },+ sessionId: 's1',+ topicId: 't1',+ } as any);++ expect(mockCreateMessage).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ parentId: 'active-main-head',+ role: 'user',+ }),+ );+ });+it('should keep the client parentId for a new thread (no server override)', async () => {const mockCreateMessage = vi.fn()diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.tsindex c6d52031691..8f9c55e1858 100644--- a/apps/server/src/routers/lambda/aiChat.ts+++ b/apps/server/src/routers/lambda/aiChat.ts@@ -337,7 +337,27 @@ export const aiChatRouter = router({() => ctx.messageModel.getLatestSpineMessageId({ threadId, topicId }),{ hasThreadId: !!threadId },);- parentId = resolvedParentId ?? parentId;+ if (!parentId) {+ parentId = resolvedParentId;+ } else if (resolvedParentId && resolvedParentId !== parentId) {+ // Advance a stale client tail only when the server head is on the+ // SAME branch. A historical taskCallback fork may contain a newer+ // assistant row on a sibling branch; blindly taking the newest row+ // attaches the user's next turn there and the UI drops it after+ // branch reconciliation.+ const advancesClientBranch = await runTimedStage(+ timingContext,+ 'lambda.aiChat.validateResolvedParentBranch',+ () =>+ ctx.messageModel.isMessageDescendantOf({+ ancestorId: parentId!,+ descendantId: resolvedParentId,+ topicId,+ }),+ { hasThreadId: !!threadId },+ );+ if (advancesClientBranch) parentId = resolvedParentId;+ }}if (input.preloadMessages?.length) {diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.tsindex d4ad663e616..2329946bfd9 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts@@ -110,6 +110,8 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.tsindex 2580973353a..a618fcf048f 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts@@ -77,6 +77,8 @@ vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: mockTopicCreate,findById: vi.fn().mockResolvedValue(undefined),+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),updateMetadata: vi.fn().mockResolvedValue(undefined),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.tsindex 1de3f6cdcd3..f17991cb63a 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts@@ -78,6 +78,8 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.tsindex c81aafea8da..cda6d260cd3 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts@@ -81,6 +81,8 @@ vi.mock('@/database/models/plugin', () => ({const topicMock = {create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),findById: vi.fn().mockResolvedValue(undefined),+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),updateMetadata: vi.fn().mockResolvedValue(undefined),};vi.mock('@/database/models/topic', () => ({diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.tsindex ab2c424aaca..cd0adfffeb5 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts@@ -95,6 +95,8 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.tsindex 829d59176d5..4e8ce10e857 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts@@ -76,6 +76,8 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.tsindex 8aaa5d5c91b..80debb47711 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts@@ -78,6 +78,8 @@ vi.mock('@/database/models/file', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.tsindex fcaf565faf1..0b5105ab591 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts@@ -46,6 +46,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.tsindex 6cd64e6058d..8778b02d55e 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts@@ -66,6 +66,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: mockTopicFindById,})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.tsindex 1d95b8b8b45..810bdffe262 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pinnedSkillContent.test.ts@@ -109,6 +109,8 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.tsindex 1a1a6c40048..ed2e6e21bfb 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts@@ -82,6 +82,8 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.tsindex 46e62fd4538..75823a235bf 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts@@ -58,6 +58,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex df585f7dd4f..b974d1599ad 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -72,6 +72,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),updateMetadata: vi.fn(),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.tsindex 508143061eb..9677b96525a 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts@@ -69,6 +69,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),updateMetadata: vi.fn(),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.tsindex 93516f3af86..5794720ec3e 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts@@ -3,12 +3,19 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';-const { mockGetLatestNonToolMessageId, mockGetLatestSpineMessageId, mockMessageCreate } =- vi.hoisted(() => ({- mockGetLatestNonToolMessageId: vi.fn(),- mockGetLatestSpineMessageId: vi.fn(),- mockMessageCreate: vi.fn(),- }));+const {+ mockGetLatestNonToolMessageId,+ mockGetLatestSpineMessageId,+ mockMessageCreate,+ mockReleaseReservation,+ mockTryReserve,+} = vi.hoisted(() => ({+ mockGetLatestNonToolMessageId: vi.fn(),+ mockGetLatestSpineMessageId: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockReleaseReservation: vi.fn(),+ mockTryReserve: vi.fn(),+}));vi.mock('@/libs/trusted-client', () => ({generateTrustedClientToken: vi.fn().mockReturnValue(undefined),@@ -67,6 +74,8 @@ vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(undefined),+ releaseTaskCallbackReservation: mockReleaseReservation,+ tryReserveTaskCallback: mockTryReserve,updateMetadata: vi.fn().mockResolvedValue(undefined),})),}));@@ -170,6 +179,8 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {}));mockGetLatestSpineMessageId.mockResolvedValue(undefined);mockGetLatestNonToolMessageId.mockResolvedValue(undefined);+ mockTryReserve.mockResolvedValue(true);+ mockReleaseReservation.mockResolvedValue(undefined);service = new AiAgentService(mockDb, 'test-user-id');});@@ -190,6 +201,11 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {expect(userMessageCall()![0]).toMatchObject({ parentId: 'spine-head-1', role: 'user' });// No spine candidate is missing, so the fallback must not be queried.expect(mockGetLatestNonToolMessageId).not.toHaveBeenCalled();+ expect(mockTryReserve).toHaveBeenCalledWith('topic-1', expect.stringMatching(/^agent-start-/));+ expect(mockReleaseReservation).toHaveBeenCalledWith(+ 'topic-1',+ expect.stringMatching(/^agent-start-/),+ );});it('falls back to the latest non-tool message when the topic has no spine candidate', async () => {diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.tsindex 4426d1b59f8..a964ccd847a 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.threadId.test.ts@@ -69,6 +69,8 @@ vi.mock('@/database/models/plugin', () => ({// Mock TopicModelvi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(undefined),updateMetadata: mockTopicUpdateMetadata,diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.tsindex bfe1711040e..06705acb37d 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts@@ -66,6 +66,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-new' }),findById: vi.fn().mockResolvedValue(undefined),updateMetadata: vi.fn().mockResolvedValue(undefined),diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.tsindex 9ba3f14a796..2c2567f5a82 100644--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts@@ -53,6 +53,8 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),create: vi.fn().mockResolvedValue({ id: 'topic-1' }),findById: vi.fn().mockResolvedValue(null),})),diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 2947b3758db..dbf7ce1d88d 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -186,6 +186,7 @@ import {resolveDeviceWorkingDirectoryConfig,} from './resolveDeviceWorkingDirectory';import { resolveServerSearchDecision } from './searchDecision';+import { acquireTopicStartReservation } from './topicStartReservation';import { isWorkspaceCacheFresh, upsertWorkspaceScan } from './workspaceInitCache';const log = debug('lobe-server:ai-agent-service');@@ -495,6 +496,11 @@ interface InternalExecAgentParams extends ExecAgentParams {* When undefined, falls back to prompt.slice(0, 50).*/title?: string;+ /**+ * Re-enter a topic-start reservation already acquired by an upstream caller,+ * such as TaskResultBridgeService.+ */+ topicStartReservationId?: string;/** Topic creation trigger source ('cron' | 'chat' | 'api' | 'task') */trigger?: string;/**@@ -1227,6 +1233,34 @@ export class AiAgentService {* β AgentRuntimeService.createOperation(...)*/async execAgent(params: InternalExecAgentParams): Promise<ExecAgentResult> {+ const topicId = params.appContext?.topicId;+ // Thread runs are isolated under an explicit parent message and do not+ // advance the topic's main spine. They may start while their parent+ // operation owns `runningOperation` (for example callAgent/callSubAgent),+ // so making them wait for the topic-start claim deadlocks the child start.+ if (!topicId || params.appContext?.threadId) return this.execAgentWithReservation(params);++ const reservationId = params.topicStartReservationId ?? `agent-start-${nanoid()}`;+ const reserved = await acquireTopicStartReservation({+ reservationId,+ topicId,+ topicModel: this.topicModel,+ });++ if (!reserved) {+ throw new Error(`Topic not found: ${topicId}`);+ }++ try {+ return await this.execAgentWithReservation(params);+ } finally {+ await this.topicModel.releaseTaskCallbackReservation(topicId, reservationId);+ }+ }++ private async execAgentWithReservation(+ params: InternalExecAgentParams,+ ): Promise<ExecAgentResult> {const {additionalPluginIds,agentId,diff --git a/apps/server/src/services/aiAgent/topicStartReservation.test.ts b/apps/server/src/services/aiAgent/topicStartReservation.test.tsnew file mode 100644index 00000000000..e47c8195117--- /dev/null+++ b/apps/server/src/services/aiAgent/topicStartReservation.test.ts@@ -0,0 +1,44 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { TopicModel } from '@/database/models/topic';++import { acquireTopicStartReservation } from './topicStartReservation';++describe('acquireTopicStartReservation', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('retries with bounded exponential backoff and then fails for workflow redelivery', async () => {+ vi.useFakeTimers();+ const tryReserveTaskCallback = vi.fn().mockResolvedValue(false);+ const topicModel = { tryReserveTaskCallback } as unknown as TopicModel;++ const reservation = acquireTopicStartReservation({+ reservationId: 'callback-1',+ topicId: 'topic-1',+ topicModel,+ });+ const expectation = expect(reservation).rejects.toThrow('Topic topic-1 remained busy');++ await vi.runAllTimersAsync();+ await expectation;++ expect(tryReserveTaskCallback).toHaveBeenCalledTimes(6);+ });++ it('returns false when the topic no longer exists', async () => {+ const topicModel = {+ tryReserveTaskCallback: vi.fn().mockResolvedValue(null),+ } as unknown as TopicModel;++ await expect(+ acquireTopicStartReservation({+ reservationId: 'callback-1',+ topicId: 'topic-1',+ topicModel,+ }),+ ).resolves.toBe(false);+ });+});diff --git a/apps/server/src/services/aiAgent/topicStartReservation.ts b/apps/server/src/services/aiAgent/topicStartReservation.tsnew file mode 100644index 00000000000..3ccd094d895--- /dev/null+++ b/apps/server/src/services/aiAgent/topicStartReservation.ts@@ -0,0 +1,42 @@+import type { TopicModel } from '@/database/models/topic';++const INITIAL_RETRY_DELAY_MS = 100;+const MAX_RETRY_DELAY_MS = 1600;+const MAX_RESERVATION_ATTEMPTS = 6;++const delay = (milliseconds: number): Promise<void> =>+ new Promise((resolve) => setTimeout(resolve, milliseconds));++/**+ * Claim the gap between choosing a conversation parent and publishing the+ * operation's `runningOperation` marker. Every existing-topic start uses the+ * same claim, so a foreground message and a task callback cannot both observe+ * the topic as idle and create competing continuations.+ *+ * The bounded backoff deliberately throws instead of holding a workflow+ * request indefinitely. QStash retries callback deliveries on the resulting+ * 500 response, while interactive callers receive a finite busy failure.+ */+export const acquireTopicStartReservation = async ({+ reservationId,+ topicId,+ topicModel,+}: {+ reservationId: string;+ topicId: string;+ topicModel: TopicModel;+}): Promise<boolean> => {+ for (let attempt = 0; attempt < MAX_RESERVATION_ATTEMPTS; attempt += 1) {+ const reservation = await topicModel.tryReserveTaskCallback(topicId, reservationId);++ if (reservation === null) return false;+ if (reservation) return true;++ if (attempt < MAX_RESERVATION_ATTEMPTS - 1) {+ const retryDelay = Math.min(INITIAL_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);+ await delay(retryDelay);+ }+ }++ throw new Error(`Topic ${topicId} remained busy while starting operation ${reservationId}`);+};diff --git a/apps/server/src/services/taskResultBridge/index.test.ts b/apps/server/src/services/taskResultBridge/index.test.tsindex 7b95cbd026b..592c5547746 100644--- a/apps/server/src/services/taskResultBridge/index.test.ts+++ b/apps/server/src/services/taskResultBridge/index.test.ts@@ -4,22 +4,32 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MessageModel } from '@/database/models/message';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';+import { TopicModel } from '@/database/models/topic';import { TaskResultBridgeService } from './index';// `MessageModel.create` is a class-field arrow (instance prop, not on the// prototype) and `AiAgentService`'s constructor builds many sub-services β mock// both modules so we observe the calls without standing up the real graph.-const { createMsg, execAgent, getLastLeaf } = vi.hoisted(() => ({+const { createMsg, execAgent, getLastLeaf, releaseReservation, tryReserve } = vi.hoisted(() => ({createMsg: vi.fn(),execAgent: vi.fn(),getLastLeaf: vi.fn(),+ releaseReservation: vi.fn(),+ tryReserve: vi.fn(),}));vi.mock('@/database/models/message', () => ({MessageModel: vi.fn(() => ({ create: createMsg, getLastMainThreadSpineMessageId: getLastLeaf })),}));+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn(() => ({+ releaseTaskCallbackReservation: releaseReservation,+ tryReserveTaskCallback: tryReserve,+ })),+}));+vi.mock('../aiAgent', () => ({AiAgentService: vi.fn(() => ({ execAgent })),}));@@ -54,6 +64,8 @@ describe('TaskResultBridgeService.deliver', () => {// The creator topic's current leaf at delivery time β the live tail of the// conversation, NOT origin.messageId (the stale create-task message).getLastLeaf.mockReset().mockResolvedValue('msg-current-leaf');+ tryReserve.mockReset().mockResolvedValue(true);+ releaseReservation.mockReset().mockResolvedValue(undefined);execAgent.mockReset().mockResolvedValue({ operationId: 'op-new', topicId: 'topic-origin' } as any);@@ -104,6 +116,7 @@ describe('TaskResultBridgeService.deliver', () => {parentMessageId: 'task-cb-task-1-topic-done',suppressUserMessage: true,});+ expect(releaseReservation).toHaveBeenCalledWith('topic-origin', 'task-cb-task-1-topic-done');});it('scopes the MessageModel to the bridge workspace so workspace tasks find their leaf', async () => {@@ -112,6 +125,7 @@ describe('TaskResultBridgeService.deliver', () => {// Personal-mode model (workspace_id IS NULL) would miss the team topic's// leaf and create the callback parentless β the lookup must be ws-scoped.expect(MessageModel).toHaveBeenCalledWith(db, TEST_USER, 'ws-1');+ expect(TopicModel).toHaveBeenCalledWith(db, TEST_USER, 'ws-1');});it('skips tasks with no origin (e.g. API-created)', async () => {@@ -123,6 +137,16 @@ describe('TaskResultBridgeService.deliver', () => {expect(execAgent).not.toHaveBeenCalled();});+ it('skips delivery when the origin topic was deleted', async () => {+ tryReserve.mockResolvedValue(null);++ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);++ expect(getLastLeaf).not.toHaveBeenCalled();+ expect(createMsg).not.toHaveBeenCalled();+ expect(execAgent).not.toHaveBeenCalled();+ });+it('is idempotent: a redelivered hook (duplicate PK) does not re-run the agent', async () => {createMsg.mockRejectedValueOnce(Object.assign(new Error('duplicate key value violates unique constraint'), { code: '23505' }),@@ -131,6 +155,68 @@ describe('TaskResultBridgeService.deliver', () => {await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);expect(execAgent).not.toHaveBeenCalled();+ expect(releaseReservation).toHaveBeenCalledTimes(1);+ });++ it('waits for the in-flight tool turn before resolving the callback parent', async () => {+ vi.useFakeTimers();+ try {+ tryReserve.mockResolvedValueOnce(false).mockResolvedValueOnce(true);++ const delivery = new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);+ await vi.waitFor(() => expect(tryReserve).toHaveBeenCalledTimes(1));++ expect(getLastLeaf).not.toHaveBeenCalled();+ expect(createMsg).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(100);+ await delivery;++ expect(tryReserve).toHaveBeenCalledTimes(2);+ expect(getLastLeaf).toHaveBeenCalledTimes(1);+ expect(createMsg.mock.calls[0][0]).toMatchObject({ parentId: 'msg-current-leaf' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps the reservation until the callback continuation is dispatched', async () => {+ let finishDispatch: (() => void) | undefined;+ execAgent.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishDispatch = () => resolve({ operationId: 'op-new', topicId: 'topic-origin' } as any);+ }),+ );++ const delivery = new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);+ await vi.waitFor(() => expect(execAgent).toHaveBeenCalledTimes(1));++ expect(releaseReservation).not.toHaveBeenCalled();++ finishDispatch?.();+ await delivery;++ expect(releaseReservation).toHaveBeenCalledTimes(1);+ });++ it('stops waiting after bounded retries so QStash can redeliver the callback', async () => {+ vi.useFakeTimers();+ try {+ tryReserve.mockResolvedValue(false);++ const delivery = new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);+ const expectation = expect(delivery).rejects.toThrow('Topic topic-origin remained busy');++ await vi.runAllTimersAsync();+ await expectation;++ expect(tryReserve).toHaveBeenCalledTimes(6);+ expect(createMsg).not.toHaveBeenCalled();+ expect(execAgent).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }});it('bridges a failed run with the error text and reason', async () => {diff --git a/apps/server/src/services/taskResultBridge/index.ts b/apps/server/src/services/taskResultBridge/index.tsindex 7cb9aeffc0d..15f4b6de7fb 100644--- a/apps/server/src/services/taskResultBridge/index.ts+++ b/apps/server/src/services/taskResultBridge/index.ts@@ -4,9 +4,11 @@ import debug from 'debug';import { MessageModel } from '@/database/models/message';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';+import { TopicModel } from '@/database/models/topic';import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '../aiAgent';+import { acquireTopicStartReservation } from '../aiAgent/topicStartReservation';const log = debug('lobe-server:taskResultBridge');@@ -144,50 +146,71 @@ export class TaskResultBridgeService {// ownership predicate β a personal-mode model (workspace_id IS NULL) finds// no leaf and the callback would be created parentless.const messageModel = new MessageModel(this.db, this.userId, this.workspaceId);-- // Anchor the callback on the creator topic's CURRENT leaf at delivery time β- // NOT origin.messageId (the assistant turn that called createTask). A task- // runs for minutes while the creator agent keeps talking, so origin.messageId- // is a stale mid-conversation node; parenting there forks a hidden sibling- // branch the linear UI never follows, so the user never sees the result- //- const parentId = await messageModel.getLastMainThreadSpineMessageId(origin.topicId);+ const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);++ // A callback can arrive while the creator is still finishing the tool+ // turn that spawned it. Reading the live leaf immediately is not enough:+ // both the callback and the later tool result would parent to the same+ // assistant shell and start competing continuations. Atomically wait for+ // the current run to clear, then reserve the topic so callback bursts are+ // delivered one at a time. `execAgent` installs `runningOperation` before+ // this reservation is released, making the next callback wait for this+ // continuation too.+ const reserved = await acquireTopicStartReservation({+ reservationId: messageId,+ topicId: origin.topicId,+ topicModel,+ });+ if (!reserved) {+ log('origin topic %s no longer exists, skipping bridge', origin.topicId);+ return;+ }try {- await messageModel.create(- {- agentId: origin.agentId,- content,- metadata: {- taskCallback: { identifier: taskIdentifier, reason, taskId, topicId },+ // Resolve the anchor only AFTER winning the idle-topic reservation. This+ // preserves the LOBE-10784 live-tail fix while closing the in-flight tool+ // continuation window described by LOBE-12497.+ const parentId = await messageModel.getLastMainThreadSpineMessageId(origin.topicId);++ try {+ await messageModel.create(+ {+ agentId: origin.agentId,+ content,+ metadata: {+ taskCallback: { identifier: taskIdentifier, reason, taskId, topicId },+ },+ parentId,+ role: 'taskCallback',+ topicId: origin.topicId,},- parentId,- role: 'taskCallback',- topicId: origin.topicId,- },- messageId,- );- } catch (error) {- if (isDuplicateKeyError(error)) {- log('task-callback %s already delivered, skipping', messageId);- return;+ messageId,+ );+ } catch (error) {+ if (isDuplicateKeyError(error)) {+ log('task-callback %s already delivered, skipping', messageId);+ return;+ }+ throw error;}- throw error;- }- // Run the creator agent off history (no new user turn): the context engine- // surfaces the task-callback card as a `<task_result>` user turn via- // TaskCallbackMessageProcessor, so the agent reads it and continues.- await new AiAgentService(this.db, this.userId, { workspaceId: this.workspaceId }).execAgent({- agentId: origin.agentId,- appContext: { topicId: origin.topicId },- autoStart: true,- parentMessageId: messageId,- prompt: `Task ${taskIdentifier} ${reason}`,- suppressUserMessage: true,- trigger: RequestTrigger.AgentSignal,- userInterventionConfig: { approvalMode: 'headless' },- });+ // Run the creator agent off history (no new user turn): the context engine+ // surfaces the task-callback card as a `<task_result>` user turn via+ // TaskCallbackMessageProcessor, so the agent reads it and continues.+ await new AiAgentService(this.db, this.userId, { workspaceId: this.workspaceId }).execAgent({+ agentId: origin.agentId,+ appContext: { topicId: origin.topicId },+ autoStart: true,+ parentMessageId: messageId,+ prompt: `Task ${taskIdentifier} ${reason}`,+ suppressUserMessage: true,+ topicStartReservationId: messageId,+ trigger: RequestTrigger.AgentSignal,+ userInterventionConfig: { approvalMode: 'headless' },+ });+ } finally {+ await topicModel.releaseTaskCallbackReservation(origin.topicId, messageId);+ }log('bridged task %s result into topic %s (%s)', taskIdentifier, origin.topicId, reason);}diff --git a/packages/conversation-flow/src/__tests__/taskCallback.test.ts b/packages/conversation-flow/src/__tests__/taskCallback.test.tsindex bbbc762a933..4e95b2d6036 100644--- a/packages/conversation-flow/src/__tests__/taskCallback.test.ts+++ b/packages/conversation-flow/src/__tests__/taskCallback.test.ts@@ -64,4 +64,155 @@ describe('parse β taskCallback role', () => {expect(result.flatList.find((m) => m.id === 'cb1')?.role).toBe('taskCallback');expect(ids).toContain('a2');});++ it('surfaces a historical callback that lost the active branch race to a tool result', () => {+ const messages = [+ {+ content: '',+ createdAt: 1,+ id: 'a1',+ role: 'assistant',+ tools: [{ apiName: 'createTasks', id: 'call-1', identifier: 'lobe-task', type: 'builtin' }],+ updatedAt: 1,+ },+ {+ content: '## task completed',+ createdAt: 2,+ id: 'cb1',+ metadata: callbackMeta,+ parentId: 'a1',+ role: 'taskCallback',+ updatedAt: 2,+ },+ {+ content: 'Started task',+ createdAt: 3,+ id: 'tool1',+ parentId: 'a1',+ role: 'tool',+ tool_call_id: 'call-1',+ updatedAt: 3,+ },+ {+ content: 'I will wait for it.',+ createdAt: 4,+ id: 'a2',+ parentId: 'tool1',+ role: 'assistant',+ updatedAt: 4,+ },+ ] as unknown as Message[];++ const result = parse(messages);++ expect(result.flatList.map((message) => message.id)).toContain('cb1');+ });++ it('recovers all five callback/tool forks observed in tpc_3d1xrMayXKgr', () => {+ // Minimal reconstruction of the five production forks recorded in the+ // tpc_VDwcmaHa889c diagnosis. Four callbacks arrived before their sibling+ // tool result; the final callback arrived after it.+ const forks = [+ {+ callbackAt: '2026-07-26T14:28:21.121494Z',+ callbackId: 'task-cb-task_vXPxOsdo8kh2-tpc_gEbmBIxxJWi7',+ parentId: 'msg_2TIuqKJ80pNWoAMntg',+ toolAt: '2026-07-26T14:28:21.907155Z',+ toolId: 'msg_yVceaOEGPrwAs7MhHL',+ },+ {+ callbackAt: '2026-07-26T14:30:45.153031Z',+ callbackId: 'task-cb-task_R05cJyUJ4jZR-tpc_CbBHlcROmoh9',+ parentId: 'msg_4GKeA5laiBJHqhW1nH',+ toolAt: '2026-07-26T14:30:55.573965Z',+ toolId: 'msg_DxDMVks6A8m6ikkPbu',+ },+ {+ callbackAt: '2026-07-26T14:33:47.251124Z',+ callbackId: 'task-cb-task_JCXs4oqUs8If-tpc_o2KxCzGsuPRX',+ parentId: 'msg_DzS8S4yNhfmDs2Yzx4',+ toolAt: '2026-07-26T14:34:10.561836Z',+ toolId: 'msg_x74KlUhS6zzzWV5knY',+ },+ {+ callbackAt: '2026-07-26T14:29:54.438458Z',+ callbackId: 'task-cb-task_Ydo3xJ6rV51k-tpc_Q6hqQyt4DPhp',+ parentId: 'msg_VAYHAoBKHnDN9r6rlY',+ toolAt: '2026-07-26T14:30:07.144843Z',+ toolId: 'msg_q8Fb5Mmt3SWZiVMBXq',+ },+ {+ callbackAt: '2026-07-26T14:33:45.877828Z',+ callbackId: 'task-cb-task_F7rB3xJ3dygO-tpc_lOotfzCHdayS',+ parentId: 'msg_yTQs1pQTNjvvDDZlSL',+ toolAt: '2026-07-26T14:33:44.387709Z',+ toolId: 'msg_5s1B3wzX6yhipH9nYT',+ },+ ];+ const messages = forks.flatMap((fork, index) => {+ const toolCallId = `call-${index}`;+ const parentAt = new Date(+ Math.min(new Date(fork.callbackAt).getTime(), new Date(fork.toolAt).getTime()) - 1000,+ ).toISOString();++ return [+ {+ content: '',+ createdAt: parentAt,+ id: fork.parentId,+ role: 'assistant',+ tools: [+ { apiName: 'queryTask', id: toolCallId, identifier: 'lobe-task', type: 'builtin' },+ ],+ updatedAt: parentAt,+ },+ {+ content: `Task callback ${index + 1}`,+ createdAt: fork.callbackAt,+ id: fork.callbackId,+ metadata: {+ taskCallback: {+ identifier: `T-${72 + index}`,+ reason: 'done',+ taskId: `task-${index}`,+ },+ },+ parentId: fork.parentId,+ role: 'taskCallback',+ updatedAt: fork.callbackAt,+ },+ {+ content: `Inactive callback continuation ${index + 1}`,+ createdAt: new Date(new Date(fork.callbackAt).getTime() + 50).toISOString(),+ id: `callback-assistant-${index}`,+ parentId: fork.callbackId,+ role: 'assistant',+ updatedAt: new Date(new Date(fork.callbackAt).getTime() + 50).toISOString(),+ },+ {+ content: `Tool result ${index + 1}`,+ createdAt: fork.toolAt,+ id: fork.toolId,+ parentId: fork.parentId,+ role: 'tool',+ tool_call_id: toolCallId,+ updatedAt: fork.toolAt,+ },+ {+ content: `Active tool continuation ${index + 1}`,+ createdAt: new Date(new Date(fork.toolAt).getTime() + 50).toISOString(),+ id: `tool-assistant-${index}`,+ parentId: fork.toolId,+ role: 'assistant',+ updatedAt: new Date(new Date(fork.toolAt).getTime() + 50).toISOString(),+ },+ ];+ }) as unknown as Message[];++ const result = parse(messages);+ const visibleIds = result.flatList.map((message) => message.id);++ expect(forks.every(({ callbackId }) => visibleIds.includes(callbackId))).toBe(true);+ expect(visibleIds.some((id) => id.startsWith('callback-assistant-'))).toBe(false);+ });});diff --git a/packages/conversation-flow/src/parse.ts b/packages/conversation-flow/src/parse.tsindex 69136fc0540..8ce61524f24 100644--- a/packages/conversation-flow/src/parse.ts+++ b/packages/conversation-flow/src/parse.ts@@ -143,9 +143,31 @@ export function parse(messages: Message[], messageGroups?: MessageGroupMetadata[return next;});+ // Historical LOBE-12497 data can contain a taskCallback and a tool result as+ // sibling branches under the same assistant tool-use shell. Normal branch+ // resolution must keep choosing one conversational continuation, but hiding+ // the inactive callback also hides the only user-visible record that a task+ // finished. Recover only those callback cards into the render list; do not+ // pull their assistant descendants across branches (they may contradict the+ // active continuation).+ const visibleIds = new Set(processedFlatList.map((message) => message.id));+ const recoveredFlatList = [...processedFlatList];+ const hiddenTaskCallbacks = processedMessages+ .filter((message) => message.role === 'taskCallback' && !visibleIds.has(message.id))+ .toSorted((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());++ for (const callback of hiddenTaskCallbacks) {+ const callbackTime = new Date(callback.createdAt).getTime();+ const insertAt = recoveredFlatList.findIndex(+ (message) => new Date(message.createdAt).getTime() > callbackTime,+ );+ if (insertAt === -1) recoveredFlatList.push(callback);+ else recoveredFlatList.splice(insertAt, 0, callback);+ }+return {contextTree,- flatList: processedFlatList,+ flatList: recoveredFlatList,messageMap: messageMapObj,};}diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 50de99f906c..b843f6e0dac 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -3297,6 +3297,63 @@ describe('MessageModel Query Tests', () => {});});+ describe('isMessageDescendantOf', () => {+ it('distinguishes a newer callback sibling from an advancement of the active branch', async () => {+ await serverDB.insert(sessions).values([{ id: 'session1', userId }]);+ await serverDB.insert(topics).values([{ id: 'topic1', sessionId: 'session1', userId }]);+ await serverDB.insert(messages).values([+ { id: 'shell', userId, topicId: 'topic1', role: 'assistant', content: '' },+ {+ id: 'tool',+ userId,+ topicId: 'topic1',+ role: 'tool',+ content: 'result',+ parentId: 'shell',+ },+ {+ id: 'active',+ userId,+ topicId: 'topic1',+ role: 'assistant',+ content: 'main',+ parentId: 'tool',+ },+ {+ id: 'callback',+ userId,+ topicId: 'topic1',+ role: 'taskCallback',+ content: 'done',+ parentId: 'shell',+ },+ {+ id: 'callback-reply',+ userId,+ topicId: 'topic1',+ role: 'assistant',+ content: 'reactive',+ parentId: 'callback',+ },+ ]);++ expect(+ await messageModel.isMessageDescendantOf({+ ancestorId: 'active',+ descendantId: 'callback-reply',+ topicId: 'topic1',+ }),+ ).toBe(false);+ expect(+ await messageModel.isMessageDescendantOf({+ ancestorId: 'callback',+ descendantId: 'callback-reply',+ topicId: 'topic1',+ }),+ ).toBe(true);+ });+ });+// Fallback anchor used when `getLatestSpineMessageId` comes back empty. Without// it a new user turn is persisted as a second root and the renderer emits the// newest reply above older messages.diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex ce2307e73ef..20b5e0f26aa 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -125,6 +125,84 @@ describe('TopicModel - Update', () => {});});+ describe('task callback reservation', () => {+ it('reserves only an idle topic and releases only the matching owner', async () => {+ const topicId = 'task-callback-reservation';+ await serverDB.insert(topics).values({ userId, id: topicId, title: 'Test' });++ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-1')).resolves.toBe(true);+ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-2')).resolves.toBe(false);++ await topicModel.releaseTaskCallbackReservation(topicId, 'callback-2');+ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-2')).resolves.toBe(false);++ await topicModel.releaseTaskCallbackReservation(topicId, 'callback-1');+ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-2')).resolves.toBe(true);+ });++ it('allows the reservation owner to re-enter the same topic-start claim', async () => {+ const topicId = 'topic-start-reentrant-reservation';+ await serverDB.insert(topics).values({ id: topicId, title: 'Test', userId });++ await expect(topicModel.tryReserveTaskCallback(topicId, 'foreground-1')).resolves.toBe(true);+ await expect(topicModel.tryReserveTaskCallback(topicId, 'foreground-1')).resolves.toBe(true);+ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-2')).resolves.toBe(false);+ });++ it('waits while a foreground operation is running', async () => {+ const topicId = 'task-callback-running-operation';+ await serverDB.insert(topics).values({+ userId,+ id: topicId,+ title: 'Test',+ metadata: {+ runningOperation: {+ assistantMessageId: 'assistant-1',+ operationId: 'operation-1',+ },+ },+ });++ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-1')).resolves.toBe(false);++ await topicModel.updateMetadata(topicId, { runningOperation: null });++ await expect(topicModel.tryReserveTaskCallback(topicId, 'callback-1')).resolves.toBe(true);+ });++ it('recovers a stale reservation left by a crashed delivery worker', async () => {+ const topicId = 'task-callback-stale-reservation';+ await serverDB.insert(topics).values({+ userId,+ id: topicId,+ title: 'Test',+ metadata: {+ taskCallbackReservation: {+ messageId: 'crashed-callback',+ reservedAt: new Date(Date.now() - 10 * 60 * 1000).toISOString(),+ },+ },+ });++ await expect(topicModel.tryReserveTaskCallback(topicId, 'retry-callback')).resolves.toBe(+ true,+ );+ });++ it('does not reserve another user topic', async () => {+ await serverDB.insert(users).values({ id: 'task-callback-other-user' });+ await serverDB.insert(topics).values({+ userId: 'task-callback-other-user',+ id: 'task-callback-other-topic',+ title: 'Test',+ });++ await expect(+ topicModel.tryReserveTaskCallback('task-callback-other-topic', 'callback-1'),+ ).resolves.toBeNull();+ });+ });+describe('recomputeUsage', () => {it('rolls the topic assistant messages into the denormalized usage/cost columns', async () => {const topicId = 'usage-recompute-1';diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex f08d7386bd8..6a54040c3bc 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -3053,6 +3053,41 @@ export class MessageModel {getLastMainThreadSpineMessageId = async (topicId: string): Promise<string | undefined> =>this.getLatestSpineMessageId({ topicId, threadId: null });+ /**+ * Whether `descendantId` belongs to the branch rooted at `ancestorId`.+ *+ * Used when reconciling a client-selected conversation tail with the latest+ * server row: a newer row may be a sibling from a historical callback fork,+ * not an advancement of the branch the user is viewing.+ */+ isMessageDescendantOf = async ({+ ancestorId,+ descendantId,+ topicId,+ }: {+ ancestorId: string;+ descendantId: string;+ topicId: string;+ }): Promise<boolean> => {+ const result = await this.db.execute(sql`+ WITH RECURSIVE ancestors(id, parent_id) AS (+ SELECT id, parent_id+ FROM messages+ WHERE id = ${descendantId}+ AND topic_id = ${topicId}+ AND ${this.ownership()}+ UNION+ SELECT parent.id, parent.parent_id+ FROM messages parent+ JOIN ancestors child ON parent.id = child.parent_id+ WHERE parent.topic_id = ${topicId}+ )+ SELECT 1 AS hit FROM ancestors WHERE id = ${ancestorId} LIMIT 1+ `);++ return result.rows.length > 0;+ };+/*** Thread-aware variant of {@link getLastMainThreadSpineMessageId}: the id of* the latest "spine" message (the most recent message that is NOT a tool anddiff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 8e988bb597a..698e5e0cc47 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -63,6 +63,7 @@ type TopicMetadataPatch = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'>* text is one click away in the topic itself.*/const LAST_MESSAGE_PREVIEW_LENGTH = 2000;+const TASK_CALLBACK_RESERVATION_TTL_MS = 5 * 60 * 1000;export interface TopicListItem extends TopicItem {/** The topic's last non-empty assistant reply, truncated with a trailing `β¦`. Only set when `queryTopics` is called with `withLastMessage`. */@@ -1346,6 +1347,77 @@ export class TopicModel {});};+ /**+ * Atomically reserve an idle topic for one task-callback delivery.+ *+ * The topic row lock closes the check/set race between callback workers:+ * only one callback can observe both `runningOperation` and the reservation+ * as empty. Foreground/tool continuations clear `runningOperation` before a+ * callback can claim the topic, so the callback always re-anchors on the+ * completed turn's latest spine.+ */+ tryReserveTaskCallback = async (id: string, messageId: string): Promise<boolean | null> =>+ this.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), this.ownership()))+ .for('update');++ if (!existing) return null;++ const reservation = existing.metadata?.taskCallbackReservation;+ const reservedAt = reservation ? Date.parse(reservation.reservedAt) : 0;+ const hasLiveReservation =+ reservation &&+ Number.isFinite(reservedAt) &&+ Date.now() - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;++ if (reservation?.messageId === messageId && hasLiveReservation) return true;+ if (existing.metadata?.runningOperation || hasLiveReservation) return false;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ taskCallbackReservation: {+ messageId,+ reservedAt: new Date().toISOString(),+ },+ },+ })+ .where(and(eq(topics.id, id), this.ownership()));++ return true;+ });++ /**+ * Release only the caller's reservation. The ownership check prevents a+ * delayed finally block from clearing a newer callback's claim.+ */+ releaseTaskCallbackReservation = async (id: string, messageId: string): Promise<void> => {+ await this.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), this.ownership()))+ .for('update');++ if (existing?.metadata?.taskCallbackReservation?.messageId !== messageId) return;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ taskCallbackReservation: null,+ },+ })+ .where(and(eq(topics.id, id), this.ownership()));+ });+ };+/*** Arm a scheduled run on an owned topic: writes `metadata.scheduledRun` and* flips the status to `scheduled` in a single update.diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 57a24fd3981..8529e66b563 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -225,6 +225,17 @@ export interface ChatTopicMetadata {* `runningOperation`); every reader treats a nullish value as "not scheduled".*/scheduledRun?: TopicScheduledRun | null;+ /**+ * Short-lived ownership marker used while a task result is being appended+ * and its continuation is being dispatched. Callback deliveries acquire+ * this only when `runningOperation` is empty, which serializes callback+ * bursts behind the foreground turn without holding a database transaction+ * open while the agent operation starts.+ */+ taskCallbackReservation?: {+ messageId: string;+ reservedAt: string;+ } | null;userMemoryExtractRunState?: TopicUserMemoryExtractRunState;userMemoryExtractStatus?: 'pending' | 'completed' | 'failed';/**@@ -454,6 +465,13 @@ export const chatTopicMetadataUpdateSchema = z.object({}).nullable().optional(),+ taskCallbackReservation: z+ .object({+ messageId: z.string(),+ reservedAt: z.string(),+ })+ .nullable()+ .optional(),scheduledRun: topicScheduledRunSchema.nullish(),workingDirectory: z.string().optional(),workingDirectoryConfig: workingDirConfigSchema.optional(),diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex d09b3164a9f..5d3de757b07 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -142,6 +142,67 @@ describe('ConversationLifecycle actions', () => {});describe('message creation', () => {+ it('continues from the active conversational tail after a recovered task callback', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicId = TEST_IDS.TOPIC_ID;+ const activeAssistant = createMockMessage({+ id: 'active-assistant',+ role: 'assistant',+ topicId,+ });+ const recoveredCallback = createMockMessage({+ id: 'recovered-task-callback',+ parentId: 'tool-use-shell',+ role: 'taskCallback',+ topicId,+ });+ const key = messageMapKey({ agentId, topicId });+ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ messagesMap: { [key]: [activeAssistant, recoveredCallback] },+ });+ });+ const sendMessageInServerSpy = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ parentId: activeAssistant.id,+ role: 'user',+ topicId,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ parentId: TEST_IDS.USER_MESSAGE_ID,+ role: 'assistant',+ topicId,+ }),+ ],+ topicId,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId },+ message: TEST_CONTENT.USER_MESSAGE,+ messages: [activeAssistant, recoveredCallback],+ });+ });++ expect(sendMessageInServerSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ newUserMessage: expect.objectContaining({ parentId: activeAssistant.id }),+ }),+ expect.any(AbortController),+ );+ });+it('should render pending compressedGroup immediately for /compact', async () => {const { result } = renderHook(() => useChatStore());const topicId = TEST_IDS.TOPIC_ID;diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex e358b248b62..508b94e247f 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -606,7 +606,13 @@ export class ConversationLifecycleActionImpl {const messages = forceNewTopicFromExisting? []: (inputMessages ?? displayMessageSelectors.getDisplayMessagesByKey(contextKey)(this.#get()));- const lastMessage = messages.at(-1);+ // Historical callback/tool sibling forks are rendered with the recovered+ // taskCallback card as supplemental history. It is not the active+ // conversational tail: using it here lets findLastMessageId descend into+ // the callback's inactive assistant branch, so the next user message is+ // persisted there and disappears from the main flow after reconciliation.+ const lastMessage =+ messages.findLast((message) => message.role !== 'taskCallback') ?? messages.at(-1);useUserMemoryStore.getState().setActiveMemoryContext({agent: agentSelectors.getAgentMetaById(agentId)(getAgentStoreState()),