fix: tool screenshots show as images, not base64 text (#16199)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
2a68a777af
commit
5eb8773087
17 files changed
+551
-21
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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): Orchest
|
||||
return {
|
||||
...item,
|
||||
input: boundDynamicValue(item.input),
|
||||
output: boundDynamicValue(item.output),
|
||||
output: boundToolOutput(item.output),
|
||||
};
|
||||
case "subagent":
|
||||
return {
|
||||
|
||||
@@ -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))
|
||||
|
||||
Reference in new issue
Block a user