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