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

CursorSdk.test.ts

182 lines6.4 KB

1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off -- The probe is a plain Node child; this deadline kills it if it hangs.
2import * as NodeChildProcess from "node:child_process";
3import { describe, expect, it } from "vite-plus/test";
4​
5import { isCursorShellSpawnFailure } from "./CursorSdk.ts";
6​
7const cursorSdkUrl = new URL("./CursorSdk.ts", import.meta.url).href;
8​
9// The vitest worker already has its own unhandledRejection listener, which
10// would hide the process-exit behavior.
11const probeProgram = `
12import { mkdtempSync, writeFileSync } from "node:fs";
13import { tmpdir } from "node:os";
14import { join } from "node:path";
15import { registerHooks } from "node:module";
16import { pathToFileURL } from "node:url";
17import { spawn } from "node:child_process";
18​
19const dir = mkdtempSync(join(tmpdir(), "cursor-sdk-stub-"));
20const stub = join(dir, "stub.cjs");
21writeFileSync(
22 stub,
23 "module.exports = { Agent: {}, AuthenticationError: class {}, createAgentPlatform: () => ({}), Cursor: {}, CursorSdkError: class {}, InMemoryCredentialStore: class {} };",
24);
25registerHooks({
26 resolve(specifier, context, next) {
27 if (specifier === "@cursor/sdk" || specifier === "@cursor/sdk/sqlite") {
28 return { url: pathToFileURL(stub).href, shortCircuit: true };
29 }
30 return next(specifier, context);
31 },
32});
33​
34const { layer } = await import(${JSON.stringify(cursorSdkUrl)});
35const Effect = await import("effect/Effect");
36const Layer = await import("effect/Layer");
37const Exit = await import("effect/Exit");
38const Scope = await import("effect/Scope");
39const scope = Scope.makeUnsafe();
40await Effect.runPromise(Layer.buildWithScope(layer, scope));
41const mode = process.argv[1];
42const missingCwd = join(tmpdir(), "t3-missing-cwd-" + process.pid);
43​
44if (mode === "cursor-shell") {
45 const child = spawn("/bin/zsh", ["-c", "dump_zsh_state >&4", "--", "true"], {
46 cwd: missingCwd,
47 });
48 child.on("error", (error) => {
49 Promise.reject(error);
50 });
51 setTimeout(() => process.exit(0), 500);
52} else if (mode === "released") {
53 await Effect.runPromise(Scope.close(scope, Exit.void));
54 Promise.reject(
55 Object.assign(new Error("spawn /bin/zsh ENOENT"), {
56 code: "ENOENT",
57 syscall: "spawn /bin/zsh",
58 spawnargs: ["-c", "dump_zsh_state >&4"],
59 }),
60 );
61 setTimeout(() => process.exit(0), 500);
62} else if (mode === "other-spawn") {
63 Promise.reject(
64 Object.assign(new Error("spawn git ENOENT"), {
65 code: "ENOENT",
66 syscall: "spawn git",
67 path: "git",
68 spawnargs: ["status"],
69 }),
70 );
71 setTimeout(() => process.exit(0), 500);
72} else if (mode === "other-rejection") {
73 Promise.reject(new Error("boom"));
74 setTimeout(() => process.exit(0), 500);
75} else if (mode === "spawn-without-listener") {
76 spawn(process.execPath, ["-e", "process.exit(0)"], { cwd: missingCwd });
77 setTimeout(() => process.exit(0), 500);
78} else {
79 console.error("Unknown cursor shell spawn guard probe: " + mode);
80 process.exit(2);
82`;
83​
84function runProbe(mode: string): Promise<{ code: number | null; stdout: string; stderr: string }> {
85 return new Promise((resolve, reject) => {
86 const child = NodeChildProcess.spawn(
87 process.execPath,
88 [
89 "--experimental-strip-types",
90 "--disable-warning=ExperimentalWarning",
91 "--input-type=module",
92 "-e",
93 probeProgram,
94 mode,
95 ],
96 { stdio: ["ignore", "pipe", "pipe"] },
97 );
98 let stdout = "";
99 let stderr = "";
100 child.stdout.setEncoding("utf8");
101 child.stderr.setEncoding("utf8");
102 child.stdout.on("data", (chunk: string) => {
103 stdout += chunk;
104 });
105 child.stderr.on("data", (chunk: string) => {
106 stderr += chunk;
107 });
108 const timer = setTimeout(() => {
109 child.kill();
110 reject(new Error(`probe ${mode} timed out`));
111 }, 5_000);
112 child.on("error", reject);
113 child.on("exit", (code) => {
114 clearTimeout(timer);
115 resolve({ code, stdout, stderr });
116 });
117 });
119​
120describe("isCursorShellSpawnFailure", () => {
121 it("matches only Cursor's shell wrapper", () => {
122 const spawnFailure = (syscall: string, spawnargs: ReadonlyArray<string>) =>
123 Object.assign(new Error(`${syscall} ENOENT`), { code: "ENOENT", syscall, spawnargs });
124 expect(
125 isCursorShellSpawnFailure(
126 spawnFailure("spawn /bin/zsh", ["-c", "dump_zsh_state >&4", "--", "true"]),
127 ),
128 ).toBe(true);
129 expect(
130 isCursorShellSpawnFailure(spawnFailure("spawn bash", ["-c", "dump_bash_state >&4"])),
131 ).toBe(true);
132 expect(
133 isCursorShellSpawnFailure(
134 spawnFailure("spawn /bin/zsh", ["-c", 'builtin eval "${__CURSOR_SANDBOX_ENV_RESTORE:-}"']),
135 ),
136 ).toBe(true);
137 expect(isCursorShellSpawnFailure(spawnFailure("spawn git", ["status"]))).toBe(false);
138 expect(isCursorShellSpawnFailure(spawnFailure("spawn /bin/zsh", ["-lc", "true"]))).toBe(false);
139 expect(
140 isCursorShellSpawnFailure(
141 Object.assign(new Error("open failed"), { code: "ENOENT", syscall: "open" }),
142 ),
143 ).toBe(false);
144 expect(isCursorShellSpawnFailure(new Error("boom"))).toBe(false);
145 expect(isCursorShellSpawnFailure("spawn ENOENT")).toBe(false);
146 });
147});
148​
149describe("Cursor shell spawn guard", () => {
150 it("keeps the process alive when Cursor's shell spawn rejects", async () => {
151 const result = await runProbe("cursor-shell");
152 expect(result.code).toBe(0);
153 expect(result.stderr).toContain("The server will keep running.");
154 expect(result.stderr).toContain("ENOENT");
155 });
156​
157 it("still exits when a different spawn failure is unhandled", async () => {
158 const result = await runProbe("other-spawn");
159 expect(result.code).toBe(1);
160 expect(result.stderr).toContain("spawn git ENOENT");
161 expect(result.stderr).not.toContain("The server will keep running.");
162 });
163​
164 it("still exits on unrelated unhandled rejections", async () => {
165 const result = await runProbe("other-rejection");
166 expect(result.code).toBe(1);
167 expect(result.stderr).toContain("boom");
168 });
169​
170 it("removes the guard when the layer is released", async () => {
171 const result = await runProbe("released");
172 expect(result.code).toBe(1);
173 expect(result.stderr).not.toContain("The server will keep running.");
174 });
175​
176 it("leaves a spawn with no error listener fatal", async () => {
177 const result = await runProbe("spawn-without-listener");
178 expect(result.code).toBe(1);
179 expect(result.stderr).toContain("Unhandled");
180 expect(result.stderr).not.toContain("The server will keep running.");
181 });
182});