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