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