diff --git a/src/screens/Profile/components/ProfileStatusError.tsx b/src/screens/Profile/components/ProfileStatusError.tsx new file mode 100644 index 000000000..3b76eb53c --- /dev/null +++ b/src/screens/Profile/components/ProfileStatusError.tsx @@ -0,0 +1,178 @@ +import {View} from 'react-native' +import { + FontAwesomeIcon, + type FontAwesomeIconStyle, +} from '@fortawesome/react-native-fontawesome' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import {usePalette} from '#/lib/hooks/usePalette' +import { + type ProfileErrorKind, + type ProfileStatusSource, + useProfileStatusSource, +} from '#/state/queries/profile-status' +import {atoms as a, useTheme} from '#/alf' +import * as Layout from '#/components/Layout' +import {InlineLinkText} from '#/components/Link' +import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' + +export function ProfileStatusError({ + kind, + didOrHandle, + did, +}: { + kind: Exclude + /** The identifier the user typed (handle, did, or 'me'-resolved did) — shown in messages */ + didOrHandle: string + /** The DID, when known — used to look up which labeler suspended the account */ + did?: string +}) { + const {_} = useLingui() + const enableSourceLookup = kind === 'suspendedOrTakedown' && !!did + const {data: source, isLoading: isSourceLoading} = useProfileStatusSource( + did, + {enabled: enableSourceLookup}, + ) + + let title: string + let body: React.ReactNode + switch (kind) { + case 'notFound': + title = _(msg`Not found`) + body = ( + + We couldn't find an account at {didOrHandle}. + + ) + break + case 'deactivated': + title = _(msg`Account deactivated`) + body = ( + + This account has been deactivated by its owner. + + ) + break + case 'suspendedOrTakedown': + title = _(msg`Account suspended`) + if (isSourceLoading) { + body = ( + + + + Account is suspended. + + + ) + } else if (source && (source.appealUrl || source.email)) { + body = + } else if (source) { + body = ( + + Account is suspended by @{source.handle}. + + ) + } else { + body = ( + + Account is suspended. + + ) + } + break + } + + return {body} +} + +function SuspendedMessage({source}: {source: ProfileStatusSource}) { + if (source.appealUrl) { + return ( + + + Account is suspended by{' '} + + @{source.handle} + + . Click{' '} + + here + {' '} + to submit an appeal. + + + ) + } + return ( + + + Account is suspended by{' '} + + @{source.handle} + + , email{' '} + + {source.email} + {' '} + to appeal. + + + ) +} + +function ProfileStatusErrorShell({ + title, + children, +}: { + title: string + children: React.ReactNode +}) { + const t = useTheme() + const pal = usePalette('default') + return ( + + + + + + Profile + + + + + + + + + + + + {title} + + {children} + + + ) +} diff --git a/src/state/queries/microcosm-fallback.ts b/src/state/queries/microcosm-fallback.ts index a288b0fc0..11de360ce 100644 --- a/src/state/queries/microcosm-fallback.ts +++ b/src/state/queries/microcosm-fallback.ts @@ -117,35 +117,6 @@ export async function fetchConstellationCounts( } } -/** - * Detect if error is AppView-related (suspended user, not found, etc.) - * - * IMPORTANT: This determines whether fallback should be triggered. - * We should NOT trigger fallback for intentional blocking/privacy errors. - */ -export function isAppViewError(error: any): boolean { - if (!error) return false - - const msg = error.message?.toLowerCase() || '' - - // Do NOT trigger fallback for intentional blocking - // "Requester has blocked actor" means the user intentionally blocked someone - // This is NOT an AppView outage - it's privacy enforcement - if (msg.includes('blocked actor')) return false - if (msg.includes('requester has blocked')) return false - if (msg.includes('blocking')) return false - - // Check HTTP status codes - if (error.status === 400 || error.status === 404) return true - - // Check error messages for actual AppView issues - if (msg.includes('not found')) return true - if (msg.includes('suspended')) return true - if (msg.includes('could not locate')) return true - - return false -} - /** * Build viewer state for fallback profiles * Checks local block/mute cache to populate viewer relationship fields @@ -180,22 +151,6 @@ function buildViewerState( return viewer } -/** - * Build a BlockedPost stub to match AppView behavior - * Returns the same structure as app.bsky.feed.defs#blockedPost - */ -function buildBlockedPost(uri: string): any { - return { - $type: 'app.bsky.feed.defs#blockedPost', - uri, - blocked: true, - author: { - did: new AtUri(uri).host, - handle: '', - }, - } -} - /** * Build a BlockedProfile stub to match AppView behavior * Returns a minimal profile view indicating the profile is blocked @@ -272,60 +227,6 @@ export async function buildSyntheticProfileView( } } -/** - * Build synthetic PostView from PDS + Constellation data - * - * SECURITY: Inherits block/mute checking from buildSyntheticProfileView. - * If the author is blocked, returns BlockedPost stub to match AppView behavior. - */ -export async function buildSyntheticPostView( - queryClient: QueryClient, - atUri: string, - authorDid: string, - authorHandle: string, -): Promise { - // Check if author is blocked first, before fetching any data - const viewer = buildViewerState(queryClient, authorDid) - if (viewer.blocking) { - console.log('[Fallback] Returning blocked post stub for', atUri) - return buildBlockedPost(atUri) - } - - const record = await fetchRecordViaSlingshot(atUri) - if (!record) return null - - const counts = await fetchConstellationCounts(atUri) - // Build profile view (will return basic info since not blocked) - const profileView = await buildSyntheticProfileView( - queryClient, - authorDid, - authorHandle, - ) - - // Get viewer state for the post itself (like, repost status) - // For now we just use empty viewer as we can't determine these from PDS - const postViewer = {} - - const embeds = resolveRecordEmbeds(authorDid, record.value) - - return { - $type: 'app.bsky.feed.defs#postView', - uri: atUri, - cid: record.cid, - author: profileView, - record: record.value, - embed: embeds.length > 0 ? embeds[0] : undefined, - indexedAt: record.value?.createdAt || new Date().toISOString(), - likeCount: counts.likeCount, - repostCount: counts.repostCount, - replyCount: counts.replyCount, - quoteCount: counts.quoteCount, - viewer: postViewer, // Post-level viewer state (likes, reposts, etc) - labels: [], - __fallbackMode: true, // Mark as fallback data - } -} - // Blacksky moderation account DID - labels from this account are authoritative const BLACKSKY_MOD_DID = 'did:plc:d2mkddsbmnrgr3domzg5qexf' @@ -581,94 +482,3 @@ export async function buildSyntheticEmbedViewRecord( __fallbackMode: true, } } - -/** - * Build synthetic feed page from PDS data - * This is used for infinite queries that need paginated results - * - * IMPORTANT: This function bypasses Slingshot and fetches directly from the user's PDS - * because Slingshot does not support the `com.atproto.repo.listRecords` endpoint needed - * for bulk record fetching. - * - * Trade-off: No caching benefit from Slingshot, but we can still provide author feed - * functionality for AppView-suspended users. - * - * Each post in the feed will trigger: - * - 1 record fetch via Slingshot (for the full post data, cached) - * - 1 Constellation request (for engagement counts) - * - Profile fetch (cached after first request) - * - * SECURITY: Respects block/mute relationships. If author is blocked, the feed will be empty. - */ -export async function buildSyntheticFeedPage( - queryClient: QueryClient, - did: string, - pdsUrl: string, - cursor?: string, -): Promise { - // Check if this author is blocked before fetching any posts - const viewer = buildViewerState(queryClient, did) - if (viewer.blocking) { - console.log('[Fallback] Author is blocked, returning empty feed for', did) - // Return empty feed to prevent viewing blocked user's posts via fallback - return { - feed: [], - cursor: undefined, - __fallbackMode: true, - __blocked: true, - } - } - - try { - const limit = 25 - const cursorParam = cursor ? `&cursor=${encodeURIComponent(cursor)}` : '' - - // Fetch posts directly from PDS using com.atproto.repo.listRecords - // NOTE: This bypasses Slingshot because listRecords is not available there - const url = `${pdsUrl}/xrpc/com.atproto.repo.listRecords?repo=${did}&collection=app.bsky.feed.post&limit=${limit}${cursorParam}` - const res = await fetch(url) - - if (!res.ok) { - console.error( - '[Fallback] Failed to fetch author feed from PDS:', - res.statusText, - ) - return null - } - - const data = await res.json() - - // Build FeedViewPost array from records - const feed = await Promise.all( - data.records.map(async (record: any) => { - const postView = await buildSyntheticPostView( - queryClient, - record.uri, - did, - '', // Handle will be resolved in buildSyntheticPostView - ) - - if (!postView) return null - - // Wrap in FeedViewPost format - return { - $type: 'app.bsky.feed.defs#feedViewPost', - post: postView, - feedContext: undefined, - } - }), - ) - - // Filter out null results - const validFeed = feed.filter(item => item !== null) - - return { - feed: validFeed, - cursor: data.cursor, - __fallbackMode: true, // Mark as fallback data - } - } catch (e) { - console.error('[Fallback] Failed to build synthetic feed page:', e) - return null - } -} diff --git a/src/state/queries/profile-status.ts b/src/state/queries/profile-status.ts new file mode 100644 index 000000000..1a61c2b42 --- /dev/null +++ b/src/state/queries/profile-status.ts @@ -0,0 +1,117 @@ +import {XRPCError} from '@atproto/api' +import {useQuery} from '@tanstack/react-query' + +import {STALE} from '#/state/queries' +import {useAgent} from '#/state/session' +import {BLACKSKY_LABELER} from '#/state/session/additional-moderation-authorities' + +export const BLUESKY_MOD_DID = 'did:plc:ar7c4by46qjdydhdevvrndac' +export const BLUESKY_MOD_EMAIL = 'moderation@blueskyweb.xyz' + +export const BLACKSKY_MOD_DID = BLACKSKY_LABELER +export const BLACKSKY_MOD_APPEAL_URL = + 'https://blackskyweb.xyz/about/support/moderation-appeal/' + +export type ProfileErrorKind = + | 'deactivated' + | 'suspendedOrTakedown' + | 'notFound' + | 'unknown' + +const SUSPEND_LABEL_VALUES = new Set(['!takedown', '!suspend']) +const KNOWN_MOD_DIDS = [BLUESKY_MOD_DID, BLACKSKY_MOD_DID] + +export function classifyProfileError(error: unknown): ProfileErrorKind { + if (!error) return 'unknown' + + let code: string | undefined + let msg = '' + if (error instanceof XRPCError) { + code = error.error + msg = (error.message || '').toLowerCase() + } else if (error instanceof Error) { + msg = error.message.toLowerCase() + } else { + msg = String(error).toLowerCase() + } + + if (code === 'AccountDeactivated' || msg.includes('deactivated')) { + return 'deactivated' + } + if ( + code === 'AccountTakedown' || + code === 'AccountSuspended' || + msg.includes('suspended') || + msg.includes('taken down') + ) { + return 'suspendedOrTakedown' + } + if ( + code === 'ActorNotFound' || + msg.includes('not found') || + msg.includes('could not find') || + msg.includes('could not locate') || + msg.includes('unable to resolve handle') + ) { + return 'notFound' + } + return 'unknown' +} + +export type ProfileStatusSource = { + src: string + handle: string + email: string + appealUrl?: string +} + +export const RQKEY_STATUS_SOURCE = (did: string) => [ + 'profile-status-source', + did, +] + +export function useProfileStatusSource( + did: string | undefined, + {enabled = true}: {enabled?: boolean} = {}, +) { + const agent = useAgent() + return useQuery({ + queryKey: RQKEY_STATUS_SOURCE(did ?? ''), + staleTime: STALE.MINUTES.FIVE, + retry: false, + enabled: !!did && enabled, + queryFn: async () => { + if (!did) return null + + const labelsRes = await agent.com.atproto.label.queryLabels({ + uriPatterns: [did], + sources: KNOWN_MOD_DIDS, + }) + + const label = labelsRes.data.labels.find( + l => !l.neg && SUSPEND_LABEL_VALUES.has(l.val), + ) + if (!label) return null + + const src = label.src + let email = '' + let appealUrl: string | undefined + if (src === BLACKSKY_MOD_DID) { + appealUrl = BLACKSKY_MOD_APPEAL_URL + } else if (src === BLUESKY_MOD_DID) { + email = BLUESKY_MOD_EMAIL + } + + let handle = src + try { + const profileRes = await agent.app.bsky.actor.getProfile({actor: src}) + handle = profileRes.data.handle || src + } catch { + // Best-effort: fall back to the DID if the labeler profile can't be + // resolved on our AppView. + } + + return {src, handle, email, appealUrl} + }, + }) +} diff --git a/src/state/queries/profile.ts b/src/state/queries/profile.ts index 0409394ee..cea591349 100644 --- a/src/state/queries/profile.ts +++ b/src/state/queries/profile.ts @@ -10,6 +10,14 @@ import { type ComAtprotoRepoUploadBlob, type Un$Typed, } from '@atproto/api' +import { + type InfiniteData, + keepPreviousData, + type QueryClient, + useMutation, + useQuery, + useQueryClient, +} from '@tanstack/react-query' import {uploadBlob} from '#/lib/api' import {until} from '#/lib/async/until' @@ -21,6 +29,7 @@ import {type ImageMeta} from '#/state/gallery' import {STALE} from '#/state/queries' import {resetProfilePostsQueries} from '#/state/queries/post-feed' import {RQKEY as PROFILE_FOLLOWS_RQKEY} from '#/state/queries/profile-follows' +import {classifyProfileError} from '#/state/queries/profile-status' import { unstableCacheProfileView, useUnstableProfileViewCache, @@ -39,15 +48,6 @@ import { import {RQKEY_ROOT as RQKEY_LIST_CONVOS} from './messages/list-conversations' import {RQKEY as RQKEY_MY_BLOCKED} from './my-blocked-accounts' import {RQKEY as RQKEY_MY_MUTED} from './my-muted-accounts' -import { - type InfiniteData, - keepPreviousData, - prefetchQueryWithFallback, - type QueryClient, - useMutation, - useQuery, - useQueryClient, -} from './useQueryWithFallback' export * from '#/state/queries/unstable-profile-cache' /** @@ -115,9 +115,8 @@ export function useProfileQuery({ return getUnstableProfile(did) as AppBskyActorDefs.ProfileViewDetailed }, enabled: !!did, - enableFallback: true, - fallbackType: 'profile', - fallbackIdentifier: did, + retry: (failureCount, error) => + classifyProfileError(error) === 'unknown' && failureCount < 1, }) } @@ -193,7 +192,7 @@ export function usePrefetchProfileQuery() { const queryClient = useQueryClient() const prefetchProfileQuery = useCallback( async (did: string) => { - await prefetchQueryWithFallback(queryClient, { + await queryClient.prefetchQuery({ staleTime: STALE.SECONDS.THIRTY, queryKey: RQKEY(did), queryFn: async () => { @@ -224,9 +223,6 @@ export function usePrefetchProfileQuery() { return profile }, - enableFallback: true, - fallbackType: 'profile', - fallbackIdentifier: did, }) }, [queryClient, agent], diff --git a/src/state/queries/resolve-uri.ts b/src/state/queries/resolve-uri.ts index 4778e873e..397c70601 100644 --- a/src/state/queries/resolve-uri.ts +++ b/src/state/queries/resolve-uri.ts @@ -35,6 +35,7 @@ const resolvedDidQueryOptions = ( return profile?.did }, enabled: !!didOrHandle, + retry: false, }) export function useResolveUriQuery(uri: string | undefined) { diff --git a/src/state/queries/usePostThread/index.ts b/src/state/queries/usePostThread/index.ts index adb6b60a0..ceb87fe47 100644 --- a/src/state/queries/usePostThread/index.ts +++ b/src/state/queries/usePostThread/index.ts @@ -1,13 +1,7 @@ import {useCallback, useMemo, useState} from 'react' -import {AppBskyUnspeccedDefs, AtUri} from '@atproto/api' +import {useQuery, useQueryClient} from '@tanstack/react-query' import {useModerationOpts} from '#/state/preferences/moderation-opts' -import { - buildSyntheticPostView, - isAuthorModerated, - isPostModerated, - resolveIdentityViaSlingshot, -} from '#/state/queries/microcosm-fallback' import {useThreadPreferences} from '#/state/queries/preferences/useThreadPreferences' import { LINEAR_VIEW_BELOW, @@ -37,57 +31,11 @@ import {useAgent, useSession} from '#/state/session' import {useMergeThreadgateHiddenReplies} from '#/state/threadgate-hidden-replies' import {useBreakpoints} from '#/alf' import {IS_WEB} from '#/env' -import {useQuery, useQueryClient} from '../useQueryWithFallback' export * from '#/state/queries/usePostThread/context' export {useUpdatePostThreadThreadgateQueryCache} from '#/state/queries/usePostThread/queryCache' export * from '#/state/queries/usePostThread/types' -/** - * Attempt to load a thread post via Slingshot when the AppView returns NotFound. - * Returns a UsePostThreadQueryResult with a single synthetic post, or null. - */ -async function tryThreadFallback( - queryClient: import('@tanstack/react-query').QueryClient, - anchorUri: string, -): Promise { - try { - const urip = new AtUri(anchorUri) - const identity = await resolveIdentityViaSlingshot(urip.host) - if (!identity) return null - - // Check moderation before allowing fallback - const [authorModerated, postModerated] = await Promise.all([ - isAuthorModerated(identity.did), - isPostModerated(anchorUri), - ]) - - if (authorModerated || postModerated) { - console.log('[Thread Fallback] Blocked by moderation for', anchorUri) - return null - } - - const post = await buildSyntheticPostView( - queryClient, - anchorUri, - identity.did, - identity.handle, - ) - if (!post) return null - - console.log('[Thread Fallback] Loaded post via Slingshot for', anchorUri) - - return { - thread: [views.postViewToThreadPlaceholder(post)], - threadgate: undefined, - hasOtherReplies: false, - } as UsePostThreadQueryResult - } catch (e) { - console.error('[Thread Fallback] Failed:', e) - return null - } -} - export function usePostThread({anchor}: {anchor?: string}) { const qc = useQueryClient() const agent = useAgent() @@ -130,16 +78,6 @@ export function usePostThread({anchor}: {anchor?: string}) { sort: sort, }) - // Check if the anchor post came back as NotFound -- try Slingshot fallback - const anchorItem = data.thread?.find(t => t.depth === 0) - if ( - anchorItem && - AppBskyUnspeccedDefs.isThreadItemNotFound(anchorItem.value) - ) { - const fallbackThread = await tryThreadFallback(qc, anchor!) - if (fallbackThread) return fallbackThread - } - /* * Initialize `ctx.meta` to track if we know we have additional replies * we could fetch once we hit the end. @@ -186,9 +124,6 @@ export function usePostThread({anchor}: {anchor?: string}) { } return data }, - enableFallback: true, - fallbackType: 'thread', - fallbackIdentifier: anchor, }) const thread = useMemo(() => query.data?.thread || [], [query.data?.thread]) diff --git a/src/state/queries/useQueryWithFallback.ts b/src/state/queries/useQueryWithFallback.ts deleted file mode 100644 index aca833837..000000000 --- a/src/state/queries/useQueryWithFallback.ts +++ /dev/null @@ -1,632 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import {AtUri} from '@atproto/api' -import { - type QueryClient, - type QueryFunctionContext, - useInfiniteQuery as useTanstackInfiniteQuery, - type UseInfiniteQueryOptions, - type UseInfiniteQueryResult, - useQuery as useTanstackQuery, - useQueryClient, - type UseQueryOptions, - type UseQueryResult, -} from '@tanstack/react-query' - -import { - buildSyntheticFeedPage, - buildSyntheticPostView, - buildSyntheticProfileView, - isAppViewError, - isAuthorModerated, - isPostModerated, - resolveIdentityViaSlingshot, -} from './microcosm-fallback' -import {postViewToThreadPlaceholder} from './usePostThread/views' - -/** - * Extended query options that include fallback configuration - */ -export interface UseQueryWithFallbackOptions< - TData, - TError, -> extends UseQueryOptions { - /** - * Enable automatic fallback to PDS + Microcosm on AppView errors - * @default true for profile/post queries, false otherwise - */ - enableFallback?: boolean - - /** - * Type of query for fallback (helps determine how to reconstruct data) - * @default 'generic' - */ - fallbackType?: 'profile' | 'post' | 'thread' | 'feed' | 'generic' - - /** - * AT URI or DID to use for fallback (extracted from queryKey if not provided) - */ - fallbackIdentifier?: string -} - -/** - * Extended infinite query options that include fallback configuration - */ -export interface UseInfiniteQueryWithFallbackOptions< - TData, - TError, - TPageParam, -> extends UseInfiniteQueryOptions< - TData, - TError, - TData, - TData, - any, - TPageParam -> { - /** - * Enable automatic fallback to PDS + Microcosm on AppView errors - * @default false - */ - enableFallback?: boolean - - /** - * Type of query for fallback (helps determine how to reconstruct data) - * @default 'generic' - */ - fallbackType?: 'profile' | 'post' | 'thread' | 'feed' | 'generic' - - /** - * AT URI or DID to use for fallback (extracted from queryKey if not provided) - */ - fallbackIdentifier?: string -} - -/** - * Custom useQuery hook with automatic PDS + Microcosm fallback - * - * Wraps TanStack Query's useQuery and adds fallback logic: - * 1. Tries original queryFn (hits AppView) - * 2. On AppView errors, attempts Slingshot + Constellation fallback - * 3. Returns synthetic data compatible with AppView format - * - * @example - * ```typescript - * export function useProfileQuery({did}) { - * const agent = useAgent() - * return useQuery({ - * queryKey: ['profile', did], - * queryFn: async () => { - * const res = await agent.getProfile({actor: did}) - * return res.data - * }, - * enableFallback: true, - * fallbackType: 'profile', - * fallbackIdentifier: did, - * }) - * } - * ``` - */ -export function useQuery( - options: UseQueryWithFallbackOptions, -): UseQueryResult { - const { - queryFn, - enableFallback = false, - fallbackType = 'generic', - fallbackIdentifier, - ...restOptions - } = options - - const queryClient = useQueryClient() - - // Wrap the original queryFn with fallback logic - const wrappedQueryFn = async (context: QueryFunctionContext) => { - if (!queryFn || typeof queryFn !== 'function') return undefined as TData - - try { - // Try the original query function (AppView) - return (await (queryFn as Function)(context)) as Awaited - } catch (error: any) { - // If fallback is disabled or this isn't an AppView error, re-throw - if (!enableFallback || !isAppViewError(error)) { - throw error - } - - console.log('[Fallback] Attempting PDS + Microcosm fallback:', { - fallbackType, - fallbackIdentifier, - error: error.message, - }) - - // Extract identifier from queryKey if not provided - const identifier = - fallbackIdentifier || - extractIdentifierFromQueryKey(context.queryKey as unknown[]) - - if (!identifier) { - console.error('[Fallback] No identifier found for fallback') - throw error - } - - // Attempt fallback based on query type - try { - const fallbackData = await attemptFallback( - queryClient, - fallbackType, - identifier, - ) - - if (!fallbackData) { - throw error // Fallback failed, re-throw original error - } - - console.log( - '[Fallback] Successfully retrieved data via PDS + Microcosm', - ) - return fallbackData as TData - } catch (fallbackError) { - console.error('[Fallback] Failed:', fallbackError) - throw error // Fallback failed, re-throw original error - } - } - } - - // Use the wrapped queryFn with TanStack Query - return useTanstackQuery({ - ...restOptions, - queryFn: wrappedQueryFn, - }) -} - -/** - * Custom useInfiniteQuery hook with automatic PDS + Microcosm fallback - * - * Wraps TanStack Query's useInfiniteQuery and adds fallback logic for paginated queries. - * This is essential for feeds, followers, following lists, and other infinite scroll features. - * - * @example - * ```typescript - * export function usePostFeedQuery({did}) { - * const agent = useAgent() - * return useInfiniteQuery({ - * queryKey: ['post-feed', did], - * queryFn: async ({pageParam}) => { - * const res = await agent.getAuthorFeed({actor: did, cursor: pageParam}) - * return res.data - * }, - * initialPageParam: undefined, - * getNextPageParam: (lastPage) => lastPage.cursor, - * enableFallback: true, - * fallbackType: 'feed', - * fallbackIdentifier: did, - * }) - * } - * ``` - */ -export function useInfiniteQuery< - TData = unknown, - TError = Error, - TPageParam = unknown, ->( - options: UseInfiniteQueryWithFallbackOptions, -): UseInfiniteQueryResult { - const { - queryFn, - enableFallback = false, - fallbackType = 'generic', - fallbackIdentifier, - ...restOptions - } = options - - const queryClient = useQueryClient() - - // Wrap the original queryFn with fallback logic - const wrappedQueryFn = async ( - context: QueryFunctionContext, - ) => { - if (!queryFn || typeof queryFn !== 'function') return undefined as TData - - try { - // Try the original query function (AppView) - return (await (queryFn as Function)(context)) as Awaited - } catch (error: any) { - // If fallback is disabled or this isn't an AppView error, re-throw - if (!enableFallback || !isAppViewError(error)) { - throw error - } - - const pageParam = 'pageParam' in context ? context.pageParam : undefined - - console.log( - '[Fallback] Attempting PDS + Microcosm fallback (infinite):', - { - fallbackType, - fallbackIdentifier, - pageParam, - error: error.message, - }, - ) - - // Extract identifier from queryKey if not provided - const identifier = - fallbackIdentifier || - extractIdentifierFromQueryKey(context.queryKey as unknown[]) - - if (!identifier) { - console.error('[Fallback] No identifier found for fallback') - throw error - } - - // Attempt fallback based on query type - try { - const fallbackData = await attemptInfiniteFallback( - queryClient, - fallbackType, - identifier, - pageParam as string | undefined, - ) - - if (!fallbackData) { - throw error // Fallback failed, re-throw original error - } - - console.log( - '[Fallback] Successfully retrieved paginated data via PDS + Microcosm', - ) - return fallbackData as TData - } catch (fallbackError) { - console.error('[Fallback] Failed:', fallbackError) - throw error // Fallback failed, re-throw original error - } - } - } - - // Use the wrapped queryFn with TanStack Query - return useTanstackInfiniteQuery({ - ...restOptions, - queryFn: wrappedQueryFn, - }) -} - -/** - * Extract DID/handle/URI from query key - */ -function extractIdentifierFromQueryKey(queryKey: unknown[]): string | null { - // Query keys typically look like: ['profile', did] or ['post', uri] - if (Array.isArray(queryKey) && queryKey.length >= 2) { - const identifier = queryKey[1] - if (typeof identifier === 'string') { - return identifier - } - } - return null -} - -/** - * Attempt to fetch data using PDS + Microcosm fallback - */ -async function attemptFallback( - queryClient: QueryClient, - type: string, - identifier: string, -): Promise { - switch (type) { - case 'profile': { - // identifier is a DID or handle - const identity = await resolveIdentityViaSlingshot(identifier) - if (!identity) return null - - return await buildSyntheticProfileView( - queryClient, - identity.did, - identity.handle, - ) - } - - case 'post': { - // identifier is an AT URI - const urip = new AtUri(identifier) - const identity = await resolveIdentityViaSlingshot(urip.host) - if (!identity) return null - - return await buildSyntheticPostView( - queryClient, - identifier, - identity.did, - identity.handle, - ) - } - - case 'thread': { - const urip = new AtUri(identifier) - const identity = await resolveIdentityViaSlingshot(urip.host) - if (!identity) return null - - // Check moderation before allowing thread fallback - const [authorModerated, postModerated] = await Promise.all([ - isAuthorModerated(identity.did), - isPostModerated(identifier), - ]) - - if (authorModerated || postModerated) { - console.log('[Fallback] Thread blocked by moderation for', identifier) - return null - } - - const post = await buildSyntheticPostView( - queryClient, - identifier, - identity.did, - identity.handle, - ) - if (!post) return null - - // Return V2 thread format expected by usePostThread - return { - thread: [postViewToThreadPlaceholder(post)], - threadgate: undefined, - hasOtherReplies: false, - } - } - - default: - // Generic fallback not supported - return null - } -} - -/** - * Attempt to fetch paginated data using PDS + Microcosm fallback - * This is used by useInfiniteQuery for feeds, followers, etc. - */ -async function attemptInfiniteFallback( - queryClient: QueryClient, - type: string, - identifier: string, - cursor?: string, -): Promise { - switch (type) { - case 'feed': { - // identifier is a DID - fetch author feed from PDS - const identity = await resolveIdentityViaSlingshot(identifier) - if (!identity) return null - - return await buildSyntheticFeedPage( - queryClient, - identity.did, - identity.pds, - cursor, - ) - } - - case 'profile': - case 'post': - case 'thread': { - // These types don't support pagination in fallback mode - // Return empty page to gracefully handle the error - return { - feed: [], - cursor: undefined, - } - } - - default: - // Generic fallback not supported - return null - } -} - -/** - * Fetch query data with automatic PDS + Microcosm fallback - * - * This is the fetch equivalent of useQuery with fallback support. - * Used for imperatively fetching data when you need the result immediately. - * - * @example - * ```typescript - * const post = await fetchQueryWithFallback(queryClient, { - * queryKey: RQKEY(uri), - * queryFn: async () => { - * const res = await agent.getPosts({uris: [uri]}) - * return res.data.posts[0] - * }, - * enableFallback: true, - * fallbackType: 'post', - * fallbackIdentifier: uri, - * }) - * ``` - */ -export async function fetchQueryWithFallback( - queryClient: QueryClient, - options: UseQueryWithFallbackOptions, -): Promise { - const { - queryFn, - enableFallback = false, - fallbackType = 'generic', - fallbackIdentifier, - queryKey, - ...restOptions - } = options - - // Wrap the original queryFn with fallback logic - const wrappedQueryFn = async (context: QueryFunctionContext) => { - if (!queryFn || typeof queryFn !== 'function') return undefined as TData - - try { - // Try the original query function (AppView) - return (await (queryFn as Function)(context)) as Awaited - } catch (error: any) { - // If fallback is disabled or this isn't an AppView error, re-throw - if (!enableFallback || !isAppViewError(error)) { - throw error - } - - console.log('[Fallback] Attempting PDS + Microcosm fallback (fetch):', { - fallbackType, - fallbackIdentifier, - error: error.message, - }) - - // Extract identifier from queryKey if not provided - const identifier = - fallbackIdentifier || - extractIdentifierFromQueryKey(context.queryKey as unknown[]) - - if (!identifier) { - console.error('[Fallback] No identifier found for fallback') - throw error - } - - // Attempt fallback based on query type - try { - const fallbackData = await attemptFallback( - queryClient, - fallbackType, - identifier, - ) - - if (!fallbackData) { - throw error // Fallback failed, re-throw original error - } - - console.log( - '[Fallback] Successfully retrieved data via PDS + Microcosm (fetch)', - ) - return fallbackData as TData - } catch (fallbackError) { - console.error('[Fallback] Failed:', fallbackError) - throw error // Fallback failed, re-throw original error - } - } - } - - // Use the wrapped queryFn with TanStack Query's fetchQuery - return await queryClient.fetchQuery({ - ...restOptions, - queryKey, - queryFn: wrappedQueryFn, - }) -} - -/** - * Prefetch query data with automatic PDS + Microcosm fallback - * - * This is the prefetch equivalent of useQuery with fallback support. - * Used for pre-loading data before it's needed (e.g., on hover interactions). - * - * @example - * ```typescript - * export function usePrefetchProfileQuery() { - * const agent = useAgent() - * const queryClient = useQueryClient() - * const prefetchProfileQuery = useCallback( - * async (did: string) => { - * await prefetchQueryWithFallback(queryClient, { - * staleTime: STALE.SECONDS.THIRTY, - * queryKey: RQKEY(did), - * queryFn: async () => { - * const res = await agent.getProfile({actor: did || ''}) - * return res.data - * }, - * enableFallback: true, - * fallbackType: 'profile', - * fallbackIdentifier: did, - * }) - * }, - * [queryClient, agent], - * ) - * return prefetchProfileQuery - * } - * ``` - */ -export async function prefetchQueryWithFallback< - TData = unknown, - TError = Error, ->( - queryClient: QueryClient, - options: UseQueryWithFallbackOptions, -): Promise { - const { - queryFn, - enableFallback = false, - fallbackType = 'generic', - fallbackIdentifier, - queryKey, - ...restOptions - } = options - - // Wrap the original queryFn with fallback logic - const wrappedQueryFn = async (context: QueryFunctionContext) => { - if (!queryFn || typeof queryFn !== 'function') return undefined as TData - - try { - // Try the original query function (AppView) - return (await (queryFn as Function)(context)) as Awaited - } catch (error: any) { - // If fallback is disabled or this isn't an AppView error, re-throw - if (!enableFallback || !isAppViewError(error)) { - throw error - } - - console.log( - '[Fallback] Attempting PDS + Microcosm fallback (prefetch):', - { - fallbackType, - fallbackIdentifier, - error: error.message, - }, - ) - - // Extract identifier from queryKey if not provided - const identifier = - fallbackIdentifier || - extractIdentifierFromQueryKey(context.queryKey as unknown[]) - - if (!identifier) { - console.error('[Fallback] No identifier found for fallback') - throw error - } - - // Attempt fallback based on query type - try { - const fallbackData = await attemptFallback( - queryClient, - fallbackType, - identifier, - ) - - if (!fallbackData) { - throw error // Fallback failed, re-throw original error - } - - console.log( - '[Fallback] Successfully retrieved data via PDS + Microcosm (prefetch)', - ) - return fallbackData as TData - } catch (fallbackError) { - console.error('[Fallback] Failed:', fallbackError) - throw error // Fallback failed, re-throw original error - } - } - } - - // Use the wrapped queryFn with TanStack Query's prefetchQuery - await queryClient.prefetchQuery({ - ...restOptions, - queryKey, - queryFn: wrappedQueryFn, - }) -} - -// Re-export other hooks and utilities from TanStack Query for convenience -export { - type InfiniteData, - keepPreviousData, - type QueryClient, - type QueryKey, - useMutation, - type UseMutationOptions, - type UseMutationResult, - useQueryClient, -} from '@tanstack/react-query' diff --git a/src/state/session/additional-moderation-authorities.ts b/src/state/session/additional-moderation-authorities.ts index afbafe805..d09288ff9 100644 --- a/src/state/session/additional-moderation-authorities.ts +++ b/src/state/session/additional-moderation-authorities.ts @@ -1,4 +1,4 @@ -import {BskyAgent} from '@atproto/api' +import {Agent} from '@atproto/api' import {logger} from '#/logger' @@ -79,7 +79,7 @@ export function configureAdditionalModerationAuthorities() { additionalLabelers.push(BLACKSKY_LABELER) const appLabelers = Array.from( - new Set([...BskyAgent.appLabelers, ...additionalLabelers]), + new Set([...Agent.appLabelers, ...additionalLabelers]), ) logger.info(`applying mod authorities`, { @@ -87,5 +87,5 @@ export function configureAdditionalModerationAuthorities() { appLabelers, }) - BskyAgent.configure({appLabelers}) + Agent.configure({appLabelers}) } diff --git a/src/state/session/moderation.ts b/src/state/session/moderation.ts index a10d7ba58..b5665f66f 100644 --- a/src/state/session/moderation.ts +++ b/src/state/session/moderation.ts @@ -1,5 +1,4 @@ -import {type Agent} from '@atproto/api' -import {BSKY_LABELER_DID, BskyAgent} from '@atproto/api' +import {Agent, BSKY_LABELER_DID, type BskyAgent} from '@atproto/api' import {IS_TEST_USER} from '#/lib/constants' import {getNoAppLabelers} from '../preferences/no-app-labelers' @@ -45,8 +44,8 @@ export async function configureModerationForAccount( } function switchToBskyAppLabeler() { - BskyAgent.configure({ - appLabelers: getNoAppLabelers() ? [] : [BSKY_LABELER_DID], + Agent.configure({ + appLabelers: getNoAppLabelers() ? [] : [BSKY_LABELER_DID, BLACKSKY_LABELER], }) } @@ -58,6 +57,6 @@ async function trySwitchToTestAppLabeler(agent: Agent | BskyAgent) { )?.data.did if (did) { console.warn('USING TEST ENV MODERATION') - BskyAgent.configure({appLabelers: [did]}) + Agent.configure({appLabelers: [did]}) } } diff --git a/src/view/screens/Profile.tsx b/src/view/screens/Profile.tsx index a8e07cb59..e70b893d0 100644 --- a/src/view/screens/Profile.tsx +++ b/src/view/screens/Profile.tsx @@ -32,6 +32,7 @@ import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useLabelerInfoQuery} from '#/state/queries/labeler' import {resetProfilePostsQueries} from '#/state/queries/post-feed' import {useProfileQuery} from '#/state/queries/profile' +import {classifyProfileError} from '#/state/queries/profile-status' import {useResolveDidQuery} from '#/state/queries/resolve-uri' import {useAgent, useSession} from '#/state/session' import {ProfileFeedgens} from '#/view/com/feeds/ProfileFeedgens' @@ -40,6 +41,7 @@ import {PagerWithHeader} from '#/view/com/pager/PagerWithHeader' import {ErrorScreen} from '#/view/com/util/error/ErrorScreen' import {FAB} from '#/view/com/util/fab/FAB' import {type ListRef} from '#/view/com/util/List' +import {ProfileStatusError} from '#/screens/Profile/components/ProfileStatusError' import {ProfileHeader, ProfileHeaderLoading} from '#/screens/Profile/Header' import {ProfileFeedSection} from '#/screens/Profile/Sections/Feed' import {ProfileLabelsSection} from '#/screens/Profile/Sections/Labels' @@ -125,6 +127,18 @@ function ProfileScreenInner({route}: Props) { ) } if (resolveError || profileError) { + const kind = classifyProfileError(profileError ?? resolveError) + if (kind !== 'unknown') { + return ( + + + + ) + } return ( ) } + if (profile?.status?.status === 'deactivated') { + return ( + + + + ) + } if (profile && moderationOpts) { return (