diff --git a/packages/adapters/cursor-local/src/server/execute-cancel-retry.test.ts b/packages/adapters/cursor-local/src/server/execute-cancel-retry.test.ts new file mode 100644 index 00000000000..3940ecc3e23 --- /dev/null +++ b/packages/adapters/cursor-local/src/server/execute-cancel-retry.test.ts @@ -0,0 +1,141 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it, vi } from "vitest"; +import type { RunProcessResult } from "@paperclipai/adapter-utils/server-utils"; +import { execute } from "./execute.js"; +import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context"; + +const { runProcessMock } = vi.hoisted(() => { + return { runProcessMock: vi.fn() }; +}); + +vi.mock("@paperclipai/adapter-utils/execution-target", async () => { + const actual = await vi.importActual( + "@paperclipai/adapter-utils/execution-target", + ); + return { + ...actual, + startAdapterExecutionTargetPaperclipBridge: async () => null, + runAdapterExecutionTargetProcess: (...args: unknown[]) => runProcessMock(...args), + }; +}); + +vi.mock("./remote-command.js", async () => { + const actual = await vi.importActual("./remote-command.js"); + return { + ...actual, + prepareCursorSandboxCommand: async (input: Parameters[0]) => ({ + command: input.command, + env: input.env, + remoteSystemHomeDir: null, + addedPathEntry: null, + preferredCommandPath: null, + }), + }; +}); + +function processResult(overrides: Partial): RunProcessResult { + return { + exitCode: 1, + signal: null, + timedOut: false, + stdout: "", + stderr: "", + pid: 123, + startedAt: "2026-11-21T00:00:00.000Z", + ...overrides, + }; +} + +const unknownSessionError = '{"type":"error","message":"Unknown session"}\n'; +const transcriptWithTriggerPhrase = + '{"type":"user","message":{"content":[{"type":"text","text":"If the session is not found, start over."}]}}\n'; + +async function runExecute(options: { + signal?: AbortSignal; + results: RunProcessResult[]; +}): Promise<{ result: Awaited>; logs: string[] }> { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-cursor-cancel-retry-")); + const workspace = path.join(root, "workspace"); + const commandPath = path.join(root, "agent.sh"); + await fs.mkdir(workspace, { recursive: true }); + await fs.writeFile(commandPath, "#!/bin/sh\ncat >/dev/null\n", { mode: 0o755 }); + const logs: string[] = []; + runProcessMock.mockReset(); + const queue = [...options.results]; + runProcessMock.mockImplementation(async (_runId: string, _target: unknown, _command: string, args: string[]) => { + const next = queue.shift(); + if (!next) throw new Error("mock process runner ran out of scripted results"); + return next; + }); + try { + const result = await execute({ + runId: "run-cursor-cancel-retry", + agent: { id: "agent-1", companyId: "company-1", name: "Cursor Coder", adapterType: "cursor", adapterConfig: {} }, + runtime: { sessionId: "cursor-session-old", sessionParams: null, sessionDisplayId: null, taskKey: null }, + config: { command: commandPath, cwd: workspace, promptTemplate: "Follow the paperclip heartbeat." }, + context: createPromptContextFixture(), + authToken: "run-jwt-token", + onLog: async (_stream, chunk) => { + logs.push(chunk); + }, + ...(options.signal ? { signal: options.signal } : {}), + }); + return { result, logs }; + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +} + +describe("cursor cancelled-run resume retry", () => { + it("does not retry a resumed run after the operator cancels it", async () => { + const controller = new AbortController(); + controller.abort(); + const { result, logs } = await runExecute({ + signal: controller.signal, + results: [processResult({ stdout: unknownSessionError })], + }); + expect(runProcessMock).toHaveBeenCalledTimes(1); + expect(result.exitCode).toBe(1); + expect(logs.join("")).not.toContain("retrying with a fresh session"); + }); + + it("does not retry a resumed run killed by a signal", async () => { + const { result, logs } = await runExecute({ + results: [processResult({ exitCode: 137, signal: "SIGKILL", stdout: unknownSessionError })], + }); + expect(runProcessMock).toHaveBeenCalledTimes(1); + expect(result.exitCode).toBe(137); + expect(logs.join("")).not.toContain("retrying with a fresh session"); + }); + + it("does not retry when the transcript mentions a missing session", async () => { + const { result, logs } = await runExecute({ + results: [processResult({ stdout: transcriptWithTriggerPhrase })], + }); + expect(runProcessMock).toHaveBeenCalledTimes(1); + expect(result.exitCode).toBe(1); + expect(logs.join("")).not.toContain("retrying with a fresh session"); + }); + + it("retries a genuine unknown-session error on a live run", async () => { + const { result, logs } = await runExecute({ + results: [ + processResult({ stdout: unknownSessionError }), + processResult({ + exitCode: 0, + stdout: + '{"type":"system","subtype":"init","session_id":"cursor-session-fresh-2","model":"auto"}\n' + + '{"type":"result","subtype":"success","session_id":"cursor-session-fresh-2","result":"ok"}\n', + }), + ], + }); + expect(runProcessMock).toHaveBeenCalledTimes(2); + expect(result.exitCode).toBe(0); + expect(logs.join("")).toContain("retrying with a fresh session"); + const retryArgs = runProcessMock.mock.calls[1]?.[3] as string[] | undefined; + expect(retryArgs).toBeDefined(); + expect(retryArgs).not.toContain("--resume"); + }); +}); diff --git a/packages/adapters/cursor-local/src/server/execute.ts b/packages/adapters/cursor-local/src/server/execute.ts index 07736f782bf..afddd9f6ec5 100644 --- a/packages/adapters/cursor-local/src/server/execute.ts +++ b/packages/adapters/cursor-local/src/server/execute.ts @@ -796,8 +796,10 @@ export async function execute(ctx: AdapterExecutionContext): Promise { it("skips trace announcements with CRLF, whitespace and ANSI color", () => { @@ -20,3 +20,16 @@ describe("Cursor diagnostic selection", () => { expect(firstCursorDiagnosticLine("\n\r\n")).toBe(""); }); }); + +describe("Cursor unknown session detection", () => { + it("matches Cursor's own error text and stderr", () => { + expect(isCursorUnknownSessionError("Unknown session", "")).toBe(true); + expect(isCursorUnknownSessionError(null, "Error: unknown session id abc")).toBe(true); + expect(isCursorUnknownSessionError(null, "chat abc not found")).toBe(true); + }); + + it("does not match unrelated errors or an empty error", () => { + expect(isCursorUnknownSessionError("Authentication failed", "")).toBe(false); + expect(isCursorUnknownSessionError(null, "")).toBe(false); + }); +}); diff --git a/packages/adapters/cursor-local/src/server/parse.ts b/packages/adapters/cursor-local/src/server/parse.ts index 8ca1d6ac47d..f507d30e782 100644 --- a/packages/adapters/cursor-local/src/server/parse.ts +++ b/packages/adapters/cursor-local/src/server/parse.ts @@ -197,8 +197,8 @@ export function createCursorJsonlParser() { }; } -export function isCursorUnknownSessionError(stdout: string, stderr: string): boolean { - const haystack = `${stdout}\n${stderr}` +export function isCursorUnknownSessionError(errorMessage: string | null, stderr: string): boolean { + const haystack = `${errorMessage ?? ""}\n${stderr}` .split(/\r?\n/) .map((line) => line.trim()) .filter(Boolean) diff --git a/server/src/__tests__/adapter-session-codecs.test.ts b/server/src/__tests__/adapter-session-codecs.test.ts index f5df3906765..db06a6101ab 100644 --- a/server/src/__tests__/adapter-session-codecs.test.ts +++ b/server/src/__tests__/adapter-session-codecs.test.ts @@ -309,19 +309,25 @@ describe("cursor resume recovery detection", () => { it("detects unknown session errors from cursor output", () => { expect( isCursorUnknownSessionError( + "Unknown session", "", + ), + ).toBe(true); + expect( + isCursorUnknownSessionError( + null, "Error: unknown session id abc", ), ).toBe(true); expect( isCursorUnknownSessionError( - "", + null, "chat abc not found", ), ).toBe(true); expect( isCursorUnknownSessionError( - "{\"type\":\"result\",\"subtype\":\"success\"}", + null, "", ), ).toBe(false); diff --git a/server/src/__tests__/cursor-local-adapter.test.ts b/server/src/__tests__/cursor-local-adapter.test.ts index 087a8667868..fc9d75047df 100644 --- a/server/src/__tests__/cursor-local-adapter.test.ts +++ b/server/src/__tests__/cursor-local-adapter.test.ts @@ -94,8 +94,8 @@ describe("cursor parser", () => { describe("cursor stale session detection", () => { it("treats missing/unknown session messages as an unknown session error", () => { - expect(isCursorUnknownSessionError("", "unknown session id chat_123")).toBe(true); - expect(isCursorUnknownSessionError("", "chat abc not found")).toBe(true); + expect(isCursorUnknownSessionError("unknown session id chat_123", "")).toBe(true); + expect(isCursorUnknownSessionError(null, "chat abc not found")).toBe(true); }); });