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 { layer as idAllocatorLayer } from "../../orchestration-v2/IdAllocator.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> } = {},
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 handle: ChildProcessSpawner.ChildProcessHandle;
129 }> = [];
130
131 const installation = Layer.mock(AntigravityInstallation)({
132 managedDirectory: root,
133 acquire: (binaryPath, environment) =>
134 Effect.gen(function* () {
135 acquisitions.push({ binaryPath, path: environment?.PATH });
136 yield* controls.beforeAcquire;
137 if (controls.failResolution) {
138 return yield* new AntigravityInstallationError({
139 operation: "resolve",
140 detail: "Fixture resolution failed.",
141 });
142 }
143 const selected = controls.selected;
144 yield* Effect.addFinalizer(() =>
145 Effect.sync(() => {
146 releases.push(selected.version);
147 }),
148 );
149 return selected;
150 }),
151 });
152 const observedSpawner = ChildProcessSpawner.make((command) =>
153 Effect.gen(function* () {
154 if (command._tag !== "StandardCommand")
155 return yield* Effect.die("Unexpected process pipeline.");
156 const handle = yield* spawner.spawn(command);
157 const environment = command.options.env ?? {};
158 launches.push({
159 command: command.command,
160 args: command.args,
161 cwd: command.options.cwd,
162 extendEnv: command.options.extendEnv,
163 profileDirectory: environment.GEMINI_HOME,
164 harnessPath: environment.ANTIGRAVITY_HARNESS_PATH,
165 forceFileStorage: environment.AGY_ACP_FORCE_FILE_STORAGE,
166 credentialKeys: Object.keys(environment).filter((key) =>
167 blockedCredentialKeys.has(key.toUpperCase()),
168 ),
169 geminiApiKey: environment.GEMINI_API_KEY,
170 handle,
171 });
172 return handle;
173 }),
174 );
175 const instance = yield* AntigravityDriver.create({
176 instanceId,
177 displayName: "Google test account",
178 enabled: false,
179 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
180 environment: [
181 { name: "PATH", value: instancePath },
182 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
183 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
184 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
185 { name: "google_api_key", value: "must-not-be-used" },
186 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
187 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
188 { name: "GEMINI_HOME", value: "/must-not-be-used" },
189 { name: "ANTIGRAVITY_HARNESS_PATH", value: "/must-not-be-used" },
190 { name: "BROWSER", value: "must-not-run" },
191 ].map((variable) => ({ ...variable, sensitive: false })),
192 }).pipe(
193 Effect.provide(installation),
194 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
195 );
196 const refresh = instance.refreshModels;
197 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
198 const readRequests = Effect.gen(function* () {
199 if (!(yield* fs.exists(requestLog))) return [];
200 const text = yield* fs.readFileString(requestLog);
201 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
202 decodeRequest(line),
203 );
204 });
205 const assertClosed = Effect.gen(function* () {
206 for (const launch of launches) {
207 // Cancelled startup can report a signal instead of a numeric exit code.
208 yield* launch.handle.exitCode.pipe(Effect.ignore);
209 expect(yield* launch.handle.isRunning).toBe(false);
210 if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
211 }
212 });
213 return {
214 instance,
215 refresh,
216 fs,
217 profileDirectory,
218 instancePath,
219 first,
220 second,
221 signedOut,
222 controls,
223 acquisitions,
224 releases,
225 launches,
226 readRequests,
227 assertClosed,
228 };
229});
230
231const testLayer = ServerConfig.layerTest(process.cwd(), {
232 prefix: "t3-antigravity-driver-config-",
233}).pipe(
234 Layer.provideMerge(NodeServices.layer),
235 Layer.provideMerge(ServerSettingsService.layerTest()),
236 Layer.provideMerge(
237 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
238 shouldRunScopeWork: () => Effect.succeed(false),
239 }),
240 ),
241 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
242 Layer.provideMerge(ModelManifest.layerTest),
243 Layer.provideMerge(idAllocatorLayer),
244);
245
246it.layer(testLayer)("AntigravityDriver", (it) => {
247 it.effect.skipIf(windowsHost)("does not launch a process for a disabled instance", () =>
248 Effect.gen(function* () {
249 const h = yield* makeHarness();
250 const snapshot = yield* h.instance.snapshot.refresh;
251 expect(snapshot.status).toBe("disabled");
252 expect(h.acquisitions).toEqual([]);
253 expect(h.launches).toEqual([]);
254 expect(yield* h.fs.exists(h.profileDirectory)).toBe(false);
255 }).pipe(Effect.scoped),
256 );
257
258 it.effect.skipIf(windowsHost)("refreshes models after slow process startup", () =>
259 Effect.gen(function* () {
260 const h = yield* makeHarness();
261 const entered = yield* Deferred.make<void>();
262 const ready = yield* Deferred.make<void>();
263 h.controls.beforeAcquire = Deferred.succeed(entered, undefined).pipe(
264 Effect.andThen(Deferred.await(ready)),
265 );
266 const refresh = yield* h.refresh().pipe(Effect.forkScoped);
267 yield* Deferred.await(entered);
268 yield* TestClock.adjust("70 seconds");
269 yield* Deferred.succeed(ready, undefined);
270 yield* Fiber.join(refresh);
271 const snapshot = yield* h.instance.snapshot.getSnapshot;
272 expect(snapshot.auth.status).toBe("authenticated");
273 expect(snapshot.models.length).toBeGreaterThan(0);
274 yield* h.assertClosed;
275 }).pipe(Effect.scoped),
276 );
277
278 it.effect.skipIf(windowsHost)(
279 "refreshes a disabled instance through the selected executable and personal Google ACP",
280 () =>
281 Effect.gen(function* () {
282 const h = yield* makeHarness();
283 yield* h.refresh();
284 const snapshot = yield* h.instance.snapshot.getSnapshot;
285 expect(snapshot.status).toBe("disabled");
286 expect(snapshot.auth.status).toBe("authenticated");
287 expect(snapshot.models.map((model) => model.slug)).toEqual([
288 "gemini-test-low",
289 "gemini-test-high",
290 ]);
291 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
292 // The mock catalog is not in the manifest's current list, so it folds
293 // under the legacy section like an old Codex model would.
294 expect(snapshot.models.every((model) => model.isLegacy === true)).toBe(true);
295 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
296 expect(snapshot.supportsTextGeneration).toBe(true);
297 h.controls.selected = h.second;
298 yield* h.refresh();
299
300 expect(h.acquisitions).toEqual([
301 { binaryPath: "", path: h.instancePath },
302 { binaryPath: "", path: h.instancePath },
303 ]);
304 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
305 expect(nativeLaunches.map((launch) => launch.command)).toEqual([
306 h.first.executablePath,
307 h.second.executablePath,
308 ]);
309 expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
310 h.first.harnessPath,
311 h.second.harnessPath,
312 ]);
313 for (const launch of nativeLaunches) {
314 expect(launch.args).toEqual(hostPlatform === "linux" ? ["--uid="] : []);
315 expect(launch.profileDirectory).toBe(h.profileDirectory);
316 expect(launch.forceFileStorage).toBe("1");
317 expect(launch.extendEnv).toBe(false);
318 }
319 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
320 expect(h.releases).toEqual([h.first.version, h.second.version]);
321 const requests = yield* h.readRequests;
322 expect(requests.map((request) => request.method)).toEqual([
323 "initialize",
324 "auth/login",
325 "session/new",
326 "initialize",
327 "auth/login",
328 "session/new",
329 ]);
330 expect(
331 requests
332 .filter((request) => request.method === "auth/login")
333 .map((request) => request.params?.methodId),
334 ).toEqual(["oauth-personal", "oauth-personal"]);
335 expect(
336 requests
337 .filter((request) => request.method === "session/new")
338 .map((request) => request.params?.mcpServers),
339 ).toEqual([[], []]);
340 yield* h.assertClosed;
341 }).pipe(Effect.scoped),
342 );
343
344 it.effect.skipIf(windowsHost)(
345 "authenticates with the configured API key method and labels the account by method",
346 () =>
347 Effect.gen(function* () {
348 const h = yield* makeHarness({
349 config: { authMethod: "gemini-api-key", apiKey: "fixture-gemini-key" },
350 });
351 yield* h.refresh();
352 const snapshot = yield* h.instance.snapshot.getSnapshot;
353 expect(snapshot.auth).toMatchObject({
354 status: "authenticated",
355 type: "gemini-api-key",
356 label: "Gemini API key",
357 });
358 expect(snapshot.models.length).toBeGreaterThan(0);
359 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
360 expect(nativeLaunches.map((launch) => launch.geminiApiKey)).toEqual(["fixture-gemini-key"]);
361 const requests = yield* h.readRequests;
362 expect(
363 requests
364 .filter((request) => request.method === "auth/login")
365 .map((request) => request.params?.methodId),
366 ).toEqual(["gemini-api-key"]);
367 yield* h.assertClosed;
368 }).pipe(Effect.scoped),
369 );
370
371 it.effect.skipIf(windowsHost)("reports the missing credential before launching a process", () =>
372 Effect.gen(function* () {
373 const h = yield* makeHarness({ config: { authMethod: "gemini-api-key" } });
374 const error = yield* h.refresh().pipe(Effect.flip);
375 expect(error.detail).toContain("API key");
376 expect(h.launches.filter((launch) => launch.harnessPath !== undefined)).toEqual([]);
377 }).pipe(Effect.scoped),
378 );
379
380 it.effect.skipIf(windowsHost)(
381 "closes refresh processes and clears account metadata when Google sign-in is required",
382 () =>
383 Effect.gen(function* () {
384 const h = yield* makeHarness();
385 yield* h.refresh();
386 h.controls.selected = h.signedOut;
387 const error = yield* h.refresh().pipe(Effect.flip);
388 expect(error.detail).toContain("Sign in to Antigravity");
389 const snapshot = yield* h.instance.snapshot.getSnapshot;
390 expect(snapshot.auth.status).toBe("unauthenticated");
391 expect(snapshot.models).toEqual([]);
392 expect(snapshot.slashCommands).toEqual([]);
393 expect(snapshot.supportsTextGeneration).toBe(false);
394 expect(h.acquisitions).toHaveLength(2);
395 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
396 yield* h.assertClosed;
397 }).pipe(Effect.scoped),
398 );
399
400 it.effect.skipIf(windowsHost)(
401 "clears account metadata when a text helper needs Google sign-in",
402 () =>
403 Effect.gen(function* () {
404 const h = yield* makeHarness();
405 yield* h.refresh();
406 h.controls.selected = h.signedOut;
407 const error = yield* h.instance.textGeneration
408 .generateThreadTitle({
409 cwd: h.profileDirectory,
410 message: "Repair Google login",
411 modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
412 })
413 .pipe(Effect.flip);
414 expect(error._tag).toBe("TextGenerationError");
415 const snapshot = yield* h.instance.snapshot.getSnapshot;
416 expect(snapshot.auth.status).toBe("unauthenticated");
417 expect(snapshot.models).toEqual([]);
418 expect(snapshot.supportsTextGeneration).toBe(false);
419 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
420 yield* h.assertClosed;
421 }).pipe(Effect.scoped),
422 );
423
424 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
425 Effect.gen(function* () {
426 const h = yield* makeHarness();
427 yield* h.refresh();
428 const before = yield* h.instance.snapshot.getSnapshot;
429 h.controls.failResolution = true;
430 const error = yield* h.refresh().pipe(Effect.flip);
431 expect(error.detail).toContain("previous model list is unchanged");
432 const after = yield* h.instance.snapshot.getSnapshot;
433 expect(after.models).toEqual(before.models);
434 expect(after.auth).toEqual(before.auth);
435 expect(h.acquisitions).toHaveLength(2);
436 expect(h.releases).toEqual([h.first.version]);
437 yield* h.assertClosed;
438 }).pipe(Effect.scoped),
439 );
440});