Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import {
4 HostProcessArchitecture,
5 HostProcessEnvironment,
6 HostProcessIsExecutable,
7 HostProcessPlatform,
8} from "@t3tools/shared/hostProcess";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Fiber from "effect/Fiber";
13import * as FileSystem from "effect/FileSystem";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as PlatformError from "effect/PlatformError";
17import * as Queue from "effect/Queue";
18import * as Schema from "effect/Schema";
19import * as Scope from "effect/Scope";
20import * as Sink from "effect/Sink";
21import * as Stream from "effect/Stream";
22import { HttpClient, HttpClientResponse } from "effect/http";
23import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
24import * as NodeCrypto from "node:crypto";
25
26import * as AntigravityInstallation from "./AntigravityInstallation.ts";
27import { ANTIGRAVITY_AUTH_BROWSER_MARKER } from "./antigravityAuthSupport.ts";
28import {
29 resolveAntigravityReleaseAsset,
30 type AntigravityReleaseAsset,
31} from "./antigravityRelease.ts";
32
33import antigravityInitialize from "../../../../packages/effect-acp/test/fixtures/antigravity-initialize.json" with { type: "json" };
34
35const serverContents = "antigravity runtime\n";
36const harnessContents = "local harness\n";
37const previousReleaseId = "1".repeat(64);
38const previousVersion = "fixture-old";
39const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
40
41// Small ZIPs made with Python's zipfile module. The unsafe entries are intentional.
42const zipFixtures = {
43 complete:
44 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAAAFAAAABIAAAAAAAAA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ABsb2NhbGhhcm5lc3NfZXh0ZXJuYWwuZXhly8lPTsxRyEgsykstLuYCAFBLAQIUAxQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAAAAAAAAAAADtgQAAAABhZ3lfYWNwX3NlcnZlci5leGVQSwECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAGQAAAAAAAAAAAAAA7YFEAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsLmV4ZVBLBQYAAAAAAgACAIcAAACLAAAAAAA=",
57};
58
59// The installation checks POSIX exec bits off the real filesystem unless the
60// platform is win32, so a linux platform mock cannot pass on NTFS. Default to
61// the host and let the fixture names follow; the suite is about install
62// mechanics, which are the same on every platform.
63const hostPlatform: NodeJS.Platform =
64 HostProcessPlatform.defaultValue() === "win32" ? "win32" : "linux";
65const completeArchive = Buffer.from(
66 hostPlatform === "win32" ? zipFixtures.windows : zipFixtures.complete,
67 "base64",
68);
69const executableName = hostPlatform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par";
70const harnessName =
71 hostPlatform === "win32" ? "localharness_external.exe" : "localharness_external";
72
73function releaseAsset(
74 archive: Uint8Array = completeArchive,
75 platform: NodeJS.Platform = hostPlatform,
76) {
77 return {
78 version: "fixture-new",
79 url: "https://dl.google.com/antigravity-test.zip",
80 sha256: NodeCrypto.createHash("sha256").update(archive).digest("hex"),
81 archiveBytes: archive.byteLength,
82 executable: {
83 name: platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par",
84 bytes: Buffer.byteLength(serverContents),
85 },
86 harness: {
87 name: platform === "win32" ? "localharness_external.exe" : "localharness_external",
88 bytes: Buffer.byteLength(harnessContents),
89 },
90 } satisfies AntigravityReleaseAsset;
91}
92
93const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* (
94 managedDirectory: string,
95 asset: AntigravityReleaseAsset,
96 active = true,
97) {
98 const fs = yield* FileSystem.FileSystem;
99 const path = yield* Path.Path;
100 const directory = path.join(managedDirectory, "versions", asset.sha256);
101 yield* fs.makeDirectory(directory, { recursive: true });
102 yield* fs.writeFileString(path.join(directory, asset.executable.name), serverContents, {
103 mode: 0o755,
104 });
105 yield* fs.writeFileString(path.join(directory, asset.harness.name), harnessContents, {
106 mode: 0o755,
107 });
108 yield* fs.writeFileString(
109 path.join(directory, ".install-complete.json"),
110 encodeJsonString({
111 releaseId: asset.sha256,
112 version: asset.version,
113 executable: asset.executable,
114 harness: asset.harness,
115 }),
116 );
117 if (active) {
118 yield* fs.writeFileString(
119 path.join(managedDirectory, "active.json"),
120 encodeJsonString({ releaseId: asset.sha256 }),
121 );
122 }
123});
124
125interface HarnessOptions {
126 readonly baseDir?: string;
127 readonly asset?: AntigravityReleaseAsset | null;
128 readonly archive?: Buffer;
129 readonly body?: Stream.Stream<Uint8Array> | undefined;
130 readonly contentLength?: number;
131 readonly contentEncoding?: string;
132 readonly platform?: NodeJS.Platform;
133 readonly path?: string;
134 readonly previous?: boolean;
135 readonly fileSystem?: FileSystem.FileSystem;
136 readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"];
137 readonly useDefaultValidation?: boolean;
138}
139
140const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
141 options: HarnessOptions = {},
142) {
143 const fs = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 const baseDir =
146 options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
147 const platform = options.platform ?? hostPlatform;
148 const archive = options.archive ?? completeArchive;
149 const asset = options.asset === undefined ? releaseAsset(archive, platform) : options.asset;
150 const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-x64`);
151 if (options.previous) {
152 yield* writeRelease(managedDirectory, {
153 ...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(HostProcessPlatform, platform),
190 Effect.provideService(HostProcessArchitecture, "x64"),
191 Effect.provideService(HostProcessEnvironment, { 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(HostProcessIsExecutable, 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, releaseAsset().sha256]),
305 );
306 expect(requests).toEqual([releaseAsset().url]);
307 }),
308 );
309
310 it.effect.each([
311 {
312 name: "the expected release with protocol 1",
313 protocolVersion: 1,
314 agentName: "antigravity-acp",
315 version: "fixture-new",
316 valid: true,
317 },
318 {
319 name: "the expected release with protocol 2 and legacy fields",
320 protocolVersion: 2,
321 agentName: "antigravity-acp",
322 version: "fixture-new",
323 valid: true,
324 },
325 {
326 name: "an unsupported protocol version",
327 protocolVersion: 3,
328 agentName: "antigravity-acp",
329 version: "fixture-new",
330 valid: false,
331 },
332 { name: "a different agent", agentName: "other-agent", version: "fixture-new", valid: false },
333 {
334 name: "a different version",
335 agentName: "antigravity-acp",
336 version: "other-version",
337 valid: false,
338 },
339 ])("validates $name with initialize only and removes the disposable profile", (testCase) =>
340 Effect.gen(function* () {
341 const fs = yield* FileSystem.FileSystem;
342 const encoder = new TextEncoder();
343 const decodeRequest = Schema.decodeUnknownEffect(
344 Schema.fromJsonString(
345 Schema.Struct({
346 id: Schema.Union([Schema.String, Schema.Number]),
347 method: Schema.String,
348 }),
349 ),
350 );
351 const methods: string[] = [];
352 const profiles = new Set<string>();
353 let closedRuntimes = 0;
354 const spawner = ChildProcessSpawner.make(
355 Effect.fn("test.spawnAntigravityValidator")(function* (command) {
356 if (command._tag !== "StandardCommand") {
357 return yield* Effect.die("Expected one validation process.");
358 }
359 const profile = command.options.env?.GEMINI_HOME;
360 if (!profile) return yield* Effect.die("Expected a disposable validation profile.");
361 profiles.add(profile);
362 const helper = command.args[0] === "-e";
363 // The runtime unpacks straight into the disposable profile.
364 if (!helper) expect(command.options.env?.TMPDIR).toBe(profile);
365 const output = yield* Queue.unbounded<Uint8Array>();
366 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
367 const terminate = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
368 Effect.asVoid,
369 );
370 yield* Effect.addFinalizer(() =>
371 terminate.pipe(
372 Effect.andThen(Queue.shutdown(output)),
373 Effect.andThen(
374 Effect.sync(() => {
375 if (!helper) closedRuntimes += 1;
376 }),
377 ),
378 ),
379 );
380 return ChildProcessSpawner.makeHandle({
381 pid: ChildProcessSpawner.ProcessId(helper ? 1 : 2),
382 exitCode: helper
383 ? Effect.succeed(ChildProcessSpawner.ExitCode(0))
384 : Deferred.await(exited),
385 isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
386 kill: () => terminate,
387 unref: Effect.succeed(Effect.void),
388 stdin: Sink.forEach((bytes: Uint8Array) =>
389 Effect.gen(function* () {
390 const request = yield* decodeRequest(new TextDecoder().decode(bytes)).pipe(
391 Effect.orDie,
392 );
393 methods.push(request.method);
394 yield* Queue.offer(
395 output,
396 encoder.encode(
397 `${encodeJsonString({
398 jsonrpc: "2.0",
399 id: request.id,
400 ...(request.method === "initialize"
401 ? {
402 result: {
403 ...antigravityInitialize,
404 protocolVersion: testCase.protocolVersion ?? 2,
405 agentInfo: { name: testCase.agentName, version: testCase.version },
406 },
407 }
408 : {
409 error: {
410 code: -32601,
411 message: "Validation must not sign in or create sessions.",
412 },
413 }),
414 })}\n`,
415 ),
416 );
417 }),
418 ),
419 stdout: helper ? Stream.empty : Stream.fromQueue(output),
420 stderr: helper
421 ? Stream.make(
422 encoder.encode(
423 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeJsonString(command.args.at(-1))}\n`,
424 ),
425 )
426 : Stream.empty,
427 all: Stream.empty,
428 getInputFd: () => Sink.drain,
429 getOutputFd: () => Stream.empty,
430 });
431 }),
432 );
433 const { installation, stagingReleased } = yield* makeHarness({
434 previous: true,
435 useDefaultValidation: true,
436 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
437 yield* installation.start;
438 expect((yield* terminalState(installation)).phase).toBe(
439 testCase.valid ? "succeeded" : "failed",
440 );
441 yield* Deferred.await(stagingReleased);
442 expect(methods).toEqual(["initialize"]);
443 expect(closedRuntimes).toBe(1);
444 expect(profiles.size).toBe(1);
445 for (const profile of profiles) {
446 expect(yield* fs.exists(profile)).toBe(false);
447 }
448 if (testCase.valid) {
449 expect((yield* installation.resolve()).version).toBe("fixture-new");
450 } else {
451 yield* expectPreviousRelease(installation);
452 }
453 }),
454 );
455
456 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
457 Effect.gen(function* () {
458 // dl.google.com gzips the archive and reports the encoded size. The decoded
459 // stream is still checked byte for byte and by hash.
460 const { installation, validations } = yield* makeHarness({
461 contentLength: completeArchive.byteLength - 1_000,
462 contentEncoding: "gzip",
463 });
464 yield* installation.start;
465 const state = yield* terminalState(installation);
466 expect(state.phase).toBe("succeeded");
467 expect(validations).toHaveLength(1);
468 }),
469 );
470
471 it.effect.each([
472 { name: "checksum mismatch", asset: { ...releaseAsset(), sha256: "2".repeat(64) } },
473 { name: "short download", archive: completeArchive.subarray(0, -1), asset: releaseAsset() },
474 {
475 name: "oversized download",
476 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
477 asset: releaseAsset(),
478 },
479 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
480 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
481 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
482 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
483 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
484 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
485 ])("rejects $name before runtime validation", (options) =>
486 Effect.gen(function* () {
487 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
488 ...options,
489 previous: true,
490 });
491 yield* installation.start;
492 const state = yield* terminalState(installation);
493 expect(state.phase).toBe("failed");
494 expect(state.message).toBeTruthy();
495 expect(validations).toEqual([]);
496 yield* Deferred.await(stagingReleased);
497 yield* expectPreviousRelease(installation);
498 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
499 [previousReleaseId],
500 );
501 }),
502 );
503
504 it.effect.each(["download", "extract", "active pointer"] as const)(
505 "preserves the old runtime after an ENOSPC error during %s",
506 (stage) =>
507 Effect.gen(function* () {
508 const fs = yield* FileSystem.FileSystem;
509 const noSpace = PlatformError.systemError({
510 _tag: "Unknown",
511 module: "FileSystem",
512 method: "write",
513 description: "ENOSPC: no space left on device",
514 });
515 const fileSystem = FileSystem.FileSystem.of({
516 ...fs,
517 sink: (target, options) =>
518 (stage === "download" && target.endsWith("download.zip")) ||
519 (stage === "extract" && target.endsWith(executableName))
520 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
521 : fs.sink(target, options),
522 writeFileString: (target, content, options) =>
523 stage === "active pointer" && target.endsWith("contents.tmp")
524 ? Effect.fail(noSpace)
525 : fs.writeFileString(target, content, options),
526 });
527 const { installation, stagingReleased, path } = yield* makeHarness({
528 previous: true,
529 fileSystem,
530 });
531 yield* installation.start;
532 expect((yield* terminalState(installation)).phase).toBe("failed");
533 yield* Deferred.await(stagingReleased);
534 yield* expectPreviousRelease(installation);
535 expect(
536 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
537 (name) => name.startsWith(".install-"),
538 ),
539 ).toBe(false);
540 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
541 "active.json",
542 "versions",
543 ]);
544 }),
545 );
546
547 it.effect.each(["downloading", "extracting", "verifying"] as const)(
548 "cancels during %s and waits for open resources to close",
549 (phase) =>
550 Effect.gen(function* () {
551 const fs = yield* FileSystem.FileSystem;
552 const entered = yield* Deferred.make<void>();
553 const release = yield* Deferred.make<void>();
554 const interrupted = yield* Deferred.make<void>();
555 const barrier = Deferred.succeed(entered, undefined).pipe(
556 Effect.andThen(Deferred.await(release)),
557 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
558 );
559 const { installation, stagingReleased, path, validations } = yield* makeHarness({
560 previous: true,
561 body:
562 phase === "downloading"
563 ? Stream.concat(
564 Stream.make(completeArchive.subarray(0, 31)),
565 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
566 )
567 : undefined,
568 validate: phase === "verifying" ? () => barrier : undefined,
569 fileSystem: FileSystem.FileSystem.of({
570 ...fs,
571 sink: (target, options) =>
572 phase === "extracting" && target.endsWith(executableName)
573 ? fs
574 .sink(target, options)
575 .pipe(
576 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
577 )
578 : fs.sink(target, options),
579 }),
580 });
581 const started = yield* installation.start;
582 yield* Deferred.await(entered);
583 expect((yield* installation.state).phase).toBe(phase);
584 expect(
585 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
586 ).toBe("cancelled");
587 yield* Deferred.await(interrupted);
588 yield* Deferred.await(stagingReleased);
589 yield* expectPreviousRelease(installation);
590 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
591 expect(
592 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
593 ).toEqual([previousReleaseId]);
594 }),
595 );
596
597 it.effect.each([
598 { name: "the committed install", restart: false },
599 { name: "a newer install", restart: true },
600 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
601 Effect.gen(function* () {
602 const fs = yield* FileSystem.FileSystem;
603 const cleanupStarted = yield* Deferred.make<void>();
604 const releaseCleanup = yield* Deferred.make<void>();
605 const nextValidationStarted = yield* Deferred.make<void>();
606 const releaseNextValidation = yield* Deferred.make<void>();
607 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
608 const cleanupError = PlatformError.systemError({
609 _tag: "PermissionDenied",
610 module: "FileSystem",
611 method: "remove",
612 description: "EPERM: pointer temp directory is in use",
613 });
614 let firstPointer = true;
615 let validationCount = 0;
616 const { installation, stagingReleased } = yield* makeHarness({
617 previous: true,
618 validate: () => {
619 validationCount += 1;
620 return validationCount === 2
621 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
622 Effect.andThen(Deferred.await(releaseNextValidation)),
623 )
624 : Effect.void;
625 },
626 fileSystem: FileSystem.FileSystem.of({
627 ...fs,
628 makeTempDirectoryScoped: (settings) => {
629 if (settings?.prefix !== "active.json." || !firstPointer) {
630 return fs.makeTempDirectoryScoped(settings);
631 }
632 firstPointer = false;
633 return Effect.fiber.pipe(
634 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
635 Effect.andThen(
636 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
637 Deferred.succeed(cleanupStarted, undefined).pipe(
638 Effect.andThen(Deferred.await(releaseCleanup)),
639 Effect.andThen(Effect.die(cleanupError)),
640 ),
641 ),
642 ),
643 );
644 },
645 }),
646 });
647 yield* Effect.gen(function* () {
648 const first = yield* installation.start;
649 yield* Deferred.await(cleanupStarted);
650 expect(yield* installation.state).toMatchObject({
651 operationId: first.operationId,
652 phase: "succeeded",
653 installedVersion: "fixture-new",
654 });
655 const current = testCase.restart ? yield* installation.start : first;
656 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
657
658 yield* Deferred.succeed(releaseCleanup, undefined);
659 yield* Fiber.await(yield* Deferred.await(firstWorker));
660 yield* Deferred.await(stagingReleased);
661 expect(yield* installation.state).toMatchObject({
662 operationId: current.operationId,
663 phase: testCase.restart ? "verifying" : "succeeded",
664 installedVersion: "fixture-new",
665 });
666 expect((yield* installation.resolve()).version).toBe("fixture-new");
667
668 yield* Deferred.succeed(releaseNextValidation, undefined);
669 expect(yield* terminalState(installation)).toMatchObject({
670 operationId: current.operationId,
671 phase: "succeeded",
672 installedVersion: "fixture-new",
673 });
674 }).pipe(
675 Effect.ensuring(
676 Deferred.succeed(releaseCleanup, undefined).pipe(
677 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
678 ),
679 ),
680 );
681 }),
682 );
683
684 it.effect(
685 "shares one install across callers and keeps it alive after the caller scope closes",
686 () =>
687 Effect.gen(function* () {
688 const entered = yield* Deferred.make<void>();
689 const release = yield* Deferred.make<void>();
690 const { installation, requests, stagingReleased } = yield* makeHarness({
691 body: Stream.fromEffect(
692 Deferred.succeed(entered, undefined).pipe(
693 Effect.andThen(Deferred.await(release)),
694 Effect.as(completeArchive),
695 ),
696 ),
697 });
698 const callerScope = yield* Scope.make();
699 const started = yield* installation.start.pipe(Scope.provide(callerScope));
700 yield* Deferred.await(entered);
701 yield* Scope.close(callerScope, Exit.void);
702 const concurrent = yield* Effect.all([installation.start, installation.start], {
703 concurrency: "unbounded",
704 });
705 expect(concurrent.map((state) => state.operationId)).toEqual([
706 started.operationId,
707 started.operationId,
708 ]);
709 expect(
710 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
711 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
712 yield* Deferred.succeed(release, undefined);
713 expect((yield* terminalState(installation)).phase).toBe("succeeded");
714 yield* Deferred.await(stagingReleased);
715
716 const next = yield* installation.start;
717 expect(next.operationId).not.toBe(started.operationId);
718 expect(
719 yield* installation
720 .cancel(started.operationId ?? "missing-operation-id")
721 .pipe(Effect.flip),
722 ).toMatchObject({ operation: "cancel" });
723 expect((yield* terminalState(installation)).phase).toBe("succeeded");
724 expect(requests).toHaveLength(1);
725 }),
726 );
727
728 // Real posix executables in a real temp dir, resolved by a linux-mocked
729 // PATH walk; a Windows temp path cannot be split on `:`.
730 it.effect.skipIf(HostProcessPlatform.defaultValue() === "win32")(
731 "honors explicit paths and reports invalid overrides without falling back",
732 () =>
733 Effect.gen(function* () {
734 const fs = yield* FileSystem.FileSystem;
735 const path = yield* Path.Path;
736 const baseDir = yield* fs
737 .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" })
738 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
739 const externalDirectory = path.join(baseDir, "external");
740 const externalExecutable = path.join(externalDirectory, executableName);
741 const externalHarness = path.join(externalDirectory, harnessName);
742 yield* fs.makeDirectory(externalDirectory);
743 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
744 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
745 const { installation } = yield* makeHarness({
746 baseDir,
747 path: externalDirectory,
748 previous: true,
749 });
750 yield* expectPreviousRelease(installation);
751 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
752 source: "managed",
753 version: previousVersion,
754 });
755 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
756 executablePath: externalExecutable,
757 source: "override",
758 managedVersionDirectory: null,
759 });
760 expect(yield* installation.resolve(executableName)).toMatchObject({
761 source: "override",
762 });
763 yield* fs.remove(externalHarness);
764 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
765 operation: "resolve",
766 });
767 expect(
768 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
769 ).toMatchObject({
770 operation: "resolve",
771 });
772 yield* expectPreviousRelease(installation);
773 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
774 yield* installation.remove();
775 expect(yield* installation.resolve()).toMatchObject({
776 source: "path",
777 executablePath: externalExecutable,
778 });
779 const isolated = yield* makeHarness({ baseDir });
780 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
781 operation: "resolve",
782 });
783 expect(
784 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
785 ).toMatchObject({
786 source: "path",
787 executablePath: externalExecutable,
788 });
789 expect(
790 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
791 ).toMatchObject({ source: "override", executablePath: externalExecutable });
792 }),
793 );
794
795 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
796 Effect.gen(function* () {
797 const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true });
798 const processScope = yield* Scope.make();
799 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
800 yield* installation.start;
801 expect((yield* terminalState(installation)).phase).toBe("succeeded");
802 yield* Deferred.await(stagingReleased);
803 const current = yield* installation.resolve();
804 expect(current.version).toBe("fixture-new");
805 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
806 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
807 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
808 yield* Scope.close(processScope, Exit.void);
809 yield* installation.remove();
810 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
811 }),
812 );
813
814 it.effect(
815 "removes an incomplete active release before reinstalling without a PATH fallback",
816 () =>
817 Effect.gen(function* () {
818 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
819 const previous = yield* installation.resolve();
820 yield* fs.remove(previous.harnessPath);
821 const externalDirectory = path.join(baseDir, "external");
822 yield* fs.makeDirectory(externalDirectory);
823 yield* fs.writeFileString(path.join(externalDirectory, executableName), "external server", {
824 mode: 0o755,
825 });
826 yield* fs.writeFileString(path.join(externalDirectory, harnessName), "external harness", {
827 mode: 0o755,
828 });
829 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
830 expect(yield* restarted.installation.state).toMatchObject({
831 phase: "failed",
832 installedVersion: null,
833 canRemove: true,
834 });
835 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
836 operation: "resolve",
837 });
838 yield* restarted.installation.remove();
839 expect(yield* restarted.installation.state).toMatchObject({
840 phase: "idle",
841 canRemove: false,
842 });
843 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
844 yield* restarted.installation.start;
845 expect(yield* terminalState(restarted.installation)).toMatchObject({
846 phase: "succeeded",
847 installedVersion: "fixture-new",
848 canRemove: true,
849 });
850 yield* Deferred.await(restarted.stagingReleased);
851 expect((yield* restarted.installation.resolve()).source).toBe("managed");
852 }),
853 );
854
855 it.effect(
856 "blocks removal of custom managed paths and leaves external executables and profiles intact",
857 () =>
858 Effect.gen(function* () {
859 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
860 const managed = yield* installation.resolve();
861 const externalDirectory = path.join(baseDir, "external");
862 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
863 yield* fs.makeDirectory(externalDirectory);
864 yield* fs.makeDirectory(profileDirectory, { recursive: true });
865 const externalExecutable = path.join(externalDirectory, executableName);
866 const externalHarness = path.join(externalDirectory, harnessName);
867 const profilePath = path.join(profileDirectory, "preferences.json");
868 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
869 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
870 yield* fs.writeFileString(profilePath, "{}");
871 expect(
872 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
873 ).toMatchObject({
874 operation: "remove",
875 });
876 yield* expectPreviousRelease(installation);
877 yield* installation.remove([externalExecutable]);
878 expect(yield* installation.state).toMatchObject({
879 phase: "idle",
880 operationId: null,
881 installedVersion: null,
882 });
883 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
884 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
885 expect(yield* fs.readFileString(profilePath)).toBe("{}");
886 }),
887 );
888
889 it.effect(
890 "reuses an immutable Windows release and preserves the pointer when rename is denied",
891 () =>
892 Effect.gen(function* () {
893 const fs = yield* FileSystem.FileSystem;
894 const path = yield* Path.Path;
895 const archive = Buffer.from(zipFixtures.windows, "base64");
896 const asset = releaseAsset(archive, "win32");
897 let denyPointerRename = true;
898 const renameTargets: string[] = [];
899 const { installation, requests, validations } = yield* makeHarness({
900 previous: true,
901 platform: "win32",
902 archive,
903 fileSystem: FileSystem.FileSystem.of({
904 ...fs,
905 rename: (source, target) => {
906 renameTargets.push(target);
907 return denyPointerRename
908 ? Effect.fail(
909 PlatformError.systemError({
910 _tag: "PermissionDenied",
911 module: "FileSystem",
912 method: "rename",
913 pathOrDescriptor: target,
914 description: "EPERM: file is in use",
915 }),
916 )
917 : fs.rename(source, target);
918 },
919 }),
920 });
921 yield* writeRelease(installation.managedDirectory, asset, false);
922 yield* installation.start;
923 expect((yield* terminalState(installation)).phase).toBe("failed");
924 yield* expectPreviousRelease(installation);
925 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
926
927 denyPointerRename = false;
928 yield* installation.start;
929 expect((yield* terminalState(installation)).phase).toBe("succeeded");
930 expect((yield* installation.resolve()).version).toBe("fixture-new");
931 expect(requests).toEqual([]);
932 expect(validations).toHaveLength(2);
933 expect(renameTargets).toEqual([
934 path.join(installation.managedDirectory, "active.json"),
935 path.join(installation.managedDirectory, "active.json"),
936 ]);
937 }),
938 );
939
940 it.effect("reports unsupported hosts without downloading or changing state", () =>
941 Effect.gen(function* () {
942 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
943 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
944 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
945 operation: "resolve",
946 });
947 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
948 expect(requests).toEqual([]);
949 }),
950 );
951
952 it("resolves all supported platform release assets including Intel Mac", () => {
953 const supportedPlatforms: Array<{ readonly platform: NodeJS.Platform; readonly arch: string }> =
954 [
955 { platform: "darwin", arch: "arm64" },
956 { platform: "darwin", arch: "x64" },
957 { platform: "linux", arch: "x64" },
958 { platform: "linux", arch: "arm64" },
959 { platform: "win32", arch: "x64" },
960 { platform: "win32", arch: "arm64" },
961 ];
962
963 for (const { platform, arch } of supportedPlatforms) {
964 const asset = resolveAntigravityReleaseAsset(platform, arch);
965 expect(asset).not.toBeNull();
966 expect(asset?.version).toBe("1.3.0");
967 expect(asset?.url).toContain("1.3.0");
968 expect(asset?.archiveBytes).toBeGreaterThan(0);
969 expect(asset?.executable.bytes).toBeGreaterThan(0);
970 expect(asset?.harness.bytes).toBeGreaterThan(0);
971 }
972
973 expect(resolveAntigravityReleaseAsset("freebsd", "x64")).toBeNull();
974 });
975});