diff --git a/doc/ANNOUNCEMENTS.md b/doc/ANNOUNCEMENTS.md index 896bec2a32c..b8105413feb 100644 --- a/doc/ANNOUNCEMENTS.md +++ b/doc/ANNOUNCEMENTS.md @@ -257,6 +257,13 @@ period. A hidden tab clears the card; becoming visible fetches fresh dismissal state before showing anything, even if that lookup takes longer than three seconds. +The Connectors promotion (`2026-09-14-connectors`) also waits for +the user's second visit. In this browser, returning to Paperclip or interacting +with it after 30 minutes of inactivity starts that visit. The board records +first-visit activity per account across tabs and companies, including time in +the onboarding wizard and the agent chat. Once eligible, the browser remembers +that the account has returned. Clearing site data starts the visit history over. + The instance caches the feed for an hour, deduplicates concurrent fetches, and uses conditional requests. Failed requests have a fifteen-minute cooldown; no card appears for unavailable/invalid/incompatible content. Each request has a diff --git a/tests/e2e/announcement-first-session.spec.ts b/tests/e2e/announcement-first-session.spec.ts index 265b7924219..d0b676a9bef 100644 --- a/tests/e2e/announcement-first-session.spec.ts +++ b/tests/e2e/announcement-first-session.spec.ts @@ -1,4 +1,5 @@ import { test, expect, request as pwRequest, type APIRequestContext, type Page } from "@playwright/test"; +import { seedReturningAnnouncementVisit } from "./helpers/announcement-visit"; /** * E2E (N-13): the in-app announcement well ("Introducing Connectors" upsell) @@ -14,7 +15,7 @@ import { test, expect, request as pwRequest, type APIRequestContext, type Page } const PORT = Number(process.env.PAPERCLIP_E2E_PORT ?? 3199); const BASE_URL = `http://127.0.0.1:${PORT}`; -const ANNOUNCEMENT_ID = "e2e-n13-connectors"; +const ANNOUNCEMENT_ID = "2026-09-14-connectors"; const SETTLE_WAIT_MS = 4_500; // ANNOUNCEMENT_SETTLE_MS (3 s) plus slack. const ONE_PIXEL_PNG = Buffer.from( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", @@ -30,7 +31,8 @@ async function createCompany(board: APIRequestContext, name: string) { data: { name: "Chief of staff", role: "ceo", adapterType: "process", adapterConfig: { command: "true" } }, }); if (!agentRes.ok()) throw new Error(`POST agents → ${agentRes.status()}: ${await agentRes.text()}`); - return { id: company.id as string, prefix: (company.issuePrefix ?? company.prefix) as string }; + const agent = await agentRes.json(); + return { agentId: agent.id as string, id: company.id as string, prefix: (company.issuePrefix ?? company.prefix) as string }; } async function createIssue(board: APIRequestContext, companyId: string, data: Record) { @@ -54,11 +56,6 @@ async function mockAnnouncementFeed(page: Page) { await page.route("**/api/workspace-preferences/me", (route) => route.fulfill({ json: { userId: "local-board", coordinatorWorkspaceEnabled: false, updatedAt: null, } })); - await page.addInitScript(() => { - for (const key of Object.keys(window.localStorage)) { - if (key.includes("announcement")) window.localStorage.removeItem(key); - } - }); } test.describe("Announcement well (N-13)", () => { @@ -79,7 +76,27 @@ test.describe("Announcement well (N-13)", () => { await mockAnnouncementFeed(page); }); + test("chat-first onboarding keeps Connectors hidden across a reload until an idle return", async ({ page }) => { + const company = await createCompany(board, "E2E-Chat-Onboarding"); + companyIds.push(company.id); + const start = await board.post(`${BASE_URL}/api/companies/${company.id}/chats/${company.agentId}/onboarding`, { data: {} }); + expect(start.ok(), await start.text()).toBe(true); + const path = `/${company.prefix}/chats/${company.agentId}`; + const well = page.getByRole("complementary", { name: "Paperclip announcements" }); + await page.clock.install(); + for (const navigate of [() => page.goto(path), () => page.reload()]) { + await Promise.all([page.waitForResponse("**/api/announcements/current"), navigate()]); + await page.clock.fastForward(SETTLE_WAIT_MS); + await expect(well).toHaveCount(0); + } + const now = await page.evaluate(() => Date.now()); + await page.clock.setSystemTime(now + 30 * 60_000); + await page.keyboard.press("Shift"); + await expect(well.getByRole("link", { name: "Explore connectors" })).toBeVisible(); + }); + test("a brand-new company with its onboarding task open does not show the upsell", async ({ page }) => { + await seedReturningAnnouncementVisit(page); const company = await createCompany(board, "E2E-N13-Onboarding"); companyIds.push(company.id); const firstTask = await createIssue(board, company.id, { diff --git a/tests/e2e/announcement-placement.spec.ts b/tests/e2e/announcement-placement.spec.ts index 89f57dc6856..6d26456c690 100644 --- a/tests/e2e/announcement-placement.spec.ts +++ b/tests/e2e/announcement-placement.spec.ts @@ -1,4 +1,5 @@ import { test, expect, type APIRequestContext, type APIResponse, type Locator, type Page } from "@playwright/test"; +import { seedReturningAnnouncementVisit } from "./helpers/announcement-visit"; /** * N-17: a new user's first task view must stay usable while the in-app @@ -54,6 +55,7 @@ async function box(locator: Locator, name: string): Promise { } async function serveConnectorsAnnouncement(page: Page, announcement: object = CONNECTORS_ANNOUNCEMENT) { + await seedReturningAnnouncementVisit(page); await page.route("**/api/announcements/current", (route) => route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(announcement) }), ); diff --git a/tests/e2e/helpers/announcement-visit.ts b/tests/e2e/helpers/announcement-visit.ts new file mode 100644 index 00000000000..c9c15126e56 --- /dev/null +++ b/tests/e2e/helpers/announcement-visit.ts @@ -0,0 +1,8 @@ +import type { Page } from "@playwright/test"; + +export async function seedReturningAnnouncementVisit(page: Page) { + await page.addInitScript(() => { + const key = "paperclip.board-visit.v1:local-board"; + if (!localStorage.getItem(key)) localStorage.setItem(key, String(Date.now() - 31 * 60_000)); + }); +} diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 4de1a8fea09..7e07680dd3b 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -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 ( - <> + }>{routeTree} - + ); } diff --git a/ui/src/components/AnnouncementWell.tsx b/ui/src/components/AnnouncementWell.tsx index 2eb996dd33c..7262f2572ca 100644 --- a/ui/src/components/AnnouncementWell.tsx +++ b/ui/src/components/AnnouncementWell.tsx @@ -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__"), diff --git a/ui/src/context/AnnouncementVisitContext.tsx b/ui/src/context/AnnouncementVisitContext.tsx new file mode 100644 index 00000000000..89509f4657a --- /dev/null +++ b/ui/src/context/AnnouncementVisitContext.tsx @@ -0,0 +1,85 @@ +import { createContext, useContext, useEffect, useState, type ReactNode } from "react"; + +const IDLE_MS = 30 * 60_000; +const ReturningUser = createContext(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(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 | 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 {children}; +} diff --git a/ui/src/hooks/useAnnouncement.test.tsx b/ui/src/hooks/useAnnouncement.test.tsx index 93002ae2cdd..baa5bc3a8d2 100644 --- a/ui/src/hooks/useAnnouncement.test.tsx +++ b/ui/src/hooks/useAnnouncement.test.tsx @@ -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
{observed.announcement?.id}
; } - const render = async () => { await act(async () => root.render()); }; + const render = async () => { await act(async () => root.render()); }; 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(""); diff --git a/ui/src/hooks/useAnnouncement.ts b/ui/src/hooks/useAnnouncement.ts index cfe7ddf25b6..9fa60f5cb30 100644 --- a/ui/src/hooks/useAnnouncement.ts +++ b/ui/src/hooks/useAnnouncement.ts @@ -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), []), + }; }