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