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