Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { expect, it } from "@effect/vitest";
4import {
5 ANTIGRAVITY_DEFAULT_MODEL,
6 ProviderInstanceId,
7 type AntigravitySettings,
8} from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Redacted from "effect/Redacted";
15import * as Schema from "effect/Schema";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17import { HttpClient } from "effect/http";
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 const env = (name: string) => {
166 const value = environment[name];
167 return Redacted.isRedacted(value) ? Redacted.value(value) : value;
168 };
169 launches.push({
170 command: command.command,
171 args: command.args.map(String),
172 cwd: command.options.cwd,
173 extendEnv: command.options.extendEnv,
174 profileDirectory: env("GEMINI_HOME"),
175 harnessPath: env("ANTIGRAVITY_HARNESS_PATH"),
176 forceFileStorage: env("AGY_ACP_FORCE_FILE_STORAGE"),
177 credentialKeys: Object.keys(environment).filter((key) =>
178 blockedCredentialKeys.has(key.toUpperCase()),
179 ),
180 geminiApiKey: env("GEMINI_API_KEY"),
181 tempDirectory:
182 environment.ANTIGRAVITY_HARNESS_PATH === undefined ? undefined : env("TMPDIR"),
183 handle,
184 });
185 return handle;
186 }),
187 );
188 const instance = yield* AntigravityDriver.create({
189 instanceId,
190 displayName: "Google test account",
191 enabled: options.enabled ?? true,
192 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
193 environment: [
194 { name: "PATH", value: instancePath },
195 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
196 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
197 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
198 { name: "google_api_key", value: "must-not-be-used" },
199 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
200 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
201 { name: "GEMINI_HOME", value: "/must-not-be-used" },
202 { name: "ANTIGRAVITY_HARNESS_PATH", value: "/must-not-be-used" },
203 { name: "BROWSER", value: "must-not-run" },
204 ].map((variable) => ({ ...variable, sensitive: false })),
205 }).pipe(
206 Effect.provide(layerInstallation),
207 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
208 );
209 const refresh = instance.refreshModels;
210 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
211 const readRequests = Effect.gen(function* () {
212 if (!(yield* fs.exists(requestLog))) return [];
213 const text = yield* fs.readFileString(requestLog);
214 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
215 decodeRequest(line),
216 );
217 });
218 const assertClosed = Effect.gen(function* () {
219 for (const launch of launches) {
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(Layer.mergeAll(NodeServices.layer, NodeCrypto.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 "refreshes through the selected executable and personal Google ACP",
280 () =>
281 Effect.gen(function* () {
282 const h = yield* makeHarness();
283 yield* h.refresh();
284 const snapshot = yield* h.instance.snapshot.getSnapshot;
285 expect(snapshot.status).toBe("ready");
286 expect(snapshot.auth.status).toBe("authenticated");
287 expect(snapshot.models.map((model) => model.slug)).toEqual([
288 "gemini-test-low",
289 "gemini-test-high",
290 ]);
291 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
292 expect(snapshot.models.every((model) => model.isLegacy !== true)).toBe(true);
293 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
294 expect(snapshot.supportsTextGeneration).toBe(true);
295 h.controls.selected = h.second;
296 yield* h.refresh();
297
298 expect(h.acquisitions).toEqual([
299 { binaryPath: "", path: h.instancePath },
300 { binaryPath: "", path: h.instancePath },
301 ]);
302 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
303 expect(nativeLaunches.map((launch) => launch.command)).toEqual([
304 h.first.executablePath,
305 h.second.executablePath,
306 ]);
307 expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
308 h.first.harnessPath,
309 h.second.harnessPath,
310 ]);
311 for (const launch of nativeLaunches) {
312 expect(launch.args).toEqual(hostPlatform === "linux" ? ["--uid="] : []);
313 expect(launch.profileDirectory).toBe(h.profileDirectory);
314 expect(launch.forceFileStorage).toBe("1");
315 expect(launch.extendEnv).toBe(false);
316 }
317 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
318 expect(h.releases).toEqual([h.first.version, h.second.version]);
319 const requests = yield* h.readRequests;
320 expect(requests.map((request) => request.method)).toEqual([
321 "initialize",
322 "auth/login",
323 "session/new",
324 "initialize",
325 "auth/login",
326 "session/new",
327 ]);
328 expect(
329 requests
330 .filter((request) => request.method === "auth/login")
331 .map((request) => request.params?.methodId),
332 ).toEqual(["oauth-personal", "oauth-personal"]);
333 expect(
334 requests
335 .filter((request) => request.method === "session/new")
336 .map((request) => request.params?.mcpServers),
337 ).toEqual([[], []]);
338 yield* h.assertClosed;
339 }).pipe(Effect.scoped),
340 );
341
342 it.effect.skipIf(windowsHost)(
343 "closes refresh processes and clears account metadata when Google sign-in is required",
344 () =>
345 Effect.gen(function* () {
346 const h = yield* makeHarness();
347 yield* h.refresh();
348 h.controls.selected = h.signedOut;
349 const error = yield* h.refresh().pipe(Effect.flip);
350 expect(error.detail).toContain("Sign in to Antigravity");
351 const snapshot = yield* h.instance.snapshot.getSnapshot;
352 expect(snapshot.auth.status).toBe("unauthenticated");
353 expect(snapshot.models).toEqual([]);
354 expect(snapshot.slashCommands).toEqual([]);
355 expect(snapshot.supportsTextGeneration).toBe(false);
356 expect(h.acquisitions).toHaveLength(2);
357 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
358 yield* h.assertClosed;
359 }).pipe(Effect.scoped),
360 );
361
362 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
363 Effect.gen(function* () {
364 const h = yield* makeHarness();
365 yield* h.refresh();
366 const before = yield* h.instance.snapshot.getSnapshot;
367 h.controls.failResolution = true;
368 const error = yield* h.refresh().pipe(Effect.flip);
369 expect(error.detail).toContain("previous model list is unchanged");
370 const after = yield* h.instance.snapshot.getSnapshot;
371 expect(after.models).toEqual(before.models);
372 expect(after.auth).toEqual(before.auth);
373 expect(h.acquisitions).toHaveLength(2);
374 expect(h.releases).toEqual([h.first.version]);
375 yield* h.assertClosed;
376 }).pipe(Effect.scoped),
377 );
378
379 it.effect.skipIf(windowsHost)(
380 "removes runtime temp directories left by a previous server on create",
381 () =>
382 Effect.gen(function* () {
383 const fs = yield* FileSystem.FileSystem;
384 const path = yield* Path.Path;
385 const config = yield* ServerConfig.ServerConfig;
386 const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
387 const directories = yield* resolveAntigravityInstanceDirectories(
388 config.stateDir,
389 instanceId,
390 );
391 const legacyRoot = path.join(directories.profile, "antigravity-acp", "tmp");
392 for (const root of [directories.runtimeTemp, legacyRoot]) {
393 const orphan = path.join(root, "run-orphan", "_MEI123", "google3");
394 yield* fs.makeDirectory(orphan, { recursive: true });
395 yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
396 }
397 yield* AntigravityDriver.create({
398 instanceId,
399 displayName: "Sweep",
400 enabled: false,
401 config: AntigravityDriver.defaultConfig(),
402 environment: [],
403 }).pipe(
404 Effect.provide(
405 Layer.mock(AntigravityInstallation.AntigravityInstallation)({
406 managedDirectory: config.stateDir,
407 resolve: () => Effect.die("unused"),
408 acquire: () => Effect.die("unused"),
409 }),
410 ),
411 );
412 expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
413 expect(yield* fs.exists(legacyRoot)).toBe(false);
414 }).pipe(Effect.scoped),
415 );
416});