TypeScript
fix(server): mark Cursor transport error answers as failed (#10337)
shivam6134b90ffb19
diff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.tsindex 9881710135c..0c192ce7e11 100644--- a/apps/server/src/provider/Layers/CursorAdapter.test.ts+++ b/apps/server/src/provider/Layers/CursorAdapter.test.ts@@ -162,6 +162,42 @@ const cursorAdapterTestLayer = it.layer();cursorAdapterTestLayer("CursorAdapterLive", (it) => {+ it.effect("rejects a Cursor transport error returned as a successful assistant answer", () =>+ Effect.gen(function* () {+ const adapter = yield* CursorAdapter;+ const settings = yield* ServerSettingsService;+ const threadId = ThreadId.make("cursor-transport-error-answer");+ const wrapperPath = yield* Effect.promise(() =>+ makeMockAgentWrapper({+ T3_ACP_PROMPT_RESPONSE_TEXT: "Error: RetriableError: WritableIterable is closed",+ }),+ );+ yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });+ const runtimeEventsFiber = yield* adapter.streamEvents.pipe(+ Stream.takeUntil((event) => event.type === "session.exited"),+ Stream.runCollect,+ Effect.forkChild,+ );+ yield* adapter.startSession({+ threadId,+ provider: ProviderDriverKind.make("cursor"),+ cwd: process.cwd(),+ runtimeMode: "full-access",+ });+ const error = yield* adapter+ .sendTurn({ threadId, input: "continue", attachments: [] })+ .pipe(Effect.flip);+ assert.equal(error._tag, "ProviderAdapterRequestError");+ if (error._tag === "ProviderAdapterRequestError") {+ assert.equal(error.detail, "Cursor reported a transport failure.");+ assert.equal(error.cause, "Error: RetriableError: WritableIterable is closed");+ }+ yield* adapter.stopSession(threadId);+ const runtimeEvents = yield* Fiber.join(runtimeEventsFiber);+ assert.isFalse(runtimeEvents.some((event) => event.type === "turn.completed"));+ }),+ );+it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>Effect.gen(function* () {const adapter = yield* CursorAdapter;diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.tsindex 1ed9648a50b..1a77f964aac 100644--- a/apps/server/src/provider/Layers/CursorAdapter.ts+++ b/apps/server/src/provider/Layers/CursorAdapter.ts@@ -67,6 +67,7 @@ import {} from "../acp/AcpRuntimeModel.ts";import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";import { applyCursorAcpModelSelection, makeCursorAcpRuntime } from "../acp/CursorAcpSupport.ts";+import { CursorTransportFailure } from "../acp/CursorTransportFailure.ts";import {CursorAskQuestionRequest,CursorCreatePlanRequest,@@ -144,6 +145,7 @@ interface CursorSessionContext {* >0 means a turn is actively running, so a new sendTurn is a steer that* continues it, and only the last remaining prompt settles the turn. */promptsInFlight: number;+ assistantReply: CursorTransportFailure;stopped: boolean;}@@ -788,6 +790,7 @@ export function makeCursorAdapter(activeTurnId: undefined,cursorSkillNames: undefined,promptsInFlight: 0,+ assistantReply: new CursorTransportFailure(),stopped: false,};@@ -801,6 +804,7 @@ export function makeCursorAdapter(case "ModeChanged":return;case "AssistantItemStarted":+ ctx.assistantReply = new CursorTransportFailure();yield* offerRuntimeEvent(makeAcpAssistantItemEvent({stamp: yield* makeEventStamp(),@@ -858,6 +862,7 @@ export function makeCursorAdapter();return;case "ContentDelta":+ ctx.assistantReply.push(event.text);yield* logNative(ctx.threadId,"session/update",@@ -957,6 +962,7 @@ export function makeCursorAdapter(ctx.activeTurnId = turnId;if (steeringTurnId === undefined) {ctx.lastPlanFingerprint = undefined;+ ctx.assistantReply = new CursorTransportFailure();}ctx.session = {...ctx.session,@@ -1061,6 +1067,17 @@ export function makeCursorAdapter(),);+ yield* ctx.acp.drainEvents;+ const failure = ctx.assistantReply.failure;+ if (ctx.promptsInFlight === 1 && result.stopReason !== "cancelled" && failure) {+ return yield* new ProviderAdapterRequestError({+ provider: PROVIDER,+ method: "session/prompt",+ detail: "Cursor reported a transport failure.",+ cause: failure,+ });+ }+const turnRecord = ctx.turns.find((turn) => turn.id === turnId);if (turnRecord) {turnRecord.items.push({ prompt: promptParts, result });diff --git a/apps/server/src/provider/acp/CursorTransportFailure.test.ts b/apps/server/src/provider/acp/CursorTransportFailure.test.tsnew file mode 100644index 00000000000..dcd4f9996bd--- /dev/null+++ b/apps/server/src/provider/acp/CursorTransportFailure.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from "vite-plus/test";++import { CursorTransportFailure } from "./CursorTransportFailure.ts";++const diagnostic = "Error: RetriableError: WritableIterable is closed";++function failureFor(chunks: string[]) {+ const reply = new CursorTransportFailure();+ for (const chunk of chunks) reply.push(chunk);+ return reply.failure;+}++describe("CursorTransportFailure", () => {+ it.each([+ diagnostic,+ "Error: ConnectError: [unavailable] transport closed",+ "Error: ConnectError: [aborted] aborted",+ "Error: ConnectError: [deadline_exceeded] timed out",+ "Something went wrong communicating with the server. Please try again.",+ ])("recognizes a terminal diagnostic: %s", (message) => {+ expect(failureFor([message])).toBe(message);+ expect(failureFor([...message])).toBe(message);+ });++ it("recognizes a standalone failure with a stack trace", () => {+ expect(failureFor(["\n", diagnostic, "\n at send (cli.js:1:2)\n\n"])).toBe(diagnostic);+ });++ it.each([+ "The error was " + diagnostic,+ "This is an example of a transport error:\n" + diagnostic,+ "I inspected the files.\n" + diagnostic,+ "> " + diagnostic,+ " " + diagnostic,+ "```text\n" + diagnostic + "\n```",+ "~~~\n" + diagnostic + "\n~~~",+ diagnostic + "\nThis is an example of a transport error.",+ "Error: ConnectError: [unauthenticated] sign in",+ "Error: ConnectError: [permission_denied] subscription required",+ "Error: HTTP 500 from the application being debugged",+ ])("preserves prose, code and non-transport errors: %s", (message) => {+ expect(failureFor([...message])).toBeUndefined();+ });++ it("tracks fences across long lines without retaining the answer", () => {+ expect(failureFor(["```\n", "x".repeat(100_000), "\n", diagnostic])).toBeUndefined();+ expect(failureFor(["```", "x".repeat(100_000), "\n", diagnostic])).toBeUndefined();+ expect(failureFor(["x".repeat(100_000), "\n", diagnostic])).toBeUndefined();+ });++ it("does not retain a previous failure after new output", () => {+ const reply = new CursorTransportFailure();+ reply.push(diagnostic);+ expect(reply.failure).toBe(diagnostic);+ reply.push("\nRecovered successfully.");+ expect(reply.failure).toBeUndefined();+ });+});diff --git a/apps/server/src/provider/acp/CursorTransportFailure.ts b/apps/server/src/provider/acp/CursorTransportFailure.tsnew file mode 100644index 00000000000..99765c74eb0--- /dev/null+++ b/apps/server/src/provider/acp/CursorTransportFailure.ts@@ -0,0 +1,51 @@+const maxLineLength = 4096;+const transportError =+ /^Error: (?:RetriableError: .+|ConnectError: \[(?:unavailable|aborted|deadline_exceeded)\].*)$/;+const serverError = "Something went wrong communicating with the server. Please try again.";++interface ReplyState {+ disqualified: boolean;+ failure: string | undefined;+}++function consumeLine(state: ReplyState, line: string) {+ if (state.disqualified) return;+ const text = line.trimEnd();+ if (transportError.test(text) || text === serverError) {+ state.failure = text;+ } else if (text.trim() !== "" && !(state.failure && /^\s+at\s/.test(text))) {+ // An explanation or code sample can quote the same diagnostic. Only+ // classify an assistant item consisting entirely of a transport dump.+ state.disqualified = true;+ state.failure = undefined;+ }+}++/** Tracks a standalone Cursor diagnostic without retaining an entire streamed answer. */+export class CursorTransportFailure {+ private state: ReplyState = { disqualified: false, failure: undefined };+ private line = "";++ push(text: string) {+ for (const [index, part] of text.split("\n").entries()) {+ if (this.state.disqualified) return;+ if (index > 0) {+ consumeLine(this.state, this.line);+ this.line = "";+ }+ if (this.line.length + part.length > maxLineLength) {+ this.state.disqualified = true;+ this.state.failure = undefined;+ this.line = "";+ return;+ }+ this.line += part;+ }+ }++ get failure() {+ const state = { ...this.state };+ consumeLine(state, this.line);+ return state.failure;+ }+}