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 ProviderInstanceId,
8 ProviderSessionId,
9 ThreadId,
10 type AntigravitySettings,
11} from "@t3tools/contracts";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Path from "effect/Path";
17import * as Redacted from "effect/Redacted";
18import * as Schema from "effect/Schema";
19import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
20import { HttpClient } from "effect/http";
21
22import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
23import * as ServerConfig from "../../config.ts";
24import * as ServerSettings from "../../serverSettings.ts";
25import * as AntigravityInstallation from "../AntigravityInstallation.ts";
26import {
27 ANTIGRAVITY_AUTH_STDOUT_PREFIX,
28 resolveAntigravityInstanceDirectories,
29} from "../antigravityAuthSupport.ts";
30import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
31import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
32import * as ModelManifest from "../ModelManifest.ts";
33import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
34import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
35import { AntigravityDriver } from "./AntigravityDriver.ts";
36import * as ProviderHostLive from "../ProviderHostLive.ts";
37import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
38
39const hostPlatform = HostProcess.Platform.defaultValue();
40const windowsHost = hostPlatform === "win32";
41const decodeRequest = Schema.decodeEffect(
42 Schema.fromJsonString(
43 Schema.Struct({
44 method: Schema.optional(Schema.String),
45 params: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
46 }),
47 ),
48);
49const blockedCredentialKeys = new Set([
50 "GEMINI_API_KEY",
51 "GOOGLE_API_KEY",
52 "GOOGLE_APPLICATION_CREDENTIALS",
53 "GOOGLE_GENAI_USE_VERTEXAI",
54]);
55
56function shellQuote(value: string): string {
57 return `'${value.replaceAll("'", `'"'"'`)}'`;
58}
59
60const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
61 options: {
62 readonly config?: Partial<AntigravitySettings>;
63 readonly enabled?: boolean;
64 /** Extra instance variables, such as ones a parent T3 turn already exported. */
65 readonly environment?: ReadonlyArray<{ readonly name: string; readonly value: string }>;
66 } = {},
67) {
68 const fs = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const config = yield* ServerConfig.ServerConfig;
71 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
72 const nodePath = yield* HostProcess.ExecutablePath;
73 const baseEnv = yield* HostProcess.Environment;
74 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-driver-" });
75 const instanceId = ProviderInstanceId.make(path.basename(root));
76 const mockAgentPath = yield* path.fromFileUrl(
77 new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
78 );
79 const requestLog = path.join(root, "requests.jsonl");
80 const directories = yield* resolveAntigravityInstanceDirectories(config.stateDir, instanceId);
81 const profileDirectory = directories.profile;
82 const instancePath = `${path.join(root, "instance-bin")}:${baseEnv.PATH ?? ""}`;
83
84 const makeExecutable = Effect.fn("AntigravityDriverTest.makeExecutable")(function* (
85 name: string,
86 options: {
87 readonly loginRequired?: boolean;
88 /** `data` of the agent's "Internal error" response to `session/new`. */
89 readonly newSessionErrorData?: unknown;
90 readonly initialMode?: string;
91 } = {},
92 ) {
93 const directory = path.join(root, name);
94 const executablePath = path.join(directory, "agy_acp_server.par");
95 const harnessPath = path.join(directory, "localharness_external");
96 yield* fs.makeDirectory(directory, { recursive: true });
97 const authorizationUrl =
98 "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";
99 yield* fs.writeFileString(
100 executablePath,
101 [
102 "#!/bin/sh",
103 ...(options.loginRequired
104 ? [`printf '%s\\n' ${shellQuote(ANTIGRAVITY_AUTH_STDOUT_PREFIX + authorizationUrl)}`]
105 : []),
106 ...(options.newSessionErrorData === undefined
107 ? []
108 : [
109 `export T3_ACP_NEW_SESSION_ERROR_DATA=${shellQuote(JSON.stringify(options.newSessionErrorData))}`,
110 ]),
111 ...(options.initialMode === undefined
112 ? []
113 : [`export T3_ACP_INITIAL_MODE=${shellQuote(options.initialMode)}`]),
114 `exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`,
115 "",
116 ].join("\n"),
117 );
118 yield* fs.writeFileString(harnessPath, "#!/bin/sh\nexit 99\n");
119 yield* fs.chmod(executablePath, 0o755);
120 yield* fs.chmod(harnessPath, 0o755);
121 return {
122 executablePath,
123 harnessPath,
124 source: "managed",
125 version: name,
126 managedVersionDirectory: directory,
127 } satisfies AntigravityInstallation.AntigravityExecutable;
128 });
129
130 const first = yield* makeExecutable("runtime 'one");
131 const second = yield* makeExecutable("runtime two");
132 const signedOut = yield* makeExecutable("runtime signed-out", { loginRequired: true });
133 const controls: {
134 selected: AntigravityInstallation.AntigravityExecutable;
135 failResolution: boolean;
136 beforeAcquire: Effect.Effect<void>;
137 } = { selected: first, failResolution: false, beforeAcquire: Effect.void };
138 const acquisitions: Array<{ binaryPath: string | undefined; path: string | undefined }> = [];
139 const releases: Array<string | null> = [];
140 const launches: Array<{
141 command: string;
142 args: ReadonlyArray<string>;
143 cwd: string | undefined;
144 extendEnv: boolean | undefined;
145 environment: Record<string, string | undefined>;
146 profileDirectory: string | undefined;
147 harnessPath: string | undefined;
148 forceFileStorage: string | undefined;
149 credentialKeys: ReadonlyArray<string>;
150 geminiApiKey: string | undefined;
151 tempDirectory: string | undefined;
152 handle: ChildProcessSpawner.ChildProcessHandle;
153 }> = [];
154
155 const layerInstallation = Layer.mock(AntigravityInstallation.AntigravityInstallation)({
156 managedDirectory: root,
157 resolve: () =>
158 Effect.gen(function* () {
159 if (controls.failResolution) {
160 return yield* new AntigravityInstallation.AntigravityInstallationError({
161 operation: "resolve",
162 detail: "Fixture resolution failed.",
163 });
164 }
165 return controls.selected;
166 }),
167 acquire: (binaryPath, environment) =>
168 Effect.gen(function* () {
169 acquisitions.push({ binaryPath, path: environment?.PATH });
170 yield* controls.beforeAcquire;
171 if (controls.failResolution) {
172 return yield* new AntigravityInstallation.AntigravityInstallationError({
173 operation: "resolve",
174 detail: "Fixture resolution failed.",
175 });
176 }
177 const selected = controls.selected;
178 yield* Effect.addFinalizer(() =>
179 Effect.sync(() => {
180 releases.push(selected.version);
181 }),
182 );
183 return selected;
184 }),
185 });
186 const observedSpawner = ChildProcessSpawner.make((command) =>
187 Effect.gen(function* () {
188 if (command._tag !== "StandardCommand")
189 return yield* Effect.die("Unexpected process pipeline.");
190 const handle = yield* spawner.spawn(command);
191 const environment = command.options.env ?? {};
192 const env = (name: string) => {
193 const value = environment[name];
194 return Redacted.isRedacted(value) ? Redacted.value(value) : value;
195 };
196 launches.push({
197 command: command.command,
198 args: command.args.map(String),
199 cwd: command.options.cwd,
200 extendEnv: command.options.extendEnv,
201 environment: Object.fromEntries(Object.keys(environment).map((name) => [name, env(name)])),
202 profileDirectory: env("GEMINI_HOME"),
203 harnessPath: env("ANTIGRAVITY_HARNESS_PATH"),
204 forceFileStorage: env("AGY_ACP_FORCE_FILE_STORAGE"),
205 credentialKeys: Object.keys(environment).filter((key) =>
206 blockedCredentialKeys.has(key.toUpperCase()),
207 ),
208 geminiApiKey: env("GEMINI_API_KEY"),
209 tempDirectory:
210 environment.ANTIGRAVITY_HARNESS_PATH === undefined ? undefined : env("TMPDIR"),
211 handle,
212 });
213 return handle;
214 }),
215 );
216 const instance = yield* AntigravityDriver.create({
217 instanceId,
218 displayName: "Google test account",
219 enabled: options.enabled ?? true,
220 config: { ...AntigravityDriver.defaultConfig(), ...options.config },
221 environment: [
222 { name: "PATH", value: instancePath },
223 { name: "T3_ACP_ANTIGRAVITY", value: "1" },
224 { name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
225 { name: "GEMINI_API_KEY", value: "must-not-be-used" },
226 { name: "google_api_key", value: "must-not-be-used" },
227 { name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
228 { name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
229 { name: "GEMINI_HOME", value: "/must-not-be-used" },
230 { name: "ANTIGRAVITY_HARNESS_PATH", value: "/must-not-be-used" },
231 { name: "BROWSER", value: "must-not-run" },
232 ...(options.environment ?? []),
233 ].map((variable) => ({ ...variable, sensitive: false })),
234 }).pipe(
235 Effect.provide(layerInstallation),
236 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
237 );
238 const refresh = instance.refreshModels;
239 if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
240 const readRequests = Effect.gen(function* () {
241 if (!(yield* fs.exists(requestLog))) return [];
242 const text = yield* fs.readFileString(requestLog);
243 return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
244 decodeRequest(line),
245 );
246 });
247 const assertClosed = Effect.gen(function* () {
248 for (const launch of launches) {
249 yield* launch.handle.exitCode.pipe(Effect.ignore);
250 expect(yield* launch.handle.isRunning).toBe(false);
251 if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
252 if (launch.tempDirectory) expect(yield* fs.exists(launch.tempDirectory)).toBe(false);
253 }
254 });
255 return {
256 instance,
257 refresh,
258 makeExecutable,
259 fs,
260 path,
261 profileDirectory,
262 directories,
263 instancePath,
264 first,
265 second,
266 signedOut,
267 controls,
268 acquisitions,
269 releases,
270 launches,
271 readRequests,
272 assertClosed,
273 };
274});
275
276const layerDeps = ServerConfig.layerTest(process.cwd(), {
277 prefix: "t3-antigravity-driver-config-",
278}).pipe(
279 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
280 Layer.provideMerge(
281 Layer.succeed(
282 HttpClient.HttpClient,
283 HttpClient.make(() => Effect.die("Unexpected quota request")),
284 ),
285 ),
286 Layer.provideMerge(ServerSettings.layerTest()),
287 Layer.provideMerge(
288 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
289 shouldRunScopeWork: () => Effect.succeed(false),
290 }),
291 ),
292 Layer.provideMerge(
293 Layer.succeed(
294 ProviderEventLoggers.ProviderEventLoggers,
295 ProviderEventLoggers.NoOpProviderEventLoggers,
296 ),
297 ),
298 Layer.provideMerge(ModelManifest.layerTest),
299 Layer.provideMerge(IdAllocator.layer),
300 Layer.provideMerge(McpProviderSessions.layer),
301);
302const layerTest = ProviderHostLive.layer.pipe(
303 Layer.provideMerge(ServerSecretStore.layer),
304 Layer.provideMerge(layerDeps),
305);
306
307it.layer(layerTest)("AntigravityDriver", (it) => {
308 it.effect.skipIf(windowsHost)(
309 "refreshes the selected executable and limits form capabilities to chat",
310 () =>
311 Effect.gen(function* () {
312 const h = yield* makeHarness();
313 yield* h.refresh();
314 const snapshot = yield* h.instance.snapshot.getSnapshot;
315 expect(snapshot.status).toBe("ready");
316 expect(snapshot.auth.status).toBe("authenticated");
317 expect(snapshot.models.map((model) => model.slug)).toEqual([
318 "gemini-test-low",
319 "gemini-test-high",
320 ]);
321 expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
322 expect(snapshot.models.every((model) => model.isLegacy !== true)).toBe(true);
323 expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
324 expect(snapshot.supportsTextGeneration).toBe(true);
325 h.controls.selected = h.second;
326 yield* h.refresh();
327
328 expect(h.acquisitions).toEqual([
329 { binaryPath: "", path: h.instancePath },
330 { binaryPath: "", path: h.instancePath },
331 ]);
332 const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
333 expect(nativeLaunches.map((launch) => launch.command)).toEqual([
334 h.first.executablePath,
335 h.second.executablePath,
336 ]);
337 expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
338 h.first.harnessPath,
339 h.second.harnessPath,
340 ]);
341 for (const launch of nativeLaunches) {
342 expect(launch.args).toEqual([
343 ...(hostPlatform === "linux" ? ["--uid="] : []),
344 "--alsologtostderr",
345 ]);
346 expect(launch.profileDirectory).toBe(h.profileDirectory);
347 expect(launch.forceFileStorage).toBe("1");
348 expect(launch.extendEnv).toBe(false);
349 }
350 for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
351 expect(h.releases).toEqual([h.first.version, h.second.version]);
352 const requests = yield* h.readRequests;
353 expect(requests.map((request) => request.method)).toEqual([
354 "initialize",
355 "auth/login",
356 "session/new",
357 "initialize",
358 "auth/login",
359 "session/new",
360 ]);
361 expect(
362 requests
363 .filter((request) => request.method === "auth/login")
364 .map((request) => request.params?.methodId),
365 ).toEqual(["oauth-personal", "oauth-personal"]);
366 expect(
367 requests
368 .filter((request) => request.method === "session/new")
369 .map((request) => request.params?.mcpServers),
370 ).toEqual([[], []]);
371 yield* h.assertClosed;
372 yield* h.instance.textGeneration
373 .generateThreadTitle({
374 cwd: h.profileDirectory,
375 message: "Name this thread",
376 modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
377 })
378 .pipe(Effect.ignore);
379 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-chat-" });
380 const threadId = ThreadId.make("thread-antigravity-capabilities");
381 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
382 runtimeMode: "approval-required",
383 interactionMode: "default",
384 cwd: workspace,
385 });
386 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
387 const session = yield* h.instance.orchestrationAdapter.openSession({
388 threadId,
389 providerSessionId: ProviderSessionId.make("provider-session-antigravity-capabilities"),
390 modelSelection,
391 runtimePolicy,
392 });
393 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
394
395 const helper = {
396 fs: { readTextFile: false, writeTextFile: false },
397 terminal: false,
398 session: { notices: {}, compaction: {} },
399 };
400 expect(
401 (yield* h.readRequests)
402 .filter((request) => request.method === "initialize")
403 .map((request) => request.params?.clientCapabilities),
404 ).toEqual([
405 // Two model refreshes, then thread title generation.
406 helper,
407 helper,
408 helper,
409 {
410 fs: { readTextFile: true, writeTextFile: false },
411 terminal: false,
412 session: { notices: {}, compaction: {} },
413 elicitation: { form: {} },
414 },
415 ]);
416
417 // The agy CLI rejects `yolo` and `auto_edit`; it stays in `default` and T3 answers its requests.
418 h.controls.selected = {
419 ...(yield* h.makeExecutable("runtime cli", { initialMode: "auto_edit" })),
420 harnessPath: null,
421 };
422 for (const runtimeMode of ["full-access", "auto-accept-edits"] as const) {
423 const requestsBefore = (yield* h.readRequests).length;
424 const cliThreadId = ThreadId.make(`thread-antigravity-cli-${runtimeMode}`);
425 const cliPolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
426 runtimeMode,
427 interactionMode: "default",
428 cwd: workspace,
429 });
430 const cliSession = yield* h.instance.orchestrationAdapter.openSession({
431 threadId: cliThreadId,
432 providerSessionId: ProviderSessionId.make(`provider-session-cli-${runtimeMode}`),
433 modelSelection,
434 runtimePolicy: cliPolicy,
435 });
436 yield* cliSession.ensureThread({
437 threadId: cliThreadId,
438 modelSelection,
439 runtimePolicy: cliPolicy,
440 });
441 expect(h.launches.at(-1)?.args).toEqual([
442 "acp",
443 "--gemini-dir",
444 h.profileDirectory,
445 "--app-data-dir",
446 "antigravity-acp",
447 ]);
448 expect(
449 (yield* h.readRequests)
450 .slice(requestsBefore)
451 .filter(
452 (request) =>
453 request.method === "session/set_config_option" &&
454 request.params?.configId === "mode",
455 )
456 .map((request) => request.params?.value),
457 ).toEqual(["default"]);
458 }
459 }),
460 );
461
462 it.effect.skipIf(windowsHost)(
463 "gives a thread session its own T3 thread and MCP fallback environment",
464 () =>
465 Effect.gen(function* () {
466 const h = yield* makeHarness({
467 environment: [
468 { name: "T3CODE_THREAD_ID", value: "thread-antigravity-ambient" },
469 { name: "T3_ACP_MCP_ENDPOINT", value: "http://127.0.0.1:9/ambient" },
470 { name: "T3_ACP_MCP_AUTHORIZATION", value: "Bearer ambient-token" },
471 { name: "T3_ACP_MCP_NODE", value: "/ambient/node" },
472 { name: "T3_ACP_MCP_ENTRYPOINT", value: "/ambient/entrypoint.mjs" },
473 ],
474 });
475 yield* h.refresh();
476 const endpoint = "http://127.0.0.1:43126/mcp";
477 const threadId = ThreadId.make("thread-antigravity-process-environment");
478 yield* (yield* McpProviderSessions.McpProviderSessions).set({
479 environmentId: EnvironmentId.make("environment-antigravity-process-environment"),
480 threadId,
481 providerSessionId: "mcp-session-antigravity-process-environment",
482 providerInstanceId: h.instance.instanceId,
483 endpoint,
484 authorizationHeader: "Bearer antigravity-thread-token",
485 browserToolsAvailable: false,
486 });
487 // Running from source, the fallback entrypoint is this process's script.
488 const entrypoint = h.path.resolve(process.argv[1]!);
489 yield* Effect.scoped(
490 Effect.gen(function* () {
491 const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-environment-" });
492 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
493 runtimeMode: "approval-required",
494 interactionMode: "default",
495 cwd: workspace,
496 });
497 const modelSelection = { instanceId: h.instance.instanceId, model: "gemini-test-low" };
498 const session = yield* h.instance.orchestrationAdapter.openSession({
499 threadId,
500 providerSessionId: ProviderSessionId.make(
501 "provider-session-antigravity-process-environment",
502 ),
503 modelSelection,
504 runtimePolicy,
505 });
506 yield* session.ensureThread({ threadId, modelSelection, runtimePolicy });
507 }),
508 );
509
510 // Gemini Enterprise can strip the native MCP servers, and the documented `acp-mcp-call`
511 // fallback reads these from the shell.
512 const agentLaunches = h.launches.filter(
513 (launch) => launch.command === h.first.executablePath,
514 );
515 expect(agentLaunches).toHaveLength(2);
516 expect(agentLaunches[1]?.environment).toMatchObject({
517 T3CODE_THREAD_ID: threadId,
518 T3_ACP_MCP_ENDPOINT: endpoint,
519 T3_ACP_MCP_AUTHORIZATION: "Bearer antigravity-thread-token",
520 T3_ACP_MCP_NODE: process.execPath,
521 T3_ACP_MCP_ENTRYPOINT: entrypoint,
522 });
523 // Model refresh and sign-in launches are not part of a thread.
524 expect(agentLaunches[0]?.environment).toMatchObject({
525 T3CODE_THREAD_ID: "thread-antigravity-ambient",
526 T3_ACP_MCP_ENDPOINT: "http://127.0.0.1:9/ambient",
527 T3_ACP_MCP_AUTHORIZATION: "Bearer ambient-token",
528 T3_ACP_MCP_NODE: "/ambient/node",
529 T3_ACP_MCP_ENTRYPOINT: "/ambient/entrypoint.mjs",
530 });
531 yield* h.assertClosed;
532 }),
533 );
534
535 it.effect.skipIf(windowsHost)(
536 "closes refresh processes and clears account metadata when Google sign-in is required",
537 () =>
538 Effect.gen(function* () {
539 const h = yield* makeHarness();
540 yield* h.refresh();
541 h.controls.selected = h.signedOut;
542 const error = yield* h.refresh().pipe(Effect.flip);
543 expect(error.detail).toContain("Sign in to Antigravity");
544 const snapshot = yield* h.instance.snapshot.getSnapshot;
545 expect(snapshot.auth.status).toBe("unauthenticated");
546 expect(snapshot.models).toEqual([]);
547 expect(snapshot.slashCommands).toEqual([]);
548 expect(snapshot.supportsTextGeneration).toBe(false);
549 expect(h.acquisitions).toHaveLength(2);
550 expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
551 yield* h.assertClosed;
552 }),
553 );
554
555 it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
556 Effect.gen(function* () {
557 const h = yield* makeHarness();
558 yield* h.refresh();
559 const before = yield* h.instance.snapshot.getSnapshot;
560 h.controls.failResolution = true;
561 const error = yield* h.refresh().pipe(Effect.flip);
562 expect(error.detail).toContain("previous model list is unchanged");
563 const after = yield* h.instance.snapshot.getSnapshot;
564 expect(after.models).toEqual(before.models);
565 expect(after.auth).toEqual(before.auth);
566 expect(h.acquisitions).toHaveLength(2);
567 expect(h.releases).toEqual([h.first.version]);
568 yield* h.assertClosed;
569 }),
570 );
571
572 it.effect.skipIf(windowsHost)(
573 "reports the missing SOCKS dependency when session creation fails and keeps the catalog",
574 () =>
575 Effect.gen(function* () {
576 const h = yield* makeHarness();
577 yield* h.refresh();
578 const before = yield* h.instance.snapshot.getSnapshot;
579 h.controls.selected = yield* h.makeExecutable("runtime socks", {
580 newSessionErrorData: { details: "python-socks is required to use a SOCKS proxy" },
581 });
582 const error = yield* h.refresh().pipe(Effect.flip);
583 expect(error.detail).toBe(
584 "Could not refresh Antigravity models. The previous model list is unchanged. Antigravity reported: python-socks is required to use a SOCKS proxy",
585 );
586 const after = yield* h.instance.snapshot.getSnapshot;
587 expect(after.models).toEqual(before.models);
588 expect(after.auth).toEqual(before.auth);
589 yield* h.assertClosed;
590 }),
591 );
592
593 it.effect.skipIf(windowsHost)(
594 "never copies unrecognized agent error details into the refresh error",
595 () =>
596 Effect.gen(function* () {
597 const h = yield* makeHarness();
598 yield* h.refresh();
599 const before = yield* h.instance.snapshot.getSnapshot;
600 const generic =
601 "Could not refresh Antigravity models. The previous model list is unchanged.";
602 const secret = "https://accounts.example.test/o/oauth2?code=sk-secret-123";
603 h.controls.selected = yield* h.makeExecutable("runtime socks with extra", {
604 newSessionErrorData: {
605 details: `Traceback (most recent call last):\n proxy ${secret}\npython-socks is required to use a SOCKS proxy`,
606 },
607 });
608 const known = yield* h.refresh().pipe(Effect.flip);
609 expect(known.detail).toBe(
610 `${generic} Antigravity reported: python-socks is required to use a SOCKS proxy`,
611 );
612
613 for (const [name, data] of [
614 ["runtime unknown details", { details: `Token refresh failed for ${secret}` }],
615 ["runtime object details", { details: { stack: "secret frame", env: { HOME: "/" } } }],
616 ["runtime no details", ["python-socks is required to use a SOCKS proxy"]],
617 ] as const) {
618 h.controls.selected = yield* h.makeExecutable(name, { newSessionErrorData: data });
619 const error = yield* h.refresh().pipe(Effect.flip);
620 expect(error.detail).toBe(generic);
621 }
622 const after = yield* h.instance.snapshot.getSnapshot;
623 expect(after.models).toEqual(before.models);
624 expect(after.auth).toEqual(before.auth);
625 expect(JSON.stringify(after)).not.toContain("sk-secret-123");
626 yield* h.assertClosed;
627 }),
628 );
629
630 it.effect.skipIf(windowsHost)(
631 "removes runtime temp directories left by a previous server on create",
632 () =>
633 Effect.gen(function* () {
634 const fs = yield* FileSystem.FileSystem;
635 const path = yield* Path.Path;
636 const config = yield* ServerConfig.ServerConfig;
637 const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
638 const directories = yield* resolveAntigravityInstanceDirectories(
639 config.stateDir,
640 instanceId,
641 );
642 const legacyRoot = path.join(directories.profile, "antigravity-acp", "tmp");
643 for (const root of [directories.runtimeTemp, legacyRoot]) {
644 const orphan = path.join(root, "run-orphan", "_MEI123", "google3");
645 yield* fs.makeDirectory(orphan, { recursive: true });
646 yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
647 }
648 yield* AntigravityDriver.create({
649 instanceId,
650 displayName: "Sweep",
651 enabled: false,
652 config: AntigravityDriver.defaultConfig(),
653 environment: [],
654 }).pipe(
655 Effect.provide(
656 Layer.mock(AntigravityInstallation.AntigravityInstallation)({
657 managedDirectory: config.stateDir,
658 resolve: () => Effect.die("unused"),
659 acquire: () => Effect.die("unused"),
660 }),
661 ),
662 );
663 expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
664 expect(yield* fs.exists(legacyRoot)).toBe(false);
665 }),
666 );
667});