Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Crypto from "effect/Crypto";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Hex from "effect/encoding/Hex";
8import * as Exit from "effect/Exit";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as PlatformError from "effect/PlatformError";
14import * as Schema from "effect/Schema";
15import * as Scope from "effect/Scope";
16import * as Sink from "effect/Sink";
17import * as Stream from "effect/Stream";
18import { HttpClient, HttpClientResponse } from "effect/http";
19
20import * as AntigravityInstallation from "./AntigravityInstallation.ts";
21import { type AntigravityReleaseAsset } from "./antigravityRelease.ts";
22
23const serverContents = "antigravity runtime\n";
24const harnessContents = "local harness\n";
25const previousReleaseId = "1".repeat(64);
26const previousVersion = "fixture-old";
27const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
28
29const zipFixtures = {
30 complete:
31 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAAAFAAAABIAAAAAAAAAAAAAAO2BAAAAAGFneV9hY3Bfc2VydmVyLnBhclBLAQIUAxQAAAAIAAAAIl1fcgMpEAAAAA4AAAAVAAAAAAAAAAAAAADtgUQAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWxQSwUGAAAAAAIAAgCDAAAAhwAAAAAA",
32 missingHarness:
33 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKl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AACLAAAAAAA=",
44};
45
46// The installation checks POSIX exec bits off the real filesystem unless the
47// platform is win32, so a linux platform mock cannot pass on NTFS. Default to
48// the host and let the fixture names follow; the suite is about install
49// mechanics, which are the same on every platform.
50const hostPlatform: NodeJS.Platform =
51 HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux";
52const completeArchive = Buffer.from(
53 hostPlatform === "win32" ? zipFixtures.windows : zipFixtures.complete,
54 "base64",
55);
56const executableName = hostPlatform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par";
57const harnessName =
58 hostPlatform === "win32" ? "localharness_external.exe" : "localharness_external";
59
60const releaseAsset = Effect.fn("test.antigravityReleaseAsset")(function* (
61 archive: Uint8Array = completeArchive,
62 platform: NodeJS.Platform = hostPlatform,
63) {
64 const crypto = yield* Crypto.Crypto;
65 return {
66 version: "fixture-new",
67 url: "https://dl.google.com/antigravity-test.zip",
68 sha256: Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie)),
69 archiveBytes: archive.byteLength,
70 executable: {
71 name: platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par",
72 bytes: Buffer.byteLength(serverContents),
73 },
74 harness: {
75 name: platform === "win32" ? "localharness_external.exe" : "localharness_external",
76 bytes: Buffer.byteLength(harnessContents),
77 },
78 } satisfies AntigravityReleaseAsset;
79});
80
81const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* (
82 managedDirectory: string,
83 asset: AntigravityReleaseAsset,
84 active = true,
85) {
86 const fs = yield* FileSystem.FileSystem;
87 const path = yield* Path.Path;
88 const directory = path.join(managedDirectory, "versions", asset.sha256);
89 yield* fs.makeDirectory(directory, { recursive: true });
90 yield* fs.writeFileString(path.join(directory, asset.executable.name), serverContents, {
91 mode: 0o755,
92 });
93 yield* fs.writeFileString(path.join(directory, asset.harness.name), harnessContents, {
94 mode: 0o755,
95 });
96 yield* fs.writeFileString(
97 path.join(directory, ".install-complete.json"),
98 encodeJsonString({
99 releaseId: asset.sha256,
100 version: asset.version,
101 executable: asset.executable,
102 harness: asset.harness,
103 }),
104 );
105 if (active) {
106 yield* fs.writeFileString(
107 path.join(managedDirectory, "active.json"),
108 encodeJsonString({ releaseId: asset.sha256 }),
109 );
110 }
111});
112
113interface HarnessOptions {
114 readonly baseDir?: string;
115 readonly asset?: AntigravityReleaseAsset | null;
116 readonly archive?: Buffer;
117 readonly body?: Stream.Stream<Uint8Array> | undefined;
118 readonly contentLength?: number;
119 readonly contentEncoding?: string;
120 readonly platform?: NodeJS.Platform;
121 readonly arch?: NodeJS.Architecture;
122 readonly path?: string;
123 readonly previous?: boolean;
124 readonly fileSystem?: FileSystem.FileSystem;
125 readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"];
126 readonly useDefaultValidation?: boolean;
127}
128
129const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
130 options: HarnessOptions = {},
131) {
132 const fs = yield* FileSystem.FileSystem;
133 const path = yield* Path.Path;
134 const baseDir =
135 options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
136 const platform = options.platform ?? hostPlatform;
137 const arch = options.arch ?? "x64";
138 const archive = options.archive ?? completeArchive;
139 const asset =
140 options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset;
141 const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`);
142 if (options.previous) {
143 yield* writeRelease(managedDirectory, {
144 ...(yield* releaseAsset(archive, platform)),
145 sha256: previousReleaseId,
146 version: previousVersion,
147 });
148 }
149 const stagingReleased = yield* Deferred.make<void>();
150 const requests: string[] = [];
151 const validations: Array<{
152 executable: AntigravityInstallation.AntigravityExecutable;
153 version: string;
154 }> = [];
155 const installationFs = options.fileSystem ?? fs;
156 const trackedFs = FileSystem.FileSystem.of({
157 ...installationFs,
158 makeTempDirectoryScoped: (settings) =>
159 settings?.prefix === ".install-"
160 ? Effect.acquireRelease(installationFs.makeTempDirectory(settings), (directory) =>
161 fs
162 .remove(directory, { recursive: true, force: true })
163 .pipe(Effect.orDie, Effect.andThen(Deferred.succeed(stagingReleased, undefined))),
164 )
165 : installationFs.makeTempDirectoryScoped(settings),
166 });
167 const installation = yield* AntigravityInstallation.makeAntigravityInstallation({
168 baseDir,
169 releaseAsset: asset,
170 ...(options.useDefaultValidation
171 ? {}
172 : {
173 validate: (executable: AntigravityInstallation.AntigravityExecutable, version: string) =>
174 Effect.sync(() => validations.push({ executable, version })).pipe(
175 Effect.andThen(options.validate?.(executable, version) ?? Effect.void),
176 ),
177 }),
178 }).pipe(
179 Effect.provideService(FileSystem.FileSystem, trackedFs),
180 Effect.provideService(HostProcess.Platform, platform),
181 Effect.provideService(HostProcess.Architecture, arch),
182 Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }),
183 Effect.provideService(
184 HttpClient.HttpClient,
185 HttpClient.make((request) =>
186 Effect.sync(() => {
187 requests.push(request.url);
188 const response = HttpClientResponse.fromWeb(
189 request,
190 new Response(null, {
191 headers: {
192 ...(options.contentLength === undefined
193 ? {}
194 : { "content-length": String(options.contentLength) }),
195 ...(options.contentEncoding === undefined
196 ? {}
197 : { "content-encoding": options.contentEncoding }),
198 },
199 }),
200 );
201 return Object.defineProperty(response, "stream", {
202 value:
203 options.body ??
204 Stream.make(
205 archive.subarray(0, 31),
206 archive.subarray(31, 149),
207 archive.subarray(149),
208 ),
209 });
210 }),
211 ),
212 ),
213 );
214 return { installation, fs, path, baseDir, requests, validations, stagingReleased };
215});
216
217const terminalState = (installation: AntigravityInstallation.AntigravityInstallation["Service"]) =>
218 installation.changes.pipe(
219 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
220 Stream.runHead,
221 Effect.map(Option.getOrThrow),
222 );
223
224const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease")(function* (
225 installation: AntigravityInstallation.AntigravityInstallation["Service"],
226) {
227 const fs = yield* FileSystem.FileSystem;
228 const path = yield* Path.Path;
229 const resolved = yield* installation.resolve();
230 expect(resolved.version).toBe(previousVersion);
231 expect(resolved.managedVersionDirectory).toBe(
232 path.join(installation.managedDirectory, "versions", previousReleaseId),
233 );
234 expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents);
235 expect(yield* fs.readFileString(resolved.harnessPath)).toBe(harnessContents);
236 expect((yield* installation.state).installedVersion).toBe(previousVersion);
237});
238
239it.layer(NodeServices.layer)("Antigravity installation", (it) => {
240 it.effect("reports missing Node before downloading the standalone provider runtime", () =>
241 Effect.gen(function* () {
242 const { installation, requests, validations } = yield* makeHarness();
243 yield* installation.start;
244 expect(yield* terminalState(installation)).toMatchObject({
245 phase: "failed",
246 message: expect.stringContaining("Install Node.js"),
247 });
248 expect(requests).toEqual([]);
249 expect(validations).toEqual([]);
250 }).pipe(Effect.provideService(HostProcess.IsExecutable, true)),
251 );
252
253 it.effect("verifies both files before activating a streamed download", () =>
254 Effect.gen(function* () {
255 const enteredValidation = yield* Deferred.make<void>();
256 const finishValidation = yield* Deferred.make<void>();
257 const { installation, fs, path, validations, requests, stagingReleased } = yield* makeHarness(
258 {
259 previous: true,
260 validate: () =>
261 Deferred.succeed(enteredValidation, undefined).pipe(
262 Effect.andThen(Deferred.await(finishValidation)),
263 ),
264 },
265 );
266 const initial = yield* installation.changes.pipe(
267 Stream.runHead,
268 Effect.map(Option.getOrThrow),
269 );
270 expect(initial).toMatchObject({ phase: "idle", installedVersion: previousVersion });
271 const started = yield* installation.start;
272 expect(started).toMatchObject({ phase: "downloading", downloadedBytes: 0 });
273 yield* Deferred.await(enteredValidation);
274 yield* expectPreviousRelease(installation);
275 const validation = validations[0];
276 expect(validation?.version).toBe("fixture-new");
277 if (!validation) return yield* Effect.die("Expected runtime validation.");
278 expect(yield* fs.readFileString(validation.executable.executablePath)).toBe(serverContents);
279 expect(yield* fs.readFileString(validation.executable.harnessPath)).toBe(harnessContents);
280
281 yield* Deferred.succeed(finishValidation, undefined);
282 expect(yield* terminalState(installation)).toMatchObject({
283 phase: "succeeded",
284 operationId: started.operationId,
285 downloadedBytes: completeArchive.byteLength,
286 installedVersion: "fixture-new",
287 });
288 yield* Deferred.await(stagingReleased);
289 const selected = yield* installation.resolve();
290 expect(selected).toMatchObject({ source: "managed", version: "fixture-new" });
291 expect(path.dirname(selected.harnessPath)).toBe(path.dirname(selected.executablePath));
292 expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents);
293 expect(yield* fs.readFileString(selected.harnessPath)).toBe(harnessContents);
294 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
295 expect.arrayContaining([previousReleaseId, (yield* releaseAsset()).sha256]),
296 );
297 expect(requests).toEqual([(yield* releaseAsset()).url]);
298 }),
299 );
300
301 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
302 Effect.gen(function* () {
303 // dl.google.com gzips the archive and reports the encoded size. The decoded
304 // stream is still checked byte for byte and by hash.
305 const { installation, validations } = yield* makeHarness({
306 contentLength: completeArchive.byteLength - 1_000,
307 contentEncoding: "gzip",
308 });
309 yield* installation.start;
310 const state = yield* terminalState(installation);
311 expect(state.phase).toBe("succeeded");
312 expect(validations).toHaveLength(1);
313 }),
314 );
315
316 it.effect.each([
317 { name: "checksum mismatch", completeAsset: { sha256: "2".repeat(64) } },
318 { name: "short download", archive: completeArchive.subarray(0, -1), completeAsset: {} },
319 {
320 name: "oversized download",
321 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
322 completeAsset: {},
323 },
324 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
325 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
326 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
327 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
328 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
329 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
330 ])("rejects $name before runtime validation", ({ completeAsset, ...options }) =>
331 Effect.gen(function* () {
332 const asset =
333 completeAsset === undefined ? undefined : { ...(yield* releaseAsset()), ...completeAsset };
334 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
335 ...options,
336 ...(asset === undefined ? {} : { asset }),
337 previous: true,
338 });
339 yield* installation.start;
340 const state = yield* terminalState(installation);
341 expect(state.phase).toBe("failed");
342 expect(state.message).toBeTruthy();
343 expect(validations).toEqual([]);
344 yield* Deferred.await(stagingReleased);
345 yield* expectPreviousRelease(installation);
346 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
347 [previousReleaseId],
348 );
349 }),
350 );
351
352 it.effect.each(["download", "extract", "active pointer"] as const)(
353 "preserves the old runtime after an ENOSPC error during %s",
354 (stage) =>
355 Effect.gen(function* () {
356 const fs = yield* FileSystem.FileSystem;
357 const noSpace = PlatformError.systemError({
358 _tag: "Unknown",
359 module: "FileSystem",
360 method: "write",
361 description: "ENOSPC: no space left on device",
362 });
363 const fileSystem = FileSystem.FileSystem.of({
364 ...fs,
365 sink: (target, options) =>
366 (stage === "download" && target.endsWith("download.zip")) ||
367 (stage === "extract" && target.endsWith(executableName))
368 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
369 : fs.sink(target, options),
370 writeFileString: (target, content, options) =>
371 stage === "active pointer" && target.endsWith("contents.tmp")
372 ? Effect.fail(noSpace)
373 : fs.writeFileString(target, content, options),
374 });
375 const { installation, stagingReleased, path } = yield* makeHarness({
376 previous: true,
377 fileSystem,
378 });
379 yield* installation.start;
380 expect((yield* terminalState(installation)).phase).toBe("failed");
381 yield* Deferred.await(stagingReleased);
382 yield* expectPreviousRelease(installation);
383 expect(
384 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
385 (name) => name.startsWith(".install-"),
386 ),
387 ).toBe(false);
388 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
389 "active.json",
390 "versions",
391 ]);
392 }),
393 );
394
395 it.effect.each(["downloading", "extracting", "verifying"] as const)(
396 "cancels during %s and waits for open resources to close",
397 (phase) =>
398 Effect.gen(function* () {
399 const fs = yield* FileSystem.FileSystem;
400 const entered = yield* Deferred.make<void>();
401 const release = yield* Deferred.make<void>();
402 const interrupted = yield* Deferred.make<void>();
403 const barrier = Deferred.succeed(entered, undefined).pipe(
404 Effect.andThen(Deferred.await(release)),
405 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
406 );
407 const { installation, stagingReleased, path, validations } = yield* makeHarness({
408 previous: true,
409 body:
410 phase === "downloading"
411 ? Stream.concat(
412 Stream.make(completeArchive.subarray(0, 31)),
413 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
414 )
415 : undefined,
416 validate: phase === "verifying" ? () => barrier : undefined,
417 fileSystem: FileSystem.FileSystem.of({
418 ...fs,
419 sink: (target, options) =>
420 phase === "extracting" && target.endsWith(executableName)
421 ? fs
422 .sink(target, options)
423 .pipe(
424 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
425 )
426 : fs.sink(target, options),
427 }),
428 });
429 const started = yield* installation.start;
430 yield* Deferred.await(entered);
431 expect((yield* installation.state).phase).toBe(phase);
432 expect(
433 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
434 ).toBe("cancelled");
435 yield* Deferred.await(interrupted);
436 yield* Deferred.await(stagingReleased);
437 yield* expectPreviousRelease(installation);
438 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
439 expect(
440 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
441 ).toEqual([previousReleaseId]);
442 }),
443 );
444
445 it.effect.each([
446 { name: "the committed install", restart: false },
447 { name: "a newer install", restart: true },
448 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
449 Effect.gen(function* () {
450 const fs = yield* FileSystem.FileSystem;
451 const cleanupStarted = yield* Deferred.make<void>();
452 const releaseCleanup = yield* Deferred.make<void>();
453 const nextValidationStarted = yield* Deferred.make<void>();
454 const releaseNextValidation = yield* Deferred.make<void>();
455 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
456 const cleanupError = PlatformError.systemError({
457 _tag: "PermissionDenied",
458 module: "FileSystem",
459 method: "remove",
460 description: "EPERM: pointer temp directory is in use",
461 });
462 let firstPointer = true;
463 let validationCount = 0;
464 const { installation, stagingReleased } = yield* makeHarness({
465 previous: true,
466 validate: () => {
467 validationCount += 1;
468 return validationCount === 2
469 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
470 Effect.andThen(Deferred.await(releaseNextValidation)),
471 )
472 : Effect.void;
473 },
474 fileSystem: FileSystem.FileSystem.of({
475 ...fs,
476 makeTempDirectoryScoped: (settings) => {
477 if (settings?.prefix !== "active.json." || !firstPointer) {
478 return fs.makeTempDirectoryScoped(settings);
479 }
480 firstPointer = false;
481 return Effect.fiber.pipe(
482 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
483 Effect.andThen(
484 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
485 Deferred.succeed(cleanupStarted, undefined).pipe(
486 Effect.andThen(Deferred.await(releaseCleanup)),
487 Effect.andThen(Effect.die(cleanupError)),
488 ),
489 ),
490 ),
491 );
492 },
493 }),
494 });
495 yield* Effect.gen(function* () {
496 const first = yield* installation.start;
497 yield* Deferred.await(cleanupStarted);
498 expect(yield* installation.state).toMatchObject({
499 operationId: first.operationId,
500 phase: "succeeded",
501 installedVersion: "fixture-new",
502 });
503 const current = testCase.restart ? yield* installation.start : first;
504 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
505
506 yield* Deferred.succeed(releaseCleanup, undefined);
507 yield* Fiber.await(yield* Deferred.await(firstWorker));
508 yield* Deferred.await(stagingReleased);
509 expect(yield* installation.state).toMatchObject({
510 operationId: current.operationId,
511 phase: testCase.restart ? "verifying" : "succeeded",
512 installedVersion: "fixture-new",
513 });
514 expect((yield* installation.resolve()).version).toBe("fixture-new");
515
516 yield* Deferred.succeed(releaseNextValidation, undefined);
517 expect(yield* terminalState(installation)).toMatchObject({
518 operationId: current.operationId,
519 phase: "succeeded",
520 installedVersion: "fixture-new",
521 });
522 }).pipe(
523 Effect.ensuring(
524 Deferred.succeed(releaseCleanup, undefined).pipe(
525 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
526 ),
527 ),
528 );
529 }),
530 );
531
532 it.effect(
533 "shares one install across callers and keeps it alive after the caller scope closes",
534 () =>
535 Effect.gen(function* () {
536 const entered = yield* Deferred.make<void>();
537 const release = yield* Deferred.make<void>();
538 const { installation, requests, stagingReleased } = yield* makeHarness({
539 body: Stream.fromEffect(
540 Deferred.succeed(entered, undefined).pipe(
541 Effect.andThen(Deferred.await(release)),
542 Effect.as(completeArchive),
543 ),
544 ),
545 });
546 const callerScope = yield* Scope.make();
547 const started = yield* installation.start.pipe(Scope.provide(callerScope));
548 yield* Deferred.await(entered);
549 yield* Scope.close(callerScope, Exit.void);
550 const concurrent = yield* Effect.all([installation.start, installation.start], {
551 concurrency: "unbounded",
552 });
553 expect(concurrent.map((state) => state.operationId)).toEqual([
554 started.operationId,
555 started.operationId,
556 ]);
557 expect(
558 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
559 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
560 yield* Deferred.succeed(release, undefined);
561 expect((yield* terminalState(installation)).phase).toBe("succeeded");
562 yield* Deferred.await(stagingReleased);
563
564 const next = yield* installation.start;
565 expect(next.operationId).not.toBe(started.operationId);
566 expect(
567 yield* installation
568 .cancel(started.operationId ?? "missing-operation-id")
569 .pipe(Effect.flip),
570 ).toMatchObject({ operation: "cancel" });
571 expect((yield* terminalState(installation)).phase).toBe("succeeded");
572 expect(requests).toHaveLength(1);
573 }),
574 );
575
576 // Real posix executables in a real temp dir, resolved by a linux-mocked
577 // PATH walk; a Windows temp path cannot be split on `:`.
578 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
579 "honors explicit paths and reports invalid overrides without falling back",
580 () =>
581 Effect.gen(function* () {
582 const fs = yield* FileSystem.FileSystem;
583 const path = yield* Path.Path;
584 const baseDir = yield* fs
585 .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" })
586 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
587 const externalDirectory = path.join(baseDir, "external");
588 const externalExecutable = path.join(externalDirectory, executableName);
589 const externalHarness = path.join(externalDirectory, harnessName);
590 yield* fs.makeDirectory(externalDirectory);
591 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
592 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
593 const { installation } = yield* makeHarness({
594 baseDir,
595 path: externalDirectory,
596 previous: true,
597 });
598 yield* expectPreviousRelease(installation);
599 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
600 source: "managed",
601 version: previousVersion,
602 });
603 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
604 executablePath: externalExecutable,
605 source: "override",
606 managedVersionDirectory: null,
607 });
608 expect(yield* installation.resolve(executableName)).toMatchObject({
609 source: "override",
610 });
611 yield* fs.remove(externalHarness);
612 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
613 operation: "resolve",
614 });
615 expect(
616 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
617 ).toMatchObject({
618 operation: "resolve",
619 });
620 yield* expectPreviousRelease(installation);
621 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
622 yield* installation.remove();
623 expect(yield* installation.resolve()).toMatchObject({
624 source: "path",
625 executablePath: externalExecutable,
626 });
627 const isolated = yield* makeHarness({ baseDir });
628 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
629 operation: "resolve",
630 });
631 expect(
632 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
633 ).toMatchObject({
634 source: "path",
635 executablePath: externalExecutable,
636 });
637 expect(
638 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
639 ).toMatchObject({ source: "override", executablePath: externalExecutable });
640 }),
641 );
642
643 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
644 Effect.gen(function* () {
645 const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true });
646 const processScope = yield* Scope.make();
647 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
648 yield* installation.start;
649 expect((yield* terminalState(installation)).phase).toBe("succeeded");
650 yield* Deferred.await(stagingReleased);
651 const current = yield* installation.resolve();
652 expect(current.version).toBe("fixture-new");
653 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
654 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
655 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
656 yield* Scope.close(processScope, Exit.void);
657 yield* installation.remove();
658 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
659 }),
660 );
661
662 it.effect(
663 "removes an incomplete active release before reinstalling without a PATH fallback",
664 () =>
665 Effect.gen(function* () {
666 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
667 const previous = yield* installation.resolve();
668 yield* fs.remove(previous.harnessPath);
669 const externalDirectory = path.join(baseDir, "external");
670 yield* fs.makeDirectory(externalDirectory);
671 yield* fs.writeFileString(path.join(externalDirectory, executableName), "external server", {
672 mode: 0o755,
673 });
674 yield* fs.writeFileString(path.join(externalDirectory, harnessName), "external harness", {
675 mode: 0o755,
676 });
677 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
678 expect(yield* restarted.installation.state).toMatchObject({
679 phase: "failed",
680 installedVersion: null,
681 canRemove: true,
682 });
683 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
684 operation: "resolve",
685 });
686 yield* restarted.installation.remove();
687 expect(yield* restarted.installation.state).toMatchObject({
688 phase: "idle",
689 canRemove: false,
690 });
691 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
692 yield* restarted.installation.start;
693 expect(yield* terminalState(restarted.installation)).toMatchObject({
694 phase: "succeeded",
695 installedVersion: "fixture-new",
696 canRemove: true,
697 });
698 yield* Deferred.await(restarted.stagingReleased);
699 expect((yield* restarted.installation.resolve()).source).toBe("managed");
700 }),
701 );
702
703 it.effect(
704 "blocks removal of custom managed paths and leaves external executables and profiles intact",
705 () =>
706 Effect.gen(function* () {
707 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
708 const managed = yield* installation.resolve();
709 const externalDirectory = path.join(baseDir, "external");
710 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
711 yield* fs.makeDirectory(externalDirectory);
712 yield* fs.makeDirectory(profileDirectory, { recursive: true });
713 const externalExecutable = path.join(externalDirectory, executableName);
714 const externalHarness = path.join(externalDirectory, harnessName);
715 const profilePath = path.join(profileDirectory, "preferences.json");
716 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
717 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
718 yield* fs.writeFileString(profilePath, "{}");
719 expect(
720 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
721 ).toMatchObject({
722 operation: "remove",
723 });
724 yield* expectPreviousRelease(installation);
725 yield* installation.remove([externalExecutable]);
726 expect(yield* installation.state).toMatchObject({
727 phase: "idle",
728 operationId: null,
729 installedVersion: null,
730 });
731 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
732 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
733 expect(yield* fs.readFileString(profilePath)).toBe("{}");
734 }),
735 );
736
737 it.effect(
738 "reuses an immutable Windows release and preserves the pointer when rename is denied",
739 () =>
740 Effect.gen(function* () {
741 const fs = yield* FileSystem.FileSystem;
742 const path = yield* Path.Path;
743 const archive = Buffer.from(zipFixtures.windows, "base64");
744 const asset = yield* releaseAsset(archive, "win32");
745 let denyPointerRename = true;
746 const renameTargets: string[] = [];
747 const { installation, requests, validations } = yield* makeHarness({
748 previous: true,
749 platform: "win32",
750 archive,
751 fileSystem: FileSystem.FileSystem.of({
752 ...fs,
753 rename: (source, target) => {
754 renameTargets.push(target);
755 return denyPointerRename
756 ? Effect.fail(
757 PlatformError.systemError({
758 _tag: "PermissionDenied",
759 module: "FileSystem",
760 method: "rename",
761 pathOrDescriptor: target,
762 description: "EPERM: file is in use",
763 }),
764 )
765 : fs.rename(source, target);
766 },
767 }),
768 });
769 yield* writeRelease(installation.managedDirectory, asset, false);
770 yield* installation.start;
771 expect((yield* terminalState(installation)).phase).toBe("failed");
772 yield* expectPreviousRelease(installation);
773 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
774
775 denyPointerRename = false;
776 yield* installation.start;
777 expect((yield* terminalState(installation)).phase).toBe("succeeded");
778 expect((yield* installation.resolve()).version).toBe("fixture-new");
779 expect(requests).toEqual([]);
780 expect(validations).toHaveLength(2);
781 expect(renameTargets).toEqual([
782 path.join(installation.managedDirectory, "active.json"),
783 path.join(installation.managedDirectory, "active.json"),
784 ]);
785 }),
786 );
787
788 it.effect("reports unsupported hosts without downloading or changing state", () =>
789 Effect.gen(function* () {
790 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
791 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
792 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
793 operation: "resolve",
794 });
795 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
796 expect(requests).toEqual([]);
797 }),
798 );
799});