Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 type AssetCreateUrlResult,
4 AssetWorkspaceAssetNotFoundError,
5 AssetWorkspaceAssetInspectionError,
6 AssetWorkspaceContextNotFoundError,
7 EnvironmentAuthorizationError,
8 EnvironmentId,
9 type ProjectCloneSnapshot,
10 ProjectId,
11 ThreadId,
12 WS_METHODS,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Result from "effect/Result";
16import * as Effect from "effect/Effect";
17import * as Stream from "effect/Stream";
18import * as SubscriptionRef from "effect/SubscriptionRef";
19import * as Option from "effect/Option";
20import * as Layer from "effect/Layer";
21import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
22
23import * as EnvironmentRegistry from "../connection/registry.ts";
24import {
25 AVAILABLE_CONNECTION_STATE,
26 PrimaryConnectionTarget,
27 type PreparedConnection,
28 type SupervisorConnectionState,
29} from "../connection/model.ts";
30import * as EnvironmentSupervisor from "../connection/supervisor.ts";
31import type { RpcSession } from "../rpc/session.ts";
32import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
33import { createProjectFaviconCache } from "../projectFaviconCache.ts";
34import {
35 createAssetEnvironmentAtoms,
36 createProjectFaviconUrlAtomFamily,
37 InvalidAssetCollectionKeyError,
38 parseAssetCollectionKey,
39} from "./assets.ts";
40
41describe("asset collection keys", () => {
42 it("preserves malformed JSON and its native cause", () => {
43 const key = "not-json";
44 let error: unknown;
45
46 try {
47 parseAssetCollectionKey(key);
48 } catch (cause) {
49 error = cause;
50 }
51
52 expect(error).toBeInstanceOf(InvalidAssetCollectionKeyError);
53 expect(error).toMatchObject({ key, cause: expect.any(SyntaxError) });
54 });
55
56 it("rejects invalid asset collection shapes", () => {
57 const key = JSON.stringify(["environment-1", [{ _tag: "unknown" }]]);
58
59 expect(() => parseAssetCollectionKey(key)).toThrowError(InvalidAssetCollectionKeyError);
60 });
61});
62
63describe("createAssetEnvironmentAtoms", () => {
64 it.effect.each([
65 { name: "missing video", path: "/tmp/clip.mp4", fallback: true },
66 { name: "literal filename characters", path: "/tmp/frame#one?two.png", fallback: true },
67 { name: "windows path", path: "C:\\Users\\demo\\clip.mp4", fallback: true },
68 { name: "inspection failure", path: "/tmp/clip.mp4", error: "inspection", fallback: true },
69 { name: "foreign thread", path: "/tmp/clip.mp4", error: "context", fallback: true },
70 { name: "missing on both hosts", path: "/tmp/clip.mp4", localFails: true },
71 {
72 name: "a defect in the local retry",
73 path: "/tmp/clip.mp4",
74 localFails: true,
75 localDefect: true,
76 },
77 { name: "remote success", path: "/tmp/clip.mp4", success: true },
78 { name: "relative path", path: "clip.mp4" },
79 { name: "no primary", path: "/tmp/clip.mp4", primary: "none" },
80 { name: "primary reconnect", path: "/tmp/frame.png", primary: "reconnecting" },
81 { name: "same environment", path: "/tmp/clip.mp4", primary: "same" },
82 { name: "non-media", path: "/tmp/report.html" },
83 { name: "authorization failure", path: "/tmp/clip.mp4", error: "auth" },
84 ])("uses the correct environment for $name", (scenario) =>
85 Effect.gen(function* () {
86 const remoteId = EnvironmentId.make("remote");
87 const localId = EnvironmentId.make("local");
88 const resource = {
89 _tag: "media-file" as const,
90 threadId: ThreadId.make("foreign-thread"),
91 path: scenario.path,
92 };
93 const error =
94 scenario.error === "auth"
95 ? new EnvironmentAuthorizationError({
96 message: "denied",
97 requiredScope: "orchestration:read",
98 })
99 : scenario.error === "inspection"
100 ? new AssetWorkspaceAssetInspectionError({ resource, cause: new Error("unreadable") })
101 : scenario.error === "context"
102 ? new AssetWorkspaceContextNotFoundError({ resource })
103 : new AssetWorkspaceAssetNotFoundError({ resource, checkedPath: "/tmp/clip.mp4" });
104 const calls: EnvironmentId[] = [];
105 const supervisors = new Map<
106 EnvironmentId,
107 EnvironmentSupervisor.EnvironmentSupervisor["Service"]
108 >();
109 for (const environmentId of [remoteId, localId]) {
110 const client = {
111 [WS_METHODS.assetsCreateUrl]: () => {
112 calls.push(environmentId);
113 if (environmentId === localId && scenario.localFails) {
114 const localError = Effect.fail(
115 new AssetWorkspaceAssetNotFoundError({ resource, checkedPath: "/local/clip.mp4" }),
116 );
117 return scenario.localDefect
118 ? localError.pipe(Effect.ensuring(Effect.die("cleanup failed")))
119 : localError;
120 }
121 return environmentId === remoteId && !scenario.success
122 ? Effect.fail(error)
123 : Effect.succeed({
124 relativeUrl: `/api/assets/${environmentId}/media`,
125 expiresAt: 999999,
126 });
127 },
128 } as unknown as WsRpcProtocolClient;
129 const session = { client } as RpcSession;
130 supervisors.set(
131 environmentId,
132 EnvironmentSupervisor.EnvironmentSupervisor.of({
133 target: new PrimaryConnectionTarget({
134 environmentId,
135 label: environmentId,
136 httpBaseUrl: `https://${environmentId}.test`,
137 wsBaseUrl: `wss://${environmentId}.test`,
138 }),
139 state: yield* SubscriptionRef.make<SupervisorConnectionState>({
140 ...AVAILABLE_CONNECTION_STATE,
141 phase: "connected" as const,
142 }),
143 session: yield* SubscriptionRef.make(Option.some(session)),
144 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
145 connect: Effect.void,
146 disconnect: Effect.void,
147 retryNow: Effect.void,
148 }),
149 );
150 }
151 const environments = EnvironmentRegistry.EnvironmentRegistry.of({
152 run: (id, effect) =>
153 Effect.provideService(
154 effect,
155 EnvironmentSupervisor.EnvironmentSupervisor,
156 supervisors.get(id)!,
157 ),
158 followStream: (id, stream) =>
159 Stream.provideService(
160 stream,
161 EnvironmentSupervisor.EnvironmentSupervisor,
162 supervisors.get(id)!,
163 ),
164 } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
165 const registry = AtomRegistry.make();
166 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
167 const localTarget = {
168 environmentId: scenario.primary === "same" ? remoteId : localId,
169 httpBaseUrl: "https://local.test",
170 };
171 const localEnvironment = Atom.make<typeof localTarget | null>(
172 scenario.primary === "none" || scenario.primary === "reconnecting" ? null : localTarget,
173 );
174 const assets = createAssetEnvironmentAtoms(
175 Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments)),
176 localEnvironment,
177 );
178 const query = assets.createUrl({ environmentId: remoteId, input: { resource } });
179 const result = AtomRegistry.getResult(registry, query, { suspendOnWaiting: true });
180 if (scenario.fallback || scenario.success) {
181 expect((yield* result).relativeUrl).toBe(
182 scenario.fallback
183 ? "https://local.test/api/assets/local/media"
184 : "/api/assets/remote/media",
185 );
186 } else if (scenario.localDefect) {
187 const cause = yield* Effect.sandbox(result).pipe(Effect.flip);
188 expect(Cause.findErrorOption(cause)).toEqual(Option.some(error));
189 expect(Cause.findDefect(cause)).toEqual(Result.succeed("cleanup failed"));
190 } else {
191 expect(yield* Effect.flip(result)).toEqual(error);
192 }
193 expect(calls).toEqual(
194 scenario.fallback || scenario.localFails ? [remoteId, localId] : [remoteId],
195 );
196 if (scenario.primary === "reconnecting") {
197 registry.set(localEnvironment, localTarget);
198 expect((yield* result).relativeUrl).toBe("https://local.test/api/assets/local/media");
199 expect(calls).toEqual([remoteId, remoteId, localId]);
200 }
201 }).pipe(Effect.scoped),
202 );
203
204 it("keys asset URL queries by environment and resource", () => {
205 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
206 EnvironmentRegistry.EnvironmentRegistry,
207 never
208 >;
209 const assets = createAssetEnvironmentAtoms(runtime);
210 const environmentId = EnvironmentId.make("environment-1");
211 const originalTarget = {
212 environmentId,
213 input: {
214 resource: {
215 _tag: "project-favicon" as const,
216 cwd: "/repo/original",
217 },
218 },
219 };
220
221 expect(assets.createUrl(originalTarget)).toBe(
222 assets.createUrl({
223 environmentId,
224 input: {
225 resource: {
226 _tag: "project-favicon",
227 cwd: "/repo/original",
228 },
229 },
230 }),
231 );
232 expect(
233 assets.createUrl({
234 environmentId,
235 input: {
236 resource: {
237 _tag: "project-favicon",
238 cwd: "/repo/next",
239 },
240 },
241 }),
242 ).not.toBe(assets.createUrl(originalTarget));
243 expect(
244 assets.createUrl({
245 environmentId,
246 input: {
247 resource: {
248 _tag: "project-favicon",
249 cwd: "/repo/original",
250 path: "brand/icon.svg",
251 },
252 },
253 }),
254 ).not.toBe(assets.createUrl(originalTarget));
255 expect(
256 assets.createUrl({
257 environmentId: EnvironmentId.make("environment-2"),
258 input: originalTarget.input,
259 }),
260 ).not.toBe(assets.createUrl(originalTarget));
261 });
262
263 it("keys collections while preserving independent resource queries", () => {
264 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
265 EnvironmentRegistry.EnvironmentRegistry,
266 never
267 >;
268 const assets = createAssetEnvironmentAtoms(runtime);
269 const environmentId = EnvironmentId.make("environment-1");
270 const resources = [
271 { _tag: "attachment" as const, attachmentId: "attachment-1" },
272 { _tag: "attachment" as const, attachmentId: "attachment-2" },
273 ];
274
275 expect(assets.createUrls({ environmentId, resources })).toBe(
276 assets.createUrls({
277 environmentId,
278 resources: resources.map((resource) => ({ ...resource })),
279 }),
280 );
281 expect(
282 assets.createUrls({
283 environmentId,
284 resources: [...resources].toReversed(),
285 }),
286 ).not.toBe(assets.createUrls({ environmentId, resources }));
287 });
288});
289
290describe("project favicon URL cache", () => {
291 it("renders a persisted thumbnail immediately in a fresh registry and refreshes it remotely", async () => {
292 const image = "data:image/png;base64,aWNvbg==";
293 const replacement = "data:image/png;base64,bmV3";
294 const records = new Map<string, unknown>();
295 const storage = {
296 list: async () => [...records.values()],
297 put: async (key: string, entry: unknown) => {
298 records.set(key, entry);
299 },
300 remove: async (key: string) => {
301 records.delete(key);
302 },
303 };
304 const target = { environmentId: EnvironmentId.make("remote"), cwd: "/workspace" };
305 const previousCache = createProjectFaviconCache({ storage, load: async () => image });
306 await previousCache.resolve(
307 target,
308 "https://remote.test/api/assets/old/v1-icon.png",
309 new AbortController().signal,
310 );
311 await previousCache.flush();
312 const cache = createProjectFaviconCache({ storage, load: async () => replacement });
313 await cache.hydrate();
314 const registry = AtomRegistry.make();
315 const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
316 AsyncResult.initial(),
317 );
318 const connection = Atom.make<Option.Option<{ httpBaseUrl: string }>>(Option.none());
319 const favicon = createProjectFaviconUrlAtomFamily({
320 createUrl: () => result,
321 preparedConnection: () => connection,
322 imageCache: cache,
323 })(target);
324 const unmount = registry.mount(favicon);
325 try {
326 expect(registry.get(favicon)).toBe(image);
327 let unsubscribe = () => {};
328 const refreshed = new Promise<void>((resolve) => {
329 unsubscribe = registry.subscribe(favicon, (value) => {
330 if (value === replacement) resolve();
331 });
332 });
333 registry.set(connection, Option.some({ httpBaseUrl: "https://remote.test" }));
334 registry.set(
335 result,
336 AsyncResult.success({
337 relativeUrl: "/api/assets/new/v2-icon.png",
338 expiresAt: 4_000_000_000_000,
339 }),
340 );
341 expect(registry.get(favicon)).toBe(image);
342 await refreshed;
343 unsubscribe();
344 expect(registry.get(favicon)).toBe(replacement);
345 registry.set(connection, Option.none());
346 registry.set(result, AsyncResult.failure(Cause.die("offline")));
347 expect(registry.get(favicon)).toBe(replacement);
348 } finally {
349 unmount();
350 registry.dispose();
351 }
352 });
353
354 it("retains icons across outages and remounts, then accepts refreshed and missing icons", () => {
355 const registry = AtomRegistry.make();
356 const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
357 AsyncResult.initial(),
358 );
359 const connection = Atom.make(Option.some({ httpBaseUrl: "https://remote.test" }));
360 const favicon = createProjectFaviconUrlAtomFamily({
361 createUrl: () => result,
362 preparedConnection: () => connection,
363 })({ environmentId: EnvironmentId.make("remote"), cwd: "/workspace" });
364 let unmount = registry.mount(favicon);
365 try {
366 expect(registry.get(favicon)).toBeNull();
367 registry.set(
368 result,
369 AsyncResult.success({
370 expiresAt: 4_000_000_000_000,
371 relativeUrl: "/api/assets/token-a/icon.svg",
372 }),
373 );
374 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
375
376 registry.set(connection, Option.none());
377 registry.set(result, AsyncResult.failure(Cause.die("disconnected")));
378 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
379 unmount();
380 unmount = registry.mount(favicon);
381 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
382
383 registry.set(result, AsyncResult.initial());
384 registry.set(connection, Option.some({ httpBaseUrl: "https://reconnected.test" }));
385 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-a/icon.svg");
386 registry.set(
387 result,
388 AsyncResult.success({
389 expiresAt: 4_000_000_000_000,
390 relativeUrl: "/api/assets/token-b/icon.svg",
391 }),
392 );
393 expect(registry.get(favicon)).toBe("https://reconnected.test/api/assets/token-b/icon.svg");
394
395 registry.set(
396 result,
397 AsyncResult.success({
398 expiresAt: 4_000_000_000_000,
399 relativeUrl: "/api/assets/token-c/project-favicon-missing",
400 }),
401 );
402 expect(registry.get(favicon)).toBe(
403 "https://reconnected.test/api/assets/token-c/project-favicon-missing",
404 );
405 registry.set(connection, Option.none());
406 expect(registry.get(favicon)).toBe(
407 "https://reconnected.test/api/assets/token-c/project-favicon-missing",
408 );
409 } finally {
410 unmount();
411 registry.dispose();
412 }
413 });
414
415 it("does not reuse another environment, workspace, or selected icon's cached URL", () => {
416 const registry = AtomRegistry.make();
417 const result = Atom.make<AsyncResult.AsyncResult<AssetCreateUrlResult, unknown>>(
418 AsyncResult.success({
419 expiresAt: 4_000_000_000_000,
420 relativeUrl: "/api/assets/token/icon.svg",
421 }),
422 );
423 const favicon = createProjectFaviconUrlAtomFamily({
424 createUrl: () => result,
425 preparedConnection: () => Atom.make(Option.some({ httpBaseUrl: "https://remote.test" })),
426 });
427 const target = { environmentId: EnvironmentId.make("remote"), cwd: "/workspace" };
428 const unmount = registry.mount(favicon(target));
429 try {
430 expect(registry.get(favicon(target))).toBe("https://remote.test/api/assets/token/icon.svg");
431 registry.set(result, AsyncResult.failure(Cause.die("disconnected")));
432 expect(
433 registry.get(favicon({ ...target, environmentId: EnvironmentId.make("other") })),
434 ).toBeNull();
435 expect(registry.get(favicon({ ...target, cwd: "/other" }))).toBeNull();
436 expect(registry.get(favicon({ ...target, faviconPath: "brand.svg" }))).toBeNull();
437 expect(registry.get(favicon({ ...target, faviconPath: null }))).toBe(
438 "https://remote.test/api/assets/token/icon.svg",
439 );
440 } finally {
441 unmount();
442 registry.dispose();
443 }
444 });
445
446 const cloning: ProjectCloneSnapshot = {
447 projectId: ProjectId.make("project-cloning"),
448 remoteUrl: "git@github.com:octocat/app.git",
449 destinationPath: "/workspace",
450 repository: null,
451 phase: "running",
452 stage: "receiving",
453 percent: 10,
454 detail: null,
455 error: null,
456 startedAt: "2026-01-01T00:00:00.000Z",
457 endedAt: null,
458 sequence: 1,
459 };
460
461 function mountClonedProjectFavicon(initialClones: ReadonlyArray<ProjectCloneSnapshot>) {
462 const registry = AtomRegistry.make();
463 const server = { lookups: 0, landed: false };
464 const result = Atom.make(() => {
465 server.lookups += 1;
466 return AsyncResult.success({
467 expiresAt: 4_000_000_000_000,
468 relativeUrl: server.landed
469 ? "/api/assets/token-b/v1-icon.svg"
470 : "/api/assets/token-a/project-favicon-missing",
471 });
472 });
473 const clones = Atom.make(initialClones);
474 const connection = Atom.make(Option.some({ httpBaseUrl: "https://remote.test" }));
475 const favicon = createProjectFaviconUrlAtomFamily({
476 createUrl: () => result,
477 preparedConnection: () => connection,
478 projectClones: () => clones,
479 })({ environmentId: EnvironmentId.make("remote"), cwd: "/workspace" });
480 const unmount = registry.mount(favicon);
481 return {
482 registry,
483 server,
484 clones,
485 favicon,
486 dispose: () => {
487 unmount();
488 registry.dispose();
489 },
490 };
491 }
492
493 it("asks for a cloned project's icon again once its clone lands", () => {
494 const { registry, server, clones, favicon, dispose } = mountClonedProjectFavicon([cloning]);
495 try {
496 expect(registry.get(favicon)).toBe(
497 "https://remote.test/api/assets/token-a/project-favicon-missing",
498 );
499 registry.set(clones, [
500 { ...cloning, percent: 80, sequence: 2 },
501 {
502 ...cloning,
503 projectId: ProjectId.make("project-other"),
504 destinationPath: "/other",
505 phase: "done",
506 sequence: 3,
507 },
508 ]);
509 expect(server.lookups).toBe(1);
510
511 server.landed = true;
512 registry.set(clones, [{ ...cloning, phase: "done", sequence: 4 }]);
513 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-b/v1-icon.svg");
514 expect(server.lookups).toBe(2);
515 } finally {
516 dispose();
517 }
518 });
519
520 it("asks again when the first clone list it sees already says done", () => {
521 const { registry, server, clones, favicon, dispose } = mountClonedProjectFavicon([]);
522 try {
523 expect(registry.get(favicon)).toBe(
524 "https://remote.test/api/assets/token-a/project-favicon-missing",
525 );
526 server.landed = true;
527 registry.set(clones, [{ ...cloning, phase: "done", sequence: 2 }]);
528 expect(registry.get(favicon)).toBe("https://remote.test/api/assets/token-b/v1-icon.svg");
529 } finally {
530 dispose();
531 }
532 });
533});