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 HostProcessIsExecutable,
12 HostProcessPlatform,
13} from "@t3tools/shared/hostProcess";
14import * as Effect from "effect/Effect";
15import * as Deferred from "effect/Deferred";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Path from "effect/Path";
20import * as Schema from "effect/Schema";
21import * as TestClock from "effect/testing/TestClock";
22import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
23
24import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
25import { ServerConfig } from "../../config.ts";
26import { ServerSettingsService } from "../../serverSettings.ts";
27import {
28 AntigravityInstallation,
29 AntigravityInstallationError,
30 type AntigravityExecutable,
31} from "../AntigravityInstallation.ts";
32import {
33 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
34 resolveAntigravityInstanceDirectories,
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 directories = yield* resolveAntigravityInstanceDirectories(config.stateDir, instanceId);
77 const profileDirectory = directories.profile;
78 const instancePath = `${path.join(root, "instance-bin")}:${baseEnv.PATH ?? ""}`;
79
80 const makeExecutable = Effect.fn("AntigravityDriverTest.makeExecutable")(function* (
81 name: string,
82 loginRequired = false,
83 ) {
84 const directory = path.join(root, name);
85 const executablePath = path.join(directory, "agy_acp_server.par");
86 const harnessPath = path.join(directory, "localharness_external");
87 yield* fs.makeDirectory(directory, { recursive: true });
88 const authorizationUrl =
89 "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";
90 yield* fs.writeFileString(
91 executablePath,
92 [
93 "#!/bin/sh",
94 ...(loginRequired
95 ? [`printf '%s\\n' ${shellQuote(ANTIGRAVITY_AUTH_STDOUT_PREFIX + authorizationUrl)}`]
96 : []),
97 `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`,
98 "",
99 ].join("\n"),
100 );
101 yield* fs.writeFileString(harnessPath, "#!/bin/sh\nexit 99\n");
102 yield* fs.chmod(executablePath, 0o755);
103 yield* fs.chmod(harnessPath, 0o755);
104 return {
105 executablePath,
106 harnessPath,
107 source: "managed",
108 version: name,
109 managedVersionDirectory: directory,
110 } satisfies AntigravityExecutable;
111 });
112
113 const first = yield* makeExecutable("runtime 'one");
114 const second = yield* makeExecutable("runtime two");
115 const signedOut = yield* makeExecutable("runtime signed-out", true);
116 const controls = { selected: first, failResolution: false, beforeAcquire: Effect.void };
117 const acquisitions: Array<{ binaryPath: string | undefined; path: string | undefined }> = [];
118 const releases: Array<string | null> = [];
119 const launches: Array<{
120 command: string;
121 args: ReadonlyArray<string>;
122 cwd: string | undefined;
123 extendEnv: boolean | undefined;
124 profileDirectory: string | undefined;
125 harnessPath: string | undefined;
126 forceFileStorage: string | undefined;
127 credentialKeys: ReadonlyArray<string>;
128 geminiApiKey: string | undefined;
129 tempDirectory: string | undefined;
130 handle: ChildProcessSpawner.ChildProcessHandle;
131 }> = [];
132
133 const installation = Layer.mock(AntigravityInstallation)({
134 managedDirectory: root,
135 resolve: () =>
136 Effect.gen(function* () {
137 if (controls.failResolution) {
138 return yield* new AntigravityInstallationError({
139 operation: "resolve",
140 detail: "Fixture resolution failed.",
141 });
142 }
143 return controls.selected;
144 }),
145 acquire: (binaryPath, environment) =>
146 Effect.gen(function* () {
147 acquisitions.push({ binaryPath, path: environment?.PATH });
148 yield* controls.beforeAcquire;
149 if (controls.failResolution) {
150 return yield* new AntigravityInstallationError({
151 operation: "resolve",
152 detail: "Fixture resolution failed.",
153 });
154 }
155 const selected = controls.selected;
156 yield* Effect.addFinalizer(() =>
157 Effect.sync(() => {
158 releases.push(selected.version);
159 }),
160 );
161 return selected;
162 }),
163 });
164 const observedSpawner = ChildProcessSpawner.make((command) =>
165 Effect.gen(function* () {
166 if (command._tag !== "StandardCommand")
167 return yield* Effect.die("Unexpected process pipeline.");
168 const handle = yield* spawner.spawn(command);
169 const environment = command.options.env ?? {};
170 launches.push({
171 command: command.command,
172 args: command.args,
173 cwd: command.options.cwd,
174 extendEnv: command.options.extendEnv,
175 profileDirectory: environment.GEMINI_HOME,
176 harnessPath: environment.ANTIGRAVITY_HARNESS_PATH,
177 forceFileStorage: environment.AGY_ACP_FORCE_FILE_STORAGE,
178 credentialKeys: Object.keys(environment).filter((key) =>
179 blockedCredentialKeys.has(key.toUpperCase()),
180 ),
181 geminiApiKey: environment.GEMINI_API_KEY,
182 // Only the agent gets a per-process temp directory. Other launches
183 // inherit the host TMPDIR.
184 tempDirectory:
185 environment.ANTIGRAVITY_HARNESS_PATH === undefined ? undefined : environment.TMPDIR,
186 handle,
187 });
188 return handle;
189 }),
190 );
191 const instance = yield* AntigravityDriver.create({
192 instanceId,
193 displayName: "Google test account",
194 enabled: options.enabled ?? false,
195 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
196 environment: [
197 { name: "PATH", value: instancePath },
198 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
199 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
200 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
201 { name: "google_api_key", value: "must-not-be-used" },
202 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
203 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
204 { name: "GEMINI_HOME", value: "/must-not-be-used" },
205 { name: "ANTIGRAVITY_HARNESS_PATH", value: "/must-not-be-used" },
206 { name: "BROWSER", value: "must-not-run" },
207 ].map((variable) => ({ ...variable, sensitive: false })),
208 }).pipe(
209 Effect.provide(installation),
210 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
211 );
212 const refresh = instance.refreshModels;
213 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
214 const readRequests = Effect.gen(function* () {
215 if (!(yield* fs.exists(requestLog))) return [];
216 const text = yield* fs.readFileString(requestLog);
217 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
218 decodeRequest(line),
219 );
220 });
221 const assertClosed = Effect.gen(function* () {
222 for (const launch of launches) {
223 // Cancelled startup can report a signal instead of a numeric exit code.
224 yield* launch.handle.exitCode.pipe(Effect.ignore);
225 expect(yield* launch.handle.isRunning).toBe(false);
226 if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
227 if (launch.tempDirectory) expect(yield* fs.exists(launch.tempDirectory)).toBe(false);
228 }
229 });
230 return {
231 instance,
232 refresh,
233 fs,
234 path,
235 profileDirectory,
236 directories,
237 instancePath,
238 first,
239 second,
240 signedOut,
241 controls,
242 acquisitions,
243 releases,
244 launches,
245 readRequests,
246 assertClosed,
247 };
248});
249
250const testLayer = ServerConfig.layerTest(process.cwd(), {
251 prefix: "t3-antigravity-driver-config-",
252}).pipe(
253 Layer.provideMerge(NodeServices.layer),
254 Layer.provideMerge(ServerSettingsService.layerTest()),
255 Layer.provideMerge(
256 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
257 shouldRunScopeWork: () => Effect.succeed(false),
258 }),
259 ),
260 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
261 Layer.provideMerge(ModelManifest.layerTest),
262);
263
264it.layer(testLayer)("AntigravityDriver", (it) => {
265 it.effect.skipIf(windowsHost)(
266 "preserves the Node install message when starting a standalone provider",
267 () =>
268 Effect.gen(function* () {
269 const h = yield* makeHarness();
270 const error = yield* h.refresh().pipe(Effect.flip);
271 expect(error.detail).toContain("Install Node.js");
272 expect(h.launches).toEqual([]);
273 }).pipe(
274 Effect.scoped,
275 Effect.provideService(HostProcessIsExecutable, true),
276 Effect.provideService(HostProcessEnvironment, { PATH: "" }),
277 ),
278 );
279
280 it.effect.skipIf(windowsHost)("does not launch a process for a disabled instance", () =>
281 Effect.gen(function* () {
282 const h = yield* makeHarness();
283 const snapshot = yield* h.instance.snapshot.refresh;
284 expect(snapshot.status).toBe("disabled");
285 expect(h.acquisitions).toEqual([]);
286 expect(h.launches).toEqual([]);
287 expect(yield* h.fs.exists(h.profileDirectory)).toBe(false);
288 }).pipe(Effect.scoped),
289 );
290
291 it.effect.skipIf(windowsHost)("refreshes models after slow process startup", () =>
292 Effect.gen(function* () {
293 const h = yield* makeHarness();
294 const entered = yield* Deferred.make<void>();
295 const ready = yield* Deferred.make<void>();
296 h.controls.beforeAcquire = Deferred.succeed(entered, undefined).pipe(
297 Effect.andThen(Deferred.await(ready)),
298 );
299 const refresh = yield* h.refresh().pipe(Effect.forkScoped);
300 yield* Deferred.await(entered);
301 yield* TestClock.adjust("70 seconds");
302 yield* Deferred.succeed(ready, undefined);
303 yield* Fiber.join(refresh);
304 const snapshot = yield* h.instance.snapshot.getSnapshot;
305 expect(snapshot.auth.status).toBe("authenticated");
306 expect(snapshot.models.length).toBeGreaterThan(0);
307 yield* h.assertClosed;
308 }).pipe(Effect.scoped),
309 );
310
311 it.effect.skipIf(windowsHost)(
312 "refreshes a disabled instance through the selected executable and personal Google ACP",
313 () =>
314 Effect.gen(function* () {
315 const h = yield* makeHarness();
316 yield* h.refresh();
317 const snapshot = yield* h.instance.snapshot.getSnapshot;
318 expect(snapshot.status).toBe("disabled");
319 expect(snapshot.auth.status).toBe("authenticated");
320 expect(snapshot.models.map((model) => model.slug)).toEqual([
321 "gemini-test-low",
322 "gemini-test-high",
323 ]);
324 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
325 // The mock catalog is not in the manifest's current list, so it folds
326 // under the legacy section like an old Codex model would.
327 expect(snapshot.models.every((model) => model.isLegacy === true)).toBe(true);
328 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
329 expect(snapshot.supportsTextGeneration).toBe(true);
330 h.controls.selected = h.second;
331 yield* h.refresh();
332
333 expect(h.acquisitions).toEqual([
334 { binaryPath: "", path: h.instancePath },
335 { binaryPath: "", path: h.instancePath },
336 ]);
337 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
338 expect(nativeLaunches.map((launch) => launch.command)).toEqual([
339 h.first.executablePath,
340 h.second.executablePath,
341 ]);
342 expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
343 h.first.harnessPath,
344 h.second.harnessPath,
345 ]);
346 for (const launch of nativeLaunches) {
347 expect(launch.args).toEqual(hostPlatform === "linux" ? ["--uid="] : []);
348 expect(launch.profileDirectory).toBe(h.profileDirectory);
349 expect(launch.forceFileStorage).toBe("1");
350 expect(launch.extendEnv).toBe(false);
351 }
352 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
353 expect(h.releases).toEqual([h.first.version, h.second.version]);
354 const requests = yield* h.readRequests;
355 expect(requests.map((request) => request.method)).toEqual([
356 "initialize",
357 "authenticate",
358 "session/new",
359 "initialize",
360 "authenticate",
361 "session/new",
362 ]);
363 expect(
364 requests
365 .filter((request) => request.method === "authenticate")
366 .map((request) => request.params?.methodId),
367 ).toEqual(["oauth-personal", "oauth-personal"]);
368 expect(
369 requests
370 .filter((request) => request.method === "session/new")
371 .map((request) => request.params?.mcpServers),
372 ).toEqual([[], []]);
373 yield* h.assertClosed;
374 }).pipe(Effect.scoped),
375 );
376
377 it.effect.skipIf(windowsHost)(
378 "authenticates with the configured API key method and labels the account by method",
379 () =>
380 Effect.gen(function* () {
381 const h = yield* makeHarness({
382 config: { authMethod: "gemini-api-key", apiKey: "fixture-gemini-key" },
383 });
384 yield* h.refresh();
385 const snapshot = yield* h.instance.snapshot.getSnapshot;
386 expect(snapshot.auth).toMatchObject({
387 status: "authenticated",
388 type: "gemini-api-key",
389 label: "Gemini API key",
390 });
391 expect(snapshot.models.length).toBeGreaterThan(0);
392 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
393 expect(nativeLaunches.map((launch) => launch.geminiApiKey)).toEqual(["fixture-gemini-key"]);
394 const requests = yield* h.readRequests;
395 expect(
396 requests
397 .filter((request) => request.method === "authenticate")
398 .map((request) => request.params?.methodId),
399 ).toEqual(["gemini-api-key"]);
400 yield* h.assertClosed;
401 }).pipe(Effect.scoped),
402 );
403
404 it.effect.skipIf(windowsHost)("reports the missing credential before launching a process", () =>
405 Effect.gen(function* () {
406 const h = yield* makeHarness({ config: { authMethod: "gemini-api-key" } });
407 const error = yield* h.refresh().pipe(Effect.flip);
408 expect(error.detail).toContain("API key");
409 expect(h.launches.filter((launch) => launch.harnessPath !== undefined)).toEqual([]);
410 }).pipe(Effect.scoped),
411 );
412
413 it.effect.skipIf(windowsHost)(
414 "closes refresh processes and clears account metadata when Google sign-in is required",
415 () =>
416 Effect.gen(function* () {
417 const h = yield* makeHarness();
418 yield* h.refresh();
419 h.controls.selected = h.signedOut;
420 const error = yield* h.refresh().pipe(Effect.flip);
421 expect(error.detail).toContain("Sign in to Antigravity");
422 const snapshot = yield* h.instance.snapshot.getSnapshot;
423 expect(snapshot.auth.status).toBe("unauthenticated");
424 expect(snapshot.models).toEqual([]);
425 expect(snapshot.slashCommands).toEqual([]);
426 expect(snapshot.supportsTextGeneration).toBe(false);
427 expect(h.acquisitions).toHaveLength(2);
428 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
429 yield* h.assertClosed;
430 }).pipe(Effect.scoped),
431 );
432
433 it.effect.skipIf(windowsHost)(
434 "clears account metadata when a text helper needs Google sign-in",
435 () =>
436 Effect.gen(function* () {
437 const h = yield* makeHarness();
438 yield* h.refresh();
439 h.controls.selected = h.signedOut;
440 const error = yield* h.instance.textGeneration
441 .generateThreadTitle({
442 cwd: h.profileDirectory,
443 message: "Repair Google login",
444 modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
445 })
446 .pipe(Effect.flip);
447 expect(error._tag).toBe("TextGenerationError");
448 const snapshot = yield* h.instance.snapshot.getSnapshot;
449 expect(snapshot.auth.status).toBe("unauthenticated");
450 expect(snapshot.models).toEqual([]);
451 expect(snapshot.supportsTextGeneration).toBe(false);
452 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
453 yield* h.assertClosed;
454 }).pipe(Effect.scoped),
455 );
456
457 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
458 Effect.gen(function* () {
459 const h = yield* makeHarness();
460 yield* h.refresh();
461 const before = yield* h.instance.snapshot.getSnapshot;
462 h.controls.failResolution = true;
463 const error = yield* h.refresh().pipe(Effect.flip);
464 expect(error.detail).toContain("previous model list is unchanged");
465 const after = yield* h.instance.snapshot.getSnapshot;
466 expect(after.models).toEqual(before.models);
467 expect(after.auth).toEqual(before.auth);
468 expect(h.acquisitions).toHaveLength(2);
469 expect(h.releases).toEqual([h.first.version]);
470 yield* h.assertClosed;
471 }).pipe(Effect.scoped),
472 );
473
474 it.effect.skipIf(windowsHost)(
475 "gives each process its own temp directory and removes it when the process closes",
476 () =>
477 Effect.gen(function* () {
478 const h = yield* makeHarness();
479 const tempRoot = h.directories.runtimeTemp;
480 yield* h.refresh();
481 yield* h.refresh();
482 const directories = h.launches.flatMap((launch) =>
483 launch.tempDirectory === undefined ? [] : [launch.tempDirectory],
484 );
485 expect(directories).toHaveLength(2);
486 for (const directory of directories) {
487 expect(h.path.dirname(directory)).toBe(tempRoot);
488 }
489 expect(new Set(directories).size).toBe(2);
490 yield* h.assertClosed;
491 }).pipe(Effect.scoped),
492 );
493
494 it.effect.skipIf(windowsHost)(
495 "removes runtime temp directories left by a previous server on create",
496 () =>
497 Effect.gen(function* () {
498 const fs = yield* FileSystem.FileSystem;
499 const path = yield* Path.Path;
500 const config = yield* ServerConfig;
501 const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
502 const directories = yield* resolveAntigravityInstanceDirectories(
503 config.stateDir,
504 instanceId,
505 );
506 // Older builds unpacked inside the profile.
507 const legacyRoot = path.join(directories.profile, "antigravity-acp", "tmp");
508 for (const root of [directories.runtimeTemp, legacyRoot]) {
509 const orphan = path.join(root, "run-orphan", "_MEI123", "google3");
510 yield* fs.makeDirectory(orphan, { recursive: true });
511 yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
512 }
513 yield* AntigravityDriver.create({
514 instanceId,
515 displayName: "Sweep",
516 enabled: false,
517 config: AntigravityDriver.defaultConfig(),
518 environment: [],
519 }).pipe(
520 Effect.provide(
521 Layer.mock(AntigravityInstallation)({
522 managedDirectory: config.stateDir,
523 resolve: () => Effect.die("unused"),
524 acquire: () => Effect.die("unused"),
525 }),
526 ),
527 );
528 expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
529 expect(yield* fs.exists(legacyRoot)).toBe(false);
530 }).pipe(Effect.scoped),
531 );
532
533 it.effect("probes through installation resolution without launching a process", () =>
534 Effect.gen(function* () {
535 const h = yield* makeHarness({ enabled: true });
536 const snapshot = yield* h.instance.snapshot.refresh;
537 expect(snapshot.installed).toBe(true);
538 expect(snapshot.version).toBe(h.first.version);
539 expect(h.launches).toEqual([]);
540 expect(h.acquisitions).toEqual([]);
541 }).pipe(Effect.scoped),
542 );
543});