Files
PaperClipAI/ui/src/hooks/useAnnouncement.test.tsx
T
d01d3c40ad fix(ui): defer the Connectors announcement until a return visit (#22790)
## Thinking Path

> - People use Paperclip to manage AI agents at work.
> - New users now meet their agent in chat after setup.
> - The Connectors card previously checked for an open onboarding task.
> - Chat-first onboarding creates no such task, so the card could appear
three seconds into a first visit.
> - This change holds that promotion until the person returns after 30
minutes of inactivity.

## Linked Issues or Issue Description

Refs: #19514, #22077

**What happened?**

On master at `11cfe0910d`, a new user could see the Connectors card in
their first agent chat.

**Expected behavior**

The card stays hidden through the first visit and can appear when the
user returns after a 30-minute gap in activity.

**Steps to reproduce**

With the Connectors announcement active, finish chat-first onboarding in
a fresh browser profile and wait for the announcement delay.

## What Changed

- Track the first visible board visit per account in browser storage.
Local input and visits in other tabs extend the first session. After the
first qualifying return, the browser remembers eligibility and stops
tracking input.
- Apply this rule to the published Connectors announcement ID. The
existing checks for dismissal, open dialogs, and legacy onboarding tasks
still apply.
- Exercise the onboarding chat, reload, idle return, account isolation,
and activity in another tab.

## Verification

- Before the fix, the Vitest regression displayed
`2026-09-14-connectors` on the first visit.
- The announcement and workspace identity Vitest suites passed locally
(28 tests). The UI typecheck passed.
- Chromium passed all four tests in `announcement-first-session.spec.ts`
and `announcement-placement.spec.ts` against a local test server.
- A second red-green regression covers dismissal in another browser
while the first tab sits idle. The return triggers a fresh check and
keeps the card hidden until it succeeds.
- At `8fab1932fa`, GitHub reported 73 successful checks and three
skipped checks. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/45449353624)

## Risks

A new browser profile or cleared site data starts the visit history
again. Storage failures keep the Connectors card hidden. Existing users
start accumulating visit history when they first use this version.

## Model Used

OpenAI Codex, GPT-6.2 Astra (`gpt-6.2-astra`), with shell, Vitest, and
Playwright.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Scott Tong <scott@scotts-mbp-m5-max.local>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-24 09:57:37 -08:00

299 lines
14 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 { AnnouncementVisitProvider } from "@/context/AnnouncementVisitContext";
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() }));
const connectors = {
...announcementPreview,
id: "2026-09-14-connectors",
primaryAction: { kind: "route", path: "/apps", label: "Explore connectors" },
};
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(<AnnouncementVisitProvider userId={userId}><Harness /></AnnouncementVisitProvider>)); };
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("keeps the Connectors card out of chat until the user returns after 30 idle minutes", async () => {
api.current.mockResolvedValue(connectors);
await render();
await settle();
expect(container.textContent).toBe("");
const idle = 30 * 60_000;
await act(async () => { await vi.advanceTimersByTimeAsync(idle - 4000); });
await event("keydown");
await visibility("hidden");
await visibility("visible");
companyId = "company-two";
await render();
await settle();
expect(container.textContent).toBe("");
await act(async () => root.unmount());
root = createRoot(container);
await render();
await settle();
expect(container.textContent).toBe("");
await act(async () => { await vi.advanceTimersByTimeAsync(idle); });
expect(container.textContent).toBe("");
await event("pointerdown");
await settle();
expect(container.textContent).toBe(connectors.id);
userId = "another-first-time-user";
await render();
await settle();
expect(container.textContent).toBe("");
});
it("uses the most recent activity across tabs, including visits while onboarding hides the feed", async () => {
api.current.mockResolvedValue(connectors);
enabled = false;
await render();
await visibility("hidden");
const idle = 30 * 60_000;
await act(async () => { await vi.advanceTimersByTimeAsync(idle); });
localStorage.setItem(`paperclip.board-visit.v1:${userId}`, String(Date.now() - idle + 1));
enabled = true;
await render();
await visibility("visible");
await settle();
expect(container.textContent).toBe("");
await visibility("hidden");
await act(async () => { await vi.advanceTimersByTimeAsync(idle - 3000); });
await visibility("visible");
await settle();
expect(container.textContent).toBe(connectors.id);
});
it("checks for a dismissal from another browser before revealing Connectors on an idle return", async () => {
api.current.mockResolvedValueOnce(connectors);
let respond!: (value: null) => void;
api.current.mockReturnValueOnce(new Promise((resolve) => { respond = resolve; }));
await render();
await act(async () => { await vi.advanceTimersByTimeAsync(30 * 60_000); });
await event("pointerdown");
await settle();
expect(container.textContent).toBe("");
expect(api.current).toHaveBeenCalledTimes(2);
await act(async () => respond(null));
expect(container.textContent).toBe("");
});
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("");
});
});