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