From 1db943c224987d7a6420628ec7cb919ca03e61aa Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Thu, 12 Nov 2026 15:34:31 +0200 Subject: [PATCH 1/8] fix(streak): count companion reads toward the reading streak The browser-extension companion never called the viewPost mutation, so reading an article with the companion on the page did not create a view and did not extend the reading streak. Only the webapp post page did, through useTrackPostView. Route useViewPost through useRequestProtocol like the other shared mutation hooks the companion uses (vote, bookmark), so the same hook proxies the mutation through the background script in the content script and keeps calling the API directly in the webapp. The companion now mounts useTrackPostView once it has resolved the post for the page, which keeps the webapp rules: logged-in users only, once per post id, failures swallowed. The protocol query is seeded with initialData so the view fired from the mount effect already sees the companion proxy instead of the default client. The view fires when the companion resolves a post for the page, whether the panel is expanded or collapsed: the user is on the article page, the same signal the webapp post page uses. Co-Authored-By: Claude Fable 5.1 --- .../src/companion/Companion.spec.tsx | 63 ++++++++++++++++--- .../extension/src/companion/Companion.tsx | 18 ++++-- packages/shared/src/graphql/posts.ts | 3 - packages/shared/src/hooks/post/useViewPost.ts | 6 +- 4 files changed, 70 insertions(+), 20 deletions(-) diff --git a/packages/extension/src/companion/Companion.spec.tsx b/packages/extension/src/companion/Companion.spec.tsx index ce1b5796655..719492b7ddb 100644 --- a/packages/extension/src/companion/Companion.spec.tsx +++ b/packages/extension/src/companion/Companion.spec.tsx @@ -1,14 +1,21 @@ import React from 'react'; import '@testing-library/jest-dom'; import type { RenderResult } from '@testing-library/react'; -import { fireEvent, render, screen } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import browser from 'webextension-polyfill'; import defaultUser from '@dailydotdev/shared/__tests__/fixture/loggedUser'; -import { UserVote } from '@dailydotdev/shared/src/graphql/posts'; +import { + UserVote, + VIEW_POST_MUTATION, +} from '@dailydotdev/shared/src/graphql/posts'; +import { ExtensionMessageType } from '@dailydotdev/shared/src/lib/extension'; +import type { AnonymousUser } from '@dailydotdev/shared/src/lib/user'; import { completeActionMock, mockGraphQL, } from '@dailydotdev/shared/__tests__/helpers/graphql'; import { ActionType } from '@dailydotdev/shared/src/graphql/actions'; +import type { CompanionData } from './App'; import App from './App'; jest.mock('webextension-polyfill', () => { @@ -27,10 +34,7 @@ jest.mock('webextension-polyfill', () => { addListener: jest.fn(), removeListener: jest.fn(), }, - sendMessage: () => - new Promise((resolve) => { - resolve(true); - }), + sendMessage: jest.fn(() => Promise.resolve(true)), }, permissions: { remove: jest.fn(), @@ -60,11 +64,28 @@ const defaultPostData = { }, }; -const renderComponent = (postdata, settings): RenderResult => { +const anonymousUser: AnonymousUser = { id: 'anonymous', firstVisit: '' }; + +const sendMessage = browser.runtime.sendMessage as jest.Mock; + +const viewPostMessages = () => + sendMessage.mock.calls.filter( + ([message]) => + message?.type === ExtensionMessageType.GraphQLRequest && + message.document === VIEW_POST_MUTATION, + ); + +const renderComponent = ( + postdata: Partial, + settings: Partial, + user: CompanionData['user'] = defaultUser, +): RenderResult => { return render( { visitId: '123', sessionId: '456', }} - user={defaultUser} + user={user} deviceId="123" accessToken={{ token: '', expiresIn: '' }} squads={[]} @@ -82,6 +103,10 @@ const renderComponent = (postdata, settings): RenderResult => { }; describe('companion app', () => { + beforeEach(() => { + sendMessage.mockClear(); + }); + it('should render the companion app', async () => { renderComponent({}, {}); const wrapper = await screen.findByTestId('companion'); @@ -177,6 +202,24 @@ describe('companion app', () => { expect(await screen.findByText('Discussion')).toBeInTheDocument(); }); + it('should send a post view once for a logged-in user', async () => { + renderComponent({}, {}); + await screen.findByTestId('companion'); + await waitFor(() => expect(viewPostMessages()).toHaveLength(1)); + expect(viewPostMessages()[0][0]).toMatchObject({ + variables: { id: defaultPostData.id }, + }); + await new Promise(process.nextTick); + expect(viewPostMessages()).toHaveLength(1); + }); + + it('should not send a post view for a logged-out user', async () => { + renderComponent({}, {}, anonymousUser); + await screen.findByTestId('companion'); + await new Promise(process.nextTick); + expect(viewPostMessages()).toHaveLength(0); + }); + it('should decrement number of upvotes if downvoting post that was upvoted', async () => { mockGraphQL(completeActionMock({ action: ActionType.VotePost })); diff --git a/packages/extension/src/companion/Companion.tsx b/packages/extension/src/companion/Companion.tsx index b0b4987d791..18aad867499 100644 --- a/packages/extension/src/companion/Companion.tsx +++ b/packages/extension/src/companion/Companion.tsx @@ -14,6 +14,7 @@ import useLogPageView from '@dailydotdev/shared/src/hooks/log/useLogPageView'; import useDebounceFn from '@dailydotdev/shared/src/hooks/useDebounceFn'; import { usePopupSelector } from '@dailydotdev/shared/src/hooks/usePopupSelector'; import { useBackgroundRequest } from '@dailydotdev/shared/src/hooks/companion'; +import { useTrackPostView } from '@dailydotdev/shared/src/hooks/post/useTrackPostView'; import { getPostByIdKey, updatePostCache, @@ -75,6 +76,12 @@ const Container = ({ export const refreshTokenKey = ['refresh_token']; +const requestProtocol = { + requestMethod: companionRequest, + fetchMethod: companionFetch, + isCompanion: true, +}; + export default function Companion({ postData, companionHelper, @@ -123,12 +130,13 @@ export default function Companion({ const [isDragging, setIsDragging] = useState(false); useQuery({ queryKey: REQUEST_PROTOCOL_KEY, - queryFn: () => ({ - requestMethod: companionRequest, - fetchMethod: companionFetch, - isCompanion: true, - }), + queryFn: () => requestProtocol, + // Seed the cache so hooks reading the protocol in this same render (the + // view below) proxy through the background instead of calling the API + // from the content script. + initialData: requestProtocol, }); + useTrackPostView({ post }); const [assetsLoadedDebounce] = useDebounceFn(() => setAssetsLoaded(true), 10); const routeChangedCallbackRef = useLogPageView(); diff --git a/packages/shared/src/graphql/posts.ts b/packages/shared/src/graphql/posts.ts index 04c14c9e1d3..47c5024374a 100644 --- a/packages/shared/src/graphql/posts.ts +++ b/packages/shared/src/graphql/posts.ts @@ -724,9 +724,6 @@ export const VIEW_POST_MUTATION = gql` } `; -export const sendViewPost = (id: string): Promise => - gqlClient.request(VIEW_POST_MUTATION, { id }); - export const LATEST_CHANGELOG_POST_QUERY = gql` query LatestChangelogPost { page: sourceFeed(source: "daily_updates", first: 1, ranking: TIME) { diff --git a/packages/shared/src/hooks/post/useViewPost.ts b/packages/shared/src/hooks/post/useViewPost.ts index 0c60c632a72..1d41cf35701 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -1,10 +1,11 @@ import type { UseMutateAsyncFunction } from '@tanstack/react-query'; import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { sendViewPost } from '../../graphql/posts'; +import { VIEW_POST_MUTATION } from '../../graphql/posts'; import { generateQueryKey, RequestKey } from '../../lib/query'; import { useAuthContext } from '../../contexts/AuthContext'; import type { UserStreak } from '../../graphql/users'; import { isSameDayInTimezone } from '../../lib/timezones'; +import { useRequestProtocol } from '../useRequestProtocol'; export const useViewPost = (): UseMutateAsyncFunction< unknown, @@ -12,11 +13,12 @@ export const useViewPost = (): UseMutateAsyncFunction< string > => { const client = useQueryClient(); + const { requestMethod } = useRequestProtocol(); const { user } = useAuthContext(); const streakKey = generateQueryKey(RequestKey.UserStreak, user); const readKey = generateQueryKey(RequestKey.ReadingStreak30Days, user); const { mutateAsync: onSendViewPost } = useMutation({ - mutationFn: sendViewPost, + mutationFn: (id: string) => requestMethod(VIEW_POST_MUTATION, { id }), onSuccess: async () => { const streak = client.getQueryData(streakKey); const isNewStreak = !streak?.lastViewAt; From 688b1a3cc50c5e9eb0bce939d0ccd1ec431f08ff Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Thu, 12 Nov 2026 15:55:32 +0200 Subject: [PATCH 2/8] feat(streak): count the read on open and retry dropped views On a slow or flaky connection the viewPost mutation fired by the post page was lost: useViewPost sent it once, swallowed the failure, and the streak stayed where it was although the user had read the post. Behind the streak_optimistic_view flag (default off), useViewPost now bumps the cached userStreak before the request when today is not yet counted (current + 1, total + 1, max, lastViewAt = now), keeps the existing refetch on success so the server value wins, and rolls the cache back to the snapshot when the API answers with a GraphQL error. A network failure keeps the optimistic streak and queues the view in localStorage (dailydev:streak:pendingViews, deduped by post id) with the user id, timestamp and profile timezone. useStreakViewQueue, mounted next to useCheckLocation in the webapp and new-tab shells, replays the queue for the signed-in user on app load and on the window `online` event. It only sends entries that still fall on the same local day in the user's timezone or inside the 00:00 to 03:00 grace window of the following day, which mirrors the API crediting early-morning reads to the previous day; older entries are dropped without a request. Entries go away on success or a GraphQL rejection and stay on another network failure. After a successful replay the streak and reading-history queries are invalidated. The companion content script keeps today's single-shot behaviour: it has no streak query so the optimistic update is a no-op, and because its localStorage belongs to the host page it never persists the queue (useRequestProtocol().isCompanion). Co-Authored-By: Claude Fable 5.1 --- packages/extension/src/newtab/App.tsx | 2 + .../src/hooks/post/useViewPost.spec.tsx | 215 ++++++++++++++++++ packages/shared/src/hooks/post/useViewPost.ts | 68 +++++- .../hooks/streaks/useStreakViewQueue.spec.tsx | 166 ++++++++++++++ .../src/hooks/streaks/useStreakViewQueue.ts | 71 ++++++ packages/shared/src/lib/featureManagement.ts | 7 + packages/shared/src/lib/storage.ts | 1 + .../shared/src/lib/streakViewQueue.spec.ts | 53 +++++ packages/shared/src/lib/streakViewQueue.ts | 150 ++++++++++++ packages/webapp/pages/_app.tsx | 2 + 10 files changed, 730 insertions(+), 5 deletions(-) create mode 100644 packages/shared/src/hooks/post/useViewPost.spec.tsx create mode 100644 packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx create mode 100644 packages/shared/src/hooks/streaks/useStreakViewQueue.ts create mode 100644 packages/shared/src/lib/streakViewQueue.spec.ts create mode 100644 packages/shared/src/lib/streakViewQueue.ts diff --git a/packages/extension/src/newtab/App.tsx b/packages/extension/src/newtab/App.tsx index 814c26338af..9ff2ca00bb3 100644 --- a/packages/extension/src/newtab/App.tsx +++ b/packages/extension/src/newtab/App.tsx @@ -36,6 +36,7 @@ import { useOnboardingActions } from '@dailydotdev/shared/src/hooks/auth'; import { useCheckCoresRole } from '@dailydotdev/shared/src/hooks/useCheckCoresRole'; import { ShortcutsProvider } from '@dailydotdev/shared/src/features/shortcuts/contexts/ShortcutsProvider'; import { useCheckLocation } from '@dailydotdev/shared/src/hooks/useCheckLocation'; +import { useStreakViewQueue } from '@dailydotdev/shared/src/hooks/streaks/useStreakViewQueue'; import { useScrollbarWidth } from '@dailydotdev/shared/src/hooks/useScrollbarWidth'; import { ErrorBoundary } from '@dailydotdev/shared/src/components/ErrorBoundary'; import { ExtensionContextProvider } from '../contexts/ExtensionContext'; @@ -119,6 +120,7 @@ function InternalApp(): ReactElement { useCheckLocation(); useCheckCoresRole(); + useStreakViewQueue(); useEffect(() => { if (routeChangedCallbackRef.current && isPageReady) { diff --git a/packages/shared/src/hooks/post/useViewPost.spec.tsx b/packages/shared/src/hooks/post/useViewPost.spec.tsx new file mode 100644 index 00000000000..cc47be0493f --- /dev/null +++ b/packages/shared/src/hooks/post/useViewPost.spec.tsx @@ -0,0 +1,215 @@ +import React from 'react'; +import type { ReactNode } from 'react'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClient, useQuery } from '@tanstack/react-query'; +import { GrowthBook } from '@growthbook/growthbook-react'; +import nock from 'nock'; +import { TestBootProvider } from '../../../__tests__/helpers/boot'; +import { mockGraphQL } from '../../../__tests__/helpers/graphql'; +import loggedUser from '../../../__tests__/fixture/loggedUser'; +import type { UserStreak } from '../../graphql/users'; +import { getReadingStreak, USER_STREAK_QUERY } from '../../graphql/users'; +import { VIEW_POST_MUTATION } from '../../graphql/posts'; +import { REQUEST_PROTOCOL_KEY } from '../../graphql/common'; +import { generateQueryKey, RequestKey } from '../../lib/query'; +import { DayOfWeek } from '../../lib/date'; +import { readStreakViewQueue } from '../../lib/streakViewQueue'; +import { useViewPost } from './useViewPost'; + +const user = { ...loggedUser, timezone: 'Europe/Amsterdam' }; +const streakKey = generateQueryKey(RequestKey.UserStreak, user); +const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000); + +const streak: UserStreak = { + max: 7, + total: 20, + current: 7, + weekStart: DayOfWeek.Monday, + lastViewAt: yesterday, + freezesAvailable: 0, +}; + +const serverStreak: UserStreak = { + ...streak, + current: 8, + max: 8, + total: 21, + lastViewAt: new Date(), +}; + +const graphqlError = { response: { data: null, errors: [{ message: 'no' }] } }; +const networkError = new TypeError('Failed to fetch'); + +const renderViewPost = ({ + client, + requestMethod, + flag = true, + isCompanion = false, +}: { + client: QueryClient; + requestMethod: jest.Mock; + flag?: boolean; + isCompanion?: boolean; +}) => { + client.setQueryData(REQUEST_PROTOCOL_KEY, { requestMethod, isCompanion }); + const gb = new GrowthBook({ + features: { streak_optimistic_view: { defaultValue: flag } }, + }); + const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + + ); + + return renderHook( + () => { + // the streak query the post page shell already has in cache + useQuery({ + queryKey: streakKey, + queryFn: getReadingStreak, + initialData: streak, + staleTime: Infinity, + }); + + return useViewPost(); + }, + { wrapper }, + ); +}; + +describe('useViewPost', () => { + let client: QueryClient; + + beforeEach(() => { + nock.cleanAll(); + localStorage.clear(); + client = new QueryClient(); + }); + + it('should bump the cached streak before the response and keep it after success', async () => { + let resolve: (value: unknown) => void; + const requestMethod = jest.fn( + () => + new Promise((res) => { + resolve = res; + }), + ); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: serverStreak } }, + }); + const { result } = renderViewPost({ client, requestMethod }); + + const promise = result.current('p1'); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + }), + ); + expect(requestMethod).toHaveBeenCalledWith(VIEW_POST_MUTATION, { + id: 'p1', + }); + + await act(async () => { + resolve!({ viewPost: { _: true } }); + await promise; + }); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + lastViewAt: serverStreak.lastViewAt.toISOString(), + }), + ); + expect(readStreakViewQueue()).toEqual([]); + }); + + it('should roll the streak back when the API rejects the view', async () => { + const requestMethod = jest.fn().mockRejectedValue(graphqlError); + const { result } = renderViewPost({ client, requestMethod }); + + await expect(result.current('p1')).rejects.toBe(graphqlError); + + expect(client.getQueryData(streakKey)).toEqual(streak); + expect(readStreakViewQueue()).toEqual([]); + }); + + it('should queue the view and keep the streak when the request never reaches the API', async () => { + const requestMethod = jest.fn().mockRejectedValue(networkError); + const { result } = renderViewPost({ client, requestMethod }); + + await expect(result.current('p1')).rejects.toBe(networkError); + + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + }); + expect(readStreakViewQueue()).toEqual([ + expect.objectContaining({ + postId: 'p1', + userId: user.id, + timezone: 'Europe/Amsterdam', + }), + ]); + }); + + it('should not persist the queue from the companion', async () => { + const requestMethod = jest.fn().mockRejectedValue(networkError); + const { result } = renderViewPost({ + client, + requestMethod, + isCompanion: true, + }); + + await expect(result.current('p1')).rejects.toBe(networkError); + + expect(readStreakViewQueue()).toEqual([]); + }); + + it('should only update the streak from the response when the flag is off', async () => { + let resolve: (value: unknown) => void; + const requestMethod = jest.fn( + () => + new Promise((res) => { + resolve = res; + }), + ); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: serverStreak } }, + }); + const { result } = renderViewPost({ client, requestMethod, flag: false }); + + const promise = result.current('p1'); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(client.getQueryData(streakKey)).toEqual(streak); + + await act(async () => { + resolve!({ viewPost: { _: true } }); + await promise; + }); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + }), + ); + }); + + it('should not queue a dropped view when the flag is off', async () => { + const requestMethod = jest.fn().mockRejectedValue(networkError); + const { result } = renderViewPost({ client, requestMethod, flag: false }); + + await expect(result.current('p1')).rejects.toBe(networkError); + + expect(client.getQueryData(streakKey)).toEqual(streak); + expect(readStreakViewQueue()).toEqual([]); + }); +}); diff --git a/packages/shared/src/hooks/post/useViewPost.ts b/packages/shared/src/hooks/post/useViewPost.ts index 1d41cf35701..21dfb560348 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -6,20 +6,41 @@ import { useAuthContext } from '../../contexts/AuthContext'; import type { UserStreak } from '../../graphql/users'; import { isSameDayInTimezone } from '../../lib/timezones'; import { useRequestProtocol } from '../useRequestProtocol'; +import { useConditionalFeature } from '../useConditionalFeature'; +import { featureStreakOptimisticView } from '../../lib/featureManagement'; +import { + enqueueStreakView, + isGraphQLRejection, +} from '../../lib/streakViewQueue'; + +interface ViewPostContext { + previousStreak?: UserStreak; + shouldRefetchStreak: boolean; +} export const useViewPost = (): UseMutateAsyncFunction< unknown, unknown, - string + string, + ViewPostContext > => { const client = useQueryClient(); - const { requestMethod } = useRequestProtocol(); + const { requestMethod, isCompanion } = useRequestProtocol(); const { user } = useAuthContext(); + const { value: isOptimisticView } = useConditionalFeature({ + feature: featureStreakOptimisticView, + shouldEvaluate: !!user, + }); const streakKey = generateQueryKey(RequestKey.UserStreak, user); const readKey = generateQueryKey(RequestKey.ReadingStreak30Days, user); - const { mutateAsync: onSendViewPost } = useMutation({ + const { mutateAsync: onSendViewPost } = useMutation< + unknown, + unknown, + string, + ViewPostContext + >({ mutationFn: (id: string) => requestMethod(VIEW_POST_MUTATION, { id }), - onSuccess: async () => { + onMutate: () => { const streak = client.getQueryData(streakKey); const isNewStreak = !streak?.lastViewAt; const isFirstViewToday = @@ -29,8 +50,25 @@ export const useViewPost = (): UseMutateAsyncFunction< new Date(), user!.timezone, ); + const shouldRefetchStreak = isNewStreak || isFirstViewToday; + + if (!isOptimisticView || !shouldRefetchStreak || !streak) { + return { shouldRefetchStreak }; + } + + const current = streak.current + 1; + client.setQueryData(streakKey, { + ...streak, + current, + total: streak.total + 1, + max: Math.max(streak.max, current), + lastViewAt: new Date(), + }); - if (isNewStreak || isFirstViewToday) { + return { previousStreak: streak, shouldRefetchStreak }; + }, + onSuccess: async (_, __, context) => { + if (context.shouldRefetchStreak) { await client.refetchQueries({ queryKey: streakKey }); // just mark the query as stale @@ -39,6 +77,26 @@ export const useViewPost = (): UseMutateAsyncFunction< return null; }, + onError: (error, id, context) => { + if (!isOptimisticView || isCompanion) { + return; + } + + if (isGraphQLRejection(error)) { + if (context?.previousStreak) { + client.setQueryData(streakKey, context.previousStreak); + } + + return; + } + + enqueueStreakView({ + postId: id, + userId: user!.id, + at: Date.now(), + timezone: user?.timezone, + }); + }, }); return onSendViewPost; diff --git a/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx b/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx new file mode 100644 index 00000000000..542882478b4 --- /dev/null +++ b/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx @@ -0,0 +1,166 @@ +import React from 'react'; +import type { ReactNode } from 'react'; +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClient } from '@tanstack/react-query'; +import { GrowthBook } from '@growthbook/growthbook-react'; +import { TestBootProvider } from '../../../__tests__/helpers/boot'; +import loggedUser from '../../../__tests__/fixture/loggedUser'; +import { VIEW_POST_MUTATION } from '../../graphql/posts'; +import { REQUEST_PROTOCOL_KEY } from '../../graphql/common'; +import type { QueuedStreakView } from '../../lib/streakViewQueue'; +import { + enqueueStreakView, + readStreakViewQueue, +} from '../../lib/streakViewQueue'; +import { useStreakViewQueue } from './useStreakViewQueue'; + +const user = { ...loggedUser, timezone: 'Europe/Amsterdam' }; +const DAY = 24 * 60 * 60 * 1000; + +const queued = ( + postId: string, + overrides: Partial = {}, +): QueuedStreakView => ({ + postId, + userId: user.id, + at: Date.now(), + timezone: user.timezone, + ...overrides, +}); + +const renderQueue = ({ + client, + requestMethod, + flag = true, + isCompanion = false, +}: { + client: QueryClient; + requestMethod: jest.Mock; + flag?: boolean; + isCompanion?: boolean; +}) => { + client.setQueryData(REQUEST_PROTOCOL_KEY, { requestMethod, isCompanion }); + const gb = new GrowthBook({ + features: { streak_optimistic_view: { defaultValue: flag } }, + }); + const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + + ); + + return renderHook(() => useStreakViewQueue(), { wrapper }); +}; + +const goOnline = () => + act(() => { + window.dispatchEvent(new Event('online')); + }); + +describe('useStreakViewQueue', () => { + let client: QueryClient; + + beforeEach(() => { + localStorage.clear(); + client = new QueryClient(); + }); + + it('should replay the queued view once on reconnect and clear it', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + renderQueue({ client, requestMethod }); + expect(requestMethod).not.toHaveBeenCalled(); + + enqueueStreakView(queued('p1')); + goOnline(); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + expect(requestMethod).toHaveBeenCalledTimes(1); + expect(requestMethod).toHaveBeenCalledWith(VIEW_POST_MUTATION, { + id: 'p1', + }); + + goOnline(); + await act(() => Promise.resolve()); + expect(requestMethod).toHaveBeenCalledTimes(1); + }); + + it('should replay the queue on app load', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + expect(requestMethod).toHaveBeenCalledTimes(1); + }); + + it('should drop a view from a previous local day without sending it', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('old', { at: Date.now() - 2 * DAY })); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + expect(requestMethod).toHaveBeenCalledTimes(1); + expect(requestMethod).toHaveBeenCalledWith(VIEW_POST_MUTATION, { + id: 'p1', + }); + }); + + it('should keep the queue when the replay fails on the network', async () => { + const requestMethod = jest + .fn() + .mockRejectedValue(new TypeError('Failed to fetch')); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(readStreakViewQueue()).toHaveLength(1); + }); + + it('should drop a view the API rejects', async () => { + const requestMethod = jest + .fn() + .mockRejectedValue({ response: { errors: [{ message: 'no' }] } }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + }); + + it('should leave views queued by another user alone', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('p1', { userId: 'someone-else' })); + + renderQueue({ client, requestMethod }); + + await act(() => Promise.resolve()); + expect(requestMethod).not.toHaveBeenCalled(); + expect(readStreakViewQueue()).toHaveLength(1); + }); + + it('should do nothing when the flag is off', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod, flag: false }); + goOnline(); + + await act(() => Promise.resolve()); + expect(requestMethod).not.toHaveBeenCalled(); + expect(readStreakViewQueue()).toHaveLength(1); + }); +}); diff --git a/packages/shared/src/hooks/streaks/useStreakViewQueue.ts b/packages/shared/src/hooks/streaks/useStreakViewQueue.ts new file mode 100644 index 00000000000..27a860e639c --- /dev/null +++ b/packages/shared/src/hooks/streaks/useStreakViewQueue.ts @@ -0,0 +1,71 @@ +import { useEffect } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { useAuthContext } from '../../contexts/AuthContext'; +import { useRequestProtocol } from '../useRequestProtocol'; +import { useConditionalFeature } from '../useConditionalFeature'; +import { featureStreakOptimisticView } from '../../lib/featureManagement'; +import { VIEW_POST_MUTATION } from '../../graphql/posts'; +import { generateQueryKey, RequestKey } from '../../lib/query'; +import { drainStreakViewQueue } from '../../lib/streakViewQueue'; + +// Replays post views that a flaky connection dropped (see useViewPost), on +// app load and whenever the browser comes back online. +export const useStreakViewQueue = (): void => { + const client = useQueryClient(); + const { user } = useAuthContext(); + const { requestMethod, isCompanion } = useRequestProtocol(); + const userId = user?.id; + const { value: isEnabled } = useConditionalFeature({ + feature: featureStreakOptimisticView, + shouldEvaluate: !!userId && !isCompanion, + }); + + useEffect(() => { + if (!isEnabled || !userId || isCompanion) { + return undefined; + } + + let isDraining = false; + let shouldDrainAgain = false; + const drain = async () => { + if (isDraining) { + shouldDrainAgain = true; + return; + } + + isDraining = true; + + try { + const sent = await drainStreakViewQueue({ + userId, + sendView: (id) => requestMethod(VIEW_POST_MUTATION, { id }), + }); + + if (sent > 0) { + const streakUser = { id: userId }; + await client.invalidateQueries({ + queryKey: generateQueryKey(RequestKey.UserStreak, streakUser), + }); + await client.invalidateQueries({ + queryKey: generateQueryKey( + RequestKey.ReadingStreak30Days, + streakUser, + ), + }); + } + } finally { + isDraining = false; + + if (shouldDrainAgain) { + shouldDrainAgain = false; + drain(); + } + } + }; + + drain(); + window.addEventListener('online', drain); + + return () => window.removeEventListener('online', drain); + }, [client, isCompanion, isEnabled, requestMethod, userId]); +}; diff --git a/packages/shared/src/lib/featureManagement.ts b/packages/shared/src/lib/featureManagement.ts index bcceed727c7..712cedb5dd3 100644 --- a/packages/shared/src/lib/featureManagement.ts +++ b/packages/shared/src/lib/featureManagement.ts @@ -100,6 +100,13 @@ export const featureStreakFreeze = new Feature('streak_freeze', isDevelopment); export const featureGtaViFreezeDay = new Feature('gta_vi_freeze_day', false); +// count the read on open: optimistic streak bump plus a retry queue for views +// dropped by a flaky connection +export const featureStreakOptimisticView = new Feature( + 'streak_optimistic_view', + false, +); + export const briefCardFeedFeature = new Feature( 'brief_card_feed', isDevelopment, diff --git a/packages/shared/src/lib/storage.ts b/packages/shared/src/lib/storage.ts index 30765a09120..175b8a5d2ba 100644 --- a/packages/shared/src/lib/storage.ts +++ b/packages/shared/src/lib/storage.ts @@ -6,6 +6,7 @@ export enum StorageTopic { Onboarding = 'onboarding', Comment = 'comment', Settings = 'settings', + Streak = 'streak', } export const APP_KEY_PREFIX = 'dailydev'; diff --git a/packages/shared/src/lib/streakViewQueue.spec.ts b/packages/shared/src/lib/streakViewQueue.spec.ts new file mode 100644 index 00000000000..baf88796f58 --- /dev/null +++ b/packages/shared/src/lib/streakViewQueue.spec.ts @@ -0,0 +1,53 @@ +import { isStreakViewCreditable } from './streakViewQueue'; + +const tz = 'Europe/Amsterdam'; +// CET (UTC+1), no DST in January +const at = new Date('2026-01-12T21:30:00+01:00'); + +describe('isStreakViewCreditable', () => { + it('should credit a view from the same local day', () => { + expect( + isStreakViewCreditable(at, new Date('2026-01-12T23:59:00+01:00'), tz), + ).toBe(true); + }); + + it('should credit a view from yesterday within the early-morning grace window', () => { + expect( + isStreakViewCreditable(at, new Date('2026-01-13T00:10:00+01:00'), tz), + ).toBe(true); + expect( + isStreakViewCreditable(at, new Date('2026-01-13T02:59:00+01:00'), tz), + ).toBe(true); + }); + + it('should drop a view from yesterday once the grace window closes', () => { + expect( + isStreakViewCreditable(at, new Date('2026-01-13T03:00:00+01:00'), tz), + ).toBe(false); + }); + + it('should drop a view older than a day even inside the grace window', () => { + expect( + isStreakViewCreditable(at, new Date('2026-01-14T01:00:00+01:00'), tz), + ).toBe(false); + }); + + it('should use the profile timezone for the day boundary', () => { + // 14:30Z is 23:30 in Tokyo; four hours later the grace window has closed + // there while Amsterdam is still on the same day + expect( + isStreakViewCreditable( + new Date('2026-01-13T14:30:00Z'), + new Date('2026-01-13T18:30:00Z'), + 'Asia/Tokyo', + ), + ).toBe(false); + expect( + isStreakViewCreditable( + new Date('2026-01-13T14:30:00Z'), + new Date('2026-01-13T18:30:00Z'), + tz, + ), + ).toBe(true); + }); +}); diff --git a/packages/shared/src/lib/streakViewQueue.ts b/packages/shared/src/lib/streakViewQueue.ts new file mode 100644 index 00000000000..697ee9f3b06 --- /dev/null +++ b/packages/shared/src/lib/streakViewQueue.ts @@ -0,0 +1,150 @@ +import { subHours } from 'date-fns'; +import type { ResponseError } from '../graphql/common'; +import { generateStorageKey, StorageTopic } from './storage'; +import { storageWrapper } from './storageWrapper'; +import { dateFormatInTimezone, isSameDayInTimezone } from './timezones'; + +export interface QueuedStreakView { + postId: string; + userId: string; + at: number; + timezone?: string; +} + +export const STREAK_VIEW_QUEUE_KEY = generateStorageKey( + StorageTopic.Streak, + 'pendingViews', +); + +// Reads in the first hours of the next local day still credit the previous +// streak day on the API, so a queued view stays worth sending that long. +export const STREAK_VIEW_GRACE_HOURS = 3; + +export const readStreakViewQueue = (): QueuedStreakView[] => { + try { + const raw = storageWrapper.getItem(STREAK_VIEW_QUEUE_KEY); + const parsed = raw ? JSON.parse(raw) : []; + + if (!Array.isArray(parsed)) { + return []; + } + + return parsed.filter( + (item): item is QueuedStreakView => + !!item && + typeof item.postId === 'string' && + typeof item.userId === 'string' && + typeof item.at === 'number', + ); + } catch { + return []; + } +}; + +const writeStreakViewQueue = (queue: QueuedStreakView[]): void => { + try { + if (queue.length) { + storageWrapper.setItem(STREAK_VIEW_QUEUE_KEY, JSON.stringify(queue)); + } else { + storageWrapper.removeItem(STREAK_VIEW_QUEUE_KEY); + } + } catch { + // ignore storage quota / privacy-mode failures + } +}; + +const isSameView = (a: QueuedStreakView, b: Pick) => + a.postId === b.postId; + +export const enqueueStreakView = (view: QueuedStreakView): void => { + const queue = readStreakViewQueue(); + + if (queue.some((item) => isSameView(item, view))) { + return; + } + + writeStreakViewQueue([...queue, view]); +}; + +export const removeStreakView = ( + view: Pick, +): void => { + writeStreakViewQueue( + readStreakViewQueue().filter((item) => !isSameView(item, view)), + ); +}; + +export const isGraphQLRejection = (error: unknown): boolean => + Array.isArray((error as Partial)?.response?.errors); + +export const isStreakViewCreditable = ( + at: Date, + now: Date, + timezone?: string, +): boolean => { + if (isSameDayInTimezone(at, now, timezone)) { + return true; + } + + const hour = parseInt(dateFormatInTimezone(now, 'HH', timezone), 10); + + if (Number.isNaN(hour) || hour >= STREAK_VIEW_GRACE_HOURS) { + return false; + } + + // Inside the grace window `now` is within a few hours of local midnight, so + // twelve hours back lands on the previous local day whatever DST does. + return isSameDayInTimezone(at, subHours(now, 12), timezone); +}; + +interface DrainStreakViewQueueProps { + userId: string; + sendView: (postId: string) => Promise; + now?: Date; +} + +const sendQueuedViews = async ( + views: QueuedStreakView[], + sendView: DrainStreakViewQueueProps['sendView'], + now: Date, + sent = 0, +): Promise => { + if (!views.length) { + return sent; + } + + const [view, ...rest] = views; + + if (!isStreakViewCreditable(new Date(view.at), now, view.timezone)) { + removeStreakView(view); + return sendQueuedViews(rest, sendView, now, sent); + } + + try { + await sendView(view.postId); + } catch (error) { + if (isGraphQLRejection(error)) { + removeStreakView(view); + return sendQueuedViews(rest, sendView, now, sent); + } + + // still offline, keep the rest for the next drain + return sent; + } + + removeStreakView(view); + return sendQueuedViews(rest, sendView, now, sent + 1); +}; + +// Replays the views queued for this user, oldest first, and resolves with how +// many the API accepted. +export const drainStreakViewQueue = ({ + userId, + sendView, + now = new Date(), +}: DrainStreakViewQueueProps): Promise => + sendQueuedViews( + readStreakViewQueue().filter((view) => view.userId === userId), + sendView, + now, + ); diff --git a/packages/webapp/pages/_app.tsx b/packages/webapp/pages/_app.tsx index 93b8e6bfe3d..318bea6833f 100644 --- a/packages/webapp/pages/_app.tsx +++ b/packages/webapp/pages/_app.tsx @@ -58,6 +58,7 @@ import { WebKitMessageHandlers, } from '@dailydotdev/shared/src/lib/ios'; import { useCheckLocation } from '@dailydotdev/shared/src/hooks/useCheckLocation'; +import { useStreakViewQueue } from '@dailydotdev/shared/src/hooks/streaks/useStreakViewQueue'; import { useSlackShareReturn } from '@dailydotdev/shared/src/hooks/integrations/slack/useSlackShareButton'; import Seo, { defaultSeo, defaultSeoTitle, robotsProps } from '../next-seo'; import useWebappVersion from '../hooks/useWebappVersion'; @@ -168,6 +169,7 @@ function InternalApp({ Component, pageProps, router }: AppProps): ReactElement { useCheckCoresRole(); useCheckLocation(); + useStreakViewQueue(); useSlackShareReturn(); useEffect(() => { From 7b2d7ca90ce3754d3a24282c47044ba131b9f83b Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Fri, 13 Nov 2026 11:45:04 +0200 Subject: [PATCH 3/8] fix(streak): guard the optimistic streak against stale refetches - useViewPost keeps the optimistic bump when the userStreak refetch still has the pre-view streak (lastViewAt not today in the profile timezone), retries once after STREAK_REFETCH_RETRY_DELAY_MS, and keeps the bump if the retry is stale too. The API credits views in the newView worker, so the first refetch can race it. - Queued views replay only on the local day they were read. viewPost has no read time, so a replay after midnight would credit the replay day. Drops STREAK_VIEW_GRACE_HOURS. - Only NOT_FOUND, FORBIDDEN and UNAUTHENTICATED roll back and drop a view. Other GraphQL errors are queued like network failures. - useStreakViewQueue no longer evaluates streak_optimistic_view, so users are not enrolled on every load. Only flagged users can fill the queue. Co-Authored-By: Claude Opus 5.5 --- .../src/hooks/post/useViewPost.spec.tsx | 112 ++++++++++++++++-- packages/shared/src/hooks/post/useViewPost.ts | 50 ++++++-- .../hooks/streaks/useStreakViewQueue.spec.tsx | 86 ++++++++++++-- .../src/hooks/streaks/useStreakViewQueue.ts | 16 +-- .../shared/src/lib/streakViewQueue.spec.ts | 54 ++++++--- packages/shared/src/lib/streakViewQueue.ts | 53 +++++---- packages/shared/src/lib/userStreak.spec.ts | 46 +++++++ packages/shared/src/lib/userStreak.ts | 14 +++ 8 files changed, 360 insertions(+), 71 deletions(-) create mode 100644 packages/shared/src/lib/userStreak.spec.ts create mode 100644 packages/shared/src/lib/userStreak.ts diff --git a/packages/shared/src/hooks/post/useViewPost.spec.tsx b/packages/shared/src/hooks/post/useViewPost.spec.tsx index cc47be0493f..ce54243fba3 100644 --- a/packages/shared/src/hooks/post/useViewPost.spec.tsx +++ b/packages/shared/src/hooks/post/useViewPost.spec.tsx @@ -14,7 +14,7 @@ import { REQUEST_PROTOCOL_KEY } from '../../graphql/common'; import { generateQueryKey, RequestKey } from '../../lib/query'; import { DayOfWeek } from '../../lib/date'; import { readStreakViewQueue } from '../../lib/streakViewQueue'; -import { useViewPost } from './useViewPost'; +import { STREAK_REFETCH_RETRY_DELAY_MS, useViewPost } from './useViewPost'; const user = { ...loggedUser, timezone: 'Europe/Amsterdam' }; const streakKey = generateQueryKey(RequestKey.UserStreak, user); @@ -37,7 +37,9 @@ const serverStreak: UserStreak = { lastViewAt: new Date(), }; -const graphqlError = { response: { data: null, errors: [{ message: 'no' }] } }; +const graphqlError = (code: string) => ({ + response: { data: null, errors: [{ message: 'no', extensions: { code } }] }, +}); const networkError = new TypeError('Failed to fetch'); const renderViewPost = ({ @@ -129,14 +131,110 @@ describe('useViewPost', () => { expect(readStreakViewQueue()).toEqual([]); }); - it('should roll the streak back when the API rejects the view', async () => { - const requestMethod = jest.fn().mockRejectedValue(graphqlError); + it.each(['NOT_FOUND', 'FORBIDDEN', 'UNAUTHENTICATED'])( + 'should roll the streak back when the API rejects the view with %s', + async (code) => { + const error = graphqlError(code); + const requestMethod = jest.fn().mockRejectedValue(error); + const { result } = renderViewPost({ client, requestMethod }); + + await expect(result.current('p1')).rejects.toBe(error); + + expect(client.getQueryData(streakKey)).toEqual(streak); + expect(readStreakViewQueue()).toEqual([]); + }, + ); + + it('should keep the streak and queue the view on a transient GraphQL error', async () => { + const error = graphqlError('RATE_LIMITED'); + const requestMethod = jest.fn().mockRejectedValue(error); const { result } = renderViewPost({ client, requestMethod }); - await expect(result.current('p1')).rejects.toBe(graphqlError); + await expect(result.current('p1')).rejects.toBe(error); - expect(client.getQueryData(streakKey)).toEqual(streak); - expect(readStreakViewQueue()).toEqual([]); + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + }); + expect(readStreakViewQueue()).toEqual([ + expect.objectContaining({ postId: 'p1', userId: user.id }), + ]); + }); + + describe('when the refetch runs before the API credited the view', () => { + // the newView worker has not written the streak yet, so userStreak still + // returns yesterday's value + const mockPreViewStreak = () => + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: streak } }, + }); + + beforeEach(() => { + jest.useFakeTimers({ advanceTimers: true }); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('should keep the optimistic streak and take the retry once it is up to date', async () => { + mockPreViewStreak(); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: { ...serverStreak, current: 9 } } }, + }); + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + const { result } = renderViewPost({ client, requestMethod }); + + let done = false; + const promise = result.current('p1').then(() => { + done = true; + }); + + await waitFor(() => expect(nock.pendingMocks()).toHaveLength(1)); + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + }); + expect(done).toBe(false); + + await act(async () => { + await jest.advanceTimersByTimeAsync(STREAK_REFETCH_RETRY_DELAY_MS); + await promise; + }); + + expect(nock.isDone()).toBe(true); + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 9, + }); + }); + + it('should keep the optimistic streak when the retry is still stale', async () => { + mockPreViewStreak(); + mockPreViewStreak(); + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + const { result } = renderViewPost({ client, requestMethod }); + + const promise = result.current('p1'); + + await waitFor(() => expect(nock.pendingMocks()).toHaveLength(1)); + await act(async () => { + await jest.advanceTimersByTimeAsync(STREAK_REFETCH_RETRY_DELAY_MS); + await promise; + }); + + expect(nock.isDone()).toBe(true); + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 8, + total: 21, + max: 8, + }); + }); }); it('should queue the view and keep the streak when the request never reaches the API', async () => { diff --git a/packages/shared/src/hooks/post/useViewPost.ts b/packages/shared/src/hooks/post/useViewPost.ts index 21dfb560348..b8c4454b806 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -10,11 +10,22 @@ import { useConditionalFeature } from '../useConditionalFeature'; import { featureStreakOptimisticView } from '../../lib/featureManagement'; import { enqueueStreakView, - isGraphQLRejection, + isFinalViewRejection, } from '../../lib/streakViewQueue'; +import { hasStreakViewToday } from '../../lib/userStreak'; + +// The API credits the view in a worker after the mutation resolves, so the +// first refetch can miss it. Give the worker this long before asking again. +export const STREAK_REFETCH_RETRY_DELAY_MS = 2000; + +const wait = (ms: number) => + new Promise((resolve) => { + setTimeout(resolve, ms); + }); interface ViewPostContext { previousStreak?: UserStreak; + optimisticStreak?: UserStreak; shouldRefetchStreak: boolean; } @@ -57,24 +68,47 @@ export const useViewPost = (): UseMutateAsyncFunction< } const current = streak.current + 1; - client.setQueryData(streakKey, { + const optimisticStreak: UserStreak = { ...streak, current, total: streak.total + 1, max: Math.max(streak.max, current), lastViewAt: new Date(), - }); + }; + client.setQueryData(streakKey, optimisticStreak); - return { previousStreak: streak, shouldRefetchStreak }; + return { previousStreak: streak, optimisticStreak, shouldRefetchStreak }; }, onSuccess: async (_, __, context) => { - if (context.shouldRefetchStreak) { + if (!context.shouldRefetchStreak) { + return null; + } + + const { optimisticStreak } = context; + const refetchStreak = async (): Promise => { await client.refetchQueries({ queryKey: streakKey }); - // just mark the query as stale - await client.invalidateQueries({ queryKey: readKey }); + return hasStreakViewToday( + client.getQueryData(streakKey), + user?.timezone, + ); + }; + const isCounted = await refetchStreak(); + + // A refetch that still has the pre-view streak would undo the + // optimistic bump, so keep the bump and ask once more after a moment. + if (optimisticStreak && !isCounted) { + client.setQueryData(streakKey, optimisticStreak); + await wait(STREAK_REFETCH_RETRY_DELAY_MS); + + if (!(await refetchStreak())) { + client.setQueryData(streakKey, optimisticStreak); + } } + // just mark the query as stale + await client.invalidateQueries({ queryKey: readKey }); + return null; }, onError: (error, id, context) => { @@ -82,7 +116,7 @@ export const useViewPost = (): UseMutateAsyncFunction< return; } - if (isGraphQLRejection(error)) { + if (isFinalViewRejection(error)) { if (context?.previousStreak) { client.setQueryData(streakKey, context.previousStreak); } diff --git a/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx b/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx index 542882478b4..d79faf90e87 100644 --- a/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx +++ b/packages/shared/src/hooks/streaks/useStreakViewQueue.spec.tsx @@ -43,13 +43,18 @@ const renderQueue = ({ const gb = new GrowthBook({ features: { streak_optimistic_view: { defaultValue: flag } }, }); + const getFeatureValue = jest.spyOn(gb, 'getFeatureValue'); const wrapper = ({ children }: { children: ReactNode }) => ( {children} ); - return renderHook(() => useStreakViewQueue(), { wrapper }); + const view = renderHook(() => useStreakViewQueue(), { wrapper }); + const hasEvaluatedFlag = () => + getFeatureValue.mock.calls.some(([id]) => id === 'streak_optimistic_view'); + + return { ...view, hasEvaluatedFlag }; }; const goOnline = () => @@ -126,10 +131,12 @@ describe('useStreakViewQueue', () => { expect(readStreakViewQueue()).toHaveLength(1); }); - it('should drop a view the API rejects', async () => { - const requestMethod = jest - .fn() - .mockRejectedValue({ response: { errors: [{ message: 'no' }] } }); + it('should drop a view the API can never count', async () => { + const requestMethod = jest.fn().mockRejectedValue({ + response: { + errors: [{ message: 'no', extensions: { code: 'NOT_FOUND' } }], + }, + }); enqueueStreakView(queued('p1')); renderQueue({ client, requestMethod }); @@ -137,6 +144,43 @@ describe('useStreakViewQueue', () => { await waitFor(() => expect(readStreakViewQueue()).toEqual([])); }); + it('should keep a view when the API fails with a transient GraphQL error', async () => { + const requestMethod = jest.fn().mockRejectedValue({ + response: { + errors: [ + { message: 'slow down', extensions: { code: 'RATE_LIMITED' } }, + ], + }, + }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod }); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(readStreakViewQueue()).toHaveLength(1); + }); + + it('should drop a view from just before midnight once the local day changed', async () => { + jest.useFakeTimers({ now: new Date('2026-01-13T00:10:00+01:00') }); + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView( + queued('late', { at: new Date('2026-01-12T23:50:00+01:00').getTime() }), + ); + + try { + renderQueue({ client, requestMethod }); + await act(() => Promise.resolve()); + await act(() => Promise.resolve()); + + expect(requestMethod).not.toHaveBeenCalled(); + expect(readStreakViewQueue()).toEqual([]); + } finally { + jest.useRealTimers(); + } + }); + it('should leave views queued by another user alone', async () => { const requestMethod = jest .fn() @@ -150,14 +194,40 @@ describe('useStreakViewQueue', () => { expect(readStreakViewQueue()).toHaveLength(1); }); - it('should do nothing when the flag is off', async () => { + it('should never evaluate the flag for a user with an empty queue', async () => { + const requestMethod = jest.fn(); + const { hasEvaluatedFlag } = renderQueue({ client, requestMethod }); + goOnline(); + + await act(() => Promise.resolve()); + expect(hasEvaluatedFlag()).toBe(false); + expect(requestMethod).not.toHaveBeenCalled(); + }); + + it('should drain queued views without reading the flag', async () => { const requestMethod = jest .fn() .mockResolvedValue({ viewPost: { _: true } }); enqueueStreakView(queued('p1')); - renderQueue({ client, requestMethod, flag: false }); - goOnline(); + const { hasEvaluatedFlag } = renderQueue({ + client, + requestMethod, + flag: false, + }); + + await waitFor(() => expect(readStreakViewQueue()).toEqual([])); + expect(requestMethod).toHaveBeenCalledTimes(1); + expect(hasEvaluatedFlag()).toBe(false); + }); + + it('should not replay from the companion', async () => { + const requestMethod = jest + .fn() + .mockResolvedValue({ viewPost: { _: true } }); + enqueueStreakView(queued('p1')); + + renderQueue({ client, requestMethod, isCompanion: true }); await act(() => Promise.resolve()); expect(requestMethod).not.toHaveBeenCalled(); diff --git a/packages/shared/src/hooks/streaks/useStreakViewQueue.ts b/packages/shared/src/hooks/streaks/useStreakViewQueue.ts index 27a860e639c..185ef9ed0a6 100644 --- a/packages/shared/src/hooks/streaks/useStreakViewQueue.ts +++ b/packages/shared/src/hooks/streaks/useStreakViewQueue.ts @@ -2,26 +2,26 @@ import { useEffect } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { useAuthContext } from '../../contexts/AuthContext'; import { useRequestProtocol } from '../useRequestProtocol'; -import { useConditionalFeature } from '../useConditionalFeature'; -import { featureStreakOptimisticView } from '../../lib/featureManagement'; import { VIEW_POST_MUTATION } from '../../graphql/posts'; import { generateQueryKey, RequestKey } from '../../lib/query'; import { drainStreakViewQueue } from '../../lib/streakViewQueue'; // Replays post views that a flaky connection dropped (see useViewPost), on // app load and whenever the browser comes back online. +// +// It deliberately does not read streak_optimistic_view: this mounts for every +// signed-in user on every load, and evaluating the flag here would enrol +// people who never open a post. Only useViewPost with the flag on fills the +// queue, so draining whatever is queued stays scoped to the treatment arm, and +// a user with an empty queue does no work beyond one storage read. export const useStreakViewQueue = (): void => { const client = useQueryClient(); const { user } = useAuthContext(); const { requestMethod, isCompanion } = useRequestProtocol(); const userId = user?.id; - const { value: isEnabled } = useConditionalFeature({ - feature: featureStreakOptimisticView, - shouldEvaluate: !!userId && !isCompanion, - }); useEffect(() => { - if (!isEnabled || !userId || isCompanion) { + if (!userId || isCompanion) { return undefined; } @@ -67,5 +67,5 @@ export const useStreakViewQueue = (): void => { window.addEventListener('online', drain); return () => window.removeEventListener('online', drain); - }, [client, isCompanion, isEnabled, requestMethod, userId]); + }, [client, isCompanion, requestMethod, userId]); }; diff --git a/packages/shared/src/lib/streakViewQueue.spec.ts b/packages/shared/src/lib/streakViewQueue.spec.ts index baf88796f58..00c0436d8ad 100644 --- a/packages/shared/src/lib/streakViewQueue.spec.ts +++ b/packages/shared/src/lib/streakViewQueue.spec.ts @@ -1,9 +1,19 @@ -import { isStreakViewCreditable } from './streakViewQueue'; +import { + isFinalViewRejection, + isStreakViewCreditable, +} from './streakViewQueue'; const tz = 'Europe/Amsterdam'; // CET (UTC+1), no DST in January const at = new Date('2026-01-12T21:30:00+01:00'); +const graphqlError = (code?: string) => ({ + response: { + data: null, + errors: [{ message: 'no', ...(code && { extensions: { code } }) }], + }, +}); + describe('isStreakViewCreditable', () => { it('should credit a view from the same local day', () => { expect( @@ -11,30 +21,23 @@ describe('isStreakViewCreditable', () => { ).toBe(true); }); - it('should credit a view from yesterday within the early-morning grace window', () => { + it('should drop a view from the previous local day, even just after midnight', () => { + // the API would credit the replay to 00:10, so the read would land on + // the wrong day expect( isStreakViewCreditable(at, new Date('2026-01-13T00:10:00+01:00'), tz), - ).toBe(true); - expect( - isStreakViewCreditable(at, new Date('2026-01-13T02:59:00+01:00'), tz), - ).toBe(true); - }); - - it('should drop a view from yesterday once the grace window closes', () => { - expect( - isStreakViewCreditable(at, new Date('2026-01-13T03:00:00+01:00'), tz), ).toBe(false); }); - it('should drop a view older than a day even inside the grace window', () => { + it('should drop a view older than a day', () => { expect( - isStreakViewCreditable(at, new Date('2026-01-14T01:00:00+01:00'), tz), + isStreakViewCreditable(at, new Date('2026-01-14T12:00:00+01:00'), tz), ).toBe(false); }); it('should use the profile timezone for the day boundary', () => { - // 14:30Z is 23:30 in Tokyo; four hours later the grace window has closed - // there while Amsterdam is still on the same day + // 14:30Z is 23:30 in Tokyo and 15:30 in Amsterdam; at 18:30Z Tokyo is on + // the next day while Amsterdam is still on the same one expect( isStreakViewCreditable( new Date('2026-01-13T14:30:00Z'), @@ -51,3 +54,24 @@ describe('isStreakViewCreditable', () => { ).toBe(true); }); }); + +describe('isFinalViewRejection', () => { + it.each(['NOT_FOUND', 'FORBIDDEN', 'UNAUTHENTICATED'])( + 'should treat %s as final', + (code) => { + expect(isFinalViewRejection(graphqlError(code))).toBe(true); + }, + ); + + it.each(['RATE_LIMITED', 'UNEXPECTED', 'INTERNAL_SERVER_ERROR', undefined])( + 'should not treat a %s GraphQL error as final', + (code) => { + expect(isFinalViewRejection(graphqlError(code))).toBe(false); + }, + ); + + it('should not treat a network failure as final', () => { + expect(isFinalViewRejection(new TypeError('Failed to fetch'))).toBe(false); + expect(isFinalViewRejection(undefined)).toBe(false); + }); +}); diff --git a/packages/shared/src/lib/streakViewQueue.ts b/packages/shared/src/lib/streakViewQueue.ts index 697ee9f3b06..53dac1baad4 100644 --- a/packages/shared/src/lib/streakViewQueue.ts +++ b/packages/shared/src/lib/streakViewQueue.ts @@ -1,8 +1,8 @@ -import { subHours } from 'date-fns'; import type { ResponseError } from '../graphql/common'; +import { ApiError } from '../graphql/common'; import { generateStorageKey, StorageTopic } from './storage'; import { storageWrapper } from './storageWrapper'; -import { dateFormatInTimezone, isSameDayInTimezone } from './timezones'; +import { isSameDayInTimezone } from './timezones'; export interface QueuedStreakView { postId: string; @@ -16,10 +16,6 @@ export const STREAK_VIEW_QUEUE_KEY = generateStorageKey( 'pendingViews', ); -// Reads in the first hours of the next local day still credit the previous -// streak day on the API, so a queued view stays worth sending that long. -export const STREAK_VIEW_GRACE_HOURS = 3; - export const readStreakViewQueue = (): QueuedStreakView[] => { try { const raw = storageWrapper.getItem(STREAK_VIEW_QUEUE_KEY); @@ -74,28 +70,35 @@ export const removeStreakView = ( ); }; -export const isGraphQLRejection = (error: unknown): boolean => - Array.isArray((error as Partial)?.response?.errors); +// Codes that mean the API will never count this view (the post is gone, the +// user cannot see it, or the session is not valid). Anything else, including +// other GraphQL errors such as rate limiting or a failed publish, is treated +// like a dropped connection and the view is kept for a retry. +const FINAL_VIEW_REJECTION_CODES: ReadonlySet = new Set([ + ApiError.NotFound, + ApiError.Forbidden, + ApiError.Unauthenticated, +]); + +export const isFinalViewRejection = (error: unknown): boolean => { + const errors = (error as Partial)?.response?.errors; + + return ( + Array.isArray(errors) && + errors.some((item) => + FINAL_VIEW_REJECTION_CODES.has(item?.extensions?.code as string), + ) + ); +}; +// viewPost takes no read time: the API credits a replayed view to the moment +// it arrives. Only a view from the same local day lands on the day it was +// read, so anything older is dropped instead of sent. export const isStreakViewCreditable = ( at: Date, now: Date, timezone?: string, -): boolean => { - if (isSameDayInTimezone(at, now, timezone)) { - return true; - } - - const hour = parseInt(dateFormatInTimezone(now, 'HH', timezone), 10); - - if (Number.isNaN(hour) || hour >= STREAK_VIEW_GRACE_HOURS) { - return false; - } - - // Inside the grace window `now` is within a few hours of local midnight, so - // twelve hours back lands on the previous local day whatever DST does. - return isSameDayInTimezone(at, subHours(now, 12), timezone); -}; +): boolean => isSameDayInTimezone(at, now, timezone); interface DrainStreakViewQueueProps { userId: string; @@ -123,12 +126,12 @@ const sendQueuedViews = async ( try { await sendView(view.postId); } catch (error) { - if (isGraphQLRejection(error)) { + if (isFinalViewRejection(error)) { removeStreakView(view); return sendQueuedViews(rest, sendView, now, sent); } - // still offline, keep the rest for the next drain + // still offline or a transient API error, keep the rest for the next drain return sent; } diff --git a/packages/shared/src/lib/userStreak.spec.ts b/packages/shared/src/lib/userStreak.spec.ts new file mode 100644 index 00000000000..0e6f1bf086f --- /dev/null +++ b/packages/shared/src/lib/userStreak.spec.ts @@ -0,0 +1,46 @@ +import { hasStreakViewToday } from './userStreak'; + +const tz = 'Europe/Amsterdam'; +// CET (UTC+1), no DST in January +const now = new Date('2026-01-13T00:30:00+01:00'); + +describe('hasStreakViewToday', () => { + it('should be true when lastViewAt is today in the profile timezone', () => { + expect( + hasStreakViewToday( + { lastViewAt: new Date('2026-01-13T00:05:00+01:00') }, + tz, + now, + ), + ).toBe(true); + }); + + it('should be false when lastViewAt is the previous local day', () => { + expect( + hasStreakViewToday( + { lastViewAt: new Date('2026-01-12T23:50:00+01:00') }, + tz, + now, + ), + ).toBe(false); + }); + + it('should accept a serialized lastViewAt', () => { + expect( + hasStreakViewToday( + { + lastViewAt: '2026-01-12T23:10:00.000Z' as unknown as Date, + }, + tz, + now, + ), + ).toBe(true); + }); + + it('should be false without a streak or lastViewAt', () => { + expect(hasStreakViewToday(undefined, tz, now)).toBe(false); + expect( + hasStreakViewToday({ lastViewAt: undefined as unknown as Date }, tz, now), + ).toBe(false); + }); +}); diff --git a/packages/shared/src/lib/userStreak.ts b/packages/shared/src/lib/userStreak.ts new file mode 100644 index 00000000000..278ca6d0057 --- /dev/null +++ b/packages/shared/src/lib/userStreak.ts @@ -0,0 +1,14 @@ +import type { UserStreak } from '../graphql/users'; +import { isSameDayInTimezone } from './timezones'; + +// The API credits a view asynchronously (viewPost only publishes it, and the +// newView worker writes the streak), so a userStreak read right after the +// mutation can still be the pre-view streak. It includes today's read only +// once its lastViewAt falls on today in the profile timezone. +export const hasStreakViewToday = ( + streak: Pick | undefined | null, + timezone?: string, + now: Date = new Date(), +): boolean => + !!streak?.lastViewAt && + isSameDayInTimezone(new Date(streak.lastViewAt), now, timezone); From d877abf7ec3be6fb6fa117b7a85a9681cbddb329 Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Fri, 13 Nov 2026 12:08:13 +0200 Subject: [PATCH 4/8] fix(streak): read the final rejection codes when called, not at module load graphql/common is in an import cycle with streakViewQueue, so ApiError could still be undefined when the module loaded and the module-level Set threw. It broke any spec that happened to load this file first (PlusFeedBanner.spec in CI). Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/lib/streakViewQueue.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/shared/src/lib/streakViewQueue.ts b/packages/shared/src/lib/streakViewQueue.ts index 53dac1baad4..f720f51e295 100644 --- a/packages/shared/src/lib/streakViewQueue.ts +++ b/packages/shared/src/lib/streakViewQueue.ts @@ -74,20 +74,21 @@ export const removeStreakView = ( // user cannot see it, or the session is not valid). Anything else, including // other GraphQL errors such as rate limiting or a failed publish, is treated // like a dropped connection and the view is kept for a retry. -const FINAL_VIEW_REJECTION_CODES: ReadonlySet = new Set([ +// Read when called, not at module load: graphql/common sits in an import +// cycle with this file, so ApiError can still be undefined at load time. +const getFinalViewRejectionCodes = (): string[] => [ ApiError.NotFound, ApiError.Forbidden, ApiError.Unauthenticated, -]); +]; export const isFinalViewRejection = (error: unknown): boolean => { const errors = (error as Partial)?.response?.errors; + const finalCodes = getFinalViewRejectionCodes(); return ( Array.isArray(errors) && - errors.some((item) => - FINAL_VIEW_REJECTION_CODES.has(item?.extensions?.code as string), - ) + errors.some((item) => finalCodes.includes(item?.extensions?.code as string)) ); }; From baf24515fc0f0d691e3abf40e4e60473948e89e1 Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Fri, 13 Nov 2026 12:25:42 +0200 Subject: [PATCH 5/8] fix(streak): accept a refetch whose count already includes this read With the API's grace window, a read before 03:00 after a missed day is credited to yesterday, so lastViewAt never falls on today and the refetch guard kept the optimistic entry. Later reads that day then skipped the refetch and the tile stayed a day behind. A refetch whose current already equals the optimistic count now counts as including the read. Co-Authored-By: Claude Opus 5.5 --- packages/shared/src/hooks/post/useViewPost.ts | 5 +-- packages/shared/src/lib/userStreak.spec.ts | 32 ++++++++++++++++++- packages/shared/src/lib/userStreak.ts | 13 ++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/hooks/post/useViewPost.ts b/packages/shared/src/hooks/post/useViewPost.ts index b8c4454b806..1ef41edb1eb 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -12,7 +12,7 @@ import { enqueueStreakView, isFinalViewRejection, } from '../../lib/streakViewQueue'; -import { hasStreakViewToday } from '../../lib/userStreak'; +import { includesThisRead } from '../../lib/userStreak'; // The API credits the view in a worker after the mutation resolves, so the // first refetch can miss it. Give the worker this long before asking again. @@ -88,9 +88,10 @@ export const useViewPost = (): UseMutateAsyncFunction< const refetchStreak = async (): Promise => { await client.refetchQueries({ queryKey: streakKey }); - return hasStreakViewToday( + return includesThisRead( client.getQueryData(streakKey), user?.timezone, + optimisticStreak?.current, ); }; const isCounted = await refetchStreak(); diff --git a/packages/shared/src/lib/userStreak.spec.ts b/packages/shared/src/lib/userStreak.spec.ts index 0e6f1bf086f..b5f29077ded 100644 --- a/packages/shared/src/lib/userStreak.spec.ts +++ b/packages/shared/src/lib/userStreak.spec.ts @@ -1,4 +1,4 @@ -import { hasStreakViewToday } from './userStreak'; +import { hasStreakViewToday, includesThisRead } from './userStreak'; const tz = 'Europe/Amsterdam'; // CET (UTC+1), no DST in January @@ -44,3 +44,33 @@ describe('hasStreakViewToday', () => { ).toBe(false); }); }); + +describe('includesThisRead', () => { + // A 00:30 read the API's grace window credited to yesterday + const credited = { + lastViewAt: new Date('2026-01-12T23:59:59.999+01:00'), + current: 6, + }; + + it('should accept a grace-credited read whose count matches the expected one', () => { + expect(includesThisRead(credited, tz, 6, now)).toBe(true); + }); + + it('should reject the pre-view streak', () => { + expect(includesThisRead({ ...credited, current: 5 }, tz, 6, now)).toBe( + false, + ); + }); + + it('should fall back to the lastViewAt check without an expected count', () => { + expect(includesThisRead(credited, tz, undefined, now)).toBe(false); + expect( + includesThisRead( + { lastViewAt: new Date('2026-01-13T00:05:00+01:00'), current: 6 }, + tz, + undefined, + now, + ), + ).toBe(true); + }); +}); diff --git a/packages/shared/src/lib/userStreak.ts b/packages/shared/src/lib/userStreak.ts index 278ca6d0057..5a3009d690b 100644 --- a/packages/shared/src/lib/userStreak.ts +++ b/packages/shared/src/lib/userStreak.ts @@ -12,3 +12,16 @@ export const hasStreakViewToday = ( ): boolean => !!streak?.lastViewAt && isSameDayInTimezone(new Date(streak.lastViewAt), now, timezone); + +// Whether a refetched streak already includes the read we just sent. Besides +// a lastViewAt today, a count that already matches the one we expect counts +// too: when the API's grace window credits an early-morning read to +// yesterday, lastViewAt lands on yesterday and never looks like today. +export const includesThisRead = ( + streak: Pick | undefined | null, + timezone?: string, + expectedCurrent?: number, + now: Date = new Date(), +): boolean => + hasStreakViewToday(streak, timezone, now) || + (expectedCurrent !== undefined && streak?.current === expectedCurrent); From f76ef8daf1b59e2478a73a1494605731c0cd0fa5 Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Fri, 13 Nov 2026 14:06:00 +0200 Subject: [PATCH 6/8] feat(streak): toast the day's streak on the first counted read (#7374) Co-authored-by: Claude Fable 5.1 --- .../src/hooks/post/useViewPost.spec.tsx | 300 +++++++++++++++++- packages/shared/src/hooks/post/useViewPost.ts | 38 ++- .../streaks/useStreakDailyCelebration.tsx | 84 +++++ packages/shared/src/lib/featureManagement.ts | 6 + packages/shared/src/lib/log.ts | 1 + .../shared/src/lib/streakDailyCelebration.ts | 51 +++ packages/shared/tailwind.config.ts | 10 + 7 files changed, 475 insertions(+), 15 deletions(-) create mode 100644 packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx create mode 100644 packages/shared/src/lib/streakDailyCelebration.ts diff --git a/packages/shared/src/hooks/post/useViewPost.spec.tsx b/packages/shared/src/hooks/post/useViewPost.spec.tsx index ce54243fba3..79f789d5824 100644 --- a/packages/shared/src/hooks/post/useViewPost.spec.tsx +++ b/packages/shared/src/hooks/post/useViewPost.spec.tsx @@ -1,6 +1,12 @@ import React from 'react'; -import type { ReactNode } from 'react'; -import { act, renderHook, waitFor } from '@testing-library/react'; +import type { ComponentProps, ReactNode } from 'react'; +import { + act, + render, + renderHook, + screen, + waitFor, +} from '@testing-library/react'; import { QueryClient, useQuery } from '@tanstack/react-query'; import { GrowthBook } from '@growthbook/growthbook-react'; import nock from 'nock'; @@ -13,7 +19,12 @@ import { VIEW_POST_MUTATION } from '../../graphql/posts'; import { REQUEST_PROTOCOL_KEY } from '../../graphql/common'; import { generateQueryKey, RequestKey } from '../../lib/query'; import { DayOfWeek } from '../../lib/date'; +import { dateFormatInTimezone } from '../../lib/timezones'; import { readStreakViewQueue } from '../../lib/streakViewQueue'; +import { getStreakCelebratedKey } from '../../lib/streakDailyCelebration'; +import type { ToastNotification } from '../useToastNotification'; +import { TOAST_NOTIF_KEY } from '../useToastNotification'; +import { LogEvent, TargetType } from '../../lib/log'; import { STREAK_REFETCH_RETRY_DELAY_MS, useViewPost } from './useViewPost'; const user = { ...loggedUser, timezone: 'Europe/Amsterdam' }; @@ -46,30 +57,51 @@ const renderViewPost = ({ client, requestMethod, flag = true, + celebrationFlag = false, isCompanion = false, + initialStreak = streak, + alerts, + log, + settings, }: { client: QueryClient; requestMethod: jest.Mock; flag?: boolean; + celebrationFlag?: boolean; isCompanion?: boolean; + initialStreak?: UserStreak; + alerts?: ComponentProps['alerts']; + log?: ComponentProps['log']; + settings?: ComponentProps['settings']; }) => { client.setQueryData(REQUEST_PROTOCOL_KEY, { requestMethod, isCompanion }); const gb = new GrowthBook({ - features: { streak_optimistic_view: { defaultValue: flag } }, + features: { + streak_optimistic_view: { defaultValue: flag }, + streak_daily_celebration: { defaultValue: celebrationFlag }, + }, }); + const getFeatureValue = jest.spyOn(gb, 'getFeatureValue'); const wrapper = ({ children }: { children: ReactNode }) => ( - + {children} ); - return renderHook( + const view = renderHook( () => { // the streak query the post page shell already has in cache useQuery({ queryKey: streakKey, queryFn: getReadingStreak, - initialData: streak, + initialData: initialStreak, staleTime: Infinity, }); @@ -77,6 +109,8 @@ const renderViewPost = ({ }, { wrapper }, ); + + return { ...view, getFeatureValue }; }; describe('useViewPost', () => { @@ -310,4 +344,258 @@ describe('useViewPost', () => { expect(client.getQueryData(streakKey)).toEqual(streak); expect(readStreakViewQueue()).toEqual([]); }); + + describe('daily celebration toast', () => { + // 5 -> 6: not a milestone (the API raises the milestone modal on + // Fibonacci days), so the daily toast is the one that celebrates it + const dayFive: UserStreak = { ...streak, current: 5, max: 5 }; + const daySix: UserStreak = { + ...dayFive, + current: 6, + max: 6, + total: 21, + lastViewAt: new Date(), + }; + const requestMethod = () => + jest.fn().mockResolvedValue({ viewPost: { _: true } }); + const getToast = () => + client.getQueryData(TOAST_NOTIF_KEY); + + it('should toast once on the first counted read of the day', async () => { + const logEvent = jest.fn(); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + initialStreak: dayFive, + log: { logEvent }, + }); + + await act(async () => { + await result.current('p1'); + }); + + render(<>{getToast()?.message}); + expect(screen.getByText('Day 6! See you tomorrow.')).toBeInTheDocument(); + expect(logEvent).toHaveBeenCalledTimes(1); + expect(logEvent).toHaveBeenCalledWith({ + event_name: LogEvent.Impression, + target_type: TargetType.StreakDailyCelebration, + target_id: 6, + }); + expect(localStorage.getItem(getStreakCelebratedKey(user.id))).toBe( + dateFormatInTimezone(new Date(), 'yyyy-MM-dd', user.timezone), + ); + + // a second first-view the same day (replay, second tab) stays quiet + client.setQueryData(TOAST_NOTIF_KEY, null); + client.setQueryData(streakKey, dayFive); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + + await act(async () => { + await result.current('p2'); + }); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 6, + }), + ); + expect(getToast()).toBeNull(); + expect(logEvent).toHaveBeenCalledTimes(1); + }); + + it('should not toast when the milestone modal is due', async () => { + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + initialStreak: dayFive, + alerts: { alerts: { showStreakMilestone: true } }, + }); + + await act(async () => { + await result.current('p1'); + }); + + expect(getToast()).toBeFalsy(); + expect(localStorage.getItem(getStreakCelebratedKey(user.id))).toBeNull(); + }); + + it('should leave milestone days to the milestone modal', async () => { + // 7 -> 8 is a Fibonacci day: the API flags showStreakMilestone for it + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: serverStreak } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + }); + + await act(async () => { + await result.current('p1'); + }); + + expect(getToast()).toBeFalsy(); + }); + + describe('when the refetch still has the pre-view streak', () => { + // the newView worker has not credited the read yet, so userStreak + // returns yesterday's 7 although this read makes it 8 + const mockPreViewStreak = () => + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: streak } }, + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('should not toast the stale count on a milestone day', async () => { + mockPreViewStreak(); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + flag: false, + celebrationFlag: true, + }); + + await act(async () => { + await result.current('p1'); + }); + + // 8 is a milestone, so the toast stays quiet instead of "Day 7!" + expect(nock.isDone()).toBe(true); + expect(getToast()).toBeFalsy(); + expect( + localStorage.getItem(getStreakCelebratedKey(user.id)), + ).toBeNull(); + }); + + it('should not toast the stale count after the retry is stale too', async () => { + jest.useFakeTimers({ advanceTimers: true }); + mockPreViewStreak(); + mockPreViewStreak(); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + }); + + const promise = result.current('p1'); + await waitFor(() => expect(nock.pendingMocks()).toHaveLength(1)); + await act(async () => { + await jest.advanceTimersByTimeAsync(STREAK_REFETCH_RETRY_DELAY_MS); + await promise; + }); + + expect(nock.isDone()).toBe(true); + expect(getToast()).toBeFalsy(); + }); + + it('should toast the count this read lands on', async () => { + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: dayFive } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + flag: false, + celebrationFlag: true, + initialStreak: dayFive, + }); + + await act(async () => { + await result.current('p1'); + }); + + render(<>{getToast()?.message}); + expect( + screen.getByText('Day 6! See you tomorrow.'), + ).toBeInTheDocument(); + }); + }); + + it('should not evaluate the flag for users who opted out of streaks', async () => { + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + const { result, getFeatureValue } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + initialStreak: dayFive, + settings: { optOutReadingStreak: true }, + }); + + await act(async () => { + await result.current('p1'); + }); + + expect(getToast()).toBeFalsy(); + expect( + getFeatureValue.mock.calls.some( + ([id]) => id === 'streak_daily_celebration', + ), + ).toBe(false); + }); + + it('should not evaluate the flag while settings are loading', async () => { + const { getFeatureValue } = renderViewPost({ + client, + requestMethod: requestMethod(), + celebrationFlag: true, + settings: { loadedSettings: false }, + }); + + await act(() => Promise.resolve()); + expect( + getFeatureValue.mock.calls.some( + ([id]) => id === 'streak_daily_celebration', + ), + ).toBe(false); + }); + + it('should not toast when the flag is off', async () => { + const logEvent = jest.fn(); + mockGraphQL({ + request: { query: USER_STREAK_QUERY }, + result: { data: { userStreak: daySix } }, + }); + const { result } = renderViewPost({ + client, + requestMethod: requestMethod(), + initialStreak: dayFive, + log: { logEvent }, + }); + + await act(async () => { + await result.current('p1'); + }); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 6, + }), + ); + expect(getToast()).toBeFalsy(); + expect(logEvent).not.toHaveBeenCalled(); + }); + }); }); diff --git a/packages/shared/src/hooks/post/useViewPost.ts b/packages/shared/src/hooks/post/useViewPost.ts index 1ef41edb1eb..5b13178ab8a 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -13,6 +13,7 @@ import { isFinalViewRejection, } from '../../lib/streakViewQueue'; import { includesThisRead } from '../../lib/userStreak'; +import { useStreakDailyCelebration } from '../streaks/useStreakDailyCelebration'; // The API credits the view in a worker after the mutation resolves, so the // first refetch can miss it. Give the worker this long before asking again. @@ -27,6 +28,9 @@ interface ViewPostContext { previousStreak?: UserStreak; optimisticStreak?: UserStreak; shouldRefetchStreak: boolean; + // the count this view should land on, used when the refetch fails or + // has not caught up with the view yet + nextStreak?: number; } export const useViewPost = (): UseMutateAsyncFunction< @@ -42,6 +46,7 @@ export const useViewPost = (): UseMutateAsyncFunction< feature: featureStreakOptimisticView, shouldEvaluate: !!user, }); + const celebrateStreakDay = useStreakDailyCelebration(); const streakKey = generateQueryKey(RequestKey.UserStreak, user); const readKey = generateQueryKey(RequestKey.ReadingStreak30Days, user); const { mutateAsync: onSendViewPost } = useMutation< @@ -62,9 +67,10 @@ export const useViewPost = (): UseMutateAsyncFunction< user!.timezone, ); const shouldRefetchStreak = isNewStreak || isFirstViewToday; + const nextStreak = streak ? streak.current + 1 : undefined; if (!isOptimisticView || !shouldRefetchStreak || !streak) { - return { shouldRefetchStreak }; + return { shouldRefetchStreak, nextStreak }; } const current = streak.current + 1; @@ -77,7 +83,12 @@ export const useViewPost = (): UseMutateAsyncFunction< }; client.setQueryData(streakKey, optimisticStreak); - return { previousStreak: streak, optimisticStreak, shouldRefetchStreak }; + return { + previousStreak: streak, + optimisticStreak, + shouldRefetchStreak, + nextStreak, + }; }, onSuccess: async (_, __, context) => { if (!context.shouldRefetchStreak) { @@ -85,24 +96,31 @@ export const useViewPost = (): UseMutateAsyncFunction< } const { optimisticStreak } = context; - const refetchStreak = async (): Promise => { + // Resolves with the refetched streak only when it already counts this + // view: the API credits it in a worker, so it can still be the + // pre-view streak. + const refetchStreak = async (): Promise => { await client.refetchQueries({ queryKey: streakKey }); + const refetched = client.getQueryData(streakKey); return includesThisRead( - client.getQueryData(streakKey), + refetched, user?.timezone, - optimisticStreak?.current, - ); + optimisticStreak?.current ?? context.nextStreak, + ) + ? refetched + : undefined; }; - const isCounted = await refetchStreak(); + let countedStreak = await refetchStreak(); // A refetch that still has the pre-view streak would undo the // optimistic bump, so keep the bump and ask once more after a moment. - if (optimisticStreak && !isCounted) { + if (optimisticStreak && !countedStreak) { client.setQueryData(streakKey, optimisticStreak); await wait(STREAK_REFETCH_RETRY_DELAY_MS); + countedStreak = await refetchStreak(); - if (!(await refetchStreak())) { + if (!countedStreak) { client.setQueryData(streakKey, optimisticStreak); } } @@ -110,6 +128,8 @@ export const useViewPost = (): UseMutateAsyncFunction< // just mark the query as stale await client.invalidateQueries({ queryKey: readKey }); + celebrateStreakDay(countedStreak?.current ?? context.nextStreak); + return null; }, onError: (error, id, context) => { diff --git a/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx b/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx new file mode 100644 index 00000000000..6f335f411a4 --- /dev/null +++ b/packages/shared/src/hooks/streaks/useStreakDailyCelebration.tsx @@ -0,0 +1,84 @@ +import React, { useCallback, useContext } from 'react'; +import { useAuthContext } from '../../contexts/AuthContext'; +import { useAlertsContext } from '../../contexts/AlertContext'; +import SettingsContext from '../../contexts/SettingsContext'; +import { useLogContext } from '../../contexts/LogContext'; +import { useToastNotification } from '../useToastNotification'; +import { useRequestProtocol } from '../useRequestProtocol'; +import { useConditionalFeature } from '../useConditionalFeature'; +import { featureStreakDailyCelebration } from '../../lib/featureManagement'; +import { LogEvent, TargetType } from '../../lib/log'; +import { + hasCelebratedStreakToday, + isStreakMilestone, + markStreakCelebrated, +} from '../../lib/streakDailyCelebration'; +import { ReadingStreakIcon } from '../../components/icons/ReadingStreak'; +import { IconSize } from '../../components/Icon'; + +export const getStreakDailyCelebrationCopy = (current: number): string => + `Day ${current}! See you tomorrow.`; + +// Toasts "Day n! See you tomorrow." once per local day, after the first read +// that extended the streak. Milestone days leave the stage to the milestone +// modal, and the companion never shows it: it has no streak in its cache, so +// every read there looks like the first of the day. +export const useStreakDailyCelebration = (): ((current?: number) => void) => { + const { user } = useAuthContext(); + const { isCompanion } = useRequestProtocol(); + const { alerts } = useAlertsContext(); + const { optOutReadingStreak, loadedSettings } = useContext(SettingsContext); + const { displayToast } = useToastNotification(); + const { logEvent } = useLogContext(); + const isStreaksEnabled = loadedSettings && !optOutReadingStreak; + // Users who opted out of streaks (or whose settings are still loading) can + // never see the toast, so keep them out of the experiment. + const { value: isEnabled } = useConditionalFeature({ + feature: featureStreakDailyCelebration, + shouldEvaluate: !!user && !isCompanion && isStreaksEnabled, + }); + const showStreakMilestone = alerts?.showStreakMilestone; + + return useCallback( + (current?: number) => { + if ( + !isEnabled || + isCompanion || + !user || + !isStreaksEnabled || + !current || + showStreakMilestone || + isStreakMilestone(current) || + hasCelebratedStreakToday(user.id, user.timezone) + ) { + return; + } + + markStreakCelebrated(user.id, user.timezone); + displayToast( + + + {getStreakDailyCelebrationCopy(current)} + , + ); + logEvent({ + event_name: LogEvent.Impression, + target_type: TargetType.StreakDailyCelebration, + target_id: current, + }); + }, + [ + displayToast, + isCompanion, + isEnabled, + isStreaksEnabled, + logEvent, + showStreakMilestone, + user, + ], + ); +}; diff --git a/packages/shared/src/lib/featureManagement.ts b/packages/shared/src/lib/featureManagement.ts index 796bf777eac..eba39e95a8a 100644 --- a/packages/shared/src/lib/featureManagement.ts +++ b/packages/shared/src/lib/featureManagement.ts @@ -109,6 +109,12 @@ export const featureStreakOptimisticView = new Feature( false, ); +// daily "streak extended" toast on the first counted read of a local day +export const featureStreakDailyCelebration = new Feature( + 'streak_daily_celebration', + false, +); + export const briefCardFeedFeature = new Feature( 'brief_card_feed', isDevelopment, diff --git a/packages/shared/src/lib/log.ts b/packages/shared/src/lib/log.ts index 98e62cc235e..1e6af795554 100644 --- a/packages/shared/src/lib/log.ts +++ b/packages/shared/src/lib/log.ts @@ -785,6 +785,7 @@ export enum TargetType { StreaksMilestone = 'streaks milestone', StreakRecover = 'streak restore', StreakFreezePurchase = 'streak freeze purchase', + StreakDailyCelebration = 'streak daily celebration', PromotionCard = 'promotion_card', PromotionalBanner = 'promotion_banner', MarketingCtaPopover = 'promotion_popover', diff --git a/packages/shared/src/lib/streakDailyCelebration.ts b/packages/shared/src/lib/streakDailyCelebration.ts new file mode 100644 index 00000000000..13384e8b562 --- /dev/null +++ b/packages/shared/src/lib/streakDailyCelebration.ts @@ -0,0 +1,51 @@ +import { generateStorageKey, StorageTopic } from './storage'; +import { storageWrapper } from './storageWrapper'; +import { dateFormatInTimezone } from './timezones'; + +const STREAK_DAY_FORMAT = 'yyyy-MM-dd'; + +export const getStreakCelebratedKey = (userId: string): string => + generateStorageKey(StorageTopic.Streak, 'celebrated', userId); + +const isPerfectSquare = (num: number): boolean => { + const root = Math.floor(Math.sqrt(num)); + return root * root === num; +}; + +const isFibonacci = (num: number): boolean => { + const square = 5 * num * num; + return isPerfectSquare(square + 4) || isPerfectSquare(square - 4); +}; + +// Mirrors the API's milestone rule (workers/newView.ts), which raises +// alerts.showStreakMilestone for the milestone modal on these days. +export const isStreakMilestone = (current: number): boolean => + current > 1 && isFibonacci(current); + +export const hasCelebratedStreakToday = ( + userId: string, + timezone?: string, +): boolean => { + try { + return ( + storageWrapper.getItem(getStreakCelebratedKey(userId)) === + dateFormatInTimezone(new Date(), STREAK_DAY_FORMAT, timezone) + ); + } catch { + return false; + } +}; + +export const markStreakCelebrated = ( + userId: string, + timezone?: string, +): void => { + try { + storageWrapper.setItem( + getStreakCelebratedKey(userId), + dateFormatInTimezone(new Date(), STREAK_DAY_FORMAT, timezone), + ); + } catch { + // ignore storage quota / privacy-mode failures + } +}; diff --git a/packages/shared/tailwind.config.ts b/packages/shared/tailwind.config.ts index c6e4ec986b1..a313969c36f 100644 --- a/packages/shared/tailwind.config.ts +++ b/packages/shared/tailwind.config.ts @@ -375,6 +375,14 @@ export default { 'color-mix(in srgb, var(--theme-accent-bacon-default) 28%, transparent)', }, }, + // Daily streak toast: the flame pops in with the same strike + rebound + // as the rail tile's earn pop, then rests at its normal size. + 'streak-toast-pop': { + '0%': { transform: 'scale(0.6)', opacity: '0' }, + '45%': { transform: 'scale(1.3)', opacity: '1' }, + '70%': { transform: 'scale(0.95)' }, + '100%': { transform: 'scale(1)' }, + }, // The search palette: the scrim and panel fade in, and the list fades // in again every time its scope changes (it is keyed on the scope). // Opacity only: a transform left by `both` would make the scrolling @@ -420,6 +428,8 @@ export default { 'streak-border-pulse': 'streak-border-pulse 2.2s ease-in-out infinite', 'streak-earn-border': 'streak-earn-border 0.6s ease-out both', 'streak-earn-fill': 'streak-earn-fill 0.6s ease-out both', + 'streak-toast-pop': + 'streak-toast-pop 0.6s cubic-bezier(0.34, 1.56, 0.64, 1) both', 'mascot-bob': 'mascot-bob 4s ease-in-out infinite', }, }, From 6bc162a302483bdf9005548b7e7bf3be3c0c26dc Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Fri, 13 Nov 2026 14:08:31 +0200 Subject: [PATCH 7/8] fix(streak): skip the optimistic bump in the companion and after a gap, queue only counting reads Co-Authored-By: Claude Opus 5.5 --- .../src/hooks/post/useViewPost.spec.tsx | 71 ++++++++++++++++++- packages/shared/src/hooks/post/useViewPost.ts | 32 ++++++++- 2 files changed, 99 insertions(+), 4 deletions(-) diff --git a/packages/shared/src/hooks/post/useViewPost.spec.tsx b/packages/shared/src/hooks/post/useViewPost.spec.tsx index ce54243fba3..4fd43bf7df5 100644 --- a/packages/shared/src/hooks/post/useViewPost.spec.tsx +++ b/packages/shared/src/hooks/post/useViewPost.spec.tsx @@ -4,6 +4,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'; import { QueryClient, useQuery } from '@tanstack/react-query'; import { GrowthBook } from '@growthbook/growthbook-react'; import nock from 'nock'; +import { subDays } from 'date-fns'; import { TestBootProvider } from '../../../__tests__/helpers/boot'; import { mockGraphQL } from '../../../__tests__/helpers/graphql'; import loggedUser from '../../../__tests__/fixture/loggedUser'; @@ -47,11 +48,13 @@ const renderViewPost = ({ requestMethod, flag = true, isCompanion = false, + initialStreak = streak, }: { client: QueryClient; requestMethod: jest.Mock; flag?: boolean; isCompanion?: boolean; + initialStreak?: UserStreak; }) => { client.setQueryData(REQUEST_PROTOCOL_KEY, { requestMethod, isCompanion }); const gb = new GrowthBook({ @@ -69,7 +72,7 @@ const renderViewPost = ({ useQuery({ queryKey: streakKey, queryFn: getReadingStreak, - initialData: streak, + initialData: initialStreak, staleTime: Infinity, }); @@ -310,4 +313,70 @@ describe('useViewPost', () => { expect(client.getQueryData(streakKey)).toEqual(streak); expect(readStreakViewQueue()).toEqual([]); }); + + it('should not bump the streak from the companion', async () => { + const requestMethod = jest.fn(() => new Promise(() => {})); + const { result } = renderViewPost({ + client, + requestMethod, + isCompanion: true, + }); + + result.current('p1'); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(client.getQueryData(streakKey)).toEqual(streak); + }); + + it('should not bump a streak last read before yesterday', async () => { + const lastRead = { ...streak, lastViewAt: subDays(new Date(), 3) }; + const requestMethod = jest.fn(() => new Promise(() => {})); + const { result } = renderViewPost({ + client, + requestMethod, + initialStreak: lastRead, + }); + + result.current('p1'); + + await waitFor(() => expect(requestMethod).toHaveBeenCalledTimes(1)); + expect(client.getQueryData(streakKey)).toEqual(lastRead); + }); + + it('should bump a reset streak to one', async () => { + const reset = { + ...streak, + current: 0, + lastViewAt: subDays(new Date(), 3), + }; + const requestMethod = jest.fn(() => new Promise(() => {})); + const { result } = renderViewPost({ + client, + requestMethod, + initialStreak: reset, + }); + + result.current('p1'); + + await waitFor(() => + expect(client.getQueryData(streakKey)).toMatchObject({ + current: 1, + total: 21, + max: 7, + }), + ); + }); + + it('should not queue a dropped view when today is already counted', async () => { + const requestMethod = jest.fn().mockRejectedValue(networkError); + const { result } = renderViewPost({ + client, + requestMethod, + initialStreak: serverStreak, + }); + + await expect(result.current('p1')).rejects.toBe(networkError); + + expect(readStreakViewQueue()).toEqual([]); + }); }); diff --git a/packages/shared/src/hooks/post/useViewPost.ts b/packages/shared/src/hooks/post/useViewPost.ts index 1ef41edb1eb..6a0395edc98 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -1,5 +1,6 @@ import type { UseMutateAsyncFunction } from '@tanstack/react-query'; import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { subDays } from 'date-fns'; import { VIEW_POST_MUTATION } from '../../graphql/posts'; import { generateQueryKey, RequestKey } from '../../lib/query'; import { useAuthContext } from '../../contexts/AuthContext'; @@ -18,6 +19,18 @@ import { includesThisRead } from '../../lib/userStreak'; // first refetch can miss it. Give the worker this long before asking again. export const STREAK_REFETCH_RETRY_DELAY_MS = 2000; +// Only bump when today's read surely extends the streak: a new or reset +// streak, or one last read yesterday. After a longer gap (weekend off days, +// freezes, a reset the cache has not seen yet) the API decides, so wait for it. +const canBumpStreak = ( + streak: UserStreak, + timezone?: string, + now: Date = new Date(), +): boolean => + !streak.lastViewAt || + streak.current === 0 || + isSameDayInTimezone(new Date(streak.lastViewAt), subDays(now, 1), timezone); + const wait = (ms: number) => new Promise((resolve) => { setTimeout(resolve, ms); @@ -40,8 +53,10 @@ export const useViewPost = (): UseMutateAsyncFunction< const { user } = useAuthContext(); const { value: isOptimisticView } = useConditionalFeature({ feature: featureStreakOptimisticView, - shouldEvaluate: !!user, + shouldEvaluate: !!user && !isCompanion, }); + // The companion cannot persist the retry queue, so it keeps the old flow. + const isOptimistic = isOptimisticView && !isCompanion; const streakKey = generateQueryKey(RequestKey.UserStreak, user); const readKey = generateQueryKey(RequestKey.ReadingStreak30Days, user); const { mutateAsync: onSendViewPost } = useMutation< @@ -63,7 +78,12 @@ export const useViewPost = (): UseMutateAsyncFunction< ); const shouldRefetchStreak = isNewStreak || isFirstViewToday; - if (!isOptimisticView || !shouldRefetchStreak || !streak) { + if ( + !isOptimistic || + !shouldRefetchStreak || + !streak || + !canBumpStreak(streak, user?.timezone) + ) { return { shouldRefetchStreak }; } @@ -113,7 +133,7 @@ export const useViewPost = (): UseMutateAsyncFunction< return null; }, onError: (error, id, context) => { - if (!isOptimisticView || isCompanion) { + if (!isOptimistic) { return; } @@ -125,6 +145,12 @@ export const useViewPost = (): UseMutateAsyncFunction< return; } + // Only a read that would have counted for today's streak is worth a + // replay; later reads add nothing to it. + if (!context?.shouldRefetchStreak) { + return; + } + enqueueStreakView({ postId: id, userId: user!.id, From 798e82c141aefbb090300b900160b5cb544ed966 Mon Sep 17 00:00:00 2001 From: Chris Bongers Date: Mon, 16 Nov 2026 14:12:13 +0200 Subject: [PATCH 8/8] fix(streak): trust the server after a stale retry and toast only confirmed counts newView skips a post the user viewed in the past week, so a stale retry can mean the read never counted. Keeping the optimistic bump then showed an extended streak all day and made later reads skip the refetch. After a stale retry the server value now stays. The toast only uses a count the refetch confirmed, and a stale first refetch gets the same single retry with the optimistic flag off, so the toast still shows once the worker catches up. The stale-toast specs use a non-milestone count. Co-Authored-By: Claude Opus 5.5 --- .../src/hooks/post/useViewPost.spec.tsx | 108 ++++++++---------- packages/shared/src/hooks/post/useViewPost.ts | 24 ++-- 2 files changed, 62 insertions(+), 70 deletions(-) diff --git a/packages/shared/src/hooks/post/useViewPost.spec.tsx b/packages/shared/src/hooks/post/useViewPost.spec.tsx index 4a051cc93ba..59f33c19bcd 100644 --- a/packages/shared/src/hooks/post/useViewPost.spec.tsx +++ b/packages/shared/src/hooks/post/useViewPost.spec.tsx @@ -247,7 +247,9 @@ describe('useViewPost', () => { }); }); - it('should keep the optimistic streak when the retry is still stale', async () => { + // a re-read of a post viewed in the past week: newView skips it, so the + // streak never moves + it('should put the server streak back when the retry is still stale', async () => { mockPreViewStreak(); mockPreViewStreak(); const requestMethod = jest @@ -265,9 +267,9 @@ describe('useViewPost', () => { expect(nock.isDone()).toBe(true); expect(client.getQueryData(streakKey)).toMatchObject({ - current: 8, - total: 21, - max: 8, + current: 7, + total: 20, + max: 7, }); }); }); @@ -520,47 +522,22 @@ describe('useViewPost', () => { }); describe('when the refetch still has the pre-view streak', () => { - // the newView worker has not credited the read yet, so userStreak - // returns yesterday's 7 although this read makes it 8 + // the newView worker has not credited the read yet, or skipped it (a + // post viewed in the past week), so userStreak still returns day 5 const mockPreViewStreak = () => mockGraphQL({ request: { query: USER_STREAK_QUERY }, - result: { data: { userStreak: streak } }, - }); - - afterEach(() => { - jest.useRealTimers(); - }); - - it('should not toast the stale count on a milestone day', async () => { - mockPreViewStreak(); - const { result } = renderViewPost({ - client, - requestMethod: requestMethod(), - flag: false, - celebrationFlag: true, - }); - - await act(async () => { - await result.current('p1'); + result: { data: { userStreak: dayFive } }, }); - - // 8 is a milestone, so the toast stays quiet instead of "Day 7!" - expect(nock.isDone()).toBe(true); - expect(getToast()).toBeFalsy(); - expect( - localStorage.getItem(getStreakCelebratedKey(user.id)), - ).toBeNull(); - }); - - it('should not toast the stale count after the retry is stale too', async () => { - jest.useFakeTimers({ advanceTimers: true }); - mockPreViewStreak(); - mockPreViewStreak(); + const renderAndView = async ( + props: Partial[0]> = {}, + ) => { const { result } = renderViewPost({ client, requestMethod: requestMethod(), celebrationFlag: true, + initialStreak: dayFive, + ...props, }); const promise = result.current('p1'); @@ -569,44 +546,57 @@ describe('useViewPost', () => { await jest.advanceTimersByTimeAsync(STREAK_REFETCH_RETRY_DELAY_MS); await promise; }); + }; - expect(nock.isDone()).toBe(true); - expect(getToast()).toBeFalsy(); + beforeEach(() => { + jest.useFakeTimers({ advanceTimers: true }); + }); + + afterEach(() => { + jest.useRealTimers(); }); + it.each([ + ['on', true], + ['off', false], + ])( + 'should not toast a read the API never counted with optimistic view %s', + async (_, flag) => { + mockPreViewStreak(); + mockPreViewStreak(); + + await renderAndView({ flag }); + + expect(nock.isDone()).toBe(true); + expect(getToast()).toBeFalsy(); + expect( + localStorage.getItem(getStreakCelebratedKey(user.id)), + ).toBeNull(); + }, + ); + it('should not toast a guessed count after a gap', async () => { mockPreViewStreak(); - const { result } = renderViewPost({ - client, - requestMethod: requestMethod(), - celebrationFlag: true, - initialStreak: { ...dayFive, lastViewAt: subDays(new Date(), 3) }, - }); + mockPreViewStreak(); - await act(async () => { - await result.current('p1'); + await renderAndView({ + initialStreak: { ...dayFive, lastViewAt: subDays(new Date(), 3) }, }); + expect(nock.isDone()).toBe(true); expect(getToast()).toBeFalsy(); }); - it('should toast the count this read lands on', async () => { + it('should toast once the retry confirms the read', async () => { + mockPreViewStreak(); mockGraphQL({ request: { query: USER_STREAK_QUERY }, - result: { data: { userStreak: dayFive } }, - }); - const { result } = renderViewPost({ - client, - requestMethod: requestMethod(), - flag: false, - celebrationFlag: true, - initialStreak: dayFive, + result: { data: { userStreak: daySix } }, }); - await act(async () => { - await result.current('p1'); - }); + await renderAndView({ flag: false }); + expect(nock.isDone()).toBe(true); render(<>{getToast()?.message}); expect( screen.getByText('Day 6! See you tomorrow.'), diff --git a/packages/shared/src/hooks/post/useViewPost.ts b/packages/shared/src/hooks/post/useViewPost.ts index 611209f9986..1636399dde2 100644 --- a/packages/shared/src/hooks/post/useViewPost.ts +++ b/packages/shared/src/hooks/post/useViewPost.ts @@ -39,8 +39,8 @@ interface ViewPostContext { previousStreak?: UserStreak; optimisticStreak?: UserStreak; shouldRefetchStreak: boolean; - // the count this view should land on, used when the refetch fails or - // has not caught up with the view yet + // the count this view should land on, to recognize a refetch that already + // includes it nextStreak?: number; } @@ -127,22 +127,24 @@ export const useViewPost = (): UseMutateAsyncFunction< }; let countedStreak = await refetchStreak(); - // A refetch that still has the pre-view streak would undo the - // optimistic bump, so keep the bump and ask once more after a moment. - if (optimisticStreak && !countedStreak) { - client.setQueryData(streakKey, optimisticStreak); - await wait(STREAK_REFETCH_RETRY_DELAY_MS); - countedStreak = await refetchStreak(); - - if (!countedStreak) { + // The worker may not have credited the view yet: keep the optimistic + // bump and ask once more after a moment. A retry that is still stale + // means the API skipped the view (it ignores a post the user viewed in + // the past week), so the server value it returned stays. + if (!countedStreak) { + if (optimisticStreak) { client.setQueryData(streakKey, optimisticStreak); } + await wait(STREAK_REFETCH_RETRY_DELAY_MS); + countedStreak = await refetchStreak(); } // just mark the query as stale await client.invalidateQueries({ queryKey: readKey }); - celebrateStreakDay(countedStreak?.current ?? context.nextStreak); + // only a count the API confirmed: a guess could celebrate a day that + // never counted and suppress the toast for the read that does + celebrateStreakDay(countedStreak?.current); return null; },