mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
<!-- Write all pull request text in Simplified Technical English (ASD-STE100): short sentences, one instruction per sentence, simple approved vocabulary, and the active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Cursor adapter runs the Cursor CLI and resumes a saved session when one exists > - A cancelled run left the CLI process dead with a non-zero exit, and the adapter read the full transcript for "unknown session" text > - The transcript match fired on agent words, so the adapter started a fresh session after the cancel > - This pull request gates the fresh-session retry on a live run and matches only Cursor's own error > - The benefit is a cancelled run stays cancelled, and a transcript phrase never restarts a run ## Linked Issues or Issue Description Fixes #22204 ## What Changed - The Cursor adapter no longer retries a resumed run with a fresh session when the run was cancelled or the process was killed. The retry gate now requires no process signal and no aborted run signal. - The unknown-session matcher no longer reads the full stdout transcript. It now reads only the parsed Cursor error message from the stream-json error or result event, plus stderr. - `isCursorUnknownSessionError` now takes the parsed error message instead of stdout. The name and the match patterns stay the same. - The codex-local adapter already gates its unknown-session retry on no process signal. This change applies the same rule to the Cursor adapter, and it adds the run-signal gate. - New tests in `packages/adapters/cursor-local/src/server/execute-cancel-retry.test.ts` cover the cancelled run, the signal-killed run, the transcript phrase, and the genuine unknown-session retry. - New matcher tests in `packages/adapters/cursor-local/src/server/parse.test.ts` cover the error text, stderr, and the empty case. - The server matcher tests in `adapter-session-codecs.test.ts` and `cursor-local-adapter.test.ts` use the new signature. ## Verification - Negative control: the new execute tests fail 3 of 4 on the unfixed code, because the adapter retries in each "does not retry" case. The genuine retry case passes on the unfixed code. With the fix, all 4 tests pass. - Targeted vitest runs pass with the fix: cursor-local `execute-cancel-retry.test.ts` and `parse.test.ts` (9 passed), `execute.test.ts`, `execute.remote.test.ts`, and `remote-command.test.ts` (13 passed), `test.test.ts` (2 passed), and server `adapter-session-codecs.test.ts` and `cursor-local-adapter.test.ts` (35 passed). Total: 59 passed, 0 failed. - Package typecheck passes: `pnpm --filter @paperclipai/adapter-cursor-local typecheck` (`tsc --noEmit`) exits 0. It covers the new test file. - The full server typecheck does not run in this sandbox. The tsc layer was killed by the system for low memory (SIGKILL on the 1285-file layer). CI is the arbiter for server typecheck. - The full server suite and the embedded-Postgres suites do not run here. CI is the arbiter for that coverage. - No live Cursor CLI run was done. The fix uses a mocked process runner. The real unknown-session error shape (error event or stderr) follows the issue report. ## Risks - A genuine unknown-session failure that Cursor reports only as plain stdout text, and not as a stream-json error event or stderr, no longer triggers the fresh-session retry. The run then fails with the error instead of retrying. This is the intended scope change. - A cancel that arrives after the retry decision but before the retry process starts still starts the retry process. The server cancel machinery must kill it. No second retry exists, so the run still ends cancelled. - The match patterns stay the same. A long stderr line can still match, but stderr is Cursor's own diagnostic output, not agent transcript text. ## Model Used Meta Muse Spark 1.3 ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge Signed-off-by: Josh Cox <joshuacox@users.noreply.github.com> Co-authored-by: Review <review@local>
This commit is contained in:
1 parent
7890ce11a7
commit
538de6bed6
6 files changed
+170
-8
No files matched your search
@@ -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<typeof import("@paperclipai/adapter-utils/execution-target")>(
|
||||
"@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<typeof import("./remote-command.js")>("./remote-command.js");
|
||||
return {
|
||||
...actual,
|
||||
prepareCursorSandboxCommand: async (input: Parameters<typeof actual.prepareCursorSandboxCommand>[0]) => ({
|
||||
command: input.command,
|
||||
env: input.env,
|
||||
remoteSystemHomeDir: null,
|
||||
addedPathEntry: null,
|
||||
preferredCommandPath: null,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
function processResult(overrides: Partial<RunProcessResult>): 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<ReturnType<typeof execute>>; 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");
|
||||
});
|
||||
});
|
||||
@@ -796,8 +796,10 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
if (
|
||||
sessionId &&
|
||||
!initial.proc.timedOut &&
|
||||
!initial.proc.signal &&
|
||||
!ctx.signal?.aborted &&
|
||||
(initial.proc.exitCode ?? 0) !== 0 &&
|
||||
isCursorUnknownSessionError(initial.proc.stdout, initial.proc.stderr)
|
||||
isCursorUnknownSessionError(initial.parsed.errorMessage, initial.proc.stderr)
|
||||
) {
|
||||
await onLog(
|
||||
"stdout",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { firstCursorDiagnosticLine } from "./parse.js";
|
||||
import { firstCursorDiagnosticLine, isCursorUnknownSessionError } from "./parse.js";
|
||||
|
||||
describe("Cursor diagnostic selection", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user