The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 2 | import { assert, describe, it } from "@effect/vitest"; |
| 3 | import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; |
| 4 | import { AgentScope } from "@t3tools/shared/AgentScope"; |
| 5 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 6 | import * as Deferred from "effect/Deferred"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Exit from "effect/Exit"; |
| 9 | import * as Fiber from "effect/Fiber"; |
| 10 | import * as FileSystem from "effect/FileSystem"; |
| 11 | import * as Path from "effect/Path"; |
| 12 | |
| 13 | import * as CursorAgentSdk from "./CursorAgentSdk.ts"; |
| 14 | import * as CursorAgentSdkProcessRunner from "./CursorAgentSdkProcessRunner.ts"; |
| 15 | import { |
| 16 | deserializeRunResult, |
| 17 | deserializeWorkerError, |
| 18 | serializeRunResult, |
| 19 | serializeWorkerError, |
| 20 | } from "./CursorAgentSdkWorkerProtocol.ts"; |
| 21 | import { isCursorSdkError, tagCursorSdkError } from "./sdk.ts"; |
| 22 | |
| 23 | // Minimal fake worker script implementing the NDJSON worker protocol in a real child Node process. |
| 24 | const FAKE_WORKER_SCRIPT = ` |
| 25 | const readline = require("node:readline"); |
| 26 | const rawWrite = process.stdout.write.bind(process.stdout); |
| 27 | const send = (msg) => rawWrite(JSON.stringify(msg) + "\\n"); |
| 28 | const mode = process.env.FAKE_WORKER_MODE || "ok"; |
| 29 | |
| 30 | const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); |
| 31 | rl.on("line", (line) => { |
| 32 | if (!line.trim()) return; |
| 33 | const req = JSON.parse(line); |
| 34 | if (req.type === "open") { |
| 35 | if (mode === "config-error") { |
| 36 | send({ |
| 37 | type: "response", |
| 38 | id: req.id, |
| 39 | ok: false, |
| 40 | error: { |
| 41 | method: "agent.create", |
| 42 | cause: { |
| 43 | name: "ConfigurationError", |
| 44 | message: "Cannot use this model: bad-model", |
| 45 | sdkErrorKind: "ConfigurationError", |
| 46 | }, |
| 47 | }, |
| 48 | }); |
| 49 | return; |
| 50 | } |
| 51 | rawWrite("non-json noise that must be ignored\\n"); |
| 52 | send({ type: "response", id: req.id, ok: true, result: { agentId: "agent-worker-1" } }); |
| 53 | return; |
| 54 | } |
| 55 | if (req.type === "send") { |
| 56 | if (mode === "hang-send") { |
| 57 | send({ type: "protocolLog", providerSessionId: "provider-session-worker-test", event: { direction: "incoming", stage: "decoded", payload: { type: "run.started", runId: "pending", agentId: "agent-worker-1" } } }); |
| 58 | return; |
| 59 | } |
| 60 | if (mode === "crash-mid-run") { |
| 61 | send({ type: "response", id: req.id, ok: true, result: { runId: "run-crash", agentId: "agent-worker-1" } }); |
| 62 | process.stderr.write("fatal worker boom\\n"); |
| 63 | process.exit(17); |
| 64 | return; |
| 65 | } |
| 66 | // Emit an early delta before the send response to verify parent buffering/ordering. |
| 67 | send({ type: "delta", sendId: req.id, update: { type: "text-delta", text: "early-" } }); |
| 68 | send({ type: "response", id: req.id, ok: true, result: { runId: "run-worker-1", agentId: "agent-worker-1" } }); |
| 69 | if (mode === "cancel") { |
| 70 | return; |
| 71 | } |
| 72 | send({ type: "delta", sendId: req.id, update: { type: "text-delta", text: "late" } }); |
| 73 | send({ |
| 74 | type: "runDone", |
| 75 | sendId: req.id, |
| 76 | ok: true, |
| 77 | result: { |
| 78 | id: "run-worker-1", |
| 79 | requestId: "req-1", |
| 80 | status: "finished", |
| 81 | result: "early-late", |
| 82 | model: { id: "default" }, |
| 83 | durationMs: 5, |
| 84 | }, |
| 85 | }); |
| 86 | if (mode === "exit-after-done") { |
| 87 | rawWrite("", () => process.exit(0)); |
| 88 | } |
| 89 | if (mode === "background-shell" && req.listenBackgroundShells) { |
| 90 | send({ type: "backgroundShell", sessionId: req.sessionId, event: { type: "started", id: "sh-1", pid: 4101, command: "sleep 60" } }); |
| 91 | send({ type: "backgroundShell", sessionId: req.sessionId, event: { type: "started", id: "sh-2", pid: 4102, command: "tail -f" } }); |
| 92 | } |
| 93 | return; |
| 94 | } |
| 95 | if (req.type === "stopBackgroundShell") { |
| 96 | send({ type: "backgroundShell", sessionId: req.sessionId, event: { type: "ended", id: req.shellId, pid: 4101, command: "sleep 60", stopped: true, exitCode: undefined, outputPath: undefined } }); |
| 97 | send({ type: "response", id: req.id, ok: true, result: null }); |
| 98 | if (mode === "background-shell") { |
| 99 | rawWrite("", () => process.exit(19)); |
| 100 | } |
| 101 | return; |
| 102 | } |
| 103 | if (req.type === "steer") { |
| 104 | send({ type: "response", id: req.id, ok: true, result: "complete_delivered" }); |
| 105 | return; |
| 106 | } |
| 107 | if (req.type === "cancel") { |
| 108 | send({ type: "protocolLog", providerSessionId: "provider-session-worker-test", event: { direction: "incoming", stage: "decoded", payload: { type: "run.cancel", runId: "run-worker-1" } } }); |
| 109 | send({ type: "response", id: req.id, ok: true, result: null }); |
| 110 | send({ |
| 111 | type: "runDone", |
| 112 | sendId: req.sendId, |
| 113 | ok: true, |
| 114 | result: { |
| 115 | id: "run-worker-1", |
| 116 | requestId: "req-1", |
| 117 | status: "cancelled", |
| 118 | model: { id: "default" }, |
| 119 | durationMs: 2, |
| 120 | }, |
| 121 | }); |
| 122 | return; |
| 123 | } |
| 124 | if (req.type === "listMessages") { |
| 125 | send({ type: "response", id: req.id, ok: true, result: [{ id: "m1", role: "assistant", text: "early-late" }] }); |
| 126 | return; |
| 127 | } |
| 128 | if (req.type === "readContextUsage") { |
| 129 | send({ type: "response", id: req.id, ok: true, result: { usedTokens: 120, maxTokens: 1000 } }); |
| 130 | return; |
| 131 | } |
| 132 | if (req.type === "runCheckpointed") { |
| 133 | send({ type: "response", id: req.id, ok: true, result: req.runId === "run-worker-1" }); |
| 134 | return; |
| 135 | } |
| 136 | if (req.type === "rewindAfterRun") { |
| 137 | send({ type: "response", id: req.id, ok: true, result: null }); |
| 138 | return; |
| 139 | } |
| 140 | if (req.type === "textGenerate" && mode === "hang-text") { |
| 141 | send({ type: "protocolLog", providerSessionId: "provider-session-worker-test", event: { direction: "incoming", stage: "decoded", payload: { type: "run.started", runId: "text", agentId: "text" } } }); |
| 142 | return; |
| 143 | } |
| 144 | if (req.type === "cancelTextGenerate") { |
| 145 | send({ type: "protocolLog", providerSessionId: "provider-session-worker-test", event: { direction: "incoming", stage: "decoded", payload: { type: "run.cancel", runId: "text" } } }); |
| 146 | send({ type: "response", id: req.id, ok: true, result: null }); |
| 147 | return; |
| 148 | } |
| 149 | if (req.type === "textGenerate") { |
| 150 | if (mode === "rate-limit-text") { |
| 151 | send({ |
| 152 | type: "response", |
| 153 | id: req.id, |
| 154 | ok: true, |
| 155 | result: { |
| 156 | id: "run-tg-1", |
| 157 | requestId: "req-tg-1", |
| 158 | status: "error", |
| 159 | model: { id: "default" }, |
| 160 | durationMs: 3, |
| 161 | error: { |
| 162 | name: "RateLimitError", |
| 163 | message: "Too many requests", |
| 164 | code: "PRO_USER_USAGE_LIMIT", |
| 165 | status: 429, |
| 166 | sdkErrorKind: "CursorSdkError", |
| 167 | }, |
| 168 | }, |
| 169 | }); |
| 170 | return; |
| 171 | } |
| 172 | send({ |
| 173 | type: "response", |
| 174 | id: req.id, |
| 175 | ok: true, |
| 176 | result: { |
| 177 | id: "run-tg-1", |
| 178 | requestId: "req-tg-1", |
| 179 | status: "finished", |
| 180 | result: JSON.stringify({ title: "Out of process" }), |
| 181 | model: { id: "default" }, |
| 182 | durationMs: 3, |
| 183 | }, |
| 184 | }); |
| 185 | return; |
| 186 | } |
| 187 | if (req.type === "closeSession") { |
| 188 | send({ type: "response", id: req.id, ok: true, result: null }); |
| 189 | return; |
| 190 | } |
| 191 | if (req.type === "close") { |
| 192 | send({ type: "response", id: req.id, ok: true, result: null }); |
| 193 | rawWrite("", () => process.exit(0)); |
| 194 | } |
| 195 | }); |
| 196 | rl.on("close", () => process.exit(0)); |
| 197 | `; |
| 198 | |
| 199 | const openInput = { |
| 200 | operation: "create" as const, |
| 201 | options: { model: { id: "default" } }, |
| 202 | threadId: ThreadId.make("thread-worker-test"), |
| 203 | providerSessionId: ProviderSessionId.make("provider-session-worker-test"), |
| 204 | }; |
| 205 | |
| 206 | describe("CursorAgentSdkWorkerProtocol", () => { |
| 207 | it("preserves SDK error classification, rate limits, and abort causes without loading @cursor/sdk", () => { |
| 208 | const configErr = tagCursorSdkError( |
| 209 | new Error("Cannot use this model: mystery"), |
| 210 | "ConfigurationError", |
| 211 | ); |
| 212 | const restoredConfig = deserializeWorkerError(serializeWorkerError(configErr)); |
| 213 | assert.isTrue(isCursorSdkError(restoredConfig, "ConfigurationError")); |
| 214 | assert.isTrue(isCursorSdkError(restoredConfig, "CursorSdkError")); |
| 215 | assert.isFalse(isCursorSdkError(restoredConfig, "AuthenticationError")); |
| 216 | |
| 217 | const rateErr = Object.assign(new Error("Quota exceeded"), { |
| 218 | name: "RateLimitError", |
| 219 | code: "PRO_USER_USAGE_LIMIT", |
| 220 | status: 429, |
| 221 | }); |
| 222 | const restoredResult = deserializeRunResult( |
| 223 | serializeRunResult({ |
| 224 | id: "r1", |
| 225 | requestId: "req1", |
| 226 | status: "error", |
| 227 | model: { id: "default" }, |
| 228 | durationMs: 1, |
| 229 | error: rateErr, |
| 230 | } as never), |
| 231 | ); |
| 232 | assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(restoredResult.error)); |
| 233 | assert.equal(restoredResult.error?.message, "Quota exceeded"); |
| 234 | |
| 235 | const abortInner = Object.assign(new Error("aborted"), { name: "AbortError" }); |
| 236 | const wrappedAbort = new Error("outer", { cause: abortInner }); |
| 237 | const restoredAbort = deserializeWorkerError(serializeWorkerError(wrappedAbort)); |
| 238 | assert.isTrue(CursorAgentSdk.isCursorCancellationError(restoredAbort)); |
| 239 | |
| 240 | const nullProto = Object.create(null) as Record<string, unknown>; |
| 241 | const restoredNullProto = deserializeWorkerError(serializeWorkerError(nullProto)); |
| 242 | assert.equal(restoredNullProto.message, "[Unserializable error]"); |
| 243 | }); |
| 244 | }); |
| 245 | |
| 246 | describe("CursorAgentSdkProcessRunner", () => { |
| 247 | const writeFakeWorker = Effect.gen(function* () { |
| 248 | const fs = yield* FileSystem.FileSystem; |
| 249 | const path = yield* Path.Path; |
| 250 | const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-worker-test-" }); |
| 251 | const scriptPath = path.join(dir, "fake-worker.cjs"); |
| 252 | yield* fs.writeFileString(scriptPath, FAKE_WORKER_SCRIPT); |
| 253 | return scriptPath; |
| 254 | }); |
| 255 | |
| 256 | it.live( |
| 257 | "runs a full session out of process with ordered deltas, scope hooks, and clean shutdown", |
| 258 | () => |
| 259 | Effect.scoped( |
| 260 | Effect.gen(function* () { |
| 261 | const scriptPath = yield* writeFakeWorker; |
| 262 | const executable = yield* HostProcess.ExecutablePath; |
| 263 | const registeredPids: Array<number> = []; |
| 264 | const unregisteredPids: Array<number> = []; |
| 265 | const stoppedUnits: Array<string> = []; |
| 266 | const protocolEvents: Array<string> = []; |
| 267 | |
| 268 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 269 | resolveLaunch: Effect.succeed({ |
| 270 | command: executable, |
| 271 | args: [scriptPath], |
| 272 | registerProcess: (pid) => { |
| 273 | registeredPids.push(pid); |
| 274 | return () => unregisteredPids.push(pid); |
| 275 | }, |
| 276 | }), |
| 277 | protocolLoggerFor: () => (event) => |
| 278 | Effect.sync(() => { |
| 279 | protocolEvents.push(event.payload.type); |
| 280 | }), |
| 281 | }).pipe( |
| 282 | Effect.provideService(AgentScope, { |
| 283 | wrap: ({ command, args, name }) => |
| 284 | Effect.succeed({ command, args, unit: `unit-${name}` }), |
| 285 | oomKilled: () => Effect.succeed(false), |
| 286 | stop: (unit) => |
| 287 | Effect.sync(() => { |
| 288 | stoppedUnits.push(unit); |
| 289 | }), |
| 290 | kill: () => Effect.succeed(false), |
| 291 | clear: () => Effect.void, |
| 292 | }), |
| 293 | ); |
| 294 | |
| 295 | const session = yield* runner.open(openInput); |
| 296 | assert.equal(session.agentId, "agent-worker-1"); |
| 297 | assert.isTrue(session.isAlive?.()); |
| 298 | const otherSession = yield* runner.open({ |
| 299 | ...openInput, |
| 300 | threadId: ThreadId.make("thread-worker-test-2"), |
| 301 | providerSessionId: ProviderSessionId.make("provider-session-worker-test-2"), |
| 302 | }); |
| 303 | yield* otherSession.close; |
| 304 | assert.isFalse(otherSession.isAlive?.()); |
| 305 | assert.isTrue(session.isAlive?.()); |
| 306 | assert.lengthOf(registeredPids, 1); |
| 307 | assert.deepEqual(unregisteredPids, []); |
| 308 | |
| 309 | const receivedDeltas: Array<string> = []; |
| 310 | const firstDeltaGate = yield* Deferred.make<void>(); |
| 311 | const run = yield* session.send({ |
| 312 | message: "hi", |
| 313 | onDelta: (update) => |
| 314 | Effect.gen(function* () { |
| 315 | const text = (update as { readonly text?: string }).text ?? ""; |
| 316 | if (text === "early-") { |
| 317 | yield* Deferred.succeed(firstDeltaGate, undefined); |
| 318 | } |
| 319 | receivedDeltas.push(text); |
| 320 | }), |
| 321 | }); |
| 322 | assert.equal(run.runId, "run-worker-1"); |
| 323 | yield* Deferred.await(firstDeltaGate); |
| 324 | |
| 325 | const steerOutcome = yield* run.steer!("change course"); |
| 326 | assert.equal(steerOutcome, "complete_delivered"); |
| 327 | |
| 328 | const result = yield* run.wait; |
| 329 | assert.equal(result.status, "finished"); |
| 330 | assert.equal(result.result, "early-late"); |
| 331 | assert.deepEqual(receivedDeltas, ["early-", "late"]); |
| 332 | |
| 333 | const [messagesA, messagesB] = yield* Effect.all( |
| 334 | [session.listMessages, session.listMessages], |
| 335 | { concurrency: "unbounded" }, |
| 336 | ); |
| 337 | assert.lengthOf(messagesA, 1); |
| 338 | assert.lengthOf(messagesB, 1); |
| 339 | const usage = yield* session.readContextUsage!; |
| 340 | assert.deepEqual(usage, { usedTokens: 120, maxTokens: 1000 }); |
| 341 | assert.isTrue(yield* session.runCheckpointed!("run-worker-1")); |
| 342 | assert.isFalse(yield* session.runCheckpointed!("other")); |
| 343 | yield* session.rewindAfterRun!("run-worker-1"); |
| 344 | yield* session.close; |
| 345 | assert.isFalse(session.isAlive?.()); |
| 346 | |
| 347 | assert.deepEqual(unregisteredPids, registeredPids); |
| 348 | assert.deepEqual(stoppedUnits, ["unit-cursor-sdk"]); |
| 349 | assert.include(protocolEvents, "agent.open"); |
| 350 | assert.include(protocolEvents, "agent.opened"); |
| 351 | assert.include(protocolEvents, "run.started"); |
| 352 | assert.include(protocolEvents, "interaction.update"); |
| 353 | assert.include(protocolEvents, "run.completed"); |
| 354 | assert.include(protocolEvents, "agent.close"); |
| 355 | }), |
| 356 | ).pipe(Effect.provide(NodeServices.layer)), |
| 357 | ); |
| 358 | |
| 359 | it.live( |
| 360 | "preserves ConfigurationError classification across IPC and cleans up on open failure", |
| 361 | () => |
| 362 | Effect.scoped( |
| 363 | Effect.gen(function* () { |
| 364 | const scriptPath = yield* writeFakeWorker; |
| 365 | const executable = yield* HostProcess.ExecutablePath; |
| 366 | let unregistered = false; |
| 367 | |
| 368 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 369 | resolveLaunch: Effect.succeed({ |
| 370 | command: executable, |
| 371 | args: [scriptPath], |
| 372 | env: { FAKE_WORKER_MODE: "config-error" }, |
| 373 | registerProcess: () => () => { |
| 374 | unregistered = true; |
| 375 | }, |
| 376 | }), |
| 377 | protocolLoggerFor: () => undefined, |
| 378 | }); |
| 379 | |
| 380 | const error = yield* Effect.flip(runner.open(openInput)); |
| 381 | assert.isTrue(isCursorSdkError(error.cause, "ConfigurationError")); |
| 382 | assert.isTrue( |
| 383 | error.cause instanceof Error && |
| 384 | error.cause.message.startsWith("Cannot use this model:"), |
| 385 | ); |
| 386 | assert.isTrue(unregistered); |
| 387 | }), |
| 388 | ).pipe(Effect.provide(NodeServices.layer)), |
| 389 | ); |
| 390 | |
| 391 | it.live("fails run.wait with exit code and stderr when the worker crashes mid-run", () => |
| 392 | Effect.scoped( |
| 393 | Effect.gen(function* () { |
| 394 | const scriptPath = yield* writeFakeWorker; |
| 395 | const executable = yield* HostProcess.ExecutablePath; |
| 396 | const unregistered = yield* Deferred.make<void>(); |
| 397 | |
| 398 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 399 | resolveLaunch: Effect.succeed({ |
| 400 | command: executable, |
| 401 | args: [scriptPath], |
| 402 | env: { FAKE_WORKER_MODE: "crash-mid-run" }, |
| 403 | registerProcess: () => () => { |
| 404 | Deferred.doneUnsafe(unregistered, Exit.void); |
| 405 | }, |
| 406 | }), |
| 407 | protocolLoggerFor: () => undefined, |
| 408 | }); |
| 409 | |
| 410 | const session = yield* runner.open(openInput); |
| 411 | const run = yield* session.send({ message: "hi" }); |
| 412 | const error = yield* Effect.flip(run.wait); |
| 413 | const msg = CursorAgentSdk.cursorSdkFailureMessage(error); |
| 414 | assert.include(msg, "code 17"); |
| 415 | assert.notInclude(msg, "fatal worker boom"); |
| 416 | const diagnostic = error.cause instanceof Error ? error.cause.cause : undefined; |
| 417 | assert.isTrue( |
| 418 | diagnostic instanceof Error && diagnostic.message.includes("fatal worker boom"), |
| 419 | ); |
| 420 | // Dead worker scope tears down immediately instead of waiting for sessions to close. |
| 421 | yield* Deferred.await(unregistered); |
| 422 | assert.isFalse(session.isAlive?.()); |
| 423 | yield* session.close; |
| 424 | }), |
| 425 | ).pipe(Effect.provide(NodeServices.layer)), |
| 426 | ); |
| 427 | |
| 428 | it.live( |
| 429 | "preserves an already-received runDone when the worker exits while onDelta is running", |
| 430 | () => |
| 431 | Effect.scoped( |
| 432 | Effect.gen(function* () { |
| 433 | const scriptPath = yield* writeFakeWorker; |
| 434 | const executable = yield* HostProcess.ExecutablePath; |
| 435 | const workerTerminated = yield* Deferred.make<void>(); |
| 436 | |
| 437 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 438 | resolveLaunch: Effect.succeed({ |
| 439 | command: executable, |
| 440 | args: [scriptPath], |
| 441 | env: { FAKE_WORKER_MODE: "exit-after-done" }, |
| 442 | }), |
| 443 | protocolLoggerFor: () => undefined, |
| 444 | onWorkerTerminated: () => { |
| 445 | Deferred.doneUnsafe(workerTerminated, Exit.void); |
| 446 | }, |
| 447 | }); |
| 448 | |
| 449 | const session = yield* runner.open(openInput); |
| 450 | const deltaStarted = yield* Deferred.make<void>(); |
| 451 | const releaseDelta = yield* Deferred.make<void>(); |
| 452 | const run = yield* session.send({ |
| 453 | message: "hi", |
| 454 | onDelta: (update) => |
| 455 | Effect.gen(function* () { |
| 456 | if ((update as { readonly text?: string }).text === "early-") { |
| 457 | yield* Deferred.succeed(deltaStarted, undefined); |
| 458 | yield* Deferred.await(releaseDelta); |
| 459 | } |
| 460 | }), |
| 461 | }); |
| 462 | yield* Deferred.await(deltaStarted); |
| 463 | yield* Deferred.await(workerTerminated); |
| 464 | yield* Deferred.succeed(releaseDelta, undefined); |
| 465 | const result = yield* run.wait; |
| 466 | assert.equal(result.status, "finished"); |
| 467 | assert.equal(result.result, "early-late"); |
| 468 | yield* session.close; |
| 469 | }), |
| 470 | ).pipe(Effect.provide(NodeServices.layer)), |
| 471 | ); |
| 472 | |
| 473 | it.live("cancels a started run when send is interrupted before handing it off", () => |
| 474 | Effect.scoped( |
| 475 | Effect.gen(function* () { |
| 476 | const scriptPath = yield* writeFakeWorker; |
| 477 | const executable = yield* HostProcess.ExecutablePath; |
| 478 | const startedLogged = yield* Deferred.make<void>(); |
| 479 | const cancelled = yield* Deferred.make<void>(); |
| 480 | |
| 481 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 482 | resolveLaunch: Effect.succeed({ |
| 483 | command: executable, |
| 484 | args: [scriptPath], |
| 485 | env: { FAKE_WORKER_MODE: "cancel" }, |
| 486 | }), |
| 487 | protocolLoggerFor: () => (event) => { |
| 488 | if (event.payload.type === "run.started") { |
| 489 | return Deferred.succeed(startedLogged, undefined).pipe(Effect.andThen(Effect.never)); |
| 490 | } |
| 491 | if (event.payload.type === "run.cancel" && event.direction === "incoming") { |
| 492 | return Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid); |
| 493 | } |
| 494 | return Effect.void; |
| 495 | }, |
| 496 | }); |
| 497 | const session = yield* runner.open(openInput); |
| 498 | const sending = yield* Effect.forkChild(session.send({ message: "hi" })); |
| 499 | yield* Deferred.await(startedLogged); |
| 500 | yield* Fiber.interrupt(sending); |
| 501 | yield* Deferred.await(cancelled); |
| 502 | yield* session.close; |
| 503 | }), |
| 504 | ).pipe(Effect.provide(NodeServices.layer)), |
| 505 | ); |
| 506 | |
| 507 | it.live( |
| 508 | "closes the session when send is interrupted after transmission before acknowledgment", |
| 509 | () => |
| 510 | Effect.scoped( |
| 511 | Effect.gen(function* () { |
| 512 | const scriptPath = yield* writeFakeWorker; |
| 513 | const executable = yield* HostProcess.ExecutablePath; |
| 514 | const receivedByWorker = yield* Deferred.make<void>(); |
| 515 | |
| 516 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 517 | resolveLaunch: Effect.succeed({ |
| 518 | command: executable, |
| 519 | args: [scriptPath], |
| 520 | env: { FAKE_WORKER_MODE: "hang-send" }, |
| 521 | }), |
| 522 | protocolLoggerFor: () => (event) => |
| 523 | event.payload.type === "run.started" |
| 524 | ? Deferred.succeed(receivedByWorker, undefined).pipe(Effect.asVoid) |
| 525 | : Effect.void, |
| 526 | }); |
| 527 | |
| 528 | const session = yield* runner.open(openInput); |
| 529 | assert.isTrue(session.isAlive?.()); |
| 530 | const sending = yield* Effect.forkChild(session.send({ message: "hi" })); |
| 531 | yield* Deferred.await(receivedByWorker); |
| 532 | yield* Fiber.interrupt(sending); |
| 533 | assert.isFalse(session.isAlive?.()); |
| 534 | yield* session.close; |
| 535 | }), |
| 536 | ).pipe(Effect.provide(NodeServices.layer)), |
| 537 | ); |
| 538 | |
| 539 | it.live("cancels an interrupted text generation in a worker that other sessions keep alive", () => |
| 540 | Effect.scoped( |
| 541 | Effect.gen(function* () { |
| 542 | const scriptPath = yield* writeFakeWorker; |
| 543 | const executable = yield* HostProcess.ExecutablePath; |
| 544 | const received = yield* Deferred.make<void>(); |
| 545 | const cancelled = yield* Deferred.make<void>(); |
| 546 | |
| 547 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 548 | resolveLaunch: Effect.succeed({ |
| 549 | command: executable, |
| 550 | args: [scriptPath], |
| 551 | env: { FAKE_WORKER_MODE: "hang-text" }, |
| 552 | }), |
| 553 | protocolLoggerFor: () => (event) => |
| 554 | event.payload.type === "run.started" |
| 555 | ? Deferred.succeed(received, undefined).pipe(Effect.asVoid) |
| 556 | : event.payload.type === "run.cancel" |
| 557 | ? Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid) |
| 558 | : Effect.void, |
| 559 | }); |
| 560 | const session = yield* runner.open(openInput); |
| 561 | const generating = yield* Effect.forkChild( |
| 562 | runner.textGenerate!({ |
| 563 | prompt: "title", |
| 564 | apiKey: "key", |
| 565 | model: { id: "default" }, |
| 566 | cwd: "/tmp", |
| 567 | stateRoot: "/tmp", |
| 568 | }), |
| 569 | ); |
| 570 | yield* Deferred.await(received); |
| 571 | yield* Fiber.interrupt(generating); |
| 572 | yield* Deferred.await(cancelled); |
| 573 | assert.isTrue(session.isAlive?.()); |
| 574 | yield* session.close; |
| 575 | }), |
| 576 | ).pipe(Effect.provide(NodeServices.layer)), |
| 577 | ); |
| 578 | |
| 579 | it.live("forwards cancel and runs textGenerate in a disposable child process", () => |
| 580 | Effect.scoped( |
| 581 | Effect.gen(function* () { |
| 582 | const scriptPath = yield* writeFakeWorker; |
| 583 | const executable = yield* HostProcess.ExecutablePath; |
| 584 | |
| 585 | const cancelRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 586 | resolveLaunch: Effect.succeed({ |
| 587 | command: executable, |
| 588 | args: [scriptPath], |
| 589 | env: { FAKE_WORKER_MODE: "cancel" }, |
| 590 | }), |
| 591 | protocolLoggerFor: () => undefined, |
| 592 | }); |
| 593 | const session = yield* cancelRunner.open(openInput); |
| 594 | const run = yield* session.send({ message: "hi" }); |
| 595 | yield* run.cancel; |
| 596 | const cancelled = yield* run.wait; |
| 597 | assert.equal(cancelled.status, "cancelled"); |
| 598 | yield* session.close; |
| 599 | |
| 600 | let textGenUnregistered = false; |
| 601 | const textGenRunner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 602 | resolveLaunch: Effect.succeed({ |
| 603 | command: executable, |
| 604 | args: [scriptPath], |
| 605 | env: { FAKE_WORKER_MODE: "rate-limit-text" }, |
| 606 | registerProcess: () => () => { |
| 607 | textGenUnregistered = true; |
| 608 | }, |
| 609 | }), |
| 610 | protocolLoggerFor: () => undefined, |
| 611 | }); |
| 612 | const textResult = yield* textGenRunner.textGenerate!({ |
| 613 | prompt: "title", |
| 614 | apiKey: "key", |
| 615 | model: { id: "default" }, |
| 616 | cwd: "/tmp", |
| 617 | stateRoot: "/tmp", |
| 618 | }); |
| 619 | assert.equal(textResult.status, "error"); |
| 620 | assert.isTrue(CursorAgentSdk.isCursorUsageLimitError(textResult.error)); |
| 621 | assert.isTrue(textGenUnregistered); |
| 622 | }), |
| 623 | ).pipe(Effect.provide(NodeServices.layer)), |
| 624 | ); |
| 625 | |
| 626 | it.live( |
| 627 | "settles active runs on a closed session without disrupting peer sessions on the shared worker", |
| 628 | () => |
| 629 | Effect.scoped( |
| 630 | Effect.gen(function* () { |
| 631 | const scriptPath = yield* writeFakeWorker; |
| 632 | const executable = yield* HostProcess.ExecutablePath; |
| 633 | const registeredPids: Array<number> = []; |
| 634 | |
| 635 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 636 | resolveLaunch: Effect.succeed({ |
| 637 | command: executable, |
| 638 | args: [scriptPath], |
| 639 | env: { FAKE_WORKER_MODE: "cancel" }, |
| 640 | registerProcess: (pid) => { |
| 641 | registeredPids.push(pid); |
| 642 | return () => {}; |
| 643 | }, |
| 644 | }), |
| 645 | protocolLoggerFor: () => undefined, |
| 646 | }); |
| 647 | |
| 648 | const sessionA = yield* runner.open(openInput); |
| 649 | const sessionB = yield* runner.open({ |
| 650 | ...openInput, |
| 651 | threadId: ThreadId.make("thread-worker-test-peer"), |
| 652 | providerSessionId: ProviderSessionId.make("provider-session-worker-test-peer"), |
| 653 | }); |
| 654 | assert.lengthOf(registeredPids, 1); |
| 655 | |
| 656 | // Start a run on sessionA that stays pending, then close sessionA while sessionB keeps the worker alive. |
| 657 | const runA = yield* sessionA.send({ message: "hi" }); |
| 658 | const waitA = yield* Effect.forkChild(Effect.flip(runA.wait)); |
| 659 | yield* sessionA.close; |
| 660 | const errorA = yield* Fiber.join(waitA); |
| 661 | assert.include(CursorAgentSdk.cursorSdkFailureMessage(errorA), "closed"); |
| 662 | assert.isFalse(sessionA.isAlive?.()); |
| 663 | assert.isTrue(sessionB.isAlive?.()); |
| 664 | assert.lengthOf(yield* sessionB.listMessages, 1); |
| 665 | yield* sessionB.close; |
| 666 | }), |
| 667 | ).pipe(Effect.provide(NodeServices.layer)), |
| 668 | ); |
| 669 | |
| 670 | it.live( |
| 671 | "forwards background shell events across IPC, routes stop(), and ends orphans on worker crash", |
| 672 | () => |
| 673 | Effect.scoped( |
| 674 | Effect.gen(function* () { |
| 675 | const scriptPath = yield* writeFakeWorker; |
| 676 | const executable = yield* HostProcess.ExecutablePath; |
| 677 | |
| 678 | const runner = yield* CursorAgentSdkProcessRunner.makeCursorAgentSdkProcessRunner({ |
| 679 | resolveLaunch: Effect.succeed({ |
| 680 | command: executable, |
| 681 | args: [scriptPath], |
| 682 | env: { FAKE_WORKER_MODE: "background-shell" }, |
| 683 | }), |
| 684 | protocolLoggerFor: () => undefined, |
| 685 | }); |
| 686 | |
| 687 | const events: Array<object> = []; |
| 688 | const startedFirst = yield* Deferred.make<() => void>(); |
| 689 | const bothEnded = yield* Deferred.make<void>(); |
| 690 | let endedCount = 0; |
| 691 | |
| 692 | const session = yield* runner.open(openInput); |
| 693 | const run = yield* session.send({ |
| 694 | message: "watch it", |
| 695 | onBackgroundShell: (event) => |
| 696 | Effect.gen(function* () { |
| 697 | if (event.type === "started") { |
| 698 | const { stop, ...started } = event; |
| 699 | events.push(started); |
| 700 | if (event.id === "sh-1") yield* Deferred.succeed(startedFirst, stop); |
| 701 | return; |
| 702 | } |
| 703 | events.push(event); |
| 704 | endedCount += 1; |
| 705 | if (endedCount === 2) yield* Deferred.succeed(bothEnded, undefined); |
| 706 | }), |
| 707 | }); |
| 708 | yield* run.wait; |
| 709 | |
| 710 | // Stopping sh-1 triggers a worker-side ended event, then the fake worker crashes to |
| 711 | // verify sh-2 gets a synthesized ended(stopped: true) event. |
| 712 | const stopFirst = yield* Deferred.await(startedFirst); |
| 713 | stopFirst(); |
| 714 | yield* Deferred.await(bothEnded); |
| 715 | |
| 716 | assert.deepEqual(events, [ |
| 717 | { type: "started", id: "sh-1", pid: 4101, command: "sleep 60" }, |
| 718 | { type: "started", id: "sh-2", pid: 4102, command: "tail -f" }, |
| 719 | { |
| 720 | type: "ended", |
| 721 | id: "sh-1", |
| 722 | pid: 4101, |
| 723 | command: "sleep 60", |
| 724 | stopped: true, |
| 725 | exitCode: undefined, |
| 726 | outputPath: undefined, |
| 727 | }, |
| 728 | { |
| 729 | type: "ended", |
| 730 | id: "sh-2", |
| 731 | pid: 4102, |
| 732 | command: "tail -f", |
| 733 | stopped: true, |
| 734 | exitCode: undefined, |
| 735 | outputPath: undefined, |
| 736 | }, |
| 737 | ]); |
| 738 | yield* session.close; |
| 739 | }), |
| 740 | ).pipe(Effect.provide(NodeServices.layer)), |
| 741 | ); |
| 742 | }); |