From d60cecf62558996f9c9ca4ca4e12dd2dc2cee99b Mon Sep 17 00:00:00 2001 From: Michael Nguyen <13559011+nguyenm7@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:57:19 -0800 Subject: [PATCH] fix(server): show a retry message when managed app sign-in is rate-limited (#22309) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People connect apps such as GitHub through the Paperclip Cloud connector > - The connector `session` call can return 429 with the reason `RATE_LIMITED` > - The OAuth start path does not catch this error, so the server answers 500 > - A 500 tells the user that Paperclip is broken. It does not tell the user to try again later. The error also goes to error reporting as a server crash > - This pull request changes a connector rate limit into a 429 with a clear retry message > - The benefit is that users see "try again in a moment" and the server does not report a false crash ## Linked Issues or Issue Description **What happened?** A user on a Cloud beta workspace started GitHub connect two times. The Paperclip Cloud connector rate-limited the `session` call (status 429, reason `RATE_LIMITED`). Both times, the UI showed an internal server error. **Steps to reproduce** 1. Use a Cloud connector where the `session` call returns 429 `RATE_LIMITED`. 2. POST `/api/companies/:companyId/tools/apps/connect` with `galleryKey: "github"` and `connectionMethodKey: "managed"`. 3. Look at the response status. **Expected behavior** The server answers 429 with a readable message and retry guidance. **Actual behavior** The server answers 500 with "Internal server error". No public GitHub issue exists for this. ## What Changed - `server/src/services/tool-access/oauth/authorization-start.ts`: the managed connector branch catches errors from `startAuthorization`. A `PaperclipCloudConnectorError` with status 429 or broker reason `RATE_LIMITED` becomes an `HttpError` 429. The message is "`` sign-in is busy right now. Try again in a moment.", the code is `paperclip_cloud_connector_rate_limited`, and `details.retryAfterSeconds` comes from the broker `Retry-After` value when the broker sends one. - All other errors pass through with no change. - `server/src/__tests__/tool-access-service.test.ts`: a new route test for a rate-limited managed GitHub connect. It checks the 429 status, the message, the code, `retryAfterSeconds`, and that the raw broker reason is not in the response. ## Verification - Reproduced first: before the fix, the new test failed with `expected 500 to be 429`. - `pnpm exec vitest run src/__tests__/tool-access-service.test.ts` in `server/`: 514 tests pass. - `pnpm typecheck` in `server/`: no errors in `server/src`. The local run reported errors only in sibling packages that the limited local install did not include. CI runs the full check. - The UI uses the `error` string of the response body as the message (`ui/src/api/errors.ts` `apiErrorMessage`), so the user sees the new text. ## Risks - Low risk. The change applies only to the managed connector sign-in start, and only when the connector reports a rate limit. - The response does not set a `Retry-After` header. The retry delay is in `details.retryAfterSeconds`, the same as other 429 responses that the service layer makes. - This change does not change the broker rate limit. A separate investigation must find out why the broker rate-limits the `session` call. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with tool use and shell code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 Co-authored-by: paperclipbugbot --- .../src/__tests__/tool-access-service.test.ts | 51 +++++++++++++++++++ .../tool-access/oauth/authorization-start.ts | 41 ++++++++++----- 2 files changed, 80 insertions(+), 12 deletions(-) diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 7571e18b2ea..8aac435e157 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -8794,6 +8794,57 @@ describeEmbeddedPostgres("tool access service", () => { } }); + it("answers a rate-limited managed GitHub sign-in start with 429 and retry guidance", async () => { + const company = await createCompany(db); + const userId = `github-rate-limited-${randomUUID()}`; + await grantBoardUser(db, company.id, userId, [], "owner"); + const connector = fakeGitHubConnector(company.id, userId); + connector.startAuthorization = vi.fn(async () => { + throw new PaperclipCloudConnectorError( + "Paperclip Cloud connector rejected the request (operation=session, status=429, reason=RATE_LIMITED)", + "CONNECTOR_REQUEST_FAILED", + 429, + Date.now() + 30_000, + "RATE_LIMITED", + ); + }); + const githubDefinition = getConnectableAppDefinition("github")!; + const previousOwnershipAvailability = + githubDefinition.ownershipAvailability; + githubDefinition.ownershipAvailability = { + ...previousOwnershipAvailability, + platform_shared: true, + }; + try { + const app = createRouteApp( + db, + boardSessionActor(company.id, "owner", userId), + undefined, + { paperclipCloudConnector: connector }, + ); + const connected = await request(app) + .post(`/api/companies/${company.id}/tools/apps/connect`) + .send({ + galleryKey: "github", + connectionMethodKey: "managed", + grantKind: "user", + name: "GitHub", + }); + + expect(connector.startAuthorization).toHaveBeenCalled(); + expect(connected.status).toBe(429); + expect(connected.body).toMatchObject({ + error: "GitHub sign-in is busy right now. Try again in a moment.", + code: "paperclip_cloud_connector_rate_limited", + }); + expect(connected.body.details.retryAfterSeconds).toBeGreaterThan(0); + expect(connected.body.details.retryAfterSeconds).toBeLessThanOrEqual(30); + expect(JSON.stringify(connected.body)).not.toContain("RATE_LIMITED"); + } finally { + githubDefinition.ownershipAvailability = previousOwnershipAvailability; + } + }); + it.each(["user", "organization"] as const)("builds one Workspace catalog from actual partial consent for a %s grant", async (grantKind) => { const company = await createCompany(db); const userId = `workspace-member-${randomUUID()}`; diff --git a/server/src/services/tool-access/oauth/authorization-start.ts b/server/src/services/tool-access/oauth/authorization-start.ts index 3dedf46c813..aae8a71d8cd 100644 --- a/server/src/services/tool-access/oauth/authorization-start.ts +++ b/server/src/services/tool-access/oauth/authorization-start.ts @@ -13,8 +13,8 @@ import type { Db } from "@paperclipai/db"; import { companies, agents, connectionGrants, issueThreadInteractions, toolConnections, toolOauthStates } from "@paperclipai/db"; import type { ConnectionGrantKind, ToolOAuthStartResult } from "@paperclipai/shared"; import { getConnectableAppDefinition } from "@paperclipai/shared"; -import { badRequest, conflict, forbidden, notFound, unprocessable } from "../../../errors.js"; -import { isPaperclipCloudConnectorStrategy, paperclipCloudConnectorConsentAllowed, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; +import { badRequest, conflict, forbidden, notFound, tooManyRequests, unprocessable } from "../../../errors.js"; +import { isPaperclipCloudConnectorStrategy, PaperclipCloudConnectorError, paperclipCloudConnectorConsentAllowed, type PaperclipCloudConnector } from "../../paperclip-cloud-connector.js"; import { deriveVercelConnectSubject, vercelConnectCallbackUrl, VercelConnectClientError, type VercelConnectClient } from "../../vercel-connect.js"; import type { ConnectionSetupPolicy } from "../connections/setup-policy.js"; @@ -36,6 +36,18 @@ type Dependencies = { assertOAuthEndpointUrl: ReturnType["assertOAuthEndpointUrl"]; }; +function cloudConnectorStartHttpError(error: unknown, providerName: string, at: Date): unknown { + if (!(error instanceof PaperclipCloudConnectorError)) return error; + if (error.status !== 429 && error.brokerReason !== "RATE_LIMITED") return error; + const retryAfterSeconds = error.retryAt === undefined + ? undefined + : Math.max(1, Math.ceil((error.retryAt - at.getTime()) / 1000)); + return tooManyRequests(`${providerName} sign-in is busy right now. Try again in a moment.`, { + code: "paperclip_cloud_connector_rate_limited", + ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }), + }); +} + export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies) { const { now, getConnectionRow, setupPolicy, fixedPersonalIdentityForReconnect, currentCloudConnector, vercelConnect, ensureOAuthClient, oauthEndpointsForConnection, assertOAuthEndpointUrl } = dependencies; const { assertConnectorConnectionSetupEnabled, assertExperimentalConnectorSetupEnabled } = setupPolicy; @@ -395,16 +407,21 @@ export function createOAuthAuthorizationStart(db: Db, dependencies: Dependencies returnUri.pathname = "/api/tools/oauth/cloud-connector/callback"; returnUri.search = ""; returnUri.hash = ""; - const session = await cloudConnector.startAuthorization({ - subject: authorizationSubjectAgentId - ? `agent:${authorizationSubjectAgentId}` - : subjectUserId!, - companyId, - profile: managedProfile.id, - ...(managedProfile.id === "workspace.all" ? { scopes: requestedScopes! } : {}), - returnUri: returnUri.toString(), - returnState: state, - }); + let session; + try { + session = await cloudConnector.startAuthorization({ + subject: authorizationSubjectAgentId + ? `agent:${authorizationSubjectAgentId}` + : subjectUserId!, + companyId, + profile: managedProfile.id, + ...(managedProfile.id === "workspace.all" ? { scopes: requestedScopes! } : {}), + returnUri: returnUri.toString(), + returnState: state, + }); + } catch (error) { + throw cloudConnectorStartHttpError(error, providerName, now()); + } const remoteExpiry = new Date(session.expiresAt); const expiresAt = Number.isFinite(remoteExpiry.getTime()) ? new Date(