mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The chat evaluation catalog checks agent replies and then the human step that follows, such as a person who reveals a key or approves a device > - Some human steps run in a separate private browser process, because they handle credentials. CI keeps the output of that process private on purpose > - Four cases failed only in that private step, so CI showed one fixed message and no cause > - I ran each private step locally against a dev server, where its output is visible, and found the cause of three failures > - This pull request fixes the harness and two product defects, and adds a closed failure record so that the next CI failure names its step > - The benefit is that these human steps work, and a private-step failure is diagnosable without any credential in logs ## Linked Issues or Issue Description Bug report (following `.github/ISSUE_TEMPLATE/bug_report.yml`). **What happened?** - `routines.webhook-trigger`: the private person opens the routine overview. The trigger cards are only in the Triggers section, so the step waits for a missing button. An unhandled response wait then stops the process. - `connection-setup.secure-api-key`: a key-protected MCP server answers 401 without a challenge header. Paperclip shows "Remote app returned HTTP 401" and does not ask for a key. The person cannot enter the key in the normal flow. - `assistant-connections.device-login`: an expired device code page shows "This item doesn't exist or was moved." The server sends "This code is expired, already decided, or invalid." in the OAuth `error_description` field, and the UI drops it. - `onboarding.new-company`: the private step reads back all saved state and then fails one proof check. CI does not say which check. **Expected behavior** - The person reveals the webhook key in the Triggers section and sends authenticated events. - A pasted MCP link that answers 401 shows the key field. - An expired device code says that the code is expired. - A private-step failure names its fixed step and error class, with no value. **Steps to reproduce** 1. Start a local dev server. 2. Create a routine with a bearer webhook, and run the private webhook worker. It times out on the "Edit webhook" button. 3. Paste the address of an MCP server that answers a plain 401 into Connectors > Add by link. No key field appears. 4. Open `/mcp-device?user_code=<expired code>`. The page shows generic not-found text. **Paperclip version or commit** `master` (reproduced on origin/master before this change) **Deployment mode** Local dev server (embedded PGlite) and the CI chat-eval runner **Installation method** Source checkout (`pnpm dev`) ## What Changed - `integrator-webhook-private-worker.ts`: open `<routine>/triggers` (also for the setup-resume link), and attach a handler to the early response wait so a failed click reports its real step. - `server/.../catalog/discovery.ts`: a 401 with no `WWW-Authenticate` header, to a connection that sends no credential, is handled like a challenge without discoverable sign-in (`oauth_challenge`). The existing UI guidance then asks for a key. A 401 to a connection that already sends a credential keeps the old error. - `ui/src/api/errors.ts`: read the OAuth `error_description` field as a readable server message. - New `private-child-failure.ts`: a private child records only a fixed step name and an error class from a fixed list. The parent echoes a step only when it is in the caller's closed list. Error text, stdout and stderr stay private. - The webhook, private browser and identity children use it. Each has a closed step list file. - `identity-new-company-native-proof.ts`: each proof check has a fixed reason name. The private child reports `new-company-proof-<reason>` when a check fails. The accepted conditions do not change. - Tests: server red/green test for the bare 401, UI red/green test for `error_description`, unit tests for the failure record (no text leaks, closed list only, extra fields dropped). ## Verification - Local dev server (embedded PostgreSQL), private workers run directly with the real child process: - Webhook, ready and setup-pending triggers: before, timeout on "Edit webhook". After, receipt with invalid status 401, valid status 202 and a linked task. - Secure key entry with the synthetic notes provider: before, timeout on the key field. After, an active connection with health `ok` and 2 authorized `tools/list` calls. - Expired device page: before, `at step device-expired-page (TimeoutError)`. After, `expiredPageVisible: true`. - `server`: `vitest run src/__tests__/tool-access-service.test.ts -t "pasted link answers"` (fails before the discovery change with 502, passes after). - `ui`: `vitest run src/api/errors.test.ts` (fails before, passes after). - `pnpm test:e2e:runner:typecheck`, `pnpm test:e2e:runner:unit`, server `tsc --noEmit`. - `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD sha> --check`: unchanged. - One paid run of the four cases on this branch. Results are in a PR comment. ## Risks - A plain 401 from an MCP link now returns 422 `oauth_challenge` instead of 502. The draft connection is removed, as for other challenges. Agents that call the connect API see the "needs sign-in" answer instead of a raw status. This only applies when the connection sends no credential. - Some API errors that carry `error_description` now show that text instead of generic copy. That text is written for people. - The failure record is opt-in per child and contains only constants. The parent ignores a record with any other field. - `onboarding.new-company` is not fixed here. Its native hello probe cannot start locally on macOS, so the failing check is not yet known. This change makes the next run name it. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edits, local browser automation through Playwright). Extended reasoning was on. ## 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 - [ ] 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>
319 lines
13 KiB
TypeScript
319 lines
13 KiB
TypeScript
/**
|
||
* 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 { 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))];
|
||
}
|
||
|
||
/**
|
||
* 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 (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;
|
||
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 = 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;
|
||
}
|