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

antigravityAuthSupport.test.ts

651 lines25.6 KB

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