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 {
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
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+gUAAAAFAAAABIAAAAAAAAAAAAAAO2BAAAAAGFneV9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ZXh0ZXJuYWwuZXhly8lPTsxRyEgsykstLuYCAFBLAQIUAxQAAAAIAAAAIl1zEy/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?: 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<{ executable: AntigravityExecutable; version: string }> = [];
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* makeAntigravityInstallation({
174 baseDir,
175 releaseAsset: asset,
176 ...(options.useDefaultValidation
177 ? {}
178 : {
179 validate: (executable: 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["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["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",
310 agentName: "antigravity-acp",
311 version: "fixture-new",
312 valid: true,
313 },
314 { name: "a different agent", agentName: "other-agent", version: "fixture-new", valid: false },
315 {
316 name: "a different version",
317 agentName: "antigravity-acp",
318 version: "other-version",
319 valid: false,
320 },
321 ])("validates $name with initialize only and removes the disposable profile", (testCase) =>
322 Effect.gen(function* () {
323 const fs = yield* FileSystem.FileSystem;
324 const encoder = new TextEncoder();
325 const decodeRequest = Schema.decodeUnknownEffect(
326 Schema.fromJsonString(
327 Schema.Struct({
328 id: Schema.Union([Schema.String, Schema.Number]),
329 method: Schema.String,
330 }),
331 ),
332 );
333 const methods: string[] = [];
334 const profiles = new Set<string>();
335 let closedRuntimes = 0;
336 const spawner = ChildProcessSpawner.make(
337 Effect.fn("test.spawnAntigravityValidator")(function* (command) {
338 if (command._tag !== "StandardCommand") {
339 return yield* Effect.die("Expected one validation process.");
340 }
341 const profile = command.options.env?.GEMINI_HOME;
342 if (!profile) return yield* Effect.die("Expected a disposable validation profile.");
343 profiles.add(profile);
344 const helper = command.args[0] === "-e";
345 // The runtime unpacks straight into the disposable profile.
346 if (!helper) expect(command.options.env?.TMPDIR).toBe(profile);
347 const output = yield* Queue.unbounded<Uint8Array>();
348 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
349 const terminate = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
350 Effect.asVoid,
351 );
352 yield* Effect.addFinalizer(() =>
353 terminate.pipe(
354 Effect.andThen(Queue.shutdown(output)),
355 Effect.andThen(
356 Effect.sync(() => {
357 if (!helper) closedRuntimes += 1;
358 }),
359 ),
360 ),
361 );
362 return ChildProcessSpawner.makeHandle({
363 pid: ChildProcessSpawner.ProcessId(helper ? 1 : 2),
364 exitCode: helper
365 ? Effect.succeed(ChildProcessSpawner.ExitCode(0))
366 : Deferred.await(exited),
367 isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
368 kill: () => terminate,
369 unref: Effect.succeed(Effect.void),
370 stdin: Sink.forEach((bytes: Uint8Array) =>
371 Effect.gen(function* () {
372 const request = yield* decodeRequest(new TextDecoder().decode(bytes)).pipe(
373 Effect.orDie,
374 );
375 methods.push(request.method);
376 yield* Queue.offer(
377 output,
378 encoder.encode(
379 `${encodeJsonString({
380 jsonrpc: "2.0",
381 id: request.id,
382 ...(request.method === "initialize"
383 ? {
384 result: {
385 protocolVersion: 1,
386 agentInfo: { name: testCase.agentName, version: testCase.version },
387 agentCapabilities: {
388 loadSession: true,
389 sessionCapabilities: { resume: {} },
390 auth: { logout: {} },
391 },
392 authMethods: [{ id: "oauth-personal", name: "Google" }],
393 },
394 }
395 : {
396 error: {
397 code: -32601,
398 message: "Validation must not sign in or create sessions.",
399 },
400 }),
401 })}\n`,
402 ),
403 );
404 }),
405 ),
406 stdout: helper ? Stream.empty : Stream.fromQueue(output),
407 stderr: helper
408 ? Stream.make(
409 encoder.encode(
410 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeJsonString(command.args.at(-1))}\n`,
411 ),
412 )
413 : Stream.empty,
414 all: Stream.empty,
415 getInputFd: () => Sink.drain,
416 getOutputFd: () => Stream.empty,
417 });
418 }),
419 );
420 const { installation, stagingReleased } = yield* makeHarness({
421 previous: true,
422 useDefaultValidation: true,
423 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
424 yield* installation.start;
425 expect((yield* terminalState(installation)).phase).toBe(
426 testCase.valid ? "succeeded" : "failed",
427 );
428 yield* Deferred.await(stagingReleased);
429 expect(methods).toEqual(["initialize"]);
430 expect(closedRuntimes).toBe(1);
431 expect(profiles.size).toBe(1);
432 for (const profile of profiles) {
433 expect(yield* fs.exists(profile)).toBe(false);
434 }
435 if (testCase.valid) {
436 expect((yield* installation.resolve()).version).toBe("fixture-new");
437 } else {
438 yield* expectPreviousRelease(installation);
439 }
440 }),
441 );
442
443 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
444 Effect.gen(function* () {
445 // dl.google.com gzips the archive and reports the encoded size. The decoded
446 // stream is still checked byte for byte and by hash.
447 const { installation, validations } = yield* makeHarness({
448 contentLength: completeArchive.byteLength - 1_000,
449 contentEncoding: "gzip",
450 });
451 yield* installation.start;
452 const state = yield* terminalState(installation);
453 expect(state.phase).toBe("succeeded");
454 expect(validations).toHaveLength(1);
455 }),
456 );
457
458 it.effect.each([
459 { name: "checksum mismatch", asset: { ...releaseAsset(), sha256: "2".repeat(64) } },
460 { name: "short download", archive: completeArchive.subarray(0, -1), asset: releaseAsset() },
461 {
462 name: "oversized download",
463 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
464 asset: releaseAsset(),
465 },
466 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
467 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
468 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
469 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
470 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
471 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
472 ])("rejects $name before runtime validation", (options) =>
473 Effect.gen(function* () {
474 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
475 ...options,
476 previous: true,
477 });
478 yield* installation.start;
479 const state = yield* terminalState(installation);
480 expect(state.phase).toBe("failed");
481 expect(state.message).toBeTruthy();
482 expect(validations).toEqual([]);
483 yield* Deferred.await(stagingReleased);
484 yield* expectPreviousRelease(installation);
485 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
486 [previousReleaseId],
487 );
488 }),
489 );
490
491 it.effect.each(["download", "extract", "active pointer"] as const)(
492 "preserves the old runtime after an ENOSPC error during %s",
493 (stage) =>
494 Effect.gen(function* () {
495 const fs = yield* FileSystem.FileSystem;
496 const noSpace = PlatformError.systemError({
497 _tag: "Unknown",
498 module: "FileSystem",
499 method: "write",
500 description: "ENOSPC: no space left on device",
501 });
502 const fileSystem = FileSystem.FileSystem.of({
503 ...fs,
504 sink: (target, options) =>
505 (stage === "download" && target.endsWith("download.zip")) ||
506 (stage === "extract" && target.endsWith(executableName))
507 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
508 : fs.sink(target, options),
509 writeFileString: (target, content, options) =>
510 stage === "active pointer" && target.endsWith("contents.tmp")
511 ? Effect.fail(noSpace)
512 : fs.writeFileString(target, content, options),
513 });
514 const { installation, stagingReleased, path } = yield* makeHarness({
515 previous: true,
516 fileSystem,
517 });
518 yield* installation.start;
519 expect((yield* terminalState(installation)).phase).toBe("failed");
520 yield* Deferred.await(stagingReleased);
521 yield* expectPreviousRelease(installation);
522 expect(
523 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
524 (name) => name.startsWith(".install-"),
525 ),
526 ).toBe(false);
527 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
528 "active.json",
529 "versions",
530 ]);
531 }),
532 );
533
534 it.effect.each(["downloading", "extracting", "verifying"] as const)(
535 "cancels during %s and waits for open resources to close",
536 (phase) =>
537 Effect.gen(function* () {
538 const fs = yield* FileSystem.FileSystem;
539 const entered = yield* Deferred.make<void>();
540 const release = yield* Deferred.make<void>();
541 const interrupted = yield* Deferred.make<void>();
542 const barrier = Deferred.succeed(entered, undefined).pipe(
543 Effect.andThen(Deferred.await(release)),
544 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
545 );
546 const { installation, stagingReleased, path, validations } = yield* makeHarness({
547 previous: true,
548 body:
549 phase === "downloading"
550 ? Stream.concat(
551 Stream.make(completeArchive.subarray(0, 31)),
552 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
553 )
554 : undefined,
555 validate: phase === "verifying" ? () => barrier : undefined,
556 fileSystem: FileSystem.FileSystem.of({
557 ...fs,
558 sink: (target, options) =>
559 phase === "extracting" && target.endsWith(executableName)
560 ? fs
561 .sink(target, options)
562 .pipe(
563 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
564 )
565 : fs.sink(target, options),
566 }),
567 });
568 const started = yield* installation.start;
569 yield* Deferred.await(entered);
570 expect((yield* installation.state).phase).toBe(phase);
571 expect(
572 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
573 ).toBe("cancelled");
574 yield* Deferred.await(interrupted);
575 yield* Deferred.await(stagingReleased);
576 yield* expectPreviousRelease(installation);
577 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
578 expect(
579 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
580 ).toEqual([previousReleaseId]);
581 }),
582 );
583
584 it.effect.each([
585 { name: "the committed install", restart: false },
586 { name: "a newer install", restart: true },
587 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
588 Effect.gen(function* () {
589 const fs = yield* FileSystem.FileSystem;
590 const cleanupStarted = yield* Deferred.make<void>();
591 const releaseCleanup = yield* Deferred.make<void>();
592 const nextValidationStarted = yield* Deferred.make<void>();
593 const releaseNextValidation = yield* Deferred.make<void>();
594 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
595 const cleanupError = PlatformError.systemError({
596 _tag: "PermissionDenied",
597 module: "FileSystem",
598 method: "remove",
599 description: "EPERM: pointer temp directory is in use",
600 });
601 let firstPointer = true;
602 let validationCount = 0;
603 const { installation, stagingReleased } = yield* makeHarness({
604 previous: true,
605 validate: () => {
606 validationCount += 1;
607 return validationCount === 2
608 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
609 Effect.andThen(Deferred.await(releaseNextValidation)),
610 )
611 : Effect.void;
612 },
613 fileSystem: FileSystem.FileSystem.of({
614 ...fs,
615 makeTempDirectoryScoped: (settings) => {
616 if (settings?.prefix !== "active.json." || !firstPointer) {
617 return fs.makeTempDirectoryScoped(settings);
618 }
619 firstPointer = false;
620 return Effect.fiber.pipe(
621 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
622 Effect.andThen(
623 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
624 Deferred.succeed(cleanupStarted, undefined).pipe(
625 Effect.andThen(Deferred.await(releaseCleanup)),
626 Effect.andThen(Effect.die(cleanupError)),
627 ),
628 ),
629 ),
630 );
631 },
632 }),
633 });
634 yield* Effect.gen(function* () {
635 const first = yield* installation.start;
636 yield* Deferred.await(cleanupStarted);
637 expect(yield* installation.state).toMatchObject({
638 operationId: first.operationId,
639 phase: "succeeded",
640 installedVersion: "fixture-new",
641 });
642 const current = testCase.restart ? yield* installation.start : first;
643 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
644
645 yield* Deferred.succeed(releaseCleanup, undefined);
646 yield* Fiber.await(yield* Deferred.await(firstWorker));
647 yield* Deferred.await(stagingReleased);
648 expect(yield* installation.state).toMatchObject({
649 operationId: current.operationId,
650 phase: testCase.restart ? "verifying" : "succeeded",
651 installedVersion: "fixture-new",
652 });
653 expect((yield* installation.resolve()).version).toBe("fixture-new");
654
655 yield* Deferred.succeed(releaseNextValidation, undefined);
656 expect(yield* terminalState(installation)).toMatchObject({
657 operationId: current.operationId,
658 phase: "succeeded",
659 installedVersion: "fixture-new",
660 });
661 }).pipe(
662 Effect.ensuring(
663 Deferred.succeed(releaseCleanup, undefined).pipe(
664 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
665 ),
666 ),
667 );
668 }),
669 );
670
671 it.effect(
672 "shares one install across callers and keeps it alive after the caller scope closes",
673 () =>
674 Effect.gen(function* () {
675 const entered = yield* Deferred.make<void>();
676 const release = yield* Deferred.make<void>();
677 const { installation, requests, stagingReleased } = yield* makeHarness({
678 body: Stream.fromEffect(
679 Deferred.succeed(entered, undefined).pipe(
680 Effect.andThen(Deferred.await(release)),
681 Effect.as(completeArchive),
682 ),
683 ),
684 });
685 const callerScope = yield* Scope.make();
686 const started = yield* installation.start.pipe(Scope.provide(callerScope));
687 yield* Deferred.await(entered);
688 yield* Scope.close(callerScope, Exit.void);
689 const concurrent = yield* Effect.all([installation.start, installation.start], {
690 concurrency: "unbounded",
691 });
692 expect(concurrent.map((state) => state.operationId)).toEqual([
693 started.operationId,
694 started.operationId,
695 ]);
696 expect(
697 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
698 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
699 yield* Deferred.succeed(release, undefined);
700 expect((yield* terminalState(installation)).phase).toBe("succeeded");
701 yield* Deferred.await(stagingReleased);
702
703 const next = yield* installation.start;
704 expect(next.operationId).not.toBe(started.operationId);
705 expect(
706 yield* installation
707 .cancel(started.operationId ?? "missing-operation-id")
708 .pipe(Effect.flip),
709 ).toMatchObject({ operation: "cancel" });
710 expect((yield* terminalState(installation)).phase).toBe("succeeded");
711 expect(requests).toHaveLength(1);
712 }),
713 );
714
715 // Real posix executables in a real temp dir, resolved by a linux-mocked
716 // PATH walk; a Windows temp path cannot be split on `:`.
717 it.effect.skipIf(HostProcessPlatform.defaultValue() === "win32")(
718 "honors explicit paths and reports invalid overrides without falling back",
719 () =>
720 Effect.gen(function* () {
721 const fs = yield* FileSystem.FileSystem;
722 const path = yield* Path.Path;
723 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" });
724 const externalDirectory = path.join(baseDir, "external");
725 const externalExecutable = path.join(externalDirectory, executableName);
726 const externalHarness = path.join(externalDirectory, harnessName);
727 yield* fs.makeDirectory(externalDirectory);
728 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
729 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
730 const { installation } = yield* makeHarness({
731 baseDir,
732 path: externalDirectory,
733 previous: true,
734 });
735 yield* expectPreviousRelease(installation);
736 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
737 source: "managed",
738 version: previousVersion,
739 });
740 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
741 executablePath: externalExecutable,
742 source: "override",
743 managedVersionDirectory: null,
744 });
745 expect(yield* installation.resolve(executableName)).toMatchObject({
746 source: "override",
747 });
748 yield* fs.remove(externalHarness);
749 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
750 operation: "resolve",
751 });
752 expect(
753 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
754 ).toMatchObject({
755 operation: "resolve",
756 });
757 yield* expectPreviousRelease(installation);
758 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
759 yield* installation.remove();
760 expect(yield* installation.resolve()).toMatchObject({
761 source: "path",
762 executablePath: externalExecutable,
763 });
764 const isolated = yield* makeHarness({ baseDir });
765 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
766 operation: "resolve",
767 });
768 expect(
769 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
770 ).toMatchObject({
771 source: "path",
772 executablePath: externalExecutable,
773 });
774 expect(
775 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
776 ).toMatchObject({ source: "override", executablePath: externalExecutable });
777 }),
778 );
779
780 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
781 Effect.gen(function* () {
782 const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true });
783 const processScope = yield* Scope.make();
784 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
785 yield* installation.start;
786 expect((yield* terminalState(installation)).phase).toBe("succeeded");
787 yield* Deferred.await(stagingReleased);
788 const current = yield* installation.resolve();
789 expect(current.version).toBe("fixture-new");
790 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
791 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
792 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
793 yield* Scope.close(processScope, Exit.void);
794 yield* installation.remove();
795 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
796 }),
797 );
798
799 it.effect(
800 "removes an incomplete active release before reinstalling without a PATH fallback",
801 () =>
802 Effect.gen(function* () {
803 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
804 const previous = yield* installation.resolve();
805 yield* fs.remove(previous.harnessPath);
806 const externalDirectory = path.join(baseDir, "external");
807 yield* fs.makeDirectory(externalDirectory);
808 yield* fs.writeFileString(path.join(externalDirectory, executableName), "external server", {
809 mode: 0o755,
810 });
811 yield* fs.writeFileString(path.join(externalDirectory, harnessName), "external harness", {
812 mode: 0o755,
813 });
814 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
815 expect(yield* restarted.installation.state).toMatchObject({
816 phase: "failed",
817 installedVersion: null,
818 canRemove: true,
819 });
820 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
821 operation: "resolve",
822 });
823 yield* restarted.installation.remove();
824 expect(yield* restarted.installation.state).toMatchObject({
825 phase: "idle",
826 canRemove: false,
827 });
828 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
829 yield* restarted.installation.start;
830 expect(yield* terminalState(restarted.installation)).toMatchObject({
831 phase: "succeeded",
832 installedVersion: "fixture-new",
833 canRemove: true,
834 });
835 yield* Deferred.await(restarted.stagingReleased);
836 expect((yield* restarted.installation.resolve()).source).toBe("managed");
837 }),
838 );
839
840 it.effect(
841 "blocks removal of custom managed paths and leaves external executables and profiles intact",
842 () =>
843 Effect.gen(function* () {
844 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
845 const managed = yield* installation.resolve();
846 const externalDirectory = path.join(baseDir, "external");
847 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
848 yield* fs.makeDirectory(externalDirectory);
849 yield* fs.makeDirectory(profileDirectory, { recursive: true });
850 const externalExecutable = path.join(externalDirectory, executableName);
851 const externalHarness = path.join(externalDirectory, harnessName);
852 const profilePath = path.join(profileDirectory, "preferences.json");
853 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
854 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
855 yield* fs.writeFileString(profilePath, "{}");
856 expect(
857 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
858 ).toMatchObject({
859 operation: "remove",
860 });
861 yield* expectPreviousRelease(installation);
862 yield* installation.remove([externalExecutable]);
863 expect(yield* installation.state).toMatchObject({
864 phase: "idle",
865 operationId: null,
866 installedVersion: null,
867 });
868 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
869 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
870 expect(yield* fs.readFileString(profilePath)).toBe("{}");
871 }),
872 );
873
874 it.effect(
875 "reuses an immutable Windows release and preserves the pointer when rename is denied",
876 () =>
877 Effect.gen(function* () {
878 const fs = yield* FileSystem.FileSystem;
879 const path = yield* Path.Path;
880 const archive = Buffer.from(zipFixtures.windows, "base64");
881 const asset = releaseAsset(archive, "win32");
882 let denyPointerRename = true;
883 const renameTargets: string[] = [];
884 const { installation, requests, validations } = yield* makeHarness({
885 previous: true,
886 platform: "win32",
887 archive,
888 fileSystem: FileSystem.FileSystem.of({
889 ...fs,
890 rename: (source, target) => {
891 renameTargets.push(target);
892 return denyPointerRename
893 ? Effect.fail(
894 PlatformError.systemError({
895 _tag: "PermissionDenied",
896 module: "FileSystem",
897 method: "rename",
898 pathOrDescriptor: target,
899 description: "EPERM: file is in use",
900 }),
901 )
902 : fs.rename(source, target);
903 },
904 }),
905 });
906 yield* writeRelease(installation.managedDirectory, asset, false);
907 yield* installation.start;
908 expect((yield* terminalState(installation)).phase).toBe("failed");
909 yield* expectPreviousRelease(installation);
910 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
911
912 denyPointerRename = false;
913 yield* installation.start;
914 expect((yield* terminalState(installation)).phase).toBe("succeeded");
915 expect((yield* installation.resolve()).version).toBe("fixture-new");
916 expect(requests).toEqual([]);
917 expect(validations).toHaveLength(2);
918 expect(renameTargets).toEqual([
919 path.join(installation.managedDirectory, "active.json"),
920 path.join(installation.managedDirectory, "active.json"),
921 ]);
922 }),
923 );
924
925 it.effect("reports unsupported hosts without downloading or changing state", () =>
926 Effect.gen(function* () {
927 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
928 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
929 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
930 operation: "resolve",
931 });
932 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
933 expect(requests).toEqual([]);
934 }),
935 );
936});