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