Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { describe, expect, it } from "@effect/vitest";
4import {
5 ANTIGRAVITY_DEFAULT_MODEL,
6 AntigravitySettings,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 ProviderSetupError,
10 type ServerProviderUsageLimits,
11} from "@t3tools/contracts";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Fiber from "effect/Fiber";
15import * as Layer from "effect/Layer";
16import * as Ref from "effect/Ref";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19import * as EffectAcpErrors from "effect-acp/errors";
20import type * as EffectAcpSchema from "effect-acp/compat";
21
22import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
23import * as ServerConfig from "../config.ts";
24import * as ServerSettings from "../serverSettings.ts";
25import * as ProviderHostLive from "./ProviderHostLive.ts";
26import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
27import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
28import type { ServerProvider } from "@t3tools/contracts";
29import {
30 buildAntigravityModelsFromSession,
31 makeAntigravityProvider,
32} from "./AntigravityProvider.ts";
33
34const decodeSettings = Schema.decodeSync(AntigravitySettings);
35const instanceId = ProviderInstanceId.make("antigravity-test");
36const driver = ProviderDriverKind.make("antigravity");
37
38const initializeResult = {
39 protocolVersion: 1,
40 agentCapabilities: {
41 loadSession: true,
42 promptCapabilities: { image: true, audio: true, embeddedContext: true },
43 sessionCapabilities: { list: {}, resume: {} },
44 },
45 authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
46 agentInfo: {
47 name: "antigravity-acp",
48 title: "Google Antigravity",
49 version: "agy_acp_server_20260818_01_RC01",
50 },
51} satisfies EffectAcpSchema.InitializeResponse;
52
53const modelOptions = [
54 { value: "gemini-3.8-flash-high", name: "Gemini 3.8 Flash (High)" },
55 { value: "gemini-3.8-flash-medium", name: "Gemini 3.8 Flash (Medium)" },
56 { value: "gemini-3.8-flash-low", name: "Gemini 3.8 Flash (Low)" },
57 { value: "gemini-3.7-flash-high", name: "Gemini 3.7 Flash (High)" },
58 { value: "gemini-3.7-flash-medium", name: "Gemini 3.7 Flash (Medium)" },
59 { value: "gemini-3.7-flash-low", name: "Gemini 3.7 Flash (Low)" },
60 { value: "gemini-3.6-flash-high", name: "Gemini 3.6 Flash (High)" },
61 { value: "gemini-3.6-flash-medium", name: "Gemini 3.6 Flash (Medium)" },
62 { value: "gemini-3.6-flash-low", name: "Gemini 3.6 Flash (Low)" },
63 { value: "gemini-pro-agent", name: "Gemini 3.1 Pro (High)" },
64 { value: "gemini-3.1-pro-low", name: "Gemini 3.1 Pro (Low)" },
65];
66
67const modelConfig = {
68 id: "model",
69 name: "Model",
70 category: "model",
71 type: "select",
72 currentValue: "gemini-3.7-flash-high",
73 options: modelOptions,
74} satisfies EffectAcpSchema.SessionConfigOption;
75
76const sessionSetupResult = {
77 sessionId: "session-1",
78 models: {
79 currentModelId: "gemini-3.7-flash-high",
80 availableModels: modelOptions.map((option) => ({ modelId: option.value, name: option.name })),
81 },
82 configOptions: [
83 modelConfig,
84 {
85 id: "mode",
86 name: "Session Mode",
87 category: "mode",
88 type: "select",
89 currentValue: "default",
90 options: [
91 { value: "default", name: "Default" },
92 { value: "yolo", name: "YOLO" },
93 ],
94 },
95 ],
96} satisfies EffectAcpSchema.NewSessionResponse;
97
98const started = {
99 sessionId: "session-1",
100 initializeResult,
101 sessionSetupResult,
102 modelConfigId: "model",
103} satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult;
104
105const commands = [
106 { name: "plan", description: "Create a plan", input: { type: "text", hint: "What to plan" } },
107 { name: "logout", description: "Sign out of Google" },
108] satisfies ReadonlyArray<EffectAcpSchema.AvailableCommand>;
109
110const expectedCommands = [
111 { name: "plan", description: "Create a plan", input: { hint: "What to plan" } },
112 { name: "logout", description: "Sign out of Google" },
113];
114
115const layerTest = ProviderHostLive.layer.pipe(
116 Layer.provideMerge(
117 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
118 shouldRunScopeWork: () => Effect.succeed(false),
119 }),
120 ),
121 Layer.provideMerge(ServerSettings.layerTest()),
122 Layer.provideMerge(ServerSecretStore.layer),
123 Layer.provide(
124 ServerConfig.layerTest(process.cwd(), { prefix: "t3-antigravity-provider-test-" }).pipe(
125 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
126 ),
127 ),
128);
129
130type ProbeError = EffectAcpErrors.AcpError | ProviderSetupError;
131
132const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (
133 options: {
134 readonly auth?: { readonly type: string; readonly label: string };
135 readonly enabled?: boolean;
136 readonly safe?: boolean;
137 readonly probeUsage?: Effect.Effect<ServerProviderUsageLimits>;
138 } = {},
139) {
140 const initialProbe = yield* Deferred.make<EffectAcpSchema.InitializeResponse, ProbeError>();
141 const probeCalls = yield* Ref.make(0);
142 const safetyCalls = yield* Ref.make(0);
143 const probe = yield* Ref.make<Effect.Effect<EffectAcpSchema.InitializeResponse, ProbeError>>(
144 Deferred.await(initialProbe),
145 );
146 const safety = yield* Ref.make<Effect.Effect<boolean>>(Effect.succeed(options.safe ?? true));
147 const provider = yield* makeAntigravityProvider(
148 decodeSettings({ enabled: options.enabled ?? true, customModels: ["do-not-seed-me"] }),
149 {
150 stampIdentity: (snapshot) => Effect.succeed({ ...snapshot, instanceId, driver }),
151 ...(options.auth ? { auth: options.auth } : {}),
152 ...(options.probeUsage ? { probeUsage: options.probeUsage } : {}),
153 probe: Ref.update(probeCalls, (count) => count + 1).pipe(
154 Effect.andThen(Ref.get(probe)),
155 Effect.flatten,
156 ),
157 supportsTextGeneration: Ref.update(safetyCalls, (count) => count + 1).pipe(
158 Effect.andThen(Ref.get(safety)),
159 Effect.flatten,
160 ),
161 },
162 );
163 const initialUpdate = yield* Stream.toPull(
164 provider.snapshot.streamChanges.pipe(
165 Stream.filter((snapshot) => snapshot.installed || snapshot.status === "error"),
166 ),
167 );
168 const initialize = Deferred.succeed(initialProbe, initializeResult).pipe(
169 Effect.andThen(initialUpdate),
170 Effect.asVoid,
171 );
172 // Subscribe before the trigger; yield the returned pull to await the publish.
173 const nextPublish = (predicate: (snapshot: ServerProvider) => boolean) =>
174 Stream.toPull(provider.snapshot.streamChanges.pipe(Stream.filter(predicate))).pipe(
175 Effect.map((pull) => pull.pipe(Effect.map((snapshots) => snapshots[0]))),
176 );
177 return {
178 provider,
179 probe,
180 probeCalls,
181 safety,
182 safetyCalls,
183 initialProbe,
184 initialUpdate,
185 initialize,
186 nextPublish,
187 };
188});
189
190describe("Antigravity model catalog", () => {
191 it("uses legacy session models only when model config is absent", () => {
192 const fromLegacy = buildAntigravityModelsFromSession({
193 models: sessionSetupResult.models,
194 });
195 expect(fromLegacy).toEqual(buildAntigravityModelsFromSession(sessionSetupResult));
196 expect(
197 buildAntigravityModelsFromSession({
198 ...sessionSetupResult,
199 configOptions: [{ ...modelConfig, options: [] }],
200 }),
201 ).toEqual([]);
202 });
203
204 it("flattens native option groups without combining distinct model IDs", () => {
205 const models = buildAntigravityModelsFromSession({
206 configOptions: [
207 {
208 ...modelConfig,
209 currentValue: "gemini-pro-agent",
210 options: [
211 { groupId: "Flash", name: "Flash", options: [modelOptions[3]!, modelOptions[4]!] },
212 { groupId: "Pro", name: "Pro", options: [modelOptions[9]!, modelOptions[3]!] },
213 ],
214 },
215 ],
216 });
217 expect(models.map((model) => model.slug)).toEqual([
218 "gemini-3.7-flash-high",
219 "gemini-3.7-flash-medium",
220 "gemini-pro-agent",
221 ]);
222 expect(models.find((model) => model.isDefault)?.slug).toBe("gemini-pro-agent");
223 expect(models.find((model) => model.aliases?.includes(ANTIGRAVITY_DEFAULT_MODEL))?.slug).toBe(
224 "gemini-pro-agent",
225 );
226 });
227
228 it("labels models that share a display name with their IDs", () => {
229 const models = buildAntigravityModelsFromSession({
230 configOptions: [
231 {
232 ...modelConfig,
233 currentValue: "gemini-3.8-flash",
234 options: [
235 { value: "gemini-3.8-flash", name: "Gemini 3.8 Flash" },
236 { value: "gemini-3.8-flash-preview", name: "Gemini 3.8 Flash" },
237 ],
238 },
239 ],
240 });
241 expect(models.map((model) => model.name)).toEqual([
242 "Gemini 3.8 Flash",
243 "Gemini 3.8 Flash (gemini-3.8-flash-preview)",
244 ]);
245 });
246
247 it("offers each model the thinking levels it reported when selected", () => {
248 const thinking = (currentValue: string) =>
249 ({
250 id: "thinking_level",
251 name: "Thinking Level",
252 category: "thought_level",
253 type: "select",
254 currentValue,
255 options: [
256 { value: "low", name: "Low" },
257 { value: "high", name: "High" },
258 ],
259 }) satisfies EffectAcpSchema.SessionConfigOption;
260 const models = buildAntigravityModelsFromSession(
261 {
262 configOptions: [
263 {
264 ...modelConfig,
265 currentValue: "gemini",
266 options: [
267 { value: "gemini", name: "Gemini" },
268 { value: "claude", name: "Claude" },
269 { value: "plain", name: "Plain" },
270 { value: "unseen", name: "Unseen" },
271 ],
272 },
273 thinking("high"),
274 ],
275 },
276 new Map([
277 ["claude", thinking("low")],
278 ["plain", null],
279 ]),
280 );
281 const thinkingOf = (slug: string) =>
282 models.find((model) => model.slug === slug)?.capabilities?.optionDescriptors?.[0];
283
284 expect(thinkingOf("gemini")).toMatchObject({ id: "thinking_level", currentValue: "high" });
285 expect(thinkingOf("claude")).toMatchObject({ id: "thinking_level", currentValue: "low" });
286 expect(thinkingOf("plain")).toBeUndefined();
287 expect(thinkingOf("unseen")).toMatchObject({ id: "thinking_level" });
288 expect(thinkingOf("unseen")).not.toHaveProperty("currentValue");
289 });
290});
291
292it.layer(layerTest)("Antigravity provider snapshots", (it) => {
293 it.effect("does not probe or run helper safety checks while disabled", () =>
294 Effect.scoped(
295 Effect.gen(function* () {
296 const harness = yield* makeHarness({ enabled: false });
297 const snapshot = yield* harness.provider.snapshot.refresh;
298 expect(snapshot).toMatchObject({
299 enabled: false,
300 installed: false,
301 status: "disabled",
302 auth: { status: "unknown" },
303 models: [],
304 setup: { canAuthenticate: true, canInstall: true },
305 showInteractionModeToggle: false,
306 supportsConversationRollback: false,
307 supportsTextGeneration: false,
308 });
309 expect(yield* Ref.get(harness.probeCalls)).toBe(0);
310 expect(yield* Ref.get(harness.safetyCalls)).toBe(0);
311 }),
312 ),
313 );
314
315 it.effect("treats initialize as installation proof, not account or model discovery", () =>
316 Effect.scoped(
317 Effect.gen(function* () {
318 for (const auth of [
319 undefined,
320 { type: "oauth-personal", label: "Google account" },
321 { type: "oauth-business", label: "Gemini Enterprise" },
322 { type: "gemini-api-key", label: "Gemini API key" },
323 { type: "agent-platform", label: "Agent Platform" },
324 ]) {
325 const harness = yield* makeHarness(auth ? { auth } : {});
326 expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({
327 installed: false,
328 status: "warning",
329 auth: { status: "unknown" },
330 models: [],
331 });
332 yield* harness.initialize;
333 const snapshot = yield* harness.provider.snapshot.getSnapshot;
334 expect(snapshot).toMatchObject({
335 installed: true,
336 status: "warning",
337 version: "agy_acp_server_20260818_01_RC01",
338 auth: { status: "unknown", ...(auth ? { type: auth.type } : {}) },
339 message:
340 auth?.type === "gemini-api-key" || auth?.type === "agent-platform"
341 ? `Antigravity is installed. Connect with ${auth.label} to load models.`
342 : "Antigravity is installed. Google account access is not checked yet.",
343 models: [],
344 });
345 expect(yield* Ref.get(harness.probeCalls)).toBe(1);
346 }
347 }),
348 ),
349 );
350
351 it.effect("publishes session metadata and native commands without another health probe", () =>
352 Effect.scoped(
353 Effect.gen(function* () {
354 const harness = yield* makeHarness();
355 yield* harness.initialize;
356 const nextReady = yield* Stream.toPull(
357 harness.provider.snapshot.streamChanges.pipe(
358 Stream.filter(
359 (snapshot) =>
360 snapshot.auth.status === "authenticated" && snapshot.slashCommands.length > 0,
361 ),
362 ),
363 );
364 yield* harness.provider.onSessionStarted(started, "/workspace");
365 yield* harness.provider.onAvailableCommands(commands, "/workspace");
366 const [snapshot] = yield* nextReady;
367 expect(snapshot).toMatchObject({
368 status: "ready",
369 auth: { status: "authenticated", type: "oauth-personal" },
370 supportsTextGeneration: true,
371 });
372 expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult));
373 expect(snapshot.slashCommands).toEqual(expectedCommands);
374 expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual(
375 expectedCommands,
376 );
377 expect(yield* Ref.get(harness.probeCalls)).toBe(1);
378 }),
379 ),
380 );
381
382 it.effect("clears all account metadata on sign-out and authentication failure", () =>
383 Effect.scoped(
384 Effect.gen(function* () {
385 const auth = { type: "gemini-api-key", label: "Gemini API key" };
386 const harness = yield* makeHarness({ auth });
387 yield* harness.initialize;
388 for (const clear of [harness.provider.onSignedOut, harness.provider.onAuthRequired]) {
389 yield* harness.provider.onSessionStarted(started, "/workspace");
390 yield* harness.provider.onAvailableCommands(commands, "/workspace");
391 yield* clear;
392 expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({
393 installed: true,
394 status: "warning",
395 auth: { status: "unauthenticated", type: auth.type, label: auth.label },
396 message: "Connect with Gemini API key to use Antigravity and load models.",
397 models: [],
398 slashCommands: [],
399 skills: [],
400 workspaceSnapshots: [],
401 supportsTextGeneration: false,
402 });
403 yield* harness.provider.onAvailableCommands(commands, "/workspace");
404 yield* harness.provider.onConfigOptionsUpdated([modelConfig]);
405 expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual([]);
406 expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]);
407 }
408 const refreshed = yield* harness.provider.snapshot.refresh;
409 expect(refreshed.auth).toEqual({
410 status: "unauthenticated",
411 type: auth.type,
412 label: auth.label,
413 });
414 expect(refreshed.message).toBe(
415 "Connect with Gemini API key to use Antigravity and load models.",
416 );
417 expect(refreshed.supportsTextGeneration).toBe(false);
418 }),
419 ),
420 );
421
422 it.effect("replaces live model choices and accepts an empty catalog", () =>
423 Effect.scoped(
424 Effect.gen(function* () {
425 const harness = yield* makeHarness();
426 yield* harness.initialize;
427 yield* harness.provider.onSessionStarted(started, "/workspace");
428 yield* harness.provider.onAvailableCommands(commands, "/workspace");
429 const before = yield* harness.provider.snapshot.getSnapshot;
430 const configOptions = [
431 {
432 ...modelConfig,
433 currentValue: "gemini-3.8-flash-high",
434 options: modelOptions.slice(0, 3),
435 },
436 ];
437 const nextSnapshot = yield* Stream.toPull(
438 harness.provider.snapshot.streamChanges.pipe(
439 Stream.filter((snapshot) => snapshot.models.length === 3),
440 ),
441 );
442 yield* harness.provider.onConfigOptionsUpdated(configOptions);
443 expect((yield* nextSnapshot)[0]).toMatchObject({
444 models: buildAntigravityModelsFromSession({ configOptions }),
445 auth: before.auth,
446 workspaceSnapshots: before.workspaceSnapshots,
447 slashCommands: expectedCommands,
448 });
449 yield* harness.provider.onConfigOptionsUpdated([]);
450 expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]);
451 }),
452 ),
453 );
454
455 it.effect("does not guess a version before a custom launcher's first handshake", () =>
456 Effect.scoped(
457 Effect.gen(function* () {
458 const harness = yield* makeHarness();
459 yield* Deferred.succeed(harness.initialProbe, {
460 ...initializeResult,
461 agentInfo: { ...initializeResult.agentInfo, version: "unknown" },
462 });
463 yield* harness.initialUpdate;
464 expect((yield* harness.provider.snapshot.getSnapshot).version).toBeNull();
465 }),
466 ),
467 );
468
469 it.effect("does not replace a handshake version with an unknown custom-launcher probe", () =>
470 Effect.scoped(
471 Effect.gen(function* () {
472 const harness = yield* makeHarness();
473 yield* harness.initialize;
474 yield* harness.provider.onSessionStarted({
475 ...started,
476 initializeResult: {
477 ...initializeResult,
478 agentInfo: { ...initializeResult.agentInfo, version: "1.4.0" },
479 },
480 });
481 yield* Ref.set(
482 harness.probe,
483 Effect.succeed({
484 ...initializeResult,
485 agentInfo: { ...initializeResult.agentInfo, version: "unknown" },
486 }),
487 );
488 expect((yield* harness.provider.snapshot.refresh).version).toBe("1.4.0");
489 }),
490 ),
491 );
492
493 it.effect("replaces one account's catalog instead of combining accounts", () =>
494 Effect.scoped(
495 Effect.gen(function* () {
496 const harness = yield* makeHarness();
497 yield* harness.initialize;
498 yield* harness.provider.onSessionStarted(started);
499 yield* harness.provider.onSignedOut;
500 yield* harness.provider.onSessionStarted({
501 ...started,
502 sessionSetupResult: {
503 sessionId: "new-account-session",
504 configOptions: [
505 { ...modelConfig, currentValue: "gemini-pro-agent", options: [modelOptions[9]!] },
506 ],
507 },
508 });
509 expect(
510 (yield* harness.provider.snapshot.getSnapshot).models.map((model) => model.slug),
511 ).toEqual(["gemini-pro-agent"]);
512 }),
513 ),
514 );
515
516 it.effect("retains known account metadata when a local health check fails", () =>
517 Effect.scoped(
518 Effect.gen(function* () {
519 const harness = yield* makeHarness();
520 yield* harness.initialize;
521 yield* harness.provider.onSessionStarted(started, "/workspace");
522 yield* harness.provider.onAvailableCommands(commands, "/workspace");
523 yield* Ref.set(
524 harness.probe,
525 Effect.fail(EffectAcpErrors.AcpRequestError.internalError("probe failed")),
526 );
527 const snapshot = yield* harness.provider.snapshot.refresh;
528 expect(snapshot).toMatchObject({
529 installed: true,
530 status: "error",
531 auth: { status: "authenticated" },
532 });
533 expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult));
534 expect(snapshot.slashCommands).toEqual(expectedCommands);
535 expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace");
536 }),
537 ),
538 );
539
540 it.effect("distinguishes missing executables from a failed installed executable", () =>
541 Effect.scoped(
542 Effect.gen(function* () {
543 const harness = yield* makeHarness();
544 yield* harness.initialize;
545 const failures = [
546 {
547 error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "ENOENT" } }),
548 installed: false,
549 },
550 {
551 error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "EACCES" } }),
552 installed: true,
553 },
554 {
555 error: new ProviderSetupError({
556 instanceId,
557 operation: "resolve",
558 detail: "Antigravity is not installed.",
559 }),
560 installed: false,
561 },
562 ];
563 for (const { error, installed } of failures) {
564 yield* harness.provider.onSessionStarted(started, "/workspace");
565 yield* harness.provider.onAvailableCommands(commands, "/workspace");
566 yield* Ref.set(harness.probe, Effect.fail(error));
567 const snapshot = yield* harness.provider.snapshot.refresh;
568 expect(snapshot).toMatchObject({
569 installed,
570 status: "error",
571 auth: { status: "authenticated" },
572 });
573 expect(snapshot.models).toHaveLength(installed ? 11 : 0);
574 expect(snapshot.slashCommands).toHaveLength(installed ? 2 : 0);
575 expect(snapshot.workspaceSnapshots).toHaveLength(installed ? 1 : 0);
576 expect(snapshot.supportsTextGeneration).toBe(installed);
577 }
578 }),
579 ),
580 );
581
582 it.effect("does not let an old health result restore a signed-out account", () =>
583 Effect.scoped(
584 Effect.gen(function* () {
585 const harness = yield* makeHarness();
586 yield* harness.initialize;
587 yield* harness.provider.onSessionStarted(started);
588 const releaseProbe = yield* Deferred.make<EffectAcpSchema.InitializeResponse>();
589 const probeEntered = yield* Deferred.make<void>();
590 yield* Ref.set(
591 harness.probe,
592 Deferred.succeed(probeEntered, undefined).pipe(
593 Effect.andThen(Deferred.await(releaseProbe)),
594 ),
595 );
596 const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild);
597 yield* Deferred.await(probeEntered);
598 yield* harness.provider.onSignedOut;
599 yield* Deferred.succeed(releaseProbe, initializeResult);
600 const snapshot = yield* Fiber.join(refresh);
601 expect(snapshot).toMatchObject({
602 auth: { status: "unauthenticated" },
603 models: [],
604 supportsTextGeneration: false,
605 });
606 }),
607 ),
608 );
609
610 it.effect("exposes helper support only when the supplied safety check allows it", () =>
611 Effect.scoped(
612 Effect.gen(function* () {
613 const harness = yield* makeHarness({ safe: false });
614 yield* harness.initialize;
615 yield* harness.provider.onSessionStarted(started);
616 expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(false);
617 yield* Ref.set(harness.safety, Effect.succeed(true));
618 yield* harness.provider.snapshot.refresh;
619 expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(true);
620 }),
621 ),
622 );
623
624 it.effect("keeps discovered workspace skills through session and command updates", () =>
625 Effect.scoped(
626 Effect.gen(function* () {
627 const harness = yield* makeHarness();
628 yield* harness.initialize;
629 const skills = [
630 {
631 name: "deploy",
632 description: "Ship it",
633 path: "/workspace/.agent/skills/deploy",
634 enabled: true,
635 },
636 ];
637 const discovered = yield* harness.provider.snapshotForCwd("/workspace", skills);
638 expect(discovered.skills).toEqual(skills);
639 yield* harness.provider.onSessionStarted(started, "/workspace");
640 yield* harness.provider.onAvailableCommands(commands, "/workspace");
641 const after = yield* harness.provider.snapshot.getSnapshot;
642 expect(
643 after.workspaceSnapshots?.find((entry) => entry.cwd === "/workspace")?.skills,
644 ).toEqual(skills);
645 expect((yield* harness.provider.snapshotForCwd("/workspace")).skills).toEqual(skills);
646
647 const rescanned = [
648 ...skills,
649 { name: "review", path: "/workspace/.agent/skills/review", enabled: true },
650 ];
651 yield* harness.provider.snapshotForCwd("/workspace", rescanned);
652 yield* harness.provider.onSessionStarted(started, "/workspace");
653 expect(
654 (yield* harness.provider.snapshot.getSnapshot).workspaceSnapshots?.find(
655 (entry) => entry.cwd === "/workspace",
656 )?.skills,
657 ).toEqual(rescanned);
658 }),
659 ),
660 );
661
662 it.effect("bounds workspace metadata without starting sessions for workspace lookup", () =>
663 Effect.scoped(
664 Effect.gen(function* () {
665 const harness = yield* makeHarness();
666 yield* harness.initialize;
667 yield* harness.provider.onSessionStarted(started);
668 for (let index = 0; index < 35; index++) {
669 yield* harness.provider.onAvailableCommands(commands, `/workspace-${index}`);
670 }
671 const snapshot = yield* harness.provider.snapshotForCwd("/workspace-34");
672 expect(snapshot.workspaceSnapshots).toHaveLength(32);
673 expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace-3");
674 expect(snapshot.slashCommands).toEqual(expectedCommands);
675 expect(yield* Ref.get(harness.probeCalls)).toBe(1);
676 }),
677 ),
678 );
679
680 it.effect(
681 "publishes limits, retains a successful read on failure, and clears them on sign-out",
682 () =>
683 Effect.scoped(
684 Effect.gen(function* () {
685 const limits: ServerProviderUsageLimits = {
686 checkedAt: "2026-10-09T12:00:00.000Z",
687 windows: [
688 {
689 id: "3p-weekly",
690 kind: "weekly",
691 label: "Claude & GPT (shared) · Weekly",
692 usedPercent: 75,
693 },
694 ],
695 };
696 const usage = yield* Ref.make(limits);
697 const harness = yield* makeHarness({ probeUsage: Ref.get(usage) });
698 const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
699 yield* harness.initialize;
700 expect((yield* published)?.usageLimits).toEqual(limits);
701 // The second health check is the one the failed background read triggers.
702 const checks = yield* Ref.make(0);
703 const failedReadApplied = yield* Deferred.make<void>();
704 yield* Ref.set(
705 harness.probe,
706 Ref.updateAndGet(checks, (count) => count + 1).pipe(
707 Effect.tap((count) =>
708 count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void,
709 ),
710 Effect.as(initializeResult),
711 ),
712 );
713 yield* Ref.set(usage, {
714 checkedAt: "2026-10-09T12:01:00.000Z",
715 windows: [],
716 unavailable: { reason: "probeFailed" },
717 });
718 yield* harness.provider.snapshot.refresh;
719 yield* Deferred.await(failedReadApplied);
720 expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
721 yield* harness.provider.onSignedOut;
722 expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
723 yield* Ref.set(usage, {
724 checkedAt: "2026-10-09T12:02:00.000Z",
725 windows: [],
726 unavailable: { reason: "unsupported" },
727 });
728 const unsupported = yield* harness.nextPublish(
729 (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported",
730 );
731 yield* harness.provider.snapshot.refresh;
732 expect((yield* unsupported)?.usageLimits?.windows).toEqual([]);
733 }),
734 ),
735 );
736
737 it.effect("a quota read finishing after sign-out cannot restore account limits", () =>
738 Effect.scoped(
739 Effect.gen(function* () {
740 const readStarted = yield* Deferred.make<void>();
741 const readResult = yield* Deferred.make<ServerProviderUsageLimits>();
742 const usage = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
743 Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }),
744 );
745 const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
746 yield* harness.initialize;
747 yield* Ref.set(harness.probe, Effect.succeed(initializeResult));
748 yield* Ref.set(
749 usage,
750 Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(readResult))),
751 );
752 const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild);
753 yield* Deferred.await(readStarted);
754 yield* harness.provider.onSignedOut;
755 yield* Deferred.succeed(readResult, {
756 checkedAt: "2026-10-09T12:01:00.000Z",
757 windows: [
758 { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 },
759 ],
760 });
761 yield* Fiber.join(refresh);
762 expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
763 }),
764 ),
765 );
766
767 it.effect("reports ready and starts sessions while one shared quota read is pending", () =>
768 Effect.scoped(
769 Effect.gen(function* () {
770 const reads = yield* Ref.make(0);
771 const readStarted = yield* Deferred.make<void>();
772 const readResult = yield* Deferred.make<ServerProviderUsageLimits>();
773 const harness = yield* makeHarness({
774 probeUsage: Ref.update(reads, (count) => count + 1).pipe(
775 Effect.andThen(Deferred.succeed(readStarted, undefined)),
776 Effect.andThen(Deferred.await(readResult)),
777 ),
778 });
779 const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
780 yield* harness.initialize;
781 yield* Deferred.await(readStarted);
782 yield* harness.provider.onSessionStarted(started, "/workspace");
783 yield* harness.provider.onSessionStarted(started, "/other");
784 const ready = yield* harness.provider.snapshot.getSnapshot;
785 expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } });
786 expect(ready.usageLimits).toBeUndefined();
787 expect(yield* Ref.get(reads)).toBe(1);
788 const limits = {
789 checkedAt: "2026-10-09T12:00:00.000Z",
790 windows: [
791 { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 },
792 ],
793 } satisfies ServerProviderUsageLimits;
794 yield* Deferred.succeed(readResult, limits);
795 expect((yield* published)?.usageLimits).toEqual(limits);
796 }),
797 ),
798 );
799
800 it.effect("a quota read for the previous account is dropped after a new sign-in", () =>
801 Effect.scoped(
802 Effect.gen(function* () {
803 const oldReadStarted = yield* Deferred.make<void>();
804 const newLimits = {
805 checkedAt: "2026-10-09T12:01:00.000Z",
806 windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }],
807 } satisfies ServerProviderUsageLimits;
808 const usage = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
809 Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)),
810 );
811 const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
812 const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
813 yield* harness.initialize;
814 yield* Deferred.await(oldReadStarted);
815 yield* Ref.set(usage, Effect.succeed(newLimits));
816 yield* harness.provider.onSignedIn;
817 yield* harness.provider.onSessionStarted(started);
818 expect((yield* published)?.usageLimits).toEqual(newLimits);
819 // Switching again must not republish the previous account's limits, even if the read fails.
820 const failed = {
821 checkedAt: "2026-10-09T12:02:00.000Z",
822 windows: [],
823 unavailable: { reason: "probeFailed" },
824 } satisfies ServerProviderUsageLimits;
825 yield* Ref.set(usage, Effect.succeed(failed));
826 const republished = yield* harness.nextPublish(
827 (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed",
828 );
829 yield* harness.provider.onSignedIn;
830 expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
831 yield* harness.provider.onSessionStarted(started);
832 expect((yield* republished)?.usageLimits).toEqual(failed);
833 }),
834 ),
835 );
836});