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

AntigravityInstallation.test.ts

1,021 lines45.1 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Layer from "effect/Layer";
4import { expect, it } from "@effect/vitest";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as Digest from "effect/crypto/Digest";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import * as Schema from "effect/Schema";
17import * as Scope from "effect/Scope";
18import * as Sink from "effect/Sink";
19import * as Stream from "effect/Stream";
20import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
21import * as ChildProcess from "effect/process/ChildProcess";
22import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
23​
24import * as AntigravityInstallation from "./AntigravityInstallation.ts";
25import { type AntigravityReleaseAsset } from "./antigravityRelease.ts";
26​
27const serverContents = "antigravity runtime\n";
28const harnessContents = "local harness\n";
29const previousReleaseId = "1".repeat(64);
30const previousVersion = "fixture-old";
31const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
32​
33const zipFixtures = {
34 complete:
35 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAAAFAAAABIAAAAAAAAAAAAAAO2BAAAAAGFneV9hY3Bfc2VydmVyLnBhclBLAQIUAxQAAAAIAAAAIl1fcgMpEAAAAA4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AAAIl1zEy/oFAAAABQAAAASAAAAAAAAAAAAAADtgQAAAABhZ3lfYWNwX3NlcnZlci5leGVQSwECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAGQAAAAAAAAAAAAAA7YFEAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsLmV4ZVBLBQYAAAAAAgACAIcAAACLAAAAAAA=",
48};
49​
50// Linux platform mocks cannot enforce POSIX exec bits on NTFS; use the host platform.
51const hostPlatform: NodeJS.Platform =
52 HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux";
53const completeArchive = Buffer.from(
54 hostPlatform === "win32" ? zipFixtures.windows : zipFixtures.complete,
55 "base64",
56);
57const executableName = hostPlatform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par";
58const harnessName =
59 hostPlatform === "win32" ? "localharness_external.exe" : "localharness_external";
60​
61const releaseAsset = Effect.fn("test.antigravityReleaseAsset")(function* (
62 archive: Uint8Array = completeArchive,
63 platform: NodeJS.Platform = hostPlatform,
64) {
65 const digest = yield* Digest.Digest;
66 return {
67 version: "fixture-new",
68 url: "https://dl.google.com/antigravity-test.zip",
69 sha256: Hex.encode(yield* digest.digest(Digest.sha256, archive).pipe(Effect.orDie)),
70 archiveBytes: archive.byteLength,
71 executable: {
72 name: platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par",
73 bytes: Buffer.byteLength(serverContents),
74 },
75 harness: {
76 name: platform === "win32" ? "localharness_external.exe" : "localharness_external",
77 bytes: Buffer.byteLength(harnessContents),
78 },
79 } satisfies AntigravityReleaseAsset;
80});
81​
82const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* (
83 managedDirectory: string,
84 asset: AntigravityReleaseAsset,
85 active = true,
86) {
87 const fs = yield* FileSystem.FileSystem;
88 const path = yield* Path.Path;
89 const directory = path.join(managedDirectory, "versions", asset.sha256);
90 yield* fs.makeDirectory(directory, { recursive: true });
91 yield* fs.writeFileString(path.join(directory, asset.executable.name), serverContents, {
92 mode: 0o755,
93 });
94 yield* fs.writeFileString(path.join(directory, asset.harness.name), harnessContents, {
95 mode: 0o755,
96 });
97 yield* fs.writeFileString(
98 path.join(directory, ".install-complete.json"),
99 encodeJsonString({
100 releaseId: asset.sha256,
101 version: asset.version,
102 executable: asset.executable,
103 harness: asset.harness,
104 }),
105 );
106 if (active) {
107 yield* fs.writeFileString(
108 path.join(managedDirectory, "active.json"),
109 encodeJsonString({ releaseId: asset.sha256 }),
110 );
111 }
112});
113​
114interface HarnessOptions {
115 readonly baseDir?: string;
116 readonly asset?: AntigravityReleaseAsset | null;
117 readonly archive?: Buffer;
118 readonly body?: Stream.Stream<Uint8Array> | undefined;
119 readonly contentLength?: number;
120 readonly contentEncoding?: string;
121 readonly platform?: NodeJS.Platform;
122 readonly arch?: NodeJS.Architecture;
123 readonly path?: string;
124 readonly previous?: boolean;
125 readonly fileSystem?: FileSystem.FileSystem;
126 readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
127 readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"];
128 readonly useDefaultValidation?: boolean;
129 readonly connectTimeout?: boolean;
131​
132const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
133 options: HarnessOptions = {},
134) {
135 const fs = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
137 const baseDir =
138 options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
139 const platform = options.platform ?? hostPlatform;
140 const arch = options.arch ?? "x64";
141 const archive = options.archive ?? completeArchive;
142 const asset =
143 options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset;
144 const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`);
145 if (options.previous) {
146 yield* writeRelease(managedDirectory, {
147 ...(yield* releaseAsset(archive, platform)),
148 sha256: previousReleaseId,
149 version: previousVersion,
150 });
151 }
152 const stagingReleased = yield* Deferred.make<void>();
153 const requests: string[] = [];
154 const validations: Array<{
155 executable: AntigravityInstallation.AntigravityExecutable;
156 version: string;
157 }> = [];
158 const installationFs = options.fileSystem ?? fs;
159 const trackedFs = FileSystem.FileSystem.of({
160 ...installationFs,
161 makeTempDirectoryScoped: (settings) =>
162 settings?.prefix === ".install-"
163 ? Effect.acquireRelease(installationFs.makeTempDirectory(settings), (directory) =>
164 fs
165 .remove(directory, { recursive: true, force: true })
166 .pipe(Effect.orDie, Effect.andThen(Deferred.succeed(stagingReleased, undefined))),
167 )
168 : installationFs.makeTempDirectoryScoped(settings),
169 });
170 const installation = yield* AntigravityInstallation.makeAntigravityInstallation({
171 baseDir,
172 releaseAsset: asset,
173 ...(options.useDefaultValidation
174 ? {}
175 : {
176 validate: (executable: AntigravityInstallation.AntigravityExecutable, version: string) =>
177 Effect.sync(() => validations.push({ executable, version })).pipe(
178 Effect.andThen(options.validate?.(executable, version) ?? Effect.void),
179 ),
180 }),
181 }).pipe(
182 options.spawner
183 ? Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, options.spawner)
184 : (effect) => effect,
185 Effect.provideService(FileSystem.FileSystem, trackedFs),
186 Effect.provideService(HostProcess.Platform, platform),
187 Effect.provideService(HostProcess.Architecture, arch),
188 Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }),
189 Effect.provideService(
190 HttpClient.HttpClient,
191 HttpClient.make((request) =>
192 Effect.suspend(() => {
193 requests.push(request.url);
194 if (options.connectTimeout) {
195 return Effect.fail(
196 new HttpClientError.HttpClientError({
197 reason: new HttpClientError.TransportError({
198 request,
199 cause: new Error("Connect Timeout Error (attempted address: dl.google.com:443)"),
200 }),
201 }),
202 );
203 }
204 const response = HttpClientResponse.fromWeb(
205 request,
206 new Response(null, {
207 headers: {
208 ...(options.contentLength === undefined
209 ? {}
210 : { "content-length": String(options.contentLength) }),
211 ...(options.contentEncoding === undefined
212 ? {}
213 : { "content-encoding": options.contentEncoding }),
214 },
215 }),
216 );
217 return Effect.succeed(
218 Object.defineProperty(response, "stream", {
219 value:
220 options.body ??
221 Stream.make(
222 archive.subarray(0, 31),
223 archive.subarray(31, 149),
224 archive.subarray(149),
225 ),
226 }),
227 );
228 }),
229 ),
230 ),
231 );
232 return { installation, fs, path, baseDir, requests, validations, stagingReleased };
233});
234​
235const terminalState = (installation: AntigravityInstallation.AntigravityInstallation["Service"]) =>
236 installation.changes.pipe(
237 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
238 Stream.runHead,
239 Effect.map(Option.getOrThrow),
240 );
241​
242const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease")(function* (
243 installation: AntigravityInstallation.AntigravityInstallation["Service"],
244) {
245 const fs = yield* FileSystem.FileSystem;
246 const path = yield* Path.Path;
247 const resolved = yield* installation.resolve();
248 expect(resolved.version).toBe(previousVersion);
249 expect(resolved.managedVersionDirectory).toBe(
250 path.join(installation.managedDirectory, "versions", previousReleaseId),
251 );
252 expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents);
253 expect(yield* fs.readFileString(resolved.harnessPath!)).toBe(harnessContents);
254 expect((yield* installation.state).installedVersion).toBe(previousVersion);
255});
256​
257it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity installation", (it) => {
258 it.effect("reports missing Node before downloading the standalone provider runtime", () =>
259 Effect.gen(function* () {
260 const { installation, requests, validations } = yield* makeHarness();
261 yield* installation.start;
262 expect(yield* terminalState(installation)).toMatchObject({
263 phase: "failed",
264 message: expect.stringContaining("Install Node.js"),
265 });
266 expect(requests).toEqual([]);
267 expect(validations).toEqual([]);
268 }).pipe(Effect.provideService(HostProcess.IsExecutable, true)),
269 );
270​
271 it.effect("verifies both files before activating a streamed download", () =>
272 Effect.gen(function* () {
273 const enteredValidation = yield* Deferred.make<void>();
274 const finishValidation = yield* Deferred.make<void>();
275 const { installation, fs, path, validations, requests, stagingReleased } = yield* makeHarness(
276 {
277 previous: true,
278 validate: () =>
279 Deferred.succeed(enteredValidation, undefined).pipe(
280 Effect.andThen(Deferred.await(finishValidation)),
281 ),
282 },
283 );
284 const initial = yield* installation.changes.pipe(
285 Stream.runHead,
286 Effect.map(Option.getOrThrow),
287 );
288 expect(initial).toMatchObject({ phase: "idle", installedVersion: previousVersion });
289 const started = yield* installation.start;
290 expect(started).toMatchObject({ phase: "downloading", downloadedBytes: 0 });
291 yield* Deferred.await(enteredValidation);
292 yield* expectPreviousRelease(installation);
293 const validation = validations[0];
294 expect(validation?.version).toBe("fixture-new");
295 if (!validation) return yield* Effect.die("Expected runtime validation.");
296 expect(yield* fs.readFileString(validation.executable.executablePath)).toBe(serverContents);
297 expect(yield* fs.readFileString(validation.executable.harnessPath!)).toBe(harnessContents);
298​
299 yield* Deferred.succeed(finishValidation, undefined);
300 expect(yield* terminalState(installation)).toMatchObject({
301 phase: "succeeded",
302 operationId: started.operationId,
303 downloadedBytes: completeArchive.byteLength,
304 installedVersion: "fixture-new",
305 });
306 yield* Deferred.await(stagingReleased);
307 const selected = yield* installation.resolve();
308 expect(selected).toMatchObject({ source: "managed", version: "fixture-new" });
309 expect(path.dirname(selected.harnessPath!)).toBe(path.dirname(selected.executablePath));
310 expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents);
311 expect(yield* fs.readFileString(selected.harnessPath!)).toBe(harnessContents);
312 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
313 expect.arrayContaining([previousReleaseId, (yield* releaseAsset()).sha256]),
314 );
315 expect(requests).toEqual([(yield* releaseAsset()).url]);
316 }),
317 );
318​
319 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
320 Effect.gen(function* () {
321 // dl.google.com reports the gzip-encoded size; byte and hash checks use the decoded stream.
322 const { installation, validations } = yield* makeHarness({
323 contentLength: completeArchive.byteLength - 1_000,
324 contentEncoding: "gzip",
325 });
326 yield* installation.start;
327 const state = yield* terminalState(installation);
328 expect(state.phase).toBe("succeeded");
329 expect(validations).toHaveLength(1);
330 }),
331 );
332​
333 it.effect.each([
334 { name: "checksum mismatch", completeAsset: { sha256: "2".repeat(64) } },
335 { name: "short download", archive: completeArchive.subarray(0, -1), completeAsset: {} },
336 {
337 name: "oversized download",
338 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
339 completeAsset: {},
340 },
341 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
342 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
343 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
344 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
345 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
346 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
347 ])("rejects $name before runtime validation", ({ completeAsset, ...options }) =>
348 Effect.gen(function* () {
349 const asset =
350 completeAsset === undefined ? undefined : { ...(yield* releaseAsset()), ...completeAsset };
351 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
352 ...options,
353 ...(asset === undefined ? {} : { asset }),
354 previous: true,
355 });
356 yield* installation.start;
357 const state = yield* terminalState(installation);
358 expect(state.phase).toBe("failed");
359 expect(state.message).toBeTruthy();
360 expect(validations).toEqual([]);
361 yield* Deferred.await(stagingReleased);
362 yield* expectPreviousRelease(installation);
363 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
364 [previousReleaseId],
365 );
366 }),
367 );
368​
369 it.effect(
370 "names the connection failure instead of disk space when the download cannot connect",
371 () =>
372 Effect.gen(function* () {
373 const { installation, validations } = yield* makeHarness({ connectTimeout: true });
374 yield* installation.start;
375 const state = yield* terminalState(installation);
376 expect(state.phase).toBe("failed");
377 expect(state.message).not.toMatch(/disk space/i);
378 expect(state.message).toMatch(/connect|network|download/i);
379 expect(validations).toEqual([]);
380 }),
381 );
382​
383 // The runtime's own abort is a real process; Windows has no POSIX sh.
384 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
385 "explains that the linux-arm64 runtime needs 4 KiB pages when it aborts on a 16 KiB kernel",
386 () =>
387 Effect.gen(function* () {
388 const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
389 // Google's linux-arm64 build aborts like this on Asahi and Raspberry Pi 5 kernels.
390 const spawner = ChildProcessSpawner.make((command) =>
391 ChildProcess.isStandardCommand(command) &&
392 String(command.command).endsWith(executableName)
393 ? realSpawner.spawn(
394 ChildProcess.make(
395 "sh",
396 [
397 "-c",
398 "echo 'F1111 11:50:12.383176 page-size.cc:19] Check failed: sysconf(_SC_PAGE_SIZE) == kPageSize (16384 vs. 4096) Compile-time page size does not match runtime page size' >&2; kill -ABRT $$",
399 ],
400 { stdin: "pipe", stdout: "pipe", stderr: "pipe" },
401 ),
402 )
403 : realSpawner.spawn(command),
404 );
405 const { installation } = yield* makeHarness({
406 arch: "arm64",
407 useDefaultValidation: true,
408 spawner,
409 });
410 yield* installation.start;
411 const state = yield* terminalState(installation);
412 expect(state.phase).toBe("failed");
413 expect(state.message).toMatch(/page/i);
414 }),
415 );
416​
417 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
418 "refuses a 16 KiB-page linux-arm64 kernel before downloading the runtime",
419 () =>
420 Effect.gen(function* () {
421 const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
422 const spawner = ChildProcessSpawner.make((command) =>
423 ChildProcess.isStandardCommand(command) && command.command === "getconf"
424 ? realSpawner.spawn(ChildProcess.make("sh", ["-c", "echo 16384"], command.options))
425 : realSpawner.spawn(command),
426 );
427 const { installation, requests } = yield* makeHarness({ arch: "arm64", spawner });
428 yield* installation.start;
429 const state = yield* terminalState(installation);
430 expect(state.phase).toBe("failed");
431 expect(state.message).toMatch(/4 KiB/);
432 expect(requests).toEqual([]);
433 }),
434 );
435​
436 it.effect.each(["download", "extract", "active pointer"] as const)(
437 "preserves the old runtime after an ENOSPC error during %s",
438 (stage) =>
439 Effect.gen(function* () {
440 const fs = yield* FileSystem.FileSystem;
441 const noSpace = PlatformError.systemError({
442 _tag: "Unknown",
443 module: "FileSystem",
444 method: "write",
445 description: "ENOSPC: no space left on device",
446 });
447 const fileSystem = FileSystem.FileSystem.of({
448 ...fs,
449 sink: (target, options) =>
450 (stage === "download" && target.endsWith("download.zip")) ||
451 (stage === "extract" && target.endsWith(executableName))
452 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
453 : fs.sink(target, options),
454 writeFileString: (target, content, options) =>
455 stage === "active pointer" && target.endsWith("contents.tmp")
456 ? Effect.fail(noSpace)
457 : fs.writeFileString(target, content, options),
458 });
459 const { installation, stagingReleased, path } = yield* makeHarness({
460 previous: true,
461 fileSystem,
462 });
463 yield* installation.start;
464 expect((yield* terminalState(installation)).phase).toBe("failed");
465 yield* Deferred.await(stagingReleased);
466 yield* expectPreviousRelease(installation);
467 expect(
468 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
469 (name) => name.startsWith(".install-"),
470 ),
471 ).toBe(false);
472 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
473 "active.json",
474 "versions",
475 ]);
476 }),
477 );
478​
479 it.effect.each(["downloading", "extracting", "verifying"] as const)(
480 "cancels during %s and waits for open resources to close",
481 (phase) =>
482 Effect.gen(function* () {
483 const fs = yield* FileSystem.FileSystem;
484 const entered = yield* Deferred.make<void>();
485 const release = yield* Deferred.make<void>();
486 const interrupted = yield* Deferred.make<void>();
487 const barrier = Deferred.succeed(entered, undefined).pipe(
488 Effect.andThen(Deferred.await(release)),
489 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
490 );
491 const { installation, stagingReleased, path, validations } = yield* makeHarness({
492 previous: true,
493 body:
494 phase === "downloading"
495 ? Stream.concat(
496 Stream.make(completeArchive.subarray(0, 31)),
497 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
498 )
499 : undefined,
500 validate: phase === "verifying" ? () => barrier : undefined,
501 fileSystem: FileSystem.FileSystem.of({
502 ...fs,
503 sink: (target, options) =>
504 phase === "extracting" && target.endsWith(executableName)
505 ? fs
506 .sink(target, options)
507 .pipe(
508 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
509 )
510 : fs.sink(target, options),
511 }),
512 });
513 const started = yield* installation.start;
514 yield* Deferred.await(entered);
515 expect((yield* installation.state).phase).toBe(phase);
516 expect(
517 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
518 ).toBe("cancelled");
519 yield* Deferred.await(interrupted);
520 yield* Deferred.await(stagingReleased);
521 yield* expectPreviousRelease(installation);
522 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
523 expect(
524 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
525 ).toEqual([previousReleaseId]);
526 }),
527 );
528​
529 it.effect.each([
530 { name: "the committed install", restart: false },
531 { name: "a newer install", restart: true },
532 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
533 Effect.gen(function* () {
534 const fs = yield* FileSystem.FileSystem;
535 const cleanupStarted = yield* Deferred.make<void>();
536 const releaseCleanup = yield* Deferred.make<void>();
537 const nextValidationStarted = yield* Deferred.make<void>();
538 const releaseNextValidation = yield* Deferred.make<void>();
539 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
540 const cleanupError = PlatformError.systemError({
541 _tag: "PermissionDenied",
542 module: "FileSystem",
543 method: "remove",
544 description: "EPERM: pointer temp directory is in use",
545 });
546 let firstPointer = true;
547 let validationCount = 0;
548 const { installation, stagingReleased } = yield* makeHarness({
549 previous: true,
550 validate: () => {
551 validationCount += 1;
552 return validationCount === 2
553 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
554 Effect.andThen(Deferred.await(releaseNextValidation)),
555 )
556 : Effect.void;
557 },
558 fileSystem: FileSystem.FileSystem.of({
559 ...fs,
560 makeTempDirectoryScoped: (settings) => {
561 if (settings?.prefix !== "active.json." || !firstPointer) {
562 return fs.makeTempDirectoryScoped(settings);
563 }
564 firstPointer = false;
565 return Effect.fiber.pipe(
566 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
567 Effect.andThen(
568 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
569 Deferred.succeed(cleanupStarted, undefined).pipe(
570 Effect.andThen(Deferred.await(releaseCleanup)),
571 Effect.andThen(Effect.die(cleanupError)),
572 ),
573 ),
574 ),
575 );
576 },
577 }),
578 });
579 yield* Effect.gen(function* () {
580 const first = yield* installation.start;
581 yield* Deferred.await(cleanupStarted);
582 expect(yield* installation.state).toMatchObject({
583 operationId: first.operationId,
584 phase: "succeeded",
585 installedVersion: "fixture-new",
586 });
587 const current = testCase.restart ? yield* installation.start : first;
588 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
589​
590 yield* Deferred.succeed(releaseCleanup, undefined);
591 yield* Fiber.await(yield* Deferred.await(firstWorker));
592 yield* Deferred.await(stagingReleased);
593 expect(yield* installation.state).toMatchObject({
594 operationId: current.operationId,
595 phase: testCase.restart ? "verifying" : "succeeded",
596 installedVersion: "fixture-new",
597 });
598 expect((yield* installation.resolve()).version).toBe("fixture-new");
599​
600 yield* Deferred.succeed(releaseNextValidation, undefined);
601 expect(yield* terminalState(installation)).toMatchObject({
602 operationId: current.operationId,
603 phase: "succeeded",
604 installedVersion: "fixture-new",
605 });
606 }).pipe(
607 Effect.ensuring(
608 Deferred.succeed(releaseCleanup, undefined).pipe(
609 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
610 ),
611 ),
612 );
613 }),
614 );
615​
616 it.effect(
617 "shares one install across callers and keeps it alive after the caller scope closes",
618 () =>
619 Effect.gen(function* () {
620 const entered = yield* Deferred.make<void>();
621 const release = yield* Deferred.make<void>();
622 const { installation, requests, stagingReleased } = yield* makeHarness({
623 body: Stream.fromEffect(
624 Deferred.succeed(entered, undefined).pipe(
625 Effect.andThen(Deferred.await(release)),
626 Effect.as(completeArchive),
627 ),
628 ),
629 });
630 const callerScope = yield* Scope.make();
631 const started = yield* installation.start.pipe(Scope.provide(callerScope));
632 yield* Deferred.await(entered);
633 yield* Scope.close(callerScope, Exit.void);
634 const concurrent = yield* Effect.all([installation.start, installation.start], {
635 concurrency: "unbounded",
636 });
637 expect(concurrent.map((state) => state.operationId)).toEqual([
638 started.operationId,
639 started.operationId,
640 ]);
641 expect(
642 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
643 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
644 yield* Deferred.succeed(release, undefined);
645 expect((yield* terminalState(installation)).phase).toBe("succeeded");
646 yield* Deferred.await(stagingReleased);
647​
648 const next = yield* installation.start;
649 expect(next.operationId).not.toBe(started.operationId);
650 expect(
651 yield* installation
652 .cancel(started.operationId ?? "missing-operation-id")
653 .pipe(Effect.flip),
654 ).toMatchObject({ operation: "cancel" });
655 expect((yield* terminalState(installation)).phase).toBe("succeeded");
656 expect(requests).toHaveLength(1);
657 }),
658 );
659​
660 // A simulated Mac install needs POSIX execute bits, which Windows files lack.
661 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
662 "re-signs the Intel Mac runtime ad hoc and records the signed sizes",
663 () =>
664 Effect.gen(function* () {
665 const fs = yield* FileSystem.FileSystem;
666 const signed: Array<ReadonlyArray<string>> = [];
667 const spawner = ChildProcessSpawner.make((command) =>
668 Effect.gen(function* () {
669 if (!ChildProcess.isStandardCommand(command))
670 return yield* Effect.die("Unexpected spawn.");
671 const args = command.args.map(String);
672 signed.push([String(command.command), ...args]);
673 // codesign rewrites the signature, which changes each file's size.
674 for (const file of args.slice(3)) {
675 yield* fs.writeFileString(file, "signature", { flag: "a" });
676 }
677 return ChildProcessSpawner.makeHandle({
678 pid: ChildProcessSpawner.ProcessId(900_000_301),
679 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
680 isRunning: Effect.succeed(false),
681 kill: () => Effect.void,
682 unref: Effect.succeed(Effect.void),
683 stdin: Sink.drain,
684 stdout: Stream.empty,
685 stderr: Stream.empty,
686 all: Stream.empty,
687 getInputFd: () => Sink.drain,
688 getOutputFd: () => Stream.empty,
689 });
690 }).pipe(Effect.orDie),
691 );
692 const { installation, validations } = yield* makeHarness({
693 platform: "darwin",
694 arch: "x64",
695 spawner,
696 });
697 yield* installation.start;
698 expect((yield* terminalState(installation)).phase).toBe("succeeded");
699 const validated = validations[0]?.executable;
700 expect(signed).toEqual([
701 [
702 "/usr/bin/codesign",
703 "--force",
704 "--sign",
705 "-",
706 validated?.executablePath,
707 validated?.harnessPath,
708 ],
709 ]);
710 const selected = yield* installation.resolve();
711 expect(yield* fs.readFileString(selected.executablePath)).toBe(
712 `${serverContents}signature`,
713 );
714 }),
715 );
716​
717 // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons.
718 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
719 "accepts the agy CLI without a harness sibling but still requires one for other binaries",
720 () =>
721 Effect.gen(function* () {
722 const fs = yield* FileSystem.FileSystem;
723 const path = yield* Path.Path;
724 const baseDir = yield* fs
725 .makeTempDirectoryScoped({ prefix: "t3-agy-cli-test-" })
726 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
727 const cliDirectory = path.join(baseDir, "cli");
728 yield* fs.makeDirectory(cliDirectory);
729 const cli = path.join(cliDirectory, "antigravity");
730 const alias = path.join(cliDirectory, "agy");
731 const other = path.join(cliDirectory, "custom-acp");
732 yield* fs.writeFileString(cli, "cli", { mode: 0o755 });
733 yield* fs.symlink(cli, alias);
734 yield* fs.writeFileString(other, "other", { mode: 0o755 });
735 const { installation } = yield* makeHarness({ baseDir });
736​
737 expect(yield* installation.resolve(cli)).toMatchObject({
738 executablePath: cli,
739 harnessPath: null,
740 source: "override",
741 version: null,
742 });
743 expect(yield* installation.resolve(alias)).toMatchObject({
744 executablePath: alias,
745 harnessPath: null,
746 });
747 expect(yield* installation.resolve("agy", { PATH: cliDirectory })).toMatchObject({
748 executablePath: alias,
749 harnessPath: null,
750 });
751 expect(yield* installation.resolve(other).pipe(Effect.flip)).toMatchObject({
752 operation: "resolve",
753 });
754​
755 // Version-manager shims dispatch by their invoked name, so the shim path is what runs.
756 const shims = path.join(baseDir, "shims");
757 const mise = path.join(baseDir, "mise");
758 yield* fs.makeDirectory(shims);
759 yield* fs.writeFileString(mise, "mise", { mode: 0o755 });
760 yield* fs.symlink(mise, path.join(shims, "agy"));
761 expect(yield* installation.resolve("agy", { PATH: shims })).toMatchObject({
762 executablePath: path.join(shims, "agy"),
763 harnessPath: null,
764 });
765​
766 const { installation: windows } = yield* makeHarness({ baseDir, platform: "win32" });
767 for (const name of ["agy.EXE", "agy.cmd"]) {
768 const windowsDirectory = path.join(baseDir, `windows-${name}`);
769 yield* fs.makeDirectory(windowsDirectory);
770 yield* fs.writeFileString(path.join(windowsDirectory, name), "cli");
771 expect(yield* windows.resolve("agy", { PATH: windowsDirectory })).toMatchObject({
772 executablePath: path.join(windowsDirectory, name),
773 harnessPath: null,
774 });
775 }
776 }),
777 );
778​
779 // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons.
780 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
781 "honors explicit paths and reports invalid overrides without falling back",
782 () =>
783 Effect.gen(function* () {
784 const fs = yield* FileSystem.FileSystem;
785 const path = yield* Path.Path;
786 const baseDir = yield* fs
787 .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" })
788 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
789 const externalDirectory = path.join(baseDir, "external");
790 const externalExecutable = path.join(externalDirectory, executableName);
791 const externalHarness = path.join(externalDirectory, harnessName);
792 yield* fs.makeDirectory(externalDirectory);
793 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
794 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
795 const { installation } = yield* makeHarness({
796 baseDir,
797 path: externalDirectory,
798 previous: true,
799 });
800 yield* expectPreviousRelease(installation);
801 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
802 source: "managed",
803 version: previousVersion,
804 });
805 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
806 executablePath: externalExecutable,
807 source: "override",
808 managedVersionDirectory: null,
809 });
810 expect(yield* installation.resolve(executableName)).toMatchObject({
811 source: "override",
812 });
813 expect(
814 yield* installation
815 .resolve(`~/external/${executableName}`)
816 .pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)),
817 ).toMatchObject({ source: "override", executablePath: externalExecutable });
818 yield* fs.remove(externalHarness);
819 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
820 operation: "resolve",
821 });
822 expect(
823 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
824 ).toMatchObject({
825 operation: "resolve",
826 });
827 yield* expectPreviousRelease(installation);
828 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
829 yield* installation.remove();
830 expect(yield* installation.resolve()).toMatchObject({
831 source: "path",
832 executablePath: externalExecutable,
833 });
834 const isolated = yield* makeHarness({ baseDir });
835 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
836 operation: "resolve",
837 });
838 expect(
839 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
840 ).toMatchObject({
841 source: "path",
842 executablePath: externalExecutable,
843 });
844 expect(
845 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
846 ).toMatchObject({ source: "override", executablePath: externalExecutable });
847​
848 const incompleteDirectory = path.join(baseDir, "incomplete");
849 yield* fs.makeDirectory(incompleteDirectory);
850 yield* fs.writeFileString(path.join(incompleteDirectory, executableName), "no harness", {
851 mode: 0o755,
852 });
853 const shadowedPath = { PATH: `${incompleteDirectory}:${externalDirectory}` };
854 expect(yield* isolated.installation.resolve(undefined, shadowedPath)).toMatchObject({
855 source: "path",
856 executablePath: externalExecutable,
857 });
858 expect(yield* isolated.installation.resolve(executableName, shadowedPath)).toMatchObject({
859 source: "override",
860 executablePath: externalExecutable,
861 });
862 }),
863 );
864​
865 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
866 Effect.gen(function* () {
867 const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true });
868 const processScope = yield* Scope.make();
869 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
870 yield* installation.start;
871 expect((yield* terminalState(installation)).phase).toBe("succeeded");
872 yield* Deferred.await(stagingReleased);
873 const current = yield* installation.resolve();
874 expect(current.version).toBe("fixture-new");
875 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
876 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
877 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
878 yield* Scope.close(processScope, Exit.void);
879 yield* installation.remove();
880 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
881 }),
882 );
883​
884 it.effect(
885 "removes an incomplete active release before reinstalling without a PATH fallback",
886 () =>
887 Effect.gen(function* () {
888 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
889 const previous = yield* installation.resolve();
890 yield* fs.remove(previous.harnessPath!);
891 const externalDirectory = path.join(baseDir, "external");
892 yield* fs.makeDirectory(externalDirectory);
893 yield* fs.writeFileString(path.join(externalDirectory, executableName), "external server", {
894 mode: 0o755,
895 });
896 yield* fs.writeFileString(path.join(externalDirectory, harnessName), "external harness", {
897 mode: 0o755,
898 });
899 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
900 expect(yield* restarted.installation.state).toMatchObject({
901 phase: "failed",
902 installedVersion: null,
903 canRemove: true,
904 });
905 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
906 operation: "resolve",
907 });
908 yield* restarted.installation.remove();
909 expect(yield* restarted.installation.state).toMatchObject({
910 phase: "idle",
911 canRemove: false,
912 });
913 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
914 yield* restarted.installation.start;
915 expect(yield* terminalState(restarted.installation)).toMatchObject({
916 phase: "succeeded",
917 installedVersion: "fixture-new",
918 canRemove: true,
919 });
920 yield* Deferred.await(restarted.stagingReleased);
921 expect((yield* restarted.installation.resolve()).source).toBe("managed");
922 }),
923 );
924​
925 it.effect(
926 "blocks removal of custom managed paths and leaves external executables and profiles intact",
927 () =>
928 Effect.gen(function* () {
929 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
930 const managed = yield* installation.resolve();
931 const externalDirectory = path.join(baseDir, "external");
932 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
933 yield* fs.makeDirectory(externalDirectory);
934 yield* fs.makeDirectory(profileDirectory, { recursive: true });
935 const externalExecutable = path.join(externalDirectory, executableName);
936 const externalHarness = path.join(externalDirectory, harnessName);
937 const profilePath = path.join(profileDirectory, "preferences.json");
938 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
939 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
940 yield* fs.writeFileString(profilePath, "{}");
941 expect(
942 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
943 ).toMatchObject({
944 operation: "remove",
945 });
946 yield* expectPreviousRelease(installation);
947 yield* installation.remove([externalExecutable]);
948 expect(yield* installation.state).toMatchObject({
949 phase: "idle",
950 operationId: null,
951 installedVersion: null,
952 });
953 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
954 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
955 expect(yield* fs.readFileString(profilePath)).toBe("{}");
956 }),
957 );
958​
959 it.effect(
960 "reuses an immutable Windows release and preserves the pointer when rename is denied",
961 () =>
962 Effect.gen(function* () {
963 const fs = yield* FileSystem.FileSystem;
964 const path = yield* Path.Path;
965 const archive = Buffer.from(zipFixtures.windows, "base64");
966 const asset = yield* releaseAsset(archive, "win32");
967 let denyPointerRename = true;
968 const renameTargets: string[] = [];
969 const { installation, requests, validations } = yield* makeHarness({
970 previous: true,
971 platform: "win32",
972 archive,
973 fileSystem: FileSystem.FileSystem.of({
974 ...fs,
975 rename: (source, target) => {
976 renameTargets.push(target);
977 return denyPointerRename
978 ? Effect.fail(
979 PlatformError.systemError({
980 _tag: "PermissionDenied",
981 module: "FileSystem",
982 method: "rename",
983 pathOrDescriptor: target,
984 description: "EPERM: file is in use",
985 }),
986 )
987 : fs.rename(source, target);
988 },
989 }),
990 });
991 yield* writeRelease(installation.managedDirectory, asset, false);
992 yield* installation.start;
993 expect((yield* terminalState(installation)).phase).toBe("failed");
994 yield* expectPreviousRelease(installation);
995 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
996​
997 denyPointerRename = false;
998 yield* installation.start;
999 expect((yield* terminalState(installation)).phase).toBe("succeeded");
1000 expect((yield* installation.resolve()).version).toBe("fixture-new");
1001 expect(requests).toEqual([]);
1002 expect(validations).toHaveLength(2);
1003 expect(renameTargets).toEqual([
1004 path.join(installation.managedDirectory, "active.json"),
1005 path.join(installation.managedDirectory, "active.json"),
1006 ]);
1007 }),
1008 );
1009​
1010 it.effect("reports unsupported hosts without downloading or changing state", () =>
1011 Effect.gen(function* () {
1012 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
1013 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
1014 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
1015 operation: "resolve",
1016 });
1017 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
1018 expect(requests).toEqual([]);
1019 }),
1020 );
1021});