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 ProviderSessionId,
8 ThreadId,
9 type AntigravitySettings,
10} from "@t3tools/contracts";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Path from "effect/Path";
16import * as Redacted from "effect/Redacted";
17import * as Schema from "effect/Schema";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19import { HttpClient } from "effect/http";
20
21import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
22import * as ServerConfig from "../../config.ts";
23import * as ServerSettings from "../../serverSettings.ts";
24import * as AntigravityInstallation from "../AntigravityInstallation.ts";
25import {
26 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
27 resolveAntigravityInstanceDirectories,
28} from "../antigravityAuthSupport.ts";
29import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
30import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
31import * as ModelManifest from "../ModelManifest.ts";
32import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
33import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
34import { AntigravityDriver } from "./AntigravityDriver.ts";
35import * as ProviderHostLive from "../ProviderHostLive.ts";
36import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
37
38const hostPlatform = HostProcess.Platform.defaultValue();
39const windowsHost = hostPlatform === "win32";
40const decodeRequest = Schema.decodeEffect(
41 Schema.fromJsonString(
42 Schema.Struct({
43 method: Schema.optional(Schema.String),
44 params: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
45 }),
46 ),
47);
48const blockedCredentialKeys = new Set([
49 "GEMINI_API_KEY",
50 "GOOGLE_API_KEY",
51 "GOOGLE_APPLICATION_CREDENTIALS",
52 "GOOGLE_GENAI_USE_VERTEXAI",
53]);
54
55function shellQuote(value: string): string {
56 return `'${value.replaceAll("'", `'"'"'`)}'`;
57}
58
59const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
60 options: { readonly config?: Partial<AntigravitySettings>; readonly enabled?: boolean } = {},
61) {
62 const fs = yield* FileSystem.FileSystem;
63 const path = yield* Path.Path;
64 const config = yield* ServerConfig.ServerConfig;
65 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
66 const nodePath = yield* HostProcess.ExecutablePath;
67 const baseEnv = yield* HostProcess.Environment;
68 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-driver-" });
69 const instanceId = ProviderInstanceId.make(path.basename(root));
70 const mockAgentPath = yield* path.fromFileUrl(
71 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
72 );
73 const requestLog = path.join(root, "requests.jsonl");
74 const directories = yield* resolveAntigravityInstanceDirectories(config.stateDir, instanceId);
75 const profileDirectory = directories.profile;
76 const instancePath = `${path.join(root, "instance-bin")}:${baseEnv.PATH ?? ""}`;
77
78 const makeExecutable = Effect.fn("AntigravityDriverTest.makeExecutable")(function* (
79 name: string,
80 options: {
81 readonly loginRequired?: boolean;
82 /** `data` of the agent's "Internal error" response to `session/new`. */
83 readonly newSessionErrorData?: unknown;
84 readonly initialMode?: string;
85 } = {},
86 ) {
87 const directory = path.join(root, name);
88 const executablePath = path.join(directory, "agy_acp_server.par");
89 const harnessPath = path.join(directory, "localharness_external");
90 yield* fs.makeDirectory(directory, { recursive: true });
91 const authorizationUrl =
92 "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";
93 yield* fs.writeFileString(
94 executablePath,
95 [
96 "#!/bin/sh",
97 ...(options.loginRequired
98 ? [`printf '%s\\n' ${shellQuote(ANTIGRAVITY_AUTH_STDOUT_PREFIX + authorizationUrl)}`]
99 : []),
100 ...(options.newSessionErrorData === undefined
101 ? []
102 : [
103 `export T3_ACP_NEW_SESSION_ERROR_DATA=${shellQuote(JSON.stringify(options.newSessionErrorData))}`,
104 ]),
105 ...(options.initialMode === undefined
106 ? []
107 : [`export T3_ACP_INITIAL_MODE=${shellQuote(options.initialMode)}`]),
108 `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`,
109 "",
110 ].join("\n"),
111 );
112 yield* fs.writeFileString(harnessPath, "#!/bin/sh\nexit 99\n");
113 yield* fs.chmod(executablePath, 0o755);
114 yield* fs.chmod(harnessPath, 0o755);
115 return {
116 executablePath,
117 harnessPath,
118 source: "managed",
119 version: name,
120 managedVersionDirectory: directory,
121 } satisfies AntigravityInstallation.AntigravityExecutable;
122 });
123
124 const first = yield* makeExecutable("runtime 'one");
125 const second = yield* makeExecutable("runtime two");
126 const signedOut = yield* makeExecutable("runtime signed-out", { loginRequired: true });
127 const controls: {
128 selected: AntigravityInstallation.AntigravityExecutable;
129 failResolution: boolean;
130 beforeAcquire: Effect.Effect<void>;
131 } = { selected: first, failResolution: false, beforeAcquire: Effect.void };
132 const acquisitions: Array<{ binaryPath: string | undefined; path: string | undefined }> = [];
133 const releases: Array<string | null> = [];
134 const launches: Array<{
135 command: string;
136 args: ReadonlyArray<string>;
137 cwd: string | undefined;
138 extendEnv: boolean | undefined;
139 profileDirectory: string | undefined;
140 harnessPath: string | undefined;
141 forceFileStorage: string | undefined;
142 credentialKeys: ReadonlyArray<string>;
143 geminiApiKey: string | undefined;
144 tempDirectory: string | undefined;
145 handle: ChildProcessSpawner.ChildProcessHandle;
146 }> = [];
147
148 const layerInstallation = Layer.mock(AntigravityInstallation.AntigravityInstallation)({
149 managedDirectory: root,
150 resolve: () =>
151 Effect.gen(function* () {
152 if (controls.failResolution) {
153 return yield* new AntigravityInstallation.AntigravityInstallationError({
154 operation: "resolve",
155 detail: "Fixture resolution failed.",
156 });
157 }
158 return controls.selected;
159 }),
160 acquire: (binaryPath, environment) =>
161 Effect.gen(function* () {
162 acquisitions.push({ binaryPath, path: environment?.PATH });
163 yield* controls.beforeAcquire;
164 if (controls.failResolution) {
165 return yield* new AntigravityInstallation.AntigravityInstallationError({
166 operation: "resolve",
167 detail: "Fixture resolution failed.",
168 });
169 }
170 const selected = controls.selected;
171 yield* Effect.addFinalizer(() =>
172 Effect.sync(() => {
173 releases.push(selected.version);
174 }),
175 );
176 return selected;
177 }),
178 });
179 const observedSpawner = ChildProcessSpawner.make((command) =>
180 Effect.gen(function* () {
181 if (command._tag !== "StandardCommand")
182 return yield* Effect.die("Unexpected process pipeline.");
183 const handle = yield* spawner.spawn(command);
184 const environment = command.options.env ?? {};
185 const env = (name: string) => {
186 const value = environment[name];
187 return Redacted.isRedacted(value) ? Redacted.value(value) : value;
188 };
189 launches.push({
190 command: command.command,
191 args: command.args.map(String),
192 cwd: command.options.cwd,
193 extendEnv: command.options.extendEnv,
194 profileDirectory: env("GEMINI_HOME"),
195 harnessPath: env("ANTIGRAVITY_HARNESS_PATH"),
196 forceFileStorage: env("AGY_ACP_FORCE_FILE_STORAGE"),
197 credentialKeys: Object.keys(environment).filter((key) =>
198 blockedCredentialKeys.has(key.toUpperCase()),
199 ),
200 geminiApiKey: env("GEMINI_API_KEY"),
201 tempDirectory:
202 environment.ANTIGRAVITY_HARNESS_PATH === undefined ? undefined : env("TMPDIR"),
203 handle,
204 });
205 return handle;
206 }),
207 );
208 const instance = yield* AntigravityDriver.create({
209 instanceId,
210 displayName: "Google test account",
211 enabled: options.enabled ?? true,
212 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
213 environment: [
214 { name: "PATH", value: instancePath },
215 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
216 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
217 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
218 { name: "google_api_key", value: "must-not-be-used" },
219 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
220 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
221 { name: "GEMINI_HOME", value: "/must-not-be-used" },
222 { name: "ANTIGRAVITY_HARNESS_PATH", value: "/must-not-be-used" },
223 { name: "BROWSER", value: "must-not-run" },
224 ].map((variable) => ({ ...variable, sensitive: false })),
225 }).pipe(
226 Effect.provide(layerInstallation),
227 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
228 );
229 const refresh = instance.refreshModels;
230 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
231 const readRequests = Effect.gen(function* () {
232 if (!(yield* fs.exists(requestLog))) return [];
233 const text = yield* fs.readFileString(requestLog);
234 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
235 decodeRequest(line),
236 );
237 });
238 const assertClosed = Effect.gen(function* () {
239 for (const launch of launches) {
240 yield* launch.handle.exitCode.pipe(Effect.ignore);
241 expect(yield* launch.handle.isRunning).toBe(false);
242 if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
243 if (launch.tempDirectory) expect(yield* fs.exists(launch.tempDirectory)).toBe(false);
244 }
245 });
246 return {
247 instance,
248 refresh,
249 makeExecutable,
250 fs,
251 path,
252 profileDirectory,
253 directories,
254 instancePath,
255 first,
256 second,
257 signedOut,
258 controls,
259 acquisitions,
260 releases,
261 launches,
262 readRequests,
263 assertClosed,
264 };
265});
266
267const layerDeps = ServerConfig.layerTest(process.cwd(), {
268 prefix: "t3-antigravity-driver-config-",
269}).pipe(
270 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
271 Layer.provideMerge(
272 Layer.succeed(
273 HttpClient.HttpClient,
274 HttpClient.make(() => Effect.die("Unexpected quota request")),
275 ),
276 ),
277 Layer.provideMerge(ServerSettings.layerTest()),
278 Layer.provideMerge(
279 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
280 shouldRunScopeWork: () => Effect.succeed(false),
281 }),
282 ),
283 Layer.provideMerge(
284 Layer.succeed(
285 ProviderEventLoggers.ProviderEventLoggers,
286 ProviderEventLoggers.NoOpProviderEventLoggers,
287 ),
288 ),
289 Layer.provideMerge(ModelManifest.layerTest),
290 Layer.provideMerge(IdAllocator.layer),
291 Layer.provideMerge(McpProviderSessions.layer),
292);
293const layerTest = ProviderHostLive.layer.pipe(
294 Layer.provideMerge(ServerSecretStore.layer),
295 Layer.provideMerge(layerDeps),
296);
297
298it.layer(layerTest)("AntigravityDriver", (it) => {
299 it.effect.skipIf(windowsHost)(
300 "refreshes the selected executable and limits form capabilities to chat",
301 () =>
302 Effect.gen(function* () {
303 const h = yield* makeHarness();
304 yield* h.refresh();
305 const snapshot = yield* h.instance.snapshot.getSnapshot;
306 expect(snapshot.status).toBe("ready");
307 expect(snapshot.auth.status).toBe("authenticated");
308 expect(snapshot.models.map((model) => model.slug)).toEqual([
309 "gemini-test-low",
310 "gemini-test-high",
311 ]);
312 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
313 expect(snapshot.models.every((model) => model.isLegacy !== true)).toBe(true);
314 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
315 expect(snapshot.supportsTextGeneration).toBe(true);
316 h.controls.selected = h.second;
317 yield* h.refresh();
318
319 expect(h.acquisitions).toEqual([
320 { binaryPath: "", path: h.instancePath },
321 { binaryPath: "", path: h.instancePath },
322 ]);
323 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
324 expect(nativeLaunches.map((launch) => launch.command)).toEqual([
325 h.first.executablePath,
326 h.second.executablePath,
327 ]);
328 expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
329 h.first.harnessPath,
330 h.second.harnessPath,
331 ]);
332 for (const launch of nativeLaunches) {
333 expect(launch.args).toEqual(hostPlatform === "linux" ? ["--uid="] : []);
334 expect(launch.profileDirectory).toBe(h.profileDirectory);
335 expect(launch.forceFileStorage).toBe("1");
336 expect(launch.extendEnv).toBe(false);
337 }
338 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
339 expect(h.releases).toEqual([h.first.version, h.second.version]);
340 const requests = yield* h.readRequests;
341 expect(requests.map((request) => request.method)).toEqual([
342 "initialize",
343 "auth/login",
344 "session/new",
345 "initialize",
346 "auth/login",
347 "session/new",
348 ]);
349 expect(
350 requests
351 .filter((request) => request.method === "auth/login")
352 .map((request) => request.params?.methodId),
353 ).toEqual(["oauth-personal", "oauth-personal"]);
354 expect(
355 requests
356 .filter((request) => request.method === "session/new")
357 .map((request) => request.params?.mcpServers),
358 ).toEqual([[], []]);
359 yield* h.assertClosed;
360 yield* h.instance.textGeneration
361 .generateThreadTitle({
362 cwd: h.profileDirectory,
363 message: "Name this thread",
364 modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
365 })
366 .pipe(Effect.ignore);
367 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-chat-" });
368 const threadId = ThreadId.make("thread-antigravity-capabilities");
369 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
370 runtimeMode: "approval-required",
371 interactionMode: "default",
372 cwd: workspace,
373 });
374 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
375 const session = yield* h.instance.orchestrationAdapter.openSession({
376 threadId,
377 providerSessionId: ProviderSessionId.make("provider-session-antigravity-capabilities"),
378 modelSelection,
379 runtimePolicy,
380 });
381 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
382
383 const helper = {
384 fs: { readTextFile: false, writeTextFile: false },
385 terminal: false,
386 session: { notices: {} },
387 };
388 expect(
389 (yield* h.readRequests)
390 .filter((request) => request.method === "initialize")
391 .map((request) => request.params?.clientCapabilities),
392 ).toEqual([
393 // Two model refreshes, then thread title generation.
394 helper,
395 helper,
396 helper,
397 {
398 fs: { readTextFile: true, writeTextFile: false },
399 terminal: false,
400 session: { notices: {} },
401 elicitation: { form: {} },
402 },
403 ]);
404
405 // The agy CLI rejects `yolo` and `auto_edit`; it stays in `default` and T3 answers its requests.
406 h.controls.selected = {
407 ...(yield* h.makeExecutable("runtime cli", { initialMode: "auto_edit" })),
408 harnessPath: null,
409 };
410 for (const runtimeMode of ["full-access", "auto-accept-edits"] as const) {
411 const requestsBefore = (yield* h.readRequests).length;
412 const cliThreadId = ThreadId.make(`thread-antigravity-cli-${runtimeMode}`);
413 const cliPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
414 runtimeMode,
415 interactionMode: "default",
416 cwd: workspace,
417 });
418 const cliSession = yield* h.instance.orchestrationAdapter.openSession({
419 threadId: cliThreadId,
420 providerSessionId: ProviderSessionId.make(`provider-session-cli-${runtimeMode}`),
421 modelSelection,
422 runtimePolicy: cliPolicy,
423 });
424 yield* cliSession.ensureThread({
425 threadId: cliThreadId,
426 modelSelection,
427 runtimePolicy: cliPolicy,
428 });
429 expect(h.launches.at(-1)?.args).toEqual(["acp"]);
430 expect(
431 (yield* h.readRequests)
432 .slice(requestsBefore)
433 .filter(
434 (request) =>
435 request.method === "session/set_config_option" &&
436 request.params?.configId === "mode",
437 )
438 .map((request) => request.params?.value),
439 ).toEqual(["default"]);
440 }
441 }).pipe(Effect.scoped),
442 );
443
444 it.effect.skipIf(windowsHost)(
445 "closes refresh processes and clears account metadata when Google sign-in is required",
446 () =>
447 Effect.gen(function* () {
448 const h = yield* makeHarness();
449 yield* h.refresh();
450 h.controls.selected = h.signedOut;
451 const error = yield* h.refresh().pipe(Effect.flip);
452 expect(error.detail).toContain("Sign in to Antigravity");
453 const snapshot = yield* h.instance.snapshot.getSnapshot;
454 expect(snapshot.auth.status).toBe("unauthenticated");
455 expect(snapshot.models).toEqual([]);
456 expect(snapshot.slashCommands).toEqual([]);
457 expect(snapshot.supportsTextGeneration).toBe(false);
458 expect(h.acquisitions).toHaveLength(2);
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 "reports the missing SOCKS dependency when session creation fails and keeps the catalog",
483 () =>
484 Effect.gen(function* () {
485 const h = yield* makeHarness();
486 yield* h.refresh();
487 const before = yield* h.instance.snapshot.getSnapshot;
488 h.controls.selected = yield* h.makeExecutable("runtime socks", {
489 newSessionErrorData: { details: "python-socks is required to use a SOCKS proxy" },
490 });
491 const error = yield* h.refresh().pipe(Effect.flip);
492 expect(error.detail).toBe(
493 "Could not refresh Antigravity models. The previous model list is unchanged. Antigravity reported: python-socks is required to use a SOCKS proxy",
494 );
495 const after = yield* h.instance.snapshot.getSnapshot;
496 expect(after.models).toEqual(before.models);
497 expect(after.auth).toEqual(before.auth);
498 yield* h.assertClosed;
499 }).pipe(Effect.scoped),
500 );
501
502 it.effect.skipIf(windowsHost)(
503 "never copies unrecognized agent error details into the refresh error",
504 () =>
505 Effect.gen(function* () {
506 const h = yield* makeHarness();
507 yield* h.refresh();
508 const before = yield* h.instance.snapshot.getSnapshot;
509 const generic =
510 "Could not refresh Antigravity models. The previous model list is unchanged.";
511 const secret = "https://accounts.example.test/o/oauth2?code=sk-secret-123";
512 h.controls.selected = yield* h.makeExecutable("runtime socks with extra", {
513 newSessionErrorData: {
514 details: `Traceback (most recent call last):\n proxy ${secret}\npython-socks is required to use a SOCKS proxy`,
515 },
516 });
517 const known = yield* h.refresh().pipe(Effect.flip);
518 expect(known.detail).toBe(
519 `${generic} Antigravity reported: python-socks is required to use a SOCKS proxy`,
520 );
521
522 for (const [name, data] of [
523 ["runtime unknown details", { details: `Token refresh failed for ${secret}` }],
524 ["runtime object details", { details: { stack: "secret frame", env: { HOME: "/" } } }],
525 ["runtime no details", ["python-socks is required to use a SOCKS proxy"]],
526 ] as const) {
527 h.controls.selected = yield* h.makeExecutable(name, { newSessionErrorData: data });
528 const error = yield* h.refresh().pipe(Effect.flip);
529 expect(error.detail).toBe(generic);
530 }
531 const after = yield* h.instance.snapshot.getSnapshot;
532 expect(after.models).toEqual(before.models);
533 expect(after.auth).toEqual(before.auth);
534 expect(JSON.stringify(after)).not.toContain("sk-secret-123");
535 yield* h.assertClosed;
536 }).pipe(Effect.scoped),
537 );
538
539 it.effect.skipIf(windowsHost)(
540 "removes runtime temp directories left by a previous server on create",
541 () =>
542 Effect.gen(function* () {
543 const fs = yield* FileSystem.FileSystem;
544 const path = yield* Path.Path;
545 const config = yield* ServerConfig.ServerConfig;
546 const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
547 const directories = yield* resolveAntigravityInstanceDirectories(
548 config.stateDir,
549 instanceId,
550 );
551 const legacyRoot = path.join(directories.profile, "antigravity-acp", "tmp");
552 for (const root of [directories.runtimeTemp, legacyRoot]) {
553 const orphan = path.join(root, "run-orphan", "_MEI123", "google3");
554 yield* fs.makeDirectory(orphan, { recursive: true });
555 yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
556 }
557 yield* AntigravityDriver.create({
558 instanceId,
559 displayName: "Sweep",
560 enabled: false,
561 config: AntigravityDriver.defaultConfig(),
562 environment: [],
563 }).pipe(
564 Effect.provide(
565 Layer.mock(AntigravityInstallation.AntigravityInstallation)({
566 managedDirectory: config.stateDir,
567 resolve: () => Effect.die("unused"),
568 acquire: () => Effect.die("unused"),
569 }),
570 ),
571 );
572 expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
573 expect(yield* fs.exists(legacyRoot)).toBe(false);
574 }).pipe(Effect.scoped),
575 );
576});