feat: render Image View outputs in chat (#4436)

This commit is contained in:
Jono Kemball authored and Gabriel De Andrade committed 2026-07-29 21:58:12 -04:00
1 parent 86756e7e49
commit a1682683ce
13 files changed
+1069 -4

No files matched your search

+62 -1
View File
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ThreadId } from "@t3tools/contracts";
import { EventId, ThreadId } from "@t3tools/contracts";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -274,6 +274,67 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact capabilities for image view activities outside the workspace", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-image-view-",
});
const imagePath = path.join(directory, "tool-output.png");
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
const canonicalImagePath = yield* fileSystem.realPath(imagePath);
const resource = {
_tag: "thread-image" as const,
threadId: ThreadId.make("thread-1"),
activityId: EventId.make("activity-1"),
};
const result = yield* issueAssetUrl({
resource,
threadImagePath: imagePath,
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "tool-output.png")).toEqual({
kind: "file",
path: canonicalImagePath,
});
expect(yield* resolveAsset(token, "other.png")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects missing and non-image paths for image view activities", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-image-view-invalid-",
});
const textPath = path.join(directory, "notes.txt");
yield* fileSystem.writeFileString(textPath, "not an image");
const resource = {
_tag: "thread-image" as const,
threadId: ThreadId.make("thread-1"),
activityId: EventId.make("activity-1"),
};
const unsupportedError = yield* issueAssetUrl({
resource,
threadImagePath: textPath,
}).pipe(Effect.flip);
expect(unsupportedError._tag).toBe("AssetThreadImageNotFoundError");
const missingError = yield* issueAssetUrl({
resource,
threadImagePath: path.join(directory, "missing.png"),
}).pipe(Effect.flip);
expect(missingError._tag).toBe("AssetThreadImageNotFoundError");
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues project favicon capabilities with a signed fallback", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
+77
View File
@@ -7,6 +7,8 @@ import {
AssetProjectFaviconNotFoundError,
AssetProjectFaviconResolutionError,
AssetSigningKeyLoadError,
AssetThreadImageNotFoundError,
AssetThreadImageResolutionError,
AssetWorkspaceAssetInspectionError,
AssetWorkspaceAssetNotFoundError,
AssetWorkspaceContextNotFoundError,
@@ -87,6 +89,12 @@ const AssetClaimsSchema = Schema.Union([
fileName: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("thread-image"),
path: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("project-favicon"),
@@ -199,6 +207,7 @@ const resolveCanonicalWorkspaceFileForRequest = (input: {
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
readonly resource: AssetResource;
readonly workspaceRoot?: string;
readonly threadImagePath?: string;
}) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -328,6 +337,55 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
fileName = artifactFileName;
break;
}
case "thread-image": {
if (
!input.threadImagePath ||
!path.isAbsolute(input.threadImagePath) ||
!isWorkspaceImagePreviewPath(input.threadImagePath)
) {
return yield* new AssetThreadImageNotFoundError({
resource: input.resource,
});
}
const canonicalPath = yield* optionOnNotFound(
fileSystem.realPath(input.threadImagePath),
).pipe(
Effect.mapError(
(cause) =>
new AssetThreadImageResolutionError({
resource: input.resource,
cause,
}),
),
);
if (Option.isNone(canonicalPath)) {
return yield* new AssetThreadImageNotFoundError({
resource: input.resource,
});
}
const info = yield* optionOnNotFound(fileSystem.stat(canonicalPath.value)).pipe(
Effect.mapError(
(cause) =>
new AssetThreadImageResolutionError({
resource: input.resource,
cause,
}),
),
);
if (Option.isNone(info) || info.value.type !== "File") {
return yield* new AssetThreadImageNotFoundError({
resource: input.resource,
});
}
claims = {
version: 1,
kind: "thread-image",
path: canonicalPath.value,
expiresAt,
};
fileName = path.basename(canonicalPath.value);
break;
}
case "project-favicon": {
const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(
Effect.mapError(
@@ -455,6 +513,25 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
: null;
}
if (claims.kind === "thread-image") {
const decodedPath = decodeRelativePath(relativePath);
const path = yield* Path.Path;
if (decodedPath !== path.basename(claims.path)) return null;
const fileSystem = yield* FileSystem.FileSystem;
const info = yield* optionOnNotFound(fileSystem.stat(claims.path)).pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to inspect image view asset.", {
path: claims.path,
cause,
}),
),
Effect.orElseSucceed(() => Option.none()),
);
return Option.isSome(info) && info.value.type === "File"
? ({ kind: "file", path: claims.path } satisfies ResolvedAsset)
: null;
}
if (claims.kind === "project-favicon") {
if (claims.relativePath === null) return null;
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
@@ -613,6 +613,95 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("maps image view items with their local path", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const imagePath = "/tmp/codex-preview.png";
yield* runtime.emit({
id: asEventId("evt-image-view-complete"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
method: "item/completed",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
itemId: asItemId("image_1"),
payload: {
completedAtMs: 1_778_000_000_000,
threadId: "thread-1",
turnId: "turn-1",
item: {
type: "imageView",
id: "image_1",
path: imagePath,
},
},
});
const firstEvent = yield* Fiber.join(firstEventFiber);
NodeAssert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some" || firstEvent.value.type !== "item.completed") {
return;
}
NodeAssert.equal(firstEvent.value.payload.itemType, "image_view");
NodeAssert.equal(firstEvent.value.payload.title, "Image view");
NodeAssert.equal(firstEvent.value.payload.detail, imagePath);
NodeAssert.deepStrictEqual(firstEvent.value.payload.data, {
completedAtMs: 1_778_000_000_000,
threadId: "thread-1",
turnId: "turn-1",
item: {
type: "imageView",
id: "image_1",
path: imagePath,
},
});
}),
);
it.effect("maps generated images with their saved path", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const imagePath = "/Users/test/.codex/generated_images/thread-1/generated.png";
yield* runtime.emit({
id: asEventId("evt-image-generation-complete"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-01-01T00:00:00.000Z",
method: "item/completed",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
itemId: asItemId("image_generation_1"),
payload: {
completedAtMs: 1_778_000_000_000,
threadId: "thread-1",
turnId: "turn-1",
item: {
type: "imageGeneration",
id: "image_generation_1",
status: "completed",
revisedPrompt: "A generated image",
result: "base64-image-data",
savedPath: imagePath,
},
},
});
const firstEvent = yield* Fiber.join(firstEventFiber);
NodeAssert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some" || firstEvent.value.type !== "item.completed") {
return;
}
NodeAssert.equal(firstEvent.value.payload.itemType, "image_view");
NodeAssert.equal(firstEvent.value.payload.title, "Image view");
NodeAssert.equal(firstEvent.value.payload.detail, imagePath);
}),
);
it.effect("maps completed plan items to canonical proposed-plan completion events", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
@@ -281,6 +281,7 @@ function itemDetail(itemType: CanonicalItemType, item: CodexLifecycleItem): stri
"summary" in item ? item.summary : undefined,
"text" in item ? item.text : undefined,
"path" in item ? item.path : undefined,
"savedPath" in item ? item.savedPath : undefined,
"prompt" in item ? item.prompt : undefined,
];
+77
View File
@@ -4878,6 +4878,83 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("issues image view asset URLs only for the exact thread activity", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const imageDirectory = yield* fs.makeTempDirectoryScoped({
prefix: "t3-ws-image-view-",
});
const imagePath = path.join(imageDirectory, "tool-output.png");
yield* fs.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
const activityId = EventId.make("image-view-activity");
const thread = {
...makeDefaultOrchestrationReadModel().threads[0]!,
activities: [
{
id: activityId,
tone: "tool" as const,
kind: "tool.completed",
summary: "Image view",
payload: {
itemType: "image_view",
data: {
item: {
type: "imageGeneration",
savedPath: imagePath,
status: "completed",
},
},
},
turnId: null,
createdAt: "2026-01-01T00:00:00.000Z",
},
],
};
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getThreadDetailById: (threadId) =>
Effect.succeed(threadId === defaultThreadId ? Option.some(thread) : Option.none()),
},
},
});
const wsUrl = yield* getWsServerUrl("/ws");
const response = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.assetsCreateUrl]({
resource: {
_tag: "thread-image",
threadId: defaultThreadId,
activityId,
},
}),
),
);
assert.include(response.relativeUrl, "/tool-output.png");
const unrelatedActivityResult = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.assetsCreateUrl]({
resource: {
_tag: "thread-image",
threadId: defaultThreadId,
activityId: EventId.make("unrelated-activity"),
},
}).pipe(Effect.result),
),
);
if (
unrelatedActivityResult._tag !== "Failure" ||
unrelatedActivityResult.failure._tag !== "AssetThreadImageNotFoundError"
) {
assert.fail("Expected an AssetThreadImageNotFoundError");
}
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("creates a missing workspace root during websocket project.create dispatch", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
+52
View File
@@ -45,6 +45,8 @@ import {
AssetWorkspaceContextNotFoundError,
AssetWorkspaceContextResolutionError,
RpcClientId,
AssetThreadImageNotFoundError,
AssetThreadImageResolutionError,
EnvironmentAuthorizationError,
ThreadId,
type TerminalAttachStreamEvent,
@@ -116,6 +118,27 @@ import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as SessionStore from "./auth/SessionStore.ts";
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
import * as RelayClient from "@t3tools/shared/relayClient";
function asUnknownRecord(value: unknown): Record<string, unknown> | null {
return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : null;
}
function extractImageViewPath(payload: unknown): string | null {
const payloadRecord = asUnknownRecord(payload);
if (payloadRecord?.itemType !== "image_view") return null;
const data = asUnknownRecord(payloadRecord.data);
const item = asUnknownRecord(data?.item);
const rawPath =
item?.type === "imageView"
? item.path
: item?.type === "imageGeneration"
? item.savedPath
: null;
if (typeof rawPath !== "string") return null;
const path = rawPath.trim();
return path.length > 0 ? path : null;
}
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
@@ -1622,6 +1645,35 @@ const makeWsRpcLayer = (
observeRpcEffect(
WS_METHODS.assetsCreateUrl,
Effect.gen(function* () {
if (input.resource._tag === "thread-image") {
const resource = input.resource;
const thread = yield* projectionSnapshotQuery
.getThreadDetailById(resource.threadId)
.pipe(
Effect.mapError(
(cause) =>
new AssetThreadImageResolutionError({
resource,
cause,
}),
),
);
const activity = Option.isSome(thread)
? thread.value.activities.find(
(candidate) => candidate.id === resource.activityId,
)
: undefined;
const threadImagePath = activity ? extractImageViewPath(activity.payload) : null;
if (!threadImagePath) {
return yield* new AssetThreadImageNotFoundError({
resource,
});
}
return yield* issueAssetUrl({
resource,
threadImagePath,
});
}
if (input.resource._tag !== "workspace-file") {
return yield* issueAssetUrl({ resource: input.resource });
}