cursor: cancel and clean up stateless Run transports (#130)

A Chat cancelled while its Run opens is closed upstream, not left running.

Before, a cancel that landed after the HTTP/2 head arrived but before runOnce
subscribed to the signal was never seen ({once:true} listener added to an
already-aborted signal): the Run kept streaming upstream for nobody with its
5s heartbeat interval, and the session was never closed. open/openH2/openH1
now check the signal at each hand-off, close what arrived, and remove their
abort listeners; runOnce checks again before starting the heartbeat. HTTP/1's
write callback now waits for its BidiAppend, so backpressure and close see
the pending upload. A cancelled open answers 410 instead of 502.

Reviewed at a4e1db1b0d734c1a1b15c1fe0cafb0f9cb5313c0 (on main 5fc0a75):
- full `bun test` (isolated HOME/TMPDIR): 1288 pass, 0 fail (main: 1265/0);
  `bun scripts/check.mjs` ok.
- own plugin-level test (fake HTTP/2 session, abort a microtask after the
  200 head, upstream never ends): on main the request hangs, req never
  closed or destroyed; at this head it answers at once, req closed once.
- broke by hand: dropping runOnce's aborted check fails "the plugin: head
  abort ..."; reverting the H1 write callback to an immediate cb() fails
  three openH1 append tests.
- checked: destroying the H1 Duplex with a write in flight emits no
  'error' (bun and node); 410 "the request was cancelled" doesn't match
  magpie's modelRetired words.
Not tried: a real Cursor account or a real proxy (offline fakes only).
This commit is contained in:
nicegui
2026-10-15 04:13:01 +08:00
committed by GitHub
parent 5fc0a75292
commit ca6415f959
2 changed files with 422 additions and 18 deletions
+62 -18
View File
@@ -1666,12 +1666,21 @@ async function agentURL(tok, fresh) {
// connection that failed (refused, no network) or a stream the server
// refused leaves the next Run to try HTTP/2 again.
let h1Until = 0
const cancelledOpen = () => ({ error: { status: 410, message: "the request was cancelled" }, h2Failed: false })
async function open(base, headers, signal) {
if (signal?.aborted) return cancelledOpen()
if (Date.now() >= h1Until) {
const o = await openH2(base, headers, signal)
// The head can arrive just before abort, before this continuation owns it.
if (signal?.aborted) {
o.req?.close(http2.constants.NGHTTP2_CANCEL)
o.session?.destroy()
return cancelledOpen()
}
if (!o.h2Failed) return o
if (o.blocked) h1Until = Date.now() + H2.retryAfter
}
if (signal?.aborted) return cancelledOpen()
return openH1(headers, signal)
}
@@ -1702,6 +1711,7 @@ function h2Blocked(e) {
// than by being cancelled, says h2Failed, and blocked when h2Blocked says
// so of the failure.
function openH2(base, headers, signal) {
if (signal?.aborted) return Promise.resolve(cancelledOpen())
return new Promise((resolve) => {
const u = new URL(base)
const session = http2.connect(u.origin)
@@ -1710,9 +1720,11 @@ function openH2(base, headers, signal) {
if (done) return
done = true
clearTimeout(timer)
signal?.removeEventListener("abort", abort)
session.destroy()
resolve({ error: { status: 502, message: e?.message ?? String(e) }, h2Failed, blocked: h2Failed && h2Blocked(e) })
resolve({ error: { status: h2Failed ? 502 : 410, message: e?.message ?? String(e) }, h2Failed, blocked: h2Failed && h2Blocked(e) })
}
const abort = () => fail(new Error("the request was cancelled"), false)
const timer = setTimeout(() => fail(Object.assign(new Error(`no answer over HTTP/2 in ${H2.wait / 1000}s`), { h2Timeout: true })), H2.wait)
session.on("error", fail)
const req = session.request({
@@ -1728,9 +1740,11 @@ function openH2(base, headers, signal) {
if (done) return
done = true
clearTimeout(timer)
signal?.removeEventListener("abort", abort)
resolve({ session, req, status: Number(h[":status"]) })
})
signal?.addEventListener("abort", () => fail(new Error("the request was cancelled"), false), { once: true })
signal?.addEventListener("abort", abort, { once: true })
if (signal?.aborted) abort()
})
}
@@ -1750,23 +1764,29 @@ function connectCode(status) {
// ends the stream with Connect's end frame, which runOnce reads as the
// Run's own.
function openH1(headers, signal) {
if (signal?.aborted) return Promise.resolve(cancelledOpen())
const ac = new AbortController()
signal?.addEventListener("abort", () => ac.abort(), { once: true })
const id = headers["x-request-id"]
const h = { ...headers, "accept-encoding": "identity", "x-cursor-streaming": "true" }
let ended = false
let seq = 0
let chain = Promise.resolve()
let reader
const req = new Duplex({
read() {},
write(chunk, _enc, cb) {
// runOnce writes one whole frame each time
const msg = Buffer.from(chunk).subarray(5)
const n = seq++
chain = chain.then(() => (ended ? undefined : append(msg, n)))
cb()
// Keep the write buffered until its append finishes, so callbacks and
// drain reflect the pending upload rather than an unbounded promise chain.
append(msg, n).then(() => cb(), (e) => cb(e))
},
})
const cleanup = () => {
signal?.removeEventListener("abort", close)
ac.abort()
reader?.cancel().catch(() => {})
}
const end = (body) => {
if (ended || req.destroyed) return
ended = true
@@ -1774,7 +1794,7 @@ function openH1(headers, signal) {
f[0] = 2
req.push(f)
req.push(null)
ac.abort()
cleanup()
}
const failed = async (res) => {
const text = await res.text().catch(() => "")
@@ -1788,6 +1808,7 @@ function openH1(headers, signal) {
// (more time for a large one) ends the Run, as cursor-agent's
// bidi_append_deadline_exceeded does: the messages after it wait on it.
const append = async (msg, n) => {
if (ended || ac.signal.aborted) return
const body = pb().str(1, msg.toString("hex")).bytes(2, pb().str(1, id).done()).varint(3, n).done()
const ms = H1.appendWait + Math.ceil(body.length / 65536) * 1000
const deadline = AbortSignal.timeout(ms)
@@ -1798,6 +1819,7 @@ function openH1(headers, signal) {
body,
signal: AbortSignal.any([ac.signal, deadline]),
})
if (ended || ac.signal.aborted) { await res.body?.cancel().catch(() => {}); return }
if (!res.ok) return failed(res)
await res.arrayBuffer()
} catch (e) {
@@ -1806,6 +1828,16 @@ function openH1(headers, signal) {
end(JSON.stringify({ error: { code: "unavailable", message: `BidiAppend: ${e?.message ?? e}` } }))
}
}
const close = () => {
ended = true
cleanup()
req.destroy()
}
signal?.addEventListener("abort", close, { once: true })
if (signal?.aborted) {
close()
return Promise.resolve(cancelledOpen())
}
;(async () => {
try {
const res = await fetch(API + "/agent.v1.AgentService/RunSSE", {
@@ -1814,25 +1846,29 @@ function openH1(headers, signal) {
body: frame(pb().str(1, id).done()),
signal: ac.signal,
})
if (ended || ac.signal.aborted) { await res.body?.cancel().catch(() => {}); return }
if (!res.ok) return failed(res)
for await (const c of res.body) {
if (ended || req.destroyed) return
req.push(Buffer.from(c))
reader = res.body.getReader()
try {
while (!ended && !req.destroyed) {
const { value, done } = await reader.read()
if (done) break
if (!ended && !req.destroyed) req.push(Buffer.from(value))
}
} finally {
reader.releaseLock()
reader = undefined
}
if (!ended && !req.destroyed) {
ended = true
req.push(null)
cleanup()
}
} catch (e) {
if (!ac.signal.aborted) end(JSON.stringify({ error: { code: "unavailable", message: `RunSSE: ${e?.message ?? e}` } }))
}
})()
const close = () => {
ended = true
ac.abort()
req.destroy()
}
return Promise.resolve({ session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true })
return Promise.resolve(signal?.aborted ? cancelledOpen() : { session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true })
}
// runOnce is one Run of the chat on the agent API at base: an async
@@ -1865,14 +1901,15 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
if (o.error) return book.done(), o
const { session, req } = o
let closed = false
let heartbeat
const send = (msg) => {
if (!closed && !req.destroyed && req.writable) req.write(frame(msg))
}
const heartbeat = setInterval(() => send(pb().bytes(7, EMPTY).done()), 5000) // the client is still there, as the CLI says
const close = () => {
if (closed) return
closed = true
clearInterval(heartbeat)
signal?.removeEventListener("abort", close)
try {
req.close(http2.constants.NGHTTP2_CANCEL)
} catch {}
@@ -1880,6 +1917,13 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
setTimeout(() => session.destroy(), 1000).unref?.()
}
signal?.addEventListener("abort", close, { once: true })
// Abort can win after open's head check but before this Run takes ownership.
if (signal?.aborted) {
close()
book.done()
return cancelledOpen()
}
heartbeat = setInterval(() => send(pb().bytes(7, EMPTY).done()), 5000) // the client is still there, as the CLI says
send(first)
if (o.status < 200 || o.status > 299) {
const chunks = []
@@ -2397,4 +2441,4 @@ export async function CursorAuthPlugin() {
}
// for tests
export const _internal = { onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, H2, H1, h2Blocked, open, openH1, STEP_WAIT, stepUsage, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry }
export const _internal = { onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry }
+360
View File
@@ -0,0 +1,360 @@
// Exercise the transport openers themselves: synthetic HTTP/2 events and fetch
// bodies make cancellation at the response head and late cleanup observable.
import "./nonet.mjs"
import { afterEach, beforeEach, expect, test } from "bun:test"
import { EventEmitter, getEventListeners } from "node:events"
import http2 from "node:http2"
import { Duplex } from "node:stream"
import { CursorAuthPlugin, _internal } from "./index.mjs"
const { open, openH1, openH2, H1, H2, fields, pb, frame, frames } = _internal
const savedFetch = globalThis.fetch
const savedConnect = http2.connect
const savedH1 = { ...H1 }
const savedH2 = { ...H2 }
const opened = []
const streams = []
const sessions = []
const until = async (predicate) => {
const deadline = Date.now() + 500
while (!predicate()) {
if (Date.now() >= deadline) throw new Error("transport fixture did not settle")
await new Promise((resolve) => setTimeout(resolve, 1))
}
}
const body = () => {
const state = { cancelled: 0 }
state.stream = new ReadableStream({
start(controller) { state.controller = controller },
cancel() { state.cancelled++ },
})
streams.push(state)
return state
}
const keep = (o) => { if (o.session) opened.push(o); return o }
const head = () => {
const req = new EventEmitter()
req.close = () => req.emit("close")
const session = new EventEmitter()
session.request = () => req
session.destroyed = 0
session.destroy = () => { session.destroyed++ }
session.close = () => session.destroy()
sessions.push(session)
let attempts = 0
http2.connect = (origin) => {
expect(origin).toBe("http://127.0.0.1:1")
attempts++
return session
}
return { req, session, attempts: () => attempts }
}
const headers = { "x-request-id": "synthetic-open", authorization: "Bearer fixture" }
beforeEach(() => {
_internal.resetH1()
H2.wait = 25
})
afterEach(() => {
for (const o of opened.splice(0)) o.session.close()
for (const stream of streams.splice(0)) {
try { stream.controller.close() } catch {}
}
for (const session of sessions.splice(0)) session.destroy()
globalThis.fetch = savedFetch
http2.connect = savedConnect
Object.assign(H1, savedH1)
Object.assign(H2, savedH2)
_internal.resetH1()
})
for (const [name, start] of [
["open", (signal) => open("http://127.0.0.1:1", headers, signal)],
["openH1", (signal) => openH1(headers, signal)],
["openH2", (signal) => openH2("http://127.0.0.1:1", headers, signal)],
]) test(`${name}: an already-aborted request creates no connection or fetch`, async () => {
const h2 = head()
let fetched = 0
globalThis.fetch = async () => { fetched++; return new Response(new Uint8Array(0)) }
const ac = new AbortController()
ac.abort()
const o = keep(await start(ac.signal))
expect(o.error).toEqual({ status: 410, message: "the request was cancelled" })
expect(o.h2Failed).toBe(false)
expect(h2.attempts()).toBe(0)
expect(fetched).toBe(0)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
test("open: cancellation before the HTTP/2 head returns 410 without fallback or a blocked-HTTP/2 cache entry", async () => {
const h2 = head()
let fetched = 0
globalThis.fetch = async () => { fetched++; throw new Error("cancelled Run fell back") }
const ac = new AbortController()
const pending = open("http://127.0.0.1:1", headers, ac.signal)
ac.abort()
const o = keep(await pending)
expect(o.error?.status).toBe(410)
expect(o.h2Failed).toBe(false)
expect(_internal.onH1()).toBe(false)
expect(fetched).toBe(0)
expect(h2.session.destroyed).toBe(1)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
test("open: abort at the HTTP/2 response head closes the opened stream before returning it", async () => {
const h2 = head()
const ac = new AbortController()
const pending = open("http://127.0.0.1:1", headers, ac.signal)
h2.req.emit("response", { ":status": 200 })
ac.abort()
const o = keep(await pending)
expect(o.error?.status).toBe(410)
expect(o.h2Failed).toBe(false)
expect(h2.session.destroyed).toBe(1)
expect(_internal.onH1()).toBe(false)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
test("open: abort between an HTTP/2 failure and fallback starts no RunSSE and does not mark HTTP/2 blocked", async () => {
const h2 = head()
let fetched = 0
globalThis.fetch = async () => { fetched++; return new Response(new Uint8Array(0)) }
const ac = new AbortController()
const pending = open("http://127.0.0.1:1", headers, ac.signal)
h2.req.emit("error", Object.assign(new Error("synthetic protocol error"), { code: "ERR_HTTP2_ERROR" }))
ac.abort()
const o = keep(await pending)
expect(o.error?.status).toBe(410)
expect(o.h2Failed).toBe(false)
expect(fetched).toBe(0)
expect(_internal.onH1()).toBe(false)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
for (const outcome of ["response", "stream error", "session error", "close", "timeout"]) {
test(`openH2: ${outcome} releases its opening abort listener`, async () => {
const h2 = head()
const ac = new AbortController()
const pending = openH2("http://127.0.0.1:1", headers, ac.signal)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(1)
const error = Object.assign(new Error("synthetic connection refused"), { code: "ECONNREFUSED" })
if (outcome === "response") h2.req.emit("response", { ":status": 200 })
else if (outcome === "stream error") h2.req.emit("error", error)
else if (outcome === "session error") h2.session.emit("error", error)
else if (outcome === "close") h2.req.emit("close")
const o = await pending
if (outcome === "response") {
expect(o.status).toBe(200)
expect(h2.session.destroyed).toBe(0)
h2.session.destroy()
} else {
expect(o.error?.status).toBe(502)
expect(o.h2Failed).toBe(true)
expect(o.blocked).toBe(outcome === "timeout")
expect(h2.session.destroyed).toBe(1)
}
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
const destroyed = h2.session.destroyed
ac.abort()
expect(h2.session.destroyed).toBe(destroyed)
})
}
for (const status of [200, 401]) test(`openH1: a late ${status} RunSSE response is cancelled after abort`, async () => {
const stream = body()
let respond
let fetchSignal
globalThis.fetch = (_url, init) => {
fetchSignal = init.signal
return new Promise((resolve) => { respond = resolve })
}
const ac = new AbortController()
const o = keep(await openH1(headers, ac.signal))
ac.abort()
// Deliver the response even when fetch has already received the abort. The
// opener must release its body without waiting for a first data chunk.
respond(new Response(stream.stream, { status }))
await until(() => stream.cancelled === 1)
expect(fetchSignal.aborted).toBe(true)
expect(o.req.destroyed).toBe(true)
expect(stream.stream.locked).toBe(false)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
test("openH1: an abort during fetch setup returns cancellation and cleans up the late body", async () => {
const ac = new AbortController()
const stream = body()
globalThis.fetch = async () => {
ac.abort()
return new Response(stream.stream)
}
const o = keep(await openH1(headers, ac.signal))
await until(() => stream.cancelled === 1)
expect(o.error?.status).toBe(410)
expect(o.h2Failed).toBe(false)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
test("openH1: abort cancels an idle RunSSE reader and destroys the request", async () => {
const stream = body()
globalThis.fetch = async () => new Response(stream.stream)
const ac = new AbortController()
const o = keep(await openH1(headers, ac.signal))
await until(() => stream.stream.locked)
ac.abort()
await until(() => stream.cancelled === 1 && !stream.stream.locked)
expect(o.req.destroyed).toBe(true)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
for (const outcome of ["EOF", "HTTP error", "read error"]) {
test(`openH1: RunSSE ${outcome} releases its abort listener`, async () => {
const stream = body()
globalThis.fetch = async () => new Response(stream.stream, { status: outcome === "HTTP error" ? 401 : 200 })
const ac = new AbortController()
const o = keep(await openH1(headers, ac.signal))
const received = (async () => {
const result = []
for await (const f of frames(o.req)) result.push(f)
return result
})()
if (outcome === "HTTP error") stream.controller.enqueue(Buffer.from('{"code":"unauthenticated","message":"synthetic sign-out"}'))
if (outcome === "read error") stream.controller.error(new Error("synthetic read failure"))
else stream.controller.close()
const result = await received
if (outcome === "EOF") expect(result).toEqual([])
else {
expect(result).toHaveLength(1)
expect(result[0].end).toBe(true)
const error = JSON.parse(result[0].data.toString()).error
expect(error.code).toBe(outcome === "HTTP error" ? "unauthenticated" : "unavailable")
expect(error.message).toContain(outcome === "HTTP error" ? "synthetic sign-out" : "synthetic read failure")
}
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
}
test("openH1: write callbacks and drain wait for serialized append response bodies", async () => {
const downstream = body()
const first = body()
const seqnos = []
const callbacks = []
globalThis.fetch = async (url, init) => {
if (String(url).endsWith("/RunSSE")) return new Response(downstream.stream)
const seq = fields(Buffer.from(init.body)).find((f) => f.num === 3)?.n ?? 0
seqnos.push(seq)
return new Response(seq === 0 ? first.stream : new Uint8Array(0))
}
const o = keep(await openH1(headers))
let drained = false
o.req.once("drain", () => { drained = true })
expect(o.req.write(frame(Buffer.alloc(128 * 1024)), () => callbacks.push(0))).toBe(false)
o.req.write(frame(Buffer.from("second")), () => callbacks.push(1))
await until(() => first.stream.locked)
expect(seqnos).toEqual([0])
expect(callbacks).toEqual([])
expect(drained).toBe(false)
first.controller.close()
await until(() => callbacks.length === 2 && drained)
expect(seqnos).toEqual([0, 1])
expect(callbacks).toEqual([0, 1])
})
for (const outcome of ["head abort", "completion", "HTTP error"]) {
test(`the plugin: ${outcome} releases transport ownership and its Run abort listener`, async () => {
const ac = new AbortController()
const writes = []
const closed = { req: 0, session: 0, destroyed: 0 }
const req = new Duplex({
read() {},
write(chunk, _encoding, callback) {
writes.push(Buffer.from(chunk))
if (outcome === "HTTP error") req.push(Buffer.from("synthetic unauthorized"))
else {
req.push(frame(pb().bytes(1, pb().bytes(1, pb().str(1, "synthetic answer"))).done()))
req.push(frame(pb().bytes(1, pb().bytes(14, pb().varint(1, 0))).done()))
const end = frame(Buffer.from("{}"))
end[0] = 2
req.push(end)
}
req.push(null)
callback()
},
})
req.close = () => { closed.req++; req.destroy() }
const session = new EventEmitter()
session.close = () => { closed.session++ }
session.destroy = () => { closed.destroyed++; req.destroy() }
session.request = () => {
queueMicrotask(() => {
req.emit("response", { ":status": outcome === "HTTP error" ? 401 : 200 })
// open's continuation runs first; abort then wins before runOnce resumes.
if (outcome === "head abort") queueMicrotask(() => ac.abort())
})
return req
}
sessions.push(session)
http2.connect = (origin) => {
expect(origin).toBe("http://127.0.0.1:1")
return session
}
globalThis.fetch = async (url) => {
if (String(url).endsWith("/GetServerConfig")) return Response.json({ agentUrlConfig: { agentUrl: "http://127.0.0.1:1" } })
if (String(url).endsWith("/GetUsableModels")) return Response.json({ models: [{ modelId: "synthetic-open-model", displayName: "Synthetic" }] })
throw new Error("unexpected synthetic API call: " + url)
}
const auth = { type: "oauth", access: "synthetic-open-" + outcome, refresh: "", expires: 0 }
const plugin = await CursorAuthPlugin()
const loader = await plugin.auth.loader(async () => auth)
const response = await loader.fetch("http://127.0.0.1:1/v1/chat/completions", {
method: "POST", signal: ac.signal,
body: JSON.stringify({ model: "synthetic-open-model", messages: [{ role: "user", content: "synthetic request" }] }),
})
const result = await response.json()
expect(response.status).toBe(outcome === "head abort" ? 410 : outcome === "HTTP error" ? 401 : 200)
if (outcome === "head abort") {
expect(result.error.message).toContain("cancelled")
expect(writes).toHaveLength(0)
} else {
expect(writes).toHaveLength(1)
if (outcome === "completion") expect(result.choices[0].message.content).toBe("synthetic answer")
else expect(result.error.message).toContain("synthetic unauthorized")
}
expect(closed.req).toBe(1)
expect(closed.session).toBe(1)
expect(req.destroyed).toBe(true)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
ac.abort()
expect(closed.req).toBe(1)
expect(closed.session).toBe(1)
})
}
for (const outcome of ["abort", "close"]) {
test(`openH1: ${outcome} cancels a pending append and skips buffered writes`, async () => {
const downstream = body()
const ac = new AbortController()
const appends = []
const callbacks = []
globalThis.fetch = async (url, init) => {
if (String(url).endsWith("/RunSSE")) return new Response(downstream.stream)
appends.push(init.signal)
return new Promise((_, reject) => {
init.signal.addEventListener("abort", () => reject(init.signal.reason), { once: true })
})
}
const o = keep(await openH1(headers, ac.signal))
o.req.on("error", () => {})
o.req.write(frame(Buffer.from("pending")), () => callbacks.push(0))
o.req.write(frame(Buffer.from("buffered")), () => callbacks.push(1))
await until(() => appends.length === 1)
if (outcome === "abort") ac.abort()
else o.session.close()
await until(() => callbacks.length === 2 && downstream.cancelled === 1)
expect(o.req.destroyed).toBe(true)
expect(appends).toHaveLength(1)
expect(appends[0].aborted).toBe(true)
expect(getEventListeners(ac.signal, "abort")).toHaveLength(0)
})
}