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