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