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

AntigravityInstallation.test.ts

1,250 lines53.7 KB

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