TypeScript
fix: tool screenshots show as images, not base64 text (#16199)
Theo Browne5eb87730871a
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 0f55d36c011..0679d4956f7 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -1933,6 +1933,7 @@ function renderFeedEntry(onToggleRow={props.onToggleWorkRow}renderImage={props.renderViewedImage}renderReasoning={props.renderReasoning}+ onPressPreview={props.onPressPreview}/>);}diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsxindex a67225f1a33..286c6a76267 100644--- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx+++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx@@ -178,7 +178,10 @@ function ThreadMarkdownImageRequest(props: {/** Environment-hosted image that loads through a signed asset URL. */export function ThreadMarkdownImage(props: {readonly environmentId: EnvironmentId;- readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "media-file" }>;+ readonly resource: Extract<+ AssetResource,+ { readonly _tag: "attachment" | "media-file" | "tool-output-image" }+ >;readonly alt: string | null;readonly srcFragment?: string;readonly actionsSource?: MediaActionsSource;@@ -192,7 +195,9 @@ export function ThreadMarkdownImage(props: {sourceKey={props.resource._tag === "attachment"? `attachment:${props.resource.attachmentId}`- : `workspace:${props.resource.path}`+ : props.resource._tag === "tool-output-image"+ ? `tool-output:${props.resource.itemId}:${props.resource.index}`+ : `workspace:${props.resource.path}`}unavailable={assetUrl._tag === "Failure"}knownSize={assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined}diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsxindex 96d275235ea..4a906752951 100644--- a/apps/mobile/src/features/threads/thread-work-log.tsx+++ b/apps/mobile/src/features/threads/thread-work-log.tsx@@ -64,7 +64,11 @@ import {type ThreadFeedActivity,workEntryRowLabel,} from "../../lib/threadActivity";-import { toolCallLines, turnItemOutputText } from "@t3tools/client-runtime/work-log/item-detail";+import {+ toolCallLines,+ turnItemOutputImages,+ turnItemOutputText,+} from "@t3tools/client-runtime/work-log/item-detail";import { useTurnItemDetail } from "../../state/queries";import {resolveThreadWorkGroupInitialScroll,@@ -80,6 +84,8 @@ import {import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";import { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution";import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";+import type { FilePreviewSource } from "../../components/FilePreviewModal";+import { ThreadMarkdownImage } from "./ThreadMarkdownImage";import Animated, {cancelAnimation,Easing,@@ -462,6 +468,7 @@ interface ThreadWorkLogProps {readonly onToggleRow: (rowId: string, anchorKey: string) => void;readonly renderImage: MarkdownImageRenderer;readonly renderReasoning: (text: string) => ReactNode;+ readonly onPressPreview: (source: FilePreviewSource) => void;}export function ThreadWorkLog(props: ThreadWorkLogProps) {@@ -479,6 +486,7 @@ export function ThreadWorkLog(props: ThreadWorkLogProps) {onToggleRow={props.onToggleRow}renderImage={props.renderImage}renderReasoning={props.renderReasoning}+ onPressPreview={props.onPressPreview}themeAppearance={props.themeAppearance}/>),@@ -492,6 +500,7 @@ export function ThreadWorkLog(props: ThreadWorkLogProps) {props.onToggleRow,props.renderImage,props.renderReasoning,+ props.onPressPreview,props.themeAppearance,],);@@ -951,12 +960,13 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(? formatItemFullDetail(row.projectedItem, fetchedItem): row.getFullDetail(): null;+ const outputImages = expanded && fetchedItem ? turnItemOutputImages(fetchedItem) : [];const fetchedOutput = !expanded? null: shownItem.type === "file_search" || shownItem.type === "web_search"? turnItemOutputText(shownItem): fetchedItem- ? (turnItemOutputText(fetchedItem) ?? "No output.")+ ? (turnItemOutputText(fetchedItem) ?? (outputImages.length > 0 ? null : "No output.")): fetchedDetail.error? `Couldn't load output: ${fetchedDetail.error}`: row.fetchesDetail@@ -1116,6 +1126,7 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(call ||fetchedOutput ||viewedImagePath ||+ outputImages.length > 0 ||row.workEntry.questionAnswer) ? (<Animated.Viewentering={WORK_LOG_DETAIL_ENTER_TRANSITION}@@ -1134,6 +1145,16 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow({props.renderImage({ href: viewedImagePath, alt: null, title: null })}</View>) : null}+ {outputImages.map((resource) => (+ <View key={resource.index} className="pb-1.5">+ <ThreadMarkdownImage+ environmentId={props.environmentId}+ resource={resource}+ alt={null}+ onPressPreview={props.onPressPreview}+ />+ </View>+ ))}<ScrollViewnestedScrollEnableddirectionalLockEnableddiff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.tsindex 0907333032d..fd94d4ec9df 100644--- a/apps/server/src/assets/AssetAccess.test.ts+++ b/apps/server/src/assets/AssetAccess.test.ts@@ -3,10 +3,16 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";import * as NodeFSP from "node:fs/promises";import * as NodeOS from "node:os";-import { AssetAccessError, AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";+import {+ AssetAccessError,+ AssetPreviewTypeValidationError,+ ThreadId,+ TurnItemId,+} from "@t3tools/contracts";import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";import { describe, expect, it } from "@effect/vitest";import * as Crypto from "effect/Crypto";+import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";@@ -20,6 +26,7 @@ import { vi } from "vite-plus/test";import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import * as ServerConfig from "../config.ts";+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";@@ -44,8 +51,70 @@ vi.mock("node:os", async (importOriginal) => {const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {prefix: "t3-asset-access-test-",});+// A PNG header is enough for the dimension read: signature, then IHDR width and height.+const screenshotPng = new Uint8Array(24);+screenshotPng.set([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52,+]);+new DataView(screenshotPng.buffer).setUint32(16, 390);+new DataView(screenshotPng.buffer).setUint32(20, 844);+const screenshotItem = {+ id: TurnItemId.make("tool-screenshot"),+ type: "dynamic_tool" as const,+ threadId: ThreadId.make("thread-1"),+ runId: null,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ status: "completed" as const,+ title: null,+ toolName: "mcp__t3-code__device_screenshot",+ input: { deviceId: "phone" },+ output: {+ content: [+ {+ type: "image",+ source: {+ type: "base64",+ media_type: "image/png",+ data: Buffer.from(screenshotPng).toString("base64"),+ },+ },+ ],+ },+ startedAt: DateTime.makeUnsafe("2026-10-05T00:00:00.000Z"),+ completedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),+ updatedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),+};++const oversizedScreenshotItem = {+ ...screenshotItem,+ id: TurnItemId.make("tool-screenshot-oversized"),+ output: {+ content: [+ {+ type: "image",+ source: { type: "base64", media_type: "image/png", data: "A".repeat(14 * 1024 * 1024) },+ },+ ],+ },+};+const testLayer = Layer.mergeAll(NodeHttpPlatform.layer,+ Layer.mock(Orchestrator.OrchestratorV2)({+ getTurnItem: ({ itemId }) =>+ Effect.succeed(+ itemId === screenshotItem.id+ ? screenshotItem+ : itemId === oversizedScreenshotItem.id+ ? oversizedScreenshotItem+ : null,+ ),+ }),configLayer,WorkspacePaths.layer,ProjectFaviconResolver.layer.pipe(@@ -103,6 +172,35 @@ describe("AssetAccess", () => {);});+ it.effect("serves an image a tool returned inline from the stored item", () =>+ Effect.gen(function* () {+ const resource = {+ _tag: "tool-output-image" as const,+ threadId: screenshotItem.threadId,+ itemId: screenshotItem.id,+ index: 0,+ };+ const result = yield* issueAssetUrl({ resource });+ expect(result.imageDimensions).toEqual({ width: 390, height: 844 });+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);+ const separator = suffix.indexOf("/");+ expect(yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1))).toEqual({+ kind: "bytes",+ mimeType: "image/png",+ bytes: Buffer.from(screenshotPng),+ });+ const missing = yield* issueAssetUrl({ resource: { ...resource, index: 1 } }).pipe(+ Effect.flip,+ );+ expect(missing._tag).toBe("AssetWorkspaceAssetNotFoundError");+ // Larger than a provider turn accepts, so it is never decoded.+ const oversized = yield* issueAssetUrl({+ resource: { ...resource, itemId: oversizedScreenshotItem.id },+ }).pipe(Effect.flip);+ expect(oversized._tag).toBe("AssetWorkspaceAssetNotFoundError");+ }).pipe(Effect.provide(testLayer)),+ );+it.effect("issues exact URLs for media and browser documents outside the workspace", () =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.tsindex 427d95b380e..19fdac25b76 100644--- a/apps/server/src/assets/AssetAccess.ts+++ b/apps/server/src/assets/AssetAccess.ts@@ -1,6 +1,7 @@import type { AssetResource } from "@t3tools/contracts";import {AssetAttachmentNotFoundError,+ PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,AssetGitHubMediaUrlValidationError,AssetPreviewTypeValidationError,AssetProjectFaviconInspectionError,@@ -13,7 +14,9 @@ import {AssetWorkspacePathValidationError,AssetWorkspaceResolutionError,AssetWorkspaceRootNormalizationError,+ ThreadId,ToolActivityNativeAppReference,+ TurnItemId,} from "@t3tools/contracts";import {audioMimeTypeFromExtension,@@ -30,6 +33,7 @@ import {} from "@t3tools/shared/imageDimensions";import { githubMediaFetchUrl, githubMediaFileName } from "@t3tools/shared/githubMedia";import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";+import { toolOutputImages } from "@t3tools/shared/toolOutput";import * as Clock from "effect/Clock";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";@@ -49,6 +53,7 @@ import {import * as ServerSecretStore from "../auth/ServerSecretStore.ts";import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";import * as ServerConfig from "../config.ts";+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";import { expandHomePathWith } from "../pathExpansion.ts";import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";@@ -138,6 +143,14 @@ const AssetClaimsSchema = Schema.Union([app: ToolActivityNativeAppReference,expiresAt: Schema.Number,}),+ Schema.Struct({+ version: Schema.Literal(1),+ kind: Schema.Literal("tool-output-image"),+ threadId: ThreadId,+ itemId: TurnItemId,+ index: Schema.Number,+ expiresAt: Schema.Number,+ }),Schema.Struct({version: Schema.Literal(1),kind: Schema.Literal("github-media"),@@ -162,6 +175,11 @@ export type ResolvedAsset =readonly mimeType?: string;readonly file?: OpenMediaFile;}+ | {+ readonly kind: "bytes";+ readonly bytes: Uint8Array;+ readonly mimeType: string;+ }| {readonly kind: "github-media";readonly url: string;@@ -198,6 +216,27 @@ const optionOnNotFound = <A, R>(}),);+// The largest image a provider turn accepts, as base64 (4 characters per 3 bytes).+const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH = Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;++/**+ * Decodes one image a tool returned inline; null when the stored item has no+ * such image, or it is larger than a provider turn accepts.+ */+const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(function* (input: {+ readonly threadId: ThreadId;+ readonly itemId: TurnItemId;+ readonly index: number;+}) {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const item = yield* orchestrator.getTurnItem(input);+ const image =+ item?.type === "dynamic_tool" ? toolOutputImages(item.output)[input.index] : undefined;+ return image?.data === undefined || image.data.length > MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH+ ? null+ : { mimeType: image.mimeType, bytes: Buffer.from(image.data, "base64") };+});+const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(function* (filePath: string,) {@@ -672,6 +711,28 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i}break;}+ case "tool-output-image": {+ const image = yield* readToolOutputImage(input.resource).pipe(+ Effect.mapError(+ (cause) => new AssetWorkspaceAssetInspectionError({ resource: input.resource, cause }),+ ),+ );+ if (image === null) {+ return yield* new AssetWorkspaceAssetNotFoundError({ resource: input.resource });+ }+ claims = {+ version: 1,+ kind: "tool-output-image",+ threadId: input.resource.threadId,+ itemId: input.resource.itemId,+ index: input.resource.index,+ expiresAt,+ };+ // The allowed types are all `image/<extension>`.+ fileName = `image-${input.resource.index + 1}.${image.mimeType.slice("image/".length)}`;+ imageDimensions = readImageDimensions(image.bytes);+ break;+ }case "native-app-icon": {claims = {version: 1,@@ -806,6 +867,20 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (} satisfies ResolvedAsset;}+ if (claims.kind === "tool-output-image") {+ const image = yield* readToolOutputImage(claims).pipe(+ Effect.tapError((cause) =>+ Effect.logError("Failed to read tool output image.", {+ threadId: claims.threadId,+ itemId: claims.itemId,+ cause,+ }),+ ),+ Effect.orElseSucceed(() => null),+ );+ return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null;+ }+if (claims.kind === "native-app-icon") {const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver;const iconPath = yield* nativeAppIconResolver.resolve(claims.app);diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex 7be9c6adad0..8f32c5503c3 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -411,6 +411,12 @@ export const assetRouteLayer = HttpRouter.add(if (!asset) {return HttpServerResponse.text("Not Found", { status: 404 });}+ if (asset.kind === "bytes") {+ return HttpServerResponse.uint8Array(asset.bytes, {+ contentType: asset.mimeType,+ headers: { "cache-control": "private, max-age=3600", "x-content-type-options": "nosniff" },+ });+ }if (asset.kind === "github-media") {return yield* githubMediaResponse(asset, request.headers).pipe(Effect.tapError((cause) =>diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.tsindex 48a4881bdfb..ba4998341db 100644--- a/apps/server/src/orchestration-v2/WireProjection.test.ts+++ b/apps/server/src/orchestration-v2/WireProjection.test.ts@@ -23,6 +23,7 @@ import {projectDomainEventForWire,} from "./WireProjection.ts";import { threadShellFromProjection } from "./ProjectionStore.ts";+import { MAX_TOOL_OUTPUT_IMAGES, toolOutputImages } from "@t3tools/shared/toolOutput";const decodeTurnItem = Schema.decodeUnknownSync(OrchestrationV2TurnItem);const encodeTurnItemJson = Schema.encodeSync(OrchestrationV2TurnItemJson);@@ -274,6 +275,56 @@ describe("orchestration V2 wire projection", () => {expect(item.input).toBe(input);});+ it("leaves a screenshot's bytes out of the fetched tool output", () => {+ const data = "A".repeat(600_000);+ const item = {+ ...base,+ type: "dynamic_tool" as const,+ toolName: "mcp__t3-code__device_screenshot",+ input: { deviceId: "phone" },+ output: {+ content: [{ type: "image", source: { type: "base64", media_type: "image/png", data } }],+ },+ };+ expect(projectTurnItemForDetail(item)).toMatchObject({+ output: { content: [{ type: "image", mimeType: "image/png" }] },+ });+ expect(item.output.content[0]?.source.data).toBe(data);+ });++ it("keeps image markers when the rest of a tool output is too large to send", () => {+ const image = {+ type: "image",+ source: { type: "base64", media_type: "image/png", data: "AAAA" },+ };+ const item = {+ ...base,+ type: "dynamic_tool" as const,+ output: { content: [{ type: "text", text: "x".repeat(300_000) }, image] },+ };+ const projected = projectTurnItemForDetail(item);+ const output = projected.type === "dynamic_tool" ? projected.output : null;+ expect(Array.isArray(output) ? output.slice(1) : null).toEqual([+ { type: "image", mimeType: "image/png" },+ ]);+ expect(JSON.stringify(output).length).toBeLessThan(270_000);+ });++ it("bounds a tool output made of many images", () => {+ const image = { type: "image", data: "AAAA", mimeType: "image/png" };+ const item = {+ ...base,+ type: "dynamic_tool" as const,+ output: Array.from({ length: 10_000 }, () => image),+ };+ const projected = projectTurnItemForDetail(item);+ const output = projected.type === "dynamic_tool" ? projected.output : null;+ // The truncated text block plus a fixed number of markers, however many images there are.+ expect(Array.isArray(output) ? output.length : null).toBe(1 + MAX_TOOL_OUTPUT_IMAGES);+ expect(Array.isArray(output) ? String(output[0]?.text).length : null).toBeLessThan(263_000);+ expect(toolOutputImages(output)).toHaveLength(MAX_TOOL_OUTPUT_IMAGES);+ });+it("keeps failure evidence without retaining command output", () => {const item = {...base,diff --git a/apps/server/src/orchestration-v2/WireProjection.ts b/apps/server/src/orchestration-v2/WireProjection.tsindex 7c17147d220..f4e8f7542ad 100644--- a/apps/server/src/orchestration-v2/WireProjection.ts+++ b/apps/server/src/orchestration-v2/WireProjection.ts@@ -4,7 +4,12 @@ import type {OrchestrationV2ThreadProjection,OrchestrationV2TurnItem,} from "@t3tools/contracts";-import { compactDynamicToolOutput, toolOutputIndicatesFailure } from "@t3tools/shared/toolOutput";+import {+ compactDynamicToolOutput,+ omitToolOutputImageData,+ toolOutputImages,+ toolOutputIndicatesFailure,+} from "@t3tools/shared/toolOutput";const MAX_DETAIL_STRING_BYTES = 32_768;const MAX_DYNAMIC_VALUE_BYTES = 16_384;@@ -142,9 +147,28 @@ function boundDynamicValue(value: unknown): unknown {: truncateDetail(json, MAX_ON_DEMAND_BYTES);}+/**+ * A tool output for a detail read, without image bytes. When the rest is too+ * large to send whole, its truncated text still comes with the image markers,+ * in order, so clients can load each image by index.+ */+function boundToolOutput(output: unknown): unknown {+ const omitted = omitToolOutputImageData(output);+ const bounded = boundDynamicValue(omitted);+ if (typeof bounded !== "string" || typeof omitted === "string") return bounded;+ const images = toolOutputImages(omitted);+ return images.length === 0+ ? bounded+ : [+ { type: "text", text: bounded },+ ...images.map((image) => ({ type: "image", mimeType: image.mimeType })),+ ];+}+/*** Projects one item for an on-demand detail read: keeps the input and output* the timeline withholds, bounded so a huge result cannot stall the socket.+ * Image bytes are left out; clients load them as `tool-output-image` assets.*/export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {switch (item.type) {@@ -158,7 +182,7 @@ export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): Orchestreturn {...item,input: boundDynamicValue(item.input),- output: boundDynamicValue(item.output),+ output: boundToolOutput(item.output),};case "subagent":return {diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex f47594e08ff..901a179ab7c 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -3148,6 +3148,7 @@ const makeWsRpcLayer = (if (input.resource._tag === "attachment" ||input.resource._tag === "native-app-icon" ||+ input.resource._tag === "tool-output-image" ||// GitHub media names the repository it authenticates through itself.input.resource._tag === "github-media" ||(input.resource._tag === "media-file" && path.isAbsolute(input.resource.path))diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex cfd0ddf1b2a..7934b2c1c77 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -1762,7 +1762,14 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(propsreadonly environmentId: EnvironmentId;readonly resource: Extract<AssetResource,- { readonly _tag: "attachment" | "workspace-file" | "media-file" | "github-media" }+ {+ readonly _tag:+ | "attachment"+ | "workspace-file"+ | "media-file"+ | "github-media"+ | "tool-output-image";+ }>;readonly kind?: "image" | "video";readonly alt: string;diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 6f01fd82116..33f51752fbc 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -2878,6 +2878,7 @@ function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "event"onOpenThread={ctx.onOpenThread}onOpenTurnDiff={ctx.onOpenTurnDiff}onRollbackCheckpoint={ctx.onRollbackCheckpoint}+ onImageExpand={ctx.onImageExpand}/></div></div>@@ -2952,6 +2953,7 @@ function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "event"onOpenThread={ctx.onOpenThread}onOpenTurnDiff={ctx.onOpenTurnDiff}onRollbackCheckpoint={ctx.onRollbackCheckpoint}+ onImageExpand={ctx.onImageExpand}/></div></div>@@ -5357,6 +5359,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {onOpenThread={ctx.onOpenThread}onOpenTurnDiff={ctx.onOpenTurnDiff}onRollbackCheckpoint={ctx.onRollbackCheckpoint}+ onImageExpand={ctx.onImageExpand}/>) : (<>@@ -5367,6 +5370,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {<FetchedToolOutputprojectedItem={workEntry.projectedItem}environmentId={ctx.activeThreadEnvironmentId}+ onImageExpand={onImageExpand}/>) : null}</>diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsxindex 7dc48a9e00a..8f92a511d69 100644--- a/apps/web/src/components/chat/V2ItemInspector.tsx+++ b/apps/web/src/components/chat/V2ItemInspector.tsx@@ -8,6 +8,7 @@ import {toolCallLines,turnItemDetailRevision,turnItemNeedsDetailFetch,+ turnItemOutputImages,turnItemOutputText,} from "@t3tools/client-runtime/work-log/item-detail";import { ExternalLinkIcon, GitBranchIcon, RotateCcwIcon } from "lucide-react";@@ -21,9 +22,10 @@ import { useTurnItemDetail } from "../../state/queries";import { useV2ItemSupport } from "../../state/v2ItemSupport";import { formatWorkspaceRelativePath } from "../../filePathDisplay";import { Button } from "../ui/button";-import ChatMarkdown from "../ChatMarkdown";+import ChatMarkdown, { ChatMarkdownAssetImage } from "../ChatMarkdown";import { RenderErrorBoundary } from "../RenderErrorBoundary";import { resolveExternalWebLinkHref } from "./externalLinkContextMenu";+import type { ExpandedImagePreview } from "./ExpandedImagePreview";import { ShellCommandBlock } from "./ShellCommandBlock";interface V2ItemInspectorProps {@@ -37,6 +39,7 @@ interface V2ItemInspectorProps {readonly checkpointId: string;readonly scopeId: string;}) => void;+ readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;}function JsonTokens({ text }: { readonly text: string }) {@@ -119,6 +122,8 @@ function useFetchedTurnItem(item,output: {output: turnItemOutputText(item),+ images: turnItemOutputImages(item),+ environmentId,pending: item === wireItem && detail.isPending,error:item !== wireItem@@ -133,32 +138,52 @@ function useFetchedTurnItem(interface ToolOutputState {readonly output: string | null;+ readonly images: ReturnType<typeof turnItemOutputImages>;+ readonly environmentId: EnvironmentId;readonly pending: boolean;readonly error: string | null;readonly empty: boolean;+ readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;}function ToolOutput(props: ToolOutputState) {- return props.output ? (+ const images = props.images.map((resource) => (+ <ChatMarkdownAssetImage+ key={resource.index}+ environmentId={props.environmentId}+ resource={resource}+ alt="Tool output image"+ maxHeightRem={16}+ onImageExpand={props.onImageExpand}+ />+ ));+ const text = props.output ? (<div className="max-h-80 overflow-auto text-muted-foreground">{props.output}</div>) : props.pending ? (<div className="text-muted-foreground italic">Loading output…</div>) : props.error ? (<div className="text-destructive">Couldn't load output: {props.error}</div>- ) : props.empty ? (+ ) : props.empty && images.length === 0 ? (<div className="text-muted-foreground italic">No output.</div>) : null;+ return (+ <>+ {images}+ {text}+ </>+ );}/** Fetched output for rows that show their own plain text instead of the inspector. */export function FetchedToolOutput(props: {readonly projectedItem: OrchestrationV2ProjectedTurnItem;readonly environmentId: EnvironmentId;+ readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;}) {const { output } = useFetchedTurnItem(props.projectedItem, props.environmentId);return (- <div className={cn("mt-1.5", monoClassName)}>- <ToolOutput {...output} />+ <div className={cn("mt-1.5 space-y-1.5", monoClassName)}>+ <ToolOutput {...output} onImageExpand={props.onImageExpand} /></div>);}@@ -220,7 +245,12 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec) : null}{item.type === "command_execution" ? (- <ToolCallBody command={item.input} exitCode={item.exitCode} {...outputState} />+ <ToolCallBody+ command={item.input}+ exitCode={item.exitCode}+ {...outputState}+ onImageExpand={props.onImageExpand}+ />) : null}{item.type === "file_change" ? (@@ -317,7 +347,9 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec</ul>) : null}- {item.type === "dynamic_tool" ? <ToolCallBody args={item.input} {...outputState} /> : null}+ {item.type === "dynamic_tool" ? (+ <ToolCallBody args={item.input} {...outputState} onImageExpand={props.onImageExpand} />+ ) : null}{item.type === "approval_request" ? <StructuredValue value={item.prompt} /> : null}{item.type === "user_input_request" ? (diff --git a/packages/client-runtime/src/work-log/itemDetail.test.ts b/packages/client-runtime/src/work-log/itemDetail.test.tsnew file mode 100644index 00000000000..3570974a7df--- /dev/null+++ b/packages/client-runtime/src/work-log/itemDetail.test.ts@@ -0,0 +1,55 @@+import { ThreadId, TurnItemId } from "@t3tools/contracts";+import * as DateTime from "effect/DateTime";+import { describe, expect, it } from "vite-plus/test";++import { turnItemOutputImages, turnItemOutputText } from "./itemDetail.ts";++const screenshot = {+ id: TurnItemId.make("tool-screenshot"),+ type: "dynamic_tool" as const,+ threadId: ThreadId.make("thread-1"),+ runId: null,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 1,+ status: "completed" as const,+ title: null,+ toolName: "mcp__t3-code__device_screenshot",+ input: { deviceId: "phone" },+ // What a detail read returns: the image's position without its bytes.+ output: {+ content: [+ { type: "text", text: "Captured the home screen." },+ { type: "image", mimeType: "image/png" },+ ],+ },+ startedAt: DateTime.makeUnsafe("2026-10-05T00:00:00.000Z"),+ completedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),+ updatedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),+};++describe("tool output images", () => {+ it("shows a screenshot as an image asset, not as text", () => {+ expect(turnItemOutputImages(screenshot)).toEqual([+ {+ _tag: "tool-output-image",+ threadId: screenshot.threadId,+ itemId: screenshot.id,+ index: 0,+ },+ ]);+ expect(turnItemOutputText(screenshot)).toBe("Captured the home screen.");+ expect(+ turnItemOutputText({ ...screenshot, output: { content: [screenshot.output.content[1]] } }),+ ).toBeNull();+ });++ it("keeps a placeholder for images it cannot show", () => {+ const output = { content: [{ type: "image", mimeType: "image/svg+xml" }] };+ expect(turnItemOutputImages({ ...screenshot, output })).toEqual([]);+ expect(turnItemOutputText({ ...screenshot, output })).toBe("[image]");+ });+});diff --git a/packages/client-runtime/src/work-log/itemDetail.ts b/packages/client-runtime/src/work-log/itemDetail.tsindex a138bed6f22..cad1bab22fb 100644--- a/packages/client-runtime/src/work-log/itemDetail.ts+++ b/packages/client-runtime/src/work-log/itemDetail.ts@@ -1,4 +1,5 @@-import type { OrchestrationV2TurnItem } from "@t3tools/contracts";+import type { AssetResource, OrchestrationV2TurnItem } from "@t3tools/contracts";+import { readToolOutputImage, toolOutputImages } from "@t3tools/shared/toolOutput";import * as DateTime from "effect/DateTime";const MAX_TEXT_BLOCK_DEPTH = 4;@@ -17,11 +18,14 @@ function textFromBlocks(value: unknown, depth: number): string | null {if (typeof value === "string") return value;if (Array.isArray(value)) {const parts = value.map((block) => textFromBlocks(block, depth + 1));- return parts.every((part) => part !== null) ? parts.join("\n") : null;+ return parts.every((part) => part !== null)+ ? parts.filter((part) => part !== "").join("\n")+ : null;}if (!isRecord(value)) return null;if (value.type === "text" && typeof value.text === "string") return value.text;- if (value.type === "image") return "[image]";+ // Images clients can show render on their own (see turnItemOutputImages).+ if (value.type === "image") return readToolOutputImage(value) ? "" : "[image]";if (value.type === "resource_link" && typeof value.uri === "string") return value.uri;if (value.type === "resource" && isRecord(value.resource)) {const resource = value.resource;@@ -200,6 +204,22 @@ export function turnItemOutputText(item: OrchestrationV2TurnItem): string | null}}+/**+ * Images in a fetched item's tool output, as assets. The detail read leaves+ * the bytes out, so each loads over HTTP by its index.+ */+export function turnItemOutputImages(+ item: OrchestrationV2TurnItem,+): ReadonlyArray<Extract<AssetResource, { readonly _tag: "tool-output-image" }>> {+ if (item.type !== "dynamic_tool" || item.outputOmitted === true) return [];+ return toolOutputImages(item.output).map((_, index) => ({+ _tag: "tool-output-image",+ threadId: item.threadId,+ itemId: item.id,+ index,+ }));+}+/*** Whether expanding the item shows anything. Rows without content must not* offer a disclosure, otherwise they open to an empty panel.diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.tsindex 51a2f0868d4..8d7b8b5d2d5 100644--- a/packages/contracts/src/assets.ts+++ b/packages/contracts/src/assets.ts@@ -1,6 +1,6 @@import * as Schema from "effect/Schema";-import { NonNegativeInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";+import { NonNegativeInt, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";import {PROVIDER_SEND_TURN_MAX_FILE_BYTES,PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,@@ -41,6 +41,13 @@ export const AssetResource = Schema.Union([inline response after deciding the file type is safe to preview. */disposition: Schema.optionalKey(Schema.Literals(["inline", "attachment"])),}),+ // An image a tool returned inline, such as a device screenshot, by its order+ // in the stored output. The timeline never carries these bytes.+ Schema.TaggedStruct("tool-output-image", {+ threadId: ThreadId,+ itemId: TurnItemId,+ index: NonNegativeInt,+ }),Schema.TaggedStruct("project-favicon", {cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),// A cache-key hint only. The server reads the authoritative path from the@@ -218,7 +225,9 @@ export class AssetWorkspaceAssetNotFoundError extends Schema.TaggedError<AssetWooverride get message(): string {return this.resource._tag === "media-file"? "Media file was not found."- : "Workspace asset was not found.";+ : this.resource._tag === "tool-output-image"+ ? "Tool output image was not found."+ : "Workspace asset was not found.";}}diff --git a/packages/shared/src/toolOutput.test.ts b/packages/shared/src/toolOutput.test.tsindex c53a3b602dc..489fa524714 100644--- a/packages/shared/src/toolOutput.test.ts+++ b/packages/shared/src/toolOutput.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from "vite-plus/test";-import { compactDynamicToolOutput, toolOutputIndicatesFailure } from "./toolOutput.ts";+import {+ compactDynamicToolOutput,+ MAX_TOOL_OUTPUT_IMAGES,+ omitToolOutputImageData,+ toolOutputImages,+ toolOutputIndicatesFailure,+} from "./toolOutput.ts";describe("compactDynamicToolOutput", () => {it("extracts IDs through the MCP result envelopes used by T3 summaries", () => {@@ -173,3 +179,51 @@ describe("toolOutputIndicatesFailure", () => {}});});++describe("toolOutputImages", () => {+ const mcpImage = { type: "image", data: "AAAA", mimeType: "image/png" };+ const claudeImage = {+ type: "image",+ source: { type: "base64", media_type: "image/JPEG", data: "BBBB" },+ };+ const text = { type: "text", text: "{}" };++ it("finds images in each place providers store them, in order", () => {+ expect(toolOutputImages({ content: [text, claudeImage, mcpImage] })).toEqual([+ { mimeType: "image/jpeg", data: "BBBB" },+ { mimeType: "image/png", data: "AAAA" },+ ]);+ expect(toolOutputImages([mcpImage])).toEqual([{ mimeType: "image/png", data: "AAAA" }]);+ expect(toolOutputImages(mcpImage)).toEqual([{ mimeType: "image/png", data: "AAAA" }]);+ });++ it("skips types the server must not serve inline", () => {+ expect(+ toolOutputImages([+ { ...mcpImage, mimeType: "image/svg+xml" },+ { ...mcpImage, mimeType: "text/html" },+ { type: "image", source: { type: "url", url: "https://example.com/a.png" } },+ ]),+ ).toEqual([]);+ });++ it("stops after the first few images", () => {+ const images = toolOutputImages(Array.from({ length: 10_000 }, () => mcpImage));+ expect(images).toHaveLength(MAX_TOOL_OUTPUT_IMAGES);+ });++ it("drops the bytes but keeps each image's position", () => {+ const omitted = omitToolOutputImageData({ content: [text, claudeImage, mcpImage] });+ expect(omitted).toEqual({+ content: [+ text,+ { type: "image", mimeType: "image/jpeg" },+ { type: "image", mimeType: "image/png" },+ ],+ });+ expect(toolOutputImages(omitted)).toEqual([+ { mimeType: "image/jpeg" },+ { mimeType: "image/png" },+ ]);+ });+});diff --git a/packages/shared/src/toolOutput.ts b/packages/shared/src/toolOutput.tsindex 255fcbf4716..a573525571d 100644--- a/packages/shared/src/toolOutput.ts+++ b/packages/shared/src/toolOutput.ts@@ -1,3 +1,4 @@+import { isProviderSendTurnSupportedImageMimeType } from "@t3tools/contracts";import * as Predicate from "effect/Predicate";const MAX_PARSED_BYTES = 16_384;@@ -166,3 +167,69 @@ export function toolOutputIndicatesFailure(text: string): boolean {/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text));}++/** An image a tool returned inline. `data` is base64; a detail read omits it. */+export interface ToolOutputImage {+ readonly mimeType: string;+ readonly data?: string;+}++/**+ * Reads one image block in the MCP `{ data, mimeType }` shape or the Anthropic+ * `{ source: { type: "base64", media_type, data } }` shape Claude stores.+ * Only raster types are recognized, so the server never serves an agent's SVG+ * or HTML inline.+ */+export function readToolOutputImage(block: unknown): ToolOutputImage | null {+ if (!Predicate.isObject(block) || block.type !== "image") return null;+ const source = Predicate.isObject(block.source) ? block.source : undefined;+ if (source !== undefined && source.type !== "base64") return null;+ const mimeType = source === undefined ? block.mimeType : source.media_type;+ const data = source === undefined ? block.data : source.data;+ if (typeof mimeType !== "string" || !isProviderSendTurnSupportedImageMimeType(mimeType)) {+ return null;+ }+ const image = { mimeType: mimeType.toLowerCase() };+ return typeof data === "string" ? { ...image, data } : image;+}++/** Tools return a block, a list of blocks, or an MCP result with a `content` list. */+function outputBlocks(value: unknown): ReadonlyArray<unknown> {+ if (Array.isArray(value)) return value;+ if (Predicate.isObject(value) && Array.isArray(value.content)) return value.content;+ return [value];+}++/** A tool returns one screenshot or a few frames; more would only flood the timeline. */+export const MAX_TOOL_OUTPUT_IMAGES = 8;++/**+ * The first images in a tool output, in order. The order is the+ * `tool-output-image` asset index, so servers and clients agree on it.+ */+export function toolOutputImages(value: unknown): ReadonlyArray<ToolOutputImage> {+ const images: ToolOutputImage[] = [];+ for (const block of outputBlocks(value)) {+ const image = readToolOutputImage(block);+ if (image === null) continue;+ images.push(image);+ if (images.length === MAX_TOOL_OUTPUT_IMAGES) break;+ }+ return images;+}++/**+ * Replaces each image's bytes with `{ type: "image", mimeType }` and keeps its+ * position, so detail reads stay small and clients load the bytes as assets.+ */+export function omitToolOutputImageData(value: unknown): unknown {+ const omit = (block: unknown) => {+ const image = readToolOutputImage(block);+ return image?.data === undefined ? block : { type: "image", mimeType: image.mimeType };+ };+ if (Array.isArray(value)) return value.map(omit);+ if (Predicate.isObject(value) && Array.isArray(value.content)) {+ return { ...value, content: value.content.map(omit) };+ }+ return omit(value);+}