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