The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,918 lines 83.2 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - tests inject swaps at the native open boundary.
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
5 import * as NodeFSP from "node:fs/promises";
6 import {
7 AssetAccessError,
8 AssetCreateUrlInput,
9 AssetPreviewTypeValidationError,
10 SOURCE_CONTROL_MEDIA_ASSET,
11 ThreadId,
12 TurnItemId,
13 } from "@t3tools/contracts";
14 import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
15 import { MCP_APP_MAX_HTML_BYTES } from "@t3tools/shared/mcpApp";
16 import { describe, expect, it } from "@effect/vitest";
17 import * as DateTime from "effect/DateTime";
18 import * as Effect from "effect/Effect";
19 import * as FileSystem from "effect/FileSystem";
20 import * as Layer from "effect/Layer";
21 import * as Path from "effect/Path";
22 import * as PlatformError from "effect/PlatformError";
23 import * as Schema from "effect/Schema";
24 import * as TestClock from "effect/testing/TestClock";
25 import { HttpClientRequest, HttpClientResponse, HttpServerResponse } from "effect/http";
26 import { vi } from "vite-plus/test";
27
28 import * as AssetSigner from "./AssetSigner.ts";
29 import * as WorkspacePreviewRevisions from "./WorkspacePreviewRevisions.ts";
30 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
31 import * as ServerConfig from "../config.ts";
32 import { makeFakeWslHost } from "../testUtils/fakeWsl.ts";
33 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
34 import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
35 import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
36 import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
37 import { assetFileResponse } from "../http.ts";
38 import { ASSET_ROUTE_PREFIX, issueAssetUrl, readMcpAppHtml, resolveAsset } from "./AssetAccess.ts";
39 import * as NativeAppIconResolver from "./NativeAppIconResolver.ts";
40 import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
41 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
42 import { fakeSourceControlDriverInstance } from "@t3tools/source-control-testing/fakeSourceControlDriver";
43 import * as BuiltInDrivers from "../sourceControl/builtInDrivers.ts";
44 import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
45 import { sourceControlMediaResponse } from "./sourceControlMediaResponse.ts";
46 import * as HostProcess from "@t3tools/shared/HostProcess";
47
48 vi.mock("node:fs/promises", async (importOriginal) => {
49 const actual = await importOriginal<typeof NodeFSP>();
50 return { ...actual, open: vi.fn(actual.open), realpath: vi.fn(actual.realpath) };
51 });
52
53 const layerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
54 prefix: "t3-asset-access-test-",
55 });
56 const screenshotPng = new Uint8Array(24);
57 screenshotPng.set([
58 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52,
59 ]);
60 new DataView(screenshotPng.buffer).setUint32(16, 390);
61 new DataView(screenshotPng.buffer).setUint32(20, 844);
62 const screenshotItem = {
63 id: TurnItemId.make("tool-screenshot"),
64 type: "dynamic_tool" as const,
65 threadId: ThreadId.make("thread-1"),
66 runId: null,
67 nodeId: null,
68 providerThreadId: null,
69 providerTurnId: null,
70 nativeItemRef: null,
71 parentItemId: null,
72 ordinal: 1,
73 status: "completed" as const,
74 title: null,
75 toolName: "mcp__t3-code__device_screenshot",
76 input: { deviceId: "phone" },
77 output: {
78 content: [
79 {
80 type: "image",
81 source: {
82 type: "base64",
83 media_type: "image/png",
84 data: Buffer.from(screenshotPng).toString("base64"),
85 },
86 },
87 ],
88 },
89 startedAt: DateTime.makeUnsafe("2026-10-05T00:00:00.000Z"),
90 completedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),
91 updatedAt: DateTime.makeUnsafe("2026-10-05T00:00:01.000Z"),
92 };
93
94 const oversizedScreenshotItem = {
95 ...screenshotItem,
96 id: TurnItemId.make("tool-screenshot-oversized"),
97 output: {
98 content: [
99 {
100 type: "image",
101 source: { type: "base64", media_type: "image/png", data: "A".repeat(14 * 1024 * 1024) },
102 },
103 ],
104 },
105 };
106
107 const layerTest = Layer.mergeAll(
108 NodeHttpPlatform.layer,
109 Layer.mock(Orchestrator.OrchestratorV2)({
110 getTurnItem: ({ itemId }) =>
111 Effect.succeed(
112 itemId === screenshotItem.id
113 ? screenshotItem
114 : itemId === oversizedScreenshotItem.id
115 ? oversizedScreenshotItem
116 : null,
117 ),
118 }),
119 layerConfig,
120 WorkspacePaths.layer,
121 ProjectFaviconResolver.layer.pipe(
122 Layer.provide(WorkspacePaths.layer),
123 Layer.provide(T3ProjectFileLoader.layer),
124 ),
125 NativeAppIconResolver.layer.pipe(Layer.provide(layerConfig)),
126 AssetSigner.layer.pipe(
127 Layer.provideMerge(ServerSecretStore.layer.pipe(Layer.provide(layerConfig))),
128 ),
129 WorkspacePreviewRevisions.layer,
130 ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
131
132 describe("AssetAccess", () => {
133 describe("readMcpAppHtml", () => {
134 it.effect("accepts snapshots at the stored HTML byte limit", () =>
135 Effect.gen(function* () {
136 const fileSystem = yield* FileSystem.FileSystem;
137 const path = yield* Path.Path;
138 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
139 const file = path.join(directory, "app.html");
140 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
141 yield* fileSystem.writeFile(file, new Uint8Array(limit).fill(120));
142
143 const bytes = yield* readMcpAppHtml(file);
144 expect(bytes?.byteLength).toBe(limit);
145 expect(bytes?.every((byte) => byte === 120)).toBe(true);
146 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
147 );
148
149 it.effect("rejects snapshots one byte past the limit and much larger files", () =>
150 Effect.gen(function* () {
151 const fileSystem = yield* FileSystem.FileSystem;
152 const path = yield* Path.Path;
153 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
154 const file = path.join(directory, "app.html");
155 const limit = MCP_APP_MAX_HTML_BYTES + 128 * 1024;
156 for (const size of [limit + 1, limit * 2]) {
157 yield* fileSystem.writeFile(file, new Uint8Array(size).fill(120));
158 expect(yield* readMcpAppHtml(file)).toBeNull();
159 }
160 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
161 );
162
163 it.effect("preserves UTF-8 bytes across stream chunks and accepts empty snapshots", () =>
164 Effect.gen(function* () {
165 const fileSystem = yield* FileSystem.FileSystem;
166 const path = yield* Path.Path;
167 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
168 const file = path.join(directory, "app.html");
169 for (const html of ["", "<body>" + "☃".repeat(100_000) + "</body>"]) {
170 const expected = new TextEncoder().encode(html);
171 yield* fileSystem.writeFile(file, expected);
172 const bytes = yield* readMcpAppHtml(file);
173 expect(bytes?.byteLength).toBe(expected.byteLength);
174 expect(bytes && new TextDecoder().decode(bytes)).toBe(html);
175 }
176 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
177 );
178
179 // regression: #17026 apply host color scheme to saved MCP apps
180 it.effect("preserves filesystem failures instead of reporting oversized HTML", () =>
181 Effect.gen(function* () {
182 const fileSystem = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-html-" });
185 const error = yield* readMcpAppHtml(path.join(directory, "missing.html")).pipe(Effect.flip);
186 expect(error._tag).toBe("PlatformError");
187 expect(error.reason._tag).toBe("NotFound");
188 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
189 );
190 });
191
192 it.effect("serves an image a tool returned inline from the stored item", () =>
193 Effect.gen(function* () {
194 const resource = {
195 _tag: "tool-output-image" as const,
196 threadId: screenshotItem.threadId,
197 itemId: screenshotItem.id,
198 index: 0,
199 };
200 const result = yield* issueAssetUrl({ resource });
201 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
202 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
203 const separator = suffix.indexOf("/");
204 expect(yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1))).toEqual({
205 kind: "bytes",
206 mimeType: "image/png",
207 bytes: Buffer.from(screenshotPng),
208 });
209 const missing = yield* issueAssetUrl({ resource: { ...resource, index: 1 } }).pipe(
210 Effect.flip,
211 );
212 expect(missing._tag).toBe("AssetWorkspaceAssetNotFoundError");
213 const oversized = yield* issueAssetUrl({
214 resource: { ...resource, itemId: oversizedScreenshotItem.id },
215 }).pipe(Effect.flip);
216 expect(oversized._tag).toBe("AssetWorkspaceAssetNotFoundError");
217 }).pipe(Effect.provide(layerTest)),
218 );
219
220 it.effect("serves the background image published beside an environment theme", () =>
221 Effect.gen(function* () {
222 const fs = yield* FileSystem.FileSystem;
223 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
224 yield* fs.makeDirectory(environmentThemesDir, { recursive: true });
225 const imagePath = `${environmentThemesDir}/frieren.png`;
226 yield* fs.writeFile(imagePath, screenshotPng);
227 const result = yield* issueAssetUrl({
228 resource: { _tag: "environment-theme-background", themeId: "frieren" },
229 });
230 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
231 const separator = suffix.indexOf("/");
232 const token = suffix.slice(0, separator);
233 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
234 expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(imagePath) });
235 if (asset?.kind !== "file") return;
236 const response = yield* assetFileResponse(asset);
237 expect(response.headers["content-type"]).toBe("image/png");
238
239 yield* fs.remove(imagePath);
240 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toBeNull();
241 }).pipe(Effect.scoped, Effect.provide(layerTest)),
242 );
243
244 it.effect("issues exact URLs for media and browser documents outside the workspace", () =>
245 Effect.gen(function* () {
246 const fs = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-root-" });
249 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-outside-" });
250 for (const [name, mimeType] of [
251 ["screenshot.png", "image/png"],
252 ["recording.mp4", "video/mp4"],
253 ["recording.webm", "video/webm"],
254 ["report.html", "text/html"],
255 ["report.pdf", "application/pdf"],
256 ["notes.odt", "application/vnd.oasis.opendocument.text"],
257 ["budget.ods", "application/vnd.oasis.opendocument.spreadsheet"],
258 ["slides.odp", "application/vnd.oasis.opendocument.presentation"],
259 ["notes.rtf", "application/rtf"],
260 ["book.epub", "application/epub+zip"],
261 ["analysis.ipynb", "application/x-ipynb+json"],
262 ["tone.wav", "audio/wav"],
263 ["tone.webm-audio", "audio/webm"],
264 ["archive.zip", "application/zip"],
265 ["archive.jar", "application/java-archive"],
266 ["archive.tar", "application/x-tar"],
267 ["archive.gz", "application/gzip"],
268 ["archive.tgz", "application/gzip"],
269 ["data.sqlite", "application/vnd.sqlite3"],
270 ["data.sqlite3", "application/vnd.sqlite3"],
271 ["data.db", "application/vnd.sqlite3"],
272 ] as const) {
273 const filePath = path.join(outside, name);
274 yield* fs.writeFileString(filePath, "media");
275 const canonicalFile = yield* fs.realPath(filePath);
276 const result = yield* issueAssetUrl({
277 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
278 workspaceRoot: root,
279 });
280 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
281 const separator = suffix.indexOf("/");
282 const token = suffix.slice(0, separator);
283 expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toMatchObject({
284 kind: "file",
285 path: canonicalFile,
286 mimeType,
287 });
288 yield* fs.writeFileString(path.join(outside, "sibling.png"), "private sibling");
289 expect(yield* resolveAsset(token, "sibling.png")).toBeNull();
290 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
291 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
292 }
293 }).pipe(Effect.provide(layerTest)),
294 );
295
296 it.effect("downloads any linked file with the same exact-file identity checks as media", () =>
297 Effect.gen(function* () {
298 const fs = yield* FileSystem.FileSystem;
299 const path = yield* Path.Path;
300 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-root-" });
301 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-outside-" });
302 for (const name of [
303 "data.csv",
304 "report.docx",
305 "sheet.xlsx",
306 "slides.pptx",
307 "archive.zip",
308 "no-extension",
309 ]) {
310 for (const directory of [root, outside]) {
311 const filePath = path.join(directory, name);
312 yield* fs.writeFileString(filePath, "shared file bytes");
313 const resource = {
314 _tag: "media-file" as const,
315 threadId: ThreadId.make("thread-1"),
316 path: directory === root ? name : filePath,
317 disposition: "attachment" as const,
318 };
319 const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
320 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
321 const separator = suffix.indexOf("/");
322 const token = suffix.slice(0, separator);
323 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
324 expect(asset).toMatchObject({
325 kind: "file",
326 download: true,
327 fileName: name,
328 mimeType: "application/octet-stream",
329 });
330 if (asset?.kind !== "file") throw new Error("Expected a downloadable file");
331 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
332 expect(response.headers.get("content-disposition")).toContain("attachment;");
333 expect(response.headers.get("content-type")).toBe("application/octet-stream");
334 expect(yield* Effect.promise(() => response.text())).toBe("shared file bytes");
335 expect(yield* resolveAsset(token, "sibling.docx")).toBeNull();
336 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
337 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
338 yield* fs.rename(filePath, `${filePath}.original`);
339 yield* fs.writeFileString(filePath, "replacement bytes");
340 expect(yield* resolveAsset(token, name)).toBeNull();
341 }
342 }
343 const directoryError = yield* issueAssetUrl({
344 resource: {
345 _tag: "media-file",
346 threadId: ThreadId.make("thread-1"),
347 path: root,
348 disposition: "attachment",
349 },
350 }).pipe(Effect.flip);
351 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
352 }).pipe(Effect.provide(layerTest)),
353 );
354
355 it.effect("resolves relative media paths from the thread workspace, including outside it", () =>
356 Effect.gen(function* () {
357 const fs = yield* FileSystem.FileSystem;
358 const path = yield* Path.Path;
359 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-relative-" });
360 const root = path.join(directory, "workspace");
361 yield* fs.makeDirectory(root);
362 for (const relativePath of ["screenshot.png", "../recording.mp4"]) {
363 const filePath = path.resolve(root, relativePath);
364 yield* fs.writeFileString(filePath, "media");
365 const result = yield* issueAssetUrl({
366 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: relativePath },
367 workspaceRoot: root,
368 });
369 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
370 const separator = suffix.indexOf("/");
371 expect(
372 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
373 ).toMatchObject({
374 kind: "file",
375 path: yield* fs.realPath(filePath),
376 });
377 }
378 }).pipe(Effect.provide(layerTest)),
379 );
380
381 it.effect("previews draft audio and video from relative workspace paths", () =>
382 Effect.gen(function* () {
383 const fs = yield* FileSystem.FileSystem;
384 const path = yield* Path.Path;
385 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-media-" });
386 for (const [name, mimeType] of [
387 ["video.mp4", "video/mp4"],
388 ["audio.wav", "audio/wav"],
389 ] as const) {
390 const filePath = path.join(root, name);
391 yield* fs.writeFileString(filePath, "media bytes");
392 const result = yield* issueAssetUrl({
393 resource: { _tag: "draft-workspace-file", cwd: root, path: name },
394 workspaceRoot: root,
395 });
396 expect(result.fileRevision).toEqual(expect.any(String));
397 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
398 const separator = suffix.indexOf("/");
399 const token = suffix.slice(0, separator);
400 const asset = yield* resolveAsset(token, suffix.slice(separator + 1));
401 expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(filePath), mimeType });
402 if (asset?.kind !== "file") throw new Error("Expected draft media file");
403 for (const [range, status, body] of [
404 [undefined, 200, "media bytes"],
405 ["bytes=2-5", 206, "dia "],
406 ] as const) {
407 const resolved = yield* resolveAsset(token, suffix.slice(separator + 1));
408 if (resolved?.kind !== "file") throw new Error("Expected draft media file");
409 const response = HttpServerResponse.toWeb(yield* assetFileResponse(resolved, range));
410 expect(response.status).toBe(status);
411 expect(response.headers.get("content-type")).toBe(mimeType);
412 expect(response.headers.get("content-length")).toBe(String(body.length));
413 if (range) expect(response.headers.get("content-range")).toBe("bytes 2-5/11");
414 expect(yield* Effect.promise(() => response.text())).toBe(body);
415 }
416 for (const requestedPath of [
417 name === "video.mp4" ? "audio.wav" : "video.mp4",
418 `../${name}`,
419 ]) {
420 expect(yield* resolveAsset(token, requestedPath)).toBeNull();
421 }
422 expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
423 }
424 }).pipe(Effect.provide(layerTest)),
425 );
426
427 it.effect(
428 "rejects draft media escapes and disallowed types without enabling non-draft media",
429 () =>
430 Effect.gen(function* () {
431 const fs = yield* FileSystem.FileSystem;
432 const path = yield* Path.Path;
433 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-boundary-" });
434 const root = path.join(directory, "workspace");
435 yield* fs.makeDirectory(root);
436 for (const name of ["video.mp4", "audio.wav", "secret.txt"]) {
437 yield* fs.writeFileString(path.join(root, name), "workspace bytes");
438 yield* fs.writeFileString(path.join(directory, name), "outside bytes");
439 }
440 for (const [requestedPath, tag] of [
441 ["../video.mp4", "AssetWorkspacePathValidationError"],
442 ["../audio.wav", "AssetWorkspacePathValidationError"],
443 ["secret.txt", "AssetPreviewTypeValidationError"],
444 ] as const) {
445 const error = yield* issueAssetUrl({
446 resource: { _tag: "draft-workspace-file", cwd: root, path: requestedPath },
447 workspaceRoot: root,
448 }).pipe(Effect.flip);
449 expect(error._tag).toBe(tag);
450 }
451 for (const name of ["video.mp4", "audio.wav"]) {
452 const error = yield* issueAssetUrl({
453 resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: name },
454 workspaceRoot: root,
455 }).pipe(Effect.flip);
456 expect(error._tag).toBe("AssetPreviewTypeValidationError");
457 }
458 }).pipe(Effect.provide(layerTest)),
459 );
460
461 it.effect.skipIf(!symlinksSupported)(
462 "rejects draft media symlinks escaping the workspace or targeting disallowed types",
463 () =>
464 Effect.gen(function* () {
465 const fs = yield* FileSystem.FileSystem;
466 const path = yield* Path.Path;
467 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-symlink-" });
468 const root = path.join(directory, "workspace");
469 yield* fs.makeDirectory(root);
470 const outside = path.join(directory, "outside.mp4");
471 const secret = path.join(root, "secret.txt");
472 yield* fs.writeFileString(outside, "outside bytes");
473 yield* fs.writeFileString(secret, "private bytes");
474 for (const [name, target] of [
475 ["escape.mp4", outside],
476 ["disguised.wav", secret],
477 ] as const) {
478 yield* fs.symlink(target, path.join(root, name));
479 const error = yield* issueAssetUrl({
480 resource: { _tag: "draft-workspace-file", cwd: root, path: name },
481 workspaceRoot: root,
482 }).pipe(Effect.flip);
483 expect(["AssetWorkspaceAssetNotFoundError", "AssetPreviewTypeValidationError"]).toContain(
484 error._tag,
485 );
486 }
487 }).pipe(Effect.provide(layerTest)),
488 );
489
490 it.effect.skipIf(!symlinksSupported)(
491 "preserves absolute draft previews through stable symlinks",
492 () =>
493 Effect.gen(function* () {
494 const fs = yield* FileSystem.FileSystem;
495 const path = yield* Path.Path;
496 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-absolute-" });
497 for (const extension of ["png", "mp4", "wav"]) {
498 const target = path.join(root, `target.${extension}`);
499 const alias = path.join(root, `alias.${extension}`);
500 yield* fs.writeFileString(target, "preview bytes");
501 yield* fs.symlink(target, alias);
502 const result = yield* issueAssetUrl({
503 resource: { _tag: "draft-workspace-file", cwd: root, path: alias },
504 workspaceRoot: root,
505 });
506 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
507 const separator = suffix.indexOf("/");
508 expect(
509 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
510 ).toMatchObject({ kind: "file", path: yield* fs.realPath(target) });
511 }
512 }).pipe(Effect.provide(layerTest)),
513 );
514
515 it.effect.skipIf(!symlinksSupported)(
516 "rejects a draft media path swapped after workspace containment validation",
517 () =>
518 Effect.gen(function* () {
519 const fs = yield* FileSystem.FileSystem;
520 const path = yield* Path.Path;
521 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-draft-swap-" });
522 const root = path.join(directory, "workspace");
523 yield* fs.makeDirectory(root);
524 const filePath = path.join(root, "video.mp4");
525 const outside = path.join(directory, "outside.mp4");
526 yield* fs.writeFileString(filePath, "workspace video");
527 yield* fs.writeFileString(outside, "outside video");
528 const canonicalFile = yield* fs.realPath(filePath);
529 let swapped = false;
530 const swappingFileSystem = FileSystem.FileSystem.of({
531 ...fs,
532 stat: Effect.fn(function* (requestedPath) {
533 const info = yield* fs.stat(requestedPath);
534 if (requestedPath === canonicalFile && !swapped) {
535 swapped = true;
536 yield* fs.remove(filePath);
537 yield* fs.symlink(outside, filePath);
538 }
539 return info;
540 }),
541 });
542 const result = yield* issueAssetUrl({
543 resource: { _tag: "draft-workspace-file", cwd: root, path: "video.mp4" },
544 workspaceRoot: root,
545 }).pipe(Effect.result, Effect.provideService(FileSystem.FileSystem, swappingFileSystem));
546 expect(swapped).toBe(true);
547 expect(result).toMatchObject({
548 _tag: "Failure",
549 failure: { _tag: "AssetWorkspaceAssetNotFoundError" },
550 });
551 }).pipe(Effect.provide(layerTest)),
552 );
553
554 it.effect.each(["media-file", "draft-workspace-file"] as const)(
555 "resolves home-relative %s paths independently of the workspace",
556 (tag) =>
557 Effect.gen(function* () {
558 const fs = yield* FileSystem.FileSystem;
559 const path = yield* Path.Path;
560 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-home-" });
561 const home = path.join(directory, "var", "home", "alice");
562 const filePath = path.join(home, "Downloads", "repro.mp4");
563 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
564 yield* fs.writeFileString(filePath, "recording bytes");
565 const canonicalFile = yield* fs.realPath(filePath);
566 yield* Effect.gen(function* () {
567 for (const workspaceRoot of [
568 path.join(home, "project"),
569 path.join(directory, "srv", "project"),
570 undefined,
571 ]) {
572 if (workspaceRoot) yield* fs.makeDirectory(workspaceRoot, { recursive: true });
573 for (const requestedPath of ["~/Downloads/repro.mp4", "~\\Downloads/repro.mp4"]) {
574 const result = yield* issueAssetUrl({
575 resource: {
576 ...(tag === "media-file"
577 ? { _tag: tag, threadId: ThreadId.make("thread-1") }
578 : { _tag: tag, cwd: workspaceRoot ?? directory }),
579 path: requestedPath,
580 },
581 ...(workspaceRoot ? { workspaceRoot } : {}),
582 });
583 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
584 const separator = suffix.indexOf("/");
585 const asset = yield* resolveAsset(
586 suffix.slice(0, separator),
587 suffix.slice(separator + 1),
588 );
589 expect(asset).toMatchObject({
590 kind: "file",
591 path: canonicalFile,
592 mimeType: "video/mp4",
593 });
594 if (asset?.kind !== "file") throw new Error("Expected a resolved home media file");
595 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset));
596 expect(yield* Effect.promise(() => response.text())).toBe("recording bytes");
597 }
598 }
599 }).pipe(Effect.provideService(HostProcess.HomeDirectory, home));
600 }).pipe(Effect.provide(layerTest)),
601 );
602
603 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
604 "resolves a Windows drive media path under WSL to where wslpath mounts it",
605 () =>
606 Effect.gen(function* () {
607 const fs = yield* FileSystem.FileSystem;
608 const path = yield* Path.Path;
609 const { mountRoot, underWsl } = yield* makeFakeWslHost;
610 const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-wsl-root-" });
611 const filePath = path.join(mountRoot, "c", "Users", "me", "Pictures", "shot.png");
612 yield* fs.makeDirectory(path.dirname(filePath), { recursive: true });
613 yield* fs.writeFile(filePath, screenshotPng);
614 const canonicalFile = yield* fs.realPath(filePath);
615 const drivePath = "C:\\Users\\me\\Pictures\\shot.png";
616
617 for (const resource of [
618 { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: drivePath },
619 { _tag: "draft-workspace-file", cwd: workspaceRoot, path: drivePath },
620 ] as const) {
621 const result = yield* underWsl(issueAssetUrl({ resource, workspaceRoot }));
622 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
623 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
624 const separator = suffix.indexOf("/");
625 expect(
626 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
627 ).toMatchObject({ kind: "file", path: canonicalFile, mimeType: "image/png" });
628 }
629 }).pipe(Effect.provide(layerTest)),
630 );
631
632 // Agents on Windows copy paths from Git Bash, which prints `C:\x` as `/c/x`.
633 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
634 "resolves a Git Bash drive media path on Windows",
635 () =>
636 Effect.gen(function* () {
637 const fs = yield* FileSystem.FileSystem;
638 const path = yield* Path.Path;
639 const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-gitbash-" });
640 const canonicalFile = path.join(yield* fs.realPath(workspaceRoot), "shot.png");
641 yield* fs.writeFile(canonicalFile, screenshotPng);
642 const gitBashPath = `/${canonicalFile[0]!.toLowerCase()}${canonicalFile.slice(2).replaceAll("\\", "/")}`;
643
644 for (const resource of [
645 { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: gitBashPath },
646 { _tag: "draft-workspace-file", cwd: workspaceRoot, path: gitBashPath },
647 ] as const) {
648 const result = yield* issueAssetUrl({ resource, workspaceRoot });
649 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
650 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
651 const separator = suffix.indexOf("/");
652 expect(
653 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)),
654 ).toMatchObject({ kind: "file", path: canonicalFile, mimeType: "image/png" });
655 }
656 }).pipe(Effect.provide(layerTest)),
657 );
658
659 // Resolving `file://attacker.test/share/cat.jpg` from an agent's markdown sent the
660 // Windows user's NTLM credentials to attacker.test.
661 it.effect("never resolves a network media path outside the thread's project", () =>
662 Effect.gen(function* () {
663 const fs = yield* FileSystem.FileSystem;
664 const path = yield* Path.Path;
665 const resolved: Array<string> = [];
666 const recordingFileSystem = FileSystem.FileSystem.of({
667 ...fs,
668 realPath: (requestedPath) => {
669 resolved.push(requestedPath);
670 return Effect.fail(
671 PlatformError.systemError({
672 _tag: "NotFound",
673 module: "FileSystem",
674 method: "realPath",
675 pathOrDescriptor: requestedPath,
676 }),
677 );
678 },
679 });
680 const share = "//nas.test/share/project";
681 for (const resource of [
682 {
683 _tag: "media-file",
684 threadId: ThreadId.make("thread-1"),
685 path: "//attacker.test/s/a.png",
686 },
687 { _tag: "draft-workspace-file", cwd: share, path: "//attacker.test/s/a.png" },
688 { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: `${share}/a.png` },
689 ] as const) {
690 const error = yield* issueAssetUrl({ resource, workspaceRoot: share }).pipe(
691 Effect.provideService(FileSystem.FileSystem, recordingFileSystem),
692 Effect.flip,
693 );
694 expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
695 }
696 expect(resolved).toEqual([path.resolve(`${share}/a.png`)]);
697 }).pipe(Effect.provide(layerTest)),
698 );
699
700 it.effect.skipIf(!symlinksSupported)(
701 "rejects non-previewable files, disguised targets, and directories",
702 () =>
703 Effect.gen(function* () {
704 const fs = yield* FileSystem.FileSystem;
705 const path = yield* Path.Path;
706 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-validation-" });
707 for (const name of ["report.md", "secret.txt", "secret.%70ng", "secret.png#private.txt"]) {
708 const filePath = path.join(root, name);
709 yield* fs.writeFileString(filePath, "not media");
710 const error = yield* issueAssetUrl({
711 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
712 }).pipe(Effect.flip);
713 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
714 }
715 const disguisedPath = path.join(root, "disguised.png");
716 yield* fs.symlink(path.join(root, "secret.txt"), disguisedPath);
717 const disguisedError = yield* issueAssetUrl({
718 resource: {
719 _tag: "media-file",
720 threadId: ThreadId.make("thread-1"),
721 path: disguisedPath,
722 },
723 }).pipe(Effect.flip);
724 expect(disguisedError).toBeInstanceOf(AssetPreviewTypeValidationError);
725 const directoryPath = path.join(root, "directory.png");
726 yield* fs.makeDirectory(directoryPath);
727 const directoryError = yield* issueAssetUrl({
728 resource: {
729 _tag: "media-file",
730 threadId: ThreadId.make("thread-1"),
731 path: directoryPath,
732 },
733 }).pipe(Effect.flip);
734 expect(directoryError._tag).toBe("AssetWorkspaceAssetNotFoundError");
735 }).pipe(Effect.provide(layerTest)),
736 );
737
738 it.effect.skipIf(!symlinksSupported)(
739 "serves a linked workspace file only while its target is previewable",
740 () =>
741 Effect.gen(function* () {
742 const fs = yield* FileSystem.FileSystem;
743 const path = yield* Path.Path;
744 const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "t3-link-" }));
745 yield* fs.writeFileString(path.join(root, "payload.xhtml"), "<html/>");
746 yield* fs.writeFileString(path.join(root, "real.pdf"), "%PDF-1.4");
747 const link = path.join(root, "report.pdf");
748 const issue = issueAssetUrl({
749 resource: {
750 _tag: "workspace-file",
751 threadId: ThreadId.make("thread-1"),
752 path: "report.pdf",
753 },
754 workspaceRoot: root,
755 });
756 const resolveIssued = (relativeUrl: string) => {
757 const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
758 const separator = suffix.indexOf("/");
759 return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
760 };
761
762 yield* fs.symlink(path.join(root, "payload.xhtml"), link);
763 expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError");
764
765 yield* fs.remove(link);
766 yield* fs.symlink(path.join(root, "real.pdf"), link);
767 const issued = yield* issue;
768 expect(yield* resolveIssued(issued.relativeUrl)).toMatchObject({
769 path: path.join(root, "real.pdf"),
770 });
771
772 yield* fs.remove(link);
773 yield* fs.symlink(path.join(root, "payload.xhtml"), link);
774 expect(yield* resolveIssued(issued.relativeUrl)).toBeNull();
775 }).pipe(Effect.provide(layerTest)),
776 );
777
778 it.effect.skipIf(!symlinksSupported)("does not issue URLs for server state files", () =>
779 Effect.gen(function* () {
780 const fs = yield* FileSystem.FileSystem;
781 const path = yield* Path.Path;
782 const config = yield* ServerConfig.ServerConfig;
783 const stateFile = path.join(config.secretsDir, "example.bin");
784 yield* fs.makeDirectory(config.secretsDir, { recursive: true });
785 yield* fs.writeFile(stateFile, new Uint8Array(32).fill(7));
786 yield* fs.writeFileString(config.dbPath, "SQLite format 3");
787 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-state-" });
788 const alias = path.join(root, "alias");
789 yield* fs.symlink(stateFile, alias);
790 const threadId = ThreadId.make("thread-1");
791 for (const resource of [
792 { _tag: "media-file", threadId, path: stateFile, disposition: "attachment" },
793 { _tag: "media-file", threadId, path: alias, disposition: "attachment" },
794 {
795 _tag: "media-file",
796 threadId,
797 path: path.join(config.secretsDir, "..", "secrets", "example.bin"),
798 disposition: "attachment",
799 },
800 { _tag: "media-file", threadId, path: config.dbPath },
801 { _tag: "draft-workspace-file", cwd: config.stateDir, path: "statev2.sqlite" },
802 ] as const) {
803 const error = yield* issueAssetUrl({ resource }).pipe(Effect.flip);
804 expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError");
805 }
806
807 const icon = path.join(config.baseDir, "icon.png");
808 yield* fs.symlink(stateFile, icon);
809 yield* fs.writeFileString(path.join(config.baseDir, "page.html"), '<img src="icon.png">');
810 const page = yield* issueAssetUrl({
811 resource: { _tag: "draft-workspace-file", cwd: config.baseDir, path: "page.html" },
812 });
813 const pageToken = page.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length).split("/")[0]!;
814 expect(yield* resolveAsset(pageToken, "icon.png")).toBeNull();
815 const faviconError = yield* issueAssetUrl({
816 resource: { _tag: "project-favicon", cwd: root },
817 projectFaviconPath: icon,
818 }).pipe(Effect.flip);
819 expect(faviconError._tag).toBe("AssetProjectFaviconNotFoundError");
820 }).pipe(Effect.provide(layerTest)),
821 );
822
823 it.effect.skipIf(!symlinksSupported)(
824 "binds media URLs to the canonical target and rejects symlink substitution",
825 () =>
826 Effect.gen(function* () {
827 const fs = yield* FileSystem.FileSystem;
828 const path = yield* Path.Path;
829 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-symlink-" });
830 const filePath = path.join(root, "actual.svg");
831 const aliasPath = path.join(root, "alias.png");
832 const replacementPath = path.join(root, "other.svg");
833 yield* fs.writeFileString(filePath, "<svg/>");
834 yield* fs.writeFileString(replacementPath, "<svg>private</svg>");
835 yield* fs.symlink(filePath, aliasPath);
836 const canonicalFile = yield* fs.realPath(filePath);
837 const result = yield* issueAssetUrl({
838 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: aliasPath },
839 });
840 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
841 const separator = suffix.indexOf("/");
842 const token = suffix.slice(0, separator);
843 const name = suffix.slice(separator + 1);
844 const expected = { kind: "file", path: canonicalFile, mimeType: "image/svg+xml" };
845 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
846 yield* fs.remove(aliasPath);
847 yield* fs.symlink(replacementPath, aliasPath);
848 expect(yield* resolveAsset(token, name)).toMatchObject(expected);
849 yield* fs.remove(filePath);
850 yield* fs.symlink(replacementPath, filePath);
851 expect(yield* resolveAsset(token, name)).toBeNull();
852 }).pipe(Effect.provide(layerTest)),
853 );
854
855 it.effect.skipIf(!symlinksSupported)(
856 "keeps full and partial responses bound to the file opened during resolution",
857 () =>
858 Effect.gen(function* () {
859 const fs = yield* FileSystem.FileSystem;
860 const path = yield* Path.Path;
861 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-file-" });
862 const filePath = path.join(root, "recording.mp4");
863 const savedPath = path.join(root, "saved.mp4");
864 const secretPath = path.join(root, "secret.txt");
865 yield* fs.writeFileString(filePath, "0123456789");
866 yield* fs.writeFileString(secretPath, "private information");
867 const result = yield* issueAssetUrl({
868 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
869 });
870 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
871 const separator = suffix.indexOf("/");
872 for (const [range, expected, status] of [
873 [undefined, "0123456789", 200],
874 ["bytes=2-5", "2345", 206],
875 ] as const) {
876 const asset = yield* resolveAsset(
877 suffix.slice(0, separator),
878 suffix.slice(separator + 1),
879 );
880 if (asset?.kind !== "file") throw new Error("Expected a resolved media file");
881
882 yield* fs.rename(filePath, savedPath);
883 yield* fs.symlink(secretPath, filePath);
884 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, range));
885 expect(response.status).toBe(status);
886 expect(response.headers.get("content-length")).toBe(String(expected.length));
887 expect(yield* Effect.promise(() => response.text())).toBe(expected);
888 yield* fs.remove(filePath);
889 yield* fs.rename(savedPath, filePath);
890 }
891 }).pipe(Effect.provide(layerTest)),
892 );
893
894 it.effect.skipIf(!symlinksSupported)(
895 "rejects a symlink swapped in after canonical validation but before open",
896 () =>
897 Effect.gen(function* () {
898 const fs = yield* FileSystem.FileSystem;
899 const path = yield* Path.Path;
900 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-open-race-" });
901 const filePath = path.join(root, "recording.mp4");
902 const secretPath = path.join(root, "secret.txt");
903 yield* fs.writeFileString(filePath, "video");
904 yield* fs.writeFileString(secretPath, "secret");
905 const canonicalPath = yield* fs.realPath(filePath);
906 const result = yield* issueAssetUrl({
907 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
908 });
909 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
910 const separator = suffix.indexOf("/");
911 const swappingFileSystem = FileSystem.FileSystem.of({
912 ...fs,
913 stat: Effect.fn(function* (requestedPath) {
914 const info = yield* fs.stat(requestedPath);
915 if (requestedPath === canonicalPath) {
916 yield* fs.remove(filePath);
917 yield* fs.symlink(secretPath, filePath);
918 }
919 return info;
920 }),
921 });
922 expect(
923 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
924 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
925 ),
926 ).toBeNull();
927 }).pipe(Effect.provide(layerTest)),
928 );
929
930 it.effect.skipIf(!symlinksSupported)(
931 "rejects an ancestor symlink race even when canonical path rechecks would pass",
932 () =>
933 Effect.gen(function* () {
934 const fs = yield* FileSystem.FileSystem;
935 const path = yield* Path.Path;
936 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-parent-race-" });
937 const publicDirectory = path.join(root, "public");
938 const privateDirectory = path.join(root, "private");
939 yield* fs.makeDirectory(publicDirectory);
940 yield* fs.makeDirectory(privateDirectory);
941 const filePath = path.join(publicDirectory, "recording.mp4");
942 yield* fs.writeFileString(filePath, "public video");
943 yield* fs.writeFileString(path.join(privateDirectory, "recording.mp4"), "private video");
944 const canonicalPath = yield* fs.realPath(filePath);
945 const result = yield* issueAssetUrl({
946 resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
947 });
948 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
949 const separator = suffix.indexOf("/");
950 const native = yield* Effect.promise(() =>
951 vi.importActual<typeof NodeFSP>("node:fs/promises"),
952 );
953 const savedDirectory = path.join(root, "saved");
954 const realpathSpy = vi.mocked(NodeFSP.realpath).mockImplementationOnce(async () => {
955 await native.unlink(publicDirectory);
956 await native.rename(savedDirectory, publicDirectory);
957 const canonical = await native.realpath(canonicalPath);
958 await native.rename(publicDirectory, savedDirectory);
959 await native.symlink(privateDirectory, publicDirectory, "junction");
960 return canonical;
961 });
962 yield* Effect.addFinalizer(() =>
963 Effect.sync(() => realpathSpy.mockReset().mockImplementation(native.realpath)),
964 );
965 const swappingFileSystem = FileSystem.FileSystem.of({
966 ...fs,
967 realPath: Effect.fn(function* (requestedPath) {
968 const canonical = yield* fs.realPath(requestedPath);
969 if (requestedPath === canonicalPath) {
970 yield* fs.rename(publicDirectory, savedDirectory);
971 yield* Effect.promise(() =>
972 NodeFSP.symlink(privateDirectory, publicDirectory, "junction"),
973 );
974 }
975 return canonical;
976 }),
977 });
978 expect(
979 yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
980 Effect.provideService(FileSystem.FileSystem, swappingFileSystem),
981 ),
982 ).toBeNull();
983 }).pipe(Effect.provide(layerTest)),
984 );
985
986 it.effect("versions media by file changes rather than by re-signing", () =>
987 Effect.gen(function* () {
988 const fs = yield* FileSystem.FileSystem;
989 const path = yield* Path.Path;
990 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-revision-" });
991 const filePath = path.join(root, "recording.mp4");
992 yield* fs.writeFileString(filePath, "original");
993 yield* Effect.promise(() => NodeFSP.utimes(filePath, 1_000, 1_000));
994 const input = {
995 resource: {
996 _tag: "media-file" as const,
997 threadId: ThreadId.make("thread-1"),
998 path: filePath,
999 },
1000 };
1001 const original = yield* issueAssetUrl(input);
1002 expect(original.fileRevision).toEqual(expect.any(String));
1003
1004 yield* TestClock.adjust("1 minute");
1005 const renewed = yield* issueAssetUrl(input);
1006 expect(renewed.relativeUrl).not.toBe(original.relativeUrl);
1007 expect(renewed.fileRevision).toBe(original.fileRevision);
1008
1009 yield* fs.writeFileString(filePath, "modified");
1010 yield* Effect.promise(() => NodeFSP.utimes(filePath, 2_000, 2_000));
1011 const edited = yield* issueAssetUrl(input);
1012 expect(edited.fileRevision).not.toBe(original.fileRevision);
1013
1014 const replacement = path.join(root, "replacement.mp4");
1015 yield* fs.writeFileString(replacement, "modified");
1016 yield* Effect.promise(() => NodeFSP.utimes(replacement, 2_000, 2_000));
1017 yield* fs.rename(replacement, filePath);
1018 const replaced = yield* issueAssetUrl(input);
1019 expect(replaced.fileRevision).not.toBe(edited.fileRevision);
1020 }).pipe(Effect.provide(layerTest)),
1021 );
1022
1023 it.effect("keeps in-place edits readable but requires a new URL after atomic replacement", () =>
1024 Effect.gen(function* () {
1025 const fs = yield* FileSystem.FileSystem;
1026 const path = yield* Path.Path;
1027 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-replacement-" });
1028 const filePath = path.join(root, "recording.mp4");
1029 yield* fs.writeFileString(filePath, "original");
1030 const input = {
1031 resource: {
1032 _tag: "media-file" as const,
1033 threadId: ThreadId.make("thread-1"),
1034 path: filePath,
1035 },
1036 };
1037 const original = yield* issueAssetUrl(input);
1038 const suffix = original.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1039 const separator = suffix.indexOf("/");
1040 const token = suffix.slice(0, separator);
1041 const name = suffix.slice(separator + 1);
1042 yield* fs.writeFileString(filePath, "in-place edit");
1043 const edited = yield* resolveAsset(token, name);
1044 if (edited?.kind !== "file") throw new Error("Expected the edited media file");
1045 const editedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(edited));
1046 expect(yield* Effect.promise(() => editedResponse.text())).toBe("in-place edit");
1047
1048 const replacement = path.join(root, "replacement.mp4");
1049 yield* fs.writeFileString(replacement, "replacement");
1050 yield* fs.rename(replacement, filePath);
1051 expect(yield* resolveAsset(token, name)).toBeNull();
1052
1053 const renewed = yield* issueAssetUrl(input);
1054 const renewedSuffix = renewed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1055 const renewedSeparator = renewedSuffix.indexOf("/");
1056 const renewedAsset = yield* resolveAsset(
1057 renewedSuffix.slice(0, renewedSeparator),
1058 renewedSuffix.slice(renewedSeparator + 1),
1059 );
1060 if (renewedAsset?.kind !== "file") throw new Error("Expected the replacement media file");
1061 const renewedResponse = HttpServerResponse.toWeb(yield* assetFileResponse(renewedAsset));
1062 expect(yield* Effect.promise(() => renewedResponse.text())).toBe("replacement");
1063 yield* fs.remove(filePath);
1064 expect(
1065 yield* resolveAsset(
1066 renewedSuffix.slice(0, renewedSeparator),
1067 renewedSuffix.slice(renewedSeparator + 1),
1068 ),
1069 ).toBeNull();
1070 }).pipe(Effect.provide(layerTest)),
1071 );
1072
1073 it.effect.skipIf(!symlinksSupported)("validates canonical preview dependency paths", () =>
1074 Effect.gen(function* () {
1075 const fs = yield* FileSystem.FileSystem;
1076 const path = yield* Path.Path;
1077 const root = yield* fs.makeTempDirectoryScoped();
1078 const page = path.join(root, "report.html");
1079 yield* fs.writeFileString(page, "<!doctype html>");
1080 for (const name of ["report.css", ".internal.css", "notes.txt"]) {
1081 yield* fs.writeFileString(path.join(root, name), "fixture");
1082 }
1083 yield* fs.symlink(path.join(root, "report.css"), path.join(root, "theme.css"));
1084 yield* fs.symlink(path.join(root, ".internal.css"), path.join(root, "internal.css"));
1085 yield* fs.symlink(path.join(root, "notes.txt"), path.join(root, "notes.css"));
1086
1087 const result = yield* issueAssetUrl({
1088 resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: page },
1089 workspaceRoot: root,
1090 });
1091 const suffix = result.relativeUrl.slice(ASSET_ROUTE_PREFIX.length + 1);
1092 const token = suffix.slice(0, suffix.indexOf("/"));
1093 expect(yield* resolveAsset(token, "theme.css")).toMatchObject({
1094 path: yield* fs.realPath(path.join(root, "report.css")),
1095 });
1096 expect(yield* resolveAsset(token, "internal.css")).toBeNull();
1097 expect(yield* resolveAsset(token, "notes.css")).toBeNull();
1098 }).pipe(Effect.provide(layerTest)),
1099 );
1100
1101 it.effect.skipIf(!symlinksSupported)(
1102 "validates canonical sibling assets for previews in dot-prefixed folders",
1103 () =>
1104 Effect.gen(function* () {
1105 const fs = yield* FileSystem.FileSystem;
1106 const path = yield* Path.Path;
1107 const root = yield* fs.makeTempDirectoryScoped();
1108 const reportsDirectory = path.join(root, ".reports");
1109 yield* fs.makeDirectory(path.join(reportsDirectory, ".cache"), { recursive: true });
1110 yield* fs.makeDirectory(path.join(root, ".secret"));
1111 const page = path.join(reportsDirectory, "report.html");
1112 yield* fs.writeFileString(page, "<!doctype html>");
1113 const dependencies = [
1114 { name: "linked.css", target: path.join(root, ".secret", "key.css"), allowed: false },
1115 {
1116 name: "inner.css",
1117 target: path.join(reportsDirectory, ".cache", "hidden.css"),
1118 allowed: false,
1119 },
1120 { name: "shared.css", target: path.join(root, "shared.css"), allowed: true },
1121 ];
1122 for (const { name, target } of dependencies) {
1123 yield* fs.writeFileString(target, "fixture");
1124 yield* fs.symlink(target, path.join(reportsDirectory, name));
1125 }
1126 const result = yield* issueAssetUrl({
1127 resource: { _tag: "workspace-file", threadId: ThreadId.make("thread-1"), path: page },
1128 workspaceRoot: root,
1129 });
1130 const suffix = result.relativeUrl.slice(ASSET_ROUTE_PREFIX.length + 1);
1131 const token = suffix.slice(0, suffix.indexOf("/"));
1132 for (const { name, target, allowed } of dependencies) {
1133 const resolved = yield* resolveAsset(token, name);
1134 if (allowed) {
1135 expect(resolved).toEqual({
1136 kind: "file",
1137 path: yield* fs.realPath(target),
1138 renderIntent: "file-preview",
1139 });
1140 } else {
1141 expect(resolved).toBeNull();
1142 }
1143 }
1144 }).pipe(Effect.provide(layerTest)),
1145 );
1146
1147 it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
1148 Effect.gen(function* () {
1149 const fileSystem = yield* FileSystem.FileSystem;
1150 const path = yield* Path.Path;
1151 const root = yield* fileSystem.makeTempDirectoryScoped({
1152 prefix: "t3-asset-workspace-",
1153 });
1154 const htmlPath = path.join(root, "report.html");
1155 const cssPath = path.join(root, "report.css");
1156 yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
1157 yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
1158 yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
1159 const canonicalHtmlPath = yield* fileSystem.realPath(htmlPath);
1160 const canonicalCssPath = yield* fileSystem.realPath(cssPath);
1161
1162 const result = yield* issueAssetUrl({
1163 resource: {
1164 _tag: "workspace-file",
1165 threadId: ThreadId.make("thread-1"),
1166 path: htmlPath,
1167 },
1168 workspaceRoot: root,
1169 });
1170 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1171 const separatorIndex = suffix.indexOf("/");
1172 const token = suffix.slice(0, separatorIndex);
1173
1174 expect(yield* resolveAsset(token, "report.html")).toEqual({
1175 kind: "file",
1176 path: canonicalHtmlPath,
1177 renderIntent: "file-preview",
1178 });
1179 expect(yield* resolveAsset(token, "report.css")).toEqual({
1180 kind: "file",
1181 path: canonicalCssPath,
1182 renderIntent: "file-preview",
1183 });
1184 yield* fileSystem.makeDirectory(path.join(root, "clips"));
1185 for (const mediaName of ["clips/clip.mp4", "clips/clip.webm", "clips/clip.mp3"]) {
1186 const mediaPath = path.join(root, mediaName);
1187 yield* fileSystem.writeFileString(mediaPath, "media bytes");
1188 expect(yield* resolveAsset(token, mediaName)).toMatchObject({
1189 kind: "file",
1190 path: yield* fileSystem.realPath(mediaPath),
1191 });
1192 }
1193 for (const extension of ["otf", "ttf", "woff", "woff2"]) {
1194 const fontName = `preview.${extension}`;
1195 const fontPath = path.join(root, fontName);
1196 yield* fileSystem.writeFileString(fontPath, "font bytes");
1197 const canonicalFontPath = yield* fileSystem.realPath(fontPath);
1198 for (const resource of [
1199 { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },
1200 { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },
1201 ]) {
1202 const url = yield* issueAssetUrl({ resource, workspaceRoot: root });
1203 const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1204 expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), fontName)).toEqual({
1205 kind: "file",
1206 path: canonicalFontPath,
1207 renderIntent: "file-preview",
1208 });
1209 }
1210 }
1211 expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
1212 expect(yield* resolveAsset(token, ".env")).toBeNull();
1213 expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
1214
1215 const reportsDirectory = path.join(root, ".reports");
1216 yield* fileSystem.makeDirectory(path.join(reportsDirectory, ".cache"), { recursive: true });
1217 const dotHtmlPath = path.join(reportsDirectory, "report.html");
1218 const dotCssPath = path.join(reportsDirectory, "report.css");
1219 yield* fileSystem.writeFileString(dotHtmlPath, "<h1>Quarterly report</h1>");
1220 yield* fileSystem.writeFileString(dotCssPath, "body { color: red; }");
1221 yield* fileSystem.writeFileString(path.join(reportsDirectory, ".cache", "hidden.css"), "");
1222 const dotUrl = yield* issueAssetUrl({
1223 resource: {
1224 _tag: "workspace-file",
1225 threadId: ThreadId.make("thread-1"),
1226 path: dotHtmlPath,
1227 },
1228 workspaceRoot: root,
1229 });
1230 const dotSuffix = dotUrl.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1231 const dotToken = dotSuffix.slice(0, dotSuffix.indexOf("/"));
1232 expect(yield* resolveAsset(dotToken, "report.html")).toEqual({
1233 kind: "file",
1234 path: yield* fileSystem.realPath(dotHtmlPath),
1235 renderIntent: "file-preview",
1236 });
1237 expect(yield* resolveAsset(dotToken, "report.css")).toEqual({
1238 kind: "file",
1239 path: yield* fileSystem.realPath(dotCssPath),
1240 renderIntent: "file-preview",
1241 });
1242 expect(yield* resolveAsset(dotToken, ".cache/hidden.css")).toBeNull();
1243 for (const extension of [
1244 "odt",
1245 "ods",
1246 "odp",
1247 "rtf",
1248 "epub",
1249 "ipynb",
1250 "zip",
1251 "jar",
1252 "tar",
1253 "gz",
1254 "tgz",
1255 "sqlite",
1256 "sqlite3",
1257 "db",
1258 "docx",
1259 "xlsx",
1260 "pptx",
1261 "bmp",
1262 "heic",
1263 "tif",
1264 "tiff",
1265 "weba",
1266 "mmd",
1267 "mermaid",
1268 ]) {
1269 const siblingName = `private.${extension}`;
1270 yield* fileSystem.writeFileString(path.join(root, siblingName), "private sibling");
1271 for (const resource of [
1272 { _tag: "workspace-file" as const, threadId: ThreadId.make("thread-1"), path: htmlPath },
1273 { _tag: "draft-workspace-file" as const, cwd: root, path: "report.html" },
1274 ]) {
1275 const url = yield* issueAssetUrl({ resource, workspaceRoot: root });
1276 const suffix = url.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1277 expect(yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), siblingName)).toBeNull();
1278 }
1279 }
1280 }).pipe(Effect.provide(layerTest)),
1281 );
1282
1283 it.effect("moves an HTML preview's revision only for the page and the files it requested", () =>
1284 Effect.gen(function* () {
1285 const fileSystem = yield* FileSystem.FileSystem;
1286 const path = yield* Path.Path;
1287 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-asset-revision-" });
1288 const pages = path.join(root, "pages");
1289 yield* fileSystem.makeDirectory(pages);
1290 const write = (name: string, text: string) =>
1291 fileSystem.writeFileString(path.join(pages, name), text);
1292 yield* write("a.html", '<link rel="stylesheet" href="a.css"><script src="late.js"></script>');
1293 yield* write("a.css", "body { color: red; }");
1294 yield* write("b.html", "<h1>b</h1>");
1295 const mint = (name: string) =>
1296 issueAssetUrl({
1297 resource: {
1298 _tag: "workspace-file",
1299 threadId: ThreadId.make("thread-1"),
1300 path: path.join(pages, name),
1301 },
1302 workspaceRoot: root,
1303 });
1304 const load = Effect.fn(function* (name: string, requests: ReadonlyArray<string>) {
1305 const { relativeUrl } = yield* mint(name);
1306 const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1307 for (const request of requests) {
1308 yield* resolveAsset(suffix.slice(0, suffix.indexOf("/")), request);
1309 }
1310 });
1311 const revisions = Effect.fn(function* () {
1312 return [(yield* mint("a.html")).fileRevision, (yield* mint("b.html")).fileRevision];
1313 });
1314
1315 // Two tabs each load a page; a.html also asks for a script that does not exist yet.
1316 const opened = yield* revisions();
1317 expect(opened[0]).toBeDefined();
1318 expect(opened[1]).not.toBe(opened[0]);
1319 yield* load("a.html", ["a.html", "a.css", "late.js"]);
1320 yield* load("b.html", ["b.html"]);
1321 expect(yield* revisions()).toEqual(opened);
1322
1323 // Files no page asked for leave both previews alone.
1324 yield* write("unrelated.css", "p {}");
1325 yield* fileSystem.writeFileString(path.join(root, "notes.md"), "notes");
1326 expect(yield* revisions()).toEqual(opened);
1327
1328 // An edit to one page leaves the page beside it alone.
1329 yield* write("b.html", "<h1>B</h1>");
1330 const afterPageEdit = yield* revisions();
1331 expect(afterPageEdit[0]).toBe(opened[0]);
1332 expect(afterPageEdit[1]).not.toBe(opened[1]);
1333
1334 // A same-size edit to a requested stylesheet reloads only the page that uses it.
1335 yield* write("a.css", "body { color: blue }");
1336 const afterStyleEdit = yield* revisions();
1337 expect(afterStyleEdit[0]).not.toBe(afterPageEdit[0]);
1338 expect(afterStyleEdit[1]).toBe(afterPageEdit[1]);
1339
1340 // So does a requested file that appears, and one that goes away.
1341 yield* write("late.js", "document.title = 'late';");
1342 const afterCreate = yield* revisions();
1343 expect(afterCreate[0]).not.toBe(afterStyleEdit[0]);
1344 yield* fileSystem.remove(path.join(pages, "a.css"));
1345 const afterRemove = yield* revisions();
1346 expect(afterRemove[0]).not.toBe(afterCreate[0]);
1347 expect(afterRemove[1]).toBe(afterPageEdit[1]);
1348
1349 // Overlapping mints after one edit agree, so the edit reloads the page once.
1350 yield* write("late.js", "document.title = 'later';");
1351 const overlapping = yield* Effect.all(
1352 Array.from({ length: 8 }, () => mint("a.html")),
1353 { concurrency: "unbounded" },
1354 );
1355 expect(new Set(overlapping.map((minted) => minted.fileRevision)).size).toBe(1);
1356 expect(overlapping[0]?.fileRevision).not.toBe(afterRemove[0]);
1357
1358 // A page that loads more files than are tracked falls back to the client's own reloads.
1359 yield* load(
1360 "b.html",
1361 Array.from(
1362 { length: WorkspacePreviewRevisions.MAX_TRACKED_FILES_PER_DOCUMENT },
1363 (_, index) => `chunk-${index}.js`,
1364 ),
1365 );
1366 expect((yield* mint("b.html")).fileRevision).toBeUndefined();
1367 expect((yield* mint("a.html")).fileRevision).toBe(overlapping[0]?.fileRevision);
1368 }).pipe(Effect.provide(layerTest)),
1369 );
1370
1371 it.effect("rejects workspace files outside the authorized root", () =>
1372 Effect.gen(function* () {
1373 const fileSystem = yield* FileSystem.FileSystem;
1374 const path = yield* Path.Path;
1375 const root = yield* fileSystem.makeTempDirectoryScoped({
1376 prefix: "t3-asset-root-",
1377 });
1378 const outside = yield* fileSystem.makeTempDirectoryScoped({
1379 prefix: "t3-asset-outside-",
1380 });
1381 const htmlPath = path.join(outside, "report.html");
1382 yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
1383
1384 const error = yield* issueAssetUrl({
1385 resource: {
1386 _tag: "workspace-file",
1387 threadId: ThreadId.make("thread-1"),
1388 path: htmlPath,
1389 },
1390 workspaceRoot: root,
1391 }).pipe(Effect.flip);
1392 expect(error.message).toBe("Workspace file path must be relative to the project root.");
1393 expect(error).toMatchObject({
1394 _tag: "AssetWorkspacePathValidationError",
1395 resource: {
1396 _tag: "workspace-file",
1397 threadId: "thread-1",
1398 path: htmlPath,
1399 },
1400 });
1401 expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError);
1402 }).pipe(Effect.provide(layerTest)),
1403 );
1404
1405 it.effect("issues exact workspace URLs for every non-HTML preview", () =>
1406 Effect.gen(function* () {
1407 const fileSystem = yield* FileSystem.FileSystem;
1408 const path = yield* Path.Path;
1409 const root = yield* fileSystem.makeTempDirectoryScoped({
1410 prefix: "t3-asset-image-workspace-",
1411 });
1412 const assetsDirectory = path.join(root, "assets");
1413 yield* fileSystem.makeDirectory(assetsDirectory, { recursive: true });
1414 yield* fileSystem.writeFileString(
1415 path.join(assetsDirectory, "private.docx"),
1416 "private document",
1417 );
1418 for (const extension of [
1419 "pdf",
1420 "odt",
1421 "ods",
1422 "odp",
1423 "rtf",
1424 "epub",
1425 "ipynb",
1426 "png",
1427 "bmp",
1428 "heic",
1429 "tif",
1430 "tiff",
1431 "docx",
1432 "xlsx",
1433 "pptx",
1434 "ttf",
1435 "otf",
1436 "woff",
1437 "woff2",
1438 "zip",
1439 "jar",
1440 "tar",
1441 "gz",
1442 "tgz",
1443 "sqlite",
1444 "sqlite3",
1445 "db",
1446 ]) {
1447 const name = `preview.${extension}`;
1448 const filePath = path.join(assetsDirectory, name);
1449 const siblingName = `other.${extension}`;
1450 yield* fileSystem.writeFileString(filePath, "preview");
1451 yield* fileSystem.writeFileString(
1452 path.join(assetsDirectory, siblingName),
1453 "private sibling",
1454 );
1455 const canonicalPath = yield* fileSystem.realPath(filePath);
1456 for (const resource of [
1457 {
1458 _tag: "workspace-file" as const,
1459 threadId: ThreadId.make("thread-1"),
1460 path: filePath,
1461 },
1462 { _tag: "draft-workspace-file" as const, cwd: root, path: `assets/${name}` },
1463 ]) {
1464 const result = yield* issueAssetUrl({ resource, workspaceRoot: root });
1465 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1466 const token = suffix.slice(0, suffix.indexOf("/"));
1467 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalPath });
1468 expect(yield* resolveAsset(token, siblingName)).toBeNull();
1469 expect(yield* resolveAsset(token, "private.docx")).toBeNull();
1470 expect(yield* resolveAsset(token, `../${name}`)).toBeNull();
1471 }
1472 }
1473 }).pipe(Effect.provide(layerTest)),
1474 );
1475
1476 it.effect("previews workspace files with literal fragment characters in their paths", () =>
1477 Effect.gen(function* () {
1478 const fileSystem = yield* FileSystem.FileSystem;
1479 const path = yield* Path.Path;
1480 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-preview-literal-" });
1481 const directory = path.join(root, "assets#archive");
1482 yield* fileSystem.makeDirectory(directory);
1483
1484 for (const name of [
1485 "icon#v2.png",
1486 "report#draft.pdf",
1487 "report.docx",
1488 "workbook.xlsx",
1489 "slides.pptx",
1490 "notes.odt",
1491 "budget.ods",
1492 "slides.odp",
1493 "notes.rtf",
1494 "book.epub",
1495 "analysis.ipynb",
1496 "specimen.ttf",
1497 "specimen.otf",
1498 "specimen.woff",
1499 "specimen.woff2",
1500 "image.bmp",
1501 "image.heic",
1502 "image.tif",
1503 "image.tiff",
1504 ]) {
1505 const filePath = path.join(directory, name);
1506 yield* fileSystem.writeFileString(filePath, "preview fixture");
1507 const canonicalFile = yield* fileSystem.realPath(filePath);
1508 const result = yield* issueAssetUrl({
1509 resource: {
1510 _tag: "workspace-file",
1511 threadId: ThreadId.make("thread-1"),
1512 path: filePath,
1513 },
1514 workspaceRoot: root,
1515 });
1516 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1517 const token = suffix.slice(0, suffix.indexOf("/"));
1518
1519 expect(yield* resolveAsset(token, name)).toEqual({ kind: "file", path: canonicalFile });
1520 if (name.endsWith(".png")) {
1521 expect(yield* resolveAsset(token, "other.png")).toBeNull();
1522 }
1523 }
1524
1525 const disguisedPath = path.join(root, "image.png#notes.txt");
1526 yield* fileSystem.writeFileString(disguisedPath, "not an image");
1527 const error = yield* issueAssetUrl({
1528 resource: {
1529 _tag: "workspace-file",
1530 threadId: ThreadId.make("thread-1"),
1531 path: disguisedPath,
1532 },
1533 workspaceRoot: root,
1534 }).pipe(Effect.flip);
1535 expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
1536 }).pipe(Effect.provide(layerTest)),
1537 );
1538
1539 it.effect("signs MCP render intent only for inline HTML attachments", () =>
1540 Effect.gen(function* () {
1541 const config = yield* ServerConfig.ServerConfig;
1542 const fs = yield* FileSystem.FileSystem;
1543 const path = yield* Path.Path;
1544 yield* fs.makeDirectory(config.attachmentsDir, { recursive: true });
1545 for (const extension of ["html", "pdf"]) {
1546 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000031-${extension}`;
1547 yield* fs.writeFileString(
1548 path.join(config.attachmentsDir, `${attachmentId}.${extension}`),
1549 "capture",
1550 );
1551 for (const disposition of ["inline", "attachment"] as const) {
1552 const result = yield* issueAssetUrl({
1553 resource: {
1554 _tag: "attachment",
1555 attachmentId,
1556 disposition,
1557 renderIntent: "mcp-app",
1558 },
1559 });
1560 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1561 const separator = suffix.indexOf("/");
1562 const asset = yield* resolveAsset(
1563 suffix.slice(0, separator),
1564 suffix.slice(separator + 1),
1565 );
1566 if (asset?.kind !== "file") throw new Error("Expected attachment file");
1567 expect("renderIntent" in asset ? asset.renderIntent : undefined).toBe(
1568 extension === "html" && disposition === "inline" ? "mcp-app" : undefined,
1569 );
1570 const token = suffix.slice(0, separator);
1571 const [payload, signature] = token.split(".");
1572 const claims = JSON.parse(Buffer.from(payload!, "base64url").toString("utf8"));
1573 claims.renderIntent = claims.renderIntent ? undefined : "mcp-app";
1574 const tampered = `${Buffer.from(JSON.stringify(claims)).toString("base64url")}.${signature}`;
1575 expect(yield* resolveAsset(tampered, suffix.slice(separator + 1))).toBeNull();
1576 }
1577 }
1578 }).pipe(Effect.provide(layerTest)),
1579 );
1580
1581 it.effect.skipIf(!symlinksSupported)(
1582 "reports image attachment dimensions when the attachments directory is a symlink",
1583 () =>
1584 Effect.gen(function* () {
1585 const config = yield* ServerConfig.ServerConfig;
1586 const fs = yield* FileSystem.FileSystem;
1587 const path = yield* Path.Path;
1588 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-attachments-link-" });
1589 const realAttachmentsDir = path.join(root, "real");
1590 const linkedAttachmentsDir = path.join(root, "linked");
1591 yield* fs.makeDirectory(realAttachmentsDir);
1592 yield* fs.symlink(realAttachmentsDir, linkedAttachmentsDir);
1593 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000041";
1594 yield* fs.writeFile(path.join(realAttachmentsDir, `${attachmentId}.png`), screenshotPng);
1595
1596 const result = yield* issueAssetUrl({
1597 resource: { _tag: "attachment", attachmentId },
1598 }).pipe(
1599 Effect.provideService(ServerConfig.ServerConfig, {
1600 ...config,
1601 attachmentsDir: linkedAttachmentsDir,
1602 }),
1603 );
1604 expect(result.imageDimensions).toEqual({ width: 390, height: 844 });
1605 }).pipe(Effect.provide(layerTest)),
1606 );
1607
1608 it.effect("serves document attachments inline when a viewer requests it", () =>
1609 Effect.gen(function* () {
1610 const config = yield* ServerConfig.ServerConfig;
1611 const fileSystem = yield* FileSystem.FileSystem;
1612 const path = yield* Path.Path;
1613 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1614 for (const [extension, mimeType] of [
1615 ["pdf", "application/pdf"],
1616 ["svg", "image/svg+xml"],
1617 ["bmp", "image/bmp"],
1618 ["ttf", "font/ttf"],
1619 ["otf", "font/otf"],
1620 ["woff", "font/woff"],
1621 ["woff2", "font/woff2"],
1622 ["weba", "audio/webm"],
1623 ["zip", "application/zip"],
1624 ["jar", "application/java-archive"],
1625 ["tar", "application/x-tar"],
1626 ["gz", "application/gzip"],
1627 ["tgz", "application/gzip"],
1628 ["sqlite", "application/vnd.sqlite3"],
1629 ["sqlite3", "application/vnd.sqlite3"],
1630 ["db", "application/vnd.sqlite3"],
1631 ] as const) {
1632 const attachmentId = `thread-1-00000000-0000-4000-8000-000000000001-${extension}`;
1633 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.${extension}`);
1634 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1635
1636 const result = yield* issueAssetUrl({
1637 resource: {
1638 _tag: "attachment",
1639 attachmentId,
1640 fileName: `report.${extension}`,
1641 mimeType: "text/html",
1642 disposition: "inline",
1643 },
1644 });
1645 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1646 const separatorIndex = suffix.indexOf("/");
1647
1648 expect(
1649 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1650 ).toEqual({
1651 kind: "file",
1652 path: attachmentPath,
1653 fileName: `report.${extension}`,
1654 mimeType,
1655 });
1656 }
1657 }).pipe(Effect.provide(layerTest)),
1658 );
1659
1660 it.effect("keeps inline requests for other attachment types as downloads", () =>
1661 Effect.gen(function* () {
1662 const config = yield* ServerConfig.ServerConfig;
1663 const fileSystem = yield* FileSystem.FileSystem;
1664 const path = yield* Path.Path;
1665 const attachmentId = "thread-1-00000000-0000-4000-8000-000000000002-7z";
1666 const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.7z`);
1667 yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
1668 yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
1669
1670 const result = yield* issueAssetUrl({
1671 resource: {
1672 _tag: "attachment",
1673 attachmentId,
1674 fileName: "archive.7z",
1675 mimeType: "text/html",
1676 disposition: "inline",
1677 },
1678 });
1679 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1680 const separatorIndex = suffix.indexOf("/");
1681
1682 expect(
1683 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1684 ).toMatchObject({ kind: "file", path: attachmentPath, download: true });
1685 }).pipe(Effect.provide(layerTest)),
1686 );
1687 it.effect("issues project favicon capabilities with a signed fallback", () =>
1688 Effect.gen(function* () {
1689 const fileSystem = yield* FileSystem.FileSystem;
1690 const path = yield* Path.Path;
1691 const root = yield* fileSystem.makeTempDirectoryScoped({
1692 prefix: "t3-asset-favicon-",
1693 });
1694 const faviconPath = path.join(root, "favicon.svg");
1695 const initialFavicon = "<svg>a</svg>";
1696 const updatedFavicon = "<svg>b</svg>";
1697 expect(updatedFavicon).toHaveLength(initialFavicon.length);
1698 yield* fileSystem.writeFileString(faviconPath, initialFavicon);
1699 const canonicalFaviconPath = yield* fileSystem.realPath(faviconPath);
1700
1701 const faviconResult = yield* issueAssetUrl({
1702 resource: { _tag: "project-favicon", cwd: root },
1703 });
1704 expect(faviconResult.sourcePath).toBe("favicon.svg");
1705 expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
1706 expect(
1707 yield* issueAssetUrl({
1708 resource: { _tag: "project-favicon", cwd: root },
1709 }),
1710 ).toEqual(faviconResult);
1711 const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1712 const faviconSeparatorIndex = faviconSuffix.indexOf("/");
1713 expect(
1714 yield* resolveAsset(
1715 faviconSuffix.slice(0, faviconSeparatorIndex),
1716 faviconSuffix.slice(faviconSeparatorIndex + 1),
1717 ),
1718 ).toEqual({ kind: "file", path: canonicalFaviconPath });
1719
1720 yield* fileSystem.writeFileString(faviconPath, updatedFavicon);
1721 const updatedFaviconResult = yield* issueAssetUrl({
1722 resource: { _tag: "project-favicon", cwd: root },
1723 });
1724 expect(
1725 updatedFaviconResult.relativeUrl.slice(updatedFaviconResult.relativeUrl.lastIndexOf("/")),
1726 ).not.toBe(faviconResult.relativeUrl.slice(faviconResult.relativeUrl.lastIndexOf("/")));
1727
1728 yield* fileSystem.remove(faviconPath);
1729 const fallbackResult = yield* issueAssetUrl({
1730 resource: { _tag: "project-favicon", cwd: root },
1731 });
1732 expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
1733 expect(fallbackResult.sourcePath).toBeUndefined();
1734 const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1735 const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
1736 expect(
1737 yield* resolveAsset(
1738 fallbackSuffix.slice(0, fallbackSeparatorIndex),
1739 fallbackSuffix.slice(fallbackSeparatorIndex + 1),
1740 ),
1741 ).toBeNull();
1742 }).pipe(Effect.provide(layerTest)),
1743 );
1744
1745 it.effect("issues an exact capability for a saved favicon outside the workspace", () =>
1746 Effect.gen(function* () {
1747 const fileSystem = yield* FileSystem.FileSystem;
1748 const path = yield* Path.Path;
1749 const root = yield* fileSystem.makeTempDirectoryScoped({
1750 prefix: "t3-asset-favicon-workspace-",
1751 });
1752 const pictures = yield* fileSystem.makeTempDirectoryScoped({
1753 prefix: "t3-asset-favicon-pictures-",
1754 });
1755 const externalPath = path.join(pictures, "custom.png");
1756 const siblingPath = path.join(pictures, "sibling.png");
1757 yield* fileSystem.writeFile(externalPath, new Uint8Array([1, 2, 3]));
1758 yield* fileSystem.writeFile(siblingPath, new Uint8Array([4, 5, 6]));
1759 const canonicalPath = yield* fileSystem.realPath(externalPath);
1760 const canonicalSiblingPath = yield* fileSystem.realPath(siblingPath);
1761
1762 const result = yield* issueAssetUrl({
1763 resource: { _tag: "project-favicon", cwd: root },
1764 projectFaviconPath: externalPath,
1765 });
1766 const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1767 const separatorIndex = suffix.indexOf("/");
1768
1769 expect(result.sourcePath).toBe(externalPath);
1770 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.png$/);
1771 expect(
1772 yield* resolveAsset(suffix.slice(0, separatorIndex), suffix.slice(separatorIndex + 1)),
1773 ).toEqual({ kind: "file", path: canonicalPath });
1774 const tamperedSuffixResult = yield* resolveAsset(
1775 suffix.slice(0, separatorIndex),
1776 "sibling.png",
1777 );
1778 expect(tamperedSuffixResult).toEqual({ kind: "file", path: canonicalPath });
1779 expect(tamperedSuffixResult).not.toEqual({ kind: "file", path: canonicalSiblingPath });
1780 }).pipe(Effect.provide(layerTest)),
1781 );
1782
1783 it.effect("ignores a client favicon path hint", () =>
1784 Effect.gen(function* () {
1785 const fileSystem = yield* FileSystem.FileSystem;
1786 const path = yield* Path.Path;
1787 const root = yield* fileSystem.makeTempDirectoryScoped({
1788 prefix: "t3-asset-favicon-hint-",
1789 });
1790 yield* fileSystem.makeDirectory(path.join(root, "brand"));
1791 yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
1792 yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
1793
1794 const result = yield* issueAssetUrl({
1795 resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
1796 projectFaviconPath: "brand/saved.svg",
1797 });
1798
1799 expect(result.sourcePath).toBe(path.join("brand", "saved.svg"));
1800 expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
1801 }).pipe(Effect.provide(layerTest)),
1802 );
1803
1804 it.effect("preserves the change request repository through RPC decoding and signed media", () =>
1805 Effect.gen(function* () {
1806 const decodeAssetCreateUrlInput = Schema.decodeEffect(AssetCreateUrlInput);
1807 const resource = {
1808 _tag: SOURCE_CONTROL_MEDIA_ASSET,
1809 cwd: "/personal-fork",
1810 url: "https://github.com/user-attachments/assets/1a1842fb-6383-492f-873c-57aa0033fa6c",
1811 repository: "enterprise/private",
1812 };
1813 const input = yield* decodeAssetCreateUrlInput({ resource });
1814 const issued = yield* issueAssetUrl(input);
1815 const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1816 const separator = suffix.indexOf("/");
1817 const resolved = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
1818
1819 expect(resolved).toEqual({
1820 kind: "source-control-media",
1821 url: resource.url,
1822 cwd: resource.cwd,
1823 repository: resource.repository,
1824 expiresAt: issued.expiresAt,
1825 });
1826 }).pipe(Effect.provide(layerTest)),
1827 );
1828
1829 it.effect("serves a host's credentialed media through that host's driver", () => {
1830 const fetched: Array<{
1831 url: string;
1832 headers: Readonly<Record<string, string>>;
1833 repository?: string;
1834 }> = [];
1835 const url = "https://github.com/owner/repo/blob/main/docs/shot.png";
1836 const media = sourceControlDefinitions.mediaUrl(url)!;
1837 const layerDrivers = Layer.succeed(BuiltInDrivers.SourceControlDrivers, [
1838 {
1839 driver: { kind: media.definition.kind, definition: media.definition },
1840 instance: fakeSourceControlDriverInstance(media.definition.kind, {
1841 pullRequests: null,
1842 fetchMedia: (request) =>
1843 Effect.sync(() => {
1844 fetched.push(request);
1845 return HttpClientResponse.fromWeb(
1846 HttpClientRequest.get(request.url),
1847 new Response("bytes", { status: 206, headers: { "content-length": "5" } }),
1848 );
1849 }),
1850 }),
1851 },
1852 ]);
1853 // Clients that predate `repository` get the checkout's.
1854 const layerIdentities = Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1855 resolve: () =>
1856 Effect.succeed({
1857 canonicalKey: "github.com/owner/repo",
1858 locator: { source: "git-remote", remoteName: "origin", remoteUrl: "" },
1859 provider: media.definition.kind,
1860 owner: "owner",
1861 name: "repo",
1862 }),
1863 });
1864 return Effect.gen(function* () {
1865 const decodeAssetCreateUrlInput = Schema.decodeEffect(AssetCreateUrlInput);
1866
1867 // Every client and server release spells the resource this way on the wire.
1868 const { resource } = yield* decodeAssetCreateUrlInput({
1869 resource: { _tag: "github-media", cwd: "/repo", url },
1870 });
1871 const issued = yield* issueAssetUrl({ resource });
1872 const suffix = issued.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
1873 const separator = suffix.indexOf("/");
1874 const asset = yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1));
1875 expect(asset).toEqual({
1876 kind: "source-control-media",
1877 url: media.fetchUrl,
1878 cwd: "/repo",
1879 expiresAt: issued.expiresAt,
1880 });
1881 if (asset?.kind !== "source-control-media") return;
1882
1883 const response = yield* sourceControlMediaResponse(asset, {
1884 range: "bytes=0-4",
1885 cookie: "session",
1886 });
1887 expect(fetched).toEqual([
1888 { url: media.fetchUrl, headers: { range: "bytes=0-4" }, repository: "owner/repo" },
1889 ]);
1890 expect(response.status).toBe(206);
1891 // The upstream sent no type, so it comes from the file name the host gave the media.
1892 expect(response.headers["content-type"]).toBe("image/png");
1893 expect(response.headers["content-length"]).toBe("5");
1894
1895 // A pull request's own repository wins over the checkout it is shown in.
1896 yield* sourceControlMediaResponse({ ...asset, repository: "enterprise/private" }, {});
1897 expect(fetched.at(-1)?.repository).toBe("enterprise/private");
1898 }).pipe(Effect.provide(Layer.mergeAll(layerTest, layerDrivers, layerIdentities)));
1899 });
1900
1901 it.effect("refuses media no host keeps behind a credential, without echoing the URL", () =>
1902 Effect.gen(function* () {
1903 const encodeAssetAccessError = Schema.encodeEffect(Schema.fromJsonString(AssetAccessError));
1904
1905 for (const url of [
1906 "https://example.com/shot.png",
1907 "https://example.com/shot.png?token=private-media-token",
1908 ]) {
1909 const error = yield* issueAssetUrl({
1910 resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
1911 }).pipe(Effect.flip);
1912 expect(error._tag).toBe("AssetGitHubMediaUrlValidationError");
1913 const encoded = yield* encodeAssetAccessError(error);
1914 expect(encoded).not.toContain(url);
1915 }
1916 }).pipe(Effect.provide(layerTest)),
1917 );
1918 });