Open History to see the last commit
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, 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+gUAAAAFAAAABIAAAAAAAAAAAAAAO2BAAAAAGFneV9hY3Bfc2VydmVyLnBhclBLAQIUAxQAAAAIAAAAIl1fcgMpEAAAAA4AAAAVAAAAAAAAAAAAAADtgUQAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWxQSwUGAAAAAA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SwECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAGQAAAAAAAAAAAAAA7YFEAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsLmV4ZVBLBQYAAAAAAgACAIcAAACLAAAAAAA=",
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}
130
131const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
132 options: HarnessOptions = {},
133) {
134 const fs = yield* FileSystem.FileSystem;
135 const path = yield* Path.Path;
136 const baseDir =
137 options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
138 const platform = options.platform ?? hostPlatform;
139 const arch = options.arch ?? "x64";
140 const archive = options.archive ?? completeArchive;
141 const asset =
142 options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset;
143 const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`);
144 if (options.previous) {
145 yield* writeRelease(managedDirectory, {
146 ...(yield* releaseAsset(archive, platform)),
147 sha256: previousReleaseId,
148 version: previousVersion,
149 });
150 }
151 const stagingReleased = yield* Deferred.make<void>();
152 const requests: string[] = [];
153 const validations: Array<{
154 executable: AntigravityInstallation.AntigravityExecutable;
155 version: string;
156 }> = [];
157 const installationFs = options.fileSystem ?? fs;
158 const trackedFs = FileSystem.FileSystem.of({
159 ...installationFs,
160 makeTempDirectoryScoped: (settings) =>
161 settings?.prefix === ".install-"
162 ? Effect.acquireRelease(installationFs.makeTempDirectory(settings), (directory) =>
163 fs
164 .remove(directory, { recursive: true, force: true })
165 .pipe(Effect.orDie, Effect.andThen(Deferred.succeed(stagingReleased, undefined))),
166 )
167 : installationFs.makeTempDirectoryScoped(settings),
168 });
169 const installation = yield* AntigravityInstallation.makeAntigravityInstallation({
170 baseDir,
171 releaseAsset: asset,
172 ...(options.useDefaultValidation
173 ? {}
174 : {
175 validate: (executable: AntigravityInstallation.AntigravityExecutable, version: string) =>
176 Effect.sync(() => validations.push({ executable, version })).pipe(
177 Effect.andThen(options.validate?.(executable, version) ?? Effect.void),
178 ),
179 }),
180 }).pipe(
181 options.spawner
182 ? Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, options.spawner)
183 : (effect) => effect,
184 Effect.provideService(FileSystem.FileSystem, trackedFs),
185 Effect.provideService(HostProcess.Platform, platform),
186 Effect.provideService(HostProcess.Architecture, arch),
187 Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }),
188 Effect.provideService(
189 HttpClient.HttpClient,
190 HttpClient.make((request) =>
191 Effect.sync(() => {
192 requests.push(request.url);
193 const response = HttpClientResponse.fromWeb(
194 request,
195 new Response(null, {
196 headers: {
197 ...(options.contentLength === undefined
198 ? {}
199 : { "content-length": String(options.contentLength) }),
200 ...(options.contentEncoding === undefined
201 ? {}
202 : { "content-encoding": options.contentEncoding }),
203 },
204 }),
205 );
206 return Object.defineProperty(response, "stream", {
207 value:
208 options.body ??
209 Stream.make(
210 archive.subarray(0, 31),
211 archive.subarray(31, 149),
212 archive.subarray(149),
213 ),
214 });
215 }),
216 ),
217 ),
218 );
219 return { installation, fs, path, baseDir, requests, validations, stagingReleased };
220});
221
222const terminalState = (installation: AntigravityInstallation.AntigravityInstallation["Service"]) =>
223 installation.changes.pipe(
224 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
225 Stream.runHead,
226 Effect.map(Option.getOrThrow),
227 );
228
229const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease")(function* (
230 installation: AntigravityInstallation.AntigravityInstallation["Service"],
231) {
232 const fs = yield* FileSystem.FileSystem;
233 const path = yield* Path.Path;
234 const resolved = yield* installation.resolve();
235 expect(resolved.version).toBe(previousVersion);
236 expect(resolved.managedVersionDirectory).toBe(
237 path.join(installation.managedDirectory, "versions", previousReleaseId),
238 );
239 expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents);
240 expect(yield* fs.readFileString(resolved.harnessPath!)).toBe(harnessContents);
241 expect((yield* installation.state).installedVersion).toBe(previousVersion);
242});
243
244it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity installation", (it) => {
245 it.effect("reports missing Node before downloading the standalone provider runtime", () =>
246 Effect.gen(function* () {
247 const { installation, requests, validations } = yield* makeHarness();
248 yield* installation.start;
249 expect(yield* terminalState(installation)).toMatchObject({
250 phase: "failed",
251 message: expect.stringContaining("Install Node.js"),
252 });
253 expect(requests).toEqual([]);
254 expect(validations).toEqual([]);
255 }).pipe(Effect.provideService(HostProcess.IsExecutable, true)),
256 );
257
258 it.effect("verifies both files before activating a streamed download", () =>
259 Effect.gen(function* () {
260 const enteredValidation = yield* Deferred.make<void>();
261 const finishValidation = yield* Deferred.make<void>();
262 const { installation, fs, path, validations, requests, stagingReleased } = yield* makeHarness(
263 {
264 previous: true,
265 validate: () =>
266 Deferred.succeed(enteredValidation, undefined).pipe(
267 Effect.andThen(Deferred.await(finishValidation)),
268 ),
269 },
270 );
271 const initial = yield* installation.changes.pipe(
272 Stream.runHead,
273 Effect.map(Option.getOrThrow),
274 );
275 expect(initial).toMatchObject({ phase: "idle", installedVersion: previousVersion });
276 const started = yield* installation.start;
277 expect(started).toMatchObject({ phase: "downloading", downloadedBytes: 0 });
278 yield* Deferred.await(enteredValidation);
279 yield* expectPreviousRelease(installation);
280 const validation = validations[0];
281 expect(validation?.version).toBe("fixture-new");
282 if (!validation) return yield* Effect.die("Expected runtime validation.");
283 expect(yield* fs.readFileString(validation.executable.executablePath)).toBe(serverContents);
284 expect(yield* fs.readFileString(validation.executable.harnessPath!)).toBe(harnessContents);
285
286 yield* Deferred.succeed(finishValidation, undefined);
287 expect(yield* terminalState(installation)).toMatchObject({
288 phase: "succeeded",
289 operationId: started.operationId,
290 downloadedBytes: completeArchive.byteLength,
291 installedVersion: "fixture-new",
292 });
293 yield* Deferred.await(stagingReleased);
294 const selected = yield* installation.resolve();
295 expect(selected).toMatchObject({ source: "managed", version: "fixture-new" });
296 expect(path.dirname(selected.harnessPath!)).toBe(path.dirname(selected.executablePath));
297 expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents);
298 expect(yield* fs.readFileString(selected.harnessPath!)).toBe(harnessContents);
299 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
300 expect.arrayContaining([previousReleaseId, (yield* releaseAsset()).sha256]),
301 );
302 expect(requests).toEqual([(yield* releaseAsset()).url]);
303 }),
304 );
305
306 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
307 Effect.gen(function* () {
308 // dl.google.com reports the gzip-encoded size; byte and hash checks use the decoded stream.
309 const { installation, validations } = yield* makeHarness({
310 contentLength: completeArchive.byteLength - 1_000,
311 contentEncoding: "gzip",
312 });
313 yield* installation.start;
314 const state = yield* terminalState(installation);
315 expect(state.phase).toBe("succeeded");
316 expect(validations).toHaveLength(1);
317 }),
318 );
319
320 it.effect.each([
321 { name: "checksum mismatch", completeAsset: { sha256: "2".repeat(64) } },
322 { name: "short download", archive: completeArchive.subarray(0, -1), completeAsset: {} },
323 {
324 name: "oversized download",
325 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
326 completeAsset: {},
327 },
328 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
329 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
330 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
331 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
332 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
333 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
334 ])("rejects $name before runtime validation", ({ completeAsset, ...options }) =>
335 Effect.gen(function* () {
336 const asset =
337 completeAsset === undefined ? undefined : { ...(yield* releaseAsset()), ...completeAsset };
338 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
339 ...options,
340 ...(asset === undefined ? {} : { asset }),
341 previous: true,
342 });
343 yield* installation.start;
344 const state = yield* terminalState(installation);
345 expect(state.phase).toBe("failed");
346 expect(state.message).toBeTruthy();
347 expect(validations).toEqual([]);
348 yield* Deferred.await(stagingReleased);
349 yield* expectPreviousRelease(installation);
350 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
351 [previousReleaseId],
352 );
353 }),
354 );
355
356 it.effect.each(["download", "extract", "active pointer"] as const)(
357 "preserves the old runtime after an ENOSPC error during %s",
358 (stage) =>
359 Effect.gen(function* () {
360 const fs = yield* FileSystem.FileSystem;
361 const noSpace = PlatformError.systemError({
362 _tag: "Unknown",
363 module: "FileSystem",
364 method: "write",
365 description: "ENOSPC: no space left on device",
366 });
367 const fileSystem = FileSystem.FileSystem.of({
368 ...fs,
369 sink: (target, options) =>
370 (stage === "download" && target.endsWith("download.zip")) ||
371 (stage === "extract" && target.endsWith(executableName))
372 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
373 : fs.sink(target, options),
374 writeFileString: (target, content, options) =>
375 stage === "active pointer" && target.endsWith("contents.tmp")
376 ? Effect.fail(noSpace)
377 : fs.writeFileString(target, content, options),
378 });
379 const { installation, stagingReleased, path } = yield* makeHarness({
380 previous: true,
381 fileSystem,
382 });
383 yield* installation.start;
384 expect((yield* terminalState(installation)).phase).toBe("failed");
385 yield* Deferred.await(stagingReleased);
386 yield* expectPreviousRelease(installation);
387 expect(
388 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
389 (name) => name.startsWith(".install-"),
390 ),
391 ).toBe(false);
392 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
393 "active.json",
394 "versions",
395 ]);
396 }),
397 );
398
399 it.effect.each(["downloading", "extracting", "verifying"] as const)(
400 "cancels during %s and waits for open resources to close",
401 (phase) =>
402 Effect.gen(function* () {
403 const fs = yield* FileSystem.FileSystem;
404 const entered = yield* Deferred.make<void>();
405 const release = yield* Deferred.make<void>();
406 const interrupted = yield* Deferred.make<void>();
407 const barrier = Deferred.succeed(entered, undefined).pipe(
408 Effect.andThen(Deferred.await(release)),
409 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
410 );
411 const { installation, stagingReleased, path, validations } = yield* makeHarness({
412 previous: true,
413 body:
414 phase === "downloading"
415 ? Stream.concat(
416 Stream.make(completeArchive.subarray(0, 31)),
417 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
418 )
419 : undefined,
420 validate: phase === "verifying" ? () => barrier : undefined,
421 fileSystem: FileSystem.FileSystem.of({
422 ...fs,
423 sink: (target, options) =>
424 phase === "extracting" && target.endsWith(executableName)
425 ? fs
426 .sink(target, options)
427 .pipe(
428 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
429 )
430 : fs.sink(target, options),
431 }),
432 });
433 const started = yield* installation.start;
434 yield* Deferred.await(entered);
435 expect((yield* installation.state).phase).toBe(phase);
436 expect(
437 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
438 ).toBe("cancelled");
439 yield* Deferred.await(interrupted);
440 yield* Deferred.await(stagingReleased);
441 yield* expectPreviousRelease(installation);
442 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
443 expect(
444 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
445 ).toEqual([previousReleaseId]);
446 }),
447 );
448
449 it.effect.each([
450 { name: "the committed install", restart: false },
451 { name: "a newer install", restart: true },
452 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
453 Effect.gen(function* () {
454 const fs = yield* FileSystem.FileSystem;
455 const cleanupStarted = yield* Deferred.make<void>();
456 const releaseCleanup = yield* Deferred.make<void>();
457 const nextValidationStarted = yield* Deferred.make<void>();
458 const releaseNextValidation = yield* Deferred.make<void>();
459 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
460 const cleanupError = PlatformError.systemError({
461 _tag: "PermissionDenied",
462 module: "FileSystem",
463 method: "remove",
464 description: "EPERM: pointer temp directory is in use",
465 });
466 let firstPointer = true;
467 let validationCount = 0;
468 const { installation, stagingReleased } = yield* makeHarness({
469 previous: true,
470 validate: () => {
471 validationCount += 1;
472 return validationCount === 2
473 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
474 Effect.andThen(Deferred.await(releaseNextValidation)),
475 )
476 : Effect.void;
477 },
478 fileSystem: FileSystem.FileSystem.of({
479 ...fs,
480 makeTempDirectoryScoped: (settings) => {
481 if (settings?.prefix !== "active.json." || !firstPointer) {
482 return fs.makeTempDirectoryScoped(settings);
483 }
484 firstPointer = false;
485 return Effect.fiber.pipe(
486 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
487 Effect.andThen(
488 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
489 Deferred.succeed(cleanupStarted, undefined).pipe(
490 Effect.andThen(Deferred.await(releaseCleanup)),
491 Effect.andThen(Effect.die(cleanupError)),
492 ),
493 ),
494 ),
495 );
496 },
497 }),
498 });
499 yield* Effect.gen(function* () {
500 const first = yield* installation.start;
501 yield* Deferred.await(cleanupStarted);
502 expect(yield* installation.state).toMatchObject({
503 operationId: first.operationId,
504 phase: "succeeded",
505 installedVersion: "fixture-new",
506 });
507 const current = testCase.restart ? yield* installation.start : first;
508 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
509
510 yield* Deferred.succeed(releaseCleanup, undefined);
511 yield* Fiber.await(yield* Deferred.await(firstWorker));
512 yield* Deferred.await(stagingReleased);
513 expect(yield* installation.state).toMatchObject({
514 operationId: current.operationId,
515 phase: testCase.restart ? "verifying" : "succeeded",
516 installedVersion: "fixture-new",
517 });
518 expect((yield* installation.resolve()).version).toBe("fixture-new");
519
520 yield* Deferred.succeed(releaseNextValidation, undefined);
521 expect(yield* terminalState(installation)).toMatchObject({
522 operationId: current.operationId,
523 phase: "succeeded",
524 installedVersion: "fixture-new",
525 });
526 }).pipe(
527 Effect.ensuring(
528 Deferred.succeed(releaseCleanup, undefined).pipe(
529 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
530 ),
531 ),
532 );
533 }),
534 );
535
536 it.effect(
537 "shares one install across callers and keeps it alive after the caller scope closes",
538 () =>
539 Effect.gen(function* () {
540 const entered = yield* Deferred.make<void>();
541 const release = yield* Deferred.make<void>();
542 const { installation, requests, stagingReleased } = yield* makeHarness({
543 body: Stream.fromEffect(
544 Deferred.succeed(entered, undefined).pipe(
545 Effect.andThen(Deferred.await(release)),
546 Effect.as(completeArchive),
547 ),
548 ),
549 });
550 const callerScope = yield* Scope.make();
551 const started = yield* installation.start.pipe(Scope.provide(callerScope));
552 yield* Deferred.await(entered);
553 yield* Scope.close(callerScope, Exit.void);
554 const concurrent = yield* Effect.all([installation.start, installation.start], {
555 concurrency: "unbounded",
556 });
557 expect(concurrent.map((state) => state.operationId)).toEqual([
558 started.operationId,
559 started.operationId,
560 ]);
561 expect(
562 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
563 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
564 yield* Deferred.succeed(release, undefined);
565 expect((yield* terminalState(installation)).phase).toBe("succeeded");
566 yield* Deferred.await(stagingReleased);
567
568 const next = yield* installation.start;
569 expect(next.operationId).not.toBe(started.operationId);
570 expect(
571 yield* installation
572 .cancel(started.operationId ?? "missing-operation-id")
573 .pipe(Effect.flip),
574 ).toMatchObject({ operation: "cancel" });
575 expect((yield* terminalState(installation)).phase).toBe("succeeded");
576 expect(requests).toHaveLength(1);
577 }),
578 );
579
580 // A simulated Mac install needs POSIX execute bits, which Windows files lack.
581 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
582 "re-signs the Intel Mac runtime ad hoc and records the signed sizes",
583 () =>
584 Effect.gen(function* () {
585 const fs = yield* FileSystem.FileSystem;
586 const signed: Array<ReadonlyArray<string>> = [];
587 const spawner = ChildProcessSpawner.make((command) =>
588 Effect.gen(function* () {
589 if (!ChildProcess.isStandardCommand(command))
590 return yield* Effect.die("Unexpected spawn.");
591 const args = command.args.map(String);
592 signed.push([String(command.command), ...args]);
593 // codesign rewrites the signature, which changes each file's size.
594 for (const file of args.slice(3)) {
595 yield* fs.writeFileString(file, "signature", { flag: "a" });
596 }
597 return ChildProcessSpawner.makeHandle({
598 pid: ChildProcessSpawner.ProcessId(900_000_301),
599 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
600 isRunning: Effect.succeed(false),
601 kill: () => Effect.void,
602 unref: Effect.succeed(Effect.void),
603 stdin: Sink.drain,
604 stdout: Stream.empty,
605 stderr: Stream.empty,
606 all: Stream.empty,
607 getInputFd: () => Sink.drain,
608 getOutputFd: () => Stream.empty,
609 });
610 }).pipe(Effect.orDie),
611 );
612 const { installation, validations } = yield* makeHarness({
613 platform: "darwin",
614 arch: "x64",
615 spawner,
616 });
617 yield* installation.start;
618 expect((yield* terminalState(installation)).phase).toBe("succeeded");
619 const validated = validations[0]?.executable;
620 expect(signed).toEqual([
621 [
622 "/usr/bin/codesign",
623 "--force",
624 "--sign",
625 "-",
626 validated?.executablePath,
627 validated?.harnessPath,
628 ],
629 ]);
630 const selected = yield* installation.resolve();
631 expect(yield* fs.readFileString(selected.executablePath)).toBe(
632 `${serverContents}signature`,
633 );
634 }),
635 );
636
637 // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons.
638 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
639 "accepts the agy CLI without a harness sibling but still requires one for other binaries",
640 () =>
641 Effect.gen(function* () {
642 const fs = yield* FileSystem.FileSystem;
643 const path = yield* Path.Path;
644 const baseDir = yield* fs
645 .makeTempDirectoryScoped({ prefix: "t3-agy-cli-test-" })
646 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
647 const cliDirectory = path.join(baseDir, "cli");
648 yield* fs.makeDirectory(cliDirectory);
649 const cli = path.join(cliDirectory, "antigravity");
650 const alias = path.join(cliDirectory, "agy");
651 const other = path.join(cliDirectory, "custom-acp");
652 yield* fs.writeFileString(cli, "cli", { mode: 0o755 });
653 yield* fs.symlink(cli, alias);
654 yield* fs.writeFileString(other, "other", { mode: 0o755 });
655 const { installation } = yield* makeHarness({ baseDir });
656
657 expect(yield* installation.resolve(cli)).toMatchObject({
658 executablePath: cli,
659 harnessPath: null,
660 source: "override",
661 version: null,
662 });
663 expect(yield* installation.resolve(alias)).toMatchObject({
664 executablePath: alias,
665 harnessPath: null,
666 });
667 expect(yield* installation.resolve("agy", { PATH: cliDirectory })).toMatchObject({
668 executablePath: alias,
669 harnessPath: null,
670 });
671 expect(yield* installation.resolve(other).pipe(Effect.flip)).toMatchObject({
672 operation: "resolve",
673 });
674
675 // Version-manager shims dispatch by their invoked name, so the shim path is what runs.
676 const shims = path.join(baseDir, "shims");
677 const mise = path.join(baseDir, "mise");
678 yield* fs.makeDirectory(shims);
679 yield* fs.writeFileString(mise, "mise", { mode: 0o755 });
680 yield* fs.symlink(mise, path.join(shims, "agy"));
681 expect(yield* installation.resolve("agy", { PATH: shims })).toMatchObject({
682 executablePath: path.join(shims, "agy"),
683 harnessPath: null,
684 });
685
686 const { installation: windows } = yield* makeHarness({ baseDir, platform: "win32" });
687 for (const name of ["agy.EXE", "agy.cmd"]) {
688 const windowsDirectory = path.join(baseDir, `windows-${name}`);
689 yield* fs.makeDirectory(windowsDirectory);
690 yield* fs.writeFileString(path.join(windowsDirectory, name), "cli");
691 expect(yield* windows.resolve("agy", { PATH: windowsDirectory })).toMatchObject({
692 executablePath: path.join(windowsDirectory, name),
693 harnessPath: null,
694 });
695 }
696 }),
697 );
698
699 // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons.
700 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
701 "honors explicit paths and reports invalid overrides without falling back",
702 () =>
703 Effect.gen(function* () {
704 const fs = yield* FileSystem.FileSystem;
705 const path = yield* Path.Path;
706 const baseDir = yield* fs
707 .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" })
708 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
709 const externalDirectory = path.join(baseDir, "external");
710 const externalExecutable = path.join(externalDirectory, executableName);
711 const externalHarness = path.join(externalDirectory, harnessName);
712 yield* fs.makeDirectory(externalDirectory);
713 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
714 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
715 const { installation } = yield* makeHarness({
716 baseDir,
717 path: externalDirectory,
718 previous: true,
719 });
720 yield* expectPreviousRelease(installation);
721 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
722 source: "managed",
723 version: previousVersion,
724 });
725 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
726 executablePath: externalExecutable,
727 source: "override",
728 managedVersionDirectory: null,
729 });
730 expect(yield* installation.resolve(executableName)).toMatchObject({
731 source: "override",
732 });
733 yield* fs.remove(externalHarness);
734 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
735 operation: "resolve",
736 });
737 expect(
738 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
739 ).toMatchObject({
740 operation: "resolve",
741 });
742 yield* expectPreviousRelease(installation);
743 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
744 yield* installation.remove();
745 expect(yield* installation.resolve()).toMatchObject({
746 source: "path",
747 executablePath: externalExecutable,
748 });
749 const isolated = yield* makeHarness({ baseDir });
750 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
751 operation: "resolve",
752 });
753 expect(
754 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
755 ).toMatchObject({
756 source: "path",
757 executablePath: externalExecutable,
758 });
759 expect(
760 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
761 ).toMatchObject({ source: "override", executablePath: externalExecutable });
762
763 const incompleteDirectory = path.join(baseDir, "incomplete");
764 yield* fs.makeDirectory(incompleteDirectory);
765 yield* fs.writeFileString(path.join(incompleteDirectory, executableName), "no harness", {
766 mode: 0o755,
767 });
768 const shadowedPath = { PATH: `${incompleteDirectory}:${externalDirectory}` };
769 expect(yield* isolated.installation.resolve(undefined, shadowedPath)).toMatchObject({
770 source: "path",
771 executablePath: externalExecutable,
772 });
773 expect(yield* isolated.installation.resolve(executableName, shadowedPath)).toMatchObject({
774 source: "override",
775 executablePath: externalExecutable,
776 });
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 = yield* 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});