Repository navigation
Expand file tree
/
Copy pathAntigravityDriver.test.ts
More file actions
550 lines (529 loc) · 21.5 KB
/
Copy pathAntigravityDriver.test.ts
File metadata and controls
550 lines (529 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import {
ANTIGRAVITY_DEFAULT_MODEL,
ProviderInstanceId,
type AntigravitySettings,
} from "@t3tools/contracts";
import {
HostProcessEnvironment,
HostProcessExecutablePath,
HostProcessIsExecutable,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as AntigravityInstallation from "../AntigravityInstallation.ts";
import {
ANTIGRAVITY_AUTH_STDOUT_PREFIX,
resolveAntigravityInstanceDirectories,
} from "../antigravityAuthSupport.ts";
import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
import * as ModelManifest from "../ModelManifest.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import { AntigravityDriver } from "./AntigravityDriver.ts";
import * as ProviderHostLive from "../ProviderHostLive.ts";
import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
const hostPlatform = HostProcessPlatform.defaultValue();
const windowsHost = hostPlatform === "win32";
const decodeRequest = Schema.decodeEffect(
Schema.fromJsonString(
Schema.Struct({
method: Schema.optional(Schema.String),
params: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
}),
),
);
const blockedCredentialKeys = new Set([
"GEMINI_API_KEY",
"GOOGLE_API_KEY",
"GOOGLE_APPLICATION_CREDENTIALS",
"GOOGLE_GENAI_USE_VERTEXAI",
]);
function shellQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const makeHarness = Effect.fn("makeAntigravityDriverHarness")(function* (
options: { readonly config?: Partial<AntigravitySettings>; readonly enabled?: boolean } = {},
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfig.ServerConfig;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const nodePath = yield* HostProcessExecutablePath;
const baseEnv = yield* HostProcessEnvironment;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-antigravity-driver-" });
const instanceId = ProviderInstanceId.make(path.basename(root));
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
const requestLog = path.join(root, "requests.jsonl");
const directories = yield* resolveAntigravityInstanceDirectories(config.stateDir, instanceId);
const profileDirectory = directories.profile;
const instancePath = `${path.join(root, "instance-bin")}:${baseEnv.PATH ?? ""}`;
const makeExecutable = Effect.fn("AntigravityDriverTest.makeExecutable")(function* (
name: string,
loginRequired = false,
) {
const directory = path.join(root, name);
const executablePath = path.join(directory, "agy_acp_server.par");
const harnessPath = path.join(directory, "localharness_external");
yield* fs.makeDirectory(directory, { recursive: true });
const authorizationUrl =
"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";
yield* fs.writeFileString(
executablePath,
[
"#!/bin/sh",
...(loginRequired
? [`printf '%s\\n' ${shellQuote(ANTIGRAVITY_AUTH_STDOUT_PREFIX + authorizationUrl)}`]
: []),
`exec ${shellQuote(nodePath)} ${shellQuote(mockAgentPath)} "$@"`,
"",
].join("\n"),
);
yield* fs.writeFileString(harnessPath, "#!/bin/sh\nexit 99\n");
yield* fs.chmod(executablePath, 0o755);
yield* fs.chmod(harnessPath, 0o755);
return {
executablePath,
harnessPath,
source: "managed",
version: name,
managedVersionDirectory: directory,
} satisfies AntigravityInstallation.AntigravityExecutable;
});
const first = yield* makeExecutable("runtime 'one");
const second = yield* makeExecutable("runtime two");
const signedOut = yield* makeExecutable("runtime signed-out", true);
const controls = { selected: first, failResolution: false, beforeAcquire: Effect.void };
const acquisitions: Array<{ binaryPath: string | undefined; path: string | undefined }> = [];
const releases: Array<string | null> = [];
const launches: Array<{
command: string;
args: ReadonlyArray<string>;
cwd: string | undefined;
extendEnv: boolean | undefined;
profileDirectory: string | undefined;
harnessPath: string | undefined;
forceFileStorage: string | undefined;
credentialKeys: ReadonlyArray<string>;
geminiApiKey: string | undefined;
tempDirectory: string | undefined;
handle: ChildProcessSpawner.ChildProcessHandle;
}> = [];
const layerInstallation = Layer.mock(AntigravityInstallation.AntigravityInstallation)({
managedDirectory: root,
resolve: () =>
Effect.gen(function* () {
if (controls.failResolution) {
return yield* new AntigravityInstallation.AntigravityInstallationError({
operation: "resolve",
detail: "Fixture resolution failed.",
});
}
return controls.selected;
}),
acquire: (binaryPath, environment) =>
Effect.gen(function* () {
acquisitions.push({ binaryPath, path: environment?.PATH });
yield* controls.beforeAcquire;
if (controls.failResolution) {
return yield* new AntigravityInstallation.AntigravityInstallationError({
operation: "resolve",
detail: "Fixture resolution failed.",
});
}
const selected = controls.selected;
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
releases.push(selected.version);
}),
);
return selected;
}),
});
const observedSpawner = ChildProcessSpawner.make((command) =>
Effect.gen(function* () {
if (command._tag !== "StandardCommand")
return yield* Effect.die("Unexpected process pipeline.");
const handle = yield* spawner.spawn(command);
const environment = command.options.env ?? {};
launches.push({
command: command.command,
args: command.args,
cwd: command.options.cwd,
extendEnv: command.options.extendEnv,
profileDirectory: environment.GEMINI_HOME,
harnessPath: environment.ANTIGRAVITY_HARNESS_PATH,
forceFileStorage: environment.AGY_ACP_FORCE_FILE_STORAGE,
credentialKeys: Object.keys(environment).filter((key) =>
blockedCredentialKeys.has(key.toUpperCase()),
),
geminiApiKey: environment.GEMINI_API_KEY,
// Only the agent gets a per-process temp directory. Other launches
// inherit the host TMPDIR.
tempDirectory:
environment.ANTIGRAVITY_HARNESS_PATH === undefined ? undefined : environment.TMPDIR,
handle,
});
return handle;
}),
);
const instance = yield* AntigravityDriver.create({
instanceId,
displayName: "Google test account",
enabled: options.enabled ?? false,
config: { ...AntigravityDriver.defaultConfig(), ...options.config },
environment: [
{ name: "PATH", value: instancePath },
{ name: "T3_ACP_ANTIGRAVITY", value: "1" },
{ name: "T3_ACP_REQUEST_LOG_PATH", value: requestLog },
{ name: "GEMINI_API_KEY", value: "must-not-be-used" },
{ name: "google_api_key", value: "must-not-be-used" },
{ name: "GOOGLE_APPLICATION_CREDENTIALS", value: "/must-not-be-used.json" },
{ name: "GOOGLE_GENAI_USE_VERTEXAI", value: "true" },
{ name: "GEMINI_HOME", value: "/must-not-be-used" },
{ name: "ANTIGRAVITY_HARNESS_PATH", value: "/must-not-be-used" },
{ name: "BROWSER", value: "must-not-run" },
].map((variable) => ({ ...variable, sensitive: false })),
}).pipe(
Effect.provide(layerInstallation),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, observedSpawner),
);
const refresh = instance.refreshModels;
if (!refresh) return yield* Effect.die("Antigravity does not expose model refresh.");
const readRequests = Effect.gen(function* () {
if (!(yield* fs.exists(requestLog))) return [];
const text = yield* fs.readFileString(requestLog);
return yield* Effect.forEach(text.split(/\r?\n/u).filter(Boolean), (line) =>
decodeRequest(line),
);
});
const assertClosed = Effect.gen(function* () {
for (const launch of launches) {
// Cancelled startup can report a signal instead of a numeric exit code.
yield* launch.handle.exitCode.pipe(Effect.ignore);
expect(yield* launch.handle.isRunning).toBe(false);
if (launch.cwd) expect(yield* fs.exists(launch.cwd)).toBe(false);
if (launch.tempDirectory) expect(yield* fs.exists(launch.tempDirectory)).toBe(false);
}
});
return {
instance,
refresh,
fs,
path,
profileDirectory,
directories,
instancePath,
first,
second,
signedOut,
controls,
acquisitions,
releases,
launches,
readRequests,
assertClosed,
};
});
const layerDeps = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-antigravity-driver-config-",
}).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
shouldRunScopeWork: () => Effect.succeed(false),
}),
),
Layer.provideMerge(
Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
),
),
Layer.provideMerge(ModelManifest.layerTest),
Layer.provideMerge(IdAllocator.layer),
);
const layerTest = ProviderHostLive.layer.pipe(
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(layerDeps),
);
it.layer(layerTest)("AntigravityDriver", (it) => {
it.effect.skipIf(windowsHost)(
"preserves the Node install message when starting a standalone provider",
() =>
Effect.gen(function* () {
const h = yield* makeHarness();
const error = yield* h.refresh().pipe(Effect.flip);
expect(error.detail).toContain("Install Node.js");
expect(h.launches).toEqual([]);
}).pipe(
Effect.scoped,
Effect.provideService(HostProcessIsExecutable, true),
Effect.provideService(HostProcessEnvironment, { PATH: "" }),
),
);
it.effect.skipIf(windowsHost)("does not launch a process for a disabled instance", () =>
Effect.gen(function* () {
const h = yield* makeHarness();
const snapshot = yield* h.instance.snapshot.refresh;
expect(snapshot.status).toBe("disabled");
expect(h.acquisitions).toEqual([]);
expect(h.launches).toEqual([]);
expect(yield* h.fs.exists(h.profileDirectory)).toBe(false);
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)("refreshes models after slow process startup", () =>
Effect.gen(function* () {
const h = yield* makeHarness();
const entered = yield* Deferred.make<void>();
const ready = yield* Deferred.make<void>();
h.controls.beforeAcquire = Deferred.succeed(entered, undefined).pipe(
Effect.andThen(Deferred.await(ready)),
);
const refresh = yield* h.refresh().pipe(Effect.forkScoped);
yield* Deferred.await(entered);
yield* TestClock.adjust("70 seconds");
yield* Deferred.succeed(ready, undefined);
yield* Fiber.join(refresh);
const snapshot = yield* h.instance.snapshot.getSnapshot;
expect(snapshot.auth.status).toBe("authenticated");
expect(snapshot.models.length).toBeGreaterThan(0);
yield* h.assertClosed;
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)(
"refreshes a disabled instance through the selected executable and personal Google ACP",
() =>
Effect.gen(function* () {
const h = yield* makeHarness();
yield* h.refresh();
const snapshot = yield* h.instance.snapshot.getSnapshot;
expect(snapshot.status).toBe("disabled");
expect(snapshot.auth.status).toBe("authenticated");
expect(snapshot.models.map((model) => model.slug)).toEqual([
"gemini-test-low",
"gemini-test-high",
]);
expect(snapshot.models[0]?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
expect(snapshot.models.every((model) => model.isLegacy !== true)).toBe(true);
expect(snapshot.slashCommands.map((command) => command.name)).toEqual(["plan", "logout"]);
expect(snapshot.supportsTextGeneration).toBe(true);
h.controls.selected = h.second;
yield* h.refresh();
expect(h.acquisitions).toEqual([
{ binaryPath: "", path: h.instancePath },
{ binaryPath: "", path: h.instancePath },
]);
const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
expect(nativeLaunches.map((launch) => launch.command)).toEqual([
h.first.executablePath,
h.second.executablePath,
]);
expect(nativeLaunches.map((launch) => launch.harnessPath)).toEqual([
h.first.harnessPath,
h.second.harnessPath,
]);
for (const launch of nativeLaunches) {
expect(launch.args).toEqual(hostPlatform === "linux" ? ["--uid="] : []);
expect(launch.profileDirectory).toBe(h.profileDirectory);
expect(launch.forceFileStorage).toBe("1");
expect(launch.extendEnv).toBe(false);
}
for (const launch of h.launches) expect(launch.credentialKeys).toEqual([]);
expect(h.releases).toEqual([h.first.version, h.second.version]);
const requests = yield* h.readRequests;
expect(requests.map((request) => request.method)).toEqual([
"initialize",
"auth/login",
"session/new",
"initialize",
"auth/login",
"session/new",
]);
expect(
requests
.filter((request) => request.method === "auth/login")
.map((request) => request.params?.methodId),
).toEqual(["oauth-personal", "oauth-personal"]);
expect(
requests
.filter((request) => request.method === "session/new")
.map((request) => request.params?.mcpServers),
).toEqual([[], []]);
yield* h.assertClosed;
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)(
"authenticates with the configured API key method and labels the account by method",
() =>
Effect.gen(function* () {
const h = yield* makeHarness({
config: { authMethod: "gemini-api-key", apiKey: "fixture-gemini-key" },
});
yield* h.refresh();
const snapshot = yield* h.instance.snapshot.getSnapshot;
expect(snapshot.auth).toMatchObject({
status: "authenticated",
type: "gemini-api-key",
label: "Gemini API key",
});
expect(snapshot.models.length).toBeGreaterThan(0);
const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined);
expect(nativeLaunches.map((launch) => launch.geminiApiKey)).toEqual(["fixture-gemini-key"]);
const requests = yield* h.readRequests;
expect(
requests
.filter((request) => request.method === "auth/login")
.map((request) => request.params?.methodId),
).toEqual(["gemini-api-key"]);
yield* h.assertClosed;
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)("reports the missing credential before launching a process", () =>
Effect.gen(function* () {
const h = yield* makeHarness({ config: { authMethod: "gemini-api-key" } });
const error = yield* h.refresh().pipe(Effect.flip);
expect(error.detail).toContain("API key");
expect(h.launches.filter((launch) => launch.harnessPath !== undefined)).toEqual([]);
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)(
"closes refresh processes and clears account metadata when Google sign-in is required",
() =>
Effect.gen(function* () {
const h = yield* makeHarness();
yield* h.refresh();
h.controls.selected = h.signedOut;
const error = yield* h.refresh().pipe(Effect.flip);
expect(error.detail).toContain("Sign in to Antigravity");
const snapshot = yield* h.instance.snapshot.getSnapshot;
expect(snapshot.auth.status).toBe("unauthenticated");
expect(snapshot.models).toEqual([]);
expect(snapshot.slashCommands).toEqual([]);
expect(snapshot.supportsTextGeneration).toBe(false);
expect(h.acquisitions).toHaveLength(2);
expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
yield* h.assertClosed;
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)(
"clears account metadata when a text helper needs Google sign-in",
() =>
Effect.gen(function* () {
const h = yield* makeHarness();
yield* h.refresh();
h.controls.selected = h.signedOut;
const error = yield* h.instance.textGeneration
.generateThreadTitle({
cwd: h.profileDirectory,
message: "Repair Google login",
modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" },
})
.pipe(Effect.flip);
expect(error._tag).toBe("TextGenerationError");
const snapshot = yield* h.instance.snapshot.getSnapshot;
expect(snapshot.auth.status).toBe("unauthenticated");
expect(snapshot.models).toEqual([]);
expect(snapshot.supportsTextGeneration).toBe(false);
expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
yield* h.assertClosed;
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
Effect.gen(function* () {
const h = yield* makeHarness();
yield* h.refresh();
const before = yield* h.instance.snapshot.getSnapshot;
h.controls.failResolution = true;
const error = yield* h.refresh().pipe(Effect.flip);
expect(error.detail).toContain("previous model list is unchanged");
const after = yield* h.instance.snapshot.getSnapshot;
expect(after.models).toEqual(before.models);
expect(after.auth).toEqual(before.auth);
expect(h.acquisitions).toHaveLength(2);
expect(h.releases).toEqual([h.first.version]);
yield* h.assertClosed;
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)(
"gives each process its own temp directory and removes it when the process closes",
() =>
Effect.gen(function* () {
const h = yield* makeHarness();
const tempRoot = h.directories.runtimeTemp;
yield* h.refresh();
yield* h.refresh();
const directories = h.launches.flatMap((launch) =>
launch.tempDirectory === undefined ? [] : [launch.tempDirectory],
);
expect(directories).toHaveLength(2);
for (const directory of directories) {
expect(h.path.dirname(directory)).toBe(tempRoot);
}
expect(new Set(directories).size).toBe(2);
yield* h.assertClosed;
}).pipe(Effect.scoped),
);
it.effect.skipIf(windowsHost)(
"removes runtime temp directories left by a previous server on create",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfig.ServerConfig;
const instanceId = ProviderInstanceId.make("antigravity-orphan-sweep");
const directories = yield* resolveAntigravityInstanceDirectories(
config.stateDir,
instanceId,
);
// Older builds unpacked inside the profile.
const legacyRoot = path.join(directories.profile, "antigravity-acp", "tmp");
for (const root of [directories.runtimeTemp, legacyRoot]) {
const orphan = path.join(root, "run-orphan", "_MEI123", "google3");
yield* fs.makeDirectory(orphan, { recursive: true });
yield* fs.writeFileString(path.join(orphan, "payload.bin"), "stale");
}
yield* AntigravityDriver.create({
instanceId,
displayName: "Sweep",
enabled: false,
config: AntigravityDriver.defaultConfig(),
environment: [],
}).pipe(
Effect.provide(
Layer.mock(AntigravityInstallation.AntigravityInstallation)({
managedDirectory: config.stateDir,
resolve: () => Effect.die("unused"),
acquire: () => Effect.die("unused"),
}),
),
);
expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
expect(yield* fs.exists(legacyRoot)).toBe(false);
}).pipe(Effect.scoped),
);
it.effect("probes through installation resolution without launching a process", () =>
Effect.gen(function* () {
const h = yield* makeHarness({ enabled: true });
const snapshot = yield* h.instance.snapshot.refresh;
expect(snapshot.installed).toBe(true);
expect(snapshot.version).toBe(h.first.version);
expect(h.launches).toEqual([]);
expect(h.acquisitions).toEqual([]);
}).pipe(Effect.scoped),
);
});