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