Files
plugins/packages/cursor/open.test.mjs
T
yetone 8f81a8aeb8 cursor 0.2.29: a native Run over HTTP/1.1 sends its history's blobs 16 at a time
ysm119 on Discord: Cursor models 30 s+ to first token, 1-4 min a turn.
0.2.28 (d9c858c) let BidiAppends go 16 at once, but only on runOnce, the
stateless fallback. Every real request goes through runNative, which
still opened HTTP/1.1 with atOnce=1, and nativeTransport.flush waits for
each write's callback, i.e. each append's answer. Cursor asks for every
history message as a KV getBlob, so a Run that fell back to HTTP/1.1
(a proxy or network that blocks h2) paid one ~265 ms round trip per
message before the model started.

Now runNative opens with H1.atOnce and kvReply: KV replies (field 3,
kv_client_message) overlap up to 16 at a time; any other message (a tool
result, the close) waits for every append before it, goes alone, and is
written once Cursor answered it, so it is never uncertain.

Measured with the real Cursor account in a sandbox HOME (bun 1.4.2,
this Mac; FORCE_H1 points h2 at a dead port so the Run falls back):
- HTTP/2, old and new alike: short prompt 5.0 s cold / 1.8 s warm;
  30-step agent request (121 messages, 40 tools, 233 KB) 6.5 / 2.9 s;
  100 steps (590 KB) 6.2-7.3 / 4.0-4.2 s.
- HTTP/1.1, 0.2.28: 30 steps 37-39 s to first token (~135 appends
  one after another); 100 steps 117-130 s.
- HTTP/1.1, 0.2.29: 30 steps 4.4-9.1 s; 100 steps 9.0-13.2 s (8 runs on
  grok-4.7@256k, 3 on composer-2.5), each answer correct about step 17
  and the first message, so the blobs arrive whole. A 6-turn tool loop
  over HTTP/1.1: turn 0 6.3 s, later turns 2.6-3.0 s.
- One early 0.2.29 run (100 steps) ended in a 187-byte error whose
  status wasn't captured; 11 runs after it, with the body printed,
  all passed. Its cause is unknown.

Run: bun test packages/cursor on mote, 316 pass 0 fail;
bun scripts/check.mjs cursor ok.
Broken by hand: runNative passing 1 again turns the two stall tests red;
the alone barrier disabled turns 4 red (the new openH1 test,
result-before-close, both uncertain-append tests).

Not tried: Opus (the account has no weekly quota for it, 429); the
reporter's own network or proxy, so whether he is on HTTP/1.1 is not
known; Cursor's own client as a baseline; a full sandbox magpie with
0.2.29 installed.
2026-10-28 15:59:22 +08:00

421 lines
18 KiB
JavaScript

// 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"
import { NATIVE_LIMITS, nativeSessions } from "./native-session.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 one at a time (a native session's Run): 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, undefined, 1))
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])
})
// A native session's Run over HTTP/1.1 (runNative): its history's KV replies
// go up together, as cursor-agent sends them; anything else (a tool result,
// an exec close) waits for every append before it, goes alone, and its
// write's callback is its own append answered.
test("openH1 with kvReply: KV replies overlap; any other message waits for them, goes alone, and is answered before its callback", async () => {
const downstream = body()
const held = new Map()
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)
const b = body()
held.set(seq, b)
return new Response(b.stream)
}
const o = keep(await openH1(headers, undefined, H1.atOnce, _internal.kvReply))
const kv = (i) => frame(pb().bytes(3, pb().varint(1, i).bytes(2, pb().bytes(1, Buffer.from("blob " + i)))).done())
const result = frame(pb().bytes(2, pb().varint(1, 7)).done())
for (let i = 0; i < 3; i++) o.req.write(kv(i), () => callbacks.push("kv" + i))
o.req.write(result, () => callbacks.push("result"))
o.req.write(kv(3), () => callbacks.push("kv3"))
await until(() => seqnos.length === 3 && callbacks.length === 3)
// three KV replies on their way at once, their callbacks already called
expect(seqnos).toEqual([0, 1, 2])
expect(callbacks).toEqual(["kv0", "kv1", "kv2"])
held.get(0).controller.close()
held.get(2).controller.close()
await new Promise((r) => setTimeout(r, 20))
expect(seqnos).toEqual([0, 1, 2]) // the result waits for append 1 too
held.get(1).controller.close()
await until(() => seqnos.length === 4)
await new Promise((r) => setTimeout(r, 20))
expect(seqnos).toEqual([0, 1, 2, 3]) // alone: nothing goes beside it
expect(callbacks).toEqual(["kv0", "kv1", "kv2"]) // nor is it written before it is answered
held.get(3).controller.close()
await until(() => callbacks.length === 5)
expect(seqnos).toEqual([0, 1, 2, 3, 4])
expect(callbacks).toEqual(["kv0", "kv1", "kv2", "result", "kv3"])
held.get(4).controller.close()
})
test("kvReply is a kv_client_message and nothing else", () => {
expect(_internal.kvReply(pb().bytes(3, pb().varint(1, 1)).done())).toBe(true)
expect(_internal.kvReply(pb().bytes(2, pb().varint(1, 1)).done())).toBe(false) // exec result
expect(_internal.kvReply(pb().bytes(5, pb().varint(1, 1)).done())).toBe(false) // exec control
expect(_internal.kvReply(pb().bytes(7, Buffer.alloc(0)).done())).toBe(false) // heartbeat
expect(_internal.kvReply(pb().bytes(1, pb().varint(1, 1)).done())).toBe(false) // run request
expect(_internal.kvReply(Buffer.alloc(0))).toBe(false)
})
// The same plugin ownership assertions cover retained Runs and capacity fallback.
for (const retained of [0, 32]) for (const outcome of ["head abort", "completion", "HTTP error"]) {
test(`the plugin (${retained ? "retained" : "stateless fallback"}): ${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 capacity = NATIVE_LIMITS.perProcess
let response
try {
await nativeSessions.clear()
NATIVE_LIMITS.perProcess = retained
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" }] }),
})
} finally { NATIVE_LIMITS.perProcess = capacity }
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 one at a time: ${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, 1))
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)
})
}