feat(chat): preview agent media on web and mobile

This commit is contained in:
Gabriel De Andrade committed 2026-07-30 17:12:44 -04:00
1 parent 3510040050
commit 084f6c7a8c
38 files changed
+2341 -81

No files matched your search

+156 -1
View File
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ThreadId } from "@t3tools/contracts";
import { ThreadId, TurnItemId } 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";
@@ -15,6 +15,14 @@ import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
async function readStream(stream: AsyncIterable<Uint8Array>): Promise<Uint8Array> {
const chunks: Uint8Array[] = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
const configLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-asset-access-test-",
});
@@ -104,6 +112,83 @@ 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 token = suffix.slice(0, suffix.indexOf("/"));
expect(yield* resolveAsset(token, "demo.webm")).toEqual({
kind: "file",
path: canonicalVideoPath,
});
expect(yield* resolveAsset(token, "other.webm")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues browser artifact URLs by media file name only", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfig.ServerConfig;
const artifactPath = path.join(
config.stateDir,
"browser-artifacts",
"browser-recording-demo.webm",
);
yield* fileSystem.writeFileString(artifactPath, "webm-bytes");
const canonicalArtifactPath = yield* fileSystem.realPath(artifactPath);
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("/"));
const resolved = yield* resolveAsset(token, "browser-recording-demo.webm");
expect(resolved).toMatchObject({
kind: "open-file",
path: canonicalArtifactPath,
});
if (!resolved || resolved.kind !== "open-file") return;
expect(
Buffer.from(yield* Effect.promise(() => readStream(resolved.stream))).toString("utf8"),
).toBe("webm-bytes");
const traversal = yield* issueAssetUrl({
resource: { _tag: "browser-artifact", fileName: "../state.sqlite" },
}).pipe(Effect.flip);
expect(traversal._tag).toBe("AssetBrowserArtifactNotFoundError");
const symlinkPath = path.join(
config.stateDir,
"browser-artifacts",
"browser-recording-link.webm",
);
yield* fileSystem.symlink(artifactPath, symlinkPath);
const symlink = yield* issueAssetUrl({
resource: { _tag: "browser-artifact", fileName: "browser-recording-link.webm" },
}).pipe(Effect.flip);
expect(symlink._tag).toBe("AssetBrowserArtifactNotFoundError");
}).pipe(Effect.provide(testLayer)),
);
it.effect("preserves non-missing canonical path failures when issuing asset URLs", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -206,6 +291,76 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact capabilities for V2 image turn items 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"),
turnItemId: TurnItemId.make("image-item-1"),
};
const result = yield* issueAssetUrl({
resource,
threadImagePath: imagePath,
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const token = suffix.slice(0, suffix.indexOf("/"));
const resolved = yield* resolveAsset(token, "tool-output.png");
expect(resolved).toMatchObject({
kind: "open-file",
path: canonicalImagePath,
});
if (!resolved || resolved.kind !== "open-file") return;
expect(Array.from(yield* Effect.promise(() => readStream(resolved.stream)))).toEqual([
137, 80, 78, 71,
]);
expect(yield* resolveAsset(token, "other.png")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects non-image and post-issuance symlink targets for V2 image items", () =>
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"),
turnItemId: TurnItemId.make("image-item-1"),
};
const unsupportedError = yield* issueAssetUrl({
resource,
threadImagePath: textPath,
}).pipe(Effect.flip);
expect(unsupportedError._tag).toBe("AssetThreadImageNotFoundError");
const imagePath = path.join(directory, "tool-output.png");
const otherPath = path.join(directory, "other.png");
yield* fileSystem.writeFile(imagePath, new Uint8Array([137, 80, 78, 71]));
yield* fileSystem.writeFile(otherPath, new Uint8Array([1, 2, 3]));
const result = yield* issueAssetUrl({ resource, threadImagePath: imagePath });
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const token = suffix.slice(0, suffix.indexOf("/"));
yield* fileSystem.remove(imagePath);
yield* fileSystem.symlink(otherPath, imagePath);
expect(yield* resolveAsset(token, "tool-output.png")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues project favicon capabilities with a signed fallback", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
+264 -17
View File
@@ -1,11 +1,17 @@
// @effect-diagnostics nodeBuiltinImport:off
import type * as NodeFS from "node:fs";
import type { AssetResource } from "@t3tools/contracts";
import {
AssetAttachmentNotFoundError,
AssetBrowserArtifactNotFoundError,
AssetPreviewTypeValidationError,
AssetProjectFaviconInspectionError,
AssetProjectFaviconNotFoundError,
AssetProjectFaviconResolutionError,
AssetSigningKeyLoadError,
AssetThreadImageNotFoundError,
AssetThreadImageResolutionError,
AssetWorkspaceAssetInspectionError,
AssetWorkspaceAssetNotFoundError,
AssetWorkspaceContextNotFoundError,
@@ -16,11 +22,15 @@ import {
import {
isWorkspaceImagePreviewPath,
isWorkspacePreviewEntryPath,
isWorkspaceVideoPreviewPath,
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
WORKSPACE_VIDEO_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import * as Clock from "effect/Clock";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -37,6 +47,7 @@ import {
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { resolveAttachmentPathById } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import { canonicalPathsMatch, openReadableFileNoFollow } from "../noFollowFile.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
@@ -47,6 +58,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 +89,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"),
@@ -91,7 +115,20 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
export type ResolvedAsset =
| { readonly kind: "file"; readonly path: string }
| {
readonly kind: "open-file";
readonly path: string;
readonly stream: NodeFS.ReadStream;
readonly size: number;
};
class ResolvedAssetOpenError extends Data.TaggedError("ResolvedAssetOpenError")<{
readonly path: string;
readonly resource: string;
readonly cause: unknown;
}> {}
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
@@ -120,6 +157,94 @@ 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),
);
const openResolvedAssetForRequest = Effect.fn("AssetAccess.openResolvedAssetForRequest")(
function* (input: { readonly path: string; readonly resource: string }) {
const platform = yield* HostProcessPlatform;
const opened = yield* Effect.tryPromise({
try: () => openReadableFileNoFollow(input.path, platform),
catch: (cause) =>
new ResolvedAssetOpenError({
path: input.path,
resource: input.resource,
cause,
}),
});
return {
kind: "open-file",
path: input.path,
...opened,
} satisfies ResolvedAsset;
},
(effect, input) =>
effect.pipe(
Effect.tapError((cause) =>
Effect.logError("Failed to safely open resolved asset.", {
path: input.path,
resource: input.resource,
cause,
}),
),
Effect.orElseSucceed(() => null),
),
);
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 platform = yield* HostProcessPlatform;
const [canonicalDir, canonicalFile] = yield* Effect.all([
optionOnNotFound(fileSystem.realPath(path.join(config.stateDir, "browser-artifacts"))),
optionOnNotFound(
fileSystem.realPath(path.join(config.stateDir, "browser-artifacts", 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;
if (
!canonicalPathsMatch(path.join(canonicalDir.value, normalized), canonicalFile.value, platform)
) {
return null;
}
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 +265,14 @@ 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;
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 +297,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 +367,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 +407,75 @@ 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,
}),
),
);
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 +592,49 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
: null;
}
if (claims.kind === "browser-artifact") {
const artifactPath = yield* resolveCanonicalBrowserArtifact(claims.fileName);
return artifactPath
? yield* openResolvedAssetForRequest({
path: artifactPath,
resource: "browser artifact",
})
: 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;
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"
? yield* openResolvedAssetForRequest({
path: canonicalPath.value,
resource: "thread image",
})
: null;
}
if (claims.kind === "project-favicon") {
if (claims.relativePath === null) return null;
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
@@ -0,0 +1,48 @@
import {
ThreadId,
TurnItemId,
type OrchestrationV2ThreadProjection,
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import { resolveThreadImagePath } from "./ThreadImagePath.ts";
describe("resolveThreadImagePath", () => {
it("returns the path only for the exact V2 image item", () => {
const now = DateTime.makeUnsafe("2026-07-30T00:00:00.000Z");
const item = {
id: TurnItemId.make("image-item"),
threadId: ThreadId.make("thread-1"),
runId: null,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "completed" as const,
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "image_view" as const,
source: "image_view" as const,
path: "/tmp/tool-output.png",
} satisfies OrchestrationV2TurnItem;
const projection = { turnItems: [item] } satisfies Pick<
OrchestrationV2ThreadProjection,
"turnItems"
>;
expect(resolveThreadImagePath(projection, item.id)).toBe(item.path);
expect(resolveThreadImagePath(projection, TurnItemId.make("missing-item"))).toBeNull();
expect(
resolveThreadImagePath(
{ turnItems: [{ ...item, status: "running", completedAt: null }] },
item.id,
),
).toBeNull();
});
});
+14
View File
@@ -0,0 +1,14 @@
import type { OrchestrationV2ThreadProjection, TurnItemId } from "@t3tools/contracts";
export function resolveThreadImagePath(
projection: Pick<OrchestrationV2ThreadProjection, "turnItems">,
turnItemId: TurnItemId,
): string | null {
const item = projection.turnItems.find(
(candidate) =>
candidate.id === turnItemId &&
candidate.type === "image_view" &&
candidate.status === "completed",
);
return item?.type === "image_view" ? item.path : null;
}
+1
View File
@@ -143,6 +143,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(path.join(derivedPaths.stateDir, "browser-artifacts"), { recursive: true }),
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
+13 -4
View File
@@ -270,12 +270,21 @@ export const assetRouteLayer = HttpRouter.add(
if (!asset) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const assetHeaders = {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
};
if (asset.kind === "open-file") {
return HttpServerResponse.raw(asset.stream, {
status: 200,
contentLength: asset.size,
contentType: Mime.getType(asset.path) ?? "application/octet-stream",
headers: assetHeaders,
});
}
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
headers: assetHeaders,
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
+134 -4
View File
@@ -1,13 +1,31 @@
import { expect, it } from "@effect/vitest";
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { afterAll, 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,
type Project,
ProviderInstanceId,
ThreadId,
type OrchestrationV2ThreadProjection,
} 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 { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "../project/ProjectService.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 +34,27 @@ 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 projectId = ProjectId.make("project-mcp-test");
const testWorkspaceRoot = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "mcp-snapshot-test-"));
afterAll(() => NodeFS.rmSync(testWorkspaceRoot, { recursive: true, force: true }));
const testProject = {
id: projectId,
title: "MCP snapshot test",
workspaceRoot: testWorkspaceRoot,
repositoryIdentity: null,
faviconPath: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-30T00:00:00.000Z",
updatedAt: "2026-07-30T00:00:00.000Z",
deletedAt: null,
} satisfies Project;
const testProjection = {
thread: {
projectId,
worktreePath: null,
},
} as unknown as OrchestrationV2ThreadProjection;
const invocation = {
environmentId,
threadId,
@@ -36,6 +75,20 @@ const client = McpSchema.McpServerClient.of({
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provideMerge(PreviewAutomationBroker.layer.pipe(Layer.provide(NodeServices.layer))),
Layer.provideMerge(
Layer.mock(ThreadManagementService)({
getThreadProjection: () => Effect.succeed(testProjection),
}),
),
Layer.provideMerge(
Layer.mock(ProjectService.ProjectService)({
getById: (candidateProjectId) =>
Effect.succeed(candidateProjectId === projectId ? Option.some(testProject) : Option.none()),
}),
),
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 +262,9 @@ 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);
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 +323,79 @@ it.effect("registers annotated tools and preserves authenticated request context
}),
).pipe(Effect.provide(TestLayer)),
);
it.effect("persists preview snapshots to workspace and artifact destinations", () =>
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 = (arguments_: Record<string, unknown>) =>
server
.callTool({ name: "preview_snapshot", arguments: arguments_ })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
const saved = yield* callSnapshot({ savePath: "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");
expect((yield* callSnapshot({ savePath: "../outside.png" })).isError).toBe(true);
expect((yield* callSnapshot({ savePath: "evidence/login.txt" })).isError).toBe(true);
expect((yield* callSnapshot({ save: true, savePath: "evidence/login.png" })).isError).toBe(
true,
);
const savedArtifact = yield* callSnapshot({ save: true });
expect(savedArtifact.isError).toBe(false);
const artifactPath = (savedArtifact.structuredContent as { savedScreenshotPath?: string })
.savedScreenshotPath;
expect(artifactPath).toBeDefined();
expect(NodePath.dirname(artifactPath!)).toBe(
NodeFS.realpathSync(
NodePath.join((yield* ServerConfig.ServerConfig).stateDir, "browser-artifacts"),
),
);
expect(NodeFS.readFileSync(artifactPath!, "utf8")).toBe("png-bytes");
}),
).pipe(Effect.provide(TestLayer)),
);
+15
View File
@@ -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,10 @@ 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 ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
@@ -136,6 +142,14 @@ 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
| ThreadManagementService.ThreadManagementService
| ProjectService.ProjectService
| WorkspacePaths.WorkspacePaths
| FileSystem.FileSystem
| Path.Path
>();
const built = yield* PreviewSnapshotToolkit;
const tool = PreviewSnapshotTool;
yield* server.addTool({
@@ -166,6 +180,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot
Stream.run(Sink.last()),
Effect.flatMap(Effect.fromOption),
Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
Effect.provideContext(snapshotHandlerContext),
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.matchCauseEffect({
onFailure: previewSnapshotFailure,
@@ -565,6 +565,8 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null {
return jsonText({ pattern: item.pattern, results: item.results });
case "web_search":
return jsonText({ patterns: item.patterns, results: item.results });
case "image_view":
return item.path;
case "approval_request":
return item.prompt ?? item.requestKind;
case "checkpoint":
@@ -1,16 +1,32 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeCrypto from "node:crypto";
import * as Clock from "effect/Clock";
import * as Data from "effect/Data";
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 { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../../../config.ts";
import { openWritableFileNoFollow } from "../../../noFollowFile.ts";
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "../../../project/ProjectService.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 +76,191 @@ const invokeTargeted = <A>(
return invoke<A>(operation, operationInput, timeoutMs, tabId);
};
class ScreenshotFileWriteError extends Data.TaggedError("ScreenshotFileWriteError")<{
readonly path: string;
readonly cause: unknown;
}> {}
const writeScreenshotFileNoFollow = Effect.fn("PreviewToolkit.writeScreenshotFileNoFollow")(
function* (input: { readonly absolutePath: string; readonly screenshotBase64: string }) {
const platform = yield* HostProcessPlatform;
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => openWritableFileNoFollow(input.absolutePath, platform),
catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }),
}),
(handle) =>
Effect.tryPromise({
try: async () => {
const info = await handle.stat();
if (!info.isFile()) {
throw new Error(`Expected a regular screenshot destination: ${input.absolutePath}`);
}
await handle.truncate(0);
await handle.writeFile(Buffer.from(input.screenshotBase64, "base64"));
},
catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }),
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) => new ScreenshotFileWriteError({ path: input.absolutePath, cause }),
}),
);
},
);
const saveSnapshotScreenshotArtifact = Effect.fn("PreviewToolkit.saveSnapshotScreenshotArtifact")(
function* (input: {
readonly scope: McpInvocationContext.McpInvocationScope;
readonly screenshotBase64: string;
}) {
const config = yield* ServerConfig.ServerConfig;
const fileName = `browser-screenshot-${(yield* Clock.currentTimeMillis).toString(36)}-${NodeCrypto.randomUUID().slice(0, 8)}.png`;
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const artifactDirectory = yield* fileSystem
.realPath(path.join(config.stateDir, "browser-artifacts"))
.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,
}),
),
);
const absolutePath = path.join(artifactDirectory, fileName);
yield* writeScreenshotFileNoFollow({
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 threadManagement = yield* ThreadManagementService.ThreadManagementService;
const projection = yield* threadManagement
.getThreadProjection(scope.threadId)
.pipe(Effect.mapError((cause) => fail("thread-workspace-resolution", cause)));
const projectService = yield* ProjectService.ProjectService;
const project = yield* projectService
.getById(projection.thread.projectId)
.pipe(Effect.mapError((cause) => fail("thread-workspace-resolution", cause)));
if (Option.isNone(project)) {
return yield* fail("thread-lookup");
}
const workspaceRoot = projection.thread.worktreePath ?? project.value.workspaceRoot;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath: savePath })
.pipe(Effect.mapError((cause) => fail("workspace-path-validation", cause)));
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)));
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");
}
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* writeScreenshotFileNoFollow({
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 +271,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) =>
+22 -5
View File
@@ -13,14 +13,21 @@ 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 ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "../../../project/ProjectService.ts";
import * as WorkspacePaths from "../../../workspace/WorkspacePaths.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
@@ -29,6 +36,16 @@ const dependencies = [
PreviewAutomationBroker.PreviewAutomationBroker,
];
const snapshotDependencies = [
...dependencies,
ServerConfig.ServerConfig,
ThreadManagementService.ThreadManagementService,
ProjectService.ProjectService,
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 +118,14 @@ export const PreviewSetAppearanceTool = safeBrowserTool(
.annotate(Tool.Idempotent, true),
);
export const PreviewSnapshotTool = readonlyBrowserTool(
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. Pass save:true to persist temporary visual evidence and receive savedScreenshotPath. Use savePath only when the PNG should live inside the thread workspace.",
parameters: PreviewAutomationSnapshotInput,
success: PreviewAutomationSnapshot,
failure: PreviewAutomationError,
dependencies,
dependencies: snapshotDependencies,
}).annotate(Tool.Title, "Inspect browser page"),
);
@@ -192,7 +209,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. Embed the returned .webm path in markdown to render a playable chat preview.",
parameters: PreviewAutomationTabTargetInput,
success: PreviewAutomationRecordingArtifact,
failure: PreviewAutomationError,
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "@effect/vitest";
import { canonicalPathsMatch } from "./noFollowFile.ts";
describe("canonicalPathsMatch", () => {
it("accepts canonical Windows paths whose casing differs", () => {
expect(
canonicalPathsMatch(
String.raw`C:\Users\Example\capture.png`,
String.raw`C:\Users\example\CAPTURE.png`,
"win32",
),
).toBe(true);
});
it("keeps canonical path comparison case-sensitive on other platforms", () => {
expect(
canonicalPathsMatch("/Users/Example/capture.png", "/users/example/capture.png", "darwin"),
).toBe(false);
});
it("rejects Windows paths that differ by more than casing", () => {
expect(
canonicalPathsMatch(
String.raw`C:\Users\Example\capture.png`,
String.raw`C:\Users\Example\outside.png`,
"win32",
),
).toBe(false);
});
});
+146
View File
@@ -0,0 +1,146 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import type * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
// Node does not expose Darwin's all-components no-follow flag.
const DARWIN_O_NOFOLLOW_ANY = 0x20000000;
function errnoCode(cause: unknown): string | undefined {
return cause instanceof Error && "code" in cause && typeof cause.code === "string"
? cause.code
: undefined;
}
async function openLinuxPath(
absolutePath: string,
flags: number,
mode?: number,
): Promise<NodeFSP.FileHandle> {
const segments = absolutePath.split(NodePath.sep).filter(Boolean);
const fileName = segments.pop();
if (!fileName || segments.some((segment) => segment === "." || segment === "..")) {
throw new Error(`Cannot safely open non-canonical path: ${absolutePath}`);
}
let directory = await NodeFS.promises.open(
NodePath.sep,
NodeFS.constants.O_RDONLY | NodeFS.constants.O_DIRECTORY,
);
try {
for (const segment of segments) {
const nextDirectory = await NodeFS.promises.open(
`/proc/self/fd/${directory.fd}/${segment}`,
NodeFS.constants.O_RDONLY | NodeFS.constants.O_DIRECTORY | NodeFS.constants.O_NOFOLLOW,
);
await directory.close();
directory = nextDirectory;
}
return await NodeFS.promises.open(
`/proc/self/fd/${directory.fd}/${fileName}`,
flags | NodeFS.constants.O_NOFOLLOW,
mode,
);
} finally {
await directory.close();
}
}
async function verifyFallbackHandle(
absolutePath: string,
handle: NodeFSP.FileHandle,
platform: NodeJS.Platform,
): Promise<NodeFSP.FileHandle> {
try {
const handleInfo = await handle.stat();
const canonicalPath = await NodeFS.promises.realpath(absolutePath);
const pathInfo = await NodeFS.promises.stat(absolutePath);
if (
!canonicalPathsMatch(absolutePath, canonicalPath, platform) ||
pathInfo.dev !== handleInfo.dev ||
pathInfo.ino !== handleInfo.ino
) {
throw new Error(`Path changed while it was being opened: ${absolutePath}`);
}
return handle;
} catch (cause) {
await handle.close();
throw cause;
}
}
export function canonicalPathsMatch(
absolutePath: string,
canonicalPath: string,
platform: NodeJS.Platform,
): boolean {
if (canonicalPath === absolutePath) {
return true;
}
return platform === "win32" && canonicalPath.toLowerCase() === absolutePath.toLowerCase();
}
async function openPathNoFollow(
absolutePath: string,
flags: number,
platform: NodeJS.Platform,
mode?: number,
): Promise<NodeFSP.FileHandle> {
if (!NodePath.isAbsolute(absolutePath) || NodePath.resolve(absolutePath) !== absolutePath) {
throw new Error(`Cannot safely open non-canonical path: ${absolutePath}`);
}
if (platform === "darwin") {
return NodeFS.promises.open(absolutePath, flags | DARWIN_O_NOFOLLOW_ANY, mode);
}
if (platform === "linux") {
return openLinuxPath(absolutePath, flags, mode);
}
const noFollow = NodeFS.constants.O_NOFOLLOW ?? 0;
const handle = await NodeFS.promises.open(absolutePath, flags | noFollow, mode);
return verifyFallbackHandle(absolutePath, handle, platform);
}
export async function openReadableFileNoFollow(
absolutePath: string,
platform: NodeJS.Platform,
): Promise<{
readonly stream: NodeFS.ReadStream;
readonly size: number;
}> {
const handle = await openPathNoFollow(absolutePath, NodeFS.constants.O_RDONLY, platform);
try {
const info = await handle.stat();
if (!info.isFile()) {
throw new Error(`Expected a regular file: ${absolutePath}`);
}
return {
stream: handle.createReadStream({ autoClose: true }),
size: info.size,
};
} catch (cause) {
await handle.close();
throw cause;
}
}
export async function openWritableFileNoFollow(
absolutePath: string,
platform: NodeJS.Platform,
): Promise<NodeFSP.FileHandle> {
try {
return await openPathNoFollow(absolutePath, NodeFS.constants.O_WRONLY, platform);
} catch (cause) {
if (errnoCode(cause) !== "ENOENT") {
throw cause;
}
return openPathNoFollow(
absolutePath,
NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL,
platform,
0o666,
);
}
}
@@ -57,6 +57,7 @@ import {
makeCodexAppServerProtocolLogger,
makeCodexAppServerSpawnCommand,
projectCodexDynamicToolItem,
projectCodexImageItem,
resolveCodexRollbackTurnCount,
} from "./CodexAdapterV2.ts";
import { makeReplayServerConfig } from "./CodexAdapterV2.testkit.ts";
@@ -609,6 +610,47 @@ describe("CodexAdapterV2 dynamic tool projection", () => {
});
});
describe("CodexAdapterV2 image projection", () => {
it("projects image-view paths into durable media items", () => {
assert.deepEqual(
projectCodexImageItem({
id: "image-view-1",
type: "imageView",
path: "/workspace/evidence.png",
}),
{
source: "image_view",
path: "/workspace/evidence.png",
},
);
});
it("projects saved image-generation paths and ignores unsaved results", () => {
assert.deepEqual(
projectCodexImageItem({
id: "image-generation-1",
type: "imageGeneration",
result: "generated",
savedPath: "/workspace/generated.png",
status: "completed",
}),
{
source: "image_generation",
path: "/workspace/generated.png",
},
);
assert.isNull(
projectCodexImageItem({
id: "image-generation-2",
type: "imageGeneration",
result: "generated",
savedPath: null,
status: "completed",
}),
);
});
});
describe("CodexAdapterV2 native protocol logging", () => {
it.effect("writes app-server protocol frames to the native provider log", () =>
Effect.gen(function* () {
@@ -909,6 +909,25 @@ type CodexWebSearchItem = {
| null;
};
export type CodexImageItem = Extract<
| CodexSchema.V2ItemStartedNotification__ThreadItem
| CodexSchema.V2ItemCompletedNotification__ThreadItem,
{ readonly type: "imageView" | "imageGeneration" }
>;
export function projectCodexImageItem(
item: CodexImageItem,
): { readonly source: "image_view" | "image_generation"; readonly path: string } | null {
const rawPath = item.type === "imageView" ? item.path : item.savedPath;
if (typeof rawPath !== "string") return null;
const path = rawPath.trim();
if (path.length === 0) return null;
return {
source: item.type === "imageView" ? "image_view" : "image_generation",
path,
};
}
export type CodexDynamicToolItem = Extract<
| CodexSchema.V2ItemStartedNotification__ThreadItem
| CodexSchema.V2ItemCompletedNotification__ThreadItem,
@@ -2698,6 +2717,66 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return { node, turnItem };
});
const buildImageArtifacts = (
context: ActiveCodexTurnContext,
item: CodexImageItem,
completed: boolean,
) =>
Effect.gen(function* () {
const projection = projectCodexImageItem(item);
if (projection === null) return null;
const updatedAt = yield* DateTime.now;
const completedAt = completed ? updatedAt : null;
const status = completed ? "completed" : "running";
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver: CODEX_PROVIDER,
nativeItemId: item.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
driver: CODEX_PROVIDER,
nativeItemId: item.id,
});
const ordinal = yield* resolveItemOrdinal(context, item.id);
const node: OrchestrationV2ExecutionNode = {
id: nodeId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
parentNodeId: context.itemParentNodeId,
rootNodeId: context.rootNodeId,
kind: "tool_call",
status,
countsForRun: false,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: context.startedAt,
completedAt,
};
const turnItem: OrchestrationV2TurnItem = {
id: turnItemId,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
nodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
nativeItemRef: codexNativeItemRef(item.id),
parentItemId: null,
ordinal,
status,
title: null,
startedAt: context.startedAt,
completedAt,
updatedAt,
type: "image_view",
source: projection.source,
path: projection.path,
};
return { node, turnItem };
});
const buildDynamicToolArtifacts = (
context: ActiveCodexTurnContext,
item: CodexDynamicToolItem,
@@ -3333,6 +3412,22 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return;
}
if (payload.item.type === "imageView" || payload.item.type === "imageGeneration") {
const artifacts = yield* buildImageArtifacts(context, payload.item, false);
if (artifacts === null) return;
yield* emitProviderEvent({
type: "node.updated",
driver: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type !== "webSearch") {
return;
}
@@ -3457,6 +3552,22 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
return;
}
if (payload.item.type === "imageView" || payload.item.type === "imageGeneration") {
const artifacts = yield* buildImageArtifacts(context, payload.item, true);
if (artifacts === null) return;
yield* emitProviderEvent({
type: "node.updated",
driver: CODEX_PROVIDER,
node: artifacts.node,
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CODEX_PROVIDER,
turnItem: artifacts.turnItem,
});
return;
}
if (payload.item.type === "fileChange") {
const artifacts = yield* buildFileChangeArtifacts(context, payload.item);
if (artifacts === null) {
+27
View File
@@ -48,6 +48,8 @@ import {
type ServerSelfUpdateProgressEvent,
type FilesystemBrowseFailure,
FilesystemBrowseError,
AssetThreadImageNotFoundError,
AssetThreadImageResolutionError,
AssetWorkspaceContextNotFoundError,
AssetWorkspaceContextResolutionError,
ChatAttachmentId,
@@ -101,6 +103,7 @@ import * as TerminalManager from "./terminal/Manager.ts";
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
import * as PreviewManager from "./preview/Manager.ts";
import { issueAssetUrl } from "./assets/AssetAccess.ts";
import { resolveThreadImagePath } from "./assets/ThreadImagePath.ts";
import { attachmentRelativePath, createDeterministicAttachmentId } from "./attachmentStore.ts";
import { parseBase64DataUrl } from "./imageMime.ts";
import * as PortScanner from "./preview/PortScanner.ts";
@@ -1564,6 +1567,30 @@ const makeWsRpcLayer = (
observeRpcEffect(
WS_METHODS.assetsCreateUrl,
Effect.gen(function* () {
if (input.resource._tag === "thread-image") {
const resource = input.resource;
const projection = yield* threadManagement
.getThreadProjection(resource.threadId)
.pipe(
Effect.mapError(
(cause) =>
new AssetThreadImageResolutionError({
resource,
cause,
}),
),
);
const threadImagePath = resolveThreadImagePath(projection, resource.turnItemId);
if (threadImagePath === null) {
return yield* new AssetThreadImageNotFoundError({
resource,
});
}
return yield* issueAssetUrl({
resource,
threadImagePath,
});
}
if (input.resource._tag !== "workspace-file") {
return yield* issueAssetUrl({ resource: input.resource });
}