@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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