GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(cursor): fail an unlabeled stream EOF that truncates an open tool… · lidge-jun/opencodex@54f68da

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src/adapters/cursor
    • cursor-errors.ts
    • live-transport.ts
  • tests
    • cursor-eof-terminal.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/adapters/cursor/cursor-errors.ts‎

Copy file name to clipboardExpand all lines: src/adapters/cursor/cursor-errors.ts
+19Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,25 @@ function errorCode(value: unknown): string {
2727
* True when Cursor intentionally cancelled the HTTP/2 stream after a client-tool suspend.
2828
* These are expected between multi-turn Responses bridge cycles, not upstream failures.
2929
*/
30+
/**
31+
* A Cursor stream that ended cleanly at the HTTP/2 layer while a client tool call was still
32+
* open — no `turnEnded`, no error trailer, just EOF. The call's buffered arguments are lost,
33+
* so the turn is truncated: reporting it as success would hand Codex a turn whose tool call
34+
* silently never happened. Not retryable — the request is committed once the session connects.
35+
*/
36+
export class CursorStreamTruncatedError extends Error {
37+
constructor(
38+
public readonly openCallIds: readonly string[],
39+
public readonly framesReceived: number,
40+
) {
41+
super(
42+
`Cursor stream ended without terminating the turn; ${openCallIds.length} tool call(s) left incomplete `
43+
+ `(${openCallIds.join(", ")}) after ${framesReceived} frame(s). Arguments may be truncated; the call was not committed.`,
44+
);
45+
this.name = "CursorStreamTruncatedError";
46+
}
47+
}
48+
3049
export function isCursorBenignCancelError(value: unknown): boolean {
3150
const message = errorMessage(value).toLowerCase();
3251
const code = errorCode(value).toUpperCase();
Collapse file

‎src/adapters/cursor/live-transport.ts‎

Copy file name to clipboardExpand all lines: src/adapters/cursor/live-transport.ts
+21-1Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import {
4848
type InteractionResponse,
4949
} from "./gen/agent_pb";
5050
import { debugProviderDiagnostic } from "../../lib/debug";
51-
import { classifyCursorError, isCursorBenignCancelError, safeCursorErrorMessage } from "./cursor-errors";
51+
import { classifyCursorError, CursorStreamTruncatedError, isCursorBenignCancelError, safeCursorErrorMessage } from "./cursor-errors";
5252
import { mcpArgsFromToolCall } from "./protobuf-events";
5353
import { OCX_RESPONSES_TOOL_PROVIDER } from "./tool-definitions";
5454
import {
@@ -410,6 +410,12 @@ class LiveCursorTransport implements CursorTransport {
410410
private firstFrameTimer?: ReturnType<typeof setTimeout>;
411411
private committed = false;
412412
private expectedClose = false;
413+
/**
414+
* True once a terminal (`done` or `error`) has been admitted to the outbound queue. Read only
415+
* by the EOF branch below: after a mapper error the bridge has already failed the turn, so
416+
* failing again on EOF would add a duplicate adapter error for no benefit.
417+
*/
418+
private emittedTerminal = false;
413419
private pendingFinalize?: ReturnType<typeof setTimeout>;
414420
private readonly clientToolFinalizeGraceMs: number;
415421
private activeClientToolFinalizeGraceMs: number;
@@ -531,6 +537,7 @@ class LiveCursorTransport implements CursorTransport {
531537
const push = (message: CursorServerMessage) => {
532538
const bytes = new TextEncoder().encode(JSON.stringify(message)).byteLength;
533539
this.reserveTransportBytes(bytes);
540+
if (message.type === "done" || message.type === "error") this.emittedTerminal = true;
534541
queue.push({ message, bytes });
535542
wake();
536543
};
@@ -769,6 +776,7 @@ class LiveCursorTransport implements CursorTransport {
769776
): void {
770777
this.turnStartedAt = Date.now();
771778
this.framesReceived = 0;
779+
this.emittedTerminal = false;
772780
this.firstFrameAt = undefined;
773781
this.firstFrameLogged = false;
774782
const dialHost = cursorHostLabel(this.input.provider.baseUrl || "https://api2.cursor.sh");
@@ -1026,6 +1034,18 @@ class LiveCursorTransport implements CursorTransport {
10261034
settler.settleFail(new Error("Cursor stream ended before any response frame (unexpected EOF)"));
10271035
return;
10281036
}
1037+
// A framed stream that ends without ANY terminal, while a client tool call is still open,
1038+
// is a truncated turn — not a success. The call was deferred (nothing was emitted for it
1039+
// at `toolCallStarted`), so a graceful finish drops it silently: streaming reports
1040+
// `response.incomplete`, but the non-streaming path defaults to `completed` and hands back
1041+
// a turn whose tool call simply vanished. `expectedClose` (client-tool suspend) and an
1042+
// already-emitted terminal are both legitimate and stay graceful.
1043+
if (!this.expectedClose && !state.terminated && !this.emittedTerminal && state.openToolCalls.size > 0) {
1044+
const openCallIds = [...state.openToolCalls.keys()];
1045+
releaseBacklogLease();
1046+
settler.settleFail(new CursorStreamTruncatedError(openCallIds, this.framesReceived));
1047+
return;
1048+
}
10291049
releaseBacklogLease();
10301050
settler.settleFinish();
10311051
}, (err) => {
Collapse file

‎tests/cursor-eof-terminal.test.ts‎

Copy file name to clipboard
+171Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
import http2 from "node:http2";
2+
import { create, toBinary } from "@bufbuild/protobuf";
3+
import { describe, expect, test } from "bun:test";
4+
import {
5+
AgentServerMessageSchema,
6+
InteractionUpdateSchema,
7+
McpArgsSchema,
8+
McpToolCallSchema,
9+
ToolCallSchema,
10+
ToolCallStartedUpdateSchema,
11+
TurnEndedUpdateSchema,
12+
} from "../src/adapters/cursor/gen/agent_pb";
13+
import { encodeConnectFrame } from "../src/adapters/cursor/framing";
14+
import { createLiveCursorTransport } from "../src/adapters/cursor/live-transport";
15+
import { createTestTranslatorBudget } from "./helpers/translator-budget";
16+
import type { CursorRunRequest, CursorServerMessage } from "../src/adapters/cursor/types";
17+
18+
const PROVIDER = "opencodex-responses";
19+
20+
async function withH2Server<T>(
21+
handler: (stream: http2.ServerHttp2Stream) => void,
22+
run: (baseUrl: string) => Promise<T>,
23+
): Promise<T> {
24+
const server = http2.createServer();
25+
server.on("stream", handler);
26+
await new Promise<void>((resolve, reject) => {
27+
const onError = (error: Error) => reject(error);
28+
server.once("error", onError);
29+
server.listen(0, "127.0.0.1", () => {
30+
server.off("error", onError);
31+
resolve();
32+
});
33+
});
34+
const address = server.address();
35+
if (!address || typeof address === "string") throw new Error("HTTP/2 fixture did not bind a TCP port");
36+
try {
37+
return await run(`http://127.0.0.1:${address.port}`);
38+
} finally {
39+
await new Promise<void>(resolve => server.close(() => resolve()));
40+
}
41+
}
42+
43+
function toolCallStartedFrame(callId: string, toolName: string): Uint8Array {
44+
const toolCall = create(ToolCallSchema, {
45+
tool: {
46+
case: "mcpToolCall",
47+
value: create(McpToolCallSchema, {
48+
args: create(McpArgsSchema, { name: toolName, toolName, toolCallId: callId, providerIdentifier: PROVIDER }),
49+
}),
50+
},
51+
});
52+
const message = create(AgentServerMessageSchema, {
53+
message: {
54+
case: "interactionUpdate",
55+
value: create(InteractionUpdateSchema, {
56+
message: {
57+
case: "toolCallStarted",
58+
value: create(ToolCallStartedUpdateSchema, { callId, modelCallId: callId, toolCall }),
59+
},
60+
}),
61+
},
62+
});
63+
return encodeConnectFrame(toBinary(AgentServerMessageSchema, message));
64+
}
65+
66+
function turnEndedFrame(): Uint8Array {
67+
const message = create(AgentServerMessageSchema, {
68+
message: {
69+
case: "interactionUpdate",
70+
value: create(InteractionUpdateSchema, {
71+
message: { case: "turnEnded", value: create(TurnEndedUpdateSchema, {}) },
72+
}),
73+
},
74+
});
75+
return encodeConnectFrame(toBinary(AgentServerMessageSchema, message));
76+
}
77+
78+
function emptyFrame(): Uint8Array {
79+
return encodeConnectFrame(toBinary(AgentServerMessageSchema, create(AgentServerMessageSchema, {})));
80+
}
81+
82+
function runRequest(tools?: CursorRunRequest["tools"]): CursorRunRequest {
83+
return {
84+
modelId: "composer-2",
85+
conversationId: "cursor_eof_terminal_test",
86+
system: [],
87+
messages: [{ role: "user", content: "hello" }],
88+
...(tools ? { tools } : {}),
89+
} as CursorRunRequest;
90+
}
91+
92+
const APPLY_PATCH_TOOL = [{
93+
name: "apply_patch",
94+
description: "apply a patch",
95+
parameters: { type: "object", properties: { input: { type: "string" } }, required: ["input"] },
96+
freeform: true,
97+
}] as unknown as CursorRunRequest["tools"];
98+
99+
async function drain(baseUrl: string, request: CursorRunRequest): Promise<{
100+
messages: CursorServerMessage[];
101+
failure?: Error;
102+
}> {
103+
const transport = createLiveCursorTransport({
104+
provider: { adapter: "cursor", baseUrl, apiKey: "test-token" },
105+
translatorBudget: createTestTranslatorBudget(),
106+
firstFrameTimeoutMs: 2_000,
107+
});
108+
const messages: CursorServerMessage[] = [];
109+
let failure: Error | undefined;
110+
try {
111+
for await (const message of transport.run(request)) messages.push(message);
112+
} catch (err) {
113+
failure = err instanceof Error ? err : new Error(String(err));
114+
} finally {
115+
await transport.close?.();
116+
}
117+
return { messages, failure };
118+
}
119+
120+
function respondWith(frames: Uint8Array[]): (stream: http2.ServerHttp2Stream) => void {
121+
return stream => {
122+
stream.on("error", () => {});
123+
stream.respond({ ":status": 200, "content-type": "application/connect+proto" });
124+
for (const frame of frames) stream.write(Buffer.from(frame));
125+
stream.end();
126+
};
127+
}
128+
129+
describe("Cursor clean-EOF terminal gate", () => {
130+
test("EOF with an open tool call fails instead of finishing silently", async () => {
131+
await withH2Server(respondWith([toolCallStartedFrame("call_open_1", "apply_patch")]), async baseUrl => {
132+
const { messages, failure } = await drain(baseUrl, runRequest(APPLY_PATCH_TOOL));
133+
134+
expect(failure).toBeDefined();
135+
expect(failure?.name).toBe("CursorStreamTruncatedError");
136+
expect(failure?.message).toContain("call_open_1");
137+
// The deferred call never became a committed tool call.
138+
expect(messages.some(m => m.type === "tool_call_end")).toBe(false);
139+
expect(messages.some(m => m.type === "done")).toBe(false);
140+
});
141+
});
142+
143+
test("EOF after a real turnEnded still finishes gracefully", async () => {
144+
await withH2Server(respondWith([emptyFrame(), turnEndedFrame()]), async baseUrl => {
145+
const { messages, failure } = await drain(baseUrl, runRequest());
146+
147+
expect(failure).toBeUndefined();
148+
expect(messages.some(m => m.type === "done")).toBe(true);
149+
});
150+
});
151+
152+
test("EOF with no open tool call keeps its existing graceful finish", async () => {
153+
await withH2Server(respondWith([emptyFrame()]), async baseUrl => {
154+
const { failure } = await drain(baseUrl, runRequest());
155+
156+
// Deliberately unchanged: the bridge turns a terminal-less EOF into
157+
// response.incomplete / adapter_eof. Only the open-call case is a failure.
158+
expect(failure).toBeUndefined();
159+
});
160+
});
161+
162+
test("a completed turn with no tool calls is unaffected by the gate", async () => {
163+
await withH2Server(respondWith([turnEndedFrame()]), async baseUrl => {
164+
const { messages, failure } = await drain(baseUrl, runRequest(APPLY_PATCH_TOOL));
165+
166+
expect(failure).toBeUndefined();
167+
expect(messages.some(m => m.type === "done")).toBe(true);
168+
});
169+
});
170+
});
171+

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.