Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58f9832f2b | ||
|
|
efede3661a | ||
|
|
cf121a7260 | ||
|
|
e3edf9bc8e | ||
|
|
6f9e892da8 | ||
|
|
f3c19bfe7c | ||
|
|
ae0c21c3f1 | ||
|
|
ad9e4fa446 | ||
|
|
44dd6f67f6 |
No files matched your search
@@ -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";
|
||||
@@ -70,6 +70,104 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues exact-file workspace URLs for video files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-video-",
|
||||
});
|
||||
const videoPath = path.join(root, "recordings", "demo.webm");
|
||||
yield* fileSystem.makeDirectory(path.join(root, "recordings"), { recursive: true });
|
||||
yield* fileSystem.writeFileString(videoPath, "webm-bytes");
|
||||
const canonicalVideoPath = yield* fileSystem.realPath(videoPath);
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: "recordings/demo.webm",
|
||||
},
|
||||
workspaceRoot: root,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const separatorIndex = suffix.indexOf("/");
|
||||
const token = suffix.slice(0, separatorIndex);
|
||||
|
||||
expect(yield* resolveAsset(token, "demo.webm")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalVideoPath,
|
||||
});
|
||||
// Exact-file claim: the token must not grant access to sibling files.
|
||||
expect(yield* resolveAsset(token, "other.webm")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues and resolves browser artifact URLs by file name only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const artifactPath = path.join(config.browserArtifactsDir, "browser-recording-demo.webm");
|
||||
yield* fileSystem.writeFileString(artifactPath, "webm-bytes");
|
||||
const canonicalArtifactPath = yield* fileSystem.realPath(artifactPath);
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(config.browserArtifactsDir, "notes.txt"),
|
||||
"not media",
|
||||
);
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "browser-recording-demo.webm" },
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
expect(yield* resolveAsset(token, "browser-recording-demo.webm")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalArtifactPath,
|
||||
});
|
||||
|
||||
// Non-media files and traversal-style names are not issuable.
|
||||
const nonMedia = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "notes.txt" },
|
||||
}).pipe(Effect.flip);
|
||||
expect(nonMedia._tag).toBe("AssetBrowserArtifactNotFoundError");
|
||||
const traversal = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "../state.sqlite" },
|
||||
}).pipe(Effect.flip);
|
||||
expect(traversal._tag).toBe("AssetBrowserArtifactNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("serves workspace files in directories whose name starts with ..", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-dotdot-name-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "..screenshots"), { recursive: true });
|
||||
const imagePath = path.join(root, "..screenshots", "capture.png");
|
||||
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
|
||||
const canonicalImagePath = yield* fileSystem.realPath(imagePath);
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "workspace-file",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
path: "..screenshots/capture.png",
|
||||
},
|
||||
workspaceRoot: root,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
expect(yield* resolveAsset(token, "capture.png")).toEqual({
|
||||
kind: "file",
|
||||
path: canonicalImagePath,
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects workspace files outside the authorized root", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -206,6 +304,168 @@ 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("rejects image view symlinks that escape to non-image files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-image-view-symlink-",
|
||||
});
|
||||
const secretPath = path.join(directory, "secret.env");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
const disguisedPath = path.join(directory, "disguised.png");
|
||||
yield* fileSystem.symlink(secretPath, disguisedPath);
|
||||
const resource = {
|
||||
_tag: "thread-image" as const,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activityId: EventId.make("activity-1"),
|
||||
};
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource,
|
||||
threadImagePath: disguisedPath,
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("AssetThreadImageNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("re-resolves image view claims so post-issuance swaps are rejected", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-image-view-swap-",
|
||||
});
|
||||
const imagePath = path.join(directory, "tool-output.png");
|
||||
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
|
||||
const outsidePath = path.join(directory, "secret.png");
|
||||
yield* fileSystem.writeFileString(outsidePath, "SECRET");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: {
|
||||
_tag: "thread-image" as const,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
activityId: EventId.make("activity-1"),
|
||||
},
|
||||
threadImagePath: imagePath,
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
|
||||
// Swap the issued file for a symlink pointing elsewhere.
|
||||
yield* fileSystem.remove(imagePath);
|
||||
yield* fileSystem.symlink(outsidePath, imagePath);
|
||||
expect(yield* resolveAsset(token, "tool-output.png")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects browser artifact symlinks that escape the artifacts directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const outsideDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-artifact-outside-",
|
||||
});
|
||||
const secretPath = path.join(outsideDir, "secret.png");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
yield* fileSystem.symlink(secretPath, path.join(config.browserArtifactsDir, "escape.png"));
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "escape.png" },
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("AssetBrowserArtifactNotFoundError");
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("re-resolves browser artifact claims so post-issuance swaps are rejected", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
yield* fileSystem.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
||||
const outsideDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-artifact-swap-",
|
||||
});
|
||||
const secretPath = path.join(outsideDir, "secret.png");
|
||||
yield* fileSystem.writeFileString(secretPath, "SECRET=value");
|
||||
const artifactPath = path.join(config.browserArtifactsDir, "swapped.png");
|
||||
yield* fileSystem.writeFile(artifactPath, new Uint8Array([137, 80, 78, 71]));
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "browser-artifact", fileName: "swapped.png" },
|
||||
});
|
||||
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const token = suffix.slice(0, suffix.indexOf("/"));
|
||||
|
||||
yield* fileSystem.remove(artifactPath);
|
||||
yield* fileSystem.symlink(secretPath, artifactPath);
|
||||
expect(yield* resolveAsset(token, "swapped.png")).toBeNull();
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues project favicon capabilities with a signed fallback", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import type { AssetResource } from "@t3tools/contracts";
|
||||
import {
|
||||
AssetAttachmentNotFoundError,
|
||||
AssetBrowserArtifactNotFoundError,
|
||||
AssetPreviewTypeValidationError,
|
||||
AssetProjectFaviconInspectionError,
|
||||
AssetProjectFaviconNotFoundError,
|
||||
AssetProjectFaviconResolutionError,
|
||||
AssetSigningKeyLoadError,
|
||||
AssetThreadImageNotFoundError,
|
||||
AssetThreadImageResolutionError,
|
||||
AssetWorkspaceAssetInspectionError,
|
||||
AssetWorkspaceAssetNotFoundError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
@@ -16,8 +19,10 @@ import {
|
||||
import {
|
||||
isWorkspaceImagePreviewPath,
|
||||
isWorkspacePreviewEntryPath,
|
||||
isWorkspaceVideoPreviewPath,
|
||||
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
|
||||
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
|
||||
WORKSPACE_VIDEO_PREVIEW_EXTENSIONS,
|
||||
} from "@t3tools/shared/filePreview";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import * as Clock from "effect/Clock";
|
||||
@@ -47,6 +52,7 @@ const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
const PREVIEW_ASSET_EXTENSIONS = new Set([
|
||||
...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
|
||||
...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
|
||||
...WORKSPACE_VIDEO_PREVIEW_EXTENSIONS,
|
||||
".css",
|
||||
".js",
|
||||
".mjs",
|
||||
@@ -77,6 +83,18 @@ const AssetClaimsSchema = Schema.Union([
|
||||
attachmentId: Schema.String,
|
||||
expiresAt: Schema.Number,
|
||||
}),
|
||||
Schema.Struct({
|
||||
version: Schema.Literal(1),
|
||||
kind: Schema.Literal("browser-artifact"),
|
||||
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"),
|
||||
@@ -120,6 +138,64 @@ const optionOnNotFound = <A, R>(
|
||||
}),
|
||||
);
|
||||
|
||||
function normalizeBrowserArtifactFileName(fileName: string): string | null {
|
||||
const trimmed = fileName.trim();
|
||||
if (
|
||||
trimmed.length === 0 ||
|
||||
trimmed.includes("/") ||
|
||||
trimmed.includes("\\") ||
|
||||
trimmed.includes("\0") ||
|
||||
trimmed.startsWith(".")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (!isWorkspaceImagePreviewPath(trimmed) && !isWorkspaceVideoPreviewPath(trimmed)) {
|
||||
return null;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const statIsFile = (path: string) =>
|
||||
FileSystem.FileSystem.pipe(
|
||||
Effect.flatMap((fileSystem) => optionOnNotFound(fileSystem.stat(path))),
|
||||
Effect.map((info) => Option.isSome(info) && info.value.type === "File"),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
/**
|
||||
* Resolve a browser artifact to its canonical path, rejecting anything that
|
||||
* escapes the artifacts directory. Names are validated before and after
|
||||
* `realPath` so a symlink with an allowed media name cannot redirect to an
|
||||
* arbitrary (or non-media) server-readable file.
|
||||
*/
|
||||
const resolveCanonicalBrowserArtifact = Effect.fn("AssetAccess.resolveCanonicalBrowserArtifact")(
|
||||
function* (fileName: string) {
|
||||
const normalized = normalizeBrowserArtifactFileName(fileName);
|
||||
if (!normalized) return null;
|
||||
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const [canonicalDir, canonicalFile] = yield* Effect.all([
|
||||
optionOnNotFound(fileSystem.realPath(config.browserArtifactsDir)),
|
||||
optionOnNotFound(fileSystem.realPath(path.join(config.browserArtifactsDir, normalized))),
|
||||
]).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to resolve the browser artifact path.", { fileName, cause }),
|
||||
),
|
||||
Effect.orElseSucceed(() => [Option.none<string>(), Option.none<string>()] as const),
|
||||
);
|
||||
if (Option.isNone(canonicalDir) || Option.isNone(canonicalFile)) return null;
|
||||
|
||||
// Artifacts are stored flat, so the canonical parent must be the
|
||||
// canonical artifacts directory itself.
|
||||
if (path.dirname(canonicalFile.value) !== canonicalDir.value) return null;
|
||||
if (!normalizeBrowserArtifactFileName(path.basename(canonicalFile.value))) return null;
|
||||
|
||||
return (yield* statIsFile(canonicalFile.value)) ? canonicalFile.value : null;
|
||||
},
|
||||
);
|
||||
|
||||
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
|
||||
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
@@ -140,7 +216,16 @@ const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWor
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const relative = path.relative(canonicalRoot.value, canonicalFile.value);
|
||||
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
|
||||
// `..name` is an ordinary in-root directory, so only a real `..` segment
|
||||
// counts as an escape.
|
||||
if (
|
||||
relative === "" ||
|
||||
relative === ".." ||
|
||||
relative.startsWith(`..${path.sep}`) ||
|
||||
path.isAbsolute(relative)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));
|
||||
return Option.isSome(info) && info.value.type === "File" ? canonicalFile.value : null;
|
||||
@@ -165,6 +250,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;
|
||||
@@ -234,21 +320,23 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
}),
|
||||
),
|
||||
);
|
||||
claims = isWorkspaceImagePreviewPath(resolved.relativePath)
|
||||
? {
|
||||
version: 1,
|
||||
kind: "workspace-file-exact",
|
||||
workspaceRoot: canonicalWorkspaceRoot,
|
||||
relativePath: resolved.relativePath,
|
||||
expiresAt,
|
||||
}
|
||||
: {
|
||||
version: 1,
|
||||
kind: "workspace-file",
|
||||
workspaceRoot: canonicalWorkspaceRoot,
|
||||
baseRelativePath: path.dirname(resolved.relativePath),
|
||||
expiresAt,
|
||||
};
|
||||
claims =
|
||||
isWorkspaceImagePreviewPath(resolved.relativePath) ||
|
||||
isWorkspaceVideoPreviewPath(resolved.relativePath)
|
||||
? {
|
||||
version: 1,
|
||||
kind: "workspace-file-exact",
|
||||
workspaceRoot: canonicalWorkspaceRoot,
|
||||
relativePath: resolved.relativePath,
|
||||
expiresAt,
|
||||
}
|
||||
: {
|
||||
version: 1,
|
||||
kind: "workspace-file",
|
||||
workspaceRoot: canonicalWorkspaceRoot,
|
||||
baseRelativePath: path.dirname(resolved.relativePath),
|
||||
expiresAt,
|
||||
};
|
||||
fileName = path.basename(resolved.relativePath);
|
||||
break;
|
||||
}
|
||||
@@ -272,6 +360,78 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
fileName = path.basename(attachmentPath);
|
||||
break;
|
||||
}
|
||||
case "browser-artifact": {
|
||||
const artifactFileName = normalizeBrowserArtifactFileName(input.resource.fileName);
|
||||
if (!artifactFileName || !(yield* resolveCanonicalBrowserArtifact(artifactFileName))) {
|
||||
return yield* new AssetBrowserArtifactNotFoundError({
|
||||
resource: input.resource,
|
||||
});
|
||||
}
|
||||
claims = {
|
||||
version: 1,
|
||||
kind: "browser-artifact",
|
||||
fileName: artifactFileName,
|
||||
expiresAt,
|
||||
};
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// The extension check above ran on the pre-realPath input; re-check the
|
||||
// canonical target so a symlink named `*.png` cannot smuggle out an
|
||||
// arbitrary non-image file.
|
||||
if (
|
||||
Option.isNone(info) ||
|
||||
info.value.type !== "File" ||
|
||||
!isWorkspaceImagePreviewPath(canonicalPath.value)
|
||||
) {
|
||||
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(
|
||||
@@ -388,6 +548,46 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
|
||||
: null;
|
||||
}
|
||||
|
||||
if (claims.kind === "browser-artifact") {
|
||||
// Re-resolved on every request: a signed token must not keep serving a
|
||||
// path that was replaced by a symlink after issuance.
|
||||
const artifactPath = yield* resolveCanonicalBrowserArtifact(claims.fileName);
|
||||
return artifactPath ? ({ kind: "file", path: artifactPath } satisfies ResolvedAsset) : null;
|
||||
}
|
||||
|
||||
if (claims.kind === "thread-image") {
|
||||
const decodedPath = decodeRelativePath(relativePath);
|
||||
const path = yield* Path.Path;
|
||||
if (decodedPath !== path.basename(claims.path)) return null;
|
||||
if (!isWorkspaceImagePreviewPath(claims.path)) return null;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
// The claim stores the path that was canonical at issuance. Re-canonicalize
|
||||
// on every request so a file later replaced by a symlink cannot redirect
|
||||
// this token to somewhere else on disk.
|
||||
const canonicalPath = yield* optionOnNotFound(fileSystem.realPath(claims.path)).pipe(
|
||||
Effect.tapError((cause) =>
|
||||
Effect.logError("Failed to resolve image view asset.", {
|
||||
path: claims.path,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => Option.none()),
|
||||
);
|
||||
if (Option.isNone(canonicalPath) || canonicalPath.value !== claims.path) return null;
|
||||
const info = yield* optionOnNotFound(fileSystem.stat(canonicalPath.value)).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: canonicalPath.value } satisfies ResolvedAsset)
|
||||
: null;
|
||||
}
|
||||
|
||||
if (claims.kind === "project-favicon") {
|
||||
if (claims.relativePath === null) return null;
|
||||
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
|
||||
|
||||
@@ -33,6 +33,12 @@ export interface ServerDerivedPaths {
|
||||
readonly providerStatusCacheDir: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
/**
|
||||
* Browser evidence artifacts (screenshots/recordings). The desktop app
|
||||
* writes recordings here too — both derive `<baseDir>/(dev|userdata)`, so
|
||||
* in the standard local setup this is the same directory.
|
||||
*/
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly logsDir: string;
|
||||
readonly serverLogPath: string;
|
||||
readonly serverTracePath: string;
|
||||
@@ -108,6 +114,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
);
|
||||
const dbPath = join(stateDir, "state.sqlite");
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const browserArtifactsDir = join(stateDir, "browser-artifacts");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
const providerLogsDir = join(logsDir, "provider");
|
||||
const providerStatusCacheDir = join(baseDir, "caches");
|
||||
@@ -119,6 +126,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
providerStatusCacheDir,
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
browserArtifactsDir,
|
||||
logsDir,
|
||||
serverLogPath: join(logsDir, "server.log"),
|
||||
serverTracePath: join(logsDir, "server.trace.ndjson"),
|
||||
@@ -143,6 +151,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.browserArtifactsDir, { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { NodeHttpServer } from "@effect/platform-node";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewTabId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { McpSchema, McpServer } from "effect/unstable/ai";
|
||||
import { HttpBody, HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import * as McpHttpServer from "./McpHttpServer.ts";
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
@@ -16,6 +31,7 @@ const environmentId = EnvironmentId.make("environment-mcp-test");
|
||||
const threadId = ThreadId.make("thread-mcp-test");
|
||||
const tabId = PreviewTabId.make("tab-mcp-test");
|
||||
const alternateTabId = PreviewTabId.make("tab-mcp-alternate");
|
||||
const testWorkspaceRoot = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "mcp-snapshot-test-"));
|
||||
const invocation = {
|
||||
environmentId,
|
||||
threadId,
|
||||
@@ -33,9 +49,44 @@ const client = McpSchema.McpServerClient.of({
|
||||
},
|
||||
getClient: Effect.die("unused"),
|
||||
});
|
||||
const stubProjectionSnapshotQueryLayer = Layer.succeed(
|
||||
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
|
||||
{
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: (contextThreadId) =>
|
||||
Effect.succeed(
|
||||
contextThreadId === threadId
|
||||
? Option.some({
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-mcp-test"),
|
||||
workspaceRoot: testWorkspaceRoot,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
})
|
||||
: Option.none(),
|
||||
),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
},
|
||||
);
|
||||
|
||||
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
|
||||
Layer.provideMerge(stubProjectionSnapshotQueryLayer),
|
||||
Layer.provideMerge(WorkspacePaths.layer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-http-test-" })),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
it("normalizes empty successful notification responses to accepted", () => {
|
||||
@@ -209,8 +260,10 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
|
||||
|
||||
const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
|
||||
expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
|
||||
expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
|
||||
// save/savePath write files, so the snapshot tool is not read-only.
|
||||
expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(false);
|
||||
expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(false);
|
||||
expect(snapshotTool?.tool.annotations?.destructiveHint).toBe(false);
|
||||
expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
|
||||
|
||||
const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
|
||||
@@ -269,3 +322,128 @@ it.effect("registers annotated tools and preserves authenticated request context
|
||||
}),
|
||||
).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("writes snapshot screenshots into the workspace when savePath is set", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const events = yield* broker.connect({
|
||||
clientId: "mcp-save-client",
|
||||
environmentId,
|
||||
});
|
||||
yield* Stream.runForEach(events, (event) =>
|
||||
event.type === "connected"
|
||||
? Effect.void
|
||||
: broker.respond({
|
||||
clientId: "mcp-save-client",
|
||||
connectionId: event.connectionId,
|
||||
requestId: event.request.requestId,
|
||||
ok: true,
|
||||
result: {
|
||||
url: "http://example.test/",
|
||||
title: "Example",
|
||||
loading: false,
|
||||
visibleText: "Example",
|
||||
interactiveElements: [],
|
||||
accessibilityTree: {},
|
||||
consoleEntries: [],
|
||||
networkEntries: [],
|
||||
actionTimeline: [],
|
||||
screenshot: {
|
||||
mimeType: "image/png",
|
||||
data: Buffer.from("png-bytes").toString("base64"),
|
||||
width: 10,
|
||||
height: 5,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
const callSnapshot = (savePath: string) =>
|
||||
server
|
||||
.callTool({ name: "preview_snapshot", arguments: { savePath } })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
|
||||
const saved = yield* callSnapshot("evidence/login.png");
|
||||
expect(saved.isError).toBe(false);
|
||||
expect(saved.structuredContent).toMatchObject({
|
||||
savedScreenshotPath: "evidence/login.png",
|
||||
});
|
||||
expect(
|
||||
NodeFS.readFileSync(NodePath.join(testWorkspaceRoot, "evidence/login.png"), "utf8"),
|
||||
).toBe("png-bytes");
|
||||
|
||||
const wrongExtension = yield* callSnapshot("evidence/login.txt");
|
||||
expect(wrongExtension.isError).toBe(true);
|
||||
|
||||
const traversal = yield* callSnapshot("../outside.png");
|
||||
expect(traversal.isError).toBe(true);
|
||||
expect(NodeFS.existsSync(NodePath.join(testWorkspaceRoot, "..", "outside.png"))).toBe(false);
|
||||
|
||||
// A directory symlink pointing outside the workspace must be rejected
|
||||
// before mkdir creates anything at the symlink target.
|
||||
const outsideDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "mcp-outside-"));
|
||||
NodeFS.symlinkSync(outsideDir, NodePath.join(testWorkspaceRoot, "escape-dir"));
|
||||
const dirSymlink = yield* callSnapshot("escape-dir/sub/leak.png");
|
||||
expect(dirSymlink.isError).toBe(true);
|
||||
expect(NodeFS.existsSync(NodePath.join(outsideDir, "sub"))).toBe(false);
|
||||
|
||||
// An existing file symlink at the destination must not be followed
|
||||
// outside the workspace.
|
||||
const victimPath = NodePath.join(outsideDir, "victim.png");
|
||||
NodeFS.writeFileSync(victimPath, "original");
|
||||
NodeFS.mkdirSync(NodePath.join(testWorkspaceRoot, "evidence"), { recursive: true });
|
||||
NodeFS.symlinkSync(victimPath, NodePath.join(testWorkspaceRoot, "evidence", "escape.png"));
|
||||
const fileSymlink = yield* callSnapshot("evidence/escape.png");
|
||||
expect(fileSymlink.isError).toBe(true);
|
||||
expect(NodeFS.readFileSync(victimPath, "utf8")).toBe("original");
|
||||
|
||||
// A dangling destination symlink must not be followed into existence.
|
||||
const danglingTarget = NodePath.join(outsideDir, "not-yet-created.png");
|
||||
NodeFS.symlinkSync(
|
||||
danglingTarget,
|
||||
NodePath.join(testWorkspaceRoot, "evidence", "dangling.png"),
|
||||
);
|
||||
const danglingSymlink = yield* callSnapshot("evidence/dangling.png");
|
||||
expect(danglingSymlink.isError).toBe(true);
|
||||
expect(NodeFS.existsSync(danglingTarget)).toBe(false);
|
||||
|
||||
// A directory whose name merely starts with ".." is inside the root.
|
||||
const dotDotName = yield* callSnapshot("..screenshots/ok.png");
|
||||
expect(dotDotName.isError).toBe(false);
|
||||
expect(
|
||||
NodeFS.readFileSync(NodePath.join(testWorkspaceRoot, "..screenshots", "ok.png"), "utf8"),
|
||||
).toBe("png-bytes");
|
||||
|
||||
const bothDestinations = yield* server
|
||||
.callTool({
|
||||
name: "preview_snapshot",
|
||||
arguments: { save: true, savePath: "evidence/login.png" },
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
expect(bothDestinations.isError).toBe(true);
|
||||
|
||||
const savedArtifact = yield* server
|
||||
.callTool({ name: "preview_snapshot", arguments: { save: true } })
|
||||
.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, client),
|
||||
);
|
||||
expect(savedArtifact.isError).toBe(false);
|
||||
const artifactPath = (savedArtifact.structuredContent as { savedScreenshotPath?: string })
|
||||
.savedScreenshotPath;
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
expect(artifactPath).toBeDefined();
|
||||
expect(NodePath.dirname(artifactPath!)).toBe(config.browserArtifactsDir);
|
||||
expect(NodeFS.readFileSync(artifactPath!, "utf8")).toBe("png-bytes");
|
||||
}),
|
||||
).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
@@ -1,8 +1,10 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import type * as Types from "effect/Types";
|
||||
@@ -10,6 +12,9 @@ import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
|
||||
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
|
||||
import packageJson from "../../package.json" with { type: "json" };
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
|
||||
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
|
||||
@@ -130,6 +135,13 @@ const previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {
|
||||
const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
|
||||
const snapshotHandlerContext = yield* Effect.context<
|
||||
| ServerConfig.ServerConfig
|
||||
| ProjectionSnapshotQuery.ProjectionSnapshotQuery
|
||||
| WorkspacePaths.WorkspacePaths
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
>();
|
||||
const built = yield* PreviewSnapshotToolkit;
|
||||
const tool = PreviewSnapshotTool;
|
||||
yield* server.addTool({
|
||||
@@ -161,6 +173,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
|
||||
Effect.flatMap(Effect.fromOption),
|
||||
Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideContext(snapshotHandlerContext),
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: previewSnapshotFailure,
|
||||
onSuccess: ({ encodedResult }) => {
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import type {
|
||||
PreviewAutomationOperation,
|
||||
PreviewAutomationOpenInput,
|
||||
PreviewAutomationRecordingArtifact,
|
||||
PreviewAutomationRecordingStatus,
|
||||
PreviewAutomationResizeResult,
|
||||
PreviewAutomationScreenshotSaveStage,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
PreviewTabId,
|
||||
} from "@t3tools/contracts";
|
||||
import { PreviewAutomationScreenshotSaveError } from "@t3tools/contracts";
|
||||
|
||||
import * as ServerConfig from "../../../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts";
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
|
||||
import { PreviewSnapshotToolkit, PreviewStandardToolkit, PreviewToolkit } from "./tools.ts";
|
||||
@@ -60,6 +72,158 @@ const invokeTargeted = <A>(
|
||||
return invoke<A>(operation, operationInput, timeoutMs, tabId);
|
||||
};
|
||||
|
||||
const writeScreenshotFile = (input: {
|
||||
readonly absolutePath: string;
|
||||
readonly screenshotBase64: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(path.dirname(input.absolutePath), { recursive: true });
|
||||
yield* fileSystem.writeFile(
|
||||
input.absolutePath,
|
||||
new Uint8Array(Buffer.from(input.screenshotBase64, "base64")),
|
||||
);
|
||||
});
|
||||
|
||||
const saveSnapshotScreenshotArtifact = Effect.fn("PreviewToolkit.saveSnapshotScreenshotArtifact")(
|
||||
function* (input: {
|
||||
readonly scope: McpInvocationContext.McpInvocationScope;
|
||||
readonly screenshotBase64: string;
|
||||
}) {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
// Timestamp for ordering plus a random component so concurrent
|
||||
// same-millisecond captures never overwrite each other.
|
||||
const fileName = `browser-screenshot-${(yield* Clock.currentTimeMillis).toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`;
|
||||
const path = yield* Path.Path;
|
||||
const absolutePath = path.join(config.browserArtifactsDir, fileName);
|
||||
yield* writeScreenshotFile({ absolutePath, screenshotBase64: input.screenshotBase64 }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PreviewAutomationScreenshotSaveError({
|
||||
operation: "snapshot",
|
||||
environmentId: input.scope.environmentId,
|
||||
threadId: input.scope.threadId,
|
||||
providerSessionId: input.scope.providerSessionId,
|
||||
providerInstanceId: input.scope.providerInstanceId,
|
||||
savePath: fileName,
|
||||
stage: "artifact-write",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return absolutePath;
|
||||
},
|
||||
);
|
||||
|
||||
const saveSnapshotScreenshot = Effect.fn("PreviewToolkit.saveSnapshotScreenshot")(
|
||||
function* (input: {
|
||||
readonly scope: McpInvocationContext.McpInvocationScope;
|
||||
readonly savePath: string;
|
||||
readonly screenshotBase64: string;
|
||||
}) {
|
||||
const { savePath, scope } = input;
|
||||
const fail = (stage: PreviewAutomationScreenshotSaveStage, cause?: unknown) =>
|
||||
new PreviewAutomationScreenshotSaveError({
|
||||
operation: "snapshot",
|
||||
environmentId: scope.environmentId,
|
||||
threadId: scope.threadId,
|
||||
providerSessionId: scope.providerSessionId,
|
||||
providerInstanceId: scope.providerInstanceId,
|
||||
savePath,
|
||||
stage,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
if (!savePath.toLowerCase().endsWith(".png")) {
|
||||
return yield* fail("extension-validation");
|
||||
}
|
||||
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const threadContext = yield* projectionSnapshotQuery
|
||||
.getThreadCheckpointContext(scope.threadId)
|
||||
.pipe(Effect.mapError((cause) => fail("thread-workspace-resolution", cause)));
|
||||
if (Option.isNone(threadContext)) {
|
||||
return yield* fail("thread-lookup");
|
||||
}
|
||||
const workspaceRoot = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
|
||||
|
||||
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
|
||||
const resolved = yield* workspacePaths
|
||||
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath: savePath })
|
||||
.pipe(Effect.mapError((cause) => fail("workspace-path-validation", cause)));
|
||||
|
||||
// Lexical containment is not enough: symlinks inside the workspace could
|
||||
// point outside it. Every filesystem step below re-verifies canonical
|
||||
// containment before it acts.
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realPathOrNull = (target: string) =>
|
||||
fileSystem.realPath(target).pipe(
|
||||
Effect.map((canonical): string | null => canonical),
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
error.reason._tag === "NotFound"
|
||||
? Effect.succeed(null)
|
||||
: Effect.fail(fail("save-path-resolution", error)),
|
||||
}),
|
||||
);
|
||||
const isOutsideRoot = (canonicalRoot: string, canonical: string) => {
|
||||
const relative = path.relative(canonicalRoot, canonical);
|
||||
return relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
|
||||
};
|
||||
|
||||
const canonicalRoot = yield* fileSystem
|
||||
.realPath(workspaceRoot)
|
||||
.pipe(Effect.mapError((cause) => fail("workspace-root-resolution", cause)));
|
||||
|
||||
// Before creating anything: the deepest EXISTING ancestor of the target
|
||||
// must canonicalize inside the root, or recursive mkdir would follow an
|
||||
// outward directory symlink and create directories outside the workspace.
|
||||
const lexicalParent = path.dirname(resolved.absolutePath);
|
||||
let existingAncestor = lexicalParent;
|
||||
let canonicalAncestor = yield* realPathOrNull(existingAncestor);
|
||||
while (canonicalAncestor === null) {
|
||||
const parent = path.dirname(existingAncestor);
|
||||
if (parent === existingAncestor) {
|
||||
return yield* fail("save-directory-resolution");
|
||||
}
|
||||
existingAncestor = parent;
|
||||
canonicalAncestor = yield* realPathOrNull(existingAncestor);
|
||||
}
|
||||
if (isOutsideRoot(canonicalRoot, canonicalAncestor)) {
|
||||
return yield* fail("workspace-containment-validation");
|
||||
}
|
||||
|
||||
yield* fileSystem
|
||||
.makeDirectory(lexicalParent, { recursive: true })
|
||||
.pipe(Effect.mapError((cause) => fail("save-directory-creation", cause)));
|
||||
const canonicalParent = yield* fileSystem
|
||||
.realPath(lexicalParent)
|
||||
.pipe(Effect.mapError((cause) => fail("save-directory-resolution", cause)));
|
||||
if (isOutsideRoot(canonicalRoot, canonicalParent)) {
|
||||
return yield* fail("workspace-containment-validation");
|
||||
}
|
||||
|
||||
// Refuse to write through a destination that is itself a symlink: the
|
||||
// write would follow it, and a dangling link (realPath reports NotFound)
|
||||
// could silently create a file outside the workspace at its target.
|
||||
const destination = path.join(canonicalParent, path.basename(resolved.absolutePath));
|
||||
const destinationIsSymlink = yield* fileSystem.readLink(destination).pipe(
|
||||
Effect.as(true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
if (destinationIsSymlink) {
|
||||
return yield* fail("destination-symlink-validation");
|
||||
}
|
||||
|
||||
yield* writeScreenshotFile({
|
||||
absolutePath: destination,
|
||||
screenshotBase64: input.screenshotBase64,
|
||||
}).pipe(Effect.mapError((cause) => fail("screenshot-write", cause)));
|
||||
return resolved.relativePath;
|
||||
},
|
||||
);
|
||||
|
||||
const handlers = {
|
||||
preview_status: (input) => invokeTargeted<PreviewAutomationStatus>("status", input ?? {}),
|
||||
preview_open: (input) =>
|
||||
@@ -70,7 +234,29 @@ const handlers = {
|
||||
invokeTargeted<PreviewAutomationResizeResult>("resize", input, input.timeoutMs),
|
||||
preview_set_appearance: (input) =>
|
||||
invokeTargeted<PreviewAutomationSetColorSchemeResult>("setColorScheme", input),
|
||||
preview_snapshot: (input) => invokeTargeted<PreviewAutomationSnapshot>("snapshot", input ?? {}),
|
||||
preview_snapshot: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const { save, savePath, ...target } = input ?? {};
|
||||
const snapshot = yield* invokeTargeted<PreviewAutomationSnapshot>("snapshot", target);
|
||||
if (savePath !== undefined) {
|
||||
const scope = yield* McpInvocationContext.McpInvocationContext;
|
||||
const savedScreenshotPath = yield* saveSnapshotScreenshot({
|
||||
scope,
|
||||
savePath,
|
||||
screenshotBase64: snapshot.screenshot.data,
|
||||
});
|
||||
return { ...snapshot, savedScreenshotPath };
|
||||
}
|
||||
if (save === true) {
|
||||
const scope = yield* McpInvocationContext.McpInvocationContext;
|
||||
const savedScreenshotPath = yield* saveSnapshotScreenshotArtifact({
|
||||
scope,
|
||||
screenshotBase64: snapshot.screenshot.data,
|
||||
});
|
||||
return { ...snapshot, savedScreenshotPath };
|
||||
}
|
||||
return snapshot;
|
||||
}),
|
||||
preview_click: (input) =>
|
||||
invokeTargeted<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
|
||||
preview_type: (input) =>
|
||||
|
||||
@@ -13,14 +13,20 @@ import {
|
||||
PreviewAutomationSetColorSchemeInput,
|
||||
PreviewAutomationSetColorSchemeResult,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationSnapshotInput,
|
||||
PreviewAutomationStatus,
|
||||
PreviewAutomationTabTargetInput,
|
||||
PreviewAutomationTypeInput,
|
||||
PreviewAutomationWaitForInput,
|
||||
} from "@t3tools/contracts";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { Tool, Toolkit } from "effect/unstable/ai";
|
||||
|
||||
import * as ServerConfig from "../../../config.ts";
|
||||
import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts";
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
|
||||
|
||||
@@ -29,6 +35,15 @@ const dependencies = [
|
||||
PreviewAutomationBroker.PreviewAutomationBroker,
|
||||
];
|
||||
|
||||
const snapshotDependencies = [
|
||||
...dependencies,
|
||||
ServerConfig.ServerConfig,
|
||||
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
|
||||
WorkspacePaths.WorkspacePaths,
|
||||
FileSystem.FileSystem,
|
||||
Path.Path,
|
||||
];
|
||||
|
||||
const browserTool = <T extends Tool.Any>(tool: T): T =>
|
||||
tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T;
|
||||
|
||||
@@ -101,14 +116,17 @@ export const PreviewSetAppearanceTool = safeBrowserTool(
|
||||
.annotate(Tool.Idempotent, true),
|
||||
);
|
||||
|
||||
export const PreviewSnapshotTool = readonlyBrowserTool(
|
||||
// Not `readonlyBrowserTool`: `save`/`savePath` write a screenshot file, and
|
||||
// `save:true` names a fresh artifact per call, so it is neither read-only
|
||||
// nor idempotent.
|
||||
export const PreviewSnapshotTool = safeBrowserTool(
|
||||
Tool.make("preview_snapshot", {
|
||||
description:
|
||||
"Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot.",
|
||||
parameters: PreviewAutomationTabTargetInput,
|
||||
"Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot. To keep visual evidence for the human (before/after states of UI work), pass save:true — the result then includes savedScreenshotPath, which you embed in your final reply with markdown image syntax, e.g. . Use savePath only when the screenshot should live inside the repo.",
|
||||
parameters: PreviewAutomationSnapshotInput,
|
||||
success: PreviewAutomationSnapshot,
|
||||
failure: PreviewAutomationError,
|
||||
dependencies,
|
||||
dependencies: snapshotDependencies,
|
||||
}).annotate(Tool.Title, "Inspect browser page"),
|
||||
);
|
||||
|
||||
@@ -192,7 +210,7 @@ export const PreviewRecordingStartTool = safeBrowserTool(
|
||||
export const PreviewRecordingStopTool = safeBrowserTool(
|
||||
Tool.make("preview_recording_stop", {
|
||||
description:
|
||||
"Stop recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted, and save it as a local evidence artifact.",
|
||||
"Stop recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted, and save it as a local evidence artifact (.webm). To show the recording to the human, embed the returned path directly in your final reply with markdown image syntax, e.g.  — the chat renders it as a playable video. The recording is saved on the machine running the desktop app; if the server runs on a different machine the embed can show as unavailable — in that case copy the file into the workspace and embed the workspace-relative path instead.",
|
||||
parameters: PreviewAutomationTabTargetInput,
|
||||
success: PreviewAutomationRecordingArtifact,
|
||||
failure: PreviewAutomationError,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { projectActivityPayload } from "./ActivityPayloadProjection.ts";
|
||||
|
||||
const makeImageActivity = (item: Record<string, unknown>): OrchestrationThreadActivity => ({
|
||||
id: EventId.make("activity-image-1"),
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
detail: "/tmp/generated.png",
|
||||
data: { completedAtMs: 1, item },
|
||||
},
|
||||
turnId: TurnId.make("turn-1"),
|
||||
createdAt: "2026-07-27T21:17:50.000Z",
|
||||
});
|
||||
|
||||
const projectedItem = (activity: OrchestrationThreadActivity): Record<string, unknown> => {
|
||||
const payload = activity.payload as { data?: { item?: Record<string, unknown> } };
|
||||
return payload.data?.item ?? {};
|
||||
};
|
||||
|
||||
describe("projectActivityPayload", () => {
|
||||
it("keeps the saved path for generated images while pruning the base64 result", () => {
|
||||
const projected = projectActivityPayload(
|
||||
makeImageActivity({
|
||||
id: "call-1",
|
||||
type: "imageGeneration",
|
||||
savedPath: "/Users/test/.codex/generated_images/thread/call.png",
|
||||
revisedPrompt: "a prompt",
|
||||
result: "iVBORw0KGgoAAAANSUhEUg",
|
||||
status: "completed",
|
||||
}),
|
||||
);
|
||||
|
||||
const item = projectedItem(projected);
|
||||
expect(item.savedPath).toBe("/Users/test/.codex/generated_images/thread/call.png");
|
||||
expect(item.type).toBe("imageGeneration");
|
||||
// The generated image bytes are megabytes per activity and unread by clients.
|
||||
expect(item.result).toBeUndefined();
|
||||
expect(item.revisedPrompt).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the viewed path for image view items", () => {
|
||||
const projected = projectActivityPayload(
|
||||
makeImageActivity({ id: "call-2", type: "imageView", path: "/tmp/screenshot.png" }),
|
||||
);
|
||||
|
||||
const item = projectedItem(projected);
|
||||
expect(item.path).toBe("/tmp/screenshot.png");
|
||||
expect(item.type).toBe("imageView");
|
||||
});
|
||||
|
||||
it("still prunes unrelated tool item payloads", () => {
|
||||
const projected = projectActivityPayload(
|
||||
makeImageActivity({ id: "call-3", type: "somethingElse", secret: "value" }),
|
||||
);
|
||||
|
||||
expect(projectedItem(projected)).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -104,6 +104,31 @@ function projectCommandData(data: Record<string, unknown>): Record<string, unkno
|
||||
return Object.keys(projectedItem).length > 0 ? projectedItem : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Image view items carry the on-disk path both clients need to render the
|
||||
* output gallery. The generated image itself also rides along in `result` as
|
||||
* base64 — that stays pruned, since it is megabytes per activity and no client
|
||||
* reads it.
|
||||
*/
|
||||
function projectImageViewData(data: Record<string, unknown>): Record<string, unknown> | undefined {
|
||||
const item = asRecord(data.item);
|
||||
if (!item) {
|
||||
return undefined;
|
||||
}
|
||||
if (item.type !== "imageView" && item.type !== "imageGeneration") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const projectedItem: Record<string, unknown> = { type: item.type };
|
||||
if (asTrimmedString(item.path)) {
|
||||
projectedItem.path = item.path;
|
||||
}
|
||||
if (asTrimmedString(item.savedPath)) {
|
||||
projectedItem.savedPath = item.savedPath;
|
||||
}
|
||||
return Object.keys(projectedItem).length > 1 ? projectedItem : undefined;
|
||||
}
|
||||
|
||||
function summarizeToolTextOutput(value: string): string | null {
|
||||
const lines: string[] = [];
|
||||
for (const rawLine of value.split(/\r?\n/u)) {
|
||||
@@ -165,7 +190,7 @@ export function projectActivityPayload(
|
||||
}
|
||||
|
||||
const projectedData: Record<string, unknown> = {};
|
||||
const item = projectCommandData(data);
|
||||
const item = projectCommandData(data) ?? projectImageViewData(data);
|
||||
if (item) {
|
||||
projectedData.item = item;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
];
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ import rehypeRaw from "rehype-raw";
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
|
||||
import remarkBreaks from "remark-breaks";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { MarkdownMedia } from "./chat/MarkdownMedia";
|
||||
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
|
||||
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
|
||||
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
|
||||
@@ -161,10 +162,12 @@ function findTaskListMarkerOffset(markdown: string, listItemStart: number): numb
|
||||
}
|
||||
const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
|
||||
...defaultSchema,
|
||||
tagNames: [...(defaultSchema.tagNames ?? []), "video"],
|
||||
attributes: {
|
||||
...defaultSchema.attributes,
|
||||
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
|
||||
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta", "dataInlineCode"],
|
||||
video: ["src", "controls", "muted", "loop", "playsInline", "poster", "preload"],
|
||||
},
|
||||
protocols: {
|
||||
...defaultSchema.protocols,
|
||||
@@ -187,8 +190,39 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [
|
||||
remarkTagInlineCode,
|
||||
] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
|
||||
|
||||
interface HastNodeLike {
|
||||
readonly type: string;
|
||||
readonly tagName?: string;
|
||||
properties?: Record<string, unknown>;
|
||||
children?: HastNodeLike[];
|
||||
}
|
||||
|
||||
const WINDOWS_DRIVE_SRC_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||
|
||||
// rehype-sanitize parses a Windows drive path source such as "C:\shot.png"
|
||||
// as an unknown "c:" protocol and strips it. Escape media sources to
|
||||
// "/C:/…" before sanitization runs; MarkdownMedia unescapes when resolving.
|
||||
function rehypeEscapeWindowsDriveMediaSrc() {
|
||||
const escapeNode = (node: HastNodeLike): void => {
|
||||
if (
|
||||
node.type === "element" &&
|
||||
(node.tagName === "img" || node.tagName === "video") &&
|
||||
node.properties &&
|
||||
typeof node.properties.src === "string" &&
|
||||
WINDOWS_DRIVE_SRC_PATTERN.test(node.properties.src)
|
||||
) {
|
||||
node.properties.src = `/${node.properties.src}`;
|
||||
}
|
||||
for (const child of node.children ?? []) {
|
||||
escapeNode(child);
|
||||
}
|
||||
};
|
||||
return escapeNode;
|
||||
}
|
||||
|
||||
const CHAT_MARKDOWN_REHYPE_PLUGINS = [
|
||||
rehypeRaw,
|
||||
rehypeEscapeWindowsDriveMediaSrc,
|
||||
[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
|
||||
] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>;
|
||||
|
||||
@@ -1584,6 +1618,24 @@ function ChatMarkdown({
|
||||
</code>
|
||||
);
|
||||
},
|
||||
img({ node: _node, src, alt }) {
|
||||
return (
|
||||
<MarkdownMedia
|
||||
src={typeof src === "string" ? src : undefined}
|
||||
alt={alt}
|
||||
threadRef={threadRef}
|
||||
/>
|
||||
);
|
||||
},
|
||||
video({ node: _node, src }) {
|
||||
return (
|
||||
<MarkdownMedia
|
||||
src={typeof src === "string" ? src : undefined}
|
||||
threadRef={threadRef}
|
||||
kind="video"
|
||||
/>
|
||||
);
|
||||
},
|
||||
table({ node: _node, ...props }) {
|
||||
return <MarkdownTable {...props} />;
|
||||
},
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import { memo, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import type { AssetResource, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { isWorkspaceVideoPreviewPath } from "@t3tools/shared/filePreview";
|
||||
|
||||
import { useAssetUrlState } from "../../assets/assetUrls";
|
||||
import { ExpandedImageDialog } from "./ExpandedImageDialog";
|
||||
|
||||
/** Sources the browser can load directly without a signed workspace asset URL. */
|
||||
const DIRECT_MEDIA_SRC_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i;
|
||||
|
||||
/** `markdownUrlTransform` escapes Windows drive paths as `/C:/…` so they survive sanitization. */
|
||||
const ESCAPED_WINDOWS_DRIVE_PATH_PATTERN = /^\/[A-Za-z]:[\\/]/;
|
||||
|
||||
/** Paths that are absolute on either platform (after Windows-drive unescaping). */
|
||||
const ABSOLUTE_PATH_PATTERN = /^(?:[/\\]|[A-Za-z]:[\\/])/;
|
||||
|
||||
const MEDIA_FRAME_CLASS_NAME =
|
||||
"my-2 block max-h-96 max-w-full rounded-lg border border-border/60 bg-background object-contain";
|
||||
|
||||
interface MarkdownMediaProps {
|
||||
src: string | undefined;
|
||||
alt?: string | undefined;
|
||||
threadRef?: ScopedThreadRef | undefined;
|
||||
/** Force the media kind; when omitted it is inferred from the file extension. */
|
||||
kind?: "image" | "video" | undefined;
|
||||
}
|
||||
|
||||
function safeDecode(value: string): string {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function mediaFileName(src: string): string {
|
||||
const withoutQuery = src.split(/[?#]/, 1)[0] ?? src;
|
||||
const basename = withoutQuery.slice(withoutQuery.lastIndexOf("/") + 1);
|
||||
return basename.length > 0 ? safeDecode(basename) : safeDecode(withoutQuery);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a non-direct markdown src into a filesystem-style path: strip
|
||||
* query/fragment, decode percent escapes, and unescape the `/C:/…` form the
|
||||
* markdown URL transform uses to carry Windows drive paths through
|
||||
* sanitization.
|
||||
*/
|
||||
function mediaPathFromSrc(src: string): string {
|
||||
const withoutQuery = src.split(/[?#]/, 1)[0] ?? src;
|
||||
const decoded = safeDecode(withoutQuery);
|
||||
return ESCAPED_WINDOWS_DRIVE_PATH_PATTERN.test(decoded) ? decoded.slice(1) : decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Browser evidence artifacts (screenshots/recordings from the embedded
|
||||
* browser) are referenced by the absolute path the preview tools return,
|
||||
* e.g. `/…/userdata/browser-artifacts/browser-recording-x.webm`. They are
|
||||
* served by file name from the server's browser-artifacts directory. Only
|
||||
* absolute paths qualify — a workspace-relative path like
|
||||
* `docs/browser-artifacts/x.png` is an ordinary repo file.
|
||||
*/
|
||||
function browserArtifactFileName(path: string): string | null {
|
||||
if (!ABSOLUTE_PATH_PATTERN.test(path)) {
|
||||
return null;
|
||||
}
|
||||
const match = /[/\\]browser-artifacts[/\\]([^/\\]+)$/.exec(path);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
|
||||
function MediaUnavailable({ name }: { name: string }) {
|
||||
return (
|
||||
<span className="my-1 inline-flex max-w-full items-baseline gap-1 rounded-md border border-border/60 bg-muted/40 px-2 py-1 text-xs text-muted-foreground">
|
||||
Media unavailable:
|
||||
<span className="truncate font-mono">{name}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ResolvedMedia({ url, name, isVideo }: { url: string; name: string; isVideo: boolean }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null);
|
||||
|
||||
if (failedUrl === url) {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
|
||||
if (isVideo) {
|
||||
return (
|
||||
<video
|
||||
src={url}
|
||||
controls
|
||||
playsInline
|
||||
preload="metadata"
|
||||
aria-label={name}
|
||||
className={MEDIA_FRAME_CLASS_NAME}
|
||||
onError={() => setFailedUrl(url)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="block max-w-full cursor-zoom-in"
|
||||
aria-label={`Expand image ${name}`}
|
||||
onClick={() => setExpanded(true)}
|
||||
>
|
||||
<img
|
||||
src={url}
|
||||
alt={name}
|
||||
loading="lazy"
|
||||
className={MEDIA_FRAME_CLASS_NAME}
|
||||
onError={() => setFailedUrl(url)}
|
||||
/>
|
||||
</button>
|
||||
{expanded &&
|
||||
// Portal to the body: message rows create containing blocks that would
|
||||
// otherwise trap the fixed-position dialog inside the chat scroller.
|
||||
createPortal(
|
||||
<ExpandedImageDialog
|
||||
preview={{ images: [{ src: url, name }], index: 0 }}
|
||||
onClose={() => setExpanded(false)}
|
||||
/>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ResourceMedia({
|
||||
threadRef,
|
||||
resource,
|
||||
name,
|
||||
isVideo,
|
||||
}: {
|
||||
threadRef: ScopedThreadRef;
|
||||
resource: AssetResource;
|
||||
name: string;
|
||||
isVideo: boolean;
|
||||
}) {
|
||||
const assetUrl = useAssetUrlState(threadRef.environmentId, resource);
|
||||
|
||||
if (assetUrl._tag === "Failure") {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
if (assetUrl._tag === "Loading") {
|
||||
return (
|
||||
<span className="my-2 flex h-24 w-56 max-w-full animate-pulse items-center justify-center rounded-lg border border-border/40 bg-muted/30 px-2 text-xs text-muted-foreground">
|
||||
<span className="truncate">{name}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <ResolvedMedia url={assetUrl.url} name={name} isVideo={isVideo} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders markdown-referenced media (images and videos) in chat messages.
|
||||
*
|
||||
* Workspace-relative sources are resolved to signed asset URLs for the
|
||||
* thread's worktree, so agents can save screenshots/recordings into the
|
||||
* workspace and embed them with plain markdown image syntax.
|
||||
*/
|
||||
export const MarkdownMedia = memo(function MarkdownMedia({
|
||||
src,
|
||||
alt,
|
||||
threadRef,
|
||||
kind,
|
||||
}: MarkdownMediaProps) {
|
||||
if (!src) {
|
||||
return null;
|
||||
}
|
||||
const name = alt && alt.trim().length > 0 ? alt.trim() : mediaFileName(src);
|
||||
const isVideo = kind === "video" || (kind === undefined && isWorkspaceVideoPreviewPath(src));
|
||||
if (DIRECT_MEDIA_SRC_PATTERN.test(src)) {
|
||||
return <ResolvedMedia url={src} name={name} isVideo={isVideo} />;
|
||||
}
|
||||
if (!threadRef) {
|
||||
return <MediaUnavailable name={name} />;
|
||||
}
|
||||
const path = mediaPathFromSrc(src);
|
||||
const artifactFileName = browserArtifactFileName(path);
|
||||
const resource: AssetResource = artifactFileName
|
||||
? { _tag: "browser-artifact", fileName: artifactFileName }
|
||||
: {
|
||||
_tag: "workspace-file",
|
||||
threadId: threadRef.threadId,
|
||||
path: path.startsWith("./") ? path.slice(2) : path,
|
||||
};
|
||||
return <ResourceMedia threadRef={threadRef} resource={resource} name={name} isVideo={isVideo} />;
|
||||
});
|
||||
@@ -261,6 +261,293 @@ describe("resolveAssistantMessageCopyState", () => {
|
||||
});
|
||||
|
||||
describe("deriveMessagesTimelineRows", () => {
|
||||
it("renders unscoped image output when no turn is unsettled", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "unscoped-image-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
entry: {
|
||||
id: "unscoped-image-activity",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
turnId: null,
|
||||
label: "Image view",
|
||||
tone: "tool" as const,
|
||||
itemType: "image_view" as const,
|
||||
imagePath: "/tmp/unscoped.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 image.",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:21Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
expandedTurnIds: new Set(),
|
||||
});
|
||||
|
||||
const imageOutputRow = rows.find((row) => row.kind === "image-output");
|
||||
expect(imageOutputRow).toMatchObject({
|
||||
kind: "image-output",
|
||||
id: "image-output:unscoped",
|
||||
images: [
|
||||
{
|
||||
entry: { id: "unscoped-image-activity" },
|
||||
imagePath: "/tmp/unscoped.png",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
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,137 @@ 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;
|
||||
}
|
||||
// Only skip images that belong to the in-flight turn; an unscoped entry
|
||||
// (null turnId) must still render when no turn is unsettled.
|
||||
if (input.unsettledTurnId !== null && 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;
|
||||
}
|
||||
// A grouped work row can cover several turns, so multiple turns may map to
|
||||
// the same target row — append rather than replacing the previous gallery.
|
||||
const existingOutputs = outputsAfterRowId.get(targetRowId);
|
||||
if (existingOutputs) {
|
||||
existingOutputs.push(outputRow);
|
||||
} else {
|
||||
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 +706,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 +744,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 +775,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 +803,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.imageActivityId ?? 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;
|
||||
|
||||
@@ -995,6 +995,111 @@ 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("keeps the image activity id paired with the path when collapsing entries", () => {
|
||||
const imagePath = "/tmp/codex-preview.png";
|
||||
const entries = deriveWorkLogEntries([
|
||||
makeActivity({
|
||||
id: "image-view-with-path",
|
||||
kind: "tool.updated",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
status: "in_progress",
|
||||
title: "Image view",
|
||||
data: {
|
||||
toolCallId: "call-image-1",
|
||||
item: { id: "call-image-1", path: imagePath, type: "imageView" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
// The completion for the same tool call carries no path; collapsing
|
||||
// adopts its id, so the path's owning activity id must be retained.
|
||||
makeActivity({
|
||||
id: "image-view-without-path",
|
||||
kind: "tool.completed",
|
||||
summary: "Image view",
|
||||
payload: {
|
||||
itemType: "image_view",
|
||||
status: "completed",
|
||||
title: "Image view",
|
||||
data: {
|
||||
toolCallId: "call-image-1",
|
||||
item: { id: "call-image-1", type: "imageView" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
id: "image-view-without-path",
|
||||
imagePath,
|
||||
imageActivityId: "image-view-with-path",
|
||||
});
|
||||
});
|
||||
|
||||
it("unwraps PowerShell command wrappers for displayed command text", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
|
||||
@@ -69,6 +69,13 @@ export interface WorkLogEntry {
|
||||
command?: string;
|
||||
rawCommand?: string;
|
||||
changedFiles?: ReadonlyArray<string>;
|
||||
imagePath?: string;
|
||||
/**
|
||||
* Activity that carried `imagePath`. Collapsing can merge a later activity's
|
||||
* `id` onto an earlier activity's `imagePath`, and the asset lookup resolves
|
||||
* the path from this activity's payload — so it must stay paired with it.
|
||||
*/
|
||||
imageActivityId?: string;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
toolTitle?: string;
|
||||
toolData?: unknown;
|
||||
@@ -740,6 +747,20 @@ 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;
|
||||
entry.imageActivityId = entry.id;
|
||||
}
|
||||
}
|
||||
if (itemType) {
|
||||
entry.itemType = itemType;
|
||||
}
|
||||
@@ -811,6 +832,11 @@ function mergeDerivedWorkLogEntries(
|
||||
const detail = next.detail ?? previous.detail;
|
||||
const command = next.command ?? previous.command;
|
||||
const rawCommand = next.rawCommand ?? previous.rawCommand;
|
||||
// Keep the owning activity id paired with the path it came from.
|
||||
const imagePath = next.imagePath ?? previous.imagePath;
|
||||
const imageActivityId = next.imagePath
|
||||
? (next.imageActivityId ?? next.id)
|
||||
: (previous.imageActivityId ?? previous.id);
|
||||
const toolTitle = next.toolTitle ?? previous.toolTitle;
|
||||
const itemType = next.itemType ?? previous.itemType;
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
@@ -824,6 +850,7 @@ function mergeDerivedWorkLogEntries(
|
||||
...(detail ? { detail } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(rawCommand ? { rawCommand } : {}),
|
||||
...(imagePath ? { imagePath, imageActivityId } : {}),
|
||||
...(changedFiles.length > 0 ? { changedFiles } : {}),
|
||||
...(toolTitle ? { toolTitle } : {}),
|
||||
...(itemType ? { itemType } : {}),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -12,6 +12,14 @@ export const AssetResource = Schema.Union([
|
||||
Schema.TaggedStruct("attachment", {
|
||||
attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),
|
||||
}),
|
||||
/** A file in the server's browser-artifacts directory (screenshots/recordings). */
|
||||
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)),
|
||||
}),
|
||||
@@ -83,7 +91,7 @@ export class AssetPreviewTypeValidationError extends Schema.TaggedErrorClass<Ass
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Only browser documents and images can be previewed.";
|
||||
return "Only browser documents, images, and videos can be previewed.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +141,40 @@ export class AssetAttachmentNotFoundError extends Schema.TaggedErrorClass<AssetA
|
||||
}
|
||||
}
|
||||
|
||||
export class AssetBrowserArtifactNotFoundError extends Schema.TaggedErrorClass<AssetBrowserArtifactNotFoundError>()(
|
||||
"AssetBrowserArtifactNotFoundError",
|
||||
{
|
||||
resource: AssetResource,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Browser artifact was not found.";
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
{
|
||||
@@ -190,6 +232,9 @@ export const AssetAccessError = Schema.Union([
|
||||
AssetWorkspaceAssetNotFoundError,
|
||||
AssetWorkspaceResolutionError,
|
||||
AssetAttachmentNotFoundError,
|
||||
AssetBrowserArtifactNotFoundError,
|
||||
AssetThreadImageNotFoundError,
|
||||
AssetThreadImageResolutionError,
|
||||
AssetProjectFaviconResolutionError,
|
||||
AssetProjectFaviconInspectionError,
|
||||
AssetProjectFaviconNotFoundError,
|
||||
|
||||
@@ -66,6 +66,31 @@ const PreviewAutomationTabTargetFields = {
|
||||
export const PreviewAutomationTabTargetInput = Schema.Struct(PreviewAutomationTabTargetFields);
|
||||
export type PreviewAutomationTabTargetInput = typeof PreviewAutomationTabTargetInput.Type;
|
||||
|
||||
const SNAPSHOT_SAVE_DESCRIPTION =
|
||||
"When true, the screenshot is persisted as a browser evidence artifact outside the workspace and the result includes savedScreenshotPath. Embed that exact path in your final reply with markdown image syntax (e.g. ) so the human sees the screenshot in chat. Preferred for before/after evidence of UI work. Cannot be combined with savePath.";
|
||||
|
||||
const SNAPSHOT_SAVE_PATH_DESCRIPTION =
|
||||
"Optional workspace-relative file path ending in .png. Use only when the screenshot should live inside the repo (e.g. committed docs or fixtures); prefer save:true for chat evidence. The file is written into the thread workspace and can be embedded with markdown image syntax, e.g. .";
|
||||
|
||||
export const PreviewAutomationSnapshotInput = Schema.Struct({
|
||||
...PreviewAutomationTabTargetFields,
|
||||
save: Schema.optional(
|
||||
Schema.Boolean.annotate({ description: SNAPSHOT_SAVE_DESCRIPTION }),
|
||||
).annotate({ description: SNAPSHOT_SAVE_DESCRIPTION }),
|
||||
savePath: Schema.optional(
|
||||
TrimmedNonEmptyString.check(Schema.isMaxLength(512)).annotate({
|
||||
description: SNAPSHOT_SAVE_PATH_DESCRIPTION,
|
||||
}),
|
||||
).annotate({ description: SNAPSHOT_SAVE_PATH_DESCRIPTION }),
|
||||
}).check(
|
||||
Schema.makeFilter(
|
||||
(input) =>
|
||||
!(input.save === true && input.savePath !== undefined) ||
|
||||
"save cannot be combined with savePath; choose one destination.",
|
||||
),
|
||||
);
|
||||
export type PreviewAutomationSnapshotInput = typeof PreviewAutomationSnapshotInput.Type;
|
||||
|
||||
export const PreviewAutomationStatus = Schema.Struct({
|
||||
available: Schema.Boolean,
|
||||
visible: Schema.Boolean,
|
||||
@@ -548,6 +573,8 @@ export const PreviewAutomationSnapshot = Schema.Struct({
|
||||
width: Schema.Int,
|
||||
height: Schema.Int,
|
||||
}),
|
||||
/** Workspace-relative path the screenshot was also written to, when savePath was requested. */
|
||||
savedScreenshotPath: Schema.optional(Schema.String),
|
||||
});
|
||||
export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
|
||||
|
||||
@@ -861,6 +888,36 @@ export class PreviewAutomationMalformedResponseError extends Schema.TaggedErrorC
|
||||
}
|
||||
}
|
||||
|
||||
export const PreviewAutomationScreenshotSaveStage = Schema.Literals([
|
||||
"artifact-write",
|
||||
"extension-validation",
|
||||
"thread-workspace-resolution",
|
||||
"thread-lookup",
|
||||
"workspace-path-validation",
|
||||
"save-path-resolution",
|
||||
"workspace-root-resolution",
|
||||
"save-directory-resolution",
|
||||
"workspace-containment-validation",
|
||||
"save-directory-creation",
|
||||
"destination-symlink-validation",
|
||||
"screenshot-write",
|
||||
]);
|
||||
export type PreviewAutomationScreenshotSaveStage = typeof PreviewAutomationScreenshotSaveStage.Type;
|
||||
|
||||
export class PreviewAutomationScreenshotSaveError extends Schema.TaggedErrorClass<PreviewAutomationScreenshotSaveError>()(
|
||||
"PreviewAutomationScreenshotSaveError",
|
||||
{
|
||||
...PreviewAutomationScopeErrorFields,
|
||||
savePath: TrimmedNonEmptyString,
|
||||
stage: PreviewAutomationScreenshotSaveStage,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to save the preview screenshot to ${this.savePath} during ${this.stage.replaceAll("-", " ")}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const PreviewAutomationError = Schema.Union([
|
||||
PreviewAutomationUnavailableError,
|
||||
PreviewAutomationNoAvailableHostError,
|
||||
@@ -876,6 +933,7 @@ export const PreviewAutomationError = Schema.Union([
|
||||
PreviewAutomationRequestQueueClosedError,
|
||||
PreviewAutomationRemoteUnavailableError,
|
||||
PreviewAutomationMalformedResponseError,
|
||||
PreviewAutomationScreenshotSaveError,
|
||||
]);
|
||||
export type PreviewAutomationError = typeof PreviewAutomationError.Type;
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ export const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [
|
||||
".webp",
|
||||
] as const;
|
||||
|
||||
export const WORKSPACE_VIDEO_PREVIEW_EXTENSIONS = [".m4v", ".mov", ".mp4", ".webm"] as const;
|
||||
|
||||
function hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {
|
||||
const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? "";
|
||||
return extensions.some((extension) => pathWithoutQuery.endsWith(extension));
|
||||
@@ -24,6 +26,14 @@ export function isWorkspaceImagePreviewPath(path: string): boolean {
|
||||
return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);
|
||||
}
|
||||
|
||||
export function isWorkspacePreviewEntryPath(path: string): boolean {
|
||||
return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);
|
||||
export function isWorkspaceVideoPreviewPath(path: string): boolean {
|
||||
return hasPreviewExtension(path, WORKSPACE_VIDEO_PREVIEW_EXTENSIONS);
|
||||
}
|
||||
|
||||
export function isWorkspacePreviewEntryPath(path: string): boolean {
|
||||
return (
|
||||
isWorkspaceBrowserPreviewPath(path) ||
|
||||
isWorkspaceImagePreviewPath(path) ||
|
||||
isWorkspaceVideoPreviewPath(path)
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user