Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Layer from "effect/Layer";
4import { expect, it } from "@effect/vitest";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as Digest from "effect/crypto/Digest";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import * as Schema from "effect/Schema";
17import * as Scope from "effect/Scope";
18import * as Sink from "effect/Sink";
19import * as Stream from "effect/Stream";
20import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
21import * as ChildProcess from "effect/process/ChildProcess";
22import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
23
24import * as AntigravityInstallation from "./AntigravityInstallation.ts";
25import * as ModelManifest from "./ModelManifest.ts";
26import { type AntigravityReleaseAsset } from "./antigravityRelease.ts";
27
28const serverContents = "antigravity runtime\n";
29const harnessContents = "local harness\n";
30const previousReleaseId = "1".repeat(64);
31const previousVersion = "fixture-old";
32const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
33
34const zipFixtures = {
35 complete:
36 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAAAFAAAABIAAAAAAAAAAAAAAO2BAAAAAGFneV9hY3Bfc2VydmVyLnBhclBLAQIUAxQAAAAIAAAAIl1fcgMpEAAAAA4AAAAVAAAAAAAAAAAAAADtgUQAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWxQSwUGAAAAAAIAAgCDAAAAhwAAAAAA",
37 missingHarness:
38 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwECFAMUAAAACAAAACJdcxMv6BQAAAAUAAAAEgAAAAAAAAAAAAAA7YEAAAAAYWd5X2FjcF9zZXJ2ZXIucGFyUEsFBgAAAAABAAEAQAAAAEQAAAAAAA==",
39 duplicate:
40 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXXMTL+gUAAAAFAAAABIAAABhZ3lfYWNwX3NlcnZlci5wYXJLzCvJTC9KLMssqVQoKgVyclO5AFBLAQIUAxQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAAAAAAAAAAADtgQAAAABhZ3lfYWNwX3NlcnZlci5wYXJQSwECFAMUAAAACAAAACJdcxMv6BQAAAAUAAAAEgAAAAAAAAAAAAAA7YFEAAAAYWd5X2FjcF9zZXJ2ZXIucGFyUEsFBgAAAAACAAIAgAAAAIgAAAAAAA==",
41 traversal:
42 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAAVAAAALi5cYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAAAFAAAABUAAAAAAAAAAAAAAO2BAAAAAC4uXGFneV9hY3Bfc2VydmVyLnBhclBLAQIUAxQAAAAIAAAAIl1fcgMpEAAAAA4AAAAVAAAAAAAAAAAAAADtgUcAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWxQSwUGAAAAAAIAAgCGAAAAigAAAAAA",
43 symlink:
44 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABUAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWzLyU9OzFHISCzKSy0u5gIAUEsBAhQDFAAAAAgAAAAiXXMTL+gUAAAAFAAAABIAAAAAAAAAAAAAAO2BAAAAAGFneV9hY3Bfc2VydmVyLnBhclBLAQIUAxQAAAAIAAAAIl1fcgMpEAAAAA4AAAAVAAAAAAAAAAAAAAD/oUQAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWxQSwUGAAAAAAIAAgCDAAAAhwAAAAAA",
45 oversizedMember:
46 "UEsDBBQAAAAIAAAAIl0WGThFFQAAABUAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyS8wryUwvSizLLKlUKCoFcnJTuSoAUEsDBBQAAAAIAAAAIl1fcgMpEAAAAA4AAAAVAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsy8lPTsxRyEgsykstLuYCAFBLAQIUAxQAAAAIAAAAIl0WGThFFQAAABUAAAASAAAAAAAAAAAAAADtgQAAAABhZ3lfYWNwX3NlcnZlci5wYXJQSwECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAFQAAAAAAAAAAAAAA7YFFAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsUEsFBgAAAAACAAIAgwAAAIgAAAAAAA==",
47 windows:
48 "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIuZXhlS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABkAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWwuZXhly8lPTsxRyEgsykstLuYCAFBLAQIUAxQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAAAAAAAAAAADtgQAAAABhZ3lfYWNwX3NlcnZlci5leGVQSwECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAGQAAAAAAAAAAAAAA7YFEAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsLmV4ZVBLBQYAAAAAAgACAIcAAACLAAAAAAA=",
49};
50
51// Linux platform mocks cannot enforce POSIX exec bits on NTFS; use the host platform.
52const hostPlatform: NodeJS.Platform =
53 HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux";
54const completeArchive = Buffer.from(
55 hostPlatform === "win32" ? zipFixtures.windows : zipFixtures.complete,
56 "base64",
57);
58const executableName = hostPlatform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par";
59const harnessName =
60 hostPlatform === "win32" ? "localharness_external.exe" : "localharness_external";
61
62const releaseAsset = Effect.fn("test.antigravityReleaseAsset")(function* (
63 archive: Uint8Array = completeArchive,
64 platform: NodeJS.Platform = hostPlatform,
65) {
66 const digest = yield* Digest.Digest;
67 return {
68 version: "fixture-new",
69 url: "https://dl.google.com/antigravity-test.zip",
70 sha256: Hex.encode(yield* digest.digest(Digest.sha256, archive).pipe(Effect.orDie)),
71 archiveBytes: archive.byteLength,
72 executable: {
73 name: platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par",
74 bytes: Buffer.byteLength(serverContents),
75 },
76 harness: {
77 name: platform === "win32" ? "localharness_external.exe" : "localharness_external",
78 bytes: Buffer.byteLength(harnessContents),
79 },
80 } satisfies AntigravityReleaseAsset;
81});
82
83const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* (
84 managedDirectory: string,
85 asset: AntigravityReleaseAsset,
86 active = true,
87) {
88 const fs = yield* FileSystem.FileSystem;
89 const path = yield* Path.Path;
90 const directory = path.join(managedDirectory, "versions", asset.sha256);
91 yield* fs.makeDirectory(directory, { recursive: true });
92 yield* fs.writeFileString(path.join(directory, asset.executable.name), serverContents, {
93 mode: 0o755,
94 });
95 yield* fs.writeFileString(path.join(directory, asset.harness.name), harnessContents, {
96 mode: 0o755,
97 });
98 yield* fs.writeFileString(
99 path.join(directory, ".install-complete.json"),
100 encodeJsonString({
101 releaseId: asset.sha256,
102 version: asset.version,
103 executable: asset.executable,
104 harness: asset.harness,
105 }),
106 );
107 if (active) {
108 yield* fs.writeFileString(
109 path.join(managedDirectory, "active.json"),
110 encodeJsonString({ releaseId: asset.sha256 }),
111 );
112 }
113});
114
115interface HarnessOptions {
116 readonly baseDir?: string;
117 readonly asset?: AntigravityReleaseAsset | null;
118 readonly archive?: Buffer;
119 readonly body?: Stream.Stream<Uint8Array> | undefined;
120 readonly contentLength?: number;
121 readonly contentEncoding?: string;
122 readonly platform?: NodeJS.Platform;
123 readonly arch?: NodeJS.Architecture;
124 readonly path?: string;
125 readonly previous?: boolean;
126 readonly fileSystem?: FileSystem.FileSystem;
127 readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
128 readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"];
129 readonly useDefaultValidation?: boolean;
130 readonly connectTimeout?: boolean;
131 readonly manifest?: Effect.Effect<ModelManifest.ModelManifestData>;
132 readonly native?: boolean;
133 readonly nativeVersion?: string;
134 readonly nativeManifest?: (manifest: { version: string; url: string; sha512: string }) => unknown;
135 readonly beforeManifest?: Effect.Effect<void>;
136 readonly updateChecksEnabled?: Effect.Effect<boolean>;
137}
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 digest = yield* Digest.Digest;
145 const baseDir =
146 options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" }));
147 const platform = options.platform ?? hostPlatform;
148 const arch = options.arch ?? "x64";
149 const archive = options.archive ?? completeArchive;
150 const asset =
151 options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset;
152 const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`);
153 if (options.previous) {
154 yield* writeRelease(managedDirectory, {
155 ...(yield* releaseAsset(archive, platform)),
156 sha256: previousReleaseId,
157 version: previousVersion,
158 });
159 }
160 const stagingReleased = yield* Deferred.make<void>();
161 const requests: string[] = [];
162 const validations: Array<{
163 executable: AntigravityInstallation.AntigravityExecutable;
164 version: string;
165 }> = [];
166 const installationFs = options.fileSystem ?? fs;
167 const trackedFs = FileSystem.FileSystem.of({
168 ...installationFs,
169 makeTempDirectoryScoped: (settings) =>
170 settings?.prefix === ".install-"
171 ? Effect.acquireRelease(installationFs.makeTempDirectory(settings), (directory) =>
172 fs
173 .remove(directory, { recursive: true, force: true })
174 .pipe(Effect.orDie, Effect.andThen(Deferred.succeed(stagingReleased, undefined))),
175 )
176 : installationFs.makeTempDirectoryScoped(settings),
177 });
178 const installation = yield* AntigravityInstallation.makeAntigravityInstallation({
179 baseDir,
180 ...(options.native ? {} : { releaseAsset: asset }),
181 ...(options.updateChecksEnabled === undefined
182 ? {}
183 : { updateChecksEnabled: options.updateChecksEnabled }),
184 ...(options.useDefaultValidation
185 ? {}
186 : {
187 validate: (executable: AntigravityInstallation.AntigravityExecutable, version: string) =>
188 Effect.sync(() => validations.push({ executable, version })).pipe(
189 Effect.andThen(options.validate?.(executable, version) ?? Effect.void),
190 ),
191 }),
192 }).pipe(
193 options.spawner
194 ? Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, options.spawner)
195 : (effect) => effect,
196 Effect.provideService(FileSystem.FileSystem, trackedFs),
197 Effect.provideService(HostProcess.Platform, platform),
198 Effect.provideService(HostProcess.Architecture, arch),
199 Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }),
200 Effect.provideService(ModelManifest.ModelManifest, {
201 current: options.manifest ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
202 refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
203 forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
204 refreshOnDemand: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
205 refreshInBackground: Effect.void,
206 }),
207 Effect.provideService(
208 HttpClient.HttpClient,
209 HttpClient.make((request) =>
210 Effect.suspend(() => {
211 requests.push(request.url);
212 if (request.url.includes("/manifests/")) {
213 return Effect.gen(function* () {
214 yield* options.beforeManifest ?? Effect.void;
215 const version = options.nativeVersion ?? "1.5.7";
216 const folder = platform === "win32" ? "windows-x64" : "linux-x64";
217 const manifest = {
218 version,
219 url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/${version}-123/${folder}/cli_${platform === "win32" ? "windows_x64.exe" : "linux_x64.tar.gz"}`,
220 sha512: Hex.encode(yield* digest.digest(Digest.sha512, archive).pipe(Effect.orDie)),
221 };
222 return HttpClientResponse.fromWeb(
223 request,
224 new Response(JSON.stringify(options.nativeManifest?.(manifest) ?? manifest)),
225 );
226 });
227 }
228 if (options.connectTimeout) {
229 return Effect.fail(
230 new HttpClientError.HttpClientError({
231 reason: new HttpClientError.TransportError({
232 request,
233 cause: new Error("Connect Timeout Error (attempted address: dl.google.com:443)"),
234 }),
235 }),
236 );
237 }
238 const response = HttpClientResponse.fromWeb(
239 request,
240 new Response(null, {
241 headers: {
242 ...(options.contentLength === undefined
243 ? {}
244 : { "content-length": String(options.contentLength) }),
245 ...(options.contentEncoding === undefined
246 ? {}
247 : { "content-encoding": options.contentEncoding }),
248 },
249 }),
250 );
251 return Effect.succeed(
252 Object.defineProperty(response, "stream", {
253 value:
254 options.body ??
255 Stream.make(
256 archive.subarray(0, 31),
257 archive.subarray(31, 149),
258 archive.subarray(149),
259 ),
260 }),
261 );
262 }),
263 ),
264 ),
265 );
266 return { installation, fs, path, baseDir, requests, validations, stagingReleased };
267});
268
269const terminalState = (installation: AntigravityInstallation.AntigravityInstallation["Service"]) =>
270 installation.changes.pipe(
271 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
272 Stream.runHead,
273 Effect.map(Option.getOrThrow),
274 );
275
276const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease")(function* (
277 installation: AntigravityInstallation.AntigravityInstallation["Service"],
278) {
279 const fs = yield* FileSystem.FileSystem;
280 const path = yield* Path.Path;
281 const resolved = yield* installation.resolve();
282 expect(resolved.version).toBe(previousVersion);
283 expect(resolved.managedVersionDirectory).toBe(
284 path.join(installation.managedDirectory, "versions", previousReleaseId),
285 );
286 expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents);
287 expect(yield* fs.readFileString(resolved.harnessPath!)).toBe(harnessContents);
288 expect((yield* installation.state).installedVersion).toBe(previousVersion);
289});
290
291it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity installation", (it) => {
292 it.effect.each([...new Set(["win32", hostPlatform])] as NodeJS.Platform[])(
293 "migrates the legacy managed runtime to the native CLI on %s and retains the old release",
294 (platform) =>
295 Effect.gen(function* () {
296 const archive =
297 platform === "win32"
298 ? Buffer.from(serverContents)
299 : Buffer.from(
300 "H4sIAAAAAAACE+3RMQ7CQAwEQNe8Ik8wgYj3XIFQCiiOCxK/56CJRA9CYqZZrxsXLpc2n2q5ze0en5LdYZpe2b1n5rhf5+d+m+MuY8j4guXaSu3n4z+V9f9DXXo5HzcBAAAAAAAAAADAz3sA56lbdQAoAAA=",
301 "base64",
302 );
303 const { installation, validations, requests, fs, baseDir, stagingReleased } =
304 yield* makeHarness({ native: true, archive, platform, previous: true });
305 yield* installation.start;
306 expect(yield* terminalState(installation)).toMatchObject({
307 phase: "succeeded",
308 installedVersion: "1.5.7",
309 });
310 yield* Deferred.await(stagingReleased);
311 const resolved = yield* installation.resolve();
312 expect(resolved).toMatchObject({ source: "managed", version: "1.5.7", harnessPath: null });
313 expect(validations[0]?.executable.harnessPath).toBeNull();
314 expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents);
315 expect(requests.some((url) => url.includes("/manifests/"))).toBe(true);
316 const restarted = yield* makeHarness({
317 baseDir,
318 native: true,
319 archive,
320 platform,
321 nativeVersion: "1.5.6",
322 });
323 expect(yield* restarted.installation.start).toMatchObject({
324 phase: "verifying",
325 message: "Checking the installed runtime.",
326 });
327 expect(yield* terminalState(restarted.installation)).toMatchObject({
328 phase: "succeeded",
329 installedVersion: "1.5.7",
330 });
331 expect(restarted.requests.filter((url) => url.includes("storage.googleapis.com"))).toEqual(
332 [],
333 );
334 expect((yield* restarted.installation.resolve()).executablePath).toBe(
335 resolved.executablePath,
336 );
337 }),
338 );
339
340 // These tar fixtures exercise the POSIX extraction path; Windows downloads one executable.
341 it.effect.skipIf(hostPlatform === "win32")(
342 "rejects unsafe native tar members before activation",
343 () =>
344 Effect.gen(function* () {
345 for (const archive of [
346 "H4sIAAAAAAACE+3OMQqDQBAFUI/iCYxZJPdZMIRtFHQN5PYOKbW2EN5j4P9iYCZPtXyW/C3111ylD69h+Gc45rk/U4r1NnXdI2be6lrG90XPbWvNS5xvAAAAAAAAAAAA4D523kNDtgAoAAA=",
347 "H4sIAAAAAAACE+3RMQ7CMBAEQNe8Ii8IBhzxHhcIpYDCcSLxewwNiJ4IiZlmb6+54vp+m691PJe8jPUWviI2x2F4ZvOZMe7Ta37sdzGlQ+hiWME81Vza+fCf3p7flbmVy2kTAAAAAAAAAAAA+Hl3jhn2/wAoAAA=",
348 "H4sIAAAAAAACE+3TPQrCQBAG0K09RY4wRoPn2UJCClOsG8Hbu6YJ2CtI3mvmp5li+PJcp7Hkx1Sf6VuiuQzDWpvPGtGft/69P0Z/itRF+oHlXnNp59M+5e3/XVnacLseEnv8v/zLv/wDAAAAAAAAAPyZF/c+VksAKAAA",
349 ]) {
350 const { installation, validations } = yield* makeHarness({
351 native: true,
352 archive: Buffer.from(archive, "base64"),
353 platform: "linux",
354 previous: true,
355 });
356 yield* installation.start;
357 expect((yield* terminalState(installation)).phase).toBe("failed");
358 expect(validations).toEqual([]);
359 yield* expectPreviousRelease(installation);
360 }
361 }),
362 );
363
364 it.effect.each([true, false])(
365 "respects background update checks (%s) while allowing explicit installation",
366 (enabled) =>
367 Effect.gen(function* () {
368 const { installation, requests } = yield* makeHarness({
369 native: true,
370 archive: Buffer.from(serverContents),
371 platform: "win32",
372 updateChecksEnabled: Effect.succeed(enabled),
373 });
374 yield* installation.checkForUpdate;
375 if (enabled) {
376 yield* installation.changes.pipe(
377 Stream.filter((value) => value.version === "1.5.7"),
378 Stream.runHead,
379 );
380 yield* installation.state;
381 expect(requests).toHaveLength(1);
382 } else {
383 yield* installation.changes.pipe(Stream.runHead);
384 expect(requests).toEqual([]);
385 }
386 yield* installation.start;
387 expect((yield* terminalState(installation)).phase).toBe("succeeded");
388 }),
389 );
390
391 it.effect("keeps withdrawn native releases from activating or launching", () =>
392 Effect.gen(function* () {
393 let withdrawn = false;
394 const manifest = Effect.sync(() =>
395 withdrawn
396 ? ({
397 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
398 compatibility: [
399 {
400 driver: "antigravity",
401 t3CodeRange: ">=0.0.42",
402 ranges: [{ range: ">=1.5.7", status: "broken" }],
403 },
404 ],
405 } satisfies ModelManifest.ModelManifestData)
406 : ModelManifest.BUNDLED_MODEL_MANIFEST,
407 );
408 const first = yield* makeHarness({
409 native: true,
410 archive: Buffer.from(serverContents),
411 platform: "win32",
412 previous: true,
413 manifest,
414 validate: () =>
415 Effect.sync(() => {
416 withdrawn = true;
417 }),
418 });
419 yield* first.installation.start;
420 expect((yield* terminalState(first.installation)).phase).toBe("failed");
421 yield* expectPreviousRelease(first.installation);
422 withdrawn = false;
423 const retry = yield* makeHarness({
424 baseDir: first.baseDir,
425 native: true,
426 archive: Buffer.from(serverContents),
427 platform: "win32",
428 manifest,
429 });
430 yield* retry.installation.start;
431 expect((yield* terminalState(retry.installation)).phase).toBe("succeeded");
432 withdrawn = true;
433 expect(yield* retry.installation.resolve().pipe(Effect.flip)).toMatchObject({
434 operation: "resolve",
435 });
436 expect(yield* retry.installation.start.pipe(Effect.flip)).toMatchObject({
437 operation: "start",
438 });
439 const recovery = yield* makeHarness({
440 baseDir: first.baseDir,
441 native: true,
442 nativeVersion: "1.5.6",
443 archive: Buffer.from("recovery runtime"),
444 platform: "win32",
445 manifest,
446 });
447 yield* recovery.installation.checkForUpdate;
448 expect(yield* recovery.installation.state).toMatchObject({
449 installedVersion: "1.5.7",
450 version: "1.5.6",
451 });
452 yield* recovery.installation.start;
453 expect(yield* terminalState(recovery.installation)).toMatchObject({
454 phase: "succeeded",
455 installedVersion: "1.5.6",
456 });
457 }),
458 );
459
460 it.effect("discovers subsequent native releases from Google's CLI channel", () =>
461 Effect.gen(function* () {
462 const first = yield* makeHarness({
463 native: true,
464 archive: Buffer.from(serverContents),
465 platform: "win32",
466 });
467 yield* first.installation.start;
468 expect((yield* terminalState(first.installation)).phase).toBe("succeeded");
469 const initialPath = (yield* first.installation.resolve()).executablePath;
470 const next = yield* makeHarness({
471 baseDir: first.baseDir,
472 native: true,
473 nativeVersion: "1.5.8",
474 archive: Buffer.from("next runtime"),
475 platform: "win32",
476 });
477 yield* next.installation.start;
478 expect(yield* terminalState(next.installation)).toMatchObject({
479 phase: "succeeded",
480 installedVersion: "1.5.8",
481 });
482 const nextPath = (yield* next.installation.resolve()).executablePath;
483 expect(nextPath).not.toBe(initialPath);
484 const republished = yield* makeHarness({
485 baseDir: first.baseDir,
486 native: true,
487 nativeVersion: "1.5.8",
488 archive: Buffer.from("republished runtime"),
489 platform: "win32",
490 });
491 yield* republished.installation.start;
492 expect((yield* terminalState(republished.installation)).phase).toBe("succeeded");
493 expect((yield* republished.installation.resolve()).executablePath).not.toBe(nextPath);
494 const offline = yield* makeHarness({
495 baseDir: first.baseDir,
496 native: true,
497 nativeManifest: () => ({}),
498 archive: Buffer.from("unused"),
499 platform: "win32",
500 });
501 yield* offline.installation.start;
502 expect(yield* terminalState(offline.installation)).toMatchObject({
503 phase: "succeeded",
504 installedVersion: "1.5.8",
505 });
506 expect(offline.requests.filter((url) => url.includes("storage.googleapis.com"))).toEqual([]);
507 }),
508 );
509
510 it.effect.each([
511 {
512 name: "invalid checksum",
513 change: (manifest: { version: string; url: string; sha512: string }) => ({
514 ...manifest,
515 sha512: "0".repeat(128),
516 }),
517 },
518 {
519 name: "foreign download",
520 change: (manifest: { version: string; url: string; sha512: string }) => ({
521 ...manifest,
522 url: "https://example.com/agy.exe",
523 }),
524 },
525 ])("rejects a native $name and preserves the legacy release", ({ change }) =>
526 Effect.gen(function* () {
527 const { installation, validations } = yield* makeHarness({
528 native: true,
529 nativeManifest: change,
530 archive: Buffer.from(serverContents),
531 platform: "win32",
532 previous: true,
533 });
534 const result = yield* Effect.result(installation.start);
535 if (result._tag === "Success")
536 expect((yield* terminalState(installation)).phase).toBe("failed");
537 expect(validations).toEqual([]);
538 yield* expectPreviousRelease(installation);
539 }),
540 );
541
542 it.effect("reports missing Node before downloading the standalone provider runtime", () =>
543 Effect.gen(function* () {
544 const { installation, requests, validations } = yield* makeHarness();
545 yield* installation.start;
546 expect(yield* terminalState(installation)).toMatchObject({
547 phase: "failed",
548 message: expect.stringContaining("Install Node.js"),
549 });
550 expect(requests).toEqual([]);
551 expect(validations).toEqual([]);
552 }).pipe(Effect.provideService(HostProcess.IsExecutable, true)),
553 );
554
555 it.effect("verifies both files before activating a streamed download", () =>
556 Effect.gen(function* () {
557 const enteredValidation = yield* Deferred.make<void>();
558 const finishValidation = yield* Deferred.make<void>();
559 const { installation, fs, path, validations, requests, stagingReleased } = yield* makeHarness(
560 {
561 previous: true,
562 validate: () =>
563 Deferred.succeed(enteredValidation, undefined).pipe(
564 Effect.andThen(Deferred.await(finishValidation)),
565 ),
566 },
567 );
568 const initial = yield* installation.changes.pipe(
569 Stream.runHead,
570 Effect.map(Option.getOrThrow),
571 );
572 expect(initial).toMatchObject({ phase: "idle", installedVersion: previousVersion });
573 const started = yield* installation.start;
574 expect(started).toMatchObject({ phase: "downloading", downloadedBytes: 0 });
575 yield* Deferred.await(enteredValidation);
576 yield* expectPreviousRelease(installation);
577 const validation = validations[0];
578 expect(validation?.version).toBe("fixture-new");
579 if (!validation) return yield* Effect.die("Expected runtime validation.");
580 expect(yield* fs.readFileString(validation.executable.executablePath)).toBe(serverContents);
581 expect(yield* fs.readFileString(validation.executable.harnessPath!)).toBe(harnessContents);
582
583 yield* Deferred.succeed(finishValidation, undefined);
584 expect(yield* terminalState(installation)).toMatchObject({
585 phase: "succeeded",
586 operationId: started.operationId,
587 downloadedBytes: completeArchive.byteLength,
588 installedVersion: "fixture-new",
589 });
590 yield* Deferred.await(stagingReleased);
591 const selected = yield* installation.resolve();
592 expect(selected).toMatchObject({ source: "managed", version: "fixture-new" });
593 expect(path.dirname(selected.harnessPath!)).toBe(path.dirname(selected.executablePath));
594 expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents);
595 expect(yield* fs.readFileString(selected.harnessPath!)).toBe(harnessContents);
596 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
597 expect.arrayContaining([previousReleaseId, (yield* releaseAsset()).sha256]),
598 );
599 expect(requests).toEqual([(yield* releaseAsset()).url]);
600 }),
601 );
602
603 it.effect("accepts an encoded Content-Length when the body is compressed", () =>
604 Effect.gen(function* () {
605 // dl.google.com reports the gzip-encoded size; byte and hash checks use the decoded stream.
606 const { installation, validations } = yield* makeHarness({
607 contentLength: completeArchive.byteLength - 1_000,
608 contentEncoding: "gzip",
609 });
610 yield* installation.start;
611 const state = yield* terminalState(installation);
612 expect(state.phase).toBe("succeeded");
613 expect(validations).toHaveLength(1);
614 }),
615 );
616
617 it.effect.each([
618 { name: "checksum mismatch", completeAsset: { sha256: "2".repeat(64) } },
619 { name: "short download", archive: completeArchive.subarray(0, -1), completeAsset: {} },
620 {
621 name: "oversized download",
622 archive: Buffer.concat([completeArchive, Buffer.from("extra")]),
623 completeAsset: {},
624 },
625 { name: "wrong Content-Length", contentLength: completeArchive.byteLength + 1 },
626 { name: "missing harness", archive: Buffer.from(zipFixtures.missingHarness, "base64") },
627 { name: "duplicate executable", archive: Buffer.from(zipFixtures.duplicate, "base64") },
628 { name: "path traversal", archive: Buffer.from(zipFixtures.traversal, "base64") },
629 { name: "symbolic link", archive: Buffer.from(zipFixtures.symlink, "base64") },
630 { name: "oversized member", archive: Buffer.from(zipFixtures.oversizedMember, "base64") },
631 ])("rejects $name before runtime validation", ({ completeAsset, ...options }) =>
632 Effect.gen(function* () {
633 const asset =
634 completeAsset === undefined ? undefined : { ...(yield* releaseAsset()), ...completeAsset };
635 const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({
636 ...options,
637 ...(asset === undefined ? {} : { asset }),
638 previous: true,
639 });
640 yield* installation.start;
641 const state = yield* terminalState(installation);
642 expect(state.phase).toBe("failed");
643 expect(state.message).toBeTruthy();
644 expect(validations).toEqual([]);
645 yield* Deferred.await(stagingReleased);
646 yield* expectPreviousRelease(installation);
647 expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual(
648 [previousReleaseId],
649 );
650 }),
651 );
652
653 it.effect(
654 "names the connection failure instead of disk space when the download cannot connect",
655 () =>
656 Effect.gen(function* () {
657 const { installation, validations } = yield* makeHarness({ connectTimeout: true });
658 yield* installation.start;
659 const state = yield* terminalState(installation);
660 expect(state.phase).toBe("failed");
661 expect(state.message).not.toMatch(/disk space/i);
662 expect(state.message).toMatch(/connect|network|download/i);
663 expect(validations).toEqual([]);
664 }),
665 );
666
667 // The runtime's own abort is a real process; Windows has no POSIX sh.
668 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
669 "explains that the linux-arm64 runtime needs 4 KiB pages when it aborts on a 16 KiB kernel",
670 () =>
671 Effect.gen(function* () {
672 const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
673 // Google's linux-arm64 build aborts like this on Asahi and Raspberry Pi 5 kernels.
674 const spawner = ChildProcessSpawner.make((command) =>
675 ChildProcess.isStandardCommand(command) &&
676 String(command.command).endsWith(executableName)
677 ? realSpawner.spawn(
678 ChildProcess.make(
679 "sh",
680 [
681 "-c",
682 "echo 'F1111 11:50:12.383176 page-size.cc:19] Check failed: sysconf(_SC_PAGE_SIZE) == kPageSize (16384 vs. 4096) Compile-time page size does not match runtime page size' >&2; kill -ABRT $$",
683 ],
684 { stdin: "pipe", stdout: "pipe", stderr: "pipe" },
685 ),
686 )
687 : realSpawner.spawn(command),
688 );
689 const { installation } = yield* makeHarness({
690 arch: "arm64",
691 useDefaultValidation: true,
692 spawner,
693 });
694 yield* installation.start;
695 const state = yield* terminalState(installation);
696 expect(state.phase).toBe("failed");
697 expect(state.message).toMatch(/page/i);
698 }),
699 );
700
701 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
702 "refuses a 16 KiB-page linux-arm64 kernel before downloading the runtime",
703 () =>
704 Effect.gen(function* () {
705 const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
706 const spawner = ChildProcessSpawner.make((command) =>
707 ChildProcess.isStandardCommand(command) && command.command === "getconf"
708 ? realSpawner.spawn(ChildProcess.make("sh", ["-c", "echo 16384"], command.options))
709 : realSpawner.spawn(command),
710 );
711 const { installation, requests } = yield* makeHarness({ arch: "arm64", spawner });
712 yield* installation.start;
713 const state = yield* terminalState(installation);
714 expect(state.phase).toBe("failed");
715 expect(state.message).toMatch(/4 KiB/);
716 expect(requests).toEqual([]);
717 }),
718 );
719
720 it.effect.each(["download", "extract", "active pointer"] as const)(
721 "preserves the old runtime after an ENOSPC error during %s",
722 (stage) =>
723 Effect.gen(function* () {
724 const fs = yield* FileSystem.FileSystem;
725 const noSpace = PlatformError.systemError({
726 _tag: "Unknown",
727 module: "FileSystem",
728 method: "write",
729 description: "ENOSPC: no space left on device",
730 });
731 const fileSystem = FileSystem.FileSystem.of({
732 ...fs,
733 sink: (target, options) =>
734 (stage === "download" && target.endsWith("download.zip")) ||
735 (stage === "extract" && target.endsWith(executableName))
736 ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace)))
737 : fs.sink(target, options),
738 writeFileString: (target, content, options) =>
739 stage === "active pointer" && target.endsWith("contents.tmp")
740 ? Effect.fail(noSpace)
741 : fs.writeFileString(target, content, options),
742 });
743 const { installation, stagingReleased, path } = yield* makeHarness({
744 previous: true,
745 fileSystem,
746 });
747 yield* installation.start;
748 expect((yield* terminalState(installation)).phase).toBe("failed");
749 yield* Deferred.await(stagingReleased);
750 yield* expectPreviousRelease(installation);
751 expect(
752 (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some(
753 (name) => name.startsWith(".install-"),
754 ),
755 ).toBe(false);
756 expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([
757 "active.json",
758 "versions",
759 ]);
760 }),
761 );
762
763 it.effect.each(["downloading", "extracting", "verifying"] as const)(
764 "cancels during %s and waits for open resources to close",
765 (phase) =>
766 Effect.gen(function* () {
767 const fs = yield* FileSystem.FileSystem;
768 const entered = yield* Deferred.make<void>();
769 const release = yield* Deferred.make<void>();
770 const interrupted = yield* Deferred.make<void>();
771 const barrier = Deferred.succeed(entered, undefined).pipe(
772 Effect.andThen(Deferred.await(release)),
773 Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
774 );
775 const { installation, stagingReleased, path, validations } = yield* makeHarness({
776 previous: true,
777 body:
778 phase === "downloading"
779 ? Stream.concat(
780 Stream.make(completeArchive.subarray(0, 31)),
781 Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))),
782 )
783 : undefined,
784 validate: phase === "verifying" ? () => barrier : undefined,
785 fileSystem: FileSystem.FileSystem.of({
786 ...fs,
787 sink: (target, options) =>
788 phase === "extracting" && target.endsWith(executableName)
789 ? fs
790 .sink(target, options)
791 .pipe(
792 Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk))),
793 )
794 : fs.sink(target, options),
795 }),
796 });
797 const started = yield* installation.start;
798 yield* Deferred.await(entered);
799 expect((yield* installation.state).phase).toBe(phase);
800 expect(
801 (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase,
802 ).toBe("cancelled");
803 yield* Deferred.await(interrupted);
804 yield* Deferred.await(stagingReleased);
805 yield* expectPreviousRelease(installation);
806 expect(validations).toHaveLength(phase === "verifying" ? 1 : 0);
807 expect(
808 yield* fs.readDirectory(path.join(installation.managedDirectory, "versions")),
809 ).toEqual([previousReleaseId]);
810 }),
811 );
812
813 it.effect.each([
814 { name: "the committed install", restart: false },
815 { name: "a newer install", restart: true },
816 ])("does not fail $name when old pointer cleanup fails", (testCase) =>
817 Effect.gen(function* () {
818 const fs = yield* FileSystem.FileSystem;
819 const cleanupStarted = yield* Deferred.make<void>();
820 const releaseCleanup = yield* Deferred.make<void>();
821 const nextValidationStarted = yield* Deferred.make<void>();
822 const releaseNextValidation = yield* Deferred.make<void>();
823 const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
824 const cleanupError = PlatformError.systemError({
825 _tag: "PermissionDenied",
826 module: "FileSystem",
827 method: "remove",
828 description: "EPERM: pointer temp directory is in use",
829 });
830 let firstPointer = true;
831 let validationCount = 0;
832 const { installation, stagingReleased } = yield* makeHarness({
833 previous: true,
834 validate: () => {
835 validationCount += 1;
836 return validationCount === 2
837 ? Deferred.succeed(nextValidationStarted, undefined).pipe(
838 Effect.andThen(Deferred.await(releaseNextValidation)),
839 )
840 : Effect.void;
841 },
842 fileSystem: FileSystem.FileSystem.of({
843 ...fs,
844 makeTempDirectoryScoped: (settings) => {
845 if (settings?.prefix !== "active.json." || !firstPointer) {
846 return fs.makeTempDirectoryScoped(settings);
847 }
848 firstPointer = false;
849 return Effect.fiber.pipe(
850 Effect.tap((worker) => Deferred.succeed(firstWorker, worker)),
851 Effect.andThen(
852 Effect.acquireRelease(fs.makeTempDirectory(settings), () =>
853 Deferred.succeed(cleanupStarted, undefined).pipe(
854 Effect.andThen(Deferred.await(releaseCleanup)),
855 Effect.andThen(Effect.die(cleanupError)),
856 ),
857 ),
858 ),
859 );
860 },
861 }),
862 });
863 yield* Effect.gen(function* () {
864 const first = yield* installation.start;
865 yield* Deferred.await(cleanupStarted);
866 expect(yield* installation.state).toMatchObject({
867 operationId: first.operationId,
868 phase: "succeeded",
869 installedVersion: "fixture-new",
870 });
871 const current = testCase.restart ? yield* installation.start : first;
872 if (testCase.restart) yield* Deferred.await(nextValidationStarted);
873
874 yield* Deferred.succeed(releaseCleanup, undefined);
875 yield* Fiber.await(yield* Deferred.await(firstWorker));
876 yield* Deferred.await(stagingReleased);
877 expect(yield* installation.state).toMatchObject({
878 operationId: current.operationId,
879 phase: testCase.restart ? "verifying" : "succeeded",
880 installedVersion: "fixture-new",
881 });
882 expect((yield* installation.resolve()).version).toBe("fixture-new");
883
884 yield* Deferred.succeed(releaseNextValidation, undefined);
885 expect(yield* terminalState(installation)).toMatchObject({
886 operationId: current.operationId,
887 phase: "succeeded",
888 installedVersion: "fixture-new",
889 });
890 }).pipe(
891 Effect.ensuring(
892 Deferred.succeed(releaseCleanup, undefined).pipe(
893 Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)),
894 ),
895 ),
896 );
897 }),
898 );
899
900 it.effect(
901 "shares one install across callers and keeps it alive after the caller scope closes",
902 () =>
903 Effect.gen(function* () {
904 const entered = yield* Deferred.make<void>();
905 const release = yield* Deferred.make<void>();
906 const { installation, requests, stagingReleased } = yield* makeHarness({
907 body: Stream.fromEffect(
908 Deferred.succeed(entered, undefined).pipe(
909 Effect.andThen(Deferred.await(release)),
910 Effect.as(completeArchive),
911 ),
912 ),
913 });
914 const callerScope = yield* Scope.make();
915 const started = yield* installation.start.pipe(Scope.provide(callerScope));
916 yield* Deferred.await(entered);
917 yield* Scope.close(callerScope, Exit.void);
918 const concurrent = yield* Effect.all([installation.start, installation.start], {
919 concurrency: "unbounded",
920 });
921 expect(concurrent.map((state) => state.operationId)).toEqual([
922 started.operationId,
923 started.operationId,
924 ]);
925 expect(
926 yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)),
927 ).toMatchObject({ phase: "downloading", operationId: started.operationId });
928 yield* Deferred.succeed(release, undefined);
929 expect((yield* terminalState(installation)).phase).toBe("succeeded");
930 yield* Deferred.await(stagingReleased);
931
932 const next = yield* installation.start;
933 expect(next.operationId).not.toBe(started.operationId);
934 expect(
935 yield* installation
936 .cancel(started.operationId ?? "missing-operation-id")
937 .pipe(Effect.flip),
938 ).toMatchObject({ operation: "cancel" });
939 expect((yield* terminalState(installation)).phase).toBe("succeeded");
940 expect(requests).toHaveLength(1);
941 }),
942 );
943
944 // A simulated Mac install needs POSIX execute bits, which Windows files lack.
945 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
946 "re-signs the Intel Mac runtime ad hoc and records the signed sizes",
947 () =>
948 Effect.gen(function* () {
949 const fs = yield* FileSystem.FileSystem;
950 const signed: Array<ReadonlyArray<string>> = [];
951 const spawner = ChildProcessSpawner.make((command) =>
952 Effect.gen(function* () {
953 if (!ChildProcess.isStandardCommand(command))
954 return yield* Effect.die("Unexpected spawn.");
955 const args = command.args.map(String);
956 signed.push([String(command.command), ...args]);
957 // codesign rewrites the signature, which changes each file's size.
958 for (const file of args.slice(3)) {
959 yield* fs.writeFileString(file, "signature", { flag: "a" });
960 }
961 return ChildProcessSpawner.makeHandle({
962 pid: ChildProcessSpawner.ProcessId(900_000_301),
963 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
964 isRunning: Effect.succeed(false),
965 kill: () => Effect.void,
966 unref: Effect.succeed(Effect.void),
967 stdin: Sink.drain,
968 stdout: Stream.empty,
969 stderr: Stream.empty,
970 all: Stream.empty,
971 getInputFd: () => Sink.drain,
972 getOutputFd: () => Stream.empty,
973 });
974 }).pipe(Effect.orDie),
975 );
976 const { installation, validations } = yield* makeHarness({
977 platform: "darwin",
978 arch: "x64",
979 spawner,
980 });
981 yield* installation.start;
982 expect((yield* terminalState(installation)).phase).toBe("succeeded");
983 const validated = validations[0]?.executable;
984 expect(signed).toEqual([
985 [
986 "/usr/bin/codesign",
987 "--force",
988 "--sign",
989 "-",
990 validated?.executablePath,
991 validated?.harnessPath,
992 ],
993 ]);
994 const selected = yield* installation.resolve();
995 expect(yield* fs.readFileString(selected.executablePath)).toBe(
996 `${serverContents}signature`,
997 );
998 }),
999 );
1000
1001 // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons.
1002 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1003 "accepts the agy CLI without a harness sibling but still requires one for other binaries",
1004 () =>
1005 Effect.gen(function* () {
1006 const fs = yield* FileSystem.FileSystem;
1007 const path = yield* Path.Path;
1008 const baseDir = yield* fs
1009 .makeTempDirectoryScoped({ prefix: "t3-agy-cli-test-" })
1010 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
1011 const cliDirectory = path.join(baseDir, "cli");
1012 yield* fs.makeDirectory(cliDirectory);
1013 const cli = path.join(cliDirectory, "antigravity");
1014 const alias = path.join(cliDirectory, "agy");
1015 const other = path.join(cliDirectory, "custom-acp");
1016 yield* fs.writeFileString(cli, "cli", { mode: 0o755 });
1017 yield* fs.symlink(cli, alias);
1018 yield* fs.writeFileString(other, "other", { mode: 0o755 });
1019 const { installation } = yield* makeHarness({ baseDir });
1020
1021 expect(yield* installation.resolve(cli)).toMatchObject({
1022 executablePath: cli,
1023 harnessPath: null,
1024 source: "override",
1025 version: null,
1026 });
1027 expect(yield* installation.resolve(alias)).toMatchObject({
1028 executablePath: alias,
1029 harnessPath: null,
1030 });
1031 expect(yield* installation.resolve("agy", { PATH: cliDirectory })).toMatchObject({
1032 executablePath: alias,
1033 harnessPath: null,
1034 });
1035 expect(yield* installation.resolve(other).pipe(Effect.flip)).toMatchObject({
1036 operation: "resolve",
1037 });
1038
1039 // Version-manager shims dispatch by their invoked name, so the shim path is what runs.
1040 const shims = path.join(baseDir, "shims");
1041 const mise = path.join(baseDir, "mise");
1042 yield* fs.makeDirectory(shims);
1043 yield* fs.writeFileString(mise, "mise", { mode: 0o755 });
1044 yield* fs.symlink(mise, path.join(shims, "agy"));
1045 expect(yield* installation.resolve("agy", { PATH: shims })).toMatchObject({
1046 executablePath: path.join(shims, "agy"),
1047 harnessPath: null,
1048 });
1049
1050 const { installation: windows } = yield* makeHarness({ baseDir, platform: "win32" });
1051 for (const name of ["agy.EXE", "agy.cmd"]) {
1052 const windowsDirectory = path.join(baseDir, `windows-${name}`);
1053 yield* fs.makeDirectory(windowsDirectory);
1054 yield* fs.writeFileString(path.join(windowsDirectory, name), "cli");
1055 const selected = yield* windows.resolve("agy", { PATH: windowsDirectory });
1056 expect(selected.harnessPath).toBeNull();
1057 expect((yield* fs.realPath(selected.executablePath)).toLowerCase()).toBe(
1058 (yield* fs.realPath(path.join(windowsDirectory, name))).toLowerCase(),
1059 );
1060 }
1061 }),
1062 );
1063
1064 // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons.
1065 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
1066 "honors explicit paths and reports invalid overrides without falling back",
1067 () =>
1068 Effect.gen(function* () {
1069 const fs = yield* FileSystem.FileSystem;
1070 const path = yield* Path.Path;
1071 const baseDir = yield* fs
1072 .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" })
1073 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
1074 const externalDirectory = path.join(baseDir, "external");
1075 const externalExecutable = path.join(externalDirectory, executableName);
1076 const externalHarness = path.join(externalDirectory, harnessName);
1077 yield* fs.makeDirectory(externalDirectory);
1078 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
1079 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
1080 const { installation } = yield* makeHarness({
1081 baseDir,
1082 path: externalDirectory,
1083 previous: true,
1084 });
1085 yield* expectPreviousRelease(installation);
1086 expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({
1087 source: "managed",
1088 version: previousVersion,
1089 });
1090 expect(yield* installation.resolve(externalExecutable)).toMatchObject({
1091 executablePath: externalExecutable,
1092 source: "override",
1093 managedVersionDirectory: null,
1094 });
1095 expect(yield* installation.resolve(executableName)).toMatchObject({
1096 source: "override",
1097 });
1098 expect(
1099 yield* installation
1100 .resolve(`~/external/${executableName}`)
1101 .pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)),
1102 ).toMatchObject({ source: "override", executablePath: externalExecutable });
1103 yield* fs.remove(externalHarness);
1104 expect(yield* installation.resolve(externalExecutable).pipe(Effect.flip)).toMatchObject({
1105 operation: "resolve",
1106 });
1107 expect(
1108 yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip),
1109 ).toMatchObject({
1110 operation: "resolve",
1111 });
1112 yield* expectPreviousRelease(installation);
1113 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
1114 yield* installation.remove();
1115 expect(yield* installation.resolve()).toMatchObject({
1116 source: "path",
1117 executablePath: externalExecutable,
1118 });
1119 const isolated = yield* makeHarness({ baseDir });
1120 expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({
1121 operation: "resolve",
1122 });
1123 expect(
1124 yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }),
1125 ).toMatchObject({
1126 source: "path",
1127 executablePath: externalExecutable,
1128 });
1129 expect(
1130 yield* isolated.installation.resolve(executableName, { PATH: externalDirectory }),
1131 ).toMatchObject({ source: "override", executablePath: externalExecutable });
1132
1133 const incompleteDirectory = path.join(baseDir, "incomplete");
1134 yield* fs.makeDirectory(incompleteDirectory);
1135 yield* fs.writeFileString(path.join(incompleteDirectory, executableName), "no harness", {
1136 mode: 0o755,
1137 });
1138 const shadowedPath = { PATH: `${incompleteDirectory}:${externalDirectory}` };
1139 expect(yield* isolated.installation.resolve(undefined, shadowedPath)).toMatchObject({
1140 source: "path",
1141 executablePath: externalExecutable,
1142 });
1143 expect(yield* isolated.installation.resolve(executableName, shadowedPath)).toMatchObject({
1144 source: "override",
1145 executablePath: externalExecutable,
1146 });
1147 }),
1148 );
1149
1150 it.effect("keeps leased releases available while new sessions resolve the new release", () =>
1151 Effect.gen(function* () {
1152 const manifestEntered = yield* Deferred.make<void>();
1153 const releaseManifest = yield* Deferred.make<void>();
1154 const { installation, fs, stagingReleased } = yield* makeHarness({
1155 native: true,
1156 platform: "win32",
1157 archive: Buffer.from(serverContents),
1158 previous: true,
1159 beforeManifest: Deferred.succeed(manifestEntered, undefined).pipe(
1160 Effect.andThen(Deferred.await(releaseManifest)),
1161 ),
1162 });
1163 const processScope = yield* Scope.make();
1164 const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope));
1165 const starting = yield* installation.start.pipe(Effect.forkScoped);
1166 yield* Deferred.await(manifestEntered);
1167 const concurrent = yield* installation.acquire().pipe(Scope.provide(processScope));
1168 expect(concurrent.executablePath).toBe(oldExecutable.executablePath);
1169 yield* Deferred.succeed(releaseManifest, undefined);
1170 yield* Fiber.join(starting);
1171 expect((yield* terminalState(installation)).phase).toBe("succeeded");
1172 yield* Deferred.await(stagingReleased);
1173 const current = yield* installation.resolve();
1174 expect(current.version).toBe("1.5.7");
1175 expect(current.executablePath).not.toBe(oldExecutable.executablePath);
1176 expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents);
1177 expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" });
1178 yield* Scope.close(processScope, Exit.void);
1179 yield* installation.remove();
1180 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
1181 }),
1182 );
1183
1184 it.effect(
1185 "removes an incomplete active release before reinstalling without a PATH fallback",
1186 () =>
1187 Effect.gen(function* () {
1188 const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true });
1189 const previous = yield* installation.resolve();
1190 yield* fs.remove(previous.harnessPath!);
1191 const externalDirectory = path.join(baseDir, "external");
1192 yield* fs.makeDirectory(externalDirectory);
1193 yield* fs.writeFileString(path.join(externalDirectory, executableName), "external server", {
1194 mode: 0o755,
1195 });
1196 yield* fs.writeFileString(path.join(externalDirectory, harnessName), "external harness", {
1197 mode: 0o755,
1198 });
1199 const restarted = yield* makeHarness({ baseDir, path: externalDirectory });
1200 expect(yield* restarted.installation.state).toMatchObject({
1201 phase: "failed",
1202 installedVersion: null,
1203 canRemove: true,
1204 });
1205 expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({
1206 operation: "resolve",
1207 });
1208 yield* restarted.installation.remove();
1209 expect(yield* restarted.installation.state).toMatchObject({
1210 phase: "idle",
1211 canRemove: false,
1212 });
1213 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
1214 yield* restarted.installation.start;
1215 expect(yield* terminalState(restarted.installation)).toMatchObject({
1216 phase: "succeeded",
1217 installedVersion: "fixture-new",
1218 canRemove: true,
1219 });
1220 yield* Deferred.await(restarted.stagingReleased);
1221 expect((yield* restarted.installation.resolve()).source).toBe("managed");
1222 }),
1223 );
1224
1225 it.effect(
1226 "blocks removal of custom managed paths and leaves external executables and profiles intact",
1227 () =>
1228 Effect.gen(function* () {
1229 const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true });
1230 const managed = yield* installation.resolve();
1231 const externalDirectory = path.join(baseDir, "external");
1232 const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile");
1233 yield* fs.makeDirectory(externalDirectory);
1234 yield* fs.makeDirectory(profileDirectory, { recursive: true });
1235 const externalExecutable = path.join(externalDirectory, executableName);
1236 const externalHarness = path.join(externalDirectory, harnessName);
1237 const profilePath = path.join(profileDirectory, "preferences.json");
1238 yield* fs.writeFileString(externalExecutable, "external server", { mode: 0o755 });
1239 yield* fs.writeFileString(externalHarness, "external harness", { mode: 0o755 });
1240 yield* fs.writeFileString(profilePath, "{}");
1241 expect(
1242 yield* installation.remove([managed.executablePath]).pipe(Effect.flip),
1243 ).toMatchObject({
1244 operation: "remove",
1245 });
1246 yield* expectPreviousRelease(installation);
1247 yield* installation.remove([externalExecutable]);
1248 expect(yield* installation.state).toMatchObject({
1249 phase: "idle",
1250 operationId: null,
1251 installedVersion: null,
1252 });
1253 expect(yield* fs.readFileString(externalExecutable)).toBe("external server");
1254 expect(yield* fs.readFileString(externalHarness)).toBe("external harness");
1255 expect(yield* fs.readFileString(profilePath)).toBe("{}");
1256 }),
1257 );
1258
1259 it.effect(
1260 "reuses an immutable Windows release and preserves the pointer when rename is denied",
1261 () =>
1262 Effect.gen(function* () {
1263 const fs = yield* FileSystem.FileSystem;
1264 const path = yield* Path.Path;
1265 const archive = Buffer.from(zipFixtures.windows, "base64");
1266 const asset = yield* releaseAsset(archive, "win32");
1267 let denyPointerRename = true;
1268 const renameTargets: string[] = [];
1269 const { installation, requests, validations } = yield* makeHarness({
1270 previous: true,
1271 platform: "win32",
1272 archive,
1273 fileSystem: FileSystem.FileSystem.of({
1274 ...fs,
1275 rename: (source, target) => {
1276 renameTargets.push(target);
1277 return denyPointerRename
1278 ? Effect.fail(
1279 PlatformError.systemError({
1280 _tag: "PermissionDenied",
1281 module: "FileSystem",
1282 method: "rename",
1283 pathOrDescriptor: target,
1284 description: "EPERM: file is in use",
1285 }),
1286 )
1287 : fs.rename(source, target);
1288 },
1289 }),
1290 });
1291 yield* writeRelease(installation.managedDirectory, asset, false);
1292 yield* installation.start;
1293 expect((yield* terminalState(installation)).phase).toBe("failed");
1294 yield* expectPreviousRelease(installation);
1295 expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]);
1296
1297 denyPointerRename = false;
1298 yield* installation.start;
1299 expect((yield* terminalState(installation)).phase).toBe("succeeded");
1300 expect((yield* installation.resolve()).version).toBe("fixture-new");
1301 expect(requests).toEqual([]);
1302 expect(validations).toHaveLength(2);
1303 expect(renameTargets).toEqual([
1304 path.join(installation.managedDirectory, "active.json"),
1305 path.join(installation.managedDirectory, "active.json"),
1306 ]);
1307 }),
1308 );
1309
1310 it.effect("reports unsupported hosts without downloading or changing state", () =>
1311 Effect.gen(function* () {
1312 const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" });
1313 expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" });
1314 expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({
1315 operation: "resolve",
1316 });
1317 expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null });
1318 expect(requests).toEqual([]);
1319 }),
1320 );
1321});