Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { expect, it } from "@effect/vitest";
4import {
5 ANTIGRAVITY_DEFAULT_MODEL,
6 EnvironmentId,
7 MessageId,
8 NodeId,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProviderSessionId,
13 RunAttemptId,
14 RunId,
15 ThreadId,
16 type AntigravitySettings,
17 type ProviderInstallState,
18 type ServerProvider,
19} from "@t3tools/contracts";
20import * as HostProcess from "@t3tools/shared/HostProcess";
21import * as Cause from "effect/Cause";
22import * as DateTime from "effect/DateTime";
23import * as Deferred from "effect/Deferred";
24import * as Effect from "effect/Effect";
25import * as Exit from "effect/Exit";
26import * as Fiber from "effect/Fiber";
27import * as FileSystem from "effect/FileSystem";
28import * as Layer from "effect/Layer";
29import * as Path from "effect/Path";
30import * as Redacted from "effect/Redacted";
31import * as Schema from "effect/Schema";
32import * as Stream from "effect/Stream";
33import * as SubscriptionRef from "effect/SubscriptionRef";
34import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
35
36import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
37import * as ServerConfig from "../../config.ts";
38import * as ServerSettings from "../../serverSettings.ts";
39import * as AntigravityInstallation from "../AntigravityInstallation.ts";
40import {
41 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
42 resolveAntigravityInstanceDirectories,
43} from "../antigravityAuthSupport.ts";
44import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
45import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
46import * as ModelManifest from "../ModelManifest.ts";
47import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
48import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
49import { knownProviderFailureMessage } from "@t3tools/provider-core/server/failure";
50import { resolveProviderCompatibility } from "../providerCompatibility.ts";
51import { writeProviderStatusCache } from "../providerStatusCache.ts";
52import { AntigravityDriver } from "./AntigravityDriver.ts";
53import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
54import * as ProviderHostLive from "../ProviderHostLive.ts";
55import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
56
57const hostPlatform = HostProcess.Platform.defaultValue();
58const windowsHost = hostPlatform === "win32";
59const decodeRequest = Schema.decodeEffect(
60 Schema.fromJsonString(
61 Schema.Struct({
62 method: Schema.optional(Schema.String),
63 params: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
64 }),
65 ),
66);
67const blockedCredentialKeys = new Set([
68 "GEMINI_API_KEY",
69 "GOOGLE_API_KEY",
70 "GOOGLE_APPLICATION_CREDENTIALS",
71 "GOOGLE_GENAI_USE_VERTEXAI",
72]);
73
74function shellQuote(value: string): string {
75 return `'${value.replaceAll("'", `'"'"'`)}'`;
76}
77
78const noManagedRuntime: ProviderInstallState = {
79 driver: ProviderDriverKind.make("antigravity"),
80 operationId: null,
81 phase: "idle",
82 downloadedBytes: 0,
83 totalBytes: null,
84 version: null,
85 installedVersion: null,
86 canRemove: false,
87 message: null,
88};
89
90const outdatedManagedRuntime: ProviderInstallState = {
91 ...noManagedRuntime,
92 version: "1.5.18",
93 installedVersion: "1.5.17",
94 canRemove: true,
95};
96
97const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
98 options: {
99 readonly config?: Partial<AntigravitySettings>;
100 readonly enabled?: boolean;
101 /** Extra instance variables, such as ones a parent T3 turn already exported. */
102 readonly environment?: ReadonlyArray<{ readonly name: string; readonly value: string }>;
103 /** Provider status saved by an earlier server run. */
104 readonly statusCache?: (instanceId: ProviderInstanceId) => ServerProvider;
105 readonly pathRuntime?: boolean;
106 readonly installState?: ProviderInstallState;
107 /** The states an install started by `start` passes through, the first one included. */
108 readonly installSteps?: ReadonlyArray<ProviderInstallState>;
109 } = {},
110) {
111 const fs = yield* FileSystem.FileSystem;
112 const path = yield* Path.Path;
113 const config = yield* ServerConfig.ServerConfig;
114 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
115 const nodePath = yield* HostProcess.ExecutablePath;
116 const baseEnv = yield* HostProcess.Environment;
117 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-driver-" });
118 const instanceId = ProviderInstanceId.make(path.basename(root));
119 const mockAgentPath = yield* path.fromFileUrl(
120 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
121 );
122 const requestLog = path.join(root, "requests.jsonl");
123 const directories = yield* resolveAntigravityInstanceDirectories(config.stateDir, instanceId);
124 const profileDirectory = directories.profile;
125 const instancePath = `${path.join(root, "instance-bin")}:${baseEnv.PATH ?? ""}`;
126
127 const agentExecutables = new Set<string>();
128 const makeExecutable = Effect.fn("AntigravityDriverTest.makeExecutable")(function* (
129 name: string,
130 options: {
131 readonly loginRequired?: boolean;
132 /** `data` of the agent's "Internal error" response to `session/new`. */
133 readonly newSessionErrorData?: unknown;
134 readonly initialMode?: string;
135 readonly agentVersion?: string;
136 } = {},
137 ) {
138 const directory = path.join(root, name);
139 const executablePath = path.join(directory, "agy");
140 yield* fs.makeDirectory(directory, { recursive: true });
141 const authorizationUrl =
142 "https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A51234%2F&state=fixture-state";
143 yield* fs.writeFileString(
144 executablePath,
145 [
146 "#!/bin/sh",
147 ...(options.loginRequired
148 ? [`printf '%s\\n' ${shellQuote(ANTIGRAVITY_AUTH_STDOUT_PREFIX + authorizationUrl)}`]
149 : []),
150 ...(options.newSessionErrorData === undefined
151 ? []
152 : [
153 `export T3_ACP_NEW_SESSION_ERROR_DATA=${shellQuote(JSON.stringify(options.newSessionErrorData))}`,
154 ]),
155 ...(options.initialMode === undefined
156 ? []
157 : [`export T3_ACP_INITIAL_MODE=${shellQuote(options.initialMode)}`]),
158 `export T3_ACP_AGENT_VERSION=${shellQuote(options.agentVersion ?? "1.5.12")}`,
159 `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`,
160 "",
161 ].join("\n"),
162 );
163 yield* fs.chmod(executablePath, 0o755);
164 agentExecutables.add(executablePath);
165 return {
166 executablePath,
167 source: "managed",
168 version: name,
169 managedVersionDirectory: directory,
170 } satisfies AntigravityInstallation.AntigravityExecutable;
171 });
172
173 const first = yield* makeExecutable("runtime 'one");
174 const second = yield* makeExecutable("runtime two");
175 const signedOut = yield* makeExecutable("runtime signed-out", { loginRequired: true });
176 const controls: {
177 selected: AntigravityInstallation.AntigravityExecutable;
178 failResolution: boolean;
179 beforeAcquire: Effect.Effect<void>;
180 } = {
181 selected: options.pathRuntime ? { ...first, source: "path", version: null } : first,
182 failResolution: false,
183 beforeAcquire: Effect.void,
184 };
185 const acquisitions: Array<{ binaryPath: string | undefined; path: string | undefined }> = [];
186 const releases: Array<string | null> = [];
187 const launches: Array<{
188 command: string;
189 args: ReadonlyArray<string>;
190 cwd: string | undefined;
191 extendEnv: boolean | undefined;
192 environment: Record<string, string | undefined>;
193 profileDirectory: string | undefined;
194 forceFileStorage: string | undefined;
195 credentialKeys: ReadonlyArray<string>;
196 geminiApiKey: string | undefined;
197 agent: boolean;
198 handle: ChildProcessSpawner.ChildProcessHandle;
199 }> = [];
200
201 const installState = yield* SubscriptionRef.make(options.installState ?? noManagedRuntime);
202 const updateChecked = yield* Deferred.make<void>();
203 let updateCheckInvalidations = 0;
204 const installSteps = options.installSteps ?? [];
205 const layerInstallation = Layer.mock(AntigravityInstallation.AntigravityInstallation)({
206 managedDirectory: root,
207 state: SubscriptionRef.get(installState),
208 changes:
209 installSteps.length > 0
210 ? Stream.fromIterable(installSteps)
211 : SubscriptionRef.changes(installState),
212 start: Effect.succeed(installSteps[0] ?? noManagedRuntime),
213 checkForUpdate: Deferred.succeed(updateChecked, undefined).pipe(Effect.asVoid),
214 invalidateUpdateCheck: Effect.sync(() => {
215 updateCheckInvalidations += 1;
216 }),
217 compatibility: (version) =>
218 Effect.succeed(
219 resolveProviderCompatibility(
220 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
221 ProviderDriverKind.make("antigravity"),
222 version,
223 ),
224 ),
225 resolve: () =>
226 Effect.gen(function* () {
227 if (controls.failResolution) {
228 return yield* new AntigravityInstallation.AntigravityInstallationError({
229 operation: "resolve",
230 detail: "Fixture resolution failed.",
231 });
232 }
233 return controls.selected;
234 }),
235 acquire: (binaryPath, environment) =>
236 Effect.gen(function* () {
237 acquisitions.push({ binaryPath, path: environment?.PATH });
238 yield* controls.beforeAcquire;
239 if (controls.failResolution) {
240 return yield* new AntigravityInstallation.AntigravityInstallationError({
241 operation: "resolve",
242 detail: "Fixture resolution failed.",
243 });
244 }
245 const selected = controls.selected;
246 yield* Effect.addFinalizer(() =>
247 Effect.sync(() => {
248 releases.push(selected.version);
249 }),
250 );
251 return selected;
252 }),
253 });
254 const observedSpawner = ChildProcessSpawner.make((command) =>
255 Effect.gen(function* () {
256 if (command._tag !== "StandardCommand")
257 return yield* Effect.die("Unexpected process pipeline.");
258 const handle = yield* spawner.spawn(command);
259 const environment = command.options.env ?? {};
260 const env = (name: string) => {
261 const value = environment[name];
262 return Redacted.isRedacted(value) ? Redacted.value(value) : value;
263 };
264 launches.push({
265 command: command.command,
266 args: command.args.map(String),
267 cwd: command.options.cwd,
268 extendEnv: command.options.extendEnv,
269 environment: Object.fromEntries(Object.keys(environment).map((name) => [name, env(name)])),
270 profileDirectory: env("GEMINI_HOME"),
271 forceFileStorage: env("AGY_ACP_FORCE_FILE_STORAGE"),
272 credentialKeys: Object.keys(environment).filter((key) =>
273 blockedCredentialKeys.has(key.toUpperCase()),
274 ),
275 geminiApiKey: env("GEMINI_API_KEY"),
276 agent: agentExecutables.has(command.command),
277 handle,
278 });
279 return handle;
280 }),
281 );
282 if (options.statusCache) {
283 yield* writeProviderStatusCache({
284 filePath: path.join(config.providerStatusCacheDir, `${instanceId}.json`),
285 provider: options.statusCache(instanceId),
286 });
287 }
288 const instance = yield* AntigravityDriver.create({
289 instanceId,
290 displayName: "Google test account",
291 enabled: options.enabled ?? true,
292 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
293 environment: [
294 { name: "PATH", value: instancePath },
295 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
296 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
297 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
298 { name: "google_api_key", value: "must-not-be-used" },
299 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
300 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
301 { name: "GEMINI_HOME", value: "/must-not-be-used" },
302 { name: "BROWSER", value: "must-not-run" },
303 ...(options.environment ?? []),
304 ].map((variable) => ({ ...variable, sensitive: false })),
305 }).pipe(
306 Effect.provide(layerInstallation),
307 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
308 );
309 const refresh = instance.refreshModels;
310 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
311 const readRequests = Effect.gen(function* () {
312 if (!(yield* fs.exists(requestLog))) return [];
313 const text = yield* fs.readFileString(requestLog);
314 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
315 decodeRequest(line),
316 );
317 });
318 const assertClosed = Effect.gen(function* () {
319 for (const launch of launches) {
320 yield* launch.handle.exitCode.pipe(Effect.ignore);
321 expect(yield* launch.handle.isRunning).toBe(false);
322 if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
323 }
324 });
325 return {
326 instance,
327 refresh,
328 makeExecutable,
329 fs,
330 path,
331 profileDirectory,
332 directories,
333 instancePath,
334 first,
335 second,
336 signedOut,
337 controls,
338 installState,
339 updateChecked,
340 updateCheckInvalidations: () => updateCheckInvalidations,
341 acquisitions,
342 releases,
343 launches,
344 readRequests,
345 assertClosed,
346 };
347});
348
349const layerDeps = ServerConfig.layerTest(process.cwd(), {
350 prefix: "t3-antigravity-driver-config-",
351}).pipe(
352 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
353 Layer.provideMerge(ServerSettings.layerTest()),
354 Layer.provideMerge(
355 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
356 shouldRunScopeWork: () => Effect.succeed(false),
357 }),
358 ),
359 Layer.provideMerge(
360 Layer.succeed(
361 ProviderEventLoggers.ProviderEventLoggers,
362 ProviderEventLoggers.NoOpProviderEventLoggers,
363 ),
364 ),
365 Layer.provideMerge(ModelManifest.layerTest),
366 Layer.provideMerge(IdAllocator.layer),
367 Layer.provideMerge(McpProviderSessions.layer),
368);
369const layerTest = ProviderHostLive.layer.pipe(
370 Layer.provideMerge(ServerSecretStore.layer),
371 Layer.provideMerge(layerDeps),
372);
373
374it.layer(layerTest)("AntigravityDriver", (it) => {
375 it.effect("starts a PATH agy from the version and commands in the saved provider status", () =>
376 Effect.gen(function* () {
377 const saved = (instanceId: ProviderInstanceId, type = "oauth-personal") =>
378 ({
379 instanceId,
380 driver: ProviderDriverKind.make("antigravity"),
381 status: "ready",
382 enabled: true,
383 installed: true,
384 auth: { status: "authenticated", type },
385 checkedAt: "2026-11-30T00:00:00.000Z",
386 version: "1.5.20",
387 models: [],
388 slashCommands: [{ name: "compact" }],
389 skills: [],
390 }) satisfies ServerProvider;
391
392 const h = yield* makeHarness({ statusCache: saved, pathRuntime: true });
393 expect(yield* h.instance.snapshot.refresh).toMatchObject({
394 installed: true,
395 version: "1.5.20",
396 slashCommands: [{ name: "compact" }],
397 });
398 expect(h.launches.filter((launch) => launch.agent)).toEqual([]);
399
400 const otherSignIn = yield* makeHarness({
401 statusCache: (instanceId) => saved(instanceId, "gemini-api-key"),
402 pathRuntime: true,
403 });
404 expect(yield* otherSignIn.instance.snapshot.refresh).toMatchObject({
405 version: null,
406 slashCommands: [],
407 });
408 }),
409 );
410
411 it.effect.skipIf(windowsHost)(
412 "reports an incompatible managed runtime during a health check",
413 () =>
414 Effect.gen(function* () {
415 const h = yield* makeHarness();
416 yield* h.refresh();
417 const installed = yield* h.makeExecutable("1.5.0", { agentVersion: "1.5.0" });
418 h.controls.selected = installed;
419 const rejected = yield* h.refresh().pipe(Effect.flip);
420 expect(rejected.detail).toContain("Update it in Antigravity setup");
421
422 expect(yield* h.instance.snapshot.refresh).toMatchObject({
423 status: "error",
424 version: "1.5.0",
425 message: rejected.detail,
426 });
427 }),
428 );
429
430 it.effect.skipIf(windowsHost)(
431 "refreshes the selected executable and limits form capabilities to chat",
432 () =>
433 Effect.gen(function* () {
434 const h = yield* makeHarness();
435 yield* h.refresh();
436 const snapshot = yield* h.instance.snapshot.getSnapshot;
437 expect(snapshot.status).toBe("ready");
438 expect(snapshot.auth.status).toBe("authenticated");
439 expect(snapshot.models.map((model) => model.slug)).toEqual([
440 "gemini-test-low",
441 "gemini-test-high",
442 ]);
443 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
444 expect(snapshot.models.every((model) => model.isLegacy !== true)).toBe(true);
445 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
446 expect(snapshot.supportsTextGeneration).toBe(true);
447 h.controls.selected = h.second;
448 yield* h.refresh();
449
450 expect(h.acquisitions).toEqual([
451 { binaryPath: "", path: h.instancePath },
452 { binaryPath: "", path: h.instancePath },
453 ]);
454 const agentLaunches = h.launches.filter((launch) => launch.agent);
455 expect(agentLaunches.map((launch) => launch.command)).toEqual([
456 h.first.executablePath,
457 h.second.executablePath,
458 ]);
459 for (const launch of agentLaunches) {
460 expect(launch.args).toEqual([
461 "acp",
462 "--gemini-dir",
463 h.profileDirectory,
464 "--app-data-dir",
465 "antigravity-acp",
466 ]);
467 expect(launch.profileDirectory).toBe(h.profileDirectory);
468 expect(launch.forceFileStorage).toBe("1");
469 expect(launch.extendEnv).toBe(false);
470 }
471 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
472 expect(h.releases).toEqual([h.first.version, h.second.version]);
473 const requests = yield* h.readRequests;
474 expect(requests.map((request) => request.method)).toEqual([
475 "initialize",
476 "auth/login",
477 "session/new",
478 "initialize",
479 "auth/login",
480 "session/new",
481 ]);
482 expect(
483 requests
484 .filter((request) => request.method === "auth/login")
485 .map((request) => request.params?.methodId),
486 ).toEqual(["oauth-personal", "oauth-personal"]);
487 expect(
488 requests
489 .filter((request) => request.method === "session/new")
490 .map((request) => request.params?.mcpServers),
491 ).toEqual([[], []]);
492 yield* h.assertClosed;
493 yield* h.instance.textGeneration
494 .generateThreadTitle({
495 cwd: h.profileDirectory,
496 message: "Name this thread",
497 modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
498 })
499 .pipe(Effect.ignore);
500 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-chat-" });
501 const threadId = ThreadId.make("thread-antigravity-capabilities");
502 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
503 runtimeMode: "approval-required",
504 interactionMode: "default",
505 cwd: workspace,
506 });
507 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
508 const session = yield* h.instance.orchestrationAdapter.openSession({
509 threadId,
510 providerSessionId: ProviderSessionId.make("provider-session-antigravity-capabilities"),
511 modelSelection,
512 runtimePolicy,
513 });
514 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
515
516 const helper = {
517 fs: { readTextFile: false, writeTextFile: false },
518 terminal: false,
519 session: { notices: {}, compaction: {} },
520 };
521 expect(
522 (yield* h.readRequests)
523 .filter((request) => request.method === "initialize")
524 .map((request) => request.params?.clientCapabilities),
525 ).toEqual([
526 // Two model refreshes, then thread title generation.
527 helper,
528 helper,
529 helper,
530 {
531 fs: { readTextFile: true, writeTextFile: false },
532 terminal: false,
533 session: { notices: {}, compaction: {} },
534 elicitation: { form: {} },
535 },
536 ]);
537
538 // The agy CLI rejects `yolo` and `auto_edit`; it stays in `default` and T3 answers its requests.
539 h.controls.selected = yield* h.makeExecutable("runtime cli", { initialMode: "auto_edit" });
540 for (const runtimeMode of ["full-access", "auto-accept-edits"] as const) {
541 const requestsBefore = (yield* h.readRequests).length;
542 const cliThreadId = ThreadId.make(`thread-antigravity-cli-${runtimeMode}`);
543 const cliPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
544 runtimeMode,
545 interactionMode: "default",
546 cwd: workspace,
547 });
548 const cliSession = yield* h.instance.orchestrationAdapter.openSession({
549 threadId: cliThreadId,
550 providerSessionId: ProviderSessionId.make(`provider-session-cli-${runtimeMode}`),
551 modelSelection,
552 runtimePolicy: cliPolicy,
553 });
554 yield* cliSession.ensureThread({
555 threadId: cliThreadId,
556 modelSelection,
557 runtimePolicy: cliPolicy,
558 });
559 expect(h.launches.at(-1)?.args).toEqual([
560 "acp",
561 "--gemini-dir",
562 h.profileDirectory,
563 "--app-data-dir",
564 "antigravity-acp",
565 ]);
566 expect(
567 (yield* h.readRequests)
568 .slice(requestsBefore)
569 .filter(
570 (request) =>
571 request.method === "session/set_config_option" &&
572 request.params?.configId === "mode",
573 )
574 .map((request) => request.params?.value),
575 ).toEqual(["default"]);
576 }
577 }),
578 );
579
580 it.effect.skipIf(windowsHost)(
581 "gives a thread session its own T3 thread and MCP fallback environment",
582 () =>
583 Effect.gen(function* () {
584 const h = yield* makeHarness({
585 environment: [
586 { name: "T3CODE_THREAD_ID", value: "thread-antigravity-ambient" },
587 { name: "T3_ACP_MCP_ENDPOINT", value: "http://127.0.0.1:9/ambient" },
588 { name: "T3_ACP_MCP_AUTHORIZATION", value: "Bearer ambient-token" },
589 { name: "T3_ACP_MCP_NODE", value: "/ambient/node" },
590 { name: "T3_ACP_MCP_ENTRYPOINT", value: "/ambient/entrypoint.mjs" },
591 ],
592 });
593 yield* h.refresh();
594 const endpoint = "http://127.0.0.1:43126/mcp";
595 const threadId = ThreadId.make("thread-antigravity-process-environment");
596 yield* (yield* McpProviderSessions.McpProviderSessions).set({
597 environmentId: EnvironmentId.make("environment-antigravity-process-environment"),
598 threadId,
599 providerSessionId: "mcp-session-antigravity-process-environment",
600 providerInstanceId: h.instance.instanceId,
601 endpoint,
602 authorizationHeader: "Bearer antigravity-thread-token",
603 browserToolsAvailable: false,
604 });
605 // Running from source, the fallback entrypoint is this process's script.
606 const entrypoint = h.path.resolve(process.argv[1]!);
607 yield* Effect.scoped(
608 Effect.gen(function* () {
609 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-environment-" });
610 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
611 runtimeMode: "approval-required",
612 interactionMode: "default",
613 cwd: workspace,
614 });
615 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
616 const session = yield* h.instance.orchestrationAdapter.openSession({
617 threadId,
618 providerSessionId: ProviderSessionId.make(
619 "provider-session-antigravity-process-environment",
620 ),
621 modelSelection,
622 runtimePolicy,
623 });
624 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
625 }),
626 );
627
628 // Gemini Enterprise can strip the native MCP servers, and the documented `acp-mcp-call`
629 // fallback reads these from the shell.
630 const agentLaunches = h.launches.filter(
631 (launch) => launch.command === h.first.executablePath,
632 );
633 expect(agentLaunches).toHaveLength(2);
634 expect(agentLaunches[1]?.environment).toMatchObject({
635 T3CODE_THREAD_ID: threadId,
636 T3_ACP_MCP_ENDPOINT: endpoint,
637 T3_ACP_MCP_AUTHORIZATION: "Bearer antigravity-thread-token",
638 T3_ACP_MCP_NODE: process.execPath,
639 T3_ACP_MCP_ENTRYPOINT: entrypoint,
640 });
641 // Model refresh and sign-in launches are not part of a thread.
642 expect(agentLaunches[0]?.environment).toMatchObject({
643 T3CODE_THREAD_ID: "thread-antigravity-ambient",
644 T3_ACP_MCP_ENDPOINT: "http://127.0.0.1:9/ambient",
645 T3_ACP_MCP_AUTHORIZATION: "Bearer ambient-token",
646 T3_ACP_MCP_NODE: "/ambient/node",
647 T3_ACP_MCP_ENTRYPOINT: "/ambient/entrypoint.mjs",
648 });
649 yield* h.assertClosed;
650 }),
651 );
652
653 for (const [agentVersion, expected] of [
654 ["1.4.5", "does not work with this T3 Code release"],
655 // 1.5.0 offers Claude and GPT only to allowlisted editors such as Zed.
656 ["1.5.0", "only serves allowlisted editors, not T3 Code"],
657 ] as const) {
658 it.effect.skipIf(windowsHost)(
659 `refuses to open a session on a PATH executable at ${agentVersion}`,
660 () =>
661 Effect.gen(function* () {
662 const h = yield* makeHarness();
663 const old = yield* h.makeExecutable("runtime old", { agentVersion });
664 h.controls.selected = { ...old, source: "path", version: null };
665 const threadId = ThreadId.make("thread-antigravity-old-runtime");
666 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
667 const error = yield* Effect.scoped(
668 Effect.gen(function* () {
669 const workspace = yield* h.fs.makeTempDirectoryScoped({
670 prefix: "t3-ag-old-runtime-",
671 });
672 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
673 runtimeMode: "approval-required",
674 interactionMode: "default",
675 cwd: workspace,
676 });
677 const session = yield* h.instance.orchestrationAdapter.openSession({
678 threadId,
679 providerSessionId: ProviderSessionId.make(
680 "provider-session-antigravity-old-runtime",
681 ),
682 modelSelection,
683 runtimePolicy,
684 });
685 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
686 }),
687 ).pipe(Effect.flip);
688 const target = agentVersion === "1.4.5" ? ">=1.5.22 <2" : "1.5.1 or newer";
689 const message = `Antigravity ${agentVersion} ${expected}. Update the Antigravity executable at ${old.executablePath} to ${target}, then retry.`;
690 expect(knownProviderFailureMessage(error)).toBe(message);
691 expect((yield* h.refresh().pipe(Effect.flip)).detail).toBe(message);
692 const methods = (yield* h.readRequests).map((request) => request.method);
693 expect(methods).toContain("initialize");
694 expect(methods).not.toContain("session/new");
695 yield* h.assertClosed;
696 }),
697 );
698 }
699
700 it.effect.skipIf(windowsHost)(
701 "closes refresh processes and clears account metadata when Google sign-in is required",
702 () =>
703 Effect.gen(function* () {
704 const h = yield* makeHarness();
705 yield* h.refresh();
706 h.controls.selected = h.signedOut;
707 const error = yield* h.refresh().pipe(Effect.flip);
708 expect(error.detail).toContain("Sign in to Antigravity");
709 const snapshot = yield* h.instance.snapshot.getSnapshot;
710 expect(snapshot.auth.status).toBe("unauthenticated");
711 expect(snapshot.models).toEqual([]);
712 expect(snapshot.slashCommands).toEqual([]);
713 expect(snapshot.supportsTextGeneration).toBe(false);
714 expect(h.acquisitions).toHaveLength(2);
715 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
716 yield* h.assertClosed;
717 }),
718 );
719
720 it.effect.skipIf(windowsHost)(
721 "reports an outdated managed runtime as a provider update (#43402)",
722 () =>
723 Effect.gen(function* () {
724 const h = yield* makeHarness({ installState: outdatedManagedRuntime });
725 h.controls.selected = yield* h.makeExecutable("1.5.17", { agentVersion: "1.5.17" });
726 yield* h.refresh();
727 const snapshot = yield* h.instance.snapshot.getSnapshot;
728 expect(snapshot.versionAdvisory?.status).toBe("behind_latest");
729 expect(snapshot.versionAdvisory?.latestVersion).toBe("1.5.18");
730 expect(snapshot.versionAdvisory?.canUpdate).toBe(true);
731 // An install replaces the runtime before the next probe reads its version.
732 yield* SubscriptionRef.set(h.installState, {
733 ...outdatedManagedRuntime,
734 installedVersion: "1.5.18",
735 });
736 expect((yield* h.instance.snapshot.getSnapshot).versionAdvisory?.status).toBe("current");
737 yield* h.instance.invalidateCaches ?? Effect.void;
738 expect(h.updateCheckInvalidations()).toBe(1);
739 yield* h.assertClosed;
740 }),
741 );
742
743 it.effect.skipIf(windowsHost)(
744 "clears and restores the managed version advisory when update checks are toggled",
745 () =>
746 Effect.gen(function* () {
747 const host = yield* ProviderHost.ProviderHost;
748 const baseSettings = yield* host.settings.get;
749 const settingsRef = yield* SubscriptionRef.make(baseSettings);
750 const h = yield* makeHarness({ installState: outdatedManagedRuntime }).pipe(
751 Effect.provideService(ProviderHost.ProviderHost, {
752 ...host,
753 settings: {
754 ...host.settings,
755 get: SubscriptionRef.get(settingsRef),
756 changes: SubscriptionRef.changes(settingsRef),
757 },
758 }),
759 );
760 h.controls.selected = yield* h.makeExecutable("1.5.17", { agentVersion: "1.5.17" });
761 yield* h.instance.snapshot.refresh;
762 expect((yield* h.instance.snapshot.getSnapshot).versionAdvisory?.status).toBe(
763 "behind_latest",
764 );
765
766 const waitChange = (
767 trigger: Effect.Effect<void>,
768 predicate: (snapshot: ServerProvider) => boolean,
769 ) =>
770 Effect.gen(function* () {
771 const fiber = yield* h.instance.snapshot.streamChanges.pipe(
772 Stream.filter(predicate),
773 Stream.runHead,
774 Effect.forkScoped,
775 );
776 yield* Effect.yieldNow;
777 yield* trigger;
778 yield* Fiber.join(fiber);
779 });
780
781 yield* waitChange(
782 SubscriptionRef.set(settingsRef, { ...baseSettings, enableProviderUpdateChecks: false }),
783 (snapshot) => snapshot.versionAdvisory === undefined,
784 );
785 expect((yield* h.instance.snapshot.getSnapshot).versionAdvisory).toBeUndefined();
786
787 yield* waitChange(
788 SubscriptionRef.set(settingsRef, { ...baseSettings, enableProviderUpdateChecks: true }),
789 (snapshot) => snapshot.versionAdvisory?.status === "behind_latest",
790 );
791 expect((yield* h.instance.snapshot.getSnapshot).versionAdvisory?.status).toBe(
792 "behind_latest",
793 );
794 }),
795 );
796
797 it.effect.skipIf(windowsHost)(
798 "checks for an update and offers it when the managed runtime cannot resolve",
799 () =>
800 Effect.gen(function* () {
801 // A pre-CLI install: the installer refuses it but keeps its version.
802 const h = yield* makeHarness({
803 installState: { ...outdatedManagedRuntime, phase: "failed", installedVersion: "1.4.5" },
804 });
805 h.controls.failResolution = true;
806 yield* h.instance.snapshot.refresh;
807 yield* Deferred.await(h.updateChecked);
808 expect((yield* h.instance.snapshot.getSnapshot).versionAdvisory).toMatchObject({
809 status: "behind_latest",
810 currentVersion: "1.4.5",
811 latestVersion: "1.5.18",
812 canUpdate: true,
813 });
814 }),
815 );
816
817 for (const finished of [
818 { phase: "succeeded", message: null },
819 { phase: "failed", message: "The download failed its checksum check." },
820 ] as const) {
821 it.effect.skipIf(windowsHost)(
822 `updates the managed runtime through its installer and reports each phase: ${finished.phase}`,
823 () =>
824 Effect.gen(function* () {
825 const step = (
826 phase: ProviderInstallState["phase"],
827 message: string | null,
828 downloadedBytes = 0,
829 ) => ({
830 ...outdatedManagedRuntime,
831 operationId: "install-1",
832 phase,
833 message,
834 downloadedBytes,
835 });
836 const h = yield* makeHarness({
837 installState: outdatedManagedRuntime,
838 installSteps: [
839 step("downloading", "Downloading.", 1),
840 step("downloading", "Downloading.", 2),
841 step("verifying", "Checking."),
842 step(finished.phase, finished.message),
843 ],
844 });
845 const update = (yield* h.instance.snapshot.resolveMaintenance()).managedUpdate;
846 if (!update) return yield* Effect.die("The managed runtime has no update action.");
847 const progress: Array<string> = [];
848 const exit = yield* update
849 .run((message) => Effect.sync(() => void progress.push(message)))
850 .pipe(Effect.exit);
851 expect(progress).toEqual(["Downloading.", "Checking."]);
852 expect(Exit.isSuccess(exit)).toBe(finished.phase === "succeeded");
853 if (Exit.isFailure(exit)) {
854 expect(Cause.squash(exit.cause)).toMatchObject({ message: finished.message });
855 }
856 }),
857 );
858 }
859
860 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
861 Effect.gen(function* () {
862 const h = yield* makeHarness();
863 yield* h.refresh();
864 const before = yield* h.instance.snapshot.getSnapshot;
865 h.controls.failResolution = true;
866 const error = yield* h.refresh().pipe(Effect.flip);
867 expect(error.detail).toBe("Fixture resolution failed.");
868 const after = yield* h.instance.snapshot.getSnapshot;
869 expect(after.models).toEqual(before.models);
870 expect(after.auth).toEqual(before.auth);
871 expect(h.acquisitions).toHaveLength(2);
872 expect(h.releases).toEqual([h.first.version]);
873 yield* h.assertClosed;
874 }),
875 );
876
877 it.effect.skipIf(windowsHost)(
878 "reports the missing SOCKS dependency when session creation fails and keeps the catalog",
879 () =>
880 Effect.gen(function* () {
881 const h = yield* makeHarness();
882 yield* h.refresh();
883 const before = yield* h.instance.snapshot.getSnapshot;
884 h.controls.selected = yield* h.makeExecutable("runtime socks", {
885 newSessionErrorData: { details: "python-socks is required to use a SOCKS proxy" },
886 });
887 const error = yield* h.refresh().pipe(Effect.flip);
888 expect(error.detail).toBe(
889 "Could not refresh Antigravity models. The previous model list is unchanged. Antigravity reported: python-socks is required to use a SOCKS proxy",
890 );
891 const after = yield* h.instance.snapshot.getSnapshot;
892 expect(after.models).toEqual(before.models);
893 expect(after.auth).toEqual(before.auth);
894 yield* h.assertClosed;
895 }),
896 );
897
898 it.effect.skipIf(windowsHost)(
899 "never copies unrecognized agent error details into the refresh error",
900 () =>
901 Effect.gen(function* () {
902 const h = yield* makeHarness();
903 yield* h.refresh();
904 const before = yield* h.instance.snapshot.getSnapshot;
905 const generic =
906 "Could not refresh Antigravity models. The previous model list is unchanged.";
907 const secret = "https://accounts.example.test/o/oauth2?code=sk-secret-123";
908 h.controls.selected = yield* h.makeExecutable("runtime socks with extra", {
909 newSessionErrorData: {
910 details: `Traceback (most recent call last):\n proxy ${secret}\npython-socks is required to use a SOCKS proxy`,
911 },
912 });
913 const known = yield* h.refresh().pipe(Effect.flip);
914 expect(known.detail).toBe(
915 `${generic} Antigravity reported: python-socks is required to use a SOCKS proxy`,
916 );
917
918 for (const [name, data] of [
919 ["runtime unknown details", { details: `Token refresh failed for ${secret}` }],
920 ["runtime object details", { details: { stack: "secret frame", env: { HOME: "/" } } }],
921 ["runtime no details", ["python-socks is required to use a SOCKS proxy"]],
922 ] as const) {
923 h.controls.selected = yield* h.makeExecutable(name, { newSessionErrorData: data });
924 const error = yield* h.refresh().pipe(Effect.flip);
925 expect(error.detail).toBe(generic);
926 }
927 const after = yield* h.instance.snapshot.getSnapshot;
928 expect(after.models).toEqual(before.models);
929 expect(after.auth).toEqual(before.auth);
930 expect(JSON.stringify(after)).not.toContain("sk-secret-123");
931 yield* h.assertClosed;
932 }),
933 );
934
935 it.effect.skipIf(windowsHost)(
936 "removes runtime temp directories left by a previous server on create",
937 () =>
938 Effect.gen(function* () {
939 const fs = yield* FileSystem.FileSystem;
940 const path = yield* Path.Path;
941 const config = yield* ServerConfig.ServerConfig;
942 const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
943 const directories = yield* resolveAntigravityInstanceDirectories(
944 config.stateDir,
945 instanceId,
946 );
947 const legacyRoot = path.join(directories.profile, "antigravity-acp", "tmp");
948 for (const root of [directories.runtimeTemp, legacyRoot]) {
949 const orphan = path.join(root, "run-orphan", "_MEI123", "google3");
950 yield* fs.makeDirectory(orphan, { recursive: true });
951 yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
952 }
953 yield* AntigravityDriver.create({
954 instanceId,
955 displayName: "Sweep",
956 enabled: false,
957 config: AntigravityDriver.defaultConfig(),
958 environment: [],
959 }).pipe(
960 Effect.provide(
961 Layer.mock(AntigravityInstallation.AntigravityInstallation)({
962 managedDirectory: config.stateDir,
963 state: Effect.succeed(noManagedRuntime),
964 changes: Stream.make(noManagedRuntime),
965 invalidateUpdateCheck: Effect.void,
966 resolve: () => Effect.die("unused"),
967 acquire: () => Effect.die("unused"),
968 }),
969 ),
970 );
971 expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
972 expect(yield* fs.exists(legacyRoot)).toBe(false);
973 }),
974 );
975
976 it.effect.skipIf(windowsHost)(
977 "keeps catalog default thinking levels when a chat session selects another level",
978 () =>
979 Effect.gen(function* () {
980 const h = yield* makeHarness({
981 environment: [
982 { name: "T3_ACP_ANTIGRAVITY_THOUGHT_LEVEL", value: "1" },
983 { name: "T3_ACP_RESUME_THOUGHT_LEVEL", value: "xhigh" },
984 ],
985 });
986 yield* h.refresh();
987 const levelOf = (snapshot: ServerProvider, slug: string) => {
988 const option = snapshot.models
989 .find((model) => model.slug === slug)
990 ?.capabilities?.optionDescriptors?.find(
991 (descriptor) => descriptor.id === "thought_level",
992 );
993 return option?.type === "select" ? option.currentValue : undefined;
994 };
995
996 const refreshed = yield* h.instance.snapshot.getSnapshot;
997 expect(levelOf(refreshed, "gemini-test-low")).toBe("high");
998 expect(levelOf(refreshed, "gemini-test-high")).toBe("medium");
999
1000 const threadId = ThreadId.make("thread-antigravity-thought-level");
1001 const xhighSelection = {
1002 instanceId: h.instance.instanceId,
1003 model: "gemini-test-low",
1004 options: [{ id: "thought_level", value: "xhigh" }],
1005 };
1006 const nativeSessionId = yield* Effect.scoped(
1007 Effect.gen(function* () {
1008 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-thought-" });
1009 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1010 runtimeMode: "approval-required",
1011 interactionMode: "default",
1012 cwd: workspace,
1013 });
1014 const session = yield* h.instance.orchestrationAdapter.openSession({
1015 threadId,
1016 providerSessionId: ProviderSessionId.make(
1017 "provider-session-antigravity-thought-level",
1018 ),
1019 modelSelection: xhighSelection,
1020 runtimePolicy,
1021 });
1022 const providerThread = yield* session.ensureThread({
1023 threadId,
1024 modelSelection: xhighSelection,
1025 runtimePolicy,
1026 });
1027 const now = yield* DateTime.now;
1028 yield* session.startTurn({
1029 appThread: {
1030 createdBy: "user",
1031 creationSource: "web",
1032 id: threadId,
1033 projectId: ProjectId.make("project-antigravity-thought-level"),
1034 title: "Antigravity thought level",
1035 providerInstanceId: h.instance.instanceId,
1036 modelSelection: xhighSelection,
1037 runtimeMode: "approval-required",
1038 interactionMode: "default",
1039 branch: null,
1040 worktreePath: null,
1041 activeProviderThreadId: providerThread.id,
1042 lineage: {
1043 parentThreadId: null,
1044 relationshipToParent: null,
1045 rootThreadId: threadId,
1046 },
1047 forkedFrom: null,
1048 createdAt: now,
1049 updatedAt: now,
1050 archivedAt: null,
1051 settledOverride: null,
1052 settledAt: null,
1053 lastVisitedAt: null,
1054 deletedAt: null,
1055 },
1056 threadId,
1057 runId: RunId.make("run-antigravity-thought-level"),
1058 runOrdinal: 1,
1059 providerTurnOrdinal: 1,
1060 attemptId: RunAttemptId.make("attempt-antigravity-thought-level"),
1061 rootNodeId: NodeId.make("node-antigravity-thought-level"),
1062 providerThread,
1063 message: {
1064 createdBy: "user",
1065 creationSource: "web",
1066 messageId: MessageId.make("message-antigravity-thought-level"),
1067 text: "Say ok.",
1068 attachments: [],
1069 },
1070 modelSelection: xhighSelection,
1071 runtimePolicy,
1072 });
1073 yield* session.events.pipe(
1074 Stream.takeUntil((event) => event.type === "turn.terminal"),
1075 Stream.runDrain,
1076 );
1077 const nativeId = providerThread.nativeThreadRef?.nativeId;
1078 if (!nativeId) {
1079 return yield* Effect.die("Expected Antigravity session to have a native thread id");
1080 }
1081 return nativeId;
1082 }),
1083 );
1084
1085 const afterLiveSession = yield* h.instance.snapshot.getSnapshot;
1086 expect(levelOf(afterLiveSession, "gemini-test-low")).toBe("high");
1087 expect(levelOf(afterLiveSession, "gemini-test-high")).toBe("medium");
1088 expect(
1089 afterLiveSession.models.find((model) => model.slug === "gemini-test-low")?.isDefault,
1090 ).toBe(true);
1091 expect(
1092 (yield* h.readRequests)
1093 .filter(
1094 (request) =>
1095 request.method === "session/set_config_option" &&
1096 request.params?.configId === "thought_level",
1097 )
1098 .map((request) => request.params?.value),
1099 ).toEqual(["xhigh"]);
1100
1101 // Resuming a session whose saved level is xhigh must also keep the catalog default.
1102 yield* Effect.scoped(
1103 Effect.gen(function* () {
1104 const workspace = yield* h.fs.makeTempDirectoryScoped({
1105 prefix: "t3-ag-thought-resume-",
1106 });
1107 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1108 runtimeMode: "approval-required",
1109 interactionMode: "default",
1110 cwd: workspace,
1111 });
1112 const resumed = yield* h.instance.orchestrationAdapter.openSession({
1113 threadId,
1114 providerSessionId: ProviderSessionId.make(
1115 "provider-session-antigravity-thought-level-resumed",
1116 ),
1117 modelSelection: xhighSelection,
1118 runtimePolicy,
1119 initialNativeThreadId: nativeSessionId,
1120 });
1121 yield* resumed.ensureThread({
1122 threadId,
1123 modelSelection: xhighSelection,
1124 runtimePolicy,
1125 });
1126 }),
1127 );
1128 expect(levelOf(yield* h.instance.snapshot.getSnapshot, "gemini-test-low")).toBe("high");
1129 yield* h.assertClosed;
1130 }),
1131 );
1132});