Skip to content

fix(cursor): weekly usage-limit errors classify as usage limits - #16

Closed
smirea wants to merge 1 commit into
mainfrom
fix/cursor-weekly-usage-limit
Closed

smirea wants to merge 1 commit into
mainfrom
fix/cursor-weekly-usage-limit

Conversation

@smirea

@smirea smirea commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Problem

When a Cursor account hits its weekly usage limit (Weekly usage limit reached. It resets in 3 days. Buy credits to keep going now.), isCursorUsageLimitError() returns false:

  1. Regular Cursor turns (packages/provider-cursor/src/server/adapter.ts) classify the failure as provider_error ("Provider error") instead of usage_limit ("Usage limit reached" / sidebar Limited badge), contradicting docs/internals/03_providers.md ("Classify quota/rate-limit errors as usage_limit (with reset time when available) rather than generic failures").
  2. Cursor text generation (packages/provider-cursor/src/server/textGeneration.ts — thread titles, branch names, commit messages, PR descriptions) falls back to "Cursor SDK request finished with an error." instead of "Cursor usage limit reached. Try again later or choose another text-generation provider.", missing the case PR fix(cursor): Cursor text generation names usage-limit failures pingdotgg/t3code#29748 and PR fix(server,cursor,opencode): refresh provider usage when a turn hits its usage limit pingdotgg/t3code#26234 intended to cover.

Root cause: In @cursor/sdk@1.5.2, AgentClient wraps a ConnectError carrying aiserver.v1.ErrorDetails (PRO_USER_USAGE_LIMIT, RATE_LIMITED, etc.) into an internal ActionRequiredError whose .cause is the ConnectError and which has no .code. LocalAgent's toRunError/wrapError only checks err instanceof CursorSdkError and err instanceof ConnectError (never err.cause), so it falls back to UnknownAgentError and returns RunResult.error = { message } with code: undefined. In addition, CURSOR_USAGE_LIMIT_CODE did not match USAGE_PRICING_REQUIRED or USAGE_PRICING_REQUIRED_CHANGEABLE.

Change

  • Update isCursorUsageLimitError() in packages/provider-cursor/src/server/CursorAgentSdk.ts:
    • Traverse the .cause chain (matching blockedInlineMcpServers and isCursorCancellationError) so wrapped SDK errors preserve structured name/status/code detection.
    • Extend CURSOR_USAGE_LIMIT_CODE to include usage_pricing_required(?:_changeable)? and \w*_usage_limit_exceeded.
    • When code is absent or generic ("", error, unknown, unspecified, custom, custom_message, provider_error), fall back to matching start-anchored Cursor usage/spending/rate-limit error messages (CURSOR_USAGE_LIMIT_MESSAGE) so embedded strings in unrelated failures (e.g., file paths) and errors with specific non-usage codes (e.g., internal) are excluded.
  • Keep fixed T3 error messages and retain raw provider error text only in cause (preserving docs/internals/02_effect-services.md and PR fix(cursor): Cursor text generation names usage-limit failures pingdotgg/t3code#29748).
  • Add unit tests in packages/provider-cursor/src/server/CursorAgentSdk.test.ts for codeless usage-limit messages, USAGE_PRICING_REQUIRED*, wrapped causes, and non-limit exclusions.

Fixing this in CursorAgentSdk.ts keeps the diff minimal without editing the 17 MB minified patches/@cursor__sdk@1.5.2.patch or pnpm-lock.yaml, survives SDK upgrades, and also handles CUSTOM_MESSAGE / USAGE_PRICING_REQUIRED payloads.

Scope

Fixes #

  • Routes covered: All Cursor paths that classify errors via isCursorUsageLimitError() — regular Cursor turns (adapter.ts on both result.error and thrown cause, across web, desktop, and mobile clients via server-side failure classification) and Cursor text generation (textGeneration.ts for thread title, branch name, commit message, and PR generation).
  • Not in this change: Cursor usage-limit polling (usageLimits.ts), parsing coarse "It resets in 3 days" text into resetsAt, and patching @cursor/sdk's wrapError to recover error codes for non-usage-limit error classes.

Verification

Reproducible on a Linux VM with no Cursor account

  • Unit tests:
    • Reverted CursorAgentSdk.ts to origin/main: new isCursorUsageLimitError test in packages/provider-cursor/src/server/CursorAgentSdk.test.ts fails (expected false to be true).
    • With the fix: vp test run packages/provider-cursor/src/server/CursorAgentSdk.test.ts packages/provider-cursor/src/server/textGeneration.test.ts packages/provider-cursor/src/server/CursorAgentSdkProcessRunner.test.ts packages/provider-cursor/src/server/adapter.test.ts — 4 files, 74/74 passed.
  • Changed checks: vp run check:changed — format, lint, knip, typecheck, and affected tests all pass.
  • End-to-end proof (scenarios:prove against origin/main):
    Ran an offline scenario against a local HTTP/1.1 ConnectRPC stub Cursor backend (CURSOR_BACKEND_URL=http://127.0.0.1:13998 CURSOR_API_KEY=test-cursor-key) returning aiserver.v1.ErrorDetails (PRO_USER_USAGE_LIMIT, title "Weekly usage limit reached.", detail "It resets in 3 days. Buy credits to keep going now.") through the real @cursor/sdk@1.5.2 worker.
    • Base df2cbe3961: ❌ failed (Provider error in timeline, no Limited badge, Regenerate title toast shows "Cursor SDK request finished with an error.").
    • Head 73c51a1093: ✅ passed (Usage limit reached banner, Limited badge in sidebar, Regenerate title toast shows "Cursor usage limit reached. Try again later or choose another text-generation provider.").
  • Unaffected path check (on fix): Ran the same offline stub returning a non-usage-limit backend error (code: "internal", "Backend service unavailable"). Confirmed regular Cursor turns still classify as Provider error and Regenerate title still shows "Cursor SDK request finished with an error.".
Before (df2cbe3961) After (73c51a1093)
Before: Provider error and generic text-generation toast After: Usage limit reached banner, Limited badge, and usage-limit toast
Offline E2E repro scenario (scripts/scenarios/cursor-weekly-usage-limit.e2e.ts)

Run with:

T3_SCENARIO_INHERIT_ENV='CURSOR_BACKEND_URL,CURSOR_API_KEY' \
CURSOR_BACKEND_URL=http://127.0.0.1:13998 \
CURSOR_API_KEY=test-cursor-key \
vp run scenarios:prove scripts/scenarios/cursor-weekly-usage-limit.e2e.ts --base origin/main
// @effect-diagnostics nodeBuiltinImport:off -- The scenario hosts a local ConnectRPC stub Cursor backend.
import * as NodeHttp from "node:http";

import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";

import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const DEFAULT_CURSOR_STUB_URL = "http://127.0.0.1:13998";
const WEEKLY_LIMIT_TITLE = "Weekly usage limit reached.";
const WEEKLY_LIMIT_DETAIL = "It resets in 3 days. Buy credits to keep going now.";

function encodeVarint(value: number): Buffer {
  const bytes: Array<number> = [];
  let remaining = value;
  while (remaining > 0x7f) {
    bytes.push((remaining & 0x7f) | 0x80);
    remaining >>>= 7;
  }
  bytes.push(remaining);
  return Buffer.from(bytes);
}

function encodeFieldBytes(fieldNumber: number, payload: Buffer): Buffer {
  return Buffer.concat([
    encodeVarint((fieldNumber << 3) | 2),
    encodeVarint(payload.length),
    payload,
  ]);
}

function encodeFieldVarint(fieldNumber: number, value: number): Buffer {
  return Buffer.concat([encodeVarint((fieldNumber << 3) | 0), encodeVarint(value)]);
}

// aiserver.v1.ErrorDetails { error: PRO_USER_USAGE_LIMIT (10), details: { title, detail } }
const errorDetailsProto = Buffer.concat([
  encodeFieldVarint(1, 10),
  encodeFieldBytes(
    2,
    Buffer.concat([
      encodeFieldBytes(1, Buffer.from(WEEKLY_LIMIT_TITLE, "utf8")),
      encodeFieldBytes(2, Buffer.from(WEEKLY_LIMIT_DETAIL, "utf8")),
    ]),
  ),
]);

function startFakeCursorBackend(urlString: string) {
  const url = new URL(urlString);
  const server = NodeHttp.createServer((req, res) => {
    req.resume();
    req.on("end", () => {
      if (req.url === "/v1/me") {
        res.writeHead(200, { "content-type": "application/json" });
        res.end(
          JSON.stringify({
            apiKeyName: "scenario-cursor-key",
            createdAt: "2026-01-01T00:00:00.000Z",
            userEmail: "scenario@example.invalid",
          }),
        );
        return;
      }
      if (req.url === "/v1/models") {
        res.writeHead(200, { "content-type": "application/json" });
        res.end(JSON.stringify({ items: [{ id: "default", displayName: "Auto" }] }));
        return;
      }
      if (req.url === "/auth/exchange_user_api_key") {
        res.writeHead(200, { "content-type": "application/json" });
        res.end(JSON.stringify({ accessToken: "scenario-cursor-access-token" }));
        return;
      }
      if (req.url?.includes("RunSSE")) {
        const endPayload = Buffer.from(
          JSON.stringify({
            error: {
              code: "resource_exhausted",
              message: WEEKLY_LIMIT_TITLE,
              details: [
                {
                  type: "aiserver.v1.ErrorDetails",
                  value: errorDetailsProto.toString("base64"),
                },
              ],
            },
          }),
          "utf8",
        );
        const header = Buffer.alloc(5);
        header[0] = 0x02;
        header.writeUInt32BE(endPayload.length, 1);
        res.writeHead(200, { "content-type": "application/connect+proto" });
        res.end(Buffer.concat([header, endPayload]));
        return;
      }
      if (req.headers["content-type"]?.includes("application/proto")) {
        res.writeHead(200, { "content-type": "application/proto" });
        res.end(Buffer.alloc(0));
        return;
      }
      res.writeHead(200, { "content-type": "application/json" });
      res.end("{}");
    });
  });

  return new Promise<NodeHttp.Server>((resolve, reject) => {
    server.once("error", reject);
    server.listen(Number(url.port), url.hostname, () => resolve(server));
  });
}

test(
  "Cursor SDK weekly usage limit is classified as usage_limit on turns and text generation",
  WEB,
  async ({ t3, app, screen }) => {
    const backendUrl = process.env.CURSOR_BACKEND_URL || DEFAULT_CURSOR_STUB_URL;
    const fakeBackend = await startFakeCursorBackend(backendUrl);
    const cursorId = ProviderInstanceId.make("cursor");
    const project = await t3.project("demo");

    try {
      await runPromise(
        Effect.gen(function* () {
          const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
          yield* client["server.updateSettings"]({
            patch: {
              textGenerationModelSelection: { instanceId: cursorId, model: "default" },
            },
            providerInstanceMutation: {
              operation: "upsert",
              instanceId: cursorId,
              instance: {
                driver: ProviderDriverKind.make("cursor"),
                displayName: "Cursor",
                enabled: true,
                config: {},
              },
            },
          });
        }).pipe(Effect.scoped),
      );

      const { cli } = makeState(T3_HOME);
      const started = await runPromise(
        cli(
          [
            "thread",
            "start",
            project,
            "Say hello",
            "--title",
            "Cursor weekly limit",
            "--provider",
            "cursor",
            "--model",
            "default",
            "--wait",
            "--json",
          ],
          [0, 1],
        ),
      );
      const { threadId } = JSON.parse(started.stdout) as { threadId: string };

      await t3.open({ threadId });
      await screen.getByRole("alert").first().waitFor({
        timeout: 30_000,
      });

      // Trigger text generation ("Regenerate title") from the thread menu so its error toast shows.
      await screen.getByRole("button", "Thread actions for Cursor weekly limit").tap();
      await screen.getByRole("menuitem", "Regenerate title").tap();
      await screen.getByText("Failed to regenerate thread title").waitFor({ timeout: 30_000 });
      await new Promise((resolve) => setTimeout(resolve, 450));
      await app.screenshot("cursor-weekly-limit");

      await expect(screen.getByText("Usage limit reached").first()).toBeVisible({
        timeout: 5_000,
      });
      await expect(
        screen.getByText(
          "Cursor usage limit reached. Try again later or choose another text-generation provider.",
          { exact: false },
        ),
      ).toBeVisible({ timeout: 5_000 });
    } finally {
      await runPromise(
        Effect.gen(function* () {
          const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
          yield* client["server.updateSettings"]({
            patch: {},
            providerInstanceMutation: {
              operation: "upsert",
              instanceId: cursorId,
              instance: {
                driver: ProviderDriverKind.make("cursor"),
                displayName: "Cursor",
                enabled: false,
                config: {},
              },
            },
          });
        }).pipe(Effect.scoped),
      ).catch(() => {});
      await new Promise<void>((resolve) => fakeBackend.close(() => resolve()));
    }
  },
);

Not verified / requires a live account

  • Not verified against a live Cursor account hitting a real weekly usage limit (the offline ConnectRPC stub sends the exact aiserver.v1.ErrorDetails PRO_USER_USAGE_LIMIT wire payload through the real @cursor/sdk@1.5.2 worker).

Note

Written by Gemini 4 Neon in T3 Code on behalf of Stefan.

@github-actions github-actions Bot added vouch:trusted Author is trusted by repo permissions or the VOUCHED list. size:M labels Nov 29, 2026
@smirea
smirea force-pushed the fix/cursor-weekly-usage-limit branch from 94adcc7 to 73c51a1 Compare November 29, 2026 21:44
@smirea

smirea commented Nov 29, 2026

Copy link
Copy Markdown
Owner Author

Opened upstream as pingdotgg#45740 (fixes pingdotgg#45739).

@smirea smirea closed this Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M vouch:trusted Author is trusted by repo permissions or the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant