Skip to content

Commit 0b65021

Browse files
t3dotggclaude
andcommitted
fix(antigravity): keep runtime temp files inside the profile
Each ACP process now unpacks into its own directory under the profile temp root, set through TEMP and TMP on Windows and TMPDIR elsewhere. The directory is removed when the runtime scope closes, after the child is killed. The driver removes the whole temp root once on create, before any process of the instance exists. Drop the sweep of the system temp directory. Windows locks loaded executables but not data files, so removing another program's _MEI folder can gut a live extraction. Drop the per-session sweep of the shared temp folder for the same reason: closing one thread could delete files a sibling thread still reads. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 2ddecb0 commit 0b65021

5 files changed

Lines changed: 158 additions & 85 deletions

File tree

‎apps/server/src/provider/Drivers/AntigravityDriver.test.ts‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
import {
3232
ANTIGRAVITY_AUTH_STDOUT_PREFIX,
3333
resolveAntigravityProfileDirectory,
34+
resolveAntigravityRuntimeTempDirectory,
3435
} from "../antigravityAuthSupport.ts";
3536
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
3637
import * as ModelManifest from "../ModelManifest.ts";
@@ -124,12 +125,13 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
124125
forceFileStorage: string | undefined;
125126
credentialKeys: ReadonlyArray<string>;
126127
geminiApiKey: string | undefined;
128+
tempDirectory: string | undefined;
127129
handle: ChildProcessSpawner.ChildProcessHandle;
128130
}> = [];
129131

130132
const installation = Layer.mock(AntigravityInstallation)({
131133
managedDirectory: root,
132-
resolve: (binaryPath, environment) =>
134+
resolve: () =>
133135
Effect.gen(function* () {
134136
if (controls.failResolution) {
135137
return yield* new AntigravityInstallationError({
@@ -176,6 +178,10 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
176178
blockedCredentialKeys.has(key.toUpperCase()),
177179
),
178180
geminiApiKey: environment.GEMINI_API_KEY,
181+
// Only the agent gets a per-process temp directory. Other launches
182+
// inherit the host TMPDIR.
183+
tempDirectory:
184+
environment.ANTIGRAVITY_HARNESS_PATH === undefined ? undefined : environment.TMPDIR,
179185
handle,
180186
});
181187
return handle;
@@ -217,12 +223,14 @@ const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
217223
yield* launch.handle.exitCode.pipe(Effect.ignore);
218224
expect(yield* launch.handle.isRunning).toBe(false);
219225
if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
226+
if (launch.tempDirectory) expect(yield* fs.exists(launch.tempDirectory)).toBe(false);
220227
}
221228
});
222229
return {
223230
instance,
224231
refresh,
225232
fs,
233+
path,
226234
profileDirectory,
227235
instancePath,
228236
first,
@@ -446,6 +454,59 @@ it.layer(testLayer)("AntigravityDriver", (it) => {
446454
}).pipe(Effect.scoped),
447455
);
448456

457+
it.effect.skipIf(windowsHost)(
458+
"gives each process its own temp directory and removes it when the process closes",
459+
() =>
460+
Effect.gen(function* () {
461+
const h = yield* makeHarness();
462+
const tempRoot = resolveAntigravityRuntimeTempDirectory(h.profileDirectory);
463+
yield* h.refresh();
464+
yield* h.refresh();
465+
const directories = h.launches.flatMap((launch) =>
466+
launch.tempDirectory === undefined ? [] : [launch.tempDirectory],
467+
);
468+
expect(directories).toHaveLength(2);
469+
for (const directory of directories) {
470+
expect(h.path.dirname(directory)).toBe(tempRoot);
471+
}
472+
expect(new Set(directories).size).toBe(2);
473+
yield* h.assertClosed;
474+
}).pipe(Effect.scoped),
475+
);
476+
477+
it.effect.skipIf(windowsHost)(
478+
"removes runtime temp directories left by a previous server on create",
479+
() =>
480+
Effect.gen(function* () {
481+
const fs = yield* FileSystem.FileSystem;
482+
const path = yield* Path.Path;
483+
const config = yield* ServerConfig;
484+
const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
485+
const tempRoot = resolveAntigravityRuntimeTempDirectory(
486+
resolveAntigravityProfileDirectory(config.stateDir, instanceId),
487+
);
488+
const orphan = path.join(tempRoot, "run-orphan", "_MEI123", "google3");
489+
yield* fs.makeDirectory(orphan, { recursive: true });
490+
yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
491+
yield* AntigravityDriver.create({
492+
instanceId,
493+
displayName: "Sweep",
494+
enabled: false,
495+
config: AntigravityDriver.defaultConfig(),
496+
environment: [],
497+
}).pipe(
498+
Effect.provide(
499+
Layer.mock(AntigravityInstallation)({
500+
managedDirectory: config.stateDir,
501+
resolve: () => Effect.die("unused"),
502+
acquire: () => Effect.die("unused"),
503+
}),
504+
),
505+
);
506+
expect(yield* fs.exists(tempRoot)).toBe(false);
507+
}).pipe(Effect.scoped),
508+
);
509+
449510
it.effect("probes through installation resolution without launching a process", () =>
450511
Effect.gen(function* () {
451512
const h = yield* makeHarness({ enabled: true });

‎apps/server/src/provider/Drivers/AntigravityDriver.ts‎

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
isAntigravitySignInRequiredError,
3131
prepareAntigravityProfile,
3232
resolveAntigravityProfileDirectory,
33+
resolveAntigravityRuntimeTempDirectory,
3334
type AntigravityAuthConfig,
3435
} from "../antigravityAuthSupport.ts";
3536
import {
@@ -39,7 +40,7 @@ import {
3940
import type { AcpSessionRuntime, AcpSessionRuntimeStartResult } from "../acp/AcpSessionRuntime.ts";
4041
import type { ServerProviderDraft } from "../providerSnapshot.ts";
4142
import {
42-
cleanOrphanedAntigravityTempDirs,
43+
removeAntigravityRuntimeTempDirs,
4344
removeAntigravitySessionFiles,
4445
} from "../acp/AntigravitySessionFiles.ts";
4546
import { ProviderDriverError } from "../Errors.ts";
@@ -101,11 +102,11 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
101102
serverConfig.stateDir,
102103
instanceId,
103104
);
104-
yield* cleanOrphanedAntigravityTempDirs(profileDirectory).pipe(
105-
Effect.provideService(FileSystem.FileSystem, fileSystem),
106-
Effect.provideService(Path.Path, path),
107-
Effect.ignore,
108-
);
105+
// No process of this instance exists yet, so every runtime temp
106+
// directory left under the profile is an orphan from a killed server.
107+
yield* removeAntigravityRuntimeTempDirs(
108+
resolveAntigravityRuntimeTempDirectory(profileDirectory),
109+
).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));
109110
const continuationIdentity = defaultProviderContinuationIdentity({
110111
driverKind: DRIVER,
111112
instanceId,
@@ -163,6 +164,31 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
163164
Effect.provideService(Path.Path, path),
164165
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
165166
);
167+
// Each process unpacks into its own directory that dies with the
168+
// runtime scope, after the child is killed. A shared directory would
169+
// let one session's teardown delete files a sibling still reads.
170+
// Removal is best effort: a handle can outlive the kill on Windows,
171+
// and the sweep on the next driver start reclaims what is left.
172+
const runtimeTempDirectory = yield* Effect.acquireRelease(
173+
fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
174+
Effect.mapError(
175+
() =>
176+
new ProviderSetupError({
177+
instanceId,
178+
operation: "start",
179+
detail: "Could not create an Antigravity runtime temp directory.",
180+
}),
181+
),
182+
),
183+
(directory) =>
184+
fileSystem
185+
.remove(directory, { recursive: true, force: true })
186+
.pipe(
187+
Effect.catch(() =>
188+
Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
189+
),
190+
),
191+
);
166192
const runtime = yield* makeAntigravityAcpRuntime({
167193
...input,
168194
authMethod: auth.authMethod,
@@ -173,6 +199,7 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
173199
cwd: input.cwd,
174200
baseEnv: withAgentDeviceEnvironment(processEnvironment, input),
175201
auth,
202+
runtimeTempDirectory,
176203
}),
177204
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
178205
return {
@@ -266,11 +293,11 @@ export const AntigravityDriver: ProviderDriver<AntigravitySettings, AntigravityD
266293
// Kick the TTL-gated manifest refresh alongside the health check, as
267294
// Codex and Claude do. Without it an environment that only runs
268295
// Antigravity would keep classifying against a stale disk cache.
269-
// Antigravity's binary is a PyInstaller single-file bundle. Spawning it
270-
// extracts ~860 MB of files to a temporary directory on every run.
271-
// The health probe only needs to verify that the executable and harness
272-
// exist on disk and resolve the installed version; actual ACP sessions
273-
// and explicit model refreshes spawn the runtime when needed.
296+
// The probe must not spawn. The agent is a PyInstaller one-file bundle
297+
// that unpacks about 1 GB per launch, and the health check runs every
298+
// minute. Resolving the install on disk is enough to report installed
299+
// and version. The response below is synthetic: only agentInfo.version
300+
// is read from it. Sessions and manual refreshes still spawn.
274301
const probe = Effect.gen(function* () {
275302
yield* modelManifest.refreshInBackground;
276303
if (authConfigIssue !== null) {

‎apps/server/src/provider/acp/AntigravitySessionFiles.ts‎

Lines changed: 14 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -38,68 +38,24 @@ export const removeAntigravitySessionFiles = Effect.fn("removeAntigravitySession
3838
recursive: true,
3939
force: true,
4040
});
41-
42-
// Best-effort cleanup of any unlocked temporary unpack directories left by PyInstaller
43-
const tmpDirectory = path.join(acpDirectory, "tmp");
44-
if (yield* fs.exists(tmpDirectory)) {
45-
const entries = yield* fs.readDirectory(tmpDirectory).pipe(Effect.orElseSucceed(() => []));
46-
for (const entry of entries) {
47-
if (entry.startsWith("_MEI")) {
48-
yield* fs
49-
.remove(path.join(tmpDirectory, entry), { recursive: true, force: true })
50-
.pipe(Effect.ignore);
51-
}
52-
}
53-
}
5441
},
5542
Effect.catch(() => Effect.logWarning("Could not remove temporary Antigravity session files.")),
5643
);
5744

58-
/** Sweeps orphaned PyInstaller unpack directories from prior runs. */
59-
export const cleanOrphanedAntigravityTempDirs = Effect.fn("cleanOrphanedAntigravityTempDirs")(
60-
function* (profileDirectory?: string) {
45+
/**
46+
* Removes every per-process runtime temp directory under the profile. Call
47+
* once when the driver starts, before it launches any process, so a previous
48+
* server that was killed mid-session cannot leave unpacked runtimes behind.
49+
* Only the profile-owned directory is touched. The system temp directory
50+
* belongs to other programs and Windows does not lock data files, so sweeping
51+
* it could gut a live extraction.
52+
*/
53+
export const removeAntigravityRuntimeTempDirs = Effect.fn("removeAntigravityRuntimeTempDirs")(
54+
function* (tempDirectory: string) {
6155
const fs = yield* FileSystem.FileSystem;
62-
const path = yield* Path.Path;
63-
64-
// 1. Clean profile-isolated tmp directory if provided
65-
if (profileDirectory) {
66-
const acpTmp = path.join(profileDirectory, "antigravity-acp", "tmp");
67-
if (yield* fs.exists(acpTmp)) {
68-
const entries = yield* fs.readDirectory(acpTmp).pipe(Effect.orElseSucceed(() => []));
69-
for (const entry of entries) {
70-
if (entry.startsWith("_MEI")) {
71-
yield* fs
72-
.remove(path.join(acpTmp, entry), { recursive: true, force: true })
73-
.pipe(Effect.ignore);
74-
}
75-
}
76-
}
77-
}
78-
79-
// 2. Clean orphaned _MEI folders in system temp directory left by previous Antigravity probes on Windows
80-
// On Unix, concurrent processes can have their files deleted without file locking protection,
81-
// so system temp sweeping is restricted to Windows where active files are lock-protected.
82-
if (process.platform === "win32") {
83-
const systemTemp = process.env.TEMP || process.env.TMP;
84-
if (systemTemp && (yield* fs.exists(systemTemp))) {
85-
const entries = yield* fs.readDirectory(systemTemp).pipe(Effect.orElseSucceed(() => []));
86-
for (const entry of entries) {
87-
if (entry.startsWith("_MEI")) {
88-
const fullPath = path.join(systemTemp, entry);
89-
const hasGoogle3 = yield* fs
90-
.exists(path.join(fullPath, "google3"))
91-
.pipe(Effect.orElseSucceed(() => false));
92-
const hasGoogle =
93-
hasGoogle3 ||
94-
(yield* fs
95-
.exists(path.join(fullPath, "google"))
96-
.pipe(Effect.orElseSucceed(() => false)));
97-
if (hasGoogle) {
98-
yield* fs.remove(fullPath, { recursive: true, force: true }).pipe(Effect.ignore);
99-
}
100-
}
101-
}
102-
}
103-
}
56+
yield* fs.remove(tempDirectory, { recursive: true, force: true });
10457
},
58+
Effect.catch(() =>
59+
Effect.logWarning("Could not remove leftover Antigravity runtime temp files."),
60+
),
10561
);

‎apps/server/src/provider/antigravityAuthSupport.test.ts‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ describe("Antigravity process environment", () => {
5151
geminiHome: "/t3/userdata/providers/antigravity/profile",
5252
acpDirectory: "/t3/userdata/providers/antigravity/profile/antigravity-acp",
5353
tokenPath: "/t3/userdata/providers/antigravity/profile/antigravity-acp/acp_token.json",
54+
tempDirectory: "/t3/userdata/providers/antigravity/profile/antigravity-acp/tmp",
5455
browserCommand: "managed-browser-helper",
5556
};
5657

@@ -101,6 +102,7 @@ describe("Antigravity process environment", () => {
101102
BROWSER: profile.browserCommand,
102103
PYTHONUNBUFFERED: "1",
103104
ELECTRON_RUN_AS_NODE: "1",
105+
TMPDIR: profile.tempDirectory,
104106
},
105107
});
106108
});
@@ -193,21 +195,39 @@ describe("Antigravity process environment", () => {
193195
geminiHome: "C:\\state\\providers\\antigravity\\profile",
194196
acpDirectory: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp",
195197
tokenPath: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp\\acp_token.json",
198+
tempDirectory: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp\\tmp",
196199
browserCommand: "managed-browser-helper",
197200
};
198-
const spawn = buildAntigravityAcpSpawnInput({
201+
const input = {
199202
installation: {
200203
executablePath: "C:\\release\\agy_acp_server.exe",
201204
harnessPath: "C:\\release\\localharness_external.exe",
202205
},
203206
profile: windowsProfile,
204207
cwd: "C:\\project",
205208
baseEnv: { PATH: "C:\\Windows\\system32", TEMP: "C:\\Users\\user\\AppData\\Local\\Temp" },
209+
};
210+
const shared = buildAntigravityAcpSpawnInput(input);
211+
expect(shared.env?.TEMP).toBe(windowsProfile.tempDirectory);
212+
expect(shared.env?.TMP).toBe(windowsProfile.tempDirectory);
213+
const perRun = buildAntigravityAcpSpawnInput({
214+
...input,
215+
runtimeTempDirectory: `${windowsProfile.tempDirectory}\\run-1`,
206216
});
207-
expect(spawn.env?.TEMP).toBe(
208-
"C:\\state\\providers\\antigravity\\profile\\antigravity-acp\\tmp",
209-
);
210-
expect(spawn.env?.TMP).toBe("C:\\state\\providers\\antigravity\\profile\\antigravity-acp\\tmp");
217+
expect(perRun.env?.TEMP).toBe(`${windowsProfile.tempDirectory}\\run-1`);
218+
expect(perRun.env?.TMP).toBe(`${windowsProfile.tempDirectory}\\run-1`);
219+
});
220+
221+
it("isolates TMPDIR to the profile directory on POSIX hosts", () => {
222+
const spawn = buildAntigravityAcpSpawnInput({
223+
installation: { executablePath: "/release/acp", harnessPath: "/release/harness" },
224+
profile,
225+
cwd: "/project",
226+
baseEnv: { TMPDIR: "/tmp" },
227+
runtimeTempDirectory: `${profile.tempDirectory}/run-1`,
228+
});
229+
expect(spawn.env?.TMPDIR).toBe(`${profile.tempDirectory}/run-1`);
230+
expect(spawn.env?.TEMP).toBeUndefined();
211231
});
212232

213233
it("uses the registry launch arguments for each supported host platform", () => {

0 commit comments

Comments
 (0)