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 it.effect("re-signs the Intel Mac runtime ad hoc and records the signed sizes", () =>
581 Effect.gen(function* () {
582 const fs = yield* FileSystem.FileSystem;
583 const signed: Array<ReadonlyArray<string>> = [];
584 const spawner = ChildProcessSpawner.make((command) =>
585 Effect.gen(function* () {
586 if (!ChildProcess.isStandardCommand(command))
587 return yield* Effect.die("Unexpected spawn.");
588 const args = command.args.map(String);
589 signed.push([String(command.command), ...args]);
590 // codesign rewrites the signature, which changes each file's size.
591 for (const file of args.slice(3)) {
592 yield* fs.writeFileString(file, "signature", { flag: "a" });
593 }
594 return ChildProcessSpawner.makeHandle({
595 pid: ChildProcessSpawner.ProcessId(900_000_301),
596 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
597 isRunning: Effect.succeed(false),
598 kill: () => Effect.void,
599 unref: Effect.succeed(Effect.void),
600 stdin: Sink.drain,
601 stdout: Stream.empty,
602 stderr: Stream.empty,
603 all: Stream.empty,
604 getInputFd: () => Sink.drain,
605 getOutputFd: () => Stream.empty,
606 });
607 }).pipe(Effect.orDie),
608 );
609 const { installation, validations } = yield* makeHarness({
610 platform: "darwin",
611 arch: "x64",
612 spawner,
613 });
614 yield* installation.start;
615 expect((yield* terminalState(installation)).phase).toBe("succeeded");
616 const validated = validations[0]?.executable;
617 expect(signed).toEqual([
618 [
619 "/usr/bin/codesign",
620 "--force",
621 "--sign",
622 "-",
623 validated?.executablePath,
624 validated?.harnessPath,
625 ],
626 ]);
627 const selected = yield* installation.resolve();
628 expect(yield* fs.readFileString(selected.executablePath)).toBe(`${serverContents}signature`);
629 }),
630 );
631
632 // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons.
633 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
634 "honors explicit paths and reports invalid overrides without falling back",
635 () =>
636 Effect.gen(function* () {
637 const fs = yield* FileSystem.FileSystem;
638 const path = yield* Path.Path;
639 const baseDir = yield* fs
640 .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" })
641 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
642 const externalDirectory = path.join(baseDir, "external");
643 const externalExecutable = path.join(externalDirectory, executableName);
644 const externalHarness = path.join(externalDirectory, harnessName);
645 yield* fs.makeDirectory(externalDirectory);
646 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
647 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
648 const { installation } = yield* makeHarness({
649 baseDir,
650 path: externalDirectory,
651 previous: true,
652 });
653 yield* expectPreviousRelease(installation);
654 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
655 source: "managed",
656 version: previousVersion,
657 });
658 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
659 executablePath: externalExecutable,
660 source: "override",
661 managedVersionDirectory: null,
662 });
663 expect(yield* installation.resolve(executableName)).toMatchObject({
664 source: "override",
665 });
666 yield* fs.remove(externalHarness);
667 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
668 operation: "resolve",
669 });
670 expect(
671 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
672 ).toMatchObject({
673 operation: "resolve",
674 });
675 yield* expectPreviousRelease(installation);
676 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
677 yield* installation.remove();
678 expect(yield* installation.resolve()).toMatchObject({
679 source: "path",
680 executablePath: externalExecutable,
681 });
682 const isolated = yield* makeHarness({ baseDir });
683 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
684 operation: "resolve",
685 });
686 expect(
687 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
688 ).toMatchObject({
689 source: "path",
690 executablePath: externalExecutable,
691 });
692 expect(
693 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
694 ).toMatchObject({ source: "override", executablePath: externalExecutable });
695 }),
696 );
697
698 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
699 Effect.gen(function* () {
700 const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true });
701 const processScope = yield* Scope.make();
702 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
703 yield* installation.start;
704 expect((yield* terminalState(installation)).phase).toBe("succeeded");
705 yield* Deferred.await(stagingReleased);
706 const current = yield* installation.resolve();
707 expect(current.version).toBe("fixture-new");
708 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
709 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
710 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
711 yield* Scope.close(processScope, Exit.void);
712 yield* installation.remove();
713 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
714 }),
715 );
716
717 it.effect(
718 "removes an incomplete active release before reinstalling without a PATH fallback",
719 () =>
720 Effect.gen(function* () {
721 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
722 const previous = yield* installation.resolve();
723 yield* fs.remove(previous.harnessPath);
724 const externalDirectory = path.join(baseDir, "external");
725 yield* fs.makeDirectory(externalDirectory);
726 yield* fs.writeFileString(path.join(externalDirectory, executableName), "external server", {
727 mode: 0o755,
728 });
729 yield* fs.writeFileString(path.join(externalDirectory, harnessName), "external harness", {
730 mode: 0o755,
731 });
732 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
733 expect(yield* restarted.installation.state).toMatchObject({
734 phase: "failed",
735 installedVersion: null,
736 canRemove: true,
737 });
738 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
739 operation: "resolve",
740 });
741 yield* restarted.installation.remove();
742 expect(yield* restarted.installation.state).toMatchObject({
743 phase: "idle",
744 canRemove: false,
745 });
746 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
747 yield* restarted.installation.start;
748 expect(yield* terminalState(restarted.installation)).toMatchObject({
749 phase: "succeeded",
750 installedVersion: "fixture-new",
751 canRemove: true,
752 });
753 yield* Deferred.await(restarted.stagingReleased);
754 expect((yield* restarted.installation.resolve()).source).toBe("managed");
755 }),
756 );
757
758 it.effect(
759 "blocks removal of custom managed paths and leaves external executables and profiles intact",
760 () =>
761 Effect.gen(function* () {
762 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
763 const managed = yield* installation.resolve();
764 const externalDirectory = path.join(baseDir, "external");
765 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
766 yield* fs.makeDirectory(externalDirectory);
767 yield* fs.makeDirectory(profileDirectory, { recursive: true });
768 const externalExecutable = path.join(externalDirectory, executableName);
769 const externalHarness = path.join(externalDirectory, harnessName);
770 const profilePath = path.join(profileDirectory, "preferences.json");
771 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
772 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
773 yield* fs.writeFileString(profilePath, "{}");
774 expect(
775 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
776 ).toMatchObject({
777 operation: "remove",
778 });
779 yield* expectPreviousRelease(installation);
780 yield* installation.remove([externalExecutable]);
781 expect(yield* installation.state).toMatchObject({
782 phase: "idle",
783 operationId: null,
784 installedVersion: null,
785 });
786 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
787 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
788 expect(yield* fs.readFileString(profilePath)).toBe("{}");
789 }),
790 );
791
792 it.effect(
793 "reuses an immutable Windows release and preserves the pointer when rename is denied",
794 () =>
795 Effect.gen(function* () {
796 const fs = yield* FileSystem.FileSystem;
797 const path = yield* Path.Path;
798 const archive = Buffer.from(zipFixtures.windows, "base64");
799 const asset = yield* releaseAsset(archive, "win32");
800 let denyPointerRename = true;
801 const renameTargets: string[] = [];
802 const { installation, requests, validations } = yield* makeHarness({
803 previous: true,
804 platform: "win32",
805 archive,
806 fileSystem: FileSystem.FileSystem.of({
807 ...fs,
808 rename: (source, target) => {
809 renameTargets.push(target);
810 return denyPointerRename
811 ? Effect.fail(
812 PlatformError.systemError({
813 _tag: "PermissionDenied",
814 module: "FileSystem",
815 method: "rename",
816 pathOrDescriptor: target,
817 description: "EPERM: file is in use",
818 }),
819 )
820 : fs.rename(source, target);
821 },
822 }),
823 });
824 yield* writeRelease(installation.managedDirectory, asset, false);
825 yield* installation.start;
826 expect((yield* terminalState(installation)).phase).toBe("failed");
827 yield* expectPreviousRelease(installation);
828 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
829
830 denyPointerRename = false;
831 yield* installation.start;
832 expect((yield* terminalState(installation)).phase).toBe("succeeded");
833 expect((yield* installation.resolve()).version).toBe("fixture-new");
834 expect(requests).toEqual([]);
835 expect(validations).toHaveLength(2);
836 expect(renameTargets).toEqual([
837 path.join(installation.managedDirectory, "active.json"),
838 path.join(installation.managedDirectory, "active.json"),
839 ]);
840 }),
841 );
842
843 it.effect("reports unsupported hosts without downloading or changing state", () =>
844 Effect.gen(function* () {
845 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
846 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
847 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
848 operation: "resolve",
849 });
850 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
851 expect(requests).toEqual([]);
852 }),
853 );
854});