The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 14:15 UTC
fix(provider-cursor): Cursor text generation no longer leaks SQLite file handles on every call (#19310)
Takeover of #18154. Per-call SqliteLocalAgentStore so Cursor text generation closes its SQLite handles, and the agent now closes before its store on sign-out. Fixes #18151. Co-authored-by: Aaron Queen <bompus@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 14, 2026 at 01:14 UTC
acb90279e2adad19a63586944543fe7346499467
6 files changed
+119
-5
packages/provider-cursor/src/server/CursorAgentSdk.test.ts
+1
@@ -104,6 +104,7 @@ vi.mock("./sdk.ts", () => ({
104
},
105
},
106
createAgentPlatform: vi.fn(),
107
+ SqliteLocalAgentStore: { open: vi.fn() },
108
}));
109
110
const layerTest = CursorAgentSdk.layer.pipe(
packages/provider-cursor/src/server/CursorSdk.test.ts
+1
-1
@@ -25,7 +25,7 @@ writeFileSync(
25
);
26
registerHooks({
27
resolve(specifier, context, next) {
28
- if (specifier === "@cursor/sdk") {
28
+ if (specifier === "@cursor/sdk" || specifier === "@cursor/sdk/sqlite") {
29
return { url: pathToFileURL(stub).href, shortCircuit: true };
30
}
31
return next(specifier, context);
packages/provider-cursor/src/server/CursorSdk.ts
+3
-2
@@ -3,7 +3,7 @@ import * as Context from "effect/Context";
3
import * as Effect from "effect/Effect";
4
import * as Layer from "effect/Layer";
5
6
-import { Agent, createAgentPlatform } from "./sdk.ts";
6
+import { Agent, createAgentPlatform, SqliteLocalAgentStore } from "./sdk.ts";
7
8
/**
9
* The Cursor Agent SDK runs in this process and spawns a shell for tool
@@ -65,6 +65,7 @@ export class CursorSdk extends Context.Service<
65
{
66
readonly Agent: typeof Agent;
67
readonly createAgentPlatform: typeof createAgentPlatform;
68
+ readonly SqliteLocalAgentStore: typeof SqliteLocalAgentStore;
69
}
70
>()("@t3tools/provider-cursor/server/CursorSdk") {}
71
@@ -79,5 +80,5 @@ export const layer = Layer.effect(
80
Effect.sync(() => {
81
process.off("unhandledRejection", onUnhandledRejection);
82
}),
82
- ).pipe(Effect.as(CursorSdk.of({ Agent, createAgentPlatform }))),
83
+ ).pipe(Effect.as(CursorSdk.of({ Agent, createAgentPlatform, SqliteLocalAgentStore }))),
84
);
packages/provider-cursor/src/server/sdk.ts
+3
@@ -12,3 +12,6 @@ export const {
12
CursorSdkError,
13
InMemoryCredentialStore,
14
} = requireCursorSdk("@cursor/sdk") as typeof import("@cursor/sdk");
15
+export const { SqliteLocalAgentStore } = requireCursorSdk(
16
+ "@cursor/sdk/sqlite",
17
+) as typeof import("@cursor/sdk/sqlite");
packages/provider-cursor/src/server/textGeneration.test.ts
+99
-1
@@ -1,8 +1,10 @@
1
-import type { RunResult } from "@cursor/sdk";
1
+import type { RunResult, SdkCredentialStore, StoredSdkCredentials } from "@cursor/sdk";
2
import { ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
3
import { CursorSettings } from "../settings.ts";
4
import { describe, expect, it } from "@effect/vitest";
5
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
6
import * as Effect from "effect/Effect";
7
+import * as Exit from "effect/Exit";
8
import * as FileSystem from "effect/FileSystem";
9
import * as Fiber from "effect/Fiber";
10
import * as Layer from "effect/Layer";
@@ -11,6 +13,7 @@ import * as Schema from "effect/Schema";
13
import { createModelSelection } from "@t3tools/shared/model";
14
import { beforeEach, vi } from "vite-plus/test";
15
16
+import { makeCursorAuth } from "./auth.ts";
17
import { makeCursorTextGeneration } from "./textGeneration.ts";
18
import * as CursorSdk from "./CursorSdk.ts";
19
@@ -19,6 +22,8 @@ const cursorSdkMock = vi.hoisted(() => ({
22
send: vi.fn<(prompt: string) => Promise<unknown>>(),
23
close: vi.fn(),
24
cancel: vi.fn(async () => {}),
25
+ storeOpen: vi.fn<(options: unknown) => Promise<unknown>>(),
26
+ storeDispose: vi.fn(async () => {}),
27
prompt: vi.fn<(prompt: string, options: unknown) => Promise<RunResult>>(async () => ({
28
id: "run-cursor-text-generation-test",
29
status: "finished",
@@ -30,6 +35,7 @@ const cursorSdkMock = vi.hoisted(() => ({
35
vi.mock("./sdk.ts", () => ({
36
Agent: { create: cursorSdkMock.create },
37
createAgentPlatform: vi.fn(),
38
+ SqliteLocalAgentStore: { open: cursorSdkMock.storeOpen },
39
}));
40
41
let hasCustomPolicy = false;
@@ -62,6 +68,9 @@ beforeEach(() => {
68
});
69
cursorSdkMock.close.mockClear();
70
cursorSdkMock.cancel.mockClear();
71
+ cursorSdkMock.storeDispose.mockClear();
72
+ cursorSdkMock.storeOpen.mockReset();
73
+ cursorSdkMock.storeOpen.mockResolvedValue({ dispose: cursorSdkMock.storeDispose });
74
cursorSdkMock.prompt.mockReset();
75
cursorSdkMock.prompt.mockResolvedValue({
76
id: "run-cursor-text-generation-test",
@@ -139,6 +148,7 @@ describe("CursorTextGeneration", () => {
148
},
149
local: {
150
cwd: "/isolated-text-generation",
151
+ store: { dispose: cursorSdkMock.storeDispose },
152
autoReview: false,
153
sandboxOptions: { enabled: true },
154
settingSources: [],
@@ -148,6 +158,93 @@ describe("CursorTextGeneration", () => {
158
}).pipe(Effect.provide(layerTest)),
159
);
160
161
+ it.effect("disposes the agent store after the agent, whether the run succeeds or fails", () =>
162
+ Effect.gen(function* () {
163
+ const textGeneration = yield* makeCursorTextGeneration(cursorSettings, {
164
+ CURSOR_API_KEY: "test-cursor-key",
165
+ });
166
+ const input = {
167
+ cwd: process.cwd(),
168
+ branch: "feature/cursor-store",
169
+ stagedSummary: "M README.md",
170
+ stagedPatch: "diff --git a/README.md b/README.md",
171
+ modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2"),
172
+ };
173
+
174
+ yield* textGeneration.generateCommitMessage(input);
175
+ expect(cursorSdkMock.storeOpen).toHaveBeenCalledWith(
176
+ expect.objectContaining({ workspaceRef: "/isolated-text-generation" }),
177
+ );
178
+ expect(cursorSdkMock.storeDispose).toHaveBeenCalledTimes(1);
179
+ expect(cursorSdkMock.close.mock.invocationCallOrder[0]).toBeLessThan(
180
+ cursorSdkMock.storeDispose.mock.invocationCallOrder[0]!,
181
+ );
182
+
183
+ cursorSdkMock.prompt.mockResolvedValueOnce({
184
+ id: "run-cursor-text-generation-test",
185
+ status: "error",
186
+ });
187
+ yield* Effect.flip(textGeneration.generateCommitMessage(input));
188
+ expect(cursorSdkMock.storeDispose).toHaveBeenCalledTimes(2);
189
+ }).pipe(Effect.provide(layerTest)),
190
+ );
191
+
192
+ it.effect("closes the agent before its store when sign-out interrupts a run", () =>
193
+ Effect.gen(function* () {
194
+ let credentials: StoredSdkCredentials | undefined = {
195
+ version: 1,
196
+ backendUrl: "https://api2.cursor.sh",
197
+ apiKey: "browser-key",
198
+ createdAtMs: 0,
199
+ };
200
+ const store: SdkCredentialStore = {
201
+ load: async () => credentials,
202
+ save: async (next) => {
203
+ credentials = next;
204
+ },
205
+ clear: async () => {
206
+ credentials = undefined;
207
+ },
208
+ };
209
+ const auth = yield* makeCursorAuth({
210
+ instanceId: ProviderInstanceId.make("cursor"),
211
+ displayName: "Cursor",
212
+ enabled: true,
213
+ store,
214
+ onChanged: () => Effect.void,
215
+ });
216
+ const started = Promise.withResolvers<void>();
217
+ cursorSdkMock.prompt.mockImplementationOnce(() => {
218
+ started.resolve();
219
+ return new Promise(() => {});
220
+ });
221
+ const generation = yield* makeCursorTextGeneration(
222
+ cursorSettings,
223
+ {},
224
+ auth.requireApiKey,
225
+ auth.withAccess,
226
+ );
227
+ const request = yield* generation
228
+ .generateCommitMessage({
229
+ cwd: process.cwd(),
230
+ branch: "feature/cursor-sign-out",
231
+ stagedSummary: "M README.md",
232
+ stagedPatch: "diff --git a/README.md b/README.md",
233
+ modelSelection: createModelSelection(ProviderInstanceId.make("cursor"), "composer-2"),
234
+ })
235
+ .pipe(Effect.forkScoped);
236
+ yield* Effect.promise(() => started.promise);
237
+
238
+ yield* auth.controller.logout(Effect.void);
239
+
240
+ expect(Exit.isFailure(yield* Fiber.await(request))).toBe(true);
241
+ expect(cursorSdkMock.storeDispose).toHaveBeenCalledTimes(1);
242
+ expect(cursorSdkMock.close.mock.invocationCallOrder[0]).toBeLessThan(
243
+ cursorSdkMock.storeDispose.mock.invocationCallOrder[0]!,
244
+ );
245
+ }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerTest, NodeCrypto.layer))),
246
+ );
247
+
248
it.effect("continues in the temp directory when the SDK cannot sandbox", () =>
249
Effect.gen(function* () {
250
cursorSdkMock.create.mockImplementationOnce(async () => {
@@ -175,6 +272,7 @@ describe("CursorTextGeneration", () => {
272
expect(cursorSdkMock.create.mock.calls[1]?.[0]).toMatchObject({
273
local: {
274
cwd: "/isolated-text-generation",
275
+ store: { dispose: cursorSdkMock.storeDispose },
276
autoReview: false,
277
sandboxOptions: { enabled: false },
278
settingSources: [],
packages/provider-cursor/src/server/textGeneration.ts
+12
-1
@@ -58,7 +58,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
58
withAccess?: CursorAuth["withAccess"],
59
) {
60
const fs = yield* FileSystem.FileSystem;
61
- const { Agent } = yield* CursorSdk.CursorSdk;
61
+ const { Agent, SqliteLocalAgentStore } = yield* CursorSdk.CursorSdk;
62
const resolvedEnvironment = environment ?? process.env;
63
64
const resolveCursorApiKey = (operation: TextGenerationOperations.Operation) =>
@@ -98,12 +98,21 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
98
});
99
}
100
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-" });
101
+ // The SDK keeps SQLite handles open after `agent.close()` and only releases
102
+ // them from a store the caller disposes. Its state lives outside `cwd` so the
103
+ // agent's workspace stays empty.
104
+ const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" });
105
+ const store = yield* Effect.acquireRelease(
106
+ Effect.tryPromise(() => SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot })),
107
+ (store) => Effect.tryPromise(() => store.dispose()).pipe(Effect.ignore({ log: true })),
108
+ );
109
const agentOptions = {
110
apiKey,
111
mode: "plan",
112
model: cursorSdkModelSelection(modelSelection),
113
local: {
114
cwd,
115
+ store,
116
autoReview: false,
117
sandboxOptions: { enabled: true },
118
settingSources: [],
@@ -184,6 +193,8 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
193
194
return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
195
}).pipe(
196
+ // Scope this call inside `withAccess`, so sign-out closes the agent before its store.
197
+ Effect.scoped,
198
(effect) => (withAccess ? withAccess(effect) : effect),
199
Effect.scoped,
200
Effect.mapError((cause) =>