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