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