The best way to control Claude Code, Codex and more from any computer or phone

main
ts 907 lines 38.3 KB
Raw
1 import * as Sink from "effect/Sink";
2 import * as Deferred from "effect/Deferred";
3 import * as Fiber from "effect/Fiber";
4 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
5 import * as TestClock from "effect/testing/TestClock";
6 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
7 import * as NodePath from "@effect/platform-node/NodePath";
8 import * as NodeServices from "@effect/platform-node/NodeServices";
9 import { ProviderInstanceId } from "@t3tools/contracts";
10 import * as HostProcess from "@t3tools/shared/HostProcess";
11 import { describe, expect, it } from "@effect/vitest";
12 import * as Effect from "effect/Effect";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Layer from "effect/Layer";
15 import * as Path from "effect/Path";
16 import * as Result from "effect/Result";
17 import * as Schema from "effect/Schema";
18 import * as Stream from "effect/Stream";
19 import * as Ndjson from "effect/encoding/Ndjson";
20 import * as AcpErrors from "effect-acp/errors";
21 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
22
23 import {
24 ANTIGRAVITY_AUTH_BROWSER_MARKER,
25 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
26 ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
27 type AntigravityAuthConfig,
28 type AntigravityProfile,
29 buildAntigravityAcpSpawnInput,
30 isAntigravitySignInRequiredError,
31 makeAntigravityStderrHandler,
32 makeAntigravityStdoutTransform,
33 antigravityLoginResponse,
34 parseAntigravityAuthorizationUrl,
35 prepareAntigravityProfile,
36 resolveAntigravityInstanceDirectories,
37 } from "./antigravityAuthSupport.ts";
38
39 const authorizationUrl =
40 "https://accounts.google.com/o/oauth2/v2/auth?response_type=code" +
41 "&client_id=test-client&redirect_uri=http%3A%2F%2F127.0.0.1%3A46353%2F" +
42 "&state=test-opaque-state&code_challenge=test-challenge&code_challenge_method=S256";
43 const authLine = `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`;
44 const encode = (text: string) => new TextEncoder().encode(text);
45 const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
46
47 const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
48
49 describe("Antigravity process environment", () => {
50 const profile: AntigravityProfile = {
51 platform: "linux",
52 geminiHome: "/t3/userdata/providers/antigravity/profile",
53 acpDirectory: "/t3/userdata/providers/antigravity/profile/antigravity-acp",
54 tokenPath: "/t3/userdata/providers/antigravity/profile/antigravity-acp/acp_token.json",
55 tempDirectory: "/t3/userdata/providers/antigravity/profile/antigravity-acp/tmp",
56 browserCommand: "managed-browser-helper",
57 };
58
59 it("runs `agy acp` with an isolated profile without changing the base environment", () => {
60 const baseEnv = {
61 HOME: "/home/developer",
62 PATH: "/usr/bin",
63 GEMINI_API_KEY: "do-not-use-api-billing",
64 google_api_key: "case-insensitive-api-key",
65 GOOGLE_CLOUD_PROJECT: "do-not-use-project",
66 GOOGLE_CLOUD_LOCATION: "do-not-use-location",
67 GOOGLE_APPLICATION_CREDENTIALS: "/credentials.json",
68 GOOGLE_CLOUD_QUOTA_PROJECT: "do-not-use-quota-project",
69 GOOGLE_GENAI_USE_VERTEXAI: "true",
70 AGY_ACP_CCPA_PROJECT: "do-not-use-consumer-project",
71 AGY_ACP_ENABLE_OAUTH: "1",
72 GEMINI_HOME: "/shared-gemini-home",
73 gemini_home: "/alias-shared-home",
74 AGY_ACP_FORCE_FILE_STORAGE: "0",
75 agy_cli_disable_auto_update: "0",
76 BROWSER: "open-real-browser",
77 browser: "another-real-browser",
78 PYTHONUNBUFFERED: "0",
79 ELECTRON_RUN_AS_NODE: "0",
80 CHROME_CRASHPAD_PIPE_NAME: "\\\\.\\pipe\\crashpad_50144_ZUJNJELFHHXPBIRT",
81 chrome_crashpad_pipe_name: "\\\\.\\pipe\\crashpad_stale_alias",
82 CUSTOM_SETTING: "keep-this",
83 };
84 const original = { ...baseEnv };
85 const spawn = buildAntigravityAcpSpawnInput({
86 installation: { executablePath: "/usr/bin/agy" },
87 profile,
88 cwd: "/project",
89 baseEnv,
90 });
91
92 expect(baseEnv).toEqual(original);
93 expect(spawn).toEqual({
94 command: "/usr/bin/agy",
95 args: ["acp", "--gemini-dir", profile.geminiHome, "--app-data-dir", "antigravity-acp"],
96 cwd: "/project",
97 extendEnv: false,
98 env: {
99 HOME: "/home/developer",
100 PATH: "/usr/bin",
101 CUSTOM_SETTING: "keep-this",
102 SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0",
103 GEMINI_HOME: profile.geminiHome,
104 AGY_ACP_FORCE_FILE_STORAGE: "1",
105 AGY_CLI_DISABLE_AUTO_UPDATE: "1",
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: "/usr/bin/agy" },
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 // Only the Google account method has the `--login` sign-in that works without the keyring.
154 for (const env of [geminiKey, vertexKey, business]) expect(env.SSH_CONNECTION).toBeUndefined();
155 expect(
156 spawnFor({ authMethod: "oauth-personal", apiKey: "", gcpProject: "", gcpLocation: "" })
157 .SSH_CONNECTION,
158 ).toBe("127.0.0.1 0 127.0.0.1 0");
159 });
160
161 it("isolates TEMP and TMP to the profile directory on Windows", () => {
162 const windowsProfile: AntigravityProfile = {
163 platform: "win32",
164 geminiHome: "C:\\state\\providers\\antigravity\\profile",
165 acpDirectory: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp",
166 tokenPath: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp\\acp_token.json",
167 tempDirectory: "C:\\state\\providers\\antigravity\\profile\\antigravity-acp\\tmp",
168 browserCommand: "managed-browser-helper",
169 };
170 const input = {
171 installation: { executablePath: "C:\\release\\agy.exe" },
172 profile: windowsProfile,
173 cwd: "C:\\project",
174 baseEnv: { PATH: "C:\\Windows\\system32", TEMP: "C:\\Users\\user\\AppData\\Local\\Temp" },
175 };
176 const shared = buildAntigravityAcpSpawnInput(input);
177 expect(shared.env?.TEMP).toBe(windowsProfile.tempDirectory);
178 expect(shared.env?.TMP).toBe(windowsProfile.tempDirectory);
179 const perRun = buildAntigravityAcpSpawnInput({
180 ...input,
181 runtimeTempDirectory: `${windowsProfile.tempDirectory}\\run-1`,
182 });
183 expect(perRun.env?.TEMP).toBe(`${windowsProfile.tempDirectory}\\run-1`);
184 expect(perRun.env?.TMP).toBe(`${windowsProfile.tempDirectory}\\run-1`);
185 });
186
187 it.effect("keeps accounts separate even when instance IDs differ only by case", () =>
188 Effect.gen(function* () {
189 const first = yield* resolveAntigravityInstanceDirectories(
190 "/userdata",
191 ProviderInstanceId.make("antigravity"),
192 );
193 const second = yield* resolveAntigravityInstanceDirectories(
194 "/userdata",
195 ProviderInstanceId.make("Antigravity"),
196 );
197 expect(first.profile).toBe(
198 "/userdata/providers/antigravity/ac0a3dfd6dddb20962cecff6ee5fe65e19d3923be20e52c5ab52ff877f7e4c32",
199 );
200 expect(first.profile.toLowerCase()).not.toBe(second.profile.toLowerCase());
201 expect(first.runtimeTemp.toLowerCase()).not.toBe(second.runtimeTemp.toLowerCase());
202 }).pipe(Effect.provide(Layer.mergeAll(NodeCrypto.layer, NodePath.layerPosix))),
203 );
204
205 it.effect("keeps the unpacked Windows runtime under MAX_PATH for long user names", () =>
206 Effect.gen(function* () {
207 const path = yield* Path.Path;
208 // Deepest member of the official agy_acp_server_1.1.1 windows-x86_64 bundle.
209 const deepestMember =
210 "google3\\cloud\\developer_experience\\antigravity_extensions\\acp_server\\_private__agy_acp_server_bin.lazy_imports_info.json";
211 const directories = yield* resolveAntigravityInstanceDirectories(
212 "C:\\Users\\a-twenty-char-person\\.t3\\userdata",
213 ProviderInstanceId.make("antigravity"),
214 );
215 const extracted = (tempDirectory: string) =>
216 path.join(tempDirectory, "run-AbC123", "_MEI000012ab2", deepestMember);
217 // MAX_PATH is 260 including the terminating NUL.
218 expect(extracted(directories.runtimeTemp).length).toBeLessThan(260);
219 expect(
220 extracted(path.join(directories.profile, "antigravity-acp", "tmp")).length,
221 ).toBeGreaterThanOrEqual(260);
222 }).pipe(Effect.provide(Layer.mergeAll(NodeCrypto.layer, NodePath.layerWin32))),
223 );
224 });
225
226 describe("Antigravity authorization URL", () => {
227 it.effect(
228 "rejects other origins, ambiguous state, and non-loopback redirects without retaining them",
229 () =>
230 Effect.gen(function* () {
231 const invalidUrls = [
232 authorizationUrl.replace("https:", "http:"),
233 authorizationUrl.replace("accounts.google.com", "accounts.google.com.example.invalid"),
234 authorizationUrl.replace("accounts.google.com", "secret@accounts.google.com"),
235 authorizationUrl.replace("/o/oauth2/v2/auth", "/another-path"),
236 `${authorizationUrl}#secret-fragment`,
237 `${authorizationUrl}&state=another-state`,
238 authorizationUrl.replace("test-opaque-state", ""),
239 authorizationUrl.replace("test-opaque-state", "opaque%0astate"),
240 authorizationUrl.replace("127.0.0.1", "localhost"),
241 authorizationUrl.replace("127.0.0.1", "169.254.169.254"),
242 authorizationUrl.replace("46353", "80"),
243 authorizationUrl.replace("46353", "70000"),
244 authorizationUrl.replace("46353%2F", "46353%2Fother"),
245 authorizationUrl.replace("response_type=code", "response_type=token"),
246 "not a URL containing secret-code",
247 ];
248 for (const invalidUrl of invalidUrls) {
249 const result = yield* parseAntigravityAuthorizationUrl(invalidUrl).pipe(Effect.result);
250 expect(Result.isFailure(result)).toBe(true);
251 if (Result.isSuccess(result)) continue;
252 expect(result.failure._tag).toBe("AcpTransportError");
253 expect(encodeUnknownJson(result.failure)).not.toContain("test-opaque-state");
254 expect(encodeUnknownJson(result.failure)).not.toContain("secret-code");
255 expect(encodeUnknownJson(result.failure)).not.toContain(invalidUrl);
256 }
257 }),
258 );
259 });
260
261 describe("Antigravity code sign-in", () => {
262 const loginUrl =
263 "https://accounts.google.com/o/oauth2/auth?access_type=offline&code_challenge_method=S256&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&response_type=code&state=login-state";
264
265 it.effect("accepts the agy CLI's link and only a code or page URL for that sign-in", () =>
266 Effect.gen(function* () {
267 const pending = yield* parseAntigravityAuthorizationUrl(loginUrl, "code");
268 expect(pending.redirectUri).toBe("https://antigravity.google/oauth-callback");
269 for (const other of [
270 loginUrl.replace("antigravity.google", "antigravity.google.example.invalid"),
271 loginUrl.replace("/o/oauth2/auth", "/o/oauth2/v2/auth"),
272 ]) {
273 expect(
274 Result.isFailure(
275 yield* parseAntigravityAuthorizationUrl(other, "code").pipe(Effect.result),
276 ),
277 ).toBe(true);
278 }
279 expect(
280 Result.isFailure(yield* parseAntigravityAuthorizationUrl(loginUrl).pipe(Effect.result)),
281 ).toBe(true);
282
283 const page = "https://antigravity.google/oauth-callback?state=login-state&code=4%2F0Ab-c";
284 expect(antigravityLoginResponse(pending, " 4/0Ab-code_1.x~ ")).toBe("4/0Ab-code_1.x~");
285 expect(antigravityLoginResponse(pending, page)).toBe(page);
286 for (const invalid of [
287 "",
288 "4/0Ab code",
289 "4/0Ab\nsecond line",
290 page.replace("login-state", "other-state"),
291 page.replace("antigravity.google", "evil.example"),
292 page.replace("&code=4%2F0Ab-c", ""),
293 `${page}&code=again`,
294 ]) {
295 expect(antigravityLoginResponse(pending, invalid)).toBeUndefined();
296 }
297 }),
298 );
299 });
300
301 describe("Antigravity sign-in errors", () => {
302 it("recognizes native auth-required errors and the blocked-login transport error", () => {
303 expect(isAntigravitySignInRequiredError(AcpErrors.AcpRequestError.authRequired())).toBe(true);
304 // The 1.5 CLI's `authenticate` answer when it has no sign-in and no display to open a browser on.
305 expect(
306 isAntigravitySignInRequiredError(
307 AcpErrors.AcpRequestError.internalError(
308 "No browser is available here (no graphical display is available to open a browser). Run `agy acp --login` in a terminal on this machine, then retry; or use a Gemini API key.",
309 ),
310 ),
311 ).toBe(true);
312 expect(
313 isAntigravitySignInRequiredError(
314 new AcpErrors.AcpTransportError({
315 detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
316 cause: undefined,
317 }),
318 ),
319 ).toBe(true);
320 });
321
322 it("does not treat other failures or arbitrary text as missing authentication", () => {
323 const otherErrors = [
324 new AcpErrors.AcpTransportError({ detail: "The process stopped.", cause: undefined }),
325 AcpErrors.AcpRequestError.internalError(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE),
326 new Error(ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE),
327 { detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE },
328 ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
329 undefined,
330 ];
331 for (const error of otherErrors) expect(isAntigravitySignInRequiredError(error)).toBe(false);
332 });
333 });
334
335 describe("Antigravity stdout compatibility", () => {
336 it.effect(
337 "handles fragmented login lines between JSON messages without changing protocol bytes",
338 () =>
339 Effect.gen(function* () {
340 const urls: string[] = [];
341 const jsonBefore = '{"jsonrpc":"2.0","id":1,"result":{}}\r\n';
342 const jsonAfter = '{"jsonrpc":"2.0","id":2,"result":{"text":"café"}}\n';
343 const chunks = [
344 encode(`${jsonBefore}${ANTIGRAVITY_AUTH_STDOUT_PREFIX.slice(0, 7)}`),
345 encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX.slice(7)),
346 encode(authorizationUrl.slice(0, 40)),
347 encode(`${authorizationUrl.slice(40)}\r`),
348 encode(`\n${jsonAfter}`),
349 ];
350 const result = yield* makeAntigravityStdoutTransform({
351 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
352 })(Stream.fromIterable(chunks)).pipe(Stream.decodeText(), Stream.mkString);
353 expect(result).toBe(`${jsonBefore}${jsonAfter}`);
354 expect(urls).toEqual([authorizationUrl]);
355 }),
356 );
357
358 it.effect("ends normal work with a safe sign-in error instead of waiting for OAuth", () =>
359 Effect.gen(function* () {
360 const result = yield* makeAntigravityStdoutTransform()(Stream.make(encode(authLine))).pipe(
361 Stream.runDrain,
362 Effect.result,
363 );
364 expect(Result.isFailure(result)).toBe(true);
365 if (Result.isSuccess(result)) return;
366 expect(result.failure).toMatchObject({
367 _tag: "AcpTransportError",
368 detail: ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE,
369 });
370 expect(encodeUnknownJson(result.failure)).not.toContain(authorizationUrl);
371 expect(encodeUnknownJson(result.failure)).not.toContain("test-opaque-state");
372 }),
373 );
374
375 it.effect("preserves typed errors from the flow owner", () =>
376 Effect.gen(function* () {
377 const failure = new AcpErrors.AcpTransportError({
378 detail: "This sign-in flow has expired.",
379 cause: undefined,
380 });
381 const result = yield* makeAntigravityStdoutTransform({
382 onAuthorizationUrl: () => Effect.fail(failure),
383 })(Stream.make(encode(authLine))).pipe(Stream.runDrain, Effect.result);
384 expect(Result.isFailure(result)).toBe(true);
385 if (Result.isSuccess(result)) return;
386 expect(result.failure).toBe(failure);
387 }),
388 );
389
390 it.effect("does not suppress malformed protocol data or similar login messages", () =>
391 Effect.gen(function* () {
392 const unrelated = [
393 "this is not JSON\n",
394 `${ANTIGRAVITY_AUTH_STDOUT_PREFIX.toLowerCase()}${authorizationUrl}\n`,
395 ` ${authLine}`,
396 ];
397 for (const line of unrelated) {
398 const transform = makeAntigravityStdoutTransform();
399 const output = yield* transform(Stream.make(encode(line))).pipe(
400 Stream.decodeText(),
401 Stream.mkString,
402 );
403 expect(output).toBe(line);
404 const decoded = yield* transform(Stream.make(encode(line))).pipe(
405 Stream.pipeThroughChannel(Ndjson.decode()),
406 Stream.runDrain,
407 Effect.result,
408 );
409 expect(Result.isFailure(decoded)).toBe(true);
410 }
411 }),
412 );
413
414 it.effect("bounds unfinished protocol lines", () =>
415 Effect.gen(function* () {
416 const result = yield* makeAntigravityStdoutTransform()(
417 Stream.make(new Uint8Array(16 * 1024 * 1024), encode("x")),
418 ).pipe(Stream.runDrain, Effect.result);
419 expect(Result.isFailure(result)).toBe(true);
420 if (Result.isSuccess(result)) return;
421 expect(result.failure).toMatchObject({
422 _tag: "AcpTransportError",
423 detail: "Antigravity sent a protocol line that is too large.",
424 });
425 }),
426 );
427 });
428
429 describe("Antigravity stderr compatibility", () => {
430 it.effect("forwards fragmented native sign-in URLs from runtime 1.1.1", () =>
431 Effect.gen(function* () {
432 const urls: string[] = [];
433 const line = `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\r\n`;
434 const handleStderr = makeAntigravityStderrHandler({
435 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
436 });
437 yield* handleStderr(`native log\n${line.slice(0, 40)}`);
438 yield* handleStderr(line.slice(40, 90));
439 yield* handleStderr(`${line.slice(90)}another native log\n`);
440 expect(urls).toEqual([authorizationUrl]);
441 }),
442 );
443
444 it.effect("rejects interactive sign-in during normal work", () =>
445 Effect.gen(function* () {
446 const handleStderr = makeAntigravityStderrHandler();
447 const error = yield* handleStderr(
448 `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`,
449 ).pipe(Effect.flip);
450 expect(isAntigravitySignInRequiredError(error)).toBe(true);
451 }),
452 );
453
454 it.effect("forwards an accepted browser-helper URL larger than 8 KiB", () =>
455 Effect.gen(function* () {
456 const urls: string[] = [];
457 const longAuthorizationUrl = `${authorizationUrl}&scope=${"a".repeat(9_000)}`;
458 const handleStderr = makeAntigravityStderrHandler({
459 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
460 });
461
462 expect(longAuthorizationUrl.length).toBeGreaterThan(8_192);
463 yield* handleStderr(
464 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson(longAuthorizationUrl)}\n`,
465 );
466
467 expect(urls).toEqual([longAuthorizationUrl]);
468 }),
469 );
470
471 it.effect("forwards a fragmented browser-helper URL without exposing other stderr", () =>
472 Effect.gen(function* () {
473 const urls: string[] = [];
474 const markerLine = `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson(authorizationUrl)}\n`;
475 const handleStderr = makeAntigravityStderrHandler({
476 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
477 });
478
479 yield* handleStderr(`native log\n${markerLine.slice(0, 12)}`);
480 yield* handleStderr(markerLine.slice(12, 70));
481 yield* handleStderr(`${markerLine.slice(70)}another native log\n`);
482
483 expect(urls).toEqual([authorizationUrl]);
484 }),
485 );
486
487 it.effect("ignores malformed and similar browser-helper messages", () =>
488 Effect.gen(function* () {
489 const urls: string[] = [];
490 const handleStderr = makeAntigravityStderrHandler({
491 onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)),
492 });
493
494 yield* handleStderr(
495 ` ${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson(authorizationUrl)}\n`,
496 );
497 yield* handleStderr(`${ANTIGRAVITY_AUTH_BROWSER_MARKER}${authorizationUrl}\n`);
498 yield* handleStderr(
499 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeUnknownJson("https://example.com")}\n`,
500 );
501 yield* handleStderr(`${ANTIGRAVITY_AUTH_STDOUT_PREFIX}https://example.com\n`);
502 yield* handleStderr(` ${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`);
503
504 expect(urls).toEqual([]);
505 }),
506 );
507 });
508
509 it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => {
510 const prepareSpawn = Effect.fn(function* (
511 bundles: ReadonlyArray<string>,
512 baseEnv: NodeJS.ProcessEnv = {},
513 platform: NodeJS.Platform = "linux",
514 ) {
515 const fs = yield* FileSystem.FileSystem;
516 const path = yield* Path.Path;
517 const directory = yield* fs.makeTempDirectoryScoped();
518 const profile = yield* prepareAntigravityProfile({
519 profileDirectory: path.join(directory, "profile"),
520 userHome: path.join(directory, "home"),
521 runtimeExecutablePath: process.execPath,
522 platform,
523 baseEnv,
524 }).pipe(
525 Effect.provideService(FileSystem.FileSystem, {
526 ...fs,
527 exists: (candidate) => Effect.succeed(bundles.includes(candidate)),
528 }),
529 );
530 return buildAntigravityAcpSpawnInput({
531 installation: { executablePath: "/usr/bin/agy" },
532 profile,
533 cwd: directory,
534 baseEnv,
535 }).env;
536 });
537
538 // A Windows Node path cannot preflight the browser helper as a POSIX host.
539 const caTest = it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32");
540
541 caTest(
542 "launches Linux agents with the first available CA bundle, preferring absolute Nix paths",
543 () =>
544 Effect.gen(function* () {
545 const systemBundles = ["/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem"];
546 const nixBundle = "/nix/store/nss-cacert/etc/ssl/certs/ca-bundle.crt";
547 expect((yield* prepareSpawn(systemBundles))?.SSL_CERT_FILE).toBe(systemBundles[0]);
548 expect(
549 (yield* prepareSpawn([nixBundle, ...systemBundles], { NIX_SSL_CERT_FILE: nixBundle }))
550 ?.SSL_CERT_FILE,
551 ).toBe(nixBundle);
552 expect(
553 (yield* prepareSpawn(systemBundles, { NIX_SSL_CERT_FILE: nixBundle }))?.SSL_CERT_FILE,
554 ).toBe(systemBundles[0]);
555 expect(
556 (yield* prepareSpawn(["certs/local.pem", ...systemBundles], {
557 NIX_SSL_CERT_FILE: "certs/local.pem",
558 }))?.SSL_CERT_FILE,
559 ).toBe(systemBundles[0]);
560 expect((yield* prepareSpawn([]))?.SSL_CERT_FILE).toBeUndefined();
561 }),
562 );
563
564 caTest("preserves explicit certificate files and directories in Linux launches", () =>
565 Effect.gen(function* () {
566 const bundles = ["/etc/ssl/certs/ca-certificates.crt"];
567 expect(
568 (yield* prepareSpawn(bundles, { SSL_CERT_FILE: "/custom/ca.pem" }))?.SSL_CERT_FILE,
569 ).toBe("/custom/ca.pem");
570 const directoryEnv = yield* prepareSpawn(bundles, { SSL_CERT_DIR: "/custom/certs" });
571 expect(directoryEnv?.SSL_CERT_DIR).toBe("/custom/certs");
572 expect(directoryEnv?.SSL_CERT_FILE).toBeUndefined();
573 }),
574 );
575
576 it.effect("runs the browser helper with installed Node in standalone builds", () =>
577 Effect.gen(function* () {
578 const fs = yield* FileSystem.FileSystem;
579 const path = yield* Path.Path;
580 const directory = yield* fs.makeTempDirectoryScoped();
581 const profile = yield* prepareAntigravityProfile({
582 profileDirectory: path.join(directory, "profile"),
583 baseEnv: { PATH: path.dirname(process.execPath) },
584 });
585 expect(profile.browserCommand).not.toContain("/packaged/t3");
586 expect(yield* fs.exists(profile.acpDirectory)).toBe(true);
587 }).pipe(
588 Effect.provideService(HostProcess.IsExecutable, true),
589 Effect.provideService(HostProcess.ExecutablePath, "/packaged/t3"),
590 ),
591 );
592
593 it.effect("reports missing Node before creating the standalone sign-in profile", () =>
594 Effect.gen(function* () {
595 const fs = yield* FileSystem.FileSystem;
596 const path = yield* Path.Path;
597 const directory = yield* fs.makeTempDirectoryScoped();
598 const profileDirectory = path.join(directory, "profile");
599 const result = yield* prepareAntigravityProfile({
600 profileDirectory,
601 baseEnv: { PATH: "" },
602 }).pipe(Effect.result);
603 expect(Result.isFailure(result)).toBe(true);
604 if (Result.isFailure(result)) {
605 expect(result.failure).toMatchObject({
606 _tag: "AcpTransportError",
607 detail: expect.stringContaining("Install Node.js"),
608 cause: {
609 _tag: "NodeRuntimeUnavailableError",
610 },
611 });
612 }
613 expect(yield* fs.exists(profileDirectory)).toBe(false);
614 }).pipe(Effect.provideService(HostProcess.IsExecutable, true)),
615 );
616
617 it.effect("preflights the no-browser helper and creates private directories only", () =>
618 Effect.gen(function* () {
619 const fs = yield* FileSystem.FileSystem;
620 const path = yield* Path.Path;
621 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
622 const profile = yield* prepareAntigravityProfile({
623 profileDirectory: path.join(temporaryDirectory, "profile"),
624 });
625
626 expect(profile.geminiHome).toBe(path.join(temporaryDirectory, "profile"));
627 expect(yield* fs.exists(profile.acpDirectory)).toBe(true);
628 expect(yield* fs.exists(profile.tokenPath)).toBe(false);
629 if ((yield* HostProcess.Platform) !== "win32") {
630 expect((yield* fs.stat(profile.geminiHome)).mode & 0o777).toBe(0o700);
631 expect((yield* fs.stat(profile.acpDirectory)).mode & 0o777).toBe(0o700);
632 }
633
634 yield* fs.writeFileString(profile.tokenPath, "synthetic-token-fixture");
635 yield* prepareAntigravityProfile({ profileDirectory: profile.geminiHome });
636 expect(yield* fs.readFileString(profile.tokenPath)).toBe("synthetic-token-fixture");
637 }),
638 );
639
640 it.effect.skipIf(!symlinksSupported)(
641 "links only the user's existing global skill directories without touching real content",
642 () =>
643 Effect.gen(function* () {
644 const fs = yield* FileSystem.FileSystem;
645 const path = yield* Path.Path;
646 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
647 const userHome = path.join(temporaryDirectory, "home");
648 const profileDirectory = path.join(temporaryDirectory, "profile");
649 const configSkills = path.join(userHome, ".gemini", "config", "skills");
650 const cliSkills = path.join(userHome, ".gemini", "antigravity-cli", "skills");
651 const isLink = (link: string) =>
652 fs.readLink(link).pipe(
653 Effect.as(true),
654 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
655 );
656 yield* fs.makeDirectory(path.join(configSkills, "review"), { recursive: true });
657
658 yield* prepareAntigravityProfile({ profileDirectory, userHome });
659 const configLink = path.join(profileDirectory, "config", "skills");
660 const cliLink = path.join(profileDirectory, "antigravity-cli", "skills");
661 expect(yield* fs.readLink(configLink)).toBe(configSkills);
662 expect(yield* isLink(cliLink)).toBe(false);
663 expect(yield* fs.exists(path.join(configLink, "review"))).toBe(true);
664 expect(yield* fs.exists(path.join(profileDirectory, "config", "mcp_config.json"))).toBe(
665 false,
666 );
667
668 // The harness leaves an empty folder where the link was skipped.
669 yield* fs.makeDirectory(cliLink, { recursive: true });
670 yield* prepareAntigravityProfile({ profileDirectory, userHome });
671 expect((yield* fs.stat(cliLink)).type).toBe("Directory");
672
673 yield* fs.makeDirectory(cliSkills, { recursive: true });
674 yield* fs.remove(configLink);
675 yield* fs.makeDirectory(path.join(configLink, "own-skill"), { recursive: true });
676 yield* prepareAntigravityProfile({ profileDirectory, userHome });
677 expect(yield* fs.readLink(cliLink)).toBe(cliSkills);
678 expect(yield* fs.exists(path.join(configLink, "own-skill"))).toBe(true);
679 expect((yield* fs.stat(configLink)).type).toBe("Directory");
680
681 yield* fs.remove(cliLink);
682 yield* fs.symlink(path.join(temporaryDirectory, "elsewhere"), cliLink);
683 yield* prepareAntigravityProfile({ profileDirectory, userHome });
684 expect(yield* fs.readLink(cliLink)).toBe(cliSkills);
685
686 yield* fs.remove(cliSkills, { recursive: true });
687 yield* prepareAntigravityProfile({ profileDirectory, userHome });
688 expect(yield* isLink(cliLink)).toBe(false);
689 }),
690 );
691
692 it.effect.skipIf(!symlinksSupported)(
693 "links the user's global rule files and never replaces the profile's own",
694 () =>
695 Effect.gen(function* () {
696 const fs = yield* FileSystem.FileSystem;
697 const path = yield* Path.Path;
698 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
699 const userHome = path.join(temporaryDirectory, "home");
700 const profileDirectory = path.join(temporaryDirectory, "profile");
701 const userGemini = path.join(userHome, ".gemini");
702 yield* fs.makeDirectory(path.join(userGemini, "config"), { recursive: true });
703 yield* fs.writeFileString(path.join(userGemini, "AGENTS.md"), "global agents rule");
704 yield* fs.writeFileString(path.join(userGemini, "GEMINI.md"), "global gemini rule");
705 yield* fs.writeFileString(
706 path.join(userGemini, "config", "skills.json"),
707 JSON.stringify({ entries: [{ path: "/tmp/shared-skills" }] }),
708 );
709
710 yield* prepareAntigravityProfile({ profileDirectory, userHome });
711 expect(yield* fs.readLink(path.join(profileDirectory, "AGENTS.md"))).toBe(
712 path.join(userGemini, "AGENTS.md"),
713 );
714 expect(yield* fs.readLink(path.join(profileDirectory, "GEMINI.md"))).toBe(
715 path.join(userGemini, "GEMINI.md"),
716 );
717 expect(yield* fs.readLink(path.join(profileDirectory, "config", "skills.json"))).toBe(
718 path.join(userGemini, "config", "skills.json"),
719 );
720
721 yield* fs.remove(path.join(userGemini, "AGENTS.md"));
722 yield* fs.remove(path.join(userGemini, "config", "skills.json"));
723 yield* fs.remove(path.join(profileDirectory, "GEMINI.md"));
724 yield* fs.writeFileString(path.join(profileDirectory, "GEMINI.md"), "profile's own rule");
725 yield* prepareAntigravityProfile({ profileDirectory, userHome });
726 expect(yield* fs.exists(path.join(profileDirectory, "AGENTS.md"))).toBe(false);
727 expect(yield* fs.exists(path.join(profileDirectory, "config", "skills.json"))).toBe(false);
728 expect(yield* fs.readFileString(path.join(profileDirectory, "GEMINI.md"))).toBe(
729 "profile's own rule",
730 );
731 }),
732 );
733
734 it.effect("copies the user's global rule files on Windows and keeps the profile's own", () =>
735 Effect.gen(function* () {
736 const fs = yield* FileSystem.FileSystem;
737 const path = yield* Path.Path;
738 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
739 const userHome = path.join(temporaryDirectory, "home");
740 const profileDirectory = path.join(temporaryDirectory, "profile");
741 const userGemini = path.join(userHome, ".gemini");
742 const prepare = prepareAntigravityProfile({ profileDirectory, userHome, platform: "win32" });
743 const profileAgents = path.join(profileDirectory, "AGENTS.md");
744 const profileGemini = path.join(profileDirectory, "GEMINI.md");
745 const profileSkillsJson = path.join(profileDirectory, "config", "skills.json");
746 const userSkillsJson = path.join(userGemini, "config", "skills.json");
747 yield* fs.makeDirectory(path.join(userGemini, "config"), { recursive: true });
748 yield* fs.writeFileString(path.join(userGemini, "AGENTS.md"), "global agents rule");
749 yield* fs.writeFileString(path.join(userGemini, "GEMINI.md"), "global gemini rule");
750 yield* fs.writeFileString(userSkillsJson, '{"entries":[]}');
751
752 yield* prepare;
753 expect(yield* fs.readFileString(profileAgents)).toBe("global agents rule");
754 expect(yield* fs.readFileString(profileGemini)).toBe("global gemini rule");
755 expect(yield* fs.readFileString(profileSkillsJson)).toBe('{"entries":[]}');
756
757 yield* fs.writeFileString(path.join(userGemini, "AGENTS.md"), "edited agents rule");
758 yield* fs.remove(path.join(userGemini, "GEMINI.md"));
759 yield* fs.writeFileString(userSkillsJson, '{"entries":[{"path":"/skills"}]}');
760 yield* prepare;
761 expect(yield* fs.readFileString(profileAgents)).toBe("edited agents rule");
762 expect(yield* fs.exists(profileGemini)).toBe(false);
763 expect(yield* fs.readFileString(profileSkillsJson)).toBe('{"entries":[{"path":"/skills"}]}');
764
765 yield* fs.writeFileString(profileGemini, "profile's own rule");
766 yield* fs.writeFileString(path.join(userGemini, "GEMINI.md"), "global gemini rule");
767 yield* fs.remove(userSkillsJson);
768 yield* prepare;
769 expect(yield* fs.readFileString(profileGemini)).toBe("profile's own rule");
770 expect(yield* fs.exists(profileSkillsJson)).toBe(false);
771 }),
772 );
773
774 it.effect("rewrites the GCP block on every launch and never stores the API key", () =>
775 Effect.gen(function* () {
776 const fs = yield* FileSystem.FileSystem;
777 const path = yield* Path.Path;
778 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
779 const profile = yield* prepareAntigravityProfile({
780 profileDirectory: temporaryDirectory,
781 auth: {
782 authMethod: "agent-platform",
783 apiKey: "vertex-secret",
784 gcpProject: "proj",
785 gcpLocation: "us-central1",
786 },
787 });
788 const settingsPath = path.join(profile.acpDirectory, "settings.json");
789 const first = yield* fs.readFileString(settingsPath);
790 expect(decodeJson(first)).toEqual({
791 auth: { type: "agent-platform" },
792 gcp: { project: "proj", location: "us-central1" },
793 });
794 expect(first).not.toContain("vertex-secret");
795
796 yield* prepareAntigravityProfile({ profileDirectory: temporaryDirectory });
797 expect(decodeJson(yield* fs.readFileString(settingsPath))).toEqual({
798 auth: { type: "oauth-personal" },
799 });
800 }),
801 );
802
803 const preflightHelper = (exitDelay: Effect.Effect<void>) => {
804 const spawns = { count: 0 };
805 const started = Deferred.makeUnsafe<void>();
806 const spawner = ChildProcessSpawner.make(() =>
807 Effect.sync(() => {
808 spawns.count += 1;
809 return ChildProcessSpawner.makeHandle({
810 pid: ChildProcessSpawner.ProcessId(1),
811 exitCode: Deferred.succeed(started, undefined).pipe(
812 Effect.andThen(exitDelay),
813 Effect.as(ChildProcessSpawner.ExitCode(0)),
814 ),
815 isRunning: Effect.succeed(false),
816 kill: () => Effect.void,
817 unref: Effect.succeed(Effect.void),
818 stdin: Sink.drain,
819 stdout: Stream.empty,
820 stderr: Stream.encodeText(
821 Stream.make(
822 `${ANTIGRAVITY_AUTH_BROWSER_MARKER}"https://example.invalid/t3-antigravity-browser-preflight"\n`,
823 ),
824 ),
825 all: Stream.empty,
826 getInputFd: () => Sink.drain,
827 getOutputFd: () => Stream.empty,
828 });
829 }),
830 );
831 return { spawner, spawns, started };
832 };
833
834 const prepareWithHelper = Effect.fn("prepareWithHelper")(function* (
835 runtimeExecutablePath: string,
836 spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
837 ) {
838 const fs = yield* FileSystem.FileSystem;
839 const path = yield* Path.Path;
840 const directory = yield* fs.makeTempDirectoryScoped();
841 return yield* prepareAntigravityProfile({
842 profileDirectory: path.join(directory, "profile"),
843 userHome: path.join(directory, "home"),
844 runtimeExecutablePath,
845 platform: "linux",
846 baseEnv: {},
847 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
848 });
849
850 it.effect("allows a browser preflight that takes longer than five seconds", () =>
851 Effect.gen(function* () {
852 const helper = preflightHelper(Effect.sleep("20 seconds"));
853 const fiber = yield* prepareWithHelper("/fake/slow-node", helper.spawner).pipe(
854 Effect.forkChild,
855 );
856 yield* Deferred.await(helper.started);
857 yield* TestClock.adjust("20 seconds");
858 yield* Fiber.join(fiber);
859
860 expect(helper.spawns.count).toBe(1);
861 }),
862 );
863
864 it.effect("fails a hung preflight after 30 seconds and verifies again on the next open", () =>
865 Effect.gen(function* () {
866 const hung = preflightHelper(Effect.never);
867 const fiber = yield* prepareWithHelper("/fake/hung-node", hung.spawner).pipe(
868 Effect.result,
869 Effect.forkChild,
870 );
871 yield* Deferred.await(hung.started);
872 yield* TestClock.adjust("29 seconds");
873 expect(fiber.pollUnsafe()).toBeUndefined();
874 yield* TestClock.adjust("1 second");
875 const result = yield* Fiber.join(fiber);
876 expect(Result.isFailure(result)).toBe(true);
877 if (Result.isFailure(result)) {
878 expect(result.failure).toMatchObject({
879 _tag: "AcpTransportError",
880 detail: "Antigravity browser suppression verification timed out.",
881 });
882 }
883
884 const recovered = preflightHelper(Effect.void);
885 yield* prepareWithHelper("/fake/hung-node", recovered.spawner);
886 expect(recovered.spawns.count).toBe(1);
887 }),
888 );
889
890 it.effect("rejects Python BROWSER delimiter collisions before starting a helper", () =>
891 Effect.gen(function* () {
892 const fs = yield* FileSystem.FileSystem;
893 const path = yield* Path.Path;
894 const temporaryDirectory = yield* fs.makeTempDirectoryScoped();
895 for (const platform of ["linux", "win32"] as const) {
896 const profileDirectory = path.join(temporaryDirectory, platform);
897 const result = yield* prepareAntigravityProfile({
898 profileDirectory,
899 platform,
900 runtimeExecutablePath: platform === "win32" ? "C:/bad;path/node.exe" : "/bad:path/node",
901 }).pipe(Effect.result);
902 expect(Result.isFailure(result)).toBe(true);
903 expect(yield* fs.exists(profileDirectory)).toBe(false);
904 }
905 }),
906 );
907 });