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>
This commit is contained in:
authored and GitHub committed 2026-11-24 09:57:37 -08:00
1 parent 6385c171fa
commit d01d3c40ad
9 files changed
+211 -18

No files matched your search

+4 -3
View File
@@ -1,3 +1,4 @@
import { AnnouncementVisitProvider } from "./context/AnnouncementVisitContext";
import { useCoordinatorWorkspaceEnabled } from "./hooks/useCoordinatorWorkspaceEnabled";
import { AgentChats } from "./pages/AgentChats";
import { lazy, Suspense, useEffect, type ReactNode } from "react";
@@ -782,7 +783,7 @@ function NoCompaniesStartPage() {
export function App() {
const { pathname } = useLocation();
const { enabled: classicStreamlinedUiEnabled, loaded: classicStreamlinedUiLoaded } = useStreamlinedUiEnabled();
const { enabled: coordinatorWorkspaceEnabled, loaded: coordinatorWorkspaceLoaded } = useCoordinatorWorkspaceEnabled();
const { enabled: coordinatorWorkspaceEnabled, loaded: coordinatorWorkspaceLoaded, userId } = useCoordinatorWorkspaceEnabled();
const streamlinedUiEnabled = classicStreamlinedUiEnabled || coordinatorWorkspaceEnabled;
const streamlinedUiLoaded = classicStreamlinedUiLoaded && coordinatorWorkspaceLoaded;
const { enabled: combinedInboxTasksEnabled } = useCombinedInboxTasksEnabled();
@@ -899,11 +900,11 @@ export function App() {
);
return (
<>
<AnnouncementVisitProvider userId={userId}>
<ConnectionStatusBanner />
<PageLoadTracker routes={routeTree} />
<Suspense fallback={<PaperclipLoading />}><Routes>{routeTree}</Routes></Suspense>
<OnboardingWizardVariant />
</>
</AnnouncementVisitProvider>
);
}
-5
View File
@@ -29,11 +29,6 @@ export function useModalOpen(enabled: boolean, selector = MODAL_SELECTOR) {
const FINISHED_ONBOARDING_STATUSES = new Set(["done", "cancelled"]);
/**
* A new user's first session is the onboarding first task. Announcements and
* other optional prompts wait until that task is finished so they cannot cover
* its questions. Unknown state (loading or a failed read) keeps them hidden.
*/
export function useOnboardingInProgress(companyId: string | null) {
const query = useQuery({
queryKey: queryKeys.issues.onboardingFirstTask(companyId ?? "__none__"),
@@ -0,0 +1,85 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
const IDLE_MS = 30 * 60_000;
const ReturningUser = createContext<string | null>(null);
export function useReturningAnnouncementUser(userId: string | null) {
const returningUser = useContext(ReturningUser);
return userId !== null && userId === returningUser;
}
export function AnnouncementVisitProvider({ userId, children }: { userId: string | null; children: ReactNode }) {
const [returningUser, setReturningUser] = useState<string | null>(null);
useEffect(() => {
setReturningUser(null);
if (!userId) return;
const key = `paperclip.board-visit.v1:${encodeURIComponent(userId)}`;
const returnedKey = `${key}:returned`;
const listeners = new AbortController();
const options = { capture: true, passive: true, signal: listeners.signal };
let lastActivity = 0;
let pending: ReturnType<typeof setTimeout> | undefined;
function finish() {
clearTimeout(pending);
pending = undefined;
listeners.abort();
setReturningUser(userId);
}
function saveActivity() {
clearTimeout(pending);
pending = undefined;
try {
const saved = Number(localStorage.getItem(key)) || 0;
if (lastActivity > saved) localStorage.setItem(key, String(lastActivity));
} catch { return; }
}
function activity() {
if (document.visibilityState === "hidden") return;
const now = Date.now();
if (!lastActivity || now - lastActivity >= IDLE_MS) {
try {
if (localStorage.getItem(returnedKey) === "1") {
finish();
return;
}
const previous = Math.max(lastActivity, Number(localStorage.getItem(key)) || 0);
if (previous > 0 && now - previous >= IDLE_MS) {
localStorage.setItem(returnedKey, "1");
finish();
return;
}
lastActivity = now;
saveActivity();
} catch { return; }
return;
}
lastActivity = now;
pending ??= setTimeout(saveActivity, 1000);
}
function visibility() {
if (document.visibilityState === "hidden") saveActivity();
else activity();
}
for (const event of ["keydown", "pointerdown", "pointermove", "wheel", "input", "pageshow"]) {
window.addEventListener(event, activity, options);
}
window.addEventListener("focus", activity, { signal: listeners.signal });
window.addEventListener("pagehide", saveActivity, options);
document.addEventListener("visibilitychange", visibility, options);
window.addEventListener("storage", (event) => {
if (event.key === returnedKey && event.newValue === "1") finish();
}, options);
activity();
return () => {
if (pending !== undefined) saveActivity();
listeners.abort();
};
}, [userId]);
return <ReturningUser.Provider value={returningUser === userId ? userId : null}>{children}</ReturningUser.Provider>;
}
+71 -1
View File
@@ -3,11 +3,17 @@ 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;
@@ -24,7 +30,7 @@ describe("announcement lifecycle", () => {
observed = useAnnouncement({ userId, companyId, enabled, onSaveFailure: failure });
return <div>{observed.announcement?.id}</div>;
}
const render = async () => { await act(async () => root.render(<Harness />)); };
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") => {
@@ -59,6 +65,70 @@ describe("announcement lifecycle", () => {
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("");
+10 -2
View File
@@ -1,10 +1,13 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { announcementIdSchema, type Announcement } from "@paperclipai/shared";
import { useReturningAnnouncementUser } from "@/context/AnnouncementVisitContext";
import { announcementsApi } from "@/api/announcements";
import { announcementStoragePrefix, readAnnouncementDismissals, saveAnnouncementDismissal } from "@/lib/announcement-dismissals";
import { intentionalAbortReason } from "@/lib/intentional-abort";
export const ANNOUNCEMENT_SETTLE_MS = 3000;
const CONNECTORS_ANNOUNCEMENT_ID = "2026-09-14-connectors";
interface Options {
userId: string | null;
companyId: string | null;
@@ -14,6 +17,7 @@ interface Options {
export function useAnnouncement(options: Options) {
const { userId, enabled } = options;
const returningUser = useReturningAnnouncementUser(userId);
const latest = useRef(options);
latest.current = options;
const [state, setState] = useState<{ userId: string; announcement: Announcement } | null>(null);
@@ -79,6 +83,7 @@ export function useAnnouncement(options: Options) {
let candidate: Announcement | null = null;
const show = () => {
if (!stillCurrent() || !settled || !loaded) return;
if (candidate?.id === CONNECTORS_ANNOUNCEMENT_ID && !returningUser) return;
if (candidate && !readAnnouncementDismissals(userId!).has(candidate.id)
&& (!candidate.expiresAt || Date.parse(candidate.expiresAt) > Date.now())) {
setState({ userId: userId!, announcement: candidate });
@@ -135,7 +140,7 @@ export function useAnnouncement(options: Options) {
window.removeEventListener("storage", onStorage);
dismissRef.current = () => {};
};
}, [userId, enabled]);
}, [userId, enabled, returningUser]);
const announcement = enabled && state?.userId === userId ? state.announcement : null;
useEffect(() => {
@@ -149,5 +154,8 @@ export function useAnnouncement(options: Options) {
check();
return () => clearTimeout(timer);
}, [announcement]);
return { announcement, dismiss: useCallback((id: string) => dismissRef.current(id), []) };
return {
announcement,
dismiss: useCallback((id: string) => dismissRef.current(id), []),
};
}