:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mobile): request inbox scopes and handle missing grants (#128837)
Chris Volzerbcd1aea48dc5
diff --git a/products/mobile/docs/AUTH.md b/products/mobile/docs/AUTH.mdindex b2f63fe383b3..ef07ad134e08 100644--- a/products/mobile/docs/AUTH.md+++ b/products/mobile/docs/AUTH.md@@ -75,7 +75,7 @@ The selected organization's current server membership determines the approval coThe app requests exactly these scopes (`OAUTH_SCOPES` in `src/auth/oauth.ts`):-`openid profile email user:read user:write organization:read project:read task:read task:write conversation:write today:read query:read dashboard:read insight:read file_system_shortcut:write error_tracking:read error_tracking:write session_recording:read replay_scanner:read replay_scanner:write`+`openid profile email user:read user:write organization:read project:read task:read task:write inbox:read inbox:write conversation:write today:read query:read dashboard:read insight:read file_system_shortcut:write error_tracking:read error_tracking:write session_recording:read replay_scanner:read replay_scanner:write`| Scope | Used by || ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |@@ -83,7 +83,8 @@ The app requests exactly these scopes (`OAUTH_SCOPES` in `src/auth/oauth.ts`):| `user:write` | push token register and unregister || `organization:read` | `GET /api/organizations/{id}/` for the project list || `project:read` | project-scoped reads |-| `task:read`, `task:write` | reports, hand-off, runs, notification routing |+| `task:read`, `task:write` | hand-off, runs, notification routing; task actions keep these scopes alongside the inbox scopes |+| `inbox:read`, `inbox:write` | inbox lists, report details, artefacts, reviewers, read states, and triage; Today report pages also need `today:read` || `conversation:write` | chat || `today:read` | `GET today/briefing/` and `GET today/reports/{id}/page/`. Without it both return 403 and the inbox always falls back to the signals report list. || `query:read` | `POST query/` for the live report metrics and charts, and in Views for web analytics, compare on an insight, and the people and recordings at a chart point. Without it the query returns 403, and the report shows each metric's saved value and series instead. |@@ -114,12 +115,20 @@ Nothing signs that user out: the inbox and chats keep working.Errors and Sessions use the same states through `useFeatureAccess('errors' | 'replay')` and `<ViewsReauthState feature=…>`.A 403 is reported per feature (`reportScopeError(error, feature)`), so a refused issue read does not lock Views.+Inbox lists and report screens use the same states with `feature="inbox"`.+They wait for an API scope rejection before asking for a new sign-in, because the server can still accept older `task:*` grants through its inbox scope fallback.+When that fallback is removed, a missing inbox scope shows the sign-in prompt, including for a failed background refresh of a cached report.+A refresh cannot add scopes to an existing grant. OAuth users must sign in again to receive the inbox scopes; personal API keys need those scopes added to the key.+### Server-side ceilingEach OAuth application has a scope ceiling: `OAuthApplication.scopes` plus `optional_scopes` (`posthog/models/oauth.py`).An empty ceiling, or one containing `@default`, allows every unprivileged scope; any other ceiling is an exact allow-list.The production app rows are not visible from this repository, so check them in Django admin when the app adds a scope.+Before removing the inbox scope fallback, check that the mobile OAuth applications in each region allow `inbox:read` and `inbox:write`, including development and preview registrations.+Keep `task:read` and `task:write`, because the app still uses task actions.+- `/authorize` normally does not reject an out-of-ceiling scope. It drops it and issues the rest, so the usual symptom is a 403 on the feature that needs it, for example the inbox never showing the Today briefing.- When the server does answer `invalid_scope` (on the authorize redirect or the token endpoint), the sign-in screen says "This app's OAuth registration is missing a permission. Ask an admin to update it."diff --git a/products/mobile/src/api/scopeErrors.test.ts b/products/mobile/src/api/scopeErrors.test.tsindex 9914f712efc3..44db6aaa39fc 100644--- a/products/mobile/src/api/scopeErrors.test.ts+++ b/products/mobile/src/api/scopeErrors.test.ts@@ -1,5 +1,5 @@import { ApiError } from './client'-import { missingFeatureScope, missingScope, missingViewsScope } from './scopeErrors'+import { missingFeatureScope, missingScope, missingViewsScope, type ScopedFeature } from './scopeErrors'describe('missingScope', () => {test.each<[string, unknown, string | null]>([@@ -33,9 +33,11 @@ describe('missingScope', () => {expect(missingViewsScope(granted)).toBe(expected)})- test.each<[string, string[], 'errors' | 'replay', string | null]>([+ test.each<[string, string[], ScopedFeature, string | null]>([['a write that covers the error tracking read', ['error_tracking:write'], 'errors', null],['a grant without the summary scopes', ['session_recording:read'], 'replay', 'replay_scanner:read'],+ ['an inbox write that covers the read', ['inbox:write'], 'inbox', null],+ ['a read-only inbox grant', ['inbox:read'], 'inbox', 'inbox:write'],])('finds the missing feature scope in %s', (_name, granted, feature, expected) => {expect(missingFeatureScope(granted, feature)).toBe(expected)})diff --git a/products/mobile/src/api/scopeErrors.ts b/products/mobile/src/api/scopeErrors.tsindex 9ea050c435e0..0c352dbc10e9 100644--- a/products/mobile/src/api/scopeErrors.ts+++ b/products/mobile/src/api/scopeErrors.ts@@ -27,12 +27,13 @@ export const ERRORS_SCOPES = ['error_tracking:read', 'error_tracking:write'] as/** The scopes the sessions list and session screen need. `replay_scanner` covers the AI summary. */export const REPLAY_SCOPES = ['session_recording:read', 'replay_scanner:read', 'replay_scanner:write'] as const-export type ScopedFeature = 'views' | 'errors' | 'replay'+export type ScopedFeature = 'views' | 'errors' | 'replay' | 'inbox'export const FEATURE_SCOPES: Record<ScopedFeature, readonly string[]> = {views: VIEWS_SCOPES,errors: ERRORS_SCOPES,replay: REPLAY_SCOPES,+ inbox: ['inbox:read', 'inbox:write'],}/** The first scope of `feature` a grant lacks, or null for an unknown grant. */diff --git a/products/mobile/src/auth/oauth.ts b/products/mobile/src/auth/oauth.tsindex 9ad7b826cee9..0e85d6a50350 100644--- a/products/mobile/src/auth/oauth.ts+++ b/products/mobile/src/auth/oauth.ts@@ -19,6 +19,8 @@ export const OAUTH_SCOPES = ['project:read','task:read','task:write',+ 'inbox:read',+ 'inbox:write','conversation:write','today:read','query:read',diff --git a/products/mobile/src/features/inbox/InboxScreen.tsx b/products/mobile/src/features/inbox/InboxScreen.tsxindex 702b265a287b..bb4303fc0bc2 100644--- a/products/mobile/src/features/inbox/InboxScreen.tsx+++ b/products/mobile/src/features/inbox/InboxScreen.tsx@@ -17,6 +17,8 @@ import { bottomOffset, topOffset, useScreenInsets } from '@/ui/useScreenInsets'import { apiErrorKind } from '../report/reportAnalytics'import { TABS_HEADER_BOTTOM } from '../tabs/TabsHeader'import { useTabHeader } from '../tabs/tabHeaderStore'+import { useFeatureAccess } from '../views/useViewsAccess'+import { ViewsReauthState } from '../views/ViewsReauthState'import type { RowAnchor } from './contextMenuPlacement'import { isDefaultInboxFilters } from './filters'import { useInboxItems, useSetReportRead } from './hooks'@@ -47,8 +49,9 @@ export function InboxScreen(): ReactElement {}, []))const filters = useInboxFilters()+ const access = useFeatureAccess('inbox')const query = useInboxItems({ refreshWhileVisible: focused, filters })- const prefetch = usePrefetchReports(query.data, focused)+ const prefetch = usePrefetchReports(query.data, focused && access.state === 'ok')const [rowMenu, setRowMenu] = useState<RowMenuTarget | null>(null)const [filtersOpen, setFiltersOpen] = useState(false)const listRef = useRef<FlatList<InboxItem>>(null)@@ -146,33 +149,36 @@ export function InboxScreen(): ReactElement {[paired, now, openReport, openRowMenu, setRead])- const empty = query.isLoading ? (- <LoadingView label="Loading your inbox" />- ) : query.isError ? (- <StateView- icon={<WarningIcon size={iconSizes.empty} color={colors.tertiary} />}- title="Couldn't load your inbox"- message={query.error?.message ?? 'Check your connection and try again.'}- actionLabel="Try again"- onAction={() => refresh('retry')}- testID="inbox-error"- />- ) : isFilteredEmpty ? (- <StateView- icon={<FilterIcon size={iconSizes.empty} color={colors.tertiary} />}- title="No reports match these filters"- actionLabel="Clear filters"- onAction={clearFilters}- testID="inbox-filtered-empty"- />- ) : query.totalCount > 0 ? null : (- <StateView- icon={<InboxIcon size={iconSizes.empty} color={colors.tertiary} />}- title="Nothing needs you right now"- message="New reports show up here when PostHog finds something worth a look."- testID="inbox-empty"- />- )+ const empty =+ access.state !== 'ok' ? (+ <ViewsReauthState access={access} feature="inbox" />+ ) : query.isLoading ? (+ <LoadingView label="Loading your inbox" />+ ) : query.isError ? (+ <StateView+ icon={<WarningIcon size={iconSizes.empty} color={colors.tertiary} />}+ title="Couldn't load your inbox"+ message={query.error?.message ?? 'Check your connection and try again.'}+ actionLabel="Try again"+ onAction={() => refresh('retry')}+ testID="inbox-error"+ />+ ) : isFilteredEmpty ? (+ <StateView+ icon={<FilterIcon size={iconSizes.empty} color={colors.tertiary} />}+ title="No reports match these filters"+ actionLabel="Clear filters"+ onAction={clearFilters}+ testID="inbox-filtered-empty"+ />+ ) : query.totalCount > 0 ? null : (+ <StateView+ icon={<InboxIcon size={iconSizes.empty} color={colors.tertiary} />}+ title="Nothing needs you right now"+ message="New reports show up here when PostHog finds something worth a look."+ testID="inbox-empty"+ />+ )return (<View style={[styles.screen, { flexDirection: 'row' }]} testID="inbox-screen">@@ -186,7 +192,7 @@ export function InboxScreen(): ReactElement {><FlatListref={listRef}- data={query.data ?? []}+ data={access.state === 'ok' ? (query.data ?? []) : []}keyExtractor={keyFor}renderItem={renderItem}ListEmptyComponent={empty}diff --git a/products/mobile/src/features/inbox/hooks.test.tsx b/products/mobile/src/features/inbox/hooks.test.tsxindex 2fee0ef8032e..e1f60e9da802 100644--- a/products/mobile/src/features/inbox/hooks.test.tsx+++ b/products/mobile/src/features/inbox/hooks.test.tsx@@ -7,6 +7,7 @@ import { inboxCacheKey, type SavedInbox } from '@/api/readCacheKeys'import { INBOX_PAGE_SIZE, postReadStates, reportKeys } from '@/api/reports'import { useAuthStore } from '@/auth/authStore'import { type DataMode, useDemoMode } from '@/demo/demoMode'+import { useFeatureAccess, useScopeErrorStore } from '@/features/views/useViewsAccess'import { inboxFromReports } from '@/model/adapters/inbox'import { reportFixture } from '@/model/adapters/testFixtures'@@ -46,6 +47,7 @@ describe('inbox hooks', () => {const posted: unknown[] = []beforeEach(() => {+ useScopeErrorStore.getState().clear()posted.length = 0useSnoozeStore.setState({ entries: {} })jest.spyOn(AppState, 'addEventListener').mockReturnValue({ remove: () => undefined })@@ -65,6 +67,27 @@ describe('inbox hooks', () => {jest.restoreAllMocks()})+ test.each([+ ["API key missing required scope 'inbox:read'", 'reauth'],+ ['You do not have permission to perform this action.', 'ok'],+ ])('handles an inbox rejection: %s', async (detail, state) => {+ globalThis.fetch = jest.fn(async () => jsonResponse({ detail }, 403)) as typeof fetch+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )+ const { result, unmount } = renderHook(() => ({ query: useInboxItems(), access: useFeatureAccess('inbox') }), {+ wrapper,+ })+ try {+ await waitFor(() => expect(result.current.query.isError).toBe(true))+ expect(result.current.access.state).toBe(state)+ } finally {+ unmount()+ client.clear()+ }+ })+test('marks each report read on a fast Prev/Next', async () => {const queryClient = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })const wrapper = ({ children }: { children: ReactNode }): ReactElement => (diff --git a/products/mobile/src/features/inbox/hooks.ts b/products/mobile/src/features/inbox/hooks.tsindex 87e1953d5ff2..88f510c3a021 100644--- a/products/mobile/src/features/inbox/hooks.ts+++ b/products/mobile/src/features/inbox/hooks.ts@@ -39,6 +39,7 @@ import type { InboxItem, QueryState } from '@/model/types'import { useAppActive } from '../handoff/useTaskRun'import { useSnoozeEntries, wakeSnooze } from '../snooze/hooks'import { applySnoozes } from '../snooze/snoozeEntries'+import { reportScopeError, useFeatureAccess } from '../views/useViewsAccess'import { applyInboxFilters, DEFAULT_INBOX_FILTERS, type InboxFilters, isDefaultInboxFilters } from './filters'/** The inbox list, which loads one page of reports at a time. */@@ -133,7 +134,8 @@ function useLiveInboxItems(const scope = useProjectScope()const offline = useConnectivity((state) => state.status === 'offline')const appActive = useAppActive()- const active = enabled && scope !== null+ const access = useFeatureAccess('inbox')+ const active = enabled && scope !== null && access.state === 'ok'const snoozes = useSnoozeEntries()const queryClient = useQueryClient()const [pulling, setPulling] = useState(false)@@ -148,6 +150,9 @@ function useLiveInboxItems(getNextPageParam: nextOffset,enabled: active,})+ useEffect(() => {+ reportScopeError(list.error, 'inbox')+ }, [list.error])const saved = useQuery<SavedInbox>({ queryKey: inboxCacheKey(scope), queryFn: skipToken })const reports = useMemo(() => (list.data ? reportsFromPages(list.data.pages) : undefined), [list.data])const baseItems = useMemo(() => (reports ? inboxFromReports(reports) : saved.data?.items), [reports, saved.data])diff --git a/products/mobile/src/features/offlineCache.test.ts b/products/mobile/src/features/offlineCache.test.tsindex c1267e94500f..143d6c0e67d7 100644--- a/products/mobile/src/features/offlineCache.test.ts+++ b/products/mobile/src/features/offlineCache.test.ts@@ -91,7 +91,7 @@ describe('authenticated offline-cache lifecycle', () => {mockDigestGates.clear()mockValues.clear()mockReads.length = 0- useScopeErrorStore.setState({ reported: { views: null, errors: null, replay: null } })+ useScopeErrorStore.setState({ reported: { views: null, errors: null, replay: null, inbox: null } })queryClient.clear()useItemErrors.setState({ errors: {} })useAuthStore.setState({@@ -272,11 +272,11 @@ describe('authenticated offline-cache lifecycle', () => {mockValues.set(`${account()}.2`, JSON.stringify(saved))let stop = installOfflineCache()await waitFor(() => expect(queryClient.getQueryData(first)).toBeDefined())- useScopeErrorStore.setState({ reported: { views: 'insights:read', errors: null, replay: null } })+ useScopeErrorStore.setState({ reported: { views: 'insights:read', errors: null, replay: null, inbox: null } })await waitFor(() => expect(mockValues.get(`${account()}.2`)).not.toContain('"views"'))stop()queryClient.clear()- useScopeErrorStore.setState({ reported: { views: null, errors: null, replay: null } })+ useScopeErrorStore.setState({ reported: { views: null, errors: null, replay: null, inbox: null } })useAuthStore.setState({ projectId: 2 })stop = installOfflineCache()await waitFor(() => expect(queryClient.getQueryData(inbox)).toBeDefined())@@ -287,7 +287,7 @@ describe('authenticated offline-cache lifecycle', () => {it('does not rehydrate views when the existing access gate reports a missing scope', async () => {const key = seed(1)- useScopeErrorStore.setState({ reported: { views: 'insights:read', errors: null, replay: null } })+ useScopeErrorStore.setState({ reported: { views: 'insights:read', errors: null, replay: null, inbox: null } })const stop = installOfflineCache()await waitFor(() => expect(JSON.parse(mockValues.get(`${account()}.1`) ?? '[]')).toEqual([]))expect(queryClient.getQueryData(key)).toBeUndefined()diff --git a/products/mobile/src/features/report/ReportScreen.tsx b/products/mobile/src/features/report/ReportScreen.tsxindex 660a48a44279..1cc340614905 100644--- a/products/mobile/src/features/report/ReportScreen.tsx+++ b/products/mobile/src/features/report/ReportScreen.tsx@@ -42,6 +42,8 @@ import { useGithubOnlyReviewerCount, useReportReviewersQuery } from '../reviewerimport { ReportNavigation } from '../tabs/ReportNavigation'import { VerdictSheet } from '../verdict/VerdictSheet'import { dismissCopy, hasOpenPullRequest, resolveCopy } from '../verdict/verdictCopy'+import { useFeatureAccess } from '../views/useViewsAccess'+import { ViewsReauthState } from '../views/ViewsReauthState'import { Activity } from './Activity'import { hasReportDetail } from './details/hasReportDetail'import { Evidence } from './Evidence'@@ -145,6 +147,7 @@ function ReportContent({ reportId, from }: ReportScreenProps): ReactElement {const colors = useColors()const router = useRouter()const viewer = useViewer()+ const access = useFeatureAccess('inbox')const query = useReportWithLiveRun(reportId)// The same filters as the inbox, so Previous and Next follow the order the inbox shows.const inbox = useInboxItems({ filters: useInboxFilters() })@@ -194,6 +197,15 @@ function ReportContent({ reportId, from }: ReportScreenProps): ReactElement {closeOverlay()}+ if (access.state !== 'ok') {+ return (+ <View style={styles.screen}>+ <TopChrome onBack={goBack} />+ <ViewsReauthState access={access} feature="inbox" />+ </View>+ )+ }+const report = query.dataif (!report) {return (diff --git a/products/mobile/src/features/report/hooks.test.tsx b/products/mobile/src/features/report/hooks.test.tsxindex 898d82486db4..8100df2b66cb 100644--- a/products/mobile/src/features/report/hooks.test.tsx+++ b/products/mobile/src/features/report/hooks.test.tsx@@ -7,6 +7,7 @@ import { setAuthProvider } from '@/api/client'import { queryClient as appQueryClient } from '@/api/queryClient'import { useHandoffStore } from '@/features/handoff/handoffStore'import { useReportWithLiveRun } from '@/features/handoff/useReportWithLiveRun'+import { useScopeErrorStore } from '@/features/views/useViewsAccess'import { reportFixture } from '@/model/adapters/testFixtures'import type { QueryState, ReportView } from '@/model/types'@@ -34,6 +35,7 @@ const REPORT_ID = 'report-1'describe('useReport', () => {beforeEach(() => {+ useScopeErrorStore.getState().clear()AppState.currentState = 'active'jest.spyOn(AppState, 'addEventListener').mockReturnValue({ remove: () => undefined })useHandoffStore.setState({ reports: {} })@@ -166,7 +168,7 @@ describe('useReport', () => {}})- test.each([200, 500])(+ test.each([200, 500, 403])('keeps the report visible while refreshing missing evidence (signals %s)',async (signalsStatus) => {jest.useFakeTimers()@@ -180,12 +182,15 @@ describe('useReport', () => {if (refreshing) {await new Promise<void>((resolve) => pending.push({ evidence: page || signals, resolve }))}- const status = page ? 404 : signals ? signalsStatus : failRefresh ? 503 : 200- const body = url.includes('/artefacts/')- ? { count: 0, next: null, results: [] }- : signals- ? { signals: [] }- : reportFixture({ id: REPORT_ID })+ const status = page ? 404 : signals ? (failRefresh ? signalsStatus : 200) : failRefresh ? 503 : 200+ const body =+ status === 403+ ? { detail: "API key missing required scope 'inbox:read'" }+ : url.includes('/artefacts/')+ ? { count: 0, next: null, results: [] }+ : signals+ ? { signals: [] }+ : reportFixture({ id: REPORT_ID })return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })}) as typeof fetchconst client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })@@ -233,6 +238,7 @@ describe('useReport', () => {await jest.advanceTimersByTimeAsync(10)})expect(result.current.isRefetching).toBe(false)+ expect(useScopeErrorStore.getState().reported.inbox).toBe(signalsStatus === 403 ? 'inbox:read' : null)expect(renders.every((state) => state.data?.id === REPORT_ID && !state.isLoading)).toBe(true)} finally {unmount()diff --git a/products/mobile/src/features/report/hooks.ts b/products/mobile/src/features/report/hooks.tsindex 5d9f4fa0f7a4..85c597473819 100644--- a/products/mobile/src/features/report/hooks.ts+++ b/products/mobile/src/features/report/hooks.ts@@ -21,6 +21,7 @@ import { useSetPriorityAction } from '../priority/hooks'import { useSetReviewersAction } from '../reviewers/hooks'import { useSnoozeAction } from '../snooze/hooks'import { useDismissAction, useResolveAction } from '../verdict/hooks'+import { reportScopeError, useFeatureAccess } from '../views/useViewsAccess'import { reportArtefactsQuery, reportDetailQuery, reportPageQuery, reportSignalsQuery } from './queries'export const REPORT_POLL_INTERVAL_MS = 15_000@@ -34,7 +35,8 @@ function useLiveReport(reportId: string, enabled: boolean, refreshWhileVisible:const scope = useProjectScope()const offline = useConnectivity((state) => state.status === 'offline')const appActive = useAppActive()- const active = enabled && appActive && scope !== null+ const access = useFeatureAccess('inbox')+ const active = enabled && appActive && scope !== null && access.state === 'ok'const queryClient = useQueryClient()const refetchInterval = active && refreshWhileVisible ? REPORT_POLL_INTERVAL_MS : falseconst [report, artefacts, page, signals] = useQueries({@@ -45,6 +47,11 @@ function useLiveReport(reportId: string, enabled: boolean, refreshWhileVisible:{ ...reportSignalsQuery(scope, reportId), enabled: active, refetchOnMount: 'always' },],})+ useEffect(() => {+ for (const error of [report.error, artefacts.error, page.error, signals.error]) {+ reportScopeError(error, 'inbox')+ }+ }, [report.error, artefacts.error, page.error, signals.error])const taskId = report.data && artefacts.data ? reportTaskId(report.data, artefacts.data.results) : undefinedconst task = useQuery({queryKey: reportKeys.task(scope, taskId),diff --git a/products/mobile/src/features/views/ViewsReauthState.tsx b/products/mobile/src/features/views/ViewsReauthState.tsxindex 1a6b6a533f8f..76f462d77618 100644--- a/products/mobile/src/features/views/ViewsReauthState.tsx+++ b/products/mobile/src/features/views/ViewsReauthState.tsx@@ -21,6 +21,12 @@ interface FeatureCopy {}const COPY: Record<ScopedFeature, FeatureCopy> = {+ inbox: {+ unavailableTitle: "Inbox isn't available yet",+ reads: 'inbox reports',+ reauthTitle: 'Sign in again to see your inbox',+ shows: 'inbox reports',+ },views: {unavailableTitle: "Views isn't available yet",reads: 'dashboards and insights',@@ -47,7 +53,7 @@ function scopeList(scopes: readonly string[]): string {/*** A feature needs scopes that an older sign-in did not grant, and a token refresh never adds them. One new sign-in fixes- * it, so the state offers it; the inbox and chats keep working until then. When the last sign-in asked for the scope+ * it, so the state offers it. When the last sign-in asked for the scope* and still did not get it, a new sign-in gets the same grant, so the state explains that and offers no sign-in.*/export function ViewsReauthState({@@ -77,7 +83,7 @@ export function ViewsReauthState({<StateViewicon={icon}title={copy.unavailableTitle}- message={`PostHog doesn't let this app read ${copy.reads} yet, so signing in again won't help. Your inbox and chats still work.`}+ message={`PostHog doesn't let this app read ${copy.reads} yet, so signing in again won't help. ${feature === 'inbox' ? 'Your chats still work.' : 'Your inbox and chats still work.'}`}testID={`${feature}-unavailable`}/>)diff --git a/products/mobile/src/features/views/useViewsAccess.test.ts b/products/mobile/src/features/views/useViewsAccess.test.tsindex 4117e5e7d273..70ae6dbde7d7 100644--- a/products/mobile/src/features/views/useViewsAccess.test.ts+++ b/products/mobile/src/features/views/useViewsAccess.test.ts@@ -16,6 +16,8 @@ jest.mock('@react-native-async-storage/async-storage', () =>const REQUESTED = ['user:read', 'query:read', 'dashboard:read', 'insight:read', 'file_system_shortcut:write']describe('featureAccessFor', () => {+ beforeEach(() => useScopeErrorStore.getState().clear())+test.each<[string, ViewsAccessInput, ViewsAccessState, ScopedFeature?]>([['a sign-in that granted every Views scope',@@ -52,19 +54,61 @@ describe('featureAccessFor', () => {'reauth','errors',],+ [+ 'an inbox session that the server still accepts through task scopes',+ {+ method: 'oauth',+ tokens: { grantedScopes: ['task:write'], requestedScopes: ['task:write'] },+ reported: null,+ },+ 'ok',+ 'inbox',+ ],+ [+ 'a legacy inbox grant rejected after the fallback is removed',+ {+ method: 'oauth',+ tokens: { grantedScopes: ['task:write'], requestedScopes: ['task:write'] },+ reported: 'inbox:read',+ },+ 'reauth',+ 'inbox',+ ],+ [+ 'an inbox scope requested but not granted by the OAuth application',+ {+ method: 'oauth',+ tokens: { grantedScopes: ['task:write'], requestedScopes: ['task:write', 'inbox:read', 'inbox:write'] },+ reported: 'inbox:read',+ },+ 'unavailable',+ 'inbox',+ ],+ [+ 'a personal API key rejected for an inbox scope',+ { method: 'personal_api_key', tokens: null, reported: 'inbox:write' },+ 'personal-key-missing-scopes',+ 'inbox',+ ],])('%s', (_name, input, expected, feature = 'views') => {expect(featureAccessFor(input, feature).state).toBe(expected)})- test('a missing scope reported by one feature leaves the others alone', () => {- const refused = new ApiError(403, { detail: "API key missing required scope 'error_tracking:read'" })+ test.each<[ScopedFeature, string, boolean]>([+ ['errors', 'error_tracking:read', true],+ ['inbox', 'inbox:read', true],+ ['inbox', 'today:read', false],+ ])('a missing %s scope %s leaves other features alone', (feature, scope, handled) => {+ const refused = new ApiError(403, { detail: `API key missing required scope '${scope}'` })- expect(reportScopeError(refused, 'errors')).toBe(true)+ expect(reportScopeError(refused, feature)).toBe(handled)expect(useScopeErrorStore.getState().reported).toEqual({views: null,- errors: 'error_tracking:read',+ errors: null,replay: null,+ inbox: null,+ ...(handled ? { [feature]: scope } : {}),})})})diff --git a/products/mobile/src/features/views/useViewsAccess.ts b/products/mobile/src/features/views/useViewsAccess.tsindex 25c02fd95c32..c25237d6c226 100644--- a/products/mobile/src/features/views/useViewsAccess.ts+++ b/products/mobile/src/features/views/useViewsAccess.ts@@ -1,11 +1,11 @@import { create } from 'zustand'-import { coversScope, missingFeatureScope, missingScope, type ScopedFeature } from '@/api/scopeErrors'+import { coversScope, FEATURE_SCOPES, missingFeatureScope, missingScope, type ScopedFeature } from '@/api/scopeErrors'import { type AuthMethod, addSessionEndTask, useAuthStore } from '@/auth/authStore'import { getSessionTokens, type SessionTokens } from '@/auth/tokens'import { useDataMode } from '@/demo/demoMode'-const NONE_REPORTED: Record<ScopedFeature, string | null> = { views: null, errors: null, replay: null }+const NONE_REPORTED: Record<ScopedFeature, string | null> = { views: null, errors: null, replay: null, inbox: null }interface ScopeErrorState {/** Per feature, the scope one of its requests was refused for in this session. */@@ -29,10 +29,11 @@ addSessionEndTask(() => useScopeErrorStore.getState().clear())*/export function reportScopeError(error: unknown, feature: ScopedFeature = 'views'): boolean {const scope = missingScope(error)- if (scope) {+ if (scope && (feature !== 'inbox' || FEATURE_SCOPES.inbox.includes(scope))) {useScopeErrorStore.getState().report(feature, scope)+ return true}- return scope !== null+ return false}/**@@ -65,7 +66,8 @@ export interface ViewsAccessInput {*/export function featureAccessFor({ method, tokens, reported }: ViewsAccessInput, feature: ScopedFeature): ViewsAccess {const granted = method === 'oauth' ? (tokens?.grantedScopes ?? null) : null- const missing = reported ?? missingFeatureScope(granted, feature)+ // The server can accept legacy task scopes for inbox access, so wait for a scope rejection before asking again.+ const missing = reported ?? (feature === 'inbox' ? null : missingFeatureScope(granted, feature))if (!missing) {return OK}