@devries-cameron20 / t3code-1 / commits / d1822be5a9
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): stop managed Antigravity CLI from self-updating in place and recover on reinstall (#39363)

Theo Browne committed Nov 19, 2026 at 20:30 UTC d1822be5a99a335fd3cd34c482234d0b36d79c09
6 files changed +1021 -142
apps/server/src/provider/AntigravityInstallation.test.ts
+379
@@ -125,6 +125,19 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* (
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,
@@ -1114,6 +1127,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst
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);
@@ -1288,4 +1304,367 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst
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 });
apps/server/src/provider/AntigravityInstallation.ts
+628 -141
@@ -23,6 +23,7 @@ import * as Layer from "effect/Layer";
23 import * as Option from "effect/Option";
24 import * as Path from "effect/Path";
25 import type { PlatformError } from "effect/PlatformError";
26 +import * as Predicate from "effect/Predicate";
27 import * as Schema from "effect/Schema";
28 import * as Schedule from "effect/Schedule";
29 import * as Scope from "effect/Scope";
@@ -35,6 +36,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
36 import * as NodeCrypto from "node:crypto";
37 import * as NodeFSP from "node:fs/promises";
38 import * as EffectAcpErrors from "effect-acp/errors";
39 +import { lock } from "proper-lockfile";
40
41 import * as ServerConfig from "../config.ts";
42 import * as ServerSettings from "../serverSettings.ts";
@@ -72,6 +74,7 @@ const InstalledRelease = Schema.Struct({
74 type InstalledRelease = typeof InstalledRelease.Type;
75 const encodeActiveRelease = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease));
76 const encodeInstalledRelease = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease));
77 +const decodeInstalledRelease = Schema.decodeEffect(Schema.fromJsonString(InstalledRelease));
78
79 export class AntigravityInstallationError extends Schema.TaggedError<AntigravityInstallationError>()(
80 "AntigravityInstallationError",
@@ -274,53 +277,296 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
277 );
278 });
279
277 - const completedRelease = Effect.fn("AntigravityInstallation.completedRelease")(function* (
280 + const isSymlink = Effect.fn("AntigravityInstallation.isSymlink")(function* (filePath: string) {
281 + return yield* fs.readLink(filePath).pipe(
282 + Effect.as(true),
283 + Effect.orElseSucceed(() => false),
284 + );
285 + });
286 +
287 + const isInsideDirectory = Effect.fn("AntigravityInstallation.isInsideDirectory")(function* (
288 + targetPath: string,
289 + rootDirectory: string,
290 + ) {
291 + const realRoot = yield* fs.realPath(rootDirectory).pipe(Effect.option);
292 + const realTarget = yield* fs.realPath(targetPath).pipe(Effect.option);
293 + if (Option.isNone(realRoot) || Option.isNone(realTarget)) return false;
294 + return (
295 + realTarget.value === realRoot.value ||
296 + realTarget.value.startsWith(`${realRoot.value}${path.sep}`)
297 + );
298 + });
299 +
300 + const hasSymlinkedManagedRoot = Effect.gen(function* () {
301 + return (yield* isSymlink(managedDirectory)) || (yield* isSymlink(versionsDirectory));
302 + });
303 +
304 + const ensureRealManagedRoot = Effect.fn("AntigravityInstallation.ensureRealManagedRoot")(
305 + function* (operation: "install" | "activate" | "resolve") {
306 + if (yield* hasSymlinkedManagedRoot) {
307 + return yield* installationError(
308 + operation,
309 + "The managed Antigravity directory is a symbolic link. Remove it and reinstall.",
310 + );
311 + }
312 + },
313 + );
314 +
315 + const isLockContentionError = (cause: unknown) =>
316 + isInstallationError(cause) &&
317 + Predicate.isObject(cause.cause) &&
318 + Predicate.hasProperty(cause.cause, "code") &&
319 + cause.cause.code === "ELOCKED";
320 +
321 + // Prevent the native CLI auto-updater from staging and replacing the managed binary in place.
322 + const lockReleaseDirectory = Effect.fn("AntigravityInstallation.lockReleaseDirectory")(function* (
323 + directory: string,
324 + executablePath: string,
325 + strict: boolean,
326 + ) {
327 + if (platform === "win32") return;
328 + const recordPath = path.join(directory, RELEASE_RECORD);
329 + const apply = Effect.gen(function* () {
330 + if (
331 + (yield* hasSymlinkedManagedRoot) ||
332 + (yield* isSymlink(directory)) ||
333 + (yield* isSymlink(executablePath)) ||
334 + (yield* isSymlink(recordPath)) ||
335 + !(yield* isInsideDirectory(directory, versionsDirectory)) ||
336 + !(yield* isInsideDirectory(executablePath, directory)) ||
337 + !(yield* isInsideDirectory(recordPath, directory))
338 + ) {
339 + return yield* installationError(
340 + "activate",
341 + "The managed Antigravity runtime contains an unexpected symbolic link. Reinstall it.",
342 + );
343 + }
344 + yield* fs.chmod(executablePath, 0o555);
345 + yield* fs.chmod(recordPath, 0o400);
346 + yield* fs.chmod(directory, 0o500);
347 + });
348 + if (strict) {
349 + yield* apply;
350 + } else {
351 + yield* apply.pipe(Effect.ignore);
352 + }
353 + });
354 +
355 + const unlockDirectoryTree = Effect.fn("AntigravityInstallation.unlockDirectoryTree")(function* (
356 + directory: string,
357 + ): Effect.fn.Return<void> {
358 + if (platform === "win32") return;
359 + if (
360 + (yield* hasSymlinkedManagedRoot) ||
361 + (yield* isSymlink(directory)) ||
362 + !(yield* isInsideDirectory(directory, managedDirectory))
363 + ) {
364 + return;
365 + }
366 + const info = yield* fs.stat(directory).pipe(Effect.option);
367 + if (Option.isNone(info) || info.value.type !== "Directory") return;
368 + yield* fs.chmod(directory, 0o700).pipe(Effect.ignore);
369 + const entries = yield* fs
370 + .readDirectory(directory)
371 + .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
372 + for (const entry of entries) {
373 + const entryPath = path.join(directory, entry);
374 + if (yield* isSymlink(entryPath)) continue;
375 + const entryInfo = yield* fs.stat(entryPath).pipe(Effect.option);
376 + if (Option.isSome(entryInfo) && entryInfo.value.type === "Directory") {
377 + yield* unlockDirectoryTree(entryPath);
378 + }
379 + }
380 + });
381 +
382 + const removeReleaseDirectory = Effect.fn("AntigravityInstallation.removeReleaseDirectory")(
383 + function* (directory: string) {
384 + yield* unlockDirectoryTree(directory);
385 + yield* fs
386 + .remove(directory, { recursive: true, force: true })
387 + .pipe(retryWhileWindowsHoldsHandles);
388 + },
389 + );
390 +
391 + // Serialize resolve, publish, activation, pruning, and removal across server instances sharing managedDirectory.
392 + // Locking managedDirectory places the lock directory beside it so remove() can delete managedDirectory safely.
393 + const withManagedLock = <A, E, R>(
394 + operation: "activate" | "remove" | "resolve",
395 + effect: Effect.Effect<A, E, R>,
396 + ): Effect.Effect<A, E | AntigravityInstallationError, R> =>
397 + Effect.scoped(
398 + Effect.acquireRelease(
399 + Effect.tryPromise({
400 + try: () =>
401 + lock(managedDirectory, {
402 + realpath: false,
403 + stale: 30_000,
404 + update: 10_000,
405 + retries: { retries: 60, minTimeout: 25, maxTimeout: 150 },
406 + onCompromised: () => {},
407 + }),
408 + catch: (cause) =>
409 + installationError(
410 + operation,
411 + Predicate.isObject(cause) &&
412 + Predicate.hasProperty(cause, "code") &&
413 + cause.code === "ELOCKED"
414 + ? "Another Antigravity installation is already in progress. Try again."
415 + : "Could not lock the managed Antigravity directory. Try again.",
416 + cause,
417 + ),
418 + }),
419 + (release) => Effect.promise(() => release().catch(() => undefined)),
420 + ).pipe(Effect.andThen(effect)),
421 + );
422 +
423 + const inspectManagedFile = Effect.fn("AntigravityInstallation.inspectManagedFile")(function* (
424 + filePath: string,
425 + expectedBytes: number,
426 + ) {
427 + if (yield* isSymlink(filePath)) return "incomplete" as const;
428 + const info = yield* fs.stat(filePath).pipe(
429 + Effect.catchIf(
430 + (error) => error.reason._tag === "NotFound",
431 + () => Effect.succeed(null),
432 + ),
433 + );
434 + if (
435 + info === null ||
436 + info.type !== "File" ||
437 + (platform !== "win32" && (info.mode & 0o111) === 0)
438 + ) {
439 + return "incomplete" as const;
440 + }
441 + return Number(info.size) === expectedBytes ? ("ok" as const) : ("changed" as const);
442 + });
443 +
444 + const inspectRelease = Effect.fn("AntigravityInstallation.inspectRelease")(function* (
445 releaseId: string,
446 ) {
447 + const incomplete = () =>
448 + ({
449 + _tag: "repairable",
450 + error: installationError(
451 + "resolve",
452 + "The managed Antigravity runtime is incomplete. Reinstall it.",
453 + ),
454 + }) as const;
455 + const invalidRecord = (cause?: unknown) =>
456 + ({
457 + _tag: "repairable",
458 + error: installationError(
459 + "resolve",
460 + "The managed runtime record is invalid. Reinstall Antigravity.",
461 + cause,
462 + ),
463 + }) as const;
464 + if (yield* hasSymlinkedManagedRoot) return incomplete();
465 const directory = path.join(versionsDirectory, releaseId);
281 - const record = yield* readRecord(path.join(directory, RELEASE_RECORD), InstalledRelease);
466 + if (yield* isSymlink(directory)) return incomplete();
467 + const directoryInfo = yield* fs.stat(directory).pipe(
468 + Effect.catchIf(
469 + (error) => error.reason._tag === "NotFound",
470 + () => Effect.succeed(null),
471 + ),
472 + );
473 + if (directoryInfo === null || directoryInfo.type !== "Directory") return incomplete();
474 + const recordPath = path.join(directory, RELEASE_RECORD);
475 + if (yield* isSymlink(recordPath)) return incomplete();
476 + const recordInfo = yield* fs.stat(recordPath).pipe(
477 + Effect.catchIf(
478 + (error) => error.reason._tag === "NotFound",
479 + () => Effect.succeed(null),
480 + ),
481 + );
482 + if (recordInfo === null) return incomplete();
483 + if (recordInfo.type !== "File" || Number(recordInfo.size) > RECORD_MAX_BYTES) {
484 + return invalidRecord();
485 + }
486 + const readResult = yield* fs.readFileString(recordPath).pipe(
487 + Effect.map((contents) => ({ _tag: "ok" as const, contents })),
488 + Effect.catchIf(
489 + (error) => error.reason._tag === "NotFound",
490 + () => Effect.succeed({ _tag: "missing" as const }),
491 + ),
492 + Effect.catchIf(
493 + (error) => error.reason._tag === "PermissionDenied",
494 + (error) => Effect.succeed({ _tag: "unreadable" as const, error }),
495 + ),
496 + );
497 + if (readResult._tag === "missing") return incomplete();
498 + if (readResult._tag === "unreadable") return invalidRecord(readResult.error);
499 + const decoded = yield* decodeInstalledRelease(readResult.contents).pipe(Effect.option);
500 + if (Option.isNone(decoded)) return invalidRecord();
501 + const record = decoded.value;
502 if (record.releaseId === releaseId && record.executable.name !== cliExecutableName) {
283 - return yield* installationError(
284 - "resolve",
285 - `Antigravity ${record.version} predates the Antigravity CLI and no longer works with this T3 Code release. Update it in Antigravity setup.`,
286 - );
503 + return {
504 + _tag: "repairable" as const,
505 + error: installationError(
506 + "resolve",
507 + `Antigravity ${record.version} predates the Antigravity CLI and no longer works with this T3 Code release. Update it in Antigravity setup.`,
508 + ),
509 + };
510 }
511 if (
512 record.releaseId !== releaseId ||
513 !Number.isSafeInteger(record.executable.bytes) ||
514 record.executable.bytes <= 0 ||
292 - !record.version.trim() ||
293 - !(yield* executableFile(
294 - path.join(directory, record.executable.name),
295 - record.executable.bytes,
296 - ))
515 + !record.version.trim()
516 ) {
298 - return yield* installationError(
299 - "resolve",
300 - "The managed Antigravity runtime is incomplete. Reinstall it.",
301 - );
517 + return incomplete();
518 + }
519 + const executablePath = path.join(directory, record.executable.name);
520 + const executableStatus = yield* inspectManagedFile(executablePath, record.executable.bytes);
521 + if (executableStatus === "incomplete") return incomplete();
522 + if (executableStatus === "changed") {
523 + return {
524 + _tag: "repairable" as const,
525 + error: installationError(
526 + "resolve",
527 + "The managed Antigravity runtime changed on disk. Reinstall it in Antigravity setup.",
528 + ),
529 + };
530 }
531 return {
304 - executablePath: path.join(directory, record.executable.name),
305 - source: "managed",
306 - version: record.version,
307 - managedVersionDirectory: directory,
308 - } satisfies AntigravityExecutable;
532 + _tag: "valid" as const,
533 + executable: {
534 + executablePath,
535 + source: "managed" as const,
536 + version: record.version,
537 + managedVersionDirectory: directory,
538 + } satisfies AntigravityExecutable,
539 + };
540 });
541
542 + const completedRelease = Effect.fn("AntigravityInstallation.completedRelease")(function* (
543 + releaseId: string,
544 + ) {
545 + const inspected = yield* inspectRelease(releaseId);
546 + if (inspected._tag === "repairable") return yield* inspected.error;
547 + return inspected.executable;
548 + });
549 +
550 + const isManagedVersionCandidate = Effect.fn("AntigravityInstallation.isManagedVersionCandidate")(
551 + function* (executablePath: string) {
552 + const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option);
553 + const directory = path.dirname(executablePath);
554 + return (
555 + Option.isSome(realVersions) &&
556 + path.dirname(directory) === realVersions.value &&
557 + /^[a-f0-9]{64}$/u.test(path.basename(directory))
558 + );
559 + },
560 + );
561 +
562 const fromExternal = Effect.fn("AntigravityInstallation.fromExternal")(function* (
563 candidate: string,
564 source: "override" | "path",
565 ) {
566 if (!(yield* executableFile(candidate))) return null;
567 const executablePath = yield* fs.realPath(candidate);
317 - const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option);
568 const directory = path.dirname(executablePath);
319 - if (
320 - Option.isSome(realVersions) &&
321 - path.dirname(directory) === realVersions.value &&
322 - /^[a-f0-9]{64}$/u.test(path.basename(directory))
323 - ) {
569 + if (yield* isManagedVersionCandidate(executablePath)) {
570 const installed = yield* completedRelease(path.basename(directory));
571 return { ...installed, source };
572 }
@@ -334,6 +580,30 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
580 } satisfies AntigravityExecutable;
581 });
582
583 + // Resolve a verified external CLI outside versions/ without taking the managed lock, so a
584 + // read-only managed parent or active repair does not block unrelated external executables.
585 + const findVerifiedExternal = Effect.fn("AntigravityInstallation.findVerifiedExternal")(function* (
586 + candidates: ReadonlyArray<string>,
587 + source: "override" | "path",
588 + ) {
589 + for (const candidate of candidates) {
590 + if (!(yield* executableFile(candidate))) continue;
591 + const resolved = yield* fs.realPath(candidate).pipe(Effect.option);
592 + if (Option.isNone(resolved)) return null;
593 + const executablePath = resolved.value;
594 + if (yield* isManagedVersionCandidate(executablePath)) return null;
595 + if (isAntigravityCli(candidate, executablePath)) {
596 + return {
597 + executablePath: candidate,
598 + source,
599 + version: null,
600 + managedVersionDirectory: null,
601 + } satisfies AntigravityExecutable;
602 + }
603 + }
604 + return null;
605 + });
606 +
607 const commandPath = (command: string, env: NodeJS.ProcessEnv) =>
608 resolveCommandPath(command, { env }).pipe(
609 Effect.map((resolved) => (resolved === null ? null : path.resolve(resolved))),
@@ -364,40 +634,71 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
634 return candidates;
635 });
636
637 + const resolveUnlocked = Effect.fn("AntigravityInstallation.resolveUnlocked")(function* (
638 + binaryPath?: string,
639 + processEnvironment?: NodeJS.ProcessEnv,
640 + ) {
641 + const override = expandHomePath(binaryPath?.trim() ?? "", yield* HostProcess.HomeDirectory);
642 + if (override) {
643 + for (const candidate of yield* commandCandidates(override, processEnvironment)) {
644 + const selected = yield* fromExternal(candidate, "override");
645 + if (selected) return selected;
646 + }
647 + return yield* installationError(
648 + "resolve",
649 + "The custom Antigravity executable is missing or not executable, or it is not the agy CLI.",
650 + );
651 + }
652 + if (yield* fs.exists(activePath)) {
653 + yield* ensureRealManagedRoot("resolve");
654 + const active = yield* readRecord(activePath, ActiveRelease);
655 + const installed = yield* completedRelease(active.releaseId);
656 + if (yield* isWithdrawn(installed.version))
657 + return yield* installationError(
658 + "resolve",
659 + `Antigravity ${installed.version} no longer works with this T3 Code release. Update it in Antigravity setup.`,
660 + );
661 + return installed;
662 + }
663 + for (const candidate of yield* commandCandidates("agy", processEnvironment)) {
664 + const selected = yield* fromExternal(candidate, "path");
665 + if (selected) return selected;
666 + }
667 + return yield* installationError(
668 + "resolve",
669 + supported
670 + ? "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."
671 + : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`,
672 + );
673 + });
674 +
675 const resolve: AntigravityInstallationService["resolve"] = Effect.fn(
676 "AntigravityInstallation.resolve",
677 )(
678 function* (binaryPath?: string, processEnvironment?: NodeJS.ProcessEnv) {
679 const override = expandHomePath(binaryPath?.trim() ?? "", yield* HostProcess.HomeDirectory);
680 if (override) {
373 - for (const candidate of yield* commandCandidates(override, processEnvironment)) {
374 - const selected = yield* fromExternal(candidate, "override");
375 - if (selected) return selected;
376 - }
377 - return yield* installationError(
378 - "resolve",
379 - "The custom Antigravity executable is missing or not executable, or it is not the agy CLI.",
681 + const external = yield* findVerifiedExternal(
682 + yield* commandCandidates(override, processEnvironment),
683 + "override",
684 );
685 + if (external !== null) return external;
686 }
382 - if (yield* fs.exists(activePath)) {
383 - const active = yield* readRecord(activePath, ActiveRelease);
384 - const installed = yield* completedRelease(active.releaseId);
385 - if (yield* isWithdrawn(installed.version))
386 - return yield* installationError(
387 - "resolve",
388 - `Antigravity ${installed.version} no longer works with this T3 Code release. Update it in Antigravity setup.`,
389 - );
390 - return installed;
391 - }
392 - for (const candidate of yield* commandCandidates("agy", processEnvironment)) {
393 - const selected = yield* fromExternal(candidate, "path");
394 - if (selected) return selected;
395 - }
396 - return yield* installationError(
397 - "resolve",
398 - supported
399 - ? "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."
400 - : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`,
687 + const lookup = resolveUnlocked(binaryPath, processEnvironment);
688 + if (!(yield* fs.exists(managedDirectory))) return yield* lookup;
689 + return yield* withManagedLock("resolve", lookup).pipe(
690 + Effect.catch((cause) =>
691 + Effect.gen(function* () {
692 + if (!override && !(yield* fs.exists(activePath))) {
693 + const external = yield* findVerifiedExternal(
694 + yield* commandCandidates("agy", processEnvironment),
695 + "path",
696 + );
697 + if (external !== null) return external;
698 + }
699 + return yield* cause;
700 + }),
701 + ),
702 );
703 },
704 Effect.mapError(
@@ -517,14 +818,20 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
818
819 // Each update lands in its own directory. Best effort: a busy gate means a session is
820 // resolving, so the next start or update finishes the cleanup.
520 - const pruneInactiveReleases = Effect.gen(function* () {
821 + const pruneInactiveReleasesBody = Effect.gen(function* () {
822 + if ((yield* isSymlink(managedDirectory)) || (yield* isSymlink(versionsDirectory))) return;
823 const active = yield* readRecord(activePath, ActiveRelease);
824 for (const entry of yield* fs.readDirectory(versionsDirectory)) {
825 if (entry === active.releaseId || !/^[a-f0-9]{64}$/u.test(entry)) continue;
826 const directory = path.join(versionsDirectory, entry);
827 if (leases.has(directory)) continue;
526 - yield* fs.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore);
828 + yield* removeReleaseDirectory(directory).pipe(Effect.ignore);
829 }
830 + });
831 +
832 + const pruneInactiveReleases = Effect.gen(function* () {
833 + if (!(yield* fs.exists(activePath))) return;
834 + yield* withManagedLock("activate", pruneInactiveReleasesBody);
835 }).pipe(
836 gate.withPermitsIfAvailable(1),
837 Effect.ignore,
@@ -546,32 +853,53 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
853 );
854 const report = (phase: ProviderInstallState["phase"], message: string | null) =>
855 SubscriptionRef.update(state, (current) => ({ ...current, phase, message }));
856 + yield* ensureRealManagedRoot("install");
857 yield* fs.makeDirectory(versionsDirectory, { recursive: true });
858 + yield* ensureRealManagedRoot("install");
859 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true }));
860 const destination = path.join(versionsDirectory, releaseId);
861 + const writeAndActivate = Effect.fn("AntigravityInstallation.writeAndActivate")(function* (
862 + pointerDirectory: string,
863 + ) {
864 + yield* ensureRealManagedRoot("activate");
865 + yield* ensureEligible(asset.version);
866 + const inspected = yield* inspectRelease(releaseId);
867 + if (inspected._tag !== "valid" || inspected.executable.version !== asset.version) {
868 + return yield* installationError(
869 + "activate",
870 + "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
871 + );
872 + }
873 + yield* lockReleaseDirectory(destination, inspected.executable.executablePath, true);
874 + const pointerPath = path.join(pointerDirectory, "contents.tmp");
875 + yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), {
876 + flag: "wx",
877 + mode: 0o600,
878 + });
879 + yield* fs.rename(pointerPath, activePath);
880 + yield* pruneInactiveReleasesBody.pipe(Effect.ignore);
881 + yield* SubscriptionRef.update(
882 + state,
883 + (current) =>
884 + ({
885 + ...current,
886 + phase: "succeeded",
887 + installedVersion: asset.version,
888 + message: null,
889 + }) satisfies ProviderInstallState,
890 + );
891 + });
892 const activate = Effect.fn("AntigravityInstallation.activate")(
893 function* () {
554 - yield* ensureEligible(asset.version);
894 const pointerDirectory = yield* fs.makeTempDirectoryScoped({
895 directory: managedDirectory,
896 prefix: "active.json.",
897 });
559 - const pointerPath = path.join(pointerDirectory, "contents.tmp");
560 - yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), {
561 - flag: "wx",
562 - mode: 0o600,
563 - });
564 - yield* fs.rename(pointerPath, activePath);
565 - yield* pruneInactiveReleases;
566 - yield* SubscriptionRef.update(
567 - state,
568 - (current) =>
569 - ({
570 - ...current,
571 - phase: "succeeded",
572 - installedVersion: asset.version,
573 - message: null,
574 - }) satisfies ProviderInstallState,
898 + yield* gate.withPermit(
899 + withManagedLock(
900 + "activate",
901 + writeAndActivate(pointerDirectory).pipe(Effect.uninterruptible),
902 + ),
903 );
904 },
905 Effect.scoped,
@@ -581,21 +909,25 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
909 "Could not activate Antigravity. The previous runtime is unchanged. Check for locked files and try again.",
910 ),
911 ),
584 - Effect.uninterruptible,
912 );
913
587 - if (yield* fs.exists(destination)) {
588 - const existing = yield* completedRelease(releaseId);
589 - if (existing.version !== asset.version) {
590 - return yield* installationError(
591 - "verify",
592 - "The existing managed release has the wrong version. Remove it before reinstalling.",
914 + if ((yield* fs.exists(destination)) || (yield* isSymlink(destination))) {
915 + const existing = yield* inspectRelease(releaseId);
916 + if (existing._tag === "valid") {
917 + if (existing.executable.version !== asset.version) {
918 + return yield* installationError(
919 + "verify",
920 + "The existing managed release has the wrong version. Remove it before reinstalling.",
921 + );
922 + }
923 + yield* report("verifying", "Checking the installed runtime.");
924 + yield* validate(existing.executable, asset.version).pipe(
925 + Effect.scoped,
926 + withValidationTimeout,
927 );
928 + yield* activate();
929 + return;
930 }
595 - yield* report("verifying", "Checking the installed runtime.");
596 - yield* validate(existing, asset.version).pipe(Effect.scoped, withValidationTimeout);
597 - yield* activate();
598 - return;
931 }
932
933 const available = yield* Effect.tryPromise({
@@ -616,6 +948,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
948 directory: versionsDirectory,
949 prefix: ".install-",
950 });
951 + yield* Effect.addFinalizer(() => unlockDirectoryTree(staging).pipe(Effect.ignore));
952 const archivePath = path.join(staging, "download");
953 const pairDirectory = path.join(staging, "runtime");
954 yield* fs.makeDirectory(pairDirectory);
@@ -739,33 +1072,143 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
1072 yield* encodeInstalledRelease(record),
1073 { flag: "wx", mode: 0o600 },
1074 );
742 - yield* fs.rename(pairDirectory, destination).pipe(
743 - retryWhileWindowsHoldsHandles,
744 - Effect.catch((cause) =>
745 - completedRelease(releaseId).pipe(
746 - Effect.flatMap((existing) =>
747 - existing.version === asset.version
748 - ? validate(existing, asset.version).pipe(Effect.scoped, withValidationTimeout)
749 - : Effect.fail(
750 - installationError(
1075 + // Lock files read-only before publishing; the directory itself is locked after cross-parent rename
1076 + // because macOS requires write permission on a moved directory to update its `..` entry.
1077 + if (platform !== "win32") {
1078 + yield* fs.chmod(executablePath, 0o555);
1079 + yield* fs.chmod(path.join(pairDirectory, RELEASE_RECORD), 0o400);
1080 + }
1081 + const published = yield* Effect.scoped(
1082 + Effect.gen(function* () {
1083 + const pointerDirectory = yield* fs.makeTempDirectoryScoped({
1084 + directory: managedDirectory,
1085 + prefix: "active.json.",
1086 + });
1087 + return yield* gate.withPermit(
1088 + withManagedLock(
1089 + "activate",
1090 + Effect.gen(function* () {
1091 + yield* ensureRealManagedRoot("activate");
1092 + const destinationExisted =
1093 + (yield* fs.exists(destination)) || (yield* isSymlink(destination));
1094 + if (!destinationExisted) {
1095 + const renameError = yield* fs.rename(pairDirectory, destination).pipe(
1096 + retryWhileWindowsHoldsHandles,
1097 + Effect.as(null),
1098 + Effect.catch((cause) => Effect.succeed(cause)),
1099 + );
1100 + if (renameError === null) {
1101 + const activateError = yield* writeAndActivate(pointerDirectory).pipe(
1102 + Effect.as(null),
1103 + Effect.catch((cause) => Effect.succeed(cause)),
1104 + );
1105 + if (activateError !== null) {
1106 + yield* removeReleaseDirectory(destination).pipe(Effect.ignore);
1107 + return yield* activateError;
1108 + }
1109 + return { _tag: "published" as const };
1110 + }
1111 + if (!(yield* fs.exists(destination)) && !(yield* isSymlink(destination))) {
1112 + return yield* installationError(
1113 + "activate",
1114 + "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
1115 + renameError,
1116 + );
1117 + }
1118 + }
1119 + const inspected = yield* inspectRelease(releaseId);
1120 + if (inspected._tag === "valid") {
1121 + if (inspected.executable.version !== asset.version) {
1122 + return yield* installationError(
1123 "activate",
1124 "Another installation published a different Antigravity release.",
1125 + );
1126 + }
1127 + return { _tag: "existing" as const, executable: inspected.executable };
1128 + }
1129 + // acquire() cannot lease a broken release, but an already-running session may hold one.
1130 + if (leases.has(destination)) {
1131 + return yield* installationError(
1132 + "activate",
1133 + "Stop Antigravity sessions and sign-in flows before reinstalling its managed runtime.",
1134 + );
1135 + }
1136 + // Move the damaged release aside into staging so failure can restore it.
1137 + const displaced = path.join(staging, "displaced");
1138 + yield* unlockDirectoryTree(destination);
1139 + yield* fs.rename(destination, displaced).pipe(
1140 + retryWhileWindowsHoldsHandles,
1141 + Effect.mapError((cause) =>
1142 + installationError(
1143 + "activate",
1144 + "Could not replace the damaged Antigravity runtime. Check for open processes and try again.",
1145 + cause,
1146 ),
1147 ),
755 - ),
756 - Effect.mapError((error) =>
757 - isInstallationError(error) && error.operation === "verify"
758 - ? error
759 - : installationError(
1148 + );
1149 + const publishError = yield* fs.rename(pairDirectory, destination).pipe(
1150 + retryWhileWindowsHoldsHandles,
1151 + Effect.as(null),
1152 + Effect.catch((cause) => Effect.succeed(cause)),
1153 + );
1154 + if (publishError !== null) {
1155 + const restored = yield* fs.rename(displaced, destination).pipe(
1156 + retryWhileWindowsHoldsHandles,
1157 + Effect.as(true),
1158 + Effect.orElseSucceed(() => false),
1159 + );
1160 + return yield* installationError(
1161 "activate",
761 - "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
762 - cause,
763 - ),
1162 + restored
1163 + ? "Could not replace the damaged Antigravity runtime. The previous files were restored. Try again."
1164 + : "Could not replace the damaged Antigravity runtime, and the damaged files could not be restored. Reinstall Antigravity.",
1165 + publishError,
1166 + );
1167 + }
1168 + const activateError = yield* writeAndActivate(pointerDirectory).pipe(
1169 + Effect.as(null),
1170 + Effect.catch((cause) => Effect.succeed(cause)),
1171 + );
1172 + if (activateError !== null) {
1173 + const rolledBack = yield* Effect.gen(function* () {
1174 + yield* removeReleaseDirectory(destination);
1175 + yield* fs.rename(displaced, destination).pipe(retryWhileWindowsHoldsHandles);
1176 + }).pipe(
1177 + Effect.as(true),
1178 + Effect.orElseSucceed(() => false),
1179 + );
1180 + return yield* installationError(
1181 + "activate",
1182 + rolledBack
1183 + ? "Could not activate the repaired Antigravity runtime. The previous files were restored. Try again."
1184 + : "Could not activate the repaired Antigravity runtime, and the damaged files could not be restored. Reinstall Antigravity.",
1185 + activateError,
1186 + );
1187 + }
1188 + return { _tag: "published" as const };
1189 + }).pipe(
1190 + Effect.mapError((error) =>
1191 + isInstallationError(error)
1192 + ? error
1193 + : installationError(
1194 + "activate",
1195 + "Could not publish the Antigravity runtime. The previous release is unchanged. Try again.",
1196 + error,
1197 + ),
1198 + ),
1199 + Effect.uninterruptible,
1200 + ),
1201 ),
765 - ),
766 - ),
1202 + );
1203 + }),
1204 );
768 - yield* activate();
1205 + if (published._tag === "existing") {
1206 + yield* validate(published.executable, asset.version).pipe(
1207 + Effect.scoped,
1208 + withValidationTimeout,
1209 + );
1210 + yield* activate();
1211 + }
1212 },
1213 Effect.scoped,
1214 Effect.mapError(
@@ -949,28 +1392,46 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
1392 "Stop Antigravity sessions and sign-in flows before removing its managed runtime.",
1393 );
1394 }
952 - const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
953 - if (Option.isSome(realManaged)) {
954 - for (const binaryPath of protectedBinaryPaths) {
955 - if (!binaryPath.trim()) continue;
956 - const selected = yield* resolve(binaryPath).pipe(Effect.option);
957 - if (Option.isSome(selected) && selected.value.managedVersionDirectory) {
958 - return yield* installationError(
959 - "remove",
960 - "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
961 - );
962 - }
963 - const resolved = yield* fs.realPath(binaryPath).pipe(Effect.option);
964 - const candidate = Option.getOrElse(resolved, () => path.resolve(binaryPath));
965 - if (candidate.startsWith(`${realManaged.value}${path.sep}`)) {
966 - return yield* installationError(
967 - "remove",
968 - "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
969 - );
970 - }
971 - }
1395 + if ((yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory))) {
1396 + const homeDirectory = yield* HostProcess.HomeDirectory;
1397 + yield* withManagedLock(
1398 + "remove",
1399 + Effect.gen(function* () {
1400 + const managedIsSymlink = yield* isSymlink(managedDirectory);
1401 + if (!managedIsSymlink) {
1402 + const realManaged = yield* fs.realPath(managedDirectory).pipe(Effect.option);
1403 + if (Option.isSome(realManaged)) {
1404 + for (const binaryPath of protectedBinaryPaths) {
1405 + const trimmed = binaryPath.trim();
1406 + if (!trimmed) continue;
1407 + const selected = yield* resolveUnlocked(trimmed).pipe(Effect.option);
1408 + if (Option.isSome(selected) && selected.value.managedVersionDirectory) {
1409 + return yield* installationError(
1410 + "remove",
1411 + "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
1412 + );
1413 + }
1414 + const expanded = expandHomePath(trimmed, homeDirectory);
1415 + const resolved = yield* fs.realPath(expanded).pipe(Effect.option);
1416 + const candidate = Option.getOrElse(resolved, () => path.resolve(expanded));
1417 + if (candidate.startsWith(`${realManaged.value}${path.sep}`)) {
1418 + return yield* installationError(
1419 + "remove",
1420 + "A provider instance has a custom path inside this managed runtime. Clear that path before removing it.",
1421 + );
1422 + }
1423 + }
1424 + }
1425 + if (!(yield* isSymlink(versionsDirectory))) {
1426 + yield* unlockDirectoryTree(versionsDirectory);
1427 + }
1428 + }
1429 + yield* fs
1430 + .remove(managedDirectory, { recursive: true, force: true })
1431 + .pipe(retryWhileWindowsHoldsHandles);
1432 + }),
1433 + );
1434 }
973 - yield* fs.remove(managedDirectory, { recursive: true, force: true });
1435 yield* SubscriptionRef.update(
1436 state,
1437 (current) =>
@@ -996,28 +1457,54 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
1457 );
1458
1459 yield* Effect.gen(function* () {
999 - const canRemove = yield* fs.exists(managedDirectory);
1460 + const canRemove = (yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory));
1461 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
1462 if (!(yield* fs.exists(activePath))) return;
1002 - const active = yield* readRecord(activePath, ActiveRelease);
1003 - const installed = yield* completedRelease(active.releaseId);
1004 - yield* SubscriptionRef.update(state, (current) => ({
1005 - ...current,
1006 - installedVersion: installed.version,
1007 - }));
1008 - }).pipe(
1009 - Effect.catch((cause) =>
1010 - SubscriptionRef.update(
1011 - state,
1012 - (current) =>
1013 - ({
1463 + yield* gate.withPermit(
1464 + withManagedLock(
1465 + "activate",
1466 + Effect.gen(function* () {
1467 + if (!(yield* fs.exists(activePath))) {
1468 + const exists =
1469 + (yield* fs.exists(managedDirectory)) || (yield* isSymlink(managedDirectory));
1470 + yield* SubscriptionRef.update(state, (current) => ({
1471 + ...current,
1472 + canRemove: exists,
1473 + }));
1474 + return;
1475 + }
1476 + yield* ensureRealManagedRoot("activate");
1477 + const active = yield* readRecord(activePath, ActiveRelease);
1478 + const installed = yield* completedRelease(active.releaseId);
1479 + if (installed.managedVersionDirectory !== null) {
1480 + yield* lockReleaseDirectory(
1481 + installed.managedVersionDirectory,
1482 + installed.executablePath,
1483 + false,
1484 + );
1485 + }
1486 + yield* SubscriptionRef.update(state, (current) => ({
1487 ...current,
1015 - phase: "failed",
1016 - message: isInstallationError(cause)
1017 - ? cause.detail
1018 - : "The managed Antigravity runtime is incomplete. Remove it and reinstall.",
1019 - }) satisfies ProviderInstallState,
1488 + installedVersion: installed.version,
1489 + }));
1490 + }),
1491 ),
1492 + );
1493 + }).pipe(
1494 + Effect.catch((cause) =>
1495 + isLockContentionError(cause)
1496 + ? Effect.void
1497 + : SubscriptionRef.update(
1498 + state,
1499 + (current) =>
1500 + ({
1501 + ...current,
1502 + phase: "failed",
1503 + message: isInstallationError(cause)
1504 + ? cause.detail
1505 + : "The managed Antigravity runtime is incomplete. Remove it and reinstall.",
1506 + }) satisfies ProviderInstallState,
1507 + ),
1508 ),
1509 );
1510
apps/server/src/provider/AntigravityProvider.test.ts
+9
@@ -597,6 +597,15 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {
597 }),
598 installed: false,
599 },
600 + {
601 + error: new ProviderSetupError({
602 + instanceId,
603 + operation: "resolve",
604 + detail:
605 + "The managed Antigravity runtime changed on disk. Reinstall it in Antigravity setup.",
606 + }),
607 + installed: false,
608 + },
609 ];
610 for (const { error, installed } of failures) {
611 yield* harness.provider.onSessionStarted(started, "/workspace");
apps/server/src/provider/AntigravityProvider.ts
+1 -1
@@ -151,7 +151,7 @@ function isMissingInstallation(error: EffectAcpErrors.AcpError | ProviderSetupEr
151 return (
152 error._tag === "ProviderSetupError" &&
153 error.operation === "resolve" &&
154 - /not installed|missing|incomplete|does not publish/i.test(error.detail)
154 + /not installed|missing|incomplete|changed on disk|does not publish/i.test(error.detail)
155 );
156 }
157
apps/server/src/provider/antigravityAuthSupport.test.ts
+2
@@ -72,6 +72,7 @@ describe("Antigravity process environment", () => {
72 GEMINI_HOME: "/shared-gemini-home",
73 gemini_home: "/alias-shared-home",
74 AGY_ACP_FORCE_FILE_STORAGE: "0",
75 + agy_cli_disable_auto_update: "0",
76 BROWSER: "open-real-browser",
77 browser: "another-real-browser",
78 PYTHONUNBUFFERED: "0",
@@ -100,6 +101,7 @@ describe("Antigravity process environment", () => {
101 CUSTOM_SETTING: "keep-this",
102 GEMINI_HOME: profile.geminiHome,
103 AGY_ACP_FORCE_FILE_STORAGE: "1",
104 + AGY_CLI_DISABLE_AUTO_UPDATE: "1",
105 BROWSER: profile.browserCommand,
106 PYTHONUNBUFFERED: "1",
107 ELECTRON_RUN_AS_NODE: "1",
apps/server/src/provider/antigravityAuthSupport.ts
+2
@@ -72,6 +72,7 @@ const removedEnvironmentKeys = new Set([
72 "AGY_ACP_ENABLE_OAUTH",
73 "GEMINI_HOME",
74 "AGY_ACP_FORCE_FILE_STORAGE",
75 + "AGY_CLI_DISABLE_AUTO_UPDATE",
76 "BROWSER",
77 "PYTHONUNBUFFERED",
78 "ELECTRON_RUN_AS_NODE",
@@ -227,6 +228,7 @@ function antigravityEnvironment(
228 : {}),
229 GEMINI_HOME: profile.geminiHome,
230 AGY_ACP_FORCE_FILE_STORAGE: "1",
231 + AGY_CLI_DISABLE_AUTO_UPDATE: "1",
232 BROWSER: profile.browserCommand,
233 PYTHONUNBUFFERED: "1",
234 ELECTRON_RUN_AS_NODE: "1",