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

AntigravityInstallation.test.ts

796 lines35.5 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, HttpClientResponse } from "effect/http";
21​
22import * as AntigravityInstallation from "./AntigravityInstallation.ts";
23import { type AntigravityReleaseAsset } from "./antigravityRelease.ts";
24​
25const serverContents = "antigravity runtime\n";
26const harnessContents = "local harness\n";
27const previousReleaseId = "1".repeat(64);
28const previousVersion = "fixture-old";
29const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
30​
31const zipFixtures = {
32 complete:
33 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAAAFAAAABIAAAAAAAAAAAAAAO2BAAAAAGFneV9hY3Bfc2VydmVyLnBhclBLAQIUAxQAAAAIAAAAIl1fcgMpEAAAAA4AAAAVAAAAAAAAAAAAAADtgUQAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWxQSwUGAAAAAAI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wECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAGQAAAAAAAAAAAAAA7YFEAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsLmV4ZVBLBQYAAAAAAgACAIcAAACLAAAAAAA=",
46};
47​
48// Linux platform mocks cannot enforce POSIX exec bits on NTFS; use the host platform.
49const hostPlatform: NodeJS.Platform =
50 HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux";
51const completeArchive = Buffer.from(
52 hostPlatform === "win32" ? zipFixtures.windows : zipFixtures.complete,
53 "base64",
54);
55const executableName = hostPlatform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par";
56const harnessName =
57 hostPlatform === "win32" ? "localharness_external.exe" : "localharness_external";
58​
59const releaseAsset = Effect.fn("test.antigravityReleaseAsset")(function* (
60 archive: Uint8Array = completeArchive,
61 platform: NodeJS.Platform = hostPlatform,
62) {
63 const digest = yield* Digest.Digest;
64 return {
65 version: "fixture-new",
66 url: "https://dl.google.com/antigravity-test.zip",
67 sha256: Hex.encode(yield* digest.digest(Digest.sha256, archive).pipe(Effect.orDie)),
68 archiveBytes: archive.byteLength,
69 executable: {
70 name: platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par",
71 bytes: Buffer.byteLength(serverContents),
72 },
73 harness: {
74 name: platform === "win32" ? "localharness_external.exe" : "localharness_external",
75 bytes: Buffer.byteLength(harnessContents),
76 },
77 } satisfies AntigravityReleaseAsset;
78});
79​
80const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* (
81 managedDirectory: string,
82 asset: AntigravityReleaseAsset,
83 active = true,
84) {
85 const fs = yield* FileSystem.FileSystem;
86 const path = yield* Path.Path;
87 const directory = path.join(managedDirectory, "versions", asset.sha256);
88 yield* fs.makeDirectory(directory, { recursive: true });
89 yield* fs.writeFileString(path.join(directory, asset.executable.name), serverContents, {
90 mode: 0o755,
91 });
92 yield* fs.writeFileString(path.join(directory, asset.harness.name), harnessContents, {
93 mode: 0o755,
94 });
95 yield* fs.writeFileString(
96 path.join(directory, ".install-complete.json"),
97 encodeJsonString({
98 releaseId: asset.sha256,
99 version: asset.version,
100 executable: asset.executable,
101 harness: asset.harness,
102 }),
103 );
104 if (active) {
105 yield* fs.writeFileString(
106 path.join(managedDirectory, "active.json"),
107 encodeJsonString({ releaseId: asset.sha256 }),
108 );
109 }
110});
111​
112interface HarnessOptions {
113 readonly baseDir?: string;
114 readonly asset?: AntigravityReleaseAsset | null;
115 readonly archive?: Buffer;
116 readonly body?: Stream.Stream<Uint8Array> | undefined;
117 readonly contentLength?: number;
118 readonly contentEncoding?: string;
119 readonly platform?: NodeJS.Platform;
120 readonly arch?: NodeJS.Architecture;
121 readonly path?: string;
122 readonly previous?: boolean;
123 readonly fileSystem?: FileSystem.FileSystem;
124 readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"];
125 readonly useDefaultValidation?: boolean;
127​
128const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
129 options: HarnessOptions = {},
130) {
131 const fs = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const baseDir =
134 options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
135 const platform = options.platform ?? hostPlatform;
136 const arch = options.arch ?? "x64";
137 const archive = options.archive ?? completeArchive;
138 const asset =
139 options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset;
140 const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`);
141 if (options.previous) {
142 yield* writeRelease(managedDirectory, {
143 ...(yield* releaseAsset(archive, platform)),
144 sha256: previousReleaseId,
145 version: previousVersion,
146 });
147 }
148 const stagingReleased = yield* Deferred.make<void>();
149 const requests: string[] = [];
150 const validations: Array<{
151 executable: AntigravityInstallation.AntigravityExecutable;
152 version: string;
153 }> = [];
154 const installationFs = options.fileSystem ?? fs;
155 const trackedFs = FileSystem.FileSystem.of({
156 ...installationFs,
157 makeTempDirectoryScoped: (settings) =>
158 settings?.prefix === ".install-"
159 ? Effect.acquireRelease(installationFs.makeTempDirectory(settings), (directory) =>
160 fs
161 .remove(directory, { recursive: true, force: true })
162 .pipe(Effect.orDie, Effect.andThen(Deferred.succeed(stagingReleased, undefined))),
163 )
164 : installationFs.makeTempDirectoryScoped(settings),
165 });
166 const installation = yield* AntigravityInstallation.makeAntigravityInstallation({
167 baseDir,
168 releaseAsset: asset,
169 ...(options.useDefaultValidation
170 ? {}
171 : {
172 validate: (executable: AntigravityInstallation.AntigravityExecutable, version: string) =>
173 Effect.sync(() => validations.push({ executable, version })).pipe(
174 Effect.andThen(options.validate?.(executable, version) ?? Effect.void),
175 ),
176 }),
177 }).pipe(
178 Effect.provideService(FileSystem.FileSystem, trackedFs),
179 Effect.provideService(HostProcess.Platform, platform),
180 Effect.provideService(HostProcess.Architecture, arch),
181 Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }),
182 Effect.provideService(
183 HttpClient.HttpClient,
184 HttpClient.make((request) =>
185 Effect.sync(() => {
186 requests.push(request.url);
187 const response = HttpClientResponse.fromWeb(
188 request,
189 new Response(null, {
190 headers: {
191 ...(options.contentLength === undefined
192 ? {}
193 : { "content-length": String(options.contentLength) }),
194 ...(options.contentEncoding === undefined
195 ? {}
196 : { "content-encoding": options.contentEncoding }),
197 },
198 }),
199 );
200 return Object.defineProperty(response, "stream", {
201 value:
202 options.body ??
203 Stream.make(
204 archive.subarray(0, 31),
205 archive.subarray(31, 149),
206 archive.subarray(149),
207 ),
208 });
209 }),
210 ),
211 ),
212 );
213 return { installation, fs, path, baseDir, requests, validations, stagingReleased };
214});
215​
216const terminalState = (installation: AntigravityInstallation.AntigravityInstallation["Service"]) =>
217 installation.changes.pipe(
218 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
219 Stream.runHead,
220 Effect.map(Option.getOrThrow),
221 );
222​
223const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease")(function* (
224 installation: AntigravityInstallation.AntigravityInstallation["Service"],
225) {
226 const fs = yield* FileSystem.FileSystem;
227 const path = yield* Path.Path;
228 const resolved = yield* installation.resolve();
229 expect(resolved.version).toBe(previousVersion);
230 expect(resolved.managedVersionDirectory).toBe(
231 path.join(installation.managedDirectory, "versions", previousReleaseId),
232 );
233 expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents);
234 expect(yield* fs.readFileString(resolved.harnessPath)).toBe(harnessContents);
235 expect((yield* installation.state).installedVersion).toBe(previousVersion);
236});
237​
238it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity installation", (it) => {
239 it.effect("reports missing Node before downloading the standalone provider runtime", () =>
240 Effect.gen(function* () {
241 const { installation, requests, validations } = yield* makeHarness();
242 yield* installation.start;
243 expect(yield* terminalState(installation)).toMatchObject({
244 phase: "failed",
245 message: expect.stringContaining("Install Node.js"),
246 });
247 expect(requests).toEqual([]);
248 expect(validations).toEqual([]);
249 }).pipe(Effect.provideService(HostProcess.IsExecutable, true)),
250 );
251​
252 it.effect("verifies both files before activating a streamed download", () =>
253 Effect.gen(function* () {
254 const enteredValidation = yield* Deferred.make<void>();
255 const finishValidation = yield* Deferred.make<void>();
256 const { installation, fs, path, validations, requests, stagingReleased } = yield* makeHarness(
257 {
258 previous: true,
259 validate: () =>
260 Deferred.succeed(enteredValidation, undefined).pipe(
261 Effect.andThen(Deferred.await(finishValidation)),
262 ),
263 },
264 );
265 const initial = yield* installation.changes.pipe(
266 Stream.runHead,
267 Effect.map(Option.getOrThrow),
268 );
269 expect(initial).toMatchObject({ phase: "idle", installedVersion: previousVersion });
270 const started = yield* installation.start;
271 expect(started).toMatchObject({ phase: "downloading", downloadedBytes: 0 });
272 yield* Deferred.await(enteredValidation);
273 yield* expectPreviousRelease(installation);
274 const validation = validations[0];
275 expect(validation?.version).toBe("fixture-new");
276 if (!validation) return yield* Effect.die("Expected runtime validation.");
277 expect(yield* fs.readFileString(validation.executable.executablePath)).toBe(serverContents);
278 expect(yield* fs.readFileString(validation.executable.harnessPath)).toBe(harnessContents);
279​
280 yield* Deferred.succeed(finishValidation, undefined);
281 expect(yield* terminalState(installation)).toMatchObject({
282 phase: "succeeded",
283 operationId: started.operationId,
284 downloadedBytes: completeArchive.byteLength,
285 installedVersion: "fixture-new",
286 });
287 yield* Deferred.await(stagingReleased);
288 const selected = yield* installation.resolve();
289 expect(selected).toMatchObject({ source: "managed", version: "fixture-new" });
290 expect(path.dirname(selected.harnessPath)).toBe(path.dirname(selected.executablePath));
291 expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents);
292 expect(yield* fs.readFileString(selected.harnessPath)).toBe(harnessContents);
293 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
294 expect.arrayContaining([previousReleaseId, (yield* releaseAsset()).sha256]),
295 );
296 expect(requests).toEqual([(yield* releaseAsset()).url]);
297 }),
298 );
299​
300 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
301 Effect.gen(function* () {
302 // dl.google.com reports the gzip-encoded size; byte and hash checks use the decoded stream.
303 const { installation, validations } = yield* makeHarness({
304 contentLength: completeArchive.byteLength - 1_000,
305 contentEncoding: "gzip",
306 });
307 yield* installation.start;
308 const state = yield* terminalState(installation);
309 expect(state.phase).toBe("succeeded");
310 expect(validations).toHaveLength(1);
311 }),
312 );
313​
314 it.effect.each([
315 { name: "checksum mismatch", completeAsset: { sha256: "2".repeat(64) } },
316 { name: "short download", archive: completeArchive.subarray(0, -1), completeAsset: {} },
317 {
318 name: "oversized download",
319 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
320 completeAsset: {},
321 },
322 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
323 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
324 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
325 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
326 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
327 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
328 ])("rejects $name before runtime validation", ({ completeAsset, ...options }) =>
329 Effect.gen(function* () {
330 const asset =
331 completeAsset === undefined ? undefined : { ...(yield* releaseAsset()), ...completeAsset };
332 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
333 ...options,
334 ...(asset === undefined ? {} : { asset }),
335 previous: true,
336 });
337 yield* installation.start;
338 const state = yield* terminalState(installation);
339 expect(state.phase).toBe("failed");
340 expect(state.message).toBeTruthy();
341 expect(validations).toEqual([]);
342 yield* Deferred.await(stagingReleased);
343 yield* expectPreviousRelease(installation);
344 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
345 [previousReleaseId],
346 );
347 }),
348 );
349​
350 it.effect.each(["download", "extract", "active pointer"] as const)(
351 "preserves the old runtime after an ENOSPC error during %s",
352 (stage) =>
353 Effect.gen(function* () {
354 const fs = yield* FileSystem.FileSystem;
355 const noSpace = PlatformError.systemError({
356 _tag: "Unknown",
357 module: "FileSystem",
358 method: "write",
359 description: "ENOSPC: no space left on device",
360 });
361 const fileSystem = FileSystem.FileSystem.of({
362 ...fs,
363 sink: (target, options) =>
364 (stage === "download" && target.endsWith("download.zip")) ||
365 (stage === "extract" && target.endsWith(executableName))
366 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
367 : fs.sink(target, options),
368 writeFileString: (target, content, options) =>
369 stage === "active pointer" && target.endsWith("contents.tmp")
370 ? Effect.fail(noSpace)
371 : fs.writeFileString(target, content, options),
372 });
373 const { installation, stagingReleased, path } = yield* makeHarness({
374 previous: true,
375 fileSystem,
376 });
377 yield* installation.start;
378 expect((yield* terminalState(installation)).phase).toBe("failed");
379 yield* Deferred.await(stagingReleased);
380 yield* expectPreviousRelease(installation);
381 expect(
382 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
383 (name) => name.startsWith(".install-"),
384 ),
385 ).toBe(false);
386 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
387 "active.json",
388 "versions",
389 ]);
390 }),
391 );
392​
393 it.effect.each(["downloading", "extracting", "verifying"] as const)(
394 "cancels during %s and waits for open resources to close",
395 (phase) =>
396 Effect.gen(function* () {
397 const fs = yield* FileSystem.FileSystem;
398 const entered = yield* Deferred.make<void>();
399 const release = yield* Deferred.make<void>();
400 const interrupted = yield* Deferred.make<void>();
401 const barrier = Deferred.succeed(entered, undefined).pipe(
402 Effect.andThen(Deferred.await(release)),
403 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
404 );
405 const { installation, stagingReleased, path, validations } = yield* makeHarness({
406 previous: true,
407 body:
408 phase === "downloading"
409 ? Stream.concat(
410 Stream.make(completeArchive.subarray(0, 31)),
411 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
412 )
413 : undefined,
414 validate: phase === "verifying" ? () => barrier : undefined,
415 fileSystem: FileSystem.FileSystem.of({
416 ...fs,
417 sink: (target, options) =>
418 phase === "extracting" && target.endsWith(executableName)
419 ? fs
420 .sink(target, options)
421 .pipe(
422 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
423 )
424 : fs.sink(target, options),
425 }),
426 });
427 const started = yield* installation.start;
428 yield* Deferred.await(entered);
429 expect((yield* installation.state).phase).toBe(phase);
430 expect(
431 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
432 ).toBe("cancelled");
433 yield* Deferred.await(interrupted);
434 yield* Deferred.await(stagingReleased);
435 yield* expectPreviousRelease(installation);
436 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
437 expect(
438 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
439 ).toEqual([previousReleaseId]);
440 }),
441 );
442​
443 it.effect.each([
444 { name: "the committed install", restart: false },
445 { name: "a newer install", restart: true },
446 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
447 Effect.gen(function* () {
448 const fs = yield* FileSystem.FileSystem;
449 const cleanupStarted = yield* Deferred.make<void>();
450 const releaseCleanup = yield* Deferred.make<void>();
451 const nextValidationStarted = yield* Deferred.make<void>();
452 const releaseNextValidation = yield* Deferred.make<void>();
453 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
454 const cleanupError = PlatformError.systemError({
455 _tag: "PermissionDenied",
456 module: "FileSystem",
457 method: "remove",
458 description: "EPERM: pointer temp directory is in use",
459 });
460 let firstPointer = true;
461 let validationCount = 0;
462 const { installation, stagingReleased } = yield* makeHarness({
463 previous: true,
464 validate: () => {
465 validationCount += 1;
466 return validationCount === 2
467 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
468 Effect.andThen(Deferred.await(releaseNextValidation)),
469 )
470 : Effect.void;
471 },
472 fileSystem: FileSystem.FileSystem.of({
473 ...fs,
474 makeTempDirectoryScoped: (settings) => {
475 if (settings?.prefix !== "active.json." || !firstPointer) {
476 return fs.makeTempDirectoryScoped(settings);
477 }
478 firstPointer = false;
479 return Effect.fiber.pipe(
480 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
481 Effect.andThen(
482 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
483 Deferred.succeed(cleanupStarted, undefined).pipe(
484 Effect.andThen(Deferred.await(releaseCleanup)),
485 Effect.andThen(Effect.die(cleanupError)),
486 ),
487 ),
488 ),
489 );
490 },
491 }),
492 });
493 yield* Effect.gen(function* () {
494 const first = yield* installation.start;
495 yield* Deferred.await(cleanupStarted);
496 expect(yield* installation.state).toMatchObject({
497 operationId: first.operationId,
498 phase: "succeeded",
499 installedVersion: "fixture-new",
500 });
501 const current = testCase.restart ? yield* installation.start : first;
502 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
503​
504 yield* Deferred.succeed(releaseCleanup, undefined);
505 yield* Fiber.await(yield* Deferred.await(firstWorker));
506 yield* Deferred.await(stagingReleased);
507 expect(yield* installation.state).toMatchObject({
508 operationId: current.operationId,
509 phase: testCase.restart ? "verifying" : "succeeded",
510 installedVersion: "fixture-new",
511 });
512 expect((yield* installation.resolve()).version).toBe("fixture-new");
513​
514 yield* Deferred.succeed(releaseNextValidation, undefined);
515 expect(yield* terminalState(installation)).toMatchObject({
516 operationId: current.operationId,
517 phase: "succeeded",
518 installedVersion: "fixture-new",
519 });
520 }).pipe(
521 Effect.ensuring(
522 Deferred.succeed(releaseCleanup, undefined).pipe(
523 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
524 ),
525 ),
526 );
527 }),
528 );
529​
530 it.effect(
531 "shares one install across callers and keeps it alive after the caller scope closes",
532 () =>
533 Effect.gen(function* () {
534 const entered = yield* Deferred.make<void>();
535 const release = yield* Deferred.make<void>();
536 const { installation, requests, stagingReleased } = yield* makeHarness({
537 body: Stream.fromEffect(
538 Deferred.succeed(entered, undefined).pipe(
539 Effect.andThen(Deferred.await(release)),
540 Effect.as(completeArchive),
541 ),
542 ),
543 });
544 const callerScope = yield* Scope.make();
545 const started = yield* installation.start.pipe(Scope.provide(callerScope));
546 yield* Deferred.await(entered);
547 yield* Scope.close(callerScope, Exit.void);
548 const concurrent = yield* Effect.all([installation.start, installation.start], {
549 concurrency: "unbounded",
550 });
551 expect(concurrent.map((state) => state.operationId)).toEqual([
552 started.operationId,
553 started.operationId,
554 ]);
555 expect(
556 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
557 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
558 yield* Deferred.succeed(release, undefined);
559 expect((yield* terminalState(installation)).phase).toBe("succeeded");
560 yield* Deferred.await(stagingReleased);
561​
562 const next = yield* installation.start;
563 expect(next.operationId).not.toBe(started.operationId);
564 expect(
565 yield* installation
566 .cancel(started.operationId ?? "missing-operation-id")
567 .pipe(Effect.flip),
568 ).toMatchObject({ operation: "cancel" });
569 expect((yield* terminalState(installation)).phase).toBe("succeeded");
570 expect(requests).toHaveLength(1);
571 }),
572 );
573​
574 // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons.
575 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
576 "honors explicit paths and reports invalid overrides without falling back",
577 () =>
578 Effect.gen(function* () {
579 const fs = yield* FileSystem.FileSystem;
580 const path = yield* Path.Path;
581 const baseDir = yield* fs
582 .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" })
583 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
584 const externalDirectory = path.join(baseDir, "external");
585 const externalExecutable = path.join(externalDirectory, executableName);
586 const externalHarness = path.join(externalDirectory, harnessName);
587 yield* fs.makeDirectory(externalDirectory);
588 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
589 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
590 const { installation } = yield* makeHarness({
591 baseDir,
592 path: externalDirectory,
593 previous: true,
594 });
595 yield* expectPreviousRelease(installation);
596 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
597 source: "managed",
598 version: previousVersion,
599 });
600 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
601 executablePath: externalExecutable,
602 source: "override",
603 managedVersionDirectory: null,
604 });
605 expect(yield* installation.resolve(executableName)).toMatchObject({
606 source: "override",
607 });
608 yield* fs.remove(externalHarness);
609 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
610 operation: "resolve",
611 });
612 expect(
613 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
614 ).toMatchObject({
615 operation: "resolve",
616 });
617 yield* expectPreviousRelease(installation);
618 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
619 yield* installation.remove();
620 expect(yield* installation.resolve()).toMatchObject({
621 source: "path",
622 executablePath: externalExecutable,
623 });
624 const isolated = yield* makeHarness({ baseDir });
625 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
626 operation: "resolve",
627 });
628 expect(
629 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
630 ).toMatchObject({
631 source: "path",
632 executablePath: externalExecutable,
633 });
634 expect(
635 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
636 ).toMatchObject({ source: "override", executablePath: externalExecutable });
637 }),
638 );
639​
640 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
641 Effect.gen(function* () {
642 const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true });
643 const processScope = yield* Scope.make();
644 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
645 yield* installation.start;
646 expect((yield* terminalState(installation)).phase).toBe("succeeded");
647 yield* Deferred.await(stagingReleased);
648 const current = yield* installation.resolve();
649 expect(current.version).toBe("fixture-new");
650 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
651 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
652 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
653 yield* Scope.close(processScope, Exit.void);
654 yield* installation.remove();
655 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
656 }),
657 );
658​
659 it.effect(
660 "removes an incomplete active release before reinstalling without a PATH fallback",
661 () =>
662 Effect.gen(function* () {
663 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
664 const previous = yield* installation.resolve();
665 yield* fs.remove(previous.harnessPath);
666 const externalDirectory = path.join(baseDir, "external");
667 yield* fs.makeDirectory(externalDirectory);
668 yield* fs.writeFileString(path.join(externalDirectory, executableName), "external server", {
669 mode: 0o755,
670 });
671 yield* fs.writeFileString(path.join(externalDirectory, harnessName), "external harness", {
672 mode: 0o755,
673 });
674 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
675 expect(yield* restarted.installation.state).toMatchObject({
676 phase: "failed",
677 installedVersion: null,
678 canRemove: true,
679 });
680 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
681 operation: "resolve",
682 });
683 yield* restarted.installation.remove();
684 expect(yield* restarted.installation.state).toMatchObject({
685 phase: "idle",
686 canRemove: false,
687 });
688 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
689 yield* restarted.installation.start;
690 expect(yield* terminalState(restarted.installation)).toMatchObject({
691 phase: "succeeded",
692 installedVersion: "fixture-new",
693 canRemove: true,
694 });
695 yield* Deferred.await(restarted.stagingReleased);
696 expect((yield* restarted.installation.resolve()).source).toBe("managed");
697 }),
698 );
699​
700 it.effect(
701 "blocks removal of custom managed paths and leaves external executables and profiles intact",
702 () =>
703 Effect.gen(function* () {
704 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
705 const managed = yield* installation.resolve();
706 const externalDirectory = path.join(baseDir, "external");
707 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
708 yield* fs.makeDirectory(externalDirectory);
709 yield* fs.makeDirectory(profileDirectory, { recursive: true });
710 const externalExecutable = path.join(externalDirectory, executableName);
711 const externalHarness = path.join(externalDirectory, harnessName);
712 const profilePath = path.join(profileDirectory, "preferences.json");
713 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
714 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
715 yield* fs.writeFileString(profilePath, "{}");
716 expect(
717 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
718 ).toMatchObject({
719 operation: "remove",
720 });
721 yield* expectPreviousRelease(installation);
722 yield* installation.remove([externalExecutable]);
723 expect(yield* installation.state).toMatchObject({
724 phase: "idle",
725 operationId: null,
726 installedVersion: null,
727 });
728 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
729 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
730 expect(yield* fs.readFileString(profilePath)).toBe("{}");
731 }),
732 );
733​
734 it.effect(
735 "reuses an immutable Windows release and preserves the pointer when rename is denied",
736 () =>
737 Effect.gen(function* () {
738 const fs = yield* FileSystem.FileSystem;
739 const path = yield* Path.Path;
740 const archive = Buffer.from(zipFixtures.windows, "base64");
741 const asset = yield* releaseAsset(archive, "win32");
742 let denyPointerRename = true;
743 const renameTargets: string[] = [];
744 const { installation, requests, validations } = yield* makeHarness({
745 previous: true,
746 platform: "win32",
747 archive,
748 fileSystem: FileSystem.FileSystem.of({
749 ...fs,
750 rename: (source, target) => {
751 renameTargets.push(target);
752 return denyPointerRename
753 ? Effect.fail(
754 PlatformError.systemError({
755 _tag: "PermissionDenied",
756 module: "FileSystem",
757 method: "rename",
758 pathOrDescriptor: target,
759 description: "EPERM: file is in use",
760 }),
761 )
762 : fs.rename(source, target);
763 },
764 }),
765 });
766 yield* writeRelease(installation.managedDirectory, asset, false);
767 yield* installation.start;
768 expect((yield* terminalState(installation)).phase).toBe("failed");
769 yield* expectPreviousRelease(installation);
770 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
771​
772 denyPointerRename = false;
773 yield* installation.start;
774 expect((yield* terminalState(installation)).phase).toBe("succeeded");
775 expect((yield* installation.resolve()).version).toBe("fixture-new");
776 expect(requests).toEqual([]);
777 expect(validations).toHaveLength(2);
778 expect(renameTargets).toEqual([
779 path.join(installation.managedDirectory, "active.json"),
780 path.join(installation.managedDirectory, "active.json"),
781 ]);
782 }),
783 );
784​
785 it.effect("reports unsupported hosts without downloading or changing state", () =>
786 Effect.gen(function* () {
787 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
788 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
789 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
790 operation: "resolve",
791 });
792 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
793 expect(requests).toEqual([]);
794 }),
795 );
796});