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

CursorProvider.test.ts

1,140 lines38.3 KB

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 };
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 };
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 = 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* discover({ ...about, version: "2026.08.12" });
759 expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
760 yield* fileSystem.writeFileString(requestLogPath, "");
761 yield* discover({
762 version: "2026.08.12",
763 auth: { ...about.auth, label: "second@example.test" },
764 });
765 expect(yield* fileSystem.readFileString(requestLogPath)).toContain("initialize");
766 }),
767 );
768 });
769​
770 it("keeps the ACP probe runtime alive long enough to discover models", async () => {
771 const wrapperPath = await runNode(makeMockAgentWrapper());
772​
773 const models = await runNode(
774 discoverCursorModelsViaAcp({
775 enabled: true,
776 binaryPath: wrapperPath,
777 apiEndpoint: "",
778 customModels: [],
779 }).pipe(Effect.scoped),
780 );
781​
782 expect(models.map((model) => model.slug)).toEqual([
783 "default",
784 "composer-2",
785 "gpt-5.4",
786 "claude-opus-4-6",
787 ]);
788 });
789​
790 it.skipIf(windowsHost)("closes the ACP probe runtime after discovery completes", async () => {
791 const { exitLogPath, wrapperPath } = await runNode(
792 makeExitLogFixture("cursor-provider-exit-log-"),
793 );
794​
795 await runNode(
796 discoverCursorModelsViaAcp({
797 enabled: true,
798 binaryPath: wrapperPath,
799 apiEndpoint: "",
800 customModels: [],
801 }),
802 );
803​
804 const exitLog = await runNode(waitForFileContent(exitLogPath));
805 expect(exitLog).toContain("SIGTERM");
806 });
807});
808​
809describe("parseCursorAboutOutput", () => {
810 it("parses json about output and forwards subscription metadata", () => {
811 expect(
812 parseCursorAboutOutput({
813 code: 0,
814 stdout: JSON.stringify({
815 cliVersion: "2026.04.09-f2b0fcd",
816 subscriptionTier: "Team",
817 userEmail: "jmarminge@gmail.com",
818 }),
819 stderr: "",
820 }),
821 ).toEqual({
822 version: "2026.04.09-f2b0fcd",
823 status: "ready",
824 auth: {
825 status: "authenticated",
826 email: "jmarminge@gmail.com",
827 type: "Team",
828 label: "Cursor Team Subscription",
829 },
830 });
831 });
832​
833 it("treats json about output with a logged-out email as unauthenticated", () => {
834 expect(
835 parseCursorAboutOutput({
836 code: 0,
837 stdout: JSON.stringify({
838 cliVersion: "2026.04.09-f2b0fcd",
839 subscriptionTier: "Team",
840 userEmail: "Not logged in",
841 }),
842 stderr: "",
843 }),
844 ).toEqual({
845 version: "2026.04.09-f2b0fcd",
846 status: "error",
847 auth: {
848 status: "unauthenticated",
849 },
850 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
851 });
852 });
853​
854 it("treats json about output with a null email as unauthenticated", () => {
855 expect(
856 parseCursorAboutOutput({
857 code: 0,
858 stdout: JSON.stringify({
859 cliVersion: "2026.04.09-f2b0fcd",
860 subscriptionTier: null,
861 userEmail: null,
862 }),
863 stderr: "",
864 }),
865 ).toEqual({
866 version: "2026.04.09-f2b0fcd",
867 status: "error",
868 auth: {
869 status: "unauthenticated",
870 },
871 message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
872 });
873 });
874});
875​
876describe("Cursor parameterized model picker preview gating", () => {
877 it("parses Cursor CLI version dates from build versions", () => {
878 expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408);
879 expect(parseCursorVersionDate("2026.04.09")).toBe(20260409);
880 expect(parseCursorVersionDate("not-a-version")).toBeUndefined();
881 });
882​
883 it("parses the Cursor CLI channel from cli-config.json", () => {
884 expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab");
885 expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable");
886 expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined();
887 expect(parseCursorCliConfigChannel("not-json")).toBeUndefined();
888 });
889​
890 it("returns no warning when the preview requirements are met", () => {
891 expect(
892 getCursorParameterizedModelPickerUnsupportedMessage({
893 version: "2026.04.08-c4e73a3",
894 channel: "lab",
895 }),
896 ).toBeUndefined();
897 });
898​
899 it("explains when the Cursor Agent version is too old", () => {
900 expect(
901 getCursorParameterizedModelPickerUnsupportedMessage({
902 version: "2026.04.07-c4e73a3",
903 channel: "lab",
904 }),
905 ).toContain("too old");
906 });
907​
908 it("explains when the Cursor Agent channel is not lab", () => {
909 expect(
910 getCursorParameterizedModelPickerUnsupportedMessage({
911 version: "2026.04.08-c4e73a3",
912 channel: "stable",
913 }),
914 ).toContain("lab channel");
915 });
916});
917​
918describe("resolveCursorAcpBaseModelId", () => {
919 it("drops bracket traits without rewriting raw ACP model ids", () => {
920 expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4");
921 expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast");
922 expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe(
923 "claude-4.6-opus-high-thinking",
924 );
925 expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2");
926 expect(resolveCursorAcpBaseModelId("auto")).toBe("auto");
927 });
928});
929​
930describe("resolveCursorAcpConfigUpdates", () => {
931 it("maps Cursor model options onto separate ACP config option updates", () => {
932 expect(
933 resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
934 { id: "reasoning", value: "xhigh" },
935 { id: "fastMode", value: true },
936 { id: "contextWindow", value: "1m" },
937 ]),
938 ).toEqual([
939 { configId: "reasoning", value: "extra-high" },
940 { configId: "context", value: "1m" },
941 { configId: "fast", value: "true" },
942 ]);
943 });
944​
945 it("maps boolean thinking toggles when the model exposes them separately", () => {
946 expect(
947 resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, [
948 { id: "thinking", value: false },
949 ]),
950 ).toEqual([{ configId: "thinking", value: false }]);
951 });
952​
953 it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
954 expect(
955 resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, [
956 { id: "fastMode", value: false },
957 ]),
958 ).toEqual([{ configId: "fast", value: "false" }]);
959 });
960​
961 it("writes Cursor effort changes through the newer model_option config when available", () => {
962 expect(
963 resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [
964 { id: "reasoning", value: "max" },
965 { id: "thinking", value: false },
966 ]),
967 ).toEqual([
968 { configId: "effort", value: "max" },
969 { configId: "thinking", value: "false" },
970 ]);
971 });
972});
973​
974describe("Cursor usage limits", () => {
975 const checkedAt = "2026-09-16T00:00:00.000Z";
976​
977 it("uses the advertised percentages and billing-cycle reset", () => {
978 const limits = cursorUsageResponseToLimits(
979 {
980 billingCycleEnd: "1789876386000",
981 planUsage: { totalPercentUsed: 72.4, autoPercentUsed: 69.5, apiPercentUsed: 100 },
982 },
983 checkedAt,
984 );
985 expect(limits.windows).toEqual(
986 expect.arrayContaining([
987 {
988 id: "totalPercentUsed",
989 kind: "monthly",
990 label: "Monthly",
991 usedPercent: 72.4,
992 resetsAt: "2026-09-20T03:53:06.000Z",
993 },
994 {
995 id: "autoPercentUsed",
996 kind: "monthly",
997 label: "Monthly · Auto",
998 usedPercent: 69.5,
999 resetsAt: "2026-09-20T03:53:06.000Z",
1000 },
1002 id: "apiPercentUsed",
1003 kind: "monthly",
1004 label: "Monthly · API",
1005 usedPercent: 100,
1006 resetsAt: "2026-09-20T03:53:06.000Z",
1007 },
1008 ]),
1009 );
1010 });
1011​
1012 it("does not invent unused allowance for absent buckets", () => {
1013 expect(cursorUsageResponseToLimits({ planUsage: {} }, checkedAt).unavailable?.reason).toBe(
1014 "unsupported",
1015 );
1016 expect(
1017 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 0 } }, checkedAt).windows,
1018 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Monthly", usedPercent: 0 }]);
1019 expect(
1020 cursorUsageResponseToLimits({ planUsage: { totalPercentUsed: 150 } }, checkedAt).windows,
1021 ).toEqual([{ id: "totalPercentUsed", kind: "monthly", label: "Monthly", usedPercent: 100 }]);
1022 });
1023​
1024 it("reads the instance's credentials and endpoint even when usage enabled is false", async () => {
1025 await runNode(
1026 Effect.gen(function* () {
1027 const fs = yield* FileSystem.FileSystem;
1028 const path = yield* Path.Path;
1029 const directory = yield* fs.makeTempDirectoryScoped();
1030 yield* fs.makeDirectory(path.join(directory, "cursor"));
1031 yield* fs.writeFileString(
1032 path.join(directory, "cursor", "auth.json"),
1033 '{"accessToken":"instance-token"}',
1034 );
1035 const client = HttpClient.make((request) => {
1036 expect(request.url).toBe(
1037 "https://cursor.example/aiserver.v1.DashboardService/GetCurrentPeriodUsage",
1038 );
1039 expect(request.method).toBe("POST");
1040 expect(request.headers.authorization).toBe("Bearer instance-token");
1041 expect(request.headers["connect-protocol-version"]).toBe("1");
1042 return Effect.succeed(
1043 HttpClientResponse.fromWeb(
1044 request,
1045 Response.json({ enabled: false, planUsage: { totalPercentUsed: 42 } }),
1046 ),
1047 );
1048 });
1049 yield* fs.makeDirectory(path.join(directory, ".cursor"));
1050 yield* fs.writeFileString(
1051 path.join(directory, ".cursor", "auth.json"),
1052 '{"accessToken":"instance-token"}',
1053 );
1054 for (const platform of ["linux", "darwin"] as const) {
1055 const limits = yield* readCursorUsageLimits(
1056 { apiEndpoint: "https://cursor.example/" },
1057 { XDG_CONFIG_HOME: directory, HOME: directory, AGENT_CLI_CREDENTIAL_STORE: "file" },
1058 ).pipe(
1059 Effect.provideService(HostProcessPlatform, platform),
1060 Effect.provideService(HttpClient.HttpClient, client),
1061 );
1062 expect(limits.windows[0]?.usedPercent).toBe(42);
1064 }).pipe(Effect.scoped),
1065 );
1066 });
1067​
1068 it("never reads stale files for keychain or memory logins, but accepts an explicit auth token", async () => {
1069 for (const platform of ["linux", "darwin"] as const) {
1070 for (const token of [undefined, "explicit-token"]) {
1071 const limits = await runNode(
1072 readCursorUsageLimits(
1073 { apiEndpoint: "" },
1075 AGENT_CLI_CREDENTIAL_STORE: platform === "linux" ? "memory" : "default",
1076 ...(token ? { CURSOR_AUTH_TOKEN: token } : {}),
1077 },
1078 ).pipe(
1079 Effect.provideService(HostProcessPlatform, platform),
1080 Effect.provideService(
1081 FileSystem.FileSystem,
1082 FileSystem.makeNoop({
1083 readFileString: () => Effect.die("must not read an unrelated credential file"),
1084 }),
1085 ),
1086 Effect.provideService(
1087 HttpClient.HttpClient,
1088 HttpClient.make((request) => {
1089 expect(token).toBe("explicit-token");
1090 expect(request.headers.authorization).toBe("Bearer explicit-token");
1091 return Effect.succeed(
1092 HttpClientResponse.fromWeb(
1093 request,
1094 Response.json({ planUsage: { totalPercentUsed: 10 } }),
1095 ),
1096 );
1097 }),
1098 ),
1099 ),
1100 );
1101 if (token) expect(limits.windows[0]?.usedPercent).toBe(10);
1102 else expect(limits.unavailable?.reason).toBe("unsupported");
1105 });
1106​
1107 it("reports failed requests without exposing credentials or response bodies", async () => {
1108 const limits = await runNode(
1109 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_AUTH_TOKEN: "private-token" }).pipe(
1110 Effect.provideService(
1111 HttpClient.HttpClient,
1112 HttpClient.make((request) =>
1113 Effect.succeed(
1114 HttpClientResponse.fromWeb(
1115 request,
1116 new Response("private response", { status: 401 }),
1117 ),
1118 ),
1119 ),
1120 ),
1121 ),
1122 );
1123 expect(limits.unavailable).toEqual({
1124 reason: "probeFailed",
1125 message: "Cursor could not read usage limits.",
1126 });
1127 });
1128​
1129 it("does not use a stored login for an explicit API key", async () => {
1130 const limits = await runNode(
1131 readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "different-account" }).pipe(
1132 Effect.provideService(
1133 HttpClient.HttpClient,
1134 HttpClient.make(() => Effect.die("must not request usage")),
1135 ),
1136 ),
1137 );
1138 expect(limits.unavailable?.reason).toBe("unsupported");
1139 });
1140});