Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AntigravityProvider.test.ts

835 lines32.2 KB

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