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

antigravityAuthSupport.test.ts

614 lines23.6 KB

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