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(hetero): hand pasted images to the agent as images (#23049)

Rdmclin2d731a5f860e0
diff --git a/apps/cli/src/utils/heteroSteer.test.ts b/apps/cli/src/utils/heteroSteer.test.ts
index 03e3626bb32..a37b7f145c8 100644
--- a/apps/cli/src/utils/heteroSteer.test.ts
+++ b/apps/cli/src/utils/heteroSteer.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
-import { type HeteroSteerClient, withHeteroSteer } from './heteroSteer';
+import {
+ buildSteerPrompt,
+ type HeteroSteerClient,
+ type HeteroSteerMessage,
+ withHeteroSteer,
+} from './heteroSteer';
vi.mock('./logger', () => ({ log: { debug: vi.fn() } }));
@@ -48,7 +53,7 @@ const replay = (uuid: string): Event => ({
});
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
-const createClient = (messages: Array<{ content: string; messageId: string } | null>) => {
+const createClient = (messages: Array<HeteroSteerMessage | null>) => {
const wait = vi.fn(async (_input: unknown, options?: { signal?: AbortSignal }) => {
const next = messages.shift();
if (next !== undefined) return { message: next };
@@ -84,13 +89,73 @@ describe('withHeteroSteer', () => {
stream.end();
expect(sendUserMessage).toHaveBeenCalledWith('use pnpm', { uuid: 'msg-1' });
- expect(wait.mock.calls[0][0]).toEqual({ blockMs: 1, operationId: 'op-1' });
+ expect(wait.mock.calls[0][0]).toEqual({ acceptsImages: true, blockMs: 1, operationId: 'op-1' });
+ expect(wait.mock.calls[1][0]).toEqual({ acceptsImages: true, operationId: 'op-1' });
expect(await out).toEqual([
{ data: { liveSteer: true, newStep: true }, type: 'stream_start' },
replay('msg-1'),
]);
});
+ it('types images pasted into a follow-up in as image blocks', async () => {
+ const image = { id: 'file_1', url: 'https://bucket.example.com/1.png?sig=s' };
+ const { client } = createClient([
+ {
+ content: '![image.png](https://app.lobehub.com/f/file_1)',
+ imageList: [image],
+ messageId: 'msg-1',
+ },
+ ]);
+ const sendUserMessage = vi.fn(async () => true);
+ const stream = createStream();
+
+ const out = collect(
+ withHeteroSteer(
+ { events: stream.events, sendUserMessage },
+ { getTrpcClient: async () => client, operationId: 'op-1' },
+ ),
+ );
+ await vi.waitFor(() => expect(sendUserMessage).toHaveBeenCalled());
+ stream.end();
+ await out;
+
+ expect(sendUserMessage).toHaveBeenCalledWith(
+ [
+ { text: '![image.png](https://app.lobehub.com/f/file_1)', type: 'text' },
+ { source: { id: 'file_1', type: 'url', url: image.url }, type: 'image' },
+ ],
+ { uuid: 'msg-1' },
+ );
+ });
+
+ it('falls back to the text when its images cannot be loaded', async () => {
+ const { client, giveBack } = createClient([
+ {
+ content: 'see this',
+ imageList: [{ id: 'f', url: 'https://x/expired' }],
+ messageId: 'msg-1',
+ },
+ ]);
+ const sendUserMessage = vi.fn(async (prompt: unknown) => {
+ if (typeof prompt !== 'string') throw new Error('image fetch failed: 403');
+ return true;
+ });
+ const stream = createStream();
+
+ const out = collect(
+ withHeteroSteer(
+ { events: stream.events, sendUserMessage },
+ { getTrpcClient: async () => client, operationId: 'op-1' },
+ ),
+ );
+ await vi.waitFor(() => expect(sendUserMessage).toHaveBeenCalledTimes(2));
+ stream.end();
+ await out;
+
+ expect(sendUserMessage).toHaveBeenLastCalledWith('see this', { uuid: 'msg-1' });
+ expect(giveBack).not.toHaveBeenCalled();
+ });
+
it('gives a refused message back and stops polling', async () => {
const { client, giveBack, wait } = createClient([{ content: 'hi', messageId: 'msg-1' }]);
const stream = createStream();
@@ -165,3 +230,10 @@ describe('withHeteroSteer', () => {
]);
});
});
+
+describe('buildSteerPrompt', () => {
+ it('keeps a text-only follow-up a plain string', () => {
+ expect(buildSteerPrompt({ content: 'hi', messageId: 'm' })).toBe('hi');
+ expect(buildSteerPrompt({ content: 'hi', imageList: [], messageId: 'm' })).toBe('hi');
+ });
+});
diff --git a/apps/cli/src/utils/heteroSteer.ts b/apps/cli/src/utils/heteroSteer.ts
index ccb89b5a121..33b6c62f55c 100644
--- a/apps/cli/src/utils/heteroSteer.ts
+++ b/apps/cli/src/utils/heteroSteer.ts
@@ -1,4 +1,4 @@
-import type { AgentPromptInput } from '@lobechat/heterogeneous-agents/spawn';
+import type { AgentContentBlock, AgentPromptInput } from '@lobechat/heterogeneous-agents/spawn';
import { log } from './logger';
@@ -10,10 +10,10 @@ export interface HeteroSteerClient {
};
waitHeteroSteer: {
mutate: (
- input: { blockMs?: number; operationId: string },
+ input: { acceptsImages?: boolean; blockMs?: number; operationId: string },
options?: { signal?: AbortSignal },
) => Promise<{
- message: { content: string; messageId: string } | null;
+ message: HeteroSteerMessage | null;
/** `false` for a run the user does not type into (a child run): stop polling. */
steerable?: false;
}>;
@@ -21,6 +21,26 @@ export interface HeteroSteerClient {
};
}
+/** A follow-up to type into the session; `imageList` holds images pasted into its body. */
+export interface HeteroSteerMessage {
+ content: string;
+ imageList?: { id: string; url: string }[];
+ messageId: string;
+}
+
+/** The prompt a follow-up is typed in as: its text, then its images as image blocks. */
+export const buildSteerPrompt = (message: HeteroSteerMessage): AgentPromptInput => {
+ const images = message.imageList ?? [];
+ if (images.length === 0) return message.content;
+ return [
+ { text: message.content, type: 'text' },
+ ...images.map(({ id, url }): AgentContentBlock => ({
+ source: { id, type: 'url', url },
+ type: 'image',
+ })),
+ ];
+};
+
export interface HeteroSteerContext {
getTrpcClient: () => Promise<HeteroSteerClient>;
operationId: string;
@@ -83,11 +103,14 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(
const poll = async () => {
const client = await context.getTrpcClient();
while (!abort.signal.aborted) {
- let message: { content: string; messageId: string } | null;
+ let message: HeteroSteerMessage | null;
try {
const res = await client.aiAgent.waitHeteroSteer.mutate(
// The first poll answers at once, so the run is marked steerable early.
- supported ? { operationId } : { blockMs: 1, operationId },
+ // The session takes image blocks, so pasted images come along.
+ supported
+ ? { acceptsImages: true, operationId }
+ : { acceptsImages: true, blockMs: 1, operationId },
{ signal: abort.signal },
);
if (res.steerable === false) return;
@@ -104,7 +127,15 @@ export async function* withHeteroSteer<E extends { data?: any; type: string }>(
}
if (!message) continue;
- const accepted = await send(message.content, { uuid: message.messageId }).catch(() => false);
+ const steer = message;
+ const options = { uuid: steer.messageId };
+ const accepted = await send(buildSteerPrompt(steer), options).catch(async (error) => {
+ if (!steer.imageList?.length) return false;
+ // An image that cannot be fetched must not cost the message: its
+ // markdown still names the image.
+ log.debug('Steer images failed, sending the text: %s', String(error));
+ return send(steer.content, options).catch(() => false);
+ });
if (accepted) {
delivered.add(message.messageId);
continue;
diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.ts
index be9a38b5fc4..defa15d155c 100644
--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts
+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts
@@ -139,6 +139,11 @@ const WaitInterventionResponseSchema = z.object({
* its session instead of waiting for the run to end.
*/
const WaitHeteroSteerSchema = z.object({
+ /**
+ * The producer types image blocks into the session (`imageList` on the
+ * message). Older producers omit it and only ever get text-only follow-ups.
+ */
+ acceptsImages: z.boolean().optional(),
blockMs: z.number().int().positive().max(25_000).default(20_000),
operationId: z.string().min(1),
});
@@ -516,7 +521,7 @@ export const heteroRouter = router({
waitHeteroSteer: heteroAgentProcedure
.input(WaitHeteroSteerSchema)
.mutation(async ({ input, ctx }) => {
- const { operationId, blockMs } = input;
+ const { acceptsImages, operationId, blockMs } = input;
await authorizeOperationCallback(ctx, operationId, 'hetero:ingest');
@@ -561,6 +566,7 @@ export const heteroRouter = router({
const deadline = Date.now() + blockMs;
for (;;) {
const message = await takeHeteroSteer(storeCtx, {
+ acceptsImages,
agentId: operation.agentId,
operationId,
scope,
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts
index 29163ef409d..61197e7d88c 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts
@@ -44,6 +44,7 @@ const mocks = vi.hoisted(() => {
openBarrier = resolve;
});
},
+ resolveInlineImages: vi.fn(),
resolveSandboxSessionConfig: vi.fn(),
signHeteroOperationJWT: vi.fn(),
span,
@@ -70,6 +71,10 @@ vi.mock('@/server/services/file', () => ({
}),
}));
+vi.mock('@/server/services/file/inlineImages', () => ({
+ resolveInlineImages: mocks.resolveInlineImages,
+}));
+
vi.mock('@/libs/trpc/utils/internalJwt', () => ({
signHeteroOperationJWT: mocks.signHeteroOperationJWT,
}));
@@ -144,6 +149,7 @@ beforeEach(() => {
mocks.getResumeSessionId.mockImplementation(mocks.gated('resume_session', () => undefined));
mocks.signHeteroOperationJWT.mockImplementation(mocks.gated('sign_operation_jwt', () => 'jwt'));
mocks.resolveSandboxSessionConfig.mockResolvedValue(undefined);
+ mocks.resolveInlineImages.mockResolvedValue([]);
});
describe('prepareHeteroRun — overlapping reads', () => {
@@ -250,4 +256,53 @@ describe('prepareHeteroRun — overlapping reads', () => {
// A resumed run still gets its fallback context built from that history.
expect(prepared.heteroParams.resumeFallbackSystemContext).toBeDefined();
});
+
+ it('hands images pasted into the prompt to the CLI after the attached ones', async () => {
+ const { deps } = createDeps();
+ const pasted = '![image.png](https://app.lobehub.com/f/file_pasted)\n\nCI 挂了';
+ mocks.resolveInlineImages.mockResolvedValue([
+ { id: 'file_pasted', url: 'https://bucket.example.com/pasted.png?sig=1' },
+ ]);
+ const attached = {
+ ...input,
+ runAttachments: {
+ ...input.runAttachments,
+ imageList: [
+ { alt: 'a.png', id: 'file_attached', url: 'https://bucket.example.com/a.png?sig=2' },
+ ],
+ },
+ };
+
+ const prepared = await prepareHeteroRun(deps, { ...ctx, prompt: pasted }, attached, 'op-1');
+
+ expect(mocks.resolveInlineImages).toHaveBeenCalledWith(deps, pasted, ['file_attached']);
+ expect(prepared.heteroParams.imageList).toEqual([
+ { id: 'file_attached', url: 'https://bucket.example.com/a.png?sig=2' },
+ { id: 'file_pasted', url: 'https://bucket.example.com/pasted.png?sig=1' },
+ ]);
+ });
+
+ it('never resolves pasted images for a share visitor', async () => {
+ const { deps } = createDeps();
+
+ const prepared = await prepareHeteroRun(deps, { ...ctx, shareGate: {} }, input, 'op-1');
+
+ expect(mocks.resolveInlineImages).not.toHaveBeenCalled();
+ expect(prepared.heteroParams.imageList).toBeUndefined();
+ });
+
+ it('dispatches without pasted images when resolving them fails', async () => {
+ const { deps, messageModel, topicModel } = createDeps();
+ deps.getMarketService.mockRejectedValue(new Error('market down'));
+ messageModel.query.mockResolvedValue([]);
+ topicModel.findById.mockResolvedValue({ metadata: {} });
+ mocks.getResumeSessionId.mockResolvedValue(undefined);
+ mocks.signHeteroOperationJWT.mockResolvedValue('jwt');
+ mocks.resolveInlineImages.mockRejectedValue(new Error('db down'));
+
+ const prepared = await prepareHeteroRun(deps, ctx, input, 'op-1');
+
+ expect(prepared.heteroParams.imageList).toBeUndefined();
+ expect(prepared.heteroParams.jwt).toBe('jwt');
+ });
});
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
index a931353b07d..075b810c6e2 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
@@ -22,6 +22,7 @@ import pMap from 'p-map';
import { signHeteroOperationJWT } from '@/libs/trpc/utils/internalJwt';
import { FileService } from '@/server/services/file';
+import { resolveInlineImages } from '@/server/services/file/inlineImages';
import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';
import type { ConversationHistoryEntry } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
import { buildCloudHeteroContext } from '@/server/services/heterogeneousAgent/cloudHeteroContext';
@@ -251,6 +252,7 @@ export const prepareHeteroRun = async (
{ conversationHistory, unansweredUserTurns },
sandbox,
[viewedTaskContext, projectContext],
+ inlineImages,
] = await settleInOrder([
githubTokenPromise,
buildRecoveryHistory(),
@@ -271,6 +273,19 @@ export const prepareHeteroRun = async (
buildHeteroProjectContext(deps, appContext?.projectId, agentConfig.id),
]),
),
+ // Images pasted into the message body ride in the markdown as file links,
+ // which the CLI reads as plain text: hand them over as images too. Not for
+ // a share visitor, whose prompt must not resolve the owner's files.
+ ctx.shareGate
+ ? Promise.resolve([])
+ : resolveInlineImages(
+ deps,
+ prompt,
+ (runAttachments.imageList ?? []).map((image) => image.id),
+ ).catch((error) => {
+ log('execAgent: failed to resolve inline images for hetero run: %O', error);
+ return [];
+ }),
]);
const sandboxPlacement = sandbox && { cwd: sandbox.cwd, mode: sandbox.mode };
@@ -315,10 +330,11 @@ export const prepareHeteroRun = async (
// mirrors the local-mode path, where the client feeds the persisted
// message's imageList into `sendPrompt`. Reuses the shared resolution above
// so bot/IM and SPA gateway attachments are handled identically.
- const heteroImageList =
- runAttachments.imageList && runAttachments.imageList.length > 0
- ? runAttachments.imageList.map((image) => ({ id: image.id, url: image.url }))
- : undefined;
+ const heteroImages = [
+ ...(runAttachments.imageList ?? []).map((image) => ({ id: image.id, url: image.url })),
+ ...inlineImages,
+ ];
+ const heteroImageList = heteroImages.length > 0 ? heteroImages : undefined;
// Protocol runtimes (DeepSeek Harness) also launch through `lh hetero exec`
// and need the selector flags (e.g. `--model <tuple>`) built for it, even
// though they are not local-CLI descriptor agents.
diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts
index 71770a41fb3..38f8a80ef0e 100644
--- a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type * as InlineImagesModule from '@/server/services/file/inlineImages';
+
import {
canSteerHeteroRun,
consumeHeteroSteer,
@@ -20,9 +22,15 @@ const mocks = vi.hoisted(() => ({
findById: vi.fn(),
isRunAlive: vi.fn(),
renew: vi.fn(),
+ resolveInlineImages: vi.fn(),
settle: vi.fn(),
}));
+vi.mock('@/server/services/file/inlineImages', async (importOriginal) => ({
+ ...(await importOriginal<typeof InlineImagesModule>()),
+ resolveInlineImages: mocks.resolveInlineImages,
+}));
+
vi.mock('@/server/services/redis', () => ({
redisService: {
steerQueue: {
@@ -86,6 +94,7 @@ beforeEach(() => {
mocks.findById.mockResolvedValue(undefined);
mocks.settle.mockResolvedValue(undefined);
mocks.renew.mockResolvedValue(true);
+ mocks.resolveInlineImages.mockResolvedValue([]);
});
describe('canSteerHeteroRun', () => {
@@ -125,6 +134,52 @@ describe('takeHeteroSteer', () => {
expect(mocks.deliveries.size).toBe(0);
});
+ describe('images pasted into the body', () => {
+ const pasted = '![image.png](https://app.lobehub.com/f/file_1)\n\nCI 挂了';
+ const image = { id: 'file_1', url: 'https://bucket.example.com/files/1.png?X-Amz-Signature=s' };
+
+ it('hands them over with the text when the session takes images', async () => {
+ mocks.drain.mockResolvedValue([followUp('a', 1, { prompt: pasted }), followUp('b', 2)]);
+ mocks.resolveInlineImages.mockResolvedValue([image]);
+
+ await expect(
+ takeHeteroSteer(ctx, { acceptsImages: true, agentId: 'agt-1', operationId: 'op-1', scope }),
+ ).resolves.toEqual({ content: pasted, imageList: [image], messageId: 'msg-a' });
+
+ expect(mocks.resolveInlineImages).toHaveBeenCalledWith(ctx, pasted);
+ expect(mocks.settle.mock.calls[0][2]).toEqual(['b']);
+ expect(mocks.deliveries.has('msg-a')).toBe(true);
+ });
+
+ it('leaves the follow-up to a turn of its own when the session only takes text', async () => {
+ mocks.drain.mockResolvedValue([followUp('a', 1, { prompt: pasted }), followUp('b', 2)]);
+ mocks.resolveInlineImages.mockResolvedValue([image]);
+
+ await expect(take()).resolves.toBeUndefined();
+
+ expect(mocks.settle.mock.calls[0][2]).toEqual(['a', 'b']);
+ expect(mocks.deliveries.size).toBe(0);
+ // Asked again on every poll: decided without reading or signing files.
+ expect(mocks.resolveInlineImages).not.toHaveBeenCalled();
+ });
+
+ it('steers as text when the links name no image of the user', async () => {
+ mocks.drain.mockResolvedValue([followUp('a', 1, { prompt: pasted })]);
+
+ await expect(
+ takeHeteroSteer(ctx, { acceptsImages: true, agentId: 'agt-1', operationId: 'op-1', scope }),
+ ).resolves.toEqual({ content: pasted, messageId: 'msg-a' });
+ });
+
+ it('reads no files for a follow-up that only quotes image syntax in code', async () => {
+ const quoted = 'use `![a](/f/file_1)` in the README';
+ mocks.drain.mockResolvedValue([followUp('a', 1, { prompt: quoted })]);
+
+ await expect(take()).resolves.toEqual({ content: quoted, messageId: 'msg-a' });
+ expect(mocks.resolveInlineImages).not.toHaveBeenCalled();
+ });
+ });
+
it('does not send a follow-up twice when its batch lapsed back', async () => {
mocks.deliveries.set(
'msg-a',
diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.ts
index 2a8c1bfec29..856b0c40897 100644
--- a/apps/server/src/services/aiAgent/steerQueue/hetero.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.ts
@@ -3,6 +3,11 @@ import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import { MessageModel } from '@/database/models/message';
+import {
+ collectMarkdownImageUrls,
+ type InlineImage,
+ resolveInlineImages,
+} from '@/server/services/file/inlineImages';
import { redisService } from '@/server/services/redis';
import type { SteerQueueScope } from '@/server/services/redis/steerQueue';
@@ -39,6 +44,11 @@ export interface HeteroSteerDelivery {
export interface HeteroSteerMessage {
content: string;
+ /**
+ * Images pasted into the follow-up's body, which `content` only holds as
+ * markdown links: signed URLs for the session to take as image input.
+ */
+ imageList?: InlineImage[];
messageId: string;
}
@@ -78,13 +88,23 @@ export const renewHeteroSteers = async (operationId: string) => {
* follow-up that cannot join (an attachment, a tool selection…) stops the
* take, and it and everything behind it wait for the run to end.
*
+ * Images pasted into the body go along as `imageList` when the session takes
+ * image input (`acceptsImages`). Otherwise the follow-up waits for a turn of
+ * its own, where the dispatch hands them over: typed in as text, the agent
+ * would only see links it cannot look at.
+ *
* @returns the message to send, or `undefined` when nothing can go now
*/
export const takeHeteroSteer = async (
ctx: StoreContext,
- params: { agentId: string | null; operationId: string; scope: SteerQueueScope },
+ params: {
+ acceptsImages?: boolean;
+ agentId: string | null;
+ operationId: string;
+ scope: SteerQueueScope;
+ },
): Promise<HeteroSteerMessage | undefined> => {
- const { agentId, operationId, scope } = params;
+ const { acceptsImages, agentId, operationId, scope } = params;
const drained = await drainOwnFollowUps(ctx, scope, operationId);
if (drained.entries.length === 0) return;
@@ -96,6 +116,24 @@ export const takeHeteroSteer = async (
await returnFollowUps(scope, drained, drained.entries, 'needs a turn of its own');
return;
}
+
+ // A session that only takes text gets no image follow-up: decided from the
+ // markdown alone, since the run asks again on every poll.
+ const hasImages = collectMarkdownImageUrls(first.request.prompt).length > 0;
+ if (hasImages && !acceptsImages) {
+ await returnFollowUps(scope, drained, drained.entries, 'its images need a turn of their own');
+ return;
+ }
+
+ let imageList: InlineImage[] = [];
+ if (hasImages) {
+ try {
+ imageList = await resolveInlineImages(ctx, first.request.prompt);
+ } catch (error) {
+ await returnFollowUps(scope, drained, drained.entries, error);
+ return;
+ }
+ }
await returnFollowUps(scope, drained, rest, 'delivered one at a time');
const request = first.request;
@@ -141,7 +179,11 @@ export const takeHeteroSteer = async (
}
log('[%s] Delivering follow-up %s as %s', operationId, first.id, messageId);
- return { content: request.prompt, messageId };
+ return {
+ content: request.prompt,
+ ...(imageList.length > 0 && { imageList }),
+ messageId,
+ };
};
/**
diff --git a/apps/server/src/services/file/extractFileIdsFromEditorData.test.ts b/apps/server/src/services/file/extractFileIdsFromEditorData.test.ts
index 62539d2913c..e72252c77fa 100644
--- a/apps/server/src/services/file/extractFileIdsFromEditorData.test.ts
+++ b/apps/server/src/services/file/extractFileIdsFromEditorData.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
collectAttachmentUrlsFromEditorData,
extractFileIdsFromEditorData,
+ resolveFileIdsFromUrls,
} from './extractFileIdsFromEditorData';
const image = (src: string, status?: string) => ({
@@ -95,7 +96,7 @@ describe('extractFileIdsFromEditorData', () => {
});
it('falls back to DB lookup by storage key for pre-signed URLs', async () => {
- const db = mockDb([{ id: 'file_resolved' }]);
+ const db = mockDb([{ id: 'file_resolved', url: 'ppp/494360/03378b6c.jpg' }]);
const json = {
root: {
children: [
@@ -111,7 +112,7 @@ describe('extractFileIdsFromEditorData', () => {
});
it('mixes proxy + signed URLs and dedupes', async () => {
- const db = mockDb([{ id: 'file_signed_one' }]);
+ const db = mockDb([{ id: 'file_signed_one', url: 'users/u/files/abc.jpg' }]);
const json = {
root: {
children: [
@@ -167,3 +168,24 @@ describe('extractFileIdsFromEditorData', () => {
void ctx; // silence unused
});
+
+describe('resolveFileIdsFromUrls', () => {
+ it('keeps the order of the URLs, whichever form each one has', async () => {
+ // Rows come back in database order, not URL order.
+ const db = mockDb([
+ { id: 'file_third', url: 'files/3.png' },
+ { id: 'file_first', url: 'files/1.png' },
+ ]);
+
+ await expect(
+ resolveFileIdsFromUrls(
+ [
+ 'https://r2.example.com/files/1.png?X-Amz-Date=…',
+ 'https://app.example.com/f/file_second',
+ 'https://r2.example.com/files/3.png?X-Amz-Date=…',
+ ],
+ { db, userId: 'u' },
+ ),
+ ).resolves.toEqual(['file_first', 'file_second', 'file_third']);
+ });
+});
diff --git a/apps/server/src/services/file/extractFileIdsFromEditorData.ts b/apps/server/src/services/file/extractFileIdsFromEditorData.ts
index 7a8bb1b2897..f0f159af920 100644
--- a/apps/server/src/services/file/extractFileIdsFromEditorData.ts
+++ b/apps/server/src/services/file/extractFileIdsFromEditorData.ts
@@ -85,46 +85,52 @@ function extractStorageKeyFromUrl(url: string): string | undefined {
}
}
-export async function extractFileIdsFromEditorData(
- json: unknown,
+/**
+ * Resolve file URLs (proxy `/f/{fileId}` form or pre-signed storage URLs) to
+ * the fileIds of the caller's files, deduped, in the order the URLs come.
+ * Storage URLs are looked up by key within the caller's user / workspace scope.
+ */
+export async function resolveFileIdsFromUrls(
+ urls: string[],
ctx: { db: LobeChatDatabase; userId: string; workspaceId?: string },
): Promise<string[]> {
- const urls = collectAttachmentUrlsFromEditorData(json);
if (urls.length === 0) return [];
- const seen = new Set<string>();
- const unresolved: string[] = [];
-
- // Pass 1: regex on the proxy-URL form.
- for (const url of urls) {
- const match = url.match(FILE_PROXY_RE);
- if (match) {
- seen.add(match[1]);
- } else {
- unresolved.push(url);
- }
- }
+ // Pass 1: regex on the proxy-URL form; the rest are storage URLs by key.
+ const proxyIds = urls.map((url) => url.match(FILE_PROXY_RE)?.[1]);
+ const keys = urls.map((url, index) =>
+ proxyIds[index] ? undefined : extractStorageKeyFromUrl(url),
+ );
// Pass 2: look up the remaining URLs by storage key in `files`. Same bytes
// re-uploaded by the same user produce multiple rows with identical
- // `url` + `file_hash`; dedupe per key so the agent doesn't receive the
+ // `url` + `file_hash`; take one id per key so the agent doesn't receive the
// same asset N times.
- if (unresolved.length > 0) {
- const keys = unresolved.map(extractStorageKeyFromUrl).filter((key): key is string => !!key);
-
- if (keys.length > 0) {
- const rows = await ctx.db
- .select({ id: files.id, url: files.url })
- .from(files)
- .where(and(buildWorkspaceWhere(ctx, files), inArray(files.url, keys)));
-
- const firstIdPerUrl = new Map<string, string>();
- for (const row of rows) {
- if (!firstIdPerUrl.has(row.url)) firstIdPerUrl.set(row.url, row.id);
- }
- for (const id of firstIdPerUrl.values()) seen.add(id);
+ const firstIdPerKey = new Map<string, string>();
+ const lookupKeys = [...new Set(keys.filter((key): key is string => !!key))];
+ if (lookupKeys.length > 0) {
+ const rows = await ctx.db
+ .select({ id: files.id, url: files.url })
+ .from(files)
+ .where(and(buildWorkspaceWhere(ctx, files), inArray(files.url, lookupKeys)));
+
+ for (const row of rows) {
+ if (!firstIdPerKey.has(row.url)) firstIdPerKey.set(row.url, row.id);
}
}
+ const seen = new Set<string>();
+ urls.forEach((_, index) => {
+ const key = keys[index];
+ const id = proxyIds[index] ?? (key ? firstIdPerKey.get(key) : undefined);
+ if (id) seen.add(id);
+ });
return [...seen];
}
+
+export async function extractFileIdsFromEditorData(
+ json: unknown,
+ ctx: { db: LobeChatDatabase; userId: string; workspaceId?: string },
+): Promise<string[]> {
+ return resolveFileIdsFromUrls(collectAttachmentUrlsFromEditorData(json), ctx);
+}
diff --git a/apps/server/src/services/file/inlineImages.test.ts b/apps/server/src/services/file/inlineImages.test.ts
new file mode 100644
index 00000000000..cae6f16db67
--- /dev/null
+++ b/apps/server/src/services/file/inlineImages.test.ts
@@ -0,0 +1,104 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { collectMarkdownImageUrls, resolveInlineImages } from './inlineImages';
+
+const mocks = vi.hoisted(() => ({
+ resolveAttachmentMetadata: vi.fn(),
+ resolveFileIdsFromUrls: vi.fn(),
+}));
+
+vi.mock('./extractFileIdsFromEditorData', () => ({
+ resolveFileIdsFromUrls: mocks.resolveFileIdsFromUrls,
+}));
+vi.mock('./resolveAttachments', () => ({
+ resolveAttachmentMetadata: mocks.resolveAttachmentMetadata,
+}));
+
+const ctx = { db: {} as any, userId: 'user-1', workspaceId: 'ws-1' };
+const pasted =
+ '![image.png](https://app.lobehub.com/f/file_VbV3vFGeXLTN)\n\n环境变量加了,然后 CI 这个好像挂了';
+
+describe('collectMarkdownImageUrls', () => {
+ it('collects the URL of every markdown image, in order', () => {
+ expect(
+ collectMarkdownImageUrls(
+ `${pasted}\n![](/f/file_2) and ![b](<https://cdn.example.com/b.png> "title")`,
+ ),
+ ).toEqual([
+ 'https://app.lobehub.com/f/file_VbV3vFGeXLTN',
+ '/f/file_2',
+ 'https://cdn.example.com/b.png',
+ ]);
+ });
+
+ it('ignores image syntax inside code or escaped', () => {
+ expect(
+ collectMarkdownImageUrls(
+ 'inline `![a](/f/file_1)`, escaped \\![b](/f/file_2)\n\n```md\n![c](/f/file_3)\n```\n![d](/f/file_4)',
+ ),
+ ).toEqual(['/f/file_4']);
+ });
+
+ it('ignores plain links and text without images', () => {
+ expect(collectMarkdownImageUrls('see [the file](https://app.lobehub.com/f/file_1)')).toEqual(
+ [],
+ );
+ expect(collectMarkdownImageUrls('just text')).toEqual([]);
+ expect(collectMarkdownImageUrls(undefined)).toEqual([]);
+ });
+});
+
+describe('resolveInlineImages', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("resolves the user's pasted images to signed URLs", async () => {
+ mocks.resolveFileIdsFromUrls.mockResolvedValue(['file_VbV3vFGeXLTN']);
+ mocks.resolveAttachmentMetadata.mockResolvedValue([
+ {
+ fileType: 'image/png',
+ id: 'file_VbV3vFGeXLTN',
+ name: 'image.png',
+ size: 1,
+ url: 'https://bucket.example.com/files/1.png?X-Amz-Signature=s',
+ },
+ ]);
+
+ await expect(resolveInlineImages(ctx, pasted)).resolves.toEqual([
+ {
+ id: 'file_VbV3vFGeXLTN',
+ url: 'https://bucket.example.com/files/1.png?X-Amz-Signature=s',
+ },
+ ]);
+ expect(mocks.resolveFileIdsFromUrls).toHaveBeenCalledWith(
+ ['https://app.lobehub.com/f/file_VbV3vFGeXLTN'],
+ { db: ctx.db, userId: 'user-1', workspaceId: 'ws-1' },
+ );
+ expect(mocks.resolveAttachmentMetadata).toHaveBeenCalledWith({
+ db: ctx.db,
+ fileIds: ['file_VbV3vFGeXLTN'],
+ userId: 'user-1',
+ workspaceId: 'ws-1',
+ });
+ });
+
+ it('drops non-image files and images already attached', async () => {
+ mocks.resolveFileIdsFromUrls.mockResolvedValue(['file_attached', 'file_doc']);
+ mocks.resolveAttachmentMetadata.mockResolvedValue([
+ { fileType: 'application/pdf', id: 'file_doc', name: 'a.pdf', size: 1, url: 'https://x/a' },
+ ]);
+
+ await expect(
+ resolveInlineImages(ctx, '![a](/f/file_attached) ![d](/f/file_doc)', ['file_attached']),
+ ).resolves.toEqual([]);
+ expect(mocks.resolveAttachmentMetadata).toHaveBeenCalledWith(
+ expect.objectContaining({ fileIds: ['file_doc'] }),
+ );
+ });
+
+ it('does not touch the database without images', async () => {
+ await expect(resolveInlineImages(ctx, 'plain text')).resolves.toEqual([]);
+ expect(mocks.resolveFileIdsFromUrls).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/file/inlineImages.ts b/apps/server/src/services/file/inlineImages.ts
new file mode 100644
index 00000000000..f586be5734a
--- /dev/null
+++ b/apps/server/src/services/file/inlineImages.ts
@@ -0,0 +1,49 @@
+import type { LobeChatDatabase } from '@/database/type';
+import { extractFinalReplyImageUrls } from '@/server/services/agentRuntime/finalReplyImages';
+
+import { resolveFileIdsFromUrls } from './extractFileIdsFromEditorData';
+import { resolveAttachmentMetadata } from './resolveAttachments';
+
+/**
+ * The URLs of every rendered markdown image in `markdown`, in order. Parsed
+ * as markdown, so image syntax inside code or escaped stays text.
+ */
+export const collectMarkdownImageUrls = (markdown?: string | null): string[] => {
+ if (!markdown || !markdown.includes('![')) return [];
+ return extractFinalReplyImageUrls(markdown);
+};
+
+export interface InlineImage {
+ id: string;
+ url: string;
+}
+
+/**
+ * Images the user put inline in a message body (an image pasted into the
+ * editor is uploaded and kept as `![name](${APP_URL}/f/{fileId})`, not as an
+ * attachment). An agent reading the markdown only sees a link, so these are
+ * resolved to the user's own image files with a signed storage URL, ready to
+ * be handed over as image input.
+ *
+ * Only the caller's files resolve (scoped by user / workspace); other links,
+ * missing files and non-image files are dropped. `excludeIds` skips images
+ * already delivered as attachments.
+ */
+export const resolveInlineImages = async (
+ ctx: { db: LobeChatDatabase; userId: string; workspaceId?: string | null },
+ markdown: string | null | undefined,
+ excludeIds: Iterable<string> = [],
+): Promise<InlineImage[]> => {
+ const urls = collectMarkdownImageUrls(markdown);
+ if (urls.length === 0) return [];
+
+ const scope = { db: ctx.db, userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined };
+ const excluded = new Set(excludeIds);
+ const fileIds = (await resolveFileIdsFromUrls(urls, scope)).filter((id) => !excluded.has(id));
+ if (fileIds.length === 0) return [];
+
+ const items = await resolveAttachmentMetadata({ ...scope, fileIds });
+ return items
+ .filter((item) => item.fileType.startsWith('image') && !!item.url)
+ .map(({ id, url }) => ({ id, url }));
+};