From 7a58d1b4f3e52fda249c63b64f312f6bbe922de7 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 19 Nov 2026 20:10:01 -0800 Subject: [PATCH] fix(server): stop managed Antigravity CLI from self-updating in place and recover on reinstall --- .../provider/AntigravityInstallation.test.ts | 379 +++++++++ .../src/provider/AntigravityInstallation.ts | 769 ++++++++++++++---- .../src/provider/AntigravityProvider.test.ts | 9 + .../src/provider/AntigravityProvider.ts | 2 +- .../provider/antigravityAuthSupport.test.ts | 2 + .../src/provider/antigravityAuthSupport.ts | 2 + 6 files changed, 1021 insertions(+), 142 deletions(-) diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index 5cd8d029e0340..5dcd840991f83 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -125,6 +125,19 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( const asset = options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset; const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`); + if (options.baseDir === undefined && HostProcess.Platform.defaultValue() !== "win32") { + const versionsDir = path.join(managedDirectory, "versions"); + yield* Effect.addFinalizer(() => + fs.readDirectory(versionsDir).pipe( + Effect.flatMap((entries) => + Effect.forEach(entries, (entry) => + fs.chmod(path.join(versionsDir, entry), 0o700).pipe(Effect.ignore), + ), + ), + Effect.ignore, + ), + ); + } if (options.previous) { yield* writeRelease(managedDirectory, { releaseId: previousReleaseId, @@ -1114,6 +1127,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst Effect.gen(function* () { const { installation, baseDir, fs, path } = yield* makeHarness({ previous: true }); const previous = yield* installation.resolve(); + if (hostPlatform !== "win32") { + yield* fs.chmod(previous.managedVersionDirectory!, 0o700); + } yield* fs.remove(previous.executablePath); const externalDirectory = path.join(baseDir, "external"); yield* fs.makeDirectory(externalDirectory); @@ -1288,4 +1304,367 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst expect(requests).toEqual([]); }), ); + + it.effect( + "locks CLI releases on POSIX, detects on-disk changes, and recovers on same-releaseId reinstall", + () => + Effect.gen(function* () { + const { installation, fs, path, baseDir, stagingReleased } = yield* makeHarness({ + native: true, + }); + yield* installation.start; + expect(yield* terminalState(installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.7", + }); + yield* Deferred.await(stagingReleased); + + const installed = yield* installation.resolve(); + const releaseDir = installed.managedVersionDirectory!; + const recordPath = path.join(releaseDir, ".install-complete.json"); + + if (hostPlatform !== "win32") { + expect((yield* fs.stat(releaseDir)).mode & 0o777).toBe(0o500); + expect((yield* fs.stat(installed.executablePath)).mode & 0o777).toBe(0o555); + expect((yield* fs.stat(recordPath)).mode & 0o777).toBe(0o400); + if (process.getuid?.() !== 0) { + const stagingAttempt = yield* fs + .makeDirectory(path.join(releaseDir, "auto-update-staging")) + .pipe(Effect.exit); + expect(Exit.isFailure(stagingAttempt)).toBe(true); + } + + // Existing writable CLI releases are re-locked on startup. + yield* fs.chmod(releaseDir, 0o700); + yield* fs.chmod(installed.executablePath, 0o755); + yield* fs.chmod(recordPath, 0o600); + const relocked = yield* makeHarness({ baseDir, native: true }); + expect(yield* relocked.installation.state).toMatchObject({ + phase: "idle", + installedVersion: "1.5.7", + }); + expect((yield* fs.stat(releaseDir)).mode & 0o777).toBe(0o500); + expect((yield* fs.stat(installed.executablePath)).mode & 0o777).toBe(0o555); + expect((yield* fs.stat(recordPath)).mode & 0o777).toBe(0o400); + } + + // Simulate an external self-update mutating the managed binary in place. + if (hostPlatform !== "win32") { + yield* fs.chmod(releaseDir, 0o700); + yield* fs.chmod(installed.executablePath, 0o755); + } + yield* fs.writeFileString(installed.executablePath, `${serverContents}self-updated\n`, { + mode: 0o755, + }); + + const resolveError = yield* installation.resolve().pipe(Effect.flip); + expect(resolveError.detail).toContain("changed on disk"); + + const restarted = yield* makeHarness({ baseDir, native: true }); + expect(yield* restarted.installation.state).toMatchObject({ + phase: "failed", + installedVersion: null, + }); + expect((yield* restarted.installation.state).message).toContain("changed on disk"); + + // Reinstalling the same releaseId replaces the damaged directory cleanly. + yield* restarted.installation.start; + expect(yield* terminalState(restarted.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.7", + }); + yield* Deferred.await(restarted.stagingReleased); + + const repaired = yield* restarted.installation.resolve(); + expect(repaired.version).toBe("1.5.7"); + expect(yield* fs.readFileString(repaired.executablePath)).toBe(serverContents); + if (hostPlatform !== "win32") { + expect((yield* fs.stat(releaseDir)).mode & 0o777).toBe(0o500); + expect((yield* fs.stat(repaired.executablePath)).mode & 0o777).toBe(0o555); + } + + // remove() unlocks and deletes read-only CLI releases cleanly. + yield* restarted.installation.remove(); + expect(yield* fs.exists(restarted.installation.managedDirectory)).toBe(false); + }), + ); + + it.effect( + "restores displaced files on repair publish failure and rejects symlinked managed binaries", + () => + Effect.gen(function* () { + const { installation, fs, path, baseDir, stagingReleased } = yield* makeHarness({ + native: true, + }); + yield* installation.start; + expect((yield* terminalState(installation)).phase).toBe("succeeded"); + yield* Deferred.await(stagingReleased); + const installed = yield* installation.resolve(); + const releaseDir = installed.managedVersionDirectory!; + const recordPath = path.join(releaseDir, ".install-complete.json"); + const damagedContents = `${serverContents}damaged\n`; + + if (hostPlatform !== "win32") { + yield* fs.chmod(releaseDir, 0o700); + yield* fs.chmod(installed.executablePath, 0o755); + } + yield* fs.writeFileString(installed.executablePath, damagedContents, { mode: 0o755 }); + + // Fail the publish rename (staged -> destination) after moving the damaged release aside. + let renameToDestinationCount = 0; + const failingRepair = yield* makeHarness({ + baseDir, + native: true, + fileSystem: FileSystem.FileSystem.of({ + ...fs, + rename: (from, to) => { + if (to === releaseDir && ++renameToDestinationCount === 1) { + return Effect.fail( + PlatformError.systemError({ + _tag: "AlreadyExists", + module: "FileSystem", + method: "rename", + pathOrDescriptor: to, + description: "EEXIST: simulated publish failure", + }), + ); + } + return fs.rename(from, to); + }, + }), + }); + yield* failingRepair.installation.start; + expect(yield* terminalState(failingRepair.installation)).toMatchObject({ + phase: "failed", + }); + yield* Deferred.await(failingRepair.stagingReleased); + // The damaged directory was rolled back instead of being left missing. + expect(yield* fs.readFileString(installed.executablePath)).toBe(damagedContents); + + // If pointer write fails (e.g. ENOSPC) after repair swapped files in, rollback restores the displaced copy. + const failingPointerWrite = yield* makeHarness({ + baseDir, + native: true, + fileSystem: FileSystem.FileSystem.of({ + ...fs, + writeFileString: (target, content, options) => + path.basename(target) === "contents.tmp" + ? Effect.fail( + PlatformError.systemError({ + _tag: "Unknown", + module: "FileSystem", + method: "writeFileString", + pathOrDescriptor: target, + description: "ENOSPC: no space left on device", + }), + ) + : fs.writeFileString(target, content, options), + }), + }); + yield* failingPointerWrite.installation.start; + expect(yield* terminalState(failingPointerWrite.installation)).toMatchObject({ + phase: "failed", + }); + yield* Deferred.await(failingPointerWrite.stagingReleased); + expect(yield* fs.readFileString(installed.executablePath)).toBe(damagedContents); + + // A symlinked executable is rejected and startup does not chmod its target. + if (hostPlatform !== "win32") { + const outsideTarget = path.join(baseDir, "outside-target"); + yield* fs.writeFileString(outsideTarget, serverContents, { mode: 0o755 }); + yield* fs.remove(installed.executablePath); + yield* fs.symlink(outsideTarget, installed.executablePath); + const symlinked = yield* makeHarness({ baseDir, native: true }); + expect((yield* symlinked.installation.state).phase).toBe("failed"); + expect(yield* symlinked.installation.resolve().pipe(Effect.flip)).toMatchObject({ + operation: "resolve", + }); + expect((yield* fs.stat(outsideTarget)).mode & 0o777).toBe(0o755); + + // An unreadable completion record is repairable on reinstall. + if (process.getuid?.() !== 0) { + yield* fs.remove(installed.executablePath); + yield* fs.writeFileString(installed.executablePath, serverContents, { mode: 0o755 }); + yield* fs.chmod(recordPath, 0o000); + const unreadableRecord = yield* makeHarness({ baseDir, native: true }); + expect((yield* unreadableRecord.installation.state).phase).toBe("failed"); + yield* unreadableRecord.installation.start; + expect(yield* terminalState(unreadableRecord.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.7", + }); + yield* Deferred.await(unreadableRecord.stagingReleased); + } + } + + // A regular file occupying the release directory path is classified as incomplete and replaced on reinstall. + if (hostPlatform !== "win32") { + yield* fs.chmod(releaseDir, 0o700); + } + yield* fs.remove(releaseDir, { recursive: true, force: true }); + yield* fs.writeFileString(releaseDir, "not a directory"); + expect(yield* installation.resolve().pipe(Effect.flip)).toMatchObject({ + operation: "resolve", + }); + const repairedFromFile = yield* makeHarness({ baseDir, native: true }); + yield* repairedFromFile.installation.start; + expect(yield* terminalState(repairedFromFile.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.7", + }); + yield* Deferred.await(repairedFromFile.stagingReleased); + expect(yield* fs.readFileString(installed.executablePath)).toBe(serverContents); + + // A second service acquiring a custom binaryPath (or external symlink to it) during a + // repair swap waits for the managed lock instead of missing the briefly displaced binary. + if (hostPlatform !== "win32") { + yield* fs.chmod(releaseDir, 0o700); + yield* fs.chmod(installed.executablePath, 0o755); + } + yield* fs.writeFileString(installed.executablePath, damagedContents, { mode: 0o755 }); + const externalSymlink = path.join(baseDir, "external-agy-link"); + if (hostPlatform !== "win32") { + yield* fs.symlink(installed.executablePath, externalSymlink); + // Even when the release is broken, remove() expands `~` and blocks deletion of a protected symlink. + expect( + yield* installation + .remove(["~/external-agy-link"]) + .pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir), Effect.flip), + ).toMatchObject({ operation: "remove" }); + } + const displacedPaused = yield* Deferred.make(); + const resumeSwap = yield* Deferred.make(); + const pausedRepair = yield* makeHarness({ + baseDir, + native: true, + fileSystem: FileSystem.FileSystem.of({ + ...fs, + rename: (from, to) => + from === releaseDir && path.basename(to) === "displaced" + ? fs + .rename(from, to) + .pipe( + Effect.andThen(Deferred.succeed(displacedPaused, undefined)), + Effect.andThen(Deferred.await(resumeSwap)), + ) + : fs.rename(from, to), + }), + }); + const managedDir = pausedRepair.installation.managedDirectory; + let watchResolveExists = false; + const expectedResolves = hostPlatform !== "win32" ? 2 : 1; + let seenResolves = 0; + const resolversEntered = yield* Deferred.make(); + const secondServer = yield* makeHarness({ + baseDir, + native: true, + fileSystem: FileSystem.FileSystem.of({ + ...fs, + exists: (target) => + watchResolveExists && target === managedDir + ? Effect.suspend(() => { + seenResolves += 1; + return seenResolves >= expectedResolves + ? Deferred.succeed(resolversEntered, undefined).pipe( + Effect.andThen(fs.exists(target)), + ) + : fs.exists(target); + }) + : fs.exists(target), + }), + }); + yield* Effect.gen(function* () { + yield* pausedRepair.installation.start; + yield* Deferred.await(displacedPaused); + expect(yield* fs.exists(releaseDir)).toBe(false); + watchResolveExists = true; + const acquireFiber = yield* secondServer.installation + .acquire(installed.executablePath) + .pipe(Effect.scoped, Effect.forkScoped); + const symlinkResolveFiber = + hostPlatform !== "win32" + ? yield* secondServer.installation.resolve(externalSymlink).pipe(Effect.forkScoped) + : null; + yield* Deferred.await(resolversEntered); + expect(yield* fs.exists(`${managedDir}.lock`)).toBe(true); + expect(yield* fs.exists(releaseDir)).toBe(false); + expect(acquireFiber.pollUnsafe()).toBeUndefined(); + if (symlinkResolveFiber !== null) { + expect(symlinkResolveFiber.pollUnsafe()).toBeUndefined(); + } + yield* Deferred.succeed(resumeSwap, undefined); + expect(yield* terminalState(pausedRepair.installation)).toMatchObject({ + phase: "succeeded", + }); + const acquired = yield* Fiber.join(acquireFiber); + expect(acquired).toMatchObject({ + source: "override", + executablePath: installed.executablePath, + version: "1.5.7", + }); + if (symlinkResolveFiber !== null) { + expect(yield* Fiber.join(symlinkResolveFiber)).toMatchObject({ + source: "override", + executablePath: installed.executablePath, + version: "1.5.7", + }); + } + expect(yield* fs.readFileString(acquired.executablePath)).toBe(serverContents); + yield* Deferred.await(pausedRepair.stagingReleased); + }).pipe(Effect.ensuring(Deferred.succeed(resumeSwap, undefined).pipe(Effect.asVoid))); + + if (hostPlatform !== "win32" && process.getuid?.() !== 0) { + // A valid external CLI override resolves even when the managed directory's parent is read-only. + const externalCli = path.join(baseDir, "agy"); + yield* fs.writeFileString(externalCli, "external cli", { mode: 0o755 }); + const managedParent = path.dirname(managedDir); + yield* fs.chmod(managedParent, 0o500); + yield* Effect.gen(function* () { + expect(yield* installation.resolve(externalCli)).toMatchObject({ + executablePath: externalCli, + source: "override", + managedVersionDirectory: null, + }); + }).pipe(Effect.ensuring(fs.chmod(managedParent, 0o700).pipe(Effect.ignore))); + + // A symlinked versions/ root is rejected on startup without chmodding outside targets, + // and a dangling managedDirectory symlink can still be removed. + const outsideVersions = path.join(baseDir, "outside-versions"); + const outsideReleaseDir = path.join(outsideVersions, path.basename(releaseDir)); + const outsideBinary = path.join(outsideReleaseDir, executableName); + yield* fs.makeDirectory(outsideReleaseDir, { recursive: true }); + yield* fs.writeFileString(outsideBinary, serverContents, { mode: 0o755 }); + yield* fs.writeFileString( + path.join(outsideReleaseDir, ".install-complete.json"), + encodeJsonString({ + releaseId: path.basename(releaseDir), + version: "1.5.7", + executable: { name: executableName, bytes: Buffer.byteLength(serverContents) }, + }), + ); + yield* fs.chmod(releaseDir, 0o700); + yield* fs.remove(path.dirname(releaseDir), { recursive: true, force: true }); + yield* fs.symlink(outsideVersions, path.dirname(releaseDir)); + + const symlinkedRoot = yield* makeHarness({ baseDir, native: true }); + expect((yield* symlinkedRoot.installation.state).phase).toBe("failed"); + expect((yield* fs.stat(outsideBinary)).mode & 0o777).toBe(0o755); + + yield* symlinkedRoot.installation.remove(); + expect(yield* fs.exists(managedDir)).toBe(false); + expect(yield* fs.readFileString(outsideBinary)).toBe(serverContents); + + yield* fs.symlink(path.join(baseDir, "nonexistent-target"), managedDir); + const danglingManaged = yield* makeHarness({ baseDir, native: true }); + expect((yield* danglingManaged.installation.state).canRemove).toBe(true); + yield* danglingManaged.installation.remove(); + expect( + yield* fs.readLink(managedDir).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ), + ).toBe(false); + } + }), + ); }); diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index a0be08b803875..569a4a6308756 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -23,6 +23,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import type { PlatformError } from "effect/PlatformError"; +import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; @@ -35,6 +36,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as NodeCrypto from "node:crypto"; import * as NodeFSP from "node:fs/promises"; import * as EffectAcpErrors from "effect-acp/errors"; +import { lock } from "proper-lockfile"; import * as ServerConfig from "../config.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -72,6 +74,7 @@ const InstalledRelease = Schema.Struct({ type InstalledRelease = typeof InstalledRelease.Type; const encodeActiveRelease = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease)); const encodeInstalledRelease = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease)); +const decodeInstalledRelease = Schema.decodeEffect(Schema.fromJsonString(InstalledRelease)); export class AntigravityInstallationError extends Schema.TaggedError()( "AntigravityInstallationError", @@ -274,53 +277,296 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); }); - const completedRelease = Effect.fn("AntigravityInstallation.completedRelease")(function* ( + const isSymlink = Effect.fn("AntigravityInstallation.isSymlink")(function* (filePath: string) { + return yield* fs.readLink(filePath).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + }); + + const isInsideDirectory = Effect.fn("AntigravityInstallation.isInsideDirectory")(function* ( + targetPath: string, + rootDirectory: string, + ) { + const realRoot = yield* fs.realPath(rootDirectory).pipe(Effect.option); + const realTarget = yield* fs.realPath(targetPath).pipe(Effect.option); + if (Option.isNone(realRoot) || Option.isNone(realTarget)) return false; + return ( + realTarget.value === realRoot.value || + realTarget.value.startsWith(`${realRoot.value}${path.sep}`) + ); + }); + + const hasSymlinkedManagedRoot = Effect.gen(function* () { + return (yield* isSymlink(managedDirectory)) || (yield* isSymlink(versionsDirectory)); + }); + + const ensureRealManagedRoot = Effect.fn("AntigravityInstallation.ensureRealManagedRoot")( + function* (operation: "install" | "activate" | "resolve") { + if (yield* hasSymlinkedManagedRoot) { + return yield* installationError( + operation, + "The managed Antigravity directory is a symbolic link. Remove it and reinstall.", + ); + } + }, + ); + + const isLockContentionError = (cause: unknown) => + isInstallationError(cause) && + Predicate.isObject(cause.cause) && + Predicate.hasProperty(cause.cause, "code") && + cause.cause.code === "ELOCKED"; + + // Prevent the native CLI auto-updater from staging and replacing the managed binary in place. + const lockReleaseDirectory = Effect.fn("AntigravityInstallation.lockReleaseDirectory")(function* ( + directory: string, + executablePath: string, + strict: boolean, + ) { + if (platform === "win32") return; + const recordPath = path.join(directory, RELEASE_RECORD); + const apply = Effect.gen(function* () { + if ( + (yield* hasSymlinkedManagedRoot) || + (yield* isSymlink(directory)) || + (yield* isSymlink(executablePath)) || + (yield* isSymlink(recordPath)) || + !(yield* isInsideDirectory(directory, versionsDirectory)) || + !(yield* isInsideDirectory(executablePath, directory)) || + !(yield* isInsideDirectory(recordPath, directory)) + ) { + return yield* installationError( + "activate", + "The managed Antigravity runtime contains an unexpected symbolic link. Reinstall it.", + ); + } + yield* fs.chmod(executablePath, 0o555); + yield* fs.chmod(recordPath, 0o400); + yield* fs.chmod(directory, 0o500); + }); + if (strict) { + yield* apply; + } else { + yield* apply.pipe(Effect.ignore); + } + }); + + const unlockDirectoryTree = Effect.fn("AntigravityInstallation.unlockDirectoryTree")(function* ( + directory: string, + ): Effect.fn.Return { + if (platform === "win32") return; + if ( + (yield* hasSymlinkedManagedRoot) || + (yield* isSymlink(directory)) || + !(yield* isInsideDirectory(directory, managedDirectory)) + ) { + return; + } + const info = yield* fs.stat(directory).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "Directory") return; + yield* fs.chmod(directory, 0o700).pipe(Effect.ignore); + const entries = yield* fs + .readDirectory(directory) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + for (const entry of entries) { + const entryPath = path.join(directory, entry); + if (yield* isSymlink(entryPath)) continue; + const entryInfo = yield* fs.stat(entryPath).pipe(Effect.option); + if (Option.isSome(entryInfo) && entryInfo.value.type === "Directory") { + yield* unlockDirectoryTree(entryPath); + } + } + }); + + const removeReleaseDirectory = Effect.fn("AntigravityInstallation.removeReleaseDirectory")( + function* (directory: string) { + yield* unlockDirectoryTree(directory); + yield* fs + .remove(directory, { recursive: true, force: true }) + .pipe(retryWhileWindowsHoldsHandles); + }, + ); + + // Serialize resolve, publish, activation, pruning, and removal across server instances sharing managedDirectory. + // Locking managedDirectory places the lock directory beside it so remove() can delete managedDirectory safely. + const withManagedLock = ( + operation: "activate" | "remove" | "resolve", + effect: Effect.Effect, + ): Effect.Effect => + Effect.scoped( + Effect.acquireRelease( + Effect.tryPromise({ + try: () => + lock(managedDirectory, { + realpath: false, + stale: 30_000, + update: 10_000, + retries: { retries: 60, minTimeout: 25, maxTimeout: 150 }, + onCompromised: () => {}, + }), + catch: (cause) => + installationError( + operation, + Predicate.isObject(cause) && + Predicate.hasProperty(cause, "code") && + cause.code === "ELOCKED" + ? "Another Antigravity installation is already in progress. Try again." + : "Could not lock the managed Antigravity directory. Try again.", + cause, + ), + }), + (release) => Effect.promise(() => release().catch(() => undefined)), + ).pipe(Effect.andThen(effect)), + ); + + const inspectManagedFile = Effect.fn("AntigravityInstallation.inspectManagedFile")(function* ( + filePath: string, + expectedBytes: number, + ) { + if (yield* isSymlink(filePath)) return "incomplete" as const; + const info = yield* fs.stat(filePath).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed(null), + ), + ); + if ( + info === null || + info.type !== "File" || + (platform !== "win32" && (info.mode & 0o111) === 0) + ) { + return "incomplete" as const; + } + return Number(info.size) === expectedBytes ? ("ok" as const) : ("changed" as const); + }); + + const inspectRelease = Effect.fn("AntigravityInstallation.inspectRelease")(function* ( releaseId: string, ) { + const incomplete = () => + ({ + _tag: "repairable", + error: installationError( + "resolve", + "The managed Antigravity runtime is incomplete. Reinstall it.", + ), + }) as const; + const invalidRecord = (cause?: unknown) => + ({ + _tag: "repairable", + error: installationError( + "resolve", + "The managed runtime record is invalid. Reinstall Antigravity.", + cause, + ), + }) as const; + if (yield* hasSymlinkedManagedRoot) return incomplete(); const directory = path.join(versionsDirectory, releaseId); - const record = yield* readRecord(path.join(directory, RELEASE_RECORD), InstalledRelease); + if (yield* isSymlink(directory)) return incomplete(); + const directoryInfo = yield* fs.stat(directory).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed(null), + ), + ); + if (directoryInfo === null || directoryInfo.type !== "Directory") return incomplete(); + const recordPath = path.join(directory, RELEASE_RECORD); + if (yield* isSymlink(recordPath)) return incomplete(); + const recordInfo = yield* fs.stat(recordPath).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed(null), + ), + ); + if (recordInfo === null) return incomplete(); + if (recordInfo.type !== "File" || Number(recordInfo.size) > RECORD_MAX_BYTES) { + return invalidRecord(); + } + const readResult = yield* fs.readFileString(recordPath).pipe( + Effect.map((contents) => ({ _tag: "ok" as const, contents })), + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + () => Effect.succeed({ _tag: "missing" as const }), + ), + Effect.catchIf( + (error) => error.reason._tag === "PermissionDenied", + (error) => Effect.succeed({ _tag: "unreadable" as const, error }), + ), + ); + if (readResult._tag === "missing") return incomplete(); + if (readResult._tag === "unreadable") return invalidRecord(readResult.error); + const decoded = yield* decodeInstalledRelease(readResult.contents).pipe(Effect.option); + if (Option.isNone(decoded)) return invalidRecord(); + const record = decoded.value; if (record.releaseId === releaseId && record.executable.name !== cliExecutableName) { - return yield* installationError( - "resolve", - `Antigravity ${record.version} predates the Antigravity CLI and no longer works with this T3 Code release. Update it in Antigravity setup.`, - ); + return { + _tag: "repairable" as const, + error: installationError( + "resolve", + `Antigravity ${record.version} predates the Antigravity CLI and no longer works with this T3 Code release. Update it in Antigravity setup.`, + ), + }; } if ( record.releaseId !== releaseId || !Number.isSafeInteger(record.executable.bytes) || record.executable.bytes <= 0 || - !record.version.trim() || - !(yield* executableFile( - path.join(directory, record.executable.name), - record.executable.bytes, - )) + !record.version.trim() ) { - return yield* installationError( - "resolve", - "The managed Antigravity runtime is incomplete. Reinstall it.", - ); + return incomplete(); + } + const executablePath = path.join(directory, record.executable.name); + const executableStatus = yield* inspectManagedFile(executablePath, record.executable.bytes); + if (executableStatus === "incomplete") return incomplete(); + if (executableStatus === "changed") { + return { + _tag: "repairable" as const, + error: installationError( + "resolve", + "The managed Antigravity runtime changed on disk. Reinstall it in Antigravity setup.", + ), + }; } return { - executablePath: path.join(directory, record.executable.name), - source: "managed", - version: record.version, - managedVersionDirectory: directory, - } satisfies AntigravityExecutable; + _tag: "valid" as const, + executable: { + executablePath, + source: "managed" as const, + version: record.version, + managedVersionDirectory: directory, + } satisfies AntigravityExecutable, + }; }); + const completedRelease = Effect.fn("AntigravityInstallation.completedRelease")(function* ( + releaseId: string, + ) { + const inspected = yield* inspectRelease(releaseId); + if (inspected._tag === "repairable") return yield* inspected.error; + return inspected.executable; + }); + + const isManagedVersionCandidate = Effect.fn("AntigravityInstallation.isManagedVersionCandidate")( + function* (executablePath: string) { + const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option); + const directory = path.dirname(executablePath); + return ( + Option.isSome(realVersions) && + path.dirname(directory) === realVersions.value && + /^[a-f0-9]{64}$/u.test(path.basename(directory)) + ); + }, + ); + const fromExternal = Effect.fn("AntigravityInstallation.fromExternal")(function* ( candidate: string, source: "override" | "path", ) { if (!(yield* executableFile(candidate))) return null; const executablePath = yield* fs.realPath(candidate); - const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option); const directory = path.dirname(executablePath); - if ( - Option.isSome(realVersions) && - path.dirname(directory) === realVersions.value && - /^[a-f0-9]{64}$/u.test(path.basename(directory)) - ) { + if (yield* isManagedVersionCandidate(executablePath)) { const installed = yield* completedRelease(path.basename(directory)); return { ...installed, source }; } @@ -334,6 +580,30 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma } satisfies AntigravityExecutable; }); + // Resolve a verified external CLI outside versions/ without taking the managed lock, so a + // read-only managed parent or active repair does not block unrelated external executables. + const findVerifiedExternal = Effect.fn("AntigravityInstallation.findVerifiedExternal")(function* ( + candidates: ReadonlyArray, + source: "override" | "path", + ) { + for (const candidate of candidates) { + if (!(yield* executableFile(candidate))) continue; + const resolved = yield* fs.realPath(candidate).pipe(Effect.option); + if (Option.isNone(resolved)) return null; + const executablePath = resolved.value; + if (yield* isManagedVersionCandidate(executablePath)) return null; + if (isAntigravityCli(candidate, executablePath)) { + return { + executablePath: candidate, + source, + version: null, + managedVersionDirectory: null, + } satisfies AntigravityExecutable; + } + } + return null; + }); + const commandPath = (command: string, env: NodeJS.ProcessEnv) => resolveCommandPath(command, { env }).pipe( Effect.map((resolved) => (resolved === null ? null : path.resolve(resolved))), @@ -364,40 +634,71 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma return candidates; }); + const resolveUnlocked = Effect.fn("AntigravityInstallation.resolveUnlocked")(function* ( + binaryPath?: string, + processEnvironment?: NodeJS.ProcessEnv, + ) { + const override = expandHomePath(binaryPath?.trim() ?? "", yield* HostProcess.HomeDirectory); + if (override) { + for (const candidate of yield* commandCandidates(override, processEnvironment)) { + const selected = yield* fromExternal(candidate, "override"); + if (selected) return selected; + } + return yield* installationError( + "resolve", + "The custom Antigravity executable is missing or not executable, or it is not the agy CLI.", + ); + } + if (yield* fs.exists(activePath)) { + yield* ensureRealManagedRoot("resolve"); + const active = yield* readRecord(activePath, ActiveRelease); + const installed = yield* completedRelease(active.releaseId); + if (yield* isWithdrawn(installed.version)) + return yield* installationError( + "resolve", + `Antigravity ${installed.version} no longer works with this T3 Code release. Update it in Antigravity setup.`, + ); + return installed; + } + for (const candidate of yield* commandCandidates("agy", processEnvironment)) { + const selected = yield* fromExternal(candidate, "path"); + if (selected) return selected; + } + return yield* installationError( + "resolve", + supported + ? "Antigravity ACP runtime is not installed. Install it in this environment's provider settings or set a custom ACP executable path. The Antigravity app, IDE, and CLI are separate installations." + : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`, + ); + }); + const resolve: AntigravityInstallationService["resolve"] = Effect.fn( "AntigravityInstallation.resolve", )( function* (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) { const override = expandHomePath(binaryPath?.trim() ?? "", yield* HostProcess.HomeDirectory); if (override) { - for (const candidate of yield* commandCandidates(override, processEnvironment)) { - const selected = yield* fromExternal(candidate, "override"); - if (selected) return selected; - } - return yield* installationError( - "resolve", - "The custom Antigravity executable is missing or not executable, or it is not the agy CLI.", + const external = yield* findVerifiedExternal( + yield* commandCandidates(override, processEnvironment), + "override", ); + if (external !== null) return external; } - if (yield* fs.exists(activePath)) { - const active = yield* readRecord(activePath, ActiveRelease); - const installed = yield* completedRelease(active.releaseId); - if (yield* isWithdrawn(installed.version)) - return yield* installationError( - "resolve", - `Antigravity ${installed.version} no longer works with this T3 Code release. Update it in Antigravity setup.`, - ); - return installed; - } - for (const candidate of yield* commandCandidates("agy", processEnvironment)) { - const selected = yield* fromExternal(candidate, "path"); - if (selected) return selected; - } - return yield* installationError( - "resolve", - supported - ? "Antigravity ACP runtime is not installed. Install it in this environment's provider settings or set a custom ACP executable path. The Antigravity app, IDE, and CLI are separate installations." - : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`, + const lookup = resolveUnlocked(binaryPath, processEnvironment); + if (!(yield* fs.exists(managedDirectory))) return yield* lookup; + return yield* withManagedLock("resolve", lookup).pipe( + Effect.catch((cause) => + Effect.gen(function* () { + if (!override && !(yield* fs.exists(activePath))) { + const external = yield* findVerifiedExternal( + yield* commandCandidates("agy", processEnvironment), + "path", + ); + if (external !== null) return external; + } + return yield* cause; + }), + ), ); }, Effect.mapError( @@ -517,14 +818,20 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma // Each update lands in its own directory. Best effort: a busy gate means a session is // resolving, so the next start or update finishes the cleanup. - const pruneInactiveReleases = Effect.gen(function* () { + const pruneInactiveReleasesBody = Effect.gen(function* () { + if ((yield* isSymlink(managedDirectory)) || (yield* isSymlink(versionsDirectory))) return; const active = yield* readRecord(activePath, ActiveRelease); for (const entry of yield* fs.readDirectory(versionsDirectory)) { if (entry === active.releaseId || !/^[a-f0-9]{64}$/u.test(entry)) continue; const directory = path.join(versionsDirectory, entry); if (leases.has(directory)) continue; - yield* fs.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore); + yield* removeReleaseDirectory(directory).pipe(Effect.ignore); } + }); + + const pruneInactiveReleases = Effect.gen(function* () { + if (!(yield* fs.exists(activePath))) return; + yield* withManagedLock("activate", pruneInactiveReleasesBody); }).pipe( gate.withPermitsIfAvailable(1), Effect.ignore, @@ -546,32 +853,53 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); const report = (phase: ProviderInstallState["phase"], message: string | null) => SubscriptionRef.update(state, (current) => ({ ...current, phase, message })); + yield* ensureRealManagedRoot("install"); yield* fs.makeDirectory(versionsDirectory, { recursive: true }); + yield* ensureRealManagedRoot("install"); yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true })); const destination = path.join(versionsDirectory, releaseId); + const writeAndActivate = Effect.fn("AntigravityInstallation.writeAndActivate")(function* ( + pointerDirectory: string, + ) { + yield* ensureRealManagedRoot("activate"); + yield* ensureEligible(asset.version); + const inspected = yield* inspectRelease(releaseId); + if (inspected._tag !== "valid" || inspected.executable.version !== asset.version) { + return yield* installationError( + "activate", + "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.", + ); + } + yield* lockReleaseDirectory(destination, inspected.executable.executablePath, true); + const pointerPath = path.join(pointerDirectory, "contents.tmp"); + yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), { + flag: "wx", + mode: 0o600, + }); + yield* fs.rename(pointerPath, activePath); + yield* pruneInactiveReleasesBody.pipe(Effect.ignore); + yield* SubscriptionRef.update( + state, + (current) => + ({ + ...current, + phase: "succeeded", + installedVersion: asset.version, + message: null, + }) satisfies ProviderInstallState, + ); + }); const activate = Effect.fn("AntigravityInstallation.activate")( function* () { - yield* ensureEligible(asset.version); const pointerDirectory = yield* fs.makeTempDirectoryScoped({ directory: managedDirectory, prefix: "active.json.", }); - const pointerPath = path.join(pointerDirectory, "contents.tmp"); - yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), { - flag: "wx", - mode: 0o600, - }); - yield* fs.rename(pointerPath, activePath); - yield* pruneInactiveReleases; - yield* SubscriptionRef.update( - state, - (current) => - ({ - ...current, - phase: "succeeded", - installedVersion: asset.version, - message: null, - }) satisfies ProviderInstallState, + yield* gate.withPermit( + withManagedLock( + "activate", + writeAndActivate(pointerDirectory).pipe(Effect.uninterruptible), + ), ); }, Effect.scoped, @@ -581,21 +909,25 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.", ), ), - Effect.uninterruptible, ); - if (yield* fs.exists(destination)) { - const existing = yield* completedRelease(releaseId); - if (existing.version !== asset.version) { - return yield* installationError( - "verify", - "The existing managed release has the wrong version. Remove it before reinstalling.", + if ((yield* fs.exists(destination)) || (yield* isSymlink(destination))) { + const existing = yield* inspectRelease(releaseId); + if (existing._tag === "valid") { + if (existing.executable.version !== asset.version) { + return yield* installationError( + "verify", + "The existing managed release has the wrong version. Remove it before reinstalling.", + ); + } + yield* report("verifying", "Checking the installed runtime."); + yield* validate(existing.executable, asset.version).pipe( + Effect.scoped, + withValidationTimeout, ); + yield* activate(); + return; } - yield* report("verifying", "Checking the installed runtime."); - yield* validate(existing, asset.version).pipe(Effect.scoped, withValidationTimeout); - yield* activate(); - return; } const available = yield* Effect.tryPromise({ @@ -616,6 +948,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma directory: versionsDirectory, prefix: ".install-", }); + yield* Effect.addFinalizer(() => unlockDirectoryTree(staging).pipe(Effect.ignore)); const archivePath = path.join(staging, "download"); const pairDirectory = path.join(staging, "runtime"); yield* fs.makeDirectory(pairDirectory); @@ -739,33 +1072,143 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma yield* encodeInstalledRelease(record), { flag: "wx", mode: 0o600 }, ); - yield* fs.rename(pairDirectory, destination).pipe( - retryWhileWindowsHoldsHandles, - Effect.catch((cause) => - completedRelease(releaseId).pipe( - Effect.flatMap((existing) => - existing.version === asset.version - ? validate(existing, asset.version).pipe(Effect.scoped, withValidationTimeout) - : Effect.fail( - installationError( + // Lock files read-only before publishing; the directory itself is locked after cross-parent rename + // because macOS requires write permission on a moved directory to update its `..` entry. + if (platform !== "win32") { + yield* fs.chmod(executablePath, 0o555); + yield* fs.chmod(path.join(pairDirectory, RELEASE_RECORD), 0o400); + } + const published = yield* Effect.scoped( + Effect.gen(function* () { + const pointerDirectory = yield* fs.makeTempDirectoryScoped({ + directory: managedDirectory, + prefix: "active.json.", + }); + return yield* gate.withPermit( + withManagedLock( + "activate", + Effect.gen(function* () { + yield* ensureRealManagedRoot("activate"); + const destinationExisted = + (yield* fs.exists(destination)) || (yield* isSymlink(destination)); + if (!destinationExisted) { + const renameError = yield* fs.rename(pairDirectory, destination).pipe( + retryWhileWindowsHoldsHandles, + Effect.as(null), + Effect.catch((cause) => Effect.succeed(cause)), + ); + if (renameError === null) { + const activateError = yield* writeAndActivate(pointerDirectory).pipe( + Effect.as(null), + Effect.catch((cause) => Effect.succeed(cause)), + ); + if (activateError !== null) { + yield* removeReleaseDirectory(destination).pipe(Effect.ignore); + return yield* activateError; + } + return { _tag: "published" as const }; + } + if (!(yield* fs.exists(destination)) && !(yield* isSymlink(destination))) { + return yield* installationError( + "activate", + "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.", + renameError, + ); + } + } + const inspected = yield* inspectRelease(releaseId); + if (inspected._tag === "valid") { + if (inspected.executable.version !== asset.version) { + return yield* installationError( "activate", "Another installation published a different Antigravity release.", + ); + } + return { _tag: "existing" as const, executable: inspected.executable }; + } + // acquire() cannot lease a broken release, but an already-running session may hold one. + if (leases.has(destination)) { + return yield* installationError( + "activate", + "Stop Antigravity sessions and sign-in flows before reinstalling its managed runtime.", + ); + } + // Move the damaged release aside into staging so failure can restore it. + const displaced = path.join(staging, "displaced"); + yield* unlockDirectoryTree(destination); + yield* fs.rename(destination, displaced).pipe( + retryWhileWindowsHoldsHandles, + Effect.mapError((cause) => + installationError( + "activate", + "Could not replace the damaged Antigravity runtime. Check for open processes and try again.", + cause, ), ), - ), - Effect.mapError((error) => - isInstallationError(error) && error.operation === "verify" - ? error - : installationError( + ); + const publishError = yield* fs.rename(pairDirectory, destination).pipe( + retryWhileWindowsHoldsHandles, + Effect.as(null), + Effect.catch((cause) => Effect.succeed(cause)), + ); + if (publishError !== null) { + const restored = yield* fs.rename(displaced, destination).pipe( + retryWhileWindowsHoldsHandles, + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + return yield* installationError( "activate", - "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.", - cause, - ), + restored + ? "Could not replace the damaged Antigravity runtime. The previous files were restored. Try again." + : "Could not replace the damaged Antigravity runtime, and the damaged files could not be restored. Reinstall Antigravity.", + publishError, + ); + } + const activateError = yield* writeAndActivate(pointerDirectory).pipe( + Effect.as(null), + Effect.catch((cause) => Effect.succeed(cause)), + ); + if (activateError !== null) { + const rolledBack = yield* Effect.gen(function* () { + yield* removeReleaseDirectory(destination); + yield* fs.rename(displaced, destination).pipe(retryWhileWindowsHoldsHandles); + }).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + return yield* installationError( + "activate", + rolledBack + ? "Could not activate the repaired Antigravity runtime. The previous files were restored. Try again." + : "Could not activate the repaired Antigravity runtime, and the damaged files could not be restored. Reinstall Antigravity.", + activateError, + ); + } + return { _tag: "published" as const }; + }).pipe( + Effect.mapError((error) => + isInstallationError(error) + ? error + : installationError( + "activate", + "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.", + error, + ), + ), + Effect.uninterruptible, + ), ), - ), - ), + ); + }), ); - yield* activate(); + if (published._tag === "existing") { + yield* validate(published.executable, asset.version).pipe( + Effect.scoped, + withValidationTimeout, + ); + yield* activate(); + } }, Effect.scoped, Effect.mapError( @@ -949,28 +1392,46 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma "Stop Antigravity sessions and sign-in flows before removing its managed runtime.", ); } - const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option); - if (Option.isSome(realManaged)) { - for (const binaryPath of protectedBinaryPaths) { - if (!binaryPath.trim()) continue; - const selected = yield* resolve(binaryPath).pipe(Effect.option); - if (Option.isSome(selected) && selected.value.managedVersionDirectory) { - return yield* installationError( - "remove", - "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.", - ); - } - const resolved = yield* fs.realPath(binaryPath).pipe(Effect.option); - const candidate = Option.getOrElse(resolved, () => path.resolve(binaryPath)); - if (candidate.startsWith(`${realManaged.value}${path.sep}`)) { - return yield* installationError( - "remove", - "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.", - ); - } - } + if ((yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory))) { + const homeDirectory = yield* HostProcess.HomeDirectory; + yield* withManagedLock( + "remove", + Effect.gen(function* () { + const managedIsSymlink = yield* isSymlink(managedDirectory); + if (!managedIsSymlink) { + const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option); + if (Option.isSome(realManaged)) { + for (const binaryPath of protectedBinaryPaths) { + const trimmed = binaryPath.trim(); + if (!trimmed) continue; + const selected = yield* resolveUnlocked(trimmed).pipe(Effect.option); + if (Option.isSome(selected) && selected.value.managedVersionDirectory) { + return yield* installationError( + "remove", + "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.", + ); + } + const expanded = expandHomePath(trimmed, homeDirectory); + const resolved = yield* fs.realPath(expanded).pipe(Effect.option); + const candidate = Option.getOrElse(resolved, () => path.resolve(expanded)); + if (candidate.startsWith(`${realManaged.value}${path.sep}`)) { + return yield* installationError( + "remove", + "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.", + ); + } + } + } + if (!(yield* isSymlink(versionsDirectory))) { + yield* unlockDirectoryTree(versionsDirectory); + } + } + yield* fs + .remove(managedDirectory, { recursive: true, force: true }) + .pipe(retryWhileWindowsHoldsHandles); + }), + ); } - yield* fs.remove(managedDirectory, { recursive: true, force: true }); yield* SubscriptionRef.update( state, (current) => @@ -996,28 +1457,54 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); yield* Effect.gen(function* () { - const canRemove = yield* fs.exists(managedDirectory); + const canRemove = (yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory)); yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove })); if (!(yield* fs.exists(activePath))) return; - const active = yield* readRecord(activePath, ActiveRelease); - const installed = yield* completedRelease(active.releaseId); - yield* SubscriptionRef.update(state, (current) => ({ - ...current, - installedVersion: installed.version, - })); - }).pipe( - Effect.catch((cause) => - SubscriptionRef.update( - state, - (current) => - ({ + yield* gate.withPermit( + withManagedLock( + "activate", + Effect.gen(function* () { + if (!(yield* fs.exists(activePath))) { + const exists = + (yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory)); + yield* SubscriptionRef.update(state, (current) => ({ + ...current, + canRemove: exists, + })); + return; + } + yield* ensureRealManagedRoot("activate"); + const active = yield* readRecord(activePath, ActiveRelease); + const installed = yield* completedRelease(active.releaseId); + if (installed.managedVersionDirectory !== null) { + yield* lockReleaseDirectory( + installed.managedVersionDirectory, + installed.executablePath, + false, + ); + } + yield* SubscriptionRef.update(state, (current) => ({ ...current, - phase: "failed", - message: isInstallationError(cause) - ? cause.detail - : "The managed Antigravity runtime is incomplete. Remove it and reinstall.", - }) satisfies ProviderInstallState, + installedVersion: installed.version, + })); + }), ), + ); + }).pipe( + Effect.catch((cause) => + isLockContentionError(cause) + ? Effect.void + : SubscriptionRef.update( + state, + (current) => + ({ + ...current, + phase: "failed", + message: isInstallationError(cause) + ? cause.detail + : "The managed Antigravity runtime is incomplete. Remove it and reinstall.", + }) satisfies ProviderInstallState, + ), ), ); diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index e28f250d0d67f..522be29a8b187 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -597,6 +597,15 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { }), installed: false, }, + { + error: new ProviderSetupError({ + instanceId, + operation: "resolve", + detail: + "The managed Antigravity runtime changed on disk. Reinstall it in Antigravity setup.", + }), + installed: false, + }, ]; for (const { error, installed } of failures) { yield* harness.provider.onSessionStarted(started, "/workspace"); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index b24712d363d99..b3b68d46e8ba8 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -151,7 +151,7 @@ function isMissingInstallation(error: EffectAcpErrors.AcpError | ProviderSetupEr return ( error._tag === "ProviderSetupError" && error.operation === "resolve" && - /not installed|missing|incomplete|does not publish/i.test(error.detail) + /not installed|missing|incomplete|changed on disk|does not publish/i.test(error.detail) ); } diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.ts index 28444db4cbe7b..34b5b78609661 100644 --- a/apps/server/src/provider/antigravityAuthSupport.test.ts +++ b/apps/server/src/provider/antigravityAuthSupport.test.ts @@ -72,6 +72,7 @@ describe("Antigravity process environment", () => { GEMINI_HOME: "/shared-gemini-home", gemini_home: "/alias-shared-home", AGY_ACP_FORCE_FILE_STORAGE: "0", + agy_cli_disable_auto_update: "0", BROWSER: "open-real-browser", browser: "another-real-browser", PYTHONUNBUFFERED: "0", @@ -100,6 +101,7 @@ describe("Antigravity process environment", () => { CUSTOM_SETTING: "keep-this", GEMINI_HOME: profile.geminiHome, AGY_ACP_FORCE_FILE_STORAGE: "1", + AGY_CLI_DISABLE_AUTO_UPDATE: "1", BROWSER: profile.browserCommand, PYTHONUNBUFFERED: "1", ELECTRON_RUN_AS_NODE: "1", diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index f16b15a522f5d..804adc430f300 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -72,6 +72,7 @@ const removedEnvironmentKeys = new Set([ "AGY_ACP_ENABLE_OAUTH", "GEMINI_HOME", "AGY_ACP_FORCE_FILE_STORAGE", + "AGY_CLI_DISABLE_AUTO_UPDATE", "BROWSER", "PYTHONUNBUFFERED", "ELECTRON_RUN_AS_NODE", @@ -227,6 +228,7 @@ function antigravityEnvironment( : {}), GEMINI_HOME: profile.geminiHome, AGY_ACP_FORCE_FILE_STORAGE: "1", + AGY_CLI_DISABLE_AUTO_UPDATE: "1", BROWSER: profile.browserCommand, PYTHONUNBUFFERED: "1", ELECTRON_RUN_AS_NODE: "1",