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