From b261f1c530622a2c30d684cd2ee7b7dc159f7af7 Mon Sep 17 00:00:00 2001 From: naki Date: Wed, 28 Oct 2026 19:28:54 +0530 Subject: [PATCH] fix(cursor): handle omitted subagent result fields Fixes #26486 --- .../src/server/CursorAgentSdk.test.ts | 93 +++++++++++++++ .../src/server/CursorAgentSdk.ts | 22 ++-- .../src/server/adapter.test.ts | 81 ++++++++++++- .../provider-cursor/src/server/adapter.ts | 107 ++++++++++++------ 4 files changed, 259 insertions(+), 44 deletions(-) diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts index d715766a309bc..55f4e7d7f76b4 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.test.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.test.ts @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import { vi } from "vite-plus/test"; @@ -22,7 +23,9 @@ const cursorSdkMock = vi.hoisted(() => { model: { id: "default" }, durationMs: 1, })); + let rejectRunWait: ((cause: unknown) => void) | undefined; const runCancel = vi.fn(async () => {}); + let onDelta: ((input: { readonly update: unknown }) => Promise) | undefined; const agentClose = vi.fn(() => { closeExecutionOrder.push("sdk:agent.close"); if (agentCloseFailure !== undefined) { @@ -35,6 +38,7 @@ const cursorSdkMock = vi.hoisted(() => { options: { readonly onDelta?: (input: { readonly update: unknown }) => Promise }, ) => { runOperations.push("run.start"); + onDelta = options.onDelta; if (staleRunActive) { throw new Error("Agent agent-cursor-agent-sdk-test already has active run"); } @@ -84,6 +88,16 @@ const cursorSdkMock = vi.hoisted(() => { runCancel, runWait, send, + deliverDelta: async (update: unknown) => onDelta?.({ update }), + setRunWaitPending: () => { + runWait.mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectRunWait = reject; + }), + ); + }, + rejectRunWait: (cause: unknown) => rejectRunWait?.(cause), setAgentCloseFailure: (failure: unknown) => { agentCloseFailure = failure; }, @@ -132,6 +146,85 @@ const layerTest = CursorAgentSdk.layer.pipe( ); describe("CursorAgentSdkRunner", () => { + it.effect("keeps dispatching after a callback failure and reports its method", () => + Effect.gen(function* () { + const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; + const session = yield* runner.open({ + operation: "create", + options: { model: { id: "default" }, mode: "agent", local: { cwd: process.cwd() } }, + threadId: ThreadId.make("thread-cursor-agent-sdk-callback-failure-test"), + providerSessionId: ProviderSessionId.make( + "provider-session-cursor-agent-sdk-callback-failure-test", + ), + }); + const received: Array = []; + const run = yield* session.send({ + message: "continue", + onDelta: (update) => { + if (update.type === "text-delta" && update.text === "bad") { + return Effect.die(new Error("local callback failed")); + } + if (update.type === "text-delta") received.push(update.text); + return Effect.void; + }, + }); + + yield* Effect.promise(() => cursorSdkMock.deliverDelta({ type: "text-delta", text: "bad" })); + yield* Effect.promise(() => + cursorSdkMock.deliverDelta({ type: "text-delta", text: "after failure" }), + ); + const error = yield* run.wait.pipe(Effect.flip); + + assert.deepEqual(received, ["after failure"]); + assert.equal(error.method, "run.onDelta"); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("waits for an in-flight callback before classifying a run.wait failure", () => + Effect.gen(function* () { + cursorSdkMock.setRunWaitPending(); + cursorSdkMock.runCancel.mockClear(); + let startCallback!: () => void; + const callbackStarted = new Promise((resolve) => { + startCallback = resolve; + }); + let failCallback!: () => void; + const runner = yield* CursorAgentSdk.CursorAgentSdkRunner; + const session = yield* runner.open({ + operation: "create", + options: { model: { id: "default" }, mode: "agent", local: { cwd: process.cwd() } }, + threadId: ThreadId.make("thread-cursor-agent-sdk-wait-race-test"), + providerSessionId: ProviderSessionId.make( + "provider-session-cursor-agent-sdk-wait-race-test", + ), + }); + const run = yield* session.send({ + message: "continue", + onDelta: (update) => { + if (update.type !== "text-delta" || update.text !== "pending") return Effect.void; + return Effect.promise( + () => + new Promise((_resolve, reject) => { + failCallback = () => reject(new Error("local callback failed")); + startCallback(); + }), + ); + }, + }); + + const wait = yield* run.wait.pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + const delivery = cursorSdkMock.deliverDelta({ type: "text-delta", text: "pending" }); + yield* Effect.promise(() => callbackStarted); + yield* Effect.sync(() => cursorSdkMock.rejectRunWait(new Error("SDK wait failed"))); + yield* Effect.sync(() => failCallback()); + yield* Effect.promise(() => delivery); + + const error = yield* Fiber.join(wait); + assert.equal(error.method, "run.onDelta"); + assert.equal(cursorSdkMock.runCancel.mock.calls.length, 0); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("retries a resumed send after cancelling its abandoned local run", () => Effect.gen(function* () { cursorSdkMock.runOperations.length = 0; diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index 7f0decb49af3f..0560c562868db 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -421,9 +421,6 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu const dispatchUpdate = (update: InteractionUpdate): Promise => { callbackChain = callbackChain .then(() => { - if (callbackFailure !== undefined) { - return; - } return Effect.runPromiseWith(context)( log({ direction: "incoming", @@ -510,14 +507,25 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu agentId: run.agentId, wait: Effect.tryPromise({ try: async () => { - const result = await run.wait(); - await callbackChain; + const [runResult] = await Promise.allSettled([run.wait()]); + let completedCallbacks: Promise; + do { + completedCallbacks = callbackChain; + await completedCallbacks; + } while (callbackChain !== completedCallbacks); if (callbackFailure !== undefined) { throw callbackFailure.cause; } - return result; + if (runResult.status === "rejected") { + throw runResult.reason; + } + return runResult.value; }, - catch: (cause) => runnerError(cause, "run.wait"), + catch: (cause) => + runnerError( + callbackFailure?.cause ?? cause, + callbackFailure === undefined ? "run.wait" : "run.onDelta", + ), }).pipe( Effect.tap((result) => log({ diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 7ab3aa8c1a3be..2d58b6e24ca2a 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -586,7 +586,7 @@ describe("CursorAdapterV2", () => { ), ); - it.effect("projects Cursor directory trees and lint diagnostics as file search results", () => + it.effect("projects Cursor directory trees after a buffered callback failure", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -606,7 +606,53 @@ describe("CursorAdapterV2", () => { fullSubtreeExtensionCounts: {}, numFiles: 0, }; + const omittedChildrenPath = path.join(workspace, "empty-json"); + const omittedRootPath = path.join(workspace, "missing-json-root"); + const wrappedLs = nestedToolCallFromEnvelope({ + toolCallId: "ls-omitted-children", + lsToolCall: { + args: { path: omittedChildrenPath }, + result: { + success: { + directoryTreeRoot: { absPath: omittedChildrenPath }, + }, + }, + }, + }); + const wrappedLsWithoutRoot = nestedToolCallFromEnvelope({ + toolCallId: "ls-omitted-root", + lsToolCall: { + args: { path: omittedRootPath }, + result: { success: {} }, + }, + }); + const wrappedLints = nestedToolCallFromEnvelope({ + toolCallId: "lints-omitted-arrays", + readLintsToolCall: { args: {}, result: { success: {} } }, + }); + const wrappedMcp = nestedToolCallFromEnvelope({ + toolCallId: "mcp-omitted-content", + mcpToolCall: { + args: { providerIdentifier: "empty", toolName: "tool" }, + result: { success: {} }, + }, + }); + const wrappedTodos = nestedToolCallFromEnvelope({ + toolCallId: "todos-omitted", + updateTodosToolCall: { args: {}, result: { success: {} } }, + }); + assert.isDefined(wrappedLs); + assert.isDefined(wrappedLsWithoutRoot); + assert.isDefined(wrappedLints); + assert.isDefined(wrappedMcp); + assert.isDefined(wrappedTodos); const updates: ReadonlyArray = [ + { + type: "tool-call-completed", + modelCallId: "native-model-call", + callId: "malformed-early-call", + toolCall: null, + } as unknown as InteractionUpdate, ...(["tool-call-started", "tool-call-completed"] as const).map((type) => ({ type, modelCallId: "native-model-call", @@ -684,6 +730,21 @@ describe("CursorAdapterV2", () => { }, }, }, + { + type: "tool-call-completed", + modelCallId: "native-model-call", + callId: wrappedLs.callId, + toolCall: wrappedLs.toolCall, + } as unknown as InteractionUpdate, + ...[wrappedLsWithoutRoot, wrappedLints, wrappedMcp, wrappedTodos].map( + (wrapped) => + ({ + type: "tool-call-completed" as const, + modelCallId: "native-model-call", + callId: wrapped.callId, + toolCall: wrapped.toolCall, + }) as unknown as InteractionUpdate, + ), { type: "tool-call-completed", modelCallId: "native-model-call", @@ -884,6 +945,9 @@ describe("CursorAdapterV2", () => { Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); + const terminal = events.find((event) => event.type === "turn.terminal"); + assert.equal(terminal?.status, "failed"); + assert.equal(terminal?.failure?.class, "provider_error"); const mcpItems = events.flatMap((event) => event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" && @@ -944,6 +1008,21 @@ describe("CursorAdapterV2", () => { status: "completed", results: undefined, }, + { + pattern: omittedChildrenPath, + status: "completed", + results: undefined, + }, + { + pattern: omittedRootPath, + status: "completed", + results: undefined, + }, + { + pattern: "", + status: "completed", + results: undefined, + }, { pattern: path.join(workspace, "missing"), status: "failed", diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 915c646be3001..d67fe9cfb9288 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -31,6 +31,7 @@ import { type ThreadId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -382,12 +383,12 @@ function cursorToolOutput(toolCall: ToolCall): unknown { function cursorToolOutputText(toolCall: ToolCall): string { if (toolCall.type === "shell" && toolCall.result?.status === "success") { - return [toolCall.result.value.stdout, toolCall.result.value.stderr] + return [toolCall.result.value.stdout ?? "", toolCall.result.value.stderr ?? ""] .filter((part) => part.length > 0) .join("\n"); } if (toolCall.type === "mcp" && toolCall.result?.status === "success") { - return toolCall.result.value.content + return (toolCall.result.value.content ?? []) .flatMap((part) => (part.text === undefined ? [] : [part.text.text])) .join("\n"); } @@ -414,7 +415,7 @@ function cursorToolFileName(toolCall: ToolCall): string { case "read": case "edit": case "ls": - return toolCall.args.path; + return toolCall.args.path ?? ""; case "generateImage": return toolCall.args.filePath ?? "generated-image"; default: @@ -425,15 +426,15 @@ function cursorToolFileName(toolCall: ToolCall): string { function cursorToolSearchPattern(toolCall: ToolCall): string | undefined { switch (toolCall.type) { case "glob": - return toolCall.args.globPattern; + return toolCall.args.globPattern ?? "**/*"; case "grep": - return toolCall.args.pattern; + return toolCall.args.pattern ?? ""; case "semSearch": - return toolCall.args.query; + return toolCall.args.query ?? ""; case "ls": - return toolCall.args.path; + return toolCall.args.path ?? ""; case "readLints": - return toolCall.args.paths.join(", "); + return (toolCall.args.paths ?? []).join(", "); default: return undefined; } @@ -445,12 +446,15 @@ type CursorLsDirectoryNode = Extract< >["value"]["directoryTreeRoot"]; function cursorLsSearchResults( - node: CursorLsDirectoryNode, + node: CursorLsDirectoryNode | undefined, path: Path.Path, ): ReadonlyArray<{ readonly fileName: string }> { + if (node === undefined) return []; return [ - ...node.childrenFiles.map((file) => ({ fileName: path.join(node.absPath, file.name) })), - ...node.childrenDirs.flatMap((child) => cursorLsSearchResults(child, path)), + ...(node.childrenFiles ?? []) + .filter((file) => typeof file.name === "string" && file.name.length > 0) + .map((file) => ({ fileName: path.join(node.absPath ?? "", file.name) })), + ...(node.childrenDirs ?? []).flatMap((child) => cursorLsSearchResults(child, path)), ]; } @@ -468,19 +472,19 @@ function cursorToolSearchResults( } switch (toolCall.type) { case "glob": - return toolCall.result.value.files.map((fileName) => ({ fileName })); + return (toolCall.result.value.files ?? []).map((fileName) => ({ fileName })); case "grep": return Object.values(toolCall.result.value.workspaceResults ?? {}).flatMap((result) => { if (result.type === "files") { - return result.output.files.map((fileName) => ({ fileName })); + return (result.output?.files ?? []).map((fileName) => ({ fileName })); } if (result.type === "count") { - return result.output.counts.map((entry) => ({ + return (result.output?.counts ?? []).map((entry) => ({ fileName: entry.file, preview: `${entry.count} matches`, })); } - return result.output.matches.map((entry) => ({ + return (result.output?.matches ?? []).map((entry) => ({ fileName: entry.file, ...(entry.lineNumber === undefined ? {} : { line: entry.lineNumber }), preview: entry.line, @@ -489,13 +493,13 @@ function cursorToolSearchResults( case "ls": return cursorLsSearchResults(toolCall.result.value.directoryTreeRoot, path); case "readLints": - return toolCall.result.value.fileDiagnostics.flatMap((file) => - file.diagnostics.map((diagnostic) => { + return (toolCall.result.value.fileDiagnostics ?? []).flatMap((file) => + (file.diagnostics ?? []).map((diagnostic) => { const line = diagnostic.range?.start?.line; const character = diagnostic.range?.start?.character; const hasLine = typeof line === "number" && Number.isInteger(line) && line >= 0; return { - fileName: file.path, + fileName: file.path ?? "", ...(hasLine ? { line: line + 1 } : {}), ...(hasLine && typeof character === "number" && @@ -503,7 +507,7 @@ function cursorToolSearchResults( character >= 0 ? { column: character + 1 } : {}), - preview: diagnostic.message, + preview: diagnostic.message ?? "", }; }), ); @@ -511,7 +515,7 @@ function cursorToolSearchResults( return [ { fileName: "semantic-search", - preview: toolCall.result.value.results, + preview: toolCall.result.value.results ?? "", }, ]; default: @@ -523,12 +527,13 @@ function cursorTodoSteps( toolCall: Extract, ): ReadonlyArray { const todos = - toolCall.result?.status === "success" ? toolCall.result.value.todos : toolCall.args.todos; + (toolCall.result?.status === "success" ? toolCall.result.value.todos : toolCall.args.todos) ?? + []; return todos - .filter((todo) => todo.status !== "cancelled" && todo.content.trim().length > 0) + .filter((todo) => todo.status !== "cancelled" && (todo.content ?? "").trim().length > 0) .map((todo, index) => ({ id: `todo-${index + 1}`, - text: todo.content, + text: todo.content ?? "", status: todo.status === "inProgress" ? "running" @@ -1227,10 +1232,10 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( turnItem = { ...base, type: "command_execution", - input: toolCall.args.command, + input: toolCall.args.command ?? "", ...(outputText.length === 0 ? {} : { output: outputText }), ...(toolCall.result?.status === "success" - ? { exitCode: toolCall.result.value.exitCode } + ? { exitCode: toolCall.result.value.exitCode ?? 0 } : {}), }; break; @@ -1259,13 +1264,13 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( : toolCall.result?.status === "error" && outputText.trim().length > 0 ? { diffStr: outputText } : {}), - ...(toolCall.type === "write" ? { newStr: toolCall.args.fileText } : {}), + ...(toolCall.type === "write" ? { newStr: toolCall.args.fileText ?? "" } : {}), }; break; case "read": turnItem = { ...base, - title: formatReadToolLabel(toolCall.args.path), + title: formatReadToolLabel(toolCall.args.path ?? ""), type: "dynamic_tool", toolName: "Read", input: toolCall.args, @@ -1311,8 +1316,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( type: "dynamic_tool", ...(toolCall.type === "mcp" ? mcpToolPresentation({ - serverName: toolCall.args.providerIdentifier, - toolName: toolCall.args.toolName, + serverName: toolCall.args.providerIdentifier ?? "mcp", + toolName: toolCall.args.toolName ?? "unknown", }) : {}), toolName: cursorToolName(toolCall), @@ -1845,7 +1850,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( yield* emitPlanArtifacts({ context, callId: update.callId, - markdown: toolCall.args.plan, + markdown: toolCall.args.plan ?? "", completed, failed: completed && cursorToolFailed(toolCall), }); @@ -2279,6 +2284,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const message = yield* resolveUserMessage(turnInput, mcpServers); const pendingUpdates: Array = []; let context: ActiveCursorTurn | null = null; + let pendingUpdateFailure: unknown; // MCP send overrides replace the ambient servers loaded when the agent opens. const sdkRun = yield* agent.session .send({ @@ -2346,12 +2352,31 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }, }); for (const update of pendingUpdates) { - yield* handleInteractionUpdate(context, update); + yield* handleInteractionUpdate(context, update).pipe( + Effect.catchCause((cause) => + Effect.sync(() => { + pendingUpdateFailure ??= Cause.squash(cause); + }), + ), + ); } yield* sdkRun.wait.pipe( Effect.flatMap((result) => Effect.gen(function* () { + if (pendingUpdateFailure !== undefined && !context.interrupted) { + const cause = pendingUpdateFailure; + yield* finalizeTurn({ + context, + status: "failed", + failure: makeProviderFailure({ + cause, + message: cause instanceof Error ? cause.message : undefined, + class: "provider_error", + }), + }); + return; + } if ( context !== null && context.assistant.nextSegment === 0 && @@ -2408,6 +2433,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( Effect.catch((cause) => Effect.gen(function* () { if (context !== null) { + const callbackFailure = pendingUpdateFailure; + const failureCause = callbackFailure ?? cause; yield* finalizeTurn({ context, status: context.interrupted ? "interrupted" : "failed", @@ -2415,11 +2442,19 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( ? {} : { failure: makeProviderFailure({ - cause, - message: CursorAgentSdk.isCursorAgentSdkRunnerError(cause) - ? CursorAgentSdk.cursorSdkFailureMessage(cause) - : undefined, - class: "transport_error", + cause: failureCause, + message: + callbackFailure instanceof Error + ? callbackFailure.message + : CursorAgentSdk.isCursorAgentSdkRunnerError(failureCause) + ? CursorAgentSdk.cursorSdkFailureMessage(failureCause) + : undefined, + class: + callbackFailure !== undefined || + (CursorAgentSdk.isCursorAgentSdkRunnerError(cause) && + cause.method === "run.onDelta") + ? "provider_error" + : "transport_error", }), }), });