Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import {
4 ANTIGRAVITY_DEFAULT_MODEL,
5 ProviderInstanceId,
6 type AntigravitySettings,
7} from "@t3tools/contracts";
8import {
9 HostProcessEnvironment,
10 HostProcessExecutablePath,
11 HostProcessPlatform,
12} from "@t3tools/shared/hostProcess";
13import * as Effect from "effect/Effect";
14import * as Deferred from "effect/Deferred";
15import * as Fiber from "effect/Fiber";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Path from "effect/Path";
19import * as Schema from "effect/Schema";
20import * as TestClock from "effect/testing/TestClock";
21import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
22
23import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
24import { ServerConfig } from "../../config.ts";
25import { ServerSettingsService } from "../../serverSettings.ts";
26import {
27 AntigravityInstallation,
28 AntigravityInstallationError,
29 type AntigravityExecutable,
30} from "../AntigravityInstallation.ts";
31import {
32 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
33 resolveAntigravityProfileDirectory,
34 resolveAntigravityRuntimeTempDirectory,
35} from "../antigravityAuthSupport.ts";
36import { NoOpProviderEventLoggers, ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
37import * as ModelManifest from "../ModelManifest.ts";
38import { AntigravityDriver } from "./AntigravityDriver.ts";
39
40const hostPlatform = HostProcessPlatform.defaultValue();
41const windowsHost = hostPlatform === "win32";
42const decodeRequest = Schema.decodeEffect(
43 Schema.fromJsonString(
44 Schema.Struct({
45 method: Schema.optional(Schema.String),
46 params: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
47 }),
48 ),
49);
50const blockedCredentialKeys = new Set([
51 "GEMINI_API_KEY",
52 "GOOGLE_API_KEY",
53 "GOOGLE_APPLICATION_CREDENTIALS",
54 "GOOGLE_GENAI_USE_VERTEXAI",
55]);
56
57function shellQuote(value: string): string {
58 return `'${value.replaceAll("'", `'"'"'`)}'`;
59}
60
61const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
62 options: { readonly config?: Partial<AntigravitySettings>; readonly enabled?: boolean } = {},
63) {
64 const fs = yield* FileSystem.FileSystem;
65 const path = yield* Path.Path;
66 const config = yield* ServerConfig;
67 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
68 const nodePath = yield* HostProcessExecutablePath;
69 const baseEnv = yield* HostProcessEnvironment;
70 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-driver-" });
71 const instanceId = ProviderInstanceId.make(path.basename(root));
72 const mockAgentPath = yield* path.fromFileUrl(
73 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
74 );
75 const requestLog = path.join(root, "requests.jsonl");
76 const profileDirectory = resolveAntigravityProfileDirectory(config.stateDir, instanceId);
77 const instancePath = `${path.join(root, "instance-bin")}:${baseEnv.PATH ?? ""}`;
78
79 const makeExecutable = Effect.fn("AntigravityDriverTest.makeExecutable")(function* (
80 name: string,
81 loginRequired = false,
82 ) {
83 const directory = path.join(root, name);
84 const executablePath = path.join(directory, "agy_acp_server.par");
85 const harnessPath = path.join(directory, "localharness_external");
86 yield* fs.makeDirectory(directory, { recursive: true });
87 const authorizationUrl =
88 "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A51234%2F&state=fixture-state";
89 yield* fs.writeFileString(
90 executablePath,
91 [
92 "#!/bin/sh",
93 ...(loginRequired
94 ? [`printf '%s\\n' ${shellQuote(ANTIGRAVITY_AUTH_STDOUT_PREFIX + authorizationUrl)}`]
95 : []),
96 `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`,
97 "",
98 ].join("\n"),
99 );
100 yield* fs.writeFileString(harnessPath, "#!/bin/sh\nexit 99\n");
101 yield* fs.chmod(executablePath, 0o755);
102 yield* fs.chmod(harnessPath, 0o755);
103 return {
104 executablePath,
105 harnessPath,
106 source: "managed",
107 version: name,
108 managedVersionDirectory: directory,
109 } satisfies AntigravityExecutable;
110 });
111
112 const first = yield* makeExecutable("runtime 'one");
113 const second = yield* makeExecutable("runtime two");
114 const signedOut = yield* makeExecutable("runtime signed-out", true);
115 const controls = { selected: first, failResolution: false, beforeAcquire: Effect.void };
116 const acquisitions: Array<{ binaryPath: string | undefined; path: string | undefined }> = [];
117 const releases: Array<string | null> = [];
118 const launches: Array<{
119 command: string;
120 args: ReadonlyArray<string>;
121 cwd: string | undefined;
122 extendEnv: boolean | undefined;
123 profileDirectory: string | undefined;
124 harnessPath: string | undefined;
125 forceFileStorage: string | undefined;
126 credentialKeys: ReadonlyArray<string>;
127 geminiApiKey: string | undefined;
128 tempDirectory: string | undefined;
129 handle: ChildProcessSpawner.ChildProcessHandle;
130 }> = [];
131
132 const installation = Layer.mock(AntigravityInstallation)({
133 managedDirectory: root,
134 resolve: () =>
135 Effect.gen(function* () {
136 if (controls.failResolution) {
137 return yield* new AntigravityInstallationError({
138 operation: "resolve",
139 detail: "Fixture resolution failed.",
140 });
141 }
142 return controls.selected;
143 }),
144 acquire: (binaryPath, environment) =>
145 Effect.gen(function* () {
146 acquisitions.push({ binaryPath, path: environment?.PATH });
147 yield* controls.beforeAcquire;
148 if (controls.failResolution) {
149 return yield* new AntigravityInstallationError({
150 operation: "resolve",
151 detail: "Fixture resolution failed.",
152 });
153 }
154 const selected = controls.selected;
155 yield* Effect.addFinalizer(() =>
156 Effect.sync(() => {
157 releases.push(selected.version);
158 }),
159 );
160 return selected;
161 }),
162 });
163 const observedSpawner = ChildProcessSpawner.make((command) =>
164 Effect.gen(function* () {
165 if (command._tag !== "StandardCommand")
166 return yield* Effect.die("Unexpected process pipeline.");
167 const handle = yield* spawner.spawn(command);
168 const environment = command.options.env ?? {};
169 launches.push({
170 command: command.command,
171 args: command.args,
172 cwd: command.options.cwd,
173 extendEnv: command.options.extendEnv,
174 profileDirectory: environment.GEMINI_HOME,
175 harnessPath: environment.ANTIGRAVITY_HARNESS_PATH,
176 forceFileStorage: environment.AGY_ACP_FORCE_FILE_STORAGE,
177 credentialKeys: Object.keys(environment).filter((key) =>
178 blockedCredentialKeys.has(key.toUpperCase()),
179 ),
180 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,
185 handle,
186 });
187 return handle;
188 }),
189 );
190 const instance = yield* AntigravityDriver.create({
191 instanceId,
192 displayName: "Google test account",
193 enabled: options.enabled ?? false,
194 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
195 environment: [
196 { name: "PATH", value: instancePath },
197 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
198 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
199 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
200 { name: "google_api_key", value: "must-not-be-used" },
201 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
202 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
203 { name: "GEMINI_HOME", value: "/must-not-be-used" },
204 { name: "ANTIGRAVITY_HARNESS_PATH", value: "/must-not-be-used" },
205 { name: "BROWSER", value: "must-not-run" },
206 ].map((variable) => ({ ...variable, sensitive: false })),
207 }).pipe(
208 Effect.provide(installation),
209 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
210 );
211 const refresh = instance.refreshModels;
212 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
213 const readRequests = Effect.gen(function* () {
214 if (!(yield* fs.exists(requestLog))) return [];
215 const text = yield* fs.readFileString(requestLog);
216 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
217 decodeRequest(line),
218 );
219 });
220 const assertClosed = Effect.gen(function* () {
221 for (const launch of launches) {
222 // Cancelled startup can report a signal instead of a numeric exit code.
223 yield* launch.handle.exitCode.pipe(Effect.ignore);
224 expect(yield* launch.handle.isRunning).toBe(false);
225 if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
226 if (launch.tempDirectory) expect(yield* fs.exists(launch.tempDirectory)).toBe(false);
227 }
228 });
229 return {
230 instance,
231 refresh,
232 fs,
233 path,
234 profileDirectory,
235 instancePath,
236 first,
237 second,
238 signedOut,
239 controls,
240 acquisitions,
241 releases,
242 launches,
243 readRequests,
244 assertClosed,
245 };
246});
247
248const testLayer = ServerConfig.layerTest(process.cwd(), {
249 prefix: "t3-antigravity-driver-config-",
250}).pipe(
251 Layer.provideMerge(NodeServices.layer),
252 Layer.provideMerge(ServerSettingsService.layerTest()),
253 Layer.provideMerge(
254 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
255 shouldRunScopeWork: () => Effect.succeed(false),
256 }),
257 ),
258 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
259 Layer.provideMerge(ModelManifest.layerTest),
260);
261
262it.layer(testLayer)("AntigravityDriver", (it) => {
263 it.effect.skipIf(windowsHost)("does not launch a process for a disabled instance", () =>
264 Effect.gen(function* () {
265 const h = yield* makeHarness();
266 const snapshot = yield* h.instance.snapshot.refresh;
267 expect(snapshot.status).toBe("disabled");
268 expect(h.acquisitions).toEqual([]);
269 expect(h.launches).toEqual([]);
270 expect(yield* h.fs.exists(h.profileDirectory)).toBe(false);
271 }).pipe(Effect.scoped),
272 );
273
274 it.effect.skipIf(windowsHost)("refreshes models after slow process startup", () =>
275 Effect.gen(function* () {
276 const h = yield* makeHarness();
277 const entered = yield* Deferred.make<void>();
278 const ready = yield* Deferred.make<void>();
279 h.controls.beforeAcquire = Deferred.succeed(entered, undefined).pipe(
280 Effect.andThen(Deferred.await(ready)),
281 );
282 const refresh = yield* h.refresh().pipe(Effect.forkScoped);
283 yield* Deferred.await(entered);
284 yield* TestClock.adjust("70 seconds");
285 yield* Deferred.succeed(ready, undefined);
286 yield* Fiber.join(refresh);
287 const snapshot = yield* h.instance.snapshot.getSnapshot;
288 expect(snapshot.auth.status).toBe("authenticated");
289 expect(snapshot.models.length).toBeGreaterThan(0);
290 yield* h.assertClosed;
291 }).pipe(Effect.scoped),
292 );
293
294 it.effect.skipIf(windowsHost)(
295 "refreshes a disabled instance through the selected executable and personal Google ACP",
296 () =>
297 Effect.gen(function* () {
298 const h = yield* makeHarness();
299 yield* h.refresh();
300 const snapshot = yield* h.instance.snapshot.getSnapshot;
301 expect(snapshot.status).toBe("disabled");
302 expect(snapshot.auth.status).toBe("authenticated");
303 expect(snapshot.models.map((model) => model.slug)).toEqual([
304 "gemini-test-low",
305 "gemini-test-high",
306 ]);
307 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
308 // The mock catalog is not in the manifest's current list, so it folds
309 // under the legacy section like an old Codex model would.
310 expect(snapshot.models.every((model) => model.isLegacy === true)).toBe(true);
311 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
312 expect(snapshot.supportsTextGeneration).toBe(true);
313 h.controls.selected = h.second;
314 yield* h.refresh();
315
316 expect(h.acquisitions).toEqual([
317 { binaryPath: "", path: h.instancePath },
318 { binaryPath: "", path: h.instancePath },
319 ]);
320 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
321 expect(nativeLaunches.map((launch) => launch.command)).toEqual([
322 h.first.executablePath,
323 h.second.executablePath,
324 ]);
325 expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
326 h.first.harnessPath,
327 h.second.harnessPath,
328 ]);
329 for (const launch of nativeLaunches) {
330 expect(launch.args).toEqual(hostPlatform === "linux" ? ["--uid="] : []);
331 expect(launch.profileDirectory).toBe(h.profileDirectory);
332 expect(launch.forceFileStorage).toBe("1");
333 expect(launch.extendEnv).toBe(false);
334 }
335 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
336 expect(h.releases).toEqual([h.first.version, h.second.version]);
337 const requests = yield* h.readRequests;
338 expect(requests.map((request) => request.method)).toEqual([
339 "initialize",
340 "authenticate",
341 "session/new",
342 "initialize",
343 "authenticate",
344 "session/new",
345 ]);
346 expect(
347 requests
348 .filter((request) => request.method === "authenticate")
349 .map((request) => request.params?.methodId),
350 ).toEqual(["oauth-personal", "oauth-personal"]);
351 expect(
352 requests
353 .filter((request) => request.method === "session/new")
354 .map((request) => request.params?.mcpServers),
355 ).toEqual([[], []]);
356 yield* h.assertClosed;
357 }).pipe(Effect.scoped),
358 );
359
360 it.effect.skipIf(windowsHost)(
361 "authenticates with the configured API key method and labels the account by method",
362 () =>
363 Effect.gen(function* () {
364 const h = yield* makeHarness({
365 config: { authMethod: "gemini-api-key", apiKey: "fixture-gemini-key" },
366 });
367 yield* h.refresh();
368 const snapshot = yield* h.instance.snapshot.getSnapshot;
369 expect(snapshot.auth).toMatchObject({
370 status: "authenticated",
371 type: "gemini-api-key",
372 label: "Gemini API key",
373 });
374 expect(snapshot.models.length).toBeGreaterThan(0);
375 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
376 expect(nativeLaunches.map((launch) => launch.geminiApiKey)).toEqual(["fixture-gemini-key"]);
377 const requests = yield* h.readRequests;
378 expect(
379 requests
380 .filter((request) => request.method === "authenticate")
381 .map((request) => request.params?.methodId),
382 ).toEqual(["gemini-api-key"]);
383 yield* h.assertClosed;
384 }).pipe(Effect.scoped),
385 );
386
387 it.effect.skipIf(windowsHost)("reports the missing credential before launching a process", () =>
388 Effect.gen(function* () {
389 const h = yield* makeHarness({ config: { authMethod: "gemini-api-key" } });
390 const error = yield* h.refresh().pipe(Effect.flip);
391 expect(error.detail).toContain("API key");
392 expect(h.launches.filter((launch) => launch.harnessPath !== undefined)).toEqual([]);
393 }).pipe(Effect.scoped),
394 );
395
396 it.effect.skipIf(windowsHost)(
397 "closes refresh processes and clears account metadata when Google sign-in is required",
398 () =>
399 Effect.gen(function* () {
400 const h = yield* makeHarness();
401 yield* h.refresh();
402 h.controls.selected = h.signedOut;
403 const error = yield* h.refresh().pipe(Effect.flip);
404 expect(error.detail).toContain("Sign in to Antigravity");
405 const snapshot = yield* h.instance.snapshot.getSnapshot;
406 expect(snapshot.auth.status).toBe("unauthenticated");
407 expect(snapshot.models).toEqual([]);
408 expect(snapshot.slashCommands).toEqual([]);
409 expect(snapshot.supportsTextGeneration).toBe(false);
410 expect(h.acquisitions).toHaveLength(2);
411 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
412 yield* h.assertClosed;
413 }).pipe(Effect.scoped),
414 );
415
416 it.effect.skipIf(windowsHost)(
417 "clears account metadata when a text helper needs Google sign-in",
418 () =>
419 Effect.gen(function* () {
420 const h = yield* makeHarness();
421 yield* h.refresh();
422 h.controls.selected = h.signedOut;
423 const error = yield* h.instance.textGeneration
424 .generateThreadTitle({
425 cwd: h.profileDirectory,
426 message: "Repair Google login",
427 modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
428 })
429 .pipe(Effect.flip);
430 expect(error._tag).toBe("TextGenerationError");
431 const snapshot = yield* h.instance.snapshot.getSnapshot;
432 expect(snapshot.auth.status).toBe("unauthenticated");
433 expect(snapshot.models).toEqual([]);
434 expect(snapshot.supportsTextGeneration).toBe(false);
435 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
436 yield* h.assertClosed;
437 }).pipe(Effect.scoped),
438 );
439
440 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
441 Effect.gen(function* () {
442 const h = yield* makeHarness();
443 yield* h.refresh();
444 const before = yield* h.instance.snapshot.getSnapshot;
445 h.controls.failResolution = true;
446 const error = yield* h.refresh().pipe(Effect.flip);
447 expect(error.detail).toContain("previous model list is unchanged");
448 const after = yield* h.instance.snapshot.getSnapshot;
449 expect(after.models).toEqual(before.models);
450 expect(after.auth).toEqual(before.auth);
451 expect(h.acquisitions).toHaveLength(2);
452 expect(h.releases).toEqual([h.first.version]);
453 yield* h.assertClosed;
454 }).pipe(Effect.scoped),
455 );
456
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
510 it.effect("probes through installation resolution without launching a process", () =>
511 Effect.gen(function* () {
512 const h = yield* makeHarness({ enabled: true });
513 const snapshot = yield* h.instance.snapshot.refresh;
514 expect(snapshot.installed).toBe(true);
515 expect(snapshot.version).toBe(h.first.version);
516 expect(h.launches).toEqual([]);
517 expect(h.acquisitions).toEqual([]);
518 }).pipe(Effect.scoped),
519 );
520});