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