From 1a5b184991e22223760f3efe80dac62f23ec0b31 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 15:10:54 +0800 Subject: [PATCH] cursor 0.2.34: the quiet error names its checkpoint; an opt-in Wire trace saves a failed Run's frames (#550) Windsland52 (#550, 0.2.33, cursor/grok-4.6 at xhigh): four Runs ended "Cursor went quiet: 24 heartbeats and nothing else for 240 s, its last message checkpoint". They asked for the checkpoint to be named, and for a way to see what Cursor sends after it. No change to quiet's budget or to retry, as asked. The quiet error now says, for a checkpoint: its number in the Run, which of its step's checkpoints it was (native path; the stateless path doesn't count steps), how many came in a row, and the kinds before it, e.g. "its last message checkpoint #1 of the Run, the first of step 1, after blob request x2, thinking". Other kinds read as before. Wire trace is a new plugin option (wire_trace), off by default. With it on, a Run that fails (not one the caller cancels), native or stateless, writes /cursor-traces/-.json (temp and rename, mode 600, newest 20 kept). It holds both directions' frames as time, size, kind, top-level field numbers with wire type and size, and the field numbers and sizes one level inside: the shape, never the bytes. No text, thinking, tool name or argument, blob or blob id, checkpoint content, token, header, account or conversation id is read into it. The error message is scrubbed of email-, uuid-, auth-id- and token-shaped strings. It also has quiet's counters, the model id and plugin version. The first 2000 and last 3000 frames are kept, the rest counted. The folder comes from input.directory, which magpie sets to its config folder. The option exists only in magpie, so OpenCode's project folder is never written to. Run on mote at this tree (33027a8 + this change): - HOME=$(mktemp -d) bun test at the root: 4186 pass, 9 skip, 0 fail. - bun scripts/check.mjs cursor ok. - native-session + native-e2e on xiaomi-gpu (Windows, win-run): 165 pass, 0 fail. Broken by hand, on mote: - The new tests against origin/main's code: 5 fail. - Raw frame bytes added to each entry: both e2e trace tests red (secret, token found). - Tracing cancelled Runs too: the cancelled test red. - Ignoring the option: "off unless the option is on" red. Not tried: a real Cursor account. The stall hasn't been reproduced here, so the fixtures follow what #550 reports (heartbeats after a checkpoint), not a captured Run. Not tried in the magpie GUI either: that the option shows as a toggle under Plugin options is from how Included usage only shows, not looked at. --- packages/cursor/README.md | 21 +++ packages/cursor/index.mjs | 38 ++++- packages/cursor/native-e2e.test.mjs | 73 +++++++++- packages/cursor/native-session.mjs | 181 +++++++++++++++++++++++- packages/cursor/native-session.test.mjs | 56 ++++++++ packages/cursor/package.json | 2 +- 6 files changed, 357 insertions(+), 14 deletions(-) diff --git a/packages/cursor/README.md b/packages/cursor/README.md index 27e28be..cc773ed 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -298,6 +298,27 @@ could still pay for them. On-demand and Total are still shown but never keep an account in routing. Use it when on-demand is a shared or paid pool you don't want spent. When off, on-demand works as described above. +### Wire trace (optional, for bug reports) + +In magpie, open the Cursor provider, turn on **Wire trace** under **Plugin +options**, and save (or set `"pluginOptions": {"cursor": {"wire_trace": +true}}` in magpie's settings.json). It is off by default and takes effect +at the next request. + +When on, each Cursor request that fails (not one you cancel) saves a JSON +file in the `cursor-traces` folder of magpie's folder: `~/.config/magpie/cursor-traces` +(on Windows `C:\Users\\.config\magpie\cursor-traces`), or the +portable data folder. The newest 20 are kept. A file holds the Run's +frames in order, both ways, as each frame's time (ms from the Run's +start), size, kind (text, thinking, checkpoint, heartbeat, ...), field +numbers and sizes, and the field numbers and sizes one level inside them, +plus the error and the model id. No prompt, reply or thinking text, tool +name or argument, blob or checkpoint content, token, header, account or +conversation id is written; the error's message has anything shaped like +an email, id or token taken out. Look the file over before you attach it. + +Turn it off again when you're done. + Sign in to the Cursor account linked in Grok Bot. A linked SuperGrok subscription grants Bot access without a paid Cursor plan; see [Grok Bot plans and billing](https://cursor.com/help/grok-bot/plans). diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 9e6c8c3..b082428 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -28,7 +28,7 @@ // // OpenCode speaks chat completions to it (@ai-sdk/openai-compatible); the // fetch here answers them. -import { NATIVE_LIMITS, nativeSessions, NativeSessionError, nativeFields, nativeMcpArgs, Quiet } from "./native-session.mjs" +import { NATIVE_LIMITS, nativeSessions, NativeSessionError, nativeFields, nativeMcpArgs, Quiet, setWireTrace } from "./native-session.mjs" import { isDeepStrictEqual } from "node:util" import http2 from "node:http2" import { STATUS_CODES } from "node:http" @@ -642,6 +642,11 @@ function credits(plan, grants, ids, resets, now = Date.now()) { // keeping nothing in routing. Off, on-demand that can still pay keeps it. const INCLUDED_ONLY = "included_only" +// WIRE_TRACE is the switch (magpie's plugin options, off by default) that +// saves a failed Run's frames, scrubbed, as a JSON file in cursor-traces in +// magpie's folder (plugins#550): see WireTrace for what one holds. +const WIRE_TRACE = "wire_trace" + // enterpriseUsage is the allowance GetCurrentPeriodUsage leaves out on an // Enterprise account. That call answers with only the billing cycle there; // the website's usage-summary has individualUsage.overall, in cents, and @@ -2772,8 +2777,13 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa const { session, req } = o let closed = false let heartbeat + // a Run Cursor stops answering ends, as a retained one does (#2672) + const quiet = new Quiet(NATIVE_LIMITS, () => close(), { path: "stateless", model: id }) const send = (msg) => { - if (!closed && !req.destroyed && req.writable) req.write(frame(msg)) + if (!closed && !req.destroyed && req.writable) { + quiet.trace?.frame("out", msg) + req.write(frame(msg)) + } } const close = () => { if (closed) return @@ -2804,8 +2814,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa book.done() return { error: failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)) } } - // a Run Cursor stops answering ends, as a retained one does (#2672) - const it = decode(new Quiet(NATIVE_LIMITS, close).frames(frames(req)), { + const it = decode(quiet.frames(frames(req)), { send, blobs, tools, @@ -2816,7 +2825,10 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa }) const wrapped = (async function* () { try { - yield* it + for await (const v of it) { + if (v?.error) quiet.failed(v.error) + yield v + } } finally { close() book.done() @@ -3328,6 +3340,16 @@ export async function CursorAuthPlugin(input) { return false } } + // the folder a failed Run's trace goes to, read at each Run's start; + // "" with Wire trace off, and outside magpie, which has no such option + // (OpenCode's directory is the project's, never written to) + setWireTrace(() => { + try { + return input?.magpie?.option?.(ID, WIRE_TRACE) === true && input.directory ? join(input.directory, "cursor-traces") : "" + } catch { + return "" + } + }) return { auth: { provider: ID, @@ -3369,6 +3391,12 @@ export async function CursorAuthPlugin(input) { description: "Keeps an account in routing only while its included usage lasts: once an included pool (Cursor Models, Other Models, a newer plan's Weekly) is used up, magpie moves its models to the next account until it resets, even if on-demand or free credit could pay.", }, + { + key: WIRE_TRACE, + label: "Wire trace", + description: + "For a bug report: when a Cursor request fails, saves the shape of what Cursor sent and what was sent back (each frame's kind, field numbers, size and time) to the cursor-traces folder in magpie's folder. No prompt or reply text, tool names or arguments, tokens, headers or account ids are written. The newest 20 are kept.", + }, ], // magpie's: how much of the plan's included usage is gone (the plan // is the one the sign-in read). The built-in's read, clean or not, diff --git a/packages/cursor/native-e2e.test.mjs b/packages/cursor/native-e2e.test.mjs index 0c11643..28c0461 100644 --- a/packages/cursor/native-e2e.test.mjs +++ b/packages/cursor/native-e2e.test.mjs @@ -2,9 +2,12 @@ import "./nonet.mjs" import { afterEach, beforeEach, expect, spyOn, test } from "bun:test" import http2 from "node:http2" import { randomUUID } from "node:crypto" +import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" import { getEventListeners } from "node:events" import { CursorAuthPlugin, _internal } from "./index.mjs" -import { NATIVE_LIMITS, nativeSessions } from "./native-session.mjs" +import { NATIVE_LIMITS, nativeSessions, setWireTrace } from "./native-session.mjs" import { message, bin, text, uint, readWire, nest, number, string, envelope, update, end, tool, setBlob, getBlob, checkpoint, abortExec, readResult } from "./native-test-wire.mjs" const savedFetch = globalThis.fetch @@ -96,6 +99,7 @@ async function agent(options = {}) { const first = () => { if (options.stallInitial) return send(update(4, text(1, options.initialReasoning ?? "native planning one"))) + for (const b of options.afterThinking ?? []) send(b) // Cursor's own heartbeats, InteractionUpdate.heartbeat, and nothing else if (options.serverHeartbeat) { const beat = () => delay(() => { send(update(13, Buffer.alloc(0))); beat() }, options.serverHeartbeat) @@ -255,8 +259,8 @@ async function agent(options = {}) { throw new Error("unexpected fake API request: " + u) } a.firstID = firstID - a.ask = async (account, chat, { signal, session = "fixture-session" } = {}) => { - const plugin = await CursorAuthPlugin() + a.ask = async (account, chat, { signal, session = "fixture-session", input } = {}) => { + const plugin = await CursorAuthPlugin(input) const loader = await plugin.auth.loader(async () => account) const res = await loader.fetch(a.base + "/v1/chat/completions", { method: "POST", headers: { "x-magpie-cursor-session": session }, body: JSON.stringify(chat), signal }) if (chat.stream) return res @@ -1549,6 +1553,69 @@ for (const path of ["native", "stateless"]) { }) } +// plugins#550: Cursor's heartbeats and nothing else after a checkpoint. The +// error names the checkpoint, and with Wire trace on, the Run's frames are +// saved in shape only: no prompt, thinking, checkpoint bytes, token or id. +for (const path of ["native", "stateless"]) { + test(`${path}: a quiet Run's error names its checkpoint, and Wire trace saves its frames scrubbed (plugins#550)`, async () => { + Object.assign(NATIVE_LIMITS, { idle: 150, quiet: 400 }) + if (path === "stateless") NATIVE_LIMITS.perProcess = 0 + const secret = "SECRET-" + randomUUID() + const a = await agent({ + thinkingOnly: true, serverHeartbeat: 40, initialReasoning: "thinking " + secret, + afterThinking: [checkpoint(message(bin(1, Buffer.from("checkpoint " + secret)), uint(10, 1), text(22, "cli")))], + }) + const dir = mkdtempSync(join(tmpdir(), "cursor-trace-")) + try { + const account = auth() + const input = { directory: dir, magpie: { option: (id, key) => id === "cursor" && key === "wire_trace" } } + const chat = initial({ stream: true, messages: [{ role: "user", content: "prompt " + secret }] }) + const sse = await sseOf(await a.ask(account, chat, { input })) + expect(sse).toMatch(path === "native" + ? /Cursor went quiet: \d+ heartbeats and nothing else for \d+ s, its last message checkpoint #1 of the Run, the first of step 1, after blob request ×2, thinking \(try again\)/ + : /Cursor went quiet: \d+ heartbeats and nothing else for \d+ s, its last message checkpoint #1 of the Run, after blob request ×2, thinking \(try again\)/) + await until(() => a.closedStreams === 1) + const files = readdirSync(join(dir, "cursor-traces")) + expect(files).toHaveLength(1) + const raw = readFileSync(join(dir, "cursor-traces", files[0]), "utf8") + for (const word of [secret, account.access, account.accountId, "synthetic-", "Bearer", "fixture-session"]) expect(raw).not.toContain(word) + const t = JSON.parse(raw) + expect(t).toMatchObject({ trace: 1, path, model: "fixture-model", error: { status: 502 } }) + expect(t.error.message).toContain("checkpoint #1") + const kinds = t.frames.filter((f) => f.dir === "in").map((f) => f.kind) + const at = kinds.indexOf("checkpoint") + // Cursor asked for the history's two blobs, thought, then checkpointed + expect(kinds.slice(0, at)).toEqual(["blob request", "blob request", "thinking"]) + // after the checkpoint, Cursor's heartbeats and nothing else + expect(kinds.slice(at + 1).length).toBeGreaterThan(0) + expect(kinds.slice(at + 1).every((k) => k === "heartbeat")).toBe(true) + // the checkpoint's shape: AgentServerMessage field 3, its state's fields by number + expect(t.frames.find((f) => f.kind === "checkpoint").fields[0].slice(0, 2)).toEqual([3, 2]) + expect(t.frames.find((f) => f.kind === "checkpoint").fields[0][3].map((c) => c[0])).toEqual([1, 10, 22]) + expect(t.frames.some((f) => f.dir === "out")).toBe(true) + expect(t.frames.some((f) => f.event === "quiet")).toBe(true) + } finally { + setWireTrace("") + rmSync(dir, { recursive: true, force: true }) + } + }) +} + +test("native: Wire trace is off unless the option is on (plugins#550)", async () => { + Object.assign(NATIVE_LIMITS, { idle: 150 }) + const a = await agent({ thinkingOnly: true }) + const dir = mkdtempSync(join(tmpdir(), "cursor-trace-")) + try { + const input = { directory: dir, magpie: { option: () => false } } + const sse = await sseOf(await a.ask(auth(), initial({ stream: true }), { input })) + expect(sse).toContain("Cursor went quiet") + await until(() => a.closedStreams === 1) + expect(readdirSync(dir)).toEqual([]) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + test("stateless: a call with no count, then silence, is an error, not a step of tool calls (#2672)", async () => { Object.assign(NATIVE_LIMITS, { idle: 150, perProcess: 0 }) const a = await agent({ noCount: true, stateDelay: 10_000 }) diff --git a/packages/cursor/native-session.mjs b/packages/cursor/native-session.mjs index beb9f20..e8d6c4f 100644 --- a/packages/cursor/native-session.mjs +++ b/packages/cursor/native-session.mjs @@ -1,4 +1,6 @@ import { createHash, randomBytes } from "node:crypto" +import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs" +import { join } from "node:path" // Retention is process-local and optional. A lost owner rebuilds Chat history // on a fresh Run; it never resubmits a result to an uncertain native exec. @@ -75,8 +77,10 @@ function kindOf(f) { // reply then waited until the agent gave up (305 s, yetone/magpie#2672). // Only time spent waiting on Cursor's next frame counts: not this side // handling one, not a slow reader of the reply, not a paused Run. +// meta names the Run for a wire trace (path, model); with the trace off it +// is unused. export class Quiet { - constructor(limits, stop) { + constructor(limits, stop, meta = {}) { this.limits = limits this.stop = stop this.heard = 0 // ms waited since Cursor's last frame that wasn't a heartbeat @@ -86,6 +90,14 @@ export class Quiet { this.paused = false this.waiting = false this.why = "" + // what the error says of a checkpoint (plugins#550): its number in the + // Run, which of its step's it was (step is 0 where the path doesn't + // count steps), and the kinds of the frames before it, run-length + this.checkpoints = 0 + this.step = 0 + this.stepCheckpoints = 0 + this.trail = [] + this.trace = WireTrace.open(meta) } arm() { clearTimeout(this.timer) @@ -102,20 +114,47 @@ export class Quiet { fire() { const gap = Date.now() - this.since const what = this.heard + gap >= this.limits.quiet ? `${this.heartbeats} heartbeats and nothing else for ${Math.round((this.heard + gap) / 1000)} s` : `no message for ${Math.round(gap / 1000)} s` - this.why = `Cursor went quiet: ${what}${this.last ? ", its last message " + this.last : ""} (try again)` + this.why = `Cursor went quiet: ${what}${this.last ? ", its last message " + this.lastSaid() : ""} (try again)` + this.trace?.event("quiet", { heard: this.heard + gap, heartbeats: this.heartbeats }) this.gone?.() this.stop({ status: 502, message: this.why }) + this.failed({ status: 502, message: this.why }) + } + // lastSaid is the last frame's kind as the error names it; a checkpoint + // with its number, its place in the step and what came before it + lastSaid() { + if (this.last !== "checkpoint") return this.last + const row = this.trail.at(-1)?.[1] ?? 1 + const before = this.trail.slice(0, -1).map(([k, n]) => n > 1 ? `${k} ×${n}` : k).join(", ") + const nth = this.stepCheckpoints === 1 ? "the first" : `number ${this.stepCheckpoints}` + return `checkpoint #${this.checkpoints} of the Run` + + (this.step ? `, ${nth} of step ${this.step}` : "") + + (row > 1 ? `, ${row} in a row` : "") + + `, after ${before || "nothing else"}` + } + // nextStep is the Run's next model call (NativeSession counts them) + nextStep(n) { + this.step = n + this.stepCheckpoints = 0 + this.trace?.event("step", { n }) + } + // failed is how the Run ended, when it failed: a wire trace, if on, is + // written then (once) + failed(error) { + this.trace?.write(error, this) } // pause stops the clock while the Run waits on the caller's tool results; // resume starts it again from nothing, for Cursor's next model call pause() { this.waited() this.paused = true + this.trace?.event("pause") } resume() { this.paused = false this.heard = 0 this.heartbeats = 0 + this.trace?.event("resume") this.arm() } // frames passes on a Run's frames; once Cursor has gone quiet, the read @@ -141,10 +180,25 @@ export class Quiet { this.waited() } if (this.why) throw Object.assign(new NativeSessionError(502, this.why), { quiet: true }) - if (r.done) return + if (r.done) { + this.trace?.event("eof") + return + } const kind = kindOf(r.value) + this.trace?.frame("in", r.value, kind) if (kind == null) this.heartbeats++ - else [this.heard, this.heartbeats, this.last] = [0, 0, kind] + else { + [this.heard, this.heartbeats, this.last] = [0, 0, kind] + if (kind === "checkpoint") { + this.checkpoints++ + this.stepCheckpoints++ + } + if (this.trail.at(-1)?.[0] === kind) this.trail.at(-1)[1]++ + else { + this.trail.push([kind, 1]) + if (this.trail.length > 4) this.trail.shift() + } + } yield r.value } } finally { @@ -158,6 +212,118 @@ export class Quiet { } } +// The wire trace (plugins#550, off by default; the plugin's Wire trace +// option): a failed Run's frames, in and out, written to a JSON file for a +// bug report. A frame is kept as its kind, size, top-level field numbers +// with their wire types and sizes, and those fields' own field numbers and +// sizes one level down: the shape of the protocol, never its bytes. No +// text, thinking, tool name or argument, blob or blob id, checkpoint +// content, token, header, account or conversation id is read into it; the +// error's message is scrubbed of anything shaped like an email, id or +// token. traceDir is the folder, or "" while off, asked at each Run's start. +let traceDir = () => "" +export function setWireTrace(dir) { + traceDir = typeof dir === "function" ? dir : () => dir || "" +} +const TRACE_HEAD = 2000 // the Run's first frames, kept +const TRACE_TAIL = 3000 // and its last, the ones in between counted only +const TRACE_FILES = 20 // the newest traces kept in the folder +// shape is a message's fields as [number, wire, size] (a varint's size 0), +// with children: the fields' own fields, for a field that is a message +function shape(data, children) { + return nativeFields(data).map((f) => { + const own = [f.num, f.wire, f.wire === 0 ? 0 : f.data.length] + if (!children || f.wire !== 2) return own + try { + return [...own, nativeFields(f.data).map((c) => [c.num, c.wire, c.wire === 0 ? 0 : c.data.length])] + } catch { + return own + } + }) +} +export function scrub(s) { + return String(s ?? "") + .replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g, "") + .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "") + .replace(/(auth0|user|google-oauth2|github)\|[\w-]+/gi, "") + .replace(/[A-Za-z0-9_\-+/=.]{24,}/g, "") + .slice(0, 2000) +} +export class WireTrace { + static open(meta) { + let dir = "" + try { dir = traceDir() } catch {} + return dir ? new WireTrace(dir, meta) : null + } + constructor(dir, meta = {}) { + this.dir = dir + this.meta = { path: String(meta.path ?? ""), model: String(meta.model ?? "") } + this.started = Date.now() + this.head = [] + this.tail = [] + this.dropped = 0 + } + push(entry) { + if (this.written) return + if (this.head.length < TRACE_HEAD) return void this.head.push(entry) + this.tail.push(entry) + if (this.tail.length > TRACE_TAIL) { + this.tail.shift() + this.dropped++ + } + } + // frame is one frame of the Run: "in" from Cursor ({data} or {end, data}), + // "out" a message this side sent + frame(dir, f, kind) { + const t = Date.now() - this.started + const data = dir === "in" ? f.data : f + const entry = { t, dir, size: data?.length ?? 0 } + if (dir === "in") entry.kind = kind ?? "heartbeat" + if (dir === "in" && f.end) entry.end = true + else try { entry.fields = shape(data, true) } catch { entry.malformed = true } + this.push(entry) + } + event(name, extra = {}) { + this.push({ t: Date.now() - this.started, event: name, ...extra }) + } + // write saves the trace once, when the Run failed; a write that fails + // leaves the Run's error as it was + write(error, quiet) { + if (this.written) return + this.written = true + try { + const at = new Date(this.started).toISOString().replace(/[:.]/g, "-") + const body = { + trace: 1, + plugin: "@magpie-community/opencode-cursor-auth", + version: version(), + ...this.meta, + started: new Date(this.started).toISOString(), + ms: Date.now() - this.started, + error: { status: error?.status ?? 0, message: scrub(error?.message) }, + quiet: quiet ? { last: quiet.last, checkpoints: quiet.checkpoints, step: quiet.step, stepCheckpoints: quiet.stepCheckpoints, heartbeats: quiet.heartbeats, heard: quiet.heard, trail: quiet.trail } : undefined, + frames: [...this.head, ...(this.dropped ? [{ dropped: this.dropped }] : []), ...this.tail], + } + mkdirSync(this.dir, { recursive: true }) + const file = join(this.dir, `${at}-${randomBytes(3).toString("hex")}.json`) + writeFileSync(file + ".tmp", JSON.stringify(body) + "\n", { mode: 0o600 }) + renameSync(file + ".tmp", file) + this.file = file + const old = readdirSync(this.dir).filter((n) => n.endsWith(".json")).sort() + for (const n of old.slice(0, Math.max(0, old.length - TRACE_FILES))) rmSync(join(this.dir, n), { force: true }) + } catch {} + this.head = this.tail = [] + } +} +// version is the package's, for a trace to say +function version() { + try { + return JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version ?? "" + } catch { + return "" + } +} + // Unlike the compatibility codec, malformed protobuf tails must fail a live // continuation. Dropping one could turn a truncated batch into a valid handoff. export function nativeFields(input, maxFields = Infinity) { @@ -587,7 +753,8 @@ class NativeSession { this.segment = new Segment(this, prepared.chat) this.retain(bytes(prepared.chat)) this.expireIn(this.limits.lifetime) - this.quiet = new Quiet(this.limits, (e) => this.fail(e)) + this.quiet = new Quiet(this.limits, (e) => this.fail(e), { path: "native", model: resolution?.id }) + this.quiet.nextStep(this.steps) } // expireIn sets the Run's absolute deadline ms from now: from its start, // the whole lifetime; a test brings it in after the first answer @@ -632,6 +799,8 @@ class NativeSession { if (this.error || this.state === "complete") return this.error = error this.state = state + // a cancelled Run is the caller's doing, not a failure to trace + if (state !== "cancelled") this.quiet.failed(error) this.segment.fail(error) for (const segment of this.batches ?? []) segment.detach?.() this.segment.detach?.() @@ -671,6 +840,7 @@ class NativeSession { } send(message) { if (this.error || this.transportClosed) invalid("native transport is no longer writable", 410) + this.quiet.trace?.frame("out", message) this.transport.send(message) } // reply answers one of Cursor's KV requests once the outbound queue has @@ -764,6 +934,7 @@ class NativeSession { // caller's results, or after a step whose calls were all answered here. nextStep(estimate) { this.steps++ + this.quiet.nextStep(this.steps) this.stepSaid = this.said if (estimate != null) this.stepEstimate = estimate } diff --git a/packages/cursor/native-session.test.mjs b/packages/cursor/native-session.test.mjs index 9dd2ee3..6e34e8e 100644 --- a/packages/cursor/native-session.test.mjs +++ b/packages/cursor/native-session.test.mjs @@ -418,3 +418,59 @@ test("native protocol: frames already passed on are not kept while the Run strea release() await pending }) + +// plugins#550: the quiet error says which checkpoint was last, its place in +// the step, whether it repeated, and what came before it. +test("native protocol: a quiet Run's error says its checkpoint was a repeat, its number and what came before (plugins#550)", async () => { + const { run } = owner({}, { idle: 150 }) + const state = message(text(22, "cli")) + run.pump((async function* () { + yield* frames([update(4, text(1, "thinking")), update(4, text(1, "more")), update(1, text(1, "answer")), checkpoint(state), checkpoint(state)]) + await new Promise(() => {}) + })()) + await until(() => run.error) + expect(run.error.message).toBe("Cursor went quiet: no message for 0 s, its last message checkpoint #2 of the Run, number 2 of step 1, 2 in a row, after thinking ×2, text (try again)") +}) + +test("native protocol: a checkpoint after the caller's results is the first of the next step (plugins#550)", async () => { + const { run } = owner({}, { idle: 150 }) + run.quiet.checkpoints = 3 + run.quiet.stepCheckpoints = 3 + run.nextStep() + run.pump((async function* () { + yield* frames([checkpoint(message(text(22, "cli")))]) + await new Promise(() => {}) + })()) + await until(() => run.error) + expect(run.error.message).toBe("Cursor went quiet: no message for 0 s, its last message checkpoint #4 of the Run, the first of step 2, after nothing else (try again)") +}) + +test("native protocol: Wire trace writes a failed Run, never a cancelled one, and only while on (plugins#550)", async () => { + const { setWireTrace } = await import("./native-session.mjs") + const { mkdtempSync, readdirSync, rmSync } = await import("node:fs") + const { tmpdir } = await import("node:os") + const { join } = await import("node:path") + const dir = mkdtempSync(join(tmpdir(), "cursor-trace-unit-")) + try { + const off = owner({}, { idle: 100 }) + off.run.pump((async function* () { yield* frames([update(4, text(1, "x"))]); await new Promise(() => {}) })()) + await until(() => off.run.error) + setWireTrace(dir) + const cancelled = owner() + await cancelled.run.cancel("the Chat response was cancelled") + expect(readdirSync(dir)).toEqual([]) + const failed = owner({}, { idle: 100 }) + failed.run.pump((async function* () { yield* frames([update(4, text(1, "x"))]); await new Promise(() => {}) })()) + await until(() => failed.run.error) + expect(readdirSync(dir)).toHaveLength(1) + } finally { + setWireTrace("") + rmSync(dir, { recursive: true, force: true }) + } +}) + +test("Wire trace: scrub takes out what could be an email, id or token (plugins#550)", async () => { + const { scrub } = await import("./native-session.mjs") + expect(scrub("Cursor said: user a.b@example.com auth0|abc123 req 0f8e4ebc-1234-4abc-9def-0123456789ab tok eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ4In0.sig, Team budget limit reached")) + .toBe("Cursor said: user req tok , Team budget limit reached") +}) diff --git a/packages/cursor/package.json b/packages/cursor/package.json index 61eab19..523d225 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.33", + "version": "0.2.34", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs",