Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions packages/provider-cursor/src/server/CursorAgentSdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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<void>) | undefined;
const agentClose = vi.fn(() => {
closeExecutionOrder.push("sdk:agent.close");
if (agentCloseFailure !== undefined) {
Expand All @@ -35,6 +38,7 @@ const cursorSdkMock = vi.hoisted(() => {
options: { readonly onDelta?: (input: { readonly update: unknown }) => Promise<void> },
) => {
runOperations.push("run.start");
onDelta = options.onDelta;
if (staleRunActive) {
throw new Error("Agent agent-cursor-agent-sdk-test already has active run");
}
Expand Down Expand Up @@ -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;
},
Expand Down Expand Up @@ -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<string> = [];
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<void>((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<void>((_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;
Expand Down
22 changes: 15 additions & 7 deletions packages/provider-cursor/src/server/CursorAgentSdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,9 +421,6 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
const dispatchUpdate = (update: InteractionUpdate): Promise<void> => {
callbackChain = callbackChain
.then(() => {
if (callbackFailure !== undefined) {
return;
}
return Effect.runPromiseWith(context)(
log({
direction: "incoming",
Expand Down Expand Up @@ -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<void>;
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({
Expand Down
81 changes: 80 additions & 1 deletion packages/provider-cursor/src/server/adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<InteractionUpdate> = [
{
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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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" &&
Expand Down Expand Up @@ -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",
Expand Down
Loading
Loading