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

AssetAccess.test.ts

1,462 lines62.0 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 ["notes.odt", "application/vnd.oasis.opendocument.text"],
225 ["budget.ods", "application/vnd.oasis.opendocument.spreadsheet"],
226 ["slides.odp", "application/vnd.oasis.opendocument.presentation"],
227 ["notes.rtf", "application/rtf"],
228 ["book.epub", "application/epub+zip"],
229 ["analysis.ipynb", "application/x-ipynb+json"],
230 ["tone.wav", "audio/wav"],
231 ["tone.webm-audio", "audio/webm"],
232 ["archive.zip", "application/zip"],
233 ["archive.jar", "application/java-archive"],
234 ["archive.tar", "application/x-tar"],
235 ["archive.gz", "application/gzip"],
236 ["archive.tgz", "application/gzip"],
237 ["data.sqlite", "application/vnd.sqlite3"],
238 ["data.sqlite3", "application/vnd.sqlite3"],
239 ["data.db", "application/vnd.sqlite3"],
240 ] as const) {
241 const filePath = path.join(outside, name);
242 yield* fs.writeFileString(filePath, "media");
243 const canonicalFile = yield* fs.realPath(filePath);
244 const result = yield* issueAssetUrl({
245 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
246 workspaceRoot: root,
247 });
248 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
249 const separator = suffix.indexOf("/");
250 const token = suffix.slice(0, separator);
251 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
252 kind: "file",
253 path: canonicalFile,
254 mimeType,
255 });
256 yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
257 expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
258 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
259 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
260 }
261 }).pipe(Effect.provide(layerTest)),
262 );
263​
264 it.effect("downloads any linked file with the same exact-file identity checks as media", () =>
265 Effect.gen(function* () {
266 const fs = yield* FileSystem.FileSystem;
267 const path = yield* Path.Path;
268 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-root-" });
269 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-outside-" });
270 for (const name of [
271 "data.csv",
272 "report.docx",
273 "sheet.xlsx",
274 "slides.pptx",
275 "archive.zip",
276 "no-extension",
277 ]) {
278 for (const directory of [root, outside]) {
279 const filePath = path.join(directory, name);
280 yield* fs.writeFileString(filePath, "shared file bytes");
281 const resource = {
282 _tag: "media-file" as const,
283 threadId: ThreadId.make("thread-1"),
284 path: directory === root ? name : filePath,
285 disposition: "attachment" as const,
286 };
287 const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
288 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
289 const separator = suffix.indexOf("/");
290 const token = suffix.slice(0, separator);
291 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
292 expect(asset).toMatchObject({
293 kind: "file",
294 download: true,
295 fileName: name,
296 mimeType: "application/octet-stream",
297 });
298 if (asset?.kind !== "file") throw new Error("Expected a downloadable file");
299 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
300 expect(response.headers.get("content-disposition")).toContain("attachment;");
301 expect(response.headers.get("content-type")).toBe("application/octet-stream");
302 expect(yield* Effect.promise(() => response.text())).toBe("shared file bytes");
303 expect(yield* resolveAsset(token, "sibling.docx")).toBeNull();
304 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
305 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
306 yield* fs.rename(filePath, `${filePath}.original`);
307 yield* fs.writeFileString(filePath, "replacement bytes");
308 expect(yield* resolveAsset(token, name)).toBeNull();
309 }
310 }
311 const directoryError = yield* issueAssetUrl({
312 resource: {
313 _tag: "media-file",
314 threadId: ThreadId.make("thread-1"),
315 path: root,
316 disposition: "attachment",
317 },
318 }).pipe(Effect.flip);
319 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
320 }).pipe(Effect.provide(layerTest)),
321 );
322​
323 it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
324 Effect.gen(function* () {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
328 const root = path.join(directory, "workspace");
329 yield* fs.makeDirectory(root);
330 for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
331 const filePath = path.resolve(root, relativePath);
332 yield* fs.writeFileString(filePath, "media");
333 const result = yield* issueAssetUrl({
334 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
335 workspaceRoot: root,
336 });
337 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
338 const separator = suffix.indexOf("/");
339 expect(
340 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
341 ).toMatchObject({
342 kind: "file",
343 path: yield* fs.realPath(filePath),
344 });
345 }
346 }).pipe(Effect.provide(layerTest)),
347 );
348​
349 it.effect("previews draft audio and video from relative workspace paths", () =>
350 Effect.gen(function* () {
351 const fs = yield* FileSystem.FileSystem;
352 const path = yield* Path.Path;
353 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-media-" });
354 for (const [name, mimeType] of [
355 ["video.mp4", "video/mp4"],
356 ["audio.wav", "audio/wav"],
357 ] as const) {
358 const filePath = path.join(root, name);
359 yield* fs.writeFileString(filePath, "media bytes");
360 const result = yield* issueAssetUrl({
361 resource: { _tag: "draft-workspace-file", cwd: root, path: name },
362 workspaceRoot: root,
363 });
364 expect(result.fileRevision).toEqual(expect.any(String));
365 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
366 const separator = suffix.indexOf("/");
367 const token = suffix.slice(0, separator);
368 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
369 expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(filePath), mimeType });
370 if (asset?.kind !== "file") throw new Error("Expected draft media file");
371 for (const [range, status, body] of [
372 [undefined, 200, "media bytes"],
373 ["bytes=2-5", 206, "dia "],
374 ] as const) {
375 const resolved = yield* resolveAsset(token, suffix.slice(separator + 1));
376 if (resolved?.kind !== "file") throw new Error("Expected draft media file");
377 const response = HttpServerResponse.toWeb(yield* assetFileResponse(resolved, range));
378 expect(response.status).toBe(status);
379 expect(response.headers.get("content-type")).toBe(mimeType);
380 expect(response.headers.get("content-length")).toBe(String(body.length));
381 if (range) expect(response.headers.get("content-range")).toBe("bytes 2-5/11");
382 expect(yield* Effect.promise(() => response.text())).toBe(body);
383 }
384 for (const requestedPath of [
385 name === "video.mp4" ? "audio.wav" : "video.mp4",
386 `../${name}`,
387 ]) {
388 expect(yield* resolveAsset(token, requestedPath)).toBeNull();
389 }
390 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
391 }
392 }).pipe(Effect.provide(layerTest)),
393 );
394​
395 it.effect(
396 "rejects draft media escapes and disallowed types without enabling non-draft media",
397 () =>
398 Effect.gen(function* () {
399 const fs = yield* FileSystem.FileSystem;
400 const path = yield* Path.Path;
401 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-boundary-" });
402 const root = path.join(directory, "workspace");
403 yield* fs.makeDirectory(root);
404 for (const name of ["video.mp4", "audio.wav", "secret.txt"]) {
405 yield* fs.writeFileString(path.join(root, name), "workspace bytes");
406 yield* fs.writeFileString(path.join(directory, name), "outside bytes");
407 }
408 for (const [requestedPath, tag] of [
409 ["../video.mp4", "AssetWorkspacePathValidationError"],
410 ["../audio.wav", "AssetWorkspacePathValidationError"],
411 ["secret.txt", "AssetPreviewTypeValidationError"],
412 ] as const) {
413 const error = yield* issueAssetUrl({
414 resource: { _tag: "draft-workspace-file", cwd: root, path: requestedPath },
415 workspaceRoot: root,
416 }).pipe(Effect.flip);
417 expect(error._tag).toBe(tag);
418 }
419 for (const name of ["video.mp4", "audio.wav"]) {
420 const error = yield* issueAssetUrl({
421 resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: name },
422 workspaceRoot: root,
423 }).pipe(Effect.flip);
424 expect(error._tag).toBe("AssetPreviewTypeValidationError");
425 }
426 }).pipe(Effect.provide(layerTest)),
427 );
428​
429 it.effect.skipIf(!symlinksSupported)(
430 "rejects draft media symlinks escaping the workspace or targeting disallowed types",
431 () =>
432 Effect.gen(function* () {
433 const fs = yield* FileSystem.FileSystem;
434 const path = yield* Path.Path;
435 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-symlink-" });
436 const root = path.join(directory, "workspace");
437 yield* fs.makeDirectory(root);
438 const outside = path.join(directory, "outside.mp4");
439 const secret = path.join(root, "secret.txt");
440 yield* fs.writeFileString(outside, "outside bytes");
441 yield* fs.writeFileString(secret, "private bytes");
442 for (const [name, target] of [
443 ["escape.mp4", outside],
444 ["disguised.wav", secret],
445 ] as const) {
446 yield* fs.symlink(target, path.join(root, name));
447 const error = yield* issueAssetUrl({
448 resource: { _tag: "draft-workspace-file", cwd: root, path: name },
449 workspaceRoot: root,
450 }).pipe(Effect.flip);
451 expect(["AssetWorkspaceAssetNotFoundError", "AssetPreviewTypeValidationError"]).toContain(
452 error._tag,
453 );
454 }
455 }).pipe(Effect.provide(layerTest)),
456 );
457​
458 it.effect.skipIf(!symlinksSupported)(
459 "preserves absolute draft previews through stable symlinks",
460 () =>
461 Effect.gen(function* () {
462 const fs = yield* FileSystem.FileSystem;
463 const path = yield* Path.Path;
464 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-absolute-" });
465 for (const extension of ["png", "mp4", "wav"]) {
466 const target = path.join(root, `target.${extension}`);
467 const alias = path.join(root, `alias.${extension}`);
468 yield* fs.writeFileString(target, "preview bytes");
469 yield* fs.symlink(target, alias);
470 const result = yield* issueAssetUrl({
471 resource: { _tag: "draft-workspace-file", cwd: root, path: alias },
472 workspaceRoot: root,
473 });
474 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
475 const separator = suffix.indexOf("/");
476 expect(
477 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
478 ).toMatchObject({ kind: "file", path: yield* fs.realPath(target) });
479 }
480 }).pipe(Effect.provide(layerTest)),
481 );
482​
483 it.effect.skipIf(!symlinksSupported)(
484 "rejects a draft media path swapped after workspace containment validation",
485 () =>
486 Effect.gen(function* () {
487 const fs = yield* FileSystem.FileSystem;
488 const path = yield* Path.Path;
489 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-swap-" });
490 const root = path.join(directory, "workspace");
491 yield* fs.makeDirectory(root);
492 const filePath = path.join(root, "video.mp4");
493 const outside = path.join(directory, "outside.mp4");
494 yield* fs.writeFileString(filePath, "workspace video");
495 yield* fs.writeFileString(outside, "outside video");
496 const canonicalFile = yield* fs.realPath(filePath);
497 let swapped = false;
498 const swappingFileSystem = FileSystem.FileSystem.of({
499 ...fs,
500 stat: Effect.fn(function* (requestedPath) {
501 const info = yield* fs.stat(requestedPath);
502 if (requestedPath === canonicalFile && !swapped) {
503 swapped = true;
504 yield* fs.remove(filePath);
505 yield* fs.symlink(outside, filePath);
506 }
507 return info;
508 }),
509 });
510 const result = yield* issueAssetUrl({
511 resource: { _tag: "draft-workspace-file", cwd: root, path: "video.mp4" },
512 workspaceRoot: root,
513 }).pipe(Effect.result, Effect.provideService(FileSystem.FileSystem, swappingFileSystem));
514 expect(swapped).toBe(true);
515 expect(result).toMatchObject({
516 _tag: "Failure",
517 failure: { _tag: "AssetWorkspaceAssetNotFoundError" },
518 });
519 }).pipe(Effect.provide(layerTest)),
520 );
521​
522 it.effect("resolves home-relative media paths independently of the workspace", () =>
523 Effect.gen(function* () {
524 const fs = yield* FileSystem.FileSystem;
525 const path = yield* Path.Path;
526 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
527 const home = path.join(directory, "var", "home", "alice");
528 const filePath = path.join(home, "Downloads", "repro.mp4");
529 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
530 yield* fs.writeFileString(filePath, "recording bytes");
531 const canonicalFile = yield* fs.realPath(filePath);
532 yield* Effect.gen(function* () {
533 for (const workspaceRoot of [
534 path.join(home, "project"),
535 path.join(directory, "srv", "project"),
536 undefined,
537 ]) {
538 if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
539 for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
540 const result = yield* issueAssetUrl({
541 resource: {
542 _tag: "media-file",
543 threadId: ThreadId.make("thread-1"),
544 path: requestedPath,
545 },
546 ...(workspaceRoot ? { workspaceRoot } : {}),
547 });
548 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
549 const separator = suffix.indexOf("/");
550 const asset = yield* resolveAsset(
551 suffix.slice(0, separator),
552 suffix.slice(separator + 1),
553 );
554 expect(asset).toMatchObject({
555 kind: "file",
556 path: canonicalFile,
557 mimeType: "video/mp4",
558 });
559 if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
560 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
561 expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
562 }
563 }
564 }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
565 }).pipe(Effect.provide(layerTest)),
566 );
567​
568 // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
569 // Windows user's NTLM credentials to attacker.test.
570 it.effect("never resolves a network media path outside the thread's project", () =>
571 Effect.gen(function* () {
572 const fs = yield* FileSystem.FileSystem;
573 const path = yield* Path.Path;
574 const resolved: Array<string> = [];
575 const recordingFileSystem = FileSystem.FileSystem.of({
576 ...fs,
577 realPath: (requestedPath) => {
578 resolved.push(requestedPath);
579 return Effect.fail(
580 PlatformError.systemError({
581 _tag: "NotFound",
582 module: "FileSystem",
583 method: "realPath",
584 pathOrDescriptor: requestedPath,
585 }),
586 );
587 },
588 });
589 const share = "//nas.test/share/project";
590 for (const resource of [
591 {
592 _tag: "media-file",
593 threadId: ThreadId.make("thread-1"),
594 path: "//attacker.test/s/a.png",
595 },
596 { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
597 { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
598 ] as const) {
599 const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
600 Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
601 Effect.flip,
602 );
603 expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
604 }
605 expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
606 }).pipe(Effect.provide(layerTest)),
607 );
608​
609 it.effect.skipIf(!symlinksSupported)(
610 "rejects non-previewable files, disguised targets, and directories",
611 () =>
612 Effect.gen(function* () {
613 const fs = yield* FileSystem.FileSystem;
614 const path = yield* Path.Path;
615 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
616 for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
617 const filePath = path.join(root, name);
618 yield* fs.writeFileString(filePath, "not media");
619 const error = yield* issueAssetUrl({
620 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
621 }).pipe(Effect.flip);
622 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
623 }
624 const disguisedPath = path.join(root, "disguised.png");
625 yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
626 const disguisedError = yield* issueAssetUrl({
627 resource: {
628 _tag: "media-file",
629 threadId: ThreadId.make("thread-1"),
630 path: disguisedPath,
631 },
632 }).pipe(Effect.flip);
633 expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
634 const directoryPath = path.join(root, "directory.png");
635 yield* fs.makeDirectory(directoryPath);
636 const directoryError = yield* issueAssetUrl({
637 resource: {
638 _tag: "media-file",
639 threadId: ThreadId.make("thread-1"),
640 path: directoryPath,
641 },
642 }).pipe(Effect.flip);
643 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
644 }).pipe(Effect.provide(layerTest)),
645 );
646​
647 it.effect.skipIf(!symlinksSupported)(
648 "binds media URLs to the canonical target and rejects symlink substitution",
649 () =>
650 Effect.gen(function* () {
651 const fs = yield* FileSystem.FileSystem;
652 const path = yield* Path.Path;
653 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
654 const filePath = path.join(root, "actual.svg");
655 const aliasPath = path.join(root, "alias.png");
656 const replacementPath = path.join(root, "other.svg");
657 yield* fs.writeFileString(filePath, "<svg/>");
658 yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
659 yield* fs.symlink(filePath, aliasPath);
660 const canonicalFile = yield* fs.realPath(filePath);
661 const result = yield* issueAssetUrl({
662 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
663 });
664 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
665 const separator = suffix.indexOf("/");
666 const token = suffix.slice(0, separator);
667 const name = suffix.slice(separator + 1);
668 const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
669 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
670 yield* fs.remove(aliasPath);
671 yield* fs.symlink(replacementPath, aliasPath);
672 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
673 yield* fs.remove(filePath);
674 yield* fs.symlink(replacementPath, filePath);
675 expect(yield* resolveAsset(token, name)).toBeNull();
676 }).pipe(Effect.provide(layerTest)),
677 );
678​
679 it.effect.skipIf(!symlinksSupported)(
680 "keeps full and partial responses bound to the file opened during resolution",
681 () =>
682 Effect.gen(function* () {
683 const fs = yield* FileSystem.FileSystem;
684 const path = yield* Path.Path;
685 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
686 const filePath = path.join(root, "recording.mp4");
687 const savedPath = path.join(root, "saved.mp4");
688 const secretPath = path.join(root, "secret.txt");
689 yield* fs.writeFileString(filePath, "0123456789");
690 yield* fs.writeFileString(secretPath, "private information");
691 const result = yield* issueAssetUrl({
692 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
693 });
694 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
695 const separator = suffix.indexOf("/");
696 for (const [range, expected, status] of [
697 [undefined, "0123456789", 200],
698 ["bytes=2-5", "2345", 206],
699 ] as const) {
700 const asset = yield* resolveAsset(
701 suffix.slice(0, separator),
702 suffix.slice(separator + 1),
703 );
704 if (asset?.kind !== "file") throw new Error("Expected a resolved media file");
705​
706 yield* fs.rename(filePath, savedPath);
707 yield* fs.symlink(secretPath, filePath);
708 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
709 expect(response.status).toBe(status);
710 expect(response.headers.get("content-length")).toBe(String(expected.length));
711 expect(yield* Effect.promise(() => response.text())).toBe(expected);
712 yield* fs.remove(filePath);
713 yield* fs.rename(savedPath, filePath);
714 }
715 }).pipe(Effect.provide(layerTest)),
716 );
717​
718 it.effect.skipIf(!symlinksSupported)(
719 "rejects a symlink swapped in after canonical validation but before open",
720 () =>
721 Effect.gen(function* () {
722 const fs = yield* FileSystem.FileSystem;
723 const path = yield* Path.Path;
724 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
725 const filePath = path.join(root, "recording.mp4");
726 const secretPath = path.join(root, "secret.txt");
727 yield* fs.writeFileString(filePath, "video");
728 yield* fs.writeFileString(secretPath, "secret");
729 const canonicalPath = yield* fs.realPath(filePath);
730 const result = yield* issueAssetUrl({
731 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
732 });
733 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
734 const separator = suffix.indexOf("/");
735 const swappingFileSystem = FileSystem.FileSystem.of({
736 ...fs,
737 stat: Effect.fn(function* (requestedPath) {
738 const info = yield* fs.stat(requestedPath);
739 if (requestedPath === canonicalPath) {
740 yield* fs.remove(filePath);
741 yield* fs.symlink(secretPath, filePath);
742 }
743 return info;
744 }),
745 });
746 expect(
747 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
748 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
749 ),
750 ).toBeNull();
751 }).pipe(Effect.provide(layerTest)),
752 );
753​
754 it.effect.skipIf(!symlinksSupported)(
755 "rejects an ancestor symlink race even when canonical path rechecks would pass",
756 () =>
757 Effect.gen(function* () {
758 const fs = yield* FileSystem.FileSystem;
759 const path = yield* Path.Path;
760 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
761 const publicDirectory = path.join(root, "public");
762 const privateDirectory = path.join(root, "private");
763 yield* fs.makeDirectory(publicDirectory);
764 yield* fs.makeDirectory(privateDirectory);
765 const filePath = path.join(publicDirectory, "recording.mp4");
766 yield* fs.writeFileString(filePath, "public video");
767 yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
768 const canonicalPath = yield* fs.realPath(filePath);
769 const result = yield* issueAssetUrl({
770 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
771 });
772 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
773 const separator = suffix.indexOf("/");
774 const native = yield* Effect.promise(() =>
775 vi.importActual<typeof NodeFSP>("node:fs/promises"),
776 );
777 const savedDirectory = path.join(root, "saved");
778 const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
779 await native.unlink(publicDirectory);
780 await native.rename(savedDirectory, publicDirectory);
781 const canonical = await native.realpath(canonicalPath);
782 await native.rename(publicDirectory, savedDirectory);
783 await native.symlink(privateDirectory, publicDirectory, "junction");
784 return canonical;
785 });
786 yield* Effect.addFinalizer(() =>
787 Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
788 );
789 const swappingFileSystem = FileSystem.FileSystem.of({
790 ...fs,
791 realPath: Effect.fn(function* (requestedPath) {
792 const canonical = yield* fs.realPath(requestedPath);
793 if (requestedPath === canonicalPath) {
794 yield* fs.rename(publicDirectory, savedDirectory);
795 yield* Effect.promise(() =>
796 NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
797 );
798 }
799 return canonical;
800 }),
801 });
802 expect(
803 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
804 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
805 ),
806 ).toBeNull();
807 }).pipe(Effect.provide(layerTest)),
808 );
809​
810 it.effect("versions media by file changes rather than by re-signing", () =>
811 Effect.gen(function* () {
812 const fs = yield* FileSystem.FileSystem;
813 const path = yield* Path.Path;
814 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-revision-" });
815 const filePath = path.join(root, "recording.mp4");
816 yield* fs.writeFileString(filePath, "original");
817 yield* Effect.promise(() => NodeFSP.utimes(filePath, 1_000, 1_000));
818 const input = {
819 resource: {
820 _tag: "media-file" as const,
821 threadId: ThreadId.make("thread-1"),
822 path: filePath,
823 },
824 };
825 const original = yield* issueAssetUrl(input);
826 expect(original.fileRevision).toEqual(expect.any(String));
827​
828 yield* TestClock.adjust("1 minute");
829 const renewed = yield* issueAssetUrl(input);
830 expect(renewed.relativeUrl).not.toBe(original.relativeUrl);
831 expect(renewed.fileRevision).toBe(original.fileRevision);
832​
833 yield* fs.writeFileString(filePath, "modified");
834 yield* Effect.promise(() => NodeFSP.utimes(filePath, 2_000, 2_000));
835 const edited = yield* issueAssetUrl(input);
836 expect(edited.fileRevision).not.toBe(original.fileRevision);
837​
838 const replacement = path.join(root, "replacement.mp4");
839 yield* fs.writeFileString(replacement, "modified");
840 yield* Effect.promise(() => NodeFSP.utimes(replacement, 2_000, 2_000));
841 yield* fs.rename(replacement, filePath);
842 const replaced = yield* issueAssetUrl(input);
843 expect(replaced.fileRevision).not.toBe(edited.fileRevision);
844 }).pipe(Effect.provide(layerTest)),
845 );
846​
847 it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
848 Effect.gen(function* () {
849 const fs = yield* FileSystem.FileSystem;
850 const path = yield* Path.Path;
851 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
852 const filePath = path.join(root, "recording.mp4");
853 yield* fs.writeFileString(filePath, "original");
854 const input = {
855 resource: {
856 _tag: "media-file" as const,
857 threadId: ThreadId.make("thread-1"),
858 path: filePath,
859 },
860 };
861 const original = yield* issueAssetUrl(input);
862 const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
863 const separator = suffix.indexOf("/");
864 const token = suffix.slice(0, separator);
865 const name = suffix.slice(separator + 1);
866 yield* fs.writeFileString(filePath, "in-place edit");
867 const edited = yield* resolveAsset(token, name);
868 if (edited?.kind !== "file") throw new Error("Expected the edited media file");
869 const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
870 expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
871​
872 const replacement = path.join(root, "replacement.mp4");
873 yield* fs.writeFileString(replacement, "replacement");
874 yield* fs.rename(replacement, filePath);
875 expect(yield* resolveAsset(token, name)).toBeNull();
876​
877 const renewed = yield* issueAssetUrl(input);
878 const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
879 const renewedSeparator = renewedSuffix.indexOf("/");
880 const renewedAsset = yield* resolveAsset(
881 renewedSuffix.slice(0, renewedSeparator),
882 renewedSuffix.slice(renewedSeparator + 1),
883 );
884 if (renewedAsset?.kind !== "file") throw new Error("Expected the replacement media file");
885 const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
886 expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
887 yield* fs.remove(filePath);
888 expect(
889 yield* resolveAsset(
890 renewedSuffix.slice(0, renewedSeparator),
891 renewedSuffix.slice(renewedSeparator + 1),
892 ),
893 ).toBeNull();
894 }).pipe(Effect.provide(layerTest)),
895 );
896​
897 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
898 Effect.gen(function* () {
899 const fileSystem = yield* FileSystem.FileSystem;
900 const path = yield* Path.Path;
901 const root = yield* fileSystem.makeTempDirectoryScoped({
902 prefix: "t3-asset-workspace-",
903 });
904 const htmlPath = path.join(root, "report.html");
905 const cssPath = path.join(root, "report.css");
906 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
907 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
908 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
909 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
910 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
911​
912 const result = yield* issueAssetUrl({
913 resource: {
914 _tag: "workspace-file",
915 threadId: ThreadId.make("thread-1"),
916 path: htmlPath,
917 },
918 workspaceRoot: root,
919 });
920 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
921 const separatorIndex = suffix.indexOf("/");
922 const token = suffix.slice(0, separatorIndex);
923​
924 expect(yield* resolveAsset(token, "report.html")).toEqual({
925 kind: "file",
926 path: canonicalHtmlPath,
927 });
928 expect(yield* resolveAsset(token, "report.css")).toEqual({
929 kind: "file",
930 path: canonicalCssPath,
931 });
932 for (const extension of ["otf", "ttf", "woff", "woff2"]) {
933 const fontName = `preview.${extension}`;
934 const fontPath = path.join(root, fontName);
935 yield* fileSystem.writeFileString(fontPath, "font bytes");
936 const canonicalFontPath = yield* fileSystem.realPath(fontPath);
937 for (const resource of [
938 { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },
939 { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },
940 ]) {
941 const url = yield* issueAssetUrl({ resource, workspaceRoot: root });
942 const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
943 expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), fontName)).toEqual({
944 kind: "file",
945 path: canonicalFontPath,
946 });
947 }
948 }
949 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
950 expect(yield* resolveAsset(token, ".env")).toBeNull();
951 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
952 for (const extension of [
953 "odt",
954 "ods",
955 "odp",
956 "rtf",
957 "epub",
958 "ipynb",
959 "zip",
960 "jar",
961 "tar",
962 "gz",
963 "tgz",
964 "sqlite",
965 "sqlite3",
966 "db",
967 "docx",
968 "xlsx",
969 "pptx",
970 "bmp",
971 "heic",
972 "tif",
973 "tiff",
974 "weba",
975 "mmd",
976 "mermaid",
977 ]) {
978 const siblingName = `private.${extension}`;
979 yield* fileSystem.writeFileString(path.join(root, siblingName), "private sibling");
980 for (const resource of [
981 { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },
982 { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },
983 ]) {
984 const url = yield* issueAssetUrl({ resource, workspaceRoot: root });
985 const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
986 expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), siblingName)).toBeNull();
987 }
988 }
989 }).pipe(Effect.provide(layerTest)),
990 );
991​
992 it.effect("rejects workspace files outside the authorized root", () =>
993 Effect.gen(function* () {
994 const fileSystem = yield* FileSystem.FileSystem;
995 const path = yield* Path.Path;
996 const root = yield* fileSystem.makeTempDirectoryScoped({
997 prefix: "t3-asset-root-",
998 });
999 const outside = yield* fileSystem.makeTempDirectoryScoped({
1000 prefix: "t3-asset-outside-",
1001 });
1002 const htmlPath = path.join(outside, "report.html");
1003 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
1004​
1005 const error = yield* issueAssetUrl({
1006 resource: {
1007 _tag: "workspace-file",
1008 threadId: ThreadId.make("thread-1"),
1009 path: htmlPath,
1010 },
1011 workspaceRoot: root,
1012 }).pipe(Effect.flip);
1013 expect(error.message).toBe("Workspace file path must be relative to the project root.");
1014 expect(error).toMatchObject({
1015 _tag: "AssetWorkspacePathValidationError",
1016 resource: {
1017 _tag: "workspace-file",
1018 threadId: "thread-1",
1019 path: htmlPath,
1020 },
1021 });
1022 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
1023 }).pipe(Effect.provide(layerTest)),
1024 );
1025​
1026 it.effect("issues exact workspace URLs for every non-HTML preview", () =>
1027 Effect.gen(function* () {
1028 const fileSystem = yield* FileSystem.FileSystem;
1029 const path = yield* Path.Path;
1030 const root = yield* fileSystem.makeTempDirectoryScoped({
1031 prefix: "t3-asset-image-workspace-",
1032 });
1033 const assetsDirectory = path.join(root, "assets");
1034 yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
1035 yield* fileSystem.writeFileString(
1036 path.join(assetsDirectory, "private.docx"),
1037 "private document",
1038 );
1039 for (const extension of [
1040 "pdf",
1041 "odt",
1042 "ods",
1043 "odp",
1044 "rtf",
1045 "epub",
1046 "ipynb",
1047 "png",
1048 "bmp",
1049 "heic",
1050 "tif",
1051 "tiff",
1052 "docx",
1053 "xlsx",
1054 "pptx",
1055 "ttf",
1056 "otf",
1057 "woff",
1058 "woff2",
1059 "zip",
1060 "jar",
1061 "tar",
1062 "gz",
1063 "tgz",
1064 "sqlite",
1065 "sqlite3",
1066 "db",
1067 ]) {
1068 const name = `preview.${extension}`;
1069 const filePath = path.join(assetsDirectory, name);
1070 const siblingName = `other.${extension}`;
1071 yield* fileSystem.writeFileString(filePath, "preview");
1072 yield* fileSystem.writeFileString(
1073 path.join(assetsDirectory, siblingName),
1074 "private sibling",
1075 );
1076 const canonicalPath = yield* fileSystem.realPath(filePath);
1077 for (const resource of [
1079 _tag: "workspace-file" as const,
1080 threadId: ThreadId.make("thread-1"),
1081 path: filePath,
1082 },
1083 { _tag: "draft-workspace-file" as const, cwd: root, path: `assets/${name}` },
1084 ]) {
1085 const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
1086 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1087 const token = suffix.slice(0, suffix.indexOf("/"));
1088 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalPath });
1089 expect(yield* resolveAsset(token, siblingName)).toBeNull();
1090 expect(yield* resolveAsset(token, "private.docx")).toBeNull();
1091 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
1094 }).pipe(Effect.provide(layerTest)),
1095 );
1096​
1097 it.effect("previews workspace files with literal fragment characters in their paths", () =>
1098 Effect.gen(function* () {
1099 const fileSystem = yield* FileSystem.FileSystem;
1100 const path = yield* Path.Path;
1101 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-preview-literal-" });
1102 const directory = path.join(root, "assets#archive");
1103 yield* fileSystem.makeDirectory(directory);
1104​
1105 for (const name of [
1106 "icon#v2.png",
1107 "report#draft.pdf",
1108 "report.docx",
1109 "workbook.xlsx",
1110 "slides.pptx",
1111 "notes.odt",
1112 "budget.ods",
1113 "slides.odp",
1114 "notes.rtf",
1115 "book.epub",
1116 "analysis.ipynb",
1117 "specimen.ttf",
1118 "specimen.otf",
1119 "specimen.woff",
1120 "specimen.woff2",
1121 "image.bmp",
1122 "image.heic",
1123 "image.tif",
1124 "image.tiff",
1125 ]) {
1126 const filePath = path.join(directory, name);
1127 yield* fileSystem.writeFileString(filePath, "preview fixture");
1128 const canonicalFile = yield* fileSystem.realPath(filePath);
1129 const result = yield* issueAssetUrl({
1130 resource: {
1131 _tag: "workspace-file",
1132 threadId: ThreadId.make("thread-1"),
1133 path: filePath,
1134 },
1135 workspaceRoot: root,
1136 });
1137 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1138 const token = suffix.slice(0, suffix.indexOf("/"));
1139​
1140 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalFile });
1141 if (name.endsWith(".png")) {
1142 expect(yield* resolveAsset(token, "other.png")).toBeNull();
1145​
1146 const disguisedPath = path.join(root, "image.png#notes.txt");
1147 yield* fileSystem.writeFileString(disguisedPath, "not an image");
1148 const error = yield* issueAssetUrl({
1149 resource: {
1150 _tag: "workspace-file",
1151 threadId: ThreadId.make("thread-1"),
1152 path: disguisedPath,
1153 },
1154 workspaceRoot: root,
1155 }).pipe(Effect.flip);
1156 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
1157 }).pipe(Effect.provide(layerTest)),
1158 );
1159​
1160 it.effect("signs MCP render intent only for inline HTML attachments", () =>
1161 Effect.gen(function* () {
1162 const config = yield* ServerConfig.ServerConfig;
1163 const fs = yield* FileSystem.FileSystem;
1164 const path = yield* Path.Path;
1165 yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
1166 for (const extension of ["html", "pdf"]) {
1167 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
1168 yield* fs.writeFileString(
1169 path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
1170 "capture",
1171 );
1172 for (const disposition of ["inline", "attachment"] as const) {
1173 const result = yield* issueAssetUrl({
1174 resource: {
1175 _tag: "attachment",
1176 attachmentId,
1177 disposition,
1178 renderIntent: "mcp-app",
1179 },
1180 });
1181 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1182 const separator = suffix.indexOf("/");
1183 const asset = yield* resolveAsset(
1184 suffix.slice(0, separator),
1185 suffix.slice(separator + 1),
1186 );
1187 if (asset?.kind !== "file") throw new Error("Expected attachment file");
1188 expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
1189 extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
1190 );
1191 const token = suffix.slice(0, separator);
1192 const [payload, signature] = token.split(".");
1193 const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
1194 claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
1195 const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
1196 expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
1199 }).pipe(Effect.provide(layerTest)),
1200 );
1201​
1202 it.effect("serves document attachments inline when a viewer requests it", () =>
1203 Effect.gen(function* () {
1204 const config = yield* ServerConfig.ServerConfig;
1205 const fileSystem = yield* FileSystem.FileSystem;
1206 const path = yield* Path.Path;
1207 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1208 for (const [extension, mimeType] of [
1209 ["pdf", "application/pdf"],
1210 ["svg", "image/svg+xml"],
1211 ["bmp", "image/bmp"],
1212 ["ttf", "font/ttf"],
1213 ["otf", "font/otf"],
1214 ["woff", "font/woff"],
1215 ["woff2", "font/woff2"],
1216 ["weba", "audio/webm"],
1217 ["zip", "application/zip"],
1218 ["jar", "application/java-archive"],
1219 ["tar", "application/x-tar"],
1220 ["gz", "application/gzip"],
1221 ["tgz", "application/gzip"],
1222 ["sqlite", "application/vnd.sqlite3"],
1223 ["sqlite3", "application/vnd.sqlite3"],
1224 ["db", "application/vnd.sqlite3"],
1225 ] as const) {
1226 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000001-${extension}`;
1227 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);
1228 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1229​
1230 const result = yield* issueAssetUrl({
1231 resource: {
1232 _tag: "attachment",
1233 attachmentId,
1234 fileName: `report.${extension}`,
1235 mimeType: "text/html",
1236 disposition: "inline",
1237 },
1238 });
1239 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1240 const separatorIndex = suffix.indexOf("/");
1241​
1242 expect(
1243 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1244 ).toEqual({
1245 kind: "file",
1246 path: attachmentPath,
1247 fileName: `report.${extension}`,
1248 mimeType,
1249 });
1251 }).pipe(Effect.provide(layerTest)),
1252 );
1253​
1254 it.effect("keeps inline requests for other attachment types as downloads", () =>
1255 Effect.gen(function* () {
1256 const config = yield* ServerConfig.ServerConfig;
1257 const fileSystem = yield* FileSystem.FileSystem;
1258 const path = yield* Path.Path;
1259 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-7z";
1260 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.7z`);
1261 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1262 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1263​
1264 const result = yield* issueAssetUrl({
1265 resource: {
1266 _tag: "attachment",
1267 attachmentId,
1268 fileName: "archive.7z",
1269 mimeType: "text/html",
1270 disposition: "inline",
1271 },
1272 });
1273 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1274 const separatorIndex = suffix.indexOf("/");
1275​
1276 expect(
1277 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1278 ).toMatchObject({ kind: "file", path: attachmentPath, download: true });
1279 }).pipe(Effect.provide(layerTest)),
1280 );
1281 it.effect("issues project favicon capabilities with a signed fallback", () =>
1282 Effect.gen(function* () {
1283 const fileSystem = yield* FileSystem.FileSystem;
1284 const path = yield* Path.Path;
1285 const root = yield* fileSystem.makeTempDirectoryScoped({
1286 prefix: "t3-asset-favicon-",
1287 });
1288 const faviconPath = path.join(root, "favicon.svg");
1289 const initialFavicon = "<svg>a</svg>";
1290 const updatedFavicon = "<svg>b</svg>";
1291 expect(updatedFavicon).toHaveLength(initialFavicon.length);
1292 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
1293 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
1294​
1295 const faviconResult = yield* issueAssetUrl({
1296 resource: { _tag: "project-favicon", cwd: root },
1297 });
1298 expect(faviconResult.sourcePath).toBe("favicon.svg");
1299 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
1300 expect(
1301 yield* issueAssetUrl({
1302 resource: { _tag: "project-favicon", cwd: root },
1303 }),
1304 ).toEqual(faviconResult);
1305 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1306 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
1307 expect(
1308 yield* resolveAsset(
1309 faviconSuffix.slice(0, faviconSeparatorIndex),
1310 faviconSuffix.slice(faviconSeparatorIndex + 1),
1311 ),
1312 ).toEqual({ kind: "file", path: canonicalFaviconPath });
1313​
1314 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
1315 const updatedFaviconResult = yield* issueAssetUrl({
1316 resource: { _tag: "project-favicon", cwd: root },
1317 });
1318 expect(
1319 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
1320 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
1321​
1322 yield* fileSystem.remove(faviconPath);
1323 const fallbackResult = yield* issueAssetUrl({
1324 resource: { _tag: "project-favicon", cwd: root },
1325 });
1326 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
1327 expect(fallbackResult.sourcePath).toBeUndefined();
1328 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1329 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
1330 expect(
1331 yield* resolveAsset(
1332 fallbackSuffix.slice(0, fallbackSeparatorIndex),
1333 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
1334 ),
1335 ).toBeNull();
1336 }).pipe(Effect.provide(layerTest)),
1337 );
1338​
1339 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
1340 Effect.gen(function* () {
1341 const fileSystem = yield* FileSystem.FileSystem;
1342 const path = yield* Path.Path;
1343 const root = yield* fileSystem.makeTempDirectoryScoped({
1344 prefix: "t3-asset-favicon-workspace-",
1345 });
1346 const pictures = yield* fileSystem.makeTempDirectoryScoped({
1347 prefix: "t3-asset-favicon-pictures-",
1348 });
1349 const externalPath = path.join(pictures, "custom.png");
1350 const siblingPath = path.join(pictures, "sibling.png");
1351 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
1352 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
1353 const canonicalPath = yield* fileSystem.realPath(externalPath);
1354 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
1355​
1356 const result = yield* issueAssetUrl({
1357 resource: { _tag: "project-favicon", cwd: root },
1358 projectFaviconPath: externalPath,
1359 });
1360 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1361 const separatorIndex = suffix.indexOf("/");
1362​
1363 expect(result.sourcePath).toBe(externalPath);
1364 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
1365 expect(
1366 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1367 ).toEqual({ kind: "file", path: canonicalPath });
1368 const tamperedSuffixResult = yield* resolveAsset(
1369 suffix.slice(0, separatorIndex),
1370 "sibling.png",
1371 );
1372 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
1373 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
1374 }).pipe(Effect.provide(layerTest)),
1375 );
1376​
1377 it.effect("ignores a client favicon path hint", () =>
1378 Effect.gen(function* () {
1379 const fileSystem = yield* FileSystem.FileSystem;
1380 const path = yield* Path.Path;
1381 const root = yield* fileSystem.makeTempDirectoryScoped({
1382 prefix: "t3-asset-favicon-hint-",
1383 });
1384 yield* fileSystem.makeDirectory(path.join(root, "brand"));
1385 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
1386 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
1387​
1388 const result = yield* issueAssetUrl({
1389 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
1390 projectFaviconPath: "brand/saved.svg",
1391 });
1392​
1393 expect(result.sourcePath).toBe(path.join("brand", "saved.svg"));
1394 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
1395 }).pipe(Effect.provide(layerTest)),
1396 );
1397​
1398 it.effect("serves a host's credentialed media through that host's driver", () => {
1399 const fetched: Array<{ url: string; headers: Readonly<Record<string, string>> }> = [];
1400 const url = "https://github.com/owner/repo/blob/main/docs/shot.png";
1401 const media = sourceControlDefinitions.mediaUrl(url)!;
1402 const layerDrivers = Layer.succeed(BuiltInDrivers.SourceControlDrivers, [
1404 driver: { kind: media.definition.kind, definition: media.definition },
1405 instance: fakeSourceControlDriverInstance(media.definition.kind, {
1406 pullRequests: null,
1407 fetchMedia: (request) =>
1408 Effect.sync(() => {
1409 fetched.push(request);
1410 return HttpClientResponse.fromWeb(
1411 HttpClientRequest.get(request.url),
1412 new Response("bytes", { status: 206, headers: { "content-length": "5" } }),
1413 );
1414 }),
1415 }),
1416 },
1417 ]);
1418 return Effect.gen(function* () {
1419 // Every client and server release spells the resource this way on the wire.
1420 const { resource } = yield* Schema.decodeEffect(AssetCreateUrlInput)({
1421 resource: { _tag: "github-media", cwd: "/repo", url },
1422 });
1423 const issued = yield* issueAssetUrl({ resource });
1424 const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1425 const separator = suffix.indexOf("/");
1426 const asset = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
1427 expect(asset).toEqual({
1428 kind: "source-control-media",
1429 url: media.fetchUrl,
1430 cwd: "/repo",
1431 expiresAt: issued.expiresAt,
1432 });
1433 if (asset?.kind !== "source-control-media") return;
1434​
1435 const response = yield* sourceControlMediaResponse(asset, {
1436 range: "bytes=0-4",
1437 cookie: "session",
1438 });
1439 expect(fetched).toEqual([{ url: media.fetchUrl, headers: { range: "bytes=0-4" } }]);
1440 expect(response.status).toBe(206);
1441 // The upstream sent no type, so it comes from the file name the host gave the media.
1442 expect(response.headers["content-type"]).toBe("image/png");
1443 expect(response.headers["content-length"]).toBe("5");
1444 }).pipe(Effect.provide(Layer.merge(layerTest, layerDrivers)), Effect.scoped);
1445 });
1446​
1447 it.effect("refuses media no host keeps behind a credential, without echoing the URL", () =>
1448 Effect.gen(function* () {
1449 for (const url of [
1450 "https://example.com/shot.png",
1451 "https://example.com/shot.png?token=private-media-token",
1452 ]) {
1453 const error = yield* issueAssetUrl({
1454 resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
1455 }).pipe(Effect.flip);
1456 expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
1457 const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(AssetAccessError))(error);
1458 expect(encoded).not.toContain(url);
1460 }).pipe(Effect.provide(layerTest)),
1461 );
1462});