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

AntigravityDriver.test.ts

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