Repository navigation
Expand file tree
/
Copy pathantigravity.test.ts
More file actions
1312 lines (1242 loc) · 63.4 KB
/
Copy pathantigravity.test.ts
File metadata and controls
1312 lines (1242 loc) · 63.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { afterEach, describe, expect, it, vi } from "vitest";
import { DATA_DIR, ensureDirs } from "../config.ts";
import { TurnNotStartedError, type ProviderInstance } from "../contracts.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import * as procs from "../procs.ts";
import { botBox } from "../bot-box/box.ts";
import { dialRelay, openBoxRelay } from "../bot-box/relay.ts";
import * as envPath from "../env-path.ts";
import * as managedRuntime from "./antigravity-runtime.ts";
import {
ANTIGRAVITY_AUTH_PREFIX,
AntigravityAcpClient,
AntigravityAuthController,
antigravityProfileAuthenticated,
antigravityProfileDirectory,
authorizationUrlFromLine,
catalogFromAntigravityConfigOptions,
isValidAntigravityInitializeResult,
parseAntigravityAuthorizationUrl,
prepareAntigravityProfile,
probeAntigravityModels,
validateAntigravityCallbackUrl,
validateAntigravityRuntime,
} from "./antigravity-acp.ts";
import {
ANTIGRAVITY_RELEASE_VERSION,
resolveAntigravityReleaseAsset,
type AntigravityReleaseAsset,
} from "./antigravity-release.ts";
import { installAntigravityRuntime, resolveAntigravityRuntime } from "./antigravity-runtime.ts";
import * as antigravityTemp from "./antigravity-temp.ts";
import { VERIFICATION_TEMP_KEY, antigravityTempDir, sweepAntigravityTemp } from "./antigravity-temp.ts";
import {
AntigravityDriver,
STATIC_ANTIGRAVITY_MODELS,
antigravityPermissionMode,
normalizeAntigravityTurn,
} from "./antigravity.ts";
const FAKE_ACP = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-acp-cli.ts");
const FAKE_SIGNIN = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-antigravity-signin.ts");
const scratch: string[] = [];
function fakeRuntime(startupDelayMs = 0): { directory: string; executable: string; harness: string } {
const directory = mkdtempSync(join(tmpdir(), "omb-antigravity-acp-"));
scratch.push(directory);
const executable = join(directory, "fake-antigravity.ts");
const harness = join(directory, process.platform === "win32" ? "localharness_external.exe" : "localharness_external");
copyFileSync(FAKE_ACP, executable);
if (startupDelayMs) {
writeFileSync(executable, `#!/usr/bin/env node\nsetTimeout(() => import(${JSON.stringify(pathToFileURL(FAKE_ACP).href)}), ${startupDelayMs});\n`);
}
copyFileSync(FAKE_ACP, harness);
if (process.platform !== "win32") {
chmodSync(executable, 0o755);
chmodSync(harness, 0o755);
}
return { directory, executable, harness };
}
afterEach(async () => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
delete process.env.FAKE_ACP_AUTH_METHOD;
delete process.env.FAKE_ACP_MODELS;
delete process.env.FAKE_ACP_MODES;
delete process.env.FAKE_ACP_DUMP;
delete process.env.FAKE_ACP_PAD_QUESTION_OPTION;
while (scratch.length) await removeTempDir(scratch.pop()!);
});
describe("official Antigravity catalog", () => {
it("uses current Gemini 3.8 variants as the offline fallback", () => {
expect(STATIC_ANTIGRAVITY_MODELS).toEqual({
default: "gemini-3.8-flash",
options: [
{
id: "gemini-3.8-flash",
label: "Gemini 3.8 Flash",
variants: [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High" },
],
},
],
});
});
it("reads the authenticated account catalog from ACP config options", () => {
const options = [{
id: "model",
type: "select",
currentValue: "account-low",
options: [
{ value: "account-high", name: "Account High" },
{ group: "More", options: [{ value: "account-low", name: "Account Low" }] },
],
}, {
id: "thinking_level",
category: "thought_level",
type: "select",
currentValue: "high",
options: [
{ value: "low", name: "Low" },
{ value: "medium", name: "Medium" },
{ value: "high", name: "High" },
],
}];
expect(catalogFromAntigravityConfigOptions(options, "missing")).toEqual({
default: "account-low",
options: [
{ id: "account-high", label: "Account High" },
{
id: "account-low",
label: "Account Low",
variants: [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High" },
],
},
],
});
});
});
describe("Antigravity sign-in lifecycle", () => {
it("preserves failed setup errors until retry or external recovery, without reviving stale errors", async () => {
if (!resolveAntigravityReleaseAsset()) return;
const fake = fakeRuntime();
const custom = join(fake.directory, "not-installed");
const install = vi.spyOn(managedRuntime, "installAntigravityRuntime")
.mockRejectedValueOnce(new Error("Antigravity initialization timed out: fixture failure"));
const instance = await AntigravityDriver.create({
instanceId: "failed-antigravity-install",
displayName: "Antigravity fixture", enabled: true,
config: { cli: custom, fullAuto: false },
environment: {},
});
try {
await expect(instance.installRuntime!()).rejects.toThrow("fixture failure");
expect(await instance.snapshot()).toEqual({ state: "unavailable", reason: "Antigravity initialization timed out: fixture failure" });
expect((await instance.snapshot()).reason).toContain("fixture failure");
// A manual/shared install can recover without this instance retrying.
copyFileSync(fake.executable, custom);
if (process.platform !== "win32") chmodSync(custom, 0o755);
expect((await instance.snapshot()).state).toBe("available");
unlinkSync(custom);
const unavailable = await instance.snapshot();
expect(unavailable.state).toBe("unavailable");
expect(unavailable.reason).not.toContain("fixture failure");
install.mockRejectedValueOnce(new Error("Antigravity initialization timed out: fixture failure"));
await expect(instance.installRuntime!()).rejects.toThrow("fixture failure");
install.mockResolvedValueOnce({ executablePath: fake.executable, harnessPath: fake.harness, source: "managed", version: "1.1.1" });
await instance.installRuntime!();
expect((await instance.snapshot()).reason).not.toContain("fixture failure");
} finally {
await instance.dispose();
}
});
it("signs out by forgetting only this account's stored Google sign-in", async () => {
ensureDirs();
const fake = fakeRuntime();
const instanceId = "antigravity-sign-out";
const profile = antigravityProfileDirectory(instanceId);
const token = join(profile, "antigravity-acp", "acp_token.json");
const other = join(antigravityProfileDirectory("antigravity-other"), "antigravity-acp", "acp_token.json");
for (const file of [token, other]) {
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, "{}", { mode: 0o600 });
}
const instance = await AntigravityDriver.create({
instanceId, displayName: "Antigravity", enabled: true,
config: { cli: fake.executable, fullAuto: false },
environment: { FAKE_ACP_AUTH_METHOD: "oauth-personal" },
});
try {
expect((await instance.snapshot()).authenticated).toBe(true);
expect(instance.signOut).toBeTypeOf("function");
await instance.signOut!();
expect(existsSync(token)).toBe(false);
expect(existsSync(join(profile, "antigravity-acp", "settings.json"))).toBe(true);
expect(existsSync(other)).toBe(true);
expect((await instance.snapshot()).authenticated).toBe(false);
await instance.signOut!();
} finally {
await instance.dispose();
rmSync(profile, { recursive: true, force: true });
rmSync(antigravityProfileDirectory("antigravity-other"), { recursive: true, force: true });
}
});
it("uses the same discovered PATH for readiness and Google sign-in", async () => {
const fake = fakeRuntime();
const executable = join(fake.directory, process.platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par");
copyFileSync(fake.executable, executable);
if (process.platform !== "win32") chmodSync(executable, 0o755);
vi.stubEnv("PATH", "");
vi.spyOn(envPath, "augmentedPath").mockReturnValue(fake.directory);
const authenticate = vi.spyOn(AntigravityAuthController.prototype, "start").mockResolvedValue({
phase: "succeeded", flowId: null, authorizationUrl: null, expiresAt: null,
});
const instance = await AntigravityDriver.create({
instanceId: "path-only-antigravity",
displayName: "Antigravity fixture",
enabled: true,
config: { cli: "agy_acp_server" + (process.platform === "win32" ? ".exe" : ".par"), fullAuto: false },
environment: { PATH: "" },
});
try {
expect((await instance.snapshot()).state).toBe("available");
await expect(instance.startAuthentication!()).resolves.toMatchObject({ phase: "succeeded" });
expect(authenticate).toHaveBeenCalledWith(
expect.objectContaining({ executablePath: executable }),
expect.objectContaining({ environment: expect.objectContaining({ PATH: fake.directory }) }),
);
} finally {
await instance.dispose();
}
});
// Google's server announces the link on stderr, never stdout.
it.each(["cancel", "provider failure"])("contains %s after handing the browser a sign-in URL", async (ending) => {
const fake = fakeRuntime();
const url = "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&state=fixture&redirect_uri=http%3A%2F%2F127.0.0.1%3A54321%2F";
writeFileSync(fake.executable, `#!/usr/bin/env node
import { createInterface } from 'node:readline';
createInterface({ input: process.stdin }).on('line', line => {
const message = JSON.parse(line);
if (message.method === 'authenticate') {
console.error(${JSON.stringify(ANTIGRAVITY_AUTH_PREFIX + url)});
${ending === "provider failure" ? `setTimeout(() => console.log(JSON.stringify({ jsonrpc: '2.0', id: message.id, error: { code: -1, message: 'Sign-in expired' } })), 100);` : ""}
} else console.log(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} }));
});
`);
const runtime = await resolveAntigravityRuntime(fake.executable);
const profile = await prepareAntigravityProfile({ instanceId: "auth-lifecycle", runtime, baseDir: fake.directory });
const signedIn = vi.fn();
const controller = new AntigravityAuthController(signedIn);
try {
const flow = await controller.start(runtime, profile);
expect(flow.phase).toBe("waiting");
if (ending === "cancel") controller.cancel();
// Let rejected pending RPCs settle: Vitest must see no unhandled rejection.
await new Promise((resolve) => setTimeout(resolve, 300));
await expect(controller.complete(flow.flowId!, "http://127.0.0.1:54321/?code=test&state=fixture"))
.rejects.toThrow(/no longer active/u);
expect(signedIn).not.toHaveBeenCalled();
} finally {
controller.cancel();
}
});
it("delivers a redirect pasted from another computer to the runtime's own callback listener, and the sign-in finishes", async () => {
const fake = fakeRuntime();
writeFileSync(fake.executable, readFileSync(FAKE_SIGNIN));
const runtime = await resolveAntigravityRuntime(fake.executable);
const profile = await prepareAntigravityProfile({ instanceId: "auth-pasted", runtime, baseDir: fake.directory });
const signedIn = vi.fn();
const controller = new AntigravityAuthController(signedIn);
try {
const flow = await controller.start(runtime, profile);
const redirect = new URL(flow.authorizationUrl!).searchParams.get("redirect_uri")!;
await controller.complete(flow.flowId!, `${redirect}?state=fixture&code=pasted`);
expect(await antigravityProfileAuthenticated(profile)).toBe(true);
expect(signedIn).toHaveBeenCalledOnce();
} finally {
controller.cancel();
}
});
// A Cloud home runs the runtime in a bot box with its own network, where only the box's relay reaches its listener
// (proved against a real box in antigravity-box.linux.test.ts); here the relay's box side runs in this process.
it.skipIf(process.platform === "win32")("delivers the redirect through the box's relay when sign-in runs in a bot box, and closes the relay after", async () => {
const fake = fakeRuntime();
writeFileSync(fake.executable, readFileSync(FAKE_SIGNIN));
const runtime = await resolveAntigravityRuntime(fake.executable);
const profile = await prepareAntigravityProfile({ instanceId: "auth-relayed", runtime, baseDir: fake.directory });
const relay = await openBoxRelay(join(fake.directory, "relay.sock"));
const inBox = dialRelay(relay.socketPath, 20);
const reach = vi.spyOn(relay, "connect");
vi.spyOn(botBox, "openRelay").mockResolvedValue(relay);
const spawned = vi.spyOn(procs, "spawnCli");
const controller = new AntigravityAuthController();
try {
const flow = await controller.start(runtime, profile);
expect(spawned.mock.calls[0]![2]).toMatchObject({ box: { relay: relay.socketPath } });
const redirect = new URL(new URL(flow.authorizationUrl!).searchParams.get("redirect_uri")!);
await controller.complete(flow.flowId!, `${redirect.href}?state=fixture&code=pasted`);
expect(reach).toHaveBeenCalledWith(Number(redirect.port));
expect(await antigravityProfileAuthenticated(profile)).toBe(true);
await vi.waitFor(() => expect(existsSync(relay.socketPath)).toBe(false));
} finally {
controller.cancel();
inBox.close();
relay.close();
}
});
it("reports a sign-in Google finishes on its own, so the account's models are read", async () => {
const fake = fakeRuntime();
const url = "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&state=fixture&redirect_uri=http%3A%2F%2F127.0.0.1%3A54321%2F";
writeFileSync(fake.executable, `#!/usr/bin/env node
import { createInterface } from 'node:readline';
createInterface({ input: process.stdin }).on('line', line => {
const message = JSON.parse(line);
if (message.method === 'authenticate') {
console.error(${JSON.stringify(ANTIGRAVITY_AUTH_PREFIX + url)});
setTimeout(() => console.log(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} })), 100);
} else console.log(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} }));
});
`);
const runtime = await resolveAntigravityRuntime(fake.executable);
const profile = await prepareAntigravityProfile({ instanceId: "auth-finishes", runtime, baseDir: fake.directory });
let signedIn!: () => void;
const reported = new Promise<void>((resolve) => { signedIn = resolve; });
const controller = new AntigravityAuthController(() => signedIn());
try {
expect((await controller.start(runtime, profile)).phase).toBe("waiting");
await expect(reported).resolves.toBeUndefined();
} finally {
controller.cancel();
}
});
});
describe("stopping the runtime before touching its files", () => {
it.skipIf(process.platform === "win32")("waits through forced shutdown when the verified runtime ignores EOF and TERM", async () => {
const fake = fakeRuntime();
// Stays up after its input ends, so close() must go on to force it.
writeFileSync(fake.executable, `#!/usr/bin/env node\nprocess.on('SIGTERM', () => {});\nsetInterval(() => {}, 1 << 30);\nawait import(${JSON.stringify(pathToFileURL(FAKE_ACP).href)});\n`);
const runtime = await resolveAntigravityRuntime(fake.executable);
vi.stubEnv("FAKE_ACP_AGENT_NAME", "Google Antigravity");
vi.stubEnv("FAKE_ACP_AGENT_VERSION", "1.1.1");
vi.stubEnv("FAKE_ACP_AUTH_METHOD", "oauth-personal");
const spawned = vi.spyOn(procs, "spawnCli");
try {
await expect(validateAntigravityRuntime(runtime, "agy_acp_server_1.1.1")).resolves.toBeUndefined();
expect(spawned.mock.results[0]!.value.signalCode).toBe("SIGKILL");
} finally {
await Promise.all(spawned.mock.results.map(({ value }) => procs.killCliTree(value, 0)));
}
}, 20_000);
it("ends the runtime's input and lets it exit by itself before any forced stop", async () => {
// On Windows a forced stop skips the runtime's cleanup of what it unpacked; its own exit removes them.
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
const profile = await prepareAntigravityProfile({ instanceId: "graceful-close", runtime, baseDir: fake.directory });
const client = new AntigravityAcpClient(runtime, profile, fake.directory);
await client.initialize();
const kill = vi.spyOn(procs, "killCliTree");
client.close();
expect(client.child.stdin?.writableEnded).toBe(true);
expect(kill).not.toHaveBeenCalled();
expect(await client.closeAndWait()).toBe(true);
// Exit code 0 and no signal: not SIGTERM (POSIX) and not taskkill's 1.
expect(client.child.exitCode).toBe(0);
expect(client.child.signalCode).toBeNull();
});
it("validates a real fake runtime and waits for its process to close before returning", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
vi.stubEnv("FAKE_ACP_AGENT_NAME", "Google Antigravity");
vi.stubEnv("FAKE_ACP_AGENT_VERSION", "1.1.1");
vi.stubEnv("FAKE_ACP_AUTH_METHOD", "oauth-personal");
let sawClose = false;
const spawn = procs.spawnCli;
const spawned = vi.spyOn(procs, "spawnCli").mockImplementation((...args) => {
const child = spawn(...args);
child.once("close", () => { sawClose = true; });
return child;
});
await validateAntigravityRuntime(runtime, "agy_acp_server_1.1.1");
expect(spawned).toHaveBeenCalledTimes(1);
expect(sawClose).toBe(true);
const child = spawned.mock.results[0]!.value;
expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
});
it("closeAndWait resolves only once the process is gone, so a rename on Windows cannot hit a running executable", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
const profile = await prepareAntigravityProfile({ instanceId: "close-and-wait", runtime, baseDir: fake.directory });
const client = new AntigravityAcpClient(runtime, profile, fake.directory);
await client.initialize();
expect(client.child.exitCode).toBeNull();
expect(await client.closeAndWait()).toBe(true);
expect(client.child.exitCode !== null || client.child.signalCode !== null).toBe(true);
expect(await client.closeAndWait(100)).toBe(true);
});
});
describe("official Antigravity runtime", () => {
it("pins Google's release metadata for this supported host", () => {
const asset = resolveAntigravityReleaseAsset();
if (!asset) return;
expect(ANTIGRAVITY_RELEASE_VERSION).toBe("1.4.3");
expect(asset.version).toBe(ANTIGRAVITY_RELEASE_VERSION);
expect(asset.url).toMatch(/^https:\/\/dl\.google\.com\/agy-extensions\/releases\//u);
expect(asset.sha256).toMatch(/^[a-f0-9]{64}$/u);
expect(asset.archiveBytes).toBeGreaterThan(100_000_000);
});
function testValidatesAcpInitializeResults() {
const basePayload = {
protocolVersion: 1,
agentInfo: { name: "antigravity-acp", version: "1.1.1" },
agentCapabilities: {
loadSession: true,
sessionCapabilities: { resume: true },
auth: { logout: true },
},
authMethods: [{ id: "oauth-personal" }],
};
expect(isValidAntigravityInitializeResult(basePayload, "agy_acp_server_1.1.1")).toBe(true);
expect(isValidAntigravityInitializeResult(basePayload, "1.1.1")).toBe(true);
expect(isValidAntigravityInitializeResult({
...basePayload,
agentInfo: { name: "antigravity-acp", version: "agy_acp_server_1.1.1" },
}, "agy_acp_server_1.1.1")).toBe(true);
expect(isValidAntigravityInitializeResult({
...basePayload,
agentInfo: { name: "Google Antigravity", version: "1.1.1" },
}, "agy_acp_server_1.1.1")).toBe(true);
expect(isValidAntigravityInitializeResult({ ...basePayload, protocolVersion: 2 }, "1.1.1")).toBe(false);
expect(isValidAntigravityInitializeResult({
...basePayload,
agentInfo: { name: "rogue-agent", version: "1.1.1" },
}, "1.1.1")).toBe(false);
expect(isValidAntigravityInitializeResult({
...basePayload,
agentInfo: { name: "antigravity-acp", version: "2.0.0" },
}, "1.1.1")).toBe(false);
expect(isValidAntigravityInitializeResult({
...basePayload,
agentCapabilities: { loadSession: false, sessionCapabilities: { resume: true }, auth: { logout: true } },
}, "1.1.1")).toBe(false);
expect(isValidAntigravityInitializeResult({
...basePayload,
authMethods: [{ id: "api-key" }],
}, "1.1.1")).toBe(false);
expect(isValidAntigravityInitializeResult({
...basePayload,
agentInfo: { name: "antigravity-acp", version: 1 },
}, "1.1.1")).toBe(false);
expect(isValidAntigravityInitializeResult({
...basePayload,
agentInfo: { name: "antigravity-acp", version: null },
}, "1.1.1")).toBe(false);
expect(isValidAntigravityInitializeResult(null, "1.1.1")).toBe(false);
expect(isValidAntigravityInitializeResult(undefined, "1.1.1")).toBe(false);
}
it("validates ACP initialize results from official Antigravity releases", testValidatesAcpInitializeResults);
// Captured from the SHA-256-pinned Google 1.4.3 Windows x64 binary, unauthenticated: optional operations are objects.
const officialInitialize = {
protocolVersion: 1,
agentInfo: { name: "antigravity-acp", title: "Google Antigravity", version: "1.4.3" },
agentCapabilities: {
loadSession: true,
sessionCapabilities: { list: {}, resume: {} },
auth: { logout: {} },
},
authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
};
it("accepts the official runtime's object-shaped capabilities", () => {
expect(isValidAntigravityInitializeResult(officialInitialize, ANTIGRAVITY_RELEASE_VERSION)).toBe(true);
});
it.each([undefined, null, false, [], "true", 1])("rejects malformed operation capabilities: %j", (value) => {
for (const capabilities of [
{ ...officialInitialize.agentCapabilities, sessionCapabilities: { resume: value } },
{ ...officialInitialize.agentCapabilities, auth: { logout: value } },
]) {
expect(isValidAntigravityInitializeResult({ ...officialInitialize, agentCapabilities: capabilities }, ANTIGRAVITY_RELEASE_VERSION)).toBe(false);
}
});
it("requires the official executable and harness as a pair", async () => {
const fake = fakeRuntime();
await expect(resolveAntigravityRuntime(fake.executable)).resolves.toMatchObject({
executablePath: fake.executable,
harnessPath: fake.harness,
source: "override",
});
rmSync(fake.harness, { force: true });
await expect(resolveAntigravityRuntime(fake.executable)).rejects.toMatchObject({
message: expect.stringMatching(/localharness_external/u),
status: 409,
});
});
it.each([
"agy.cmd",
"C:\\Users\\Someone\\AppData\\Roaming\\npm\\agy.cmd",
"C:\\Tools\\agy.exe",
"C:\\Tools\\agy.bat",
"C:\\Tools\\agy.ps1",
"/opt/homebrew/bin/agy",
"/Users/someone/.local/bin/agy",
])("migrates the saved legacy CLI path %s to the official runtime", async (legacyPath) => {
const fake = fakeRuntime();
const officialExecutable = join(fake.directory, process.platform === "win32" ? "agy_acp_server.exe" : "agy_acp_server.par");
copyFileSync(fake.executable, officialExecutable);
if (process.platform !== "win32") chmodSync(officialExecutable, 0o755);
const runtime = await resolveAntigravityRuntime(legacyPath, { PATH: fake.directory }, fake.directory);
expect(runtime).toMatchObject({ executablePath: officialExecutable, source: "path" });
});
it("explains the official setup when a legacy CLI has no replacement installed", async () => {
if (!resolveAntigravityReleaseAsset()) return;
const fake = fakeRuntime();
await expect(resolveAntigravityRuntime("/old/bin/agy", { PATH: "" }, fake.directory))
.rejects.toThrow(/Install official Antigravity, then Sign in with Google/);
});
it("preserves a valid explicitly selected official runtime even if named agy", async () => {
const fake = fakeRuntime();
const custom = join(fake.directory, "agy");
copyFileSync(fake.executable, custom);
if (process.platform !== "win32") chmodSync(custom, 0o755);
await expect(resolveAntigravityRuntime(custom, { PATH: "" }, fake.directory))
.resolves.toMatchObject({ executablePath: custom, source: "override" });
});
it("does not silently replace an unrecognized custom executable", async () => {
const fake = fakeRuntime();
await expect(resolveAntigravityRuntime(join(fake.directory, "custom-acp"), { PATH: "" }, fake.directory))
.rejects.toThrow(/custom Antigravity ACP executable/);
});
it("atomically prepares one complete profile for concurrent callers", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
const profileDirectory = join(fake.directory, "profile");
await Promise.all(Array.from({ length: 8 }, () => prepareAntigravityProfile({
instanceId: "shared",
runtime,
baseEnv: {},
profileDirectory,
})));
const acpDirectory = join(profileDirectory, "antigravity-acp");
expect(JSON.parse(readFileSync(join(acpDirectory, "settings.json"), "utf8"))).toEqual({
auth: { type: "oauth-personal" },
});
expect(readdirSync(acpDirectory).filter((name) => name.endsWith(".tmp"))).toEqual([]);
});
it("keeps the existing Google sign-in when the runtime version changes", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
const input = { instanceId: "persistent", runtime, baseEnv: {}, baseDir: fake.directory };
const before = await prepareAntigravityProfile(input);
writeFileSync(before.tokenPath, '{"fixture":"existing-login"}', { mode: 0o600 });
const after = await prepareAntigravityProfile({ ...input, runtime: { ...runtime, version: "new-version" } });
expect(after.tokenPath).toBe(before.tokenPath);
expect(readFileSync(after.tokenPath, "utf8")).toBe('{"fixture":"existing-login"}');
expect(await antigravityProfileAuthenticated(after)).toBe(true);
});
it("discovers account models when the packaged runtime takes over five seconds to start", async () => {
const fake = fakeRuntime(5_500);
const runtime = await resolveAntigravityRuntime(fake.executable);
const profile = await prepareAntigravityProfile({
instanceId: "slow-start", runtime, baseDir: fake.directory,
baseEnv: { PATH: process.env.PATH, FAKE_ACP_AUTH_METHOD: "oauth-personal", FAKE_ACP_MODELS: "account-model" },
});
await expect(probeAntigravityModels({ runtime, profile, fallbackDefault: "account-model" }))
.resolves.toMatchObject({ options: [{ id: "account-model" }] });
}, 20_000);
it("discovers thinking levels for every account model, not only the one a new session starts on", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
const levels = [{ value: "low", name: "Low" }, { value: "high", name: "High" }];
const profile = await prepareAntigravityProfile({
instanceId: "thinking-levels", runtime, baseDir: fake.directory,
baseEnv: {
PATH: process.env.PATH,
FAKE_ACP_AUTH_METHOD: "oauth-personal",
FAKE_ACP_MODELS: "gemini-flash,gemini-argon,gemini-plain",
FAKE_ACP_VARIANTS: JSON.stringify({
"gemini-flash": { id: "thought_level", currentValue: "low", options: levels },
"gemini-argon": { id: "thought_level", currentValue: "high", options: levels },
}),
},
});
const variants = [{ id: "low", label: "Low" }, { id: "high", label: "High" }];
await expect(probeAntigravityModels({ runtime, profile, fallbackDefault: "gemini-flash" })).resolves.toEqual({
default: "gemini-flash",
options: [
{ id: "gemini-flash", label: "gemini-flash", variants },
{ id: "gemini-argon", label: "gemini-argon", variants },
{ id: "gemini-plain", label: "gemini-plain" },
],
});
}, 20_000);
it("rejects a download redirected to insecure HTTP", async () => {
const baseDir = mkdtempSync(join(tmpdir(), "omb-antigravity-insecure-"));
scratch.push(baseDir);
const asset: AntigravityReleaseAsset = {
version: "insecure-test",
url: "https://dl.google.com/test-antigravity.zip",
sha256: "00".repeat(32),
archiveBytes: 1,
executable: { name: "agy_acp_server.par", bytes: 1 },
harness: { name: "localharness_external", bytes: 1 },
};
const response = new Response(new Uint8Array([0]), { headers: { "content-length": "1" } });
Object.defineProperty(response, "url", { value: "http://dl.google.com/test-antigravity.zip" });
await expect(installAntigravityRuntime({
baseDir,
asset,
fetchImpl: async () => response,
})).rejects.toThrow(/redirected outside/u);
});
it("coalesces, verifies, extracts, and reuses a pinned download without touching another install", async () => {
const baseDir = mkdtempSync(join(tmpdir(), "omb-antigravity-install-"));
scratch.push(baseDir);
const versions = join(baseDir, "tools", "antigravity-acp", `${process.platform}-${process.arch}`, "versions");
const otherStaging = join(versions, ".install-other-active", "runtime");
mkdirSync(otherStaging, { recursive: true });
const otherFile = join(otherStaging, "agy_acp_server.exe");
writeFileSync(otherFile, "another app process is still installing");
const archive = Buffer.from(
"UEsDBBQAAAAIAMaAI13ihkXDEwAAABEAAAASAAAAYWd5X2FjcF9zZXJ2ZXIucGFyU1bUT8rM0y/O4EqtyCxRMOACAFBLAwQUAAAACADGgCNd4oZFwxMAAAARAAAAFQAAAGxvY2FsaGFybmVzc19leHRlcm5hbFNW1E/KzNMvzuBKrcgsUTDgAgBQSwECFAMUAAAACADGgCNd4oZFwxMAAAARAAAAEgAAAAAAAAAAAAAAgAEAAAAAYWd5X2FjcF9zZXJ2ZXIucGFyUEsBAhQDFAAAAAgAxoAjXeKGRcMTAAAAEQAAABUAAAAAAAAAAAAAAIABQwAAAGxvY2FsaGFybmVzc19leHRlcm5hbFBLBQYAAAAAAgACAIMAAACJAAAAAAA=",
"base64",
);
const asset: AntigravityReleaseAsset = {
version: "test-release",
url: "https://dl.google.com/test-antigravity.zip",
sha256: "ebefcc10b5101013da6d0cb2a101ca644015377ee0f9ec5cf4efec7d9dfb7442",
archiveBytes: archive.length,
executable: { name: "agy_acp_server.par", bytes: 17 },
harness: { name: "localharness_external", bytes: 17 },
};
let fetches = 0;
let validations = 0;
const options = {
baseDir,
asset,
fetchImpl: async () => {
fetches += 1;
return new Response(archive, { headers: { "content-length": String(archive.length) } });
},
validate: async () => { validations += 1; },
};
const first = installAntigravityRuntime(options);
expect(installAntigravityRuntime(options)).toBe(first);
const installed = await first;
expect(readFileSync(installed.executablePath, "utf8")).toBe("#!/bin/sh\nexit 0\n");
expect(readFileSync(installed.harnessPath, "utf8")).toBe("#!/bin/sh\nexit 0\n");
await installAntigravityRuntime(options);
expect(fetches).toBe(1);
expect(validations).toBe(2);
expect(readFileSync(otherFile, "utf8")).toBe("another app process is still installing");
expect(readdirSync(versions).filter((name) => name.startsWith(".install-"))).toEqual([".install-other-active"]);
});
it("isolates profiles by instance and strips ambient Google credentials", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
const first = await prepareAntigravityProfile({
instanceId: "work",
runtime,
baseEnv: { HOME: "/tmp/home", GEMINI_API_KEY: "must-not-leak", GOOGLE_API_KEY: "also-no" },
});
const second = await prepareAntigravityProfile({ instanceId: "personal", runtime, baseEnv: {} });
expect(first.directory).not.toBe(second.directory);
expect(first.environment.GEMINI_API_KEY).toBeUndefined();
expect(first.environment.GOOGLE_API_KEY).toBeUndefined();
expect(first.environment.GEMINI_HOME).toBe(first.directory);
expect(first.environment.ANTIGRAVITY_HARNESS_PATH).toBe(fake.harness);
});
it("points TEMP on Windows at one stable folder per instance under DATA_DIR/tmp", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
const input = {
instanceId: "work",
runtime,
baseDir: fake.directory,
platform: "win32" as const,
baseEnv: { Temp: "C:\\Users\\ada\\AppData\\Local\\Temp", tmp: "C:\\Temp", PATH: process.env.PATH },
};
const first = await prepareAntigravityProfile(input);
const again = await prepareAntigravityProfile(input);
const expected = antigravityTempDir(fake.directory, "work");
expect(first.tempDirectory).toBe(expected);
expect(first.environment.TEMP).toBe(expected);
expect(first.environment.TMP).toBe(expected);
expect(Object.keys(first.environment).filter((key) => /^(?:temp|tmp)$/iu.test(key)).sort()).toEqual(["TEMP", "TMP"]);
expect(statSync(expected).isDirectory()).toBe(true);
expect(again.environment).toEqual(first.environment);
expect(expected.startsWith(join(fake.directory, "tmp", "agy"))).toBe(true);
expect(expected.startsWith(first.directory)).toBe(false);
const other = await prepareAntigravityProfile({ ...input, instanceId: "personal" });
expect(other.environment.TEMP).not.toBe(expected);
});
it("leaves TEMP alone on macOS and Linux", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
for (const platform of ["darwin", "linux"] as const) {
const profile = await prepareAntigravityProfile({
instanceId: "work", runtime, baseDir: fake.directory, platform, baseEnv: { TEMP: "/inherited", TMPDIR: "/inherited-dir" },
});
expect(profile.tempDirectory).toBeUndefined();
expect(profile.environment.TEMP).toBe("/inherited");
expect(profile.environment.TMPDIR).toBe("/inherited-dir");
}
expect(existsSync(join(fake.directory, "tmp"))).toBe(false);
});
it("clears what an earlier run of this instance left behind when the driver starts", async () => {
ensureDirs();
const instanceId = "antigravity-leftovers";
// Owned by an ID no process can have, so it is certainly abandoned.
const abandoned = join(antigravityTempDir(DATA_DIR, instanceId), `_MEI7ffffff02`);
// And one a runtime verification left when its runtime would not stop.
const verification = join(antigravityTempDir(DATA_DIR, VERIFICATION_TEMP_KEY), `_MEI7ffffff03`);
for (const folder of [abandoned, verification]) {
mkdirSync(join(folder, "google3"), { recursive: true });
writeFileSync(join(folder, "google3", "payload.bin"), "unpacked");
}
const scheduled = vi.spyOn(antigravityTemp, "scheduleAntigravityTempSweep");
const instance = await AntigravityDriver.create({
instanceId,
displayName: "Antigravity fixture",
enabled: true,
config: { cli: join(DATA_DIR, "not-installed"), fullAuto: false },
environment: {},
});
try {
expect(scheduled).toHaveBeenCalledWith(instanceId);
expect(scheduled).toHaveBeenCalledWith(VERIFICATION_TEMP_KEY);
await sweepAntigravityTemp(instanceId);
await sweepAntigravityTemp(VERIFICATION_TEMP_KEY);
expect(existsSync(abandoned)).toBe(false);
expect(existsSync(verification)).toBe(false);
} finally {
await instance.dispose();
}
});
it("bounds model discovery with one deadline", async () => {
const fake = fakeRuntime();
const runtime = await resolveAntigravityRuntime(fake.executable);
const profile = await prepareAntigravityProfile({
instanceId: "slow-models",
runtime,
baseEnv: { ...process.env, FAKE_ACP_MODE: "hang-initialize" },
});
const started = Date.now();
await expect(probeAntigravityModels({
runtime,
profile,
fallbackDefault: STATIC_ANTIGRAVITY_MODELS.default,
timeoutMs: 100,
})).rejects.toThrow(/timed out/u);
expect(Date.now() - started).toBeLessThan(1_000);
});
});
describe("Antigravity OAuth validation", () => {
const state = "state-123";
const redirectUri = "http://127.0.0.1:8765/";
const authorizationUrl = `https://accounts.google.com/o/oauth2/v2/auth?response_type=code&state=${state}&redirect_uri=${encodeURIComponent(redirectUri)}`;
it("accepts only Google's exact loopback authorization request", () => {
expect(ANTIGRAVITY_AUTH_PREFIX).toContain("authenticate the ACP server");
expect(parseAntigravityAuthorizationUrl(authorizationUrl)).toEqual({ authorizationUrl, redirectUri, state });
expect(() => parseAntigravityAuthorizationUrl(authorizationUrl.replace("accounts.google.com", "example.com"))).toThrow(/invalid/u);
expect(() => parseAntigravityAuthorizationUrl(authorizationUrl.replace("127.0.0.1", "localhost"))).toThrow(/invalid/u);
});
it("reads the sign-in link from either announcement Google makes", () => {
expect(authorizationUrlFromLine(`__OPENMAUS_ANTIGRAVITY_AUTH_URL__${JSON.stringify(authorizationUrl)}`))
.toBe(authorizationUrl);
expect(authorizationUrlFromLine(`${ANTIGRAVITY_AUTH_PREFIX}${authorizationUrl}`)).toBe(authorizationUrl);
});
it("ignores ordinary server logs, including ones quoting a link", () => {
expect(authorizationUrlFromLine("I0905 11:02:06.473720 8283299200 main.py:80] Starting AGY ACP Server...")).toBeNull();
expect(authorizationUrlFromLine(`I0905 credential_manager.py:553] ${ANTIGRAVITY_AUTH_PREFIX}${authorizationUrl}`)).toBeNull();
expect(authorizationUrlFromLine("__OPENMAUS_ANTIGRAVITY_AUTH_URL__not-json")).toBeNull();
expect(authorizationUrlFromLine("")).toBeNull();
});
it("ties a pasted remote callback to the active state and loopback port", () => {
expect(validateAntigravityCallbackUrl(
{ redirectUri, state },
`${redirectUri}?code=secret&state=${state}&iss=${encodeURIComponent("https://accounts.google.com")}`,
).searchParams.get("code")).toBe("secret");
expect(() => validateAntigravityCallbackUrl(
{ redirectUri, state },
`${redirectUri}?code=secret&state=wrong`,
)).toThrow(/does not belong/u);
});
});
describe("Antigravity driver over shared ACP", () => {
let instance: ProviderInstance | null = null;
let recorder: EventRecorder | null = null;
afterEach(async () => {
recorder?.stop();
await instance?.dispose();
});
it("uses managed setup and defaults to approval cards", () => {
expect(AntigravityDriver.defaultConfig()).toEqual({ cli: "agy", fullAuto: false, workspace: undefined });
expect(AntigravityDriver.install?.docsUrl).toContain("antigravity-acp");
if (resolveAntigravityReleaseAsset()) expect(AntigravityDriver.install?.managed?.downloadBytes).toBeGreaterThan(0);
expect(antigravityPermissionMode(false)).toBe("default");
expect(antigravityPermissionMode(false, "ask")).toBe("default");
expect(antigravityPermissionMode(false, "auto")).toBe("default");
expect(antigravityPermissionMode(false, "edits")).toBe("auto_edit");
expect(antigravityPermissionMode(false, "full")).toBe("yolo");
expect(antigravityPermissionMode(true)).toBe("yolo");
expect(antigravityPermissionMode(true, "edits")).toBe("yolo");
});
it.each(["ask", "edits", "auto", "full"] as const)("runs an authenticated %s turn with explicit mode and session-scoped MCP", async (approvalMode) => {
ensureDirs();
const fake = fakeRuntime();
const dump = join(fake.directory, "dump.json");
const instanceId = "antigravity-work";
const tokenDirectory = join(antigravityProfileDirectory(instanceId), "antigravity-acp");
mkdirSync(tokenDirectory, { recursive: true });
writeFileSync(join(tokenDirectory, "acp_token.json"), "{}", { mode: 0o600 });
instance = await AntigravityDriver.create({
instanceId,
displayName: "Antigravity Work",
environment: {
GEMINI_API_KEY: "must-not-leak",
GOOGLE_API_KEY: "also-must-not-leak",
FAKE_ACP_AUTH_METHOD: "oauth-personal",
FAKE_ACP_MODELS: "gemini-3.8-flash",
FAKE_ACP_VARIANTS: JSON.stringify({
"gemini-3.8-flash": {
id: "thinking_level",
currentValue: "medium",
options: [
{ value: "low", name: "Low" },
{ value: "medium", name: "Medium" },
{ value: "high", name: "High" },
],
},
}),
FAKE_ACP_MODES: "default,yolo,auto_edit",
FAKE_ACP_DUMP: dump,
// Inherited temp folders: replaced on Windows, passed through elsewhere.
TEMP: fake.directory,
TMP: fake.directory,
},
enabled: true,
config: { cli: fake.executable, fullAuto: false },
});
recorder = recordEvents(instance.adapter);
const { turnId } = await instance.adapter.sendTurn({
threadId: "thread-antigravity",
text: "hello",
approvalMode,
resumeCursor: "fake-acp-session",
// Existing bots can have the pre-variant fallback ID saved. The official
// runtime only accepts the base model plus its thinking-level option.
model: "gemini-3.8-flash-high",
integrations: {
custom: { docs: { command: "docs-mcp", args: ["serve"], env: { TOKEN: "scoped" } } },
},
cwd: fake.directory,
});
await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
const events = recorder.events.filter((event) => event.turnId === turnId);
expect(events.some((event) => event.type === "item.completed" && event.itemType === "assistant_text")).toBe(true);
expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
const dumpState = JSON.parse(readFileSync(dump, "utf8"));
expect(dumpState.argv).toEqual(process.platform === "linux" ? ["--uid="] : []);
expect(dumpState.env.GEMINI_HOME).toBe(antigravityProfileDirectory(instanceId));
expect(dumpState.env.GEMINI_API_KEY).toBeUndefined();
expect(dumpState.env.GOOGLE_API_KEY).toBeUndefined();
expect(dumpState.env.AGY_ACP_DEFAULT_MODEL).toBeUndefined();
const calls = JSON.parse(readFileSync(`${dump}.config.json`, "utf8"));
expect(calls).toEqual([
{ method: "session/set_config_option", params: { sessionId: "fake-acp-session", configId: "mode", value: approvalMode === "full" ? "yolo" : approvalMode === "edits" ? "auto_edit" : "default" } },
{ method: "session/set_config_option", params: { sessionId: "fake-acp-session", configId: "thinking_level", value: "high" } },
]);
const mcp = JSON.parse(readFileSync(`${dump}.mcp.json`, "utf8"));
expect(mcp).toEqual([{ name: "docs", command: "docs-mcp", args: ["serve"], env: [{ name: "TOKEN", value: "scoped" }] }]);
// Checked on every OS, so the macOS and Linux runs prove the dump carries TEMP.
const expectedTemp = process.platform === "win32" ? antigravityTempDir(DATA_DIR, instanceId) : fake.directory;
expect([dumpState.env.TEMP, dumpState.env.TMP]).toEqual([expectedTemp, expectedTemp]);
});
const legacyPickTurn = async (instanceId: string, sessionModels: string, model: string) => {
ensureDirs();
const fake = fakeRuntime();
const dump = join(fake.directory, "dump.json");
const tokenDirectory = join(antigravityProfileDirectory(instanceId), "antigravity-acp");
mkdirSync(tokenDirectory, { recursive: true });
writeFileSync(join(tokenDirectory, "acp_token.json"), "{}", { mode: 0o600 });
instance = await AntigravityDriver.create({
instanceId,
displayName: "Antigravity",
environment: {
FAKE_ACP_AUTH_METHOD: "oauth-personal",
FAKE_ACP_MODELS: sessionModels,
FAKE_ACP_VARIANTS: JSON.stringify(Object.fromEntries(["gemini-3.8-flash", "gemini-4-argon"].map((id) => [id, {
id: "thinking_level",
currentValue: "high",
options: [{ value: "low", name: "Low" }, { value: "medium", name: "Medium" }, { value: "high", name: "High" }],
}]))),
FAKE_ACP_MODES: "default,yolo,auto_edit",
FAKE_ACP_DUMP: dump,
},
enabled: true,
config: { cli: fake.executable, fullAuto: false },
});
recorder = recordEvents(instance.adapter);
const { turnId } = await instance.adapter.sendTurn({ threadId: "thread-legacy-pick", text: "hello", approvalMode: "ask", model, cwd: fake.directory });
const done = await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
const events = recorder.events.filter((event) => event.turnId === turnId);
expect(events.filter((event) => event.type === "runtime.error")).toEqual([]);
expect(done).toMatchObject({ ok: true });
return {
events,
calls: JSON.parse(readFileSync(`${dump}.config.json`, "utf8")),
selection: JSON.parse(readFileSync(`${dump}.selection.json`, "utf8")),
};
};
it("runs a saved Gemini 3.8 Flash (Medium) pick as the base model at Medium thinking when the runtime offers only the base", async () => {
const { events, calls, selection } = await legacyPickTurn("antigravity-legacy-medium", "gemini-3.8-flash", "gemini-3.8-flash-medium");
expect(selection).toEqual({ sessionId: expect.any(String), model: "gemini-3.8-flash", variant: "medium" });
// The session already runs the base model, so only the thinking level is set; never the retired id.
expect(calls.filter((call: any) => call.params.configId !== "mode")).toEqual([
{ method: "session/set_config_option", params: { sessionId: selection.sessionId, configId: "thinking_level", value: "medium" } },
]);
expect(events.find((event) => event.type === "session.started")).toMatchObject({ model: "gemini-3.8-flash" });
// Thought options are still reported under the bot's saved pick, which the picker matches on.
expect(events.filter((event) => event.type === "session.model-variants").at(-1)).toMatchObject({
model: "gemini-3.8-flash-medium",
variants: { currentValue: "medium" },
});
});
it("runs a saved Gemini 4 Argon (High) pick as the base model at High thinking when the runtime offers only the base", async () => {
const { calls, selection } = await legacyPickTurn("antigravity-legacy-argon", "gemini-3.8-flash,gemini-4-argon", "gemini-4-argon-high");
expect(selection).toEqual({ sessionId: expect.any(String), model: "gemini-4-argon", variant: "high" });
expect(calls.some((call: any) => call.params.value === "gemini-4-argon-high")).toBe(false);
});
it("keeps a suffixed Gemini 3.8 Flash pick unchanged when the runtime still offers it", async () => {
const { calls, selection } = await legacyPickTurn("antigravity-suffixed-offered", "gemini-3.8-flash,gemini-3.8-flash-medium", "gemini-3.8-flash-medium");
expect(selection).toEqual({ sessionId: expect.any(String), model: "gemini-3.8-flash-medium" });
expect(calls.filter((call: any) => call.params.configId !== "mode")).toEqual([]);
});
it("maps only a retired suffixed id the session lacks, and never overrides a chosen thinking level", () => {
const turn = { threadId: "t", text: "hi", model: "gemini-3.8-flash-low" };
expect(normalizeAntigravityTurn(turn, ["gemini-3.8-flash"])).toEqual({ ...turn, model: "gemini-3.8-flash", variant: "low" });
expect(normalizeAntigravityTurn(turn, ["gemini-3.8-flash", "gemini-3.8-flash-low"])).toBe(turn);
expect(normalizeAntigravityTurn(turn, ["gemini-3.7-flash"])).toBe(turn);
expect(normalizeAntigravityTurn({ ...turn, variant: "high" }, ["gemini-3.8-flash"])).toMatchObject({ model: "gemini-3.8-flash-low", variant: "high" });
expect(normalizeAntigravityTurn({ ...turn, model: "gemini-4-argon-medium" }, ["gemini-3.8-flash", "gemini-4-argon"])).toEqual({ ...turn, model: "gemini-4-argon", variant: "medium" });
expect(normalizeAntigravityTurn({ ...turn, model: "gemini-4-argon-high" }, ["gemini-4-argon", "gemini-4-argon-high"])).toEqual({ ...turn, model: "gemini-4-argon-high" });
expect(normalizeAntigravityTurn({ ...turn, model: "gemini-4-argon-high" }, ["gemini-3.8-flash"])).toEqual({ ...turn, model: "gemini-4-argon-high" });
});
it("keeps one process across approval and model changes, starting on OMB's model", async () => {
ensureDirs();
const fake = fakeRuntime();
const dump = join(fake.directory, "dump.json");
const launches = join(fake.directory, "launches");
const instanceId = "antigravity-pooled";