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

AssetAccess.test.ts

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