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("detects and invokes digit-leading Cursor skills without rewriting money", () => {
465 const names = new Set(["2spec", "20k", "100M", "1e6"]);
466 // Repeated presence checks must not carry a global-regex cursor.
467 expect(hasCursorSkillMention("use $2spec here")).toBe(true);
468 expect(hasCursorSkillMention("use $2spec here")).toBe(true);
469 expect(rewriteCursorSkillMentions("use $2spec here", names)).toBe("use /2spec here");
470 expect(rewriteCursorSkillMentions("use $2spec here", new Set())).toBe("use $2spec here");
471 for (const text of [
472 "pay $20 tomorrow",
473 "budget $20k here",
474 "cost $100M total",
475 "limit $1e6 here",
476 ]) {
477 expect(hasCursorSkillMention(text)).toBe(false);
478 expect(rewriteCursorSkillMentions(text, names)).toBe(text);
479 }
480 });
481});
482
483describe("Cursor command catalog", () => {
484 effectIt.effect(
485 "publishes workspace commands without leaking them globally and retains them across refreshes",
486 () =>
487 Effect.gen(function* () {
488 const base = {
489 ...buildCursorProviderSnapshot({
490 checkedAt: "2026-01-01T00:00:00.000Z",
491 cursorSettings: baseCursorSettings,
492 parsed: { version: null, status: "ready", auth: { status: "authenticated" } },
493 }),
494 instanceId: ProviderInstanceId.make("cursor-catalog"),
495 driver: ProviderDriverKind.make("cursor"),
496 };
497 const catalog = yield* makeCursorCommandCatalog({
498 getSnapshot: Effect.succeed(base),
499 refresh: Effect.succeed(base),
500 streamChanges: Stream.empty,
501 resolveMaintenance: () => Effect.die("Not used"),
502 applyUsageLimits: () => Effect.void,
503 });
504 const skills = [
505 { name: "review", path: "/one/.cursor/skills/review/SKILL.md", enabled: true },
506 ];
507 const probedSkills = [
508 { name: "explain", path: "/probed/.cursor/skills/explain/SKILL.md", enabled: true },
509 ];
510 yield* catalog.snapshotForCwd("/probed", probedSkills);
511 yield* catalog.onAvailableCommands(
512 [
513 { name: "review", description: "Review changes", input: { hint: "target" } },
514 { name: "compact", description: "Native duplicate" },
515 { name: "review", description: "Duplicate" },
516 ],
517 "/one",
518 skills,
519 );
520 yield* catalog.onAvailableCommands([{ name: "deploy", description: "Deploy" }], "/two", []);
521 const reprobed = yield* catalog.snapshotForCwd("/one", skills);
522 expect(reprobed.slashCommands.map((command) => command.name)).toEqual([
523 "compact",
524 "review",
525 ]);
526 const published = yield* catalog.snapshot.streamChanges.pipe(
527 Stream.take(1),
528 Stream.runCollect,
529 );
530 expect(published[0]?.slashCommands.map((command) => command.name)).toEqual(["compact"]);
531 const refreshed = yield* catalog.snapshot.refresh;
532 expect(
533 refreshed.workspaceSnapshots?.find((entry) => entry.cwd === "/probed"),
534 ).toMatchObject({
535 slashCommands: [{ name: "compact" }],
536 skills: probedSkills,
537 });
538 expect(refreshed.workspaceSnapshots?.find((entry) => entry.cwd === "/one")).toMatchObject({
539 slashCommands: [
540 { name: "compact" },
541 { name: "review", description: "Review changes", input: { hint: "target" } },
542 ],
543 skills,
544 });
545 yield* catalog.onAvailableCommands([], "/one", skills);
546 const updated = yield* catalog.snapshot.getSnapshot;
547 expect(
548 updated.workspaceSnapshots?.find((entry) => entry.cwd === "/probed")?.skills,
549 ).toEqual(probedSkills);
550 expect(
551 updated.workspaceSnapshots
552 ?.find((entry) => entry.cwd === "/one")
553 ?.slashCommands.map((command) => command.name),
554 ).toEqual(["compact"]);
555 expect(
556 updated.workspaceSnapshots
557 ?.find((entry) => entry.cwd === "/two")
558 ?.slashCommands.map((command) => command.name),
559 ).toEqual(["compact", "deploy"]);
560 }),
561 );
562});
563
564describe("buildCursorProviderSnapshot", () => {
565 it("downgrades ready status to warning when ACP model discovery times out", () => {
566 expect(
567 buildCursorProviderSnapshot({
568 checkedAt: "2026-01-01T00:00:00.000Z",
569 cursorSettings: baseCursorSettings,
570 parsed: {
571 version: "2026.04.09-f2b0fcd",
572 status: "ready",
573 auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
574 },
575 discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
576 }),
577 ).toMatchObject({
578 status: "warning",
579 message: "Cursor ACP model discovery timed out after 15000ms.",
580 models: [],
581 supportsConversationRollback: false,
582 });
583 });
584
585 it("preserves provider error state while appending discovery warnings", () => {
586 expect(
587 buildCursorProviderSnapshot({
588 checkedAt: "2026-01-01T00:00:00.000Z",
589 cursorSettings: {
590 ...baseCursorSettings,
591 customModels: ["claude-sonnet-4-6"],
592 },
593 parsed: {
594 version: "2026.04.09-f2b0fcd",
595 status: "error",
596 auth: { status: "unauthenticated" },
597 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
598 },
599 discoveryWarning: cursorAcpDiscoveryFailedMessage,
600 }),
601 ).toMatchObject({
602 status: "error",
603 message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
604 models: [
605 {
606 slug: "claude-sonnet-4-6",
607 isCustom: true,
608 },
609 ],
610 });
611 });
612});
613
614describe("buildCursorCapabilitiesFromConfigOptions", () => {
615 it("derives model capabilities from parameterized Cursor ACP config options", () => {
616 expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual(
617 createModelCapabilities({
618 optionDescriptors: [
619 selectDescriptor("reasoning", "Reasoning", [
620 { id: "low", label: "Low" },
621 { id: "medium", label: "Medium", isDefault: true },
622 { id: "high", label: "High" },
623 { id: "xhigh", label: "Extra High" },
624 ]),
625 selectDescriptor("contextWindow", "Context", [
626 { id: "272k", label: "272K", isDefault: true },
627 { id: "1m", label: "1M" },
628 ]),
629 booleanDescriptor("fastMode", "Fast", false),
630 ],
631 }),
632 );
633 });
634
635 it("detects boolean thinking toggles from model_config options", () => {
636 expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual(
637 createModelCapabilities({
638 optionDescriptors: [
639 selectDescriptor("reasoning", "Reasoning", [
640 { id: "low", label: "Low" },
641 { id: "medium", label: "Medium" },
642 { id: "high", label: "High", isDefault: true },
643 ]),
644 booleanDescriptor("thinking", "Thinking", true),
645 ],
646 }),
647 );
648 });
649
650 it("prefers the newer model_option effort control over legacy thought_level", () => {
651 expect(
652 buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
653 ).toEqual(
654 createModelCapabilities({
655 optionDescriptors: [
656 selectDescriptor("reasoning", "Effort", [
657 { id: "low", label: "Low" },
658 { id: "medium", label: "Medium" },
659 { id: "high", label: "High" },
660 { id: "max", label: "Max", isDefault: true },
661 ]),
662 booleanDescriptor("fastMode", "Fast", true),
663 booleanDescriptor("thinking", "Thinking", true),
664 ],
665 }),
666 );
667 });
668});
669
670describe("checkCursorProviderStatus", () => {
671 it("reports the install docs when the Cursor CLI command is missing", async () => {
672 const provider = await runNode(
673 checkCursorProviderStatus({
674 enabled: true,
675 binaryPath: missingCursorBinaryPath,
676 apiEndpoint: "",
677 customModels: [],
678 }),
679 );
680
681 expect(provider).toMatchObject({
682 installed: false,
683 status: "error",
684 auth: { status: "unknown" },
685 message: cursorCliCommandMissingMessage,
686 });
687 });
688
689 it("passes the injected environment to ACP model discovery", async () => {
690 const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
691
692 const provider = await runNode(
693 checkCursorProviderStatus(
694 {
695 enabled: true,
696 binaryPath: wrapperPath,
697 apiEndpoint: "",
698 customModels: [],
699 },
700 {
701 ...process.env,
702 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
703 },
704 ),
705 );
706
707 expect(provider.models.map((model) => model.slug)).toEqual([
708 "default",
709 "composer-2",
710 "gpt-5.4",
711 "claude-opus-4-6",
712 ]);
713 await expect(runNode(waitForFileContent(requestLogPath))).resolves.toContain("initialize");
714 });
715});
716
717describe("discoverCursorModelsViaAcp", () => {
718 it("reuses successful discovery until the CLI version or account changes", async () => {
719 await runNode(
720 Effect.gen(function* () {
721 const { requestLogPath, wrapperPath } = yield* makeProviderStatusEnvFixture();
722 const fileSystem = yield* FileSystem.FileSystem;
723 const settings = {
724 enabled: true,
725 binaryPath: wrapperPath,
726 apiEndpoint: "",
727 customModels: [],
728 };
729 const discover = yield* makeCursorModelDiscovery(settings, {
730 ...process.env,
731 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
732 });
733 const about = {
734 version: "2026.08.11",
735 auth: { status: "authenticated" as const, label: "first@example.test" },
736 };
737 const first = yield* discover(about);
738 expect(first.length).toBeGreaterThan(0);
739 yield* fileSystem.writeFileString(requestLogPath, "");
740 expect(yield* discover(about)).toEqual(first);
741 expect(yield* fileSystem.readFileString(requestLogPath)).toBe("");
742 yield* discover({ ...about, version: "2026.08.12" });
743 expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
744 yield* fileSystem.writeFileString(requestLogPath, "");
745 yield* discover({
746 version: "2026.08.12",
747 auth: { ...about.auth, label: "second@example.test" },
748 });
749 expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
750 }),
751 );
752 });
753
754 it("keeps the ACP probe runtime alive long enough to discover models", async () => {
755 const wrapperPath = await runNode(makeMockAgentWrapper());
756
757 const models = await runNode(
758 discoverCursorModelsViaAcp({
759 enabled: true,
760 binaryPath: wrapperPath,
761 apiEndpoint: "",
762 customModels: [],
763 }).pipe(Effect.scoped),
764 );
765
766 expect(models.map((model) => model.slug)).toEqual([
767 "default",
768 "composer-2",
769 "gpt-5.4",
770 "claude-opus-4-6",
771 ]);
772 });
773
774 it.skipIf(windowsHost)("closes the ACP probe runtime after discovery completes", async () => {
775 const { exitLogPath, wrapperPath } = await runNode(
776 makeExitLogFixture("cursor-provider-exit-log-"),
777 );
778
779 await runNode(
780 discoverCursorModelsViaAcp({
781 enabled: true,
782 binaryPath: wrapperPath,
783 apiEndpoint: "",
784 customModels: [],
785 }),
786 );
787
788 const exitLog = await runNode(waitForFileContent(exitLogPath));
789 expect(exitLog).toContain("SIGTERM");
790 });
791});
792
793describe("parseCursorAboutOutput", () => {
794 it("parses json about output and forwards subscription metadata", () => {
795 expect(
796 parseCursorAboutOutput({
797 code: 0,
798 stdout: JSON.stringify({
799 cliVersion: "2026.04.09-f2b0fcd",
800 subscriptionTier: "Team",
801 userEmail: "jmarminge@gmail.com",
802 }),
803 stderr: "",
804 }),
805 ).toEqual({
806 version: "2026.04.09-f2b0fcd",
807 status: "ready",
808 auth: {
809 status: "authenticated",
810 email: "jmarminge@gmail.com",
811 type: "Team",
812 label: "Cursor Team Subscription",
813 },
814 });
815 });
816
817 it("treats json about output with a logged-out email as unauthenticated", () => {
818 expect(
819 parseCursorAboutOutput({
820 code: 0,
821 stdout: JSON.stringify({
822 cliVersion: "2026.04.09-f2b0fcd",
823 subscriptionTier: "Team",
824 userEmail: "Not logged in",
825 }),
826 stderr: "",
827 }),
828 ).toEqual({
829 version: "2026.04.09-f2b0fcd",
830 status: "error",
831 auth: {
832 status: "unauthenticated",
833 },
834 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
835 });
836 });
837
838 it("treats json about output with a null email as unauthenticated", () => {
839 expect(
840 parseCursorAboutOutput({
841 code: 0,
842 stdout: JSON.stringify({
843 cliVersion: "2026.04.09-f2b0fcd",
844 subscriptionTier: null,
845 userEmail: null,
846 }),
847 stderr: "",
848 }),
849 ).toEqual({
850 version: "2026.04.09-f2b0fcd",
851 status: "error",
852 auth: {
853 status: "unauthenticated",
854 },
855 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
856 });
857 });
858});
859
860describe("Cursor parameterized model picker preview gating", () => {
861 it("parses Cursor CLI version dates from build versions", () => {
862 expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408);
863 expect(parseCursorVersionDate("2026.04.09")).toBe(20260409);
864 expect(parseCursorVersionDate("not-a-version")).toBeUndefined();
865 });
866
867 it("parses the Cursor CLI channel from cli-config.json", () => {
868 expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab");
869 expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable");
870 expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined();
871 expect(parseCursorCliConfigChannel("not-json")).toBeUndefined();
872 });
873
874 it("returns no warning when the preview requirements are met", () => {
875 expect(
876 getCursorParameterizedModelPickerUnsupportedMessage({
877 version: "2026.04.08-c4e73a3",
878 channel: "lab",
879 }),
880 ).toBeUndefined();
881 });
882
883 it("explains when the Cursor Agent version is too old", () => {
884 expect(
885 getCursorParameterizedModelPickerUnsupportedMessage({
886 version: "2026.04.07-c4e73a3",
887 channel: "lab",
888 }),
889 ).toContain("too old");
890 });
891
892 it("explains when the Cursor Agent channel is not lab", () => {
893 expect(
894 getCursorParameterizedModelPickerUnsupportedMessage({
895 version: "2026.04.08-c4e73a3",
896 channel: "stable",
897 }),
898 ).toContain("lab channel");
899 });
900});
901
902describe("resolveCursorAcpBaseModelId", () => {
903 it("drops bracket traits without rewriting raw ACP model ids", () => {
904 expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4");
905 expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast");
906 expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe(
907 "claude-4.6-opus-high-thinking",
908 );
909 expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2");
910 expect(resolveCursorAcpBaseModelId("auto")).toBe("auto");
911 });
912});
913
914describe("resolveCursorAcpConfigUpdates", () => {
915 it("maps Cursor model options onto separate ACP config option updates", () => {
916 expect(
917 resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
918 { id: "reasoning", value: "xhigh" },
919 { id: "fastMode", value: true },
920 { id: "contextWindow", value: "1m" },
921 ]),
922 ).toEqual([
923 { configId: "reasoning", value: "extra-high" },
924 { configId: "context", value: "1m" },
925 { configId: "fast", value: "true" },
926 ]);
927 });
928
929 it("maps boolean thinking toggles when the model exposes them separately", () => {
930 expect(
931 resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, [
932 { id: "thinking", value: false },
933 ]),
934 ).toEqual([{ configId: "thinking", value: false }]);
935 });
936
937 it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
938 expect(
939 resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
940 { id: "fastMode", value: false },
941 ]),
942 ).toEqual([{ configId: "fast", value: "false" }]);
943 });
944
945 it("writes Cursor effort changes through the newer model_option config when available", () => {
946 expect(
947 resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [
948 { id: "reasoning", value: "max" },
949 { id: "thinking", value: false },
950 ]),
951 ).toEqual([
952 { configId: "effort", value: "max" },
953 { configId: "thinking", value: "false" },
954 ]);
955 });
956});
957
958describe("Cursor usage limits", () => {
959 const checkedAt = "2026-09-16T00:00:00.000Z";
960
961 it("uses the advertised percentages and billing-cycle reset", () => {
962 const limits = cursorUsageResponseToLimits(
963 {
964 billingCycleEnd: "1789876386000",
965 planUsage: { totalPercentUsed: 72.4, autoPercentUsed: 69.5, apiPercentUsed: 100 },
966 },
967 checkedAt,
968 );
969 expect(limits.windows).toEqual(
970 expect.arrayContaining([
971 {
972 id: "totalPercentUsed",
973 kind: "monthly",
974 label: "Monthly",
975 usedPercent: 72.4,
976 resetsAt: "2026-09-20T03:53:06.000Z",
977 },
978 {
979 id: "autoPercentUsed",
980 kind: "monthly",
981 label: "Monthly · Auto",
982 usedPercent: 69.5,
983 resetsAt: "2026-09-20T03:53:06.000Z",
984 },
985 {
986 id: "apiPercentUsed",
987 kind: "monthly",
988 label: "Monthly · API",
989 usedPercent: 100,
990 resetsAt: "2026-09-20T03:53:06.000Z",
991 },
992 ]),
993 );
994 });
995
996 it("does not invent unused allowance for absent buckets", () => {
997 expect(cursorUsageResponseToLimits({ planUsage: {} }, checkedAt).unavailable?.reason).toBe(
998 "unsupported",
999 );
1000 expect(
1001 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 0 } }, checkedAt).windows,
1002 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Monthly", usedPercent: 0 }]);
1003 expect(
1004 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 150 } }, checkedAt).windows,
1005 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Monthly", usedPercent: 100 }]);
1006 });
1007
1008 it("reads the instance's credentials and endpoint even when usage enabled is false", async () => {
1009 await runNode(
1010 Effect.gen(function* () {
1011 const fs = yield* FileSystem.FileSystem;
1012 const path = yield* Path.Path;
1013 const directory = yield* fs.makeTempDirectoryScoped();
1014 yield* fs.makeDirectory(path.join(directory, "cursor"));
1015 yield* fs.writeFileString(
1016 path.join(directory, "cursor", "auth.json"),
1017 '{"accessToken":"instance-token"}',
1018 );
1019 const client = HttpClient.make((request) => {
1020 expect(request.url).toBe(
1021 "https://cursor.example/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
1022 );
1023 expect(request.method).toBe("POST");
1024 expect(request.headers.authorization).toBe("Bearer instance-token");
1025 expect(request.headers["connect-protocol-version"]).toBe("1");
1026 return Effect.succeed(
1027 HttpClientResponse.fromWeb(
1028 request,
1029 Response.json({ enabled: false, planUsage: { totalPercentUsed: 42 } }),
1030 ),
1031 );
1032 });
1033 yield* fs.makeDirectory(path.join(directory, ".cursor"));
1034 yield* fs.writeFileString(
1035 path.join(directory, ".cursor", "auth.json"),
1036 '{"accessToken":"instance-token"}',
1037 );
1038 for (const platform of ["linux", "darwin"] as const) {
1039 const limits = yield* readCursorUsageLimits(
1040 { apiEndpoint: "https://cursor.example/" },
1041 { XDG_CONFIG_HOME: directory, HOME: directory, AGENT_CLI_CREDENTIAL_STORE: "file" },
1042 ).pipe(
1043 Effect.provideService(HostProcessPlatform, platform),
1044 Effect.provideService(HttpClient.HttpClient, client),
1045 );
1046 expect(limits.windows[0]?.usedPercent).toBe(42);
1047 }
1048 }).pipe(Effect.scoped),
1049 );
1050 });
1051
1052 it("never reads stale files for keychain or memory logins, but accepts an explicit auth token", async () => {
1053 for (const platform of ["linux", "darwin"] as const) {
1054 for (const token of [undefined, "explicit-token"]) {
1055 const limits = await runNode(
1056 readCursorUsageLimits(
1057 { apiEndpoint: "" },
1058 {
1059 AGENT_CLI_CREDENTIAL_STORE: platform === "linux" ? "memory" : "default",
1060 ...(token ? { CURSOR_AUTH_TOKEN: token } : {}),
1061 },
1062 ).pipe(
1063 Effect.provideService(HostProcessPlatform, platform),
1064 Effect.provideService(
1065 FileSystem.FileSystem,
1066 FileSystem.makeNoop({
1067 readFileString: () => Effect.die("must not read an unrelated credential file"),
1068 }),
1069 ),
1070 Effect.provideService(
1071 HttpClient.HttpClient,
1072 HttpClient.make((request) => {
1073 expect(token).toBe("explicit-token");
1074 expect(request.headers.authorization).toBe("Bearer explicit-token");
1075 return Effect.succeed(
1076 HttpClientResponse.fromWeb(
1077 request,
1078 Response.json({ planUsage: { totalPercentUsed: 10 } }),
1079 ),
1080 );
1081 }),
1082 ),
1083 ),
1084 );
1085 if (token) expect(limits.windows[0]?.usedPercent).toBe(10);
1086 else expect(limits.unavailable?.reason).toBe("unsupported");
1087 }
1088 }
1089 });
1090
1091 it("reports failed requests without exposing credentials or response bodies", async () => {
1092 const limits = await runNode(
1093 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_AUTH_TOKEN: "private-token" }).pipe(
1094 Effect.provideService(
1095 HttpClient.HttpClient,
1096 HttpClient.make((request) =>
1097 Effect.succeed(
1098 HttpClientResponse.fromWeb(
1099 request,
1100 new Response("private response", { status: 401 }),
1101 ),
1102 ),
1103 ),
1104 ),
1105 ),
1106 );
1107 expect(limits.unavailable).toEqual({
1108 reason: "probeFailed",
1109 message: "Cursor could not read usage limits.",
1110 });
1111 });
1112
1113 it("does not use a stored login for an explicit API key", async () => {
1114 const limits = await runNode(
1115 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "different-account" }).pipe(
1116 Effect.provideService(
1117 HttpClient.HttpClient,
1118 HttpClient.make(() => Effect.die("must not request usage")),
1119 ),
1120 ),
1121 );
1122 expect(limits.unavailable?.reason).toBe("unsupported");
1123 });
1124});