Files
PaperClipAI/ui/src/api/errors.ts
T
DottaandPaperclip a1b9eed57d fix(mcp): stop masking upstream MCP and OAuth 502 errors as Paperclip outages (#23295)
## 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>
2026-11-30 14:20:23 -06:00

355 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Shared error classification and user-facing copy.
*
* Every surface that reacts to a failed request asks two questions: "is this a
* blip that will fix itself?" and "what do I tell the user?". This module is
* the single answer to both, so retry policy, the connectivity banner, toasts,
* and inline errors agree with each other.
*
* Classification is structural on purpose: it reads `status`, `code`, `body`,
* and `name` instead of importing `ApiError`/`ApiUnavailableError`, so the API
* client can depend on this module without an import cycle, and errors thrown
* by hand-rolled fetches (health, uploads) classify the same way.
*/
import {
isRetryableUpstreamFailure,
isUpstreamBadGatewayFailureCode,
} from "@paperclipai/shared";
import { CancelledError } from "@tanstack/react-query";
export type ErrorKind =
| "transient"
| "auth"
| "forbidden"
| "not_found"
| "conflict"
| "invalid"
| "aborted"
| "unknown";
export interface ErrorDescription {
title: string;
body: string;
/** True when trying the same request again later can succeed. */
retryable: boolean;
}
export interface DescribeErrorOptions {
/** What the user was doing, as a verb phrase: "save the comment". */
action?: string;
}
/** HTTP statuses that mean "the server or a proxy will likely recover". */
const TRANSIENT_STATUSES = new Set([408, 425, 429, 502, 503, 504]);
/**
* Error codes that mean "temporarily unavailable" regardless of the HTTP status
* they arrive with. The Cloud gateway has sent `tenant_app_unavailable` with
* non-5xx statuses, so these are matched by code, never by status alone.
*/
const TRANSIENT_CODES = new Set([
"tenant_app_unavailable",
"tenant_app_starting",
// Plugin bridge (`PluginBridgeErrorCode`).
"WORKER_UNAVAILABLE",
"TIMEOUT",
]);
/** Transient errors that say "the whole server is unreachable", not one route. */
const CONNECTIVITY_STATUSES = new Set([502, 503, 504]);
const CONNECTIVITY_CODES = new Set(["tenant_app_unavailable", "tenant_app_starting"]);
// --- Copy table ---------------------------------------------------------------
//
// The only place user-facing error copy lives. Keys are server error codes (the
// raw `body.error`/`body.code`) or an `ErrorKind` fallback. Never return a raw
// code to the user: anything not in this table falls back to its kind's copy.
const UNAVAILABLE_BODY = "Paperclip is temporarily unavailable. Please try again in a moment.";
const CODE_COPY: Record<string, { title: string; body: string }> = {
tenant_app_unavailable: {
title: "Reconnecting to Paperclip",
body: "Paperclip is restarting or updating. Please try again in a moment.",
},
tenant_app_starting: {
title: "Paperclip is starting",
body: "Paperclip is starting up. Please try again in a few seconds.",
},
WORKER_UNAVAILABLE: {
title: "Plugin unavailable",
body: "This plugin is restarting. Please try again in a moment.",
},
TIMEOUT: {
title: "Request timed out",
body: "This took too long to respond. Please try again in a moment.",
},
// Queued message edits. The editor keeps the person's text in every case.
queued_comment_revision_conflict: {
title: "Queue changed",
body: "The queue changed in another session. Your edit is still here; save again to apply it to the latest queue.",
},
queued_comment_stale_queue: {
title: "Queue changed",
body: "The queue changed in another session. Your edit is still here; save again to apply it to the latest queue.",
},
queued_comment_stale_target: {
title: "Queued message changed",
body: "This queued message was already sent or removed. Your text is still here; you can queue it as a new message.",
},
queued_comment_not_pending: {
title: "Queued message changed",
body: "This queued message was already sent or removed. Your text is still here; you can queue it as a new message.",
},
// Issue-thread interaction resolution (moved from lib/interaction-resolution-error.ts).
interaction_audience_denied: {
title: "You can’t respond to this card",
body: "You are not in this card's resolver audience.",
},
interaction_forbidden: {
title: "You can’t respond to this card",
body: "You do not have permission to respond to this card.",
},
interaction_settled: {
title: "Already handled",
body: "This request is no longer waiting for a decision.",
},
interaction_submit_failed: {
title: "Couldn't submit",
body: "Couldn't submit. Try again.",
},
};
const KIND_COPY: Record<ErrorKind, { title: string; body: string }> = {
// Moved from `ApiUnavailableError` (api/response.ts).
transient: { title: "Connection interrupted", body: UNAVAILABLE_BODY },
auth: { title: "Signed out", body: "Your session has ended. Sign in again to continue." },
forbidden: { title: "Not allowed", body: "You don’t have permission to do that." },
not_found: { title: "Not found", body: "This item doesn’t exist or was moved." },
conflict: { title: "Out of date", body: "This changed since you loaded it. Refresh and try again." },
invalid: { title: "Check your input", body: "Some details aren’t valid. Review them and try again." },
aborted: { title: "Cancelled", body: "The request was cancelled." },
unknown: { title: "Something went wrong", body: "An unexpected error occurred. Please try again." },
};
/** Copy for a specific code or kind, for callers that build their own messages. */
export function errorCopy(key: string): { title: string; body: string } {
return CODE_COPY[key] ?? KIND_COPY[key as ErrorKind] ?? KIND_COPY.unknown;
}
// --- Field extraction -------------------------------------------------------------
function record(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function stringField(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
/** The HTTP status an error carries, if any. */
export function errorStatus(err: unknown): number | null {
const status = record(err)?.status;
return typeof status === "number" && Number.isFinite(status) ? status : null;
}
/**
* Every server-provided code on an error: `ApiError.code` (the raw
* `body.error`), `body.code`, and `body.details.code`. Plugin bridge errors put
* their code on `body.code`; HttpErrors put a machine code on `details.code`.
*/
export function errorCodes(err: unknown): string[] {
const error = record(err);
if (!error) return [];
const body = record(error.body);
const codes = [
stringField(error.code),
stringField(body?.error),
stringField(body?.code),
stringField(record(body?.details)?.code),
];
return [...new Set(codes.filter((code): code is string => code !== null))];
}
function structuredApplicationCodes(err: unknown): string[] {
const body = record(record(err)?.body);
if (!body) return [];
const codes = [
stringField(body.code),
stringField(record(body.details)?.code),
];
return [...new Set(codes.filter((code): code is string => code !== null))];
}
function isStructuredUpstreamBadGateway(err: unknown): boolean {
if (isApiUnavailableError(err) || errorStatus(err) !== 502) return false;
const codes = structuredApplicationCodes(err);
if (!codes.some((code) => isUpstreamBadGatewayFailureCode(code))) return false;
return !errorCodes(err).some((code) => TRANSIENT_CODES.has(code));
}
function isRetryableUpstreamBadGateway(err: unknown): boolean {
const details = record(record(record(err)?.body)?.details);
const upstreamStatus = typeof details?.status === "number" && Number.isFinite(details.status)
? details.status
: null;
return isRetryableUpstreamFailure(structuredApplicationCodes(err), {
providerError: stringField(details?.providerError),
status: upstreamStatus,
});
}
/**
* True for a machine code (`tenant_app_unavailable`, `WORKER_UNAVAILABLE`,
* `TIMEOUT`) rather than a sentence a person wrote. Single readable words such
* as "Forbidden" are not codes.
*/
export function isRawErrorCode(value: string): boolean {
const text = value.trim();
if (!text || /\s/.test(text)) return false;
return Object.hasOwn(KIND_COPY, text) || text === "unauthorized"
|| /^[A-Za-z0-9]+(?:[_.][A-Za-z0-9]+)+$/.test(text) || /^[A-Z][A-Z0-9_]{2,}$/.test(text);
}
/** A server message that is safe to show: not a raw code, not a generic status line. */
function readableServerMessage(err: unknown): string | null {
const error = record(err);
const body = record(error?.body);
// OAuth endpoints (RFC 6749) put the readable sentence in `error_description`
// and a machine code in `error`.
const candidates = [stringField(body?.message), stringField(body?.error), stringField(body?.error_description)];
if (err instanceof Error) candidates.push(stringField(err.message));
for (const candidate of candidates) {
if (!candidate) continue;
if (isRawErrorCode(candidate)) continue;
if (/^Request failed: \d+$/.test(candidate)) continue;
if (candidate === UNAVAILABLE_BODY) continue;
return candidate;
}
return null;
}
// --- Classification ---------------------------------------------------------------
function isAbortError(err: unknown): boolean {
// React Query's `CancelledError` keeps the default `name` ("Error"), so it
// can only be recognized by class.
return record(err)?.name === "AbortError" || err instanceof CancelledError;
}
function isNetworkTypeError(err: unknown): boolean {
// Fetch uses different network-failure messages across browsers. Do not
// classify arbitrary TypeErrors (programming bugs) as outages.
return err instanceof TypeError && /fetch|network|load failed/i.test(err.message);
}
function isApiUnavailableError(err: unknown): boolean {
return record(err)?.name === "ApiUnavailableError";
}
export function classifyError(err: unknown): ErrorKind {
if (err === null || err === undefined) return "unknown";
if (isAbortError(err)) return "aborted";
if (isApiUnavailableError(err) || isNetworkTypeError(err)) return "transient";
if (errorCodes(err).some((code) => TRANSIENT_CODES.has(code))) return "transient";
const status = errorStatus(err);
if (status === null) return "unknown";
if (isStructuredUpstreamBadGateway(err)) return "unknown";
if (TRANSIENT_STATUSES.has(status)) return "transient";
if (status === 401) return "auth";
if (status === 403) return "forbidden";
if (status === 404 || status === 410) return "not_found";
if (status === 409 || status === 412) return "conflict";
if (status >= 400 && status < 500) return "invalid";
return "unknown";
}
export function isTransientError(err: unknown): boolean {
return classifyError(err) === "transient";
}
/**
* A transient error that means the server as a whole is unreachable (network
* drop, proxy 5xx, gateway "app unavailable"), as opposed to one route being
* busy (429, a plugin worker restarting). Only these move the app-wide
* connectivity state; per-route blips are left to query retry.
*/
export function isConnectivityError(err: unknown): boolean {
if (isApiUnavailableError(err) || isNetworkTypeError(err)) return true;
if (errorCodes(err).some((code) => CONNECTIVITY_CODES.has(code))) return true;
if (isStructuredUpstreamBadGateway(err)) return false;
const status = errorStatus(err);
if (status === null || !CONNECTIVITY_STATUSES.has(status)) return false;
// A plugin worker 503 is one route, not the server.
return !errorCodes(err).some((code) => TRANSIENT_CODES.has(code) && !CONNECTIVITY_CODES.has(code));
}
/** HTTP 4xx other than the transient ones; retrying the same request cannot help. */
export function isClientError(err: unknown): boolean {
const kind = classifyError(err);
return kind === "auth" || kind === "forbidden" || kind === "not_found" || kind === "conflict" || kind === "invalid";
}
// --- Retry-After --------------------------------------------------------------------
const MAX_RETRY_AFTER_MS = 5 * 60_000;
/** Parse an HTTP `Retry-After` value (delta-seconds or HTTP-date) into milliseconds. */
export function parseRetryAfter(value: string | null | undefined, now = Date.now()): number | null {
if (!value) return null;
const text = value.trim();
if (/^\d+(?:\.\d+)?$/.test(text)) {
return Math.min(Math.round(Number(text) * 1000), MAX_RETRY_AFTER_MS);
}
const date = Date.parse(text);
if (Number.isNaN(date)) return null;
return Math.min(Math.max(0, date - now), MAX_RETRY_AFTER_MS);
}
/** The server-requested delay carried by an error, if any. */
export function errorRetryAfterMs(err: unknown): number | null {
const value = record(err)?.retryAfterMs;
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
}
// --- Copy -----------------------------------------------------------------------------
/**
* User-facing copy for any error. Never returns a raw `snake_case` code:
* known codes use the table above, readable server messages pass through for
* client errors, and everything else uses the copy for its kind.
*/
export function describeError(err: unknown, options: DescribeErrorOptions = {}): ErrorDescription {
const kind = classifyError(err);
const retryable = isStructuredUpstreamBadGateway(err)
? isRetryableUpstreamBadGateway(err)
: (kind === "transient" || kind === "unknown");
const coded = errorCodes(err).map((code) => CODE_COPY[code]).find(Boolean);
const fallback = KIND_COPY[kind];
let body: string;
if (coded) body = coded.body;
else if (kind === "transient" || kind === "aborted") body = fallback.body;
else body = readableServerMessage(err) ?? fallback.body;
const title = options.action && kind !== "transient"
? `Couldn't ${options.action}`
: (coded?.title ?? fallback.title);
return { title, body, retryable };
}
/**
* The `message` for an `ApiError` built from an HTTP response: the server's own
* text when it is readable, otherwise copy from the table. Keeps raw codes out
* of every `{error.message}` render and `toast(err.message)` call.
*/
export function apiErrorMessage(status: number, body: unknown): string {
const raw = stringField(record(body)?.error);
if (raw && !isRawErrorCode(raw)) return raw;
return describeError({ status, body, code: raw }).body;
}