Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodePath from "node:path";
3import * as NodeOS from "node:os";
4import * as NodeURL from "node:url";
5import * as NodeFS from "node:fs";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { it } from "@effect/vitest";
9import * as Clock from "effect/Clock";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Layer from "effect/Layer";
13import * as Schema from "effect/Schema";
14import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
15import { createModelSelection } from "@t3tools/shared/model";
16import { expect } from "vite-plus/test";
17
18import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts";
19
20import * as ServerConfig from "../config.ts";
21import * as TextGeneration from "./TextGeneration.ts";
22import { makeCursorTextGeneration } from "./CursorTextGeneration.ts";
23import { execScriptSource, writeFakeCli } from "../testUtils/fakeCli.ts";
24const decodeCursorSettings = Schema.decodeSync(CursorSettings);
25
26const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
27const mockAgentPath = NodePath.join(__dirname, "../../scripts/acp-mock-agent.ts");
28
29const CursorTextGenerationTestLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
30 prefix: "t3code-cursor-text-generation-test-",
31}).pipe(Layer.provideMerge(NodeServices.layer));
32
33function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
34 return writeFakeCli({
35 directory: NodePath.join(dir, "bin"),
36 name: "agent",
37 env,
38 source: execScriptSource({
39 scriptPath: mockAgentPath,
40 expectedArgs: ["acp"],
41 }),
42 });
43}
44
45function withFakeAcpAgent<A, E, R>(
46 env: Record<string, string>,
47 effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
48) {
49 return Effect.gen(function* () {
50 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-cursor-text-acp-"));
51 yield* Effect.addFinalizer(() =>
52 Effect.sync(() => {
53 NodeFS.rmSync(tempDir, { recursive: true, force: true });
54 }),
55 );
56 const agentPath = makeAcpAgentWrapper(tempDir, env);
57 const config = decodeCursorSettings({ binaryPath: agentPath });
58 const textGeneration = yield* makeCursorTextGeneration(config);
59 return yield* effectFn(textGeneration);
60 }).pipe(Effect.scoped);
61}
62
63function waitForFileContent(path: string): Effect.Effect<string> {
64 return Effect.gen(function* () {
65 const deadline = (yield* Clock.currentTimeMillis) + 5_000;
66 for (;;) {
67 const result = yield* Effect.exit(Effect.sync(() => NodeFS.readFileSync(path, "utf8")));
68 if (Exit.isSuccess(result)) {
69 return result.value;
70 }
71 {
72 if ((yield* Clock.currentTimeMillis) >= deadline) {
73 return yield* Effect.die(result.cause);
74 }
75 }
76 yield* Effect.sleep(25);
77 }
78 });
79}
80
81it.layer(CursorTextGenerationTestLayer)("CursorTextGeneration", (it) => {
82 it.effect("uses ACP model config options instead of raw CLI model ids", () => {
83 const requestLogDir = NodeFS.mkdtempSync(
84 NodePath.join(NodeOS.tmpdir(), "t3code-cursor-text-log-"),
85 );
86 const requestLogPath = NodePath.join(requestLogDir, "requests.ndjson");
87
88 return withFakeAcpAgent(
89 {
90 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
91 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
92 subject: "Add generated commit message",
93 body: "- verify cursor acp model config path",
94 }),
95 },
96 (textGeneration) =>
97 Effect.gen(function* () {
98 const generated = yield* textGeneration.generateCommitMessage({
99 cwd: process.cwd(),
100 branch: "feature/cursor-text-generation",
101 stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
102 stagedPatch:
103 "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
104 modelSelection: {
105 ...createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
106 { id: "reasoning", value: "xhigh" },
107 { id: "fastMode", value: true },
108 { id: "contextWindow", value: "1m" },
109 ]),
110 },
111 });
112
113 expect(generated.subject).toBe("Add generated commit message");
114 expect(generated.body).toBe("- verify cursor acp model config path");
115
116 const requests = NodeFS.readFileSync(requestLogPath, "utf8")
117 .trim()
118 .split("\n")
119 .filter((line) => line.length > 0)
120 .map(
121 (line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> },
122 );
123
124 expect(
125 requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
126 ).toMatchObject({
127 _meta: {
128 parameterizedModelPicker: true,
129 },
130 });
131 expect(
132 requests.some(
133 (request) =>
134 request.method === "session/set_config_option" &&
135 request.params?.configId === "model" &&
136 request.params?.value === "gpt-5.4",
137 ),
138 ).toBe(true);
139 expect(
140 requests.some(
141 (request) =>
142 request.method === "session/set_config_option" &&
143 request.params?.configId === "reasoning" &&
144 request.params?.value === "extra-high",
145 ),
146 ).toBe(true);
147 expect(
148 requests.some(
149 (request) =>
150 request.method === "session/set_config_option" &&
151 request.params?.configId === "context" &&
152 request.params?.value === "1m",
153 ),
154 ).toBe(true);
155 expect(
156 requests.some(
157 (request) =>
158 request.method === "session/set_config_option" &&
159 request.params?.configId === "fast" &&
160 request.params?.value === "true",
161 ),
162 ).toBe(true);
163 expect(
164 requests.find((request) => request.method === "session/prompt")?.params?.prompt,
165 ).toEqual(
166 expect.arrayContaining([
167 expect.objectContaining({
168 type: "text",
169 text: expect.stringContaining("Staged patch:"),
170 }),
171 ]),
172 );
173
174 NodeFS.rmSync(requestLogDir, { recursive: true, force: true });
175 }),
176 );
177 });
178
179 it.effect("accepts json objects with extra assistant text around them", () =>
180 withFakeAcpAgent(
181 {
182 T3_ACP_PROMPT_RESPONSE_TEXT:
183 'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
184 },
185 (textGeneration) =>
186 Effect.gen(function* () {
187 const generated = yield* textGeneration.generateCommitMessage({
188 cwd: process.cwd(),
189 branch: "feature/cursor-noisy-json",
190 stagedSummary: "M README.md",
191 stagedPatch: "diff --git a/README.md b/README.md",
192 modelSelection: {
193 instanceId: ProviderInstanceId.make("cursor"),
194 model: "composer-2",
195 },
196 });
197
198 expect(generated.subject).toBe("Update README dummy comment with attribution and date");
199 expect(generated.body).toBe("");
200 }),
201 ),
202 );
203
204 it.effect("generates thread titles through Cursor ACP text generation", () =>
205 withFakeAcpAgent(
206 {
207 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
208 title: '"Trim reconnect spinner status after resume."',
209 }),
210 },
211 (textGeneration) =>
212 Effect.gen(function* () {
213 const generated = yield* textGeneration.generateThreadTitle({
214 cwd: process.cwd(),
215 message: "Fix the reconnect spinner after a resumed session.",
216 modelSelection: {
217 instanceId: ProviderInstanceId.make("cursor"),
218 model: "composer-2",
219 },
220 });
221
222 expect(generated.title).toBe("Trim reconnect spinner status after resume.");
223 }),
224 ),
225 );
226
227 // Closing the runtime on Windows is taskkill /F, which never lets the mock
228 // agent reach its exit handler, so there is no exit log to assert on.
229 it.effect.skipIf(HostProcessPlatform.defaultValue() === "win32")(
230 "closes the ACP child process after text generation completes",
231 () => {
232 const exitLogDir = NodeFS.mkdtempSync(
233 NodePath.join(NodeOS.tmpdir(), "t3code-cursor-text-exit-log-"),
234 );
235 const exitLogPath = NodePath.join(exitLogDir, "exit.log");
236
237 return withFakeAcpAgent(
238 {
239 T3_ACP_EXIT_LOG_PATH: exitLogPath,
240 T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
241 subject: "Close runtime after generation",
242 body: "",
243 }),
244 },
245 (textGeneration) =>
246 Effect.gen(function* () {
247 const generated = yield* textGeneration.generateCommitMessage({
248 cwd: process.cwd(),
249 branch: "feature/cursor-runtime-close",
250 stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
251 stagedPatch:
252 "diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
253 modelSelection: {
254 instanceId: ProviderInstanceId.make("cursor"),
255 model: "composer-2",
256 },
257 });
258
259 expect(generated.subject).toBe("Close runtime after generation");
260
261 const exitLog = yield* waitForFileContent(exitLogPath);
262 expect(exitLog).toContain("exit:0");
263
264 NodeFS.rmSync(exitLogDir, { recursive: true, force: true });
265 }),
266 );
267 },
268 );
269});