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: recover Codex generated image outputs (#20521)

Arvin Xu47401ba1457b
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
index bc708bdf225..404c56dcef4 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -3224,8 +3224,10 @@ export default class HeterogeneousAgentCtr {
const pipeline = new AgentStreamPipeline({
agentType: session.agentType,
cwd,
+ env: spawnEnv,
initialCumulativeUsage,
initialModel: session.model,
+ startedAt: startedAt ? Date.parse(startedAt) : undefined,
operationId: params.operationId,
uploadImage: this.uploadResultImage,
});
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 91a375f4274..510b5987d7e 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -5119,6 +5119,87 @@ describe('HeterogeneousAgentCtr', () => {
mockGetAllWindows.mockReturnValue([]);
});
+ it.each(['uploaded', 'failed'])(
+ 'recovers desktop Codex images from the spawned profile (%s)',
+ async (mode) => {
+ const startedAt = Date.now();
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(startedAt);
+ const codexHome = path.join(appStoragePath, 'isolated-codex');
+ const dir = path.join(codexHome, 'sessions', '2026', '10', '08');
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, 'rollout-desktop-images.jsonl'),
+ [
+ {
+ timestamp: new Date(startedAt + 1000).toISOString(),
+ type: 'event_msg',
+ payload: { type: 'task_started' },
+ },
+ {
+ type: 'response_item',
+ payload: {
+ type: 'custom_tool_call_output',
+ call_id: 'dog-image',
+ output: [{ type: 'input_image', image_url: 'data:image/png;base64,AAAA' }],
+ },
+ },
+ ]
+ .map((record) => JSON.stringify(record))
+ .join('\n') + '\n',
+ );
+ // The CLI starts its turn before the pipeline is constructed.
+ onSpawnMock.mockImplementation(() => vi.setSystemTime(startedAt + 5000));
+ nextFakeProc = createFakeProc({
+ stdoutLines: [
+ { type: 'thread.started', thread_id: 'desktop-images' },
+ { type: 'turn.started' },
+ { type: 'item.completed', item: { id: 'reply', type: 'agent_message', text: 'Done.' } },
+ { type: 'turn.completed' },
+ ].map((record) => JSON.stringify(record) + '\n'),
+ }).proc;
+ const ctr = new HeterogeneousAgentCtr({
+ appStoragePath,
+ storeManager: { get: vi.fn() },
+ } as any);
+ const upload = vi.fn(async () => {
+ if (mode === 'failed') throw new Error('Upload rejected');
+ return { fileId: 'file-dog', url: 'https://cdn/dog.png' };
+ });
+ Object.assign(ctr, { uploadResultImage: upload });
+ try {
+ const { sessionId } = await ctr.startSession({
+ agentType: 'codex',
+ command: 'codex',
+ env: { CODEX_HOME: codexHome },
+ });
+ await ctr.sendPrompt({
+ operationId: 'op-desktop-images',
+ prompt: 'draw a dog',
+ sessionId,
+ });
+ const events = broadcasts
+ .filter((b) => b.channel === 'heteroAgentEvent')
+ .map((b) => b.data.event);
+ const results = events.filter((event) => event.type === 'tool_result');
+ expect(results).toHaveLength(1);
+ expect(results[0].data).toMatchObject({
+ toolCallId: 'dog-image',
+ content:
+ mode === 'uploaded' ? '![image/png](https://cdn/dog.png)' : '[Image: image/png]',
+ });
+ expect(upload).toHaveBeenCalledOnce();
+ expect(JSON.stringify(events)).not.toContain('AAAA');
+ expect(
+ events.some((event) => event.type === 'stream_chunk' && event.data.content === 'Done.'),
+ ).toBe(true);
+ } finally {
+ onSpawnMock.mockReset();
+ vi.useRealTimers();
+ }
+ },
+ );
+
it('delivers pipeline.flush() events BEFORE heteroAgentSessionComplete even when proc exit precedes stdout end', async () => {
// Codex `item.started` for a tool — adapter buffers it as a pending
// tool call. On flush, adapter synthesizes a trailing `tool_end`. This
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 47e4ffc2872..7a8b1669d5e 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -39,6 +39,7 @@
"builtins.codex.apiName.collab_tool_call": "Coordinate subagents",
"builtins.codex.apiName.command_execution": "Run command",
"builtins.codex.apiName.file_change": "Edit files",
+ "builtins.codex.apiName.image_output": "Image result",
"builtins.codex.apiName.mcp_tool_call": "Call MCP tool",
"builtins.codex.apiName.todo_list": "Update tasks",
"builtins.codex.apiName.web_search": "Search the web",
@@ -64,6 +65,7 @@
"builtins.codex.fileChange.editing": "Editing files",
"builtins.codex.fileChange.noChanges": "No file changes",
"builtins.codex.fileChange.unknownFile": "Unknown file",
+ "builtins.codex.imageOutput.unavailable": "The image could not be uploaded.",
"builtins.codex.mcpTool.error": "Error",
"builtins.codex.mcpTool.input": "Input",
"builtins.codex.mcpTool.result": "Result",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 72f830bcc96..8224ced52ce 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -39,6 +39,7 @@
"builtins.codex.apiName.collab_tool_call": "协调子代理",
"builtins.codex.apiName.command_execution": "运行命令",
"builtins.codex.apiName.file_change": "编辑文件",
+ "builtins.codex.apiName.image_output": "图片结果",
"builtins.codex.apiName.mcp_tool_call": "调用 MCP 工具",
"builtins.codex.apiName.todo_list": "更新任务",
"builtins.codex.apiName.web_search": "搜索网页",
@@ -64,6 +65,7 @@
"builtins.codex.fileChange.editing": "编辑文件中",
"builtins.codex.fileChange.noChanges": "没有文件改动",
"builtins.codex.fileChange.unknownFile": "未知文件",
+ "builtins.codex.imageOutput.unavailable": "图片上传失败。",
"builtins.codex.mcpTool.error": "错误",
"builtins.codex.mcpTool.input": "输入",
"builtins.codex.mcpTool.result": "结果",
diff --git a/package.json b/package.json
index e89c515d6ac..d3f05a066d6 100644
--- a/package.json
+++ b/package.json
@@ -416,7 +416,7 @@
"model-bank": "workspace:*",
"motion": "^12.43.0",
"nanoid": "^5.1.16",
- "next": "^16.3.0",
+ "next": "~16.3.8",
"next-mdx-remote": "^6.0.0",
"next-themes": "^0.4.6",
"nextjs-toploader": "^3.9.17",
diff --git a/packages/builtin-tools/src/codex/ImageOutputInspector.tsx b/packages/builtin-tools/src/codex/ImageOutputInspector.tsx
new file mode 100644
index 00000000000..13a400730fc
--- /dev/null
+++ b/packages/builtin-tools/src/codex/ImageOutputInspector.tsx
@@ -0,0 +1,11 @@
+'use client';
+
+import { inspectorTextStyles } from '@lobechat/shared-tool-ui/styles';
+import { useTranslation } from 'react-i18next';
+
+export const ImageOutputInspector = () => {
+ const { t } = useTranslation('plugin');
+ return (
+ <span className={inspectorTextStyles.root}>{t('builtins.codex.apiName.image_output')}</span>
+ );
+};
diff --git a/packages/builtin-tools/src/codex/ImageOutputRender.tsx b/packages/builtin-tools/src/codex/ImageOutputRender.tsx
new file mode 100644
index 00000000000..193c196aac8
--- /dev/null
+++ b/packages/builtin-tools/src/codex/ImageOutputRender.tsx
@@ -0,0 +1,34 @@
+'use client';
+
+import type { BuiltinRenderProps } from '@lobechat/types';
+import { Flexbox, Image, PreviewGroup } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+
+interface ImageOutputState {
+ images?: Array<{ fileId?: string; url?: string }>;
+}
+
+export const ImageOutputRender = ({
+ pluginState,
+}: BuiltinRenderProps<unknown, ImageOutputState>) => {
+ const { t } = useTranslation('plugin');
+ const images = pluginState?.images?.filter(({ url }) => !!url) ?? [];
+ if (images.length === 0) return <Text>{t('builtins.codex.imageOutput.unavailable')}</Text>;
+
+ return (
+ <PreviewGroup>
+ <Flexbox gap={8}>
+ {images.map((image, index) => (
+ <Image
+ alt={t('builtins.codex.apiName.image_output')}
+ key={image.fileId || image.url || index}
+ maxHeight={600}
+ src={image.url}
+ style={{ alignSelf: 'flex-start', maxWidth: '100%' }}
+ />
+ ))}
+ </Flexbox>
+ </PreviewGroup>
+ );
+};
diff --git a/packages/builtin-tools/src/codex/displayControls.ts b/packages/builtin-tools/src/codex/displayControls.ts
index e96ebeb8c71..5c653216cb6 100644
--- a/packages/builtin-tools/src/codex/displayControls.ts
+++ b/packages/builtin-tools/src/codex/displayControls.ts
@@ -4,6 +4,7 @@ export const CodexRenderDisplayControls: Record<string, RenderDisplayControl> =
collab_tool_call: 'expand',
command_execution: 'collapsed',
file_change: 'collapsed',
+ image_output: 'expand',
mcp_tool_call: 'collapsed',
todo_list: 'expand',
web_search: 'collapsed',
diff --git a/packages/builtin-tools/src/codex/index.ts b/packages/builtin-tools/src/codex/index.ts
index 1328871907e..d1e3aac26be 100644
--- a/packages/builtin-tools/src/codex/index.ts
+++ b/packages/builtin-tools/src/codex/index.ts
@@ -7,6 +7,8 @@ import { CodexRenderDisplayControls } from './displayControls';
import ErrorInspector from './ErrorInspector';
import FileChangeInspector from './FileChangeInspector';
import FileChangeRender from './FileChangeRender';
+import { ImageOutputInspector } from './ImageOutputInspector';
+import { ImageOutputRender } from './ImageOutputRender';
import McpToolInspector from './McpToolInspector';
import McpToolRender from './McpToolRender';
import TodoListInspector from './TodoListInspector';
@@ -19,6 +21,7 @@ export const CodexInspectors: Record<string, BuiltinInspector> = {
command_execution: CommandExecutionInspector as BuiltinInspector,
error: ErrorInspector as BuiltinInspector,
file_change: FileChangeInspector as BuiltinInspector,
+ image_output: ImageOutputInspector as BuiltinInspector,
mcp_tool_call: McpToolInspector as BuiltinInspector,
todo_list: TodoListInspector as BuiltinInspector,
web_search: WebSearchInspector as BuiltinInspector,
@@ -27,6 +30,7 @@ export const CodexInspectors: Record<string, BuiltinInspector> = {
export const CodexRenders: Record<string, BuiltinRender> = {
collab_tool_call: CollabToolRender as BuiltinRender,
file_change: FileChangeRender as BuiltinRender,
+ image_output: ImageOutputRender as BuiltinRender,
mcp_tool_call: McpToolRender as BuiltinRender,
todo_list: TodoListRender as BuiltinRender,
web_search: WebSearchRender as BuiltinRender,
diff --git a/packages/builtin-tools/src/displayControls.test.ts b/packages/builtin-tools/src/displayControls.test.ts
index a9673d3b2cd..6c927805cb0 100644
--- a/packages/builtin-tools/src/displayControls.test.ts
+++ b/packages/builtin-tools/src/displayControls.test.ts
@@ -13,6 +13,10 @@ vi.mock('@lobechat/builtin-tool-claude-code/client', () => ({
}));
describe('CodexRenderDisplayControls', () => {
+ it('expands Codex image results so users see generated images immediately', () => {
+ expect(getBuiltinRenderDisplayControl('codex', 'image_output')).toBe('expand');
+ });
+
it('collapses Codex command output by default', () => {
expect(CodexRenderDisplayControls.command_execution).toBe('collapsed');
expect(getBuiltinRenderDisplayControl('codex', 'command_execution')).toBe('collapsed');
diff --git a/packages/heterogeneous-agents/src/adapters/codex.ts b/packages/heterogeneous-agents/src/adapters/codex.ts
index fae4198940b..3ecd03ad80d 100644
--- a/packages/heterogeneous-agents/src/adapters/codex.ts
+++ b/packages/heterogeneous-agents/src/adapters/codex.ts
@@ -1,8 +1,10 @@
+import { imagePlaceholder } from '../imageEcho';
import type {
AgentEventAdapter,
HeterogeneousAgentEvent,
HeterogeneousRateLimitInfo,
HeterogeneousTerminalErrorData,
+ HeterogeneousToolResultImage,
StepCompleteData,
StreamStartData,
ToolCallPayload,
@@ -47,6 +49,12 @@ interface CodexCommandExecutionItem extends CodexBaseItem {
exit_code?: number | null;
}
+/** Image tool outputs omitted by exec --json and recovered from its rollout. */
+export interface CodexImageOutputItem extends CodexBaseItem {
+ images: HeterogeneousToolResultImage[];
+ type: 'image_output';
+}
+
interface CodexTodoListEntry {
completed?: boolean;
text?: string;
@@ -113,6 +121,7 @@ type CodexToolItem =
| CodexCollabToolCallItem
| CodexCommandExecutionItem
| CodexFileChangeItem
+ | CodexImageOutputItem
| CodexMcpToolCallItem
| CodexTodoListItem
| CodexWebSearchItem;
@@ -126,6 +135,9 @@ interface ZonedDateTimeParts {
year: number;
}
+const isImageOutputItem = (item: CodexToolItem): item is CodexImageOutputItem =>
+ item.type === 'image_output';
+
const isCommandExecutionItem = (item: CodexToolItem): item is CodexCommandExecutionItem =>
item.type === CODEX_COMMAND_API;
@@ -343,11 +355,13 @@ const toMcpToolPayloadArguments = (item: CodexMcpToolCallItem) => ({
const toToolPayload = (item: CodexToolItem): ToolCallPayload => ({
apiName: item.type || CODEX_COMMAND_API,
arguments: JSON.stringify(
- isCommandExecutionItem(item)
- ? { command: item.command || '' }
- : isMcpToolCallItem(item)
- ? toMcpToolPayloadArguments(item)
- : item,
+ isImageOutputItem(item)
+ ? {}
+ : isCommandExecutionItem(item)
+ ? { command: item.command || '' }
+ : isMcpToolCallItem(item)
+ ? toMcpToolPayloadArguments(item)
+ : item,
),
id: item.id,
identifier: CODEX_IDENTIFIER,
@@ -474,6 +488,15 @@ const isSuccessfulToolCompletion = (item: CodexToolItem): boolean => {
};
const getToolResultData = (item: CodexToolItem): ToolResultData => {
+ if (isImageOutputItem(item)) {
+ return {
+ content: item.images.map(({ mediaType }) => imagePlaceholder(mediaType)).join('\n\n'),
+ isError: false,
+ pluginState: { images: item.images },
+ toolCallId: item.id,
+ };
+ }
+
const isSuccess = isSuccessfulToolCompletion(item);
const output = getToolContent(item, isSuccess);
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
index 7859838d14b..510c3c9b3e3 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.test.ts
@@ -63,6 +63,81 @@ describe('AgentStreamPipeline', () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
});
+ it.each(['uploaded', 'unavailable', 'failed'])(
+ 'recovers only the current rollout images before stream end (%s)',
+ async (upload) => {
+ const codexHome = await mkdtemp(path.join(os.tmpdir(), 'codex-images-'));
+ tempDirs.push(codexHome);
+ const sessionDir = path.join(codexHome, 'sessions', '2026', '10', '08');
+ await mkdir(sessionDir, { recursive: true });
+ const oldTimestamp = new Date(Date.now() - 60_000).toISOString();
+ const pipeline = new AgentStreamPipeline({
+ agentType: 'codex',
+ env: { CODEX_HOME: codexHome },
+ operationId: 'op-images',
+ uploadImage:
+ upload === 'unavailable'
+ ? undefined
+ : async () => {
+ if (upload === 'failed') throw new Error('Upload failed');
+ return { fileId: 'file-dog', url: 'https://cdn/dog.png' };
+ },
+ });
+ const timestamp = new Date().toISOString();
+ const record = (type: string, payload: unknown, at = timestamp) =>
+ JSON.stringify({ payload, timestamp: at, type });
+ const output = (callId: string) => ({
+ call_id: callId,
+ output: [
+ { text: 'Script completed', type: 'input_text' },
+ { image_url: 'data:image/png;base64,AAAA', type: 'input_image' },
+ ],
+ type: 'custom_tool_call_output',
+ });
+ await writeFile(
+ path.join(sessionDir, 'rollout-thread-images.jsonl'),
+ [
+ record('event_msg', { type: 'task_started' }, oldTimestamp),
+ record('response_item', output('old-image'), oldTimestamp),
+ record('event_msg', { type: 'task_started' }),
+ record('response_item', {
+ call_id: 'dog-image',
+ input: 'generate a dog',
+ name: 'exec',
+ type: 'custom_tool_call',
+ }),
+ record('response_item', output('dog-image')),
+ ].join('\n') + '\n',
+ );
+ const events = await pipeline.push(
+ [
+ { thread_id: 'thread-images', type: 'thread.started' },
+ { type: 'turn.started' },
+ { item: { id: 'reply', text: 'Done.', type: 'agent_message' }, type: 'item.completed' },
+ { type: 'turn.completed' },
+ ]
+ .map((event) => JSON.stringify(event))
+ .join('\n') + '\n',
+ );
+ const result = events.find(({ type }) => type === 'tool_result');
+ expect(result?.data).toMatchObject({
+ content: upload === 'uploaded' ? '![image/png](https://cdn/dog.png)' : '[Image: image/png]',
+ toolCallId: 'dog-image',
+ });
+ expect(result?.data.pluginState.images).toEqual(
+ upload === 'uploaded'
+ ? [{ fileId: 'file-dog', mediaType: 'image/png', url: 'https://cdn/dog.png' }]
+ : undefined,
+ );
+ expect(events.filter(({ type }) => type === 'tool_result')).toHaveLength(1);
+ expect(events.findIndex(({ type }) => type === 'tool_result')).toBeLessThan(
+ events.findIndex(({ data, type }) => type === 'stream_chunk' && data.chunkType === 'text'),
+ );
+ expect(JSON.stringify(events)).not.toContain('AAAA');
+ expect((await pipeline.flush()).some(({ type }) => type === 'tool_result')).toBe(false);
+ },
+ );
+
it('runs JSONL → adapter → toStreamEvent and stamps operationId', async () => {
const pipeline = new AgentStreamPipeline({
agentType: 'claude-code',
diff --git a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
index 1a6a6344fa5..8443f491865 100644
--- a/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
+++ b/packages/heterogeneous-agents/src/spawn/agentStreamPipeline.ts
@@ -10,6 +10,7 @@ import type {
UsageData,
} from '../types';
import { CodexFileChangeTracker } from './codexFileChangeTracker';
+import { createCodexImageOutputReader } from './codexImageOutputs';
import { JsonlStreamProcessor } from './jsonlProcessor';
import { readPostRunUsage } from './postRunUsage';
import { toStreamEvent } from './streamEvent';
@@ -32,12 +33,16 @@ export interface AgentStreamPipelineOptions {
agentType: string;
/** Working directory used to resolve relative file paths emitted by CLI tools. */
cwd?: string;
+ /** Environment of the spawned CLI, including its CODEX_HOME. */
+ env?: Record<string, string | undefined>;
/** Last known Codex cumulative usage before a resumed turn starts. */
initialCumulativeUsage?: UsageData | undefined;
/** Host-known model to emit before the CLI's first stdout payload. */
initialModel?: string | undefined;
/** Operation id to stamp onto every emitted `AgentStreamEvent`. */
operationId: string;
+ /** Invocation start, recorded before spawning the CLI. */
+ startedAt?: number;
/**
* Uploader for tool_result images. When omitted, `pluginState.images` base64
* entries are dropped (the `[Image: …]` content placeholder is the fallback)
@@ -65,11 +70,17 @@ export class AgentStreamPipeline {
private readonly operationId: string;
private readonly codexTracker?: CodexFileChangeTracker;
private readonly uploadImage?: UploadHeterogeneousImage;
+ private readonly readCodexImages: ReturnType<typeof createCodexImageOutputReader>;
+ private recoveredCodexImageCallIds = new Set<string>();
private queuedEvents: AgentStreamEvent[] = [];
constructor(options: AgentStreamPipelineOptions) {
this.adapter = createAdapter(options.agentType);
this.agentType = options.agentType;
+ this.readCodexImages = createCodexImageOutputReader({
+ env: options.env ?? process.env,
+ startedAt: options.startedAt ?? Date.now(),
+ });
this.operationId = options.operationId;
this.uploadImage = options.uploadImage;
this.codexTracker =
@@ -105,7 +116,8 @@ export class AgentStreamPipeline {
*/
async flush(): Promise<AgentStreamEvent[]> {
const trailing = await this.processPayloads(this.processor.flush());
- const flushedEvents = this.adapter.flush();
+ const recovered = await this.recoverCodexImages();
+ const flushedEvents = [...recovered, ...this.adapter.flush()];
await this.uploadResultImages(flushedEvents);
const flushed = flushedEvents.map((event) => toStreamEvent(event, this.operationId));
return [...trailing, ...flushed];
@@ -164,7 +176,13 @@ export class AgentStreamPipeline {
for (const raw of payloads) {
const payload = this.codexTracker ? await this.codexTracker.track(raw as any) : raw;
- const events = this.adapter.adapt(payload);
+ const rawEvent = payload as { item?: { type?: string }; type?: string };
+ const recoverImages =
+ rawEvent?.type === 'turn.completed' ||
+ rawEvent?.type === 'turn.failed' ||
+ (rawEvent?.type === 'item.completed' && rawEvent.item?.type === 'agent_message');
+ const recovered = recoverImages ? await this.recoverCodexImages() : [];
+ const events = [...recovered, ...this.adapter.adapt(payload)];
await this.uploadResultImages(events);
out.push(...this.toStreamEvents(events));
}
@@ -172,6 +190,21 @@ export class AgentStreamPipeline {
return out;
}
+ private async recoverCodexImages(): Promise<HeterogeneousAgentEvent[]> {
+ if (this.agentType !== 'codex' || !this.adapter.sessionId) return [];
+ try {
+ const items = await this.readCodexImages(this.adapter.sessionId);
+ return items.flatMap((item) => {
+ if (this.recoveredCodexImageCallIds.has(item.id)) return [];
+ this.recoveredCodexImageCallIds.add(item.id);
+ return this.adapter.adapt({ item, type: 'item.completed' });
+ });
+ } catch (error) {
+ console.error('Failed to recover Codex tool images from the session transcript:', error);
+ return [];
+ }
+ }
+
/**
* Rewrite any `tool_result` `pluginState.images` from base64 into uploaded
* `{ fileId, url }` references, mutating the events in place before they are
diff --git a/packages/heterogeneous-agents/src/spawn/codexImageOutputs.test.ts b/packages/heterogeneous-agents/src/spawn/codexImageOutputs.test.ts
new file mode 100644
index 00000000000..a8365ad738d
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/codexImageOutputs.test.ts
@@ -0,0 +1,116 @@
+import * as fs from 'node:fs/promises';
+import { appendFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createCodexImageOutputReader, readCodexImageOutputs } from './codexImageOutputs';
+
+vi.mock('node:fs/promises', { spy: true });
+
+const tempDirs: string[] = [];
+const startedAt = Date.parse('2026-10-08T02:52:15.000Z');
+const record = (payload: unknown, type = 'response_item', timestamp = '2026-10-08T02:52:16.000Z') =>
+ JSON.stringify({ payload, timestamp, type });
+const imageOutput = (callId: string, urls: string[]) => ({
+ call_id: callId,
+ output: urls.map((image_url) => ({ image_url, type: 'input_image' })),
+ type: 'custom_tool_call_output',
+});
+
+const prepare = async (content: string) => {
+ const codexHome = await mkdtemp(path.join(os.tmpdir(), 'codex-image-output-'));
+ tempDirs.push(codexHome);
+ const dir = path.join(codexHome, 'sessions', '2026', '10', '08');
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, 'rollout-thread-1.jsonl'), content);
+ return { env: { CODEX_HOME: codexHome }, startedAt };
+};
+
+describe('readCodexImageOutputs', () => {
+ it('does not rescan or reparse unchanged history, but reads newly appended outputs', async () => {
+ const options = await prepare(record({ type: 'task_started' }, 'event_msg') + '\n');
+ const source = path.join(
+ options.env.CODEX_HOME,
+ 'sessions',
+ '2026',
+ '10',
+ '08',
+ 'rollout-thread-1.jsonl',
+ );
+ const read = createCodexImageOutputReader(options);
+ const readSpy = vi.mocked(fs.readFile).mockClear();
+ const scanSpy = vi.mocked(fs.readdir).mockClear();
+ expect(await read('thread-1')).toEqual([]);
+ const scans = scanSpy.mock.calls.length;
+ expect(await read('thread-1')).toEqual([]);
+ expect(readSpy).toHaveBeenCalledTimes(1);
+ expect(scanSpy).toHaveBeenCalledTimes(scans);
+ await appendFile(
+ source,
+ record(imageOutput('new-image', ['data:image/png;base64,AAAA'])) + '\n',
+ );
+ expect(await read('thread-1')).toMatchObject([{ id: 'new-image' }]);
+ expect(await read('thread-1')).toMatchObject([{ id: 'new-image' }]);
+ expect(readSpy).toHaveBeenCalledTimes(2);
+ expect(scanSpy).toHaveBeenCalledTimes(scans);
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
+ });
+
+ it('keeps image order, ignores non-image URLs and deduplicates echoed outputs', async () => {
+ const output = imageOutput('call-image', [
+ 'data:image/png;base64,AAAA',
+ 'data:image/jpeg;base64,BBBB',
+ 'data:text/plain;base64,CCCC',
+ 'file:///private/image.png',
+ ]);
+ const options = await prepare(
+ [
+ record({ type: 'task_started' }, 'event_msg'),
+ record(output),
+ 'null',
+ record(output),
+ '{truncated',
+ ].join('\n'),
+ );
+ expect(await readCodexImageOutputs('thread-1', options)).toEqual([
+ {
+ id: 'call-image',
+ images: [
+ { data: 'AAAA', mediaType: 'image/png' },
+ { data: 'BBBB', mediaType: 'image/jpeg' },
+ ],
+ status: 'completed',
+ type: 'image_output',
+ },
+ ]);
+ });
+
+ it.each(['2026-10-08T02:50:00.000Z', 'invalid'])(
+ 'does not replay an old or undated turn (%s)',
+ async (timestamp) => {
+ const options = await prepare(
+ [
+ record({ type: 'task_started' }, 'event_msg', timestamp),
+ record(imageOutput('old', ['data:image/png;base64,AAAA'])),
+ ].join('\n'),
+ );
+ expect(await readCodexImageOutputs('thread-1', options)).toEqual([]);
+ },
+ );
+
+ it('does not confuse another session with the requested session', async () => {
+ const options = await prepare(
+ [
+ record({ type: 'task_started' }, 'event_msg'),
+ record(imageOutput('other', ['data:image/png;base64,AAAA'])),
+ ].join('\n'),
+ );
+ expect(await readCodexImageOutputs('thread-missing', options)).toEqual([]);
+ });
+});
diff --git a/packages/heterogeneous-agents/src/spawn/codexImageOutputs.ts b/packages/heterogeneous-agents/src/spawn/codexImageOutputs.ts
new file mode 100644
index 00000000000..2f4cdcaac41
--- /dev/null
+++ b/packages/heterogeneous-agents/src/spawn/codexImageOutputs.ts
@@ -0,0 +1,91 @@
+import { readFile, stat } from 'node:fs/promises';
+
+import { isRecord } from '@lobechat/utils/object';
+
+import type { CodexImageOutputItem } from '../adapters/codex';
+import { parseJsonlRecords } from '../transcript/utils';
+import type { HeterogeneousToolResultImage } from '../types';
+import { getCodexHome, readNewestMatchingSessionFile } from './codexModel';
+
+interface CodexImageOutputOptions {
+ env: Record<string, string | undefined>;
+ startedAt: number;
+}
+
+/** Cache the current invocation's rollout path and unchanged parsed output. */
+export const createCodexImageOutputReader = (options: CodexImageOutputOptions) => {
+ let cached:
+ | {
+ sessionId: string;
+ source: string;
+ mtimeMs?: number;
+ size?: number;
+ outputs?: CodexImageOutputItem[];
+ }
+ | undefined;
+ return async (sessionId: string): Promise<CodexImageOutputItem[]> => {
+ if (cached?.sessionId !== sessionId) {
+ const source = await readNewestMatchingSessionFile(getCodexHome(options.env), sessionId);
+ if (!source) return [];
+ cached = { sessionId, source };
+ }
+ const info = await stat(cached.source);
+ if (cached.outputs && cached.mtimeMs === info.mtimeMs && cached.size === info.size)
+ return cached.outputs;
+ const outputs = await readImageOutputs(cached.source, options.startedAt);
+ Object.assign(cached, { mtimeMs: info.mtimeMs, outputs, size: info.size });
+ return outputs;
+ };
+};
+
+/** Recover only the invocation's latest turn, never historical images on resume. */
+export const readCodexImageOutputs = async (sessionId: string, options: CodexImageOutputOptions) =>
+ createCodexImageOutputReader(options)(sessionId);
+
+const readImageOutputs = async (
+ source: string,
+ startedAt: number,
+): Promise<CodexImageOutputItem[]> => {
+ const records = parseJsonlRecords(await readFile(source, 'utf8'));
+ const turnStart = records.findLastIndex(
+ (record) =>
+ isRecord(record) &&
+ record.type === 'event_msg' &&
+ isRecord(record.payload) &&
+ record.payload.type === 'task_started',
+ );
+ const timestamp = records[turnStart]?.timestamp;
+ const turnStartedAt = typeof timestamp === 'string' ? Date.parse(timestamp) : NaN;
+ if (!Number.isFinite(turnStartedAt) || turnStartedAt < startedAt) return [];
+
+ const outputs = new Map<string, CodexImageOutputItem>();
+ for (const record of records.slice(turnStart + 1)) {
+ if (!isRecord(record)) continue;
+ const payload = record.payload;
+ if (
+ record.type !== 'response_item' ||
+ !isRecord(payload) ||
+ (payload.type !== 'custom_tool_call_output' && payload.type !== 'function_call_output') ||
+ typeof payload.call_id !== 'string' ||
+ !Array.isArray(payload.output)
+ )
+ continue;
+
+ const images: HeterogeneousToolResultImage[] = [];
+ for (const block of payload.output) {
+ if (!isRecord(block) || block.type !== 'input_image' || typeof block.image_url !== 'string')
+ continue;
+ const match = /^data:(image\/[\w.+-]+);base64,([\s\S]+)$/.exec(block.image_url);
+ if (match) images.push({ data: match[2], mediaType: match[1] });
+ }
+ if (images.length > 0) {
+ outputs.set(payload.call_id, {
+ id: payload.call_id,
+ images,
+ status: 'completed',
+ type: 'image_output',
+ });
+ }
+ }
+ return [...outputs.values()];
+};
diff --git a/packages/heterogeneous-agents/src/spawn/codexModel.ts b/packages/heterogeneous-agents/src/spawn/codexModel.ts
index b8dd5849845..a7b240c3fde 100644
--- a/packages/heterogeneous-agents/src/spawn/codexModel.ts
+++ b/packages/heterogeneous-agents/src/spawn/codexModel.ts
@@ -227,7 +227,7 @@ const findCodexSessionFiles = async (root: string, threadId: string): Promise<st
return out;
};
-const readNewestMatchingSessionFile = async (
+export const readNewestMatchingSessionFile = async (
codexHome: string,
threadId: string,
): Promise<string | undefined> => {
diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
index d6b8c073ac4..5309ccc4aaa 100644
--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts
@@ -708,6 +708,7 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
const cliSpawnPlan = await resolveCliSpawnPlan(command, args);
const detached = platform() !== 'win32' && (options.detached ?? true);
+ const startedAt = Date.now();
const proc = spawnManaged(cliSpawnPlan.command, cliSpawnPlan.args, {
cwd,
detached,
@@ -718,9 +719,11 @@ export const spawnAgent = async (options: SpawnAgentOptions): Promise<SpawnAgent
const pipeline = new AgentStreamPipeline({
agentType: options.agentType,
cwd,
+ env: childEnv,
initialCumulativeUsage,
initialModel,
operationId: options.operationId,
+ startedAt,
uploadImage: options.uploadImage,
});
const stdout = proc.stdout!;
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 9d4453b1ca0..5c41c9c8b05 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -160,6 +160,8 @@ export default {
'builtins.codex.apiName.collab_tool_call': 'Coordinate subagents',
'builtins.codex.apiName.command_execution': 'Run command',
'builtins.codex.apiName.file_change': 'Edit files',
+ 'builtins.codex.apiName.image_output': 'Image result',
+ 'builtins.codex.imageOutput.unavailable': 'The image could not be uploaded.',
'builtins.codex.apiName.mcp_tool_call': 'Call MCP tool',
'builtins.codex.apiName.todo_list': 'Update tasks',
'builtins.codex.apiName.web_search': 'Search the web',
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
index a2fb4e6158f..6fb1ad71b92 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts
@@ -54,6 +54,34 @@ describe('hasRenderableFinalAnswer', () => {
});
describe('shouldFoldProcess', () => {
+ it.each([undefined, { images: [{ url: 'https://x/image.png' }] }])(
+ 'keeps Codex image outputs visible, including upload failures',
+ (state) => {
+ const output = {
+ id: 'image',
+ apiName: 'image_output',
+ identifier: 'codex',
+ result: { state },
+ };
+ expect(
+ shouldFoldProcess({
+ enabled: true,
+ hasFinalAnswer: true,
+ isGenerating: false,
+ isLatestItem: true,
+ operationEnded: true,
+ processSegments: [
+ w('commands', 2),
+ {
+ kind: 'workflow',
+ blocks: [{ id: 'image', tools: [output] } as any],
+ standalone: true,
+ },
+ ],
+ }),
+ ).toBe(false);
+ },
+ );
const proc = [w('t1')];
it('folds a finished, non-latest turn that has a workflow when enabled', () => {
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
index b6922eae8e7..f402289304b 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.ts
@@ -2,6 +2,7 @@ import type { AssistantGroupSegment } from '@lobechat/conversation-flow';
import { LOADING_FLAT } from '@/const/message';
+import { isImageBearingTool } from '../toolRenderRules';
import type { RenderableAssistantContentBlock } from './types';
import type { WorkflowExpandLevel, WorkflowExpandLevelDefault } from './WorkflowCollapse';
@@ -65,7 +66,12 @@ export const shouldFoldProcess = ({
operationEnded &&
(!isLatestItem || !!hasFinalAnswer) &&
!isGenerating &&
- processSegments.some((segment) => segment.kind === 'workflow');
+ processSegments.some((segment) => segment.kind === 'workflow') &&
+ !processSegments.some((segment) =>
+ (segment.kind === 'answer' ? [segment.block] : segment.blocks).some((block) =>
+ block.tools?.some(isImageBearingTool),
+ ),
+ );
/**
* Merge the per-surface expand override with the user's streaming preference.
diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts
index 330969814b3..65cdc20828a 100644
--- a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts
+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts
@@ -31,6 +31,9 @@ const hasGeneratedImage = (state: unknown): boolean =>
);
export const isImageBearingTool = (tool: ChatToolPayloadWithResult): boolean => {
+ // Image delivery failures must stay visible alongside successful outputs.
+ if (tool.identifier === 'codex' && tool.apiName === 'image_output') return true;
+
const state = tool.result?.state;
if (!state) return false;