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