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