Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import {
4 HostProcessArchitecture,
5 HostProcessEnvironment,
6 HostProcessPlatform,
7} from "@t3tools/shared/hostProcess";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
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 Queue from "effect/Queue";
17import * as Schema from "effect/Schema";
18import * as Scope from "effect/Scope";
19import * as Sink from "effect/Sink";
20import * as Stream from "effect/Stream";
21import { HttpClient, HttpClientResponse } from "effect/unstable/http";
22import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
23import * as NodeCrypto from "node:crypto";
24
25import {
26 makeAntigravityInstallation,
27 type AntigravityExecutable,
28 type AntigravityInstallation,
29 type AntigravityInstallationOptions,
30} from "./AntigravityInstallation.ts";
31import { ANTIGRAVITY_AUTH_BROWSER_MARKER } from "./antigravityAuthSupport.ts";
32import type { AntigravityReleaseAsset } from "./antigravityRelease.ts";
33
34const serverContents = "antigravity runtime\n";
35const harnessContents = "local harness\n";
36const previousReleaseId = "1".repeat(64);
37const previousVersion = "fixture-old";
38const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
39
40// Small ZIPs made with Python's zipfile module. The unsafe entries are intentional.
41const zipFixtures = {
42 complete:
43 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAAAFAAAABIAAAAAAAAAAAAAAO2BAAAAAGFneV9hY3Bfc2VydmVyLn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hly8lPTsxRyEgsykstLuYCAFBLAQIUAxQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAAAAAAAAAAADtgQAAAABhZ3lfYWNwX3NlcnZlci5leGVQSwECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAGQAAAAAAAAAAAAAA7YFEAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsLmV4ZVBLBQYAAAAAAgACAIcAAACLAAAAAAA=",
56};
57
58const completeArchive = Buffer.from(zipFixtures.complete, "base64");
59
60function releaseAsset(archive: Uint8Array = completeArchive, platform: NodeJS.Platform = "linux") {
61 return {
62 version: "fixture-new",
63 url: "https://dl.google.com/antigravity-test.zip",
64 sha256: NodeCrypto.createHash("sha256").update(archive).digest("hex"),
65 archiveBytes: archive.byteLength,
66 executable: {
67 name: platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par",
68 bytes: Buffer.byteLength(serverContents),
69 },
70 harness: {
71 name: platform === "win32" ? "localharness_external.exe" : "localharness_external",
72 bytes: Buffer.byteLength(harnessContents),
73 },
74 } satisfies AntigravityReleaseAsset;
75}
76
77const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* (
78 managedDirectory: string,
79 asset: AntigravityReleaseAsset,
80 active = true,
81) {
82 const fs = yield* FileSystem.FileSystem;
83 const path = yield* Path.Path;
84 const directory = path.join(managedDirectory, "versions", asset.sha256);
85 yield* fs.makeDirectory(directory, { recursive: true });
86 yield* fs.writeFileString(path.join(directory, asset.executable.name), serverContents, {
87 mode: 0o755,
88 });
89 yield* fs.writeFileString(path.join(directory, asset.harness.name), harnessContents, {
90 mode: 0o755,
91 });
92 yield* fs.writeFileString(
93 path.join(directory, ".install-complete.json"),
94 encodeJsonString({
95 releaseId: asset.sha256,
96 version: asset.version,
97 executable: asset.executable,
98 harness: asset.harness,
99 }),
100 );
101 if (active) {
102 yield* fs.writeFileString(
103 path.join(managedDirectory, "active.json"),
104 encodeJsonString({ releaseId: asset.sha256 }),
105 );
106 }
107});
108
109interface HarnessOptions {
110 readonly baseDir?: string;
111 readonly asset?: AntigravityReleaseAsset | null;
112 readonly archive?: Buffer;
113 readonly body?: Stream.Stream<Uint8Array> | undefined;
114 readonly contentLength?: number;
115 readonly contentEncoding?: string;
116 readonly platform?: NodeJS.Platform;
117 readonly path?: string;
118 readonly previous?: boolean;
119 readonly fileSystem?: FileSystem.FileSystem;
120 readonly validate?: AntigravityInstallationOptions["validate"];
121 readonly useDefaultValidation?: boolean;
122}
123
124const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
125 options: HarnessOptions = {},
126) {
127 const fs = yield* FileSystem.FileSystem;
128 const path = yield* Path.Path;
129 const baseDir =
130 options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
131 const platform = options.platform ?? "linux";
132 const archive = options.archive ?? completeArchive;
133 const asset = options.asset === undefined ? releaseAsset(archive, platform) : options.asset;
134 const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-x64`);
135 if (options.previous) {
136 yield* writeRelease(managedDirectory, {
137 ...releaseAsset(archive, platform),
138 sha256: previousReleaseId,
139 version: previousVersion,
140 });
141 }
142 const stagingReleased = yield* Deferred.make<void>();
143 const requests: string[] = [];
144 const validations: Array<{ executable: AntigravityExecutable; version: string }> = [];
145 const installationFs = options.fileSystem ?? fs;
146 const trackedFs = FileSystem.FileSystem.of({
147 ...installationFs,
148 makeTempDirectoryScoped: (settings) =>
149 settings?.prefix === ".install-"
150 ? Effect.acquireRelease(installationFs.makeTempDirectory(settings), (directory) =>
151 fs
152 .remove(directory, { recursive: true, force: true })
153 .pipe(Effect.orDie, Effect.andThen(Deferred.succeed(stagingReleased, undefined))),
154 )
155 : installationFs.makeTempDirectoryScoped(settings),
156 });
157 const installation = yield* makeAntigravityInstallation({
158 baseDir,
159 releaseAsset: asset,
160 ...(options.useDefaultValidation
161 ? {}
162 : {
163 validate: (executable: AntigravityExecutable, version: string) =>
164 Effect.sync(() => validations.push({ executable, version })).pipe(
165 Effect.andThen(options.validate?.(executable, version) ?? Effect.void),
166 ),
167 }),
168 }).pipe(
169 Effect.provideService(FileSystem.FileSystem, trackedFs),
170 Effect.provideService(HostProcessPlatform, platform),
171 Effect.provideService(HostProcessArchitecture, "x64"),
172 Effect.provideService(HostProcessEnvironment, { PATH: options.path ?? "" }),
173 Effect.provideService(
174 HttpClient.HttpClient,
175 HttpClient.make((request) =>
176 Effect.sync(() => {
177 requests.push(request.url);
178 const response = HttpClientResponse.fromWeb(
179 request,
180 new Response(null, {
181 headers: {
182 ...(options.contentLength === undefined
183 ? {}
184 : { "content-length": String(options.contentLength) }),
185 ...(options.contentEncoding === undefined
186 ? {}
187 : { "content-encoding": options.contentEncoding }),
188 },
189 }),
190 );
191 return Object.defineProperty(response, "stream", {
192 value:
193 options.body ??
194 Stream.make(
195 archive.subarray(0, 31),
196 archive.subarray(31, 149),
197 archive.subarray(149),
198 ),
199 });
200 }),
201 ),
202 ),
203 );
204 return { installation, fs, path, baseDir, requests, validations, stagingReleased };
205});
206
207const terminalState = (installation: AntigravityInstallation["Service"]) =>
208 installation.changes.pipe(
209 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
210 Stream.runHead,
211 Effect.map(Option.getOrThrow),
212 );
213
214const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease")(function* (
215 installation: AntigravityInstallation["Service"],
216) {
217 const fs = yield* FileSystem.FileSystem;
218 const path = yield* Path.Path;
219 const resolved = yield* installation.resolve();
220 expect(resolved.version).toBe(previousVersion);
221 expect(resolved.managedVersionDirectory).toBe(
222 path.join(installation.managedDirectory, "versions", previousReleaseId),
223 );
224 expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents);
225 expect(yield* fs.readFileString(resolved.harnessPath)).toBe(harnessContents);
226 expect((yield* installation.state).installedVersion).toBe(previousVersion);
227});
228
229it.layer(NodeServices.layer)("Antigravity installation", (it) => {
230 it.effect("verifies both files before activating a streamed download", () =>
231 Effect.gen(function* () {
232 const enteredValidation = yield* Deferred.make<void>();
233 const finishValidation = yield* Deferred.make<void>();
234 const { installation, fs, path, validations, requests, stagingReleased } = yield* makeHarness(
235 {
236 previous: true,
237 validate: () =>
238 Deferred.succeed(enteredValidation, undefined).pipe(
239 Effect.andThen(Deferred.await(finishValidation)),
240 ),
241 },
242 );
243 const initial = yield* installation.changes.pipe(
244 Stream.runHead,
245 Effect.map(Option.getOrThrow),
246 );
247 expect(initial).toMatchObject({ phase: "idle", installedVersion: previousVersion });
248 const started = yield* installation.start;
249 expect(started).toMatchObject({ phase: "downloading", downloadedBytes: 0 });
250 yield* Deferred.await(enteredValidation);
251 yield* expectPreviousRelease(installation);
252 const validation = validations[0];
253 expect(validation?.version).toBe("fixture-new");
254 if (!validation) return yield* Effect.die("Expected runtime validation.");
255 expect(yield* fs.readFileString(validation.executable.executablePath)).toBe(serverContents);
256 expect(yield* fs.readFileString(validation.executable.harnessPath)).toBe(harnessContents);
257
258 yield* Deferred.succeed(finishValidation, undefined);
259 expect(yield* terminalState(installation)).toMatchObject({
260 phase: "succeeded",
261 operationId: started.operationId,
262 downloadedBytes: completeArchive.byteLength,
263 installedVersion: "fixture-new",
264 });
265 yield* Deferred.await(stagingReleased);
266 const selected = yield* installation.resolve();
267 expect(selected).toMatchObject({ source: "managed", version: "fixture-new" });
268 expect(path.dirname(selected.harnessPath)).toBe(path.dirname(selected.executablePath));
269 expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents);
270 expect(yield* fs.readFileString(selected.harnessPath)).toBe(harnessContents);
271 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
272 expect.arrayContaining([previousReleaseId, releaseAsset().sha256]),
273 );
274 expect(requests).toEqual([releaseAsset().url]);
275 }),
276 );
277
278 it.effect.each([
279 {
280 name: "the expected release",
281 agentName: "antigravity-acp",
282 version: "fixture-new",
283 valid: true,
284 },
285 { name: "a different agent", agentName: "other-agent", version: "fixture-new", valid: false },
286 {
287 name: "a different version",
288 agentName: "antigravity-acp",
289 version: "other-version",
290 valid: false,
291 },
292 ])("validates $name with initialize only and removes the disposable profile", (testCase) =>
293 Effect.gen(function* () {
294 const fs = yield* FileSystem.FileSystem;
295 const encoder = new TextEncoder();
296 const decodeRequest = Schema.decodeUnknownEffect(
297 Schema.fromJsonString(
298 Schema.Struct({
299 id: Schema.Union([Schema.String, Schema.Number]),
300 method: Schema.String,
301 }),
302 ),
303 );
304 const methods: string[] = [];
305 const profiles = new Set<string>();
306 let closedRuntimes = 0;
307 const spawner = ChildProcessSpawner.make(
308 Effect.fn("test.spawnAntigravityValidator")(function* (command) {
309 if (command._tag !== "StandardCommand") {
310 return yield* Effect.die("Expected one validation process.");
311 }
312 const profile = command.options.env?.GEMINI_HOME;
313 if (!profile) return yield* Effect.die("Expected a disposable validation profile.");
314 profiles.add(profile);
315 const helper = command.args[0] === "-e";
316 const output = yield* Queue.unbounded<Uint8Array>();
317 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
318 const terminate = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
319 Effect.asVoid,
320 );
321 yield* Effect.addFinalizer(() =>
322 terminate.pipe(
323 Effect.andThen(Queue.shutdown(output)),
324 Effect.andThen(
325 Effect.sync(() => {
326 if (!helper) closedRuntimes += 1;
327 }),
328 ),
329 ),
330 );
331 return ChildProcessSpawner.makeHandle({
332 pid: ChildProcessSpawner.ProcessId(helper ? 1 : 2),
333 exitCode: helper
334 ? Effect.succeed(ChildProcessSpawner.ExitCode(0))
335 : Deferred.await(exited),
336 isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
337 kill: () => terminate,
338 unref: Effect.succeed(Effect.void),
339 stdin: Sink.forEach((bytes: Uint8Array) =>
340 Effect.gen(function* () {
341 const request = yield* decodeRequest(new TextDecoder().decode(bytes)).pipe(
342 Effect.orDie,
343 );
344 methods.push(request.method);
345 yield* Queue.offer(
346 output,
347 encoder.encode(
348 `${encodeJsonString({
349 jsonrpc: "2.0",
350 id: request.id,
351 ...(request.method === "initialize"
352 ? {
353 result: {
354 protocolVersion: 1,
355 agentInfo: { name: testCase.agentName, version: testCase.version },
356 agentCapabilities: {
357 loadSession: true,
358 sessionCapabilities: { resume: {} },
359 auth: { logout: {} },
360 },
361 authMethods: [{ id: "oauth-personal", name: "Google" }],
362 },
363 }
364 : {
365 error: {
366 code: -32601,
367 message: "Validation must not sign in or create sessions.",
368 },
369 }),
370 })}\n`,
371 ),
372 );
373 }),
374 ),
375 stdout: helper ? Stream.empty : Stream.fromQueue(output),
376 stderr: helper
377 ? Stream.make(
378 encoder.encode(
379 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeJsonString(command.args.at(-1))}\n`,
380 ),
381 )
382 : Stream.empty,
383 all: Stream.empty,
384 getInputFd: () => Sink.drain,
385 getOutputFd: () => Stream.empty,
386 });
387 }),
388 );
389 const { installation, stagingReleased } = yield* makeHarness({
390 previous: true,
391 useDefaultValidation: true,
392 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
393 yield* installation.start;
394 expect((yield* terminalState(installation)).phase).toBe(
395 testCase.valid ? "succeeded" : "failed",
396 );
397 yield* Deferred.await(stagingReleased);
398 expect(methods).toEqual(["initialize"]);
399 expect(closedRuntimes).toBe(1);
400 expect(profiles.size).toBe(1);
401 for (const profile of profiles) {
402 expect(yield* fs.exists(profile)).toBe(false);
403 }
404 if (testCase.valid) {
405 expect((yield* installation.resolve()).version).toBe("fixture-new");
406 } else {
407 yield* expectPreviousRelease(installation);
408 }
409 }),
410 );
411
412 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
413 Effect.gen(function* () {
414 // dl.google.com gzips the archive and reports the encoded size. The decoded
415 // stream is still checked byte for byte and by hash.
416 const { installation, validations } = yield* makeHarness({
417 contentLength: completeArchive.byteLength - 1_000,
418 contentEncoding: "gzip",
419 });
420 yield* installation.start;
421 const state = yield* terminalState(installation);
422 expect(state.phase).toBe("succeeded");
423 expect(validations).toHaveLength(1);
424 }),
425 );
426
427 it.effect.each([
428 { name: "checksum mismatch", asset: { ...releaseAsset(), sha256: "2".repeat(64) } },
429 { name: "short download", archive: completeArchive.subarray(0, -1), asset: releaseAsset() },
430 {
431 name: "oversized download",
432 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
433 asset: releaseAsset(),
434 },
435 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
436 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
437 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
438 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
439 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
440 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
441 ])("rejects $name before runtime validation", (options) =>
442 Effect.gen(function* () {
443 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
444 ...options,
445 previous: true,
446 });
447 yield* installation.start;
448 const state = yield* terminalState(installation);
449 expect(state.phase).toBe("failed");
450 expect(state.message).toBeTruthy();
451 expect(validations).toEqual([]);
452 yield* Deferred.await(stagingReleased);
453 yield* expectPreviousRelease(installation);
454 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
455 [previousReleaseId],
456 );
457 }),
458 );
459
460 it.effect.each(["download", "extract", "active pointer"] as const)(
461 "preserves the old runtime after an ENOSPC error during %s",
462 (stage) =>
463 Effect.gen(function* () {
464 const fs = yield* FileSystem.FileSystem;
465 const noSpace = PlatformError.systemError({
466 _tag: "Unknown",
467 module: "FileSystem",
468 method: "write",
469 description: "ENOSPC: no space left on device",
470 });
471 const fileSystem = FileSystem.FileSystem.of({
472 ...fs,
473 sink: (target, options) =>
474 (stage === "download" && target.endsWith("download.zip")) ||
475 (stage === "extract" && target.endsWith("agy_acp_server.par"))
476 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
477 : fs.sink(target, options),
478 writeFileString: (target, content, options) =>
479 stage === "active pointer" && target.endsWith("contents.tmp")
480 ? Effect.fail(noSpace)
481 : fs.writeFileString(target, content, options),
482 });
483 const { installation, stagingReleased, path } = yield* makeHarness({
484 previous: true,
485 fileSystem,
486 });
487 yield* installation.start;
488 expect((yield* terminalState(installation)).phase).toBe("failed");
489 yield* Deferred.await(stagingReleased);
490 yield* expectPreviousRelease(installation);
491 expect(
492 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
493 (name) => name.startsWith(".install-"),
494 ),
495 ).toBe(false);
496 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
497 "active.json",
498 "versions",
499 ]);
500 }),
501 );
502
503 it.effect.each(["downloading", "extracting", "verifying"] as const)(
504 "cancels during %s and waits for open resources to close",
505 (phase) =>
506 Effect.gen(function* () {
507 const fs = yield* FileSystem.FileSystem;
508 const entered = yield* Deferred.make<void>();
509 const release = yield* Deferred.make<void>();
510 const interrupted = yield* Deferred.make<void>();
511 const barrier = Deferred.succeed(entered, undefined).pipe(
512 Effect.andThen(Deferred.await(release)),
513 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
514 );
515 const { installation, stagingReleased, path, validations } = yield* makeHarness({
516 previous: true,
517 body:
518 phase === "downloading"
519 ? Stream.concat(
520 Stream.make(completeArchive.subarray(0, 31)),
521 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
522 )
523 : undefined,
524 validate: phase === "verifying" ? () => barrier : undefined,
525 fileSystem: FileSystem.FileSystem.of({
526 ...fs,
527 sink: (target, options) =>
528 phase === "extracting" && target.endsWith("agy_acp_server.par")
529 ? fs
530 .sink(target, options)
531 .pipe(
532 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
533 )
534 : fs.sink(target, options),
535 }),
536 });
537 const started = yield* installation.start;
538 yield* Deferred.await(entered);
539 expect((yield* installation.state).phase).toBe(phase);
540 expect(
541 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
542 ).toBe("cancelled");
543 yield* Deferred.await(interrupted);
544 yield* Deferred.await(stagingReleased);
545 yield* expectPreviousRelease(installation);
546 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
547 expect(
548 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
549 ).toEqual([previousReleaseId]);
550 }),
551 );
552
553 it.effect.each([
554 { name: "the committed install", restart: false },
555 { name: "a newer install", restart: true },
556 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
557 Effect.gen(function* () {
558 const fs = yield* FileSystem.FileSystem;
559 const cleanupStarted = yield* Deferred.make<void>();
560 const releaseCleanup = yield* Deferred.make<void>();
561 const nextValidationStarted = yield* Deferred.make<void>();
562 const releaseNextValidation = yield* Deferred.make<void>();
563 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
564 const cleanupError = PlatformError.systemError({
565 _tag: "PermissionDenied",
566 module: "FileSystem",
567 method: "remove",
568 description: "EPERM: pointer temp directory is in use",
569 });
570 let firstPointer = true;
571 let validationCount = 0;
572 const { installation, stagingReleased } = yield* makeHarness({
573 previous: true,
574 validate: () => {
575 validationCount += 1;
576 return validationCount === 2
577 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
578 Effect.andThen(Deferred.await(releaseNextValidation)),
579 )
580 : Effect.void;
581 },
582 fileSystem: FileSystem.FileSystem.of({
583 ...fs,
584 makeTempDirectoryScoped: (settings) => {
585 if (settings?.prefix !== "active.json." || !firstPointer) {
586 return fs.makeTempDirectoryScoped(settings);
587 }
588 firstPointer = false;
589 return Effect.fiber.pipe(
590 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
591 Effect.andThen(
592 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
593 Deferred.succeed(cleanupStarted, undefined).pipe(
594 Effect.andThen(Deferred.await(releaseCleanup)),
595 Effect.andThen(Effect.die(cleanupError)),
596 ),
597 ),
598 ),
599 );
600 },
601 }),
602 });
603 yield* Effect.gen(function* () {
604 const first = yield* installation.start;
605 yield* Deferred.await(cleanupStarted);
606 expect(yield* installation.state).toMatchObject({
607 operationId: first.operationId,
608 phase: "succeeded",
609 installedVersion: "fixture-new",
610 });
611 const current = testCase.restart ? yield* installation.start : first;
612 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
613
614 yield* Deferred.succeed(releaseCleanup, undefined);
615 yield* Fiber.await(yield* Deferred.await(firstWorker));
616 yield* Deferred.await(stagingReleased);
617 expect(yield* installation.state).toMatchObject({
618 operationId: current.operationId,
619 phase: testCase.restart ? "verifying" : "succeeded",
620 installedVersion: "fixture-new",
621 });
622 expect((yield* installation.resolve()).version).toBe("fixture-new");
623
624 yield* Deferred.succeed(releaseNextValidation, undefined);
625 expect(yield* terminalState(installation)).toMatchObject({
626 operationId: current.operationId,
627 phase: "succeeded",
628 installedVersion: "fixture-new",
629 });
630 }).pipe(
631 Effect.ensuring(
632 Deferred.succeed(releaseCleanup, undefined).pipe(
633 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
634 ),
635 ),
636 );
637 }),
638 );
639
640 it.effect(
641 "shares one install across callers and keeps it alive after the caller scope closes",
642 () =>
643 Effect.gen(function* () {
644 const entered = yield* Deferred.make<void>();
645 const release = yield* Deferred.make<void>();
646 const { installation, requests, stagingReleased } = yield* makeHarness({
647 body: Stream.fromEffect(
648 Deferred.succeed(entered, undefined).pipe(
649 Effect.andThen(Deferred.await(release)),
650 Effect.as(completeArchive),
651 ),
652 ),
653 });
654 const callerScope = yield* Scope.make();
655 const started = yield* installation.start.pipe(Scope.provide(callerScope));
656 yield* Deferred.await(entered);
657 yield* Scope.close(callerScope, Exit.void);
658 const concurrent = yield* Effect.all([installation.start, installation.start], {
659 concurrency: "unbounded",
660 });
661 expect(concurrent.map((state) => state.operationId)).toEqual([
662 started.operationId,
663 started.operationId,
664 ]);
665 expect(
666 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
667 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
668 yield* Deferred.succeed(release, undefined);
669 expect((yield* terminalState(installation)).phase).toBe("succeeded");
670 yield* Deferred.await(stagingReleased);
671
672 const next = yield* installation.start;
673 expect(next.operationId).not.toBe(started.operationId);
674 expect(
675 yield* installation
676 .cancel(started.operationId ?? "missing-operation-id")
677 .pipe(Effect.flip),
678 ).toMatchObject({ operation: "cancel" });
679 expect((yield* terminalState(installation)).phase).toBe("succeeded");
680 expect(requests).toHaveLength(1);
681 }),
682 );
683
684 it.effect("honors explicit paths and reports invalid overrides without falling back", () =>
685 Effect.gen(function* () {
686 const fs = yield* FileSystem.FileSystem;
687 const path = yield* Path.Path;
688 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" });
689 const externalDirectory = path.join(baseDir, "external");
690 const externalExecutable = path.join(externalDirectory, "agy_acp_server.par");
691 const externalHarness = path.join(externalDirectory, "localharness_external");
692 yield* fs.makeDirectory(externalDirectory);
693 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
694 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
695 const { installation } = yield* makeHarness({
696 baseDir,
697 path: externalDirectory,
698 previous: true,
699 });
700 yield* expectPreviousRelease(installation);
701 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
702 source: "managed",
703 version: previousVersion,
704 });
705 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
706 executablePath: externalExecutable,
707 source: "override",
708 managedVersionDirectory: null,
709 });
710 expect(yield* installation.resolve("agy_acp_server.par")).toMatchObject({
711 source: "override",
712 });
713 yield* fs.remove(externalHarness);
714 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
715 operation: "resolve",
716 });
717 expect(
718 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
719 ).toMatchObject({
720 operation: "resolve",
721 });
722 yield* expectPreviousRelease(installation);
723 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
724 yield* installation.remove();
725 expect(yield* installation.resolve()).toMatchObject({
726 source: "path",
727 executablePath: externalExecutable,
728 });
729 const isolated = yield* makeHarness({ baseDir });
730 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
731 operation: "resolve",
732 });
733 expect(
734 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
735 ).toMatchObject({
736 source: "path",
737 executablePath: externalExecutable,
738 });
739 expect(
740 yield* isolated.installation.resolve("agy_acp_server.par", { PATH: externalDirectory }),
741 ).toMatchObject({ source: "override", executablePath: externalExecutable });
742 }),
743 );
744
745 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
746 Effect.gen(function* () {
747 const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true });
748 const processScope = yield* Scope.make();
749 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
750 yield* installation.start;
751 expect((yield* terminalState(installation)).phase).toBe("succeeded");
752 yield* Deferred.await(stagingReleased);
753 const current = yield* installation.resolve();
754 expect(current.version).toBe("fixture-new");
755 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
756 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
757 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
758 yield* Scope.close(processScope, Exit.void);
759 yield* installation.remove();
760 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
761 }),
762 );
763
764 it.effect(
765 "removes an incomplete active release before reinstalling without a PATH fallback",
766 () =>
767 Effect.gen(function* () {
768 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
769 const previous = yield* installation.resolve();
770 yield* fs.remove(previous.harnessPath);
771 const externalDirectory = path.join(baseDir, "external");
772 yield* fs.makeDirectory(externalDirectory);
773 yield* fs.writeFileString(
774 path.join(externalDirectory, "agy_acp_server.par"),
775 "external server",
776 {
777 mode: 0o755,
778 },
779 );
780 yield* fs.writeFileString(
781 path.join(externalDirectory, "localharness_external"),
782 "external harness",
783 {
784 mode: 0o755,
785 },
786 );
787 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
788 expect(yield* restarted.installation.state).toMatchObject({
789 phase: "failed",
790 installedVersion: null,
791 canRemove: true,
792 });
793 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
794 operation: "resolve",
795 });
796 yield* restarted.installation.remove();
797 expect(yield* restarted.installation.state).toMatchObject({
798 phase: "idle",
799 canRemove: false,
800 });
801 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
802 yield* restarted.installation.start;
803 expect(yield* terminalState(restarted.installation)).toMatchObject({
804 phase: "succeeded",
805 installedVersion: "fixture-new",
806 canRemove: true,
807 });
808 yield* Deferred.await(restarted.stagingReleased);
809 expect((yield* restarted.installation.resolve()).source).toBe("managed");
810 }),
811 );
812
813 it.effect(
814 "blocks removal of custom managed paths and leaves external executables and profiles intact",
815 () =>
816 Effect.gen(function* () {
817 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
818 const managed = yield* installation.resolve();
819 const externalDirectory = path.join(baseDir, "external");
820 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
821 yield* fs.makeDirectory(externalDirectory);
822 yield* fs.makeDirectory(profileDirectory, { recursive: true });
823 const externalExecutable = path.join(externalDirectory, "agy_acp_server.par");
824 const externalHarness = path.join(externalDirectory, "localharness_external");
825 const profilePath = path.join(profileDirectory, "preferences.json");
826 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
827 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
828 yield* fs.writeFileString(profilePath, "{}");
829 expect(
830 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
831 ).toMatchObject({
832 operation: "remove",
833 });
834 yield* expectPreviousRelease(installation);
835 yield* installation.remove([externalExecutable]);
836 expect(yield* installation.state).toMatchObject({
837 phase: "idle",
838 operationId: null,
839 installedVersion: null,
840 });
841 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
842 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
843 expect(yield* fs.readFileString(profilePath)).toBe("{}");
844 }),
845 );
846
847 it.effect(
848 "reuses an immutable Windows release and preserves the pointer when rename is denied",
849 () =>
850 Effect.gen(function* () {
851 const fs = yield* FileSystem.FileSystem;
852 const path = yield* Path.Path;
853 const archive = Buffer.from(zipFixtures.windows, "base64");
854 const asset = releaseAsset(archive, "win32");
855 let denyPointerRename = true;
856 const renameTargets: string[] = [];
857 const { installation, requests, validations } = yield* makeHarness({
858 previous: true,
859 platform: "win32",
860 archive,
861 fileSystem: FileSystem.FileSystem.of({
862 ...fs,
863 rename: (source, target) => {
864 renameTargets.push(target);
865 return denyPointerRename
866 ? Effect.fail(
867 PlatformError.systemError({
868 _tag: "PermissionDenied",
869 module: "FileSystem",
870 method: "rename",
871 pathOrDescriptor: target,
872 description: "EPERM: file is in use",
873 }),
874 )
875 : fs.rename(source, target);
876 },
877 }),
878 });
879 yield* writeRelease(installation.managedDirectory, asset, false);
880 yield* installation.start;
881 expect((yield* terminalState(installation)).phase).toBe("failed");
882 yield* expectPreviousRelease(installation);
883 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
884
885 denyPointerRename = false;
886 yield* installation.start;
887 expect((yield* terminalState(installation)).phase).toBe("succeeded");
888 expect((yield* installation.resolve()).version).toBe("fixture-new");
889 expect(requests).toEqual([]);
890 expect(validations).toHaveLength(2);
891 expect(renameTargets).toEqual([
892 path.join(installation.managedDirectory, "active.json"),
893 path.join(installation.managedDirectory, "active.json"),
894 ]);
895 }),
896 );
897
898 it.effect("reports unsupported hosts without downloading or changing state", () =>
899 Effect.gen(function* () {
900 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
901 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
902 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
903 operation: "resolve",
904 });
905 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
906 expect(requests).toEqual([]);
907 }),
908 );
909});