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-runtime): preserve grouped sub-agent final answers (#17725)

Coooolfanaa06851a9c89
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 94fdf54729e..8895c73f69d 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -159,6 +159,55 @@ describe('AgentRuntimeService', () => {
let mockDb: any;
const mockUserId = 'test-user-id';
+ const buildPersistedToolChain = (
+ finalContent: string,
+ finalMetadata?: Record<string, unknown>,
+ ) => [
+ {
+ content: 'question',
+ createdAt: 1,
+ id: 'user-1',
+ role: 'user',
+ updatedAt: 1,
+ },
+ {
+ content: '',
+ createdAt: 2,
+ id: 'assistant-tools',
+ parentId: 'user-1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'command_execution',
+ arguments: '{}',
+ id: 'tool-call-1',
+ identifier: 'codex',
+ result_msg_id: 'tool-result-1',
+ type: 'default',
+ },
+ ],
+ updatedAt: 2,
+ },
+ {
+ content: 'tool result',
+ createdAt: 3,
+ id: 'tool-result-1',
+ parentId: 'assistant-tools',
+ role: 'tool',
+ tool_call_id: 'tool-call-1',
+ updatedAt: 3,
+ },
+ {
+ content: finalContent,
+ createdAt: 4,
+ id: 'assistant-final',
+ metadata: finalMetadata,
+ parentId: 'tool-result-1',
+ role: 'assistant',
+ updatedAt: 4,
+ },
+ ];
+
beforeEach(() => {
vi.clearAllMocks();
process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';
@@ -2060,6 +2109,80 @@ describe('AgentRuntimeService', () => {
);
});
+ it('single isolated member: extracts the final answer from an assistantGroup', async () => {
+ await service.completeGroupActionMember({
+ anchorMessageId: 'grp-tool-1',
+ expectedMembers: 1,
+ finalState: {
+ ...memberState,
+ messages: [
+ { content: 'question', role: 'user' },
+ {
+ children: [
+ {
+ content: '',
+ id: 'assistant-tools',
+ tools: [
+ {
+ id: 'tool-call-1',
+ result: { content: 'tool result', id: 'tool-result-1' },
+ },
+ ],
+ },
+ { content: 'grouped member answer', id: 'assistant-final' },
+ ],
+ content: '',
+ id: 'assistant-group',
+ role: 'assistantGroup',
+ },
+ ],
+ } as any,
+ groupToolMessageId: 'grp-tool-1',
+ mode: 'isolated',
+ onComplete: 'resume',
+ operationId: 'child-1',
+ parentOperationId: 'parent-1',
+ reason: 'done',
+ });
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'grp-tool-1',
+ expect.objectContaining({ content: 'grouped member answer' }),
+ );
+ });
+
+ it('single isolated member: extracts serialized multimodal text after DB rehydration', async () => {
+ mockCoordinator.loadAgentState.mockResolvedValue({
+ ...memberState,
+ messages: undefined,
+ });
+ (service as any).messageModel.query.mockResolvedValue(
+ buildPersistedToolChain(
+ JSON.stringify([
+ { text: 'persisted member answer', type: 'text' },
+ { image: 'https://example.com/image.png', type: 'image' },
+ ]),
+ { isMultimodal: true },
+ ),
+ );
+
+ await service.completeGroupActionMember({
+ anchorMessageId: 'grp-tool-1',
+ expectedMembers: 1,
+ groupToolMessageId: 'grp-tool-1',
+ mode: 'isolated',
+ onComplete: 'resume',
+ operationId: 'child-1',
+ parentOperationId: 'parent-1',
+ reason: 'done',
+ });
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'grp-tool-1',
+ expect.objectContaining({ content: 'persisted member answer' }),
+ );
+ });
+
it('multi-member: holds (no group-tool backfill, no resume) until the barrier is met', async () => {
(service as any).serverDB.query = {
messagePlugins: { findFirst: vi.fn() },
@@ -2211,6 +2334,120 @@ describe('AgentRuntimeService', () => {
);
});
+ it('extracts a grouped final answer after webhook state is rehydrated from the DB', async () => {
+ mockCoordinator.loadAgentState.mockResolvedValue({
+ ...childState,
+ messages: undefined,
+ });
+ (service as any).messageModel.query.mockResolvedValue(
+ buildPersistedToolChain('final answer after tool use'),
+ );
+
+ await service.completeSubAgentBridge(bridgeParams);
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'tool-msg-1',
+ expect.objectContaining({ content: 'final answer after tool use' }),
+ );
+ });
+
+ it('extracts text from serialized multimodal content after DB query and group parsing', async () => {
+ mockCoordinator.loadAgentState.mockResolvedValue({
+ ...childState,
+ messages: undefined,
+ });
+ (service as any).messageModel.query.mockResolvedValue(
+ buildPersistedToolChain(
+ JSON.stringify([
+ { text: 'persisted multimodal answer', type: 'text' },
+ { image: 'https://example.com/image.png', type: 'image' },
+ ]),
+ { isMultimodal: true },
+ ),
+ );
+
+ await service.completeSubAgentBridge(bridgeParams);
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'tool-msg-1',
+ expect.objectContaining({ content: 'persisted multimodal answer' }),
+ );
+ });
+
+ it('uses the no-text fallback for an image-only serialized final assistant', async () => {
+ mockCoordinator.loadAgentState.mockResolvedValue({
+ ...childState,
+ messages: undefined,
+ });
+ (service as any).messageModel.query.mockResolvedValue(
+ buildPersistedToolChain(
+ JSON.stringify([{ image: 'https://example.com/image.png', type: 'image' }]),
+ { isMultimodal: true },
+ ),
+ );
+
+ await service.completeSubAgentBridge(bridgeParams);
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'tool-msg-1',
+ expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),
+ );
+ });
+
+ it('extracts text parts from the grouped final assistant content', async () => {
+ await service.completeSubAgentBridge({
+ ...bridgeParams,
+ finalState: {
+ ...childState,
+ messages: [
+ {
+ children: [
+ {
+ content: [
+ { text: 'final answer', type: 'text' },
+ { image_url: { url: 'https://example.com/image.png' }, type: 'image_url' },
+ ],
+ id: 'assistant-final',
+ },
+ ],
+ content: '',
+ id: 'assistant-group',
+ role: 'assistantGroup',
+ },
+ ],
+ } as any,
+ });
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'tool-msg-1',
+ expect.objectContaining({ content: 'final answer' }),
+ );
+ });
+
+ it('does not fall back to stale text when the grouped final assistant is empty', async () => {
+ await service.completeSubAgentBridge({
+ ...bridgeParams,
+ finalState: {
+ ...childState,
+ messages: [
+ { content: 'stale answer', id: 'assistant-stale', role: 'assistant' },
+ { content: 'follow-up', id: 'user-follow-up', role: 'user' },
+ {
+ children: [{ content: '', id: 'assistant-final' }],
+ content: '',
+ id: 'assistant-group',
+ role: 'assistantGroup',
+ },
+ ],
+ } as any,
+ });
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'tool-msg-1',
+ expect.objectContaining({ content: 'Sub-agent completed without a textual answer.' }),
+ );
+ });
+
it('writes an error note + pluginError when the child failed, surfacing the real reason', async () => {
// The parent agent's LLM only sees `content`; without the inlined reason it
// gets the opaque generic note and cannot tell why the dispatch failed
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index bc92309c7fd..d2b98dbf45c 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -63,7 +63,13 @@ import { ToolExecutionService } from '@/server/services/toolExecution';
import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';
import { isAbortError, throwIfAborted } from './abort';
-import { CompletionLifecycle, isSuccessLikeCompletionReason } from './CompletionLifecycle';
+import {
+ CompletionLifecycle,
+ extractTextFromMessage,
+ findLastAssistantMessage,
+ isSuccessLikeCompletionReason,
+ normalizeCompletionMessages,
+} from './CompletionLifecycle';
import { hookDispatcher } from './hooks';
import { HumanInterventionHandler } from './HumanInterventionHandler';
import { OperationTraceRecorder } from './OperationTraceRecorder';
@@ -2173,31 +2179,31 @@ export class AgentRuntimeService {
//
// A state loaded via the fallback above arrives without `messages` (the
// persisted Redis blob no longer carries them β€” see
- // AgentStateManager.serializeStateForPersist), so rehydrate from the DB
- // before reading the sub-agent's final answer. An in-process
- // params.finalState already carries them and skips this.
+ // AgentStateManager.serializeStateForPersist). Resolve the final leaf from
+ // the parsed DB conversation, then recover the original row by id so its
+ // serialized content stays paired with metadata.isMultimodal. An in-process
+ // params.finalState already carries messages and skips this query.
+ let lastAssistant: unknown;
if (!failed && finalState && !Array.isArray(finalState.messages)) {
try {
- finalState.messages = await this.refreshMessagesFromDB(finalState);
+ lastAssistant = await this.resolveLastAssistantMessageFromDB(finalState);
} catch (error) {
console.error(
- '[%s] sub-agent bridge: failed to refresh messages from DB: %O',
+ '[%s] sub-agent bridge: failed to resolve final assistant from DB: %O',
operationId,
error,
);
}
}
const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];
- const lastAssistant = [...messages]
- .reverse()
- .find((m: { role?: string }) => m?.role === 'assistant');
+ lastAssistant ??= findLastAssistantMessage(normalizeCompletionMessages(messages));
+ const lastAssistantContent = extractTextFromMessage(lastAssistant);
const errorReason = failed ? formatSubAgentErrorReason(finalState?.error) : undefined;
const content = failed
? errorReason
? `Sub-agent did not complete (${reason}): ${errorReason}`
: `Sub-agent did not complete (${reason}).`
- : (lastAssistant?.content as string | undefined) ||
- 'Sub-agent completed without a textual answer.';
+ : lastAssistantContent || 'Sub-agent completed without a textual answer.';
const backfill = await this.messageModel.updateToolMessage(toolMessageId, {
content,
@@ -2368,23 +2374,24 @@ export class AgentRuntimeService {
// The member's textual answer is only read in delegate mode below; a state
// loaded via the fallback above arrives without `messages` (dropped from
// the persisted Redis blob β€” see AgentStateManager.serializeStateForPersist),
- // so rehydrate from the DB when we actually need them. An in-process
- // params.finalState already carries them and skips this.
+ // so resolve the original final leaf from the DB when we actually need it.
+ // Keeping the original row preserves the exact content/metadata pairing
+ // that conversation-flow display grouping intentionally aggregates.
+ let lastAssistant: unknown;
if (!failed && mode !== 'in_group' && finalState && !Array.isArray(finalState.messages)) {
try {
- finalState.messages = await this.refreshMessagesFromDB(finalState);
+ lastAssistant = await this.resolveLastAssistantMessageFromDB(finalState);
} catch (error) {
console.error(
- '[%s] group-member bridge: failed to refresh messages from DB: %O',
+ '[%s] group-member bridge: failed to resolve final assistant from DB: %O',
operationId,
error,
);
}
}
const messages = Array.isArray(finalState?.messages) ? finalState.messages : [];
- const lastAssistant = [...messages]
- .reverse()
- .find((m: { role?: string }) => m?.role === 'assistant');
+ lastAssistant ??= findLastAssistantMessage(normalizeCompletionMessages(messages));
+ const lastAssistantContent = extractTextFromMessage(lastAssistant);
const agentLabel = (finalState?.metadata?.agentId as string | undefined) ?? 'member';
const memberErrorReason = failed ? formatSubAgentErrorReason(finalState?.error) : undefined;
const anchorContent = failed
@@ -2393,8 +2400,7 @@ export class AgentRuntimeService {
: `Agent member did not complete (${reason}).`
: mode === 'in_group'
? `Agent ${agentLabel} responded in the group.`
- : (lastAssistant?.content as string | undefined) ||
- 'Agent member completed without a textual answer.';
+ : lastAssistantContent || 'Agent member completed without a textual answer.';
const anchorBackfill = await this.messageModel.updateToolMessage(anchorMessageId, {
content: anchorContent,
@@ -2542,12 +2548,7 @@ export class AgentRuntimeService {
return { nextStepScheduled: resumed, state: {}, success: true };
}
- /**
- * Reload the conversation messages from the database and flatten them for the
- * runtime. Used when resuming a parked op so the next LLM step sees tool
- * results written out-of-band (e.g. by a sub-agent completion bridge).
- */
- private async refreshMessagesFromDB(state: AgentState): Promise<AgentState['messages']> {
+ private async queryMessagesFromDB(state: AgentState) {
let postProcessUrl: ((path: string | null) => Promise<string>) | undefined;
try {
const fileService = new FileService(this.serverDB, this.userId);
@@ -2556,7 +2557,7 @@ export class AgentRuntimeService {
postProcessUrl = undefined;
}
- const dbMessages = await this.messageModel.query(
+ return this.messageModel.query(
{
agentId: state.metadata?.agentId,
// Group runs must pass groupId, else the query filters `groupId IS NULL`
@@ -2568,11 +2569,39 @@ export class AgentRuntimeService {
},
{ postProcessUrl },
);
+ }
+
+ /**
+ * Reload the conversation messages from the database and flatten them for the
+ * runtime. Used when resuming a parked op so the next LLM step sees tool
+ * results written out-of-band (e.g. by a sub-agent completion bridge).
+ */
+ private async refreshMessagesFromDB(state: AgentState): Promise<AgentState['messages']> {
+ const dbMessages = await this.queryMessagesFromDB(state);
const { flatList } = parse(dbMessages);
return flatList as AgentState['messages'];
}
+ /**
+ * Use conversation-flow to select the active final assistant leaf, then
+ * recover that leaf from the original query result. FlatListBuilder moves
+ * child metadata onto its display-only group/first child, so the parsed leaf
+ * alone cannot reliably identify serialized multimodal content.
+ */
+ private async resolveLastAssistantMessageFromDB(state: AgentState): Promise<unknown> {
+ const dbMessages = await this.queryMessagesFromDB(state);
+ const { flatList } = parse(dbMessages);
+ const lastAssistant = findLastAssistantMessage(normalizeCompletionMessages(flatList));
+ const lastAssistantId = typeof lastAssistant?.id === 'string' ? lastAssistant.id : undefined;
+
+ return (
+ (lastAssistantId
+ ? dbMessages.find((message) => message.id === lastAssistantId)
+ : undefined) ?? lastAssistant
+ );
+ }
+
/**
* Overwrite `state.messages` in place with the canonical DB conversation at
* step entry, making the DB the single source of truth for messages.
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 90c64b97fea..0332814d7bc 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -1,5 +1,4 @@
import { isParkedStatus } from '@lobechat/agent-runtime';
-import type { MessageContentPart } from '@lobechat/types';
import { deserializeParts } from '@lobechat/utils';
import { isRecord } from '@lobechat/utils/object';
import debug from 'debug';
@@ -796,16 +795,8 @@ export class CompletionLifecycle {
// in DisplayContent) rather than sniffing the string, so a legitimate
// plain-text reply that happens to be a JSON array is preserved as-is.
// Extract only the text parts; an image-only row recovers nothing.
- const isMultimodal =
- (row?.metadata as { isMultimodal?: boolean } | null | undefined)?.isMultimodal === true;
- const parts = isMultimodal ? deserializeParts(raw) : null;
- const content = parts
- ? parts
- .filter((p): p is Extract<MessageContentPart, { type: 'text' }> => p.type === 'text')
- .map((p) => p.text)
- .join('')
- : raw;
- if (!content.trim()) return undefined;
+ const content = extractTextFromMessage(row);
+ if (!content?.trim()) return undefined;
// console (not debug) so state/DB divergence stays visible in
// production logs β€” the silent variant of this is what made
@@ -834,10 +825,7 @@ export class CompletionLifecycle {
// the turn has any text β€” so an image-only or tool-output final turn
// doesn't fall through to an earlier assistant message and ship stale
// text alongside the current attachments.
- const lastAssistantMessage = messages
- .slice()
- .reverse()
- .find((message) => message.role === 'assistant');
+ const lastAssistantMessage = findLastAssistantMessage(messages);
const lastAssistantContent = lastAssistantMessage
? extractTextFromMessageContent(lastAssistantMessage.content)
: undefined;
@@ -945,7 +933,7 @@ const buildAttachmentFromUrl = (
* Pull text out of a message's `content` field. Accepts both string and
* OpenAI-style multimodal arrays `[{ type: 'text', text }, { type: 'image_url', image_url: { url } }]`.
*/
-const extractTextFromMessageContent = (content: unknown): string | undefined => {
+export const extractTextFromMessageContent = (content: unknown): string | undefined => {
if (typeof content === 'string') return content || undefined;
if (!Array.isArray(content)) return undefined;
const parts: string[] = [];
@@ -961,6 +949,23 @@ const extractTextFromMessageContent = (content: unknown): string | undefined =>
return joined || undefined;
};
+/**
+ * Extract text from either an in-memory message or a DB-rehydrated row.
+ * Persisted multimodal content is serialized, so only deserialize when the
+ * row's explicit metadata flag identifies that storage representation.
+ */
+export const extractTextFromMessage = (message: unknown): string | undefined => {
+ if (!isRecord(message)) return undefined;
+
+ const metadata = isRecord(message.metadata) ? message.metadata : undefined;
+ const content =
+ typeof message.content === 'string' && metadata?.isMultimodal === true
+ ? (deserializeParts(message.content) ?? message.content)
+ : message.content;
+
+ return extractTextFromMessageContent(content);
+};
+
/**
* Expand display-only assistant groups back into the assistant/tool sequence
* expected by terminal lifecycle consumers.
@@ -971,7 +976,9 @@ const extractTextFromMessageContent = (content: unknown): string | undefined =>
* the persisted leaf turns rather than that virtual wrapper, otherwise they
* lose both the final text and the message id used by DB recovery.
*/
-const normalizeCompletionMessages = (messages: unknown[]): Record<PropertyKey, unknown>[] => {
+export const normalizeCompletionMessages = (
+ messages: unknown[],
+): Record<PropertyKey, unknown>[] => {
const normalized: Record<PropertyKey, unknown>[] = [];
for (const message of messages) {
@@ -1019,6 +1026,19 @@ const normalizeCompletionMessages = (messages: unknown[]): Record<PropertyKey, u
return normalized;
};
+/**
+ * Find the final assistant boundary after display-only groups have been
+ * normalized. Match by role rather than content so an empty/image-only final
+ * turn never falls through to stale text from an earlier assistant message.
+ */
+export const findLastAssistantMessage = (
+ messages: Record<PropertyKey, unknown>[],
+): Record<PropertyKey, unknown> | undefined =>
+ messages
+ .slice()
+ .reverse()
+ .find((message) => message.role === 'assistant');
+
/**
* Extract image/file parts from a message's `content` array. Each entry is
* mapped to the JSON-safe outbound attachment shape (data or fetchUrl).