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