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

AntigravityDriver.test.ts

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