Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

antigravityAuthSupport.test.ts

834 lines33.4 KB

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