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