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

driver.test.ts

392 lines14.6 KB

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