Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AssetAccess.test.ts

1,017 lines44.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - tests inject swaps at the native open boundary.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
4import * as NodeFSP from "node:fs/promises";
5import {
6 AssetAccessError,
7 AssetCreateUrlInput,
8 AssetPreviewTypeValidationError,
9 SOURCE_CONTROL_MEDIA_ASSET,
10 ThreadId,
11 TurnItemId,
12} from "@t3tools/contracts";
13import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
14import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
15import { describe, expect, it } from "@effect/vitest";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Path from "effect/Path";
21import * as PlatformError from "effect/PlatformError";
22import * as Schema from "effect/Schema";
23import * as TestClock from "effect/testing/TestClock";
24import { HttpClientRequest, HttpClientResponse, HttpServerResponse } from "effect/http";
25import { vi } from "vite-plus/test";
26​
27import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
28import * as ServerConfig from "../config.ts";
29import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
30import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
31import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
32import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
33import { assetFileResponse } from "../http.ts";
34import { ASSET_ROUTE_PREFIX, issueAssetUrl, readMcpAppHtml, resolveAsset } from "./AssetAccess.ts";
35import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
36import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
37import { fakeSourceControlDriverInstance } from "@t3tools/source-control-testing/fakeSourceControlDriver";
38import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
39import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
40import { sourceControlMediaResponse } from "./sourceControlMediaResponse.ts";
41import * as HostProcess from "@t3tools/shared/HostProcess";
42​
43vi.mock("node:fs/promises", async (importOriginal) => {
44 const actual = await importOriginal<typeof NodeFSP>();
45 return { ...actual, open: vi.fn(actual.open), realpath: vi.fn(actual.realpath) };
46});
47​
48const layerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
49 prefix: "t3-asset-access-test-",
50});
51const screenshotPng = new Uint8Array(24);
52screenshotPng.set([
53 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52,
54]);
55new DataView(screenshotPng.buffer).setUint32(16, 390);
56new DataView(screenshotPng.buffer).setUint32(20, 844);
57const screenshotItem = {
58 id: TurnItemId.make("tool-screenshot"),
59 type: "dynamic_tool" as const,
60 threadId: ThreadId.make("thread-1"),
61 runId: null,
62 nodeId: null,
63 providerThreadId: null,
64 providerTurnId: null,
65 nativeItemRef: null,
66 parentItemId: null,
67 ordinal: 1,
68 status: "completed" as const,
69 title: null,
70 toolName: "mcp__t3-code__device_screenshot",
71 input: { deviceId: "phone" },
72 output: {
73 content: [
74 {
75 type: "image",
76 source: {
77 type: "base64",
78 media_type: "image/png",
79 data: Buffer.from(screenshotPng).toString("base64"),
80 },
81 },
82 ],
83 },
84 startedAt: DateTime.makeUnsafe("2026-10-05T00:00:00.000Z"),
85 completedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),
86 updatedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),
87};
88​
89const oversizedScreenshotItem = {
90 ...screenshotItem,
91 id: TurnItemId.make("tool-screenshot-oversized"),
92 output: {
93 content: [
94 {
95 type: "image",
96 source: { type: "base64", media_type: "image/png", data: "A".repeat(14 * 1024 * 1024) },
97 },
98 ],
99 },
100};
101​
102const layerTest = Layer.mergeAll(
103 NodeHttpPlatform.layer,
104 Layer.mock(Orchestrator.OrchestratorV2)({
105 getTurnItem: ({ itemId }) =>
106 Effect.succeed(
107 itemId === screenshotItem.id
108 ? screenshotItem
109 : itemId === oversizedScreenshotItem.id
110 ? oversizedScreenshotItem
111 : null,
112 ),
113 }),
114 layerConfig,
115 WorkspacePaths.layer,
116 ProjectFaviconResolver.layer.pipe(
117 Layer.provide(WorkspacePaths.layer),
118 Layer.provide(T3ProjectFileLoader.layer),
119 ),
120 NativeAppIconResolver.layer.pipe(Layer.provide(layerConfig)),
121 ServerSecretStore.layer.pipe(Layer.provide(layerConfig)),
122).pipe(Layer.provideMerge(NodeServices.layer));
123​
124describe("AssetAccess", () => {
125 describe("readMcpAppHtml", () => {
126 it.effect("accepts snapshots at the stored HTML byte limit", () =>
127 Effect.gen(function* () {
128 const fileSystem = yield* FileSystem.FileSystem;
129 const path = yield* Path.Path;
130 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
131 const file = path.join(directory, "app.html");
132 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
133 yield* fileSystem.writeFile(file, new Uint8Array(limit).fill(120));
134​
135 const bytes = yield* readMcpAppHtml(file);
136 expect(bytes?.byteLength).toBe(limit);
137 expect(bytes?.every((byte) => byte === 120)).toBe(true);
138 }).pipe(Effect.provide(NodeServices.layer)),
139 );
140​
141 it.effect("rejects snapshots one byte past the limit and much larger files", () =>
142 Effect.gen(function* () {
143 const fileSystem = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
146 const file = path.join(directory, "app.html");
147 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
148 for (const size of [limit + 1, limit * 2]) {
149 yield* fileSystem.writeFile(file, new Uint8Array(size).fill(120));
150 expect(yield* readMcpAppHtml(file)).toBeNull();
151 }
152 }).pipe(Effect.provide(NodeServices.layer)),
153 );
154​
155 it.effect("preserves UTF-8 bytes across stream chunks and accepts empty snapshots", () =>
156 Effect.gen(function* () {
157 const fileSystem = yield* FileSystem.FileSystem;
158 const path = yield* Path.Path;
159 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
160 const file = path.join(directory, "app.html");
161 for (const html of ["", "<body>" + "☃".repeat(100_000) + "</body>"]) {
162 const expected = new TextEncoder().encode(html);
163 yield* fileSystem.writeFile(file, expected);
164 const bytes = yield* readMcpAppHtml(file);
165 expect(bytes?.byteLength).toBe(expected.byteLength);
166 expect(bytes && new TextDecoder().decode(bytes)).toBe(html);
167 }
168 }).pipe(Effect.provide(NodeServices.layer)),
169 );
170​
171 // regression: #17026 apply host color scheme to saved MCP apps
172 it.effect("preserves filesystem failures instead of reporting oversized HTML", () =>
173 Effect.gen(function* () {
174 const fileSystem = yield* FileSystem.FileSystem;
175 const path = yield* Path.Path;
176 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
177 const error = yield* readMcpAppHtml(path.join(directory, "missing.html")).pipe(Effect.flip);
178 expect(error._tag).toBe("PlatformError");
179 expect(error.reason._tag).toBe("NotFound");
180 }).pipe(Effect.provide(NodeServices.layer)),
181 );
182 });
183​
184 it.effect("serves an image a tool returned inline from the stored item", () =>
185 Effect.gen(function* () {
186 const resource = {
187 _tag: "tool-output-image" as const,
188 threadId: screenshotItem.threadId,
189 itemId: screenshotItem.id,
190 index: 0,
191 };
192 const result = yield* issueAssetUrl({ resource });
193 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
194 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
195 const separator = suffix.indexOf("/");
196 expect(yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1))).toEqual({
197 kind: "bytes",
198 mimeType: "image/png",
199 bytes: Buffer.from(screenshotPng),
200 });
201 const missing = yield* issueAssetUrl({ resource: { ...resource, index: 1 } }).pipe(
202 Effect.flip,
203 );
204 expect(missing._tag).toBe("AssetWorkspaceAssetNotFoundError");
205 const oversized = yield* issueAssetUrl({
206 resource: { ...resource, itemId: oversizedScreenshotItem.id },
207 }).pipe(Effect.flip);
208 expect(oversized._tag).toBe("AssetWorkspaceAssetNotFoundError");
209 }).pipe(Effect.provide(layerTest)),
210 );
211​
212 it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
213 Effect.gen(function* () {
214 const fs = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-root-" });
217 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-outside-" });
218 for (const [name, mimeType] of [
219 ["screenshot.png", "image/png"],
220 ["recording.mp4", "video/mp4"],
221 ["recording.webm", "video/webm"],
222 ["report.html", "text/html"],
223 ["report.pdf", "application/pdf"],
224 ] as const) {
225 const filePath = path.join(outside, name);
226 yield* fs.writeFileString(filePath, "media");
227 const canonicalFile = yield* fs.realPath(filePath);
228 const result = yield* issueAssetUrl({
229 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
230 workspaceRoot: root,
231 });
232 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
233 const separator = suffix.indexOf("/");
234 const token = suffix.slice(0, separator);
235 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
236 kind: "file",
237 path: canonicalFile,
238 mimeType,
239 });
240 yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
241 expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
242 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
243 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
244 }
245 }).pipe(Effect.provide(layerTest)),
246 );
247​
248 it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
249 Effect.gen(function* () {
250 const fs = yield* FileSystem.FileSystem;
251 const path = yield* Path.Path;
252 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
253 const root = path.join(directory, "workspace");
254 yield* fs.makeDirectory(root);
255 for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
256 const filePath = path.resolve(root, relativePath);
257 yield* fs.writeFileString(filePath, "media");
258 const result = yield* issueAssetUrl({
259 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
260 workspaceRoot: root,
261 });
262 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
263 const separator = suffix.indexOf("/");
264 expect(
265 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
266 ).toMatchObject({
267 kind: "file",
268 path: yield* fs.realPath(filePath),
269 });
270 }
271 }).pipe(Effect.provide(layerTest)),
272 );
273​
274 it.effect("resolves home-relative media paths independently of the workspace", () =>
275 Effect.gen(function* () {
276 const fs = yield* FileSystem.FileSystem;
277 const path = yield* Path.Path;
278 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
279 const home = path.join(directory, "var", "home", "alice");
280 const filePath = path.join(home, "Downloads", "repro.mp4");
281 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
282 yield* fs.writeFileString(filePath, "recording bytes");
283 const canonicalFile = yield* fs.realPath(filePath);
284 yield* Effect.gen(function* () {
285 for (const workspaceRoot of [
286 path.join(home, "project"),
287 path.join(directory, "srv", "project"),
288 undefined,
289 ]) {
290 if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
291 for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
292 const result = yield* issueAssetUrl({
293 resource: {
294 _tag: "media-file",
295 threadId: ThreadId.make("thread-1"),
296 path: requestedPath,
297 },
298 ...(workspaceRoot ? { workspaceRoot } : {}),
299 });
300 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
301 const separator = suffix.indexOf("/");
302 const asset = yield* resolveAsset(
303 suffix.slice(0, separator),
304 suffix.slice(separator + 1),
305 );
306 expect(asset).toMatchObject({
307 kind: "file",
308 path: canonicalFile,
309 mimeType: "video/mp4",
310 });
311 if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
312 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
313 expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
314 }
315 }
316 }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
317 }).pipe(Effect.provide(layerTest)),
318 );
319​
320 // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
321 // Windows user's NTLM credentials to attacker.test.
322 it.effect("never resolves a network media path outside the thread's project", () =>
323 Effect.gen(function* () {
324 const fs = yield* FileSystem.FileSystem;
325 const path = yield* Path.Path;
326 const resolved: Array<string> = [];
327 const recordingFileSystem = FileSystem.FileSystem.of({
328 ...fs,
329 realPath: (requestedPath) => {
330 resolved.push(requestedPath);
331 return Effect.fail(
332 PlatformError.systemError({
333 _tag: "NotFound",
334 module: "FileSystem",
335 method: "realPath",
336 pathOrDescriptor: requestedPath,
337 }),
338 );
339 },
340 });
341 const share = "//nas.test/share/project";
342 for (const resource of [
343 {
344 _tag: "media-file",
345 threadId: ThreadId.make("thread-1"),
346 path: "//attacker.test/s/a.png",
347 },
348 { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
349 { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
350 ] as const) {
351 const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
352 Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
353 Effect.flip,
354 );
355 expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
356 }
357 expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
358 }).pipe(Effect.provide(layerTest)),
359 );
360​
361 it.effect.skipIf(!symlinksSupported)(
362 "rejects non-previewable files, disguised targets, and directories",
363 () =>
364 Effect.gen(function* () {
365 const fs = yield* FileSystem.FileSystem;
366 const path = yield* Path.Path;
367 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
368 for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
369 const filePath = path.join(root, name);
370 yield* fs.writeFileString(filePath, "not media");
371 const error = yield* issueAssetUrl({
372 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
373 }).pipe(Effect.flip);
374 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
375 }
376 const disguisedPath = path.join(root, "disguised.png");
377 yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
378 const disguisedError = yield* issueAssetUrl({
379 resource: {
380 _tag: "media-file",
381 threadId: ThreadId.make("thread-1"),
382 path: disguisedPath,
383 },
384 }).pipe(Effect.flip);
385 expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
386 const directoryPath = path.join(root, "directory.png");
387 yield* fs.makeDirectory(directoryPath);
388 const directoryError = yield* issueAssetUrl({
389 resource: {
390 _tag: "media-file",
391 threadId: ThreadId.make("thread-1"),
392 path: directoryPath,
393 },
394 }).pipe(Effect.flip);
395 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
396 }).pipe(Effect.provide(layerTest)),
397 );
398​
399 it.effect.skipIf(!symlinksSupported)(
400 "binds media URLs to the canonical target and rejects symlink substitution",
401 () =>
402 Effect.gen(function* () {
403 const fs = yield* FileSystem.FileSystem;
404 const path = yield* Path.Path;
405 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
406 const filePath = path.join(root, "actual.svg");
407 const aliasPath = path.join(root, "alias.png");
408 const replacementPath = path.join(root, "other.svg");
409 yield* fs.writeFileString(filePath, "<svg/>");
410 yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
411 yield* fs.symlink(filePath, aliasPath);
412 const canonicalFile = yield* fs.realPath(filePath);
413 const result = yield* issueAssetUrl({
414 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
415 });
416 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
417 const separator = suffix.indexOf("/");
418 const token = suffix.slice(0, separator);
419 const name = suffix.slice(separator + 1);
420 const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
421 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
422 yield* fs.remove(aliasPath);
423 yield* fs.symlink(replacementPath, aliasPath);
424 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
425 yield* fs.remove(filePath);
426 yield* fs.symlink(replacementPath, filePath);
427 expect(yield* resolveAsset(token, name)).toBeNull();
428 }).pipe(Effect.provide(layerTest)),
429 );
430​
431 it.effect.skipIf(!symlinksSupported)(
432 "keeps full and partial responses bound to the file opened during resolution",
433 () =>
434 Effect.gen(function* () {
435 const fs = yield* FileSystem.FileSystem;
436 const path = yield* Path.Path;
437 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
438 const filePath = path.join(root, "recording.mp4");
439 const savedPath = path.join(root, "saved.mp4");
440 const secretPath = path.join(root, "secret.txt");
441 yield* fs.writeFileString(filePath, "0123456789");
442 yield* fs.writeFileString(secretPath, "private information");
443 const result = yield* issueAssetUrl({
444 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
445 });
446 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
447 const separator = suffix.indexOf("/");
448 for (const [range, expected, status] of [
449 [undefined, "0123456789", 200],
450 ["bytes=2-5", "2345", 206],
451 ] as const) {
452 const asset = yield* resolveAsset(
453 suffix.slice(0, separator),
454 suffix.slice(separator + 1),
455 );
456 if (asset?.kind !== "file") throw new Error("Expected a resolved media file");
457​
458 yield* fs.rename(filePath, savedPath);
459 yield* fs.symlink(secretPath, filePath);
460 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
461 expect(response.status).toBe(status);
462 expect(response.headers.get("content-length")).toBe(String(expected.length));
463 expect(yield* Effect.promise(() => response.text())).toBe(expected);
464 yield* fs.remove(filePath);
465 yield* fs.rename(savedPath, filePath);
466 }
467 }).pipe(Effect.provide(layerTest)),
468 );
469​
470 it.effect.skipIf(!symlinksSupported)(
471 "rejects a symlink swapped in after canonical validation but before open",
472 () =>
473 Effect.gen(function* () {
474 const fs = yield* FileSystem.FileSystem;
475 const path = yield* Path.Path;
476 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
477 const filePath = path.join(root, "recording.mp4");
478 const secretPath = path.join(root, "secret.txt");
479 yield* fs.writeFileString(filePath, "video");
480 yield* fs.writeFileString(secretPath, "secret");
481 const canonicalPath = yield* fs.realPath(filePath);
482 const result = yield* issueAssetUrl({
483 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
484 });
485 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
486 const separator = suffix.indexOf("/");
487 const swappingFileSystem = FileSystem.FileSystem.of({
488 ...fs,
489 stat: Effect.fn(function* (requestedPath) {
490 const info = yield* fs.stat(requestedPath);
491 if (requestedPath === canonicalPath) {
492 yield* fs.remove(filePath);
493 yield* fs.symlink(secretPath, filePath);
494 }
495 return info;
496 }),
497 });
498 expect(
499 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
500 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
501 ),
502 ).toBeNull();
503 }).pipe(Effect.provide(layerTest)),
504 );
505​
506 it.effect.skipIf(!symlinksSupported)(
507 "rejects an ancestor symlink race even when canonical path rechecks would pass",
508 () =>
509 Effect.gen(function* () {
510 const fs = yield* FileSystem.FileSystem;
511 const path = yield* Path.Path;
512 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
513 const publicDirectory = path.join(root, "public");
514 const privateDirectory = path.join(root, "private");
515 yield* fs.makeDirectory(publicDirectory);
516 yield* fs.makeDirectory(privateDirectory);
517 const filePath = path.join(publicDirectory, "recording.mp4");
518 yield* fs.writeFileString(filePath, "public video");
519 yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
520 const canonicalPath = yield* fs.realPath(filePath);
521 const result = yield* issueAssetUrl({
522 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
523 });
524 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
525 const separator = suffix.indexOf("/");
526 const native = yield* Effect.promise(() =>
527 vi.importActual<typeof NodeFSP>("node:fs/promises"),
528 );
529 const savedDirectory = path.join(root, "saved");
530 const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
531 await native.unlink(publicDirectory);
532 await native.rename(savedDirectory, publicDirectory);
533 const canonical = await native.realpath(canonicalPath);
534 await native.rename(publicDirectory, savedDirectory);
535 await native.symlink(privateDirectory, publicDirectory, "junction");
536 return canonical;
537 });
538 yield* Effect.addFinalizer(() =>
539 Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
540 );
541 const swappingFileSystem = FileSystem.FileSystem.of({
542 ...fs,
543 realPath: Effect.fn(function* (requestedPath) {
544 const canonical = yield* fs.realPath(requestedPath);
545 if (requestedPath === canonicalPath) {
546 yield* fs.rename(publicDirectory, savedDirectory);
547 yield* Effect.promise(() =>
548 NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
549 );
550 }
551 return canonical;
552 }),
553 });
554 expect(
555 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
556 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
557 ),
558 ).toBeNull();
559 }).pipe(Effect.provide(layerTest)),
560 );
561​
562 it.effect("versions media by file changes rather than by re-signing", () =>
563 Effect.gen(function* () {
564 const fs = yield* FileSystem.FileSystem;
565 const path = yield* Path.Path;
566 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-revision-" });
567 const filePath = path.join(root, "recording.mp4");
568 yield* fs.writeFileString(filePath, "original");
569 yield* Effect.promise(() => NodeFSP.utimes(filePath, 1_000, 1_000));
570 const input = {
571 resource: {
572 _tag: "media-file" as const,
573 threadId: ThreadId.make("thread-1"),
574 path: filePath,
575 },
576 };
577 const original = yield* issueAssetUrl(input);
578 expect(original.fileRevision).toEqual(expect.any(String));
579​
580 yield* TestClock.adjust("1 minute");
581 const renewed = yield* issueAssetUrl(input);
582 expect(renewed.relativeUrl).not.toBe(original.relativeUrl);
583 expect(renewed.fileRevision).toBe(original.fileRevision);
584​
585 yield* fs.writeFileString(filePath, "modified");
586 yield* Effect.promise(() => NodeFSP.utimes(filePath, 2_000, 2_000));
587 const edited = yield* issueAssetUrl(input);
588 expect(edited.fileRevision).not.toBe(original.fileRevision);
589​
590 const replacement = path.join(root, "replacement.mp4");
591 yield* fs.writeFileString(replacement, "modified");
592 yield* Effect.promise(() => NodeFSP.utimes(replacement, 2_000, 2_000));
593 yield* fs.rename(replacement, filePath);
594 const replaced = yield* issueAssetUrl(input);
595 expect(replaced.fileRevision).not.toBe(edited.fileRevision);
596 }).pipe(Effect.provide(layerTest)),
597 );
598​
599 it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
600 Effect.gen(function* () {
601 const fs = yield* FileSystem.FileSystem;
602 const path = yield* Path.Path;
603 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
604 const filePath = path.join(root, "recording.mp4");
605 yield* fs.writeFileString(filePath, "original");
606 const input = {
607 resource: {
608 _tag: "media-file" as const,
609 threadId: ThreadId.make("thread-1"),
610 path: filePath,
611 },
612 };
613 const original = yield* issueAssetUrl(input);
614 const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
615 const separator = suffix.indexOf("/");
616 const token = suffix.slice(0, separator);
617 const name = suffix.slice(separator + 1);
618 yield* fs.writeFileString(filePath, "in-place edit");
619 const edited = yield* resolveAsset(token, name);
620 if (edited?.kind !== "file") throw new Error("Expected the edited media file");
621 const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
622 expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
623​
624 const replacement = path.join(root, "replacement.mp4");
625 yield* fs.writeFileString(replacement, "replacement");
626 yield* fs.rename(replacement, filePath);
627 expect(yield* resolveAsset(token, name)).toBeNull();
628​
629 const renewed = yield* issueAssetUrl(input);
630 const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
631 const renewedSeparator = renewedSuffix.indexOf("/");
632 const renewedAsset = yield* resolveAsset(
633 renewedSuffix.slice(0, renewedSeparator),
634 renewedSuffix.slice(renewedSeparator + 1),
635 );
636 if (renewedAsset?.kind !== "file") throw new Error("Expected the replacement media file");
637 const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
638 expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
639 yield* fs.remove(filePath);
640 expect(
641 yield* resolveAsset(
642 renewedSuffix.slice(0, renewedSeparator),
643 renewedSuffix.slice(renewedSeparator + 1),
644 ),
645 ).toBeNull();
646 }).pipe(Effect.provide(layerTest)),
647 );
648​
649 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
650 Effect.gen(function* () {
651 const fileSystem = yield* FileSystem.FileSystem;
652 const path = yield* Path.Path;
653 const root = yield* fileSystem.makeTempDirectoryScoped({
654 prefix: "t3-asset-workspace-",
655 });
656 const htmlPath = path.join(root, "report.html");
657 const cssPath = path.join(root, "report.css");
658 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
659 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
660 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
661 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
662 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
663​
664 const result = yield* issueAssetUrl({
665 resource: {
666 _tag: "workspace-file",
667 threadId: ThreadId.make("thread-1"),
668 path: htmlPath,
669 },
670 workspaceRoot: root,
671 });
672 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
673 const separatorIndex = suffix.indexOf("/");
674 const token = suffix.slice(0, separatorIndex);
675​
676 expect(yield* resolveAsset(token, "report.html")).toEqual({
677 kind: "file",
678 path: canonicalHtmlPath,
679 });
680 expect(yield* resolveAsset(token, "report.css")).toEqual({
681 kind: "file",
682 path: canonicalCssPath,
683 });
684 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
685 expect(yield* resolveAsset(token, ".env")).toBeNull();
686 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
687 }).pipe(Effect.provide(layerTest)),
688 );
689​
690 it.effect("rejects workspace files outside the authorized root", () =>
691 Effect.gen(function* () {
692 const fileSystem = yield* FileSystem.FileSystem;
693 const path = yield* Path.Path;
694 const root = yield* fileSystem.makeTempDirectoryScoped({
695 prefix: "t3-asset-root-",
696 });
697 const outside = yield* fileSystem.makeTempDirectoryScoped({
698 prefix: "t3-asset-outside-",
699 });
700 const htmlPath = path.join(outside, "report.html");
701 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
702​
703 const error = yield* issueAssetUrl({
704 resource: {
705 _tag: "workspace-file",
706 threadId: ThreadId.make("thread-1"),
707 path: htmlPath,
708 },
709 workspaceRoot: root,
710 }).pipe(Effect.flip);
711 expect(error.message).toBe("Workspace file path must be relative to the project root.");
712 expect(error).toMatchObject({
713 _tag: "AssetWorkspacePathValidationError",
714 resource: {
715 _tag: "workspace-file",
716 threadId: "thread-1",
717 path: htmlPath,
718 },
719 });
720 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
721 }).pipe(Effect.provide(layerTest)),
722 );
723​
724 it.effect("previews workspace files with literal fragment characters in their paths", () =>
725 Effect.gen(function* () {
726 const fileSystem = yield* FileSystem.FileSystem;
727 const path = yield* Path.Path;
728 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-preview-literal-" });
729 const directory = path.join(root, "assets#archive");
730 yield* fileSystem.makeDirectory(directory);
731​
732 for (const name of ["icon#v2.png", "report#draft.pdf"]) {
733 const filePath = path.join(directory, name);
734 yield* fileSystem.writeFileString(filePath, "preview fixture");
735 const canonicalFile = yield* fileSystem.realPath(filePath);
736 const result = yield* issueAssetUrl({
737 resource: {
738 _tag: "workspace-file",
739 threadId: ThreadId.make("thread-1"),
740 path: filePath,
741 },
742 workspaceRoot: root,
743 });
744 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
745 const token = suffix.slice(0, suffix.indexOf("/"));
746​
747 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalFile });
748 if (name.endsWith(".png")) {
749 expect(yield* resolveAsset(token, "other.png")).toBeNull();
750 }
751 }
752​
753 const disguisedPath = path.join(root, "image.png#notes.txt");
754 yield* fileSystem.writeFileString(disguisedPath, "not an image");
755 const error = yield* issueAssetUrl({
756 resource: {
757 _tag: "workspace-file",
758 threadId: ThreadId.make("thread-1"),
759 path: disguisedPath,
760 },
761 workspaceRoot: root,
762 }).pipe(Effect.flip);
763 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
764 }).pipe(Effect.provide(layerTest)),
765 );
766​
767 it.effect("signs MCP render intent only for inline HTML attachments", () =>
768 Effect.gen(function* () {
769 const config = yield* ServerConfig.ServerConfig;
770 const fs = yield* FileSystem.FileSystem;
771 const path = yield* Path.Path;
772 yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
773 for (const extension of ["html", "pdf"]) {
774 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
775 yield* fs.writeFileString(
776 path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
777 "capture",
778 );
779 for (const disposition of ["inline", "attachment"] as const) {
780 const result = yield* issueAssetUrl({
781 resource: {
782 _tag: "attachment",
783 attachmentId,
784 disposition,
785 renderIntent: "mcp-app",
786 },
787 });
788 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
789 const separator = suffix.indexOf("/");
790 const asset = yield* resolveAsset(
791 suffix.slice(0, separator),
792 suffix.slice(separator + 1),
793 );
794 if (asset?.kind !== "file") throw new Error("Expected attachment file");
795 expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
796 extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
797 );
798 const token = suffix.slice(0, separator);
799 const [payload, signature] = token.split(".");
800 const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
801 claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
802 const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
803 expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
804 }
805 }
806 }).pipe(Effect.provide(layerTest)),
807 );
808​
809 it.effect("keeps inline requests for other attachment types as downloads", () =>
810 Effect.gen(function* () {
811 const config = yield* ServerConfig.ServerConfig;
812 const fileSystem = yield* FileSystem.FileSystem;
813 const path = yield* Path.Path;
814 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-zip";
815 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.zip`);
816 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
817 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
818​
819 const result = yield* issueAssetUrl({
820 resource: {
821 _tag: "attachment",
822 attachmentId,
823 fileName: "archive.zip",
824 mimeType: "text/html",
825 disposition: "inline",
826 },
827 });
828 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
829 const separatorIndex = suffix.indexOf("/");
830​
831 expect(
832 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
833 ).toMatchObject({ kind: "file", path: attachmentPath, download: true });
834 }).pipe(Effect.provide(layerTest)),
835 );
836 it.effect("issues project favicon capabilities with a signed fallback", () =>
837 Effect.gen(function* () {
838 const fileSystem = yield* FileSystem.FileSystem;
839 const path = yield* Path.Path;
840 const root = yield* fileSystem.makeTempDirectoryScoped({
841 prefix: "t3-asset-favicon-",
842 });
843 const faviconPath = path.join(root, "favicon.svg");
844 const initialFavicon = "<svg>a</svg>";
845 const updatedFavicon = "<svg>b</svg>";
846 expect(updatedFavicon).toHaveLength(initialFavicon.length);
847 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
848 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
849​
850 const faviconResult = yield* issueAssetUrl({
851 resource: { _tag: "project-favicon", cwd: root },
852 });
853 expect(faviconResult.sourcePath).toBe("favicon.svg");
854 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
855 expect(
856 yield* issueAssetUrl({
857 resource: { _tag: "project-favicon", cwd: root },
858 }),
859 ).toEqual(faviconResult);
860 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
861 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
862 expect(
863 yield* resolveAsset(
864 faviconSuffix.slice(0, faviconSeparatorIndex),
865 faviconSuffix.slice(faviconSeparatorIndex + 1),
866 ),
867 ).toEqual({ kind: "file", path: canonicalFaviconPath });
868​
869 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
870 const updatedFaviconResult = yield* issueAssetUrl({
871 resource: { _tag: "project-favicon", cwd: root },
872 });
873 expect(
874 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
875 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
876​
877 yield* fileSystem.remove(faviconPath);
878 const fallbackResult = yield* issueAssetUrl({
879 resource: { _tag: "project-favicon", cwd: root },
880 });
881 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
882 expect(fallbackResult.sourcePath).toBeUndefined();
883 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
884 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
885 expect(
886 yield* resolveAsset(
887 fallbackSuffix.slice(0, fallbackSeparatorIndex),
888 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
889 ),
890 ).toBeNull();
891 }).pipe(Effect.provide(layerTest)),
892 );
893​
894 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
895 Effect.gen(function* () {
896 const fileSystem = yield* FileSystem.FileSystem;
897 const path = yield* Path.Path;
898 const root = yield* fileSystem.makeTempDirectoryScoped({
899 prefix: "t3-asset-favicon-workspace-",
900 });
901 const pictures = yield* fileSystem.makeTempDirectoryScoped({
902 prefix: "t3-asset-favicon-pictures-",
903 });
904 const externalPath = path.join(pictures, "custom.png");
905 const siblingPath = path.join(pictures, "sibling.png");
906 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
907 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
908 const canonicalPath = yield* fileSystem.realPath(externalPath);
909 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
910​
911 const result = yield* issueAssetUrl({
912 resource: { _tag: "project-favicon", cwd: root },
913 projectFaviconPath: externalPath,
914 });
915 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
916 const separatorIndex = suffix.indexOf("/");
917​
918 expect(result.sourcePath).toBe(externalPath);
919 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
920 expect(
921 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
922 ).toEqual({ kind: "file", path: canonicalPath });
923 const tamperedSuffixResult = yield* resolveAsset(
924 suffix.slice(0, separatorIndex),
925 "sibling.png",
926 );
927 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
928 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
929 }).pipe(Effect.provide(layerTest)),
930 );
931​
932 it.effect("ignores a client favicon path hint", () =>
933 Effect.gen(function* () {
934 const fileSystem = yield* FileSystem.FileSystem;
935 const path = yield* Path.Path;
936 const root = yield* fileSystem.makeTempDirectoryScoped({
937 prefix: "t3-asset-favicon-hint-",
938 });
939 yield* fileSystem.makeDirectory(path.join(root, "brand"));
940 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
941 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
942​
943 const result = yield* issueAssetUrl({
944 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
945 projectFaviconPath: "brand/saved.svg",
946 });
947​
948 expect(result.sourcePath).toBe(path.join("brand", "saved.svg"));
949 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
950 }).pipe(Effect.provide(layerTest)),
951 );
952​
953 it.effect("serves a host's credentialed media through that host's driver", () => {
954 const fetched: Array<{ url: string; headers: Readonly<Record<string, string>> }> = [];
955 const url = "https://github.com/owner/repo/blob/main/docs/shot.png";
956 const media = sourceControlDefinitions.mediaUrl(url)!;
957 const layerDrivers = Layer.succeed(BuiltInDrivers.SourceControlDrivers, [
958 {
959 driver: { kind: media.definition.kind, definition: media.definition },
960 instance: fakeSourceControlDriverInstance(media.definition.kind, {
961 pullRequests: null,
962 fetchMedia: (request) =>
963 Effect.sync(() => {
964 fetched.push(request);
965 return HttpClientResponse.fromWeb(
966 HttpClientRequest.get(request.url),
967 new Response("bytes", { status: 206, headers: { "content-length": "5" } }),
968 );
969 }),
970 }),
971 },
972 ]);
973 return Effect.gen(function* () {
974 // Every client and server release spells the resource this way on the wire.
975 const { resource } = yield* Schema.decodeUnknownEffect(AssetCreateUrlInput)({
976 resource: { _tag: "github-media", cwd: "/repo", url },
977 });
978 const issued = yield* issueAssetUrl({ resource });
979 const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
980 const separator = suffix.indexOf("/");
981 const asset = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
982 expect(asset).toEqual({
983 kind: "source-control-media",
984 url: media.fetchUrl,
985 cwd: "/repo",
986 expiresAt: issued.expiresAt,
987 });
988 if (asset?.kind !== "source-control-media") return;
989​
990 const response = yield* sourceControlMediaResponse(asset, {
991 range: "bytes=0-4",
992 cookie: "session",
993 });
994 expect(fetched).toEqual([{ url: media.fetchUrl, headers: { range: "bytes=0-4" } }]);
995 expect(response.status).toBe(206);
996 // The upstream sent no type, so it comes from the file name the host gave the media.
997 expect(response.headers["content-type"]).toBe("image/png");
998 expect(response.headers["content-length"]).toBe("5");
999 }).pipe(Effect.provide(Layer.merge(layerTest, layerDrivers)), Effect.scoped);
1000 });
1001​
1002 it.effect("refuses media no host keeps behind a credential, without echoing the URL", () =>
1003 Effect.gen(function* () {
1004 for (const url of [
1005 "https://example.com/shot.png",
1006 "https://example.com/shot.png?token=private-media-token",
1007 ]) {
1008 const error = yield* issueAssetUrl({
1009 resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
1010 }).pipe(Effect.flip);
1011 expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
1012 const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(AssetAccessError))(error);
1013 expect(encoded).not.toContain(url);
1015 }).pipe(Effect.provide(layerTest)),
1016 );
1017});