π€― 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
β¨ feat(hetero): upload CC Read-on-image results on the desktop local spawn path (#16965)
Arvin Xu740a77e710e6
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.mdindex 5cd9ddd1f06..ed5377af05b 100644--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md@@ -515,3 +515,49 @@- With `http_proxy`/`HTTP_PROXY` set, `curl http://localhost:<port>` returns theproxy's 502 instead of connection-refused, faking a "server up but broken" signal.Always `curl --noproxy '*'` for local port probes.++### E8. β WORKS β Electron pool instance boots BLANK because the copied golden login is dead++- **Situation**: `electron-dev.sh start <id>` seeds userData from the golden dev profile,+ but the app renders an empty `#root` (innerText length 0, only the LobeHub watermark) and+ `app-probe.sh auth` returns `isSignedIn:false`. The instance log shows+ `Refresh response missing access_token or refresh_token { error: 'invalid_grant' }`.+- **Cause (measured, not guessed)**: OIDC refresh tokens are single-use. Every prior+ `start <id>` copied the same golden profile and consumed/rotated its refresh token, so the+ copy's token is already dead. A blank shell here is an AUTH failure, not a render bug β+ read the instance log before chasing the SPA.+- **Doesn't work**: pointing `LOBE_GOLDEN_PROFILE` at the packaged app's profile+ (`~/Library/Application Support/LobeHub`) β the pool instance's startup refresh will rotate+ that token too and log the user out of their real desktop app.+- **Works β inject a valid credential the app already owns, no new OAuth grant**:+ the prod lambda accepts any of the user's valid OIDC access tokens via the `Oidc-Auth`+ header, and the CLI keeps one in `~/.lobehub`. Extract it with the CLI's own+ `getValidToken()` (it auto-refreshes), then override the single main-process accessor:+ ```ts+ // apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts β [AGENT-TEST] REMOVE+ async getAccessToken(): Promise<string | null> {+ if (process.env.LOBE_TEST_ACCESS_TOKEN) return process.env.LOBE_TEST_ACCESS_TOKEN;+ ...+ ```+ `export LOBE_TEST_ACCESS_TOKEN=...` before `electron-dev.sh start <id>` (the script forwards+ the shell env). This authenticates BOTH the renderer (BackendProxyProtocolManager injects the+ same token) and any main-process fetch, so the whole app comes up signed in. Revert with+ `git checkout --` + `grep -rn AGENT-TEST` afterwards, and never echo the token.+- **Gotcha**: a worktree installed with `pnpm install --ignore-scripts` has NO electron binary+ (`node_modules/.pnpm/electron@*/node_modules/electron/dist` missing). Fix with+ `cd apps/desktop && pnpm rebuild electron`. Also remember `apps/desktop` and `apps/cli` are+ NOT in the root pnpm workspace β install inside each.++### C5. β WORKS β main-process `logger.info` is invisible unless `DEBUG` is set++- **Situation**: proving WHICH code path the Electron main process took (e.g. hetero+ `ClaudeAgentSdkSession` vs the CLI-spawn `AgentStreamPipeline`). Both produce identical+ user-visible output, so the verdict needs a main-process log line.+- **Doesn't work**: grepping the instance log for the `logger.info('Starting Claude Code SDK+session:')` line. In development `createLogger().info` routes to the `debug` package, which+ prints nothing unless its namespace is enabled (only `console.error` shows up unconditionally).+ Absence of the line is NOT evidence the branch didn't run.+- **Works**: `export DEBUG='controllers:*'` before `electron-dev.sh start <id>`, then+ `grep -oE "controllers:HeterogeneousAgentCtr INFO: [^']*" /tmp/lobe-electron-pool/instance-<id>.log`.+ Don't trust the hetero tracing dir for this β it is gated and the copied golden profile ships+ STALE trace sessions from months earlier that look like a fresh run.diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.tsindex 0328eac5f47..e7b7ec87bed 100644--- a/apps/cli/src/commands/hetero.test.ts+++ b/apps/cli/src/commands/hetero.test.ts@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';import path from 'node:path';import { PassThrough } from 'node:stream';+import type * as HeteroSpawn from '@lobechat/heterogeneous-agents/spawn';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -18,7 +19,10 @@ const { mockGetTrpcClient, mockHeteroFinishMutate, mockHeteroIngestMutate } = vimockHeteroIngestMutate: vi.fn(),}));-vi.mock('@lobechat/heterogeneous-agents/spawn', () => ({+// Keep the real module (notably `createFileStoreImageUploader`) and stub only+// the process spawn, so the wiring below exercises the actual uploader factory.+vi.mock('@lobechat/heterogeneous-agents/spawn', async (importOriginal) => ({+ ...(await importOriginal<typeof HeteroSpawn>()),spawnAgent: mockSpawnAgent,}));@@ -472,6 +476,37 @@ describe('hetero exec command', () => {expect(exitSpy).toHaveBeenCalledWith(1);});+ // `codex` rather than `claude-code`: the latter mounts the AskUserQuestion MCP+ // long-poll on server-ingest runs, which never settles under a faked handle.+ it('wires a tool_result image uploader for server-ingest runs', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd([+ 'hetero',+ 'exec',+ '--type',+ 'codex',+ '--prompt',+ 'hi',+ '--topic',+ 'topic-1',+ '--operation-id',+ 'op-server',+ '--render',+ 'none',+ ]);++ expect(mockSpawnAgent.mock.calls[0][0].uploadImage).toBeInstanceOf(Function);+ });++ it('leaves the image uploader unwired for standalone runs, which persist nothing', async () => {+ mockSpawnAgent.mockReturnValue(createFakeHandle());++ await runCmd(['hetero', 'exec', '--type', 'codex', '--prompt', 'hi', '--render', 'none']);++ expect(mockSpawnAgent.mock.calls[0][0].uploadImage).toBeUndefined();+ });+it('finishes server-ingest runs with error when spawnAgent rejects before streaming', async () => {mockSpawnAgent.mockRejectedValue(new Error('spawn claude ENOENT'));diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex f008cc2ef36..1d020ccef2c 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -15,26 +15,17 @@ import type {AgentStreamEvent,UploadHeterogeneousImage,} from '@lobechat/heterogeneous-agents/spawn';-import { spawnAgent } from '@lobechat/heterogeneous-agents/spawn';+import { createFileStoreImageUploader, spawnAgent } from '@lobechat/heterogeneous-agents/spawn';import type { Command } from 'commander';import { getTrpcClient } from '../api/client';import { log } from '../utils/logger';import { TrpcIngestSink } from '../utils/TrpcIngestSink';-import { uploadFileBuffer } from '../utils/uploadLocalFile';const SUPPORTED_AGENT_TYPES = new Set(['claude-code', 'codex']);const CODEX_REASONING_EFFORT_CONFIG_KEY = 'model_reasoning_effort';const CODEX_SERVICE_TIER_CONFIG_KEY = 'service_tier';-/** Extension seed for an uploaded tool_result image, by IANA media type. */-const IMAGE_EXT_BY_MEDIA_TYPE: Record<string, string> = {- 'image/gif': 'gif',- 'image/jpeg': 'jpg',- 'image/png': 'png',- 'image/webp': 'webp',-};-/*** Patterns that indicate a `--resume <sessionId>` run should be retried* without `--resume`. Two classes of failure:@@ -504,15 +495,14 @@ const exec = async (options: ExecOptions): Promise<void> => {);serverIngester = new SerialServerIngester(sink);- uploadImage = async ({ data, mediaType }) => {- const ext = IMAGE_EXT_BY_MEDIA_TYPE[mediaType] ?? 'png';- const record = await uploadFileBuffer(await getTrpcClient(), {- buffer: Buffer.from(data, 'base64'),- fileName: `cc-read-image.${ext}`,- fileType: mediaType,- });- return { fileId: record.id, url: record.url };- };+ uploadImage = createFileStoreImageUploader(async () => {+ const lambda = await getTrpcClient();+ return {+ checkFileHash: (input) => lambda.file.checkFileHash.mutate(input),+ createFile: (input) => lambda.file.createFile.mutate(input),+ createS3PreSignedUrl: (input) => lambda.upload.createS3PreSignedUrl.mutate(input),+ };+ });}// βββ AskUserQuestion MCP β remote Human-in-the-loop (claude-code only) ββββββdiff --git a/apps/cli/src/utils/uploadLocalFile.ts b/apps/cli/src/utils/uploadLocalFile.tsindex a438922df43..6b576632a76 100644--- a/apps/cli/src/utils/uploadLocalFile.ts+++ b/apps/cli/src/utils/uploadLocalFile.ts@@ -58,12 +58,11 @@ export interface UploadFileBufferInput {/*** Upload an in-memory buffer to S3 via a pre-signed URL and create the file- * record. This is the buffer-based core shared by {@link uploadLocalFile} (path- * source) and in-memory producers such as the heterogeneous-agent image echo.+ * record β the buffer-based core behind {@link uploadLocalFile}.** @returns the created file record (`{ id, url, ... }`)*/-export const uploadFileBuffer = async (+const uploadFileBuffer = async (client: TrpcClient,{ buffer, fileName, fileType }: UploadFileBufferInput,options: UploadLocalFileOptions = {},diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.tsindex 8770324c7a5..59696573d97 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts@@ -32,6 +32,7 @@ import {AgentStreamPipeline,buildAgentInput,ClaudeAgentSdkSession,+ createFileStoreImageUploader,materializeImageToPath,normalizeImage,readCodexSessionModel,@@ -45,6 +46,7 @@ import { detectHeterogeneousCliCommand } from '@/modules/binaries';import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';import { fetchClaudeCodeQuota } from '@/modules/heterogeneousAgent/claudeCodeQuota';import { fetchCodexQuota } from '@/modules/heterogeneousAgent/codexQuota';+import { createLambdaFileStorePort } from '@/modules/heterogeneousAgent/fileStorePort';import type {HeterogeneousAgentBuildPlan,HeterogeneousAgentImageAttachment,@@ -53,6 +55,7 @@ import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';import { createLogger } from '@/utils/logger';import { ControllerModule, IpcMethod } from './index';+import RemoteServerConfigCtr from './RemoteServerConfigCtr';const logger = createLogger('controllers:HeterogeneousAgentCtr');@@ -276,6 +279,22 @@ export default class HeterogeneousAgentCtr extends ControllerModule {private askUserMcpServer?: AskUserMcpServer;private askUserMcpStartPromise?: Promise<AskUserMcpServer>;+ private get remoteServerConfigCtr() {+ return this.app.getController(RemoteServerConfigCtr);+ }++ /**+ * Uploads a base64 tool_result image (CC `Read` on an image file) to the file+ * store, so the persisted event carries a `{ fileId, url }` reference instead+ * of heavy base64. Mirrors what `lh hetero exec` does for the gateway path.+ */+ private uploadResultImage = createFileStoreImageUploader(() =>+ createLambdaFileStorePort({+ getAccessToken: () => this.remoteServerConfigCtr.getAccessToken(),+ getServerUrl: async () => (await this.remoteServerConfigCtr.getRemoteServerUrl()) ?? null,+ }),+ );+private resolveSessionCommand(session: AgentSession): string {const resolvedCommand = session.command.trim();if (resolvedCommand) return resolvedCommand;@@ -1125,6 +1144,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {resumeSessionId: session.agentSessionId,sessionId: session.sessionId,stdinPayload,+ uploadImage: this.uploadResultImage,});session.sdkSession = sdkSession;@@ -1294,6 +1314,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {initialCumulativeUsage,initialModel: session.model,operationId: params.operationId,+ uploadImage: this.uploadResultImage,});let stdoutBroadcastQueue: Promise<void> = Promise.resolve();diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.tsindex a9e1aa4fc4e..7968b4fb3d3 100644--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts@@ -442,6 +442,9 @@ describe('HeterogeneousAgentCtr', () => {cwd: FAKE_DESKTOP_PATH,operationId: 'op-test',stdinPayload: expect.stringContaining('watch ci'),+ // `Read` on an image echoes base64; without this the SDK path would+ // persist an `[Image: β¦]` placeholder instead of a thumbnail.+ uploadImage: expect.any(Function),}),);diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.tsnew file mode 100644index 00000000000..124bef3bd04--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.test.ts@@ -0,0 +1,100 @@+import superjson from 'superjson';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createLambdaFileStorePort } from './fileStorePort';++vi.mock('@/utils/logger', () => ({+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),+}));++const auth = {+ getAccessToken: async () => 'token-123',+ getServerUrl: async () => 'https://cloud.lobehub.com',+};++/** A tRPC v11 success envelope: `result.data` is a superjson payload. */+const trpcOk = (data: unknown) => ({+ json: async () => ({ result: { data: superjson.serialize(data) } }),+ ok: true,+ status: 200,+ statusText: 'OK',+});++describe('createLambdaFileStorePort', () => {+ beforeEach(() => {+ vi.stubGlobal('fetch', vi.fn());+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('returns undefined when the app has no authed remote server', async () => {+ expect(+ await createLambdaFileStorePort({ ...auth, getAccessToken: async () => null }),+ ).toBeUndefined();+ expect(+ await createLambdaFileStorePort({ ...auth, getServerUrl: async () => null }),+ ).toBeUndefined();+ });++ it('POSTs a superjson-serialized input to the lambda procedure and deserializes the result', async () => {+ vi.mocked(fetch).mockResolvedValue(trpcOk({ isExist: true, url: 'files/a/b.png' }) as any);++ const port = await createLambdaFileStorePort(auth);+ const result = await port!.checkFileHash({ hash: 'abc' });++ expect(result).toEqual({ isExist: true, url: 'files/a/b.png' });+ expect(fetch).toHaveBeenCalledWith('https://cloud.lobehub.com/trpc/lambda/file.checkFileHash', {+ body: JSON.stringify(superjson.serialize({ hash: 'abc' })),+ headers: { 'Content-Type': 'application/json', 'Oidc-Auth': 'token-123' },+ method: 'POST',+ });+ });++ it('strips a trailing slash from the server url', async () => {+ vi.mocked(fetch).mockResolvedValue(trpcOk('https://s3/presigned') as any);++ const port = await createLambdaFileStorePort({+ ...auth,+ getServerUrl: async () => 'https://cloud.lobehub.com/',+ });+ await port!.createS3PreSignedUrl({ pathname: 'files/a/b.png' });++ expect(vi.mocked(fetch).mock.calls[0][0]).toBe(+ 'https://cloud.lobehub.com/trpc/lambda/upload.createS3PreSignedUrl',+ );+ });++ it('surfaces a tRPC error envelope as a throw', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: async () => ({+ error: superjson.serialize({ code: -32_001, message: 'UNAUTHORIZED' }),+ }),+ ok: false,+ status: 401,+ statusText: 'Unauthorized',+ } as any);++ const port = await createLambdaFileStorePort(auth);++ await expect(port!.createFile({} as any)).rejects.toThrow(+ 'trpc file.createFile failed: 401 UNAUTHORIZED',+ );+ });++ it('surfaces a non-JSON failure response as a throw', async () => {+ vi.mocked(fetch).mockResolvedValue({+ json: async () => {+ throw new Error('not json');+ },+ ok: false,+ status: 502,+ statusText: 'Bad Gateway',+ } as any);++ const port = await createLambdaFileStorePort(auth);++ await expect(port!.checkFileHash({ hash: 'abc' })).rejects.toThrow('502');+ });+});diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.ts b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.tsnew file mode 100644index 00000000000..a7059e498f1--- /dev/null+++ b/apps/desktop/src/main/modules/heterogeneousAgent/fileStorePort.ts@@ -0,0 +1,92 @@+import type { FileStorePort } from '@lobechat/heterogeneous-agents/spawn';+import superjson from 'superjson';++import { createLogger } from '@/utils/logger';++const logger = createLogger('modules:heterogeneousAgent:fileStorePort');++export interface RemoteServerAuth {+ getAccessToken: () => Promise<string | null>;+ getServerUrl: () => Promise<string | null>;+}++interface LambdaCallContext {+ accessToken: string;+ serverUrl: string;+}++/**+ * A failing call may carry a superjson `error` envelope, or nothing at all when+ * a proxy answered with HTML β never let extracting the detail mask the failure.+ */+const errorDetail = (payload: { error?: unknown } | undefined, response: Response): string => {+ if (!payload?.error) return response.statusText;++ try {+ const error = superjson.deserialize(payload.error as any) as { message?: string };+ return error?.message ?? response.statusText;+ } catch {+ return response.statusText;+ }+};++/**+ * Call a Lambda tRPC mutation over plain fetch.+ *+ * Electron main has no tRPC client β and can't reuse the renderer's, which+ * reaches the server through the `BackendProxyProtocolManager` custom protocol.+ * The wire shape is tRPC v11's non-batched `httpLink`: POST to+ * `<url>/<procedure>` with the superjson-serialized input as the body, and a+ * `{ result: { data } }` / `{ error }` envelope back, both superjson payloads.+ */+const lambdaMutation = async <T>(+ { accessToken, serverUrl }: LambdaCallContext,+ procedure: string,+ input: unknown,+): Promise<T> => {+ const base = serverUrl.replace(/\/$/, '');++ const response = await fetch(`${base}/trpc/lambda/${procedure}`, {+ body: JSON.stringify(superjson.serialize(input)),+ headers: { 'Content-Type': 'application/json', 'Oidc-Auth': accessToken },+ method: 'POST',+ });++ const payload = (await response.json().catch(() => undefined)) as+ { error?: unknown; result?: { data?: unknown } } | undefined;++ if (!response.ok || !payload || 'error' in payload) {+ throw new Error(+ `trpc ${procedure} failed: ${response.status} ${errorDetail(payload, response)}`,+ );+ }++ return superjson.deserialize(payload.result?.data as any) as T;+};++/**+ * Resolve the file-store port backing the heterogeneous-agent image echo on the+ * desktop's local direct-spawn path.+ *+ * Returns `undefined` when the app has no authed remote server (never signed+ * in, or token decryption failed) β the pipeline then drops the image and keeps+ * the `[Image: β¦]` placeholder rather than failing the run.+ */+export const createLambdaFileStorePort = async (+ auth: RemoteServerAuth,+): Promise<FileStorePort | undefined> => {+ const [serverUrl, accessToken] = await Promise.all([auth.getServerUrl(), auth.getAccessToken()]);++ if (!serverUrl || !accessToken) {+ logger.debug('No authed remote server β skipping tool_result image upload');+ return undefined;+ }++ const ctx: LambdaCallContext = { accessToken, serverUrl };++ return {+ checkFileHash: (input) => lambdaMutation(ctx, 'file.checkFileHash', input),+ createFile: (input) => lambdaMutation(ctx, 'file.createFile', input),+ createS3PreSignedUrl: (input) => lambdaMutation(ctx, 'upload.createS3PreSignedUrl', input),+ };+};diff --git a/packages/builtin-tool-claude-code/src/client/Render/displayControls.test.ts b/packages/builtin-tool-claude-code/src/client/Render/displayControls.test.tsnew file mode 100644index 00000000000..fb723fb551f--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Render/displayControls.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { ClaudeCodeApiName } from '../../types';+import { resolveClaudeCodeRenderDisplayControl } from './displayControls';++const uploaded = { images: [{ mediaType: 'image/png', url: 'https://cdn/a.png' }] };++describe('resolveClaudeCodeRenderDisplayControl', () => {+ describe('Read', () => {+ it('expands once the result carries an uploaded image', () => {+ expect(resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.Read, uploaded)).toBe(+ 'expand',+ );+ });++ it('stays collapsed for source text, so a Read never dumps a file into the transcript', () => {+ expect(resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.Read)).toBeUndefined();+ expect(resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.Read, {})).toBeUndefined();+ expect(+ resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.Read, { images: [] }),+ ).toBeUndefined();+ });++ it('stays collapsed when the image failed to upload (no url to render)', () => {+ // The pipeline drops a failed entry, but an entry with no `url` must not+ // expand an empty card β the `[Image: β¦]` placeholder is the fallback.+ expect(+ resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.Read, {+ images: [{ mediaType: 'image/png' }],+ }),+ ).toBeUndefined();+ });++ it('is still collapsed while the call is in flight (no result yet)', () => {+ expect(+ resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.Read, undefined),+ ).toBeUndefined();+ });+ });++ it('keeps the static map for every other api, regardless of pluginState', () => {+ expect(resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.Edit)).toBe('expand');+ expect(resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.TodoWrite)).toBe('expand');+ // An unrelated api with images on its result must not be force-expanded.+ expect(resolveClaudeCodeRenderDisplayControl(ClaudeCodeApiName.Grep, uploaded)).toBeUndefined();+ });+});diff --git a/packages/builtin-tool-claude-code/src/client/Render/displayControls.ts b/packages/builtin-tool-claude-code/src/client/Render/displayControls.tsnew file mode 100644index 00000000000..334a588a228--- /dev/null+++ b/packages/builtin-tool-claude-code/src/client/Render/displayControls.ts@@ -0,0 +1,64 @@+import type { RenderDisplayControl } from '@lobechat/types';++import { ClaudeCodeApiName } from '../../types';+import {+ isLinearMcpApiName,+ LINEAR_MCP_PREFIX,+ LINEAR_MCP_TOOL_NAMES,+} from '../Inspector/linearMcpLabels';++/**+ * Per-APIName default display control for CC tool renders.+ *+ * CC doesn't ship a LobeChat manifest (its tools come from Anthropic tool_use+ * blocks at runtime), so the store's manifest-based `getRenderDisplayControl`+ * can't reach these. The builtin-tools aggregator exposes them via+ * `getBuiltinRenderDisplayControl` as a fallback.+ */+const FixedClaudeCodeRenderDisplayControls: Record<string, RenderDisplayControl> = {+ [ClaudeCodeApiName.Edit]: 'expand',+ [ClaudeCodeApiName.SendMessage]: 'expand',+ [ClaudeCodeApiName.TaskList]: 'expand',+ [ClaudeCodeApiName.TaskUpdate]: 'expand',+ [ClaudeCodeApiName.TodoWrite]: 'expand',+ [ClaudeCodeApiName.Write]: 'expand',+ ...Object.fromEntries(+ LINEAR_MCP_TOOL_NAMES.map((tool) => [`${LINEAR_MCP_PREFIX}${tool}`, 'expand']),+ ),+};++export const ClaudeCodeRenderDisplayControls: Record<string, RenderDisplayControl> = new Proxy(+ FixedClaudeCodeRenderDisplayControls,+ {+ get: (target, prop) => {+ if (typeof prop !== 'string') return undefined;+ return target[prop] || (isLinearMcpApiName(prop) ? 'expand' : undefined);+ },+ },+);++/** True once a tool_result carries at least one successfully uploaded image. */+const hasUploadedImage = (pluginState?: unknown): boolean => {+ const images = (pluginState as { images?: { url?: string }[] } | undefined)?.images;+ return !!images?.some((image) => !!image.url);+};++/**+ * Display control for a CC tool, refined by the tool_result when the static map+ * alone can't decide.+ *+ * `Read` is the one API whose output shape depends on its target: on an image+ * file it renders uploaded thumbnails, on anything else the source text. A+ * thumbnail is the whole point of the card, so expand it; source text stays+ * collapsed rather than dumping a file into the transcript. `pluginState` is+ * undefined while the call is still in flight, so the card only pops open once+ * the image has actually landed.+ */+export const resolveClaudeCodeRenderDisplayControl = (+ apiName: string,+ pluginState?: unknown,+): RenderDisplayControl | undefined => {+ if (apiName === ClaudeCodeApiName.Read && hasUploadedImage(pluginState)) return 'expand';++ return ClaudeCodeRenderDisplayControls[apiName];+};diff --git a/packages/builtin-tool-claude-code/src/client/Render/index.ts b/packages/builtin-tool-claude-code/src/client/Render/index.tsindex a6f3d11c12f..7a3f6c566c3 100644--- a/packages/builtin-tool-claude-code/src/client/Render/index.ts+++ b/packages/builtin-tool-claude-code/src/client/Render/index.ts@@ -1,12 +1,7 @@import { RunCommandRender } from '@lobechat/shared-tool-ui/renders';-import type { BuiltinRender, RenderDisplayControl } from '@lobechat/types';+import type { BuiltinRender } from '@lobechat/types';import { ClaudeCodeApiName } from '../../types';-import {- isLinearMcpApiName,- LINEAR_MCP_PREFIX,- LINEAR_MCP_TOOL_NAMES,-} from '../Inspector/linearMcpLabels';import Agent from './Agent';import AskUserQuestion from './AskUserQuestion';import Edit from './Edit';@@ -63,32 +58,7 @@ export const ClaudeCodeRenders = new Proxy(FixedClaudeCodeRenders, {},}) as unknown as Record<string, BuiltinRender>;-/**- * Per-APIName default display control for CC tool renders.- *- * CC doesn't ship a LobeChat manifest (its tools come from Anthropic tool_use- * blocks at runtime), so the store's manifest-based `getRenderDisplayControl`- * can't reach these. The builtin-tools aggregator exposes this map via- * `getBuiltinRenderDisplayControl` as a fallback.- */-const FixedClaudeCodeRenderDisplayControls: Record<string, RenderDisplayControl> = {- [ClaudeCodeApiName.Edit]: 'expand',- [ClaudeCodeApiName.SendMessage]: 'expand',- [ClaudeCodeApiName.TaskList]: 'expand',- [ClaudeCodeApiName.TaskUpdate]: 'expand',- [ClaudeCodeApiName.TodoWrite]: 'expand',- [ClaudeCodeApiName.Write]: 'expand',- ...Object.fromEntries(- LINEAR_MCP_TOOL_NAMES.map((tool) => [`${LINEAR_MCP_PREFIX}${tool}`, 'expand']),- ),-};--export const ClaudeCodeRenderDisplayControls: Record<string, RenderDisplayControl> = new Proxy(- FixedClaudeCodeRenderDisplayControls,- {- get: (target, prop) => {- if (typeof prop !== 'string') return undefined;- return target[prop] || (isLinearMcpApiName(prop) ? 'expand' : undefined);- },- },-);+export {+ ClaudeCodeRenderDisplayControls,+ resolveClaudeCodeRenderDisplayControl,+} from './displayControls';diff --git a/packages/builtin-tool-claude-code/src/client/index.ts b/packages/builtin-tool-claude-code/src/client/index.tsindex a66286d8a3b..75ddb1caf1e 100644--- a/packages/builtin-tool-claude-code/src/client/index.ts+++ b/packages/builtin-tool-claude-code/src/client/index.ts@@ -2,6 +2,10 @@ export { ClaudeCodeApiName, ClaudeCodeIdentifier } from '../types';export { ClaudeCodeInspectors } from './Inspector';export { formatLinearMcpShortLabel } from './Inspector/linearMcpLabels';export { ClaudeCodeInterventions } from './Intervention';-export { ClaudeCodeRenderDisplayControls, ClaudeCodeRenders } from './Render';+export {+ ClaudeCodeRenderDisplayControls,+ ClaudeCodeRenders,+ resolveClaudeCodeRenderDisplayControl,+} from './Render';export { ClaudeCodeStreamings } from './Streaming';export { CC_SUBAGENT_TYPES, type CCSubagentTypeInfo, resolveCCSubagentType } from './subagentTypes';diff --git a/packages/builtin-tool-claude-code/vitest.config.mts b/packages/builtin-tool-claude-code/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-claude-code/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/builtin-tools/src/displayControls.test.ts b/packages/builtin-tools/src/displayControls.test.tsindex b428b2e258f..2cef6862638 100644--- a/packages/builtin-tools/src/displayControls.test.ts+++ b/packages/builtin-tools/src/displayControls.test.ts@@ -5,7 +5,11 @@ import { getBuiltinRenderDisplayControl } from './displayControls';vi.mock('@lobechat/builtin-tool-claude-code/client', () => ({ClaudeCodeIdentifier: 'claude-code',- ClaudeCodeRenderDisplayControls: {},+ // Stand-in for the real resolver: only `Read` on an uploaded image expands.+ resolveClaudeCodeRenderDisplayControl: (apiName: string, pluginState?: any) =>+ apiName === 'Read' && pluginState?.images?.some((image: any) => !!image.url)+ ? 'expand'+ : undefined,}));describe('CodexRenderDisplayControls', () => {@@ -14,3 +18,23 @@ describe('CodexRenderDisplayControls', () => {expect(getBuiltinRenderDisplayControl('codex', 'command_execution')).toBe('collapsed');});});++describe('getBuiltinRenderDisplayControl', () => {+ it('routes a package with a dynamic resolver through it, forwarding pluginState', () => {+ expect(+ getBuiltinRenderDisplayControl('claude-code', 'Read', {+ images: [{ mediaType: 'image/png', url: 'https://cdn/a.png' }],+ }),+ ).toBe('expand');+ });++ it('leaves a non-image Read undecided, so the caller falls back to collapsed', () => {+ expect(getBuiltinRenderDisplayControl('claude-code', 'Read')).toBeUndefined();+ expect(getBuiltinRenderDisplayControl('claude-code', 'Read', {})).toBeUndefined();+ });++ it('returns undefined without an identifier or apiName', () => {+ expect(getBuiltinRenderDisplayControl(undefined, 'Read')).toBeUndefined();+ expect(getBuiltinRenderDisplayControl('claude-code', undefined)).toBeUndefined();+ });+});diff --git a/packages/builtin-tools/src/displayControls.ts b/packages/builtin-tools/src/displayControls.tsindex 78ff93eab02..7bec5549d88 100644--- a/packages/builtin-tools/src/displayControls.ts+++ b/packages/builtin-tools/src/displayControls.ts@@ -1,6 +1,6 @@import {ClaudeCodeIdentifier,- ClaudeCodeRenderDisplayControls,+ resolveClaudeCodeRenderDisplayControl,} from '@lobechat/builtin-tool-claude-code/client';import { type RenderDisplayControl } from '@lobechat/types';@@ -14,15 +14,32 @@ const getBuiltinRenderDisplayControls = (): Record<Record<string, RenderDisplayControl>> => {return {- [ClaudeCodeIdentifier]: ClaudeCodeRenderDisplayControls,codex: CodexRenderDisplayControls,};};+/**+ * Packages whose display control can't be decided from `apiName` alone β the+ * same API renders differently depending on what its result carries.+ */+const getDynamicRenderDisplayControlResolvers = (): Record<+ string,+ (apiName: string, pluginState?: unknown) => RenderDisplayControl | undefined+> => {+ return {+ [ClaudeCodeIdentifier]: resolveClaudeCodeRenderDisplayControl,+ };+};+export const getBuiltinRenderDisplayControl = (identifier?: string,apiName?: string,+ pluginState?: unknown,): RenderDisplayControl | undefined => {if (!identifier || !apiName) return undefined;++ const resolve = getDynamicRenderDisplayControlResolvers()[identifier];+ if (resolve) return resolve(apiName, pluginState);+return getBuiltinRenderDisplayControls()[identifier]?.[apiName];};diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex dea21cbeb3a..e37ed7a636d 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -6,7 +6,7 @@ import type {} from '@anthropic-ai/claude-agent-sdk';import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';-import { AgentStreamPipeline } from './agentStreamPipeline';+import { AgentStreamPipeline, type UploadHeterogeneousImage } from './agentStreamPipeline';const CLAUDE_SDK_DISALLOWED_TOOLS = ['AskUserQuestion', 'Monitor', 'ScheduleWakeup'] as const;const DEFAULT_INACTIVITY_TIMEOUT_MS = 5 * 60 * 1000;@@ -134,6 +134,8 @@ export interface ClaudeAgentSdkSessionOptions {resumeSessionId?: string;sessionId: string;stdinPayload: string;+ /** Uploader for base64 tool_result images; see `AgentStreamPipelineOptions`. */+ uploadImage?: UploadHeterogeneousImage;}export class ClaudeAgentSdkSession {@@ -154,6 +156,7 @@ export class ClaudeAgentSdkSession {agentType: 'claude-code-sdk',cwd: options.cwd,operationId: options.operationId,+ uploadImage: options.uploadImage,});}diff --git a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.tsnew file mode 100644index 00000000000..e52c4dcdbbe--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.test.ts@@ -0,0 +1,102 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createFileStoreImageUploader, type FileStorePort } from './fileStoreImageUploader';++// sha256 of the bytes behind `PNG_BASE64`, i.e. what the port sees as `hash`.+const PNG_BASE64 = Buffer.from('fake-png-bytes').toString('base64');+const PNG_HASH = '3c6ed5fc41c950bf0db531eb22f945467fb8d999f80d82ba27dcc9fd90add54d';++const createPort = (overrides: Partial<FileStorePort> = {}): FileStorePort => ({+ checkFileHash: vi.fn().mockResolvedValue({ isExist: false }),+ createFile: vi.fn().mockResolvedValue({ id: 'file_1', url: 'https://cdn/x.png' }),+ createS3PreSignedUrl: vi.fn().mockResolvedValue('https://s3/presigned'),+ ...overrides,+});++describe('createFileStoreImageUploader', () => {+ beforeEach(() => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200, statusText: 'OK' }));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('uploads the bytes to S3 and returns the created file reference', async () => {+ const port = createPort();+ const upload = createFileStoreImageUploader(async () => port);++ const result = await upload({ data: PNG_BASE64, mediaType: 'image/png' });++ expect(result).toEqual({ fileId: 'file_1', url: 'https://cdn/x.png' });++ // The bytes are PUT to the pre-signed URL with the image's own media type.+ expect(fetch).toHaveBeenCalledWith('https://s3/presigned', {+ body: Buffer.from(PNG_BASE64, 'base64'),+ headers: { 'Content-Type': 'image/png' },+ method: 'PUT',+ });++ const createFileInput = vi.mocked(port.createFile).mock.calls[0][0];+ expect(createFileInput).toMatchObject({+ fileType: 'image/png',+ name: 'cc-read-image.png',+ size: Buffer.from(PNG_BASE64, 'base64').length,+ });+ // `url` is the S3 pathname, not the pre-signed URL.+ expect(createFileInput.url).toMatch(/^files\/\d{4}-\d{2}-\d{2}\/[a-f0-9]{64}\.png$/);+ });++ it('reuses the stored object and skips the S3 PUT when the hash already exists', async () => {+ const port = createPort({+ checkFileHash: vi.fn().mockResolvedValue({ isExist: true, url: 'files/old/abc.png' }),+ });+ const upload = createFileStoreImageUploader(async () => port);++ await upload({ data: PNG_BASE64, mediaType: 'image/png' });++ expect(port.createS3PreSignedUrl).not.toHaveBeenCalled();+ expect(fetch).not.toHaveBeenCalled();+ expect(vi.mocked(port.createFile).mock.calls[0][0].url).toBe('files/old/abc.png');+ });++ it('hashes the decoded bytes so identical images dedup across runs', async () => {+ const port = createPort();+ const upload = createFileStoreImageUploader(async () => port);++ await upload({ data: PNG_BASE64, mediaType: 'image/png' });++ expect(port.checkFileHash).toHaveBeenCalledWith({ hash: PNG_HASH });+ expect(vi.mocked(port.createFile).mock.calls[0][0].hash).toBe(PNG_HASH);+ });++ it('falls back to a png extension for an unknown media type', async () => {+ const port = createPort();+ const upload = createFileStoreImageUploader(async () => port);++ await upload({ data: PNG_BASE64, mediaType: 'image/avif' });++ expect(vi.mocked(port.createFile).mock.calls[0][0].name).toBe('cc-read-image.png');+ });++ it('returns undefined when no file store is available, so the placeholder survives', async () => {+ const upload = createFileStoreImageUploader(async () => undefined);++ await expect(upload({ data: PNG_BASE64, mediaType: 'image/png' })).resolves.toBeUndefined();+ expect(fetch).not.toHaveBeenCalled();+ });++ it('throws when the S3 PUT fails, letting the pipeline degrade to the placeholder', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({ ok: false, status: 403, statusText: 'Forbidden' }),+ );+ const port = createPort();+ const upload = createFileStoreImageUploader(async () => port);++ await expect(upload({ data: PNG_BASE64, mediaType: 'image/png' })).rejects.toThrow(+ 'Upload failed: 403 Forbidden',+ );+ expect(port.createFile).not.toHaveBeenCalled();+ });+});diff --git a/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.tsnew file mode 100644index 00000000000..26db3667d71--- /dev/null+++ b/packages/heterogeneous-agents/src/spawn/fileStoreImageUploader.ts@@ -0,0 +1,86 @@+import crypto from 'node:crypto';++import type { UploadHeterogeneousImage } from './agentStreamPipeline';++/** Extension seed for an uploaded tool_result image, by IANA media type. */+const IMAGE_EXT_BY_MEDIA_TYPE: Record<string, string> = {+ 'image/gif': 'gif',+ 'image/jpeg': 'jpg',+ 'image/png': 'png',+ 'image/webp': 'webp',+};++export interface FileStoreCreateFileInput {+ fileType: string;+ hash: string;+ metadata: { date: string; dirname: string; filename: string; path: string };+ name: string;+ size: number;+ url: string;+}++/**+ * The three LobeHub file-store procedures the image echo needs, decoupled from+ * how a runtime reaches them: `lh hetero exec` calls them through its typed+ * tRPC client, Electron main through a hand-rolled authed fetch. Only the+ * runtime that spawned the CLI holds those credentials.+ */+export interface FileStorePort {+ checkFileHash: (input: { hash: string }) => Promise<{ isExist?: boolean; url?: string }>;+ createFile: (input: FileStoreCreateFileInput) => Promise<{ id: string; url: string }>;+ createS3PreSignedUrl: (input: { pathname: string }) => Promise<string | { url: string }>;+}++/**+ * Build the {@link UploadHeterogeneousImage} hook `AgentStreamPipeline` calls+ * for each base64 image a tool_result echoes (CC `Read` on an image file).+ *+ * `resolvePort` returning `undefined` means the runtime has no file store to+ * upload into (e.g. a desktop that was never signed in to a remote server);+ * the pipeline then drops the image and keeps the `[Image: β¦]` placeholder.+ */+export const createFileStoreImageUploader =+ (resolvePort: () => Promise<FileStorePort | undefined>): UploadHeterogeneousImage =>+ async ({ data, mediaType }) => {+ const port = await resolvePort();+ if (!port) return undefined;++ const buffer = Buffer.from(data, 'base64');+ const hash = crypto.createHash('sha256').update(buffer).digest('hex');+ const ext = IMAGE_EXT_BY_MEDIA_TYPE[mediaType] ?? 'png';+ const fileName = `cc-read-image.${ext}`;+ const date = new Date().toLocaleDateString('en-CA'); // YYYY-MM-DD++ // Dedup: if the same bytes are already stored (and the object still+ // exists), skip the S3 upload entirely and reuse the existing pathname.+ const existing = await port.checkFileHash({ hash });++ let pathname: string;+ if (existing?.isExist && existing.url) {+ pathname = existing.url;+ } else {+ pathname = `files/${date}/${hash}.${ext}`;+ const presigned = await port.createS3PreSignedUrl({ pathname });+ const presignedUrl = typeof presigned === 'string' ? presigned : presigned.url;++ const uploadRes = await fetch(presignedUrl, {+ body: buffer,+ headers: { 'Content-Type': mediaType },+ method: 'PUT',+ });+ if (!uploadRes.ok) {+ throw new Error(`Upload failed: ${uploadRes.status} ${uploadRes.statusText}`);+ }+ }++ const record = await port.createFile({+ fileType: mediaType,+ hash,+ metadata: { date, dirname: '', filename: fileName, path: pathname },+ name: fileName,+ size: buffer.length,+ url: pathname,+ });++ return { fileId: record.id, url: record.url };+ };diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.tsindex ad6c509a9ce..c3c85415157 100644--- a/packages/heterogeneous-agents/src/spawn/index.ts+++ b/packages/heterogeneous-agents/src/spawn/index.ts@@ -38,6 +38,11 @@ export {readCodexSessionModel,resolveCodexInitialModel,} from './codexModel';+export {+ createFileStoreImageUploader,+ type FileStoreCreateFileInput,+ type FileStorePort,+} from './fileStoreImageUploader';export {type AgentContentBlock,type AgentImageBlock,diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsxindex 28f990951ea..7fdbb1672a0 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx@@ -48,9 +48,11 @@ const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) =const type = tool?.type;const toolMessageId = tool?.result_msg_id;- // Get renderDisplayControl from manifest+ // Get renderDisplayControl from manifest. `result.state` lets an API whose+ // output shape varies by target refine it β CC `Read` expands once the result+ // turns out to be an image, and stays collapsed for source text.const renderDisplayControl = useToolStore(- toolSelectors.getRenderDisplayControl(identifier, apiName),+ toolSelectors.getRenderDisplayControl(identifier, apiName, result?.state),);const [showDebug, setShowDebug] = useState(false);const [showToolRender, setShowToolRender] = useState(false);diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.tsindex 47c89c0b6f3..b3eb3b31a09 100644--- a/src/store/tool/selectors/tool.ts+++ b/src/store/tool/selectors/tool.ts@@ -89,10 +89,14 @@ const isToolHasUI = (id: string) => (s: ToolStoreState) => {* Only works for builtin tools, plugins don't support this feature yet* @param identifier - Tool identifier* @param apiName - API name+ * @param pluginState - The tool_result's plugin state, for APIs whose display+ * control depends on what the result carries (e.g. CC `Read` renders a+ * thumbnail for an image and source text for anything else). Undefined while+ * the call is still in flight.* @returns RenderDisplayControl value, defaults to 'collapsed'*/const getRenderDisplayControl =- (identifier: string, apiName: string) =>+ (identifier: string, apiName: string, pluginState?: unknown) =>(s: ToolStoreState): RenderDisplayControl => {const builtinTool = s.builtinTools.find((t) => t.identifier === identifier);const manifestControl = builtinTool?.manifest.api.find(@@ -102,7 +106,7 @@ const getRenderDisplayControl =// Fallback for packages that don't ship a LobeChat manifest (e.g. Claude Code β// its tools come from Anthropic tool_use blocks at runtime).- return getBuiltinRenderDisplayControl(identifier, apiName) ?? 'collapsed';+ return getBuiltinRenderDisplayControl(identifier, apiName, pluginState) ?? 'collapsed';};export interface AvailableToolForDiscovery {