The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import { expect, it } from "@effect/vitest"; |
| 5 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 6 | import * as Digest from "effect/crypto/Digest"; |
| 7 | import * as Deferred from "effect/Deferred"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Hex from "effect/encoding/Hex"; |
| 10 | import * as Exit from "effect/Exit"; |
| 11 | import * as Fiber from "effect/Fiber"; |
| 12 | import * as FileSystem from "effect/FileSystem"; |
| 13 | import * as Option from "effect/Option"; |
| 14 | import * as Path from "effect/Path"; |
| 15 | import * as PlatformError from "effect/PlatformError"; |
| 16 | import * as Schema from "effect/Schema"; |
| 17 | import * as Scope from "effect/Scope"; |
| 18 | import * as Sink from "effect/Sink"; |
| 19 | import * as Stream from "effect/Stream"; |
| 20 | import * as TestClock from "effect/testing/TestClock"; |
| 21 | import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; |
| 22 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 23 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 24 | |
| 25 | import * as AntigravityInstallation from "./AntigravityInstallation.ts"; |
| 26 | import * as ModelManifest from "./ModelManifest.ts"; |
| 27 | import { type AntigravityCliReleaseAsset } from "./antigravityCliRelease.ts"; |
| 28 | |
| 29 | const serverContents = "antigravity runtime\n"; |
| 30 | const previousReleaseId = "1".repeat(64); |
| 31 | const previousVersion = "1.5.3"; |
| 32 | const assetVersion = "1.5.5"; |
| 33 | const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); |
| 34 | // One regular member, `antigravity`, holding serverContents. |
| 35 | const cliTarball = Buffer.from( |
| 36 | "H4sIAAAAAAACE+3RMQ7CQAwEQNe8Ik8wgYj3XIFQCiiOCxK/56CJRA9CYqZZrxsXLpc2n2q5ze0en5LdYZpe2b1n5rhf5+d+m+MuY8j4guXaSu3n4z+V9f9DXXo5HzcBAAAAAAAAAADAz3sA56lbdQAoAAA=", |
| 37 | "base64", |
| 38 | ); |
| 39 | |
| 40 | // Linux platform mocks cannot enforce POSIX exec bits on NTFS; use the host platform. |
| 41 | const hostPlatform: NodeJS.Platform = |
| 42 | HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux"; |
| 43 | const completeArchive = hostPlatform === "win32" ? Buffer.from(serverContents) : cliTarball; |
| 44 | const executableName = hostPlatform === "win32" ? "agy.exe" : "antigravity"; |
| 45 | |
| 46 | const releaseAsset = Effect.fn("test.antigravityReleaseAsset")(function* ( |
| 47 | archive: Uint8Array = completeArchive, |
| 48 | platform: NodeJS.Platform = hostPlatform, |
| 49 | ) { |
| 50 | const digest = yield* Digest.Digest; |
| 51 | return { |
| 52 | version: assetVersion, |
| 53 | url: "https://storage.googleapis.com/antigravity-test", |
| 54 | sha512: Hex.encode(yield* digest.digest(Digest.sha512, archive).pipe(Effect.orDie)), |
| 55 | executable: { name: platform === "win32" ? "agy.exe" : "antigravity" }, |
| 56 | format: platform === "win32" ? "executable" : "tar.gz", |
| 57 | } satisfies AntigravityCliReleaseAsset; |
| 58 | }); |
| 59 | |
| 60 | const writeRelease = Effect.fn("test.writeAntigravityRelease")(function* ( |
| 61 | managedDirectory: string, |
| 62 | release: { readonly releaseId: string; readonly version: string; readonly name: string }, |
| 63 | active = true, |
| 64 | ) { |
| 65 | const fs = yield* FileSystem.FileSystem; |
| 66 | const path = yield* Path.Path; |
| 67 | const directory = path.join(managedDirectory, "versions", release.releaseId); |
| 68 | yield* fs.makeDirectory(directory, { recursive: true }); |
| 69 | yield* fs.writeFileString(path.join(directory, release.name), serverContents, { mode: 0o755 }); |
| 70 | yield* fs.writeFileString( |
| 71 | path.join(directory, ".install-complete.json"), |
| 72 | encodeJsonString({ |
| 73 | releaseId: release.releaseId, |
| 74 | version: release.version, |
| 75 | executable: { name: release.name, bytes: Buffer.byteLength(serverContents) }, |
| 76 | }), |
| 77 | ); |
| 78 | if (active) { |
| 79 | yield* fs.writeFileString( |
| 80 | path.join(managedDirectory, "active.json"), |
| 81 | encodeJsonString({ releaseId: release.releaseId }), |
| 82 | ); |
| 83 | } |
| 84 | }); |
| 85 | |
| 86 | const assetRelease = (asset: AntigravityCliReleaseAsset) => ({ |
| 87 | releaseId: asset.sha512.slice(0, 64), |
| 88 | version: asset.version, |
| 89 | name: asset.executable.name, |
| 90 | }); |
| 91 | |
| 92 | interface HarnessOptions { |
| 93 | readonly baseDir?: string; |
| 94 | readonly asset?: AntigravityCliReleaseAsset | null; |
| 95 | readonly archive?: Buffer; |
| 96 | readonly body?: Stream.Stream<Uint8Array> | undefined; |
| 97 | readonly platform?: NodeJS.Platform; |
| 98 | readonly arch?: NodeJS.Architecture; |
| 99 | readonly path?: string; |
| 100 | readonly previous?: boolean; |
| 101 | readonly fileSystem?: FileSystem.FileSystem; |
| 102 | readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; |
| 103 | readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"]; |
| 104 | readonly useDefaultValidation?: boolean; |
| 105 | readonly connectTimeout?: boolean; |
| 106 | readonly manifest?: Effect.Effect<ModelManifest.ModelManifestData>; |
| 107 | readonly native?: boolean; |
| 108 | readonly nativeVersion?: string; |
| 109 | readonly nativeManifest?: (manifest: { version: string; url: string; sha512: string }) => unknown; |
| 110 | readonly beforeManifest?: Effect.Effect<void>; |
| 111 | readonly updateChecksEnabled?: Effect.Effect<boolean>; |
| 112 | } |
| 113 | |
| 114 | const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( |
| 115 | options: HarnessOptions = {}, |
| 116 | ) { |
| 117 | const fs = yield* FileSystem.FileSystem; |
| 118 | const path = yield* Path.Path; |
| 119 | const digest = yield* Digest.Digest; |
| 120 | const baseDir = |
| 121 | options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" })); |
| 122 | const platform = options.platform ?? hostPlatform; |
| 123 | const arch = options.arch ?? "x64"; |
| 124 | const archive = options.archive ?? completeArchive; |
| 125 | const asset = |
| 126 | options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset; |
| 127 | const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`); |
| 128 | if (options.baseDir === undefined && HostProcess.Platform.defaultValue() !== "win32") { |
| 129 | const versionsDir = path.join(managedDirectory, "versions"); |
| 130 | yield* Effect.addFinalizer(() => |
| 131 | fs.readDirectory(versionsDir).pipe( |
| 132 | Effect.flatMap((entries) => |
| 133 | Effect.forEach(entries, (entry) => |
| 134 | fs.chmod(path.join(versionsDir, entry), 0o700).pipe(Effect.ignore), |
| 135 | ), |
| 136 | ), |
| 137 | Effect.ignore, |
| 138 | ), |
| 139 | ); |
| 140 | } |
| 141 | if (options.previous) { |
| 142 | yield* writeRelease(managedDirectory, { |
| 143 | releaseId: previousReleaseId, |
| 144 | version: previousVersion, |
| 145 | name: platform === "win32" ? "agy.exe" : "antigravity", |
| 146 | }); |
| 147 | } |
| 148 | const stagingReleased = yield* Deferred.make<void>(); |
| 149 | const requests: string[] = []; |
| 150 | const validations: Array<{ |
| 151 | executable: AntigravityInstallation.AntigravityExecutable; |
| 152 | version: string; |
| 153 | }> = []; |
| 154 | const installationFs = options.fileSystem ?? fs; |
| 155 | const trackedFs = FileSystem.FileSystem.of({ |
| 156 | ...installationFs, |
| 157 | makeTempDirectoryScoped: (settings) => |
| 158 | settings?.prefix === ".install-" |
| 159 | ? Effect.acquireRelease(installationFs.makeTempDirectory(settings), (directory) => |
| 160 | fs |
| 161 | .remove(directory, { recursive: true, force: true }) |
| 162 | .pipe(Effect.orDie, Effect.andThen(Deferred.succeed(stagingReleased, undefined))), |
| 163 | ) |
| 164 | : installationFs.makeTempDirectoryScoped(settings), |
| 165 | }); |
| 166 | const installation = yield* AntigravityInstallation.makeAntigravityInstallation({ |
| 167 | baseDir, |
| 168 | ...(options.native ? {} : { releaseAsset: asset }), |
| 169 | ...(options.updateChecksEnabled === undefined |
| 170 | ? {} |
| 171 | : { updateChecksEnabled: options.updateChecksEnabled }), |
| 172 | ...(options.useDefaultValidation |
| 173 | ? {} |
| 174 | : { |
| 175 | validate: (executable: AntigravityInstallation.AntigravityExecutable, version: string) => |
| 176 | Effect.sync(() => validations.push({ executable, version })).pipe( |
| 177 | Effect.andThen(options.validate?.(executable, version) ?? Effect.void), |
| 178 | ), |
| 179 | }), |
| 180 | }).pipe( |
| 181 | options.spawner |
| 182 | ? Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, options.spawner) |
| 183 | : (effect) => effect, |
| 184 | Effect.provideService(FileSystem.FileSystem, trackedFs), |
| 185 | Effect.provideService(HostProcess.Platform, platform), |
| 186 | Effect.provideService(HostProcess.Architecture, arch), |
| 187 | Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }), |
| 188 | Effect.provideService(ModelManifest.ModelManifest, { |
| 189 | current: options.manifest ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), |
| 190 | refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), |
| 191 | forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), |
| 192 | refreshOnDemand: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), |
| 193 | refreshInBackground: Effect.void, |
| 194 | }), |
| 195 | Effect.provideService( |
| 196 | HttpClient.HttpClient, |
| 197 | HttpClient.make((request) => |
| 198 | Effect.suspend(() => { |
| 199 | requests.push(request.url); |
| 200 | if (request.url.includes("/manifests/")) { |
| 201 | return Effect.gen(function* () { |
| 202 | yield* options.beforeManifest ?? Effect.void; |
| 203 | const version = options.nativeVersion ?? "1.5.7"; |
| 204 | const folder = platform === "win32" ? "windows-x64" : "linux-x64"; |
| 205 | const manifest = { |
| 206 | version, |
| 207 | url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/${version}-123/${folder}/cli_${platform === "win32" ? "windows_x64.exe" : "linux_x64.tar.gz"}`, |
| 208 | sha512: Hex.encode(yield* digest.digest(Digest.sha512, archive).pipe(Effect.orDie)), |
| 209 | }; |
| 210 | return HttpClientResponse.fromWeb( |
| 211 | request, |
| 212 | new Response(JSON.stringify(options.nativeManifest?.(manifest) ?? manifest)), |
| 213 | ); |
| 214 | }); |
| 215 | } |
| 216 | if (options.connectTimeout) { |
| 217 | return Effect.fail( |
| 218 | new HttpClientError.HttpClientError({ |
| 219 | reason: new HttpClientError.TransportError({ |
| 220 | request, |
| 221 | cause: new Error("Connect Timeout Error (attempted address: dl.google.com:443)"), |
| 222 | }), |
| 223 | }), |
| 224 | ); |
| 225 | } |
| 226 | const response = HttpClientResponse.fromWeb(request, new Response(null)); |
| 227 | return Effect.succeed( |
| 228 | Object.defineProperty(response, "stream", { |
| 229 | value: |
| 230 | options.body ?? |
| 231 | Stream.make( |
| 232 | archive.subarray(0, 31), |
| 233 | archive.subarray(31, 149), |
| 234 | archive.subarray(149), |
| 235 | ), |
| 236 | }), |
| 237 | ); |
| 238 | }), |
| 239 | ), |
| 240 | ), |
| 241 | ); |
| 242 | return { installation, fs, path, baseDir, requests, validations, stagingReleased }; |
| 243 | }); |
| 244 | |
| 245 | const terminalState = (installation: AntigravityInstallation.AntigravityInstallation["Service"]) => |
| 246 | installation.changes.pipe( |
| 247 | Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)), |
| 248 | Stream.runHead, |
| 249 | Effect.map(Option.getOrThrow), |
| 250 | ); |
| 251 | |
| 252 | const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease")(function* ( |
| 253 | installation: AntigravityInstallation.AntigravityInstallation["Service"], |
| 254 | ) { |
| 255 | const fs = yield* FileSystem.FileSystem; |
| 256 | const path = yield* Path.Path; |
| 257 | const resolved = yield* installation.resolve(); |
| 258 | expect(resolved.version).toBe(previousVersion); |
| 259 | expect(resolved.managedVersionDirectory).toBe( |
| 260 | path.join(installation.managedDirectory, "versions", previousReleaseId), |
| 261 | ); |
| 262 | expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents); |
| 263 | expect((yield* installation.state).installedVersion).toBe(previousVersion); |
| 264 | }); |
| 265 | |
| 266 | it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity installation", (it) => { |
| 267 | it.effect.each([...new Set(["win32", hostPlatform])] as NodeJS.Platform[])( |
| 268 | "replaces a managed runtime from before the Antigravity CLI on %s", |
| 269 | (platform) => |
| 270 | Effect.gen(function* () { |
| 271 | const archive = platform === "win32" ? Buffer.from(serverContents) : cliTarball; |
| 272 | const { installation, validations, requests, fs, path, baseDir, stagingReleased } = |
| 273 | yield* makeHarness({ native: true, archive, platform }); |
| 274 | // A 1.4.x install recorded agy_acp_server with its localharness_external sibling. |
| 275 | const legacyId = "2".repeat(64); |
| 276 | const legacyDirectory = path.join(installation.managedDirectory, "versions", legacyId); |
| 277 | yield* fs.makeDirectory(legacyDirectory, { recursive: true }); |
| 278 | yield* fs.writeFileString( |
| 279 | path.join(legacyDirectory, "agy_acp_server.par"), |
| 280 | serverContents, |
| 281 | { |
| 282 | mode: 0o755, |
| 283 | }, |
| 284 | ); |
| 285 | yield* fs.writeFileString( |
| 286 | path.join(legacyDirectory, ".install-complete.json"), |
| 287 | encodeJsonString({ |
| 288 | releaseId: legacyId, |
| 289 | version: "1.4.5", |
| 290 | executable: { name: "agy_acp_server.par", bytes: Buffer.byteLength(serverContents) }, |
| 291 | harness: { name: "localharness_external", bytes: 1 }, |
| 292 | }), |
| 293 | ); |
| 294 | yield* fs.writeFileString( |
| 295 | path.join(installation.managedDirectory, "active.json"), |
| 296 | encodeJsonString({ releaseId: legacyId }), |
| 297 | ); |
| 298 | expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({ |
| 299 | operation: "resolve", |
| 300 | detail: expect.stringContaining("Antigravity 1.4.5 predates the Antigravity CLI"), |
| 301 | }); |
| 302 | yield* installation.start; |
| 303 | expect(yield* terminalState(installation)).toMatchObject({ |
| 304 | phase: "succeeded", |
| 305 | installedVersion: "1.5.7", |
| 306 | }); |
| 307 | yield* Deferred.await(stagingReleased); |
| 308 | const resolved = yield* installation.resolve(); |
| 309 | expect(resolved).toMatchObject({ source: "managed", version: "1.5.7" }); |
| 310 | expect(validations).toHaveLength(1); |
| 311 | expect(yield* fs.exists(legacyDirectory)).toBe(false); |
| 312 | expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents); |
| 313 | expect(requests.some((url) => url.includes("/manifests/"))).toBe(true); |
| 314 | const restarted = yield* makeHarness({ |
| 315 | baseDir, |
| 316 | native: true, |
| 317 | archive, |
| 318 | platform, |
| 319 | nativeVersion: "1.5.6", |
| 320 | }); |
| 321 | expect(yield* restarted.installation.start).toMatchObject({ |
| 322 | phase: "verifying", |
| 323 | message: "Checking the installed runtime.", |
| 324 | }); |
| 325 | expect(yield* terminalState(restarted.installation)).toMatchObject({ |
| 326 | phase: "succeeded", |
| 327 | installedVersion: "1.5.7", |
| 328 | }); |
| 329 | expect(restarted.requests.filter((url) => url.includes("storage.googleapis.com"))).toEqual( |
| 330 | [], |
| 331 | ); |
| 332 | expect((yield* restarted.installation.resolve()).executablePath).toBe( |
| 333 | resolved.executablePath, |
| 334 | ); |
| 335 | }), |
| 336 | ); |
| 337 | |
| 338 | // These tar fixtures exercise the POSIX extraction path; Windows downloads one executable. |
| 339 | it.effect.skipIf(hostPlatform === "win32")( |
| 340 | "rejects unsafe native tar members before activation", |
| 341 | () => |
| 342 | Effect.gen(function* () { |
| 343 | for (const archive of [ |
| 344 | "H4sIAAAAAAACE+3OMQqDQBAFUI/iCYxZJPdZMIRtFHQN5PYOKbW2EN5j4P9iYCZPtXyW/C3111ylD69h+Gc45rk/U4r1NnXdI2be6lrG90XPbWvNS5xvAAAAAAAAAAAA4D523kNDtgAoAAA=", |
| 345 | "H4sIAAAAAAACE+3RMQ7CMBAEQNe8Ii8IBhzxHhcIpYDCcSLxewwNiJ4IiZlmb6+54vp+m691PJe8jPUWviI2x2F4ZvOZMe7Ta37sdzGlQ+hiWME81Vza+fCf3p7flbmVy2kTAAAAAAAAAAAA+Hl3jhn2/wAoAAA=", |
| 346 | "H4sIAAAAAAACE+3TPQrCQBAG0K09RY4wRoPn2UJCClOsG8Hbu6YJ2CtI3mvmp5li+PJcp7Hkx1Sf6VuiuQzDWpvPGtGft/69P0Z/itRF+oHlXnNp59M+5e3/XVnacLseEnv8v/zLv/wDAAAAAAAAAPyZF/c+VksAKAAA", |
| 347 | ]) { |
| 348 | const { installation, validations } = yield* makeHarness({ |
| 349 | native: true, |
| 350 | archive: Buffer.from(archive, "base64"), |
| 351 | platform: "linux", |
| 352 | previous: true, |
| 353 | }); |
| 354 | yield* installation.start; |
| 355 | expect((yield* terminalState(installation)).phase).toBe("failed"); |
| 356 | expect(validations).toEqual([]); |
| 357 | yield* expectPreviousRelease(installation); |
| 358 | } |
| 359 | }), |
| 360 | ); |
| 361 | |
| 362 | it.effect.each([true, false])( |
| 363 | "respects background update checks (%s) while allowing explicit installation", |
| 364 | (enabled) => |
| 365 | Effect.gen(function* () { |
| 366 | const { installation, requests } = yield* makeHarness({ |
| 367 | native: true, |
| 368 | archive: Buffer.from(serverContents), |
| 369 | platform: "win32", |
| 370 | updateChecksEnabled: Effect.succeed(enabled), |
| 371 | }); |
| 372 | yield* installation.checkForUpdate; |
| 373 | if (enabled) { |
| 374 | yield* installation.changes.pipe( |
| 375 | Stream.filter((value) => value.version === "1.5.7"), |
| 376 | Stream.runHead, |
| 377 | ); |
| 378 | yield* installation.state; |
| 379 | expect(requests).toHaveLength(1); |
| 380 | } else { |
| 381 | yield* installation.changes.pipe(Stream.runHead); |
| 382 | expect(requests).toEqual([]); |
| 383 | } |
| 384 | yield* installation.start; |
| 385 | expect((yield* terminalState(installation)).phase).toBe("succeeded"); |
| 386 | }), |
| 387 | ); |
| 388 | |
| 389 | it.effect("keeps withdrawn native releases from activating or launching", () => |
| 390 | Effect.gen(function* () { |
| 391 | let withdrawn = false; |
| 392 | const manifest = Effect.sync(() => |
| 393 | withdrawn |
| 394 | ? ({ |
| 395 | ...ModelManifest.BUNDLED_MODEL_MANIFEST, |
| 396 | compatibility: [ |
| 397 | { |
| 398 | driver: "antigravity", |
| 399 | t3CodeRange: ">=0.0.42", |
| 400 | ranges: [{ range: ">=1.5.7", status: "broken" }], |
| 401 | }, |
| 402 | ], |
| 403 | } satisfies ModelManifest.ModelManifestData) |
| 404 | : ModelManifest.BUNDLED_MODEL_MANIFEST, |
| 405 | ); |
| 406 | const first = yield* makeHarness({ |
| 407 | native: true, |
| 408 | archive: Buffer.from(serverContents), |
| 409 | platform: "win32", |
| 410 | previous: true, |
| 411 | manifest, |
| 412 | validate: () => |
| 413 | Effect.sync(() => { |
| 414 | withdrawn = true; |
| 415 | }), |
| 416 | }); |
| 417 | yield* first.installation.start; |
| 418 | expect((yield* terminalState(first.installation)).phase).toBe("failed"); |
| 419 | yield* expectPreviousRelease(first.installation); |
| 420 | withdrawn = false; |
| 421 | const retry = yield* makeHarness({ |
| 422 | baseDir: first.baseDir, |
| 423 | native: true, |
| 424 | archive: Buffer.from(serverContents), |
| 425 | platform: "win32", |
| 426 | manifest, |
| 427 | }); |
| 428 | yield* retry.installation.start; |
| 429 | expect((yield* terminalState(retry.installation)).phase).toBe("succeeded"); |
| 430 | withdrawn = true; |
| 431 | expect(yield* retry.installation.resolve().pipe(Effect.flip)).toMatchObject({ |
| 432 | operation: "resolve", |
| 433 | }); |
| 434 | expect(yield* retry.installation.start.pipe(Effect.flip)).toMatchObject({ |
| 435 | operation: "start", |
| 436 | }); |
| 437 | const recovery = yield* makeHarness({ |
| 438 | baseDir: first.baseDir, |
| 439 | native: true, |
| 440 | nativeVersion: "1.5.6", |
| 441 | archive: Buffer.from("recovery runtime"), |
| 442 | platform: "win32", |
| 443 | manifest, |
| 444 | }); |
| 445 | yield* recovery.installation.checkForUpdate; |
| 446 | expect(yield* recovery.installation.state).toMatchObject({ |
| 447 | installedVersion: "1.5.7", |
| 448 | version: "1.5.6", |
| 449 | }); |
| 450 | yield* recovery.installation.start; |
| 451 | expect(yield* terminalState(recovery.installation)).toMatchObject({ |
| 452 | phase: "succeeded", |
| 453 | installedVersion: "1.5.6", |
| 454 | }); |
| 455 | }), |
| 456 | ); |
| 457 | |
| 458 | it.effect("discovers subsequent native releases from Google's CLI channel", () => |
| 459 | Effect.gen(function* () { |
| 460 | const first = yield* makeHarness({ |
| 461 | native: true, |
| 462 | archive: Buffer.from(serverContents), |
| 463 | platform: "win32", |
| 464 | }); |
| 465 | yield* first.installation.start; |
| 466 | expect((yield* terminalState(first.installation)).phase).toBe("succeeded"); |
| 467 | const initialPath = (yield* first.installation.resolve()).executablePath; |
| 468 | const next = yield* makeHarness({ |
| 469 | baseDir: first.baseDir, |
| 470 | native: true, |
| 471 | nativeVersion: "1.5.8", |
| 472 | archive: Buffer.from("next runtime"), |
| 473 | platform: "win32", |
| 474 | }); |
| 475 | yield* next.installation.start; |
| 476 | expect(yield* terminalState(next.installation)).toMatchObject({ |
| 477 | phase: "succeeded", |
| 478 | installedVersion: "1.5.8", |
| 479 | }); |
| 480 | const nextPath = (yield* next.installation.resolve()).executablePath; |
| 481 | expect(nextPath).not.toBe(initialPath); |
| 482 | const republished = yield* makeHarness({ |
| 483 | baseDir: first.baseDir, |
| 484 | native: true, |
| 485 | nativeVersion: "1.5.8", |
| 486 | archive: Buffer.from("republished runtime"), |
| 487 | platform: "win32", |
| 488 | }); |
| 489 | yield* republished.installation.start; |
| 490 | expect((yield* terminalState(republished.installation)).phase).toBe("succeeded"); |
| 491 | expect((yield* republished.installation.resolve()).executablePath).not.toBe(nextPath); |
| 492 | const offline = yield* makeHarness({ |
| 493 | baseDir: first.baseDir, |
| 494 | native: true, |
| 495 | nativeManifest: () => ({}), |
| 496 | archive: Buffer.from("unused"), |
| 497 | platform: "win32", |
| 498 | }); |
| 499 | yield* offline.installation.start; |
| 500 | expect(yield* terminalState(offline.installation)).toMatchObject({ |
| 501 | phase: "succeeded", |
| 502 | installedVersion: "1.5.8", |
| 503 | }); |
| 504 | expect(offline.requests.filter((url) => url.includes("storage.googleapis.com"))).toEqual([]); |
| 505 | }), |
| 506 | ); |
| 507 | |
| 508 | it.effect.each([ |
| 509 | { |
| 510 | name: "invalid checksum", |
| 511 | change: (manifest: { version: string; url: string; sha512: string }) => ({ |
| 512 | ...manifest, |
| 513 | sha512: "0".repeat(128), |
| 514 | }), |
| 515 | }, |
| 516 | { |
| 517 | name: "foreign download", |
| 518 | change: (manifest: { version: string; url: string; sha512: string }) => ({ |
| 519 | ...manifest, |
| 520 | url: "https://example.com/agy.exe", |
| 521 | }), |
| 522 | }, |
| 523 | ])("rejects a native $name and preserves the previous release", ({ change }) => |
| 524 | Effect.gen(function* () { |
| 525 | const { installation, validations, requests } = yield* makeHarness({ |
| 526 | native: true, |
| 527 | nativeManifest: change, |
| 528 | archive: Buffer.from(serverContents), |
| 529 | platform: "win32", |
| 530 | previous: true, |
| 531 | }); |
| 532 | const result = yield* Effect.result(installation.start); |
| 533 | // Without an acceptable release, start re-verifies the installed one. |
| 534 | if (result._tag === "Success") yield* terminalState(installation); |
| 535 | expect(validations.map(({ version }) => version)).not.toContain("1.5.7"); |
| 536 | expect(requests.some((url) => url.startsWith("https://example.com"))).toBe(false); |
| 537 | yield* expectPreviousRelease(installation); |
| 538 | }), |
| 539 | ); |
| 540 | |
| 541 | it.effect("reports missing Node before downloading the standalone provider runtime", () => |
| 542 | Effect.gen(function* () { |
| 543 | const { installation, requests, validations } = yield* makeHarness(); |
| 544 | yield* installation.start; |
| 545 | expect(yield* terminalState(installation)).toMatchObject({ |
| 546 | phase: "failed", |
| 547 | message: expect.stringContaining("Install Node.js"), |
| 548 | }); |
| 549 | expect(requests).toEqual([]); |
| 550 | expect(validations).toEqual([]); |
| 551 | }).pipe(Effect.provideService(HostProcess.IsExecutable, true)), |
| 552 | ); |
| 553 | |
| 554 | it.effect("verifies the executable before activating a streamed download", () => |
| 555 | Effect.gen(function* () { |
| 556 | const enteredValidation = yield* Deferred.make<void>(); |
| 557 | const finishValidation = yield* Deferred.make<void>(); |
| 558 | const { installation, fs, path, validations, requests, stagingReleased } = yield* makeHarness( |
| 559 | { |
| 560 | previous: true, |
| 561 | validate: () => |
| 562 | Deferred.succeed(enteredValidation, undefined).pipe( |
| 563 | Effect.andThen(Deferred.await(finishValidation)), |
| 564 | ), |
| 565 | }, |
| 566 | ); |
| 567 | const initial = yield* installation.changes.pipe( |
| 568 | Stream.runHead, |
| 569 | Effect.map(Option.getOrThrow), |
| 570 | ); |
| 571 | expect(initial).toMatchObject({ phase: "idle", installedVersion: previousVersion }); |
| 572 | const started = yield* installation.start; |
| 573 | expect(started).toMatchObject({ phase: "downloading", downloadedBytes: 0 }); |
| 574 | yield* Deferred.await(enteredValidation); |
| 575 | yield* expectPreviousRelease(installation); |
| 576 | const validation = validations[0]; |
| 577 | expect(validation?.version).toBe(assetVersion); |
| 578 | if (!validation) return yield* Effect.die("Expected runtime validation."); |
| 579 | expect(yield* fs.readFileString(validation.executable.executablePath)).toBe(serverContents); |
| 580 | |
| 581 | yield* Deferred.succeed(finishValidation, undefined); |
| 582 | expect(yield* terminalState(installation)).toMatchObject({ |
| 583 | phase: "succeeded", |
| 584 | operationId: started.operationId, |
| 585 | installedVersion: assetVersion, |
| 586 | }); |
| 587 | yield* Deferred.await(stagingReleased); |
| 588 | const selected = yield* installation.resolve(); |
| 589 | expect(selected).toMatchObject({ source: "managed", version: assetVersion }); |
| 590 | expect(yield* fs.readFileString(selected.executablePath)).toBe(serverContents); |
| 591 | expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual( |
| 592 | [assetRelease(yield* releaseAsset()).releaseId], |
| 593 | ); |
| 594 | expect(requests).toEqual([(yield* releaseAsset()).url]); |
| 595 | }), |
| 596 | ); |
| 597 | |
| 598 | it.effect.each([ |
| 599 | { name: "checksum mismatch", completeAsset: { sha512: "2".repeat(128) } }, |
| 600 | { name: "short download", archive: completeArchive.subarray(0, -1), completeAsset: {} }, |
| 601 | { |
| 602 | name: "oversized download", |
| 603 | archive: Buffer.concat([completeArchive, Buffer.from("extra")]), |
| 604 | completeAsset: {}, |
| 605 | }, |
| 606 | ])("rejects $name before runtime validation", ({ completeAsset, ...options }) => |
| 607 | Effect.gen(function* () { |
| 608 | const asset = |
| 609 | completeAsset === undefined ? undefined : { ...(yield* releaseAsset()), ...completeAsset }; |
| 610 | const { installation, validations, stagingReleased, fs, path } = yield* makeHarness({ |
| 611 | ...options, |
| 612 | ...(asset === undefined ? {} : { asset }), |
| 613 | previous: true, |
| 614 | }); |
| 615 | yield* installation.start; |
| 616 | const state = yield* terminalState(installation); |
| 617 | expect(state.phase).toBe("failed"); |
| 618 | expect(state.message).toBeTruthy(); |
| 619 | expect(validations).toEqual([]); |
| 620 | yield* Deferred.await(stagingReleased); |
| 621 | yield* expectPreviousRelease(installation); |
| 622 | expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual( |
| 623 | [previousReleaseId], |
| 624 | ); |
| 625 | }), |
| 626 | ); |
| 627 | |
| 628 | it.effect( |
| 629 | "names the connection failure instead of disk space when the download cannot connect", |
| 630 | () => |
| 631 | Effect.gen(function* () { |
| 632 | const { installation, validations } = yield* makeHarness({ connectTimeout: true }); |
| 633 | yield* installation.start; |
| 634 | const state = yield* terminalState(installation); |
| 635 | expect(state.phase).toBe("failed"); |
| 636 | expect(state.message).not.toMatch(/disk space/i); |
| 637 | expect(state.message).toMatch(/connect|network|download/i); |
| 638 | expect(validations).toEqual([]); |
| 639 | }), |
| 640 | ); |
| 641 | |
| 642 | // The runtime's own abort is a real process; Windows has no POSIX sh. |
| 643 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 644 | "explains that the linux-arm64 runtime needs 4 KiB pages when it aborts on a 16 KiB kernel", |
| 645 | () => |
| 646 | Effect.gen(function* () { |
| 647 | const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 648 | // Google's linux-arm64 build aborts like this on Asahi and Raspberry Pi 5 kernels. |
| 649 | const spawner = ChildProcessSpawner.make((command) => |
| 650 | ChildProcess.isStandardCommand(command) && |
| 651 | String(command.command).endsWith(executableName) |
| 652 | ? realSpawner.spawn( |
| 653 | ChildProcess.make( |
| 654 | "sh", |
| 655 | [ |
| 656 | "-c", |
| 657 | "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 $$", |
| 658 | ], |
| 659 | { stdin: "pipe", stdout: "pipe", stderr: "pipe" }, |
| 660 | ), |
| 661 | ) |
| 662 | : realSpawner.spawn(command), |
| 663 | ); |
| 664 | const { installation } = yield* makeHarness({ |
| 665 | arch: "arm64", |
| 666 | useDefaultValidation: true, |
| 667 | spawner, |
| 668 | }); |
| 669 | yield* installation.start; |
| 670 | const state = yield* terminalState(installation); |
| 671 | expect(state.phase).toBe("failed"); |
| 672 | expect(state.message).toMatch(/page/i); |
| 673 | }), |
| 674 | ); |
| 675 | |
| 676 | it.effect.each(["downloaded", "existing", "concurrent"] as const)( |
| 677 | "reports a verification timeout for a %s runtime without changing the active release", |
| 678 | (source) => |
| 679 | Effect.gen(function* () { |
| 680 | const fs = yield* FileSystem.FileSystem; |
| 681 | const path = yield* Path.Path; |
| 682 | const asset = yield* releaseAsset(); |
| 683 | const entered = yield* Deferred.make<void>(); |
| 684 | let verificationCount = 0; |
| 685 | const { installation, stagingReleased, requests, validations } = yield* makeHarness({ |
| 686 | previous: true, |
| 687 | asset, |
| 688 | fileSystem: FileSystem.FileSystem.of({ |
| 689 | ...fs, |
| 690 | rename: (from, to) => |
| 691 | source === "concurrent" && path.basename(path.dirname(to)) === "versions" |
| 692 | ? writeRelease(path.dirname(path.dirname(to)), assetRelease(asset), false).pipe( |
| 693 | Effect.provideService(FileSystem.FileSystem, fs), |
| 694 | Effect.provideService(Path.Path, path), |
| 695 | Effect.andThen( |
| 696 | Effect.fail( |
| 697 | PlatformError.systemError({ |
| 698 | _tag: "AlreadyExists", |
| 699 | module: "FileSystem", |
| 700 | method: "rename", |
| 701 | pathOrDescriptor: to, |
| 702 | }), |
| 703 | ), |
| 704 | ), |
| 705 | ) |
| 706 | : fs.rename(from, to), |
| 707 | }), |
| 708 | validate: () => |
| 709 | Effect.suspend(() => |
| 710 | source === "concurrent" && verificationCount++ === 0 |
| 711 | ? Effect.void |
| 712 | : Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never)), |
| 713 | ), |
| 714 | }); |
| 715 | if (source === "existing") { |
| 716 | yield* writeRelease(installation.managedDirectory, assetRelease(asset), false); |
| 717 | } |
| 718 | yield* installation.start; |
| 719 | yield* Deferred.await(entered); |
| 720 | yield* TestClock.adjust("90 seconds"); |
| 721 | expect(yield* terminalState(installation)).toMatchObject({ |
| 722 | phase: "failed", |
| 723 | message: |
| 724 | "Antigravity runtime verification timed out after 90 seconds. Check this environment's server logs for startup errors, then retry installation.", |
| 725 | }); |
| 726 | if (source !== "existing") yield* Deferred.await(stagingReleased); |
| 727 | yield* expectPreviousRelease(installation); |
| 728 | expect(requests).toHaveLength(source === "existing" ? 0 : 1); |
| 729 | expect(validations).toHaveLength(source === "concurrent" ? 2 : 1); |
| 730 | }), |
| 731 | ); |
| 732 | |
| 733 | // Windows hosts copy the downloaded executable, so no extraction stream exists there. |
| 734 | it.effect.each( |
| 735 | hostPlatform === "win32" |
| 736 | ? (["download", "active pointer"] as const) |
| 737 | : (["download", "extract", "active pointer"] as const), |
| 738 | )("preserves the old runtime after an ENOSPC error during %s", (stage) => |
| 739 | Effect.gen(function* () { |
| 740 | const fs = yield* FileSystem.FileSystem; |
| 741 | const noSpace = PlatformError.systemError({ |
| 742 | _tag: "Unknown", |
| 743 | module: "FileSystem", |
| 744 | method: "write", |
| 745 | description: "ENOSPC: no space left on device", |
| 746 | }); |
| 747 | const fileSystem = FileSystem.FileSystem.of({ |
| 748 | ...fs, |
| 749 | sink: (target, options) => |
| 750 | (stage === "download" && target.endsWith("download")) || |
| 751 | (stage === "extract" && target.endsWith(executableName)) |
| 752 | ? fs.sink(target, options).pipe(Sink.mapInputEffect(() => Effect.fail(noSpace))) |
| 753 | : fs.sink(target, options), |
| 754 | writeFileString: (target, content, options) => |
| 755 | stage === "active pointer" && target.endsWith("contents.tmp") |
| 756 | ? Effect.fail(noSpace) |
| 757 | : fs.writeFileString(target, content, options), |
| 758 | }); |
| 759 | const { installation, stagingReleased, path } = yield* makeHarness({ |
| 760 | previous: true, |
| 761 | fileSystem, |
| 762 | }); |
| 763 | yield* installation.start; |
| 764 | expect((yield* terminalState(installation)).phase).toBe("failed"); |
| 765 | yield* Deferred.await(stagingReleased); |
| 766 | yield* expectPreviousRelease(installation); |
| 767 | expect( |
| 768 | (yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).some( |
| 769 | (name) => name.startsWith(".install-"), |
| 770 | ), |
| 771 | ).toBe(false); |
| 772 | expect(yield* fs.readDirectory(installation.managedDirectory)).toEqual([ |
| 773 | "active.json", |
| 774 | "versions", |
| 775 | ]); |
| 776 | }), |
| 777 | ); |
| 778 | |
| 779 | it.effect.each( |
| 780 | hostPlatform === "win32" |
| 781 | ? (["downloading", "verifying"] as const) |
| 782 | : (["downloading", "extracting", "verifying"] as const), |
| 783 | )("cancels during %s and waits for open resources to close", (phase) => |
| 784 | Effect.gen(function* () { |
| 785 | const fs = yield* FileSystem.FileSystem; |
| 786 | const entered = yield* Deferred.make<void>(); |
| 787 | const release = yield* Deferred.make<void>(); |
| 788 | const interrupted = yield* Deferred.make<void>(); |
| 789 | const barrier = Deferred.succeed(entered, undefined).pipe( |
| 790 | Effect.andThen(Deferred.await(release)), |
| 791 | Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)), |
| 792 | ); |
| 793 | const { installation, stagingReleased, path, validations } = yield* makeHarness({ |
| 794 | previous: true, |
| 795 | body: |
| 796 | phase === "downloading" |
| 797 | ? Stream.concat( |
| 798 | Stream.make(completeArchive.subarray(0, 31)), |
| 799 | Stream.fromEffect(barrier.pipe(Effect.as(completeArchive.subarray(31)))), |
| 800 | ) |
| 801 | : undefined, |
| 802 | validate: phase === "verifying" ? () => barrier : undefined, |
| 803 | fileSystem: FileSystem.FileSystem.of({ |
| 804 | ...fs, |
| 805 | sink: (target, options) => |
| 806 | phase === "extracting" && target.endsWith(executableName) |
| 807 | ? fs |
| 808 | .sink(target, options) |
| 809 | .pipe(Sink.mapInputEffect((chunk: Uint8Array) => barrier.pipe(Effect.as(chunk)))) |
| 810 | : fs.sink(target, options), |
| 811 | }), |
| 812 | }); |
| 813 | const started = yield* installation.start; |
| 814 | yield* Deferred.await(entered); |
| 815 | expect((yield* installation.state).phase).toBe(phase); |
| 816 | expect( |
| 817 | (yield* installation.cancel(started.operationId ?? "missing-operation-id")).phase, |
| 818 | ).toBe("cancelled"); |
| 819 | yield* Deferred.await(interrupted); |
| 820 | yield* Deferred.await(stagingReleased); |
| 821 | yield* expectPreviousRelease(installation); |
| 822 | expect(validations).toHaveLength(phase === "verifying" ? 1 : 0); |
| 823 | expect(yield* fs.readDirectory(path.join(installation.managedDirectory, "versions"))).toEqual( |
| 824 | [previousReleaseId], |
| 825 | ); |
| 826 | }), |
| 827 | ); |
| 828 | |
| 829 | it.effect.each([ |
| 830 | { name: "the committed install", restart: false }, |
| 831 | { name: "a newer install", restart: true }, |
| 832 | ])("does not fail $name when old pointer cleanup fails", (testCase) => |
| 833 | Effect.gen(function* () { |
| 834 | const fs = yield* FileSystem.FileSystem; |
| 835 | const cleanupStarted = yield* Deferred.make<void>(); |
| 836 | const releaseCleanup = yield* Deferred.make<void>(); |
| 837 | const nextValidationStarted = yield* Deferred.make<void>(); |
| 838 | const releaseNextValidation = yield* Deferred.make<void>(); |
| 839 | const firstWorker = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>(); |
| 840 | const cleanupError = PlatformError.systemError({ |
| 841 | _tag: "PermissionDenied", |
| 842 | module: "FileSystem", |
| 843 | method: "remove", |
| 844 | description: "EPERM: pointer temp directory is in use", |
| 845 | }); |
| 846 | let firstPointer = true; |
| 847 | let validationCount = 0; |
| 848 | const { installation, stagingReleased } = yield* makeHarness({ |
| 849 | previous: true, |
| 850 | validate: () => { |
| 851 | validationCount += 1; |
| 852 | return validationCount === 2 |
| 853 | ? Deferred.succeed(nextValidationStarted, undefined).pipe( |
| 854 | Effect.andThen(Deferred.await(releaseNextValidation)), |
| 855 | ) |
| 856 | : Effect.void; |
| 857 | }, |
| 858 | fileSystem: FileSystem.FileSystem.of({ |
| 859 | ...fs, |
| 860 | makeTempDirectoryScoped: (settings) => { |
| 861 | if (settings?.prefix !== "active.json." || !firstPointer) { |
| 862 | return fs.makeTempDirectoryScoped(settings); |
| 863 | } |
| 864 | firstPointer = false; |
| 865 | return Effect.fiber.pipe( |
| 866 | Effect.tap((worker) => Deferred.succeed(firstWorker, worker)), |
| 867 | Effect.andThen( |
| 868 | Effect.acquireRelease(fs.makeTempDirectory(settings), () => |
| 869 | Deferred.succeed(cleanupStarted, undefined).pipe( |
| 870 | Effect.andThen(Deferred.await(releaseCleanup)), |
| 871 | Effect.andThen(Effect.die(cleanupError)), |
| 872 | ), |
| 873 | ), |
| 874 | ), |
| 875 | ); |
| 876 | }, |
| 877 | }), |
| 878 | }); |
| 879 | yield* Effect.gen(function* () { |
| 880 | const first = yield* installation.start; |
| 881 | yield* Deferred.await(cleanupStarted); |
| 882 | expect(yield* installation.state).toMatchObject({ |
| 883 | operationId: first.operationId, |
| 884 | phase: "succeeded", |
| 885 | installedVersion: assetVersion, |
| 886 | }); |
| 887 | const current = testCase.restart ? yield* installation.start : first; |
| 888 | if (testCase.restart) yield* Deferred.await(nextValidationStarted); |
| 889 | |
| 890 | yield* Deferred.succeed(releaseCleanup, undefined); |
| 891 | yield* Fiber.await(yield* Deferred.await(firstWorker)); |
| 892 | yield* Deferred.await(stagingReleased); |
| 893 | expect(yield* installation.state).toMatchObject({ |
| 894 | operationId: current.operationId, |
| 895 | phase: testCase.restart ? "verifying" : "succeeded", |
| 896 | installedVersion: assetVersion, |
| 897 | }); |
| 898 | expect((yield* installation.resolve()).version).toBe(assetVersion); |
| 899 | |
| 900 | yield* Deferred.succeed(releaseNextValidation, undefined); |
| 901 | expect(yield* terminalState(installation)).toMatchObject({ |
| 902 | operationId: current.operationId, |
| 903 | phase: "succeeded", |
| 904 | installedVersion: assetVersion, |
| 905 | }); |
| 906 | }).pipe( |
| 907 | Effect.ensuring( |
| 908 | Deferred.succeed(releaseCleanup, undefined).pipe( |
| 909 | Effect.andThen(Deferred.succeed(releaseNextValidation, undefined)), |
| 910 | ), |
| 911 | ), |
| 912 | ); |
| 913 | }), |
| 914 | ); |
| 915 | |
| 916 | it.effect( |
| 917 | "shares one install across callers and keeps it alive after the caller scope closes", |
| 918 | () => |
| 919 | Effect.gen(function* () { |
| 920 | const entered = yield* Deferred.make<void>(); |
| 921 | const release = yield* Deferred.make<void>(); |
| 922 | const { installation, requests, stagingReleased } = yield* makeHarness({ |
| 923 | body: Stream.fromEffect( |
| 924 | Deferred.succeed(entered, undefined).pipe( |
| 925 | Effect.andThen(Deferred.await(release)), |
| 926 | Effect.as(completeArchive), |
| 927 | ), |
| 928 | ), |
| 929 | }); |
| 930 | const callerScope = yield* Scope.make(); |
| 931 | const started = yield* installation.start.pipe(Scope.provide(callerScope)); |
| 932 | yield* Deferred.await(entered); |
| 933 | yield* Scope.close(callerScope, Exit.void); |
| 934 | const concurrent = yield* Effect.all([installation.start, installation.start], { |
| 935 | concurrency: "unbounded", |
| 936 | }); |
| 937 | expect(concurrent.map((state) => state.operationId)).toEqual([ |
| 938 | started.operationId, |
| 939 | started.operationId, |
| 940 | ]); |
| 941 | expect( |
| 942 | yield* installation.changes.pipe(Stream.runHead, Effect.map(Option.getOrThrow)), |
| 943 | ).toMatchObject({ phase: "downloading", operationId: started.operationId }); |
| 944 | yield* Deferred.succeed(release, undefined); |
| 945 | expect((yield* terminalState(installation)).phase).toBe("succeeded"); |
| 946 | yield* Deferred.await(stagingReleased); |
| 947 | |
| 948 | const next = yield* installation.start; |
| 949 | expect(next.operationId).not.toBe(started.operationId); |
| 950 | expect( |
| 951 | yield* installation |
| 952 | .cancel(started.operationId ?? "missing-operation-id") |
| 953 | .pipe(Effect.flip), |
| 954 | ).toMatchObject({ operation: "cancel" }); |
| 955 | expect((yield* terminalState(installation)).phase).toBe("succeeded"); |
| 956 | expect(requests).toHaveLength(1); |
| 957 | }), |
| 958 | ); |
| 959 | |
| 960 | // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons. |
| 961 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 962 | "accepts only the agy CLI as a custom or PATH executable", |
| 963 | () => |
| 964 | Effect.gen(function* () { |
| 965 | const fs = yield* FileSystem.FileSystem; |
| 966 | const path = yield* Path.Path; |
| 967 | const baseDir = yield* fs |
| 968 | .makeTempDirectoryScoped({ prefix: "t3-agy-cli-test-" }) |
| 969 | .pipe(Effect.flatMap((directory) => fs.realPath(directory))); |
| 970 | const cliDirectory = path.join(baseDir, 'cli" '); |
| 971 | yield* fs.makeDirectory(cliDirectory); |
| 972 | const siblingDirectory = path.join(baseDir, 'cli"'); |
| 973 | yield* fs.makeDirectory(siblingDirectory); |
| 974 | yield* fs.writeFileString(path.join(siblingDirectory, "agy"), "other cli", { mode: 0o755 }); |
| 975 | const cli = path.join(cliDirectory, "antigravity"); |
| 976 | const alias = path.join(cliDirectory, "agy"); |
| 977 | const other = path.join(cliDirectory, "custom-acp"); |
| 978 | yield* fs.writeFileString(cli, "cli", { mode: 0o755 }); |
| 979 | yield* fs.symlink(cli, alias); |
| 980 | yield* fs.writeFileString(other, "other", { mode: 0o755 }); |
| 981 | const { installation } = yield* makeHarness({ baseDir }); |
| 982 | |
| 983 | expect(yield* installation.resolve(cli)).toMatchObject({ |
| 984 | executablePath: cli, |
| 985 | source: "override", |
| 986 | version: null, |
| 987 | }); |
| 988 | expect(yield* installation.resolve(alias)).toMatchObject({ |
| 989 | executablePath: alias, |
| 990 | }); |
| 991 | expect(yield* installation.resolve("agy", { PATH: cliDirectory })).toMatchObject({ |
| 992 | executablePath: alias, |
| 993 | }); |
| 994 | expect(yield* installation.resolve(undefined, { PATH: cliDirectory })).toMatchObject({ |
| 995 | executablePath: alias, |
| 996 | source: "path", |
| 997 | }); |
| 998 | expect(yield* installation.resolve(other).pipe(Effect.flip)).toMatchObject({ |
| 999 | operation: "resolve", |
| 1000 | }); |
| 1001 | |
| 1002 | // Version-manager shims dispatch by their invoked name, so the shim path is what runs. |
| 1003 | const shims = path.join(baseDir, "shims"); |
| 1004 | const mise = path.join(baseDir, "mise"); |
| 1005 | yield* fs.makeDirectory(shims); |
| 1006 | yield* fs.writeFileString(mise, "mise", { mode: 0o755 }); |
| 1007 | yield* fs.symlink(mise, path.join(shims, "agy")); |
| 1008 | expect(yield* installation.resolve("agy", { PATH: shims })).toMatchObject({ |
| 1009 | executablePath: path.join(shims, "agy"), |
| 1010 | }); |
| 1011 | |
| 1012 | const { installation: windows } = yield* makeHarness({ baseDir, platform: "win32" }); |
| 1013 | for (const name of ["agy.EXE", "agy.cmd"]) { |
| 1014 | const windowsDirectory = path.join(baseDir, `windows-${name}`); |
| 1015 | yield* fs.makeDirectory(windowsDirectory); |
| 1016 | yield* fs.writeFileString(path.join(windowsDirectory, name), "cli"); |
| 1017 | const selected = yield* windows.resolve("agy", { PATH: `"${windowsDirectory}"` }); |
| 1018 | expect((yield* fs.realPath(selected.executablePath)).toLowerCase()).toBe( |
| 1019 | (yield* fs.realPath(path.join(windowsDirectory, name))).toLowerCase(), |
| 1020 | ); |
| 1021 | } |
| 1022 | }), |
| 1023 | ); |
| 1024 | |
| 1025 | // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons. |
| 1026 | it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( |
| 1027 | "honors explicit paths and reports invalid overrides without falling back", |
| 1028 | () => |
| 1029 | Effect.gen(function* () { |
| 1030 | const fs = yield* FileSystem.FileSystem; |
| 1031 | const path = yield* Path.Path; |
| 1032 | const baseDir = yield* fs |
| 1033 | .makeTempDirectoryScoped({ prefix: "t3-agy-path-test-" }) |
| 1034 | .pipe(Effect.flatMap((directory) => fs.realPath(directory))); |
| 1035 | const externalDirectory = path.join(baseDir, "external"); |
| 1036 | const externalExecutable = path.join(externalDirectory, "agy"); |
| 1037 | yield* fs.makeDirectory(externalDirectory); |
| 1038 | yield* fs.writeFileString(externalExecutable, "external cli", { mode: 0o755 }); |
| 1039 | const { installation } = yield* makeHarness({ |
| 1040 | baseDir, |
| 1041 | path: externalDirectory, |
| 1042 | previous: true, |
| 1043 | }); |
| 1044 | yield* expectPreviousRelease(installation); |
| 1045 | expect(yield* installation.resolve(undefined, { PATH: externalDirectory })).toMatchObject({ |
| 1046 | source: "managed", |
| 1047 | version: previousVersion, |
| 1048 | }); |
| 1049 | expect(yield* installation.resolve(externalExecutable)).toMatchObject({ |
| 1050 | executablePath: externalExecutable, |
| 1051 | source: "override", |
| 1052 | managedVersionDirectory: null, |
| 1053 | }); |
| 1054 | expect(yield* installation.resolve("agy")).toMatchObject({ source: "override" }); |
| 1055 | expect( |
| 1056 | yield* installation |
| 1057 | .resolve("~/external/agy") |
| 1058 | .pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)), |
| 1059 | ).toMatchObject({ source: "override", executablePath: externalExecutable }); |
| 1060 | expect( |
| 1061 | yield* installation.resolve(path.join(baseDir, "missing")).pipe(Effect.flip), |
| 1062 | ).toMatchObject({ |
| 1063 | operation: "resolve", |
| 1064 | }); |
| 1065 | yield* expectPreviousRelease(installation); |
| 1066 | yield* installation.remove(); |
| 1067 | expect(yield* installation.resolve()).toMatchObject({ |
| 1068 | source: "path", |
| 1069 | executablePath: externalExecutable, |
| 1070 | }); |
| 1071 | const isolated = yield* makeHarness({ baseDir }); |
| 1072 | expect(yield* isolated.installation.resolve().pipe(Effect.flip)).toMatchObject({ |
| 1073 | operation: "resolve", |
| 1074 | }); |
| 1075 | expect( |
| 1076 | yield* isolated.installation.resolve(undefined, { PATH: externalDirectory }), |
| 1077 | ).toMatchObject({ |
| 1078 | source: "path", |
| 1079 | executablePath: externalExecutable, |
| 1080 | }); |
| 1081 | expect( |
| 1082 | yield* isolated.installation.resolve("agy", { PATH: externalDirectory }), |
| 1083 | ).toMatchObject({ source: "override", executablePath: externalExecutable }); |
| 1084 | }), |
| 1085 | ); |
| 1086 | |
| 1087 | it.effect("keeps leased releases available while new sessions resolve the new release", () => |
| 1088 | Effect.gen(function* () { |
| 1089 | const manifestEntered = yield* Deferred.make<void>(); |
| 1090 | const releaseManifest = yield* Deferred.make<void>(); |
| 1091 | const { installation, fs, baseDir, stagingReleased } = yield* makeHarness({ |
| 1092 | native: true, |
| 1093 | platform: "win32", |
| 1094 | archive: Buffer.from(serverContents), |
| 1095 | previous: true, |
| 1096 | beforeManifest: Deferred.succeed(manifestEntered, undefined).pipe( |
| 1097 | Effect.andThen(Deferred.await(releaseManifest)), |
| 1098 | ), |
| 1099 | }); |
| 1100 | const processScope = yield* Scope.make(); |
| 1101 | const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope)); |
| 1102 | const starting = yield* installation.start.pipe(Effect.forkScoped); |
| 1103 | yield* Deferred.await(manifestEntered); |
| 1104 | const concurrent = yield* installation.acquire().pipe(Scope.provide(processScope)); |
| 1105 | expect(concurrent.executablePath).toBe(oldExecutable.executablePath); |
| 1106 | yield* Deferred.succeed(releaseManifest, undefined); |
| 1107 | yield* Fiber.join(starting); |
| 1108 | expect((yield* terminalState(installation)).phase).toBe("succeeded"); |
| 1109 | yield* Deferred.await(stagingReleased); |
| 1110 | const current = yield* installation.resolve(); |
| 1111 | expect(current.version).toBe("1.5.7"); |
| 1112 | expect(current.executablePath).not.toBe(oldExecutable.executablePath); |
| 1113 | expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents); |
| 1114 | expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" }); |
| 1115 | yield* Scope.close(processScope, Exit.void); |
| 1116 | yield* makeHarness({ native: true, platform: "win32", baseDir }); |
| 1117 | expect(yield* fs.exists(oldExecutable.managedVersionDirectory!)).toBe(false); |
| 1118 | expect(yield* fs.readFileString(current.executablePath)).toBe(serverContents); |
| 1119 | yield* installation.remove(); |
| 1120 | expect(yield* fs.exists(installation.managedDirectory)).toBe(false); |
| 1121 | }), |
| 1122 | ); |
| 1123 | |
| 1124 | it.effect( |
| 1125 | "removes an incomplete active release before reinstalling without a PATH fallback", |
| 1126 | () => |
| 1127 | Effect.gen(function* () { |
| 1128 | const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true }); |
| 1129 | const previous = yield* installation.resolve(); |
| 1130 | if (hostPlatform !== "win32") { |
| 1131 | yield* fs.chmod(previous.managedVersionDirectory!, 0o700); |
| 1132 | } |
| 1133 | yield* fs.remove(previous.executablePath); |
| 1134 | const externalDirectory = path.join(baseDir, "external"); |
| 1135 | yield* fs.makeDirectory(externalDirectory); |
| 1136 | yield* fs.writeFileString(path.join(externalDirectory, "agy"), "external cli", { |
| 1137 | mode: 0o755, |
| 1138 | }); |
| 1139 | const restarted = yield* makeHarness({ baseDir, path: externalDirectory }); |
| 1140 | expect(yield* restarted.installation.state).toMatchObject({ |
| 1141 | phase: "failed", |
| 1142 | installedVersion: null, |
| 1143 | canRemove: true, |
| 1144 | }); |
| 1145 | expect(yield* restarted.installation.resolve().pipe(Effect.flip)).toMatchObject({ |
| 1146 | operation: "resolve", |
| 1147 | }); |
| 1148 | yield* restarted.installation.remove(); |
| 1149 | expect(yield* restarted.installation.state).toMatchObject({ |
| 1150 | phase: "idle", |
| 1151 | canRemove: false, |
| 1152 | }); |
| 1153 | expect(yield* fs.exists(installation.managedDirectory)).toBe(false); |
| 1154 | yield* restarted.installation.start; |
| 1155 | expect(yield* terminalState(restarted.installation)).toMatchObject({ |
| 1156 | phase: "succeeded", |
| 1157 | installedVersion: assetVersion, |
| 1158 | canRemove: true, |
| 1159 | }); |
| 1160 | yield* Deferred.await(restarted.stagingReleased); |
| 1161 | expect((yield* restarted.installation.resolve()).source).toBe("managed"); |
| 1162 | }), |
| 1163 | ); |
| 1164 | |
| 1165 | it.effect( |
| 1166 | "blocks removal of custom managed paths and leaves external executables and profiles intact", |
| 1167 | () => |
| 1168 | Effect.gen(function* () { |
| 1169 | const { installation, fs, path, baseDir } = yield* makeHarness({ previous: true }); |
| 1170 | const managed = yield* installation.resolve(); |
| 1171 | const externalDirectory = path.join(baseDir, "external"); |
| 1172 | const profileDirectory = path.join(baseDir, "providers", "antigravity", "profile"); |
| 1173 | yield* fs.makeDirectory(externalDirectory); |
| 1174 | yield* fs.makeDirectory(profileDirectory, { recursive: true }); |
| 1175 | const externalExecutable = path.join(externalDirectory, "agy"); |
| 1176 | const profilePath = path.join(profileDirectory, "preferences.json"); |
| 1177 | yield* fs.writeFileString(externalExecutable, "external cli", { mode: 0o755 }); |
| 1178 | yield* fs.writeFileString(profilePath, "{}"); |
| 1179 | expect( |
| 1180 | yield* installation.remove([managed.executablePath]).pipe(Effect.flip), |
| 1181 | ).toMatchObject({ |
| 1182 | operation: "remove", |
| 1183 | }); |
| 1184 | yield* expectPreviousRelease(installation); |
| 1185 | yield* installation.remove([externalExecutable]); |
| 1186 | expect(yield* installation.state).toMatchObject({ |
| 1187 | phase: "idle", |
| 1188 | operationId: null, |
| 1189 | installedVersion: null, |
| 1190 | }); |
| 1191 | expect(yield* fs.readFileString(externalExecutable)).toBe("external cli"); |
| 1192 | expect(yield* fs.readFileString(profilePath)).toBe("{}"); |
| 1193 | }), |
| 1194 | ); |
| 1195 | |
| 1196 | it.effect( |
| 1197 | "reuses an immutable Windows release and preserves the pointer when rename is denied", |
| 1198 | () => |
| 1199 | Effect.gen(function* () { |
| 1200 | const fs = yield* FileSystem.FileSystem; |
| 1201 | const path = yield* Path.Path; |
| 1202 | const archive = Buffer.from(serverContents); |
| 1203 | const asset = yield* releaseAsset(archive, "win32"); |
| 1204 | let denyPointerRename = true; |
| 1205 | const renameTargets: string[] = []; |
| 1206 | const { installation, requests, validations } = yield* makeHarness({ |
| 1207 | previous: true, |
| 1208 | platform: "win32", |
| 1209 | archive, |
| 1210 | fileSystem: FileSystem.FileSystem.of({ |
| 1211 | ...fs, |
| 1212 | rename: (source, target) => { |
| 1213 | renameTargets.push(target); |
| 1214 | return denyPointerRename |
| 1215 | ? Effect.fail( |
| 1216 | PlatformError.systemError({ |
| 1217 | _tag: "PermissionDenied", |
| 1218 | module: "FileSystem", |
| 1219 | method: "rename", |
| 1220 | pathOrDescriptor: target, |
| 1221 | description: "EPERM: file is in use", |
| 1222 | }), |
| 1223 | ) |
| 1224 | : fs.rename(source, target); |
| 1225 | }, |
| 1226 | }), |
| 1227 | }); |
| 1228 | yield* writeRelease(installation.managedDirectory, assetRelease(asset), false); |
| 1229 | yield* installation.start; |
| 1230 | expect((yield* terminalState(installation)).phase).toBe("failed"); |
| 1231 | yield* expectPreviousRelease(installation); |
| 1232 | expect(renameTargets).toEqual([path.join(installation.managedDirectory, "active.json")]); |
| 1233 | |
| 1234 | denyPointerRename = false; |
| 1235 | yield* installation.start; |
| 1236 | expect((yield* terminalState(installation)).phase).toBe("succeeded"); |
| 1237 | expect((yield* installation.resolve()).version).toBe(assetVersion); |
| 1238 | expect(requests).toEqual([]); |
| 1239 | expect(validations).toHaveLength(2); |
| 1240 | expect(renameTargets).toEqual([ |
| 1241 | path.join(installation.managedDirectory, "active.json"), |
| 1242 | path.join(installation.managedDirectory, "active.json"), |
| 1243 | ]); |
| 1244 | }), |
| 1245 | ); |
| 1246 | |
| 1247 | it.effect("publishes a Windows release once a transient EPERM on the release rename clears", () => |
| 1248 | Effect.gen(function* () { |
| 1249 | const fs = yield* FileSystem.FileSystem; |
| 1250 | const path = yield* Path.Path; |
| 1251 | const archive = Buffer.from(serverContents); |
| 1252 | const releaseRenameDenied = yield* Deferred.make<void>(); |
| 1253 | let releaseRenameDenials = 3; |
| 1254 | const { installation } = yield* makeHarness({ |
| 1255 | platform: "win32", |
| 1256 | archive, |
| 1257 | fileSystem: FileSystem.FileSystem.of({ |
| 1258 | ...fs, |
| 1259 | rename: (source, target) => |
| 1260 | Effect.suspend(() => { |
| 1261 | if ( |
| 1262 | path.basename(path.dirname(target)) !== "versions" || |
| 1263 | releaseRenameDenials === 0 |
| 1264 | ) { |
| 1265 | return fs.rename(source, target); |
| 1266 | } |
| 1267 | releaseRenameDenials -= 1; |
| 1268 | return Deferred.succeed(releaseRenameDenied, undefined).pipe( |
| 1269 | Effect.andThen( |
| 1270 | Effect.fail( |
| 1271 | PlatformError.systemError({ |
| 1272 | _tag: "Unknown", |
| 1273 | module: "FileSystem", |
| 1274 | method: "rename", |
| 1275 | pathOrDescriptor: source, |
| 1276 | description: "EPERM: operation not permitted, rename", |
| 1277 | }), |
| 1278 | ), |
| 1279 | ), |
| 1280 | ); |
| 1281 | }), |
| 1282 | }), |
| 1283 | }); |
| 1284 | yield* installation.start; |
| 1285 | const terminal = yield* terminalState(installation).pipe(Effect.forkChild); |
| 1286 | yield* Deferred.await(releaseRenameDenied); |
| 1287 | yield* TestClock.adjust("30 seconds"); |
| 1288 | expect(yield* Fiber.join(terminal)).toMatchObject({ |
| 1289 | phase: "succeeded", |
| 1290 | installedVersion: assetVersion, |
| 1291 | }); |
| 1292 | expect((yield* installation.resolve()).version).toBe(assetVersion); |
| 1293 | }), |
| 1294 | ); |
| 1295 | |
| 1296 | it.effect("reports unsupported hosts without downloading or changing state", () => |
| 1297 | Effect.gen(function* () { |
| 1298 | const { installation, requests } = yield* makeHarness({ asset: null, platform: "darwin" }); |
| 1299 | expect(yield* installation.start.pipe(Effect.flip)).toMatchObject({ operation: "start" }); |
| 1300 | expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({ |
| 1301 | operation: "resolve", |
| 1302 | }); |
| 1303 | expect(yield* installation.state).toMatchObject({ phase: "idle", operationId: null }); |
| 1304 | expect(requests).toEqual([]); |
| 1305 | }), |
| 1306 | ); |
| 1307 | |
| 1308 | it.effect( |
| 1309 | "locks CLI releases on POSIX, detects on-disk changes, and recovers on same-releaseId reinstall", |
| 1310 | () => |
| 1311 | Effect.gen(function* () { |
| 1312 | const { installation, fs, path, baseDir, stagingReleased } = yield* makeHarness({ |
| 1313 | native: true, |
| 1314 | }); |
| 1315 | yield* installation.start; |
| 1316 | expect(yield* terminalState(installation)).toMatchObject({ |
| 1317 | phase: "succeeded", |
| 1318 | installedVersion: "1.5.7", |
| 1319 | }); |
| 1320 | yield* Deferred.await(stagingReleased); |
| 1321 | |
| 1322 | const installed = yield* installation.resolve(); |
| 1323 | const releaseDir = installed.managedVersionDirectory!; |
| 1324 | const recordPath = path.join(releaseDir, ".install-complete.json"); |
| 1325 | |
| 1326 | if (hostPlatform !== "win32") { |
| 1327 | expect((yield* fs.stat(releaseDir)).mode & 0o777).toBe(0o500); |
| 1328 | expect((yield* fs.stat(installed.executablePath)).mode & 0o777).toBe(0o555); |
| 1329 | expect((yield* fs.stat(recordPath)).mode & 0o777).toBe(0o400); |
| 1330 | if (process.getuid?.() !== 0) { |
| 1331 | const stagingAttempt = yield* fs |
| 1332 | .makeDirectory(path.join(releaseDir, "auto-update-staging")) |
| 1333 | .pipe(Effect.exit); |
| 1334 | expect(Exit.isFailure(stagingAttempt)).toBe(true); |
| 1335 | } |
| 1336 | |
| 1337 | // Existing writable CLI releases are re-locked on startup. |
| 1338 | yield* fs.chmod(releaseDir, 0o700); |
| 1339 | yield* fs.chmod(installed.executablePath, 0o755); |
| 1340 | yield* fs.chmod(recordPath, 0o600); |
| 1341 | const relocked = yield* makeHarness({ baseDir, native: true }); |
| 1342 | expect(yield* relocked.installation.state).toMatchObject({ |
| 1343 | phase: "idle", |
| 1344 | installedVersion: "1.5.7", |
| 1345 | }); |
| 1346 | expect((yield* fs.stat(releaseDir)).mode & 0o777).toBe(0o500); |
| 1347 | expect((yield* fs.stat(installed.executablePath)).mode & 0o777).toBe(0o555); |
| 1348 | expect((yield* fs.stat(recordPath)).mode & 0o777).toBe(0o400); |
| 1349 | } |
| 1350 | |
| 1351 | // Simulate an external self-update mutating the managed binary in place. |
| 1352 | if (hostPlatform !== "win32") { |
| 1353 | yield* fs.chmod(releaseDir, 0o700); |
| 1354 | yield* fs.chmod(installed.executablePath, 0o755); |
| 1355 | } |
| 1356 | yield* fs.writeFileString(installed.executablePath, `${serverContents}self-updated\n`, { |
| 1357 | mode: 0o755, |
| 1358 | }); |
| 1359 | |
| 1360 | const resolveError = yield* installation.resolve().pipe(Effect.flip); |
| 1361 | expect(resolveError.detail).toContain("changed on disk"); |
| 1362 | |
| 1363 | const restarted = yield* makeHarness({ baseDir, native: true }); |
| 1364 | expect(yield* restarted.installation.state).toMatchObject({ |
| 1365 | phase: "failed", |
| 1366 | installedVersion: null, |
| 1367 | }); |
| 1368 | expect((yield* restarted.installation.state).message).toContain("changed on disk"); |
| 1369 | |
| 1370 | // Reinstalling the same releaseId replaces the damaged directory cleanly. |
| 1371 | yield* restarted.installation.start; |
| 1372 | expect(yield* terminalState(restarted.installation)).toMatchObject({ |
| 1373 | phase: "succeeded", |
| 1374 | installedVersion: "1.5.7", |
| 1375 | }); |
| 1376 | yield* Deferred.await(restarted.stagingReleased); |
| 1377 | |
| 1378 | const repaired = yield* restarted.installation.resolve(); |
| 1379 | expect(repaired.version).toBe("1.5.7"); |
| 1380 | expect(yield* fs.readFileString(repaired.executablePath)).toBe(serverContents); |
| 1381 | if (hostPlatform !== "win32") { |
| 1382 | expect((yield* fs.stat(releaseDir)).mode & 0o777).toBe(0o500); |
| 1383 | expect((yield* fs.stat(repaired.executablePath)).mode & 0o777).toBe(0o555); |
| 1384 | } |
| 1385 | |
| 1386 | // remove() unlocks and deletes read-only CLI releases cleanly. |
| 1387 | yield* restarted.installation.remove(); |
| 1388 | expect(yield* fs.exists(restarted.installation.managedDirectory)).toBe(false); |
| 1389 | }), |
| 1390 | ); |
| 1391 | |
| 1392 | it.effect( |
| 1393 | "restores displaced files on repair publish failure and rejects symlinked managed binaries", |
| 1394 | () => |
| 1395 | Effect.gen(function* () { |
| 1396 | const { installation, fs, path, baseDir, stagingReleased } = yield* makeHarness({ |
| 1397 | native: true, |
| 1398 | }); |
| 1399 | yield* installation.start; |
| 1400 | expect((yield* terminalState(installation)).phase).toBe("succeeded"); |
| 1401 | yield* Deferred.await(stagingReleased); |
| 1402 | const installed = yield* installation.resolve(); |
| 1403 | const releaseDir = installed.managedVersionDirectory!; |
| 1404 | const recordPath = path.join(releaseDir, ".install-complete.json"); |
| 1405 | const damagedContents = `${serverContents}damaged\n`; |
| 1406 | |
| 1407 | if (hostPlatform !== "win32") { |
| 1408 | yield* fs.chmod(releaseDir, 0o700); |
| 1409 | yield* fs.chmod(installed.executablePath, 0o755); |
| 1410 | } |
| 1411 | yield* fs.writeFileString(installed.executablePath, damagedContents, { mode: 0o755 }); |
| 1412 | |
| 1413 | // Fail the publish rename (staged -> destination) after moving the damaged release aside. |
| 1414 | let renameToDestinationCount = 0; |
| 1415 | const failingRepair = yield* makeHarness({ |
| 1416 | baseDir, |
| 1417 | native: true, |
| 1418 | fileSystem: FileSystem.FileSystem.of({ |
| 1419 | ...fs, |
| 1420 | rename: (from, to) => { |
| 1421 | if (to === releaseDir && ++renameToDestinationCount === 1) { |
| 1422 | return Effect.fail( |
| 1423 | PlatformError.systemError({ |
| 1424 | _tag: "AlreadyExists", |
| 1425 | module: "FileSystem", |
| 1426 | method: "rename", |
| 1427 | pathOrDescriptor: to, |
| 1428 | description: "EEXIST: simulated publish failure", |
| 1429 | }), |
| 1430 | ); |
| 1431 | } |
| 1432 | return fs.rename(from, to); |
| 1433 | }, |
| 1434 | }), |
| 1435 | }); |
| 1436 | yield* failingRepair.installation.start; |
| 1437 | expect(yield* terminalState(failingRepair.installation)).toMatchObject({ |
| 1438 | phase: "failed", |
| 1439 | }); |
| 1440 | yield* Deferred.await(failingRepair.stagingReleased); |
| 1441 | // The damaged directory was rolled back instead of being left missing. |
| 1442 | expect(yield* fs.readFileString(installed.executablePath)).toBe(damagedContents); |
| 1443 | |
| 1444 | // If pointer write fails (e.g. ENOSPC) after repair swapped files in, rollback restores the displaced copy. |
| 1445 | const failingPointerWrite = yield* makeHarness({ |
| 1446 | baseDir, |
| 1447 | native: true, |
| 1448 | fileSystem: FileSystem.FileSystem.of({ |
| 1449 | ...fs, |
| 1450 | writeFileString: (target, content, options) => |
| 1451 | path.basename(target) === "contents.tmp" |
| 1452 | ? Effect.fail( |
| 1453 | PlatformError.systemError({ |
| 1454 | _tag: "Unknown", |
| 1455 | module: "FileSystem", |
| 1456 | method: "writeFileString", |
| 1457 | pathOrDescriptor: target, |
| 1458 | description: "ENOSPC: no space left on device", |
| 1459 | }), |
| 1460 | ) |
| 1461 | : fs.writeFileString(target, content, options), |
| 1462 | }), |
| 1463 | }); |
| 1464 | yield* failingPointerWrite.installation.start; |
| 1465 | expect(yield* terminalState(failingPointerWrite.installation)).toMatchObject({ |
| 1466 | phase: "failed", |
| 1467 | }); |
| 1468 | yield* Deferred.await(failingPointerWrite.stagingReleased); |
| 1469 | expect(yield* fs.readFileString(installed.executablePath)).toBe(damagedContents); |
| 1470 | |
| 1471 | // A symlinked executable is rejected and startup does not chmod its target. |
| 1472 | if (hostPlatform !== "win32") { |
| 1473 | const outsideTarget = path.join(baseDir, "outside-target"); |
| 1474 | yield* fs.writeFileString(outsideTarget, serverContents, { mode: 0o755 }); |
| 1475 | yield* fs.remove(installed.executablePath); |
| 1476 | yield* fs.symlink(outsideTarget, installed.executablePath); |
| 1477 | const symlinked = yield* makeHarness({ baseDir, native: true }); |
| 1478 | expect((yield* symlinked.installation.state).phase).toBe("failed"); |
| 1479 | expect(yield* symlinked.installation.resolve().pipe(Effect.flip)).toMatchObject({ |
| 1480 | operation: "resolve", |
| 1481 | }); |
| 1482 | expect((yield* fs.stat(outsideTarget)).mode & 0o777).toBe(0o755); |
| 1483 | |
| 1484 | // An unreadable completion record is repairable on reinstall. |
| 1485 | if (process.getuid?.() !== 0) { |
| 1486 | yield* fs.remove(installed.executablePath); |
| 1487 | yield* fs.writeFileString(installed.executablePath, serverContents, { mode: 0o755 }); |
| 1488 | yield* fs.chmod(recordPath, 0o000); |
| 1489 | const unreadableRecord = yield* makeHarness({ baseDir, native: true }); |
| 1490 | expect((yield* unreadableRecord.installation.state).phase).toBe("failed"); |
| 1491 | yield* unreadableRecord.installation.start; |
| 1492 | expect(yield* terminalState(unreadableRecord.installation)).toMatchObject({ |
| 1493 | phase: "succeeded", |
| 1494 | installedVersion: "1.5.7", |
| 1495 | }); |
| 1496 | yield* Deferred.await(unreadableRecord.stagingReleased); |
| 1497 | } |
| 1498 | } |
| 1499 | |
| 1500 | // A regular file occupying the release directory path is classified as incomplete and replaced on reinstall. |
| 1501 | if (hostPlatform !== "win32") { |
| 1502 | yield* fs.chmod(releaseDir, 0o700); |
| 1503 | } |
| 1504 | yield* fs.remove(releaseDir, { recursive: true, force: true }); |
| 1505 | yield* fs.writeFileString(releaseDir, "not a directory"); |
| 1506 | expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({ |
| 1507 | operation: "resolve", |
| 1508 | }); |
| 1509 | const repairedFromFile = yield* makeHarness({ baseDir, native: true }); |
| 1510 | yield* repairedFromFile.installation.start; |
| 1511 | expect(yield* terminalState(repairedFromFile.installation)).toMatchObject({ |
| 1512 | phase: "succeeded", |
| 1513 | installedVersion: "1.5.7", |
| 1514 | }); |
| 1515 | yield* Deferred.await(repairedFromFile.stagingReleased); |
| 1516 | expect(yield* fs.readFileString(installed.executablePath)).toBe(serverContents); |
| 1517 | |
| 1518 | // A second service acquiring a custom binaryPath (or external symlink to it) during a |
| 1519 | // repair swap waits for the managed lock instead of missing the briefly displaced binary. |
| 1520 | if (hostPlatform !== "win32") { |
| 1521 | yield* fs.chmod(releaseDir, 0o700); |
| 1522 | yield* fs.chmod(installed.executablePath, 0o755); |
| 1523 | } |
| 1524 | yield* fs.writeFileString(installed.executablePath, damagedContents, { mode: 0o755 }); |
| 1525 | const externalSymlink = path.join(baseDir, "external-agy-link"); |
| 1526 | if (hostPlatform !== "win32") { |
| 1527 | yield* fs.symlink(installed.executablePath, externalSymlink); |
| 1528 | // Even when the release is broken, remove() expands `~` and blocks deletion of a protected symlink. |
| 1529 | expect( |
| 1530 | yield* installation |
| 1531 | .remove(["~/external-agy-link"]) |
| 1532 | .pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir), Effect.flip), |
| 1533 | ).toMatchObject({ operation: "remove" }); |
| 1534 | } |
| 1535 | const displacedPaused = yield* Deferred.make<void>(); |
| 1536 | const resumeSwap = yield* Deferred.make<void>(); |
| 1537 | const pausedRepair = yield* makeHarness({ |
| 1538 | baseDir, |
| 1539 | native: true, |
| 1540 | fileSystem: FileSystem.FileSystem.of({ |
| 1541 | ...fs, |
| 1542 | rename: (from, to) => |
| 1543 | from === releaseDir && path.basename(to) === "displaced" |
| 1544 | ? fs |
| 1545 | .rename(from, to) |
| 1546 | .pipe( |
| 1547 | Effect.andThen(Deferred.succeed(displacedPaused, undefined)), |
| 1548 | Effect.andThen(Deferred.await(resumeSwap)), |
| 1549 | ) |
| 1550 | : fs.rename(from, to), |
| 1551 | }), |
| 1552 | }); |
| 1553 | const managedDir = pausedRepair.installation.managedDirectory; |
| 1554 | let watchResolveExists = false; |
| 1555 | const expectedResolves = hostPlatform !== "win32" ? 2 : 1; |
| 1556 | let seenResolves = 0; |
| 1557 | const resolversEntered = yield* Deferred.make<void>(); |
| 1558 | const secondServer = yield* makeHarness({ |
| 1559 | baseDir, |
| 1560 | native: true, |
| 1561 | fileSystem: FileSystem.FileSystem.of({ |
| 1562 | ...fs, |
| 1563 | exists: (target) => |
| 1564 | watchResolveExists && target === managedDir |
| 1565 | ? Effect.suspend(() => { |
| 1566 | seenResolves += 1; |
| 1567 | return seenResolves >= expectedResolves |
| 1568 | ? Deferred.succeed(resolversEntered, undefined).pipe( |
| 1569 | Effect.andThen(fs.exists(target)), |
| 1570 | ) |
| 1571 | : fs.exists(target); |
| 1572 | }) |
| 1573 | : fs.exists(target), |
| 1574 | }), |
| 1575 | }); |
| 1576 | yield* Effect.gen(function* () { |
| 1577 | yield* pausedRepair.installation.start; |
| 1578 | yield* Deferred.await(displacedPaused); |
| 1579 | expect(yield* fs.exists(releaseDir)).toBe(false); |
| 1580 | watchResolveExists = true; |
| 1581 | const acquireFiber = yield* secondServer.installation |
| 1582 | .acquire(installed.executablePath) |
| 1583 | .pipe(Effect.scoped, Effect.forkScoped); |
| 1584 | const symlinkResolveFiber = |
| 1585 | hostPlatform !== "win32" |
| 1586 | ? yield* secondServer.installation.resolve(externalSymlink).pipe(Effect.forkScoped) |
| 1587 | : null; |
| 1588 | yield* Deferred.await(resolversEntered); |
| 1589 | expect(yield* fs.exists(`${managedDir}.lock`)).toBe(true); |
| 1590 | expect(yield* fs.exists(releaseDir)).toBe(false); |
| 1591 | expect(acquireFiber.pollUnsafe()).toBeUndefined(); |
| 1592 | if (symlinkResolveFiber !== null) { |
| 1593 | expect(symlinkResolveFiber.pollUnsafe()).toBeUndefined(); |
| 1594 | } |
| 1595 | yield* Deferred.succeed(resumeSwap, undefined); |
| 1596 | expect(yield* terminalState(pausedRepair.installation)).toMatchObject({ |
| 1597 | phase: "succeeded", |
| 1598 | }); |
| 1599 | const acquired = yield* Fiber.join(acquireFiber); |
| 1600 | expect(acquired).toMatchObject({ |
| 1601 | source: "override", |
| 1602 | executablePath: installed.executablePath, |
| 1603 | version: "1.5.7", |
| 1604 | }); |
| 1605 | if (symlinkResolveFiber !== null) { |
| 1606 | expect(yield* Fiber.join(symlinkResolveFiber)).toMatchObject({ |
| 1607 | source: "override", |
| 1608 | executablePath: installed.executablePath, |
| 1609 | version: "1.5.7", |
| 1610 | }); |
| 1611 | } |
| 1612 | expect(yield* fs.readFileString(acquired.executablePath)).toBe(serverContents); |
| 1613 | yield* Deferred.await(pausedRepair.stagingReleased); |
| 1614 | }).pipe(Effect.ensuring(Deferred.succeed(resumeSwap, undefined).pipe(Effect.asVoid))); |
| 1615 | |
| 1616 | if (hostPlatform !== "win32" && process.getuid?.() !== 0) { |
| 1617 | // A valid external CLI override resolves even when the managed directory's parent is read-only. |
| 1618 | const externalCli = path.join(baseDir, "agy"); |
| 1619 | yield* fs.writeFileString(externalCli, "external cli", { mode: 0o755 }); |
| 1620 | const managedParent = path.dirname(managedDir); |
| 1621 | yield* fs.chmod(managedParent, 0o500); |
| 1622 | yield* Effect.gen(function* () { |
| 1623 | expect(yield* installation.resolve(externalCli)).toMatchObject({ |
| 1624 | executablePath: externalCli, |
| 1625 | source: "override", |
| 1626 | managedVersionDirectory: null, |
| 1627 | }); |
| 1628 | }).pipe(Effect.ensuring(fs.chmod(managedParent, 0o700).pipe(Effect.ignore))); |
| 1629 | |
| 1630 | // A symlinked versions/ root is rejected on startup without chmodding outside targets, |
| 1631 | // and a dangling managedDirectory symlink can still be removed. |
| 1632 | const outsideVersions = path.join(baseDir, "outside-versions"); |
| 1633 | const outsideReleaseDir = path.join(outsideVersions, path.basename(releaseDir)); |
| 1634 | const outsideBinary = path.join(outsideReleaseDir, executableName); |
| 1635 | yield* fs.makeDirectory(outsideReleaseDir, { recursive: true }); |
| 1636 | yield* fs.writeFileString(outsideBinary, serverContents, { mode: 0o755 }); |
| 1637 | yield* fs.writeFileString( |
| 1638 | path.join(outsideReleaseDir, ".install-complete.json"), |
| 1639 | encodeJsonString({ |
| 1640 | releaseId: path.basename(releaseDir), |
| 1641 | version: "1.5.7", |
| 1642 | executable: { name: executableName, bytes: Buffer.byteLength(serverContents) }, |
| 1643 | }), |
| 1644 | ); |
| 1645 | yield* fs.chmod(releaseDir, 0o700); |
| 1646 | yield* fs.remove(path.dirname(releaseDir), { recursive: true, force: true }); |
| 1647 | yield* fs.symlink(outsideVersions, path.dirname(releaseDir)); |
| 1648 | |
| 1649 | const symlinkedRoot = yield* makeHarness({ baseDir, native: true }); |
| 1650 | expect((yield* symlinkedRoot.installation.state).phase).toBe("failed"); |
| 1651 | expect((yield* fs.stat(outsideBinary)).mode & 0o777).toBe(0o755); |
| 1652 | |
| 1653 | yield* symlinkedRoot.installation.remove(); |
| 1654 | expect(yield* fs.exists(managedDir)).toBe(false); |
| 1655 | expect(yield* fs.readFileString(outsideBinary)).toBe(serverContents); |
| 1656 | |
| 1657 | yield* fs.symlink(path.join(baseDir, "nonexistent-target"), managedDir); |
| 1658 | const danglingManaged = yield* makeHarness({ baseDir, native: true }); |
| 1659 | expect((yield* danglingManaged.installation.state).canRemove).toBe(true); |
| 1660 | yield* danglingManaged.installation.remove(); |
| 1661 | expect( |
| 1662 | yield* fs.readLink(managedDir).pipe( |
| 1663 | Effect.as(true), |
| 1664 | Effect.orElseSucceed(() => false), |
| 1665 | ), |
| 1666 | ).toBe(false); |
| 1667 | } |
| 1668 | }), |
| 1669 | ); |
| 1670 | }); |