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

AntigravityInstallation.test.ts

950 lines41.1 KB

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