Open History to see the last commit
1import * as path from "node:path";
2import * as os from "node:os";
3import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
4import { fileURLToPath } from "node:url";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { Effect } from "effect";
8import { describe, expect, it } from "vitest";
9import type * as EffectAcpSchema from "effect-acp/schema";
10import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
11import { createModelCapabilities } from "@t3tools/shared/model";
12
13import {
14 buildCursorProviderSnapshot,
15 buildCursorCapabilitiesFromConfigOptions,
16 buildCursorDiscoveredModelsFromConfigOptions,
17 discoverCursorModelCapabilitiesViaAcp,
18 discoverCursorModelsViaAcp,
19 getCursorFallbackModels,
20 getCursorParameterizedModelPickerUnsupportedMessage,
21 parseCursorAboutOutput,
22 parseCursorCliConfigChannel,
23 parseCursorVersionDate,
24 resolveCursorAcpBaseModelId,
25 resolveCursorAcpConfigUpdates,
26} from "./CursorProvider.ts";
27
28const __dirname = path.dirname(fileURLToPath(import.meta.url));
29const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
30
31function selectDescriptor(
32 id: string,
33 label: string,
34 options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
35) {
36 return {
37 id,
38 label,
39 type: "select" as const,
40 options: [...options],
41 ...(options.find((option) => option.isDefault)?.id
42 ? { currentValue: options.find((option) => option.isDefault)?.id }
43 : {}),
44 };
45}
46
47function booleanDescriptor(id: string, label: string, currentValue?: boolean) {
48 return {
49 id,
50 label,
51 type: "boolean" as const,
52 ...(typeof currentValue === "boolean" ? { currentValue } : {}),
53 };
54}
55
56async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
57 const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
58 const wrapperPath = path.join(dir, "fake-agent.sh");
59 const envExports = Object.entries(extraEnv ?? {})
60 .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
61 .join("\n");
62 const script = `#!/bin/sh
63${envExports}
64exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
65`;
66 await writeFile(wrapperPath, script, "utf8");
67 await chmod(wrapperPath, 0o755);
68 return wrapperPath;
69}
70
71async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
72 for (let attempt = 0; attempt < attempts; attempt += 1) {
73 try {
74 const content = await readFile(filePath, "utf8");
75 if (content.trim().length > 0) {
76 return content;
77 }
78 } catch {}
79 await new Promise((resolve) => setTimeout(resolve, 50));
80 }
81 throw new Error(`Timed out waiting for file content at ${filePath}`);
82}
83
84const parameterizedGpt54ConfigOptions = [
85 {
86 type: "select",
87 currentValue: "gpt-5.4-medium-fast",
88 options: [{ name: "GPT-5.4", value: "gpt-5.4-medium-fast" }],
89 category: "model",
90 id: "model",
91 name: "Model",
92 },
93 {
94 type: "select",
95 currentValue: "medium",
96 options: [
97 { name: "None", value: "none" },
98 { name: "Low", value: "low" },
99 { name: "Medium", value: "medium" },
100 { name: "High", value: "high" },
101 { name: "Extra High", value: "extra-high" },
102 ],
103 category: "thought_level",
104 id: "reasoning",
105 name: "Reasoning",
106 },
107 {
108 type: "select",
109 currentValue: "272k",
110 options: [
111 { name: "272K", value: "272k" },
112 { name: "1M", value: "1m" },
113 ],
114 category: "model_config",
115 id: "context",
116 name: "Context",
117 },
118 {
119 type: "select",
120 currentValue: "false",
121 options: [
122 { name: "Off", value: "false" },
123 { name: "Fast", value: "true" },
124 ],
125 category: "model_config",
126 id: "fast",
127 name: "Fast",
128 },
129] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
130
131const parameterizedClaudeConfigOptions = [
132 {
133 type: "select",
134 currentValue: "claude-4.6-opus-high-thinking",
135 options: [{ name: "Opus 4.6", value: "claude-4.6-opus-high-thinking" }],
136 category: "model",
137 id: "model",
138 name: "Model",
139 },
140 {
141 type: "select",
142 currentValue: "high",
143 options: [
144 { name: "Low", value: "low" },
145 { name: "Medium", value: "medium" },
146 { name: "High", value: "high" },
147 ],
148 category: "thought_level",
149 id: "reasoning",
150 name: "Reasoning",
151 },
152 {
153 type: "boolean",
154 currentValue: true,
155 category: "model_config",
156 id: "thinking",
157 name: "Thinking",
158 },
159] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
160
161const parameterizedClaudeModelOptionConfigOptions = [
162 {
163 type: "select",
164 currentValue: "claude-opus-4-6",
165 options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
166 category: "model",
167 id: "model",
168 name: "Model",
169 },
170 {
171 type: "select",
172 currentValue: "high",
173 options: [
174 { name: "Low", value: "low" },
175 { name: "Medium", value: "medium" },
176 { name: "High", value: "high" },
177 ],
178 category: "thought_level",
179 id: "reasoning",
180 name: "Reasoning",
181 },
182 {
183 type: "select",
184 currentValue: "max",
185 options: [
186 { name: "Low", value: "low" },
187 { name: "Medium", value: "medium" },
188 { name: "High", value: "high" },
189 { name: "Max", value: "max" },
190 ],
191 category: "model_option",
192 id: "effort",
193 name: "Effort",
194 },
195 {
196 type: "select",
197 currentValue: "true",
198 options: [
199 { name: "Off", value: "false" },
200 { name: "Fast", value: "true" },
201 ],
202 category: "model_config",
203 id: "fast",
204 name: "Fast",
205 },
206 {
207 type: "select",
208 currentValue: "true",
209 options: [
210 { name: "Off", value: "false" },
211 { name: ":icon-brain:", value: "true" },
212 ],
213 category: "model_config",
214 id: "thinking",
215 name: "Thinking",
216 },
217] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
218
219const sessionNewCursorConfigOptions = [
220 {
221 type: "select",
222 currentValue: "agent",
223 options: [
224 { name: "Agent", value: "agent", description: "Full agent capabilities with tool access" },
225 ],
226 category: "mode",
227 id: "mode",
228 name: "Mode",
229 description: "Controls how the agent executes tasks",
230 },
231 {
232 type: "select",
233 currentValue: "composer-2",
234 options: [
235 { name: "Auto", value: "default" },
236 { name: "Composer 2", value: "composer-2" },
237 { name: "GPT-5.4", value: "gpt-5.4" },
238 { name: "Sonnet 4.6", value: "claude-sonnet-4-6" },
239 { name: "Opus 4.6", value: "claude-opus-4-6" },
240 { name: "Codex 5.3 Spark", value: "gpt-5.3-codex-spark" },
241 ],
242 category: "model",
243 id: "model",
244 name: "Model",
245 description: "Controls which model is used for responses",
246 },
247 {
248 type: "select",
249 currentValue: "true",
250 options: [
251 { name: "Off", value: "false" },
252 { name: "Fast", value: "true" },
253 ],
254 category: "model_config",
255 id: "fast",
256 name: "Fast",
257 description: "Faster speeds.",
258 },
259] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
260
261const baseCursorSettings: CursorSettings = {
262 enabled: true,
263 binaryPath: "agent",
264 apiEndpoint: "",
265 customModels: [],
266};
267
268const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
269
270describe("getCursorFallbackModels", () => {
271 it("does not publish any built-in cursor models before ACP discovery", () => {
272 expect(
273 getCursorFallbackModels({
274 customModels: ["internal/cursor-model"],
275 }).map((model) => model.slug),
276 ).toEqual(["internal/cursor-model"]);
277 });
278});
279
280describe("buildCursorProviderSnapshot", () => {
281 it("downgrades ready status to warning when ACP model discovery times out", () => {
282 expect(
283 buildCursorProviderSnapshot({
284 checkedAt: "2026-01-01T00:00:00.000Z",
285 cursorSettings: baseCursorSettings,
286 parsed: {
287 version: "2026.04.09-f2b0fcd",
288 status: "ready",
289 auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
290 },
291 discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
292 }),
293 ).toMatchObject({
294 status: "warning",
295 message: "Cursor ACP model discovery timed out after 15000ms.",
296 models: [],
297 });
298 });
299
300 it("preserves provider error state while appending discovery warnings", () => {
301 expect(
302 buildCursorProviderSnapshot({
303 checkedAt: "2026-01-01T00:00:00.000Z",
304 cursorSettings: {
305 ...baseCursorSettings,
306 customModels: ["claude-sonnet-4-6"],
307 },
308 parsed: {
309 version: "2026.04.09-f2b0fcd",
310 status: "error",
311 auth: { status: "unauthenticated" },
312 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
313 },
314 discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
315 }),
316 ).toMatchObject({
317 status: "error",
318 message:
319 "Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
320 models: [
321 {
322 slug: "claude-sonnet-4-6",
323 isCustom: true,
324 },
325 ],
326 });
327 });
328});
329
330describe("buildCursorCapabilitiesFromConfigOptions", () => {
331 it("derives model capabilities from parameterized Cursor ACP config options", () => {
332 expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual(
333 createModelCapabilities({
334 optionDescriptors: [
335 selectDescriptor("reasoning", "Reasoning", [
336 { id: "low", label: "Low" },
337 { id: "medium", label: "Medium", isDefault: true },
338 { id: "high", label: "High" },
339 { id: "xhigh", label: "Extra High" },
340 ]),
341 selectDescriptor("contextWindow", "Context", [
342 { id: "272k", label: "272K", isDefault: true },
343 { id: "1m", label: "1M" },
344 ]),
345 booleanDescriptor("fastMode", "Fast", false),
346 ],
347 }),
348 );
349 });
350
351 it("detects boolean thinking toggles from model_config options", () => {
352 expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual(
353 createModelCapabilities({
354 optionDescriptors: [
355 selectDescriptor("reasoning", "Reasoning", [
356 { id: "low", label: "Low" },
357 { id: "medium", label: "Medium" },
358 { id: "high", label: "High", isDefault: true },
359 ]),
360 booleanDescriptor("thinking", "Thinking", true),
361 ],
362 }),
363 );
364 });
365
366 it("prefers the newer model_option effort control over legacy thought_level", () => {
367 expect(
368 buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
369 ).toEqual(
370 createModelCapabilities({
371 optionDescriptors: [
372 selectDescriptor("reasoning", "Effort", [
373 { id: "low", label: "Low" },
374 { id: "medium", label: "Medium" },
375 { id: "high", label: "High" },
376 { id: "max", label: "Max", isDefault: true },
377 ]),
378 booleanDescriptor("fastMode", "Fast", true),
379 booleanDescriptor("thinking", "Thinking", true),
380 ],
381 }),
382 );
383 });
384});
385
386describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
387 it("publishes ACP model choices immediately from session/new config options", () => {
388 expect(buildCursorDiscoveredModelsFromConfigOptions(sessionNewCursorConfigOptions)).toEqual([
389 {
390 slug: "default",
391 name: "Auto",
392 isCustom: false,
393 capabilities: emptyCapabilities,
394 },
395 {
396 slug: "composer-2",
397 name: "Composer 2",
398 isCustom: false,
399 capabilities: createModelCapabilities({
400 optionDescriptors: [booleanDescriptor("fastMode", "Fast", true)],
401 }),
402 },
403 {
404 slug: "gpt-5.4",
405 name: "GPT-5.4",
406 isCustom: false,
407 capabilities: emptyCapabilities,
408 },
409 {
410 slug: "claude-sonnet-4-6",
411 name: "Sonnet 4.6",
412 isCustom: false,
413 capabilities: emptyCapabilities,
414 },
415 {
416 slug: "claude-opus-4-6",
417 name: "Opus 4.6",
418 isCustom: false,
419 capabilities: emptyCapabilities,
420 },
421 {
422 slug: "gpt-5.3-codex-spark",
423 name: "Codex 5.3 Spark",
424 isCustom: false,
425 capabilities: emptyCapabilities,
426 },
427 ]);
428 });
429});
430
431describe("discoverCursorModelsViaAcp", () => {
432 it("keeps the ACP probe runtime alive long enough to discover models", async () => {
433 const wrapperPath = await makeMockAgentWrapper();
434
435 const models = await Effect.runPromise(
436 discoverCursorModelsViaAcp({
437 enabled: true,
438 binaryPath: wrapperPath,
439 apiEndpoint: "",
440 customModels: [],
441 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
442 );
443
444 expect(models.map((model) => model.slug)).toEqual([
445 "default",
446 "composer-2",
447 "gpt-5.4",
448 "claude-opus-4-6",
449 ]);
450 });
451
452 it("closes the ACP probe runtime after discovery completes", async () => {
453 const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
454 const exitLogPath = path.join(tempDir, "exit.log");
455 const wrapperPath = await makeMockAgentWrapper({
456 T3_ACP_EXIT_LOG_PATH: exitLogPath,
457 });
458
459 await Effect.runPromise(
460 discoverCursorModelsViaAcp({
461 enabled: true,
462 binaryPath: wrapperPath,
463 apiEndpoint: "",
464 customModels: [],
465 }).pipe(Effect.provide(NodeServices.layer)),
466 );
467
468 const exitLog = await waitForFileContent(exitLogPath);
469 expect(exitLog).toContain("SIGTERM");
470 });
471});
472
473describe("discoverCursorModelCapabilitiesViaAcp", () => {
474 it("closes all ACP probe runtimes after capability enrichment completes", async () => {
475 const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
476 const exitLogPath = path.join(tempDir, "exit.log");
477 const wrapperPath = await makeMockAgentWrapper({
478 T3_ACP_EXIT_LOG_PATH: exitLogPath,
479 });
480 const existingModels: ReadonlyArray<ServerProviderModel> = [
481 { slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
482 { slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
483 { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
484 {
485 slug: "claude-opus-4-6",
486 name: "Opus 4.6",
487 isCustom: false,
488 capabilities: emptyCapabilities,
489 },
490 ];
491
492 const models = await Effect.runPromise(
493 discoverCursorModelCapabilitiesViaAcp(
494 {
495 enabled: true,
496 binaryPath: wrapperPath,
497 apiEndpoint: "",
498 customModels: [],
499 },
500 existingModels,
501 ).pipe(Effect.provide(NodeServices.layer)),
502 );
503
504 expect(models.map((model) => model.slug)).toEqual([
505 "default",
506 "composer-2",
507 "gpt-5.4",
508 "claude-opus-4-6",
509 ]);
510
511 const exitLog = await waitForFileContent(exitLogPath);
512 expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
513 });
514});
515
516describe("parseCursorAboutOutput", () => {
517 it("parses json about output and forwards subscription metadata", () => {
518 expect(
519 parseCursorAboutOutput({
520 code: 0,
521 stdout: JSON.stringify({
522 cliVersion: "2026.04.09-f2b0fcd",
523 subscriptionTier: "Team",
524 userEmail: "jmarminge@gmail.com",
525 }),
526 stderr: "",
527 }),
528 ).toEqual({
529 version: "2026.04.09-f2b0fcd",
530 status: "ready",
531 auth: {
532 status: "authenticated",
533 type: "Team",
534 label: "Cursor Team Subscription",
535 },
536 });
537 });
538
539 it("treats json about output with a logged-out email as unauthenticated", () => {
540 expect(
541 parseCursorAboutOutput({
542 code: 0,
543 stdout: JSON.stringify({
544 cliVersion: "2026.04.09-f2b0fcd",
545 subscriptionTier: "Team",
546 userEmail: "Not logged in",
547 }),
548 stderr: "",
549 }),
550 ).toEqual({
551 version: "2026.04.09-f2b0fcd",
552 status: "error",
553 auth: {
554 status: "unauthenticated",
555 },
556 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
557 });
558 });
559
560 it("treats json about output with a null email as unauthenticated", () => {
561 expect(
562 parseCursorAboutOutput({
563 code: 0,
564 stdout: JSON.stringify({
565 cliVersion: "2026.04.09-f2b0fcd",
566 subscriptionTier: null,
567 userEmail: null,
568 }),
569 stderr: "",
570 }),
571 ).toEqual({
572 version: "2026.04.09-f2b0fcd",
573 status: "error",
574 auth: {
575 status: "unauthenticated",
576 },
577 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
578 });
579 });
580});
581
582describe("Cursor parameterized model picker preview gating", () => {
583 it("parses Cursor CLI version dates from build versions", () => {
584 expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408);
585 expect(parseCursorVersionDate("2026.04.09")).toBe(20260409);
586 expect(parseCursorVersionDate("not-a-version")).toBeUndefined();
587 });
588
589 it("parses the Cursor CLI channel from cli-config.json", () => {
590 expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab");
591 expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable");
592 expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined();
593 expect(parseCursorCliConfigChannel("not-json")).toBeUndefined();
594 });
595
596 it("returns no warning when the preview requirements are met", () => {
597 expect(
598 getCursorParameterizedModelPickerUnsupportedMessage({
599 version: "2026.04.08-c4e73a3",
600 channel: "lab",
601 }),
602 ).toBeUndefined();
603 });
604
605 it("explains when the Cursor Agent version is too old", () => {
606 expect(
607 getCursorParameterizedModelPickerUnsupportedMessage({
608 version: "2026.04.07-c4e73a3",
609 channel: "lab",
610 }),
611 ).toContain("too old");
612 });
613
614 it("explains when the Cursor Agent channel is not lab", () => {
615 expect(
616 getCursorParameterizedModelPickerUnsupportedMessage({
617 version: "2026.04.08-c4e73a3",
618 channel: "stable",
619 }),
620 ).toContain("lab channel");
621 });
622});
623
624describe("resolveCursorAcpBaseModelId", () => {
625 it("drops bracket traits without rewriting raw ACP model ids", () => {
626 expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4");
627 expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast");
628 expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe(
629 "claude-4.6-opus-high-thinking",
630 );
631 expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2");
632 expect(resolveCursorAcpBaseModelId("auto")).toBe("auto");
633 });
634});
635
636describe("resolveCursorAcpConfigUpdates", () => {
637 it("maps Cursor model options onto separate ACP config option updates", () => {
638 expect(
639 resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
640 { id: "reasoning", value: "xhigh" },
641 { id: "fastMode", value: true },
642 { id: "contextWindow", value: "1m" },
643 ]),
644 ).toEqual([
645 { configId: "reasoning", value: "extra-high" },
646 { configId: "context", value: "1m" },
647 { configId: "fast", value: "true" },
648 ]);
649 });
650
651 it("maps boolean thinking toggles when the model exposes them separately", () => {
652 expect(
653 resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, [
654 { id: "thinking", value: false },
655 ]),
656 ).toEqual([{ configId: "thinking", value: false }]);
657 });
658
659 it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
660 expect(
661 resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
662 { id: "fastMode", value: false },
663 ]),
664 ).toEqual([{ configId: "fast", value: "false" }]);
665 });
666
667 it("writes Cursor effort changes through the newer model_option config when available", () => {
668 expect(
669 resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [
670 { id: "reasoning", value: "max" },
671 { id: "thinking", value: false },
672 ]),
673 ).toEqual([
674 { configId: "effort", value: "max" },
675 { configId: "thinking", value: "false" },
676 ]);
677 });
678});