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 ServerProvider,
18} from "@t3tools/contracts";
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as Path from "effect/Path";
25import * as Redacted from "effect/Redacted";
26import * as Schema from "effect/Schema";
27import * as Stream from "effect/Stream";
28import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
29
30import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
31import * as ServerConfig from "../../config.ts";
32import * as ServerSettings from "../../serverSettings.ts";
33import * as AntigravityInstallation from "../AntigravityInstallation.ts";
34import {
35 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
36 resolveAntigravityInstanceDirectories,
37} from "../antigravityAuthSupport.ts";
38import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
39import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
40import * as ModelManifest from "../ModelManifest.ts";
41import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
42import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
43import { knownProviderFailureMessage } from "@t3tools/provider-core/server/failure";
44import { resolveProviderCompatibility } from "../providerCompatibility.ts";
45import { AntigravityDriver } from "./AntigravityDriver.ts";
46import * as ProviderHostLive from "../ProviderHostLive.ts";
47import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
48
49const hostPlatform = HostProcess.Platform.defaultValue();
50const windowsHost = hostPlatform === "win32";
51const decodeRequest = Schema.decodeEffect(
52 Schema.fromJsonString(
53 Schema.Struct({
54 method: Schema.optional(Schema.String),
55 params: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
56 }),
57 ),
58);
59const blockedCredentialKeys = new Set([
60 "GEMINI_API_KEY",
61 "GOOGLE_API_KEY",
62 "GOOGLE_APPLICATION_CREDENTIALS",
63 "GOOGLE_GENAI_USE_VERTEXAI",
64]);
65
66function shellQuote(value: string): string {
67 return `'${value.replaceAll("'", `'"'"'`)}'`;
68}
69
70const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
71 options: {
72 readonly config?: Partial<AntigravitySettings>;
73 readonly enabled?: boolean;
74 /** Extra instance variables, such as ones a parent T3 turn already exported. */
75 readonly environment?: ReadonlyArray<{ readonly name: string; readonly value: string }>;
76 } = {},
77) {
78 const fs = yield* FileSystem.FileSystem;
79 const path = yield* Path.Path;
80 const config = yield* ServerConfig.ServerConfig;
81 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
82 const nodePath = yield* HostProcess.ExecutablePath;
83 const baseEnv = yield* HostProcess.Environment;
84 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-driver-" });
85 const instanceId = ProviderInstanceId.make(path.basename(root));
86 const mockAgentPath = yield* path.fromFileUrl(
87 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
88 );
89 const requestLog = path.join(root, "requests.jsonl");
90 const directories = yield* resolveAntigravityInstanceDirectories(config.stateDir, instanceId);
91 const profileDirectory = directories.profile;
92 const instancePath = `${path.join(root, "instance-bin")}:${baseEnv.PATH ?? ""}`;
93
94 const agentExecutables = new Set<string>();
95 const makeExecutable = Effect.fn("AntigravityDriverTest.makeExecutable")(function* (
96 name: string,
97 options: {
98 readonly loginRequired?: boolean;
99 /** `data` of the agent's "Internal error" response to `session/new`. */
100 readonly newSessionErrorData?: unknown;
101 readonly initialMode?: string;
102 readonly agentVersion?: string;
103 } = {},
104 ) {
105 const directory = path.join(root, name);
106 const executablePath = path.join(directory, "agy");
107 yield* fs.makeDirectory(directory, { recursive: true });
108 const authorizationUrl =
109 "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";
110 yield* fs.writeFileString(
111 executablePath,
112 [
113 "#!/bin/sh",
114 ...(options.loginRequired
115 ? [`printf '%s\\n' ${shellQuote(ANTIGRAVITY_AUTH_STDOUT_PREFIX + authorizationUrl)}`]
116 : []),
117 ...(options.newSessionErrorData === undefined
118 ? []
119 : [
120 `export T3_ACP_NEW_SESSION_ERROR_DATA=${shellQuote(JSON.stringify(options.newSessionErrorData))}`,
121 ]),
122 ...(options.initialMode === undefined
123 ? []
124 : [`export T3_ACP_INITIAL_MODE=${shellQuote(options.initialMode)}`]),
125 `export T3_ACP_AGENT_VERSION=${shellQuote(options.agentVersion ?? "1.5.12")}`,
126 `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`,
127 "",
128 ].join("\n"),
129 );
130 yield* fs.chmod(executablePath, 0o755);
131 agentExecutables.add(executablePath);
132 return {
133 executablePath,
134 source: "managed",
135 version: name,
136 managedVersionDirectory: directory,
137 } satisfies AntigravityInstallation.AntigravityExecutable;
138 });
139
140 const first = yield* makeExecutable("runtime 'one");
141 const second = yield* makeExecutable("runtime two");
142 const signedOut = yield* makeExecutable("runtime signed-out", { loginRequired: true });
143 const controls: {
144 selected: AntigravityInstallation.AntigravityExecutable;
145 failResolution: boolean;
146 beforeAcquire: Effect.Effect<void>;
147 } = { selected: first, failResolution: false, beforeAcquire: Effect.void };
148 const acquisitions: Array<{ binaryPath: string | undefined; path: string | undefined }> = [];
149 const releases: Array<string | null> = [];
150 const launches: Array<{
151 command: string;
152 args: ReadonlyArray<string>;
153 cwd: string | undefined;
154 extendEnv: boolean | undefined;
155 environment: Record<string, string | undefined>;
156 profileDirectory: string | undefined;
157 forceFileStorage: string | undefined;
158 credentialKeys: ReadonlyArray<string>;
159 geminiApiKey: string | undefined;
160 tempDirectory: string | undefined;
161 handle: ChildProcessSpawner.ChildProcessHandle;
162 }> = [];
163
164 const layerInstallation = Layer.mock(AntigravityInstallation.AntigravityInstallation)({
165 managedDirectory: root,
166 compatibility: (version) =>
167 Effect.succeed(
168 resolveProviderCompatibility(
169 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
170 ProviderDriverKind.make("antigravity"),
171 version,
172 ),
173 ),
174 resolve: () =>
175 Effect.gen(function* () {
176 if (controls.failResolution) {
177 return yield* new AntigravityInstallation.AntigravityInstallationError({
178 operation: "resolve",
179 detail: "Fixture resolution failed.",
180 });
181 }
182 return controls.selected;
183 }),
184 acquire: (binaryPath, environment) =>
185 Effect.gen(function* () {
186 acquisitions.push({ binaryPath, path: environment?.PATH });
187 yield* controls.beforeAcquire;
188 if (controls.failResolution) {
189 return yield* new AntigravityInstallation.AntigravityInstallationError({
190 operation: "resolve",
191 detail: "Fixture resolution failed.",
192 });
193 }
194 const selected = controls.selected;
195 yield* Effect.addFinalizer(() =>
196 Effect.sync(() => {
197 releases.push(selected.version);
198 }),
199 );
200 return selected;
201 }),
202 });
203 const observedSpawner = ChildProcessSpawner.make((command) =>
204 Effect.gen(function* () {
205 if (command._tag !== "StandardCommand")
206 return yield* Effect.die("Unexpected process pipeline.");
207 const handle = yield* spawner.spawn(command);
208 const environment = command.options.env ?? {};
209 const env = (name: string) => {
210 const value = environment[name];
211 return Redacted.isRedacted(value) ? Redacted.value(value) : value;
212 };
213 launches.push({
214 command: command.command,
215 args: command.args.map(String),
216 cwd: command.options.cwd,
217 extendEnv: command.options.extendEnv,
218 environment: Object.fromEntries(Object.keys(environment).map((name) => [name, env(name)])),
219 profileDirectory: env("GEMINI_HOME"),
220 forceFileStorage: env("AGY_ACP_FORCE_FILE_STORAGE"),
221 credentialKeys: Object.keys(environment).filter((key) =>
222 blockedCredentialKeys.has(key.toUpperCase()),
223 ),
224 geminiApiKey: env("GEMINI_API_KEY"),
225 tempDirectory: agentExecutables.has(command.command) ? env("TMPDIR") : undefined,
226 handle,
227 });
228 return handle;
229 }),
230 );
231 const instance = yield* AntigravityDriver.create({
232 instanceId,
233 displayName: "Google test account",
234 enabled: options.enabled ?? true,
235 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
236 environment: [
237 { name: "PATH", value: instancePath },
238 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
239 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
240 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
241 { name: "google_api_key", value: "must-not-be-used" },
242 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
243 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
244 { name: "GEMINI_HOME", value: "/must-not-be-used" },
245 { name: "BROWSER", value: "must-not-run" },
246 ...(options.environment ?? []),
247 ].map((variable) => ({ ...variable, sensitive: false })),
248 }).pipe(
249 Effect.provide(layerInstallation),
250 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
251 );
252 const refresh = instance.refreshModels;
253 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
254 const readRequests = Effect.gen(function* () {
255 if (!(yield* fs.exists(requestLog))) return [];
256 const text = yield* fs.readFileString(requestLog);
257 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
258 decodeRequest(line),
259 );
260 });
261 const assertClosed = Effect.gen(function* () {
262 for (const launch of launches) {
263 yield* launch.handle.exitCode.pipe(Effect.ignore);
264 expect(yield* launch.handle.isRunning).toBe(false);
265 if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
266 if (launch.tempDirectory) expect(yield* fs.exists(launch.tempDirectory)).toBe(false);
267 }
268 });
269 return {
270 instance,
271 refresh,
272 makeExecutable,
273 fs,
274 path,
275 profileDirectory,
276 directories,
277 instancePath,
278 first,
279 second,
280 signedOut,
281 controls,
282 acquisitions,
283 releases,
284 launches,
285 readRequests,
286 assertClosed,
287 };
288});
289
290const layerDeps = ServerConfig.layerTest(process.cwd(), {
291 prefix: "t3-antigravity-driver-config-",
292}).pipe(
293 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
294 Layer.provideMerge(ServerSettings.layerTest()),
295 Layer.provideMerge(
296 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
297 shouldRunScopeWork: () => Effect.succeed(false),
298 }),
299 ),
300 Layer.provideMerge(
301 Layer.succeed(
302 ProviderEventLoggers.ProviderEventLoggers,
303 ProviderEventLoggers.NoOpProviderEventLoggers,
304 ),
305 ),
306 Layer.provideMerge(ModelManifest.layerTest),
307 Layer.provideMerge(IdAllocator.layer),
308 Layer.provideMerge(McpProviderSessions.layer),
309);
310const layerTest = ProviderHostLive.layer.pipe(
311 Layer.provideMerge(ServerSecretStore.layer),
312 Layer.provideMerge(layerDeps),
313);
314
315it.layer(layerTest)("AntigravityDriver", (it) => {
316 it.effect.skipIf(windowsHost)(
317 "refreshes the selected executable and limits form capabilities to chat",
318 () =>
319 Effect.gen(function* () {
320 const h = yield* makeHarness();
321 yield* h.refresh();
322 const snapshot = yield* h.instance.snapshot.getSnapshot;
323 expect(snapshot.status).toBe("ready");
324 expect(snapshot.auth.status).toBe("authenticated");
325 expect(snapshot.models.map((model) => model.slug)).toEqual([
326 "gemini-test-low",
327 "gemini-test-high",
328 ]);
329 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
330 expect(snapshot.models.every((model) => model.isLegacy !== true)).toBe(true);
331 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
332 expect(snapshot.supportsTextGeneration).toBe(true);
333 h.controls.selected = h.second;
334 yield* h.refresh();
335
336 expect(h.acquisitions).toEqual([
337 { binaryPath: "", path: h.instancePath },
338 { binaryPath: "", path: h.instancePath },
339 ]);
340 const agentLaunches = h.launches.filter((launch) => launch.tempDirectory !== undefined);
341 expect(agentLaunches.map((launch) => launch.command)).toEqual([
342 h.first.executablePath,
343 h.second.executablePath,
344 ]);
345 for (const launch of agentLaunches) {
346 expect(launch.args).toEqual([
347 "acp",
348 "--gemini-dir",
349 h.profileDirectory,
350 "--app-data-dir",
351 "antigravity-acp",
352 ]);
353 expect(launch.profileDirectory).toBe(h.profileDirectory);
354 expect(launch.forceFileStorage).toBe("1");
355 expect(launch.extendEnv).toBe(false);
356 }
357 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
358 expect(h.releases).toEqual([h.first.version, h.second.version]);
359 const requests = yield* h.readRequests;
360 expect(requests.map((request) => request.method)).toEqual([
361 "initialize",
362 "auth/login",
363 "session/new",
364 "initialize",
365 "auth/login",
366 "session/new",
367 ]);
368 expect(
369 requests
370 .filter((request) => request.method === "auth/login")
371 .map((request) => request.params?.methodId),
372 ).toEqual(["oauth-personal", "oauth-personal"]);
373 expect(
374 requests
375 .filter((request) => request.method === "session/new")
376 .map((request) => request.params?.mcpServers),
377 ).toEqual([[], []]);
378 yield* h.assertClosed;
379 yield* h.instance.textGeneration
380 .generateThreadTitle({
381 cwd: h.profileDirectory,
382 message: "Name this thread",
383 modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
384 })
385 .pipe(Effect.ignore);
386 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-chat-" });
387 const threadId = ThreadId.make("thread-antigravity-capabilities");
388 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
389 runtimeMode: "approval-required",
390 interactionMode: "default",
391 cwd: workspace,
392 });
393 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
394 const session = yield* h.instance.orchestrationAdapter.openSession({
395 threadId,
396 providerSessionId: ProviderSessionId.make("provider-session-antigravity-capabilities"),
397 modelSelection,
398 runtimePolicy,
399 });
400 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
401
402 const helper = {
403 fs: { readTextFile: false, writeTextFile: false },
404 terminal: false,
405 session: { notices: {}, compaction: {} },
406 };
407 expect(
408 (yield* h.readRequests)
409 .filter((request) => request.method === "initialize")
410 .map((request) => request.params?.clientCapabilities),
411 ).toEqual([
412 // Two model refreshes, then thread title generation.
413 helper,
414 helper,
415 helper,
416 {
417 fs: { readTextFile: true, writeTextFile: false },
418 terminal: false,
419 session: { notices: {}, compaction: {} },
420 elicitation: { form: {} },
421 },
422 ]);
423
424 // The agy CLI rejects `yolo` and `auto_edit`; it stays in `default` and T3 answers its requests.
425 h.controls.selected = yield* h.makeExecutable("runtime cli", { initialMode: "auto_edit" });
426 for (const runtimeMode of ["full-access", "auto-accept-edits"] as const) {
427 const requestsBefore = (yield* h.readRequests).length;
428 const cliThreadId = ThreadId.make(`thread-antigravity-cli-${runtimeMode}`);
429 const cliPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
430 runtimeMode,
431 interactionMode: "default",
432 cwd: workspace,
433 });
434 const cliSession = yield* h.instance.orchestrationAdapter.openSession({
435 threadId: cliThreadId,
436 providerSessionId: ProviderSessionId.make(`provider-session-cli-${runtimeMode}`),
437 modelSelection,
438 runtimePolicy: cliPolicy,
439 });
440 yield* cliSession.ensureThread({
441 threadId: cliThreadId,
442 modelSelection,
443 runtimePolicy: cliPolicy,
444 });
445 expect(h.launches.at(-1)?.args).toEqual([
446 "acp",
447 "--gemini-dir",
448 h.profileDirectory,
449 "--app-data-dir",
450 "antigravity-acp",
451 ]);
452 expect(
453 (yield* h.readRequests)
454 .slice(requestsBefore)
455 .filter(
456 (request) =>
457 request.method === "session/set_config_option" &&
458 request.params?.configId === "mode",
459 )
460 .map((request) => request.params?.value),
461 ).toEqual(["default"]);
462 }
463 }),
464 );
465
466 it.effect.skipIf(windowsHost)(
467 "gives a thread session its own T3 thread and MCP fallback environment",
468 () =>
469 Effect.gen(function* () {
470 const h = yield* makeHarness({
471 environment: [
472 { name: "T3CODE_THREAD_ID", value: "thread-antigravity-ambient" },
473 { name: "T3_ACP_MCP_ENDPOINT", value: "http://127.0.0.1:9/ambient" },
474 { name: "T3_ACP_MCP_AUTHORIZATION", value: "Bearer ambient-token" },
475 { name: "T3_ACP_MCP_NODE", value: "/ambient/node" },
476 { name: "T3_ACP_MCP_ENTRYPOINT", value: "/ambient/entrypoint.mjs" },
477 ],
478 });
479 yield* h.refresh();
480 const endpoint = "http://127.0.0.1:43126/mcp";
481 const threadId = ThreadId.make("thread-antigravity-process-environment");
482 yield* (yield* McpProviderSessions.McpProviderSessions).set({
483 environmentId: EnvironmentId.make("environment-antigravity-process-environment"),
484 threadId,
485 providerSessionId: "mcp-session-antigravity-process-environment",
486 providerInstanceId: h.instance.instanceId,
487 endpoint,
488 authorizationHeader: "Bearer antigravity-thread-token",
489 browserToolsAvailable: false,
490 });
491 // Running from source, the fallback entrypoint is this process's script.
492 const entrypoint = h.path.resolve(process.argv[1]!);
493 yield* Effect.scoped(
494 Effect.gen(function* () {
495 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-environment-" });
496 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
497 runtimeMode: "approval-required",
498 interactionMode: "default",
499 cwd: workspace,
500 });
501 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
502 const session = yield* h.instance.orchestrationAdapter.openSession({
503 threadId,
504 providerSessionId: ProviderSessionId.make(
505 "provider-session-antigravity-process-environment",
506 ),
507 modelSelection,
508 runtimePolicy,
509 });
510 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
511 }),
512 );
513
514 // Gemini Enterprise can strip the native MCP servers, and the documented `acp-mcp-call`
515 // fallback reads these from the shell.
516 const agentLaunches = h.launches.filter(
517 (launch) => launch.command === h.first.executablePath,
518 );
519 expect(agentLaunches).toHaveLength(2);
520 expect(agentLaunches[1]?.environment).toMatchObject({
521 T3CODE_THREAD_ID: threadId,
522 T3_ACP_MCP_ENDPOINT: endpoint,
523 T3_ACP_MCP_AUTHORIZATION: "Bearer antigravity-thread-token",
524 T3_ACP_MCP_NODE: process.execPath,
525 T3_ACP_MCP_ENTRYPOINT: entrypoint,
526 });
527 // Model refresh and sign-in launches are not part of a thread.
528 expect(agentLaunches[0]?.environment).toMatchObject({
529 T3CODE_THREAD_ID: "thread-antigravity-ambient",
530 T3_ACP_MCP_ENDPOINT: "http://127.0.0.1:9/ambient",
531 T3_ACP_MCP_AUTHORIZATION: "Bearer ambient-token",
532 T3_ACP_MCP_NODE: "/ambient/node",
533 T3_ACP_MCP_ENTRYPOINT: "/ambient/entrypoint.mjs",
534 });
535 yield* h.assertClosed;
536 }),
537 );
538
539 it.effect.skipIf(windowsHost)(
540 "refuses to open a session on a PATH executable older than 1.5",
541 () =>
542 Effect.gen(function* () {
543 const h = yield* makeHarness();
544 const old = yield* h.makeExecutable("runtime old", { agentVersion: "1.4.5" });
545 h.controls.selected = { ...old, source: "path", version: null };
546 const threadId = ThreadId.make("thread-antigravity-old-runtime");
547 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
548 const error = yield* Effect.scoped(
549 Effect.gen(function* () {
550 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-old-runtime-" });
551 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
552 runtimeMode: "approval-required",
553 interactionMode: "default",
554 cwd: workspace,
555 });
556 const session = yield* h.instance.orchestrationAdapter.openSession({
557 threadId,
558 providerSessionId: ProviderSessionId.make("provider-session-antigravity-old-runtime"),
559 modelSelection,
560 runtimePolicy,
561 });
562 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
563 }),
564 ).pipe(Effect.flip);
565 const message = `Antigravity 1.4.5 does not work with this T3 Code release. Update the Antigravity executable at ${old.executablePath} to >=1.5.12 <2, then retry.`;
566 expect(knownProviderFailureMessage(error)).toBe(message);
567 expect((yield* h.refresh().pipe(Effect.flip)).detail).toBe(message);
568 const methods = (yield* h.readRequests).map((request) => request.method);
569 expect(methods).toContain("initialize");
570 expect(methods).not.toContain("session/new");
571 yield* h.assertClosed;
572 }),
573 );
574
575 it.effect.skipIf(windowsHost)(
576 "closes refresh processes and clears account metadata when Google sign-in is required",
577 () =>
578 Effect.gen(function* () {
579 const h = yield* makeHarness();
580 yield* h.refresh();
581 h.controls.selected = h.signedOut;
582 const error = yield* h.refresh().pipe(Effect.flip);
583 expect(error.detail).toContain("Sign in to Antigravity");
584 const snapshot = yield* h.instance.snapshot.getSnapshot;
585 expect(snapshot.auth.status).toBe("unauthenticated");
586 expect(snapshot.models).toEqual([]);
587 expect(snapshot.slashCommands).toEqual([]);
588 expect(snapshot.supportsTextGeneration).toBe(false);
589 expect(h.acquisitions).toHaveLength(2);
590 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
591 yield* h.assertClosed;
592 }),
593 );
594
595 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
596 Effect.gen(function* () {
597 const h = yield* makeHarness();
598 yield* h.refresh();
599 const before = yield* h.instance.snapshot.getSnapshot;
600 h.controls.failResolution = true;
601 const error = yield* h.refresh().pipe(Effect.flip);
602 expect(error.detail).toBe("Fixture resolution failed.");
603 const after = yield* h.instance.snapshot.getSnapshot;
604 expect(after.models).toEqual(before.models);
605 expect(after.auth).toEqual(before.auth);
606 expect(h.acquisitions).toHaveLength(2);
607 expect(h.releases).toEqual([h.first.version]);
608 yield* h.assertClosed;
609 }),
610 );
611
612 it.effect.skipIf(windowsHost)(
613 "reports the missing SOCKS dependency when session creation fails and keeps the catalog",
614 () =>
615 Effect.gen(function* () {
616 const h = yield* makeHarness();
617 yield* h.refresh();
618 const before = yield* h.instance.snapshot.getSnapshot;
619 h.controls.selected = yield* h.makeExecutable("runtime socks", {
620 newSessionErrorData: { details: "python-socks is required to use a SOCKS proxy" },
621 });
622 const error = yield* h.refresh().pipe(Effect.flip);
623 expect(error.detail).toBe(
624 "Could not refresh Antigravity models. The previous model list is unchanged. Antigravity reported: python-socks is required to use a SOCKS proxy",
625 );
626 const after = yield* h.instance.snapshot.getSnapshot;
627 expect(after.models).toEqual(before.models);
628 expect(after.auth).toEqual(before.auth);
629 yield* h.assertClosed;
630 }),
631 );
632
633 it.effect.skipIf(windowsHost)(
634 "never copies unrecognized agent error details into the refresh error",
635 () =>
636 Effect.gen(function* () {
637 const h = yield* makeHarness();
638 yield* h.refresh();
639 const before = yield* h.instance.snapshot.getSnapshot;
640 const generic =
641 "Could not refresh Antigravity models. The previous model list is unchanged.";
642 const secret = "https://accounts.example.test/o/oauth2?code=sk-secret-123";
643 h.controls.selected = yield* h.makeExecutable("runtime socks with extra", {
644 newSessionErrorData: {
645 details: `Traceback (most recent call last):\n proxy ${secret}\npython-socks is required to use a SOCKS proxy`,
646 },
647 });
648 const known = yield* h.refresh().pipe(Effect.flip);
649 expect(known.detail).toBe(
650 `${generic} Antigravity reported: python-socks is required to use a SOCKS proxy`,
651 );
652
653 for (const [name, data] of [
654 ["runtime unknown details", { details: `Token refresh failed for ${secret}` }],
655 ["runtime object details", { details: { stack: "secret frame", env: { HOME: "/" } } }],
656 ["runtime no details", ["python-socks is required to use a SOCKS proxy"]],
657 ] as const) {
658 h.controls.selected = yield* h.makeExecutable(name, { newSessionErrorData: data });
659 const error = yield* h.refresh().pipe(Effect.flip);
660 expect(error.detail).toBe(generic);
661 }
662 const after = yield* h.instance.snapshot.getSnapshot;
663 expect(after.models).toEqual(before.models);
664 expect(after.auth).toEqual(before.auth);
665 expect(JSON.stringify(after)).not.toContain("sk-secret-123");
666 yield* h.assertClosed;
667 }),
668 );
669
670 it.effect.skipIf(windowsHost)(
671 "removes runtime temp directories left by a previous server on create",
672 () =>
673 Effect.gen(function* () {
674 const fs = yield* FileSystem.FileSystem;
675 const path = yield* Path.Path;
676 const config = yield* ServerConfig.ServerConfig;
677 const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
678 const directories = yield* resolveAntigravityInstanceDirectories(
679 config.stateDir,
680 instanceId,
681 );
682 const legacyRoot = path.join(directories.profile, "antigravity-acp", "tmp");
683 for (const root of [directories.runtimeTemp, legacyRoot]) {
684 const orphan = path.join(root, "run-orphan", "_MEI123", "google3");
685 yield* fs.makeDirectory(orphan, { recursive: true });
686 yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
687 }
688 yield* AntigravityDriver.create({
689 instanceId,
690 displayName: "Sweep",
691 enabled: false,
692 config: AntigravityDriver.defaultConfig(),
693 environment: [],
694 }).pipe(
695 Effect.provide(
696 Layer.mock(AntigravityInstallation.AntigravityInstallation)({
697 managedDirectory: config.stateDir,
698 resolve: () => Effect.die("unused"),
699 acquire: () => Effect.die("unused"),
700 }),
701 ),
702 );
703 expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
704 expect(yield* fs.exists(legacyRoot)).toBe(false);
705 }),
706 );
707
708 it.effect.skipIf(windowsHost)(
709 "keeps catalog default thinking levels when a chat session selects another level",
710 () =>
711 Effect.gen(function* () {
712 const h = yield* makeHarness({
713 environment: [
714 { name: "T3_ACP_ANTIGRAVITY_THOUGHT_LEVEL", value: "1" },
715 { name: "T3_ACP_RESUME_THOUGHT_LEVEL", value: "xhigh" },
716 ],
717 });
718 yield* h.refresh();
719 const levelOf = (snapshot: ServerProvider, slug: string) => {
720 const option = snapshot.models
721 .find((model) => model.slug === slug)
722 ?.capabilities?.optionDescriptors?.find(
723 (descriptor) => descriptor.id === "thought_level",
724 );
725 return option?.type === "select" ? option.currentValue : undefined;
726 };
727
728 const refreshed = yield* h.instance.snapshot.getSnapshot;
729 expect(levelOf(refreshed, "gemini-test-low")).toBe("high");
730 expect(levelOf(refreshed, "gemini-test-high")).toBe("medium");
731
732 const threadId = ThreadId.make("thread-antigravity-thought-level");
733 const xhighSelection = {
734 instanceId: h.instance.instanceId,
735 model: "gemini-test-low",
736 options: [{ id: "thought_level", value: "xhigh" }],
737 };
738 const nativeSessionId = yield* Effect.scoped(
739 Effect.gen(function* () {
740 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-thought-" });
741 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
742 runtimeMode: "approval-required",
743 interactionMode: "default",
744 cwd: workspace,
745 });
746 const session = yield* h.instance.orchestrationAdapter.openSession({
747 threadId,
748 providerSessionId: ProviderSessionId.make(
749 "provider-session-antigravity-thought-level",
750 ),
751 modelSelection: xhighSelection,
752 runtimePolicy,
753 });
754 const providerThread = yield* session.ensureThread({
755 threadId,
756 modelSelection: xhighSelection,
757 runtimePolicy,
758 });
759 const now = yield* DateTime.now;
760 yield* session.startTurn({
761 appThread: {
762 createdBy: "user",
763 creationSource: "web",
764 id: threadId,
765 projectId: ProjectId.make("project-antigravity-thought-level"),
766 title: "Antigravity thought level",
767 providerInstanceId: h.instance.instanceId,
768 modelSelection: xhighSelection,
769 runtimeMode: "approval-required",
770 interactionMode: "default",
771 branch: null,
772 worktreePath: null,
773 activeProviderThreadId: providerThread.id,
774 lineage: {
775 parentThreadId: null,
776 relationshipToParent: null,
777 rootThreadId: threadId,
778 },
779 forkedFrom: null,
780 createdAt: now,
781 updatedAt: now,
782 archivedAt: null,
783 settledOverride: null,
784 settledAt: null,
785 lastVisitedAt: null,
786 deletedAt: null,
787 },
788 threadId,
789 runId: RunId.make("run-antigravity-thought-level"),
790 runOrdinal: 1,
791 providerTurnOrdinal: 1,
792 attemptId: RunAttemptId.make("attempt-antigravity-thought-level"),
793 rootNodeId: NodeId.make("node-antigravity-thought-level"),
794 providerThread,
795 message: {
796 createdBy: "user",
797 creationSource: "web",
798 messageId: MessageId.make("message-antigravity-thought-level"),
799 text: "Say ok.",
800 attachments: [],
801 },
802 modelSelection: xhighSelection,
803 runtimePolicy,
804 });
805 yield* session.events.pipe(
806 Stream.takeUntil((event) => event.type === "turn.terminal"),
807 Stream.runDrain,
808 );
809 const nativeId = providerThread.nativeThreadRef?.nativeId;
810 if (!nativeId) {
811 return yield* Effect.die("Expected Antigravity session to have a native thread id");
812 }
813 return nativeId;
814 }),
815 );
816
817 const afterLiveSession = yield* h.instance.snapshot.getSnapshot;
818 expect(levelOf(afterLiveSession, "gemini-test-low")).toBe("high");
819 expect(levelOf(afterLiveSession, "gemini-test-high")).toBe("medium");
820 expect(
821 afterLiveSession.models.find((model) => model.slug === "gemini-test-low")?.isDefault,
822 ).toBe(true);
823 expect(
824 (yield* h.readRequests)
825 .filter(
826 (request) =>
827 request.method === "session/set_config_option" &&
828 request.params?.configId === "thought_level",
829 )
830 .map((request) => request.params?.value),
831 ).toEqual(["xhigh"]);
832
833 // Resuming a session whose saved level is xhigh must also keep the catalog default.
834 yield* Effect.scoped(
835 Effect.gen(function* () {
836 const workspace = yield* h.fs.makeTempDirectoryScoped({
837 prefix: "t3-ag-thought-resume-",
838 });
839 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
840 runtimeMode: "approval-required",
841 interactionMode: "default",
842 cwd: workspace,
843 });
844 const resumed = yield* h.instance.orchestrationAdapter.openSession({
845 threadId,
846 providerSessionId: ProviderSessionId.make(
847 "provider-session-antigravity-thought-level-resumed",
848 ),
849 modelSelection: xhighSelection,
850 runtimePolicy,
851 initialNativeThreadId: nativeSessionId,
852 });
853 yield* resumed.ensureThread({
854 threadId,
855 modelSelection: xhighSelection,
856 runtimePolicy,
857 });
858 }),
859 );
860 expect(levelOf(yield* h.instance.snapshot.getSnapshot, "gemini-test-low")).toBe("high");
861 yield* h.assertClosed;
862 }),
863 );
864});