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

AntigravityDriver.test.ts

410 lines15.9 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 * as HostProcess from "@t3tools/shared/HostProcess";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15import { HttpClient } from "effect/http";
16​
17import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
18import * as ServerConfig from "../../config.ts";
19import * as ServerSettings from "../../serverSettings.ts";
20import * as AntigravityInstallation from "../AntigravityInstallation.ts";
21import {
22 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
23 resolveAntigravityInstanceDirectories,
24} from "../antigravityAuthSupport.ts";
25import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
26import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
27import * as ModelManifest from "../ModelManifest.ts";
28import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
29import { AntigravityDriver } from "./AntigravityDriver.ts";
30import * as ProviderHostLive from "../ProviderHostLive.ts";
31import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
32​
33const hostPlatform = HostProcess.Platform.defaultValue();
34const windowsHost = hostPlatform === "win32";
35const decodeRequest = Schema.decodeEffect(
36 Schema.fromJsonString(
37 Schema.Struct({
38 method: Schema.optional(Schema.String),
39 params: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
40 }),
41 ),
42);
43const blockedCredentialKeys = new Set([
44 "GEMINI_API_KEY",
45 "GOOGLE_API_KEY",
46 "GOOGLE_APPLICATION_CREDENTIALS",
47 "GOOGLE_GENAI_USE_VERTEXAI",
48]);
49​
50function shellQuote(value: string): string {
51 return `'${value.replaceAll("'", `'"'"'`)}'`;
53​
54const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
55 options: { readonly config?: Partial<AntigravitySettings>; readonly enabled?: boolean } = {},
56) {
57 const fs = yield* FileSystem.FileSystem;
58 const path = yield* Path.Path;
59 const config = yield* ServerConfig.ServerConfig;
60 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
61 const nodePath = yield* HostProcess.ExecutablePath;
62 const baseEnv = yield* HostProcess.Environment;
63 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-driver-" });
64 const instanceId = ProviderInstanceId.make(path.basename(root));
65 const mockAgentPath = yield* path.fromFileUrl(
66 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
67 );
68 const requestLog = path.join(root, "requests.jsonl");
69 const directories = yield* resolveAntigravityInstanceDirectories(config.stateDir, instanceId);
70 const profileDirectory = directories.profile;
71 const instancePath = `${path.join(root, "instance-bin")}:${baseEnv.PATH ?? ""}`;
72​
73 const makeExecutable = Effect.fn("AntigravityDriverTest.makeExecutable")(function* (
74 name: string,
75 loginRequired = false,
76 ) {
77 const directory = path.join(root, name);
78 const executablePath = path.join(directory, "agy_acp_server.par");
79 const harnessPath = path.join(directory, "localharness_external");
80 yield* fs.makeDirectory(directory, { recursive: true });
81 const authorizationUrl =
82 "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";
83 yield* fs.writeFileString(
84 executablePath,
85 [
86 "#!/bin/sh",
87 ...(loginRequired
88 ? [`printf '%s\\n' ${shellQuote(ANTIGRAVITY_AUTH_STDOUT_PREFIX + authorizationUrl)}`]
89 : []),
90 `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`,
91 "",
92 ].join("\n"),
93 );
94 yield* fs.writeFileString(harnessPath, "#!/bin/sh\nexit 99\n");
95 yield* fs.chmod(executablePath, 0o755);
96 yield* fs.chmod(harnessPath, 0o755);
97 return {
98 executablePath,
99 harnessPath,
100 source: "managed",
101 version: name,
102 managedVersionDirectory: directory,
103 } satisfies AntigravityInstallation.AntigravityExecutable;
104 });
105​
106 const first = yield* makeExecutable("runtime 'one");
107 const second = yield* makeExecutable("runtime two");
108 const signedOut = yield* makeExecutable("runtime signed-out", true);
109 const controls = { selected: first, failResolution: false, beforeAcquire: Effect.void };
110 const acquisitions: Array<{ binaryPath: string | undefined; path: string | undefined }> = [];
111 const releases: Array<string | null> = [];
112 const launches: Array<{
113 command: string;
114 args: ReadonlyArray<string>;
115 cwd: string | undefined;
116 extendEnv: boolean | undefined;
117 profileDirectory: string | undefined;
118 harnessPath: string | undefined;
119 forceFileStorage: string | undefined;
120 credentialKeys: ReadonlyArray<string>;
121 geminiApiKey: string | undefined;
122 tempDirectory: string | undefined;
123 handle: ChildProcessSpawner.ChildProcessHandle;
124 }> = [];
125​
126 const layerInstallation = Layer.mock(AntigravityInstallation.AntigravityInstallation)({
127 managedDirectory: root,
128 resolve: () =>
129 Effect.gen(function* () {
130 if (controls.failResolution) {
131 return yield* new AntigravityInstallation.AntigravityInstallationError({
132 operation: "resolve",
133 detail: "Fixture resolution failed.",
134 });
135 }
136 return controls.selected;
137 }),
138 acquire: (binaryPath, environment) =>
139 Effect.gen(function* () {
140 acquisitions.push({ binaryPath, path: environment?.PATH });
141 yield* controls.beforeAcquire;
142 if (controls.failResolution) {
143 return yield* new AntigravityInstallation.AntigravityInstallationError({
144 operation: "resolve",
145 detail: "Fixture resolution failed.",
146 });
147 }
148 const selected = controls.selected;
149 yield* Effect.addFinalizer(() =>
150 Effect.sync(() => {
151 releases.push(selected.version);
152 }),
153 );
154 return selected;
155 }),
156 });
157 const observedSpawner = ChildProcessSpawner.make((command) =>
158 Effect.gen(function* () {
159 if (command._tag !== "StandardCommand")
160 return yield* Effect.die("Unexpected process pipeline.");
161 const handle = yield* spawner.spawn(command);
162 const environment = command.options.env ?? {};
163 launches.push({
164 command: command.command,
165 args: command.args,
166 cwd: command.options.cwd,
167 extendEnv: command.options.extendEnv,
168 profileDirectory: environment.GEMINI_HOME,
169 harnessPath: environment.ANTIGRAVITY_HARNESS_PATH,
170 forceFileStorage: environment.AGY_ACP_FORCE_FILE_STORAGE,
171 credentialKeys: Object.keys(environment).filter((key) =>
172 blockedCredentialKeys.has(key.toUpperCase()),
173 ),
174 geminiApiKey: environment.GEMINI_API_KEY,
175 tempDirectory:
176 environment.ANTIGRAVITY_HARNESS_PATH === undefined ? undefined : environment.TMPDIR,
177 handle,
178 });
179 return handle;
180 }),
181 );
182 const instance = yield* AntigravityDriver.create({
183 instanceId,
184 displayName: "Google test account",
185 enabled: options.enabled ?? true,
186 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
187 environment: [
188 { name: "PATH", value: instancePath },
189 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
190 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
191 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
192 { name: "google_api_key", value: "must-not-be-used" },
193 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
194 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
195 { name: "GEMINI_HOME", value: "/must-not-be-used" },
196 { name: "ANTIGRAVITY_HARNESS_PATH", value: "/must-not-be-used" },
197 { name: "BROWSER", value: "must-not-run" },
198 ].map((variable) => ({ ...variable, sensitive: false })),
199 }).pipe(
200 Effect.provide(layerInstallation),
201 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
202 );
203 const refresh = instance.refreshModels;
204 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
205 const readRequests = Effect.gen(function* () {
206 if (!(yield* fs.exists(requestLog))) return [];
207 const text = yield* fs.readFileString(requestLog);
208 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
209 decodeRequest(line),
210 );
211 });
212 const assertClosed = Effect.gen(function* () {
213 for (const launch of launches) {
214 yield* launch.handle.exitCode.pipe(Effect.ignore);
215 expect(yield* launch.handle.isRunning).toBe(false);
216 if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
217 if (launch.tempDirectory) expect(yield* fs.exists(launch.tempDirectory)).toBe(false);
218 }
219 });
220 return {
221 instance,
222 refresh,
223 fs,
224 path,
225 profileDirectory,
226 directories,
227 instancePath,
228 first,
229 second,
230 signedOut,
231 controls,
232 acquisitions,
233 releases,
234 launches,
235 readRequests,
236 assertClosed,
237 };
238});
239​
240const layerDeps = ServerConfig.layerTest(process.cwd(), {
241 prefix: "t3-antigravity-driver-config-",
242}).pipe(
243 Layer.provideMerge(NodeServices.layer),
244 Layer.provideMerge(
245 Layer.succeed(
246 HttpClient.HttpClient,
247 HttpClient.make(() => Effect.die("Unexpected quota request")),
248 ),
249 ),
250 Layer.provideMerge(ServerSettings.layerTest()),
251 Layer.provideMerge(
252 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
253 shouldRunScopeWork: () => Effect.succeed(false),
254 }),
255 ),
256 Layer.provideMerge(
257 Layer.succeed(
258 ProviderEventLoggers.ProviderEventLoggers,
259 ProviderEventLoggers.NoOpProviderEventLoggers,
260 ),
261 ),
262 Layer.provideMerge(ModelManifest.layerTest),
263 Layer.provideMerge(IdAllocator.layer),
264 Layer.provideMerge(McpProviderSessions.layer),
265);
266const layerTest = ProviderHostLive.layer.pipe(
267 Layer.provideMerge(ServerSecretStore.layer),
268 Layer.provideMerge(layerDeps),
269);
270​
271it.layer(layerTest)("AntigravityDriver", (it) => {
272 it.effect.skipIf(windowsHost)(
273 "refreshes through the selected executable and personal Google ACP",
274 () =>
275 Effect.gen(function* () {
276 const h = yield* makeHarness();
277 yield* h.refresh();
278 const snapshot = yield* h.instance.snapshot.getSnapshot;
279 expect(snapshot.status).toBe("ready");
280 expect(snapshot.auth.status).toBe("authenticated");
281 expect(snapshot.models.map((model) => model.slug)).toEqual([
282 "gemini-test-low",
283 "gemini-test-high",
284 ]);
285 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
286 expect(snapshot.models.every((model) => model.isLegacy !== true)).toBe(true);
287 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
288 expect(snapshot.supportsTextGeneration).toBe(true);
289 h.controls.selected = h.second;
290 yield* h.refresh();
291​
292 expect(h.acquisitions).toEqual([
293 { binaryPath: "", path: h.instancePath },
294 { binaryPath: "", path: h.instancePath },
295 ]);
296 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
297 expect(nativeLaunches.map((launch) => launch.command)).toEqual([
298 h.first.executablePath,
299 h.second.executablePath,
300 ]);
301 expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
302 h.first.harnessPath,
303 h.second.harnessPath,
304 ]);
305 for (const launch of nativeLaunches) {
306 expect(launch.args).toEqual(hostPlatform === "linux" ? ["--uid="] : []);
307 expect(launch.profileDirectory).toBe(h.profileDirectory);
308 expect(launch.forceFileStorage).toBe("1");
309 expect(launch.extendEnv).toBe(false);
310 }
311 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
312 expect(h.releases).toEqual([h.first.version, h.second.version]);
313 const requests = yield* h.readRequests;
314 expect(requests.map((request) => request.method)).toEqual([
315 "initialize",
316 "auth/login",
317 "session/new",
318 "initialize",
319 "auth/login",
320 "session/new",
321 ]);
322 expect(
323 requests
324 .filter((request) => request.method === "auth/login")
325 .map((request) => request.params?.methodId),
326 ).toEqual(["oauth-personal", "oauth-personal"]);
327 expect(
328 requests
329 .filter((request) => request.method === "session/new")
330 .map((request) => request.params?.mcpServers),
331 ).toEqual([[], []]);
332 yield* h.assertClosed;
333 }).pipe(Effect.scoped),
334 );
335​
336 it.effect.skipIf(windowsHost)(
337 "closes refresh processes and clears account metadata when Google sign-in is required",
338 () =>
339 Effect.gen(function* () {
340 const h = yield* makeHarness();
341 yield* h.refresh();
342 h.controls.selected = h.signedOut;
343 const error = yield* h.refresh().pipe(Effect.flip);
344 expect(error.detail).toContain("Sign in to Antigravity");
345 const snapshot = yield* h.instance.snapshot.getSnapshot;
346 expect(snapshot.auth.status).toBe("unauthenticated");
347 expect(snapshot.models).toEqual([]);
348 expect(snapshot.slashCommands).toEqual([]);
349 expect(snapshot.supportsTextGeneration).toBe(false);
350 expect(h.acquisitions).toHaveLength(2);
351 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
352 yield* h.assertClosed;
353 }).pipe(Effect.scoped),
354 );
355​
356 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
357 Effect.gen(function* () {
358 const h = yield* makeHarness();
359 yield* h.refresh();
360 const before = yield* h.instance.snapshot.getSnapshot;
361 h.controls.failResolution = true;
362 const error = yield* h.refresh().pipe(Effect.flip);
363 expect(error.detail).toContain("previous model list is unchanged");
364 const after = yield* h.instance.snapshot.getSnapshot;
365 expect(after.models).toEqual(before.models);
366 expect(after.auth).toEqual(before.auth);
367 expect(h.acquisitions).toHaveLength(2);
368 expect(h.releases).toEqual([h.first.version]);
369 yield* h.assertClosed;
370 }).pipe(Effect.scoped),
371 );
372​
373 it.effect.skipIf(windowsHost)(
374 "removes runtime temp directories left by a previous server on create",
375 () =>
376 Effect.gen(function* () {
377 const fs = yield* FileSystem.FileSystem;
378 const path = yield* Path.Path;
379 const config = yield* ServerConfig.ServerConfig;
380 const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
381 const directories = yield* resolveAntigravityInstanceDirectories(
382 config.stateDir,
383 instanceId,
384 );
385 const legacyRoot = path.join(directories.profile, "antigravity-acp", "tmp");
386 for (const root of [directories.runtimeTemp, legacyRoot]) {
387 const orphan = path.join(root, "run-orphan", "_MEI123", "google3");
388 yield* fs.makeDirectory(orphan, { recursive: true });
389 yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
390 }
391 yield* AntigravityDriver.create({
392 instanceId,
393 displayName: "Sweep",
394 enabled: false,
395 config: AntigravityDriver.defaultConfig(),
396 environment: [],
397 }).pipe(
398 Effect.provide(
399 Layer.mock(AntigravityInstallation.AntigravityInstallation)({
400 managedDirectory: config.stateDir,
401 resolve: () => Effect.die("unused"),
402 acquire: () => Effect.die("unused"),
403 }),
404 ),
405 );
406 expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
407 expect(yield* fs.exists(legacyRoot)).toBe(false);
408 }).pipe(Effect.scoped),
409 );
410});