mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Users connect external MCP servers and OAuth apps in Paperclip so
agents can use their tools
> - When a remote MCP server or OAuth authorization server rejects
automatic registration or discovery (for example, returning HTTP 400
`invalid_redirect_uri` during Dynamic Client Registration), Paperclip
returns HTTP 502 with a structured upstream error payload
> - The UI error classifier previously treated every HTTP 502 without a
`CODE_COPY` entry as a Paperclip outage, so it discarded the server
message and showed "Paperclip is temporarily unavailable"
> - This pull request shares a canonical allowlist of upstream
MCP/OAuth/remote HTTP 502 error codes between the server and UI,
preserves upstream error messages with accurate retryability, shows
clear sign-in guidance with Paperclip's copyable callback URL, and
resumes the saved draft connection during manual client recovery
> - The benefit is that users immediately see why a remote MCP server
rejected sign-in and how to fix it (allowlisting Paperclip's callback
URL or entering a client ID) without hitting a false Paperclip outage or
creating duplicate connections
## Linked Issues or Issue Description
**What happened?**
When a user connects a remote MCP server with browser sign-in and the
remote authorization server rejects Dynamic Client Registration (for
example, returning HTTP 400 `invalid_redirect_uri` because it requires a
client allowlist), the Paperclip server returns HTTP 502 with `{ error:
"The authorization server rejected Paperclip's callback URL.", details:
{ code: "oauth_dynamic_client_registration_failed", providerError:
"invalid_redirect_uri", status: 400 } }`. The UI classified that HTTP
502 as a transient connectivity outage and displayed "Paperclip is
temporarily unavailable. Please try again in a moment." instead of the
actual reason.
**Expected behavior**
Paperclip should preserve its server-authored error message for
allowlisted upstream HTTP 502 responses, derive `retryable` accurately
(non-retryable for permanent upstream rejections, retryable for upstream
outages/5xx/rate-limits/timeouts), and avoid triggering the app-wide
outage banner. In the MCP connection flow, Paperclip should explain why
the remote server rejected automatic sign-in setup, expand the Browser
sign-in section with Paperclip's copyable callback URL above Client ID
and Client secret, and resume the saved draft connection instead of
creating duplicate numbered connections when the user retries.
**Steps to reproduce**
1. Open Apps and connect a custom MCP server URL whose OAuth
authorization server rejects Dynamic Client Registration (such as HTTP
400 `invalid_redirect_uri` or another upstream registration/metadata
error).
2. Start browser sign-in.
3. Observe that Paperclip previously showed "Paperclip is temporarily
unavailable. Please try again in a moment." instead of explaining the
callback URL or registration rejection.
**Paperclip version or commit**
Reproduced on `master` at commit `2d764bebc6` (and prior `bc98abda0c`).
**Deployment mode**
Other (applies to both Paperclip Cloud and self-hosted deployments).
## What Changed
- **Shared contracts (`packages/shared`)**:
- Added `packages/shared/src/upstream-failure-codes.ts` (re-exported
from `packages/shared/src/index.ts`) defining the single canonical
allowlist of upstream HTTP 502 error codes
(`UPSTREAM_MCP_OAUTH_FAILURE_CODES`,
`UPSTREAM_REMOTE_HTTP_FAILURE_CODES`,
`UPSTREAM_BAD_GATEWAY_FAILURE_CODES`,
`isUpstreamBadGatewayFailureCode`), transient HTTP status helper
(`TRANSIENT_UPSTREAM_HTTP_STATUSES`, `isTransientUpstreamHttpStatus`),
and shared retryability policy (`isRetryableUpstreamFailure`). Transient
HTTP statuses (408, 425, 429, and 5xx) are checked before the permanent
`oauth_dynamic_client_registration_failed` fallback so rate-limited or
timed-out registration attempts remain retryable. Any unlisted
structured 502 still falls back to the transient outage path.
- Updated `connectToolAppSchema` in
`packages/shared/src/validators/tool-access.ts` so `resumeConnectionId`
works for generic `link` connections as well as gallery apps (still
requiring `galleryKey || link`), enabling the recovery path to resume a
saved generic MCP draft instead of creating a duplicate connection.
- **Server (`server/`)**:
- Updated `server/src/services/mcp-connection-failure.ts` so
`mcpDiscoveryHttpFailure` emits `{ code: "mcp_remote_http_error", status
}` in `HttpError` details.
- Updated `server/src/services/tool-access/catalog/failures.ts` so
`sanitizeHttpFailure` imports `UPSTREAM_MCP_OAUTH_FAILURE_CODES` from
`@paperclipai/shared` and preserves upstream MCP/OAuth failure codes
with HTTP 502 instead of collapsing them to `"paperclip_error"`.
- Updated `server/src/routes/tool-access.ts` so when `svc.startOAuth`
throws a non-manual-client `HttpError` after creating a `draft`
connection, `error.details` includes `connectionId:
result.connectionId`.
- Updated `server/src/services/tool-access.ts` (`connectGalleryApp`) so
resuming a draft via `resumeConnectionId` with a generic `link` enforces
that the draft is not a curated gallery app and that its stored MCP
endpoint matches the requested `link`.
- **UI (`ui/`)**:
- Updated `ui/src/api/errors.ts` so `isStructuredUpstreamBadGateway` and
`isRetryableUpstreamBadGateway` delegate to
`isUpstreamBadGatewayFailureCode` and `isRetryableUpstreamFailure` from
`@paperclipai/shared` (keeping unlisted structured 502s,
`ApiUnavailableError`, and `TRANSIENT_CODES` on the outage banner path,
and returning `retryable: false` for permanent upstream rejections vs
`retryable: true` for upstream 5xx, rate limits, timeouts, or temporary
outages).
- Updated `ui/src/pages/apps/generic-mcp-connect.ts` with
`"oauth_client"` focus, plain-English guidance for DCR (including
temporary rate-limit/timeout/5xx guidance with `focus: "none"` vs
permanent rejection guidance with `focus: "oauth_client"`), metadata,
redirect, token, and remote HTTP failures, plus pure
`genericGuidanceFormPatch` and `resolveGenericDraftResumeId` helpers.
- Updated `ui/src/features/connections/oauthFailureMessages.ts` to cover
`oauth_dynamic_client_registration_failed` (including transient HTTP
429/408/425/5xx responses), `oauth_dcr_response_invalid`, and
`oauth_metadata_failed`, extract `connectionId` in
`readOAuthApiErrorDetails`, and add `oauthStartFailureMessage`.
- Added `ui/src/features/connections/useGenericDraftResume.ts`
(`useGenericDraftResume` + `grantKindFromConnection`) and updated
`ui/src/features/connections/GenericMcpConnectStep.tsx`,
`ui/src/features/connections/ConnectionSetupFlow.tsx`, and
`ui/src/pages/tools/PasteConfigTab.tsx` to deduplicate guidance form
transitions via `applyGenericConnectGuidance`, preserve and resume the
failed generic draft connection ID across retries without creating
duplicates while starting a fresh draft if the URL, company, credential
ownership (`grantKind`), or dedicated agent changes, clear stale drafts
on `404` / `connection_setup_not_incomplete`, display Paperclip's
copyable callback URL (using `useCopyAction`) above Client ID and Client
secret when Browser sign-in expands, and remove the unused `ApiError`
import. No source file crossed the 1,000-line threshold
(`ConnectionSetupFlow.tsx` and `tool-access.ts` were already above 1,000
lines).
- **Tests**:
- Synchronized `tests/runner-e2e/source-sdk-public-inputs.json` for the
`@paperclipai/shared` public source graph.
- Added/updated regression tests in
`packages/shared/src/upstream-failure-codes.test.ts`,
`packages/shared/src/validators/tool-access.test.ts`,
`ui/src/api/errors.test.ts`,
`ui/src/pages/apps/generic-mcp-connect.test.ts`,
`ui/src/features/connections/oauthFailureMessages.test.ts`,
`ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx`,
`ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx`,
`server/src/services/tool-access/catalog/failures.test.ts`,
`server/src/services/__tests__/mcp-connection-failure.test.ts`, and
`server/src/__tests__/generic-mcp-connection.test.ts`.
## Verification
Ran on latest commit `9d088abf91`:
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/shared exec
vitest run src/upstream-failure-codes.test.ts
src/validators/tool-access.test.ts` — passed (2 files, 20 tests).
- `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors).
- `pnpm --filter @paperclipai/ui exec vitest run src/api/errors.test.ts
src/pages/apps/generic-mcp-connect.test.ts
src/features/connections/oauthFailureMessages.test.ts
src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx
src/features/connections/ConnectionSetupFlow.oauth.test.ts` — passed (5
files, 140 tests).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`changed: false`, 582 inputs).
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — passed (13 tests).
Full GitHub CI & review gates on final head `9d088abf91` ([`ci` run
46468259760](https://github.com/paperclipai/paperclip/actions/runs/46468259760)):
- `ci / verify`, `ci / e2e` (all 16 shards), `ci / Typecheck + Release
Registry`, `ci / policy`, `ci / General tests` (20/20), `ci / Runner
support suite` (4/4), `ci / Verify Paperclip` (9/9), `ci / Verify
serialized server suites` (9/9), `ci / Sandbox profile`, `Superagent
Security Scan`, `Socket Security`, `Contributor trust`, `security/snyk`,
`commitperclip PR Review`, and `Greptile Review` (5/5, 0 unresolved
threads) all passed on `9d088abf91`.
Visual states covered via component and flow tests using existing design
tokens (`border-input`, `bg-muted/40`, `text-foreground`,
`text-muted-foreground`): initial generic MCP connect step, expanded
Browser sign-in with copyable Paperclip callback URL (`Copy` / `Copied`
/ `Copy failed`), inline guidance banner for DCR/metadata/credential
errors (including transient rate-limit/timeout/5xx copy), draft resume
on manual client retry, fresh draft creation on access ownership change,
and draft clearing on `404` / `connection_setup_not_incomplete`.
## Risks
- Low risk. Uncoded HTTP 502 responses, unlisted structured 502 codes,
proxy HTML `ApiUnavailableError` responses, and `tenant_app_unavailable`
/ `tenant_app_starting` responses still classify as `"transient"` and
still trigger the app-wide outage banner.
- Security: Untrusted upstream OAuth `error_description`, `error_uri`,
and response bodies remain blocked; only Paperclip-authored messages and
allowlisted RFC error codes drive UI copy. Generic draft resume enforces
route-level configure authorization
(`assertToolConnectionConfigureAccess`), rejects curated gallery drafts,
and requires a matching normalized server endpoint.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Google DeepMind Antigravity (Gemini-based coding agent via ACPX
runtime) with tool use and 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
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
325 lines
14 KiB
TypeScript
325 lines
14 KiB
TypeScript
import { CancelledError } from "@tanstack/react-query";
|
||
import { describe, expect, it } from "vitest";
|
||
import { ApiError } from "./api-error";
|
||
import {
|
||
apiErrorMessage,
|
||
classifyError,
|
||
describeError,
|
||
errorCodes,
|
||
isConnectivityError,
|
||
isRawErrorCode,
|
||
isTransientError,
|
||
parseRetryAfter,
|
||
type ErrorKind,
|
||
} from "./errors";
|
||
import { ApiUnavailableError } from "./response";
|
||
|
||
function apiError(status: number, body: unknown = null) {
|
||
return new ApiError(apiErrorMessage(status, body), status, body);
|
||
}
|
||
|
||
describe("classifyError", () => {
|
||
it.each<[string, unknown, ErrorKind]>([
|
||
["a browser network failure", new TypeError("Failed to fetch"), "transient"],
|
||
["a Safari network failure", new TypeError("Load failed"), "transient"],
|
||
["a proxy HTML page", new ApiUnavailableError(502), "transient"],
|
||
["408", apiError(408), "transient"],
|
||
["425", apiError(425), "transient"],
|
||
["429", apiError(429, { error: "Too many requests" }), "transient"],
|
||
["502", apiError(502), "transient"],
|
||
["502 without a structured code", apiError(502, { error: "Bad gateway" }), "transient"],
|
||
["503", apiError(503, { error: "Service unavailable" }), "transient"],
|
||
["504", apiError(504), "transient"],
|
||
["401", apiError(401, { error: "Unauthorized" }), "auth"],
|
||
["403", apiError(403, { error: "Forbidden" }), "forbidden"],
|
||
["404", apiError(404, { error: "Issue not found" }), "not_found"],
|
||
["410", apiError(410), "not_found"],
|
||
["409", apiError(409, { error: "Document is locked" }), "conflict"],
|
||
["412", apiError(412), "conflict"],
|
||
["400", apiError(400, { error: "Title is required" }), "invalid"],
|
||
["422", apiError(422), "invalid"],
|
||
["500", apiError(500, { error: "boom" }), "unknown"],
|
||
["an abort", new DOMException("Aborted", "AbortError"), "aborted"],
|
||
["a React Query cancellation", new CancelledError({ revert: false }), "aborted"],
|
||
["a programming TypeError", new TypeError("Cannot read properties of undefined"), "unknown"],
|
||
["a plain Error", new Error("nope"), "unknown"],
|
||
["undefined", undefined, "unknown"],
|
||
])("classifies %s", (_label, error, kind) => {
|
||
expect(classifyError(error)).toBe(kind);
|
||
});
|
||
|
||
it.each([200, 400, 403, 404, 409, 500, 502])(
|
||
"treats the gateway's tenant_app_unavailable as transient in any status (%s)",
|
||
(status) => {
|
||
expect(classifyError(apiError(status, { error: "tenant_app_unavailable" }))).toBe("transient");
|
||
expect(classifyError(apiError(status, { code: "tenant_app_unavailable" }))).toBe("transient");
|
||
expect(classifyError(apiError(status, { error: "tenant_app_starting" }))).toBe("transient");
|
||
},
|
||
);
|
||
|
||
it.each(["WORKER_UNAVAILABLE", "TIMEOUT"])("treats plugin bridge %s as transient", (code) => {
|
||
expect(classifyError(apiError(500, { code, message: "Plugin worker is restarting" }))).toBe("transient");
|
||
});
|
||
|
||
it("reads a code from details, as HttpErrors serialize it", () => {
|
||
const error = apiError(409, { error: "Locked", details: { code: "tenant_app_starting" } });
|
||
expect(classifyError(error)).toBe("transient");
|
||
});
|
||
|
||
it("does not classify a structured upstream MCP/OAuth 502 from Paperclip as a Paperclip outage", () => {
|
||
const dcrError = apiError(502, {
|
||
error: "The authorization server rejected Paperclip's callback URL.",
|
||
code: "oauth_dynamic_client_registration_failed",
|
||
details: {
|
||
code: "oauth_dynamic_client_registration_failed",
|
||
providerError: "invalid_redirect_uri",
|
||
status: 400,
|
||
},
|
||
});
|
||
const detailsOnlyError = apiError(502, {
|
||
error: "Remote app returned HTTP 500",
|
||
details: { code: "mcp_remote_http_error", status: 500 },
|
||
});
|
||
|
||
expect(classifyError(dcrError)).toBe("unknown");
|
||
expect(isTransientError(dcrError)).toBe(false);
|
||
expect(classifyError(detailsOnlyError)).toBe("unknown");
|
||
expect(isTransientError(detailsOnlyError)).toBe(false);
|
||
});
|
||
|
||
it("keeps non-upstream structured 502 codes on the transient outage path", () => {
|
||
const nonUpstream502 = apiError(502, {
|
||
error: "Cloud stack signing key is not configured",
|
||
code: "cloud_inference_auth_unconfigured",
|
||
details: { code: "cloud_inference_auth_unconfigured" },
|
||
});
|
||
const unknownCode502 = apiError(502, {
|
||
error: "Gateway backend failed",
|
||
details: { code: "internal_gateway_fault" },
|
||
});
|
||
|
||
expect(classifyError(nonUpstream502)).toBe("transient");
|
||
expect(isConnectivityError(nonUpstream502)).toBe(true);
|
||
expect(classifyError(unknownCode502)).toBe("transient");
|
||
expect(isConnectivityError(unknownCode502)).toBe(true);
|
||
});
|
||
|
||
it("classifies structurally, without the ApiError class", () => {
|
||
expect(classifyError({ status: 503, body: null })).toBe("transient");
|
||
expect(classifyError({ name: "AuthApiError", status: 401, code: null })).toBe("auth");
|
||
});
|
||
});
|
||
|
||
describe("isConnectivityError", () => {
|
||
it("is true for server-wide outages only", () => {
|
||
expect(isConnectivityError(new TypeError("Failed to fetch"))).toBe(true);
|
||
expect(isConnectivityError(new ApiUnavailableError(200))).toBe(true);
|
||
expect(isConnectivityError(new ApiUnavailableError(502))).toBe(true);
|
||
expect(isConnectivityError(apiError(502))).toBe(true);
|
||
expect(isConnectivityError(apiError(502, { error: "Bad gateway" }))).toBe(true);
|
||
expect(isConnectivityError(apiError(502, { code: "tenant_app_unavailable" }))).toBe(true);
|
||
expect(isConnectivityError(apiError(502, { code: "internal_gateway_fault" }))).toBe(true);
|
||
expect(isConnectivityError(apiError(503))).toBe(true);
|
||
expect(isConnectivityError(apiError(404, { error: "tenant_app_unavailable" }))).toBe(true);
|
||
expect(isConnectivityError(apiError(502, {
|
||
error: "The authorization server rejected Paperclip's callback URL.",
|
||
details: { code: "oauth_dynamic_client_registration_failed", providerError: "invalid_redirect_uri" },
|
||
}))).toBe(false);
|
||
expect(isConnectivityError(apiError(502, {
|
||
error: "Remote MCP server returned HTTP 500",
|
||
code: "mcp_catalog_error",
|
||
}))).toBe(false);
|
||
// Transient, but one route: left to query retry, not the app banner.
|
||
expect(isConnectivityError(apiError(429))).toBe(false);
|
||
expect(isConnectivityError(apiError(503, { code: "WORKER_UNAVAILABLE", message: "x" }))).toBe(false);
|
||
expect(isConnectivityError(apiError(500))).toBe(false);
|
||
expect(isConnectivityError(apiError(403))).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe("describeError", () => {
|
||
const rawCode = /\b[a-z]+(?:_[a-z]+)+\b|\b[A-Z]+_[A-Z]+\b/;
|
||
|
||
it("never returns a raw code", () => {
|
||
const errors = [
|
||
apiError(503, { error: "tenant_app_unavailable" }),
|
||
apiError(200, { error: "tenant_app_starting" }),
|
||
apiError(404, { error: "issue_not_found" }),
|
||
apiError(500, { error: "internal_error" }),
|
||
apiError(502, { error: "oauth_dynamic_client_registration_failed", details: { code: "oauth_dynamic_client_registration_failed" } }),
|
||
apiError(503, { code: "WORKER_UNAVAILABLE", message: "WORKER_UNAVAILABLE" }),
|
||
new ApiError("tenant_app_unavailable", 503, { error: "tenant_app_unavailable" }),
|
||
];
|
||
for (const error of errors) {
|
||
const { title, body } = describeError(error);
|
||
expect(title).not.toMatch(rawCode);
|
||
expect(body).not.toMatch(rawCode);
|
||
}
|
||
});
|
||
|
||
it("uses the shared transient copy for outages", () => {
|
||
expect(describeError(new ApiUnavailableError(502))).toEqual({
|
||
title: "Connection interrupted",
|
||
body: "Paperclip is temporarily unavailable. Please try again in a moment.",
|
||
retryable: true,
|
||
});
|
||
expect(describeError(apiError(503, { error: "tenant_app_unavailable" }))).toMatchObject({
|
||
title: "Reconnecting to Paperclip",
|
||
retryable: true,
|
||
});
|
||
});
|
||
|
||
it("preserves Paperclip's message for structured upstream 502 errors and derives retryability accurately", () => {
|
||
const rejectedDcr = apiError(502, {
|
||
error: "The authorization server rejected Paperclip's callback URL.",
|
||
details: {
|
||
code: "oauth_dynamic_client_registration_failed",
|
||
providerError: "invalid_redirect_uri",
|
||
status: 400,
|
||
},
|
||
});
|
||
expect(describeError(rejectedDcr, { action: "connect this server" })).toEqual({
|
||
title: "Couldn't connect this server",
|
||
body: "The authorization server rejected Paperclip's callback URL.",
|
||
retryable: false,
|
||
});
|
||
|
||
const providerOutageDcr = apiError(502, {
|
||
error: "The authorization server failed during dynamic client registration.",
|
||
details: {
|
||
code: "oauth_dynamic_client_registration_failed",
|
||
providerError: "temporarily_unavailable",
|
||
status: 503,
|
||
},
|
||
});
|
||
expect(describeError(providerOutageDcr, { action: "connect this server" })).toEqual({
|
||
title: "Couldn't connect this server",
|
||
body: "The authorization server failed during dynamic client registration.",
|
||
retryable: true,
|
||
});
|
||
|
||
const rateLimitedDcr = apiError(502, {
|
||
error: "The authorization server rate-limited dynamic client registration.",
|
||
details: {
|
||
code: "oauth_dynamic_client_registration_failed",
|
||
status: 429,
|
||
},
|
||
});
|
||
expect(describeError(rateLimitedDcr, { action: "connect this server" })).toEqual({
|
||
title: "Couldn't connect this server",
|
||
body: "The authorization server rate-limited dynamic client registration.",
|
||
retryable: true,
|
||
});
|
||
|
||
const upstream5xx = apiError(502, {
|
||
error: "Remote app returned HTTP 500",
|
||
details: {
|
||
code: "mcp_remote_http_error",
|
||
status: 500,
|
||
},
|
||
});
|
||
expect(describeError(upstream5xx)).toMatchObject({
|
||
body: "Remote app returned HTTP 500",
|
||
retryable: true,
|
||
});
|
||
|
||
const upstream404 = apiError(502, {
|
||
error: "Remote app returned HTTP 404",
|
||
details: {
|
||
code: "mcp_remote_http_error",
|
||
status: 404,
|
||
},
|
||
});
|
||
expect(describeError(upstream404)).toMatchObject({
|
||
body: "Remote app returned HTTP 404",
|
||
retryable: false,
|
||
});
|
||
});
|
||
|
||
it("keeps a readable server message for client errors", () => {
|
||
expect(describeError(apiError(400, { error: "Title is required" }))).toEqual({
|
||
title: "Check your input",
|
||
body: "Title is required",
|
||
retryable: false,
|
||
});
|
||
});
|
||
|
||
it("keeps an OAuth error description instead of generic not-found copy", () => {
|
||
const error = apiError(404, {
|
||
error: "invalid_request",
|
||
error_description: "This code is expired, already decided, or invalid. Start a new connection from your assistant.",
|
||
});
|
||
expect(describeError(error).body).toBe("This code is expired, already decided, or invalid. Start a new connection from your assistant.");
|
||
expect(error.message).toBe("This code is expired, already decided, or invalid. Start a new connection from your assistant.");
|
||
});
|
||
|
||
it("falls back to the kind's copy when the server sent a code or nothing", () => {
|
||
expect(describeError(apiError(404, { error: "issue_not_found" })).body).toBe("This item doesn’t exist or was moved.");
|
||
expect(describeError(apiError(403, null))).toMatchObject({ title: "Not allowed", retryable: false });
|
||
expect(describeError(new Error("Something odd"))).toMatchObject({ body: "Something odd", retryable: true });
|
||
expect(describeError(undefined)).toMatchObject({ title: "Something went wrong", retryable: true });
|
||
});
|
||
|
||
it("names the action in the title for real failures, not outages", () => {
|
||
expect(describeError(apiError(409, { error: "Document is locked" }), { action: "save the document" })).toEqual({
|
||
title: "Couldn't save the document",
|
||
body: "Document is locked",
|
||
retryable: false,
|
||
});
|
||
expect(describeError(apiError(503), { action: "save the document" }).title).toBe("Connection interrupted");
|
||
});
|
||
});
|
||
|
||
describe("ApiError", () => {
|
||
it("keeps the raw body.error as code and a readable message", () => {
|
||
const error = apiError(503, { error: "tenant_app_unavailable" });
|
||
expect(error.code).toBe("tenant_app_unavailable");
|
||
expect(error.message).toBe("Paperclip is restarting or updating. Please try again in a moment.");
|
||
});
|
||
|
||
it("passes a readable server message through unchanged", () => {
|
||
const error = apiError(409, { error: "Document is locked" });
|
||
expect(error.code).toBe("Document is locked");
|
||
expect(error.message).toBe("Document is locked");
|
||
});
|
||
|
||
it("replaces the generic status line with readable copy", () => {
|
||
expect(apiError(404).message).toBe("This item doesn’t exist or was moved.");
|
||
expect(apiError(404).code).toBeNull();
|
||
});
|
||
|
||
it("exposes every code for matching", () => {
|
||
expect(errorCodes(apiError(403, { error: "Denied", code: "interaction_human_only", details: { code: "x_y" } })))
|
||
.toEqual(["Denied", "interaction_human_only", "x_y"]);
|
||
});
|
||
});
|
||
|
||
describe("isRawErrorCode", () => {
|
||
it.each(["tenant_app_unavailable", "WORKER_UNAVAILABLE", "TIMEOUT", "issue.not_found", "forbidden", "unauthorized", "conflict"])("%s is a code", (value) => {
|
||
expect(isRawErrorCode(value)).toBe(true);
|
||
});
|
||
|
||
it.each(["Forbidden", "Unauthorized", "Document is locked", "Request failed: 503", ""])("%s is not a code", (value) => {
|
||
expect(isRawErrorCode(value)).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe("parseRetryAfter", () => {
|
||
it("parses delta-seconds", () => {
|
||
expect(parseRetryAfter("5")).toBe(5_000);
|
||
expect(parseRetryAfter(" 1.5 ")).toBe(1_500);
|
||
});
|
||
|
||
it("parses an HTTP date relative to now", () => {
|
||
const now = Date.parse("2026-10-09T12:00:00Z");
|
||
expect(parseRetryAfter("Fri, 09 Oct 2026 12:00:30 GMT", now)).toBe(30_000);
|
||
expect(parseRetryAfter("Fri, 09 Oct 2026 11:00:00 GMT", now)).toBe(0);
|
||
});
|
||
|
||
it("caps absurd values and ignores garbage", () => {
|
||
expect(parseRetryAfter("86400")).toBe(5 * 60_000);
|
||
expect(parseRetryAfter("soon")).toBeNull();
|
||
expect(parseRetryAfter(null)).toBeNull();
|
||
});
|
||
});
|