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

assets.test.ts

504 lines18.5 KB

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