mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-21 10:52:06 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The browser UI shows an optional announcement card. The `useAnnouncement` hook fetches it and cancels that fetch when the tab is hidden, when the user dismisses the card, or when the hook unmounts > - The hook aborts with no reason. 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 > - #22090 adds a marked abort reason, `intentionalAbortReason()`, and a Sentry `beforeSend` rule that drops an unhandled rejection only when its value is that exact marked object > - This pull request makes the announcement hook use that marked reason for its own cancellations > - The benefit is that hiding a tab no longer appears as a production error, and every other `AbortError` is still reported ## Linked Issues or Issue Description Refs #22090, which is merged. This change uses its `intentionalAbortReason()` marker and its Sentry `beforeSend` rule. The diff against `master` contains only the `useAnnouncement` change. **What happened?** A hosted browser reported one unhandled rejection: `AbortError: signal is aborted without reason` (DOMException code 20, mechanism `onunhandledrejection`, native trusted promise, tab visibility `hidden` less than one second after the change). The stack is: `document` `visibilitychange` → `useAnnouncement` `onVisibility` → `suspend` → `fetchController.abort()`. **Expected behavior** An intentional cancellation of the announcement fetch does not appear in error monitoring. A real abort failure still appears. **Steps to reproduce** 1. 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. 2. Sign in, so that the announcement hook starts its fetch. 3. Hide the tab while that fetch is in flight. 4. The hook aborts the fetch. The wrapper's derived promise rejects with no handler. The app's own chain ends in `.catch()`, so the app does not cause the rejection. **Paperclip version or commit** Reported on release `651749bdb4`. `ui/src/hooks/useAnnouncement.ts` and `ui/src/api/announcements.ts` are unchanged on `master` up to this branch's base. **Deployment mode** Hosted, browser UI (Chrome-family message text). I searched open and closed PRs for this error message and for `useAnnouncement` abort changes. I found only #22090, which this change reuses. ## What Changed - `ui/src/hooks/useAnnouncement.ts`: the hide, dismiss, and unmount aborts now use `intentionalAbortReason()`. This includes the abort of pending dismissal writes on unmount. - The 10-second dismissal-write timeout still aborts with no reason. A timeout is a real failure, not a cancellation, so it stays reportable. - `ui/src/hooks/useAnnouncement.test.tsx`: a new test checks that each of those aborts carries the marked reason. ## Verification - Red first: with only the new test, `cd ui && npx vitest run src/hooks/useAnnouncement.test.tsx` failed (`isIntentionalAbortReason(hidden.reason)` was `false`). - Green (also again after the merge of `master` with #22090, head `afc31cb0ea`): `cd ui && npx vitest run src/hooks/useAnnouncement.test.tsx src/components/AnnouncementWell.test.tsx src/components/AnnouncementWell.onboarding.test.tsx src/lib/sentry.test.ts src/api/client.test.ts` → 5 files, 72 tests pass. - `cd ui && npx tsc --noEmit -p .` shows no errors in the changed files. The 14 errors it reports are in `storybook/support/feature-map` and are the same without this change. - The `beforeSend` filter itself is tested in #22090 with the real Sentry SDK. ## Risks - Low risk. The hook's behavior does not change: the same requests are cancelled at the same times. Only the abort reason object changes, and no code in the hook reads that reason. - The marked reason has the message "The operation was aborted." instead of the browser default. No code depends on the message. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, 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>
229 lines
11 KiB
TypeScript
229 lines
11 KiB
TypeScript
// @vitest-environment jsdom
|
|
import { act } from "react";
|
|
import { createRoot, type Root } from "react-dom/client";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { useAnnouncement } from "./useAnnouncement";
|
|
import { announcementPreview } from "@/lib/announcement-preview";
|
|
import { announcementStoragePrefix } from "@/lib/announcement-dismissals";
|
|
import { isIntentionalAbortReason } from "@/lib/intentional-abort";
|
|
|
|
const api = vi.hoisted(() => ({ current: vi.fn(), dismiss: vi.fn() }));
|
|
vi.mock("@/api/announcements", () => ({ announcementsApi: api }));
|
|
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
describe("announcement lifecycle", () => {
|
|
let container: HTMLDivElement;
|
|
let root: Root;
|
|
let userId: string;
|
|
let companyId: string;
|
|
let enabled: boolean;
|
|
let failure: ReturnType<typeof vi.fn<(savedLocally: boolean) => void>>;
|
|
let observed: ReturnType<typeof useAnnouncement>;
|
|
let sequence = 0;
|
|
function Harness() {
|
|
observed = useAnnouncement({ userId, companyId, enabled, onSaveFailure: failure });
|
|
return <div>{observed.announcement?.id}</div>;
|
|
}
|
|
const render = async () => { await act(async () => root.render(<Harness />)); };
|
|
const settle = async () => { await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); };
|
|
const event = async (name: string) => { await act(async () => window.dispatchEvent(new Event(name))); };
|
|
const visibility = async (value: "hidden" | "visible") => {
|
|
Object.defineProperty(document, "visibilityState", { configurable: true, value });
|
|
await act(async () => document.dispatchEvent(new Event("visibilitychange")));
|
|
};
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
vi.clearAllMocks();
|
|
api.current.mockResolvedValue(announcementPreview);
|
|
api.dismiss.mockResolvedValue(undefined);
|
|
userId = `user-${++sequence}`;
|
|
companyId = "company-one";
|
|
enabled = true;
|
|
failure = vi.fn();
|
|
// The repository's generic storage stub lacks key()/length; this feature
|
|
// enumerates per-announcement entries, so exercise the full browser API.
|
|
const entries = new Map<string, string>();
|
|
const storage = {
|
|
get length() { return entries.size; },
|
|
key: (index: number) => [...entries.keys()][index] ?? null,
|
|
getItem: (key: string) => entries.get(key) ?? null,
|
|
setItem: (key: string, value: string) => { entries.set(key, String(value)); },
|
|
removeItem: (key: string) => { entries.delete(key); },
|
|
clear: () => entries.clear(),
|
|
};
|
|
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
|
|
Object.defineProperty(window, "localStorage", { configurable: true, value: storage });
|
|
Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" });
|
|
container = document.createElement("div");
|
|
document.body.append(container);
|
|
root = createRoot(container);
|
|
});
|
|
afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
|
|
it("settles before showing and never polls during uninterrupted work", async () => {
|
|
await render();
|
|
expect(container.textContent).toBe("");
|
|
await settle();
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(3_600_000); });
|
|
expect(api.current).toHaveBeenCalledTimes(1);
|
|
companyId = "company-two";
|
|
await render();
|
|
expect(api.current).toHaveBeenCalledTimes(1);
|
|
});
|
|
it("keeps a visible card stable when page focus moves to browser chrome or another pane", async () => {
|
|
await render(); await settle();
|
|
const request = api.current.mock.calls[0][0] as AbortSignal;
|
|
await event("blur");
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
await event("focus");
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
await settle();
|
|
expect(api.current).toHaveBeenCalledTimes(1);
|
|
expect(request.aborted).toBe(false);
|
|
});
|
|
it("does not restart the initial settling period when a visible page gains focus", async () => {
|
|
await render();
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(2500); });
|
|
await event("blur"); await event("focus");
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(500); });
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
expect(api.current).toHaveBeenCalledTimes(1);
|
|
});
|
|
it("dismisses immediately and stays dismissed after a remount and copy edit", async () => {
|
|
await render(); await settle();
|
|
await act(async () => observed.dismiss(announcementPreview.id));
|
|
expect(container.textContent).toBe("");
|
|
expect(api.dismiss).toHaveBeenCalledWith(announcementPreview.id, companyId, expect.any(AbortSignal));
|
|
await act(async () => root.unmount());
|
|
root = createRoot(container);
|
|
api.current.mockResolvedValue({ ...announcementPreview, title: "Corrected" });
|
|
await render(); await settle();
|
|
expect(container.textContent).toBe("");
|
|
expect(api.dismiss).toHaveBeenCalledTimes(1);
|
|
});
|
|
it("refreshes on return, showing a new ID but honoring dismissal in another browser", async () => {
|
|
await render(); await settle();
|
|
api.current.mockResolvedValue(null);
|
|
await visibility("hidden"); await visibility("visible"); await settle();
|
|
expect(container.textContent).toBe("");
|
|
api.current.mockResolvedValue({ ...announcementPreview, id: "new-id" });
|
|
await visibility("hidden"); await visibility("visible"); await settle();
|
|
expect(container.textContent).toBe("new-id");
|
|
});
|
|
it("withholds a returning tab until its fresh dismissal check completes", async () => {
|
|
await render(); await settle();
|
|
await visibility("hidden");
|
|
expect(container.textContent).toBe("");
|
|
let resolve!: (value: null) => void;
|
|
api.current.mockReturnValueOnce(new Promise((done) => { resolve = done; }));
|
|
await visibility("visible");
|
|
// Browsers may report focus as well; it must not abort or duplicate the check.
|
|
await event("focus"); await settle();
|
|
expect(api.current).toHaveBeenCalledTimes(2);
|
|
expect(container.textContent).toBe("");
|
|
await act(async () => resolve(null));
|
|
expect(container.textContent).toBe("");
|
|
});
|
|
it("ignores a late response from before the tab was hidden", async () => {
|
|
let resolve!: (value: typeof announcementPreview) => void;
|
|
api.current.mockReturnValueOnce(new Promise((done) => { resolve = done; }));
|
|
await render();
|
|
const request = api.current.mock.calls[0][0] as AbortSignal;
|
|
await visibility("hidden");
|
|
expect(request.aborted).toBe(true);
|
|
await act(async () => resolve(announcementPreview)); await settle();
|
|
expect(container.textContent).toBe("");
|
|
api.current.mockResolvedValue({ ...announcementPreview, id: "after-return" });
|
|
await visibility("visible");
|
|
expect(container.textContent).toBe("");
|
|
await settle();
|
|
expect(container.textContent).toBe("after-return");
|
|
});
|
|
it("aborts with an intentional reason when the tab is hidden, a card is dismissed, or the hook unmounts", async () => {
|
|
api.current.mockReturnValue(new Promise(() => {}));
|
|
await render();
|
|
const hidden = api.current.mock.calls[0][0] as AbortSignal;
|
|
await visibility("hidden");
|
|
expect(hidden.aborted).toBe(true);
|
|
expect(isIntentionalAbortReason(hidden.reason)).toBe(true);
|
|
|
|
await visibility("visible");
|
|
const dismissed = api.current.mock.calls[1][0] as AbortSignal;
|
|
api.dismiss.mockReturnValue(new Promise(() => {}));
|
|
await act(async () => observed.dismiss(announcementPreview.id));
|
|
expect(dismissed.aborted).toBe(true);
|
|
expect(isIntentionalAbortReason(dismissed.reason)).toBe(true);
|
|
|
|
const write = api.dismiss.mock.calls[0][2] as AbortSignal;
|
|
await visibility("hidden"); await visibility("visible");
|
|
const unmounted = api.current.mock.calls[2][0] as AbortSignal;
|
|
await act(async () => root.unmount());
|
|
root = createRoot(container);
|
|
expect(isIntentionalAbortReason(unmounted.reason)).toBe(true);
|
|
expect(isIntentionalAbortReason(write.reason)).toBe(true);
|
|
});
|
|
it("keeps failed writes pending and retries on reconnect", async () => {
|
|
api.dismiss.mockRejectedValueOnce(new Error("offline"));
|
|
await render(); await settle();
|
|
await act(async () => observed.dismiss(announcementPreview.id));
|
|
expect(container.textContent).toBe("");
|
|
expect(failure).toHaveBeenCalledWith(true);
|
|
expect(localStorage.getItem(`${announcementStoragePrefix(userId)}${announcementPreview.id}`)).toBe("pending");
|
|
await event("online");
|
|
expect(localStorage.getItem(`${announcementStoragePrefix(userId)}${announcementPreview.id}`)).toBe("synced");
|
|
});
|
|
it("does not leak a late fetch across an account change", async () => {
|
|
let resolve!: (value: typeof announcementPreview) => void;
|
|
api.current.mockReturnValueOnce(new Promise((done) => { resolve = done; }));
|
|
await render(); await settle();
|
|
userId = "different-account";
|
|
api.current.mockResolvedValue(null);
|
|
await render();
|
|
await act(async () => resolve(announcementPreview));
|
|
await settle();
|
|
expect(container.textContent).toBe("");
|
|
});
|
|
it("closes after another tab writes a dismissal", async () => {
|
|
await render(); await settle();
|
|
const key = `${announcementStoragePrefix(userId)}${announcementPreview.id}`;
|
|
localStorage.setItem(key, "synced");
|
|
await act(async () => window.dispatchEvent(new StorageEvent("storage", { key, newValue: "synced" })));
|
|
expect(container.textContent).toBe("");
|
|
});
|
|
it("honors a broadcast even when browser storage is unavailable", async () => {
|
|
let channel!: { onmessage: ((event: MessageEvent) => void) | null };
|
|
vi.stubGlobal("BroadcastChannel", class {
|
|
onmessage = null;
|
|
constructor() { channel = this; }
|
|
postMessage() {}
|
|
close() {}
|
|
});
|
|
await render(); await settle();
|
|
vi.spyOn(localStorage, "setItem").mockImplementation(() => { throw new Error("Storage denied"); });
|
|
await act(async () => channel.onmessage?.(new MessageEvent("message", { data: announcementPreview.id })));
|
|
expect(container.textContent).toBe("");
|
|
await visibility("hidden"); await visibility("visible"); await settle();
|
|
expect(container.textContent).toBe("");
|
|
expect(api.dismiss).toHaveBeenCalled();
|
|
});
|
|
it("withholds unknown state, disabled/onboarding state and hidden tabs", async () => {
|
|
api.current.mockRejectedValue(new Error("unavailable"));
|
|
await render(); await settle();
|
|
expect(container.textContent).toBe("");
|
|
enabled = false; await render();
|
|
api.current.mockClear();
|
|
await event("focus"); await settle();
|
|
expect(api.current).not.toHaveBeenCalled();
|
|
Object.defineProperty(document, "visibilityState", { configurable: true, value: "hidden" });
|
|
enabled = true; await render(); await settle();
|
|
expect(api.current).not.toHaveBeenCalled();
|
|
});
|
|
it("expires while visible", async () => {
|
|
api.current.mockResolvedValue({ ...announcementPreview, expiresAt: new Date(Date.now() + 4000).toISOString() });
|
|
await render(); await settle();
|
|
expect(container.textContent).toBe(announcementPreview.id);
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
|
|
expect(container.textContent).toBe("");
|
|
});
|
|
});
|