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

CursorAdapter.test.ts

1,307 lines50.1 KB

1import * as path from "node:path";
2import * as os from "node:os";
3import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
4import { fileURLToPath } from "node:url";
5​
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { assert, it } from "@effect/vitest";
8import { Context, Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect";
9import { createModelSelection } from "@t3tools/shared/model";
10​
11import {
12 ApprovalRequestId,
13 CursorSettings,
14 ProviderDriverKind,
15 type ProviderRuntimeEvent,
16 ThreadId,
17 ProviderInstanceId,
18} from "@t3tools/contracts";
19​
20import { ServerConfig } from "../../config.ts";
21import { ServerSettingsService } from "../../serverSettings.ts";
22import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
23import { makeCursorAdapter } from "./CursorAdapter.ts";
24​
25// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`.
26class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(
27 "test/CursorAdapter",
28) {}
29​
30const __dirname = path.dirname(fileURLToPath(import.meta.url));
31const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
32const bunExe = "bun";
33​
34async function makeMockAgentWrapper(
35 extraEnv?: Record<string, string>,
36 options?: { initialDelaySeconds?: number },
37) {
38 const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-acp-mock-"));
39 const wrapperPath = path.join(dir, "fake-agent.sh");
40 const envExports = Object.entries(extraEnv ?? {})
41 .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
42 .join("\n");
43 const script = `#!/bin/sh
44${envExports}
45${options?.initialDelaySeconds ? `sleep ${JSON.stringify(String(options.initialDelaySeconds))}` : ""}
46exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
47`;
48 await writeFile(wrapperPath, script, "utf8");
49 await chmod(wrapperPath, 0o755);
50 return wrapperPath;
52​
53async function makeProbeWrapper(
54 requestLogPath: string,
55 argvLogPath: string,
56 extraEnv?: Record<string, string>,
57) {
58 const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-acp-probe-"));
59 const wrapperPath = path.join(dir, "fake-agent.sh");
60 const envExports = Object.entries(extraEnv ?? {})
61 .map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
62 .join("\n");
63 const script = `#!/bin/sh
64printf '%s\t' "$@" >> ${JSON.stringify(argvLogPath)}
65printf '\n' >> ${JSON.stringify(argvLogPath)}
66export T3_ACP_REQUEST_LOG_PATH=${JSON.stringify(requestLogPath)}
67${envExports}
68exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
69`;
70 await writeFile(wrapperPath, script, "utf8");
71 await chmod(wrapperPath, 0o755);
72 return wrapperPath;
74​
75async function readArgvLog(filePath: string) {
76 const raw = await readFile(filePath, "utf8");
77 return raw
78 .split("\n")
79 .map((line) => line.trim())
80 .filter((line) => line.length > 0)
81 .map((line) => line.split("\t").filter((token) => token.length > 0));
83​
84async function readJsonLines(filePath: string) {
85 const raw = await readFile(filePath, "utf8");
86 return raw
87 .split("\n")
88 .map((line) => line.trim())
89 .filter((line) => line.length > 0)
90 .map((line) => JSON.parse(line) as Record<string, unknown>);
92​
93async function waitForFileContent(filePath: string, attempts = 40) {
94 for (let attempt = 0; attempt < attempts; attempt += 1) {
95 try {
96 const raw = await readFile(filePath, "utf8");
97 if (raw.trim().length > 0) {
98 return raw;
99 }
100 } catch {}
101 await new Promise((resolve) => setTimeout(resolve, 50));
102 }
103 throw new Error(`Timed out waiting for file content at ${filePath}`);
105​
106// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
107// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
108// captures `cursorSettings` once at construction, so without a resolver
109// the mutation is invisible — sessions would spawn the constructor's
110// (empty) binary path. Wiring `resolveSettings` through
111// `ServerSettingsService.getSettings` makes each session read the latest
112// snapshot, matching the old "always read live" behavior that these
113// tests assumed.
114const makeResolveCursorSettings = Effect.gen(function* () {
115 const serverSettings = yield* ServerSettingsService;
116 // @effect-diagnostics effect/returnEffectInGen:off
117 return serverSettings.getSettings.pipe(
118 Effect.map((snapshot) => snapshot.providers.cursor),
119 Effect.orDie,
120 );
121});
122​
123const cursorAdapterTestLayer = it.layer(
124 Layer.effect(
125 CursorAdapter,
126 Effect.gen(function* () {
127 const cursorConfig = Schema.decodeSync(CursorSettings)({});
128 const resolveSettings = yield* makeResolveCursorSettings;
129 return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
130 }),
131 ).pipe(
132 Layer.provideMerge(ServerSettingsService.layerTest()),
133 Layer.provideMerge(
134 ServerConfig.layerTest(process.cwd(), {
135 prefix: "t3code-cursor-adapter-test-",
136 }),
137 ),
138 Layer.provideMerge(NodeServices.layer),
139 ),
140);
141​
142cursorAdapterTestLayer("CursorAdapterLive", (it) => {
143 it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
144 Effect.gen(function* () {
145 const adapter = yield* CursorAdapter;
146 const settings = yield* ServerSettingsService;
147 const threadId = ThreadId.make("cursor-mock-thread");
148​
149 const wrapperPath = yield* Effect.promise(() => makeMockAgentWrapper());
150 yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
151​
152 const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 9).pipe(
153 Stream.runCollect,
154 Effect.forkChild,
155 );
156​
157 const session = yield* adapter.startSession({
158 threadId,
159 provider: ProviderDriverKind.make("cursor"),
160 cwd: process.cwd(),
161 runtimeMode: "full-access",
162 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
163 });
164​
165 assert.equal(session.provider, "cursor");
166 assert.deepStrictEqual(session.resumeCursor, {
167 schemaVersion: 1,
168 sessionId: "mock-session-1",
169 });
170​
171 yield* adapter.sendTurn({
172 threadId,
173 input: "hello mock",
174 attachments: [],
175 });
176​
177 const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
178 const types = runtimeEvents.map((e) => e.type);
179​
180 for (const t of [
181 "session.started",
182 "session.state.changed",
183 "thread.started",
184 "turn.started",
185 "turn.plan.updated",
186 "item.started",
187 "content.delta",
188 "item.completed",
189 "turn.completed",
190 ] as const) {
191 assert.include(types, t);
192 }
193​
194 const assistantStarted = runtimeEvents.find(
195 (event) => event.type === "item.started" && event.payload.itemType === "assistant_message",
196 );
197 assert.isDefined(assistantStarted);
198​
199 const delta = runtimeEvents.find((e) => e.type === "content.delta");
200 assert.isDefined(delta);
201 if (delta?.type === "content.delta") {
202 assert.equal(delta.payload.delta, "hello from mock");
203 assert.match(String(delta.itemId), /^assistant:mock-session-1:segment:0$/);
204 }
205​
206 const assistantCompleted = runtimeEvents.find(
207 (event) =>
208 event.type === "item.completed" && event.payload.itemType === "assistant_message",
209 );
210 assert.isDefined(assistantCompleted);
211​
212 const planUpdate = runtimeEvents.find((event) => event.type === "turn.plan.updated");
213 assert.isDefined(planUpdate);
214 if (planUpdate?.type === "turn.plan.updated") {
215 assert.deepStrictEqual(planUpdate.payload.plan, [
216 { step: "Inspect mock ACP state", status: "completed" },
217 { step: "Implement the requested change", status: "inProgress" },
218 ]);
219 }
220​
221 yield* adapter.stopSession(threadId);
222 }),
223 );
224​
225 it.effect("closes the ACP child process when a session stops", () =>
226 Effect.gen(function* () {
227 const adapter = yield* CursorAdapter;
228 const settings = yield* ServerSettingsService;
229 const threadId = ThreadId.make("cursor-stop-session-close");
230 const tempDir = yield* Effect.promise(() =>
231 mkdtemp(path.join(os.tmpdir(), "cursor-adapter-exit-log-")),
232 );
233 const exitLogPath = path.join(tempDir, "exit.log");
234​
235 const wrapperPath = yield* Effect.promise(() =>
236 makeMockAgentWrapper({
237 T3_ACP_EXIT_LOG_PATH: exitLogPath,
238 }),
239 );
240 yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
241​
242 yield* adapter.startSession({
243 threadId,
244 provider: ProviderDriverKind.make("cursor"),
245 cwd: process.cwd(),
246 runtimeMode: "full-access",
247 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
248 });
249​
250 yield* adapter.stopSession(threadId);
251​
252 const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath));
253 assert.include(exitLog, "SIGTERM");
254 }),
255 );
256​
257 it.effect(
258 "serializes concurrent startSession calls for the same thread and closes the replaced ACP session",
259 () =>
260 Effect.gen(function* () {
261 const adapter = yield* CursorAdapter;
262 const settings = yield* ServerSettingsService;
263 const threadId = ThreadId.make("cursor-concurrent-start-session");
264 const tempDir = yield* Effect.promise(() =>
265 mkdtemp(path.join(os.tmpdir(), "cursor-adapter-concurrent-exit-log-")),
266 );
267 const exitLogPath = path.join(tempDir, "exit.log");
268​
269 const wrapperPath = yield* Effect.promise(() =>
270 makeMockAgentWrapper(
271 {
272 T3_ACP_EXIT_LOG_PATH: exitLogPath,
273 },
274 { initialDelaySeconds: 0.2 },
275 ),
276 );
277 yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
278​
279 const [firstSession, secondSession] = yield* Effect.all(
280 [
281 adapter.startSession({
282 threadId,
283 provider: ProviderDriverKind.make("cursor"),
284 cwd: process.cwd(),
285 runtimeMode: "full-access",
286 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
287 }),
288 adapter.startSession({
289 threadId,
290 provider: ProviderDriverKind.make("cursor"),
291 cwd: process.cwd(),
292 runtimeMode: "full-access",
293 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
294 }),
295 ],
296 { concurrency: "unbounded" },
297 );
298​
299 assert.equal(firstSession.threadId, threadId);
300 assert.equal(secondSession.threadId, threadId);
301​
302 yield* adapter.stopSession(threadId);
303​
304 const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath));
305 assert.equal(exitLog.match(/SIGTERM/g)?.length ?? 0, 2);
306 }),
307 );
308​
309 it.effect("rejects startSession when provider mismatches", () =>
310 Effect.gen(function* () {
311 const adapter = yield* CursorAdapter;
312 const result = yield* adapter
313 .startSession({
314 threadId: ThreadId.make("bad-provider"),
315 provider: ProviderDriverKind.make("codex"),
316 cwd: process.cwd(),
317 runtimeMode: "full-access",
318 })
319 .pipe(Effect.result);
320​
321 assert.equal(result._tag, "Failure");
322 }),
323 );
324​
325 it.effect("maps app plan mode onto the ACP plan session mode", () =>
326 Effect.gen(function* () {
327 const adapter = yield* CursorAdapter;
328 const serverSettings = yield* ServerSettingsService;
329 const threadId = ThreadId.make("cursor-plan-mode-probe");
330 const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
331 const requestLogPath = path.join(tempDir, "requests.ndjson");
332 const argvLogPath = path.join(tempDir, "argv.txt");
333 yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
334 const wrapperPath = yield* Effect.promise(() =>
335 makeProbeWrapper(requestLogPath, argvLogPath),
336 );
337 yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
338​
339 yield* adapter.startSession({
340 threadId,
341 provider: ProviderDriverKind.make("cursor"),
342 cwd: process.cwd(),
343 runtimeMode: "full-access",
344 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
345 });
346​
347 yield* adapter.sendTurn({
348 threadId,
349 input: "plan this change",
350 attachments: [],
351 interactionMode: "plan",
352 });
353 yield* adapter.stopSession(threadId);
354​
355 const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
356 const modeRequest = requests
357 .toReversed()
358 .find(
359 (entry) =>
360 entry.method === "session/set_mode" ||
361 (entry.method === "session/set_config_option" &&
362 (entry.params as Record<string, unknown> | undefined)?.configId === "mode"),
363 );
364 assert.isDefined(modeRequest);
365 assert.equal(
366 (modeRequest?.params as Record<string, unknown> | undefined)?.sessionId,
367 "mock-session-1",
368 );
369 assert.include(
370 ["architect", "plan"],
371 String(
372 (modeRequest?.params as Record<string, unknown> | undefined)?.modeId ??
373 (modeRequest?.params as Record<string, unknown> | undefined)?.value,
374 ),
375 );
376 }),
377 );
378​
379 it.effect(
380 "applies initial model and mode configuration during startSession and skips repeating it on first send",
381 () =>
382 Effect.gen(function* () {
383 const adapter = yield* CursorAdapter;
384 const serverSettings = yield* ServerSettingsService;
385 const threadId = ThreadId.make("cursor-initial-config-probe");
386 const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
387 const requestLogPath = path.join(tempDir, "requests.ndjson");
388 const argvLogPath = path.join(tempDir, "argv.txt");
389 yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
390 const wrapperPath = yield* Effect.promise(() =>
391 makeProbeWrapper(requestLogPath, argvLogPath),
392 );
393 yield* serverSettings.updateSettings({
394 providers: { cursor: { binaryPath: wrapperPath } },
395 });
396​
397 const modelSelection = createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
398 { id: "reasoning", value: "xhigh" },
399 { id: "contextWindow", value: "1m" },
400 { id: "fastMode", value: true },
401 ]);
402​
403 yield* adapter.startSession({
404 threadId,
405 provider: ProviderDriverKind.make("cursor"),
406 cwd: process.cwd(),
407 runtimeMode: "full-access",
408 modelSelection,
409 });
410​
411 yield* Effect.promise(() => waitForFileContent(requestLogPath));
412​
413 const requestsAfterStart = yield* Effect.promise(() => readJsonLines(requestLogPath));
414 const configIdsAfterStart = requestsAfterStart.flatMap((entry) =>
415 entry.method === "session/set_config_option" &&
416 typeof (entry.params as Record<string, unknown> | undefined)?.configId === "string"
417 ? [String((entry.params as Record<string, unknown>).configId)]
418 : [],
419 );
420 assert.deepStrictEqual(configIdsAfterStart, [
421 "model",
422 "reasoning",
423 "context",
424 "fast",
425 "mode",
426 ]);
427​
428 yield* adapter.sendTurn({
429 threadId,
430 input: "hello mock",
431 attachments: [],
432 modelSelection,
433 interactionMode: "default",
434 });
435 yield* adapter.stopSession(threadId);
436​
437 const finalRequests = yield* Effect.promise(() => readJsonLines(requestLogPath));
438 const finalConfigIds = finalRequests.flatMap((entry) =>
439 entry.method === "session/set_config_option" &&
440 typeof (entry.params as Record<string, unknown> | undefined)?.configId === "string"
441 ? [String((entry.params as Record<string, unknown>).configId)]
442 : [],
443 );
444 assert.deepStrictEqual(finalConfigIds, ["model", "reasoning", "context", "fast", "mode"]);
445 assert.equal(finalRequests.filter((entry) => entry.method === "session/prompt").length, 1);
446 }),
447 );
448​
449 it.effect(
450 "streams ACP tool calls and approvals on the active turn in approval-required mode",
451 () =>
452 Effect.gen(function* () {
453 const previousEmitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS;
454 process.env.T3_ACP_EMIT_TOOL_CALLS = "1";
455​
456 const adapter = yield* CursorAdapter;
457 const serverSettings = yield* ServerSettingsService;
458 const threadId = ThreadId.make("cursor-tool-call-probe");
459 const runtimeEvents: Array<ProviderRuntimeEvent> = [];
460 const settledEventTypes = new Set<string>();
461 const settledEventsReady = yield* Deferred.make<void>();
462​
463 const wrapperPath = yield* Effect.promise(() =>
464 makeMockAgentWrapper({ T3_ACP_EMIT_TOOL_CALLS: "1" }),
465 );
466 yield* serverSettings.updateSettings({
467 providers: { cursor: { binaryPath: wrapperPath } },
468 });
469​
470 yield* Stream.runForEach(adapter.streamEvents, (event) =>
471 Effect.gen(function* () {
472 runtimeEvents.push(event);
473 if (String(event.threadId) !== String(threadId)) {
474 return;
475 }
476 if (event.type === "request.opened" && event.requestId) {
477 yield* adapter.respondToRequest(
478 threadId,
479 ApprovalRequestId.make(String(event.requestId)),
480 "accept",
481 );
482 }
483 if (
484 event.type === "turn.completed" ||
485 (event.type === "item.completed" && event.payload.itemType === "command_execution") ||
486 event.type === "content.delta"
487 ) {
488 settledEventTypes.add(event.type);
489 if (settledEventTypes.size === 3) {
490 yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie);
491 }
492 }
493 }),
494 ).pipe(Effect.forkChild);
495​
496 const program = Effect.gen(function* () {
497 yield* adapter.startSession({
498 threadId,
499 provider: ProviderDriverKind.make("cursor"),
500 cwd: process.cwd(),
501 runtimeMode: "approval-required",
502 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
503 });
504​
505 const turn = yield* adapter.sendTurn({
506 threadId,
507 input: "run a tool call",
508 attachments: [],
509 });
510 yield* Deferred.await(settledEventsReady);
511​
512 const threadEvents = runtimeEvents.filter(
513 (event) => String(event.threadId) === String(threadId),
514 );
515 assert.includeMembers(
516 threadEvents.map((event) => event.type),
517 [
518 "session.started",
519 "session.state.changed",
520 "thread.started",
521 "turn.started",
522 "request.opened",
523 "request.resolved",
524 "item.updated",
525 "item.completed",
526 "content.delta",
527 "turn.completed",
528 ],
529 );
530​
531 const turnEvents = threadEvents.filter(
532 (event) => String(event.turnId) === String(turn.turnId),
533 );
534 const toolUpdates = turnEvents.filter((event) => event.type === "item.updated");
535 // ACP updates can arrive either as distinct pending + in-progress events
536 // or as a single coalesced in-progress update before approval resolves.
537 assert.isAtLeast(toolUpdates.length, 1);
538 for (const toolUpdate of toolUpdates) {
539 if (toolUpdate.type !== "item.updated") {
540 continue;
541 }
542 assert.equal(toolUpdate.payload.itemType, "command_execution");
543 assert.equal(toolUpdate.payload.status, "inProgress");
544 assert.equal(toolUpdate.payload.detail, "cat server/package.json");
545 assert.equal(String(toolUpdate.itemId), "tool-call-1");
546 }
547​
548 const requestOpened = turnEvents.find((event) => event.type === "request.opened");
549 assert.isDefined(requestOpened);
550 if (requestOpened?.type === "request.opened") {
551 assert.equal(String(requestOpened.turnId), String(turn.turnId));
552 assert.equal(requestOpened.payload.requestType, "exec_command_approval");
553 assert.equal(requestOpened.payload.detail, "cat server/package.json");
554 }
555​
556 const requestResolved = turnEvents.find((event) => event.type === "request.resolved");
557 assert.isDefined(requestResolved);
558 if (requestResolved?.type === "request.resolved") {
559 assert.equal(String(requestResolved.turnId), String(turn.turnId));
560 assert.equal(requestResolved.payload.requestType, "exec_command_approval");
561 assert.equal(requestResolved.payload.decision, "accept");
562 }
563​
564 const toolCompleted = turnEvents.find(
565 (event) =>
566 event.type === "item.completed" && event.payload.itemType === "command_execution",
567 );
568 assert.isDefined(toolCompleted);
569 if (toolCompleted?.type === "item.completed") {
570 assert.equal(String(toolCompleted.turnId), String(turn.turnId));
571 assert.equal(toolCompleted.payload.itemType, "command_execution");
572 assert.equal(toolCompleted.payload.status, "completed");
573 assert.equal(toolCompleted.payload.detail, "cat server/package.json");
574 assert.equal(String(toolCompleted.itemId), "tool-call-1");
575 }
576​
577 const contentDelta = turnEvents.find((event) => event.type === "content.delta");
578 assert.isDefined(contentDelta);
579 if (contentDelta?.type === "content.delta") {
580 assert.equal(String(contentDelta.turnId), String(turn.turnId));
581 assert.equal(contentDelta.payload.delta, "hello from mock");
582 assert.equal(String(contentDelta.itemId), "assistant:mock-session-1:segment:0");
583 }
584 });
585​
586 yield* program.pipe(
587 Effect.ensuring(
588 Effect.sync(() => {
589 if (previousEmitToolCalls === undefined) {
590 delete process.env.T3_ACP_EMIT_TOOL_CALLS;
591 } else {
592 process.env.T3_ACP_EMIT_TOOL_CALLS = previousEmitToolCalls;
593 }
594 }),
595 ),
596 );
597 }).pipe(
598 Effect.provide(
599 Layer.effect(
600 CursorAdapter,
601 Effect.gen(function* () {
602 const cursorConfig = Schema.decodeSync(CursorSettings)({});
603 const resolveSettings = yield* makeResolveCursorSettings;
604 return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
605 }),
606 ).pipe(
607 Layer.provideMerge(ServerSettingsService.layerTest()),
608 Layer.provideMerge(
609 ServerConfig.layerTest(process.cwd(), {
610 prefix: "t3code-cursor-adapter-test-",
611 }),
612 ),
613 Layer.provideMerge(NodeServices.layer),
614 ),
615 ),
616 ),
617 );
618​
619 it.effect(
620 "auto-approves ACP tool permissions in full-access mode without approval runtime events",
621 () =>
622 Effect.gen(function* () {
623 const adapter = yield* CursorAdapter;
624 const serverSettings = yield* ServerSettingsService;
625 const threadId = ThreadId.make("cursor-full-access-auto-approve");
626 const runtimeEvents: Array<ProviderRuntimeEvent> = [];
627 const settledEventTypes = new Set<string>();
628 const settledEventsReady = yield* Deferred.make<void>();
629 const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
630 const requestLogPath = path.join(tempDir, "requests.ndjson");
631 const argvLogPath = path.join(tempDir, "argv.txt");
632 yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
633 const wrapperPath = yield* Effect.promise(() =>
634 makeProbeWrapper(requestLogPath, argvLogPath, { T3_ACP_EMIT_TOOL_CALLS: "1" }),
635 );
636 yield* serverSettings.updateSettings({
637 providers: { cursor: { binaryPath: wrapperPath } },
638 });
639​
640 const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
641 Effect.gen(function* () {
642 runtimeEvents.push(event);
643 if (String(event.threadId) !== String(threadId)) {
644 return;
645 }
646 if (
647 event.type === "turn.completed" ||
648 (event.type === "item.completed" && event.payload.itemType === "command_execution") ||
649 event.type === "content.delta"
650 ) {
651 settledEventTypes.add(event.type);
652 if (settledEventTypes.size === 3) {
653 yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie);
654 }
655 }
656 }),
657 ).pipe(Effect.forkChild);
658​
659 yield* adapter.startSession({
660 threadId,
661 provider: ProviderDriverKind.make("cursor"),
662 cwd: process.cwd(),
663 runtimeMode: "full-access",
664 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
665 });
666​
667 const turn = yield* adapter.sendTurn({
668 threadId,
669 input: "run a tool call",
670 attachments: [],
671 });
672​
673 yield* Deferred.await(settledEventsReady);
674 yield* Fiber.interrupt(runtimeEventsFiber);
675​
676 const turnEvents = runtimeEvents.filter(
677 (event) =>
678 String(event.threadId) === String(threadId) &&
679 String(event.turnId) === String(turn.turnId),
680 );
681 assert.notInclude(
682 turnEvents.map((event) => event.type),
683 "request.opened",
684 );
685 assert.notInclude(
686 turnEvents.map((event) => event.type),
687 "request.resolved",
688 );
689 assert.includeMembers(
690 turnEvents.map((event) => event.type),
691 ["item.updated", "item.completed", "content.delta", "turn.completed"],
692 );
693​
694 const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
695 const permissionResponse = requests.find(
696 (entry) =>
697 !("method" in entry) &&
698 typeof entry.result === "object" &&
699 entry.result !== null &&
700 "outcome" in entry.result &&
701 typeof entry.result.outcome === "object" &&
702 entry.result.outcome !== null &&
703 "outcome" in entry.result.outcome &&
704 entry.result.outcome.outcome === "selected" &&
705 "optionId" in entry.result.outcome &&
706 entry.result.outcome.optionId === "allow-always",
707 );
708 assert.isDefined(permissionResponse);
709​
710 yield* adapter.stopSession(threadId);
711 }),
712 );
713​
714 it.effect("segments assistant messages around ACP tool activity in full-access mode", () =>
715 Effect.gen(function* () {
716 const adapter = yield* CursorAdapter;
717 const serverSettings = yield* ServerSettingsService;
718 const threadId = ThreadId.make("cursor-assistant-tool-segmentation");
719 const runtimeEvents: Array<ProviderRuntimeEvent> = [];
720 const settledEventTypes = new Set<string>();
721 const settledEventsReady = yield* Deferred.make<void>();
722​
723 const wrapperPath = yield* Effect.promise(() =>
724 makeMockAgentWrapper({ T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1" }),
725 );
726 yield* serverSettings.updateSettings({
727 providers: { cursor: { binaryPath: wrapperPath } },
728 });
729​
730 const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
731 Effect.gen(function* () {
732 runtimeEvents.push(event);
733 if (String(event.threadId) !== String(threadId)) {
734 return;
735 }
736 if (
737 event.type === "content.delta" ||
738 (event.type === "item.completed" && event.payload.itemType === "command_execution") ||
739 event.type === "turn.completed"
740 ) {
741 if (event.type === "content.delta") {
742 settledEventTypes.add(`delta:${event.payload.delta}`);
743 } else {
744 settledEventTypes.add(event.type);
745 }
746 if (
747 settledEventTypes.has("delta:before tool") &&
748 settledEventTypes.has("delta:after tool") &&
749 settledEventTypes.has("item.completed") &&
750 settledEventTypes.has("turn.completed")
751 ) {
752 yield* Deferred.succeed(settledEventsReady, undefined).pipe(Effect.orDie);
753 }
754 }
755 }),
756 ).pipe(Effect.forkChild);
757​
758 yield* adapter.startSession({
759 threadId,
760 provider: ProviderDriverKind.make("cursor"),
761 cwd: process.cwd(),
762 runtimeMode: "full-access",
763 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
764 });
765​
766 const turn = yield* adapter.sendTurn({
767 threadId,
768 input: "run an interleaved tool call",
769 attachments: [],
770 });
771​
772 yield* Deferred.await(settledEventsReady);
773 yield* Fiber.interrupt(runtimeEventsFiber);
774​
775 const turnEvents = runtimeEvents.filter(
776 (event) =>
777 String(event.threadId) === String(threadId) &&
778 String(event.turnId) === String(turn.turnId),
779 );
780 const firstAssistantStartIndex = turnEvents.findIndex(
781 (event) => event.type === "item.started" && event.payload.itemType === "assistant_message",
782 );
783 const firstAssistantDeltaIndex = turnEvents.findIndex(
784 (event) => event.type === "content.delta" && event.payload.delta === "before tool",
785 );
786 const assistantBoundaryIndex = turnEvents.findIndex(
787 (event) =>
788 event.type === "item.completed" && event.payload.itemType === "assistant_message",
789 );
790 const toolUpdateIndex = turnEvents.findIndex(
791 (event) => event.type === "item.updated" && event.payload.itemType === "command_execution",
792 );
793 const toolCompletedIndex = turnEvents.findIndex(
794 (event) =>
795 event.type === "item.completed" && event.payload.itemType === "command_execution",
796 );
797 const secondAssistantStartIndex = turnEvents.findIndex(
798 (event, index) =>
799 index > toolCompletedIndex &&
800 event.type === "item.started" &&
801 event.payload.itemType === "assistant_message",
802 );
803 const secondAssistantDeltaIndex = turnEvents.findIndex(
804 (event) => event.type === "content.delta" && event.payload.delta === "after tool",
805 );
806​
807 assert.isAtLeast(firstAssistantStartIndex, 0);
808 assert.isAtLeast(firstAssistantDeltaIndex, 0);
809 assert.isAtLeast(assistantBoundaryIndex, 0);
810 assert.isAtLeast(toolUpdateIndex, 0);
811 assert.isAtLeast(toolCompletedIndex, 0);
812 assert.isAtLeast(secondAssistantStartIndex, 0);
813 assert.isAtLeast(secondAssistantDeltaIndex, 0);
814 assert.isBelow(firstAssistantStartIndex, firstAssistantDeltaIndex);
815 assert.isBelow(firstAssistantDeltaIndex, assistantBoundaryIndex);
816 assert.isBelow(assistantBoundaryIndex, toolUpdateIndex);
817 assert.isBelow(toolUpdateIndex, toolCompletedIndex);
818 assert.isBelow(toolCompletedIndex, secondAssistantStartIndex);
819 assert.isBelow(secondAssistantStartIndex, secondAssistantDeltaIndex);
820​
821 const assistantStarts = turnEvents.filter(
822 (event) => event.type === "item.started" && event.payload.itemType === "assistant_message",
823 );
824 const assistantDeltas = turnEvents.filter((event) => event.type === "content.delta");
825 assert.lengthOf(assistantStarts, 2);
826 assert.lengthOf(assistantDeltas, 2);
827 if (
828 assistantStarts[0]?.type === "item.started" &&
829 assistantStarts[1]?.type === "item.started" &&
830 assistantDeltas[0]?.type === "content.delta" &&
831 assistantDeltas[1]?.type === "content.delta"
832 ) {
833 assert.notEqual(String(assistantStarts[0].itemId), String(assistantStarts[1].itemId));
834 assert.equal(String(assistantDeltas[0].itemId), String(assistantStarts[0].itemId));
835 assert.equal(String(assistantDeltas[1].itemId), String(assistantStarts[1].itemId));
836 }
837​
838 yield* adapter.stopSession(threadId);
839 }),
840 );
841​
842 it.effect("cancels pending ACP approvals and marks the turn cancelled when interrupted", () =>
843 Effect.gen(function* () {
844 const adapter = yield* CursorAdapter;
845 const serverSettings = yield* ServerSettingsService;
846 const threadId = ThreadId.make("cursor-cancel-probe");
847 const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
848 const requestLogPath = path.join(tempDir, "requests.ndjson");
849 const argvLogPath = path.join(tempDir, "argv.txt");
850 yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
851 const wrapperPath = yield* Effect.promise(() =>
852 makeProbeWrapper(requestLogPath, argvLogPath, { T3_ACP_EMIT_TOOL_CALLS: "1" }),
853 );
854 yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
855​
856 const requestResolvedReady = yield* Deferred.make<ProviderRuntimeEvent>();
857 const turnCompletedReady = yield* Deferred.make<ProviderRuntimeEvent>();
858 let interrupted = false;
859​
860 const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
861 Effect.gen(function* () {
862 if (String(event.threadId) !== String(threadId)) {
863 return;
864 }
865 if (event.type === "request.opened" && !interrupted) {
866 interrupted = true;
867 yield* adapter.interruptTurn(threadId);
868 return;
869 }
870 if (event.type === "request.resolved") {
871 yield* Deferred.succeed(requestResolvedReady, event).pipe(Effect.ignore);
872 return;
873 }
874 if (event.type === "turn.completed") {
875 yield* Deferred.succeed(turnCompletedReady, event).pipe(Effect.ignore);
876 }
877 }),
878 ).pipe(Effect.forkChild);
879​
880 yield* adapter.startSession({
881 threadId,
882 provider: ProviderDriverKind.make("cursor"),
883 cwd: process.cwd(),
884 runtimeMode: "approval-required",
885 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
886 });
887​
888 const sendTurnFiber = yield* adapter
889 .sendTurn({
890 threadId,
891 input: "cancel this turn",
892 attachments: [],
893 })
894 .pipe(Effect.forkChild);
895​
896 const requestResolved = yield* Deferred.await(requestResolvedReady);
897 const turnCompleted = yield* Deferred.await(turnCompletedReady);
898 yield* Fiber.join(sendTurnFiber);
899 yield* Fiber.interrupt(runtimeEventsFiber);
900​
901 assert.equal(requestResolved.type, "request.resolved");
902 if (requestResolved.type === "request.resolved") {
903 assert.equal(requestResolved.payload.decision, "cancel");
904 }
905​
906 assert.equal(turnCompleted.type, "turn.completed");
907 if (turnCompleted.type === "turn.completed") {
908 assert.equal(turnCompleted.payload.state, "cancelled");
909 assert.equal(turnCompleted.payload.stopReason, "cancelled");
910 }
911​
912 const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
913 assert.isTrue(requests.some((entry) => entry.method === "session/cancel"));
914 assert.isTrue(
915 requests.some(
916 (entry) =>
917 !("method" in entry) &&
918 typeof entry.result === "object" &&
919 entry.result !== null &&
920 "outcome" in entry.result &&
921 typeof entry.result.outcome === "object" &&
922 entry.result.outcome !== null &&
923 "outcome" in entry.result.outcome &&
924 entry.result.outcome.outcome === "cancelled",
925 ),
926 );
927​
928 yield* adapter.stopSession(threadId);
929 }),
930 );
931 it.effect("stopping a session settles pending approval waits", () =>
932 Effect.gen(function* () {
933 const adapter = yield* CursorAdapter;
934 const serverSettings = yield* ServerSettingsService;
935 const threadId = ThreadId.make("cursor-stop-pending-approval");
936 const approvalRequested = yield* Deferred.make<void>();
937​
938 const wrapperPath = yield* Effect.promise(() =>
939 makeMockAgentWrapper({ T3_ACP_EMIT_TOOL_CALLS: "1" }),
940 );
941 yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
942​
943 yield* Stream.runForEach(adapter.streamEvents, (event) => {
944 if (String(event.threadId) !== String(threadId) || event.type !== "request.opened") {
945 return Effect.void;
946 }
947 return Deferred.succeed(approvalRequested, undefined).pipe(Effect.ignore);
948 }).pipe(Effect.forkChild);
949​
950 yield* adapter.startSession({
951 threadId,
952 provider: ProviderDriverKind.make("cursor"),
953 cwd: process.cwd(),
954 runtimeMode: "approval-required",
955 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
956 });
957​
958 const sendTurnFiber = yield* adapter
959 .sendTurn({
960 threadId,
961 input: "run a tool call and then stop",
962 attachments: [],
963 })
964 .pipe(Effect.forkChild);
965​
966 yield* Deferred.await(approvalRequested);
967 yield* adapter.stopSession(threadId);
968 yield* Fiber.await(sendTurnFiber);
969​
970 assert.equal(yield* adapter.hasSession(threadId), false);
971 }),
972 );
973​
974 it.effect("stopping a session settles pending user-input waits", () =>
975 Effect.gen(function* () {
976 const adapter = yield* CursorAdapter;
977 const serverSettings = yield* ServerSettingsService;
978 const threadId = ThreadId.make("cursor-stop-pending-user-input");
979 const userInputRequested = yield* Deferred.make<void>();
980​
981 const wrapperPath = yield* Effect.promise(() =>
982 makeMockAgentWrapper({ T3_ACP_EMIT_ASK_QUESTION: "1" }),
983 );
984 yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
985​
986 yield* Stream.runForEach(adapter.streamEvents, (event) => {
987 if (String(event.threadId) !== String(threadId) || event.type !== "user-input.requested") {
988 return Effect.void;
989 }
990 return Deferred.succeed(userInputRequested, undefined).pipe(Effect.ignore);
991 }).pipe(Effect.forkChild);
992​
993 yield* adapter.startSession({
994 threadId,
995 provider: ProviderDriverKind.make("cursor"),
996 cwd: process.cwd(),
997 runtimeMode: "full-access",
998 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
999 });
1000​
1001 const sendTurnFiber = yield* adapter
1002 .sendTurn({
1003 threadId,
1004 input: "ask me a question and then stop",
1005 attachments: [],
1006 })
1007 .pipe(Effect.forkChild);
1008​
1009 yield* Deferred.await(userInputRequested);
1010 yield* adapter.stopSession(threadId);
1011 yield* Fiber.await(sendTurnFiber);
1012​
1013 assert.equal(yield* adapter.hasSession(threadId), false);
1014 }),
1015 );
1016​
1017 it.effect("interrupting a session settles pending user-input waits", () =>
1018 Effect.gen(function* () {
1019 const adapter = yield* CursorAdapter;
1020 const serverSettings = yield* ServerSettingsService;
1021 const threadId = ThreadId.make("cursor-interrupt-pending-user-input");
1022 const userInputRequested = yield* Deferred.make<void>();
1023​
1024 const wrapperPath = yield* Effect.promise(() =>
1025 makeMockAgentWrapper({ T3_ACP_EMIT_ASK_QUESTION: "1" }),
1026 );
1027 yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
1028​
1029 yield* Stream.runForEach(adapter.streamEvents, (event) => {
1030 if (String(event.threadId) !== String(threadId) || event.type !== "user-input.requested") {
1031 return Effect.void;
1033 return Deferred.succeed(userInputRequested, undefined).pipe(Effect.ignore);
1034 }).pipe(Effect.forkChild);
1035​
1036 yield* adapter.startSession({
1037 threadId,
1038 provider: ProviderDriverKind.make("cursor"),
1039 cwd: process.cwd(),
1040 runtimeMode: "full-access",
1041 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
1042 });
1043​
1044 const sendTurnFiber = yield* adapter
1045 .sendTurn({
1046 threadId,
1047 input: "ask me a question and then interrupt",
1048 attachments: [],
1049 })
1050 .pipe(Effect.forkChild);
1051​
1052 yield* Deferred.await(userInputRequested);
1053 yield* adapter.interruptTurn(threadId);
1054 yield* Fiber.await(sendTurnFiber);
1055​
1056 assert.equal(yield* adapter.hasSession(threadId), true);
1057 yield* adapter.stopSession(threadId);
1058 }),
1059 );
1060​
1061 it.effect("broadcasts runtime events to multiple stream consumers", () =>
1062 Effect.gen(function* () {
1063 const adapter = yield* CursorAdapter;
1064 const settings = yield* ServerSettingsService;
1065 const threadId = ThreadId.make("cursor-runtime-event-broadcast");
1066​
1067 const wrapperPath = yield* Effect.promise(() => makeMockAgentWrapper());
1068 yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
1069​
1070 const firstConsumer = yield* Stream.take(adapter.streamEvents, 3).pipe(
1071 Stream.runCollect,
1072 Effect.forkChild,
1073 );
1074 const secondConsumer = yield* Stream.take(adapter.streamEvents, 3).pipe(
1075 Stream.runCollect,
1076 Effect.forkChild,
1077 );
1078​
1079 yield* adapter.startSession({
1080 threadId,
1081 provider: ProviderDriverKind.make("cursor"),
1082 cwd: process.cwd(),
1083 runtimeMode: "full-access",
1084 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
1085 });
1086​
1087 const firstEvents = Array.from(yield* Fiber.join(firstConsumer));
1088 const secondEvents = Array.from(yield* Fiber.join(secondConsumer));
1089​
1090 assert.deepStrictEqual(
1091 firstEvents.map((event) => event.type),
1092 ["session.started", "session.state.changed", "thread.started"],
1093 );
1094 assert.deepStrictEqual(
1095 secondEvents.map((event) => event.type),
1096 ["session.started", "session.state.changed", "thread.started"],
1097 );
1098​
1099 yield* adapter.stopSession(threadId);
1100 }),
1101 );
1102​
1103 it.effect("switches model in-session via session/set_config_option", () =>
1104 Effect.gen(function* () {
1105 const adapter = yield* CursorAdapter;
1106 const serverSettings = yield* ServerSettingsService;
1107 const threadId = ThreadId.make("cursor-model-switch");
1108 const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
1109 const requestLogPath = path.join(tempDir, "requests.ndjson");
1110 const argvLogPath = path.join(tempDir, "argv.txt");
1111 yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
1112 const wrapperPath = yield* Effect.promise(() =>
1113 makeProbeWrapper(requestLogPath, argvLogPath),
1114 );
1115 yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
1116​
1117 yield* adapter.startSession({
1118 threadId,
1119 provider: ProviderDriverKind.make("cursor"),
1120 cwd: process.cwd(),
1121 runtimeMode: "full-access",
1122 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
1123 });
1124​
1125 yield* adapter.sendTurn({
1126 threadId,
1127 input: "first turn",
1128 attachments: [],
1129 });
1130​
1131 yield* adapter.sendTurn({
1132 threadId,
1133 input: "second turn after switching model",
1134 attachments: [],
1135 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
1136 { id: "fastMode", value: true },
1137 ]),
1138 });
1139​
1140 const argvRuns = yield* Effect.promise(() => readArgvLog(argvLogPath));
1141 assert.lengthOf(argvRuns, 1, "session should not restart — only one spawn");
1142 assert.deepStrictEqual(argvRuns[0], ["acp"]);
1143​
1144 const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
1145 const setConfigRequests = requests.filter(
1146 (entry) =>
1147 entry.method === "session/set_config_option" &&
1148 (entry.params as Record<string, unknown> | undefined)?.configId === "model",
1149 );
1150 assert.isAbove(setConfigRequests.length, 0, "should call session/set_config_option");
1151 assert.equal((setConfigRequests[0]?.params as Record<string, unknown>)?.value, "composer-2");
1152​
1153 const fastConfigRequests = requests.filter(
1154 (entry) =>
1155 entry.method === "session/set_config_option" &&
1156 (entry.params as Record<string, unknown> | undefined)?.configId === "fast",
1157 );
1158 assert.isAbove(fastConfigRequests.length, 0, "should apply fast mode as a separate config");
1159 const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1];
1160 assert.equal((lastFastConfig?.params as Record<string, unknown>)?.value, "true");
1161​
1162 yield* adapter.stopSession(threadId);
1163 }),
1164 );
1165​
1166 it.effect("clears prior fast mode in-session when the next turn sets fastMode: false", () =>
1167 Effect.gen(function* () {
1168 const adapter = yield* CursorAdapter;
1169 const serverSettings = yield* ServerSettingsService;
1170 const threadId = ThreadId.make("cursor-fast-mode-reset");
1171 const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
1172 const requestLogPath = path.join(tempDir, "requests.ndjson");
1173 const argvLogPath = path.join(tempDir, "argv.txt");
1174 yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
1175 const wrapperPath = yield* Effect.promise(() =>
1176 makeProbeWrapper(requestLogPath, argvLogPath),
1177 );
1178 yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
1179​
1180 yield* adapter.startSession({
1181 threadId,
1182 provider: ProviderDriverKind.make("cursor"),
1183 cwd: process.cwd(),
1184 runtimeMode: "full-access",
1185 modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "composer-2" },
1186 });
1187​
1188 yield* adapter.sendTurn({
1189 threadId,
1190 input: "first turn with fast mode",
1191 attachments: [],
1192 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
1193 { id: "fastMode", value: true },
1194 ]),
1195 });
1196​
1197 yield* adapter.sendTurn({
1198 threadId,
1199 input: "second turn without fast mode",
1200 attachments: [],
1201 modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
1202 { id: "fastMode", value: false },
1203 ]),
1204 });
1205​
1206 const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
1207 const fastConfigRequests = requests.filter(
1208 (entry) =>
1209 entry.method === "session/set_config_option" &&
1210 (entry.params as Record<string, unknown> | undefined)?.configId === "fast",
1211 );
1212 assert.isAtLeast(fastConfigRequests.length, 2, "should set fast mode on and then off");
1213​
1214 const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1];
1215 assert.equal((lastFastConfig?.params as Record<string, unknown>)?.value, "false");
1216​
1217 yield* adapter.stopSession(threadId);
1218 }),
1219 );
1220​
1221 it.effect(
1222 "applies fast mode on the first turn when modelSelection uses a non-default instance id",
1223 () => {
1224 const customInstanceId = ProviderInstanceId.make("cursor_secondary");
1225 // Custom-instance cases can't share the suite-level `CursorAdapter`
1226 // layer because that one binds `instanceId: "cursor"`. We build a
1227 // fresh layer graph — including a fresh `ServerSettingsService` — so
1228 // mid-test `updateSettings` calls target the same service instance the
1229 // adapter's `resolveSettings` reads from, and so the outer
1230 // `yield* ServerSettingsService` sees the same snapshot as well.
1231 const customAdapterLayer = Layer.effect(
1232 CursorAdapter,
1233 Effect.gen(function* () {
1234 const cursorConfig = Schema.decodeSync(CursorSettings)({});
1235 const resolveSettings = yield* makeResolveCursorSettings;
1236 return yield* makeCursorAdapter(cursorConfig, {
1237 instanceId: customInstanceId,
1238 resolveSettings,
1239 });
1240 }),
1241 ).pipe(
1242 Layer.provideMerge(ServerSettingsService.layerTest()),
1243 Layer.provideMerge(
1244 ServerConfig.layerTest(process.cwd(), {
1245 prefix: "t3code-cursor-adapter-custom-instance-",
1246 }),
1247 ),
1248 Layer.provideMerge(NodeServices.layer),
1249 );
1250​
1251 return Effect.gen(function* () {
1252 const adapter = yield* CursorAdapter;
1253 const serverSettings = yield* ServerSettingsService;
1254 const threadId = ThreadId.make("cursor-fast-mode-custom-instance");
1255 const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
1256 const requestLogPath = path.join(tempDir, "requests.ndjson");
1257 const argvLogPath = path.join(tempDir, "argv.txt");
1258 yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
1259 const wrapperPath = yield* Effect.promise(() =>
1260 makeProbeWrapper(requestLogPath, argvLogPath),
1261 );
1262 yield* serverSettings.updateSettings({
1263 providers: { cursor: { binaryPath: wrapperPath } },
1264 });
1265​
1266 yield* adapter.startSession({
1267 threadId,
1268 provider: ProviderDriverKind.make("cursor"),
1269 cwd: process.cwd(),
1270 runtimeMode: "full-access",
1271 modelSelection: {
1272 instanceId: customInstanceId,
1273 model: "composer-2",
1274 },
1275 });
1276​
1277 yield* adapter.sendTurn({
1278 threadId,
1279 input: "first turn with fast mode",
1280 attachments: [],
1281 modelSelection: {
1282 ...createModelSelection(ProviderInstanceId.make("cursor"), "composer-2", [
1283 { id: "fastMode", value: true },
1284 ]),
1285 instanceId: customInstanceId,
1286 },
1287 });
1288​
1289 const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
1290 const fastConfigRequests = requests.filter(
1291 (entry) =>
1292 entry.method === "session/set_config_option" &&
1293 (entry.params as Record<string, unknown> | undefined)?.configId === "fast",
1294 );
1295 assert.isAbove(
1296 fastConfigRequests.length,
1297 0,
1298 "fast mode should apply when instance id matches the adapter binding",
1299 );
1300 const lastFastConfig = fastConfigRequests[fastConfigRequests.length - 1];
1301 assert.equal((lastFastConfig?.params as Record<string, unknown>)?.value, "true");
1302​
1303 yield* adapter.stopSession(threadId);
1304 }).pipe(Effect.provide(customAdapterLayer));
1305 },
1306 );
1307});