fix(ui): stop reporting the shared GET's own cancellation as an unhandled rejection (#22090)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The browser UI reads API data through a client that shares one
`fetch` between identical in-flight GETs (`ui/src/api/client.ts`)
> - When every caller of a shared GET leaves, the client aborts that
`fetch`. A live-update refetch that cancels an older read does this many
times in a busy tab
> - The app handles that rejection. But a `fetch` wrapper outside the
app, such as a browser extension, can drop it. The browser then reports
`AbortError: signal is aborted without reason` as an unhandled
rejection, and Sentry records an error that has no user effect
> - This pull request marks the abort reason that the client uses, and
makes the Sentry `beforeSend` hook drop an unhandled rejection only when
its value is that exact marked object
> - The benefit is that an intentional cancellation no longer appears as
a production error, and every other `AbortError` is still reported

## 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: signal
is aborted without reason` (DOMException code 20, mechanism
`onunhandledrejection`, native trusted promise). The stack is:
query-invalidation-batcher `flush` → `invalidateQueries` →
`refetchQueries` with `cancelRefetch` → React Query `Query.cancel` →
`onCancel` aborts the query signal → `coalescedGet` `onAbort` →
`releaseRef` → `controller.abort()` on the shared GET.

**Expected behavior**
An intentional cancellation of a shared GET does not appear in error
monitoring. A real abort failure still appears.

**Steps to reproduce**
1. Create a `QueryClient` and an observer whose `queryFn` calls
`api.get(path, { signal })`.
2. Replace `window.fetch` with a wrapper that calls the real `fetch` and
attaches only `.then(() => {})` to its promise. Some extensions and
injected scripts do this.
3. Start a refetch. While it is in flight, call `invalidateQueries` for
the same key through the batcher.
4. React Query cancels the first fetch, the shared GET is aborted, and
the wrapper's derived promise rejects with no handler. The app's own
promise chains do not cause the rejection: without the wrapper, the same
steps give zero unhandled rejections.

**Paperclip version or commit**
Reported on release `3a2f71db31`. `ui/src/api/client.ts` and
`ui/src/lib/sentry.ts` are unchanged on master up to this branch's base.

**Deployment mode**
Hosted, browser UI (Chrome-family message text).

Related: #21475 (groups failed-query Sentry reports) and #15940
(attributes stackless unhandled rejections). I searched open and closed
PRs for `releaseRef`, `inflightGets`, and this error message, and found
no duplicate.

## What Changed

- Added `ui/src/lib/intentional-abort.ts`. `intentionalAbortReason()`
makes an `AbortError` and records it in a `WeakSet`.
`isIntentionalAbortReason()` checks that identity without reading the
value.
- `ui/src/api/client.ts`: when the last caller leaves (abort or
timeout), the shared GET aborts with `intentionalAbortReason()` instead
of a reasonless `abort()`.
- `ui/src/lib/sentry.ts`: `beforeSend` returns `null` for an
unhandled-rejection event only when `hint.originalException` is a marked
reason. It also consumes the rejection-event snapshot, so the snapshot
cannot attach to a later report. The unhandled-rejection check is
computed once and reused by the existing diagnostics.
- `ui/src/lib/sentry.test.ts`: the real-SDK test harness now treats a
`null` return from `beforeSend` as a dropped event. Before, `?? event`
sent the event on.
- Tests: the shared signal reason is marked after an abort and after a
timeout, and a caller's own reason is not marked. Against the real
`@sentry/browser` SDK, the marked rejection is dropped and an unmarked
`AbortError` is still sent.

## Verification

- `cd ui && npx vitest run src/api/client.test.ts src/lib/sentry.test.ts
src/lib/browser-error-context.test.ts
src/lib/query-invalidation-batcher.test.ts` → 4 files, 100 tests pass.
- Red check: with the original `client.ts`, the new client test fails
(the reason is not marked). With the original `sentry.ts`, the new
Sentry test fails (the marked rejection is sent).
- A throwaway reproduction (not committed) used a real `QueryClient`,
the invalidation batcher, `api.get`, and a `fetch` stub that rejects
with `signal.reason`. Without a wrapper: 0 unhandled rejections. With
the `.then(() => {})` wrapper: exactly 1 unhandled `AbortError`, which
matches the report.
- `tsc --noEmit` for `ui` reports no errors in the changed files.

## Risks

- Low risk. The filter matches by object identity, and only the client
makes these objects. An `AbortError` from any other source is still
reported.
- The shared GET's rejection message changes from the browser's text to
"The operation was aborted.". Callers already receive their own
`AbortError`, and nothing reads the shared reason.
- If app code drops this rejection in the future, the filter also hides
that. The effect is the same: the request was cancelled on purpose.

> 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

- Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used through
Claude Code with tool use (shell, file edits, test runs).

## 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-19 23:39:19 -08:00
1 parent ce8006de3c
commit 201abacd6e
5 files changed
+65 -7

No files matched your search

+20
View File
@@ -3,6 +3,7 @@ import {
createTenantSessionRecoveryCoordinator, createTenantSessionRecoveryCoordinator,
tenantSessionRecovery, tenantSessionRecovery,
} from "@/lib/tenant-session-recovery"; } from "@/lib/tenant-session-recovery";
import { isIntentionalAbortReason } from "@/lib/intentional-abort";
import { api, detachInflightGet } from "./client"; import { api, detachInflightGet } from "./client";
import { toolsApi } from "./tools"; import { toolsApi } from "./tools";
import { museInvitationsApi } from "./museInvitations"; import { museInvitationsApi } from "./museInvitations";
@@ -279,6 +280,25 @@ describe("per-caller abort semantics", () => {
expect(await fresh).toEqual({ value: "fresh" }); expect(await fresh).toEqual({ value: "fresh" });
}); });
it("marks the shared fetch's cancellation, whether every caller aborted or timed out", async () => {
vi.useFakeTimers();
fetchMock.mockReturnValue(deferred<Response>().promise);
const controller = new AbortController();
const aborted = api.get("/intentional-abort", { signal: controller.signal });
const timed = api.get("/intentional-timeout", { timeoutMs: 100 }).catch(error => error);
const [abortedSignal, timedSignal] = fetchMock.mock.calls.map(([, init]) => init.signal as AbortSignal);
controller.abort();
await expect(aborted).rejects.toMatchObject({ name: "AbortError" });
await vi.advanceTimersByTimeAsync(100);
expect(await timed).toMatchObject({ status: 408 });
expect(abortedSignal.reason).toMatchObject({ name: "AbortError" });
expect(isIntentionalAbortReason(abortedSignal.reason)).toBe(true);
expect(isIntentionalAbortReason(timedSignal.reason)).toBe(true);
expect(isIntentionalAbortReason(controller.signal.reason)).toBe(false);
});
it("rejects immediately if the caller signal is already aborted", async () => { it("rejects immediately if the caller signal is already aborted", async () => {
const controller = new AbortController(); const controller = new AbortController();
controller.abort(); controller.abort();
+2 -1
View File
@@ -1,3 +1,4 @@
import { intentionalAbortReason } from "@/lib/intentional-abort";
import { getPageVisibility, getVisibilityHeaderValue } from "@/lib/page-visibility"; import { getPageVisibility, getVisibilityHeaderValue } from "@/lib/page-visibility";
import { tenantSessionRecovery } from "@/lib/tenant-session-recovery"; import { tenantSessionRecovery } from "@/lib/tenant-session-recovery";
import { ApiError, apiErrorFromResponse } from "./api-error"; import { ApiError, apiErrorFromResponse } from "./api-error";
@@ -208,7 +209,7 @@ function coalescedGet<T>(path: string, options?: RequestOptions): Promise<T> {
// Last caller gone before the fetch settled → abort the shared request. // Last caller gone before the fetch settled → abort the shared request.
if (activeEntry.refs.size === 0) { if (activeEntry.refs.size === 0) {
if (inflightGets.get(key) === activeEntry) inflightGets.delete(key); if (inflightGets.get(key) === activeEntry) inflightGets.delete(key);
activeEntry.controller.abort(); activeEntry.controller.abort(intentionalAbortReason());
} }
}; };
+11
View File
@@ -0,0 +1,11 @@
const reasons = new WeakSet<object>();
export function intentionalAbortReason(): DOMException {
const reason = new DOMException("The operation was aborted.", "AbortError");
reasons.add(reason);
return reason;
}
export function isIntentionalAbortReason(value: unknown): boolean {
return typeof value === "object" && value !== null && reasons.has(value);
}
+22 -2
View File
@@ -559,8 +559,8 @@ describe("captured event shape against the real @sentry/browser SDK", () => {
...options, ...options,
transport: () => ({ send: async () => ({}), flush: async () => true }), transport: () => ({ send: async () => ({}), flush: async () => true }),
beforeSend: async (event, hint) => { beforeSend: async (event, hint) => {
const enriched = await options.beforeSend?.(event, hint) ?? event; const enriched = options.beforeSend ? await options.beforeSend(event, hint) : event;
onEvent(enriched as unknown as Record<string, unknown>); if (enriched) onEvent(enriched as unknown as Record<string, unknown>);
return enriched; return enriched;
}, },
}); });
@@ -590,6 +590,26 @@ describe("captured event shape against the real @sentry/browser SDK", () => {
} }
}); });
it("drops only the rejection carrying the app's own request cancellation", async () => {
const captured: Record<string, unknown>[] = [];
const Sentry = await initRealSentryForTest((event) => { captured.push(event); });
const { intentionalAbortReason } = await import("./intentional-abort");
try {
window.onunhandledrejection?.call(window, { reason: intentionalAbortReason() } as PromiseRejectionEvent);
await Sentry.flush(2000);
expect(captured).toEqual([]);
window.onunhandledrejection?.call(window, {
reason: new DOMException("signal is aborted without reason", "AbortError"),
} as PromiseRejectionEvent);
await Sentry.flush(2000);
expect(captured).toHaveLength(1);
expect(captured[0]).toMatchObject({ exception: { values: [{ type: "AbortError" }] } });
} finally {
await Sentry.close();
}
});
it.each([ it.each([
["staging", "staging"], ["staging", "staging"],
["production", "production"], ["production", "production"],
+10 -4
View File
@@ -48,6 +48,7 @@ import {
takeRejectionEventSnapshot, takeRejectionEventSnapshot,
type BrowserErrorDetails, type BrowserErrorDetails,
} from "./browser-error-context"; } from "./browser-error-context";
import { isIntentionalAbortReason } from "./intentional-abort";
let queue: Promise<void> = Promise.resolve(); let queue: Promise<void> = Promise.resolve();
@@ -211,6 +212,14 @@ export function buildBrowserSentryInitOptions(
tracesSampleRate: 0, tracesSampleRate: 0,
sendDefaultPii: false, sendDefaultPii: false,
beforeSend: (event, hint) => { beforeSend: (event, hint) => {
const isUnhandledRejection = event.exception?.values?.some((value) =>
value.mechanism?.type === "onunhandledrejection"
|| value.mechanism?.type === "auto.browser.global_handlers.onunhandledrejection",
) ?? false;
if (isUnhandledRejection && isIntentionalAbortReason(hint.originalException)) {
takeRejectionEventSnapshot(classifyRejectionReason(hint.originalException));
return null;
}
// Global handlers do not pass through our React boundaries. Give their // Global handlers do not pass through our React boundaries. Give their
// reports the same bounded document state, without URLs or breadcrumbs. // reports the same bounded document state, without URLs or breadcrumbs.
// Preserve a boundary's earlier snapshot across the asynchronous queue. // Preserve a boundary's earlier snapshot across the asynchronous queue.
@@ -224,10 +233,7 @@ export function buildBrowserSentryInitOptions(
...event.tags, ...event.tags,
browser_build_mode: import.meta.env.DEV ? "development" : "production", browser_build_mode: import.meta.env.DEV ? "development" : "production",
}; };
if (event.exception?.values?.some((value) => if (isUnhandledRejection) {
value.mechanism?.type === "onunhandledrejection"
|| value.mechanism?.type === "auto.browser.global_handlers.onunhandledrejection",
)) {
// The SDK supplies the rejected value directly. Classify without // The SDK supplies the rejected value directly. Classify without
// reading object properties, coercing strings, or copying its value. // reading object properties, coercing strings, or copying its value.
const kind = classifyRejectionReason(hint.originalException); const kind = classifyRejectionReason(hint.originalException);