🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(work): accept sandbox-exported images in collection Works (#23566)
YuTengjing843d626ea622
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.mdindex 8070670416d..91c02b9c771 100644--- a/.agents/skills/agent-work/SKILL.md+++ b/.agents/skills/agent-work/SKILL.md@@ -60,7 +60,7 @@ Five write paths, two timing classes:- The run is resolved server-side from `operationId` (`resolveAgentWorkRun`): topic, agent and share scope come from the operation row, and versions are stamped with the root of its `parentOperationId` chain so run completion fills their cost; and an operation token needs the `work:write` capability. A desktop-local run has no operation row and cannot use it.- The CLI sends only the uploaded file id; size, type and URL come from the file row (`resolveAgentWorkFile`).- Links register as external `resourceType: 'link'` with `<userId>:<topicId>:<canonical URL>` as identity (`linkWorkResourceId`), like file Works: the same link again in the same conversation adds a version, while another conversation or workspace member gets a Work of its own. `works.url` holds the URL; `lh work update` never changes it (the identity would then name the old URL), so a new URL is a new Work. GitHub and Linear links are refused because their own paths register them.-- A `collection` Work (`resourceType: 'collection'`, `col_` resource id) holds an ordered image list in `work_versions.metadata.collection`; every create is a new collection and every update stores the complete list. `works.url` holds the cover URL for list rows. Images must be files the run's user generated or uploaded as run output (`resolveAgentWorkCollectionItems`), named by the `generationId` image generation lists (resolved through `generations.fileId`), a file id or a `/f/<id>` link. In a share visitor run the named id must appear in a tool result (`role = 'tool'`) of the visitor topic; a visitor's own message or an assistant echo does not count. The item count is checked before any image is resolved.+- A `collection` Work (`resourceType: 'collection'`, `col_` resource id) holds an ordered image list in `work_versions.metadata.collection`; every create is a new collection and every update stores the complete list. `works.url` holds the cover URL for list rows. Images must be image files of the run's user (`resolveAgentWorkCollectionItems`), named by the `generationId` image generation lists (resolved through `generations.fileId`), a file id or a `/f/<id>` link. Generated images and run outputs qualify as they are, and in a share visitor run their id must also appear in a tool result (`role = 'tool'`) of the visitor topic; a visitor's own message, an assistant echo or a `lobe-work` refusal does not count. Any other image (the cloud sandbox stores `exportFile` results without a source) qualifies only through the `fileId` in the state of a `lobe-cloud-sandbox` or `lobe-skills` `exportFile` call of the run's topic, never through message text. The item count is checked before any image is resolved.- Delete removes the Work row and, through the FK cascade, its versions; the files stay.- `rootOperationId` is the run's operation, so the completion lifecycle stamps the display anchor; the card appears after the run completes.diff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.mdindex db14f25ab89..3ebe30a05f1 100644--- a/apps/server/src/services/aiAgent/shareGate/README.md+++ b/apps/server/src/services/aiAgent/shareGate/README.md@@ -222,10 +222,11 @@ absence of a known exploit.3. `updateWork` / `deleteWork` reach only Works this conversation createdthrough the tool or `lh work` (`agentEditable`), never ones collectedautomatically or made in another conversation;- 4. collection images must be generated images or run outputs of the run's- account (`resolveAgentWorkCollectionItems`), and in a visitor run each image- must also appear in a message of the visitor topic (`visitorTopicId`), so- a guessed id of another creator image is refused as not found.+ 4. collection images must be images of the run's account+ (`resolveAgentWorkCollectionItems`): a generated image or run output must+ also appear in a tool result of the visitor topic, and any other image must+ come from an `exportFile` call of that topic (its state's `fileId`), so a+ guessed id of another creator image is refused as not found.Its implied grant is added after the activator check, so it never implies`lobe-activator` on its own.diff --git a/apps/server/src/services/toolExecution/serverRuntimes/work.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/work.test.tsindex dfb68ae8a09..d866a7729ca 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/work.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/work.test.ts@@ -114,6 +114,8 @@ describe('workRuntime', () => {expect(mocks.resolveCollection).toHaveBeenCalledWith({db: context.serverDB,items: [{ image: 'file_a' }, { caption: 'Night', image: '/f/file_b' }],+ shareVisitor: false,+ topicId: 'topic',userId: 'user',workspaceId: 'workspace',});@@ -282,7 +284,7 @@ describe('workRuntime', () => {.createWork({ items: [{ image: 'file_a' }], title: 'Covers', type: 'collection' });expect(mocks.resolveCollection).toHaveBeenCalledWith(- expect.objectContaining({ visitorTopicId: context.topicId }),+ expect.objectContaining({ shareVisitor: true, topicId: context.topicId }),);});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/work.ts b/apps/server/src/services/toolExecution/serverRuntimes/work.tsindex 8271d5c5e7d..41ca760c545 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/work.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/work.ts@@ -107,7 +107,8 @@ export const createWorkToolService = (context: ToolExecutionContext): WorkToolSedb,items,userId,- visitorTopicId: agentShareVisitor ? topicId : undefined,+ shareVisitor: !!agentShareVisitor,+ topicId,workspaceId,});// The cover names one of the items the same way; map it to that item'sdiff --git a/apps/server/src/services/workRegistration/agentWork.collectionProof.test.ts b/apps/server/src/services/workRegistration/agentWork.collectionProof.test.tsnew file mode 100644index 00000000000..18aaa68de27--- /dev/null+++ b/apps/server/src/services/workRegistration/agentWork.collectionProof.test.ts@@ -0,0 +1,112 @@+// @vitest-environment node+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { files, messagePlugins, messages, topics, users } from '@/database/schemas';++import { AgentWorkRunError, resolveAgentWorkCollectionItems } from './agentWork';++vi.mock('@/server/services/file', () => ({+ FileService: class {+ getFileAccessUrl = async (file: { id: string }) => `https://app.example.com/f/${file.id}`;+ },+}));++const db = await getTestDB();+const userId = 'collection-proof-user';+const topicId = 'collection-proof-topic';+const otherTopicId = 'collection-proof-other-topic';+const fileId = 'file_exported';++/** A tool call message of `topic` with its plugin row. */+const toolCall = async (+ id: string,+ plugin: { apiName: string; identifier: string; state?: unknown },+ content: string,+ topic = topicId,+) => {+ await db.insert(messages).values({ content, id, role: 'tool', topicId: topic, userId });+ await db.insert(messagePlugins).values({ id, userId, ...plugin });+};++const exportCall = (id: string, state: unknown, topic?: string) =>+ toolCall(+ id,+ { apiName: 'exportFile', identifier: 'lobe-cloud-sandbox', state },+ `File exported successfully.\n\nDownload URL: https://app.example.com/f/${fileId}`,+ topic,+ );++const resolve = (options: { shareVisitor?: boolean; topicId?: string } = {}) =>+ resolveAgentWorkCollectionItems({+ db,+ items: [{ image: `https://app.example.com/f/${fileId}` }],+ shareVisitor: options.shareVisitor,+ topicId: 'topicId' in options ? options.topicId : topicId,+ userId,+ });++const expectNotFound = async (promise: Promise<unknown>) => {+ const error = await promise.catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(AgentWorkRunError);+ expect((error as AgentWorkRunError).status).toBe(404);+};++beforeEach(async () => {+ await db.insert(users).values({ id: userId });+ await db.insert(topics).values([+ { id: topicId, userId },+ { id: otherTopicId, userId },+ ]);+ // The cloud sandbox stores its exports without a source.+ await db.insert(files).values({+ fileType: 'image/png',+ id: fileId,+ name: 'collection.png',+ size: 1024,+ url: 'files/collection.png',+ userId,+ });+});++afterEach(async () => {+ await db.delete(users).where(eq(users.id, userId));+});++describe('resolveAgentWorkCollectionItems for an image without a source', () => {+ it('accepts the file a sandbox exportFile call of the run conversation produced', async () => {+ await exportCall('msg_export', { fileId, success: true });++ await expect(resolve()).resolves.toEqual([+ { fileId, mimeType: 'image/png', url: `https://app.example.com/f/${fileId}` },+ ]);+ // A share visitor's own conversation proves it the same way.+ await expect(resolve({ shareVisitor: true })).resolves.toHaveLength(1);+ });++ it('refuses it when only message text names it', async () => {+ // This tool's own refusal, and any tool echoing the link, name the id in+ // their text; neither produced the file.+ await toolCall(+ 'msg_refusal',+ { apiName: 'createWork', identifier: 'lobe-work', state: { error: { code: 'not_found' } } },+ `Image ${fileId} not found`,+ );+ await toolCall(+ 'msg_echo',+ { apiName: 'runCommand', identifier: 'lobe-cloud-sandbox', state: { success: true } },+ `Download URL: https://app.example.com/f/${fileId}`,+ );++ await expectNotFound(resolve());+ await expectNotFound(resolve({ shareVisitor: true }));+ });++ it('refuses an export of another conversation or a run without one', async () => {+ await exportCall('msg_export_elsewhere', { fileId, success: true }, otherTopicId);++ await expectNotFound(resolve());+ await expectNotFound(resolve({ topicId: undefined }));+ });+});diff --git a/apps/server/src/services/workRegistration/agentWork.test.ts b/apps/server/src/services/workRegistration/agentWork.test.tsindex 354de771122..74b3981e371 100644--- a/apps/server/src/services/workRegistration/agentWork.test.ts+++ b/apps/server/src/services/workRegistration/agentWork.test.ts@@ -301,7 +301,7 @@ describe('resolveAgentWorkCollectionItems', () => {it.each([['an image of another user', { ...generatedImage, userId: 'user_2' }, 404],- ['a library upload', { ...generatedImage, source: null }, 404],+ ['a library upload no tool result names', { ...generatedImage, source: null }, 404],['a file that is not an image', { ...generatedImage, fileType: 'application/pdf' }, 409],])('refuses %s', async (_, file, status) => {mocks.findFile.mockResolvedValue(file);@@ -341,21 +341,30 @@ describe('resolveAgentWorkCollectionItems', () => {);});+ /** A run whose conversation holds `shown`, the messages naming the images. */+ const runShowing = (+ shown: { content: string; identifier?: string; role: string }[],+ options: { image?: string; shareVisitor?: boolean; topicId?: string } = {},+ ) => {+ const query = {+ from: vi.fn(() => query),+ leftJoin: vi.fn(() => query),+ where: vi.fn(async () => shown),+ };+ return resolveAgentWorkCollectionItems({+ db: { select: vi.fn(() => query) } as unknown as LobeChatDatabase,+ items: [{ image: options.image ?? 'file_img' }],+ shareVisitor: options.shareVisitor,+ topicId: 'topicId' in options ? options.topicId : 'tpc_run',+ userId: 'user_1',+ });+ };+it("keeps a share visitor's collection to images shown in that conversation", async () => {mocks.findFile.mockResolvedValue(generatedImage);mocks.fileAccessUrl.mockResolvedValue('https://app.example.com/f/file_img');- const visitorRun = (shown: { content: string; role: string }[]) => {- const query = {- from: vi.fn(() => query),- where: vi.fn(async () => shown),- };- return resolveAgentWorkCollectionItems({- db: { select: vi.fn(() => query) } as unknown as LobeChatDatabase,- items: [{ image: 'file_img' }],- userId: 'user_1',- visitorTopicId: 'tpc_visitor',- });- };+ const visitorRun = (shown: { content: string; identifier?: string; role: string }[]) =>+ runShowing(shown, { shareVisitor: true, topicId: 'tpc_visitor' });await expect(visitorRun([{ content: '', role: 'tool' }]),@@ -369,6 +378,11 @@ describe('resolveAgentWorkCollectionItems', () => {]),404,);+ // This tool's own refusal names the id too, and must not prove it on a retry.+ await expectStatus(+ visitorRun([{ content: 'Image file_img not found', identifier: 'lobe-work', role: 'tool' }]),+ 404,+ );// The creator's other images never appeared to this visitor.await expectStatus(visitorRun([]), 404);});diff --git a/apps/server/src/services/workRegistration/agentWork.ts b/apps/server/src/services/workRegistration/agentWork.tsindex e04469b5b82..11cd1e39e15 100644--- a/apps/server/src/services/workRegistration/agentWork.ts+++ b/apps/server/src/services/workRegistration/agentWork.ts@@ -1,11 +1,14 @@+import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';+import { WorkIdentifier } from '@lobechat/builtin-tool-work';+import { CLOUD_SANDBOX_IDENTIFIER } from '@lobechat/builtin-tools/fileEditScan';import type { AgentWorkRunContext, CollectionWorkItem, WorkAccessScope } from '@lobechat/types';import { COLLECTION_WORK_MAX_ITEMS, FileSource } from '@lobechat/types';-import { and, eq, or, sql } from 'drizzle-orm';+import { and, eq, inArray, or, sql } from 'drizzle-orm';import { FileModel } from '@/database/models/file';import { AgentWorkError, WorkModel } from '@/database/models/work';import { hasActiveWorkspaceMembership } from '@/database/models/workspace';-import { agentOperations, generations, messages } from '@/database/schemas';+import { agentOperations, generations, messagePlugins, messages } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import type { HeteroOperationJwtClaims } from '@/libs/trpc/utils/internalJwt';import { FileService } from '@/server/services/file';@@ -222,22 +225,32 @@ const isGenerationId = (id: string) => id.startsWith('gen_');/*** Resolve the images of a collection to stored image entries. Each must be an- * image the run's user generated or uploaded as run output; the URL the card- * shows comes from the file row, never from the agent.+ * image of the run's user; the URL the card shows comes from the file row,+ * never from the agent.*- * `visitorTopicId` is set for a share visitor's run, which executes as the- * creator: each image must then appear in a tool result of that visitor's- * conversation, so a visitor cannot pull the creator's other images into a- * card by guessing their ids.+ * Generated images and run outputs qualify as they are. Any other image of the+ * user qualifies only when a successful sandbox `exportFile` call of the run's+ * conversation produced it: the cloud sandbox stores its exports without a+ * source, and the agent must not claim the user's library uploads by id. The+ * proof is the `fileId` the server wrote to that call's state, never message+ * text, which any tool can echo (this tool's own "not found" included).+ *+ * A share visitor's run executes as the creator, so there every generated+ * image or run output must also appear in a tool result of the visitor's+ * conversation: a visitor cannot pull the creator's other images into a card+ * by guessing their ids.*/export const resolveAgentWorkCollectionItems = async (params: {db: LobeChatDatabase;items: { caption?: string; image: string }[];+ /** Whether the run is a share visitor's, which requires the proof for every image. */+ shareVisitor?: boolean;+ /** The run's conversation, whose tool results prove where an image came from. */+ topicId?: string;userId: string;- visitorTopicId?: string;workspaceId?: string;}): Promise<CollectionWorkItem[]> => {- const { db, items, userId, visitorTopicId, workspaceId } = params;+ const { db, items, shareVisitor, topicId, userId, workspaceId } = params;// Check the count before resolving: every item costs file (and generation)// queries, so an oversized list is refused before any of them run.if (items.length === 0) {@@ -267,35 +280,72 @@ export const resolveAgentWorkCollectionItems = async (params: {fileId = generation.fileId;}const file = await fileModel.findById(fileId);- if (!file || file.userId !== userId || !COLLECTION_IMAGE_SOURCES.has(file.source ?? '')) {+ if (!file || file.userId !== userId) {throw new AgentWorkRunError(`Image ${image} not found`, 404);}if (!file.fileType.startsWith('image/')) {throw new AgentWorkRunError(`File ${fileId} is not an image`, 409);}- return { caption, file, image, ref };+ const exported = !COLLECTION_IMAGE_SOURCES.has(file.source ?? '');+ return { caption, exported, file, image, ref };}),);- if (visitorTopicId) {+ const exports = files.filter(({ exported }) => exported);+ if (exports.length > 0) {+ if (!topicId) throw new AgentWorkRunError(`Image ${exports[0].image} not found`, 404);+ const exportCalls = await db+ .select({ fileId: sql<string>`${messagePlugins.state} ->> 'fileId'` })+ .from(messagePlugins)+ .innerJoin(messages, eq(messages.id, messagePlugins.id))+ .where(+ and(+ eq(messages.topicId, topicId),+ eq(messages.userId, userId),+ eq(messagePlugins.apiName, 'exportFile'),+ inArray(messagePlugins.identifier, [CLOUD_SANDBOX_IDENTIFIER, SkillsIdentifier]),+ inArray(+ sql`${messagePlugins.state} ->> 'fileId'`,+ exports.map(({ file }) => file.id),+ ),+ ),+ );+ const missing = exports.find(+ ({ file }) => !exportCalls.some((call) => call.fileId === file.id),+ );+ if (missing) throw new AgentWorkRunError(`Image ${missing.image} not found`, 404);+ }++ const shownToVisitor = files.filter(({ exported }) => shareVisitor && !exported);+ if (shownToVisitor.length > 0) {+ if (!topicId) throw new AgentWorkRunError(`Image ${shownToVisitor[0].image} not found`, 404);// Generated images live in generation topics; the conversation only holds// the id the agent names them by (the generation id or file link) in the// tool result that produced them. One scan of the topic returns the// messages naming any of the images.const shown = await db- .select({ content: messages.content, role: messages.role })+ .select({+ content: messages.content,+ identifier: messagePlugins.identifier,+ role: messages.role,+ }).from(messages)+ .leftJoin(messagePlugins, eq(messagePlugins.id, messages.id)).where(and(- eq(messages.topicId, visitorTopicId),+ eq(messages.topicId, topicId),eq(messages.userId, userId),- or(...files.map(({ ref }) => sql`position(${ref} in ${messages.content}) > 0`)),+ or(...shownToVisitor.map(({ ref }) => sql`position(${ref} in ${messages.content}) > 0`)),),);// Only tool results count: a message the visitor typed, or an assistant- // reply echoing it, can name any id the visitor guessed.- const toolResults = shown.filter(({ role }) => role === 'tool');- const missing = files.find(+ // reply echoing it, can name any id the visitor guessed. So can this tool's+ // own refusal ("Image <id> not found"), which a retry would otherwise read+ // as proof.+ const toolResults = shown.filter(+ ({ identifier, role }) => role === 'tool' && identifier !== WorkIdentifier,+ );+ const missing = shownToVisitor.find(({ ref }) => !toolResults.some(({ content }) => content?.includes(ref)),);if (missing) throw new AgentWorkRunError(`Image ${missing.image} not found`, 404);diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 0d6716aeddc..b674699988f 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -281,7 +281,8 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([// (operation, topic, tool call) from the execution context only, writes under// the share scope pinned to the visitor topic (`resolveRunWorkAccessScope`),// and changes or deletes only Works this conversation created. Collection images- // must be generated images or run outputs (`resolveAgentWorkCollectionItems`).+ // must be the creator's images the visitor conversation produced or showed+ // in a tool result (`resolveAgentWorkCollectionItems`).// See the allowed-builtins section of `shareGate/README.md`.WorkManifest.identifier,]);