Open History to see the last commit
1import * as NodeOS from "node:os";
2
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { it as effectIt } from "@effect/vitest";
5import type * as Crypto from "effect/Crypto";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Stream from "effect/Stream";
10import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
11import { describe, expect, it } from "vite-plus/test";
12import type * as EffectAcpSchema from "effect-acp/schema";
13import { ProviderDriverKind, ProviderInstanceId, type CursorSettings } from "@t3tools/contracts";
14import { createModelCapabilities } from "@t3tools/shared/model";
15
16import {
17 buildCursorProviderSnapshot,
18 buildCursorCapabilitiesFromConfigOptions,
19 checkCursorProviderStatus,
20 discoverCursorModelsViaAcp,
21 makeCursorModelDiscovery,
22 makeCursorCommandCatalog,
23 getCursorParameterizedModelPickerUnsupportedMessage,
24 parseCursorAboutOutput,
25 parseCursorCliConfigChannel,
26 parseCursorVersionDate,
27 resolveCursorAcpBaseModelId,
28 resolveCursorAcpConfigUpdates,
29} from "./CursorProvider.ts";
30import {
31 discoverCursorSkills,
32 hasCursorSkillMention,
33 probeCursorSkills,
34 rewriteCursorSkillMentions,
35} from "../Drivers/CursorSkills.ts";
36import { execScriptSource, writeFakeCli } from "../../testUtils/fakeCli.ts";
37import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
38import { HttpClient, HttpClientResponse } from "effect/unstable/http";
39import { cursorUsageResponseToLimits, readCursorUsageLimits } from "./cursorUsageLimits.ts";
40
41const runNode = <A, E>(
42 effect: Effect.Effect<
43 A,
44 E,
45 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
46 >,
47): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
48
49// Closing the probe kills the agent with SIGTERM; Windows terminates the
50// process instead, so the mock never sees a signal to log.
51const windowsHost = HostProcessPlatform.defaultValue() === "win32";
52
53const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
54 const path = yield* Path.Path;
55 return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url));
56});
57
58function selectDescriptor(
59 id: string,
60 label: string,
61 options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
62) {
63 return {
64 id,
65 label,
66 type: "select" as const,
67 options: [...options],
68 ...(options.find((option) => option.isDefault)?.id
69 ? { currentValue: options.find((option) => option.isDefault)?.id }
70 : {}),
71 };
72}
73
74function booleanDescriptor(id: string, label: string, currentValue?: boolean) {
75 return {
76 id,
77 label,
78 type: "boolean" as const,
79 ...(typeof currentValue === "boolean" ? { currentValue } : {}),
80 };
81}
82
83const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (
84 extraEnv?: Record<string, string>,
85) {
86 const fileSystem = yield* FileSystem.FileSystem;
87 const mockAgentPath = yield* resolveMockAgentPath();
88 const dir = yield* fileSystem.makeTempDirectory({
89 directory: NodeOS.tmpdir(),
90 prefix: "cursor-provider-mock-",
91 });
92 return writeFakeCli({
93 directory: dir,
94 name: "fake-agent",
95 env: extraEnv ?? {},
96 source: execScriptSource({ scriptPath: mockAgentPath }),
97 });
98});
99
100const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")(function* () {
101 const fileSystem = yield* FileSystem.FileSystem;
102 const mockAgentPath = yield* resolveMockAgentPath();
103 const dir = yield* fileSystem.makeTempDirectory({
104 directory: NodeOS.tmpdir(),
105 prefix: "cursor-provider-about-mock-",
106 });
107 return writeFakeCli({
108 directory: dir,
109 name: "fake-agent",
110 source: [
111 'if (process.argv[2] === "about") {',
112 ' process.stdout.write("CLI Version 2026.04.09-f2b0fcd\\n");',
113 ' process.stdout.write("User Email cursor@example.com\\n");',
114 " process.exit(0);",
115 "}",
116 execScriptSource({ scriptPath: mockAgentPath }),
117 ].join("\n"),
118 });
119});
120
121const waitForFileContent = Effect.fn("waitForFileContent")(function* (
122 filePath: string,
123 attempts = 40,
124) {
125 const fileSystem = yield* FileSystem.FileSystem;
126 for (let attempt = 0; attempt < attempts; attempt += 1) {
127 const content = yield* fileSystem
128 .readFileString(filePath)
129 .pipe(Effect.catch(() => Effect.void));
130 if (content !== undefined) {
131 if (content.trim().length > 0) {
132 return content;
133 }
134 }
135 yield* Effect.sleep("50 millis");
136 }
137 return yield* Effect.die(`Timed out waiting for file content at ${filePath}`);
138});
139
140const makeProviderStatusEnvFixture = Effect.fn("makeProviderStatusEnvFixture")(function* () {
141 const fileSystem = yield* FileSystem.FileSystem;
142 const path = yield* Path.Path;
143 const tempDir = yield* fileSystem.makeTempDirectory({
144 directory: NodeOS.tmpdir(),
145 prefix: "cursor-provider-status-env-",
146 });
147 return {
148 requestLogPath: path.join(tempDir, "requests.ndjson"),
149 wrapperPath: yield* makeMockAgentWithAboutWrapper(),
150 };
151});
152
153const makeExitLogFixture = Effect.fn("makeExitLogFixture")(function* (prefix: string) {
154 const fileSystem = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156 const tempDir = yield* fileSystem.makeTempDirectory({
157 directory: NodeOS.tmpdir(),
158 prefix,
159 });
160 const exitLogPath = path.join(tempDir, "exit.log");
161 return {
162 exitLogPath,
163 wrapperPath: yield* makeMockAgentWrapper({
164 T3_ACP_EXIT_LOG_PATH: exitLogPath,
165 }),
166 };
167});
168
169const parameterizedGpt54ConfigOptions = [
170 {
171 type: "select",
172 currentValue: "gpt-5.4-medium-fast",
173 options: [{ name: "GPT-5.4", value: "gpt-5.4-medium-fast" }],
174 category: "model",
175 id: "model",
176 name: "Model",
177 },
178 {
179 type: "select",
180 currentValue: "medium",
181 options: [
182 { name: "None", value: "none" },
183 { name: "Low", value: "low" },
184 { name: "Medium", value: "medium" },
185 { name: "High", value: "high" },
186 { name: "Extra High", value: "extra-high" },
187 ],
188 category: "thought_level",
189 id: "reasoning",
190 name: "Reasoning",
191 },
192 {
193 type: "select",
194 currentValue: "272k",
195 options: [
196 { name: "272K", value: "272k" },
197 { name: "1M", value: "1m" },
198 ],
199 category: "model_config",
200 id: "context",
201 name: "Context",
202 },
203 {
204 type: "select",
205 currentValue: "false",
206 options: [
207 { name: "Off", value: "false" },
208 { name: "Fast", value: "true" },
209 ],
210 category: "model_config",
211 id: "fast",
212 name: "Fast",
213 },
214] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
215
216const parameterizedClaudeConfigOptions = [
217 {
218 type: "select",
219 currentValue: "claude-4.6-opus-high-thinking",
220 options: [{ name: "Opus 4.6", value: "claude-4.6-opus-high-thinking" }],
221 category: "model",
222 id: "model",
223 name: "Model",
224 },
225 {
226 type: "select",
227 currentValue: "high",
228 options: [
229 { name: "Low", value: "low" },
230 { name: "Medium", value: "medium" },
231 { name: "High", value: "high" },
232 ],
233 category: "thought_level",
234 id: "reasoning",
235 name: "Reasoning",
236 },
237 {
238 type: "boolean",
239 currentValue: true,
240 category: "model_config",
241 id: "thinking",
242 name: "Thinking",
243 },
244] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
245
246const parameterizedClaudeModelOptionConfigOptions = [
247 {
248 type: "select",
249 currentValue: "claude-opus-4-6",
250 options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
251 category: "model",
252 id: "model",
253 name: "Model",
254 },
255 {
256 type: "select",
257 currentValue: "high",
258 options: [
259 { name: "Low", value: "low" },
260 { name: "Medium", value: "medium" },
261 { name: "High", value: "high" },
262 ],
263 category: "thought_level",
264 id: "reasoning",
265 name: "Reasoning",
266 },
267 {
268 type: "select",
269 currentValue: "max",
270 options: [
271 { name: "Low", value: "low" },
272 { name: "Medium", value: "medium" },
273 { name: "High", value: "high" },
274 { name: "Max", value: "max" },
275 ],
276 category: "model_option",
277 id: "effort",
278 name: "Effort",
279 },
280 {
281 type: "select",
282 currentValue: "true",
283 options: [
284 { name: "Off", value: "false" },
285 { name: "Fast", value: "true" },
286 ],
287 category: "model_config",
288 id: "fast",
289 name: "Fast",
290 },
291 {
292 type: "select",
293 currentValue: "true",
294 options: [
295 { name: "Off", value: "false" },
296 { name: ":icon-brain:", value: "true" },
297 ],
298 category: "model_config",
299 id: "thinking",
300 name: "Thinking",
301 },
302] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
303
304const baseCursorSettings: CursorSettings = {
305 enabled: true,
306 binaryPath: "cursor-agent",
307 apiEndpoint: "",
308 customModels: [],
309};
310const cursorAcpDiscoveryFailedMessage = [
311 "Cursor ACP model discovery failed.",
312 "Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
313 "See https://cursor.com/docs/cli/installation.",
314 "Check server logs for ACP details.",
315].join(" ");
316const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
317const cursorCliCommandMissingMessage = [
318 `Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
319 `Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
320 "See https://cursor.com/docs/cli/installation.",
321].join(" ");
322
323describe("Cursor skills", () => {
324 it("discovers recursive project skills with project precedence", async () =>
325 await runNode(
326 Effect.gen(function* () {
327 const fileSystem = yield* FileSystem.FileSystem;
328 const path = yield* Path.Path;
329 const userHome = yield* fileSystem.makeTempDirectory({
330 directory: NodeOS.tmpdir(),
331 prefix: "cursor-skills-home-",
332 });
333 const workspace = yield* fileSystem.makeTempDirectory({
334 directory: NodeOS.tmpdir(),
335 prefix: "cursor-skills-workspace-",
336 });
337 const writeSkill = Effect.fn("writeCursorSkill")(function* (
338 root: string,
339 name: string,
340 contents: string,
341 ) {
342 const skillDirectory = path.join(root, name);
343 yield* fileSystem.makeDirectory(skillDirectory, { recursive: true });
344 yield* fileSystem.writeFileString(path.join(skillDirectory, "SKILL.md"), contents);
345 });
346
347 yield* writeSkill(
348 path.join(userHome, ".cursor", "skills"),
349 "review",
350 "---\ndescription: user review\n---\n",
351 );
352 yield* writeSkill(
353 path.join(workspace, ".agents", "skills", "nested"),
354 "review",
355 "---\nname: Review changes\ndescription: project review\n---\n",
356 );
357 yield* writeSkill(
358 path.join(workspace, ".cursor", "skills"),
359 "internal",
360 "---\nuser-invocable: false\n---\n",
361 );
362 yield* writeSkill(
363 path.join(workspace, ".cursor", "skills"),
364 "oversized",
365 "x".repeat(1_000_001),
366 );
367 yield* fileSystem.makeDirectory(path.join(userHome, ".codex"), { recursive: true });
368 yield* fileSystem.writeFileString(
369 path.join(userHome, ".codex", "skills"),
370 "not a directory",
371 );
372
373 const skills = yield* discoverCursorSkills(workspace, { HOME: userHome });
374 expect(skills).toEqual([
375 {
376 name: "internal",
377 path: path.join(workspace, ".cursor", "skills", "internal", "SKILL.md"),
378 scope: "project",
379 enabled: true,
380 userInvocable: false,
381 },
382 {
383 name: "oversized",
384 path: path.join(workspace, ".cursor", "skills", "oversized", "SKILL.md"),
385 scope: "project",
386 enabled: true,
387 },
388 {
389 name: "review",
390 displayName: "Review changes",
391 description: "project review",
392 path: path.join(workspace, ".agents", "skills", "nested", "review", "SKILL.md"),
393 scope: "project",
394 enabled: true,
395 },
396 ]);
397 expect(
398 (yield* probeCursorSkills(workspace, { HOME: userHome }).pipe(Effect.result))._tag,
399 ).toBe("Failure");
400 }),
401 ));
402
403 it("treats a symlinked skill outside the root as a package boundary", async () =>
404 await runNode(
405 Effect.gen(function* () {
406 const fileSystem = yield* FileSystem.FileSystem;
407 const path = yield* Path.Path;
408 const userHome = yield* fileSystem.makeTempDirectory({
409 directory: NodeOS.tmpdir(),
410 prefix: "cursor-skills-home-",
411 });
412 const workspace = yield* fileSystem.makeTempDirectory({
413 directory: NodeOS.tmpdir(),
414 prefix: "cursor-skills-workspace-",
415 });
416 const library = yield* fileSystem.makeTempDirectory({
417 directory: NodeOS.tmpdir(),
418 prefix: "cursor-skills-library-",
419 });
420 const writeSkill = Effect.fn("writeCursorSkill")(function* (
421 directory: string,
422 contents: string,
423 ) {
424 yield* fileSystem.makeDirectory(directory, { recursive: true });
425 yield* fileSystem.writeFileString(path.join(directory, "SKILL.md"), contents);
426 });
427
428 // A skill package managed in a config repo and installed by symlink.
429 // Its own SKILL.md must be discovered under the link name, but nothing
430 // below the target may be walked.
431 yield* writeSkill(path.join(library, "shared-review"), "---\ndescription: shared\n---\n");
432 yield* writeSkill(path.join(library, "shared-review", "hidden"), "---\n---\n");
433 const root = path.join(workspace, ".cursor", "skills");
434 yield* fileSystem.makeDirectory(root, { recursive: true });
435 yield* fileSystem.symlink(path.join(library, "shared-review"), path.join(root, "review"));
436
437 const skills = yield* discoverCursorSkills(workspace, { HOME: userHome });
438 expect(skills).toEqual([
439 {
440 name: "review",
441 description: "shared",
442 path: path.join(root, "review", "SKILL.md"),
443 scope: "project",
444 enabled: true,
445 },
446 ]);
447 expect(
448 (yield* probeCursorSkills(workspace, { HOME: userHome }).pipe(Effect.result))._tag,
449 ).toBe("Success");
450 }),
451 ));
452
453 it("rewrites only discovered skill mentions into Cursor slash invocations", () => {
454 expect(hasCursorSkillMention("use $Review_Pr:V2 here")).toBe(true);
455 expect(hasCursorSkillMention("please $review this")).toBe(true);
456 expect(
457 rewriteCursorSkillMentions("use $review, keep $HOME and 5$review", new Set(["review"])),
458 ).toBe("use $review, keep $HOME and 5$review");
459 expect(rewriteCursorSkillMentions("please $review this", new Set(["review"]))).toBe(
460 "please /review this",
461 );
462 });
463
464 it("rewrites currency-prefixed skill mentions into Cursor slash invocations", () => {
465 const names = new Set(["review", "2spec", "20k", "100M", "1e6"]);
466 for (const symbol of ["€", "£", "¥", "₹", "₩", "₿", "𑿝"]) {
467 expect(hasCursorSkillMention(`please ${symbol}review this`)).toBe(true);
468 expect(hasCursorSkillMention(`please ${symbol}review this`)).toBe(true);
469 expect(rewriteCursorSkillMentions(`${symbol}review then ${symbol}2spec this`, names)).toBe(
470 "/review then /2spec this",
471 );
472 const money = `${symbol}20 ${symbol}20k ${symbol}100M ${symbol}1e6`;
473 expect(hasCursorSkillMention(money)).toBe(false);
474 expect(rewriteCursorSkillMentions(money, names)).toBe(money);
475 const prose = `5${symbol}review ${symbol}unknown`;
476 expect(rewriteCursorSkillMentions(prose, names)).toBe(prose);
477 }
478 });
479
480 it("detects and invokes digit-leading Cursor skills without rewriting money", () => {
481 const names = new Set(["2spec", "20k", "100M", "1e6"]);
482 // Repeated presence checks must not carry a global-regex cursor.
483 expect(hasCursorSkillMention("use $2spec here")).toBe(true);
484 expect(hasCursorSkillMention("use $2spec here")).toBe(true);
485 expect(rewriteCursorSkillMentions("use $2spec here", names)).toBe("use /2spec here");
486 expect(rewriteCursorSkillMentions("use $2spec here", new Set())).toBe("use $2spec here");
487 for (const text of [
488 "pay $20 tomorrow",
489 "budget $20k here",
490 "cost $100M total",
491 "limit $1e6 here",
492 ]) {
493 expect(hasCursorSkillMention(text)).toBe(false);
494 expect(rewriteCursorSkillMentions(text, names)).toBe(text);
495 }
496 });
497});
498
499describe("Cursor command catalog", () => {
500 effectIt.effect(
501 "publishes workspace commands without leaking them globally and retains them across refreshes",
502 () =>
503 Effect.gen(function* () {
504 const base = {
505 ...buildCursorProviderSnapshot({
506 checkedAt: "2026-01-01T00:00:00.000Z",
507 cursorSettings: baseCursorSettings,
508 parsed: { version: null, status: "ready", auth: { status: "authenticated" } },
509 }),
510 instanceId: ProviderInstanceId.make("cursor-catalog"),
511 driver: ProviderDriverKind.make("cursor"),
512 };
513 const catalog = yield* makeCursorCommandCatalog({
514 getSnapshot: Effect.succeed(base),
515 refresh: Effect.succeed(base),
516 streamChanges: Stream.empty,
517 resolveMaintenance: () => Effect.die("Not used"),
518 applyUsageLimits: () => Effect.void,
519 });
520 const skills = [
521 { name: "review", path: "/one/.cursor/skills/review/SKILL.md", enabled: true },
522 ];
523 const probedSkills = [
524 { name: "explain", path: "/probed/.cursor/skills/explain/SKILL.md", enabled: true },
525 ];
526 yield* catalog.snapshotForCwd("/probed", probedSkills);
527 yield* catalog.onAvailableCommands(
528 [
529 { name: "review", description: "Review changes", input: { hint: "target" } },
530 { name: "compact", description: "Native duplicate" },
531 { name: "review", description: "Duplicate" },
532 ],
533 "/one",
534 skills,
535 );
536 yield* catalog.onAvailableCommands([{ name: "deploy", description: "Deploy" }], "/two", []);
537 const reprobed = yield* catalog.snapshotForCwd("/one", skills);
538 expect(reprobed.slashCommands.map((command) => command.name)).toEqual([
539 "compact",
540 "review",
541 ]);
542 const published = yield* catalog.snapshot.streamChanges.pipe(
543 Stream.take(1),
544 Stream.runCollect,
545 );
546 expect(published[0]?.slashCommands.map((command) => command.name)).toEqual(["compact"]);
547 const refreshed = yield* catalog.snapshot.refresh;
548 expect(
549 refreshed.workspaceSnapshots?.find((entry) => entry.cwd === "/probed"),
550 ).toMatchObject({
551 slashCommands: [{ name: "compact" }],
552 skills: probedSkills,
553 });
554 expect(refreshed.workspaceSnapshots?.find((entry) => entry.cwd === "/one")).toMatchObject({
555 slashCommands: [
556 { name: "compact" },
557 { name: "review", description: "Review changes", input: { hint: "target" } },
558 ],
559 skills,
560 });
561 yield* catalog.onAvailableCommands([], "/one", skills);
562 const updated = yield* catalog.snapshot.getSnapshot;
563 expect(
564 updated.workspaceSnapshots?.find((entry) => entry.cwd === "/probed")?.skills,
565 ).toEqual(probedSkills);
566 expect(
567 updated.workspaceSnapshots
568 ?.find((entry) => entry.cwd === "/one")
569 ?.slashCommands.map((command) => command.name),
570 ).toEqual(["compact"]);
571 expect(
572 updated.workspaceSnapshots
573 ?.find((entry) => entry.cwd === "/two")
574 ?.slashCommands.map((command) => command.name),
575 ).toEqual(["compact", "deploy"]);
576 }),
577 );
578});
579
580describe("buildCursorProviderSnapshot", () => {
581 it("downgrades ready status to warning when ACP model discovery times out", () => {
582 expect(
583 buildCursorProviderSnapshot({
584 checkedAt: "2026-01-01T00:00:00.000Z",
585 cursorSettings: baseCursorSettings,
586 parsed: {
587 version: "2026.04.09-f2b0fcd",
588 status: "ready",
589 auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
590 },
591 discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
592 }),
593 ).toMatchObject({
594 status: "warning",
595 message: "Cursor ACP model discovery timed out after 15000ms.",
596 models: [],
597 supportsConversationRollback: false,
598 });
599 });
600
601 it("preserves provider error state while appending discovery warnings", () => {
602 expect(
603 buildCursorProviderSnapshot({
604 checkedAt: "2026-01-01T00:00:00.000Z",
605 cursorSettings: {
606 ...baseCursorSettings,
607 customModels: ["claude-sonnet-4-6"],
608 },
609 parsed: {
610 version: "2026.04.09-f2b0fcd",
611 status: "error",
612 auth: { status: "unauthenticated" },
613 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
614 },
615 discoveryWarning: cursorAcpDiscoveryFailedMessage,
616 }),
617 ).toMatchObject({
618 status: "error",
619 message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
620 models: [
621 {
622 slug: "claude-sonnet-4-6",
623 isCustom: true,
624 },
625 ],
626 });
627 });
628});
629
630describe("buildCursorCapabilitiesFromConfigOptions", () => {
631 it("derives model capabilities from parameterized Cursor ACP config options", () => {
632 expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual(
633 createModelCapabilities({
634 optionDescriptors: [
635 selectDescriptor("reasoning", "Reasoning", [
636 { id: "low", label: "Low" },
637 { id: "medium", label: "Medium", isDefault: true },
638 { id: "high", label: "High" },
639 { id: "xhigh", label: "Extra High" },
640 ]),
641 selectDescriptor("contextWindow", "Context", [
642 { id: "272k", label: "272K", isDefault: true },
643 { id: "1m", label: "1M" },
644 ]),
645 booleanDescriptor("fastMode", "Fast", false),
646 ],
647 }),
648 );
649 });
650
651 it("detects boolean thinking toggles from model_config options", () => {
652 expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual(
653 createModelCapabilities({
654 optionDescriptors: [
655 selectDescriptor("reasoning", "Reasoning", [
656 { id: "low", label: "Low" },
657 { id: "medium", label: "Medium" },
658 { id: "high", label: "High", isDefault: true },
659 ]),
660 booleanDescriptor("thinking", "Thinking", true),
661 ],
662 }),
663 );
664 });
665
666 it("prefers the newer model_option effort control over legacy thought_level", () => {
667 expect(
668 buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
669 ).toEqual(
670 createModelCapabilities({
671 optionDescriptors: [
672 selectDescriptor("reasoning", "Effort", [
673 { id: "low", label: "Low" },
674 { id: "medium", label: "Medium" },
675 { id: "high", label: "High" },
676 { id: "max", label: "Max", isDefault: true },
677 ]),
678 booleanDescriptor("fastMode", "Fast", true),
679 booleanDescriptor("thinking", "Thinking", true),
680 ],
681 }),
682 );
683 });
684});
685
686describe("checkCursorProviderStatus", () => {
687 it("reports the install docs when the Cursor CLI command is missing", async () => {
688 const provider = await runNode(
689 checkCursorProviderStatus({
690 enabled: true,
691 binaryPath: missingCursorBinaryPath,
692 apiEndpoint: "",
693 customModels: [],
694 }),
695 );
696
697 expect(provider).toMatchObject({
698 installed: false,
699 status: "error",
700 auth: { status: "unknown" },
701 message: cursorCliCommandMissingMessage,
702 });
703 });
704
705 it("passes the injected environment to ACP model discovery", async () => {
706 const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
707
708 const provider = await runNode(
709 checkCursorProviderStatus(
710 {
711 enabled: true,
712 binaryPath: wrapperPath,
713 apiEndpoint: "",
714 customModels: [],
715 },
716 {
717 ...process.env,
718 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
719 },
720 ),
721 );
722
723 expect(provider.models.map((model) => model.slug)).toEqual([
724 "default",
725 "composer-2",
726 "gpt-5.4",
727 "claude-opus-4-6",
728 ]);
729 await expect(runNode(waitForFileContent(requestLogPath))).resolves.toContain("initialize");
730 });
731});
732
733describe("discoverCursorModelsViaAcp", () => {
734 it("reuses successful discovery until the CLI version or account changes", async () => {
735 await runNode(
736 Effect.gen(function* () {
737 const { requestLogPath, wrapperPath } = yield* makeProviderStatusEnvFixture();
738 const fileSystem = yield* FileSystem.FileSystem;
739 const settings = {
740 enabled: true,
741 binaryPath: wrapperPath,
742 apiEndpoint: "",
743 customModels: [],
744 };
745 const { discover, invalidate } = yield* makeCursorModelDiscovery(settings, {
746 ...process.env,
747 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
748 });
749 const about = {
750 version: "2026.08.11",
751 auth: { status: "authenticated" as const, label: "first@example.test" },
752 };
753 const first = yield* discover(about);
754 expect(first.length).toBeGreaterThan(0);
755 yield* fileSystem.writeFileString(requestLogPath, "");
756 expect(yield* discover(about)).toEqual(first);
757 expect(yield* fileSystem.readFileString(requestLogPath)).toBe("");
758 yield* invalidate;
759 expect(yield* discover(about)).toEqual(first);
760 expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
761 yield* fileSystem.writeFileString(requestLogPath, "");
762 yield* discover({ ...about, version: "2026.08.12" });
763 expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
764 yield* fileSystem.writeFileString(requestLogPath, "");
765 yield* discover({
766 version: "2026.08.12",
767 auth: { ...about.auth, label: "second@example.test" },
768 });
769 expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
770 }),
771 );
772 });
773
774 it("keeps the ACP probe runtime alive long enough to discover models", async () => {
775 const wrapperPath = await runNode(makeMockAgentWrapper());
776
777 const models = await runNode(
778 discoverCursorModelsViaAcp({
779 enabled: true,
780 binaryPath: wrapperPath,
781 apiEndpoint: "",
782 customModels: [],
783 }).pipe(Effect.scoped),
784 );
785
786 expect(models.map((model) => model.slug)).toEqual([
787 "default",
788 "composer-2",
789 "gpt-5.4",
790 "claude-opus-4-6",
791 ]);
792 });
793
794 it.skipIf(windowsHost)("closes the ACP probe runtime after discovery completes", async () => {
795 const { exitLogPath, wrapperPath } = await runNode(
796 makeExitLogFixture("cursor-provider-exit-log-"),
797 );
798
799 await runNode(
800 discoverCursorModelsViaAcp({
801 enabled: true,
802 binaryPath: wrapperPath,
803 apiEndpoint: "",
804 customModels: [],
805 }),
806 );
807
808 const exitLog = await runNode(waitForFileContent(exitLogPath));
809 expect(exitLog).toContain("SIGTERM");
810 });
811});
812
813describe("parseCursorAboutOutput", () => {
814 it("parses json about output and forwards subscription metadata", () => {
815 expect(
816 parseCursorAboutOutput({
817 code: 0,
818 stdout: JSON.stringify({
819 cliVersion: "2026.04.09-f2b0fcd",
820 subscriptionTier: "Team",
821 userEmail: "jmarminge@gmail.com",
822 }),
823 stderr: "",
824 }),
825 ).toEqual({
826 version: "2026.04.09-f2b0fcd",
827 status: "ready",
828 auth: {
829 status: "authenticated",
830 email: "jmarminge@gmail.com",
831 type: "Team",
832 label: "Cursor Team Subscription",
833 },
834 });
835 });
836
837 it("treats json about output with a logged-out email as unauthenticated", () => {
838 expect(
839 parseCursorAboutOutput({
840 code: 0,
841 stdout: JSON.stringify({
842 cliVersion: "2026.04.09-f2b0fcd",
843 subscriptionTier: "Team",
844 userEmail: "Not logged in",
845 }),
846 stderr: "",
847 }),
848 ).toEqual({
849 version: "2026.04.09-f2b0fcd",
850 status: "error",
851 auth: {
852 status: "unauthenticated",
853 },
854 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
855 });
856 });
857
858 it("treats json about output with a null email as unauthenticated", () => {
859 expect(
860 parseCursorAboutOutput({
861 code: 0,
862 stdout: JSON.stringify({
863 cliVersion: "2026.04.09-f2b0fcd",
864 subscriptionTier: null,
865 userEmail: null,
866 }),
867 stderr: "",
868 }),
869 ).toEqual({
870 version: "2026.04.09-f2b0fcd",
871 status: "error",
872 auth: {
873 status: "unauthenticated",
874 },
875 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
876 });
877 });
878});
879
880describe("Cursor parameterized model picker preview gating", () => {
881 it("parses Cursor CLI version dates from build versions", () => {
882 expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408);
883 expect(parseCursorVersionDate("2026.04.09")).toBe(20260409);
884 expect(parseCursorVersionDate("not-a-version")).toBeUndefined();
885 });
886
887 it("parses the Cursor CLI channel from cli-config.json", () => {
888 expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab");
889 expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable");
890 expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined();
891 expect(parseCursorCliConfigChannel("not-json")).toBeUndefined();
892 });
893
894 it("returns no warning when the preview requirements are met", () => {
895 expect(
896 getCursorParameterizedModelPickerUnsupportedMessage({
897 version: "2026.04.08-c4e73a3",
898 channel: "lab",
899 }),
900 ).toBeUndefined();
901 });
902
903 it("explains when the Cursor Agent version is too old", () => {
904 expect(
905 getCursorParameterizedModelPickerUnsupportedMessage({
906 version: "2026.04.07-c4e73a3",
907 channel: "lab",
908 }),
909 ).toContain("too old");
910 });
911
912 it("explains when the Cursor Agent channel is not lab", () => {
913 expect(
914 getCursorParameterizedModelPickerUnsupportedMessage({
915 version: "2026.04.08-c4e73a3",
916 channel: "stable",
917 }),
918 ).toContain("lab channel");
919 });
920});
921
922describe("resolveCursorAcpBaseModelId", () => {
923 it("drops bracket traits without rewriting raw ACP model ids", () => {
924 expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4");
925 expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast");
926 expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe(
927 "claude-4.6-opus-high-thinking",
928 );
929 expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2");
930 expect(resolveCursorAcpBaseModelId("auto")).toBe("auto");
931 });
932});
933
934describe("resolveCursorAcpConfigUpdates", () => {
935 it("maps Cursor model options onto separate ACP config option updates", () => {
936 expect(
937 resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
938 { id: "reasoning", value: "xhigh" },
939 { id: "fastMode", value: true },
940 { id: "contextWindow", value: "1m" },
941 ]),
942 ).toEqual([
943 { configId: "reasoning", value: "extra-high" },
944 { configId: "context", value: "1m" },
945 { configId: "fast", value: "true" },
946 ]);
947 });
948
949 it("maps boolean thinking toggles when the model exposes them separately", () => {
950 expect(
951 resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, [
952 { id: "thinking", value: false },
953 ]),
954 ).toEqual([{ configId: "thinking", value: false }]);
955 });
956
957 it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
958 expect(
959 resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
960 { id: "fastMode", value: false },
961 ]),
962 ).toEqual([{ configId: "fast", value: "false" }]);
963 });
964
965 it("writes Cursor effort changes through the newer model_option config when available", () => {
966 expect(
967 resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [
968 { id: "reasoning", value: "max" },
969 { id: "thinking", value: false },
970 ]),
971 ).toEqual([
972 { configId: "effort", value: "max" },
973 { configId: "thinking", value: "false" },
974 ]);
975 });
976});
977
978describe("Cursor usage limits", () => {
979 const checkedAt = "2026-09-16T00:00:00.000Z";
980
981 it("uses the advertised percentages and billing-cycle reset", () => {
982 const limits = cursorUsageResponseToLimits(
983 {
984 billingCycleEnd: "1789876386000",
985 planUsage: { totalPercentUsed: 72.4, autoPercentUsed: 69.5, apiPercentUsed: 100 },
986 },
987 checkedAt,
988 );
989 expect(limits.windows).toEqual(
990 expect.arrayContaining([
991 {
992 id: "totalPercentUsed",
993 kind: "monthly",
994 label: "Overall",
995 usedPercent: 72.4,
996 resetsAt: "2026-09-20T03:53:06.000Z",
997 },
998 {
999 id: "autoPercentUsed",
1000 kind: "monthly",
1001 label: "Cursor Models",
1002 usedPercent: 69.5,
1003 resetsAt: "2026-09-20T03:53:06.000Z",
1004 },
1005 {
1006 id: "apiPercentUsed",
1007 kind: "monthly",
1008 label: "Other Models",
1009 usedPercent: 100,
1010 resetsAt: "2026-09-20T03:53:06.000Z",
1011 },
1012 ]),
1013 );
1014 });
1015
1016 it("does not invent unused allowance for absent buckets", () => {
1017 expect(cursorUsageResponseToLimits({ planUsage: {} }, checkedAt).unavailable?.reason).toBe(
1018 "unsupported",
1019 );
1020 expect(
1021 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 0 } }, checkedAt).windows,
1022 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 0 }]);
1023 expect(
1024 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 150 } }, checkedAt).windows,
1025 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Overall", usedPercent: 100 }]);
1026 });
1027
1028 it("reads the instance's credentials and endpoint even when usage enabled is false", async () => {
1029 await runNode(
1030 Effect.gen(function* () {
1031 const fs = yield* FileSystem.FileSystem;
1032 const path = yield* Path.Path;
1033 const directory = yield* fs.makeTempDirectoryScoped();
1034 yield* fs.makeDirectory(path.join(directory, "cursor"));
1035 yield* fs.writeFileString(
1036 path.join(directory, "cursor", "auth.json"),
1037 '{"accessToken":"instance-token"}',
1038 );
1039 const client = HttpClient.make((request) => {
1040 expect(request.url).toBe(
1041 "https://cursor.example/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
1042 );
1043 expect(request.method).toBe("POST");
1044 expect(request.headers.authorization).toBe("Bearer instance-token");
1045 expect(request.headers["connect-protocol-version"]).toBe("1");
1046 return Effect.succeed(
1047 HttpClientResponse.fromWeb(
1048 request,
1049 Response.json({ enabled: false, planUsage: { totalPercentUsed: 42 } }),
1050 ),
1051 );
1052 });
1053 yield* fs.makeDirectory(path.join(directory, ".cursor"));
1054 yield* fs.writeFileString(
1055 path.join(directory, ".cursor", "auth.json"),
1056 '{"accessToken":"instance-token"}',
1057 );
1058 for (const platform of ["linux", "darwin"] as const) {
1059 const limits = yield* readCursorUsageLimits(
1060 { apiEndpoint: "https://cursor.example/" },
1061 { XDG_CONFIG_HOME: directory, HOME: directory, AGENT_CLI_CREDENTIAL_STORE: "file" },
1062 ).pipe(
1063 Effect.provideService(HostProcessPlatform, platform),
1064 Effect.provideService(HttpClient.HttpClient, client),
1065 );
1066 expect(limits.windows[0]?.usedPercent).toBe(42);
1067 }
1068 }).pipe(Effect.scoped),
1069 );
1070 });
1071
1072 it("never reads stale files for keychain or memory logins, but accepts an explicit auth token", async () => {
1073 for (const platform of ["linux", "darwin"] as const) {
1074 for (const token of [undefined, "explicit-token"]) {
1075 const limits = await runNode(
1076 readCursorUsageLimits(
1077 { apiEndpoint: "" },
1078 {
1079 AGENT_CLI_CREDENTIAL_STORE: platform === "linux" ? "memory" : "default",
1080 ...(token ? { CURSOR_AUTH_TOKEN: token } : {}),
1081 },
1082 false,
1083 async () => {
1084 throw new Error("must not read Keychain before opt-in");
1085 },
1086 ).pipe(
1087 Effect.provideService(HostProcessPlatform, platform),
1088 Effect.provideService(
1089 FileSystem.FileSystem,
1090 FileSystem.makeNoop({
1091 readFileString: () => Effect.die("must not read an unrelated credential file"),
1092 }),
1093 ),
1094 Effect.provideService(
1095 HttpClient.HttpClient,
1096 HttpClient.make((request) => {
1097 expect(token).toBe("explicit-token");
1098 expect(request.headers.authorization).toBe("Bearer explicit-token");
1099 return Effect.succeed(
1100 HttpClientResponse.fromWeb(
1101 request,
1102 Response.json({ planUsage: { totalPercentUsed: 10 } }),
1103 ),
1104 );
1105 }),
1106 ),
1107 ),
1108 );
1109 if (token) expect(limits.windows[0]?.usedPercent).toBe(10);
1110 else expect(limits.unavailable?.reason).toBe("unsupported");
1111 }
1112 }
1113 });
1114
1115 it("reads the default macOS Cursor login from Keychain for limits", async () => {
1116 const limits = await runNode(
1117 readCursorUsageLimits({ apiEndpoint: "" }, {}, true, async () => "keychain-token").pipe(
1118 Effect.provideService(HostProcessPlatform, "darwin"),
1119 Effect.provideService(
1120 FileSystem.FileSystem,
1121 FileSystem.makeNoop({
1122 readFileString: () => Effect.die("must not read a stale credential file"),
1123 }),
1124 ),
1125 Effect.provideService(
1126 HttpClient.HttpClient,
1127 HttpClient.make((request) => {
1128 expect(request.headers.authorization).toBe("Bearer keychain-token");
1129 return Effect.succeed(
1130 HttpClientResponse.fromWeb(
1131 request,
1132 Response.json({ planUsage: { totalPercentUsed: 42 } }),
1133 ),
1134 );
1135 }),
1136 ),
1137 ),
1138 );
1139 expect(limits.windows[0]?.usedPercent).toBe(42);
1140 });
1141
1142 it("reports a Keychain initialization failure without failing the provider refresh", async () => {
1143 const limits = await runNode(
1144 readCursorUsageLimits({ apiEndpoint: "" }, {}, true, async () => {
1145 throw new Error("Keychain initialization failed");
1146 }).pipe(
1147 Effect.provideService(HostProcessPlatform, "darwin"),
1148 Effect.provideService(
1149 HttpClient.HttpClient,
1150 HttpClient.make(() => Effect.die("must not request limits without a login")),
1151 ),
1152 ),
1153 );
1154 expect(limits.unavailable?.reason).toBe("probeFailed");
1155 });
1156
1157 it("does not read Keychain or send its token to a custom endpoint", async () => {
1158 for (const [apiEndpoint, environment] of [
1159 ["http://localhost:3000", {}],
1160 ["", { CURSOR_API_ENDPOINT: "http://localhost:3000" }],
1161 ["https://cursor-proxy.example", {}],
1162 ["", { CURSOR_API_ENDPOINT: "https://cursor-proxy.example" }],
1163 ] as const) {
1164 const limits = await runNode(
1165 readCursorUsageLimits({ apiEndpoint }, environment, true, async () => {
1166 throw new Error("must not read Keychain for a custom endpoint");
1167 }).pipe(
1168 Effect.provideService(HostProcessPlatform, "darwin"),
1169 Effect.provideService(
1170 HttpClient.HttpClient,
1171 HttpClient.make(() => Effect.die("must not send a Keychain credential to a proxy")),
1172 ),
1173 ),
1174 );
1175 expect(limits.unavailable?.reason).toBe("unsupported");
1176 expect(limits.unavailable?.message).toContain("default Cursor endpoint");
1177 }
1178 });
1179
1180 it("reports failed requests without exposing credentials or response bodies", async () => {
1181 const limits = await runNode(
1182 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_AUTH_TOKEN: "private-token" }).pipe(
1183 Effect.provideService(
1184 HttpClient.HttpClient,
1185 HttpClient.make((request) =>
1186 Effect.succeed(
1187 HttpClientResponse.fromWeb(
1188 request,
1189 new Response("private response", { status: 401 }),
1190 ),
1191 ),
1192 ),
1193 ),
1194 ),
1195 );
1196 expect(limits.unavailable).toEqual({
1197 reason: "probeFailed",
1198 message: "Cursor could not read usage limits.",
1199 });
1200 });
1201
1202 it("does not use a stored login for an explicit API key", async () => {
1203 const limits = await runNode(
1204 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "different-account" }).pipe(
1205 Effect.provideService(
1206 HttpClient.HttpClient,
1207 HttpClient.make(() => Effect.die("must not request usage")),
1208 ),
1209 ),
1210 );
1211 expect(limits.unavailable?.reason).toBe("unsupported");
1212 });
1213});