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 21, 04:45 UTC
| 1 | import type { ListRunsOptions } from "@cursor/sdk"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { assert, describe, it } from "@effect/vitest"; |
| 4 | import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; |
| 5 | import * as Deferred from "effect/Deferred"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as FileSystem from "effect/FileSystem"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Exit from "effect/Exit"; |
| 10 | import * as Cause from "effect/Cause"; |
| 11 | import { vi } from "vite-plus/test"; |
| 12 | |
| 13 | import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; |
| 14 | import * as CursorAgentSdk from "./CursorAgentSdk.ts"; |
| 15 | import * as CursorSdk from "./CursorSdk.ts"; |
| 16 | |
| 17 | const cursorSdkMock = vi.hoisted(() => { |
| 18 | const closeExecutionOrder: Array<string> = []; |
| 19 | const runOperations: Array<string> = []; |
| 20 | let agentCloseFailure: unknown; |
| 21 | // The local store lists runs oldest first, like the real SDK. |
| 22 | let storedRuns: Array<{ readonly id: string; readonly status: string }> = []; |
| 23 | const runWait = vi.fn(async () => ({ |
| 24 | id: "run-cursor-agent-sdk-test", |
| 25 | requestId: "request-cursor-agent-sdk-test", |
| 26 | status: "finished", |
| 27 | result: "ok", |
| 28 | model: { id: "default" }, |
| 29 | durationMs: 1, |
| 30 | })); |
| 31 | const runCancel = vi.fn(async () => {}); |
| 32 | const runSteer = vi.fn(async () => "complete_delivered" as const); |
| 33 | const agentClose = vi.fn(() => { |
| 34 | closeExecutionOrder.push("sdk:agent.close"); |
| 35 | if (agentCloseFailure !== undefined) { |
| 36 | throw agentCloseFailure; |
| 37 | } |
| 38 | }); |
| 39 | const send = vi.fn( |
| 40 | async ( |
| 41 | _message: unknown, |
| 42 | options: { readonly onDelta?: (input: { readonly update: unknown }) => Promise<void> }, |
| 43 | ) => { |
| 44 | runOperations.push("run.start"); |
| 45 | if (storedRuns.some((run) => run.status === "running")) { |
| 46 | throw new Error("Agent agent-cursor-agent-sdk-test already has active run"); |
| 47 | } |
| 48 | await options.onDelta?.({ |
| 49 | update: { |
| 50 | type: "assistant-message-chunk", |
| 51 | text: "hello", |
| 52 | }, |
| 53 | }); |
| 54 | return { |
| 55 | id: "run-cursor-agent-sdk-test", |
| 56 | agentId: "agent-cursor-agent-sdk-test", |
| 57 | wait: runWait, |
| 58 | cancel: runCancel, |
| 59 | steer: runSteer as typeof runSteer | undefined, |
| 60 | }; |
| 61 | }, |
| 62 | ); |
| 63 | const create = vi.fn(async (_options?: unknown) => ({ |
| 64 | agentId: "agent-cursor-agent-sdk-test", |
| 65 | send, |
| 66 | close: agentClose, |
| 67 | })); |
| 68 | const resume = vi.fn(async () => ({ |
| 69 | agentId: "agent-cursor-agent-sdk-test", |
| 70 | send, |
| 71 | close: agentClose, |
| 72 | })); |
| 73 | const listRuns = vi.fn(async (_agentId: string, options?: ListRunsOptions) => { |
| 74 | runOperations.push("agent.listRuns"); |
| 75 | // Mirrors the SDK's opaque cursor pagination with its default page size of 50. |
| 76 | const offset = options?.cursor === undefined ? 0 : Number(options.cursor); |
| 77 | const end = offset + (options?.limit ?? 50); |
| 78 | return { |
| 79 | items: storedRuns.slice(offset, end), |
| 80 | ...(end < storedRuns.length ? { nextCursor: String(end) } : {}), |
| 81 | }; |
| 82 | }); |
| 83 | const cancelRun = vi.fn(async (runId: string) => { |
| 84 | runOperations.push("agent.cancelRun"); |
| 85 | storedRuns = storedRuns.map((run) => |
| 86 | run.id === runId ? { ...run, status: "cancelled" } : run, |
| 87 | ); |
| 88 | }); |
| 89 | |
| 90 | const sqliteOpen = vi.fn<() => Promise<unknown>>(async () => undefined); |
| 91 | |
| 92 | return { |
| 93 | agentClose, |
| 94 | cancelRun, |
| 95 | closeExecutionOrder, |
| 96 | create, |
| 97 | listRuns, |
| 98 | resume, |
| 99 | runOperations, |
| 100 | runCancel, |
| 101 | runSteer, |
| 102 | runWait, |
| 103 | send, |
| 104 | sqliteOpen, |
| 105 | setAgentCloseFailure: (failure: unknown) => { |
| 106 | agentCloseFailure = failure; |
| 107 | }, |
| 108 | setStoredRuns: (runs: Array<{ readonly id: string; readonly status: string }>) => { |
| 109 | storedRuns = runs; |
| 110 | }, |
| 111 | }; |
| 112 | }); |
| 113 | |
| 114 | vi.mock("./sdk.ts", () => ({ |
| 115 | loadCursorSdk: () => ({ |
| 116 | Agent: { |
| 117 | create: cursorSdkMock.create, |
| 118 | resume: cursorSdkMock.resume, |
| 119 | listRuns: cursorSdkMock.listRuns, |
| 120 | cancelRun: cursorSdkMock.cancelRun, |
| 121 | messages: { |
| 122 | list: vi.fn(async () => []), |
| 123 | }, |
| 124 | }, |
| 125 | createAgentPlatform: vi.fn(), |
| 126 | }), |
| 127 | loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: cursorSdkMock.sqliteOpen } }), |
| 128 | })); |
| 129 | |
| 130 | const layerTest = CursorAgentSdk.layer.pipe( |
| 131 | Layer.provide( |
| 132 | Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, { |
| 133 | native: { |
| 134 | filePath: "cursor-agent-sdk-test.log", |
| 135 | write: (event: unknown) => |
| 136 | Effect.sync(() => { |
| 137 | if ( |
| 138 | typeof event === "object" && |
| 139 | event !== null && |
| 140 | Reflect.get(Reflect.get(event, "event"), "payload")?.type === "agent.close" |
| 141 | ) { |
| 142 | cursorSdkMock.closeExecutionOrder.push("protocol:agent.close"); |
| 143 | } |
| 144 | }), |
| 145 | close: () => Effect.void, |
| 146 | }, |
| 147 | canonical: undefined, |
| 148 | }), |
| 149 | ), |
| 150 | Layer.provide(CursorSdk.layer), |
| 151 | Layer.provide(NodeServices.layer), |
| 152 | ); |
| 153 | |
| 154 | describe("CursorAgentSdkRunner", () => { |
| 155 | it.effect("resumes from the original store after the working directory changes", () => |
| 156 | Effect.gen(function* () { |
| 157 | const fileSystem = yield* FileSystem.FileSystem; |
| 158 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-resume-" }); |
| 159 | const loaders = yield* Effect.promise(() => |
| 160 | vi.importActual<typeof import("./sdk.ts")>("./sdk.ts"), |
| 161 | ); |
| 162 | const sdk = loaders.loadCursorSdk(); |
| 163 | const store = new sdk.JsonlLocalAgentStore(workspace); |
| 164 | const storeCwd = `${workspace}/checkout`; |
| 165 | const cwd = `${workspace}/worktree`; |
| 166 | const platform = yield* Effect.promise(() => |
| 167 | sdk.createAgentPlatform({ localStore: store, workspaceRef: storeCwd }), |
| 168 | ); |
| 169 | const { agent, run } = yield* Effect.promise(() => |
| 170 | platform.store.createAgent({ agentId: "agent-moved", workspaceRef: storeCwd }), |
| 171 | ); |
| 172 | const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe( |
| 173 | Effect.provideService(CursorSdk.CursorSdk, { |
| 174 | load: loaders.loadCursorSdk, |
| 175 | loadSqlite: loaders.loadCursorSqlite, |
| 176 | }), |
| 177 | ); |
| 178 | const session = yield* runner.open({ |
| 179 | operation: "resume", |
| 180 | agentId: agent.agentId, |
| 181 | storeCwd, |
| 182 | options: { apiKey: "synthetic-cursor-key", local: { cwd, store } }, |
| 183 | threadId: ThreadId.make("moved-workspace"), |
| 184 | providerSessionId: ProviderSessionId.make("moved-workspace"), |
| 185 | }); |
| 186 | assert.equal(session.agentId, agent.agentId); |
| 187 | assert.deepStrictEqual(yield* session.listMessages, []); |
| 188 | assert.strictEqual(yield* session.readContextUsage!, undefined); |
| 189 | |
| 190 | // Cursor's conversation holds a run's request only once that run saved its own checkpoint. |
| 191 | assert.isFalse(yield* session.runCheckpointed!()); |
| 192 | yield* Effect.promise(() => |
| 193 | platform.store.patchCheckpoint(agent.agentId, run.runId, { |
| 194 | blobId: "checkpoint-1", |
| 195 | storeKind: "local", |
| 196 | }), |
| 197 | ); |
| 198 | assert.isTrue(yield* session.runCheckpointed!()); |
| 199 | yield* Effect.promise(() => |
| 200 | platform.store.markRunTerminal(agent.agentId, run.runId, { status: "CANCELLED" }), |
| 201 | ); |
| 202 | const followUp = yield* Effect.promise(() => |
| 203 | platform.store.createFollowUpRun(agent.agentId, {}), |
| 204 | ); |
| 205 | assert.isFalse(yield* session.runCheckpointed!(), "the follow-up has no checkpoint yet"); |
| 206 | assert.isTrue(yield* session.runCheckpointed!(run.runId)); |
| 207 | assert.isFalse(yield* session.runCheckpointed!(followUp.runId)); |
| 208 | yield* session.close; |
| 209 | }).pipe(Effect.provide(NodeServices.layer)), |
| 210 | ); |
| 211 | |
| 212 | it.effect("rewinds the agent to the state its first unwound run started from", () => |
| 213 | Effect.gen(function* () { |
| 214 | const fileSystem = yield* FileSystem.FileSystem; |
| 215 | const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-rewind-" }); |
| 216 | const loaders = yield* Effect.promise(() => |
| 217 | vi.importActual<typeof import("./sdk.ts")>("./sdk.ts"), |
| 218 | ); |
| 219 | const sdk = loaders.loadCursorSdk(); |
| 220 | const store = new sdk.JsonlLocalAgentStore(workspace); |
| 221 | const platform = yield* Effect.promise(() => |
| 222 | sdk.createAgentPlatform({ localStore: store, workspaceRef: workspace }), |
| 223 | ); |
| 224 | const { agent, run: first } = yield* Effect.promise(() => |
| 225 | platform.store.createAgent({ agentId: "agent-rewind", workspaceRef: workspace }), |
| 226 | ); |
| 227 | const finishRun = (runId: string, state: string) => |
| 228 | Effect.promise(async () => { |
| 229 | const checkpoint = await platform.checkpointStore.saveCheckpoint(agent.agentId, { |
| 230 | toBinary: () => new TextEncoder().encode(state), |
| 231 | }); |
| 232 | await platform.store.patchCheckpoint(agent.agentId, runId, checkpoint); |
| 233 | await platform.store.markRunTerminal(agent.agentId, runId, { status: "FINISHED" }); |
| 234 | return checkpoint.blobId; |
| 235 | }); |
| 236 | const followUp = Effect.promise(() => platform.store.createFollowUpRun(agent.agentId, {})); |
| 237 | const head = Effect.promise( |
| 238 | async () => (await platform.store.getAgent(agent.agentId))?.latestCheckpointRef?.blobId, |
| 239 | ); |
| 240 | |
| 241 | const afterFirst = yield* finishRun(first.runId, "after first"); |
| 242 | const second = yield* followUp; |
| 243 | yield* finishRun(second.runId, "after second"); |
| 244 | const third = yield* followUp; |
| 245 | const afterThird = yield* finishRun(third.runId, "after third"); |
| 246 | |
| 247 | const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe( |
| 248 | Effect.provideService(CursorSdk.CursorSdk, { |
| 249 | load: loaders.loadCursorSdk, |
| 250 | loadSqlite: loaders.loadCursorSqlite, |
| 251 | }), |
| 252 | ); |
| 253 | const session = yield* runner.open({ |
| 254 | operation: "resume", |
| 255 | agentId: agent.agentId, |
| 256 | storeCwd: workspace, |
| 257 | options: { apiKey: "synthetic-cursor-key", local: { cwd: workspace, store } }, |
| 258 | threadId: ThreadId.make("rewind"), |
| 259 | providerSessionId: ProviderSessionId.make("rewind"), |
| 260 | }); |
| 261 | |
| 262 | yield* session.rewindAfterRun!(third.runId); |
| 263 | assert.strictEqual(yield* head, afterThird, "nothing ran after the kept run"); |
| 264 | yield* session.rewindAfterRun!(first.runId); |
| 265 | assert.strictEqual(yield* head, afterFirst); |
| 266 | yield* session.close; |
| 267 | }).pipe(Effect.provide(NodeServices.layer)), |
| 268 | ); |
| 269 | |
| 270 | it.effect("constructs without loading and reports first-use load failures as runner errors", () => |
| 271 | Effect.gen(function* () { |
| 272 | const failure = new Error("missing SDK chunk"); |
| 273 | const load = vi.fn(() => { |
| 274 | throw failure; |
| 275 | }); |
| 276 | const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe( |
| 277 | Effect.provideService(CursorSdk.CursorSdk, { |
| 278 | load, |
| 279 | loadSqlite: () => { |
| 280 | throw new Error("unused SQLite"); |
| 281 | }, |
| 282 | }), |
| 283 | ); |
| 284 | assert.strictEqual(load.mock.calls.length, 0); |
| 285 | const result = yield* runner |
| 286 | .open({ |
| 287 | operation: "create", |
| 288 | options: {}, |
| 289 | threadId: ThreadId.make("lazy-load"), |
| 290 | providerSessionId: ProviderSessionId.make("lazy-load"), |
| 291 | }) |
| 292 | .pipe(Effect.exit); |
| 293 | assert(Exit.isFailure(result)); |
| 294 | assert.deepStrictEqual( |
| 295 | Cause.squash(result.cause), |
| 296 | new CursorAgentSdk.CursorAgentSdkRunnerError({ |
| 297 | method: "agent.create", |
| 298 | cause: failure, |
| 299 | }), |
| 300 | ); |
| 301 | assert.strictEqual(load.mock.calls.length, 1); |
| 302 | }), |
| 303 | ); |
| 304 | |
| 305 | it.effect("retries a resumed send after cancelling its abandoned local run", () => |
| 306 | Effect.gen(function* () { |
| 307 | cursorSdkMock.runOperations.length = 0; |
| 308 | cursorSdkMock.listRuns.mockClear(); |
| 309 | cursorSdkMock.cancelRun.mockClear(); |
| 310 | cursorSdkMock.setStoredRuns([ |
| 311 | ...Array.from({ length: 50 }, (_, index) => ({ |
| 312 | id: `run-terminal-${index}`, |
| 313 | status: index === 0 ? "cancelled" : "finished", |
| 314 | })), |
| 315 | { id: "run-stale", status: "running" }, |
| 316 | ]); |
| 317 | |
| 318 | const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; |
| 319 | const session = yield* runner.open({ |
| 320 | operation: "resume", |
| 321 | agentId: "agent-cursor-agent-sdk-test", |
| 322 | options: { model: { id: "default" }, mode: "agent", local: { cwd: process.cwd() } }, |
| 323 | threadId: ThreadId.make("thread-cursor-agent-sdk-stale-run-test"), |
| 324 | providerSessionId: ProviderSessionId.make( |
| 325 | "provider-session-cursor-agent-sdk-stale-run-test", |
| 326 | ), |
| 327 | }); |
| 328 | assert.deepStrictEqual(cursorSdkMock.runOperations, []); |
| 329 | const run = yield* session.send({ message: "continue" }); |
| 330 | yield* run.wait; |
| 331 | |
| 332 | assert.deepStrictEqual(cursorSdkMock.runOperations, [ |
| 333 | "run.start", |
| 334 | "agent.listRuns", |
| 335 | "agent.listRuns", |
| 336 | "agent.cancelRun", |
| 337 | "run.start", |
| 338 | ]); |
| 339 | assert.deepStrictEqual(cursorSdkMock.listRuns.mock.calls[0], [ |
| 340 | "agent-cursor-agent-sdk-test", |
| 341 | { runtime: "local", cwd: process.cwd() }, |
| 342 | ]); |
| 343 | assert.strictEqual(cursorSdkMock.listRuns.mock.calls.length, 2); |
| 344 | assert.deepStrictEqual(cursorSdkMock.listRuns.mock.calls[1], [ |
| 345 | "agent-cursor-agent-sdk-test", |
| 346 | { runtime: "local", cwd: process.cwd(), cursor: "50" }, |
| 347 | ]); |
| 348 | assert.deepStrictEqual(cursorSdkMock.cancelRun.mock.calls[0], [ |
| 349 | "run-stale", |
| 350 | { |
| 351 | runtime: "local", |
| 352 | cwd: process.cwd(), |
| 353 | }, |
| 354 | ]); |
| 355 | }).pipe(Effect.provide(layerTest)), |
| 356 | ); |
| 357 | |
| 358 | it.effect("forwards the agent's own shell stream output as shell-output-delta", () => |
| 359 | Effect.gen(function* () { |
| 360 | const publish = (conversationId: string, data: string) => |
| 361 | (Reflect.get(globalThis, Symbol.for("@cursor/sdk.shellStreamOutput")) as Function)({ |
| 362 | conversationId, |
| 363 | toolCallId: "tool-shell", |
| 364 | event: { case: "stdout", value: { data } }, |
| 365 | }); |
| 366 | cursorSdkMock.runWait.mockImplementationOnce(async () => { |
| 367 | publish("agent-cursor-agent-sdk-test", "tick 1\n"); |
| 368 | publish("agent-someone-else", "not ours\n"); |
| 369 | return { |
| 370 | id: "run-cursor-agent-sdk-test", |
| 371 | requestId: "request-cursor-agent-sdk-test", |
| 372 | status: "finished", |
| 373 | result: "ok", |
| 374 | model: { id: "default" }, |
| 375 | durationMs: 1, |
| 376 | }; |
| 377 | }); |
| 378 | const updates: Array<unknown> = []; |
| 379 | const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; |
| 380 | const session = yield* runner.open({ |
| 381 | operation: "create", |
| 382 | options: {}, |
| 383 | threadId: ThreadId.make("thread-cursor-agent-sdk-shell"), |
| 384 | providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-shell"), |
| 385 | }); |
| 386 | const run = yield* session.send({ |
| 387 | message: "run it", |
| 388 | onDelta: (update) => Effect.sync(() => updates.push(update)), |
| 389 | }); |
| 390 | yield* run.wait; |
| 391 | publish("agent-cursor-agent-sdk-test", "after the run\n"); |
| 392 | |
| 393 | assert.deepStrictEqual( |
| 394 | updates.filter( |
| 395 | (update) => (update as { readonly type: string }).type === "shell-output-delta", |
| 396 | ), |
| 397 | [ |
| 398 | { |
| 399 | type: "shell-output-delta", |
| 400 | event: { case: "stdout", value: { data: "tick 1\n" }, toolCallId: "tool-shell" }, |
| 401 | }, |
| 402 | ], |
| 403 | ); |
| 404 | }).pipe(Effect.provide(layerTest)), |
| 405 | ); |
| 406 | |
| 407 | it.effect("keeps an agent's background shells and reports each start and end in order", () => |
| 408 | Effect.gen(function* () { |
| 409 | const start = (conversationId: string, id: number) => { |
| 410 | let complete: (completion: object) => void = () => {}; |
| 411 | const abort = vi.fn(); |
| 412 | const kept: unknown = ( |
| 413 | Reflect.get(globalThis, Symbol.for("@cursor/sdk.backgroundShell")) as Function |
| 414 | )({ |
| 415 | conversationId, |
| 416 | command: "sleep 60", |
| 417 | shell: { |
| 418 | id, |
| 419 | pid: id + 1, |
| 420 | abort, |
| 421 | onComplete: (listener: typeof complete) => (complete = listener), |
| 422 | }, |
| 423 | }); |
| 424 | return { kept, abort, complete: (completion: object) => complete(completion) }; |
| 425 | }; |
| 426 | const events: Array<object> = []; |
| 427 | const stops: Array<() => void> = []; |
| 428 | const reported = yield* Deferred.make<void>(); |
| 429 | const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; |
| 430 | const session = yield* runner.open({ |
| 431 | operation: "create", |
| 432 | options: {}, |
| 433 | threadId: ThreadId.make("thread-cursor-agent-sdk-background"), |
| 434 | providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-background"), |
| 435 | }); |
| 436 | const run = yield* session.send({ |
| 437 | message: "watch it", |
| 438 | onBackgroundShell: (event) => |
| 439 | Effect.gen(function* () { |
| 440 | if (event.type === "started") { |
| 441 | const { stop, ...started } = event; |
| 442 | stops.push(stop); |
| 443 | events.push(started); |
| 444 | return; |
| 445 | } |
| 446 | events.push(event); |
| 447 | if (!event.stopped) yield* Deferred.succeed(reported, undefined); |
| 448 | }), |
| 449 | }); |
| 450 | yield* run.wait; |
| 451 | |
| 452 | const killed = start("agent-cursor-agent-sdk-test", 10); |
| 453 | const finished = start("agent-cursor-agent-sdk-test", 20); |
| 454 | const foreign = start("agent-someone-else", 30); |
| 455 | killed.complete({ code: null, aborted: true }); |
| 456 | finished.complete({ code: 3, aborted: false, outputPath: "/terminals/20.txt" }); |
| 457 | yield* Deferred.await(reported); |
| 458 | stops[0]!(); |
| 459 | |
| 460 | assert.deepStrictEqual([killed.kept, finished.kept, foreign.kept], [true, true, false]); |
| 461 | assert.strictEqual(killed.abort.mock.calls.length, 1); |
| 462 | const shell = (id: string, pid: number) => ({ id, pid, command: "sleep 60" }); |
| 463 | assert.deepStrictEqual(events, [ |
| 464 | { ...shell("10", 11), type: "started" }, |
| 465 | { ...shell("20", 21), type: "started" }, |
| 466 | { |
| 467 | ...shell("10", 11), |
| 468 | type: "ended", |
| 469 | stopped: true, |
| 470 | exitCode: undefined, |
| 471 | outputPath: undefined, |
| 472 | }, |
| 473 | { |
| 474 | ...shell("20", 21), |
| 475 | type: "ended", |
| 476 | stopped: false, |
| 477 | exitCode: 3, |
| 478 | outputPath: "/terminals/20.txt", |
| 479 | }, |
| 480 | ]); |
| 481 | }).pipe(Effect.provide(layerTest)), |
| 482 | ); |
| 483 | |
| 484 | it.effect("forwards Run.steer and reports a missing method as a follow-up", () => |
| 485 | Effect.gen(function* () { |
| 486 | cursorSdkMock.runSteer.mockClear(); |
| 487 | const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; |
| 488 | const session = yield* runner.open({ |
| 489 | operation: "create", |
| 490 | options: {}, |
| 491 | threadId: ThreadId.make("thread-cursor-agent-sdk-steer"), |
| 492 | providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-steer"), |
| 493 | }); |
| 494 | const run = yield* session.send({ message: "continue" }); |
| 495 | assert.equal(yield* run.steer!("keep going"), "complete_delivered"); |
| 496 | assert.deepStrictEqual(cursorSdkMock.runSteer.mock.calls, [["keep going"]]); |
| 497 | |
| 498 | cursorSdkMock.runSteer.mockImplementationOnce(async () => { |
| 499 | throw new Error("steer transport failed"); |
| 500 | }); |
| 501 | const failed = yield* run.steer!("again").pipe(Effect.exit); |
| 502 | assert(Exit.isFailure(failed)); |
| 503 | |
| 504 | cursorSdkMock.send.mockImplementationOnce(async () => ({ |
| 505 | id: "run-without-steer", |
| 506 | agentId: "agent-cursor-agent-sdk-test", |
| 507 | wait: cursorSdkMock.runWait, |
| 508 | cancel: cursorSdkMock.runCancel, |
| 509 | steer: undefined, |
| 510 | })); |
| 511 | const plain = yield* session.send({ message: "plain" }); |
| 512 | assert.equal(yield* plain.steer!("later"), "revert_to_followup"); |
| 513 | }).pipe(Effect.provide(layerTest)), |
| 514 | ); |
| 515 | |
| 516 | it.effect( |
| 517 | "ref-counts one disposable SqliteLocalAgentStore with no-op runEvents per workspace", |
| 518 | () => |
| 519 | Effect.gen(function* () { |
| 520 | const dispose = vi.fn(async () => {}); |
| 521 | const underlyingAppend = vi.fn(async () => { |
| 522 | throw new Error("runEvents.append must not hit SQLite"); |
| 523 | }); |
| 524 | const fakeStore = { |
| 525 | agents: { get: vi.fn() }, |
| 526 | runs: { list: vi.fn() }, |
| 527 | checkpoints: { save: vi.fn() }, |
| 528 | runEvents: { append: underlyingAppend, list: vi.fn(), delete: vi.fn() }, |
| 529 | dispose, |
| 530 | }; |
| 531 | cursorSdkMock.sqliteOpen.mockClear(); |
| 532 | cursorSdkMock.sqliteOpen.mockResolvedValueOnce(fakeStore); |
| 533 | cursorSdkMock.create.mockClear(); |
| 534 | |
| 535 | const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; |
| 536 | const session = yield* runner.open({ |
| 537 | operation: "create", |
| 538 | options: { local: { cwd: "/workspace/cursor-store-test" } }, |
| 539 | threadId: ThreadId.make("thread-cursor-agent-sdk-store"), |
| 540 | providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-store"), |
| 541 | }); |
| 542 | const peer = yield* runner.open({ |
| 543 | operation: "create", |
| 544 | options: { local: { cwd: "/workspace/cursor-store-test" } }, |
| 545 | threadId: ThreadId.make("thread-cursor-agent-sdk-store-peer"), |
| 546 | providerSessionId: ProviderSessionId.make("provider-session-cursor-agent-sdk-store-peer"), |
| 547 | }); |
| 548 | |
| 549 | assert.deepStrictEqual(cursorSdkMock.sqliteOpen.mock.calls, [ |
| 550 | [{ workspaceRef: "/workspace/cursor-store-test" }], |
| 551 | ]); |
| 552 | const passedOptions = cursorSdkMock.create.mock.calls[0]?.[0] as |
| 553 | | { |
| 554 | readonly local?: { |
| 555 | readonly store?: { |
| 556 | readonly agents: unknown; |
| 557 | readonly checkpoints: unknown; |
| 558 | readonly runEvents: { |
| 559 | readonly append: (event: { |
| 560 | readonly runId: string; |
| 561 | readonly eventType: string; |
| 562 | readonly payload?: unknown; |
| 563 | }) => Promise<{ readonly seq: number }>; |
| 564 | }; |
| 565 | }; |
| 566 | }; |
| 567 | } |
| 568 | | undefined; |
| 569 | const peerOptions = cursorSdkMock.create.mock.calls[1]?.[0] as typeof passedOptions; |
| 570 | const passedStore = passedOptions?.local?.store; |
| 571 | assert.isDefined(passedStore); |
| 572 | assert.strictEqual(peerOptions?.local?.store, passedStore); |
| 573 | assert.strictEqual(passedStore?.agents, fakeStore.agents); |
| 574 | assert.strictEqual(passedStore?.checkpoints, fakeStore.checkpoints); |
| 575 | const appended = yield* Effect.promise(() => |
| 576 | passedStore!.runEvents.append({ |
| 577 | runId: "run-1", |
| 578 | eventType: "text-delta", |
| 579 | payload: { text: "hi" }, |
| 580 | }), |
| 581 | ); |
| 582 | assert.equal(appended.seq, 1); |
| 583 | assert.equal(underlyingAppend.mock.calls.length, 0); |
| 584 | assert.equal(dispose.mock.calls.length, 0); |
| 585 | |
| 586 | // Closing one session keeps the shared workspace store alive; repeated close does not double-release. |
| 587 | yield* session.close; |
| 588 | yield* session.close; |
| 589 | assert.equal(dispose.mock.calls.length, 0); |
| 590 | |
| 591 | yield* peer.close; |
| 592 | assert.equal(dispose.mock.calls.length, 1); |
| 593 | |
| 594 | // Failed open disposes the newly opened store instead of leaking SQLite FDs. |
| 595 | const failingDispose = vi.fn(async () => {}); |
| 596 | cursorSdkMock.sqliteOpen.mockResolvedValueOnce({ ...fakeStore, dispose: failingDispose }); |
| 597 | cursorSdkMock.create.mockRejectedValueOnce(new Error("boom")); |
| 598 | const failed = yield* runner |
| 599 | .open({ |
| 600 | operation: "create", |
| 601 | options: { local: { cwd: "/workspace/cursor-store-fail" } }, |
| 602 | threadId: ThreadId.make("thread-cursor-agent-sdk-store-fail"), |
| 603 | providerSessionId: ProviderSessionId.make( |
| 604 | "provider-session-cursor-agent-sdk-store-fail", |
| 605 | ), |
| 606 | }) |
| 607 | .pipe(Effect.exit); |
| 608 | assert(Exit.isFailure(failed)); |
| 609 | assert.equal(failingDispose.mock.calls.length, 1); |
| 610 | }).pipe(Effect.provide(layerTest)), |
| 611 | ); |
| 612 | }); |