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): preview tool-result images from remote device runs (#22211)

AmAzing-6d83a77dc1ff
diff --git a/apps/server/src/routers/lambda/file/upload.operationToken.test.ts b/apps/server/src/routers/lambda/file/upload.operationToken.test.ts
index d5bd746156a..920a82fc826 100644
--- a/apps/server/src/routers/lambda/file/upload.operationToken.test.ts
+++ b/apps/server/src/routers/lambda/file/upload.operationToken.test.ts
@@ -58,13 +58,24 @@ const upload = {
url: 'files/2026-10-21/evidence-hash.png',
};
-const operationCaller = () =>
+const operationCaller = (
+ capabilities = [
+ 'hetero:ingest',
+ 'hetero:finish',
+ 'hetero:intervention:read',
+ 'acceptance:evidence',
+ ],
+) =>
uploadRouter.createCaller({
+ heteroOperationCapabilities: capabilities,
heteroOperationScope: 'op_task_run',
userId: 'operation-owner',
workspaceId: 'workspace-1',
} as any);
+const chatRunCaller = () =>
+ operationCaller(['hetero:ingest', 'hetero:finish', 'hetero:intervention:read']);
+
describe('uploadRouter.createFile with a run operation token', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -113,3 +124,51 @@ describe('uploadRouter.createFile with a run operation token', () => {
);
});
});
+
+describe('uploadRouter.createFile with a chat run operation token', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.checkHash.mockResolvedValue({ isExist: false });
+ mocks.create.mockResolvedValue({ id: 'tool-image' });
+ });
+
+ it.each([
+ ['names it', { source: FileSource.ToolResult }],
+ // The image uploader of a CLI already on a device sends no source.
+ ['names no source', {}],
+ ])('files a tool-result image when the upload %s', async (_label, extra) => {
+ await expect(chatRunCaller().createFile({ ...upload, ...extra })).resolves.toEqual({
+ id: 'tool-image',
+ url: 'https://lobehub.com/f/tool-image',
+ });
+
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ source: FileSource.ToolResult, visibility: 'private' }),
+ true,
+ mocks.transaction,
+ );
+ });
+
+ it.each([
+ ['acceptance evidence', { source: FileSource.Acceptance }],
+ ['a library source', { source: FileSource.PageEditor }],
+ ['an unknown source', { source: 'not-a-source' }],
+ ['a knowledge base', { knowledgeBaseId: 'kb_owner', source: FileSource.ToolResult }],
+ ['public visibility', { source: FileSource.ToolResult, visibility: 'public' as const }],
+ ])('refuses %s', async (_label, extra) => {
+ await expect(chatRunCaller().createFile({ ...upload, ...extra })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(mocks.create).not.toHaveBeenCalled();
+ });
+
+ it('lets a Task run name a tool-result image alongside its evidence', async () => {
+ await operationCaller().createFile({ ...upload, source: FileSource.ToolResult });
+
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ source: FileSource.ToolResult, visibility: 'private' }),
+ true,
+ mocks.transaction,
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/file/upload.ts b/apps/server/src/routers/lambda/file/upload.ts
index f4576e9b4d4..544c34e7575 100644
--- a/apps/server/src/routers/lambda/file/upload.ts
+++ b/apps/server/src/routers/lambda/file/upload.ts
@@ -9,6 +9,7 @@ import { businessFileUploadCheck } from '@/business/server/lambda-routers/file';
import { checkFileStorageUsage } from '@/business/server/trpc-middlewares/lambda';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { router } from '@/libs/trpc/lambda';
+import type { HeteroOperationCapability } from '@/libs/trpc/utils/internalJwt';
import type { FileService } from '@/server/services/file';
import { downloadRemoteImage } from '@/server/services/file/downloadRemoteImage';
import {
@@ -35,10 +36,14 @@ const isStoredObjectAvailable = async (fileService: FileService, url: string): P
/**
* A run's operation token reaches `createFile` only to upload evidence into its
- * own acceptance round (see `authorizeHeteroOperationEvidence`). Keep what it
- * creates out of the creator's library: no folder or document parent, no
- * knowledge base, never public, and always filed as acceptance evidence, which
- * the resource listings hide.
+ * own acceptance round, or an image its tools returned (see
+ * `authorizeHeteroOperationEvidence`). Keep what it creates out of the
+ * creator's library: no folder or document parent, no knowledge base, never
+ * public, and always filed under a source the resource listings hide.
+ *
+ * An upload that names no source is evidence when the token may file evidence
+ * (the acceptance CLI sends none), and a tool-result image otherwise (so does
+ * the image uploader of a CLI released before `ToolResult` existed).
*/
const scopeOperationTokenUpload = <
T extends {
@@ -49,20 +54,28 @@ const scopeOperationTokenUpload = <
},
>(
input: T,
+ capabilities: HeteroOperationCapability[] = [],
): T => {
+ const allowed = [
+ ...(capabilities.includes('acceptance:evidence') ? [FileSource.Acceptance] : []),
+ ...(capabilities.includes('hetero:ingest') ? [FileSource.ToolResult] : []),
+ ];
+ const source = input.source === undefined ? allowed[0] : toFileSource(input.source);
+
if (
input.parentId ||
input.knowledgeBaseId ||
input.visibility === 'public' ||
- (input.source !== undefined && input.source !== FileSource.Acceptance)
+ !source ||
+ !allowed.includes(source)
) {
throw new TRPCError({
code: 'FORBIDDEN',
- message: "This run's token can only upload acceptance evidence",
+ message: "This run's token can only upload acceptance evidence or tool-result images",
});
}
- return { ...input, source: FileSource.Acceptance, visibility: 'private' };
+ return { ...input, source, visibility: 'private' };
};
export const uploadRouter = router({
@@ -89,7 +102,9 @@ export const uploadRouter = router({
}),
)
.mutation(async ({ ctx, input: requested }) => {
- const input = ctx.heteroOperationScope ? scopeOperationTokenUpload(requested) : requested;
+ const input = ctx.heteroOperationScope
+ ? scopeOperationTokenUpload(requested, ctx.heteroOperationCapabilities)
+ : requested;
const metadata = stripAgentShareFileProvenance(input.metadata);
const existingFile = await ctx.fileModel.checkHash(input.hash!);
const { isExist } = existingFile;
diff --git a/apps/server/src/routers/lambda/upload.ts b/apps/server/src/routers/lambda/upload.ts
index 8f293da65d1..4c4732f1e1a 100644
--- a/apps/server/src/routers/lambda/upload.ts
+++ b/apps/server/src/routers/lambda/upload.ts
@@ -39,7 +39,7 @@ const CONTENT_ADDRESSED_PATHNAME = /^files\/\d{4}-\d{2}-\d{2}\/[\da-f]{64}(?:\.[
/**
* A run's operation token reaches this router only to upload acceptance
- * evidence. It must sign a sized PUT through the reservation, which charges
+ * evidence or an image its tools returned. It must sign a sized PUT through the reservation, which charges
* quota, bounds the length and refuses a key that already holds an object, and
* only under a content-addressed key, never a pathname of its choosing.
*/
@@ -51,7 +51,7 @@ const assertOperationTokenUpload = (
if (input.size === undefined || !CONTENT_ADDRESSED_PATHNAME.test(input.pathname)) {
throw new TRPCError({
code: 'FORBIDDEN',
- message: "This run's token uploads only sized evidence under a content-addressed path",
+ message: "This run's token uploads only sized files under a content-addressed path",
});
}
};
diff --git a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
index df907745277..3f491f92526 100644
--- a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts
@@ -52,6 +52,18 @@ describe('createFileStoreImageUploader', () => {
expect(createFileInput.url).toMatch(/^files\/\d{4}-\d{2}-\d{2}\/[a-f0-9]{64}\.png$/);
});
+ it('files the image as a tool-result attachment, the one source a run token may create', async () => {
+ // A remote device uploads under the run's operation token, which may file
+ // only `tool-result` images outside a Task run; it also keeps the image out
+ // of the library when a desktop uploads under its own session.
+ const port = createPort();
+ const upload = createFileStoreImageUploader(async () => port);
+
+ await upload({ data: PNG_BASE64, mediaType: 'image/png' });
+
+ expect(vi.mocked(port.createFile).mock.calls[0][0].source).toBe('tool-result');
+ });
+
it('records the intrinsic size on the file metadata, matching the web uploader', async () => {
const port = createPort();
const upload = createFileStoreImageUploader(async () => port);
diff --git a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts
index eb67585b024..055b6ba5ae1 100644
--- a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts
+++ b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts
@@ -24,6 +24,12 @@ export interface FileStoreCreateFileInput {
};
name: string;
size: number;
+ /**
+ * `tool-result`: the image is an attachment of its tool message, not a
+ * library resource, and it is the only kind of file a run's operation token
+ * may create outside a Task run.
+ */
+ source: 'tool-result';
url: string;
}
@@ -106,6 +112,7 @@ export const createFileStoreImageUploader =
},
name: fileName,
size: buffer.length,
+ source: 'tool-result',
url: pathname,
});
diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.ts
index 1e590afcbb5..3da9d4534f6 100644
--- a/packages/trpc/src/lambda/context.ts
+++ b/packages/trpc/src/lambda/context.ts
@@ -24,6 +24,7 @@ import { isApiKeyExpired, validateApiKeyFormat } from '@/utils/apiKey';
import { getRequestClientIP } from '@/utils/requestClientIP';
import { describeOIDCAuthFailure, setAuthFailureHeader } from '../utils/authFailure';
+import type { HeteroOperationCapability } from '../utils/internalJwt';
import { HETERO_OPERATION_JWT_PURPOSE } from '../utils/internalJwt';
// Create context logger namespace
@@ -100,10 +101,17 @@ export interface AuthContext {
clientIp?: string | null;
clientMetadata?: ClientMetadata;
/**
- * Set only when a `hetero-operation` token was let through to an acceptance
- * evidence route: the operation it was minted for. Those routes must keep
- * their writes and reads on this operation's verification round β€” see
- * `authorizeHeteroOperationEvidence`.
+ * Set with `heteroOperationScope`: what the operation token was minted for,
+ * so a route open to several capabilities can tell which of its writes this
+ * token may make (`file.createFile` files acceptance evidence only for a
+ * Task run).
+ */
+ heteroOperationCapabilities?: HeteroOperationCapability[];
+ /**
+ * Set only when a `hetero-operation` token was let through to one of its
+ * routes (acceptance evidence, or tool-result image upload): the operation
+ * it was minted for. Those routes must keep their writes and reads on this
+ * operation β€” see `authorizeHeteroOperationEvidence`.
*/
heteroOperationScope?: string;
jwtPayload?: ClientSecretPayload | null;
diff --git a/packages/trpc/src/lambda/middleware/__tests__/heteroOperationEvidence.test.ts b/packages/trpc/src/lambda/middleware/__tests__/heteroOperationEvidence.test.ts
index 6b7757e5f04..b5c0238a3ee 100644
--- a/packages/trpc/src/lambda/middleware/__tests__/heteroOperationEvidence.test.ts
+++ b/packages/trpc/src/lambda/middleware/__tests__/heteroOperationEvidence.test.ts
@@ -33,6 +33,16 @@ const scopeOf = ({ ctx }: { ctx: any }) => ({
});
const testRouter = trpc.router({
+ file: trpc.router({
+ createFile: trpc.procedure.use(oidcAuth).mutation(({ ctx }: { ctx: any }) => ({
+ ...scopeOf({ ctx }),
+ capabilities: ctx.heteroOperationCapabilities,
+ })),
+ removeFile: trpc.procedure.use(oidcAuth).mutation(scopeOf),
+ }),
+ upload: trpc.router({
+ createS3PreSignedUrl: trpc.procedure.use(oidcAuth).mutation(scopeOf),
+ }),
verify: trpc.router({
deleteRun: trpc.procedure.use(oidcAuth).mutation(scopeOf),
submitCheckEvidence: trpc.procedure.use(oidcAuth).mutation(scopeOf),
@@ -119,3 +129,64 @@ describe('oidcAuth with a Task run operation token', () => {
});
});
});
+
+describe('oidcAuth with a chat run operation token', () => {
+ const chatRunToken = () =>
+ operationToken({
+ capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read'],
+ operation_id: 'op_chat_run',
+ });
+
+ beforeEach(() => {
+ resolvePrincipal.mockReset();
+ resolvePrincipal.mockResolvedValue({
+ operationId: 'op_chat_run',
+ userId: 'operation-owner',
+ workspaceId: 'ws_1',
+ });
+ });
+
+ it('lets the run upload the images its tools return, as the operation owner', async () => {
+ // A remote device holds no other identity for the owner: without these
+ // routes a Claude Code `Read` on an image reaches the card as `[Image: …]`.
+ const caller = createCaller({ oidcAuth: chatRunToken() } as any);
+
+ await expect(caller.upload.createS3PreSignedUrl()).resolves.toEqual({
+ scope: 'op_chat_run',
+ userId: 'operation-owner',
+ workspaceId: 'ws_1',
+ });
+ await expect(caller.file.createFile()).resolves.toMatchObject({
+ capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read'],
+ scope: 'op_chat_run',
+ });
+ expect(resolvePrincipal).toHaveBeenCalledWith(
+ expect.objectContaining({ capability: 'hetero:ingest', operationId: 'op_chat_run' }),
+ );
+ });
+
+ it('keeps the acceptance evidence routes closed to it', async () => {
+ const caller = createCaller({ oidcAuth: chatRunToken() } as any);
+
+ await expect(caller.verify.submitCheckEvidence()).rejects.toMatchObject({
+ code: 'UNAUTHORIZED',
+ });
+ expect(resolvePrincipal).not.toHaveBeenCalled();
+ });
+
+ it('keeps every other file route closed to it', async () => {
+ const caller = createCaller({ oidcAuth: chatRunToken() } as any);
+
+ await expect(caller.file.removeFile()).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ expect(resolvePrincipal).not.toHaveBeenCalled();
+ });
+
+ it('rejects a token that may not ingest', async () => {
+ const caller = createCaller({
+ oidcAuth: operationToken({ capabilities: ['hetero:finish'] }),
+ } as any);
+
+ await expect(caller.file.createFile()).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
+ expect(resolvePrincipal).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/trpc/src/lambda/middleware/heteroOperationEvidence.ts b/packages/trpc/src/lambda/middleware/heteroOperationEvidence.ts
index 2eee2f95ab2..c22e8ac6898 100644
--- a/packages/trpc/src/lambda/middleware/heteroOperationEvidence.ts
+++ b/packages/trpc/src/lambda/middleware/heteroOperationEvidence.ts
@@ -1,48 +1,63 @@
import { TRPCError } from '@trpc/server';
+import type { HeteroOperationCapability } from '../../utils/internalJwt';
import { validateHeteroOperationClaims } from '../../utils/internalJwt';
import type { OIDCAuth } from '../context';
+const EVIDENCE: readonly HeteroOperationCapability[] = ['acceptance:evidence'];
+const FILE_STORE: readonly HeteroOperationCapability[] = ['acceptance:evidence', 'hetero:ingest'];
+
/**
- * Routes a Task run's operation token may call to file evidence into its own
- * verification round: what `lh acceptance run result submit --operation` and
- * `lh acceptance run ingest --operation` reach on the plan-round path.
+ * Routes a run's operation token may call, and the capability each needs.
+ *
+ * A Task run (`acceptance:evidence`) files evidence into its own verification
+ * round: what `lh acceptance run result submit --operation` and
+ * `lh acceptance run ingest --operation` reach on the plan-round path. The
+ * round is owned by the operation's creator. On a device logged in as another
+ * member the token is the only identity that can reach it, so without these
+ * routes the run can produce evidence but never hand it in.
*
- * The round is owned by the operation's creator. On a device logged in as
- * another member the token is the only identity that can reach it, so without
- * these routes the run can produce evidence but never hand it in.
+ * Any run (`hetero:ingest`) also reaches the four file-store routes, to upload
+ * the images its tools return (Claude Code `Read` on an image file) so the
+ * ingested tool card can preview them. A device run holds no other identity
+ * for the operation's owner, so without them the card shows only an
+ * `[Image: …]` placeholder.
*
* The `verify.*` routes bind every read and write to `heteroOperationScope`,
* and `submitCheckEvidence` takes evidence only: the verdict and the rest of
* the result belong to the round's verifier. `upload.createS3PreSignedUrl`
* signs only a sized, reserved PUT under a content-addressed key.
- * `file.createFile` files what this token uploads as private acceptance
- * evidence, kept out of the creator's library, folders and knowledge bases, and
- * `user.getUserState` (the report-language check) returns only the response
- * language to it. Every other route keeps rejecting the token.
+ * `file.createFile` files what this token uploads as a private acceptance or
+ * tool-result attachment, kept out of the creator's library, folders and
+ * knowledge bases, and `user.getUserState` (the report-language check) returns
+ * only the response language to it. Every other route keeps rejecting the token.
*/
-export const HETERO_OPERATION_EVIDENCE_PATHS: ReadonlySet<string> = new Set([
- 'file.checkFileHash',
- 'file.createFile',
- 'upload.abortS3Upload',
- 'upload.createS3PreSignedUrl',
- 'user.getUserState',
- 'verify.getRun',
- 'verify.getVerifyState',
- 'verify.listResults',
- 'verify.submitCheckEvidence',
- 'verify.uploadEvidence',
+export const HETERO_OPERATION_ROUTE_CAPABILITIES: ReadonlyMap<
+ string,
+ readonly HeteroOperationCapability[]
+> = new Map([
+ ['file.checkFileHash', FILE_STORE],
+ ['file.createFile', FILE_STORE],
+ ['upload.abortS3Upload', FILE_STORE],
+ ['upload.createS3PreSignedUrl', FILE_STORE],
+ ['user.getUserState', EVIDENCE],
+ ['verify.getRun', EVIDENCE],
+ ['verify.getVerifyState', EVIDENCE],
+ ['verify.listResults', EVIDENCE],
+ ['verify.submitCheckEvidence', EVIDENCE],
+ ['verify.uploadEvidence', EVIDENCE],
]);
const reject = (message = 'hetero-operation tokens are not accepted on this endpoint') =>
new TRPCError({ code: 'UNAUTHORIZED', message });
/**
- * Let a `hetero-operation` token through to an evidence route, or throw.
+ * Let a `hetero-operation` token through to one of its routes, or throw.
*
- * The token must carry `acceptance:evidence`, stay in the workspace it was
- * minted for, and belong to a run that is still going under a principal that
- * is still authorized β€” the same re-check every other operation endpoint makes.
+ * The token must carry a capability the route accepts, stay in the workspace
+ * it was minted for, and belong to a run that is still going under a principal
+ * that is still authorized β€” the same re-check every other operation endpoint
+ * makes.
*/
export const authorizeHeteroOperationEvidence = async (params: {
oidcAuth: OIDCAuth;
@@ -50,16 +65,18 @@ export const authorizeHeteroOperationEvidence = async (params: {
workspaceId?: string | null;
}) => {
const { oidcAuth, path, workspaceId } = params;
- if (!HETERO_OPERATION_EVIDENCE_PATHS.has(path)) throw reject();
+ const accepted = HETERO_OPERATION_ROUTE_CAPABILITIES.get(path);
+ if (!accepted) throw reject();
const claims = validateHeteroOperationClaims(oidcAuth as Record<string, unknown>);
- if (!claims?.capabilities.includes('acceptance:evidence')) throw reject();
+ const capability = accepted.find((item) => claims?.capabilities.includes(item));
+ if (!claims || !capability) throw reject();
// A header naming another workspace must not move the token out of its own.
if (workspaceId && workspaceId !== claims.workspace_id) {
throw reject('Operation token is bound to another workspace');
}
- // Loaded only once an operation token reaches an evidence route: `oidcAuth`
+ // Loaded only once an operation token reaches one of its routes: `oidcAuth`
// sits in front of every authed router, and a static import would pull the
// workspace and RBAC models into each of them at module load.
const [
@@ -72,12 +89,13 @@ export const authorizeHeteroOperationEvidence = async (params: {
try {
const principal = await resolveActiveHeteroOperationPrincipal({
- capability: 'acceptance:evidence',
+ capability,
claims,
db: await getServerDB(),
operationId: claims.operation_id,
});
return {
+ heteroOperationCapabilities: claims.capabilities,
heteroOperationScope: principal.operationId,
userId: principal.userId,
workspaceId: principal.workspaceId,
diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.ts
index 4d80bc427b0..3e328dfe042 100644
--- a/packages/types/src/files/index.ts
+++ b/packages/types/src/files/index.ts
@@ -26,6 +26,12 @@ export enum FileSource {
Canvas = 'canvas',
ImageGeneration = 'image_generation',
PageEditor = 'page-editor',
+ /**
+ * Image an agent's tool returned β€” a Claude Code `Read` on an image file β€”
+ * uploaded so the tool card can preview it. Owned by that message, not by
+ * the user's library.
+ */
+ ToolResult = 'tool-result',
VideoGeneration = 'video_generation',
}
@@ -45,6 +51,7 @@ export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [
FileSource.Acceptance,
FileSource.AgentDocument,
FileSource.Canvas,
+ FileSource.ToolResult,
];
/** Sources a generation model wrote, as opposed to anything a human put there. */