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

AntigravityInstallation.test.ts

1,078 lines46.2 KB

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 Queue from "effect/Queue";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as Sink from "effect/Sink";
18import * as Stream from "effect/Stream";
19import * as TestClock from "effect/testing/TestClock";
20import { HttpClient, HttpClientResponse } from "effect/http";
21import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
22​
23import * as AntigravityInstallation from "./AntigravityInstallation.ts";
24import { ANTIGRAVITY_AUTH_BROWSER_MARKER } from "./antigravityAuthSupport.ts";
25import {
26 resolveAntigravityReleaseAsset,
27 type AntigravityReleaseAsset,
28} from "./antigravityRelease.ts";
29​
30import antigravityInitialize from "../../../../packages/effect-acp/test/fixtures/antigravity-initialize.json" with { type: "json" };
31​
32const serverContents = "antigravity runtime\n";
33const harnessContents = "local harness\n";
34const previousReleaseId = "1".repeat(64);
35const previousVersion = "fixture-old";
36const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
37​
38const zipFixtures = {
39 complete:
40 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAA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9yAykQAAAADgAAABkAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWwuZXhly8lPTsxRyEgsykstLuYCAFBLAQIUAxQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAAAAAAAAAAADtgQAAAABhZ3lfYWNwX3NlcnZlci5leGVQSwECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAGQAAAAAAAAAAAAAA7YFEAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsLmV4ZVBLBQYAAAAAAgACAIcAAACLAAAAAAA=",
53};
54​
55// The installation checks POSIX exec bits off the real filesystem unless the
56// platform is win32, so a linux platform mock cannot pass on NTFS. Default to
57// the host and let the fixture names follow; the suite is about install
58// mechanics, which are the same on every platform.
59const hostPlatform: NodeJS.Platform =
60 HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux";
61const completeArchive = Buffer.from(
62 hostPlatform === "win32" ? zipFixtures.windows : zipFixtures.complete,
63 "base64",
64);
65const executableName = hostPlatform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par";
66const harnessName =
67 hostPlatform === "win32" ? "localharness_external.exe" : "localharness_external";
68​
69const releaseAsset = Effect.fn("test.antigravityReleaseAsset")(function* (
70 archive: Uint8Array = completeArchive,
71 platform: NodeJS.Platform = hostPlatform,
72) {
73 const crypto = yield* Crypto.Crypto;
74 return {
75 version: "fixture-new",
76 url: "https://dl.google.com/antigravity-test.zip",
77 sha256: Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie)),
78 archiveBytes: archive.byteLength,
79 executable: {
80 name: platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par",
81 bytes: Buffer.byteLength(serverContents),
82 },
83 harness: {
84 name: platform === "win32" ? "localharness_external.exe" : "localharness_external",
85 bytes: Buffer.byteLength(harnessContents),
86 },
87 } satisfies AntigravityReleaseAsset;
88});
89​
90const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* (
91 managedDirectory: string,
92 asset: AntigravityReleaseAsset,
93 active = true,
94) {
95 const fs = yield* FileSystem.FileSystem;
96 const path = yield* Path.Path;
97 const directory = path.join(managedDirectory, "versions", asset.sha256);
98 yield* fs.makeDirectory(directory, { recursive: true });
99 yield* fs.writeFileString(path.join(directory, asset.executable.name), serverContents, {
100 mode: 0o755,
101 });
102 yield* fs.writeFileString(path.join(directory, asset.harness.name), harnessContents, {
103 mode: 0o755,
104 });
105 yield* fs.writeFileString(
106 path.join(directory, ".install-complete.json"),
107 encodeJsonString({
108 releaseId: asset.sha256,
109 version: asset.version,
110 executable: asset.executable,
111 harness: asset.harness,
112 }),
113 );
114 if (active) {
115 yield* fs.writeFileString(
116 path.join(managedDirectory, "active.json"),
117 encodeJsonString({ releaseId: asset.sha256 }),
118 );
119 }
120});
121​
122interface HarnessOptions {
123 readonly baseDir?: string;
124 readonly asset?: AntigravityReleaseAsset | null;
125 readonly archive?: Buffer;
126 readonly body?: Stream.Stream<Uint8Array> | undefined;
127 readonly contentLength?: number;
128 readonly contentEncoding?: string;
129 readonly platform?: NodeJS.Platform;
130 readonly arch?: NodeJS.Architecture;
131 readonly path?: string;
132 readonly previous?: boolean;
133 readonly fileSystem?: FileSystem.FileSystem;
134 readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"];
135 readonly useDefaultValidation?: boolean;
137​
138const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
139 options: HarnessOptions = {},
140) {
141 const fs = yield* FileSystem.FileSystem;
142 const path = yield* Path.Path;
143 const baseDir =
144 options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
145 const platform = options.platform ?? hostPlatform;
146 const arch = options.arch ?? "x64";
147 const archive = options.archive ?? completeArchive;
148 const asset =
149 options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset;
150 const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`);
151 if (options.previous) {
152 yield* writeRelease(managedDirectory, {
153 ...(yield* releaseAsset(archive, platform)),
154 sha256: previousReleaseId,
155 version: previousVersion,
156 });
157 }
158 const stagingReleased = yield* Deferred.make<void>();
159 const requests: string[] = [];
160 const validations: Array<{
161 executable: AntigravityInstallation.AntigravityExecutable;
162 version: string;
163 }> = [];
164 const installationFs = options.fileSystem ?? fs;
165 const trackedFs = FileSystem.FileSystem.of({
166 ...installationFs,
167 makeTempDirectoryScoped: (settings) =>
168 settings?.prefix === ".install-"
169 ? Effect.acquireRelease(installationFs.makeTempDirectory(settings), (directory) =>
170 fs
171 .remove(directory, { recursive: true, force: true })
172 .pipe(Effect.orDie, Effect.andThen(Deferred.succeed(stagingReleased, undefined))),
173 )
174 : installationFs.makeTempDirectoryScoped(settings),
175 });
176 const installation = yield* AntigravityInstallation.makeAntigravityInstallation({
177 baseDir,
178 releaseAsset: asset,
179 ...(options.useDefaultValidation
180 ? {}
181 : {
182 validate: (executable: AntigravityInstallation.AntigravityExecutable, version: string) =>
183 Effect.sync(() => validations.push({ executable, version })).pipe(
184 Effect.andThen(options.validate?.(executable, version) ?? Effect.void),
185 ),
186 }),
187 }).pipe(
188 Effect.provideService(FileSystem.FileSystem, trackedFs),
189 Effect.provideService(HostProcess.Platform, platform),
190 Effect.provideService(HostProcess.Architecture, arch),
191 Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }),
192 Effect.provideService(
193 HttpClient.HttpClient,
194 HttpClient.make((request) =>
195 Effect.sync(() => {
196 requests.push(request.url);
197 const response = HttpClientResponse.fromWeb(
198 request,
199 new Response(null, {
200 headers: {
201 ...(options.contentLength === undefined
202 ? {}
203 : { "content-length": String(options.contentLength) }),
204 ...(options.contentEncoding === undefined
205 ? {}
206 : { "content-encoding": options.contentEncoding }),
207 },
208 }),
209 );
210 return Object.defineProperty(response, "stream", {
211 value:
212 options.body ??
213 Stream.make(
214 archive.subarray(0, 31),
215 archive.subarray(31, 149),
216 archive.subarray(149),
217 ),
218 });
219 }),
220 ),
221 ),
222 );
223 return { installation, fs, path, baseDir, requests, validations, stagingReleased };
224});
225​
226const terminalState = (installation: AntigravityInstallation.AntigravityInstallation["Service"]) =>
227 installation.changes.pipe(
228 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
229 Stream.runHead,
230 Effect.map(Option.getOrThrow),
231 );
232​
233const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease")(function* (
234 installation: AntigravityInstallation.AntigravityInstallation["Service"],
235) {
236 const fs = yield* FileSystem.FileSystem;
237 const path = yield* Path.Path;
238 const resolved = yield* installation.resolve();
239 expect(resolved.version).toBe(previousVersion);
240 expect(resolved.managedVersionDirectory).toBe(
241 path.join(installation.managedDirectory, "versions", previousReleaseId),
242 );
243 expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents);
244 expect(yield* fs.readFileString(resolved.harnessPath)).toBe(harnessContents);
245 expect((yield* installation.state).installedVersion).toBe(previousVersion);
246});
247​
248it.layer(NodeServices.layer)("Antigravity installation", (it) => {
249 it.effect("reports missing Node before downloading the standalone provider runtime", () =>
250 Effect.gen(function* () {
251 const { installation, requests, validations } = yield* makeHarness();
252 yield* installation.start;
253 expect(yield* terminalState(installation)).toMatchObject({
254 phase: "failed",
255 message: expect.stringContaining("Install Node.js"),
256 });
257 expect(requests).toEqual([]);
258 expect(validations).toEqual([]);
259 }).pipe(Effect.provideService(HostProcess.IsExecutable, true)),
260 );
261​
262 it.effect("verifies both files before activating a streamed download", () =>
263 Effect.gen(function* () {
264 const enteredValidation = yield* Deferred.make<void>();
265 const finishValidation = yield* Deferred.make<void>();
266 const { installation, fs, path, validations, requests, stagingReleased } = yield* makeHarness(
267 {
268 previous: true,
269 validate: () =>
270 Deferred.succeed(enteredValidation, undefined).pipe(
271 Effect.andThen(Deferred.await(finishValidation)),
272 ),
273 },
274 );
275 const initial = yield* installation.changes.pipe(
276 Stream.runHead,
277 Effect.map(Option.getOrThrow),
278 );
279 expect(initial).toMatchObject({ phase: "idle", installedVersion: previousVersion });
280 const started = yield* installation.start;
281 expect(started).toMatchObject({ phase: "downloading", downloadedBytes: 0 });
282 yield* Deferred.await(enteredValidation);
283 yield* expectPreviousRelease(installation);
284 const validation = validations[0];
285 expect(validation?.version).toBe("fixture-new");
286 if (!validation) return yield* Effect.die("Expected runtime validation.");
287 expect(yield* fs.readFileString(validation.executable.executablePath)).toBe(serverContents);
288 expect(yield* fs.readFileString(validation.executable.harnessPath)).toBe(harnessContents);
289​
290 yield* Deferred.succeed(finishValidation, undefined);
291 expect(yield* terminalState(installation)).toMatchObject({
292 phase: "succeeded",
293 operationId: started.operationId,
294 downloadedBytes: completeArchive.byteLength,
295 installedVersion: "fixture-new",
296 });
297 yield* Deferred.await(stagingReleased);
298 const selected = yield* installation.resolve();
299 expect(selected).toMatchObject({ source: "managed", version: "fixture-new" });
300 expect(path.dirname(selected.harnessPath)).toBe(path.dirname(selected.executablePath));
301 expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents);
302 expect(yield* fs.readFileString(selected.harnessPath)).toBe(harnessContents);
303 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
304 expect.arrayContaining([previousReleaseId, (yield* releaseAsset()).sha256]),
305 );
306 expect(requests).toEqual([(yield* releaseAsset()).url]);
307 }),
308 );
309​
310 it.effect.each(
311 [
312 {
313 name: "the expected release with protocol 1",
314 protocolVersion: 1,
315 agentName: "antigravity-acp",
316 version: "fixture-new",
317 valid: true,
318 },
319 {
320 name: "the expected release with protocol 2 and legacy fields",
321 protocolVersion: 2,
322 agentName: "antigravity-acp",
323 version: "fixture-new",
324 valid: true,
325 },
326 {
327 name: "an unsupported protocol version",
328 protocolVersion: 3,
329 agentName: "antigravity-acp",
330 version: "fixture-new",
331 valid: false,
332 },
333 { name: "a different agent", agentName: "other-agent", version: "fixture-new", valid: false },
334 {
335 name: "a different version",
336 agentName: "antigravity-acp",
337 version: "other-version",
338 valid: false,
339 },
340 {
341 name: "the Windows ARM release with locked child processes",
342 platform: "win32" as const,
343 arch: "arm64" as const,
344 agentName: "antigravity-acp",
345 version: "fixture-new",
346 valid: true,
347 },
348 {
349 name: "an invalid Windows ARM release with locked child processes",
350 platform: "win32" as const,
351 arch: "arm64" as const,
352 agentName: "antigravity-acp",
353 version: "other-version",
354 valid: false,
355 },
356 {
357 name: "a cancelled Windows ARM verification with locked child processes",
358 platform: "win32" as const,
359 arch: "arm64" as const,
360 agentName: "antigravity-acp",
361 version: "fixture-new",
362 cancel: true,
363 valid: false,
364 },
365 ].flatMap((testCase) => {
366 const cleanupErrorTags =
367 testCase.platform === "win32"
368 ? (["Unknown", "PermissionDenied", "Busy"] as const)
369 : (["Unknown"] as const);
370 return cleanupErrorTags.map((cleanupErrorTag) => ({
371 ...testCase,
372 cleanupErrorTag,
373 name: `${cleanupErrorTag}: ${testCase.name}`,
374 }));
375 }),
376 )("validates $name with initialize only and removes the disposable profile", (testCase) =>
377 Effect.gen(function* () {
378 const fs = yield* FileSystem.FileSystem;
379 const platform = testCase.platform ?? hostPlatform;
380 const encoder = new TextEncoder();
381 const decodeRequest = Schema.decodeUnknownEffect(
382 Schema.fromJsonString(
383 Schema.Struct({
384 id: Schema.Union([Schema.String, Schema.Number]),
385 method: Schema.String,
386 }),
387 ),
388 );
389 const methods: string[] = [];
390 const profiles = new Set<string>();
391 const cleanupRetryStarted = yield* Deferred.make<void>();
392 const initializationStarted = yield* Deferred.make<void>();
393 let childProcessesRunning = false;
394 let profileRemovalAttempts = 0;
395 let closedRuntimes = 0;
396 const spawner = ChildProcessSpawner.make(
397 Effect.fn("test.spawnAntigravityValidator")(function* (command) {
398 if (command._tag !== "StandardCommand") {
399 return yield* Effect.die("Expected one validation process.");
400 }
401 const profile = command.options.env?.GEMINI_HOME;
402 if (!profile) return yield* Effect.die("Expected a disposable validation profile.");
403 profiles.add(profile);
404 const helper = command.args[0] === "-e";
405 if (!helper) childProcessesRunning = true;
406 if (!helper) {
407 if (platform === "win32") {
408 expect(command.options.env?.TEMP).toBe(profile);
409 expect(command.options.env?.TMP).toBe(profile);
410 } else {
411 expect(command.options.env?.TMPDIR).toBe(profile);
412 }
413 }
414 const output = yield* Queue.unbounded<Uint8Array>();
415 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
416 const terminate = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
417 Effect.asVoid,
418 );
419 yield* Effect.addFinalizer(() =>
420 terminate.pipe(
421 Effect.andThen(Queue.shutdown(output)),
422 Effect.andThen(
423 Effect.sync(() => {
424 if (!helper) closedRuntimes += 1;
425 }),
426 ),
427 ),
428 );
429 return ChildProcessSpawner.makeHandle({
430 pid: ChildProcessSpawner.ProcessId(helper ? 1 : 2),
431 exitCode: helper
432 ? Effect.succeed(ChildProcessSpawner.ExitCode(0))
433 : Deferred.await(exited),
434 isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
435 kill: () =>
436 Effect.sync(() => {
437 if (!helper) childProcessesRunning = false;
438 }).pipe(Effect.andThen(terminate)),
439 unref: Effect.succeed(Effect.void),
440 stdin: Sink.forEach((bytes: Uint8Array) =>
441 Effect.gen(function* () {
442 const request = yield* decodeRequest(new TextDecoder().decode(bytes)).pipe(
443 Effect.orDie,
444 );
445 methods.push(request.method);
446 if (testCase.cancel) {
447 yield* Deferred.succeed(initializationStarted, undefined);
448 return;
449 }
450 yield* Queue.offer(
451 output,
452 encoder.encode(
453 `${encodeJsonString({
454 jsonrpc: "2.0",
455 id: request.id,
456 ...(request.method === "initialize"
457 ? {
458 result: {
459 ...antigravityInitialize,
460 protocolVersion: testCase.protocolVersion ?? 2,
461 agentInfo: { name: testCase.agentName, version: testCase.version },
462 },
463 }
464 : {
465 error: {
466 code: -32601,
467 message: "Validation must not sign in or create sessions.",
468 },
469 }),
470 })}\n`,
471 ),
472 );
473 }),
474 ),
475 stdout: helper ? Stream.empty : Stream.fromQueue(output),
476 stderr: helper
477 ? Stream.make(
478 encoder.encode(
479 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeJsonString(command.args.at(-1))}\n`,
480 ),
481 )
482 : Stream.empty,
483 all: Stream.empty,
484 getInputFd: () => Sink.drain,
485 getOutputFd: () => Stream.empty,
486 });
487 }),
488 );
489 const { installation, stagingReleased } = yield* makeHarness({
490 previous: true,
491 useDefaultValidation: true,
492 platform,
493 ...(testCase.arch ? { arch: testCase.arch } : {}),
494 archive:
495 platform === "win32" ? Buffer.from(zipFixtures.windows, "base64") : completeArchive,
496 fileSystem: FileSystem.FileSystem.of({
497 ...fs,
498 remove: (target, options) =>
499 Effect.suspend(() => {
500 if (platform === "win32" && profiles.has(target)) {
501 profileRemovalAttempts += 1;
502 expect(childProcessesRunning).toBe(false);
503 // Even after the tree exits, Windows can briefly retain a DLL handle.
504 if (profileRemovalAttempts === 1) {
505 return Deferred.succeed(cleanupRetryStarted, undefined).pipe(
506 Effect.andThen(
507 Effect.fail(
508 PlatformError.systemError({
509 _tag: testCase.cleanupErrorTag,
510 module: "FileSystem",
511 method: "remove",
512 description: "Unpacked DLL is in use",
513 }),
514 ),
515 ),
516 );
517 }
518 }
519 return fs.remove(target, options);
520 }),
521 }),
522 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
523 const started = yield* installation.start;
524 const cancellation = testCase.cancel
525 ? yield* Deferred.await(initializationStarted).pipe(
526 Effect.andThen(installation.cancel(started.operationId!)),
527 Effect.forkChild,
528 )
529 : undefined;
530 if (platform === "win32") {
531 yield* Effect.raceFirst(
532 Deferred.await(cleanupRetryStarted).pipe(Effect.andThen(TestClock.adjust("100 millis"))),
533 terminalState(installation),
534 );
535 }
536 if (cancellation) yield* Fiber.join(cancellation);
537 expect((yield* terminalState(installation)).phase).toBe(
538 testCase.cancel ? "cancelled" : testCase.valid ? "succeeded" : "failed",
539 );
540 yield* Deferred.await(stagingReleased);
541 expect(methods).toEqual(["initialize"]);
542 expect(closedRuntimes).toBe(1);
543 expect(profiles.size).toBe(1);
544 if (platform === "win32") expect(profileRemovalAttempts).toBe(2);
545 for (const profile of profiles) {
546 expect(yield* fs.exists(profile)).toBe(false);
547 }
548 if (testCase.valid) {
549 expect((yield* installation.resolve()).version).toBe("fixture-new");
550 } else {
551 yield* expectPreviousRelease(installation);
552 }
553 }),
554 );
555​
556 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
557 Effect.gen(function* () {
558 // dl.google.com gzips the archive and reports the encoded size. The decoded
559 // stream is still checked byte for byte and by hash.
560 const { installation, validations } = yield* makeHarness({
561 contentLength: completeArchive.byteLength - 1_000,
562 contentEncoding: "gzip",
563 });
564 yield* installation.start;
565 const state = yield* terminalState(installation);
566 expect(state.phase).toBe("succeeded");
567 expect(validations).toHaveLength(1);
568 }),
569 );
570​
571 it.effect.each([
572 { name: "checksum mismatch", completeAsset: { sha256: "2".repeat(64) } },
573 { name: "short download", archive: completeArchive.subarray(0, -1), completeAsset: {} },
574 {
575 name: "oversized download",
576 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
577 completeAsset: {},
578 },
579 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
580 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
581 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
582 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
583 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
584 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
585 ])("rejects $name before runtime validation", ({ completeAsset, ...options }) =>
586 Effect.gen(function* () {
587 const asset =
588 completeAsset === undefined ? undefined : { ...(yield* releaseAsset()), ...completeAsset };
589 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
590 ...options,
591 ...(asset === undefined ? {} : { asset }),
592 previous: true,
593 });
594 yield* installation.start;
595 const state = yield* terminalState(installation);
596 expect(state.phase).toBe("failed");
597 expect(state.message).toBeTruthy();
598 expect(validations).toEqual([]);
599 yield* Deferred.await(stagingReleased);
600 yield* expectPreviousRelease(installation);
601 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
602 [previousReleaseId],
603 );
604 }),
605 );
606​
607 it.effect.each(["download", "extract", "active pointer"] as const)(
608 "preserves the old runtime after an ENOSPC error during %s",
609 (stage) =>
610 Effect.gen(function* () {
611 const fs = yield* FileSystem.FileSystem;
612 const noSpace = PlatformError.systemError({
613 _tag: "Unknown",
614 module: "FileSystem",
615 method: "write",
616 description: "ENOSPC: no space left on device",
617 });
618 const fileSystem = FileSystem.FileSystem.of({
619 ...fs,
620 sink: (target, options) =>
621 (stage === "download" && target.endsWith("download.zip")) ||
622 (stage === "extract" && target.endsWith(executableName))
623 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
624 : fs.sink(target, options),
625 writeFileString: (target, content, options) =>
626 stage === "active pointer" && target.endsWith("contents.tmp")
627 ? Effect.fail(noSpace)
628 : fs.writeFileString(target, content, options),
629 });
630 const { installation, stagingReleased, path } = yield* makeHarness({
631 previous: true,
632 fileSystem,
633 });
634 yield* installation.start;
635 expect((yield* terminalState(installation)).phase).toBe("failed");
636 yield* Deferred.await(stagingReleased);
637 yield* expectPreviousRelease(installation);
638 expect(
639 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
640 (name) => name.startsWith(".install-"),
641 ),
642 ).toBe(false);
643 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
644 "active.json",
645 "versions",
646 ]);
647 }),
648 );
649​
650 it.effect.each(["downloading", "extracting", "verifying"] as const)(
651 "cancels during %s and waits for open resources to close",
652 (phase) =>
653 Effect.gen(function* () {
654 const fs = yield* FileSystem.FileSystem;
655 const entered = yield* Deferred.make<void>();
656 const release = yield* Deferred.make<void>();
657 const interrupted = yield* Deferred.make<void>();
658 const barrier = Deferred.succeed(entered, undefined).pipe(
659 Effect.andThen(Deferred.await(release)),
660 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
661 );
662 const { installation, stagingReleased, path, validations } = yield* makeHarness({
663 previous: true,
664 body:
665 phase === "downloading"
666 ? Stream.concat(
667 Stream.make(completeArchive.subarray(0, 31)),
668 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
669 )
670 : undefined,
671 validate: phase === "verifying" ? () => barrier : undefined,
672 fileSystem: FileSystem.FileSystem.of({
673 ...fs,
674 sink: (target, options) =>
675 phase === "extracting" && target.endsWith(executableName)
676 ? fs
677 .sink(target, options)
678 .pipe(
679 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
680 )
681 : fs.sink(target, options),
682 }),
683 });
684 const started = yield* installation.start;
685 yield* Deferred.await(entered);
686 expect((yield* installation.state).phase).toBe(phase);
687 expect(
688 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
689 ).toBe("cancelled");
690 yield* Deferred.await(interrupted);
691 yield* Deferred.await(stagingReleased);
692 yield* expectPreviousRelease(installation);
693 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
694 expect(
695 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
696 ).toEqual([previousReleaseId]);
697 }),
698 );
699​
700 it.effect.each([
701 { name: "the committed install", restart: false },
702 { name: "a newer install", restart: true },
703 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
704 Effect.gen(function* () {
705 const fs = yield* FileSystem.FileSystem;
706 const cleanupStarted = yield* Deferred.make<void>();
707 const releaseCleanup = yield* Deferred.make<void>();
708 const nextValidationStarted = yield* Deferred.make<void>();
709 const releaseNextValidation = yield* Deferred.make<void>();
710 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
711 const cleanupError = PlatformError.systemError({
712 _tag: "PermissionDenied",
713 module: "FileSystem",
714 method: "remove",
715 description: "EPERM: pointer temp directory is in use",
716 });
717 let firstPointer = true;
718 let validationCount = 0;
719 const { installation, stagingReleased } = yield* makeHarness({
720 previous: true,
721 validate: () => {
722 validationCount += 1;
723 return validationCount === 2
724 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
725 Effect.andThen(Deferred.await(releaseNextValidation)),
726 )
727 : Effect.void;
728 },
729 fileSystem: FileSystem.FileSystem.of({
730 ...fs,
731 makeTempDirectoryScoped: (settings) => {
732 if (settings?.prefix !== "active.json." || !firstPointer) {
733 return fs.makeTempDirectoryScoped(settings);
734 }
735 firstPointer = false;
736 return Effect.fiber.pipe(
737 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
738 Effect.andThen(
739 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
740 Deferred.succeed(cleanupStarted, undefined).pipe(
741 Effect.andThen(Deferred.await(releaseCleanup)),
742 Effect.andThen(Effect.die(cleanupError)),
743 ),
744 ),
745 ),
746 );
747 },
748 }),
749 });
750 yield* Effect.gen(function* () {
751 const first = yield* installation.start;
752 yield* Deferred.await(cleanupStarted);
753 expect(yield* installation.state).toMatchObject({
754 operationId: first.operationId,
755 phase: "succeeded",
756 installedVersion: "fixture-new",
757 });
758 const current = testCase.restart ? yield* installation.start : first;
759 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
760​
761 yield* Deferred.succeed(releaseCleanup, undefined);
762 yield* Fiber.await(yield* Deferred.await(firstWorker));
763 yield* Deferred.await(stagingReleased);
764 expect(yield* installation.state).toMatchObject({
765 operationId: current.operationId,
766 phase: testCase.restart ? "verifying" : "succeeded",
767 installedVersion: "fixture-new",
768 });
769 expect((yield* installation.resolve()).version).toBe("fixture-new");
770​
771 yield* Deferred.succeed(releaseNextValidation, undefined);
772 expect(yield* terminalState(installation)).toMatchObject({
773 operationId: current.operationId,
774 phase: "succeeded",
775 installedVersion: "fixture-new",
776 });
777 }).pipe(
778 Effect.ensuring(
779 Deferred.succeed(releaseCleanup, undefined).pipe(
780 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
781 ),
782 ),
783 );
784 }),
785 );
786​
787 it.effect(
788 "shares one install across callers and keeps it alive after the caller scope closes",
789 () =>
790 Effect.gen(function* () {
791 const entered = yield* Deferred.make<void>();
792 const release = yield* Deferred.make<void>();
793 const { installation, requests, stagingReleased } = yield* makeHarness({
794 body: Stream.fromEffect(
795 Deferred.succeed(entered, undefined).pipe(
796 Effect.andThen(Deferred.await(release)),
797 Effect.as(completeArchive),
798 ),
799 ),
800 });
801 const callerScope = yield* Scope.make();
802 const started = yield* installation.start.pipe(Scope.provide(callerScope));
803 yield* Deferred.await(entered);
804 yield* Scope.close(callerScope, Exit.void);
805 const concurrent = yield* Effect.all([installation.start, installation.start], {
806 concurrency: "unbounded",
807 });
808 expect(concurrent.map((state) => state.operationId)).toEqual([
809 started.operationId,
810 started.operationId,
811 ]);
812 expect(
813 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
814 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
815 yield* Deferred.succeed(release, undefined);
816 expect((yield* terminalState(installation)).phase).toBe("succeeded");
817 yield* Deferred.await(stagingReleased);
818​
819 const next = yield* installation.start;
820 expect(next.operationId).not.toBe(started.operationId);
821 expect(
822 yield* installation
823 .cancel(started.operationId ?? "missing-operation-id")
824 .pipe(Effect.flip),
825 ).toMatchObject({ operation: "cancel" });
826 expect((yield* terminalState(installation)).phase).toBe("succeeded");
827 expect(requests).toHaveLength(1);
828 }),
829 );
830​
831 // Real posix executables in a real temp dir, resolved by a linux-mocked
832 // PATH walk; a Windows temp path cannot be split on `:`.
833 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
834 "honors explicit paths and reports invalid overrides without falling back",
835 () =>
836 Effect.gen(function* () {
837 const fs = yield* FileSystem.FileSystem;
838 const path = yield* Path.Path;
839 const baseDir = yield* fs
840 .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" })
841 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
842 const externalDirectory = path.join(baseDir, "external");
843 const externalExecutable = path.join(externalDirectory, executableName);
844 const externalHarness = path.join(externalDirectory, harnessName);
845 yield* fs.makeDirectory(externalDirectory);
846 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
847 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
848 const { installation } = yield* makeHarness({
849 baseDir,
850 path: externalDirectory,
851 previous: true,
852 });
853 yield* expectPreviousRelease(installation);
854 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
855 source: "managed",
856 version: previousVersion,
857 });
858 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
859 executablePath: externalExecutable,
860 source: "override",
861 managedVersionDirectory: null,
862 });
863 expect(yield* installation.resolve(executableName)).toMatchObject({
864 source: "override",
865 });
866 yield* fs.remove(externalHarness);
867 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
868 operation: "resolve",
869 });
870 expect(
871 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
872 ).toMatchObject({
873 operation: "resolve",
874 });
875 yield* expectPreviousRelease(installation);
876 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
877 yield* installation.remove();
878 expect(yield* installation.resolve()).toMatchObject({
879 source: "path",
880 executablePath: externalExecutable,
881 });
882 const isolated = yield* makeHarness({ baseDir });
883 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
884 operation: "resolve",
885 });
886 expect(
887 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
888 ).toMatchObject({
889 source: "path",
890 executablePath: externalExecutable,
891 });
892 expect(
893 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
894 ).toMatchObject({ source: "override", executablePath: externalExecutable });
895 }),
896 );
897​
898 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
899 Effect.gen(function* () {
900 const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true });
901 const processScope = yield* Scope.make();
902 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
903 yield* installation.start;
904 expect((yield* terminalState(installation)).phase).toBe("succeeded");
905 yield* Deferred.await(stagingReleased);
906 const current = yield* installation.resolve();
907 expect(current.version).toBe("fixture-new");
908 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
909 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
910 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
911 yield* Scope.close(processScope, Exit.void);
912 yield* installation.remove();
913 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
914 }),
915 );
916​
917 it.effect(
918 "removes an incomplete active release before reinstalling without a PATH fallback",
919 () =>
920 Effect.gen(function* () {
921 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
922 const previous = yield* installation.resolve();
923 yield* fs.remove(previous.harnessPath);
924 const externalDirectory = path.join(baseDir, "external");
925 yield* fs.makeDirectory(externalDirectory);
926 yield* fs.writeFileString(path.join(externalDirectory, executableName), "external server", {
927 mode: 0o755,
928 });
929 yield* fs.writeFileString(path.join(externalDirectory, harnessName), "external harness", {
930 mode: 0o755,
931 });
932 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
933 expect(yield* restarted.installation.state).toMatchObject({
934 phase: "failed",
935 installedVersion: null,
936 canRemove: true,
937 });
938 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
939 operation: "resolve",
940 });
941 yield* restarted.installation.remove();
942 expect(yield* restarted.installation.state).toMatchObject({
943 phase: "idle",
944 canRemove: false,
945 });
946 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
947 yield* restarted.installation.start;
948 expect(yield* terminalState(restarted.installation)).toMatchObject({
949 phase: "succeeded",
950 installedVersion: "fixture-new",
951 canRemove: true,
952 });
953 yield* Deferred.await(restarted.stagingReleased);
954 expect((yield* restarted.installation.resolve()).source).toBe("managed");
955 }),
956 );
957​
958 it.effect(
959 "blocks removal of custom managed paths and leaves external executables and profiles intact",
960 () =>
961 Effect.gen(function* () {
962 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
963 const managed = yield* installation.resolve();
964 const externalDirectory = path.join(baseDir, "external");
965 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
966 yield* fs.makeDirectory(externalDirectory);
967 yield* fs.makeDirectory(profileDirectory, { recursive: true });
968 const externalExecutable = path.join(externalDirectory, executableName);
969 const externalHarness = path.join(externalDirectory, harnessName);
970 const profilePath = path.join(profileDirectory, "preferences.json");
971 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
972 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
973 yield* fs.writeFileString(profilePath, "{}");
974 expect(
975 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
976 ).toMatchObject({
977 operation: "remove",
978 });
979 yield* expectPreviousRelease(installation);
980 yield* installation.remove([externalExecutable]);
981 expect(yield* installation.state).toMatchObject({
982 phase: "idle",
983 operationId: null,
984 installedVersion: null,
985 });
986 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
987 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
988 expect(yield* fs.readFileString(profilePath)).toBe("{}");
989 }),
990 );
991​
992 it.effect(
993 "reuses an immutable Windows release and preserves the pointer when rename is denied",
994 () =>
995 Effect.gen(function* () {
996 const fs = yield* FileSystem.FileSystem;
997 const path = yield* Path.Path;
998 const archive = Buffer.from(zipFixtures.windows, "base64");
999 const asset = yield* releaseAsset(archive, "win32");
1000 let denyPointerRename = true;
1001 const renameTargets: string[] = [];
1002 const { installation, requests, validations } = yield* makeHarness({
1003 previous: true,
1004 platform: "win32",
1005 archive,
1006 fileSystem: FileSystem.FileSystem.of({
1007 ...fs,
1008 rename: (source, target) => {
1009 renameTargets.push(target);
1010 return denyPointerRename
1011 ? Effect.fail(
1012 PlatformError.systemError({
1013 _tag: "PermissionDenied",
1014 module: "FileSystem",
1015 method: "rename",
1016 pathOrDescriptor: target,
1017 description: "EPERM: file is in use",
1018 }),
1020 : fs.rename(source, target);
1021 },
1022 }),
1023 });
1024 yield* writeRelease(installation.managedDirectory, asset, false);
1025 yield* installation.start;
1026 expect((yield* terminalState(installation)).phase).toBe("failed");
1027 yield* expectPreviousRelease(installation);
1028 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
1029​
1030 denyPointerRename = false;
1031 yield* installation.start;
1032 expect((yield* terminalState(installation)).phase).toBe("succeeded");
1033 expect((yield* installation.resolve()).version).toBe("fixture-new");
1034 expect(requests).toEqual([]);
1035 expect(validations).toHaveLength(2);
1036 expect(renameTargets).toEqual([
1037 path.join(installation.managedDirectory, "active.json"),
1038 path.join(installation.managedDirectory, "active.json"),
1039 ]);
1040 }),
1041 );
1042​
1043 it.effect("reports unsupported hosts without downloading or changing state", () =>
1044 Effect.gen(function* () {
1045 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
1046 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
1047 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
1048 operation: "resolve",
1049 });
1050 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
1051 expect(requests).toEqual([]);
1052 }),
1053 );
1054​
1055 it("resolves all supported platform release assets including Intel Mac", () => {
1056 const supportedPlatforms: Array<{ readonly platform: NodeJS.Platform; readonly arch: string }> =
1058 { platform: "darwin", arch: "arm64" },
1059 { platform: "darwin", arch: "x64" },
1060 { platform: "linux", arch: "x64" },
1061 { platform: "linux", arch: "arm64" },
1062 { platform: "win32", arch: "x64" },
1063 { platform: "win32", arch: "arm64" },
1064 ];
1065​
1066 for (const { platform, arch } of supportedPlatforms) {
1067 const asset = resolveAntigravityReleaseAsset(platform, arch);
1068 expect(asset).not.toBeNull();
1069 expect(asset?.version).toBe("1.3.0");
1070 expect(asset?.url).toContain("1.3.0");
1071 expect(asset?.archiveBytes).toBeGreaterThan(0);
1072 expect(asset?.executable.bytes).toBeGreaterThan(0);
1073 expect(asset?.harness.bytes).toBeGreaterThan(0);
1075​
1076 expect(resolveAntigravityReleaseAsset("freebsd", "x64")).toBeNull();
1077 });
1078});