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

antigravityAuthSupport.test.ts

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