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

AntigravityInstallation.test.ts

920 lines40.0 KB

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