Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import type { AgentOptions, SDKModel } from "@cursor/sdk";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { expect, it } from "@effect/vitest";
5import {
6 MessageId,
7 NodeId,
8 ProjectId,
9 ProviderInstanceId,
10 ProviderSessionId,
11 RunAttemptId,
12 RunId,
13 ThreadId,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16import * as Fiber from "effect/Fiber";
17import * as FileSystem from "effect/FileSystem";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Stream from "effect/Stream";
22import { vi } from "vite-plus/test";
23import * as HttpClient from "effect/http/HttpClient";
24import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
25
26import {
27 DEFAULT_HANDOFF_TOKEN_CAP,
28 handoffBudget,
29} from "@t3tools/provider-core/server/handoffBudget";
30import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
31import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
32import { CursorDriver } from "./driver.ts";
33import * as CursorAgentSdk from "./CursorAgentSdk.ts";
34import * as CursorSdk from "./CursorSdk.ts";
35import * as CursorKeychain from "./CursorKeychain.ts";
36import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
37import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
38import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
39import { Cursor } from "./sdk.ts";
40
41const layerTest = TestProviderHost.layer({ runBackgroundWork: false }).pipe(
42 Layer.provideMerge(NodeServices.layer),
43 Layer.provideMerge(IdAllocator.layer),
44 Layer.provideMerge(McpProviderSessions.layer),
45 Layer.provideMerge(CursorSdk.layer),
46 Layer.provideMerge(
47 Layer.mock(CursorAgentSdk.CursorAgentSdkRunner)({
48 open: () => Effect.die("Maintenance resolution must not open a Cursor session"),
49 }),
50 ),
51 Layer.provideMerge(
52 Layer.succeed(CursorKeychain.CursorKeychain, {
53 accessToken: Effect.die("The driver test must not read the Keychain"),
54 }),
55 ),
56 Layer.provideMerge(
57 Layer.succeed(
58 ProviderEventLoggers.ProviderEventLoggers,
59 ProviderEventLoggers.NoOpProviderEventLoggers,
60 ),
61 ),
62 Layer.provideMerge(
63 Layer.succeed(
64 HttpClient.HttpClient,
65 HttpClient.make(() => Effect.die("Disabled Cursor must not make an HTTP request")),
66 ),
67 ),
68);
69
70it.layer(layerTest)("CursorDriver", (it) => {
71 it.effect(
72 "persists browser credentials, uses them for chat, and closes the SDK session on logout",
73 () =>
74 Effect.gen(function* () {
75 const login = vi.spyOn(Cursor.auth, "login").mockImplementation(async (options) => {
76 options?.onLoginUrl?.("https://cursor.com/loginDeepControl?challenge=test-only");
77 await options?.store?.save({
78 version: 1,
79 backendUrl: "https://api2.cursor.sh",
80 apiKey: "instance-browser-key",
81 createdAtMs: 0,
82 apiKeyExpiresAtMs: 4_000_000_000_000,
83 email: "cursor@example.com",
84 });
85 return { apiKey: "instance-browser-key", apiKeyExpiresAtMs: 4_000_000_000_000 };
86 });
87 const me = vi.spyOn(Cursor, "me").mockResolvedValue({
88 apiKeyName: "T3 Code",
89 createdAt: "2026-01-01T00:00:00.000Z",
90 userEmail: "cursor@example.com",
91 });
92 const models = vi
93 .spyOn(Cursor.models, "list")
94 .mockResolvedValue([{ id: "auto", displayName: "Auto" }]);
95 yield* Effect.addFinalizer(() =>
96 Effect.sync(() => {
97 login.mockRestore();
98 me.mockRestore();
99 models.mockRestore();
100 }),
101 );
102 const input = {
103 instanceId: ProviderInstanceId.make("cursor-browser-persisted"),
104 displayName: "Personal Cursor",
105 enabled: true,
106 environment: [{ name: "CURSOR_API_KEY", value: "", sensitive: true }],
107 config: CursorDriver.defaultConfig(),
108 };
109 const openedKeys: Array<string | undefined> = [];
110 let closed = 0;
111 const instance = yield* CursorDriver.create(input).pipe(
112 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
113 assertComplete: Effect.void,
114 open: (request) =>
115 Effect.sync(() => {
116 openedKeys.push(request.options.apiKey);
117 return {
118 agentId: "browser-auth-agent",
119 listMessages: Effect.succeed([]),
120 send: () => Effect.die("This test only opens a session"),
121 close: Effect.sync(() => {
122 closed += 1;
123 }),
124 };
125 }),
126 }),
127 );
128 expect((yield* instance.snapshot.refresh).auth.status).toBe("unauthenticated");
129 yield* instance.auth!.start("client");
130 yield* instance.auth!.subscribe("client").pipe(
131 Stream.filter((state) => state.phase === "succeeded"),
132 Stream.runHead,
133 Effect.map(Option.getOrThrow),
134 );
135 expect(me).toHaveBeenCalledWith({ apiKey: "instance-browser-key" });
136 expect(yield* instance.snapshot.getSnapshot).toMatchObject({
137 status: "ready",
138 auth: {
139 status: "authenticated",
140 type: "browser",
141 canLogout: true,
142 email: "cursor@example.com",
143 },
144 setup: { canAuthenticate: true, canInstall: false },
145 });
146 const threadId = ThreadId.make("cursor-browser-thread");
147 const modelSelection = { instanceId: input.instanceId, model: "auto" };
148 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
149 runtimeMode: "full-access",
150 interactionMode: "default",
151 cwd: process.cwd(),
152 });
153 const runtime = yield* instance.orchestrationAdapter.openSession({
154 threadId,
155 providerSessionId: ProviderSessionId.make("cursor-browser-session"),
156 modelSelection,
157 runtimePolicy,
158 });
159 yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
160 expect(openedKeys).toEqual(["instance-browser-key"]);
161 expect(closed).toBe(0);
162 const recreated = yield* CursorDriver.create(input);
163 expect((yield* recreated.snapshot.refresh).auth.status).toBe("authenticated");
164 yield* instance.auth!.logout(Effect.void);
165 expect(closed).toBe(1);
166 expect((yield* instance.snapshot.getSnapshot).auth.status).toBe("unauthenticated");
167 expect((yield* recreated.snapshot.refresh).auth.status).toBe("unauthenticated");
168 expect(
169 (yield* Effect.exit(runtime.ensureThread({ threadId, modelSelection, runtimePolicy })))
170 ._tag,
171 ).toBe("Failure");
172 expect(openedKeys).toEqual(["instance-browser-key"]);
173 expect(closed).toBe(1);
174 }).pipe(Effect.scoped),
175 );
176
177 it.effect("budgets handoffs for the SDK model across catalog refreshes and option changes", () =>
178 Effect.gen(function* () {
179 const fileSystem = yield* FileSystem.FileSystem;
180 const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-window-" });
181 const catalog = Promise.withResolvers<Array<SDKModel>>();
182 const catalogRequested = Promise.withResolvers<void>();
183 const me = vi.spyOn(Cursor, "me").mockResolvedValue({
184 apiKeyName: "T3 Code",
185 createdAt: "2026-01-01T00:00:00.000Z",
186 });
187 const models = vi.spyOn(Cursor.models, "list").mockImplementation(() => {
188 catalogRequested.resolve();
189 return catalog.promise;
190 });
191 yield* Effect.addFinalizer(() =>
192 Effect.sync(() => {
193 me.mockRestore();
194 models.mockRestore();
195 }),
196 );
197 const instanceId = ProviderInstanceId.make("cursor-catalog-window");
198 const openedModels: Array<AgentOptions["model"]> = [];
199 const sentModels: Array<AgentOptions["model"]> = [];
200 const instance = yield* CursorDriver.create({
201 instanceId,
202 displayName: "Cursor",
203 enabled: true,
204 environment: [{ name: "CURSOR_API_KEY", value: "catalog-window-key", sensitive: true }],
205 config: CursorDriver.defaultConfig(),
206 }).pipe(
207 Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
208 assertComplete: Effect.void,
209 open: (request) =>
210 Effect.sync(() => {
211 openedModels.push(request.options.model);
212 return {
213 agentId: "native-cursor-window",
214 listMessages: Effect.succeed([]),
215 close: Effect.void,
216 send: (input) =>
217 Effect.sync(() => {
218 sentModels.push(input.options?.model);
219 const runId = `native-cursor-window-run-${sentModels.length}`;
220 return {
221 agentId: "native-cursor-window",
222 runId,
223 cancel: Effect.void,
224 wait: Effect.succeed({
225 id: runId,
226 requestId: runId,
227 status: "finished" as const,
228 model: { id: "claude-opus-5-5" },
229 durationMs: 1,
230 }),
231 };
232 }),
233 };
234 }),
235 }),
236 );
237 const selection = (contextWindow?: string) => ({
238 instanceId,
239 model: "claude-opus-5-5",
240 ...(contextWindow === undefined
241 ? {}
242 : { options: [{ id: "contextWindow", value: contextWindow }] }),
243 });
244 const threadId = ThreadId.make("cursor-catalog-window-thread");
245 const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
246 runtimeMode: "full-access",
247 interactionMode: "default",
248 cwd: workspace,
249 });
250 const runtime = yield* instance.orchestrationAdapter.openSession({
251 threadId,
252 providerSessionId: ProviderSessionId.make("cursor-catalog-window-session"),
253 modelSelection: selection("1m"),
254 runtimePolicy,
255 });
256 const refresh = yield* instance.snapshot.refresh.pipe(Effect.forkScoped);
257 yield* Effect.promise(() => catalogRequested.promise);
258 expect(runtime.getModelContextWindow?.(selection())).toBeUndefined();
259 const providerThread = yield* runtime.ensureThread({
260 threadId,
261 modelSelection: selection("1m"),
262 runtimePolicy,
263 });
264 const now = yield* DateTime.now;
265 const startTurn = Effect.fnUntraced(function* (contextWindow?: string) {
266 const modelSelection = selection(contextWindow);
267 const ordinal = sentModels.length + 1;
268 yield* runtime.startTurn({
269 threadId,
270 providerThread,
271 modelSelection,
272 runtimePolicy,
273 runId: RunId.make(`cursor-window-run-${ordinal}`),
274 runOrdinal: ordinal,
275 providerTurnOrdinal: ordinal,
276 attemptId: RunAttemptId.make(`cursor-window-attempt-${ordinal}`),
277 rootNodeId: NodeId.make(`cursor-window-root-${ordinal}`),
278 appThread: {
279 id: threadId,
280 projectId: ProjectId.make("cursor-window-project"),
281 createdBy: "user",
282 creationSource: "web",
283 title: "Cursor context window",
284 providerInstanceId: instanceId,
285 modelSelection,
286 runtimeMode: "full-access",
287 interactionMode: "default",
288 branch: null,
289 worktreePath: null,
290 activeProviderThreadId: providerThread.id,
291 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
292 forkedFrom: null,
293 createdAt: now,
294 updatedAt: now,
295 archivedAt: null,
296 settledOverride: null,
297 settledAt: null,
298 lastVisitedAt: null,
299 deletedAt: null,
300 },
301 message: {
302 messageId: MessageId.make(`cursor-window-message-${ordinal}`),
303 createdBy: "user",
304 creationSource: "web",
305 text: "Continue.",
306 attachments: [],
307 },
308 });
309 yield* runtime.events.pipe(
310 Stream.takeUntil((event) => event.type === "turn.terminal"),
311 Stream.runDrain,
312 );
313 const window = runtime.getModelContextWindow?.(modelSelection);
314 return {
315 model: sentModels.at(-1),
316 window,
317 allowance: handoffBudget({
318 tokenCap: DEFAULT_HANDOFF_TOKEN_CAP,
319 userText: "Continue.",
320 attachments: [],
321 providerThread,
322 nativeContextEstimate: 400_000,
323 modelContextWindow: window,
324 }),
325 };
326 });
327 const beforeCatalog = yield* startTurn("1m");
328 catalog.resolve([
329 {
330 id: "claude-opus-5-5",
331 displayName: "Claude Opus 5.5",
332 parameters: [
333 {
334 id: "context",
335 displayName: "Context",
336 values: [{ value: "300k" }, { value: "1m" }],
337 },
338 ],
339 variants: [
340 {
341 displayName: "Claude Opus 5.5",
342 isDefault: true,
343 params: [{ id: "context", value: "1m" }],
344 },
345 ],
346 },
347 ]);
348 expect((yield* Fiber.join(refresh)).status).toBe("ready");
349 const catalogDefault = yield* startTurn();
350 const explicitWindow = yield* startTurn("500k");
351 const unknownWindow = yield* startTurn("max");
352 me.mockRejectedValue(new Error("Cursor is unreachable"));
353 expect((yield* instance.snapshot.refresh).status).toBe("error");
354 const retainedDefault = yield* startTurn();
355
356 expect(openedModels).toEqual([
357 {
358 id: "claude-opus-5-5",
359 params: [{ id: "context", value: "1m" }],
360 },
361 ]);
362 expect({
363 beforeCatalog,
364 catalogDefault,
365 explicitWindow,
366 unknownWindow,
367 retainedDefault,
368 }).toEqual({
369 beforeCatalog: {
370 model: { id: "claude-opus-5-5", params: [{ id: "context", value: "1m" }] },
371 window: 1_000_000,
372 allowance: DEFAULT_HANDOFF_TOKEN_CAP,
373 },
374 catalogDefault: {
375 model: { id: "claude-opus-5-5" },
376 window: 1_000_000,
377 allowance: DEFAULT_HANDOFF_TOKEN_CAP,
378 },
379 explicitWindow: {
380 model: { id: "claude-opus-5-5", params: [{ id: "context", value: "500k" }] },
381 window: 500_000,
382 allowance: 0,
383 },
384 unknownWindow: {
385 model: { id: "claude-opus-5-5", params: [{ id: "context", value: "max" }] },
386 window: undefined,
387 allowance: 0,
388 },
389 retainedDefault: catalogDefault,
390 });
391 }).pipe(Effect.scoped),
392 );
393
394 it.effect("keeps the bundled SDK manual-only without probing or updating cursor-agent", () =>
395 Effect.gen(function* () {
396 const instance = yield* CursorDriver.create({
397 instanceId: ProviderInstanceId.make("cursor-sdk"),
398 displayName: "Cursor test",
399 enabled: false,
400 environment: [],
401 config: CursorDriver.defaultConfig(),
402 });
403 expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
404 expect((yield* instance.snapshot.refresh).status).toBe("disabled");
405 }).pipe(
406 Effect.provideService(
407 ChildProcessSpawner.ChildProcessSpawner,
408 ChildProcessSpawner.make(() => Effect.die("SDK maintenance must not spawn a process")),
409 ),
410 Effect.scoped,
411 ),
412 );
413});