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

CursorAdapter.test.ts

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