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 });
}
@@ -261,6 +261,238 @@ describe("resolveAssistantMessageCopyState", () => {
});
describe("deriveMessagesTimelineRows", () => {
it("deduplicates and groups image output after the terminal assistant message", () => {
const timelineEntries = [
{
id: "user-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:00Z",
message: {
id: "user-message" as never,
role: "user" as const,
text: "Generate an image",
turnId: null,
createdAt: "2026-01-01T00:00:00Z",
updatedAt: "2026-01-01T00:00:00Z",
streaming: false,
},
},
{
id: "image-view-entry",
kind: "work" as const,
createdAt: "2026-01-01T00:00:10Z",
entry: {
id: "image-view-activity",
createdAt: "2026-01-01T00:00:10Z",
turnId: "turn-1" as never,
label: "Image view",
tone: "tool" as const,
itemType: "image_view" as const,
imagePath: "/tmp/generated.png",
toolLifecycleStatus: "completed" as const,
},
},
{
id: "duplicate-image-view-entry",
kind: "work" as const,
createdAt: "2026-01-01T00:00:11Z",
entry: {
id: "duplicate-image-view-activity",
createdAt: "2026-01-01T00:00:11Z",
turnId: "turn-1" as never,
label: "Image view",
tone: "tool" as const,
itemType: "image_view" as const,
imagePath: "/tmp/generated.png",
toolLifecycleStatus: "completed" as const,
},
},
{
id: "second-image-view-entry",
kind: "work" as const,
createdAt: "2026-01-01T00:00:12Z",
entry: {
id: "second-image-view-activity",
createdAt: "2026-01-01T00:00:12Z",
turnId: "turn-1" as never,
label: "Image view",
tone: "tool" as const,
itemType: "image_view" as const,
imagePath: "/tmp/second.png",
toolLifecycleStatus: "completed" as const,
},
},
{
id: "assistant-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:20Z",
message: {
id: "assistant-message" as never,
role: "assistant" as const,
text: "Here is the generated image.",
turnId: "turn-1" as never,
createdAt: "2026-01-01T00:00:20Z",
updatedAt: "2026-01-01T00:00:21Z",
streaming: false,
},
},
];
const input = {
timelineEntries,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
};
const expandedRows = deriveMessagesTimelineRows({
...input,
expandedTurnIds: new Set(["turn-1" as never]),
});
const toolRowIndex = expandedRows.findIndex((row) => row.kind === "work");
const assistantRowIndex = expandedRows.findIndex(
(row) => row.kind === "message" && row.message.role === "assistant",
);
const assistantRow = expandedRows[assistantRowIndex];
expect(toolRowIndex).toBeGreaterThan(-1);
expect(assistantRowIndex).toBeGreaterThan(toolRowIndex);
expect(assistantRow).toMatchObject({
kind: "message",
assistantImageOutputs: [
{
entry: { id: "image-view-activity" },
imagePath: "/tmp/generated.png",
},
{
entry: { id: "second-image-view-activity" },
imagePath: "/tmp/second.png",
},
],
});
expect(expandedRows.some((row) => row.kind === "image-output")).toBe(false);
const collapsedRows = deriveMessagesTimelineRows(input);
expect(collapsedRows.some((row) => row.kind === "work")).toBe(false);
expect(collapsedRows.at(-1)).toMatchObject({
kind: "message",
assistantImageOutputs: [
{
entry: { id: "image-view-activity" },
imagePath: "/tmp/generated.png",
},
{
entry: { id: "second-image-view-activity" },
imagePath: "/tmp/second.png",
},
],
});
});
it("withholds image output until its turn is settled", () => {
const timelineEntries = [
{
id: "image-view-entry",
kind: "work" as const,
createdAt: "2026-01-01T00:00:10Z",
entry: {
id: "image-view-activity",
createdAt: "2026-01-01T00:00:10Z",
turnId: "turn-1" as never,
label: "Image view",
tone: "tool" as const,
itemType: "image_view" as const,
imagePath: "/tmp/generated.png",
toolLifecycleStatus: "completed" as const,
},
},
];
const sharedInput = {
timelineEntries,
activeTurnStartedAt: "2026-01-01T00:00:00Z",
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
};
const runningRows = deriveMessagesTimelineRows({
...sharedInput,
latestTurn: {
turnId: "turn-1" as never,
state: "running" as const,
startedAt: "2026-01-01T00:00:00Z",
completedAt: null,
},
isWorking: true,
});
expect(runningRows.some((row) => row.kind === "image-output")).toBe(false);
const settledRows = deriveMessagesTimelineRows({
...sharedInput,
latestTurn: {
turnId: "turn-1" as never,
state: "completed" as const,
startedAt: "2026-01-01T00:00:00Z",
completedAt: "2026-01-01T00:00:20Z",
},
isWorking: false,
});
expect(settledRows.some((row) => row.kind === "image-output")).toBe(true);
});
it("allows the same image to appear once in each turn", () => {
const imagePath = "/tmp/shared.png";
const makeImageEntry = (turnId: string, id: string, createdAt: string) => ({
id: `${id}-entry`,
kind: "work" as const,
createdAt,
entry: {
id,
createdAt,
turnId: turnId as never,
label: "Image view",
tone: "tool" as const,
itemType: "image_view" as const,
imagePath,
toolLifecycleStatus: "completed" as const,
},
});
const makeAssistantEntry = (turnId: string, id: string, createdAt: string) => ({
id: `${id}-entry`,
kind: "message" as const,
createdAt,
message: {
id: id as never,
role: "assistant" as const,
text: `Response for ${turnId}`,
turnId: turnId as never,
createdAt,
updatedAt: createdAt,
streaming: false,
},
});
const rows = deriveMessagesTimelineRows({
timelineEntries: [
makeImageEntry("turn-1", "image-view-1", "2026-01-01T00:00:01Z"),
makeAssistantEntry("turn-1", "assistant-1", "2026-01-01T00:00:02Z"),
makeImageEntry("turn-2", "image-view-2", "2026-01-01T00:00:03Z"),
makeAssistantEntry("turn-2", "assistant-2", "2026-01-01T00:00:04Z"),
],
isWorking: false,
activeTurnStartedAt: null,
expandedTurnIds: new Set(["turn-1" as never, "turn-2" as never]),
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
expect(
rows.filter((row) => row.kind === "message").map((row) => row.assistantImageOutputs),
).toMatchObject([
[{ entry: { id: "image-view-1" }, imagePath }],
[{ entry: { id: "image-view-2" }, imagePath }],
]);
});
it("only enables assistant copy for the terminal assistant message in a turn", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
@@ -133,6 +133,11 @@ export type TimelineLatestTurn = Pick<
"turnId" | "state" | "startedAt" | "completedAt"
>;
export interface TimelineImageOutput {
entry: WorkLogEntry;
imagePath: string;
}
export type MessagesTimelineRow =
| {
kind: "work";
@@ -140,6 +145,12 @@ export type MessagesTimelineRow =
createdAt: string;
groupedEntries: WorkLogEntry[];
}
| {
kind: "image-output";
id: string;
createdAt: string;
images: TimelineImageOutput[];
}
| {
kind: "work-toggle";
id: string;
@@ -167,6 +178,7 @@ export type MessagesTimelineRow =
showAssistantCopyButton: boolean;
assistantCopyStreaming: boolean;
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
assistantImageOutputs?: TimelineImageOutput[] | undefined;
revertTurnCount?: number | undefined;
}
| {
@@ -247,6 +259,128 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
return new Set(lastAssistantMessageIdByResponseKey.values());
}
function appendImageOutputRows(input: {
rows: ReadonlyArray<MessagesTimelineRow>;
timelineEntries: ReadonlyArray<TimelineEntry>;
terminalAssistantMessageIds: ReadonlySet<string>;
unsettledTurnId: TurnId | null;
}): MessagesTimelineRow[] {
const outputsByTurnId = new Map<TurnId, TimelineImageOutput[]>();
const unscopedOutputs: TimelineImageOutput[] = [];
const seenImagePathsByTurnId = new Map<TurnId | null, Set<string>>();
for (const timelineEntry of input.timelineEntries) {
if (timelineEntry.kind !== "work") {
continue;
}
const entry = timelineEntry.entry;
if (entry.itemType !== "image_view" || !entry.imagePath) {
continue;
}
if (entry.turnId === input.unsettledTurnId) {
continue;
}
const turnId = entry.turnId ?? null;
const seenImagePaths = seenImagePathsByTurnId.get(turnId) ?? new Set<string>();
if (seenImagePaths.has(entry.imagePath)) {
continue;
}
seenImagePaths.add(entry.imagePath);
seenImagePathsByTurnId.set(turnId, seenImagePaths);
const output = {
entry,
imagePath: entry.imagePath,
};
if (!entry.turnId) {
unscopedOutputs.push(output);
continue;
}
const existing = outputsByTurnId.get(entry.turnId);
if (existing) {
existing.push(output);
} else {
outputsByTurnId.set(entry.turnId, [output]);
}
}
if (outputsByTurnId.size === 0 && unscopedOutputs.length === 0) {
return [...input.rows];
}
const toRow = (
id: string,
images: TimelineImageOutput[],
): Extract<MessagesTimelineRow, { kind: "image-output" }> => ({
kind: "image-output",
id,
createdAt: images.at(-1)?.entry.createdAt ?? "",
images,
});
const terminalRowIdByTurnId = new Map<TurnId, string>();
const lastRowIdByTurnId = new Map<TurnId, string>();
for (const row of input.rows) {
if (row.kind === "turn-fold") {
lastRowIdByTurnId.set(row.turnId, row.id);
continue;
}
if (row.kind === "work") {
for (const entry of row.groupedEntries) {
if (entry.turnId) {
lastRowIdByTurnId.set(entry.turnId, row.id);
}
}
continue;
}
if (row.kind !== "message") {
continue;
}
const message = row.message;
if (message.role !== "assistant" || !message.turnId) {
continue;
}
lastRowIdByTurnId.set(message.turnId, row.id);
if (input.terminalAssistantMessageIds.has(message.id)) {
terminalRowIdByTurnId.set(message.turnId, row.id);
}
}
const outputsAfterRowId = new Map<
string,
Array<Extract<MessagesTimelineRow, { kind: "image-output" }>>
>();
const outputsByAssistantRowId = new Map<string, TimelineImageOutput[]>();
const trailingOutputs: Array<Extract<MessagesTimelineRow, { kind: "image-output" }>> = [];
if (unscopedOutputs.length > 0) {
trailingOutputs.push(toRow("image-output:unscoped", unscopedOutputs));
}
for (const [turnId, outputs] of outputsByTurnId) {
const terminalRowId = terminalRowIdByTurnId.get(turnId);
if (terminalRowId) {
outputsByAssistantRowId.set(terminalRowId, outputs);
continue;
}
const outputRow = toRow(`image-output:turn:${turnId}`, outputs);
const targetRowId = lastRowIdByTurnId.get(turnId) ?? null;
if (!targetRowId) {
trailingOutputs.push(outputRow);
continue;
}
outputsAfterRowId.set(targetRowId, [outputRow]);
}
return input.rows
.flatMap((row) => [
row.kind === "message" && outputsByAssistantRowId.has(row.id)
? {
...row,
assistantImageOutputs: outputsByAssistantRowId.get(row.id),
}
: row,
...(outputsAfterRowId.get(row.id) ?? []),
])
.concat(trailingOutputs);
}
interface TurnFold {
turnId: TurnId;
anchorEntryId: string;
@@ -563,15 +697,22 @@ export function deriveMessagesTimelineRows(input: {
});
}
const rowsWithImageOutputs = appendImageOutputRows({
rows: nextRows,
timelineEntries: input.timelineEntries,
terminalAssistantMessageIds,
unsettledTurnId,
});
if (input.isWorking) {
nextRows.push({
rowsWithImageOutputs.push({
kind: "working",
id: "working-indicator-row",
createdAt: input.activeTurnStartedAt,
});
}
return nextRows;
return rowsWithImageOutputs;
}
export function computeStableMessagesTimelineRows(
@@ -594,6 +735,21 @@ export function computeStableMessagesTimelineRows(
return anyChanged ? { byId: next, result } : previous;
}
function imageOutputsEqual(
a: ReadonlyArray<TimelineImageOutput> | undefined,
b: ReadonlyArray<TimelineImageOutput> | undefined,
): boolean {
const aImages = a ?? [];
const bImages = b ?? [];
return (
aImages.length === bImages.length &&
aImages.every(
(image, index) =>
image.entry === bImages[index]?.entry && image.imagePath === bImages[index]?.imagePath,
)
);
}
/** Shallow field comparison per row variant — avoids deep equality cost. */
function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
if (a.kind !== b.kind || a.id !== b.id) return false;
@@ -610,6 +766,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
case "proposed-plan":
return a.proposedPlan === (b as typeof a).proposedPlan;
case "image-output": {
const bi = b as typeof a;
return imageOutputsEqual(a.images, bi.images);
}
case "work":
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
@@ -633,6 +794,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
a.assistantCopyStreaming === bm.assistantCopyStreaming &&
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
imageOutputsEqual(a.assistantImageOutputs, bm.assistantImageOutputs) &&
a.revertTurnCount === bm.revertTurnCount
);
}
@@ -122,6 +122,13 @@ vi.mock("@pierre/diffs/react", () => {
return { FileDiff: MockFileDiff };
});
vi.mock("~/assets/assetUrls", () => ({
useAssetUrlState: () => ({
_tag: "Success",
url: "https://environment.example/api/assets/image-token/tool-output.png",
}),
}));
function matchMedia() {
return {
matches: false,
@@ -655,4 +662,109 @@ describe("MessagesTimeline", () => {
expect(markup).toContain("lucide-x");
expect(markup).toContain('aria-label="Tool call failed"');
});
it("renders deduplicated image view output as a compact gallery row", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const assistantMessageId = MessageId.make("assistant-final");
const turnId = TurnId.make("turn-image-view");
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
workspaceRoot="/repo"
turnDiffSummaryByAssistantMessageId={
new Map([
[
assistantMessageId,
{
turnId,
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.make("checkpoint-image-view"),
status: "ready",
files: [{ path: "image.ts", kind: "modified", additions: 2, deletions: 1 }],
assistantMessageId,
completedAt: "2026-03-17T19:12:30.000Z",
},
],
])
}
timelineEntries={[
{
id: "entry-image-view",
kind: "work",
createdAt: "2026-03-17T19:12:28.000Z",
entry: {
id: "image-view-complete",
createdAt: "2026-03-17T19:12:28.000Z",
turnId,
label: "Image view",
tone: "tool",
itemType: "image_view",
imagePath: "/tmp/tool-output.png",
toolLifecycleStatus: "completed",
},
},
{
id: "entry-image-view-duplicate",
kind: "work",
createdAt: "2026-03-17T19:12:28.100Z",
entry: {
id: "image-view-duplicate",
createdAt: "2026-03-17T19:12:28.100Z",
turnId,
label: "Image view",
tone: "tool",
itemType: "image_view",
imagePath: "/tmp/tool-output.png",
toolLifecycleStatus: "completed",
},
},
{
id: "entry-image-view-second",
kind: "work",
createdAt: "2026-03-17T19:12:28.200Z",
entry: {
id: "image-view-second",
createdAt: "2026-03-17T19:12:28.200Z",
turnId,
label: "Image view",
tone: "tool",
itemType: "image_view",
imagePath: "/tmp/second-output.png",
toolLifecycleStatus: "completed",
},
},
{
id: "entry-assistant-final",
kind: "message",
createdAt: "2026-03-17T19:12:29.000Z",
message: {
id: assistantMessageId,
role: "assistant",
text: "Here is the generated image.",
turnId,
createdAt: "2026-03-17T19:12:29.000Z",
updatedAt: "2026-03-17T19:12:30.000Z",
streaming: false,
},
},
]}
/>,
);
expect(markup).toContain('data-image-view-activity-id="image-view-complete"');
expect(markup).not.toContain('data-image-view-activity-id="image-view-duplicate"');
expect(markup).toContain('data-image-view-activity-id="image-view-second"');
expect(markup).toContain('aria-label="Image outputs"');
expect(markup).toContain("size-32");
expect(markup).toContain(
'src="https://environment.example/api/assets/image-token/tool-output.png"',
);
expect(markup).toContain('aria-label="Preview tool-output.png"');
expect(markup).toContain('aria-label="Preview second-output.png"');
const responseIndex = markup.indexOf("Here is the generated image.");
const imageIndex = markup.indexOf('data-image-view-activity-id="image-view-complete"');
const changedFilesIndex = markup.indexOf("1 changed file");
expect(responseIndex).toBeLessThan(imageIndex);
expect(imageIndex).toBeLessThan(changedFilesIndex);
});
});
@@ -1,4 +1,5 @@
import {
EventId,
type EnvironmentId,
type MessageId,
type ScopedThreadRef,
@@ -77,6 +78,7 @@ import {
resolveTimelineMinimapInteractiveWidth,
resolveTimelineMinimapTopPercent,
type StableMessagesTimelineRowsState,
type TimelineImageOutput,
type MessagesTimelineRow,
TIMELINE_MINIMAP_MIN_ITEMS,
type TimelineLatestTurn,
@@ -96,6 +98,7 @@ import {
type ParsedPreviewAnnotation,
} from "~/lib/previewAnnotation";
import { cn } from "~/lib/utils";
import { useAssetUrlState } from "~/assets/assetUrls";
import { useUiStateStore } from "~/uiStateStore";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { formatChatTimestampTooltip, formatShortTimestamp } from "../../timestampFormat";
@@ -856,6 +859,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
{row.kind === "work-toggle" ? <WorkGroupToggleTimelineRow row={row} /> : null}
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
{row.kind === "image-output" ? <ImageOutputTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "assistant" ? (
<AssistantTimelineRow row={row} />
@@ -1029,6 +1033,13 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
isStreaming={Boolean(row.message.streaming)}
skills={ctx.skills}
/>
{ctx.threadRef && row.assistantImageOutputs?.length ? (
<ImageOutputGallery
images={row.assistantImageOutputs}
threadRef={ctx.threadRef}
className="mt-3"
/>
) : null}
<AssistantChangedFilesSection
turnSummary={row.assistantTurnDiffSummary}
routeThreadKey={ctx.routeThreadKey}
@@ -1921,6 +1932,90 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
function imageFileName(path: string): string {
return path.split(/[\\/]/).at(-1) || "Image";
}
function ImageOutputTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "image-output" }> }) {
const { threadRef } = use(TimelineRowCtx);
if (!threadRef) return null;
return <ImageOutputGallery images={row.images} threadRef={threadRef} />;
}
function ImageOutputGallery({
images,
threadRef,
className,
}: {
images: TimelineImageOutput[];
threadRef: ScopedThreadRef;
className?: string;
}) {
return (
<article
className={cn("flex max-w-full items-start gap-2 overflow-x-auto px-1 pb-1", className)}
aria-label={images.length === 1 ? "Image output" : "Image outputs"}
>
{images.map((image) => (
<ImageOutputThumbnail key={image.imagePath} image={image} threadRef={threadRef} />
))}
</article>
);
}
function ImageOutputThumbnail({
image,
threadRef,
}: {
image: TimelineImageOutput;
threadRef: ScopedThreadRef;
}) {
const { activeThreadEnvironmentId, onImageExpand } = use(TimelineRowCtx);
const imageName = imageFileName(image.imagePath);
const assetUrl = useAssetUrlState(activeThreadEnvironmentId, {
_tag: "thread-image",
threadId: threadRef.threadId,
activityId: EventId.make(image.entry.id),
});
const [failedUrl, setFailedUrl] = useState<string | null>(null);
const loadedUrl = assetUrl._tag === "Success" && assetUrl.url !== failedUrl ? assetUrl.url : null;
const failed = assetUrl._tag === "Failure" || failedUrl !== null;
return (
<div className="shrink-0" data-image-view-activity-id={image.entry.id}>
{loadedUrl ? (
<button
type="button"
className="block size-32 cursor-zoom-in overflow-hidden rounded-xl border border-border/70 bg-muted/20 p-1 transition-colors hover:border-border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70"
aria-label={`Preview ${imageName}`}
onClick={() =>
onImageExpand({
images: [{ src: loadedUrl, name: imageName }],
index: 0,
})
}
>
<img
src={loadedUrl}
alt={imageName}
className="block size-full rounded-md object-contain"
onError={() => setFailedUrl(loadedUrl)}
/>
</button>
) : failed ? (
<div className="flex size-32 items-center justify-center rounded-xl border border-dashed border-border/70 bg-muted/20 px-3 text-center text-xs text-muted-foreground">
Image no longer available
</div>
) : (
<div
className="size-32 animate-pulse rounded-xl border border-border/50 bg-muted/35"
aria-label={`Loading ${imageName}`}
/>
)}
</div>
);
}
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
+62
View File
@@ -995,6 +995,68 @@ describe("deriveWorkLogEntries", () => {
expect(entry?.toolData).toEqual(item);
});
it("extracts the local path from completed image view activities", () => {
const imagePath = "/tmp/codex-preview.png";
const [entry] = deriveWorkLogEntries([
makeActivity({
id: "image-view-complete",
kind: "tool.completed",
summary: "Image view",
payload: {
itemType: "image_view",
status: "completed",
title: "Image view",
detail: imagePath,
data: {
item: {
id: "call-image-1",
path: imagePath,
type: "imageView",
},
},
},
}),
]);
expect(entry).toMatchObject({
id: "image-view-complete",
itemType: "image_view",
imagePath,
toolLifecycleStatus: "completed",
});
});
it("extracts the saved path from completed image generation activities", () => {
const imagePath = "/Users/test/.codex/generated_images/thread-1/generated.png";
const [entry] = deriveWorkLogEntries([
makeActivity({
id: "image-generation-complete",
kind: "tool.completed",
summary: "Image view",
payload: {
itemType: "image_view",
data: {
item: {
id: "call-image-generation-1",
result: "base64-image-data",
revisedPrompt: "A generated image",
savedPath: imagePath,
status: "completed",
type: "imageGeneration",
},
},
},
}),
]);
expect(entry).toMatchObject({
id: "image-generation-complete",
itemType: "image_view",
imagePath,
toolLifecycleStatus: "completed",
});
});
it("unwraps PowerShell command wrappers for displayed command text", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
+16
View File
@@ -69,6 +69,7 @@ export interface WorkLogEntry {
command?: string;
rawCommand?: string;
changedFiles?: ReadonlyArray<string>;
imagePath?: string;
tone: "thinking" | "tool" | "info" | "error";
toolTitle?: string;
toolData?: unknown;
@@ -740,6 +741,19 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
entry.toolData = data.item;
}
}
if (itemType === "image_view") {
const data = asRecord(payload?.data);
const item = asRecord(data?.item);
const imagePath =
item?.type === "imageView"
? asTrimmedString(item.path)
: item?.type === "imageGeneration"
? asTrimmedString(item.savedPath)
: null;
if (imagePath) {
entry.imagePath = imagePath;
}
}
if (itemType) {
entry.itemType = itemType;
}
@@ -811,6 +825,7 @@ function mergeDerivedWorkLogEntries(
const detail = next.detail ?? previous.detail;
const command = next.command ?? previous.command;
const rawCommand = next.rawCommand ?? previous.rawCommand;
const imagePath = next.imagePath ?? previous.imagePath;
const toolTitle = next.toolTitle ?? previous.toolTitle;
const itemType = next.itemType ?? previous.itemType;
const requestKind = next.requestKind ?? previous.requestKind;
@@ -824,6 +839,7 @@ function mergeDerivedWorkLogEntries(
...(detail ? { detail } : {}),
...(command ? { command } : {}),
...(rawCommand ? { rawCommand } : {}),
...(imagePath ? { imagePath } : {}),
...(changedFiles.length > 0 ? { changedFiles } : {}),
...(toolTitle ? { toolTitle } : {}),
...(itemType ? { itemType } : {}),
+30 -1
View File
@@ -1,6 +1,6 @@
import * as Schema from "effect/Schema";
import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { EventId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
const ASSET_PATH_MAX_LENGTH = 1024;
@@ -16,6 +16,10 @@ export const AssetResource = Schema.Union([
Schema.TaggedStruct("browser-artifact", {
fileName: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
}),
Schema.TaggedStruct("thread-image", {
threadId: ThreadId,
activityId: EventId,
}),
Schema.TaggedStruct("project-favicon", {
cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),
}),
@@ -148,6 +152,29 @@ export class AssetBrowserArtifactNotFoundError extends Schema.TaggedErrorClass<A
}
}
export class AssetThreadImageNotFoundError extends Schema.TaggedErrorClass<AssetThreadImageNotFoundError>()(
"AssetThreadImageNotFoundError",
{
resource: AssetResource,
},
) {
override get message(): string {
return "Image view asset was not found.";
}
}
export class AssetThreadImageResolutionError extends Schema.TaggedErrorClass<AssetThreadImageResolutionError>()(
"AssetThreadImageResolutionError",
{
resource: AssetResource,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to resolve image view asset.";
}
}
export class AssetProjectFaviconResolutionError extends Schema.TaggedErrorClass<AssetProjectFaviconResolutionError>()(
"AssetProjectFaviconResolutionError",
{
@@ -206,6 +233,8 @@ export const AssetAccessError = Schema.Union([
AssetWorkspaceResolutionError,
AssetAttachmentNotFoundError,
AssetBrowserArtifactNotFoundError,
AssetThreadImageNotFoundError,
AssetThreadImageResolutionError,
AssetProjectFaviconResolutionError,
AssetProjectFaviconInspectionError,
AssetProjectFaviconNotFoundError,