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