Repository navigation
feat(streak): count the read on open and retry dropped views - #7373
rebelchris wants to merge 15 commits into
Conversation
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
…c-view # Conflicts: # packages/extension/src/newtab/App.tsx # packages/shared/src/hooks/post/useViewPost.ts # packages/webapp/pages/_app.tsx
rebelchris
left a comment
There was a problem hiding this comment.
Two blockers, both about how the API credits a view: viewPost only publishes to the views topic, and the streak is written later by the newView worker using the server time it receives the event. Details inline, plus two non-blocking notes. CI is green.
Reviewed by AI.
- 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 <noreply@anthropic.com>
…e 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 <noreply@anthropic.com>
rebelchris
left a comment
There was a problem hiding this comment.
Re-checked at d877abf. Both blockers are fixed: the stale-refetch guard is covered by specs, and replays are now same-day only. The two non-blocking notes are addressed too. NOT_FOUND matches how the API formats EntityNotFoundError, so a missing post is dropped as intended. One small edge case remains, inline. CI is green.
Reviewed by AI.
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 <noreply@anthropic.com>
…c-view # Conflicts: # packages/shared/src/lib/featureManagement.ts
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
…p, queue only counting reads Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…uiet after a gap The daily toast fell back to current + 1 when the refetch had not caught up. After a gap the API may reset or freeze the streak, so there is no safe guess: only a refetch that includes the read is toasted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Three more fixes, plus a merge of #7374, which was squashed into this branch:
There's a spec for each case, and the new specs fail on the old code. |
…c-view # Conflicts: # packages/shared/src/lib/log.ts
rebelchris
left a comment
There was a problem hiding this comment.
Re-review of the changes since d877abf: 6bc162a (companion, gaps, queue) and the toast from #7374 as resolved in c09c25d. CI is green and the branch merges cleanly.
The earlier grace-window thread is fixed: includesThisRead accepts a matching count. The companion skip, the no-bump-after-a-gap rule and queueing only counting reads all look right, and each has a spec.
One blocker remains, explained inline. A stale refetch does not always mean the worker is slow. newView also ignores a view on purpose: addView skips any post this user viewed in the last week, so the streak is never written. If the first read of the day is a re-read (a bookmark, history, a post from yesterday), the tile stays at the bumped count for the rest of the day and the toast celebrates a day that was not counted. There is also one spec that passes for the wrong reason.
Specs were not run locally; I relied on CI.
Reviewed by AI.
| countedStreak = await refetchStreak(); | ||
|
|
||
| if (!countedStreak) { | ||
| client.setQueryData<UserStreak>(streakKey, optimisticStreak); |
There was a problem hiding this comment.
Blocking: when the retry is still stale, this keeps the optimistic entry on the assumption that the newView worker is just slow. But the worker also drops views on purpose. addView in daily-api skips a view of a post this user already viewed within the last week (ONE_WEEK), and in that case incrementReadingStreak never runs. So if the first read of the day is a re-read (a bookmark, reading history, yesterday's post opened again), the API does not extend the streak, while this branch:
- leaves the tile at
current + 1withlastViewAt = now; - makes every later read today skip the refetch, because
isFirstViewTodayis now false, so nothing corrects it during the session.
The reader sees their streak as extended, stops reading, and loses it at midnight. That is the opposite of what this flag is for.
Suggested fix: after a stale retry, put the server value back instead of the optimistic one. Or don't bump at all when the post is already read: Post.read is on the post the callers already have, so useTrackPostView could pass it in. Please add a spec where both refetches return the pre-view streak and the expected result is the server value, not the bump.
Reviewed by AI.
There was a problem hiding this comment.
Fixed in 798e82c. When the retry is still stale, the hook now keeps the server value the refetch returned, instead of putting the bump back. For a re-read the API skipped, the tile goes back to N, lastViewAt stays on yesterday, and the next read today is treated as the first one again, so it can correct itself. The spec "should put the server streak back when the retry is still stale" has both refetches return the pre-view streak and expects the server value. I didn't gate the bump on Post.read. It means read at any time, not within the API's one-week window, and it would mean threading a flag through all six callers. The server-value fallback covers both cases.
| // just mark the query as stale | ||
| await client.invalidateQueries({ queryKey: readKey }); | ||
|
|
||
| celebrateStreakDay(countedStreak?.current ?? context.nextStreak); |
There was a problem hiding this comment.
Blocking (same cause as above): the ?? context.nextStreak fallback still toasts a guessed count whenever the refetch has not confirmed the read. With the flag on, that happens after both refetches are stale. With streak_optimistic_view off, a single stale refetch is enough. For a re-read the API never counts, the reader gets "Day n+1! See you tomorrow." for a day that does not count. markStreakCelebrated then suppresses the toast for the real counting read later that day, and the impression logs a target_id that never existed.
The #7374 change made the toast confirm-only after a gap. Please apply the same rule here: toast only countedStreak?.current, and drop the nextStreak fallback. The milestone guard can then use the confirmed count too.
Reviewed by AI.
There was a problem hiding this comment.
Fixed in 798e82c. The toast now uses only countedStreak?.current, and the nextStreak fallback is gone. So the milestone guard and the impression target_id only see confirmed counts. To keep the toast working with streak_optimistic_view off, a stale first refetch now gets the same single 2s retry in both arms. If the retry confirms the read, it toasts. If not, nothing. Specs: no toast after two stale refetches with the flag on and with it off, no toast after a gap, and a toast once the retry confirms.
| ).toBeNull(); | ||
| }); | ||
|
|
||
| it('should not toast the stale count after the retry is stale too', async () => { |
There was a problem hiding this comment.
Non-blocking (test): this passes because of the milestone rule, not because of the stale retry. The shared streak fixture has current: 7, so the guessed count is 8, which is a Fibonacci milestone, and isStreakMilestone suppresses the toast. With a non-milestone fixture (for example dayFive), the code today toasts "Day 6!" from the nextStreak fallback. Please use a non-milestone count here, so the spec covers what its name says and fails until the fallback is removed.
Reviewed by AI.
There was a problem hiding this comment.
Fixed in 798e82c. The stale-refetch toast specs now start from dayFive and the pre-view mock returns dayFive, so a guessed count would be 6, not a milestone. They fail on the previous code. The "retry confirms" spec also asserts both refetches ran, so it can't pass on a guess.
…c-view # Conflicts: # packages/shared/src/lib/log.ts
…irmed 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 <noreply@anthropic.com>
…c-view # Conflicts: # packages/shared/src/lib/log.ts
Changes
Count the read on open (
streak_optimistic_view)viewPostpublishes it, and thenewViewworker writes the streak), so the refetch after the mutation can still return the streak from before the read. The refetched streak is accepted only if it already includes the read: itslastViewAtis today in the profile timezone, or itscurrentalready matches the expected count (this covers a read the API's grace window credits to yesterday). Otherwise the optimistic entry is kept and the refetch is retried once after 2s (STREAK_REFETCH_RETRY_DELAY_MS). If the retry is still stale, the server value stays:newViewskips a post the user viewed in the past week, so a re-read may never count, and the tile must not show an extended streak for it.NOT_FOUND,FORBIDDEN,UNAUTHENTICATED. Network failures and every other GraphQL error (rate limiting, a failed publish) keep the optimistic streak and go to a localStorage queue. Only a read that would count for today's streak is queued.viewPostcarries no read time, so the API would credit a replay after midnight to the replay day. Older entries are dropped without being sent. Not used in the companion.useStreakViewQueue, mounted app-wide) does not evaluate the flag, so it doesn't enroll every signed-in user. Only flagged users can add to the queue.Daily streak toast (
streak_daily_celebration, from #7374, which was squashed into this branch)streak_optimistic_view, so the toast still shows once the worker catches up. A read the API never counts shows no toast.What to review since the last review (d877abf)
baf24515f: accept a refetch whose count already matches (grace-credited read).6bc162a30: no bump in the companion, no bump after a gap, queue only counting reads.c09c25d4a(merge of feat(streak): toast the day's streak on the first counted read #7374): besides the merge,useViewPost.tssetsnextStreakonly whencanBumpStreakpasses, so the toast doesn't guess after a gap. There's a spec for it: "should not toast a guessed count after a gap".Events
Yes:
impressionstreak daily celebration6)Experiment
Yes, two flags, both default off:
streak_optimistic_view: users are exposed only whenuseViewPostruns for a signed-in user outside the companion.streak_daily_celebration: evaluated only for signed-in users outside the companion who have streaks enabled.#experiments message not posted yet.
Manual Testing
Specs:
useViewPost(refetch with the pre-view streak, companion, gaps, reset streak, toast cases),useStreakViewQueue,streakViewQueue,userStreak, webappPostPage,Companion.🤖 Generated with Claude Code
Preview domain
https://feat-streak-optimistic-view.preview.app.daily.dev