Open History to see the last commit
1import * as Sink from "effect/Sink";
2import * as Deferred from "effect/Deferred";
3import * as Fiber from "effect/Fiber";
4import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
5import * as TestClock from "effect/testing/TestClock";
6import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
7import * as NodePath from "@effect/platform-node/NodePath";
8import * as NodeServices from "@effect/platform-node/NodeServices";
9import { ProviderInstanceId } from "@t3tools/contracts";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { describe, expect, it } from "@effect/vitest";
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 Result from "effect/Result";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import * as Ndjson from "effect/encoding/Ndjson";
20import * as AcpErrors from "effect-acp/errors";
21import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
22
23import {
24 ANTIGRAVITY_AUTH_BROWSER_MARKER,
25 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
26 ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
27 type AntigravityAuthConfig,
28 type AntigravityProfile,
29 buildAntigravityAcpSpawnInput,
30 isAntigravitySignInRequiredError,
31 makeAntigravityStderrHandler,
32 makeAntigravityStdoutTransform,
33 parseAntigravityAuthorizationUrl,
34 prepareAntigravityProfile,
35 resolveAntigravityInstanceDirectories,
36} from "./antigravityAuthSupport.ts";
37
38const authorizationUrl =
39 "https://accounts.google.com/o/oauth2/v2/auth?response_type=code" +
40 "&client_id=test-client&redirect_uri=http%3A%2F%2F127.0.0.1%3A46353%2F" +
41 "&state=test-opaque-state&code_challenge=test-challenge&code_challenge_method=S256";
42const authLine = `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`;
43const encode = (text: string) => new TextEncoder().encode(text);
44const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
45
46const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
47
48describe("Antigravity process environment", () => {
49 const profile: AntigravityProfile = {
50 platform: "linux",
51 geminiHome: "/t3/userdata/providers/antigravity/profile",
52 acpDirectory: "/t3/userdata/providers/antigravity/profile/antigravity-acp",
53 tokenPath: "/t3/userdata/providers/antigravity/profile/antigravity-acp/acp_token.json",
54 tempDirectory: "/t3/userdata/providers/antigravity/profile/antigravity-acp/tmp",
55 browserCommand: "managed-browser-helper",
56 };
57
58 it("isolates the profile and harness after merging overrides without changing the base environment", () => {
59 const baseEnv = {
60 HOME: "/home/developer",
61 PATH: "/usr/bin",
62 GEMINI_API_KEY: "do-not-use-api-billing",
63 google_api_key: "case-insensitive-api-key",
64 GOOGLE_CLOUD_PROJECT: "do-not-use-project",
65 GOOGLE_CLOUD_LOCATION: "do-not-use-location",
66 GOOGLE_APPLICATION_CREDENTIALS: "/credentials.json",
67 GOOGLE_CLOUD_QUOTA_PROJECT: "do-not-use-quota-project",
68 GOOGLE_GENAI_USE_VERTEXAI: "true",
69 AGY_ACP_CCPA_PROJECT: "do-not-use-consumer-project",
70 AGY_ACP_ENABLE_OAUTH: "1",
71 GEMINI_HOME: "/shared-gemini-home",
72 gemini_home: "/alias-shared-home",
73 AGY_ACP_FORCE_FILE_STORAGE: "0",
74 ANTIGRAVITY_HARNESS_PATH: "/wrong-version/harness",
75 BROWSER: "open-real-browser",
76 browser: "another-real-browser",
77 PYTHONUNBUFFERED: "0",
78 ELECTRON_RUN_AS_NODE: "0",
79 CUSTOM_SETTING: "keep-this",
80 };
81 const original = { ...baseEnv };
82 const spawn = buildAntigravityAcpSpawnInput({
83 installation: { executablePath: "/release/acp", harnessPath: "/release/harness" },
84 profile,
85 cwd: "/project",
86 baseEnv,
87 });
88
89 expect(baseEnv).toEqual(original);
90 expect(spawn).toEqual({
91 command: "/release/acp",
92 args: ["--uid="],
93 cwd: "/project",
94 extendEnv: false,
95 env: {
96 HOME: "/home/developer",
97 PATH: "/usr/bin",
98 CUSTOM_SETTING: "keep-this",
99 GEMINI_HOME: profile.geminiHome,
100 AGY_ACP_FORCE_FILE_STORAGE: "1",
101 ANTIGRAVITY_HARNESS_PATH: "/release/harness",
102 BROWSER: profile.browserCommand,
103 PYTHONUNBUFFERED: "1",
104 ELECTRON_RUN_AS_NODE: "1",
105 TMPDIR: profile.tempDirectory,
106 },
107 });
108 });
109
110 it("runs the agy CLI as `agy acp` without a harness", () => {
111 const spawn = buildAntigravityAcpSpawnInput({
112 installation: { executablePath: "/usr/bin/agy", harnessPath: null },
113 profile,
114 cwd: "/project",
115 baseEnv: { PATH: "/usr/bin", ANTIGRAVITY_HARNESS_PATH: "/stale/harness" },
116 });
117
118 expect(spawn.command).toBe("/usr/bin/agy");
119 expect(spawn.args).toEqual(["acp"]);
120 expect(spawn.env).not.toHaveProperty("ANTIGRAVITY_HARNESS_PATH");
121 expect(spawn.env).toMatchObject({ GEMINI_HOME: profile.geminiHome, PATH: "/usr/bin" });
122 });
123
124 it("passes only the configured method's credential and keeps the GCP pair out of the environment", () => {
125 const baseEnv = { PATH: "/usr/bin", GOOGLE_API_KEY: "ambient-key" };
126 const spawnFor = (auth: AntigravityAuthConfig) =>
127 buildAntigravityAcpSpawnInput({
128 installation: { executablePath: "/release/acp", harnessPath: "/release/harness" },
129 profile,
130 cwd: "/project",
131 baseEnv,
132 auth,
133 }).env ?? {};
134
135 const geminiKey = spawnFor({
136 authMethod: "gemini-api-key",
137 apiKey: "gemini-secret",
138 gcpProject: "proj",
139 gcpLocation: "us-central1",
140 });
141 expect(geminiKey.GEMINI_API_KEY).toBe("gemini-secret");
142 expect(geminiKey.GOOGLE_API_KEY).toBeUndefined();
143 expect(geminiKey.GOOGLE_CLOUD_PROJECT).toBeUndefined();
144
145 const vertexKey = spawnFor({
146 authMethod: "agent-platform",
147 apiKey: "vertex-secret",
148 gcpProject: "",
149 gcpLocation: "",
150 });
151 expect(vertexKey.GOOGLE_API_KEY).toBe("vertex-secret");
152 expect(vertexKey.GEMINI_API_KEY).toBeUndefined();
153
154 const business = spawnFor({
155 authMethod: "oauth-business",
156 apiKey: "ignored",
157 gcpProject: "proj",
158 gcpLocation: "us-central1",
159 });
160 expect(business.GEMINI_API_KEY).toBeUndefined();
161 expect(business.GOOGLE_API_KEY).toBeUndefined();
162 });
163
164 it("isolates TEMP and TMP to the profile directory on Windows", () => {
165 const windowsProfile: AntigravityProfile = {
166 platform: "win32",
167 geminiHome: "C:\\state\\providers\\antigravity\\profile",
168 acpDirectory: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp",
169 tokenPath: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp\\acp_token.json",
170 tempDirectory: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp\\tmp",
171 browserCommand: "managed-browser-helper",
172 };
173 const input = {
174 installation: {
175 executablePath: "C:\\release\\agy_acp_server.exe",
176 harnessPath: "C:\\release\\localharness_external.exe",
177 },
178 profile: windowsProfile,
179 cwd: "C:\\project",
180 baseEnv: { PATH: "C:\\Windows\\system32", TEMP: "C:\\Users\\user\\AppData\\Local\\Temp" },
181 };
182 const shared = buildAntigravityAcpSpawnInput(input);
183 expect(shared.env?.TEMP).toBe(windowsProfile.tempDirectory);
184 expect(shared.env?.TMP).toBe(windowsProfile.tempDirectory);
185 const perRun = buildAntigravityAcpSpawnInput({
186 ...input,
187 runtimeTempDirectory: `${windowsProfile.tempDirectory}\\run-1`,
188 });
189 expect(perRun.env?.TEMP).toBe(`${windowsProfile.tempDirectory}\\run-1`);
190 expect(perRun.env?.TMP).toBe(`${windowsProfile.tempDirectory}\\run-1`);
191 });
192
193 it.effect("keeps accounts separate even when instance IDs differ only by case", () =>
194 Effect.gen(function* () {
195 const first = yield* resolveAntigravityInstanceDirectories(
196 "/userdata",
197 ProviderInstanceId.make("antigravity"),
198 );
199 const second = yield* resolveAntigravityInstanceDirectories(
200 "/userdata",
201 ProviderInstanceId.make("Antigravity"),
202 );
203 expect(first.profile).toBe(
204 "/userdata/providers/antigravity/ac0a3dfd6dddb20962cecff6ee5fe65e19d3923be20e52c5ab52ff877f7e4c32",
205 );
206 expect(first.profile.toLowerCase()).not.toBe(second.profile.toLowerCase());
207 expect(first.runtimeTemp.toLowerCase()).not.toBe(second.runtimeTemp.toLowerCase());
208 }).pipe(Effect.provide(Layer.mergeAll(NodeCrypto.layer, NodePath.layerPosix))),
209 );
210
211 it.effect("keeps the unpacked Windows runtime under MAX_PATH for long user names", () =>
212 Effect.gen(function* () {
213 const path = yield* Path.Path;
214 // Deepest member of the official agy_acp_server_1.1.1 windows-x86_64 bundle.
215 const deepestMember =
216 "google3\\cloud\\developer_experience\\antigravity_extensions\\acp_server\\_private__agy_acp_server_bin.lazy_imports_info.json";
217 const directories = yield* resolveAntigravityInstanceDirectories(
218 "C:\\Users\\a-twenty-char-person\\.t3\\userdata",
219 ProviderInstanceId.make("antigravity"),
220 );
221 const extracted = (tempDirectory: string) =>
222 path.join(tempDirectory, "run-AbC123", "_MEI000012ab2", deepestMember);
223 // MAX_PATH is 260 including the terminating NUL.
224 expect(extracted(directories.runtimeTemp).length).toBeLessThan(260);
225 expect(
226 extracted(path.join(directories.profile, "antigravity-acp", "tmp")).length,
227 ).toBeGreaterThanOrEqual(260);
228 }).pipe(Effect.provide(Layer.mergeAll(NodeCrypto.layer, NodePath.layerWin32))),
229 );
230});
231
232describe("Antigravity authorization URL", () => {
233 it.effect(
234 "rejects other origins, ambiguous state, and non-loopback redirects without retaining them",
235 () =>
236 Effect.gen(function* () {
237 const invalidUrls = [
238 authorizationUrl.replace("https:", "http:"),
239 authorizationUrl.replace("accounts.google.com", "accounts.google.com.example.invalid"),
240 authorizationUrl.replace("accounts.google.com", "secret@accounts.google.com"),
241 authorizationUrl.replace("/o/oauth2/v2/auth", "/another-path"),
242 `${authorizationUrl}#secret-fragment`,
243 `${authorizationUrl}&state=another-state`,
244 authorizationUrl.replace("test-opaque-state", ""),
245 authorizationUrl.replace("test-opaque-state", "opaque%0astate"),
246 authorizationUrl.replace("127.0.0.1", "localhost"),
247 authorizationUrl.replace("127.0.0.1", "169.254.169.254"),
248 authorizationUrl.replace("46353", "80"),
249 authorizationUrl.replace("46353", "70000"),
250 authorizationUrl.replace("46353%2F", "46353%2Fother"),
251 authorizationUrl.replace("response_type=code", "response_type=token"),
252 "not a URL containing secret-code",
253 ];
254 for (const invalidUrl of invalidUrls) {
255 const result = yield* parseAntigravityAuthorizationUrl(invalidUrl).pipe(Effect.result);
256 expect(Result.isFailure(result)).toBe(true);
257 if (Result.isSuccess(result)) continue;
258 expect(result.failure._tag).toBe("AcpTransportError");
259 expect(encodeUnknownJson(result.failure)).not.toContain("test-opaque-state");
260 expect(encodeUnknownJson(result.failure)).not.toContain("secret-code");
261 expect(encodeUnknownJson(result.failure)).not.toContain(invalidUrl);
262 }
263 }),
264 );
265});
266
267describe("Antigravity sign-in errors", () => {
268 it("recognizes native auth-required errors and the blocked-login transport error", () => {
269 expect(isAntigravitySignInRequiredError(AcpErrors.AcpRequestError.authRequired())).toBe(true);
270 expect(
271 isAntigravitySignInRequiredError(
272 new AcpErrors.AcpTransportError({
273 detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
274 cause: undefined,
275 }),
276 ),
277 ).toBe(true);
278 });
279
280 it("does not treat other failures or arbitrary text as missing authentication", () => {
281 const otherErrors = [
282 new AcpErrors.AcpTransportError({ detail: "The process stopped.", cause: undefined }),
283 AcpErrors.AcpRequestError.internalError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE),
284 new Error(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE),
285 { detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE },
286 ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
287 undefined,
288 ];
289 for (const error of otherErrors) expect(isAntigravitySignInRequiredError(error)).toBe(false);
290 });
291});
292
293describe("Antigravity stdout compatibility", () => {
294 it.effect(
295 "handles fragmented login lines between JSON messages without changing protocol bytes",
296 () =>
297 Effect.gen(function* () {
298 const urls: string[] = [];
299 const jsonBefore = '{"jsonrpc":"2.0","id":1,"result":{}}\r\n';
300 const jsonAfter = '{"jsonrpc":"2.0","id":2,"result":{"text":"café"}}\n';
301 const chunks = [
302 encode(`${jsonBefore}${ANTIGRAVITY_AUTH_STDOUT_PREFIX.slice(0, 7)}`),
303 encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX.slice(7)),
304 encode(authorizationUrl.slice(0, 40)),
305 encode(`${authorizationUrl.slice(40)}\r`),
306 encode(`\n${jsonAfter}`),
307 ];
308 const result = yield* makeAntigravityStdoutTransform({
309 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
310 })(Stream.fromIterable(chunks)).pipe(Stream.decodeText(), Stream.mkString);
311 expect(result).toBe(`${jsonBefore}${jsonAfter}`);
312 expect(urls).toEqual([authorizationUrl]);
313 }),
314 );
315
316 it.effect("ends normal work with a safe sign-in error instead of waiting for OAuth", () =>
317 Effect.gen(function* () {
318 const result = yield* makeAntigravityStdoutTransform()(Stream.make(encode(authLine))).pipe(
319 Stream.runDrain,
320 Effect.result,
321 );
322 expect(Result.isFailure(result)).toBe(true);
323 if (Result.isSuccess(result)) return;
324 expect(result.failure).toMatchObject({
325 _tag: "AcpTransportError",
326 detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
327 });
328 expect(encodeUnknownJson(result.failure)).not.toContain(authorizationUrl);
329 expect(encodeUnknownJson(result.failure)).not.toContain("test-opaque-state");
330 }),
331 );
332
333 it.effect("preserves typed errors from the flow owner", () =>
334 Effect.gen(function* () {
335 const failure = new AcpErrors.AcpTransportError({
336 detail: "This sign-in flow has expired.",
337 cause: undefined,
338 });
339 const result = yield* makeAntigravityStdoutTransform({
340 onAuthorizationUrl: () => Effect.fail(failure),
341 })(Stream.make(encode(authLine))).pipe(Stream.runDrain, Effect.result);
342 expect(Result.isFailure(result)).toBe(true);
343 if (Result.isSuccess(result)) return;
344 expect(result.failure).toBe(failure);
345 }),
346 );
347
348 it.effect("does not suppress malformed protocol data or similar login messages", () =>
349 Effect.gen(function* () {
350 const unrelated = [
351 "this is not JSON\n",
352 `${ANTIGRAVITY_AUTH_STDOUT_PREFIX.toLowerCase()}${authorizationUrl}\n`,
353 ` ${authLine}`,
354 ];
355 for (const line of unrelated) {
356 const transform = makeAntigravityStdoutTransform();
357 const output = yield* transform(Stream.make(encode(line))).pipe(
358 Stream.decodeText(),
359 Stream.mkString,
360 );
361 expect(output).toBe(line);
362 const decoded = yield* transform(Stream.make(encode(line))).pipe(
363 Stream.pipeThroughChannel(Ndjson.decode()),
364 Stream.runDrain,
365 Effect.result,
366 );
367 expect(Result.isFailure(decoded)).toBe(true);
368 }
369 }),
370 );
371
372 it.effect("bounds unfinished protocol lines", () =>
373 Effect.gen(function* () {
374 const result = yield* makeAntigravityStdoutTransform()(
375 Stream.make(new Uint8Array(16 * 1024 * 1024), encode("x")),
376 ).pipe(Stream.runDrain, Effect.result);
377 expect(Result.isFailure(result)).toBe(true);
378 if (Result.isSuccess(result)) return;
379 expect(result.failure).toMatchObject({
380 _tag: "AcpTransportError",
381 detail: "Antigravity sent a protocol line that is too large.",
382 });
383 }),
384 );
385});
386
387describe("Antigravity stderr compatibility", () => {
388 it.effect("forwards fragmented native sign-in URLs from runtime 1.1.1", () =>
389 Effect.gen(function* () {
390 const urls: string[] = [];
391 const line = `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\r\n`;
392 const handleStderr = makeAntigravityStderrHandler({
393 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
394 });
395 yield* handleStderr(`native log\n${line.slice(0, 40)}`);
396 yield* handleStderr(line.slice(40, 90));
397 yield* handleStderr(`${line.slice(90)}another native log\n`);
398 expect(urls).toEqual([authorizationUrl]);
399 }),
400 );
401
402 it.effect("rejects interactive sign-in during normal work", () =>
403 Effect.gen(function* () {
404 const handleStderr = makeAntigravityStderrHandler();
405 const error = yield* handleStderr(
406 `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`,
407 ).pipe(Effect.flip);
408 expect(isAntigravitySignInRequiredError(error)).toBe(true);
409 }),
410 );
411
412 it.effect("forwards an accepted browser-helper URL larger than 8 KiB", () =>
413 Effect.gen(function* () {
414 const urls: string[] = [];
415 const longAuthorizationUrl = `${authorizationUrl}&scope=${"a".repeat(9_000)}`;
416 const handleStderr = makeAntigravityStderrHandler({
417 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
418 });
419
420 expect(longAuthorizationUrl.length).toBeGreaterThan(8_192);
421 yield* handleStderr(
422 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson(longAuthorizationUrl)}\n`,
423 );
424
425 expect(urls).toEqual([longAuthorizationUrl]);
426 }),
427 );
428
429 it.effect("forwards a fragmented browser-helper URL without exposing other stderr", () =>
430 Effect.gen(function* () {
431 const urls: string[] = [];
432 const markerLine = `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson(authorizationUrl)}\n`;
433 const handleStderr = makeAntigravityStderrHandler({
434 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
435 });
436
437 yield* handleStderr(`native log\n${markerLine.slice(0, 12)}`);
438 yield* handleStderr(markerLine.slice(12, 70));
439 yield* handleStderr(`${markerLine.slice(70)}another native log\n`);
440
441 expect(urls).toEqual([authorizationUrl]);
442 }),
443 );
444
445 it.effect("ignores malformed and similar browser-helper messages", () =>
446 Effect.gen(function* () {
447 const urls: string[] = [];
448 const handleStderr = makeAntigravityStderrHandler({
449 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
450 });
451
452 yield* handleStderr(
453 ` ${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson(authorizationUrl)}\n`,
454 );
455 yield* handleStderr(`${ANTIGRAVITY_AUTH_BROWSER_MARKER}${authorizationUrl}\n`);
456 yield* handleStderr(
457 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson("https://example.com")}\n`,
458 );
459 yield* handleStderr(`${ANTIGRAVITY_AUTH_STDOUT_PREFIX}https://example.com\n`);
460 yield* handleStderr(` ${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`);
461
462 expect(urls).toEqual([]);
463 }),
464 );
465});
466
467it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => {
468 const prepareSpawn = Effect.fn(function* (
469 bundles: ReadonlyArray<string>,
470 baseEnv: NodeJS.ProcessEnv = {},
471 platform: NodeJS.Platform = "linux",
472 ) {
473 const fs = yield* FileSystem.FileSystem;
474 const path = yield* Path.Path;
475 const directory = yield* fs.makeTempDirectoryScoped();
476 const profile = yield* prepareAntigravityProfile({
477 profileDirectory: path.join(directory, "profile"),
478 userHome: path.join(directory, "home"),
479 runtimeExecutablePath: process.execPath,
480 platform,
481 baseEnv,
482 }).pipe(
483 Effect.provideService(FileSystem.FileSystem, {
484 ...fs,
485 exists: (candidate) => Effect.succeed(bundles.includes(candidate)),
486 }),
487 );
488 return buildAntigravityAcpSpawnInput({
489 installation: { executablePath: "/release/acp", harnessPath: "/release/harness" },
490 profile,
491 cwd: directory,
492 baseEnv,
493 }).env;
494 });
495
496 // A Windows Node path cannot preflight the browser helper as a POSIX host.
497 const caTest = it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32");
498
499 caTest(
500 "launches Linux agents with the first available CA bundle, preferring absolute Nix paths",
501 () =>
502 Effect.gen(function* () {
503 const systemBundles = ["/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem"];
504 const nixBundle = "/nix/store/nss-cacert/etc/ssl/certs/ca-bundle.crt";
505 expect((yield* prepareSpawn(systemBundles))?.SSL_CERT_FILE).toBe(systemBundles[0]);
506 expect(
507 (yield* prepareSpawn([nixBundle, ...systemBundles], { NIX_SSL_CERT_FILE: nixBundle }))
508 ?.SSL_CERT_FILE,
509 ).toBe(nixBundle);
510 expect(
511 (yield* prepareSpawn(systemBundles, { NIX_SSL_CERT_FILE: nixBundle }))?.SSL_CERT_FILE,
512 ).toBe(systemBundles[0]);
513 expect(
514 (yield* prepareSpawn(["certs/local.pem", ...systemBundles], {
515 NIX_SSL_CERT_FILE: "certs/local.pem",
516 }))?.SSL_CERT_FILE,
517 ).toBe(systemBundles[0]);
518 expect((yield* prepareSpawn([]))?.SSL_CERT_FILE).toBeUndefined();
519 }),
520 );
521
522 caTest("preserves explicit certificate files and directories in Linux launches", () =>
523 Effect.gen(function* () {
524 const bundles = ["/etc/ssl/certs/ca-certificates.crt"];
525 expect(
526 (yield* prepareSpawn(bundles, { SSL_CERT_FILE: "/custom/ca.pem" }))?.SSL_CERT_FILE,
527 ).toBe("/custom/ca.pem");
528 const directoryEnv = yield* prepareSpawn(bundles, { SSL_CERT_DIR: "/custom/certs" });
529 expect(directoryEnv?.SSL_CERT_DIR).toBe("/custom/certs");
530 expect(directoryEnv?.SSL_CERT_FILE).toBeUndefined();
531 }),
532 );
533
534 it.effect("runs the browser helper with installed Node in standalone builds", () =>
535 Effect.gen(function* () {
536 const fs = yield* FileSystem.FileSystem;
537 const path = yield* Path.Path;
538 const directory = yield* fs.makeTempDirectoryScoped();
539 const profile = yield* prepareAntigravityProfile({
540 profileDirectory: path.join(directory, "profile"),
541 baseEnv: { PATH: path.dirname(process.execPath) },
542 });
543 expect(profile.browserCommand).not.toContain("/packaged/t3");
544 expect(yield* fs.exists(profile.acpDirectory)).toBe(true);
545 }).pipe(
546 Effect.provideService(HostProcess.IsExecutable, true),
547 Effect.provideService(HostProcess.ExecutablePath, "/packaged/t3"),
548 ),
549 );
550
551 it.effect("reports missing Node before creating the standalone sign-in profile", () =>
552 Effect.gen(function* () {
553 const fs = yield* FileSystem.FileSystem;
554 const path = yield* Path.Path;
555 const directory = yield* fs.makeTempDirectoryScoped();
556 const profileDirectory = path.join(directory, "profile");
557 const result = yield* prepareAntigravityProfile({
558 profileDirectory,
559 baseEnv: { PATH: "" },
560 }).pipe(Effect.result);
561 expect(Result.isFailure(result)).toBe(true);
562 if (Result.isFailure(result)) {
563 expect(result.failure).toMatchObject({
564 _tag: "AcpTransportError",
565 detail: expect.stringContaining("Install Node.js"),
566 cause: {
567 _tag: "NodeRuntimeUnavailableError",
568 },
569 });
570 }
571 expect(yield* fs.exists(profileDirectory)).toBe(false);
572 }).pipe(Effect.provideService(HostProcess.IsExecutable, true)),
573 );
574
575 it.effect("preflights the no-browser helper and creates private directories only", () =>
576 Effect.gen(function* () {
577 const fs = yield* FileSystem.FileSystem;
578 const path = yield* Path.Path;
579 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
580 const profile = yield* prepareAntigravityProfile({
581 profileDirectory: path.join(temporaryDirectory, "profile"),
582 });
583
584 expect(profile.geminiHome).toBe(path.join(temporaryDirectory, "profile"));
585 expect(yield* fs.exists(profile.acpDirectory)).toBe(true);
586 expect(yield* fs.exists(profile.tokenPath)).toBe(false);
587 if ((yield* HostProcess.Platform) !== "win32") {
588 expect((yield* fs.stat(profile.geminiHome)).mode & 0o777).toBe(0o700);
589 expect((yield* fs.stat(profile.acpDirectory)).mode & 0o777).toBe(0o700);
590 }
591
592 yield* fs.writeFileString(profile.tokenPath, "synthetic-token-fixture");
593 yield* prepareAntigravityProfile({ profileDirectory: profile.geminiHome });
594 expect(yield* fs.readFileString(profile.tokenPath)).toBe("synthetic-token-fixture");
595 }),
596 );
597
598 it.effect.skipIf(!symlinksSupported)(
599 "links only the user's existing global skill directories without touching real content",
600 () =>
601 Effect.gen(function* () {
602 const fs = yield* FileSystem.FileSystem;
603 const path = yield* Path.Path;
604 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
605 const userHome = path.join(temporaryDirectory, "home");
606 const profileDirectory = path.join(temporaryDirectory, "profile");
607 const configSkills = path.join(userHome, ".gemini", "config", "skills");
608 const cliSkills = path.join(userHome, ".gemini", "antigravity-cli", "skills");
609 const isLink = (link: string) =>
610 fs.readLink(link).pipe(
611 Effect.as(true),
612 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
613 );
614 yield* fs.makeDirectory(path.join(configSkills, "review"), { recursive: true });
615
616 yield* prepareAntigravityProfile({ profileDirectory, userHome });
617 const configLink = path.join(profileDirectory, "config", "skills");
618 const cliLink = path.join(profileDirectory, "antigravity-cli", "skills");
619 expect(yield* fs.readLink(configLink)).toBe(configSkills);
620 expect(yield* isLink(cliLink)).toBe(false);
621 expect(yield* fs.exists(path.join(configLink, "review"))).toBe(true);
622 expect(yield* fs.exists(path.join(profileDirectory, "config", "mcp_config.json"))).toBe(
623 false,
624 );
625
626 // The harness leaves an empty folder where the link was skipped.
627 yield* fs.makeDirectory(cliLink, { recursive: true });
628 yield* prepareAntigravityProfile({ profileDirectory, userHome });
629 expect((yield* fs.stat(cliLink)).type).toBe("Directory");
630
631 yield* fs.makeDirectory(cliSkills, { recursive: true });
632 yield* fs.remove(configLink);
633 yield* fs.makeDirectory(path.join(configLink, "own-skill"), { recursive: true });
634 yield* prepareAntigravityProfile({ profileDirectory, userHome });
635 expect(yield* fs.readLink(cliLink)).toBe(cliSkills);
636 expect(yield* fs.exists(path.join(configLink, "own-skill"))).toBe(true);
637 expect((yield* fs.stat(configLink)).type).toBe("Directory");
638
639 yield* fs.remove(cliLink);
640 yield* fs.symlink(path.join(temporaryDirectory, "elsewhere"), cliLink);
641 yield* prepareAntigravityProfile({ profileDirectory, userHome });
642 expect(yield* fs.readLink(cliLink)).toBe(cliSkills);
643
644 yield* fs.remove(cliSkills, { recursive: true });
645 yield* prepareAntigravityProfile({ profileDirectory, userHome });
646 expect(yield* isLink(cliLink)).toBe(false);
647 }),
648 );
649
650 it.effect("rewrites the GCP block on every launch and never stores the API key", () =>
651 Effect.gen(function* () {
652 const fs = yield* FileSystem.FileSystem;
653 const path = yield* Path.Path;
654 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
655 const profile = yield* prepareAntigravityProfile({
656 profileDirectory: temporaryDirectory,
657 auth: {
658 authMethod: "agent-platform",
659 apiKey: "vertex-secret",
660 gcpProject: "proj",
661 gcpLocation: "us-central1",
662 },
663 });
664 const settingsPath = path.join(profile.acpDirectory, "settings.json");
665 const first = yield* fs.readFileString(settingsPath);
666 expect(decodeJson(first)).toEqual({
667 auth: { type: "agent-platform" },
668 gcp: { project: "proj", location: "us-central1" },
669 });
670 expect(first).not.toContain("vertex-secret");
671
672 yield* prepareAntigravityProfile({ profileDirectory: temporaryDirectory });
673 expect(decodeJson(yield* fs.readFileString(settingsPath))).toEqual({
674 auth: { type: "oauth-personal" },
675 });
676 }),
677 );
678
679 const preflightHelper = (exitDelay: Effect.Effect<void>) => {
680 const spawns = { count: 0 };
681 const started = Deferred.makeUnsafe<void>();
682 const spawner = ChildProcessSpawner.make(() =>
683 Effect.sync(() => {
684 spawns.count += 1;
685 return ChildProcessSpawner.makeHandle({
686 pid: ChildProcessSpawner.ProcessId(1),
687 exitCode: Deferred.succeed(started, undefined).pipe(
688 Effect.andThen(exitDelay),
689 Effect.as(ChildProcessSpawner.ExitCode(0)),
690 ),
691 isRunning: Effect.succeed(false),
692 kill: () => Effect.void,
693 unref: Effect.succeed(Effect.void),
694 stdin: Sink.drain,
695 stdout: Stream.empty,
696 stderr: Stream.encodeText(
697 Stream.make(
698 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"https://example.invalid/t3-antigravity-browser-preflight"\n`,
699 ),
700 ),
701 all: Stream.empty,
702 getInputFd: () => Sink.drain,
703 getOutputFd: () => Stream.empty,
704 });
705 }),
706 );
707 return { spawner, spawns, started };
708 };
709
710 const prepareWithHelper = Effect.fn("prepareWithHelper")(function* (
711 runtimeExecutablePath: string,
712 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
713 ) {
714 const fs = yield* FileSystem.FileSystem;
715 const path = yield* Path.Path;
716 const directory = yield* fs.makeTempDirectoryScoped();
717 return yield* prepareAntigravityProfile({
718 profileDirectory: path.join(directory, "profile"),
719 userHome: path.join(directory, "home"),
720 runtimeExecutablePath,
721 platform: "linux",
722 baseEnv: {},
723 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
724 });
725
726 it.effect("allows a browser preflight that takes longer than five seconds", () =>
727 Effect.gen(function* () {
728 const helper = preflightHelper(Effect.sleep("20 seconds"));
729 const fiber = yield* prepareWithHelper("/fake/slow-node", helper.spawner).pipe(
730 Effect.forkChild,
731 );
732 yield* Deferred.await(helper.started);
733 yield* TestClock.adjust("20 seconds");
734 yield* Fiber.join(fiber);
735
736 expect(helper.spawns.count).toBe(1);
737 }),
738 );
739
740 it.effect("fails a hung preflight after 30 seconds and verifies again on the next open", () =>
741 Effect.gen(function* () {
742 const hung = preflightHelper(Effect.never);
743 const fiber = yield* prepareWithHelper("/fake/hung-node", hung.spawner).pipe(
744 Effect.result,
745 Effect.forkChild,
746 );
747 yield* Deferred.await(hung.started);
748 yield* TestClock.adjust("29 seconds");
749 expect(fiber.pollUnsafe()).toBeUndefined();
750 yield* TestClock.adjust("1 second");
751 const result = yield* Fiber.join(fiber);
752 expect(Result.isFailure(result)).toBe(true);
753 if (Result.isFailure(result)) {
754 expect(result.failure).toMatchObject({
755 _tag: "AcpTransportError",
756 detail: "Antigravity browser suppression verification timed out.",
757 });
758 }
759
760 const recovered = preflightHelper(Effect.void);
761 yield* prepareWithHelper("/fake/hung-node", recovered.spawner);
762 expect(recovered.spawns.count).toBe(1);
763 }),
764 );
765
766 it.effect("rejects Python BROWSER delimiter collisions before starting a helper", () =>
767 Effect.gen(function* () {
768 const fs = yield* FileSystem.FileSystem;
769 const path = yield* Path.Path;
770 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
771 for (const platform of ["linux", "win32"] as const) {
772 const profileDirectory = path.join(temporaryDirectory, platform);
773 const result = yield* prepareAntigravityProfile({
774 profileDirectory,
775 platform,
776 runtimeExecutablePath: platform === "win32" ? "C:/bad;path/node.exe" : "/bad:path/node",
777 }).pipe(Effect.result);
778 expect(Result.isFailure(result)).toBe(true);
779 expect(yield* fs.exists(profileDirectory)).toBe(false);
780 }
781 }),
782 );
783});