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.

✨ feat(task): bridge finished task handoff back to creator conversation (#16238)

Arvin Xu461472129cc5
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index c4e701bd574..756a275adb9 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -31,6 +31,7 @@ import { TopicModel } from '@/database/models/topic';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { SystemAgentService } from '@/server/services/systemAgent';
+import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
import { TaskReviewService } from '@/server/services/taskReview';
import { createTaskSchedulerModule } from '@/server/services/taskScheduler';
@@ -142,7 +143,12 @@ export class TaskLifecycleService {
)
: false;
- if (reviewTerminated) return;
+ if (reviewTerminated) {
+ // Review (Judge) already transitioned the task to its terminal state —
+ // bridge the result here before the early return.
+ await this.bridgeResultToCreator(params);
+ return;
+ }
// 4. Synthesize a programmatic brief for the user (auto mode only).
// The agent-driven `createBrief` tool path stays the default until
@@ -208,6 +214,14 @@ export class TaskLifecycleService {
await this.taskModel.updateStatus(taskId, 'paused');
}
+ // Bridge the finished task's handoff back to the creator conversation
+ // (LOBE-10625). Runs HERE — after all status transitions above — so the
+ // bridge reads the settled task status. Doing it as a separate webhook
+ // racing `on-topic-complete` could observe the pre-transition status and
+ // silently drop the only callback for automation tasks that become terminal
+ // in this path (e.g. a scheduled task hitting its execution cap).
+ await this.bridgeResultToCreator(params);
+
// Heartbeat re-arm: re-read task state (status / context may have just
// been mutated by the branches above) and decide whether to publish the
// next tick.
@@ -215,6 +229,27 @@ export class TaskLifecycleService {
if (finalTask) await this.maybeRearmHeartbeat(finalTask, reason);
}
+ /**
+ * Deliver the finished task's result back to the conversation that created
+ * it. Always best-effort: a bridge failure must never affect task status, so
+ * it's wrapped here and the underlying service also avoids throwing.
+ */
+ private async bridgeResultToCreator(params: TopicCompleteParams): Promise<void> {
+ try {
+ await new TaskResultBridgeService(this.db, this.userId, this.workspaceId).deliver({
+ errorMessage: params.errorMessage,
+ lastAssistantContent: params.lastAssistantContent,
+ operationId: params.operationId,
+ reason: params.reason,
+ taskId: params.taskId,
+ taskIdentifier: params.taskIdentifier,
+ topicId: params.topicId,
+ });
+ } catch (error) {
+ log('result bridge failed for task=%s (non-fatal): %O', params.taskIdentifier, error);
+ }
+ }
+
/**
* Has the task already consumed every allowed scheduled execution?
*
diff --git a/apps/server/src/services/taskResultBridge/index.test.ts b/apps/server/src/services/taskResultBridge/index.test.ts
new file mode 100644
index 00000000000..96993abff1e
--- /dev/null
+++ b/apps/server/src/services/taskResultBridge/index.test.ts
@@ -0,0 +1,173 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+
+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 } = vi.hoisted(() => ({ createMsg: vi.fn(), execAgent: vi.fn() }));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn(() => ({ create: createMsg })),
+}));
+
+vi.mock('../aiAgent', () => ({
+ AiAgentService: vi.fn(() => ({ execAgent })),
+}));
+
+const TEST_USER = 'user-1';
+const db = {} as any;
+
+const ORIGIN = {
+ agentId: 'agent-creator',
+ messageId: 'msg-anchor',
+ operationId: 'op-creator',
+ toolCallId: 'tc-1',
+ topicId: 'topic-origin',
+};
+
+const baseParams = {
+ operationId: 'op-task',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ topicId: 'topic-done',
+};
+
+describe('TaskResultBridgeService.deliver', () => {
+ // Loosely typed: vi.spyOn's generic MockInstance isn't assignable from the
+ // method-specific spy types (TaskModel.findById / TaskTopicModel.findByTopicId).
+ let findById: any;
+ let findByTopicId: any;
+
+ beforeEach(() => {
+ createMsg.mockReset().mockResolvedValue({ id: 'task-cb-task-1-topic-done' } as any);
+ execAgent
+ .mockReset()
+ .mockResolvedValue({ operationId: 'op-new', topicId: 'topic-origin' } as any);
+ findById = vi.spyOn(TaskModel.prototype, 'findById').mockResolvedValue({
+ automationMode: null,
+ context: { origin: ORIGIN },
+ status: 'running',
+ } as any);
+ findByTopicId = vi.spyOn(TaskTopicModel.prototype, 'findByTopicId').mockResolvedValue({
+ handoff: {
+ keyFindings: ['a', 'b'],
+ nextAction: 'ship it',
+ summary: 'Fixed the null deref',
+ title: 'Fix',
+ },
+ } as any);
+ });
+
+ afterEach(() => vi.restoreAllMocks());
+
+ it('appends a taskCallback card to the origin topic and runs the creator agent off history', async () => {
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+
+ expect(createMsg).toHaveBeenCalledTimes(1);
+ const [params, id] = createMsg.mock.calls[0] as [any, string];
+ expect(params).toMatchObject({
+ agentId: 'agent-creator',
+ parentId: 'msg-anchor',
+ role: 'taskCallback',
+ topicId: 'topic-origin',
+ });
+ expect(params.metadata.taskCallback).toMatchObject({
+ identifier: 'T-1',
+ reason: 'done',
+ taskId: 'task-1',
+ topicId: 'topic-done',
+ });
+ expect(params.content).toContain('Fixed the null deref');
+ expect(params.content).toContain('ship it');
+ // deterministic id keyed on (task, completed topic) for idempotency
+ expect(id).toBe('task-cb-task-1-topic-done');
+
+ expect(execAgent).toHaveBeenCalledTimes(1);
+ expect(execAgent.mock.calls[0][0]).toMatchObject({
+ agentId: 'agent-creator',
+ appContext: { topicId: 'topic-origin' },
+ parentMessageId: 'task-cb-task-1-topic-done',
+ suppressUserMessage: true,
+ });
+ });
+
+ it('skips tasks with no origin (e.g. API-created)', async () => {
+ findById.mockResolvedValue({ context: {}, status: 'completed' } as any);
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+
+ 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' }),
+ );
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+
+ expect(execAgent).not.toHaveBeenCalled();
+ });
+
+ it('bridges a failed run with the error text and reason', async () => {
+ findByTopicId.mockResolvedValue({ handoff: undefined } as any);
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver({
+ ...baseParams,
+ errorMessage: 'boom: provider 500',
+ reason: 'error',
+ });
+
+ const [params] = createMsg.mock.calls[0] as [any, string];
+ expect(params.metadata.taskCallback.reason).toBe('error');
+ expect(params.content).toContain('boom: provider 500');
+ });
+
+ it('defers automation tasks until the task itself is terminal', async () => {
+ findById.mockResolvedValue({
+ automationMode: 'schedule',
+ context: { origin: ORIGIN },
+ status: 'running',
+ } as any);
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+
+ expect(createMsg).not.toHaveBeenCalled();
+ expect(execAgent).not.toHaveBeenCalled();
+ });
+
+ // The bridge runs from onTopicComplete AFTER status transitions, so a
+ // scheduled task that hit its cap is already `completed` when we read it —
+ // the callback must NOT be dropped (the race that this fix closes).
+ it('bridges an automation task once it has reached a terminal status', async () => {
+ findById.mockResolvedValue({
+ automationMode: 'schedule',
+ context: { origin: ORIGIN },
+ status: 'completed',
+ } as any);
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver(baseParams);
+
+ expect(createMsg).toHaveBeenCalledTimes(1);
+ expect(execAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to lastAssistantContent when the handoff is not yet written (cloud race)', async () => {
+ findByTopicId.mockResolvedValue({ handoff: undefined } as any);
+
+ await new TaskResultBridgeService(db, TEST_USER).deliver({
+ ...baseParams,
+ lastAssistantContent: 'Raw final output from the run',
+ });
+
+ const [params] = createMsg.mock.calls[0] as [any, string];
+ expect(params.content).toContain('Raw final output from the run');
+ });
+});
diff --git a/apps/server/src/services/taskResultBridge/index.ts b/apps/server/src/services/taskResultBridge/index.ts
new file mode 100644
index 00000000000..d23bd418e9a
--- /dev/null
+++ b/apps/server/src/services/taskResultBridge/index.ts
@@ -0,0 +1,181 @@
+import { RequestTrigger, type TaskContext, type TaskTopicHandoff } from '@lobechat/types';
+import debug from 'debug';
+
+import { MessageModel } from '@/database/models/message';
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { AiAgentService } from '../aiAgent';
+
+const log = debug('lobe-server:taskResultBridge');
+
+// Task statuses at which an automation task (heartbeat/schedule) is "done"
+// enough to report back — so we don't ping the creator on every tick.
+const TERMINAL_TASK_STATUS = new Set(['completed', 'failed', 'canceled']);
+
+type CallbackReason = 'done' | 'error' | 'interrupted';
+
+const FALLBACK_MAX_LENGTH = 2000;
+
+const normalizeReason = (reason: string): CallbackReason => {
+ if (reason === 'interrupted') return 'interrupted';
+ if (reason === 'error') return 'error';
+ // 'done' | 'max_steps' | 'cost_limit' | … → treat as a normal completion.
+ 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;
+
+/**
+ * Render the handoff (or a fallback) into the markdown body carried by the
+ * task-callback message: it is both the card body AND — wrapped by
+ * `TaskCallbackMessageProcessor` — what the creator agent reads to continue.
+ */
+const renderHandoff = (params: {
+ errorMessage?: string;
+ fallbackContent?: string;
+ handoff?: TaskTopicHandoff;
+ reason: CallbackReason;
+}): string => {
+ const { errorMessage, fallbackContent, handoff, reason } = params;
+
+ if (reason !== 'done') {
+ const lead = reason === 'error' ? 'The task failed.' : 'The task was interrupted.';
+ const detail = errorMessage?.trim() || handoff?.summary?.trim() || fallbackContent?.trim();
+ return detail ? `${lead}\n\n${truncate(detail)}` : lead;
+ }
+
+ const parts: string[] = [];
+ if (handoff?.title) parts.push(`### ${handoff.title}`);
+ const body = handoff?.summary?.trim() || fallbackContent?.trim();
+ if (body) parts.push(truncate(body));
+ if (handoff?.keyFindings?.length) {
+ parts.push(['**Key findings**', ...handoff.keyFindings.map((f) => `- ${f}`)].join('\n'));
+ }
+ if (handoff?.nextAction) parts.push(`**Next action:** ${handoff.nextAction}`);
+ return parts.join('\n\n') || 'Task completed.';
+};
+
+export interface DeliverTaskResultParams {
+ /** Error text when the run failed. */
+ errorMessage?: string;
+ /** Raw final assistant text from the run — fallback when the handoff isn't ready. */
+ lastAssistantContent?: string;
+ operationId: string;
+ /** Terminal reason from the lifecycle hook: 'done' | 'error' | 'interrupted' | … */
+ reason: string;
+ taskId: string;
+ taskIdentifier: string;
+ /** The task topic that just completed. */
+ topicId?: string;
+}
+
+/**
+ * Delivers a finished task's handoff back to the conversation that created it
+ * (LOBE-10625). Fire-and-forget: appends a `role='taskCallback'` card into the
+ * creator topic and runs the creator agent off history so it reads the result
+ * and continues — without impersonating a user turn.
+ *
+ * Invoked from `TaskLifecycleService.onTopicComplete` AFTER all status
+ * transitions, so the automation gate below reads the settled task status
+ * (never racing the post-tick terminal transition). The caller guards against
+ * throws so a bridge failure never affects task status.
+ */
+export class TaskResultBridgeService {
+ private db: LobeChatDatabase;
+ private userId: string;
+ private workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ async deliver(params: DeliverTaskResultParams): Promise<void> {
+ const { taskId, taskIdentifier, topicId } = params;
+
+ const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
+ const task = await taskModel.findById(taskId);
+ const origin = (task?.context as TaskContext | undefined)?.origin;
+
+ // No creator conversation to report back to (e.g. task created via API).
+ if (!origin?.agentId || !origin?.topicId) {
+ log('no origin for task %s, skipping bridge', taskIdentifier);
+ return;
+ }
+
+ // Automation tasks (heartbeat/schedule) run many topics — only bridge once
+ // the task itself reaches a terminal state, to avoid per-tick spam. One-shot
+ // tasks have no automationMode and bridge on topic completion.
+ if (task?.automationMode && !TERMINAL_TASK_STATUS.has(task.status)) {
+ log('automation task %s not terminal (%s), deferring bridge', taskIdentifier, task.status);
+ return;
+ }
+
+ const reason = normalizeReason(params.reason);
+
+ const handoff = topicId
+ ? (await new TaskTopicModel(this.db, this.userId, this.workspaceId).findByTopicId(topicId))
+ ?.handoff
+ : undefined;
+
+ const content = renderHandoff({
+ errorMessage: params.errorMessage,
+ fallbackContent: params.lastAssistantContent,
+ handoff: handoff ?? undefined,
+ reason,
+ });
+
+ // Idempotency: a deterministic id keyed on (task, completed topic). QStash
+ // can redeliver the `on-topic-complete` webhook (which drives this bridge) —
+ // the second create loses the PK race and we skip.
+ const messageId = `task-cb-${taskId}-${topicId ?? params.operationId}`;
+ const messageModel = new MessageModel(this.db, this.userId);
+ try {
+ await messageModel.create(
+ {
+ agentId: origin.agentId,
+ content,
+ metadata: {
+ taskCallback: { identifier: taskIdentifier, reason, taskId, topicId },
+ },
+ parentId: origin.messageId,
+ role: 'taskCallback',
+ topicId: origin.topicId,
+ },
+ messageId,
+ );
+ } catch (error) {
+ if (isDuplicateKeyError(error)) {
+ log('task-callback %s already delivered, skipping', messageId);
+ return;
+ }
+ 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' },
+ });
+
+ log('bridged task %s result into topic %s (%s)', taskIdentifier, origin.topicId, reason);
+ }
+}
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 0aa80b394ad..82673034350 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -648,6 +648,10 @@
"task.status.initializing": "Initializing task...",
"task.subtask": "Subtask",
"task.title": "Tasks",
+ "taskCallback.done": "Task completed",
+ "taskCallback.error": "Task failed",
+ "taskCallback.interrupted": "Task interrupted",
+ "taskCallback.viewTask": "View task",
"taskDetail.activities": "Activities",
"taskDetail.activities.agentTag": "Agent",
"taskDetail.activities.fallback.brief": "posted a brief",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 39efc15576d..7c4fa385759 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -648,6 +648,10 @@
"task.status.initializing": "任务启动中…",
"task.subtask": "子任务",
"task.title": "任务",
+ "taskCallback.done": "任务已完成",
+ "taskCallback.error": "任务失败",
+ "taskCallback.interrupted": "任务已中断",
+ "taskCallback.viewTask": "查看任务",
"taskDetail.activities": "活动",
"taskDetail.activities.agentTag": "智能体",
"taskDetail.activities.fallback.brief": "发布了简要说明",
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index b00528c4f81..da6edf4c481 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -17,6 +17,7 @@ import {
PlaceholderVariablesProcessor,
ReactionFeedbackProcessor,
SupervisorRoleRestoreProcessor,
+ TaskCallbackMessageProcessor,
TaskMessageProcessor,
TasksFlattenProcessor,
ToolCallProcessor,
@@ -411,6 +412,9 @@ export class MessagesEngine {
// Verify (delivery-checker) cards: drop empty UI-only ones; surface
// auto-repair failure feedback as a user turn for the repair run
new VerifyMessageProcessor(),
+ // Task-callback cards: surface a finished task's handoff as a user turn
+ // so the creator agent reads it and continues (LOBE-10625)
+ new TaskCallbackMessageProcessor(),
// Supervisor role restore
new SupervisorRoleRestoreProcessor(),
// Compressed group role transform
diff --git a/packages/context-engine/src/processors/TaskCallbackMessage.ts b/packages/context-engine/src/processors/TaskCallbackMessage.ts
new file mode 100644
index 00000000000..734466b5739
--- /dev/null
+++ b/packages/context-engine/src/processors/TaskCallbackMessage.ts
@@ -0,0 +1,61 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { PipelineContext } from '../types';
+
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ taskCallbackMessagesSurfaced?: number;
+ }
+}
+
+const log = debug('context-engine:processor:TaskCallbackMessageProcessor');
+
+/**
+ * Task Callback Message Processor
+ *
+ * `role='taskCallback'` messages are the result-bridge cards: when a task
+ * dispatched from this conversation finishes, the lifecycle injects one carrying
+ * the handoff summary (LOBE-10625). `taskCallback` is not a valid model role, so
+ * it can't reach the model as-is. We surface it as a `user` turn wrapped in a
+ * `<task_result>` tag — so the creator agent reads it as the task reporting back
+ * (not as human input) and continues the conversation off it.
+ *
+ * An empty-content card (no handoff text) is dropped from the model context; it
+ * stays persisted + rendered as a UI-only card.
+ */
+export class TaskCallbackMessageProcessor extends BaseProcessor {
+ readonly name = 'TaskCallbackMessageProcessor';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ let surfaced = 0;
+
+ clonedContext.messages = clonedContext.messages.flatMap((message) => {
+ if (message.role !== 'taskCallback') return [message];
+
+ const content = typeof message.content === 'string' ? message.content.trim() : '';
+ // UI-only card with no handoff text — drop it from the model context.
+ if (!content) return [];
+
+ const callback = message.metadata?.taskCallback;
+ const identifier = callback?.identifier ?? 'task';
+ const reason = callback?.reason ?? 'done';
+
+ surfaced += 1;
+ return [
+ {
+ ...message,
+ content: `<task_result task="${identifier}" status="${reason}">\n${content}\n</task_result>`,
+ role: 'user' as const,
+ },
+ ];
+ });
+
+ clonedContext.metadata.taskCallbackMessagesSurfaced = surfaced;
+ if (surfaced > 0) log(`Surfaced ${surfaced} task-callback message(s) as user turn(s)`);
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/processors/__tests__/TaskCallbackMessage.test.ts b/packages/context-engine/src/processors/__tests__/TaskCallbackMessage.test.ts
new file mode 100644
index 00000000000..0133d6de655
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/TaskCallbackMessage.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { TaskCallbackMessageProcessor } from '../TaskCallbackMessage';
+
+describe('TaskCallbackMessageProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ it('surfaces a task-callback card as a tagged user turn the model can read', async () => {
+ const processor = new TaskCallbackMessageProcessor();
+ const context = createContext([
+ { content: 'Fix the bug', role: 'user' },
+ { content: 'Dispatched T-42', role: 'assistant' },
+ {
+ content: 'Fixed the null deref in foo().',
+ metadata: { taskCallback: { identifier: 'T-42', reason: 'done', taskId: 't1' } },
+ role: 'taskCallback',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ const last = result.messages[2];
+ expect(last.role).toBe('user');
+ expect(last.content).toContain('<task_result task="T-42" status="done">');
+ expect(last.content).toContain('Fixed the null deref');
+ expect(result.metadata.taskCallbackMessagesSurfaced).toBe(1);
+ });
+
+ it('carries the failure reason into the wrapper status', async () => {
+ const processor = new TaskCallbackMessageProcessor();
+ const context = createContext([
+ {
+ content: 'The task failed.',
+ metadata: { taskCallback: { identifier: 'T-7', reason: 'error', taskId: 't7' } },
+ role: 'taskCallback',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].content).toContain('status="error"');
+ });
+
+ it('drops an empty UI-only task-callback card from the model context', async () => {
+ const processor = new TaskCallbackMessageProcessor();
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { content: ' \n ', role: 'taskCallback' },
+ { content: 'Hi', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages.map((m) => m.role)).toEqual(['user', 'assistant']);
+ expect(result.metadata.taskCallbackMessagesSurfaced).toBe(0);
+ });
+});
diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.ts
index 6d554f2eb54..425d240247f 100644
--- a/packages/context-engine/src/processors/index.ts
+++ b/packages/context-engine/src/processors/index.ts
@@ -21,6 +21,7 @@ export {
} from './PlaceholderVariables';
export { ReactionFeedbackProcessor } from './ReactionFeedback';
export { SupervisorRoleRestoreProcessor } from './SupervisorRoleRestore';
+export { TaskCallbackMessageProcessor } from './TaskCallbackMessage';
export { TaskMessageProcessor } from './TaskMessage';
export { TasksFlattenProcessor } from './TasksFlatten';
export { ToolCallProcessor } from './ToolCall';
diff --git a/packages/conversation-flow/src/__tests__/taskCallback.test.ts b/packages/conversation-flow/src/__tests__/taskCallback.test.ts
new file mode 100644
index 00000000000..8f150702c1b
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/taskCallback.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest';
+
+import { parse } from '../parse';
+import type { Message } from '../types/shared';
+
+// A task-callback card injected by the result-bridge (LOBE-10625) must survive
+// the display-flow transform as a standalone `role='taskCallback'` node so the
+// renderer can show it as a card — both as a leaf and mid-chain (when the
+// creator agent's continuation parents under it).
+describe('parse — taskCallback role', () => {
+ const callbackMeta = {
+ taskCallback: { identifier: 'T-1', reason: 'done' as const, taskId: 't1', topicId: 'tp1' },
+ };
+
+ it('keeps a leaf taskCallback message in the flatList with metadata intact', () => {
+ const messages = [
+ { content: 'dispatched', createdAt: 1, id: 'a1', role: 'assistant', updatedAt: 1 },
+ {
+ content: '## done\n\nsummary',
+ createdAt: 2,
+ id: 'cb1',
+ metadata: callbackMeta,
+ parentId: 'a1',
+ role: 'taskCallback',
+ updatedAt: 2,
+ },
+ ] as unknown as Message[];
+
+ const result = parse(messages);
+ const cb = result.flatList.find((m) => m.id === 'cb1');
+
+ expect(cb).toBeDefined();
+ expect(cb?.role).toBe('taskCallback');
+ expect((cb?.metadata as any)?.taskCallback?.identifier).toBe('T-1');
+ });
+
+ it('keeps a taskCallback mid-chain when a continuation parents under it', () => {
+ const messages = [
+ { content: 'dispatched', createdAt: 1, id: 'a1', role: 'assistant', updatedAt: 1 },
+ {
+ content: '## done',
+ createdAt: 2,
+ id: 'cb1',
+ metadata: callbackMeta,
+ parentId: 'a1',
+ role: 'taskCallback',
+ updatedAt: 2,
+ },
+ {
+ content: 'great, next?',
+ createdAt: 3,
+ id: 'a2',
+ parentId: 'cb1',
+ role: 'assistant',
+ updatedAt: 3,
+ },
+ ] as unknown as Message[];
+
+ const result = parse(messages);
+ const ids = result.flatList.map((m) => m.id);
+
+ // The card node must not be swallowed by the assistant chain around it.
+ expect(ids).toContain('cb1');
+ expect(result.flatList.find((m) => m.id === 'cb1')?.role).toBe('taskCallback');
+ expect(ids).toContain('a2');
+ });
+});
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index f40d12390ac..64f268e0005 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -716,6 +716,10 @@ export default {
'task.status.fetchingDetails': 'Fetching details...',
'task.status.initializing': 'Initializing task...',
'task.subtask': 'Subtask',
+ 'taskCallback.done': 'Task completed',
+ 'taskCallback.error': 'Task failed',
+ 'taskCallback.interrupted': 'Task interrupted',
+ 'taskCallback.viewTask': 'View task',
'taskSchedule.advancedSettings': 'Advanced settings',
'taskSchedule.clear': 'Clear',
'taskSchedule.continuous': 'Continuous',
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index ba0361e4540..ca4dc009abd 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -167,6 +167,17 @@ export const MessageSignalSchema = z.object({
type: z.enum(['tool-stdout', 'tool-callback', 'task-completion']),
});
+export const MessageTaskCallbackSchema = z.object({
+ // Task identifier (e.g. `T-42`) for the card header + jump link.
+ identifier: z.string(),
+ // Terminal outcome of the task run that produced this callback.
+ reason: z.enum(['done', 'error', 'interrupted']),
+ // The task id (jump target → task detail).
+ taskId: z.string(),
+ // The completed task topic, for an optional "view run" link.
+ topicId: z.string().optional(),
+});
+
export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSchema).extend({
collapsed: z.boolean().optional(),
inspectExpanded: z.boolean().optional(),
@@ -183,6 +194,9 @@ export const MessageMetadataSchema = ModelUsageSchema.merge(ModelPerformanceSche
// External-signal lineage for Monitor-style callback turns ().
signal: MessageSignalSchema.optional(),
subAgentId: z.string().optional(),
+ // role='taskCallback' card: which task delivered its handoff back to this
+ // conversation, and the run outcome. The card header + jump link read this.
+ taskCallback: MessageTaskCallbackSchema.optional(),
toolExecutionTimeMs: z.number().optional(),
trigger: z.nativeEnum(RequestTrigger).optional(),
// role='verify' card: which Agent Run (agent_operations.id) it renders.
@@ -350,6 +364,12 @@ export interface MessageMetadata {
* Used by callAgent tool (sub_agent) and group orchestration (group modes)
*/
subAgentId?: string;
+ /**
+ * Task-callback card pointer (for role='taskCallback' messages). Identifies
+ * the task whose handoff result was delivered back into this conversation and
+ * the run outcome; the card header + jump link read off it.
+ */
+ taskCallback?: MessageTaskCallback;
taskTitle?: string;
// message content is multimodal, display content in the streaming, won't save to db
tempDisplayContent?: string;
@@ -386,6 +406,23 @@ export interface MessageMetadata {
verifyRound?: number;
}
+/**
+ * Pointer carried on a `role='taskCallback'` message — the result-bridge card
+ * that reports a finished task's handoff back to its creator conversation
+ * (LOBE-10625). The handoff summary itself lives in the message `content`; this
+ * pointer drives the card header (identifier + outcome) and the jump link.
+ */
+export interface MessageTaskCallback {
+ /** Task identifier (e.g. `T-42`) for the card header + jump link. */
+ identifier: string;
+ /** Terminal outcome of the task run that produced this callback. */
+ reason: 'done' | 'error' | 'interrupted';
+ /** The task id (jump target → task detail). */
+ taskId: string;
+ /** The completed task topic, for an optional "view run" link. */
+ topicId?: string;
+}
+
/**
* Persisted form of an external-signal trigger context — stamped on
* messages produced as reactive replies to out-of-band events.
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 2a4a83b477b..f9c93936971 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -32,7 +32,8 @@ export type UIMessageRoleType =
| 'agentCouncil'
| 'compressedGroup'
| 'compareGroup'
- | 'verify';
+ | 'verify'
+ | 'taskCallback';
export interface ChatFileItem {
content?: string;
diff --git a/packages/types/src/message/ui/params.ts b/packages/types/src/message/ui/params.ts
index 561e4eda60f..9bc87863177 100644
--- a/packages/types/src/message/ui/params.ts
+++ b/packages/types/src/message/ui/params.ts
@@ -18,7 +18,8 @@ export type CreateMessageRoleType =
| 'tool'
| 'task'
| 'supervisor'
- | 'verify';
+ | 'verify'
+ | 'taskCallback';
export interface CreateMessageParams extends Partial<
Omit<UIChatMessage, 'content' | 'role' | 'topicId' | 'chunksList'>
@@ -174,7 +175,14 @@ export interface SendGroupMessageParams {
// ========== Zod Schemas ========== //
-const UIMessageRoleTypeSchema = z.enum(['user', 'assistant', 'tool', 'task', 'supervisor']);
+const UIMessageRoleTypeSchema = z.enum([
+ 'user',
+ 'assistant',
+ 'tool',
+ 'task',
+ 'supervisor',
+ 'taskCallback',
+]);
const ChatPluginPayloadSchema = z.object({
apiName: z.string(),
diff --git a/src/features/Conversation/Messages/TaskCallback/index.tsx b/src/features/Conversation/Messages/TaskCallback/index.tsx
new file mode 100644
index 00000000000..a021b3b6199
--- /dev/null
+++ b/src/features/Conversation/Messages/TaskCallback/index.tsx
@@ -0,0 +1,97 @@
+'use client';
+
+import { Button, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { CircleAlert, CircleCheck, CircleSlash, SquareArrowOutUpRight } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useNavigateToTaskDetail } from '@/features/AgentTasks/shared/taskDetailPath';
+
+import { dataSelectors, useConversationStore } from '../../store';
+
+const useStyles = createStyles(({ css, token }) => ({
+ card: css`
+ overflow: hidden;
+
+ padding-block: 12px;
+ padding-inline: 16px;
+ border: 1px solid ${token.colorBorderSecondary};
+ border-radius: 16px;
+
+ background: ${token.colorBgElevated};
+ `,
+ identifier: css`
+ font-family: ${token.fontFamilyCode};
+ color: ${token.colorTextSecondary};
+ `,
+}));
+
+interface TaskCallbackMessageProps {
+ id: string;
+ index: number;
+}
+
+type CallbackReason = 'done' | 'error' | 'interrupted';
+
+const reasonMeta: Record<
+ CallbackReason,
+ {
+ color: string;
+ i18nKey: 'taskCallback.done' | 'taskCallback.error' | 'taskCallback.interrupted';
+ icon: typeof CircleCheck;
+ }
+> = {
+ done: { color: 'colorSuccess', i18nKey: 'taskCallback.done', icon: CircleCheck },
+ error: { color: 'colorError', i18nKey: 'taskCallback.error', icon: CircleAlert },
+ interrupted: { color: 'colorWarning', i18nKey: 'taskCallback.interrupted', icon: CircleSlash },
+};
+
+/**
+ * Renders a `role='taskCallback'` message — the result-bridge card that reports
+ * a finished task's handoff back into its creator conversation (LOBE-10625). The
+ * task pointer (identifier / reason / taskId) is carried on
+ * `metadata.taskCallback`; the handoff summary lives in the message content.
+ * Renders as a standalone card (no avatar bubble), like the verify card.
+ */
+const TaskCallbackMessage = memo<TaskCallbackMessageProps>(({ id }) => {
+ const { styles, theme } = useStyles();
+ const { t } = useTranslation('chat');
+ const navigateToTask = useNavigateToTaskDetail();
+ const item = useConversationStore(dataSelectors.getDisplayMessageById(id), isEqual);
+
+ const callback = item?.metadata?.taskCallback;
+ if (!callback) return null;
+
+ const reason = (callback.reason ?? 'done') as CallbackReason;
+ const { color, i18nKey, icon } = reasonMeta[reason] ?? reasonMeta.done;
+ const content = typeof item?.content === 'string' ? item.content : '';
+
+ return (
+ <Flexbox paddingBlock={8}>
+ <Flexbox className={styles.card} gap={8}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={(theme as any)[color]} icon={icon} size={18} />
+ <Text strong>{t(i18nKey)}</Text>
+ <span className={styles.identifier}>{callback.identifier}</span>
+ </Flexbox>
+ <Button
+ icon={SquareArrowOutUpRight}
+ size={'small'}
+ type={'text'}
+ onClick={() => navigateToTask(callback.taskId)}
+ >
+ {t('taskCallback.viewTask')}
+ </Button>
+ </Flexbox>
+ {content ? <Markdown variant={'chat'}>{content}</Markdown> : null}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+TaskCallbackMessage.displayName = 'TaskCallbackMessage';
+
+export default TaskCallbackMessage;
diff --git a/src/features/Conversation/Messages/index.tsx b/src/features/Conversation/Messages/index.tsx
index e5b4b451687..ffc1f0db820 100644
--- a/src/features/Conversation/Messages/index.tsx
+++ b/src/features/Conversation/Messages/index.tsx
@@ -21,6 +21,7 @@ import CompressedGroupMessage from './CompressedGroup';
import GroupTasksMessage from './GroupTasks';
import SupervisorMessage from './Supervisor';
import TaskMessage from './Task';
+import TaskCallbackMessage from './TaskCallback';
import TasksMessage from './Tasks';
import ToolMessage from './Tool';
import UserMessage from './User';
@@ -191,6 +192,10 @@ const MessageItem = memo<MessageItemProps>(
case 'verify': {
return <VerifyMessage id={id} index={index} />;
}
+
+ case 'taskCallback': {
+ return <TaskCallbackMessage id={id} index={index} />;
+ }
}
return null;