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

AntigravityDriver.test.ts

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