fix(server): show a retry message when managed app sign-in is rate-limited (#22309)

## 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 "`<App>`
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 <noreply@anthropic.com>
Co-authored-by: paperclipbugbot <bots+paperclipbugbot@paperclip.ing>
This commit is contained in:
authored and GitHub committed 2026-11-20 03:57:19 -08:00
1 parent 62bc0519d9
commit d60cecf625
2 files changed
+80 -12

No files matched your search

@@ -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<typeof createOAuthEndpointPolicy>["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(