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(bot): attach Markdown images from final replies (#19383)

Jiyuan Zheng7aa2a4a73c09
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 44fd58daf14..36b7256a418 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -31,6 +31,7 @@ import { registerWorksForOperation } from '@/server/services/workRegistration';
import { after } from '@/server/utils/scheduleAfterResponse';
import { buildRuntimeInterventionNotification } from './agentInterventionNotification';
+import { extractFinalReplyImageUrls } from './finalReplyImages';
import { CriticalHookDeliveryError, hookDispatcher, type SerializedHook } from './hooks';
const log = debug('lobe-server:completion-lifecycle');
@@ -936,7 +937,13 @@ export class CompletionLifecycle {
runOrigin.userId || this.userId,
typeof runOrigin.topicId === 'string' ? runOrigin.topicId : undefined,
);
- if (recovered) event.lastAssistantContent = recovered;
+ if (recovered) {
+ event.lastAssistantContent = recovered;
+ const attachments = extractOutboundAttachments([
+ { content: recovered, role: 'assistant' },
+ ]);
+ event.attachments = attachments.length > 0 ? attachments : undefined;
+ }
}
await hookDispatcher.dispatch(operationId, 'onComplete', event, state?.host?.hooks);
@@ -1461,8 +1468,18 @@ const extractOutboundAttachments = (messages: any[]): OutboundAttachment[] => {
if (role === 'assistant') {
if (!crossedFinalAssistant) {
- // The final assistant turn: harvest its multimodal parts.
- collected.push(...extractAttachmentsFromContent(content));
+ // Only the final reply's Markdown expresses an intent to send images.
+ // Do not promote generation state or intermediate tool Markdown.
+ const attachments: OutboundAttachment[] = [];
+ const text = extractTextFromMessageContent(content);
+ if (text) {
+ for (const url of extractFinalReplyImageUrls(text)) {
+ const attachment = buildAttachmentFromUrl(url, 'image');
+ if (attachment) attachments.push(attachment);
+ }
+ }
+ attachments.push(...extractAttachmentsFromContent(content));
+ collected.unshift(...attachments);
crossedFinalAssistant = true;
continue;
}
@@ -1473,12 +1490,11 @@ const extractOutboundAttachments = (messages: any[]): OutboundAttachment[] => {
if (role === 'tool') {
// Tool results between the previous assistant turn and the final one.
- collected.push(...extractAttachmentsFromContent(content));
+ collected.unshift(...extractAttachmentsFromContent(content));
}
}
- // Reverse so message-order (older first) is preserved, then dedupe.
- collected.reverse();
+ // Prepending each message preserves both message and within-message order.
const seen = new Set<string>();
const result: OutboundAttachment[] = [];
for (const att of collected) {
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 3491e753cfb..ff76f7c1feb 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -171,6 +171,78 @@ describe('CompletionLifecycle.buildLifecycleEvent', () => {
const callBuild = (state: unknown, reason = 'completed') =>
(buildLifecycle() as any).buildLifecycleEvent('op-1', state, reason);
+ it('attaches Markdown images explicitly included in the final reply without changing its text', () => {
+ const url = 'https://cdn.example.com/f/file_image';
+ const content = `Here is the result: ![Result](${url})`;
+ const { event } = callBuild({ messages: [{ role: 'assistant', content }] });
+ expect(event.attachments).toEqual([{ fetchUrl: url, type: 'image' }]);
+ expect(event.lastAssistantContent).toBe(content);
+ });
+
+ it('preserves the order of distinct final-reply images', () => {
+ const { event } = callBuild({
+ messages: [
+ {
+ role: 'assistant',
+ content:
+ '![Before](https://cdn.example.com/before.png) ![After](https://cdn.example.com/after.png)',
+ },
+ ],
+ });
+ expect(event.attachments?.map((attachment: any) => attachment.fetchUrl)).toEqual([
+ 'https://cdn.example.com/before.png',
+ 'https://cdn.example.com/after.png',
+ ]);
+ });
+
+ it('parses reference images in final text parts and deduplicates structured images', () => {
+ const url = 'https://cdn.example.com/result.png';
+ const { event } = callBuild({
+ messages: [
+ {
+ role: 'assistant',
+ content: [
+ { type: 'text', text: `![one][result] ![two](${url})\n\n[result]: ${url}` },
+ { type: 'image_url', image_url: { url } },
+ ],
+ },
+ ],
+ });
+ expect(event.attachments).toEqual([{ fetchUrl: url, type: 'image' }]);
+ });
+
+ it('does not promote tool state, tool Markdown, or an earlier reply to final attachments', () => {
+ const url = 'https://cdn.example.com/intermediate.png';
+ const { event } = callBuild({
+ messages: [
+ { role: 'assistant', content: `![earlier](${url})` },
+ { role: 'user', content: 'Analyze the result without sending an image.' },
+ { role: 'assistant', content: '', tools: [{ id: 'call-image' }] },
+ {
+ role: 'tool',
+ content: `![tool result](${url})`,
+ state: { generations: [{ asset: { url, type: 'image' } }] },
+ },
+ { role: 'assistant', content: 'The composition is balanced.' },
+ ],
+ });
+ expect(event.attachments).toBeUndefined();
+ });
+
+ it('does not treat ordinary links, code, escaped syntax or unsafe schemes as images', () => {
+ const content = [
+ 'https://cdn.example.com/plain.png',
+ '[download](https://cdn.example.com/download.png)',
+ '`![inline](https://cdn.example.com/inline.png)`',
+ '```md\n![fenced](https://cdn.example.com/fenced.png)\n```',
+ '\\![escaped](https://cdn.example.com/escaped.png)',
+ '![unsafe](file:///tmp/image.png)',
+ '![unsafe](javascript:alert)',
+ ].join('\n\n');
+ const { event } = callBuild({ messages: [{ role: 'assistant', content }] });
+ expect(event.attachments).toBeUndefined();
+ });
+
it('extracts text content from a plain-string final assistant turn', () => {
const state = {
messages: [
@@ -1239,6 +1311,27 @@ describe('CompletionLifecycle.dispatchHooks — lastAssistantContent DB recovery
);
});
+ it('extracts final Markdown images when the reply is recovered from the database', async () => {
+ const lifecycle = buildLifecycle();
+ const dispatchSpy = setupSpies(lifecycle);
+ const content = '![Result](https://cdn.example.com/recovered.png)';
+ (lifecycle as any).messageModel = {
+ findById: vi.fn().mockResolvedValue({ content, id: 'msg-assistant' }),
+ };
+
+ await lifecycle.dispatchHooks('op-1', buildDoneState(''), 'done');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ 'op-1',
+ 'onComplete',
+ expect.objectContaining({
+ attachments: [{ fetchUrl: 'https://cdn.example.com/recovered.png', type: 'image' }],
+ lastAssistantContent: content,
+ }),
+ [],
+ );
+ });
+
it('recovers by the final assistantGroup child id when grouped state carries no text', async () => {
const lifecycle = buildLifecycle();
const dispatchSpy = setupSpies(lifecycle);
diff --git a/apps/server/src/services/agentRuntime/finalReplyImages.ts b/apps/server/src/services/agentRuntime/finalReplyImages.ts
new file mode 100644
index 00000000000..25f359ab2f8
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/finalReplyImages.ts
@@ -0,0 +1,23 @@
+import { parseMarkdown } from 'chat';
+import { visit } from 'unist-util-visit';
+
+/** Read explicit image references, never ordinary links or code examples. */
+export const extractFinalReplyImageUrls = (text: string): string[] => {
+ const tree = parseMarkdown(text);
+ const definitions = new Map<string, string>();
+ visit(tree, 'definition', (node) => {
+ const id = node.identifier.toUpperCase();
+ // CommonMark resolves duplicate definitions to the first definition.
+ if (!definitions.has(id)) definitions.set(id, node.url);
+ });
+
+ const urls: string[] = [];
+ visit(tree, (node) => {
+ if (node.type === 'image') urls.push(node.url);
+ if (node.type === 'imageReference') {
+ const url = definitions.get(node.identifier.toUpperCase());
+ if (url) urls.push(url);
+ }
+ });
+ return urls;
+};