diff --git a/package.json b/package.json index fb1e99fff..d0e7dba53 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.127.1", + "version": "1.127.2", "private": true, "packageManager": "pnpm@11.7.0", "engines": { diff --git a/src/lib/api/__tests__/community-notifications.test.ts b/src/lib/api/__tests__/community-notifications.test.ts new file mode 100644 index 000000000..203d5794a --- /dev/null +++ b/src/lib/api/__tests__/community-notifications.test.ts @@ -0,0 +1,204 @@ +import { + type AppBskyNotificationGetUnreadCount, + type AppBskyNotificationListNotifications, + type AtpAgent, + lexicons, +} from '@atproto/api' + +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) +jest.mock('multiformats/cid', () => ({ + CID: { + asCID: () => null, + parse: (value: string) => { + if (!value.startsWith('bafy')) throw new Error('invalid cid') + return {toString: () => value} + }, + }, +})) + +import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' +import { + type CommunityNotificationXrpcError, + GET_UNREAD_COUNT_METHOD, + getUnreadCount, + LIST_NOTIFICATIONS_METHOD, + listNotifications, +} from '../community-notifications' + +const SPACE = 'at://did:plc:tenant/space/community.blacksky.feed/private' +const PRIVATE_URI = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kprivate` +const PUBLIC_URI = 'at://did:plc:alice/app.bsky.feed.post/3kpublic' +const CID = 'bafyreihhl5mpvjkrhnnagen2fomozzhnhhdq2jr6cego2nzbvmwewv5rd4' + +function notification(uri: string) { + return { + uri, + cid: CID, + author: {did: 'did:plc:alice', handle: 'alice.test'}, + reason: 'mention', + reasonSubject: uri, + record: { + $type: 'app.bsky.feed.post', + text: 'hello', + createdAt: '2026-09-01T00:00:00.000Z', + }, + isRead: false, + indexedAt: '2026-09-01T00:00:00.000Z', + } +} + +function listBody(uri = PRIVATE_URI) { + return { + cursor: 'next', + notifications: [notification(uri)], + priority: false, + seenAt: '2026-09-01T00:00:00.000Z', + } +} + +function mockAgent() { + const fetchHandler = jest.fn, [string, RequestInit]>() + const standardList = jest.fn< + Promise<{data: AppBskyNotificationListNotifications.OutputSchema}>, + [AppBskyNotificationListNotifications.QueryParams, unknown] + >() + const standardCount = jest.fn< + Promise<{data: AppBskyNotificationGetUnreadCount.OutputSchema}>, + [AppBskyNotificationGetUnreadCount.QueryParams, unknown] + >() + const agent = { + fetchHandler, + app: { + bsky: { + notification: { + listNotifications: standardList, + getUnreadCount: standardCount, + }, + }, + }, + } as unknown as AtpAgent + return {agent, fetchHandler, standardList, standardCount} +} + +describe('community notification API', () => { + it('accepts private notification output rejected by the standard catalog', async () => { + const {agent, fetchHandler} = mockAgent() + const body = listBody() + fetchHandler.mockResolvedValue(new Response(JSON.stringify(body))) + + expect(() => + lexicons.assertValidXrpcOutput( + 'app.bsky.notification.listNotifications', + body, + ), + ).toThrow() + await expect( + listNotifications(agent, {limit: 30, reasons: ['mention']}), + ).resolves.toEqual(body) + expect(fetchHandler).toHaveBeenCalledWith( + expect.stringContaining(`/xrpc/${LIST_NOTIFICATIONS_METHOD}?`), + expect.objectContaining({method: 'GET'}), + ) + }) + + it('keeps public notification output compatible', async () => { + const {agent, fetchHandler} = mockAgent() + const body = listBody(PUBLIC_URI) + fetchHandler.mockResolvedValue(new Response(JSON.stringify(body))) + + expect(() => + lexicons.assertValidXrpcOutput( + 'app.bsky.notification.listNotifications', + body, + ), + ).not.toThrow() + await expect(listNotifications(agent, {})).resolves.toEqual(body) + }) + + it('rejects malformed successful output before returning it', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response(JSON.stringify({notifications: [{uri: PRIVATE_URI}]})), + ) + + await expect(listNotifications(agent, {})).rejects.toThrow() + }) + + it('falls back only for a 501 MethodNotImplemented response', async () => { + const {agent, fetchHandler, standardList, standardCount} = mockAgent() + fetchHandler + .mockResolvedValueOnce( + new Response(JSON.stringify({error: 'MethodNotImplemented'}), { + status: 501, + }), + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({error: 'MethodNotImplemented'}), { + status: 501, + }), + ) + standardList.mockResolvedValue({ + data: listBody(PUBLIC_URI), + }) + standardCount.mockResolvedValue({data: {count: 4}}) + + await expect(listNotifications(agent, {limit: 20})).resolves.toEqual( + listBody(PUBLIC_URI), + ) + await expect(getUnreadCount(agent, {priority: true})).resolves.toEqual({ + count: 4, + }) + expect(standardList).toHaveBeenCalledWith( + {limit: 20}, + HOME_APPVIEW_PINNED_OPTS, + ) + expect(standardCount).toHaveBeenCalledWith( + {priority: true}, + HOME_APPVIEW_PINNED_OPTS, + ) + }) + + it.each([ + [404, 'MethodNotImplemented'], + [501, 'UnknownMethod'], + [501, undefined], + [403, 'Forbidden'], + [503, 'UpstreamFailure'], + ])('does not fall back for status %s and error %s', async (status, error) => { + const {agent, fetchHandler, standardList} = mockAgent() + fetchHandler.mockResolvedValue( + new Response(JSON.stringify(error ? {error} : {}), {status}), + ) + + await expect(listNotifications(agent, {})).rejects.toEqual( + expect.objectContaining>({ + status, + error, + }), + ) + expect(standardList).not.toHaveBeenCalled() + }) + + it('surfaces transport failures without fallback', async () => { + const {agent, fetchHandler, standardList} = mockAgent() + const error = new Error('offline') + fetchHandler.mockRejectedValue(error) + + await expect(listNotifications(agent, {})).rejects.toBe(error) + expect(standardList).not.toHaveBeenCalled() + }) + + it('validates and returns the custom unread count', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue(new Response(JSON.stringify({count: 8}))) + + await expect(getUnreadCount(agent)).resolves.toEqual({count: 8}) + expect(fetchHandler).toHaveBeenCalledWith( + `/xrpc/${GET_UNREAD_COUNT_METHOD}`, + expect.objectContaining({method: 'GET'}), + ) + }) +}) diff --git a/src/lib/api/__tests__/community.test.ts b/src/lib/api/__tests__/community.test.ts index 3ab2c7e8c..ced31d3f2 100644 --- a/src/lib/api/__tests__/community.test.ts +++ b/src/lib/api/__tests__/community.test.ts @@ -63,6 +63,33 @@ describe('communityXrpc', () => { ) }) + it('serializes repeated primitive parameters and omits empty values', async () => { + const {agent, fetchHandler} = mockAgent() + + await communityXrpc( + agent, + 'community.blacksky.notification.listNotifications', + { + params: { + reasons: ['mention', 'reply'], + empty: [], + limit: 30, + priority: false, + cursor: 'before value', + seenAt: undefined, + }, + }, + ) + + const url = new URL(fetchHandler.mock.calls[0][0], 'https://example.test') + expect(url.searchParams.getAll('reasons')).toEqual(['mention', 'reply']) + expect(url.searchParams.get('limit')).toBe('30') + expect(url.searchParams.get('priority')).toBe('false') + expect(url.searchParams.get('cursor')).toBe('before value') + expect(url.searchParams.has('empty')).toBe(false) + expect(url.searchParams.has('seenAt')).toBe(false) + }) + it('fetches space likes through the permission-aware endpoint', async () => { const {agent, fetchHandler} = mockAgent() fetchHandler.mockResolvedValue( diff --git a/src/lib/api/community-notifications.ts b/src/lib/api/community-notifications.ts new file mode 100644 index 000000000..3f59f88cc --- /dev/null +++ b/src/lib/api/community-notifications.ts @@ -0,0 +1,237 @@ +import { + type AppBskyNotificationGetUnreadCount, + type AppBskyNotificationListNotifications, + type AtpAgent, + jsonToLex, + lexicons, +} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' + +export const LIST_NOTIFICATIONS_METHOD = + 'community.blacksky.notification.listNotifications' +export const GET_UNREAD_COUNT_METHOD = + 'community.blacksky.notification.getUnreadCount' + +const listNotificationsSchema = { + lexicon: 1, + id: LIST_NOTIFICATIONS_METHOD, + defs: { + main: { + type: 'query', + description: + 'Enumerate public and authorized permissioned-space notifications for the requesting account. An empty page may include a cursor and should be continued.', + parameters: { + type: 'params', + properties: { + reasons: { + description: 'Notification reasons to include in response.', + type: 'array', + items: { + type: 'string', + description: + 'A reason that matches the reason property of #notification.', + }, + }, + limit: {type: 'integer', minimum: 1, maximum: 100, default: 50}, + priority: {type: 'boolean'}, + cursor: {type: 'string'}, + seenAt: {type: 'string', format: 'datetime'}, + }, + }, + output: { + encoding: 'application/json', + schema: { + type: 'object', + required: ['notifications'], + properties: { + cursor: {type: 'string'}, + notifications: { + type: 'array', + items: {type: 'ref', ref: '#notification'}, + }, + priority: {type: 'boolean'}, + seenAt: {type: 'string', format: 'datetime'}, + }, + }, + }, + }, + notification: { + type: 'object', + required: [ + 'uri', + 'cid', + 'author', + 'reason', + 'record', + 'isRead', + 'indexedAt', + ], + properties: { + uri: { + type: 'string', + description: + 'The public AT URI or permissioned-space record URI that caused the notification.', + }, + cid: {type: 'string', format: 'cid'}, + author: {type: 'ref', ref: 'app.bsky.actor.defs#profileView'}, + reason: { + type: 'string', + description: 'The reason why this notification was delivered.', + knownValues: [ + 'like', + 'repost', + 'follow', + 'mention', + 'reply', + 'quote', + 'starterpack-joined', + 'verified', + 'unverified', + 'like-via-repost', + 'repost-via-repost', + 'subscribed-post', + 'contact-match', + ], + }, + reasonSubject: { + type: 'string', + description: + 'The public AT URI or permissioned-space record URI that is the notification subject.', + }, + record: {type: 'unknown'}, + starterPack: { + description: 'The starter pack associated with this notification.', + type: 'ref', + ref: 'app.bsky.graph.defs#starterPackViewBasic', + }, + isRead: {type: 'boolean'}, + indexedAt: {type: 'string', format: 'datetime'}, + labels: { + type: 'array', + items: {type: 'ref', ref: 'com.atproto.label.defs#label'}, + }, + }, + }, + }, +} as const + +const getUnreadCountSchema = { + lexicon: 1, + id: GET_UNREAD_COUNT_METHOD, + defs: { + main: { + type: 'query', + description: + 'Count unread public and authorized permissioned-space notifications for the requesting account.', + parameters: { + type: 'params', + properties: { + priority: {type: 'boolean'}, + seenAt: {type: 'string', format: 'datetime'}, + }, + }, + output: { + encoding: 'application/json', + schema: { + type: 'object', + required: ['count'], + properties: {count: {type: 'integer'}}, + }, + }, + }, + }, +} as const + +type LexiconDoc = Parameters[0] + +function registerLexicon(doc: LexiconDoc) { + if (!lexicons.get(doc.id)) { + lexicons.add(doc) + } +} + +registerLexicon(listNotificationsSchema as unknown as LexiconDoc) +registerLexicon(getUnreadCountSchema as unknown as LexiconDoc) + +export class CommunityNotificationXrpcError extends Error { + constructor( + method: string, + public readonly status: number, + public readonly error?: string, + ) { + super(`${method} failed (${status}${error ? ` ${error}` : ''})`) + } +} + +export async function listNotifications( + agent: AtpAgent, + params: AppBskyNotificationListNotifications.QueryParams, +): Promise { + const response = await communityXrpc(agent, LIST_NOTIFICATIONS_METHOD, { + params, + }) + if (!response.ok) { + if (await isUnsupportedMethod(response)) { + const result = await agent.app.bsky.notification.listNotifications( + params, + HOME_APPVIEW_PINNED_OPTS, + ) + return result.data + } + throw await toXrpcError(LIST_NOTIFICATIONS_METHOD, response) + } + const data = jsonToLex(await response.json()) + lexicons.assertValidXrpcOutput(LIST_NOTIFICATIONS_METHOD, data) + return data as AppBskyNotificationListNotifications.OutputSchema +} + +export async function getUnreadCount( + agent: AtpAgent, + params: AppBskyNotificationGetUnreadCount.QueryParams = {}, +): Promise { + const response = await communityXrpc(agent, GET_UNREAD_COUNT_METHOD, { + params, + }) + if (!response.ok) { + if (await isUnsupportedMethod(response)) { + const result = await agent.app.bsky.notification.getUnreadCount( + params, + HOME_APPVIEW_PINNED_OPTS, + ) + return result.data + } + throw await toXrpcError(GET_UNREAD_COUNT_METHOD, response) + } + const data = jsonToLex(await response.json()) + lexicons.assertValidXrpcOutput(GET_UNREAD_COUNT_METHOD, data) + return data as AppBskyNotificationGetUnreadCount.OutputSchema +} + +async function parseXrpcError(response: Response): Promise<{ + error?: string +}> { + try { + const body: unknown = await response.clone().json() + return typeof body === 'object' && + body !== null && + 'error' in body && + typeof body.error === 'string' + ? {error: body.error} + : {} + } catch { + return {} + } +} + +async function isUnsupportedMethod(response: Response): Promise { + if (response.status !== 501) return false + const body = await parseXrpcError(response) + return body.error === 'MethodNotImplemented' +} + +async function toXrpcError(method: string, response: Response) { + const body = await parseXrpcError(response) + return new CommunityNotificationXrpcError(method, response.status, body.error) +} diff --git a/src/lib/api/community.ts b/src/lib/api/community.ts index 817580059..9b03a78fa 100644 --- a/src/lib/api/community.ts +++ b/src/lib/api/community.ts @@ -8,18 +8,31 @@ import { import {HOME_PROXY_HEADER} from '#/lib/constants' import {toPostView} from './space-views' +export type CommunityXrpcParam = string | number | boolean + export async function communityXrpc( agent: BskyAgent, method: string, opts?: { - params?: Record + params?: Record< + string, + CommunityXrpcParam | readonly CommunityXrpcParam[] | undefined + > body?: unknown serviceDid?: string }, ): Promise { - const qs = opts?.params - ? '?' + new URLSearchParams(opts.params).toString() - : '' + const searchParams = new URLSearchParams() + for (const [key, value] of Object.entries(opts?.params ?? {})) { + const values = Array.isArray(value) ? value : [value] + for (const item of values) { + if (item !== undefined) { + searchParams.append(key, String(item)) + } + } + } + const encodedParams = searchParams.toString() + const qs = encodedParams ? `?${encodedParams}` : '' const path = `/xrpc/${method}${qs}` const headers: Record = { diff --git a/src/state/queries/notifications/__tests__/fetch-page.test.ts b/src/state/queries/notifications/__tests__/fetch-page.test.ts new file mode 100644 index 000000000..5eaa176ff --- /dev/null +++ b/src/state/queries/notifications/__tests__/fetch-page.test.ts @@ -0,0 +1,90 @@ +import {type AtpAgent} from '@atproto/api' +import {QueryClient} from '@tanstack/react-query' + +const mockListNotifications = jest.fn() + +jest.mock('#/lib/api/community-notifications', () => ({ + listNotifications: (...args: unknown[]) => mockListNotifications(...args), +})) +jest.mock('#/state/queries/profile', () => ({precacheProfile: jest.fn()})) + +import {fetchPage} from '../util' + +const SPACE = 'at://did:plc:tenant/space/community.blacksky.feed/private' +const PRIVATE_URI = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kprivate` + +describe(fetchPage, () => { + const agent = {} as AtpAgent + const queryClient = new QueryClient() + + beforeEach(() => { + jest.clearAllMocks() + }) + + it('converts a private notification from the custom ordered stream', async () => { + mockListNotifications.mockResolvedValue({ + cursor: 'next', + priority: false, + seenAt: '2026-09-01T00:00:00.000Z', + notifications: [ + { + uri: PRIVATE_URI, + cid: 'bafyreiacsg6vsw7ppwbnowzsdgstulhrwftirtcnvkcbnfgvhwjrnzfmsu', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + reason: 'mention', + reasonSubject: PRIVATE_URI, + record: {$type: 'app.bsky.feed.post', text: 'private'}, + isRead: false, + indexedAt: '2026-09-01T00:00:00.000Z', + }, + ], + }) + + const result = await fetchPage({ + agent, + cursor: undefined, + limit: 30, + queryClient, + moderationOpts: undefined, + hideFollowNotifications: undefined, + fetchAdditionalData: false, + reasons: [], + }) + + expect(mockListNotifications).toHaveBeenCalledWith(agent, { + limit: 30, + cursor: undefined, + reasons: [], + }) + expect(result.page.cursor).toBe('next') + expect(result.page.items).toHaveLength(1) + expect(result.page.items[0].subjectUri).toBe(PRIVATE_URI) + }) + + it('preserves a cursor on an empty mentions page', async () => { + mockListNotifications.mockResolvedValue({ + cursor: 'continue', + notifications: [], + }) + + const result = await fetchPage({ + agent, + cursor: 'before', + limit: 30, + queryClient, + moderationOpts: undefined, + hideFollowNotifications: undefined, + fetchAdditionalData: false, + reasons: ['mention', 'reply', 'quote'], + }) + + expect(result.page).toMatchObject({cursor: 'continue', items: []}) + expect(mockListNotifications).toHaveBeenCalledWith( + agent, + expect.objectContaining({ + cursor: 'before', + reasons: ['mention', 'reply', 'quote'], + }), + ) + }) +}) diff --git a/src/state/queries/notifications/__tests__/pagination.test.ts b/src/state/queries/notifications/__tests__/pagination.test.ts new file mode 100644 index 000000000..7fe5334c4 --- /dev/null +++ b/src/state/queries/notifications/__tests__/pagination.test.ts @@ -0,0 +1,92 @@ +import {nextAutoPaginationAttemptCount, shouldAutoPaginate} from '../pagination' + +describe(shouldAutoPaginate, () => { + it('continues through an empty page that has a cursor', () => { + expect( + shouldAutoPaginate({ + hasNextPage: true, + itemCount: 0, + wantedItemCount: 30, + attemptCount: 0, + }), + ).toBe(true) + }) + + it('continues when filtering leaves a short page', () => { + expect( + shouldAutoPaginate({ + hasNextPage: true, + itemCount: 4, + wantedItemCount: 30, + attemptCount: 3, + }), + ).toBe(true) + }) + + it('stops on a terminal empty page', () => { + expect( + shouldAutoPaginate({ + hasNextPage: false, + itemCount: 0, + wantedItemCount: 30, + attemptCount: 0, + }), + ).toBe(false) + }) + + it('stops at the 50-attempt safety bound', () => { + expect( + shouldAutoPaginate({ + hasNextPage: true, + itemCount: 0, + wantedItemCount: 30, + attemptCount: 49, + }), + ).toBe(true) + expect( + shouldAutoPaginate({ + hasNextPage: true, + itemCount: 0, + wantedItemCount: 30, + attemptCount: 50, + }), + ).toBe(false) + }) +}) + +describe(nextAutoPaginationAttemptCount, () => { + it.each([ + {isLoading: true, isRefetching: false, hasNextPage: true}, + {isLoading: false, isRefetching: true, hasNextPage: true}, + {isLoading: false, isRefetching: false, hasNextPage: false}, + ])('resets attempts for $isLoading/$isRefetching/$hasNextPage', state => { + expect( + nextAutoPaginationAttemptCount({ + attemptCount: 17, + requestNextPage: false, + ...state, + }), + ).toBe(0) + }) + + it('increments only when the active cycle requests another page', () => { + expect( + nextAutoPaginationAttemptCount({ + attemptCount: 17, + hasNextPage: true, + isLoading: false, + isRefetching: false, + requestNextPage: true, + }), + ).toBe(18) + expect( + nextAutoPaginationAttemptCount({ + attemptCount: 17, + hasNextPage: true, + isLoading: false, + isRefetching: false, + requestNextPage: false, + }), + ).toBe(17) + }) +}) diff --git a/src/state/queries/notifications/__tests__/unread.test.tsx b/src/state/queries/notifications/__tests__/unread.test.tsx new file mode 100644 index 000000000..79a9770c3 --- /dev/null +++ b/src/state/queries/notifications/__tests__/unread.test.tsx @@ -0,0 +1,245 @@ +import {type PropsWithChildren} from 'react' +import {AppState} from 'react-native' +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {act, renderHook} from '@testing-library/react-native' + +const mockGetUnreadCount = jest.fn() +const mockFetchPage = jest.fn() +const mockResetBadgeCount = jest.fn() +const mockTruncateAndInvalidate = jest.fn() +const mockUpdateSeen = jest.fn().mockResolvedValue(undefined) +const mockBroadcastPostMessage = jest.fn() +let mockBroadcastListener: ((event: MessageEvent) => void) | undefined +const mockAgent = { + session: {did: 'did:plc:viewer'}, + app: { + bsky: { + notification: {updateSeen: mockUpdateSeen}, + }, + }, +} + +jest.mock('#/lib/api/community-notifications', () => ({ + getUnreadCount: (...args: unknown[]) => mockGetUnreadCount(...args), +})) +jest.mock('#/lib/broadcast', () => + jest.fn().mockImplementation(() => ({ + postMessage: (...args: unknown[]) => mockBroadcastPostMessage(...args), + addEventListener: ( + _type: string, + listener: (event: MessageEvent) => void, + ) => { + mockBroadcastListener = listener + }, + removeEventListener: ( + _type: string, + listener: (event: MessageEvent) => void, + ) => { + if (mockBroadcastListener === listener) mockBroadcastListener = undefined + }, + })), +) +jest.mock('#/lib/notifications/notifications', () => ({ + resetBadgeCount: () => mockResetBadgeCount(), +})) +jest.mock('#/state/preferences/moderation-opts', () => ({ + useModerationOpts: () => undefined, +})) +jest.mock('#/state/queries/util', () => ({ + truncateAndInvalidate: (...args: unknown[]) => + mockTruncateAndInvalidate(...args), +})) +jest.mock('#/state/session', () => ({ + useAgent: () => mockAgent, + useSession: () => ({hasSession: false}), +})) +jest.mock('../util', () => ({ + fetchPage: (...args: unknown[]) => mockFetchPage(...args), +})) + +import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' +import {type FeedPage} from '../types' +import { + Provider, + useUnreadNotifications, + useUnreadNotificationsApi, +} from '../unread' + +function deferred() { + let resolve!: (value: T) => void + let reject!: (reason: unknown) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return {promise, resolve, reject} +} + +const page: FeedPage = { + cursor: 'next', + seenAt: new Date('2026-09-01T00:00:00.000Z'), + items: [], + priority: false, +} + +describe('notification unread synchronization', () => { + let queryClient: QueryClient + + beforeEach(() => { + jest.clearAllMocks() + mockBroadcastListener = undefined + Object.defineProperty(AppState, 'currentState', { + configurable: true, + value: 'active', + }) + queryClient = new QueryClient({ + defaultOptions: {queries: {retry: false}}, + }) + }) + + function wrapper({children}: PropsWithChildren) { + return ( + + {children} + + ) + } + + function setup() { + return renderHook( + () => ({ + count: useUnreadNotifications(), + api: useUnreadNotificationsApi(), + }), + {wrapper}, + ) + } + + it('uses count-only polling without fetching or hydrating a page', async () => { + mockGetUnreadCount.mockResolvedValue({count: 6}) + const {result} = setup() + + await act(() => result.current.api.checkUnread()) + + expect(result.current.count).toBe('6') + expect(mockFetchPage).not.toHaveBeenCalled() + expect(result.current.api.getCachedUnreadPage()).toBeUndefined() + }) + + it('commits an invalidating page and authoritative count only after both resolve', async () => { + const countRequest = deferred<{count: number}>() + const pageRequest = deferred<{page: FeedPage; indexedAt: string}>() + mockGetUnreadCount.mockReturnValue(countRequest.promise) + mockFetchPage.mockReturnValue(pageRequest.promise) + const {result} = setup() + + let refresh!: Promise + act(() => { + refresh = result.current.api.checkUnread({invalidate: true}) + }) + pageRequest.resolve({ + page, + indexedAt: '2099-09-01T00:00:00.000Z', + }) + await act(async () => Promise.resolve()) + expect(result.current.count).toBe('') + expect(result.current.api.getCachedUnreadPage()).toBeUndefined() + + countRequest.resolve({count: 7}) + await act(() => refresh) + + expect(result.current.count).toBe('7') + expect(result.current.api.getCachedUnreadPage()).toBe(page) + expect(mockFetchPage).toHaveBeenCalledWith( + expect.objectContaining({fetchAdditionalData: true, reasons: []}), + ) + expect(mockTruncateAndInvalidate).toHaveBeenCalledTimes(2) + }) + + it.each(['count', 'page'] as const)( + 'preserves the prior badge and cache when the %s request fails', + async failure => { + mockGetUnreadCount.mockResolvedValueOnce({count: 3}) + mockFetchPage.mockResolvedValueOnce({ + page, + indexedAt: '2026-09-01T00:00:00.000Z', + }) + const {result} = setup() + await act(() => result.current.api.checkUnread({invalidate: true})) + expect(result.current.count).toBe('3') + + const error = new Error(`${failure} failed`) + mockGetUnreadCount.mockImplementationOnce(() => + failure === 'count' + ? Promise.reject(error) + : Promise.resolve({count: 9}), + ) + mockFetchPage.mockImplementationOnce(() => + failure === 'page' + ? Promise.reject(error) + : Promise.resolve({page: {...page, cursor: 'new'}, indexedAt: ''}), + ) + + await expect( + act(() => result.current.api.checkUnread({invalidate: true})), + ).rejects.toBe(error) + expect(result.current.count).toBe('3') + expect(result.current.api.getCachedUnreadPage()).toBe(page) + }, + ) + + it('prevents an older refresh from resurrecting the badge after mark-all-read', async () => { + const countRequest = deferred<{count: number}>() + const pageRequest = deferred<{page: FeedPage; indexedAt: string}>() + mockGetUnreadCount.mockReturnValue(countRequest.promise) + mockFetchPage.mockReturnValue(pageRequest.promise) + const {result} = setup() + + let refresh!: Promise + act(() => { + refresh = result.current.api.checkUnread({invalidate: true}) + }) + await act(() => result.current.api.markAllRead()) + countRequest.resolve({count: 12}) + pageRequest.resolve({ + page, + indexedAt: '2099-09-01T00:00:00.000Z', + }) + await act(() => refresh) + + expect(result.current.count).toBe('') + expect(result.current.api.getCachedUnreadPage()).toBeUndefined() + expect(mockUpdateSeen).toHaveBeenCalledWith( + {seenAt: expect.any(String)}, + HOME_APPVIEW_PINNED_OPTS, + ) + expect(mockResetBadgeCount).toHaveBeenCalledTimes(1) + }) + + it('prevents an older refresh from overwriting a broadcast badge', async () => { + const countRequest = deferred<{count: number}>() + const pageRequest = deferred<{page: FeedPage; indexedAt: string}>() + mockGetUnreadCount.mockReturnValue(countRequest.promise) + mockFetchPage.mockReturnValue(pageRequest.promise) + const {result} = setup() + + let refresh!: Promise + act(() => { + refresh = result.current.api.checkUnread({invalidate: true}) + }) + act(() => { + mockBroadcastListener?.({data: {event: '4'}} as MessageEvent) + }) + expect(result.current.count).toBe('4') + + countRequest.resolve({count: 12}) + pageRequest.resolve({ + page, + indexedAt: '2099-09-01T00:00:00.000Z', + }) + await act(() => refresh) + + expect(result.current.count).toBe('4') + expect(result.current.api.getCachedUnreadPage()).toBeUndefined() + }) +}) diff --git a/src/state/queries/notifications/feed.ts b/src/state/queries/notifications/feed.ts index 97091e31e..745e61081 100644 --- a/src/state/queries/notifications/feed.ts +++ b/src/state/queries/notifications/feed.ts @@ -37,6 +37,7 @@ import { getEmbeddedPost, makeUriMatcher, } from '../util' +import {nextAutoPaginationAttemptCount, shouldAutoPaginate} from './pagination' import {type FeedPage} from './types' import {useUnreadNotificationsApi} from './unread' import {fetchPage} from './util' @@ -247,6 +248,13 @@ export function useNotificationFeedQuery(opts: { if (isLoading || isRefetching) { // During the initial fetch, we want to get an entire page's worth of items. wantedItemCount.current = PAGE_SIZE + autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ + attemptCount: autoPaginationAttemptCount.current, + hasNextPage: !!hasNextPage, + isLoading, + isRefetching, + requestNextPage: false, + }) } else if (isFetchingNextPage) { if (itemCount > wantedItemCount.current) { // We have more items than wantedItemCount, so wantedItemCount must be out of date. @@ -258,13 +266,33 @@ export function useNotificationFeedQuery(opts: { // At this point we're not fetching anymore, so it's time to make a decision. // If we didn't receive enough items from the server, paginate again until we do. if (itemCount < wantedItemCount.current) { - autoPaginationAttemptCount.current++ - if (autoPaginationAttemptCount.current < 50 /* failsafe */) { + const requestNextPage = shouldAutoPaginate({ + hasNextPage, + itemCount, + wantedItemCount: wantedItemCount.current, + attemptCount: autoPaginationAttemptCount.current, + }) + autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ + attemptCount: autoPaginationAttemptCount.current, + hasNextPage, + isLoading, + isRefetching, + requestNextPage, + }) + if (requestNextPage) { query.fetchNextPage() } } else { autoPaginationAttemptCount.current = 0 } + } else { + autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ + attemptCount: autoPaginationAttemptCount.current, + hasNextPage: false, + isLoading, + isRefetching, + requestNextPage: false, + }) } }, [query]) diff --git a/src/state/queries/notifications/pagination.ts b/src/state/queries/notifications/pagination.ts new file mode 100644 index 000000000..044adce63 --- /dev/null +++ b/src/state/queries/notifications/pagination.ts @@ -0,0 +1,36 @@ +const MAX_AUTO_PAGINATION_ATTEMPTS = 50 + +export function shouldAutoPaginate({ + hasNextPage, + itemCount, + wantedItemCount, + attemptCount, +}: { + hasNextPage: boolean + itemCount: number + wantedItemCount: number + attemptCount: number +}): boolean { + return ( + hasNextPage && + itemCount < wantedItemCount && + attemptCount < MAX_AUTO_PAGINATION_ATTEMPTS + ) +} + +export function nextAutoPaginationAttemptCount({ + attemptCount, + hasNextPage, + isLoading, + isRefetching, + requestNextPage, +}: { + attemptCount: number + hasNextPage: boolean + isLoading: boolean + isRefetching: boolean + requestNextPage: boolean +}): number { + if (isLoading || isRefetching || !hasNextPage) return 0 + return requestNextPage ? attemptCount + 1 : attemptCount +} diff --git a/src/state/queries/notifications/unread.tsx b/src/state/queries/notifications/unread.tsx index a3c4426f6..8d89ac6bd 100644 --- a/src/state/queries/notifications/unread.tsx +++ b/src/state/queries/notifications/unread.tsx @@ -14,6 +14,7 @@ import {AppState} from 'react-native' import {useQueryClient} from '@tanstack/react-query' import {EventEmitter} from 'eventemitter3' +import {getUnreadCount} from '#/lib/api/community-notifications' import BroadcastChannel from '#/lib/broadcast' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {resetBadgeCount} from '#/lib/notifications/notifications' @@ -60,6 +61,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { const [numUnread, setNumUnread] = useState('') const checkUnreadRef = useRef(null) + const refreshGenerationRef = useRef(0) const cacheRef = useRef({ usableInFeed: false, syncedAt: new Date(), @@ -95,6 +97,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { // listen for broadcasts useEffect(() => { const listener = ({data}: MessageEvent) => { + refreshGenerationRef.current += 1 cacheRef.current = { usableInFeed: false, syncedAt: new Date(), @@ -120,13 +123,22 @@ export function Provider({children}: React.PropsWithChildren<{}>) { const api = useMemo(() => { return { async markAllRead() { + refreshGenerationRef.current += 1 + const seenAt = cacheRef.current.syncedAt + // update server await agent.app.bsky.notification.updateSeen( - {seenAt: cacheRef.current.syncedAt.toISOString()}, + {seenAt: seenAt.toISOString()}, HOME_APPVIEW_PINNED_OPTS, ) // update & broadcast + cacheRef.current = { + ...cacheRef.current, + usableInFeed: false, + syncedAt: seenAt, + unreadCount: 0, + } setNumUnread('') broadcast.postMessage({event: ''}) resetBadgeCount() @@ -155,22 +167,53 @@ export function Provider({children}: React.PropsWithChildren<{}>) { } // Do not move this without ensuring it gets a symmetrical reset in the finally block. isFetchingRef.current = true + const generation = ++refreshGenerationRef.current - // count - const {page, indexedAt: lastIndexed} = await fetchPage({ - agent, - cursor: undefined, - limit: 40, - queryClient, - moderationOpts, - hideFollowNotifications: undefined, - reasons: [], - - // only fetch subjects when the page is going to be used - // in the notifications query, otherwise skip it - fetchAdditionalData: !!invalidate, - }) - const unreadCount = countUnread(page) + let nextCache: CachedFeedPage + if (invalidate) { + const [{count}, {page, indexedAt: lastIndexed}] = await Promise.all( + [ + getUnreadCount(agent), + fetchPage({ + agent, + cursor: undefined, + limit: 40, + queryClient, + moderationOpts, + hideFollowNotifications: undefined, + reasons: [], + fetchAdditionalData: true, + }), + ], + ) + const now = new Date() + const lastIndexedDate = lastIndexed + ? new Date(lastIndexed) + : undefined + nextCache = { + usableInFeed: true, + data: page, + syncedAt: + !lastIndexedDate || now > lastIndexedDate + ? now + : lastIndexedDate, + unreadCount: count, + } + } else { + const {count} = await getUnreadCount(agent) + nextCache = { + ...cacheRef.current, + usableInFeed: false, + syncedAt: new Date(), + unreadCount: count, + } + } + + if (generation !== refreshGenerationRef.current) { + return + } + + const unreadCount = nextCache.unreadCount const unreadCountStr = unreadCount >= 30 ? '30+' @@ -178,18 +221,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { ? '' : String(unreadCount) - // track last sync - const now = new Date() - const lastIndexedDate = lastIndexed - ? new Date(lastIndexed) - : undefined - cacheRef.current = { - usableInFeed: !!invalidate, // will be used immediately - data: page, - syncedAt: - !lastIndexedDate || now > lastIndexedDate ? now : lastIndexedDate, - unreadCount, - } + cacheRef.current = nextCache // update & broadcast setNumUnread(unreadCountStr) @@ -228,23 +260,6 @@ export function useUnreadNotificationsApi() { return useContext(apiContext) } -function countUnread(page: FeedPage) { - let num = 0 - for (const item of page.items) { - if (!item.notification.isRead) { - num++ - } - if (item.additional) { - for (const item2 of item.additional) { - if (!item2.isRead) { - num++ - } - } - } - } - return num -} - export function invalidateCachedUnreadPage() { emitter.emit('invalidate') } diff --git a/src/state/queries/notifications/util.ts b/src/state/queries/notifications/util.ts index 59e8f5d5f..e6637083c 100644 --- a/src/state/queries/notifications/util.ts +++ b/src/state/queries/notifications/util.ts @@ -16,9 +16,9 @@ import {type QueryClient} from '@tanstack/react-query' import chunk from 'lodash.chunk' import {communityXrpc} from '#/lib/api/community' +import {listNotifications} from '#/lib/api/community-notifications' import {isCommunityPostUri} from '#/lib/api/community-post' import {toPostView} from '#/lib/api/space-views' -import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {labelIsHideableOffense} from '#/lib/moderation' import * as bsky from '#/types/bsky' import {precacheProfile} from '../profile' @@ -64,19 +64,12 @@ export async function fetchPage({ page: FeedPage indexedAt: string | undefined }> { - const res = await agent.app.bsky.notification.listNotifications( - { - limit, - cursor, - reasons, - }, - HOME_APPVIEW_PINNED_OPTS, - ) + const data = await listNotifications(agent, {limit, cursor, reasons}) - const indexedAt = res.data.notifications[0]?.indexedAt + const indexedAt = data.notifications[0]?.indexedAt // filter out notifs by mod rules - const notifs = res.data.notifications.filter( + const notifs = data.notifications.filter( notif => !shouldFilterNotif(notif, moderationOpts, hideFollowNotifications), ) @@ -106,17 +99,17 @@ export async function fetchPage({ } } - let seenAt = res.data.seenAt ? new Date(res.data.seenAt) : new Date() + let seenAt = data.seenAt ? new Date(data.seenAt) : new Date() if (Number.isNaN(seenAt.getTime())) { seenAt = new Date() } return { page: { - cursor: res.data.cursor, + cursor: data.cursor, seenAt, items: notifsGrouped, - priority: res.data.priority ?? false, + priority: data.priority ?? false, }, indexedAt, }