Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityDriver.test.ts

536 lines20.9 KB

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 { AntigravityDriver } from "./AntigravityDriver.ts";
40​
41const hostPlatform = HostProcessPlatform.defaultValue();
42const windowsHost = hostPlatform === "win32";
43const decodeRequest = Schema.decodeEffect(
44 Schema.fromJsonString(
45 Schema.Struct({
46 method: Schema.optional(Schema.String),
47 params: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
48 }),
49 ),
50);
51const blockedCredentialKeys = new Set([
52 "GEMINI_API_KEY",
53 "GOOGLE_API_KEY",
54 "GOOGLE_APPLICATION_CREDENTIALS",
55 "GOOGLE_GENAI_USE_VERTEXAI",
56]);
57​
58function shellQuote(value: string): string {
59 return `'${value.replaceAll("'", `'"'"'`)}'`;
61​
62const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
63 options: { readonly config?: Partial<AntigravitySettings>; readonly enabled?: boolean } = {},
64) {
65 const fs = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const config = yield* ServerConfig;
68 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
69 const nodePath = yield* HostProcessExecutablePath;
70 const baseEnv = yield* HostProcessEnvironment;
71 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-driver-" });
72 const instanceId = ProviderInstanceId.make(path.basename(root));
73 const mockAgentPath = yield* path.fromFileUrl(
74 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
75 );
76 const requestLog = path.join(root, "requests.jsonl");
77 const profileDirectory = resolveAntigravityProfileDirectory(config.stateDir, instanceId);
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 instancePath,
237 first,
238 second,
239 signedOut,
240 controls,
241 acquisitions,
242 releases,
243 launches,
244 readRequests,
245 assertClosed,
246 };
247});
248​
249const testLayer = ServerConfig.layerTest(process.cwd(), {
250 prefix: "t3-antigravity-driver-config-",
251}).pipe(
252 Layer.provideMerge(NodeServices.layer),
253 Layer.provideMerge(ServerSettingsService.layerTest()),
254 Layer.provideMerge(
255 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
256 shouldRunScopeWork: () => Effect.succeed(false),
257 }),
258 ),
259 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
260 Layer.provideMerge(ModelManifest.layerTest),
261);
262​
263it.layer(testLayer)("AntigravityDriver", (it) => {
264 it.effect.skipIf(windowsHost)(
265 "preserves the Node install message when starting a standalone provider",
266 () =>
267 Effect.gen(function* () {
268 const h = yield* makeHarness();
269 const error = yield* h.refresh().pipe(Effect.flip);
270 expect(error.detail).toContain("Install Node.js");
271 expect(h.launches).toEqual([]);
272 }).pipe(
273 Effect.scoped,
274 Effect.provideService(HostProcessIsExecutable, true),
275 Effect.provideService(HostProcessEnvironment, { PATH: "" }),
276 ),
277 );
278​
279 it.effect.skipIf(windowsHost)("does not launch a process for a disabled instance", () =>
280 Effect.gen(function* () {
281 const h = yield* makeHarness();
282 const snapshot = yield* h.instance.snapshot.refresh;
283 expect(snapshot.status).toBe("disabled");
284 expect(h.acquisitions).toEqual([]);
285 expect(h.launches).toEqual([]);
286 expect(yield* h.fs.exists(h.profileDirectory)).toBe(false);
287 }).pipe(Effect.scoped),
288 );
289​
290 it.effect.skipIf(windowsHost)("refreshes models after slow process startup", () =>
291 Effect.gen(function* () {
292 const h = yield* makeHarness();
293 const entered = yield* Deferred.make<void>();
294 const ready = yield* Deferred.make<void>();
295 h.controls.beforeAcquire = Deferred.succeed(entered, undefined).pipe(
296 Effect.andThen(Deferred.await(ready)),
297 );
298 const refresh = yield* h.refresh().pipe(Effect.forkScoped);
299 yield* Deferred.await(entered);
300 yield* TestClock.adjust("70 seconds");
301 yield* Deferred.succeed(ready, undefined);
302 yield* Fiber.join(refresh);
303 const snapshot = yield* h.instance.snapshot.getSnapshot;
304 expect(snapshot.auth.status).toBe("authenticated");
305 expect(snapshot.models.length).toBeGreaterThan(0);
306 yield* h.assertClosed;
307 }).pipe(Effect.scoped),
308 );
309​
310 it.effect.skipIf(windowsHost)(
311 "refreshes a disabled instance through the selected executable and personal Google ACP",
312 () =>
313 Effect.gen(function* () {
314 const h = yield* makeHarness();
315 yield* h.refresh();
316 const snapshot = yield* h.instance.snapshot.getSnapshot;
317 expect(snapshot.status).toBe("disabled");
318 expect(snapshot.auth.status).toBe("authenticated");
319 expect(snapshot.models.map((model) => model.slug)).toEqual([
320 "gemini-test-low",
321 "gemini-test-high",
322 ]);
323 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
324 // The mock catalog is not in the manifest's current list, so it folds
325 // under the legacy section like an old Codex model would.
326 expect(snapshot.models.every((model) => model.isLegacy === true)).toBe(true);
327 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
328 expect(snapshot.supportsTextGeneration).toBe(true);
329 h.controls.selected = h.second;
330 yield* h.refresh();
331​
332 expect(h.acquisitions).toEqual([
333 { binaryPath: "", path: h.instancePath },
334 { binaryPath: "", path: h.instancePath },
335 ]);
336 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
337 expect(nativeLaunches.map((launch) => launch.command)).toEqual([
338 h.first.executablePath,
339 h.second.executablePath,
340 ]);
341 expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
342 h.first.harnessPath,
343 h.second.harnessPath,
344 ]);
345 for (const launch of nativeLaunches) {
346 expect(launch.args).toEqual(hostPlatform === "linux" ? ["--uid="] : []);
347 expect(launch.profileDirectory).toBe(h.profileDirectory);
348 expect(launch.forceFileStorage).toBe("1");
349 expect(launch.extendEnv).toBe(false);
350 }
351 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
352 expect(h.releases).toEqual([h.first.version, h.second.version]);
353 const requests = yield* h.readRequests;
354 expect(requests.map((request) => request.method)).toEqual([
355 "initialize",
356 "authenticate",
357 "session/new",
358 "initialize",
359 "authenticate",
360 "session/new",
361 ]);
362 expect(
363 requests
364 .filter((request) => request.method === "authenticate")
365 .map((request) => request.params?.methodId),
366 ).toEqual(["oauth-personal", "oauth-personal"]);
367 expect(
368 requests
369 .filter((request) => request.method === "session/new")
370 .map((request) => request.params?.mcpServers),
371 ).toEqual([[], []]);
372 yield* h.assertClosed;
373 }).pipe(Effect.scoped),
374 );
375​
376 it.effect.skipIf(windowsHost)(
377 "authenticates with the configured API key method and labels the account by method",
378 () =>
379 Effect.gen(function* () {
380 const h = yield* makeHarness({
381 config: { authMethod: "gemini-api-key", apiKey: "fixture-gemini-key" },
382 });
383 yield* h.refresh();
384 const snapshot = yield* h.instance.snapshot.getSnapshot;
385 expect(snapshot.auth).toMatchObject({
386 status: "authenticated",
387 type: "gemini-api-key",
388 label: "Gemini API key",
389 });
390 expect(snapshot.models.length).toBeGreaterThan(0);
391 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
392 expect(nativeLaunches.map((launch) => launch.geminiApiKey)).toEqual(["fixture-gemini-key"]);
393 const requests = yield* h.readRequests;
394 expect(
395 requests
396 .filter((request) => request.method === "authenticate")
397 .map((request) => request.params?.methodId),
398 ).toEqual(["gemini-api-key"]);
399 yield* h.assertClosed;
400 }).pipe(Effect.scoped),
401 );
402​
403 it.effect.skipIf(windowsHost)("reports the missing credential before launching a process", () =>
404 Effect.gen(function* () {
405 const h = yield* makeHarness({ config: { authMethod: "gemini-api-key" } });
406 const error = yield* h.refresh().pipe(Effect.flip);
407 expect(error.detail).toContain("API key");
408 expect(h.launches.filter((launch) => launch.harnessPath !== undefined)).toEqual([]);
409 }).pipe(Effect.scoped),
410 );
411​
412 it.effect.skipIf(windowsHost)(
413 "closes refresh processes and clears account metadata when Google sign-in is required",
414 () =>
415 Effect.gen(function* () {
416 const h = yield* makeHarness();
417 yield* h.refresh();
418 h.controls.selected = h.signedOut;
419 const error = yield* h.refresh().pipe(Effect.flip);
420 expect(error.detail).toContain("Sign in to Antigravity");
421 const snapshot = yield* h.instance.snapshot.getSnapshot;
422 expect(snapshot.auth.status).toBe("unauthenticated");
423 expect(snapshot.models).toEqual([]);
424 expect(snapshot.slashCommands).toEqual([]);
425 expect(snapshot.supportsTextGeneration).toBe(false);
426 expect(h.acquisitions).toHaveLength(2);
427 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
428 yield* h.assertClosed;
429 }).pipe(Effect.scoped),
430 );
431​
432 it.effect.skipIf(windowsHost)(
433 "clears account metadata when a text helper needs Google sign-in",
434 () =>
435 Effect.gen(function* () {
436 const h = yield* makeHarness();
437 yield* h.refresh();
438 h.controls.selected = h.signedOut;
439 const error = yield* h.instance.textGeneration
440 .generateThreadTitle({
441 cwd: h.profileDirectory,
442 message: "Repair Google login",
443 modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
444 })
445 .pipe(Effect.flip);
446 expect(error._tag).toBe("TextGenerationError");
447 const snapshot = yield* h.instance.snapshot.getSnapshot;
448 expect(snapshot.auth.status).toBe("unauthenticated");
449 expect(snapshot.models).toEqual([]);
450 expect(snapshot.supportsTextGeneration).toBe(false);
451 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
452 yield* h.assertClosed;
453 }).pipe(Effect.scoped),
454 );
455​
456 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
457 Effect.gen(function* () {
458 const h = yield* makeHarness();
459 yield* h.refresh();
460 const before = yield* h.instance.snapshot.getSnapshot;
461 h.controls.failResolution = true;
462 const error = yield* h.refresh().pipe(Effect.flip);
463 expect(error.detail).toContain("previous model list is unchanged");
464 const after = yield* h.instance.snapshot.getSnapshot;
465 expect(after.models).toEqual(before.models);
466 expect(after.auth).toEqual(before.auth);
467 expect(h.acquisitions).toHaveLength(2);
468 expect(h.releases).toEqual([h.first.version]);
469 yield* h.assertClosed;
470 }).pipe(Effect.scoped),
471 );
472​
473 it.effect.skipIf(windowsHost)(
474 "gives each process its own temp directory and removes it when the process closes",
475 () =>
476 Effect.gen(function* () {
477 const h = yield* makeHarness();
478 const tempRoot = resolveAntigravityRuntimeTempDirectory(h.profileDirectory);
479 yield* h.refresh();
480 yield* h.refresh();
481 const directories = h.launches.flatMap((launch) =>
482 launch.tempDirectory === undefined ? [] : [launch.tempDirectory],
483 );
484 expect(directories).toHaveLength(2);
485 for (const directory of directories) {
486 expect(h.path.dirname(directory)).toBe(tempRoot);
487 }
488 expect(new Set(directories).size).toBe(2);
489 yield* h.assertClosed;
490 }).pipe(Effect.scoped),
491 );
492​
493 it.effect.skipIf(windowsHost)(
494 "removes runtime temp directories left by a previous server on create",
495 () =>
496 Effect.gen(function* () {
497 const fs = yield* FileSystem.FileSystem;
498 const path = yield* Path.Path;
499 const config = yield* ServerConfig;
500 const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
501 const tempRoot = resolveAntigravityRuntimeTempDirectory(
502 resolveAntigravityProfileDirectory(config.stateDir, instanceId),
503 );
504 const orphan = path.join(tempRoot, "run-orphan", "_MEI123", "google3");
505 yield* fs.makeDirectory(orphan, { recursive: true });
506 yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
507 yield* AntigravityDriver.create({
508 instanceId,
509 displayName: "Sweep",
510 enabled: false,
511 config: AntigravityDriver.defaultConfig(),
512 environment: [],
513 }).pipe(
514 Effect.provide(
515 Layer.mock(AntigravityInstallation)({
516 managedDirectory: config.stateDir,
517 resolve: () => Effect.die("unused"),
518 acquire: () => Effect.die("unused"),
519 }),
520 ),
521 );
522 expect(yield* fs.exists(tempRoot)).toBe(false);
523 }).pipe(Effect.scoped),
524 );
525​
526 it.effect("probes through installation resolution without launching a process", () =>
527 Effect.gen(function* () {
528 const h = yield* makeHarness({ enabled: true });
529 const snapshot = yield* h.instance.snapshot.refresh;
530 expect(snapshot.installed).toBe(true);
531 expect(snapshot.version).toBe(h.first.version);
532 expect(h.launches).toEqual([]);
533 expect(h.acquisitions).toEqual([]);
534 }).pipe(Effect.scoped),
535 );
536});