mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
## 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>
347 lines
14 KiB
TypeScript
347 lines
14 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import {
|
|
createTenantSessionRecoveryCoordinator,
|
|
tenantSessionRecovery,
|
|
} from "@/lib/tenant-session-recovery";
|
|
import { isIntentionalAbortReason } from "@/lib/intentional-abort";
|
|
import { api, detachInflightGet } from "./client";
|
|
import { toolsApi } from "./tools";
|
|
import { museInvitationsApi } from "./museInvitations";
|
|
|
|
interface Deferred<T> {
|
|
promise: Promise<T>;
|
|
resolve: (value: T) => void;
|
|
reject: (reason?: unknown) => void;
|
|
}
|
|
|
|
function deferred<T>(): Deferred<T> {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (reason?: unknown) => void;
|
|
const promise = new Promise<T>((res, rej) => {
|
|
resolve = res;
|
|
reject = rej;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
|
|
function jsonResponse(body: unknown) {
|
|
return { ok: true, status: 200, json: async () => body } as unknown as Response;
|
|
}
|
|
|
|
function errorResponse(body: unknown, status = 401) {
|
|
return { ok: false, status, json: async () => body } as unknown as Response;
|
|
}
|
|
|
|
const fetchMock = vi.fn();
|
|
|
|
beforeEach(() => {
|
|
fetchMock.mockReset();
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
describe("tenant-session recovery", () => {
|
|
it("loads anonymous Dot consent despite concurrent protected background probes", async () => {
|
|
const reload = vi.fn();
|
|
const requestId = `pcmcp_request_${"a".repeat(43)}`;
|
|
const recovery = createTenantSessionRecoveryCoordinator(reload, () => `/dot-connect/${requestId}`);
|
|
vi.spyOn(tenantSessionRecovery, "recoverIfNeeded").mockImplementation(recovery.recoverIfNeeded);
|
|
fetchMock.mockImplementation((url: string) => Promise.resolve(
|
|
url.includes("/dot-mcp/requests/")
|
|
? jsonResponse({ id: requestId, agentConnection: true })
|
|
: errorResponse({ error: "tenant_session_required" }),
|
|
));
|
|
|
|
const background = api.get("/health");
|
|
const consent = api.get(`/dot-mcp/requests/${requestId}`);
|
|
await expect(background).rejects.toMatchObject({ status: 401 });
|
|
await expect(consent).resolves.toEqual({ id: requestId, agentConnection: true });
|
|
expect(reload).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps concurrent failures pending and schedules one top-level reload", async () => {
|
|
const reload = vi.fn();
|
|
const recovery = createTenantSessionRecoveryCoordinator(reload);
|
|
vi.spyOn(tenantSessionRecovery, "recoverIfNeeded").mockImplementation(recovery.recoverIfNeeded);
|
|
fetchMock.mockResolvedValue(errorResponse({ error: "tenant_session_required" }));
|
|
|
|
const first = api.post("/tenant-session-a", { value: 1 });
|
|
const second = api.post("/tenant-session-b", { value: 2 });
|
|
|
|
await vi.waitFor(() => {
|
|
expect(tenantSessionRecovery.recoverIfNeeded).toHaveBeenCalledTimes(2);
|
|
expect(reload).toHaveBeenCalledTimes(1);
|
|
});
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
|
|
let settled = false;
|
|
void Promise.all([first, second]).then(
|
|
() => { settled = true; },
|
|
() => { settled = true; },
|
|
);
|
|
await Promise.resolve();
|
|
expect(settled).toBe(false);
|
|
});
|
|
|
|
it("preserves ApiError handling for an unrelated 401", async () => {
|
|
fetchMock.mockResolvedValue(errorResponse({ error: "unauthorized" }));
|
|
|
|
await expect(api.get("/ordinary-401")).rejects.toMatchObject({
|
|
name: "ApiError",
|
|
status: 401,
|
|
code: "unauthorized",
|
|
message: "Your session has ended. Sign in again to continue.",
|
|
});
|
|
|
|
fetchMock.mockResolvedValue(jsonResponse({ recovered: true }));
|
|
await expect(api.get("/ordinary-401")).resolves.toEqual({ recovered: true });
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
});
|
|
});
|
|
|
|
describe("in-tab GET coalescing", () => {
|
|
it("keeps fresh validation reads separate from older and concurrent requests", async () => {
|
|
const old = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(old.promise).mockResolvedValue(jsonResponse({ title: "Current C" }));
|
|
const stale = api.get("/fresh-validation");
|
|
const first = api.get("/fresh-validation", { cache: "no-store", fresh: true });
|
|
const second = api.get("/fresh-validation", { cache: "no-store", fresh: true });
|
|
const joined = api.get("/fresh-validation");
|
|
expect(fetchMock).toHaveBeenCalledTimes(3);
|
|
expect(fetchMock.mock.calls[1][1]).toMatchObject({ cache: "no-store" });
|
|
await expect(first).resolves.toEqual({ title: "Current C" });
|
|
await expect(second).resolves.toEqual({ title: "Current C" });
|
|
old.resolve(jsonResponse({ title: "Old A" }));
|
|
await expect(stale).resolves.toEqual({ title: "Old A" });
|
|
await expect(joined).resolves.toEqual({ title: "Old A" });
|
|
});
|
|
|
|
it("times out a caller without cancelling another and starts a fresh fetch on retry", async () => {
|
|
vi.useFakeTimers();
|
|
const first = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(first.promise);
|
|
const survivorController = new AbortController();
|
|
const survivor = api.get("/deadline-shared", { signal: survivorController.signal });
|
|
const timed = api.get("/deadline-shared", { timeoutMs: 100 }).catch(error => error);
|
|
const sharedSignal = fetchMock.mock.calls[0][1].signal as AbortSignal;
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(await timed).toMatchObject({ status: 408, body: { error: "TIMEOUT" } });
|
|
expect(sharedSignal.aborted).toBe(false);
|
|
fetchMock.mockResolvedValueOnce(jsonResponse({ fresh: true }));
|
|
await expect(api.get("/deadline-shared", { timeoutMs: 100 })).resolves.toEqual({ fresh: true });
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
survivorController.abort();
|
|
await expect(survivor).rejects.toMatchObject({ name: "AbortError" });
|
|
expect(sharedSignal.aborted).toBe(true);
|
|
first.resolve(jsonResponse({ stale: true }));
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("bounds response-body reads and aborts the last caller's fetch", async () => {
|
|
vi.useFakeTimers();
|
|
const body = deferred<unknown>();
|
|
fetchMock.mockResolvedValue({ ok: true, status: 200, json: () => body.promise });
|
|
const result = api.get("/deadline-body", { timeoutMs: 100 }).catch(error => error);
|
|
const signal = fetchMock.mock.calls[0][1].signal as AbortSignal;
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect(await result).toMatchObject({ status: 408 });
|
|
expect(signal.aborted).toBe(true);
|
|
body.resolve({ tooLate: true });
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("clears a successful or cancelled caller's deadline", async () => {
|
|
vi.useFakeTimers();
|
|
fetchMock.mockResolvedValueOnce(jsonResponse({ ok: true }));
|
|
await expect(api.get("/deadline-success", { timeoutMs: 100 })).resolves.toEqual({ ok: true });
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
const controller = new AbortController();
|
|
fetchMock.mockReturnValueOnce(deferred<Response>().promise);
|
|
const result = api.get("/deadline-cancel", { signal: controller.signal, timeoutMs: 100 });
|
|
controller.abort();
|
|
await expect(result).rejects.toMatchObject({ name: "AbortError" });
|
|
expect(vi.getTimerCount()).toBe(0);
|
|
});
|
|
|
|
it("shares one underlying fetch for identical in-flight GETs", async () => {
|
|
const d = deferred<Response>();
|
|
fetchMock.mockReturnValue(d.promise);
|
|
|
|
const p1 = api.get("/coalesce-a");
|
|
const p2 = api.get("/coalesce-a");
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
|
|
d.resolve(jsonResponse({ value: 1 }));
|
|
expect(await p1).toEqual({ value: 1 });
|
|
expect(await p2).toEqual({ value: 1 });
|
|
});
|
|
|
|
it("issues a fresh fetch after the previous one settles", async () => {
|
|
fetchMock.mockResolvedValue(jsonResponse({ value: "x" }));
|
|
await api.get("/coalesce-b");
|
|
await api.get("/coalesce-b");
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("does not coalesce different paths", async () => {
|
|
fetchMock.mockReturnValue(deferred<Response>().promise);
|
|
const c1 = new AbortController();
|
|
const c2 = new AbortController();
|
|
const p1 = api.get("/path-1", { signal: c1.signal });
|
|
const p2 = api.get("/path-2", { signal: c2.signal });
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
// Clean up the never-settling shared entries so the module map does not leak.
|
|
c1.abort();
|
|
c2.abort();
|
|
await expect(p1).rejects.toMatchObject({ name: "AbortError" });
|
|
await expect(p2).rejects.toMatchObject({ name: "AbortError" });
|
|
});
|
|
|
|
it("stops later callers joining a detached in-flight GET", async () => {
|
|
// A GET issued under one account's session must not answer a caller that
|
|
// runs after the account changed.
|
|
const first = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(first.promise);
|
|
const previousAccount = api.get("/detach-me");
|
|
|
|
detachInflightGet("/detach-me");
|
|
|
|
const second = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(second.promise);
|
|
const currentAccount = api.get("/detach-me");
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
|
|
// Each caller gets its own response, not the other's.
|
|
first.resolve(jsonResponse({ companies: ["previous"] }));
|
|
second.resolve(jsonResponse({ companies: ["current"] }));
|
|
expect(await previousAccount).toEqual({ companies: ["previous"] });
|
|
expect(await currentAccount).toEqual({ companies: ["current"] });
|
|
});
|
|
|
|
it("never coalesces mutations", async () => {
|
|
fetchMock.mockResolvedValue(jsonResponse({ ok: true }));
|
|
await Promise.all([api.post("/mutate", { a: 1 }), api.post("/mutate", { a: 1 })]);
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
});
|
|
});
|
|
|
|
describe("per-caller abort semantics", () => {
|
|
it("aborting one caller rejects only that caller, not the shared fetch", async () => {
|
|
const d = deferred<Response>();
|
|
let sharedSignal: AbortSignal | undefined;
|
|
fetchMock.mockImplementation((_url: string, init: RequestInit) => {
|
|
sharedSignal = init.signal ?? undefined;
|
|
return d.promise;
|
|
});
|
|
|
|
const c1 = new AbortController();
|
|
const c2 = new AbortController();
|
|
const p1 = api.get("/abort-a", { signal: c1.signal });
|
|
const p2 = api.get("/abort-a", { signal: c2.signal });
|
|
|
|
c1.abort();
|
|
await expect(p1).rejects.toMatchObject({ name: "AbortError" });
|
|
// The shared fetch is still alive because caller 2 has not aborted.
|
|
expect(sharedSignal?.aborted).toBe(false);
|
|
|
|
d.resolve(jsonResponse({ value: 2 }));
|
|
expect(await p2).toEqual({ value: 2 });
|
|
});
|
|
|
|
it("aborts the shared fetch after all callers cancel and permits a fresh request", async () => {
|
|
const d = deferred<Response>();
|
|
let sharedSignal: AbortSignal | undefined;
|
|
fetchMock.mockImplementation((_url: string, init: RequestInit) => {
|
|
sharedSignal = init.signal ?? undefined;
|
|
return d.promise;
|
|
});
|
|
|
|
const c1 = new AbortController();
|
|
const c2 = new AbortController();
|
|
const p1 = api.get("/abort-b", { signal: c1.signal });
|
|
const p2 = api.get("/abort-b", { signal: c2.signal });
|
|
|
|
c1.abort();
|
|
c2.abort();
|
|
await expect(p1).rejects.toMatchObject({ name: "AbortError" });
|
|
await expect(p2).rejects.toMatchObject({ name: "AbortError" });
|
|
expect(sharedSignal?.aborted).toBe(true);
|
|
|
|
fetchMock.mockResolvedValueOnce(jsonResponse({ value: "fresh" }));
|
|
const fresh = api.get("/abort-b");
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
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 () => {
|
|
const controller = new AbortController();
|
|
controller.abort();
|
|
await expect(api.get("/already-aborted", { signal: controller.signal })).rejects.toMatchObject({
|
|
name: "AbortError",
|
|
});
|
|
expect(fetchMock).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
|
|
describe("managed-account request isolation", () => {
|
|
it("does not share a previous viewing user's pending account response", async () => {
|
|
const previous = deferred<Response>();
|
|
const current = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(previous.promise).mockReturnValueOnce(current.promise);
|
|
const previousUser = toolsApi.listAggregatorApps("shared-gateway");
|
|
const currentUser = toolsApi.listAggregatorApps("shared-gateway");
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
expect(fetchMock.mock.calls.every(([, options]) => options.cache === "no-store")).toBe(true);
|
|
current.resolve(jsonResponse({ apps: ["current-user-account"] }));
|
|
previous.resolve(jsonResponse({ apps: ["previous-user-account"] }));
|
|
expect(await currentUser).toEqual({ apps: ["current-user-account"] });
|
|
expect(await previousUser).toEqual({ apps: ["previous-user-account"] });
|
|
});
|
|
});
|
|
|
|
describe("Muse operator request isolation", () => {
|
|
it.each([
|
|
["invitation resume", () => museInvitationsApi.resume("company")],
|
|
["connection evidence", () => museInvitationsApi.connection("company", "agent")],
|
|
] as const)("does not join the previous operator's %s request", async (_name, read) => {
|
|
const previous = deferred<Response>();
|
|
const current = deferred<Response>();
|
|
fetchMock.mockReturnValueOnce(previous.promise).mockReturnValueOnce(current.promise);
|
|
const previousOperator = read();
|
|
const currentOperator = read();
|
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
expect(fetchMock.mock.calls.every(([, options]) => options.cache === "no-store")).toBe(true);
|
|
current.resolve(jsonResponse({ operator: "current" }));
|
|
previous.resolve(jsonResponse({ operator: "previous" }));
|
|
expect(await currentOperator).toEqual({ operator: "current" });
|
|
expect(await previousOperator).toEqual({ operator: "previous" });
|
|
});
|
|
});
|