diff --git a/src/analytics/features/types.ts b/src/analytics/features/types.ts index bca196c70..9f0c58149 100644 --- a/src/analytics/features/types.ts +++ b/src/analytics/features/types.ts @@ -14,6 +14,7 @@ export enum Features { ComposerLanguageDetectionEnable = 'composer:language_detection:enable', PostGalleryEmbedEnable = 'post_gallery_embed:enable', NotificationsExpandedProfileCardEnable = 'notifications:expanded_profile_card:enable', + AppviewFallbackMode = 'appview_fallback:mode', AATest = 'aa-test', } diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 4d1b68be5..45bdb622e 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -27,6 +27,16 @@ export type Events = { variationId?: string } + 'appviewFallback:changed': { + active: boolean + trigger: 'flag' + } + 'appviewFallback:probe': { + result: 'eligible' | 'ineligible' | 'unknown' + errorName?: string + status?: number + } + 'account:loggedIn': { logContext: | 'LoginForm' diff --git a/src/components/AppviewFallbackBanner.tsx b/src/components/AppviewFallbackBanner.tsx new file mode 100644 index 000000000..a0a1e3e65 --- /dev/null +++ b/src/components/AppviewFallbackBanner.tsx @@ -0,0 +1,36 @@ +import {View} from 'react-native' +import {Trans} from '@lingui/react/macro' + +import {useAppviewFallback} from '#/state/appview-fallback' +import {atoms as a, useTheme} from '#/alf' +import {Text} from '#/components/Typography' + +/** + * Thin notice shown while app.bsky.* reads are served by the fallback + * appview. Community surfaces stay on the home appview and may lag. + * Rendered inside the shell's safe-area padding, so no inset handling here. + */ +export function AppviewFallbackBanner() { + const t = useTheme() + const active = useAppviewFallback() + + if (!active) return null + + return ( + + + + Compatibility mode — community features and some accounts may be + delayed or unavailable. + + + + ) +} diff --git a/src/locale/locales/en/messages.po b/src/locale/locales/en/messages.po index 2e93d8e32..96ec97115 100644 --- a/src/locale/locales/en/messages.po +++ b/src/locale/locales/en/messages.po @@ -1510,6 +1510,11 @@ msgstr "" msgid "Alt text will be truncated. {MAX_ALT_TEXT, plural, other {Limit: {0} characters.}}" msgstr "" +#: src/screens/Settings/ContentAndMediaSettings.tsx:187 +#: src/screens/Settings/ContentAndMediaSettings.tsx:193 +msgid "Always use Blacksky's servers" +msgstr "Always use Blacksky's servers" + #. placeholder {0}: currentAccount?.email || '(no email)' #: src/screens/Settings/components/DisableEmail2FADialog.tsx:94 msgid "An email has been sent to {0}. It includes a confirmation code which you can enter below." @@ -1902,8 +1907,8 @@ msgstr "Automation label" msgid "Automation Label" msgstr "Automation Label" -#: src/screens/Settings/ContentAndMediaSettings.tsx:118 -#: src/screens/Settings/ContentAndMediaSettings.tsx:124 +#: src/screens/Settings/ContentAndMediaSettings.tsx:126 +#: src/screens/Settings/ContentAndMediaSettings.tsx:132 msgid "Autoplay videos and GIFs" msgstr "" @@ -2302,7 +2307,7 @@ msgstr "" msgid "Camera access needed" msgstr "Camera access needed" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:213 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:217 #: src/components/contacts/screens/GetContacts.tsx:292 #: src/components/contacts/screens/GetContacts.tsx:297 #: src/components/dialogs/EmailDialog/screens/Manage2FA/Enable.tsx:122 @@ -2465,7 +2470,7 @@ msgstr "" msgid "Changes hosting provider" msgstr "" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:179 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:183 msgid "Changes saved" msgstr "" @@ -2776,7 +2781,7 @@ msgstr "Close banner" msgid "Close dialog" msgstr "" -#: src/view/shell/index.web.tsx:100 +#: src/view/shell/index.web.tsx:104 msgid "Close drawer menu" msgstr "" @@ -2868,6 +2873,10 @@ msgstr "Community Builder" msgid "Community Guidelines" msgstr "" +#: src/components/AppviewFallbackBanner.tsx:29 +msgid "Compatibility mode — community features and some accounts may be delayed or unavailable." +msgstr "Compatibility mode — community features and some accounts may be delayed or unavailable." + #: src/screens/Onboarding/StepFinished/index.tsx:333 msgid "Complete onboarding and start using your account" msgstr "" @@ -2958,7 +2967,7 @@ msgstr "" msgid "Contacts removed" msgstr "" -#: src/screens/Settings/ContentAndMediaSettings.tsx:53 +#: src/screens/Settings/ContentAndMediaSettings.tsx:61 msgid "Content & Media" msgstr "" @@ -3269,7 +3278,7 @@ msgid "Could not remove member." msgstr "Could not remove member." #. placeholder {0}: cleanError(error) -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:295 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:299 msgid "Could not save changes: {0}" msgstr "" @@ -3277,7 +3286,7 @@ msgstr "" msgid "Could not share – please try again" msgstr "Could not share – please try again" -#: src/state/queries/notifications/settings.ts:49 +#: src/state/queries/notifications/settings.ts:55 msgid "Could not update notification settings" msgstr "" @@ -4287,13 +4296,13 @@ msgstr "" msgid "Enable this source only" msgstr "" -#: src/screens/Settings/ContentAndMediaSettings.tsx:134 -#: src/screens/Settings/ContentAndMediaSettings.tsx:148 +#: src/screens/Settings/ContentAndMediaSettings.tsx:142 +#: src/screens/Settings/ContentAndMediaSettings.tsx:156 msgid "Enable trending topics" msgstr "" -#: src/screens/Settings/ContentAndMediaSettings.tsx:155 -#: src/screens/Settings/ContentAndMediaSettings.tsx:169 +#: src/screens/Settings/ContentAndMediaSettings.tsx:163 +#: src/screens/Settings/ContentAndMediaSettings.tsx:177 msgid "Enable trending videos in your Discover feed" msgstr "" @@ -4556,8 +4565,8 @@ msgstr "" msgid "Export my profile data" msgstr "Export my profile data" -#: src/screens/Settings/ContentAndMediaSettings.tsx:86 -#: src/screens/Settings/ContentAndMediaSettings.tsx:89 +#: src/screens/Settings/ContentAndMediaSettings.tsx:94 +#: src/screens/Settings/ContentAndMediaSettings.tsx:97 msgid "External media" msgstr "" @@ -4863,7 +4872,7 @@ msgstr "" msgid "Failed to update feeds" msgstr "" -#: src/state/queries/activity-subscriptions.ts:101 +#: src/state/queries/activity-subscriptions.ts:105 msgid "Failed to update notification declaration" msgstr "" @@ -5233,8 +5242,8 @@ msgstr "Following {displayName}" msgid "Following {handle}" msgstr "" -#: src/screens/Settings/ContentAndMediaSettings.tsx:78 -#: src/screens/Settings/ContentAndMediaSettings.tsx:81 +#: src/screens/Settings/ContentAndMediaSettings.tsx:86 +#: src/screens/Settings/ContentAndMediaSettings.tsx:89 msgid "Following feed preferences" msgstr "" @@ -5398,11 +5407,11 @@ msgstr "Get notifications when there's activity on posts you're subscribed to." msgid "Get notified about new posts" msgstr "" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:226 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:230 msgid "Get notified of new posts from {name}" msgstr "" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:233 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:237 msgid "Get notified of this account’s activity" msgstr "" @@ -6329,7 +6338,7 @@ msgstr "" msgid "Keep editing" msgstr "" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:230 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:234 msgid "Keep me posted" msgstr "" @@ -6869,8 +6878,8 @@ msgstr "" msgid "Make sure this is where you intend to go!" msgstr "" -#: src/screens/Settings/ContentAndMediaSettings.tsx:62 -#: src/screens/Settings/ContentAndMediaSettings.tsx:65 +#: src/screens/Settings/ContentAndMediaSettings.tsx:70 +#: src/screens/Settings/ContentAndMediaSettings.tsx:73 msgid "Manage saved feeds" msgstr "" @@ -8227,6 +8236,10 @@ msgstr "" msgid "Options:" msgstr "" +#: src/screens/Settings/ContentAndMediaSettings.tsx:200 +msgid "Opts out of compatibility mode during slowdowns. Feeds may be delayed instead." +msgstr "Opts out of compatibility mode during slowdowns. Feeds may be delayed instead." + #: src/screens/Deactivated.tsx:330 msgid "Or, continue with another account." msgstr "" @@ -8796,8 +8809,8 @@ msgctxt "toast" msgid "Post unpinned" msgstr "" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:257 -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:269 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:261 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:273 #: src/screens/ProfileList/index.tsx:167 #: src/screens/StarterPack/StarterPackScreen.tsx:197 #: src/view/screens/Profile.tsx:264 @@ -9416,8 +9429,8 @@ msgstr "Replied-to message from {senderName}, tap to scroll to it" msgid "Replied-to message, tap to scroll to it" msgstr "Replied-to message, tap to scroll to it" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:274 -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:286 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:278 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:290 #: src/lib/hooks/useNotificationHandler.ts:174 #: src/screens/Settings/NotificationSettings/index.tsx:161 #: src/screens/Settings/NotificationSettings/index.tsx:276 @@ -9835,8 +9848,8 @@ msgstr "" msgid "Save birthdate" msgstr "Save birthdate" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:198 -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:207 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:202 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:211 #: src/screens/SavedFeeds.tsx:122 #: src/screens/SavedFeeds.tsx:126 #: src/screens/SavedFeeds.tsx:314 @@ -11127,7 +11140,7 @@ msgstr "Subscribe to {publicationTitle} on {0}" msgid "Subscribe to @{0} to use these labels:" msgstr "" -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:252 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:256 msgid "Subscribe to account activity" msgstr "" @@ -12090,8 +12103,8 @@ msgstr "" msgid "Thread options" msgstr "" -#: src/screens/Settings/ContentAndMediaSettings.tsx:70 -#: src/screens/Settings/ContentAndMediaSettings.tsx:73 +#: src/screens/Settings/ContentAndMediaSettings.tsx:78 +#: src/screens/Settings/ContentAndMediaSettings.tsx:81 msgid "Thread preferences" msgstr "" @@ -12673,8 +12686,8 @@ msgstr "" msgid "Use in-app browser" msgstr "" -#: src/screens/Settings/ContentAndMediaSettings.tsx:104 -#: src/screens/Settings/ContentAndMediaSettings.tsx:110 +#: src/screens/Settings/ContentAndMediaSettings.tsx:112 +#: src/screens/Settings/ContentAndMediaSettings.tsx:118 msgid "Use in-app browser to open links" msgstr "" @@ -13813,7 +13826,7 @@ msgid "You will be signed out of all your accounts." msgstr "" #. placeholder {0}: sanitizeHandle(profile.handle, '@') -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:140 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:144 msgid "You will no longer receive notifications for {0}" msgstr "" @@ -13860,7 +13873,7 @@ msgid "You'll need to go to the System Settings for Bluesky and give permission msgstr "" #. placeholder {0}: sanitizeHandle(profile.handle, '@') -#: src/components/activity-notifications/SubscribeProfileDialog.tsx:172 +#: src/components/activity-notifications/SubscribeProfileDialog.tsx:176 msgid "You'll start receiving notifications for {0}!" msgstr "" @@ -14038,8 +14051,8 @@ msgstr "" #: src/Navigation.tsx:484 #: src/screens/Search/modules/ExploreInterestsCard.tsx:68 -#: src/screens/Settings/ContentAndMediaSettings.tsx:94 -#: src/screens/Settings/ContentAndMediaSettings.tsx:97 +#: src/screens/Settings/ContentAndMediaSettings.tsx:102 +#: src/screens/Settings/ContentAndMediaSettings.tsx:105 #: src/screens/Settings/InterestsSettings.tsx:49 msgid "Your interests" msgstr "" diff --git a/src/screens/Settings/ContentAndMediaSettings.tsx b/src/screens/Settings/ContentAndMediaSettings.tsx index 3aae0b491..b61a5f1a1 100644 --- a/src/screens/Settings/ContentAndMediaSettings.tsx +++ b/src/screens/Settings/ContentAndMediaSettings.tsx @@ -4,7 +4,12 @@ import {Trans} from '@lingui/react/macro' import {type NativeStackScreenProps} from '@react-navigation/native-stack' import {type CommonNavigatorParams} from '#/lib/routes/types' -import {useAutoplayDisabled, useSetAutoplayDisabled} from '#/state/preferences' +import { + useAlwaysUseHomeAppview, + useAutoplayDisabled, + useSetAlwaysUseHomeAppview, + useSetAutoplayDisabled, +} from '#/state/preferences' import { useInAppBrowser, useSetInAppBrowser, @@ -15,6 +20,7 @@ import { } from '#/state/preferences/trending' import {useTrendingConfig} from '#/state/service-config' import * as SettingsList from '#/screens/Settings/components/SettingsList' +import {atoms as a} from '#/alf' import * as Toggle from '#/components/forms/Toggle' import {Bubbles_Stroke2_Corner2_Rounded as BubblesIcon} from '#/components/icons/Bubble' import {CircleInfo_Stroke2_Corner0_Rounded as CircleInfo} from '#/components/icons/CircleInfo' @@ -37,6 +43,8 @@ export function ContentAndMediaSettingsScreen({}: Props) { const ax = useAnalytics() const autoplayDisabledPref = useAutoplayDisabled() const setAutoplayDisabledPref = useSetAutoplayDisabled() + const alwaysUseHomeAppview = useAlwaysUseHomeAppview() + const setAlwaysUseHomeAppview = useSetAlwaysUseHomeAppview() const inAppBrowserPref = useInAppBrowser() const setUseInAppBrowser = useSetInAppBrowser() const {enabled: trendingEnabled} = useTrendingConfig() @@ -173,6 +181,28 @@ export function ContentAndMediaSettingsScreen({}: Props) { ) : null} + + setAlwaysUseHomeAppview(value)}> + + + + Always use Blacksky's servers + + + + + + + + Opts out of compatibility mode during slowdowns. Feeds may be + delayed instead. + + + diff --git a/src/state/__tests__/appview-fallback-probe.test.ts b/src/state/__tests__/appview-fallback-probe.test.ts new file mode 100644 index 000000000..9edac8e93 --- /dev/null +++ b/src/state/__tests__/appview-fallback-probe.test.ts @@ -0,0 +1,76 @@ +import {type AtpAgent} from '@atproto/api' + +import { + probeFallbackEligibility, + resetProbeCacheForTesting, +} from '../appview-fallback-probe' + +jest.mock('#/analytics/metrics', () => ({ + metrics: {track: jest.fn()}, +})) + +function agentWith(getProfile: jest.Mock, did = 'did:plc:test123'): AtpAgent { + return { + session: {did}, + app: {bsky: {actor: {getProfile}}}, + } as unknown as AtpAgent +} + +describe('probeFallbackEligibility', () => { + beforeEach(() => { + resetProbeCacheForTesting() + }) + + it('eligible when the fallback appview serves the profile', async () => { + const getProfile = jest.fn().mockResolvedValue({data: {}}) + expect(await probeFallbackEligibility(agentWith(getProfile))).toBe( + 'eligible', + ) + }) + + it.each([ + ['AccountTakedown error name', {error: 'AccountTakedown', status: 400}], + ['AccountDeactivated error name', {error: 'AccountDeactivated'}], + ['401 status', {status: 401}], + ['403 status', {status: 403}], + ['suspended message', {message: 'Account has been suspended'}], + ['taken down message', {message: 'this account was taken down'}], + ])('ineligible on %s', async (_name, errShape) => { + const getProfile = jest + .fn() + .mockRejectedValue(Object.assign(new Error(), errShape)) + expect(await probeFallbackEligibility(agentWith(getProfile))).toBe( + 'ineligible', + ) + }) + + it('unknown on network/transient errors, and not cached', async () => { + const getProfile = jest + .fn() + .mockRejectedValueOnce(new Error('Network request failed')) + .mockResolvedValueOnce({data: {}}) + const agent = agentWith(getProfile) + + expect(await probeFallbackEligibility(agent)).toBe('unknown') + expect(await probeFallbackEligibility(agent)).toBe('eligible') + }) + + it('caches a definitive result per DID', async () => { + const getProfile = jest.fn().mockResolvedValue({data: {}}) + const agent = agentWith(getProfile) + + await probeFallbackEligibility(agent) + await probeFallbackEligibility(agent) + expect(getProfile).toHaveBeenCalledTimes(1) + }) + + it('unknown without a session', async () => { + const getProfile = jest.fn() + const agent = { + session: undefined, + app: {bsky: {actor: {getProfile}}}, + } as unknown as AtpAgent + expect(await probeFallbackEligibility(agent)).toBe('unknown') + expect(getProfile).not.toHaveBeenCalled() + }) +}) diff --git a/src/state/__tests__/appview-fallback.test.ts b/src/state/__tests__/appview-fallback.test.ts new file mode 100644 index 000000000..8a26eb8fd --- /dev/null +++ b/src/state/__tests__/appview-fallback.test.ts @@ -0,0 +1,77 @@ +import {type BskyAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import { + BLUESKY_FALLBACK_PROXY_HEADER, + BLUESKY_PROXY_HEADER, + HOME_PROXY_HEADER, +} from '#/lib/constants' +import { + isFallbackActive, + setFallbackActive, + subscribe, +} from '../appview-fallback' + +function mocks() { + const configureProxy = jest.fn() + const resetQueries = jest.fn().mockResolvedValue(undefined) + return { + agent: {configureProxy} as unknown as BskyAgent, + queryClient: {resetQueries} as unknown as QueryClient, + configureProxy, + resetQueries, + } +} + +describe('appview fallback state', () => { + afterEach(() => { + const {agent, queryClient} = mocks() + setFallbackActive(false, agent, queryClient) + BLUESKY_PROXY_HEADER.set(HOME_PROXY_HEADER) + }) + + it('activating flips the global header, live agent, and resets the cache', () => { + const {agent, queryClient, configureProxy, resetQueries} = mocks() + + setFallbackActive(true, agent, queryClient) + + expect(isFallbackActive()).toBe(true) + expect(BLUESKY_PROXY_HEADER.get()).toBe(BLUESKY_FALLBACK_PROXY_HEADER) + expect(configureProxy).toHaveBeenCalledWith(BLUESKY_FALLBACK_PROXY_HEADER) + expect(resetQueries).toHaveBeenCalledTimes(1) + }) + + it('deactivating restores the home appview header', () => { + const first = mocks() + setFallbackActive(true, first.agent, first.queryClient) + + const second = mocks() + setFallbackActive(false, second.agent, second.queryClient) + + expect(isFallbackActive()).toBe(false) + expect(BLUESKY_PROXY_HEADER.get()).toBe(HOME_PROXY_HEADER) + expect(second.configureProxy).toHaveBeenCalledWith(HOME_PROXY_HEADER) + }) + + it('setting the same value is a no-op', () => { + const {agent, queryClient, configureProxy, resetQueries} = mocks() + + setFallbackActive(false, agent, queryClient) + + expect(configureProxy).not.toHaveBeenCalled() + expect(resetQueries).not.toHaveBeenCalled() + }) + + it('notifies subscribers on change and stops after unsubscribe', () => { + const {agent, queryClient} = mocks() + const fn = jest.fn() + const unsub = subscribe(fn) + + setFallbackActive(true, agent, queryClient) + expect(fn).toHaveBeenCalledTimes(1) + + unsub() + setFallbackActive(false, agent, queryClient) + expect(fn).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/state/appview-fallback-controller.tsx b/src/state/appview-fallback-controller.tsx new file mode 100644 index 000000000..3e49806ff --- /dev/null +++ b/src/state/appview-fallback-controller.tsx @@ -0,0 +1,65 @@ +import {useCallback, useEffect} from 'react' +import {AppState} from 'react-native' +import {useQueryClient} from '@tanstack/react-query' + +import {setFallbackActive} from '#/state/appview-fallback' +import {probeFallbackEligibility} from '#/state/appview-fallback-probe' +import {useAlwaysUseHomeAppview} from '#/state/preferences' +import {useAgent, useSession} from '#/state/session' +import {Features, features} from '#/analytics/features' + +const RECHECK_INTERVAL = 3 * 60e3 + +type FallbackMode = 'auto' | 'force-fallback' | 'force-primary' + +function getMode(): FallbackMode { + const value = features.getFeatureValue( + Features.AppviewFallbackMode, + 'force-primary', + ) + if (value === 'force-fallback' || value === 'auto') return value + return 'force-primary' +} + +/** + * Headless component that decides whether app.bsky.* reads should be served + * by the fallback appview. v1: driven entirely by the feature flag ('auto' + * behaves as 'force-primary' until the lag poller lands). + */ +export function AppviewFallbackController() { + const agent = useAgent() + const queryClient = useQueryClient() + const {hasSession} = useSession() + const alwaysUseHomeAppview = useAlwaysUseHomeAppview() + + const evaluate = useCallback(async () => { + if (!hasSession) { + setFallbackActive(false, agent, queryClient) + return + } + const wantsFallback = getMode() === 'force-fallback' + + if (!wantsFallback || alwaysUseHomeAppview) { + setFallbackActive(false, agent, queryClient) + return + } + + const eligibility = await probeFallbackEligibility(agent) + setFallbackActive(eligibility === 'eligible', agent, queryClient) + }, [agent, queryClient, hasSession, alwaysUseHomeAppview]) + + useEffect(() => { + void evaluate() + + const interval = setInterval(() => void evaluate(), RECHECK_INTERVAL) + const sub = AppState.addEventListener('change', state => { + if (state === 'active') void evaluate() + }) + return () => { + clearInterval(interval) + sub.remove() + } + }, [evaluate]) + + return null +} diff --git a/src/state/appview-fallback-probe.ts b/src/state/appview-fallback-probe.ts new file mode 100644 index 000000000..2b3472a73 --- /dev/null +++ b/src/state/appview-fallback-probe.ts @@ -0,0 +1,68 @@ +import {type AtpAgent} from '@atproto/api' + +import {BLUESKY_FALLBACK_PROXY_HEADER} from '#/lib/constants' +import {metrics} from '#/analytics/metrics' + +export type ProbeResult = 'eligible' | 'ineligible' | 'unknown' + +const cache = new Map() + +const INELIGIBLE_ERROR_NAMES = ['AccountTakedown', 'AccountDeactivated'] +const INELIGIBLE_MESSAGE_FRAGMENTS = ['suspended', 'taken down', 'deactivated'] + +/** + * Whether this account can read from the fallback appview at all. Accounts + * taken down there get errors or silently stripped context, so they must + * stay on the home appview. Matches broadly: any auth rejection or takedown + * signal counts, mirroring isAuthorModerated in microcosm-fallback. + */ +export async function probeFallbackEligibility( + agent: AtpAgent, +): Promise { + const did = agent.session?.did + if (!did) return 'unknown' + + const cached = cache.get(did) + if (cached && cached !== 'unknown') return cached + + let result: ProbeResult + let errorName: string | undefined + let status: number | undefined + try { + await agent.app.bsky.actor.getProfile( + {actor: did}, + {headers: {'atproto-proxy': BLUESKY_FALLBACK_PROXY_HEADER}}, + ) + result = 'eligible' + } catch (e) { + const err = e as {status?: number; error?: string} + errorName = typeof err?.error === 'string' ? err.error : undefined + status = typeof err?.status === 'number' ? err.status : undefined + result = classifyProbeError(e) + } + + cache.set(did, result) + metrics.track('appviewFallback:probe', {result, errorName, status}) + return result +} + +function classifyProbeError(e: unknown): ProbeResult { + const err = e as {status?: number; error?: string; message?: string} + const status = typeof err?.status === 'number' ? err.status : undefined + const name = typeof err?.error === 'string' ? err.error : '' + const message = typeof err?.message === 'string' ? err.message : '' + + if (status === 401 || status === 403) return 'ineligible' + if (INELIGIBLE_ERROR_NAMES.includes(name)) return 'ineligible' + const lower = message.toLowerCase() + if (INELIGIBLE_MESSAGE_FRAGMENTS.some(f => lower.includes(f))) { + return 'ineligible' + } + // Anything else (network failure, transient 5xx) leaves eligibility + // undetermined; don't activate fallback on it. + return 'unknown' +} + +export function resetProbeCacheForTesting() { + cache.clear() +} diff --git a/src/state/appview-fallback.ts b/src/state/appview-fallback.ts new file mode 100644 index 000000000..cec640b95 --- /dev/null +++ b/src/state/appview-fallback.ts @@ -0,0 +1,55 @@ +import {useSyncExternalStore} from 'react' +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import { + BLUESKY_FALLBACK_PROXY_HEADER, + BLUESKY_PROXY_HEADER, + HOME_PROXY_HEADER, +} from '#/lib/constants' +import {logger} from '#/logger' +import {metrics} from '#/analytics/metrics' + +export type FallbackMode = 'auto' | 'force-fallback' | 'force-primary' + +let active = false +const listeners = new Set<() => void>() + +export function isFallbackActive(): boolean { + return active +} + +export function subscribe(fn: () => void): () => void { + listeners.add(fn) + return () => { + listeners.delete(fn) + } +} + +/** + * Switch app.bsky.* reads between the home appview and the fallback appview. + * + * Flips the global proxy header (used by all agents at construction), points + * the live agent at the new appview, and resets the query cache — pagination + * cursors are appview-specific, so a cached page from one appview must never + * be continued against the other. + */ +export function setFallbackActive( + next: boolean, + agent: AtpAgent, + queryClient: QueryClient, +): void { + if (next === active) return + active = next + const header = next ? BLUESKY_FALLBACK_PROXY_HEADER : HOME_PROXY_HEADER + BLUESKY_PROXY_HEADER.set(header) + agent.configureProxy(header) + void queryClient.resetQueries() + logger.info('appview fallback changed', {active: next}) + metrics.track('appviewFallback:changed', {active: next, trigger: 'flag'}) + listeners.forEach(fn => fn()) +} + +export function useAppviewFallback(): boolean { + return useSyncExternalStore(subscribe, isFallbackActive, isFallbackActive) +} diff --git a/src/state/persisted/schema.ts b/src/state/persisted/schema.ts index 19b7feab6..bb2781844 100644 --- a/src/state/persisted/schema.ts +++ b/src/state/persisted/schema.ts @@ -145,6 +145,7 @@ const schema = z.object({ hideFollowNotifications: z.boolean().optional(), showLinkInHandle: z.boolean().optional(), blackskyOnlyDefault: z.boolean().optional(), + alwaysUseHomeAppview: z.boolean().optional(), /** @deprecated */ mutedThreads: z.array(z.string()), @@ -205,6 +206,7 @@ export const defaults: Schema = { repostCarouselEnabled: false, hideFollowNotifications: false, showLinkInHandle: false, + alwaysUseHomeAppview: false, } export function tryParse(rawData: string): Schema | undefined { diff --git a/src/state/preferences/always-use-home-appview.tsx b/src/state/preferences/always-use-home-appview.tsx new file mode 100644 index 000000000..32f2b1554 --- /dev/null +++ b/src/state/preferences/always-use-home-appview.tsx @@ -0,0 +1,50 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useState, +} from 'react' + +import * as persisted from '#/state/persisted' + +type StateContext = boolean +type SetContext = (v: boolean) => void + +const stateContext = createContext( + Boolean(persisted.defaults.alwaysUseHomeAppview), +) +stateContext.displayName = 'AlwaysUseHomeAppviewStateContext' +const setContext = createContext((_: boolean) => {}) +setContext.displayName = 'AlwaysUseHomeAppviewSetContext' + +export function Provider({children}: {children: React.ReactNode}) { + const [state, setState] = useState( + Boolean(persisted.get('alwaysUseHomeAppview')), + ) + + const setStateWrapped = useCallback( + (value: persisted.Schema['alwaysUseHomeAppview']) => { + setState(Boolean(value)) + void persisted.write('alwaysUseHomeAppview', value) + }, + [setState], + ) + + useEffect(() => { + return persisted.onUpdate('alwaysUseHomeAppview', next => { + setState(Boolean(next)) + }) + }, [setStateWrapped]) + + return ( + + + {children} + + + ) +} + +export const useAlwaysUseHomeAppview = () => useContext(stateContext) +export const useSetAlwaysUseHomeAppview = () => useContext(setContext) diff --git a/src/state/preferences/index.tsx b/src/state/preferences/index.tsx index 37e08f149..48c8a8cd3 100644 --- a/src/state/preferences/index.tsx +++ b/src/state/preferences/index.tsx @@ -1,4 +1,5 @@ import {Provider as AltTextRequiredProvider} from './alt-text-required' +import {Provider as AlwaysUseHomeAppviewProvider} from './always-use-home-appview' import {Provider as AutoplayProvider} from './autoplay' import {Provider as BlackskyOnlyDefaultProvider} from './blacksky-only-default' import {Provider as DisableHapticsProvider} from './disable-haptics' @@ -16,6 +17,10 @@ export { useRequireAltTextEnabled, useSetRequireAltTextEnabled, } from './alt-text-required' +export { + useAlwaysUseHomeAppview, + useSetAlwaysUseHomeAppview, +} from './always-use-home-appview' export {useAutoplayDisabled, useSetAutoplayDisabled} from './autoplay' export { useBlackskyOnlyDefault, @@ -45,7 +50,9 @@ export function Provider({children}: React.PropsWithChildren<{}>) { - {children} + + {children} + diff --git a/src/view/shell/index.tsx b/src/view/shell/index.tsx index a6473f5f6..242a17d58 100644 --- a/src/view/shell/index.tsx +++ b/src/view/shell/index.tsx @@ -11,6 +11,7 @@ import {useIntentHandler} from '#/lib/hooks/useIntentHandler' import {useNotificationsHandler} from '#/lib/hooks/useNotificationHandler' import {useNotificationsRegistration} from '#/lib/notifications/notifications' import {isStateAtTabRoot} from '#/lib/routes/helpers' +import {AppviewFallbackController} from '#/state/appview-fallback-controller' import {useDialogFullyExpandedCountContext} from '#/state/dialogs' import {useProfileEnrichment} from '#/state/queries/profile-enrichment' import {useSession} from '#/state/session' @@ -25,6 +26,7 @@ import {Deactivated} from '#/screens/Deactivated' import {Takendown} from '#/screens/Takendown' import {atoms as a, select, useTheme} from '#/alf' import {setSystemUITheme} from '#/alf/util/systemUI' +import {AppviewFallbackBanner} from '#/components/AppviewFallbackBanner' import {EmailDialog} from '#/components/dialogs/EmailDialog' import {InAppBrowserConsentDialog} from '#/components/dialogs/InAppBrowserConsent' import {LinkWarningDialog} from '#/components/dialogs/LinkWarning' @@ -95,9 +97,11 @@ function ShellInner() { + + diff --git a/src/view/shell/index.web.tsx b/src/view/shell/index.web.tsx index d4db6034b..99cb0ee0f 100644 --- a/src/view/shell/index.web.tsx +++ b/src/view/shell/index.web.tsx @@ -7,6 +7,7 @@ import {RemoveScrollBar} from 'react-remove-scroll-bar' import {useIntentHandler} from '#/lib/hooks/useIntentHandler' import {type NavigationProp} from '#/lib/routes/types' +import {AppviewFallbackController} from '#/state/appview-fallback-controller' import {useSession} from '#/state/session' import {useIsDrawerOpen, useSetDrawerOpen} from '#/state/shell' import {useCloseAllActiveElements} from '#/state/util' @@ -14,6 +15,7 @@ import {ErrorBoundary} from '#/view/com/util/ErrorBoundary' import {Deactivated} from '#/screens/Deactivated' import {Takendown} from '#/screens/Takendown' import {atoms as a, select, useBreakpoints, useTheme} from '#/alf' +import {AppviewFallbackBanner} from '#/components/AppviewFallbackBanner' import {EmailDialog} from '#/components/dialogs/EmailDialog' import {LinkWarningDialog} from '#/components/dialogs/LinkWarning' import {MutedWordsDialog} from '#/components/dialogs/MutedWords' @@ -48,8 +50,10 @@ function ShellInner() { return ( <> + +