fix(ui): stop reporting posthog-js request timeouts as unhandled rejections (#22381)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip Cloud loads PostHog's browser script (`posthog-js`)
through a same-origin proxy for product analytics, and reports browser
errors to Sentry
> - posthog-js stops its own requests at a client-side timeout. For
`/flags` this timeout is 3000 ms by default. It makes `AbortError:
PostHog request timed out after 3000ms`, logs it as a warning, and tries
again
> - On a slow visitor network, this abort reason can escape as an
unhandled promise rejection inside PostHog's script. Sentry's global
handler then reports it as a board error. The board has no handler to
attach there, and the visitor sees no effect, because analytics never
gates the UI
> - This pull request makes the browser Sentry `beforeSend` drop exactly
that one error, and only when it comes through the unhandled-rejection
handler
> - The benefit is that Sentry shows board failures, not third-party
analytics timeouts

## Linked Issues or Issue Description

No public issue exists. This is the problem, in the bug template fields:

**What happened?**
A hosted browser reported one unhandled rejection: `AbortError: PostHog
request timed out after 3000ms` (mechanism `onunhandledrejection`,
native trusted promise). All stack frames are in `/_ph/static/array.js`
(posthog-js), below the SDK's `setTimeout` wrapper. posthog-js 1.453.0
makes this error in its fetch transport timeout (`abort(new
Error("PostHog request timed out after <n>ms"))` with `name =
"AbortError"`). `feature_flag_request_timeout_ms` is 3000 by default, so
this is the `/flags` request. posthog-js logs this as a warning and
tries again. The board has no handler that it can attach inside
PostHog's script.

**Expected behavior**
A timeout of an analytics request that posthog-js handles and retries
does not appear in error monitoring. Analytics never gates the board, so
the visitor sees no effect. Any other `AbortError` still appears.

**Steps to reproduce**
1. Open a Cloud board with browser analytics on, on a slow network.
2. Let a posthog-js `/flags` request take more than 3000 ms.
3. posthog-js aborts the request with its own `AbortError`. The reason
escapes as an unhandled rejection, and Sentry reports it.

**Paperclip version or commit**
Reported on release `651749bdb463aa09d1eb2ae6e61ac3da26161a74`. This
branch is based on `201abacd6e`.

**Deployment mode**
Hosted Paperclip Cloud, browser UI.

Related: #22090 (drops the shared GET's own cancellation through the
same `beforeSend` check). This change adds a second exact match to that
check. The PostHog proxy (`server/src/routes/posthog-proxy.ts`) refuses
at once at its limits and has a 30 s upstream timeout, so it does not
cause a 3 s client stall. I searched open and closed PRs for this error
message and found no duplicate.

## What Changed

- `ui/src/lib/sentry.ts`: add `isPostHogRequestTimeout`. It matches only
an `Error` with `name === "AbortError"` and the exact posthog-js message
`PostHog request timed out` (with an optional ` after <n>ms`).
- `ui/src/lib/sentry.ts`: the existing unhandled-rejection drop in
`beforeSend` (from #22090) now also matches `isPostHogRequestTimeout`.
As for the existing match, it consumes the rejection-event snapshot. All
other events keep the same enrichment and are sent.
- `ui/src/lib/sentry.test.ts`: add real `@sentry/browser` SDK tests that
count what reaches the transport.

## Verification

- `cd ui && npx vitest run src/lib/sentry.test.ts
src/api/client.test.ts`: 2 files, 56 tests pass.
- Red proof: with master's `sentry.ts`, the new test "drops posthog-js's
own timeout when it escapes as an unhandled rejection" fails (1 failed,
36 passed).
- The tests prove that these are still reported: another `AbortError`,
the same text on a plain `Error`, a string reason with the same text,
and the same error when Paperclip code captures it with
`captureException`.
- `npx tsc --noEmit -p ui/tsconfig.json` shows no errors in the changed
files. Other errors come from the unbuilt `@paperclipai/plugin-sdk` in
the local checkout.

## Risks

- Low risk. The filter matches one exact third-party error name and
message, and only on the unhandled-rejection path.
- If posthog-js changes the message, the filter stops matching, and
Sentry reports the error again. No board failure can be hidden.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.

## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-20 04:47:42 -08:00
1 parent 9874608d0a
commit 434e574ec6
2 files changed
+79 -1

No files matched your search

+63
View File
@@ -616,6 +616,69 @@ describe("captured event shape against the real @sentry/browser SDK", () => {
}
});
describe("posthog-js request timeouts", () => {
function postHogTimeoutError(message = "PostHog request timed out after 3000ms"): Error {
const error = new Error(message);
Object.defineProperty(error, "name", { value: "AbortError" });
return error;
}
async function initCountingSentry() {
const { buildBrowserSentryInitOptions } = await importFreshSentry();
const Sentry = await import("@sentry/browser");
const send = vi.fn(async () => ({}));
Sentry.init({
...buildBrowserSentryInitOptions(DSN, "production"),
transport: () => ({ send, flush: async () => true }),
});
const sentEvents = () => send.mock.calls.map((call: unknown[]) => JSON.stringify(call[0]))
.filter((envelope) => envelope.includes("\"type\":\"event\""));
return { Sentry, sentEvents };
}
function rejectUnhandled(reason: unknown) {
window.onunhandledrejection?.call(window, { reason } as PromiseRejectionEvent);
}
it("drops posthog-js's own timeout when it escapes as an unhandled rejection", async () => {
const { Sentry, sentEvents } = await initCountingSentry();
try {
rejectUnhandled(postHogTimeoutError());
rejectUnhandled(postHogTimeoutError("PostHog request timed out"));
await Sentry.flush(2000);
expect(sentEvents()).toHaveLength(0);
} finally {
await Sentry.close();
}
});
it.each([
["another AbortError", () => Object.assign(new Error("The user aborted a request."), { name: "AbortError" })],
["the same text on a plain Error", () => new Error("PostHog request timed out after 3000ms")],
["a string reason with the same text", () => "PostHog request timed out after 3000ms"],
])("still reports %s", async (_label, makeReason) => {
const { Sentry, sentEvents } = await initCountingSentry();
try {
rejectUnhandled(makeReason());
await Sentry.flush(2000);
expect(sentEvents()).toHaveLength(1);
} finally {
await Sentry.close();
}
});
it("still reports the same error when Paperclip code captures it", async () => {
const { Sentry, sentEvents } = await initCountingSentry();
try {
Sentry.captureException(postHogTimeoutError());
await Sentry.flush(2000);
expect(sentEvents()).toHaveLength(1);
} finally {
await Sentry.close();
}
});
});
it.each([
["staging", "staging"],
["production", "production"],
+16 -1
View File
@@ -191,6 +191,18 @@ function enqueueCapture(
});
}
const POSTHOG_REQUEST_TIMEOUT_MESSAGE = /^PostHog request timed out(?: after \d+ms)?$/;
export function isPostHogRequestTimeout(reason: unknown): boolean {
try {
return reason instanceof Error
&& reason.name === "AbortError"
&& POSTHOG_REQUEST_TIMEOUT_MESSAGE.test(reason.message);
} catch {
return false;
}
}
/**
* Build the `Sentry.init` options object. A pure function, split out from
* `initBrowserErrorMonitoring` so a test can call it with the real
@@ -217,7 +229,10 @@ export function buildBrowserSentryInitOptions(
value.mechanism?.type === "onunhandledrejection"
|| value.mechanism?.type === "auto.browser.global_handlers.onunhandledrejection",
) ?? false;
if (isUnhandledRejection && isIntentionalAbortReason(hint.originalException)) {
if (
isUnhandledRejection
&& (isIntentionalAbortReason(hint.originalException) || isPostHogRequestTimeout(hint.originalException))
) {
takeRejectionEventSnapshot(classifyRejectionReason(hint.originalException));
return null;
}