Skip to content

🀯 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.

πŸ› fix(agent): make creator task callbacks durable (#18089)

Arvin Xu975e21cf806c
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 0332814d7bc..3b6bf08dd9c 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -20,7 +20,7 @@ import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observab
import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';
import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';
-import { hookDispatcher, type SerializedHook } from './hooks';
+import { CriticalHookDeliveryError, hookDispatcher, type SerializedHook } from './hooks';
import { registerWorksForOperation } from './workRegistration';
const log = debug('lobe-server:completion-lifecycle');
@@ -111,9 +111,9 @@ const toAgentSignalSnapshotEvents = (
* events, dispatching `onComplete`/`onError` hooks, and writing the final
* error back onto the assistant message row.
*
- * All public methods are fire-and-forget: errors are logged but never thrown,
- * so the executor's terminal cleanup path (snapshot finalize, lock release)
- * always runs.
+ * Ordinary side-effect errors are logged and remain non-fatal. Critical
+ * no-fallback webhook failures are rethrown after terminal persistence so a
+ * queue execution can retry the control-flow handoff.
*/
export class CompletionLifecycle {
private readonly messageModel: MessageModel;
@@ -752,6 +752,7 @@ export class CompletionLifecycle {
}
}
} catch (error) {
+ if (error instanceof CriticalHookDeliveryError) throw error;
log('[%s] Hook dispatch error (non-fatal): %O', operationId, error);
} finally {
// Keep hooks registered across an async-tool park so the eventual resume
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index f35ba6b519d..c556d829d05 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -7,7 +7,7 @@ import * as agentSignalService from '@/server/services/agentSignal';
import * as verifyServices from '@/server/services/verify';
import { CompletionLifecycle, isSuccessLikeCompletionReason } from '../CompletionLifecycle';
-import { hookDispatcher } from '../hooks';
+import { CriticalHookDeliveryError, hookDispatcher } from '../hooks';
import { registerWorksForOperation } from '../workRegistration';
// Default async no-op implementation: the production code chains `.catch` on
@@ -525,6 +525,29 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
}),
});
});
+
+ it('rethrows critical webhook failures after terminal persistence', async () => {
+ const lifecycle = buildLifecycle();
+ const persistCompletion = vi
+ .spyOn(lifecycle as any, 'persistCompletion')
+ .mockResolvedValue(undefined);
+ const dispatch = vi
+ .spyOn(hookDispatcher, 'dispatch')
+ .mockRejectedValue(
+ new CriticalHookDeliveryError('task-on-complete', new Error('qstash down')),
+ );
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});
+
+ await expect(
+ lifecycle.dispatchHooks(
+ 'op-1',
+ { metadata: { _hooks: [] }, status: 'interrupted' },
+ 'interrupted',
+ ),
+ ).rejects.toThrow('Critical webhook delivery failed: task-on-complete');
+
+ expect(persistCompletion).toHaveBeenCalledBefore(dispatch);
+ });
});
describe('CompletionLifecycle.dispatchHooks β€” verify plan race', () => {
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index e9f13dfc639..3fa5789f562 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -16,6 +16,16 @@ import type {
const log = debug('lobe-server:hook-dispatcher');
+export class CriticalHookDeliveryError extends Error {
+ constructor(
+ public readonly hookId: string,
+ public readonly cause: unknown,
+ ) {
+ super(`Critical webhook delivery failed: ${hookId}`, { cause });
+ this.name = 'CriticalHookDeliveryError';
+ }
+}
+
/**
* Delivers a webhook via HTTP POST (fetch or QStash)
*/
@@ -67,17 +77,15 @@ export async function deliverWebhook(
}
async function fetchDeliver(url: string, payload: Record<string, unknown>): Promise<void> {
- try {
- const res = await fetch(url, {
- body: JSON.stringify(payload),
- headers: { 'Content-Type': 'application/json' },
- method: 'POST',
- });
- log('Webhook delivered via fetch: %s (status: %d)', url, res.status);
- } catch (error) {
- log('Webhook fetch delivery failed: %s %O', url, error);
- // Hook errors should not affect main flow
+ const res = await fetch(url, {
+ body: JSON.stringify(payload),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+ if (res.status < 200 || res.status >= 300) {
+ throw new Error(`Webhook delivery failed: ${res.status} ${res.statusText}`);
}
+ log('Webhook delivered via fetch: %s (status: %d)', url, res.status);
}
function buildWebhookPayload(
@@ -148,6 +156,7 @@ export class HookDispatcher {
this.getSerializedHooks(operationId)?.filter((h) => h.type === type) ||
[];
+ let criticalError: CriticalHookDeliveryError | undefined;
for (const hook of webhookHooks) {
try {
log(
@@ -173,6 +182,7 @@ export class HookDispatcher {
`[HookDispatcher][${operationId}][${type}] Webhook delivery failed with no fallback: ${hook.id} β†’ ${hook.webhook.url}`,
error,
);
+ criticalError ??= new CriticalHookDeliveryError(hook.id, error);
} else {
log(
'[%s][%s] Webhook delivery error (non-fatal): %s %O',
@@ -184,6 +194,11 @@ export class HookDispatcher {
}
}
}
+
+ // Finish independent sibling hooks first, then fail the queue execution.
+ // Queue runtimes can retry a lost control-flow handoff instead of
+ // reporting success while stranding its consumer.
+ if (criticalError) throw criticalError;
}
}
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
index b922253717d..fe4744354a8 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
@@ -315,7 +315,7 @@ describe('HookDispatcher', () => {
expect(global.fetch).not.toHaveBeenCalled();
});
- it('dispatch surfaces a no-fallback delivery failure without breaking other hooks', async () => {
+ it('dispatch rejects a no-fallback delivery failure after delivering other hooks', async () => {
vi.mocked(isQueueAgentRuntimeEnabled).mockReturnValue(true);
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -337,7 +337,7 @@ describe('HookDispatcher', () => {
const serialized = dispatcher.getSerializedHooks(operationId);
await expect(
dispatcher.dispatch(operationId, 'onComplete', makeEvent(), serialized),
- ).resolves.toBeUndefined();
+ ).rejects.toThrow('Critical webhook delivery failed: critical-hook');
// The failure is escalated to production logs, and the sibling webhook
// still gets delivered.
diff --git a/apps/server/src/services/agentRuntime/hooks/index.ts b/apps/server/src/services/agentRuntime/hooks/index.ts
index a1ab473ed9b..6ec43b8794a 100644
--- a/apps/server/src/services/agentRuntime/hooks/index.ts
+++ b/apps/server/src/services/agentRuntime/hooks/index.ts
@@ -1,4 +1,4 @@
-export { HookDispatcher, hookDispatcher } from './HookDispatcher';
+export { CriticalHookDeliveryError, HookDispatcher, hookDispatcher } from './HookDispatcher';
export type {
AgentHook,
AgentHookEvent,
diff --git a/apps/server/src/services/bot/AgentBridgeService.ts b/apps/server/src/services/bot/AgentBridgeService.ts
index efc5ff35621..78ce719c7b0 100644
--- a/apps/server/src/services/bot/AgentBridgeService.ts
+++ b/apps/server/src/services/bot/AgentBridgeService.ts
@@ -15,6 +15,7 @@ import { getMessageGatewayClient } from '@/server/services/gateway/MessageGatewa
import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
import { SystemAgentService } from '@/server/services/systemAgent';
+import { createBotCompletionWebhook } from './createBotCompletionHook';
import { formatPrompt as formatPromptUtil } from './formatPrompt';
import type { BotReplyLocale, PlatformClient } from './platforms';
import {
@@ -998,11 +999,19 @@ export class AgentBridgeService {
},
id: 'bot-completion',
type: 'onComplete',
- webhook: {
- body: { ...webhookBody, type: 'completion', userPrompt: prompt },
- delivery: 'qstash',
- url: callbackUrl,
- },
+ webhook: botContext
+ ? createBotCompletionWebhook({
+ body: { ...webhookBody, userPrompt: prompt },
+ botContext,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ })
+ : {
+ body: { ...webhookBody, type: 'completion', userPrompt: prompt },
+ delivery: 'qstash',
+ fallback: 'none',
+ url: callbackUrl,
+ },
},
],
prompt,
@@ -1388,11 +1397,19 @@ export class AgentBridgeService {
},
id: 'bot-completion',
type: 'onComplete' as const,
- webhook: {
- body: { ...webhookBody, type: 'completion', userPrompt: prompt },
- delivery: 'qstash' as const,
- url: callbackUrl,
- },
+ webhook: botContext
+ ? createBotCompletionWebhook({
+ body: { ...webhookBody, userPrompt: prompt },
+ botContext,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ })
+ : {
+ body: { ...webhookBody, type: 'completion', userPrompt: prompt },
+ delivery: 'qstash' as const,
+ fallback: 'none' as const,
+ url: callbackUrl,
+ },
},
],
prompt,
diff --git a/apps/server/src/services/bot/BotCallbackService.ts b/apps/server/src/services/bot/BotCallbackService.ts
index 1abdc7edb8b..c7701136666 100644
--- a/apps/server/src/services/bot/BotCallbackService.ts
+++ b/apps/server/src/services/bot/BotCallbackService.ts
@@ -129,6 +129,12 @@ export interface BotCallbackBody {
workspaceId?: string;
}
+export interface BotCallbackOptions {
+ deliveredChunkCount?: number;
+ onChunkDelivered?: (deliveredChunkCount: number) => Promise<void>;
+ strictDelivery?: boolean;
+}
+
// --------------- Service ---------------
export class BotCallbackService {
@@ -138,7 +144,7 @@ export class BotCallbackService {
this.db = db;
}
- async handleCallback(body: BotCallbackBody): Promise<void> {
+ async handleCallback(body: BotCallbackBody, options?: BotCallbackOptions): Promise<void> {
const {
type,
applicationId,
@@ -189,6 +195,9 @@ export class BotCallbackService {
replyLocale,
charLimit,
canEdit,
+ options?.strictDelivery,
+ options?.deliveredChunkCount,
+ options?.onChunkDelivered,
);
await this.clearStepReaction(body, client, platform);
// Clear the active thread tracker so the thread can accept new messages.
@@ -407,6 +416,9 @@ export class BotCallbackService {
replyLocale: BotReplyLocale,
charLimit?: number,
canEdit = true,
+ strictDelivery = false,
+ deliveredChunkCount = 0,
+ onChunkDelivered?: (deliveredChunkCount: number) => Promise<void>,
): Promise<void> {
const {
reason,
@@ -433,15 +445,28 @@ export class BotCallbackService {
errorAttribution,
);
const errorText = client.formatMarkdown?.(errorBody) ?? errorBody;
- await this.deliverFirstChunk(messenger, progressMessageId, errorText, canEdit);
+ if (deliveredChunkCount < 1) {
+ const delivered = await this.deliverFirstChunk(
+ messenger,
+ progressMessageId,
+ errorText,
+ canEdit,
+ undefined,
+ strictDelivery,
+ );
+ if (delivered) await onChunkDelivered?.(1);
+ }
return;
}
if (reason === 'interrupted') {
+ if (deliveredChunkCount >= 1) return;
const stoppedText = renderStopped(errorMessage, replyLocale);
try {
await messenger.createMessage(stoppedText);
+ await onChunkDelivered?.(1);
} catch (error) {
+ if (strictDelivery) throw error;
log('handleCompletion: failed to send interrupted message: %O', error);
}
return;
@@ -465,6 +490,7 @@ export class BotCallbackService {
console.error(
`[BotCallbackService] completion had no lastAssistantContent and no attachments, skipping reply (operationId=${operationId}, topicId=${body.topicId}, thread=${body.platformThreadId})`,
);
+ if (strictDelivery) throw new Error('Creator callback completed without deliverable content');
return;
}
@@ -499,22 +525,28 @@ export class BotCallbackService {
const lastIndex = chunks.length - 1;
const firstChunkAttachments = lastIndex === 0 ? attachments : undefined;
- await this.deliverFirstChunk(
- messenger,
- progressMessageId,
- chunks[0],
- canEdit,
- firstChunkAttachments,
- );
+ if (deliveredChunkCount < 1) {
+ const delivered = await this.deliverFirstChunk(
+ messenger,
+ progressMessageId,
+ chunks[0],
+ canEdit,
+ firstChunkAttachments,
+ strictDelivery,
+ );
+ if (delivered) await onChunkDelivered?.(1);
+ }
// Each remaining chunk gets its own try/catch so a single transient failure
// (rate-limit, network blip) doesn't drop everything that follows.
- for (let i = 1; i < chunks.length; i++) {
+ for (let i = Math.max(1, deliveredChunkCount); i < chunks.length; i++) {
try {
const isLast = i === lastIndex;
await messenger.createMessage(
isLast && attachments?.length ? { attachments, content: chunks[i] } : chunks[i],
);
+ await onChunkDelivered?.(i + 1);
} catch (error) {
+ if (strictDelivery) throw error;
console.error(
`[BotCallbackService] failed to send reply chunk ${i}/${lastIndex} (thread=${body.platformThreadId}): ${describePlatformError(error)}`,
);
@@ -534,7 +566,8 @@ export class BotCallbackService {
text: string,
canEdit: boolean,
attachments?: BotMessageAttachment[],
- ): Promise<void> {
+ strictDelivery = false,
+ ): Promise<boolean> {
const payload = attachments && attachments.length > 0 ? { attachments, content: text } : text;
if (canEdit && progressMessageId) {
@@ -548,7 +581,7 @@ export class BotCallbackService {
console.info(
`[BotCallbackService] completion reply delivered via editMessage (message=${progressMessageId})`,
);
- return;
+ return true;
} catch (error) {
log('handleCompletion: editMessage failed, falling back to createMessage: %O', error);
}
@@ -556,13 +589,16 @@ export class BotCallbackService {
try {
await messenger.createMessage(payload);
console.info('[BotCallbackService] completion reply delivered via createMessage');
+ return true;
} catch (error) {
// Last resort failed β€” the reply is lost. console (not debug) so the
- // "agent ran but no reply appeared" class of failures
+ // "agent ran but no reply appeared" class of failures
// is visible in production logs instead of an HTTP 200 with nothing.
console.error(
`[BotCallbackService] createMessage fallback failed, reply lost: ${describePlatformError(error)}`,
);
+ if (strictDelivery) throw error;
+ return false;
}
}
diff --git a/apps/server/src/services/bot/__tests__/BotCallbackService.test.ts b/apps/server/src/services/bot/__tests__/BotCallbackService.test.ts
index 753436b2c0b..78693eaf013 100644
--- a/apps/server/src/services/bot/__tests__/BotCallbackService.test.ts
+++ b/apps/server/src/services/bot/__tests__/BotCallbackService.test.ts
@@ -582,6 +582,14 @@ describe('BotCallbackService', () => {
expect(mockEditMessage).not.toHaveBeenCalled();
});
+ it('should fail strict proactive delivery when completion has no content', async () => {
+ const body = makeBody({ reason: 'completed', type: 'completion' });
+
+ await expect(service.handleCallback(body, { strictDelivery: true })).rejects.toThrow(
+ 'Creator callback completed without deliverable content',
+ );
+ });
+
it('should edit progress message with final reply content', async () => {
const body = makeBody({
cost: 0.005,
@@ -634,6 +642,20 @@ describe('BotCallbackService', () => {
);
});
+ it('should fail strict proactive delivery when the platform rejects the reply', async () => {
+ mockEditMessage.mockRejectedValueOnce(new Error('message to edit not found'));
+ mockCreateMessage.mockRejectedValueOnce(new Error('Discord channel unavailable'));
+ const body = makeBody({
+ lastAssistantContent: 'A result that must reach the creator.',
+ reason: 'completed',
+ type: 'completion',
+ });
+
+ await expect(service.handleCallback(body, { strictDelivery: true })).rejects.toThrow(
+ 'Discord channel unavailable',
+ );
+ });
+
it('should fall back to createMessage when error-state edit fails', async () => {
mockEditMessage.mockRejectedValueOnce(new Error('message to edit not found'));
@@ -687,6 +709,27 @@ describe('BotCallbackService', () => {
expect(mockCreateMessage.mock.calls.length).toBeGreaterThanOrEqual(2);
});
+ it('should resume strict delivery after the last checkpointed chunk', async () => {
+ const onChunkDelivered = vi.fn().mockResolvedValue(undefined);
+ const longContent = 'A'.repeat(2000) + '\n\n' + 'B'.repeat(2000);
+ const body = makeBody({
+ lastAssistantContent: longContent,
+ reason: 'completed',
+ type: 'completion',
+ });
+
+ await service.handleCallback(body, {
+ deliveredChunkCount: 1,
+ onChunkDelivered,
+ strictDelivery: true,
+ });
+
+ expect(mockEditMessage).not.toHaveBeenCalled();
+ expect(mockCreateMessage).toHaveBeenCalled();
+ expect(onChunkDelivered).toHaveBeenCalledWith(2);
+ expect(onChunkDelivered).not.toHaveBeenCalledWith(1);
+ });
+
it('should not throw when sending interrupted message fails', async () => {
mockCreateMessage.mockRejectedValueOnce(new Error('Send failed'));
diff --git a/apps/server/src/services/bot/createBotCompletionHook.ts b/apps/server/src/services/bot/createBotCompletionHook.ts
new file mode 100644
index 00000000000..5d7b9904506
--- /dev/null
+++ b/apps/server/src/services/bot/createBotCompletionHook.ts
@@ -0,0 +1,32 @@
+import type { ChatTopicBotContext } from '@lobechat/types';
+
+import type { AgentHookWebhook } from '@/server/services/agentRuntime/hooks/types';
+
+const BOT_CALLBACK_URL = '/api/agent/webhooks/bot-callback';
+
+export interface CreateBotCompletionHookParams {
+ body?: Record<string, unknown>;
+ botContext: ChatTopicBotContext;
+ userId: string;
+ workspaceId?: string;
+}
+
+export const createBotCompletionWebhook = ({
+ botContext,
+ body,
+ userId,
+ workspaceId,
+}: CreateBotCompletionHookParams): AgentHookWebhook => ({
+ body: {
+ applicationId: botContext.applicationId,
+ messengerInstallationKey: botContext.messengerInstallationKey,
+ platformThreadId: botContext.platformThreadId,
+ type: 'completion',
+ userId,
+ workspaceId,
+ ...body,
+ },
+ delivery: 'qstash',
+ fallback: 'none',
+ url: BOT_CALLBACK_URL,
+});
diff --git a/apps/server/src/services/taskResultBridge/index.test.ts b/apps/server/src/services/taskResultBridge/index.test.ts
index 592c5547746..c230e5a4cd8 100644
--- a/apps/server/src/services/taskResultBridge/index.test.ts
+++ b/apps/server/src/services/taskResultBridge/index.test.ts
@@ -11,20 +11,55 @@ 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, releaseReservation, tryReserve } = vi.hoisted(() => ({
+const {
+ attachCreatorOperation,
+ claimPending,
+ createMsg,
+ createPending,
+ execAgent,
+ findMessage,
+ getLastLeaf,
+ release,
+ settle,
+ topicFindById,
+ releaseReservation,
+ tryReserve,
+} = vi.hoisted(() => ({
+ attachCreatorOperation: vi.fn(),
+ claimPending: vi.fn(),
createMsg: vi.fn(),
+ createPending: vi.fn(),
execAgent: vi.fn(),
+ findMessage: vi.fn(),
getLastLeaf: vi.fn(),
releaseReservation: vi.fn(),
tryReserve: vi.fn(),
+ release: vi.fn(),
+ settle: vi.fn(),
+ topicFindById: vi.fn(),
}));
vi.mock('@/database/models/message', () => ({
- MessageModel: vi.fn(() => ({ create: createMsg, getLastMainThreadSpineMessageId: getLastLeaf })),
+ MessageModel: vi.fn(() => ({
+ create: createMsg,
+ findById: findMessage,
+ getLastMainThreadSpineMessageId: getLastLeaf,
+ })),
+}));
+
+vi.mock('./redisStore', () => ({
+ TaskResultCallbackRedisStore: vi.fn(() => ({
+ attachCreatorOperation,
+ claimPending,
+ createPending,
+ release,
+ settle,
+ })),
}));
vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn(() => ({
+ findById: topicFindById,
releaseTaskCallbackReservation: releaseReservation,
tryReserveTaskCallback: tryReserve,
})),
@@ -35,7 +70,9 @@ vi.mock('../aiAgent', () => ({
}));
const TEST_USER = 'user-1';
-const db = {} as any;
+const db = {
+ transaction: vi.fn(async (callback) => callback({ execute: vi.fn() })),
+} as any;
const ORIGIN = {
agentId: 'agent-creator',
@@ -61,9 +98,21 @@ describe('TaskResultBridgeService.deliver', () => {
beforeEach(() => {
createMsg.mockReset().mockResolvedValue({ id: 'task-cb-task-1-topic-done' } as any);
+ createPending.mockReset().mockResolvedValue({ id: 'receipt-1' });
+ claimPending
+ .mockReset()
+ .mockResolvedValue([{ callbackMessageId: 'task-cb-task-1-topic-done', id: 'receipt-1' }]);
+ attachCreatorOperation.mockReset().mockResolvedValue(undefined);
+ release.mockReset().mockResolvedValue(undefined);
+ settle.mockReset().mockResolvedValue('topic-origin');
+ findMessage.mockReset().mockResolvedValue(null);
+ topicFindById.mockReset().mockResolvedValue({ agentId: 'agent-creator', metadata: {} });
// 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');
+ getLastLeaf
+ .mockReset()
+ .mockResolvedValueOnce('msg-current-leaf')
+ .mockResolvedValue('task-cb-task-1-topic-done');
tryReserve.mockReset().mockResolvedValue(true);
releaseReservation.mockReset().mockResolvedValue(undefined);
execAgent
@@ -116,7 +165,7 @@ describe('TaskResultBridgeService.deliver', () => {
parentMessageId: 'task-cb-task-1-topic-done',
suppressUserMessage: true,
});
- expect(releaseReservation).toHaveBeenCalledWith('topic-origin', 'task-cb-task-1-topic-done');
+ expect(releaseReservation).toHaveBeenCalledWith('topic-origin', 'task-result-wakeup-receipt-1');
});
it('scopes the MessageModel to the bridge workspace so workspace tasks find their leaf', async () => {
@@ -124,7 +173,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(MessageModel).toHaveBeenCalledWith(expect.anything(), TEST_USER, 'ws-1');
expect(TopicModel).toHaveBeenCalledWith(db, TEST_USER, 'ws-1');
});
@@ -137,25 +186,24 @@ describe('TaskResultBridgeService.deliver', () => {
expect(execAgent).not.toHaveBeenCalled();
});
- it('skips delivery when the origin topic was deleted', async () => {
+ it('does not wake the creator 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(createPending).toHaveBeenCalledTimes(1);
expect(execAgent).not.toHaveBeenCalled();
+ expect(settle).toHaveBeenCalledWith(['receipt-1']);
});
- 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' }),
- );
+ it('resumes an incomplete wakeup when the callback message already exists', async () => {
+ findMessage.mockResolvedValueOnce({ id: 'task-cb-task-1-topic-done' });
await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
- expect(execAgent).not.toHaveBeenCalled();
- expect(releaseReservation).toHaveBeenCalledTimes(1);
+ expect(createMsg).not.toHaveBeenCalled();
+ expect(createPending).toHaveBeenCalledTimes(1);
+ expect(execAgent).toHaveBeenCalledTimes(1);
});
it('waits for the in-flight tool turn before resolving the callback parent', async () => {
@@ -166,14 +214,16 @@ describe('TaskResultBridgeService.deliver', () => {
const delivery = new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
await vi.waitFor(() => expect(tryReserve).toHaveBeenCalledTimes(1));
- expect(getLastLeaf).not.toHaveBeenCalled();
- expect(createMsg).not.toHaveBeenCalled();
+ expect(execAgent).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(100);
await delivery;
expect(tryReserve).toHaveBeenCalledTimes(2);
- expect(getLastLeaf).toHaveBeenCalledTimes(1);
+ expect(getLastLeaf).toHaveBeenCalledTimes(2);
+ expect(tryReserve.mock.invocationCallOrder.at(-1)).toBeLessThan(
+ getLastLeaf.mock.invocationCallOrder[1],
+ );
expect(createMsg.mock.calls[0][0]).toMatchObject({ parentId: 'msg-current-leaf' });
} finally {
vi.useRealTimers();
@@ -212,13 +262,64 @@ describe('TaskResultBridgeService.deliver', () => {
await expectation;
expect(tryReserve).toHaveBeenCalledTimes(6);
- expect(createMsg).not.toHaveBeenCalled();
+ expect(createMsg).toHaveBeenCalledTimes(1);
expect(execAgent).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
+ it('restores messenger routing and registers a proactive bot completion hook', async () => {
+ topicFindById.mockResolvedValue({
+ agentId: 'agent-creator',
+ metadata: {
+ bot: {
+ applicationId: 'messenger-discord',
+ isOwner: true,
+ messengerInstallationKey: 'discord:singleton',
+ platform: 'discord',
+ platformThreadId: 'discord:guild:channel:thread',
+ senderExternalUserId: 'discord-user',
+ },
+ },
+ });
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+
+ const hooks = execAgent.mock.calls[0][0].hooks;
+ const botHook = hooks.find((hook: any) => hook.id === 'task-creator-completion');
+ expect(botHook.webhook).toMatchObject({
+ delivery: 'qstash',
+ fallback: 'none',
+ url: '/api/workflows/task/on-creator-complete',
+ });
+ expect(botHook.webhook.body).toMatchObject({
+ messengerInstallationKey: 'discord:singleton',
+ platformThreadId: 'discord:guild:channel:thread',
+ type: 'completion',
+ });
+ });
+
+ it('aggregates all pending callbacks into one creator wakeup', async () => {
+ claimPending.mockResolvedValue([
+ { callbackMessageId: 'callback-1', id: 'receipt-1' },
+ { callbackMessageId: 'callback-2', id: 'receipt-2' },
+ ]);
+ getLastLeaf
+ .mockReset()
+ .mockResolvedValueOnce('msg-current-leaf')
+ .mockResolvedValue('callback-2');
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+
+ expect(execAgent).toHaveBeenCalledTimes(1);
+ expect(execAgent.mock.calls[0][0]).toMatchObject({
+ parentMessageId: 'callback-2',
+ prompt: 'Process 2 completed task results',
+ });
+ expect(attachCreatorOperation).toHaveBeenCalledWith(['receipt-1', 'receipt-2'], 'op-new');
+ });
+
it('bridges a failed run with the error text and reason', async () => {
findByTopicId.mockResolvedValue({ handoff: undefined } as any);
diff --git a/apps/server/src/services/taskResultBridge/index.ts b/apps/server/src/services/taskResultBridge/index.ts
index 15f4b6de7fb..bc0ac3fd4bb 100644
--- a/apps/server/src/services/taskResultBridge/index.ts
+++ b/apps/server/src/services/taskResultBridge/index.ts
@@ -1,14 +1,20 @@
-import { RequestTrigger, type TaskContext, type TaskTopicHandoff } from '@lobechat/types';
+import type { ChatTopicBotContext, TaskContext, TaskTopicHandoff } from '@lobechat/types';
+import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
+import { sql } from 'drizzle-orm';
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 type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
+import type { BotCallbackBody } from '@/server/services/bot/BotCallbackService';
+import { BotCallbackService } from '@/server/services/bot/BotCallbackService';
import { AiAgentService } from '../aiAgent';
import { acquireTopicStartReservation } from '../aiAgent/topicStartReservation';
+import { TaskResultCallbackRedisStore } from './redisStore';
const log = debug('lobe-server:taskResultBridge');
@@ -27,12 +33,6 @@ const normalizeReason = (reason: string): CallbackReason => {
return 'done';
};
-const isDuplicateKeyError = (error: unknown): boolean => {
- const err = error as { cause?: { code?: string }; code?: string; message?: string };
- const blob = `${err?.message ?? ''}${err?.cause?.code ?? ''}${err?.code ?? ''}`;
- return blob.includes('23505') || blob.includes('unique') || blob.includes('duplicate');
-};
-
const truncate = (text: string): string =>
text.length > FALLBACK_MAX_LENGTH ? `${text.slice(0, FALLBACK_MAX_LENGTH)}…` : text;
@@ -80,6 +80,12 @@ export interface DeliverTaskResultParams {
topicId?: string;
}
+export interface CompleteCreatorWakeupParams {
+ agentId: string;
+ originTopicId: string;
+ receiptIds: string[];
+}
+
/**
* Delivers a finished task's handoff back to the conversation that created it
* Fire-and-forget: appends a `role='taskCallback'` card into the
@@ -114,6 +120,8 @@ export class TaskResultBridgeService {
log('no origin for task %s, skipping bridge', taskIdentifier);
return;
}
+ const originAgentId = origin.agentId;
+ const originTopicId = origin.topicId;
// Automation tasks (heartbeat/schedule) run many topics β€” only bridge once
// the task itself reaches a terminal state, to avoid per-tick spam. One-shot
@@ -145,73 +153,179 @@ export class TaskResultBridgeService {
// team workspace, so the leaf lookup + create must use the matching
// 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);
- 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 {
- // 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 {
+ // Serialize callback-card insertion per creator topic. Two tasks can finish
+ // at the same instant; without the advisory lock they can both anchor on
+ // the same leaf and create sibling branches, hiding one result from the
+ // creator's main spine.
+ await this.db.transaction(async (tx) => {
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${originTopicId}))`);
+ const messageModel = new MessageModel(tx, this.userId, this.workspaceId);
+ const existing = await messageModel.findById(messageId);
+ if (!existing) {
+ const parentId = await messageModel.getLastMainThreadSpineMessageId(originTopicId);
await messageModel.create(
{
- agentId: origin.agentId,
+ agentId: originAgentId,
content,
metadata: {
taskCallback: { identifier: taskIdentifier, reason, taskId, topicId },
},
parentId,
role: 'taskCallback',
- topicId: origin.topicId,
+ topicId: originTopicId,
},
messageId,
);
- } catch (error) {
- if (isDuplicateKeyError(error)) {
- log('task-callback %s already delivered, skipping', messageId);
- return;
- }
- throw error;
}
+ });
+
+ await new TaskResultCallbackRedisStore(
+ this.userId,
+ originTopicId,
+ this.workspaceId,
+ ).createPending({
+ agentId: originAgentId,
+ callbackMessageId: messageId,
+ operationId: params.operationId,
+ taskId,
+ taskTopicId: topicId,
+ });
- // 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 },
+ await this.drain(originAgentId, originTopicId);
+ log('queued task %s result for creator topic %s (%s)', taskIdentifier, originTopicId, reason);
+ }
+
+ /** Claim and start one aggregated creator wakeup for the topic. */
+ async drain(agentId: string, originTopicId: string): Promise<void> {
+ const callbackStore = new TaskResultCallbackRedisStore(
+ this.userId,
+ originTopicId,
+ this.workspaceId,
+ );
+ const receipts = await callbackStore.claimPending();
+ if (receipts.length === 0) return;
+
+ const receiptIds = receipts.map((item) => item.id);
+ const topicModel = new TopicModel(this.db, this.userId, this.workspaceId);
+ const topic = await topicModel.findById(originTopicId);
+ const botContext = topic?.metadata?.bot as ChatTopicBotContext | undefined;
+ const hooks: AgentHook[] = [
+ this.createCreatorCompletionHook(receiptIds, agentId, originTopicId, botContext),
+ ];
+ const reservationId = `task-result-wakeup-${receiptIds[0]}`;
+
+ try {
+ const reserved = await acquireTopicStartReservation({
+ reservationId,
+ topicId: originTopicId,
+ topicModel,
+ });
+ if (!reserved) {
+ await callbackStore.settle(receiptIds);
+ return;
+ }
+
+ // Receipt ordering is a queue concern, not the conversation's source of
+ // truth. Re-read the live spine only after owning the topic reservation
+ // so the Creator sees every callback card that landed before this run.
+ const parentMessageId = await new MessageModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).getLastMainThreadSpineMessageId(originTopicId);
+
+ const result = await new AiAgentService(this.db, this.userId, {
+ workspaceId: this.workspaceId,
+ }).execAgent({
+ agentId,
+ appContext: { topicId: originTopicId },
autoStart: true,
- parentMessageId: messageId,
- prompt: `Task ${taskIdentifier} ${reason}`,
+ botContext,
+ hooks,
+ parentMessageId,
+ prompt: `Process ${receipts.length} completed task result${receipts.length === 1 ? '' : 's'}`,
suppressUserMessage: true,
- topicStartReservationId: messageId,
+ topicStartReservationId: reservationId,
trigger: RequestTrigger.AgentSignal,
userInterventionConfig: { approvalMode: 'headless' },
});
+ await callbackStore.attachCreatorOperation(receiptIds, result.operationId);
+ } catch (error) {
+ const errorMessage = error instanceof Error ? error.message : 'Failed to start creator agent';
+ await callbackStore.release(receiptIds, errorMessage);
+ throw error;
} finally {
- await topicModel.releaseTaskCallbackReservation(origin.topicId, messageId);
+ await topicModel.releaseTaskCallbackReservation(originTopicId, reservationId);
}
+ }
- log('bridged task %s result into topic %s (%s)', taskIdentifier, origin.topicId, reason);
+ async completeCreatorWakeup(params: CompleteCreatorWakeupParams): Promise<void> {
+ const callbackStore = new TaskResultCallbackRedisStore(
+ this.userId,
+ params.originTopicId,
+ this.workspaceId,
+ );
+ await callbackStore.settle(params.receiptIds);
+ await this.drain(params.agentId, params.originTopicId);
+ }
+
+ private createCreatorCompletionHook(
+ receiptIds: string[],
+ agentId: string,
+ originTopicId: string,
+ botContext?: ChatTopicBotContext,
+ ): AgentHook {
+ return {
+ handler: async (event) => {
+ if (botContext?.platformThreadId) {
+ const callbackStore = new TaskResultCallbackRedisStore(
+ this.userId,
+ originTopicId,
+ this.workspaceId,
+ );
+ const deliveredChunkCount = await callbackStore.getDeliveredChunkCount(event.operationId);
+ await new BotCallbackService(this.db).handleCallback(
+ {
+ ...event,
+ applicationId: botContext.applicationId,
+ messengerInstallationKey: botContext.messengerInstallationKey,
+ platformThreadId: botContext.platformThreadId,
+ type: 'completion',
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ } as BotCallbackBody,
+ {
+ deliveredChunkCount,
+ onChunkDelivered: (count) =>
+ callbackStore.markDeliveryChunk(event.operationId, count),
+ strictDelivery: true,
+ },
+ );
+ }
+ await this.completeCreatorWakeup({
+ agentId,
+ originTopicId,
+ receiptIds,
+ });
+ },
+ id: 'task-creator-completion',
+ type: 'onComplete',
+ webhook: {
+ body: {
+ agentId,
+ applicationId: botContext?.applicationId,
+ messengerInstallationKey: botContext?.messengerInstallationKey,
+ platformThreadId: botContext?.platformThreadId,
+ receiptIds,
+ originTopicId,
+ type: 'completion',
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ },
+ delivery: 'qstash',
+ fallback: 'none',
+ url: '/api/workflows/task/on-creator-complete',
+ },
+ };
}
}
diff --git a/apps/server/src/services/taskResultBridge/redisStore.test.ts b/apps/server/src/services/taskResultBridge/redisStore.test.ts
new file mode 100644
index 00000000000..5d55e40a5b1
--- /dev/null
+++ b/apps/server/src/services/taskResultBridge/redisStore.test.ts
@@ -0,0 +1,227 @@
+// @vitest-environment node
+import type Redis from 'ioredis';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskResultCallbackRedisStore } from './redisStore';
+
+const createRedis = () => {
+ const transaction = {
+ exec: vi.fn().mockResolvedValue([]),
+ hset: vi.fn(),
+ };
+ transaction.hset.mockReturnValue(transaction);
+
+ return {
+ eval: vi.fn(),
+ get: vi.fn(),
+ hget: vi.fn(),
+ hgetall: vi.fn(),
+ lrange: vi.fn(),
+ multi: vi.fn(() => transaction),
+ transaction,
+ zrange: vi.fn(),
+ zrem: vi.fn(),
+ };
+};
+
+describe('TaskResultCallbackRedisStore', () => {
+ let redis: ReturnType<typeof createRedis>;
+
+ beforeEach(() => {
+ redis = createRedis();
+ });
+
+ it('requires Redis instead of silently losing a callback', () => {
+ expect(() => new TaskResultCallbackRedisStore('user-1', 'topic-1', undefined, null)).toThrow(
+ 'Redis is required for task result callbacks',
+ );
+ });
+
+ it('creates an idempotent pending receipt with a scoped recovery entry', async () => {
+ redis.eval.mockResolvedValue('pending');
+ const store = new TaskResultCallbackRedisStore(
+ 'user-1',
+ 'topic-1',
+ 'workspace-1',
+ redis as unknown as Redis,
+ );
+
+ await store.createPending({
+ agentId: 'agent-1',
+ callbackMessageId: 'message-1',
+ operationId: 'operation-1',
+ taskId: 'task-1',
+ });
+
+ expect(redis.eval).toHaveBeenCalledTimes(1);
+ expect(redis.eval.mock.calls[0].slice(0, 6)).toEqual([
+ expect.stringContaining("local status = redis.call('HGET'"),
+ 4,
+ 'task-result-callback:receipt:operation-1',
+ 'task-result-callback:pending:user-1:workspace-1:topic-1',
+ 'task-result-callback:scope:user-1:workspace-1:topic-1',
+ 'task-result-callback:recovery',
+ ]);
+ expect(redis.eval.mock.calls[0].slice(-10)).toEqual([
+ 'agentId',
+ 'agent-1',
+ 'originTopicId',
+ 'topic-1',
+ 'userId',
+ 'user-1',
+ 'workspaceId',
+ 'workspace-1',
+ expect.any(String),
+ 'user-1:workspace-1:topic-1',
+ ]);
+ });
+
+ it('claims the pending batch and hydrates its receipt payloads', async () => {
+ redis.eval.mockResolvedValue(['operation-1']);
+ redis.hgetall.mockResolvedValue({
+ attempts: '1',
+ callbackMessageId: 'message-1',
+ id: 'operation-1',
+ operationId: 'operation-1',
+ originTopicId: 'topic-1',
+ status: 'processing',
+ taskId: 'task-1',
+ updatedAt: '123',
+ userId: 'user-1',
+ workspaceId: '',
+ });
+ const store = new TaskResultCallbackRedisStore(
+ 'user-1',
+ 'topic-1',
+ undefined,
+ redis as unknown as Redis,
+ );
+
+ await expect(store.claimPending()).resolves.toEqual([
+ expect.objectContaining({
+ attempts: 1,
+ callbackMessageId: 'message-1',
+ id: 'operation-1',
+ status: 'processing',
+ }),
+ ]);
+ });
+
+ it('recognizes a fully delivered batch for webhook dedupe', async () => {
+ redis.hget.mockResolvedValue('delivered');
+ const store = new TaskResultCallbackRedisStore(
+ 'user-1',
+ 'topic-1',
+ undefined,
+ redis as unknown as Redis,
+ );
+
+ await expect(store.areDelivered(['operation-1', 'operation-2'])).resolves.toBe(true);
+ });
+
+ it('stores a monotonic per-operation delivery checkpoint', async () => {
+ redis.eval.mockResolvedValue(2);
+ const store = new TaskResultCallbackRedisStore(
+ 'user-1',
+ 'topic-1',
+ undefined,
+ redis as unknown as Redis,
+ );
+
+ await store.markDeliveryChunk('creator-operation-1', 2);
+
+ expect(redis.eval).toHaveBeenCalledWith(
+ expect.stringContaining('if next > current'),
+ 1,
+ 'task-result-callback:delivery:creator-operation-1',
+ 2,
+ 6 * 60 * 60,
+ );
+ });
+
+ it('returns due recovery scopes and prunes expired scope metadata', async () => {
+ redis.zrange.mockResolvedValue(['valid-scope', 'expired-scope']);
+ redis.hgetall
+ .mockResolvedValueOnce({
+ agentId: 'agent-1',
+ originTopicId: 'topic-1',
+ userId: 'user-1',
+ })
+ .mockResolvedValueOnce({});
+
+ await expect(
+ TaskResultCallbackRedisStore.findRecoverableScopes(redis as unknown as Redis),
+ ).resolves.toEqual([
+ {
+ agentId: 'agent-1',
+ originTopicId: 'topic-1',
+ scopeKey: 'valid-scope',
+ userId: 'user-1',
+ workspaceId: undefined,
+ },
+ ]);
+ expect(redis.zrem).toHaveBeenCalledWith('task-result-callback:recovery', 'expired-scope');
+ });
+
+ it('requeues a stale processing batch for watchdog recovery', async () => {
+ redis.get.mockResolvedValue('1');
+ redis.lrange.mockResolvedValue(['operation-1']);
+ redis.eval.mockResolvedValue(1);
+ const store = new TaskResultCallbackRedisStore(
+ 'user-1',
+ 'topic-1',
+ undefined,
+ redis as unknown as Redis,
+ );
+
+ await store.resetStaleProcessing();
+
+ expect(redis.lrange).toHaveBeenCalledWith(
+ 'task-result-callback:processing:user-1:personal:topic-1',
+ 0,
+ -1,
+ );
+ expect(redis.eval).toHaveBeenCalledWith(
+ expect.stringContaining("'status', 'pending'"),
+ 4,
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ 'Creator callback processing timed out',
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ 'operation-1',
+ );
+ });
+
+ it('keeps a delivered marker so a delayed QStash redelivery stays deduped', async () => {
+ redis.eval.mockResolvedValue(1);
+ const store = new TaskResultCallbackRedisStore(
+ 'user-1',
+ 'topic-1',
+ undefined,
+ redis as unknown as Redis,
+ );
+
+ await store.settle(['operation-1']);
+
+ expect(redis.eval).toHaveBeenCalledWith(
+ expect.stringContaining("'status', 'delivered'"),
+ 4,
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ 'task-result-callback:receipt:',
+ expect.anything(),
+ String(6 * 60 * 60),
+ 'user-1:personal:topic-1',
+ expect.anything(),
+ 'operation-1',
+ );
+ });
+});
diff --git a/apps/server/src/services/taskResultBridge/redisStore.ts b/apps/server/src/services/taskResultBridge/redisStore.ts
new file mode 100644
index 00000000000..34b98ca8393
--- /dev/null
+++ b/apps/server/src/services/taskResultBridge/redisStore.ts
@@ -0,0 +1,345 @@
+import type Redis from 'ioredis';
+
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+const PREFIX = 'task-result-callback:';
+const RECEIPT_TTL_SECONDS = 6 * 60 * 60;
+const PENDING_RETRY_DELAY_MS = 60_000;
+const PROCESSING_TIMEOUT_MS = 35 * 60_000;
+
+const MARK_DELIVERY_CHUNK_SCRIPT = `
+local current = tonumber(redis.call('GET', KEYS[1]) or '0')
+local next = tonumber(ARGV[1])
+if next > current then redis.call('SET', KEYS[1], next, 'EX', ARGV[2]) end
+return math.max(current, next)
+`;
+
+export interface TaskResultCallbackReceipt {
+ attempts: number;
+ callbackMessageId: string;
+ creatorOperationId?: string;
+ error?: string;
+ id: string;
+ operationId: string;
+ originTopicId: string;
+ status: 'pending' | 'processing';
+ taskId: string;
+ taskTopicId?: string;
+ updatedAt: number;
+ userId: string;
+ workspaceId: string | undefined;
+}
+
+export interface TaskResultCallbackScope {
+ agentId: string;
+ originTopicId: string;
+ scopeKey: string;
+ userId: string;
+ workspaceId: string | undefined;
+}
+
+interface CreatePendingParams {
+ agentId: string;
+ callbackMessageId: string;
+ operationId: string;
+ taskId: string;
+ taskTopicId?: string;
+}
+
+const CREATE_PENDING_SCRIPT = `
+local status = redis.call('HGET', KEYS[1], 'status')
+if status then return status end
+redis.call('HSET', KEYS[1], unpack(ARGV, 1, 22))
+redis.call('EXPIRE', KEYS[1], ARGV[23])
+redis.call('ZADD', KEYS[2], ARGV[24], ARGV[25])
+redis.call('EXPIRE', KEYS[2], ARGV[23])
+redis.call('HSET', KEYS[3], unpack(ARGV, 26, 33))
+redis.call('EXPIRE', KEYS[3], ARGV[23])
+redis.call('ZADD', KEYS[4], ARGV[34], ARGV[35])
+return 'pending'
+`;
+
+const CLAIM_SCRIPT = `
+if redis.call('EXISTS', KEYS[2]) == 1 then return {} end
+local ids = redis.call('ZRANGE', KEYS[1], 0, -1)
+if #ids == 0 then
+ redis.call('ZREM', KEYS[3], ARGV[1])
+ return {}
+end
+redis.call('DEL', KEYS[2])
+for _, id in ipairs(ids) do
+ redis.call('RPUSH', KEYS[2], id)
+ redis.call('HSET', ARGV[2] .. id, 'status', 'processing', 'updatedAt', ARGV[3])
+ redis.call('HINCRBY', ARGV[2] .. id, 'attempts', 1)
+ redis.call('ZREM', KEYS[1], id)
+end
+redis.call('EXPIRE', KEYS[2], ARGV[4])
+redis.call('SET', KEYS[4], ARGV[3], 'EX', ARGV[4])
+redis.call('ZADD', KEYS[3], ARGV[5], ARGV[1])
+return ids
+`;
+
+const RELEASE_SCRIPT = `
+redis.call('DEL', KEYS[2], KEYS[3])
+for index = 7, #ARGV do
+ local id = ARGV[index]
+ redis.call('HSET', ARGV[1] .. id, 'status', 'pending', 'creatorOperationId', '', 'error', ARGV[2], 'updatedAt', ARGV[3])
+ redis.call('ZADD', KEYS[1], ARGV[3], id)
+end
+redis.call('EXPIRE', KEYS[1], ARGV[4])
+redis.call('ZADD', KEYS[4], ARGV[5], ARGV[6])
+return #ARGV - 6
+`;
+
+const SETTLE_SCRIPT = `
+redis.call('DEL', KEYS[1], KEYS[2])
+for index = 6, #ARGV do
+ local id = ARGV[index]
+ redis.call('HSET', ARGV[1] .. id, 'status', 'delivered', 'updatedAt', ARGV[2])
+ redis.call('EXPIRE', ARGV[1] .. id, ARGV[3])
+end
+if redis.call('ZCARD', KEYS[3]) == 0 then
+ redis.call('ZREM', KEYS[4], ARGV[4])
+else
+ redis.call('ZADD', KEYS[4], ARGV[5], ARGV[4])
+end
+return #ARGV - 5
+`;
+
+const parseReceipt = (payload: Record<string, string>): TaskResultCallbackReceipt | undefined => {
+ if (!payload.id || !payload.operationId || !payload.originTopicId || !payload.userId) return;
+ if (payload.status !== 'pending' && payload.status !== 'processing') return;
+
+ return {
+ attempts: Number(payload.attempts || 0),
+ callbackMessageId: payload.callbackMessageId,
+ creatorOperationId: payload.creatorOperationId || undefined,
+ error: payload.error || undefined,
+ id: payload.id,
+ operationId: payload.operationId,
+ originTopicId: payload.originTopicId,
+ status: payload.status,
+ taskId: payload.taskId,
+ taskTopicId: payload.taskTopicId || undefined,
+ updatedAt: Number(payload.updatedAt),
+ userId: payload.userId,
+ workspaceId: payload.workspaceId || undefined,
+ };
+};
+
+export class TaskResultCallbackRedisStore {
+ private readonly redis: Redis;
+ private readonly scopeKey: string;
+
+ constructor(
+ private readonly userId: string,
+ private readonly originTopicId: string,
+ private readonly workspaceId?: string,
+ redis = getAgentRuntimeRedisClient(),
+ ) {
+ if (!redis) throw new Error('Redis is required for task result callbacks');
+ this.redis = redis;
+ this.scopeKey = `${userId}:${workspaceId || 'personal'}:${originTopicId}`;
+ }
+
+ static async findRecoverableScopes(
+ redis = getAgentRuntimeRedisClient(),
+ ): Promise<TaskResultCallbackScope[]> {
+ if (!redis) throw new Error('Redis is required for task result callbacks');
+ const scopeKeys = await redis.zrange(
+ `${PREFIX}recovery`,
+ '-inf',
+ Date.now(),
+ 'BYSCORE',
+ 'LIMIT',
+ 0,
+ 100,
+ );
+ const scopes = await Promise.all(
+ scopeKeys.map(async (scopeKey) => {
+ const payload = await redis.hgetall(`${PREFIX}scope:${scopeKey}`);
+ if (!payload.agentId || !payload.originTopicId || !payload.userId) return;
+ return {
+ agentId: payload.agentId,
+ originTopicId: payload.originTopicId,
+ scopeKey,
+ userId: payload.userId,
+ workspaceId: payload.workspaceId || undefined,
+ };
+ }),
+ );
+ const missingScopeKeys = scopeKeys.filter((_, index) => !scopes[index]);
+ if (missingScopeKeys.length > 0) {
+ await redis.zrem(`${PREFIX}recovery`, ...missingScopeKeys);
+ }
+ return scopes.filter((scope): scope is TaskResultCallbackScope => Boolean(scope));
+ }
+
+ async createPending(params: CreatePendingParams): Promise<void> {
+ const now = Date.now();
+ await this.redis.eval(
+ CREATE_PENDING_SCRIPT,
+ 4,
+ this.receiptKey(params.operationId),
+ this.pendingKey,
+ this.scopeMetadataKey,
+ `${PREFIX}recovery`,
+ 'attempts',
+ '0',
+ 'callbackMessageId',
+ params.callbackMessageId,
+ 'id',
+ params.operationId,
+ 'operationId',
+ params.operationId,
+ 'originTopicId',
+ this.originTopicId,
+ 'status',
+ 'pending',
+ 'taskId',
+ params.taskId,
+ 'taskTopicId',
+ params.taskTopicId || '',
+ 'updatedAt',
+ String(now),
+ 'userId',
+ this.userId,
+ 'workspaceId',
+ this.workspaceId || '',
+ String(RECEIPT_TTL_SECONDS),
+ String(now),
+ params.operationId,
+ 'agentId',
+ params.agentId,
+ 'originTopicId',
+ this.originTopicId,
+ 'userId',
+ this.userId,
+ 'workspaceId',
+ this.workspaceId || '',
+ String(now + PENDING_RETRY_DELAY_MS),
+ this.scopeKey,
+ );
+ }
+
+ async getDeliveredChunkCount(operationId: string): Promise<number> {
+ return Number((await this.redis.get(this.deliveryKey(operationId))) || 0);
+ }
+
+ async markDeliveryChunk(operationId: string, deliveredChunkCount: number): Promise<void> {
+ await this.redis.eval(
+ MARK_DELIVERY_CHUNK_SCRIPT,
+ 1,
+ this.deliveryKey(operationId),
+ deliveredChunkCount,
+ RECEIPT_TTL_SECONDS,
+ );
+ }
+
+ async claimPending(): Promise<TaskResultCallbackReceipt[]> {
+ const now = Date.now();
+ const ids = (await this.redis.eval(
+ CLAIM_SCRIPT,
+ 4,
+ this.pendingKey,
+ this.processingKey,
+ `${PREFIX}recovery`,
+ this.processingStartedAtKey,
+ this.scopeKey,
+ `${PREFIX}receipt:`,
+ String(now),
+ String(RECEIPT_TTL_SECONDS),
+ String(now + PROCESSING_TIMEOUT_MS),
+ )) as string[];
+ const receipts = await Promise.all(ids.map((id) => this.redis.hgetall(this.receiptKey(id))));
+ return receipts
+ .map(parseReceipt)
+ .filter((receipt): receipt is TaskResultCallbackReceipt => Boolean(receipt));
+ }
+
+ async attachCreatorOperation(ids: string[], creatorOperationId: string): Promise<void> {
+ if (ids.length === 0) return;
+ const transaction = this.redis.multi();
+ for (const id of ids) {
+ transaction.hset(this.receiptKey(id), { creatorOperationId, updatedAt: String(Date.now()) });
+ }
+ await transaction.exec();
+ }
+
+ async areDelivered(ids: string[]): Promise<boolean> {
+ if (ids.length === 0) return true;
+ const statuses = await Promise.all(
+ ids.map((id) => this.redis.hget(this.receiptKey(id), 'status')),
+ );
+ return statuses.every((status) => status === 'delivered');
+ }
+
+ async release(ids: string[], error: string): Promise<void> {
+ if (ids.length === 0) return;
+ const now = Date.now();
+ await this.redis.eval(
+ RELEASE_SCRIPT,
+ 4,
+ this.pendingKey,
+ this.processingKey,
+ this.processingStartedAtKey,
+ `${PREFIX}recovery`,
+ `${PREFIX}receipt:`,
+ error,
+ String(now),
+ String(RECEIPT_TTL_SECONDS),
+ String(now + PENDING_RETRY_DELAY_MS),
+ this.scopeKey,
+ ...ids,
+ );
+ }
+
+ async resetStaleProcessing(): Promise<void> {
+ const startedAt = Number((await this.redis.get(this.processingStartedAtKey)) || 0);
+ if (!startedAt || startedAt > Date.now() - PROCESSING_TIMEOUT_MS) return;
+ const ids = await this.redis.lrange(this.processingKey, 0, -1);
+ await this.release(ids, 'Creator callback processing timed out');
+ }
+
+ async settle(ids: string[]): Promise<void> {
+ if (ids.length === 0) return;
+ await this.redis.eval(
+ SETTLE_SCRIPT,
+ 4,
+ this.processingKey,
+ this.processingStartedAtKey,
+ this.pendingKey,
+ `${PREFIX}recovery`,
+ `${PREFIX}receipt:`,
+ String(Date.now()),
+ String(RECEIPT_TTL_SECONDS),
+ this.scopeKey,
+ String(Date.now() + PENDING_RETRY_DELAY_MS),
+ ...ids,
+ );
+ }
+
+ private get pendingKey() {
+ return `${PREFIX}pending:${this.scopeKey}`;
+ }
+
+ private get processingKey() {
+ return `${PREFIX}processing:${this.scopeKey}`;
+ }
+
+ private get processingStartedAtKey() {
+ return `${PREFIX}processing-started:${this.scopeKey}`;
+ }
+
+ private receiptKey(operationId: string) {
+ return `${PREFIX}receipt:${operationId}`;
+ }
+
+ private deliveryKey(operationId: string) {
+ return `${PREFIX}delivery:${operationId}`;
+ }
+
+ private get scopeMetadataKey() {
+ return `${PREFIX}scope:${this.scopeKey}`;
+ }
+}
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index 967e5a18328..17aac325a05 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -216,6 +216,7 @@ export class TaskRunnerService {
// knows whether this was a manual run or an automation tick.
body: { runTrigger: trigger, taskId, taskIdentifier, userId },
delivery: 'qstash' as const,
+ fallback: 'none' as const,
url: '/api/workflows/task/on-topic-complete',
},
},
diff --git a/apps/server/src/workflows-hono/task/handlers/onCreatorComplete.test.ts b/apps/server/src/workflows-hono/task/handlers/onCreatorComplete.test.ts
new file mode 100644
index 00000000000..d31cb96cec7
--- /dev/null
+++ b/apps/server/src/workflows-hono/task/handlers/onCreatorComplete.test.ts
@@ -0,0 +1,106 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { onCreatorComplete } from './onCreatorComplete';
+
+const {
+ areDelivered,
+ completeCreatorWakeup,
+ getDeliveredChunkCount,
+ getServerDB,
+ handleCallback,
+ markDeliveryChunk,
+} = vi.hoisted(() => ({
+ areDelivered: vi.fn(),
+ completeCreatorWakeup: vi.fn(),
+ getDeliveredChunkCount: vi.fn(),
+ getServerDB: vi.fn(),
+ handleCallback: vi.fn(),
+ markDeliveryChunk: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({ getServerDB }));
+vi.mock('@/server/services/bot/BotCallbackService', () => ({
+ BotCallbackService: vi.fn(() => ({ handleCallback })),
+}));
+vi.mock('@/server/services/taskResultBridge', () => ({
+ TaskResultBridgeService: vi.fn(() => ({ completeCreatorWakeup })),
+}));
+vi.mock('@/server/services/taskResultBridge/redisStore', () => ({
+ TaskResultCallbackRedisStore: vi.fn(() => ({
+ areDelivered,
+ getDeliveredChunkCount,
+ markDeliveryChunk,
+ })),
+}));
+
+const makeContext = (body: Record<string, unknown>) => {
+ const json = vi.fn((payload, status = 200) => ({ payload, status }));
+ return {
+ context: { json, req: { json: vi.fn().mockResolvedValue(body) } } as any,
+ json,
+ };
+};
+
+const payload = {
+ agentId: 'agent-creator',
+ applicationId: 'messenger-discord',
+ lastAssistantContent: 'The task result is ready.',
+ operationId: 'op-creator',
+ originTopicId: 'topic-origin',
+ platformThreadId: 'discord:guild:channel:thread',
+ reason: 'done',
+ receiptIds: ['receipt-1'],
+ userId: 'user-1',
+};
+
+describe('onCreatorComplete', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getServerDB.mockResolvedValue({});
+ handleCallback.mockResolvedValue(undefined);
+ completeCreatorWakeup.mockResolvedValue(undefined);
+ areDelivered.mockResolvedValue(false);
+ getDeliveredChunkCount.mockResolvedValue(1);
+ markDeliveryChunk.mockResolvedValue(undefined);
+ });
+
+ it('delivers to Messenger before settling the callback receipt', async () => {
+ const { context } = makeContext(payload);
+
+ const response = await onCreatorComplete(context);
+
+ expect(response).toMatchObject({ status: 200 });
+ expect(handleCallback).toHaveBeenCalledWith(
+ expect.objectContaining({
+ lastAssistantContent: 'The task result is ready.',
+ platformThreadId: 'discord:guild:channel:thread',
+ type: 'completion',
+ }),
+ expect.objectContaining({ deliveredChunkCount: 1, strictDelivery: true }),
+ );
+ expect(handleCallback.mock.invocationCallOrder[0]).toBeLessThan(
+ completeCreatorWakeup.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('keeps the receipt processing when Messenger delivery fails', async () => {
+ handleCallback.mockRejectedValue(new Error('Discord unavailable'));
+ const { context } = makeContext(payload);
+
+ const response = await onCreatorComplete(context);
+
+ expect(response).toMatchObject({ status: 500 });
+ expect(completeCreatorWakeup).not.toHaveBeenCalled();
+ });
+
+ it('does not redeliver Messenger output after the receipt was settled', async () => {
+ areDelivered.mockResolvedValue(true);
+ const { context } = makeContext(payload);
+
+ const response = await onCreatorComplete(context);
+
+ expect(response).toMatchObject({ payload: { deduped: true, success: true }, status: 200 });
+ expect(handleCallback).not.toHaveBeenCalled();
+ expect(completeCreatorWakeup).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/workflows-hono/task/handlers/onCreatorComplete.ts b/apps/server/src/workflows-hono/task/handlers/onCreatorComplete.ts
new file mode 100644
index 00000000000..90da237f16f
--- /dev/null
+++ b/apps/server/src/workflows-hono/task/handlers/onCreatorComplete.ts
@@ -0,0 +1,71 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { getServerDB } from '@/database/server';
+import type { BotCallbackBody } from '@/server/services/bot/BotCallbackService';
+import { BotCallbackService } from '@/server/services/bot/BotCallbackService';
+import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
+import { TaskResultCallbackRedisStore } from '@/server/services/taskResultBridge/redisStore';
+
+const log = debug('lobe-server:workflows:task:on-creator-complete');
+
+interface OnCreatorCompletePayload extends Partial<BotCallbackBody> {
+ agentId: string;
+ operationId: string;
+ originTopicId: string;
+ receiptIds: string[];
+ userId: string;
+ workspaceId?: string;
+}
+
+export async function onCreatorComplete(c: Context) {
+ try {
+ const body = (await c.req.json()) as OnCreatorCompletePayload;
+ if (
+ !body.agentId ||
+ !body.operationId ||
+ !body.originTopicId ||
+ !body.userId ||
+ !Array.isArray(body.receiptIds)
+ ) {
+ return c.json({ error: 'Missing required fields' }, 400);
+ }
+
+ const db = await getServerDB();
+ const callbackStore = new TaskResultCallbackRedisStore(
+ body.userId,
+ body.originTopicId,
+ body.workspaceId,
+ );
+ if (await callbackStore.areDelivered(body.receiptIds)) {
+ return c.json({ deduped: true, success: true });
+ }
+ const deliveredChunkCount = await callbackStore.getDeliveredChunkCount(body.operationId);
+ // Messenger delivery and receipt settlement intentionally share this
+ // retryable QStash handler. A platform failure returns 500, so the receipt
+ // stays processing and QStash retries instead of reporting a false success.
+ if (body.platformThreadId && body.applicationId) {
+ await new BotCallbackService(db).handleCallback(
+ {
+ ...body,
+ type: 'completion',
+ } as BotCallbackBody,
+ {
+ deliveredChunkCount,
+ onChunkDelivered: (count) => callbackStore.markDeliveryChunk(body.operationId, count),
+ strictDelivery: true,
+ },
+ );
+ }
+ await new TaskResultBridgeService(db, body.userId, body.workspaceId).completeCreatorWakeup({
+ agentId: body.agentId,
+ originTopicId: body.originTopicId,
+ receiptIds: body.receiptIds,
+ });
+ log('settled creator operation=%s receipts=%d', body.operationId, body.receiptIds.length);
+ return c.json({ success: true });
+ } catch (error) {
+ console.error('[task/on-creator-complete] Error:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
diff --git a/apps/server/src/workflows-hono/task/handlers/watchdog.ts b/apps/server/src/workflows-hono/task/handlers/watchdog.ts
index 1be6be6f3f2..84ec6e8ef6e 100644
--- a/apps/server/src/workflows-hono/task/handlers/watchdog.ts
+++ b/apps/server/src/workflows-hono/task/handlers/watchdog.ts
@@ -4,6 +4,8 @@ import type { Context } from 'hono';
import { BriefModel } from '@/database/models/brief';
import { TaskModel } from '@/database/models/task';
import { getServerDB } from '@/database/server';
+import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
+import { TaskResultCallbackRedisStore } from '@/server/services/taskResultBridge/redisStore';
const log = debug('lobe-server:workflows:task:watchdog');
@@ -44,10 +46,41 @@ export async function watchdog(c: Context) {
failed.push(task.identifier);
}
- log('Watchdog scan: checked=%d failed=%d', stuckTasks.length, failed.length);
+ const recoverableCallbacks = await TaskResultCallbackRedisStore.findRecoverableScopes();
+ const recoveredCallbacks: string[] = [];
+ for (const scope of recoverableCallbacks) {
+ if (!scope.agentId) continue;
+ try {
+ const workspaceId = scope.workspaceId ?? undefined;
+ const callbackStore = new TaskResultCallbackRedisStore(
+ scope.userId,
+ scope.originTopicId,
+ workspaceId,
+ );
+ await callbackStore.resetStaleProcessing();
+ await new TaskResultBridgeService(db, scope.userId, workspaceId).drain(
+ scope.agentId,
+ scope.originTopicId,
+ );
+ recoveredCallbacks.push(scope.originTopicId);
+ } catch (error) {
+ console.error(
+ `[task/watchdog] Failed to recover creator callback scope ${scope.originTopicId}:`,
+ error,
+ );
+ }
+ }
+
+ log(
+ 'Watchdog scan: checked=%d failed=%d callbacks=%d',
+ stuckTasks.length,
+ failed.length,
+ recoveredCallbacks.length,
+ );
return c.json({
checked: stuckTasks.length,
failed,
+ recoveredCallbacks,
success: true,
});
} catch (error) {
diff --git a/apps/server/src/workflows-hono/task/index.ts b/apps/server/src/workflows-hono/task/index.ts
index 0632b3ffe7a..f62924ebe0f 100644
--- a/apps/server/src/workflows-hono/task/index.ts
+++ b/apps/server/src/workflows-hono/task/index.ts
@@ -2,6 +2,7 @@ import { Hono } from 'hono';
import { qstashAuth } from '../middlewares/qstashAuth';
import { heartbeatTick } from './handlers/heartbeatTick';
+import { onCreatorComplete } from './handlers/onCreatorComplete';
import { onTopicComplete } from './handlers/onTopicComplete';
import { scheduleDispatch } from './handlers/scheduleDispatch';
import { scheduledTopicDispatch } from './handlers/scheduledTopicDispatch';
@@ -11,6 +12,7 @@ import { watchdog } from './handlers/watchdog';
const app = new Hono();
app.post('/on-topic-complete', qstashAuth(), onTopicComplete);
+app.post('/on-creator-complete', qstashAuth(), onCreatorComplete);
app.post('/heartbeat-tick', qstashAuth(), heartbeatTick);
app.post('/schedule-dispatch', qstashAuth(), scheduleDispatch);
app.post('/schedule-execute', qstashAuth(), scheduleExecute);