diff --git a/bskyweb/static/oauth-client-metadata.json b/bskyweb/static/oauth-client-metadata.json index 1b50cb4b2..ce5f5fbac 100644 --- a/bskyweb/static/oauth-client-metadata.json +++ b/bskyweb/static/oauth-client-metadata.json @@ -5,7 +5,7 @@ "redirect_uris": [ "https://blacksky.community/auth/web/callback" ], - "scope": "atproto transition:generic transition:email transition:chat.bsky identity:handle account:email?action=manage account:status?action=manage", + "scope": "atproto transition:generic transition:email transition:chat.bsky identity:handle account:email?action=manage account:status?action=manage repo:community.lexicon.preference.ai", "token_endpoint_auth_method": "none", "response_types": [ "code" diff --git a/src/Navigation.tsx b/src/Navigation.tsx index 35d5cf500..fe61a0174 100644 --- a/src/Navigation.tsx +++ b/src/Navigation.tsx @@ -102,6 +102,7 @@ import {AboutSettingsScreen} from '#/screens/Settings/AboutSettings' import {AccessibilitySettingsScreen} from '#/screens/Settings/AccessibilitySettings' import {AccountSettingsScreen} from '#/screens/Settings/AccountSettings' import {ActivityPrivacySettingsScreen} from '#/screens/Settings/ActivityPrivacySettings' +import {AIPreferencesSettingsScreen} from '#/screens/Settings/AIPreferencesSettings' import {AppearanceSettingsScreen} from '#/screens/Settings/AppearanceSettings' import {AppIconSettingsScreen} from '#/screens/Settings/AppIconSettings' import {AppPasswordsScreen} from '#/screens/Settings/AppPasswords' @@ -399,6 +400,14 @@ function commonScreens(Stack: typeof Flat, unreadCountLabel?: string) { requireAuth: true, }} /> + AIPreferencesSettingsScreen} + options={{ + title: title(msg`AI Preferences`), + requireAuth: true, + }} + /> AppearanceSettingsScreen} diff --git a/src/lib/routes/types.ts b/src/lib/routes/types.ts index 4911406a8..e932ecae1 100644 --- a/src/lib/routes/types.ts +++ b/src/lib/routes/types.ts @@ -50,6 +50,7 @@ export type CommonNavigatorParams = { PreferencesThreads: undefined PreferencesExternalEmbeds: undefined AccessibilitySettings: undefined + AIPreferencesSettings: undefined AppearanceSettings: undefined AccountSettings: undefined PrivacyAndSecuritySettings: undefined diff --git a/src/routes.ts b/src/routes.ts index 2da95d01b..6a4edc049 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -48,6 +48,7 @@ export const router = new Router({ PreferencesThreads: '/settings/threads', PreferencesExternalEmbeds: '/settings/external-embeds', AccessibilitySettings: '/settings/accessibility', + AIPreferencesSettings: '/settings/ai-preferences', AppearanceSettings: '/settings/appearance', SavedFeeds: '/settings/saved-feeds', AccountSettings: '/settings/account', diff --git a/src/screens/Settings/AIPreferencesSettings.tsx b/src/screens/Settings/AIPreferencesSettings.tsx new file mode 100644 index 000000000..8134e59da --- /dev/null +++ b/src/screens/Settings/AIPreferencesSettings.tsx @@ -0,0 +1,239 @@ +import {View} from 'react-native' +import {msg, Trans} from '@lingui/macro' +import {useLingui} from '@lingui/react' +import {type NativeStackScreenProps} from '@react-navigation/native-stack' + +import {type CommonNavigatorParams} from '#/lib/routes/types' +import { + useAIPreferencesQuery, + useUpdateAIPreferencesMutation, +} from '#/state/queries/ai-preferences' +import {preferenceSetToTriStates} from '#/state/queries/ai-preferences/serde' +import { + AI_PREFERENCE_CATEGORIES, + type AIPreferenceCategory, +} from '#/state/queries/ai-preferences/types' +import * as SettingsList from '#/screens/Settings/components/SettingsList' +import {atoms as a, useBreakpoints, useTheme} from '#/alf' +import * as ToggleButton from '#/components/forms/ToggleButton' +import * as Layout from '#/components/Layout' +import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' + +type Props = NativeStackScreenProps< + CommonNavigatorParams, + 'AIPreferencesSettings' +> + +export function AIPreferencesSettingsScreen({}: Props) { + const {_} = useLingui() + const t = useTheme() + + const {data: record, isLoading} = useAIPreferencesQuery() + const {mutate} = useUpdateAIPreferencesMutation() + + // The mutation's onMutate writes the optimistic record straight to the + // cache, so reading triStates from `record` already reflects in-flight taps. + const triStates = preferenceSetToTriStates(record?.preferences) + + const allowLabel = _(msg`Allow`) + const unsetLabel = _(msg`No preference`) + const denyLabel = _(msg`Deny`) + + const categoryCopy = useCategoryCopy() + + const onChange = (category: AIPreferenceCategory) => (values: string[]) => { + const value = values[0] + if (value !== 'allow' && value !== 'deny' && value !== 'unset') return + mutate({[category]: value}) + } + + return ( + + + + + + AI preferences + + + + + + + + + How AI may use your data + + + + Experimental + + + + + + These settings tell AI systems how you want your data used across + the AT Protocol network: posts, blogs, listening history, stories, + and any other content tied to your account. Your data stays + public, but you can say how AI should handle it. + + + + + Blacksky will follow the preferences you set here. We took an + ecosystem approach by publishing this as a community lexicon other + AT Protocol services can adopt and choose to respect. Bad actors + may ignore these signals and work around them, which is outside + the control of Blacksky, your PDS operator, and other intermediary + services on the network. + + + + + These preferences apply across your entire account. The lexicon + allows finer controls, like rules for specific AI services or + specific types of content, but those aren't exposed in this + interface yet. + + + + + Safety tools like spam and bot detection aren't affected. They + stay on for everyone. + + + + + + {isLoading && !record ? ( + + + + ) : ( + AI_PREFERENCE_CATEGORIES.map(category => { + const copy = categoryCopy[category] + return ( + + ) + }) + )} + + + + ) +} + +function CategoryRow({ + name, + description, + value, + allowLabel, + unsetLabel, + denyLabel, + onChange, +}: { + name: string + description: string + value: 'allow' | 'deny' | 'unset' + allowLabel: string + unsetLabel: string + denyLabel: string + onChange: (values: string[]) => void +}) { + const {_} = useLingui() + const t = useTheme() + const {gtPhone} = useBreakpoints() + + return ( + + + + {name} + + + {description} + + + + + + {allowLabel} + + + {unsetLabel} + + + {denyLabel} + + + + + ) +} + +function useCategoryCopy(): Record< + AIPreferenceCategory, + {name: string; description: string} +> { + const {_} = useLingui() + return { + training: { + name: _(msg`Training`), + description: _( + msg`Use your data to build or train new AI models. Once your work is in a model, it stays there, even if you delete your account later.`, + ), + }, + inference: { + name: _(msg`Inference`), + description: _( + msg`Look up your data when AI is answering someone's question. The AI doesn't keep it, but it might quote or reference it in real time.`, + ), + }, + syntheticContent: { + name: _(msg`Synthetic content`), + description: _( + msg`Generate new content or interactions modeled on your data. This includes AI imitations of your writing, AI-generated versions of your photos or audio, or bots designed to sound like you.`, + ), + }, + embedding: { + name: _(msg`Embedding`), + description: _( + msg`Use your data in AI search and recommendation systems. This is how AI finds similar accounts, groups users by interests, and decides what to show in personalized feeds (e.g. 'discover', 'for you', etc.)`, + ), + }, + } +} diff --git a/src/screens/Settings/Settings.tsx b/src/screens/Settings/Settings.tsx index 9a956032e..3464a984f 100644 --- a/src/screens/Settings/Settings.tsx +++ b/src/screens/Settings/Settings.tsx @@ -57,6 +57,7 @@ import { PersonX_Stroke2_Corner0_Rounded as PersonXIcon, } from '#/components/icons/Person' import {RaisingHand4Finger_Stroke2_Corner2_Rounded as HandIcon} from '#/components/icons/RaisingHand' +import {Sparkle_Stroke2_Corner0_Rounded as SparkleIcon} from '#/components/icons/Sparkle' import {Window_Stroke2_Corner2_Rounded as WindowIcon} from '#/components/icons/Window' import * as Layout from '#/components/Layout' import {Loader} from '#/components/Loader' @@ -193,6 +194,14 @@ export function SettingsScreen({}: Props) { Moderation + + + + AI preferences + + diff --git a/src/state/queries/ai-preferences/index.ts b/src/state/queries/ai-preferences/index.ts new file mode 100644 index 000000000..a368066ec --- /dev/null +++ b/src/state/queries/ai-preferences/index.ts @@ -0,0 +1,106 @@ +import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' + +import {logger} from '#/logger' +import {STALE} from '#/state/queries' +import {useAgent, useSession} from '#/state/session' +import {buildGlobalRecord, type Patch} from './serde' +import {AI_PREFERENCE_NSID, type AIPreferenceRecord} from './types' + +const RQKEY_ROOT = 'ai-preferences' + +export const RQKEY = (did: string | undefined) => [ + RQKEY_ROOT, + did ?? '', +] + +function isRecordNotFoundError(e: unknown): boolean { + if (e instanceof Error) { + return e.message.includes('Could not locate record:') + } + return false +} + +export function useAIPreferencesQuery() { + const {currentAccount} = useSession() + const agent = useAgent() + + return useQuery({ + queryKey: RQKEY(currentAccount?.did), + enabled: !!currentAccount?.did, + staleTime: STALE.MINUTES.FIVE, + queryFn: async () => { + if (!currentAccount) throw new Error('Not signed in') + try { + const {data} = await agent.com.atproto.repo.getRecord({ + repo: currentAccount.did, + collection: AI_PREFERENCE_NSID, + rkey: 'self', + }) + return data.value as AIPreferenceRecord + } catch (e) { + if (isRecordNotFoundError(e)) return null + throw e + } + }, + }) +} + +export function useUpdateAIPreferencesMutation({ + onSuccess, + onError, +}: { + onSuccess?: () => void + onError?: (error: Error) => void +} = {}) { + const queryClient = useQueryClient() + const {currentAccount} = useSession() + const agent = useAgent() + + type Ctx = {prev: AIPreferenceRecord | null} + + return useMutation({ + mutationFn: async patch => { + if (!currentAccount) throw new Error('Not signed in') + const queryKey = RQKEY(currentAccount.did) + const prev = + queryClient.getQueryData(queryKey) ?? null + const next = buildGlobalRecord(prev, patch) + await agent.com.atproto.repo.putRecord({ + repo: currentAccount.did, + collection: AI_PREFERENCE_NSID, + rkey: 'self', + record: next, + }) + }, + onMutate: async patch => { + if (!currentAccount) return + const queryKey = RQKEY(currentAccount.did) + await queryClient.cancelQueries({queryKey}) + const prev = + queryClient.getQueryData(queryKey) ?? null + const next = buildGlobalRecord(prev, patch) + queryClient.setQueryData(queryKey, next) + return {prev} + }, + onSuccess: () => { + onSuccess?.() + }, + onError: (error, _patch, context) => { + logger.error('Failed to update AI preferences', {safeMessage: error}) + if (currentAccount && context) { + queryClient.setQueryData( + RQKEY(currentAccount.did), + context.prev, + ) + } + onError?.(error) + }, + onSettled: () => { + if (currentAccount) { + void queryClient.invalidateQueries({ + queryKey: RQKEY(currentAccount.did), + }) + } + }, + }) +} diff --git a/src/state/queries/ai-preferences/serde.test.ts b/src/state/queries/ai-preferences/serde.test.ts new file mode 100644 index 000000000..0cadd083f --- /dev/null +++ b/src/state/queries/ai-preferences/serde.test.ts @@ -0,0 +1,159 @@ +import { + applyPatch, + buildGlobalRecord, + fieldToTriState, + mostRecentUpdatedAt, + preferenceSetToTriStates, + recordToTriStates, +} from './serde' +import {type AIPreferenceRecord} from './types' + +describe('AI preferences serde', () => { + describe('fieldToTriState', () => { + it('maps undefined to "unset"', () => { + expect(fieldToTriState(undefined)).toBe('unset') + }) + it('maps allow:true to "allow"', () => { + expect(fieldToTriState({allow: true})).toBe('allow') + }) + it('maps allow:false to "deny"', () => { + expect(fieldToTriState({allow: false})).toBe('deny') + }) + }) + + describe('preferenceSetToTriStates', () => { + it('returns all "unset" for undefined input', () => { + expect(preferenceSetToTriStates(undefined)).toEqual({ + training: 'unset', + inference: 'unset', + syntheticContent: 'unset', + embedding: 'unset', + }) + }) + + it('maps a mixed set', () => { + expect( + preferenceSetToTriStates({ + training: {allow: false, updatedAt: '2026-05-05T00:00:00.000Z'}, + inference: {allow: true, updatedAt: '2026-05-05T00:00:00.000Z'}, + }), + ).toEqual({ + training: 'deny', + inference: 'allow', + syntheticContent: 'unset', + embedding: 'unset', + }) + }) + }) + + describe('recordToTriStates', () => { + it('maps a null record to all "unset"', () => { + expect(recordToTriStates(null)).toEqual({ + training: 'unset', + inference: 'unset', + syntheticContent: 'unset', + embedding: 'unset', + }) + }) + }) + + describe('applyPatch', () => { + const NOW = '2026-05-05T12:00:00.000Z' + + it('adds a new field with stamped updatedAt', () => { + const next = applyPatch(undefined, {training: 'allow'}, NOW) + expect(next).toEqual({training: {allow: true, updatedAt: NOW}}) + }) + + it('flips an existing field and stamps updatedAt only on touched fields', () => { + const prev = { + training: {allow: true, updatedAt: '2026-01-01T00:00:00.000Z'}, + inference: {allow: false, updatedAt: '2026-02-01T00:00:00.000Z'}, + } + const next = applyPatch(prev, {training: 'deny'}, NOW) + expect(next.training).toEqual({allow: false, updatedAt: NOW}) + expect(next.inference).toEqual(prev.inference) + }) + + it('omits a category from the output when set to "unset" (does not write allow:false)', () => { + const prev = { + training: {allow: true, updatedAt: '2026-01-01T00:00:00.000Z'}, + inference: {allow: false, updatedAt: '2026-02-01T00:00:00.000Z'}, + } + const next = applyPatch(prev, {training: 'unset'}, NOW) + expect(next.training).toBeUndefined() + expect('training' in next).toBe(false) + expect(next.inference).toEqual(prev.inference) + }) + + it('ignores undefined entries in the patch', () => { + const prev = { + training: {allow: true, updatedAt: '2026-01-01T00:00:00.000Z'}, + } + const next = applyPatch(prev, {inference: undefined}, NOW) + expect(next).toEqual(prev) + }) + }) + + describe('buildGlobalRecord', () => { + const NOW = '2026-05-05T12:00:00.000Z' + + it('produces a globalScope record with the correct $type and rkey-agnostic shape', () => { + const record = buildGlobalRecord(null, {training: 'allow'}, NOW) + expect(record.$type).toBe('community.lexicon.preference.ai') + expect(record.scope).toEqual({ + $type: 'community.lexicon.preference.ai#globalScope', + }) + expect(record.updatedAt).toBe(NOW) + expect(record.preferences.training).toEqual({allow: true, updatedAt: NOW}) + }) + + it('preserves untouched preferences from the previous record', () => { + const prev: AIPreferenceRecord = { + $type: 'community.lexicon.preference.ai', + updatedAt: '2026-01-01T00:00:00.000Z', + scope: {$type: 'community.lexicon.preference.ai#globalScope'}, + preferences: { + training: {allow: true, updatedAt: '2026-01-01T00:00:00.000Z'}, + embedding: {allow: false, updatedAt: '2026-01-01T00:00:00.000Z'}, + }, + } + const record = buildGlobalRecord(prev, {inference: 'deny'}, NOW) + expect(record.preferences.training).toEqual(prev.preferences.training) + expect(record.preferences.embedding).toEqual(prev.preferences.embedding) + expect(record.preferences.inference).toEqual({ + allow: false, + updatedAt: NOW, + }) + }) + + it('round-trips through recordToTriStates after a tri-state edit', () => { + const r1 = buildGlobalRecord(null, {training: 'allow'}, NOW) + const r2 = buildGlobalRecord(r1, {inference: 'deny'}, NOW) + const r3 = buildGlobalRecord(r2, {training: 'unset'}, NOW) + expect(recordToTriStates(r3)).toEqual({ + training: 'unset', + inference: 'deny', + syntheticContent: 'unset', + embedding: 'unset', + }) + }) + }) + + describe('mostRecentUpdatedAt', () => { + it('returns undefined for an empty set', () => { + expect(mostRecentUpdatedAt({})).toBeUndefined() + expect(mostRecentUpdatedAt(undefined)).toBeUndefined() + }) + + it('returns the latest field updatedAt', () => { + expect( + mostRecentUpdatedAt({ + training: {allow: true, updatedAt: '2026-01-01T00:00:00.000Z'}, + inference: {allow: false, updatedAt: '2026-03-01T00:00:00.000Z'}, + embedding: {allow: false, updatedAt: '2026-02-01T00:00:00.000Z'}, + }), + ).toBe('2026-03-01T00:00:00.000Z') + }) + }) +}) diff --git a/src/state/queries/ai-preferences/serde.ts b/src/state/queries/ai-preferences/serde.ts new file mode 100644 index 000000000..1066ceac1 --- /dev/null +++ b/src/state/queries/ai-preferences/serde.ts @@ -0,0 +1,82 @@ +import { + AI_PREFERENCE_CATEGORIES, + type AIPreferenceCategory, + type AIPreferenceRecord, + type AIPreferenceSet, + type AIPreferenceTriStates, + DEFAULT_TRI_STATES, + type TriState, +} from './types' + +export function fieldToTriState(field: {allow: boolean} | undefined): TriState { + if (!field) return 'unset' + return field.allow ? 'allow' : 'deny' +} + +export function preferenceSetToTriStates( + set: AIPreferenceSet | undefined, +): AIPreferenceTriStates { + if (!set) return {...DEFAULT_TRI_STATES} + return { + training: fieldToTriState(set.training), + inference: fieldToTriState(set.inference), + syntheticContent: fieldToTriState(set.syntheticContent), + embedding: fieldToTriState(set.embedding), + } +} + +export function recordToTriStates( + record: AIPreferenceRecord | null | undefined, +): AIPreferenceTriStates { + return preferenceSetToTriStates(record?.preferences) +} + +export type Patch = Partial> + +export function applyPatch( + prev: AIPreferenceSet | undefined, + patch: Patch, + now: string, +): AIPreferenceSet { + const next: AIPreferenceSet = {...(prev ?? {})} + for (const category of AI_PREFERENCE_CATEGORIES) { + const value = patch[category] + if (value === undefined) continue + if (value === 'unset') { + delete next[category] + } else { + next[category] = { + allow: value === 'allow', + updatedAt: now, + } + } + } + return next +} + +export function buildGlobalRecord( + prev: AIPreferenceRecord | null | undefined, + patch: Patch, + now: string = new Date().toISOString(), +): AIPreferenceRecord { + const preferences = applyPatch(prev?.preferences, patch, now) + return { + $type: 'community.lexicon.preference.ai', + updatedAt: now, + scope: {$type: 'community.lexicon.preference.ai#globalScope'}, + preferences, + } +} + +export function mostRecentUpdatedAt( + set: AIPreferenceSet | undefined, +): string | undefined { + if (!set) return undefined + let latest: string | undefined + for (const category of AI_PREFERENCE_CATEGORIES) { + const field = set[category] + if (!field) continue + if (!latest || field.updatedAt > latest) latest = field.updatedAt + } + return latest +} diff --git a/src/state/queries/ai-preferences/types.ts b/src/state/queries/ai-preferences/types.ts new file mode 100644 index 000000000..265299d0b --- /dev/null +++ b/src/state/queries/ai-preferences/types.ts @@ -0,0 +1,63 @@ +export const AI_PREFERENCE_NSID = 'community.lexicon.preference.ai' + +export type AIPreferenceCategory = + | 'training' + | 'inference' + | 'syntheticContent' + | 'embedding' + +export const AI_PREFERENCE_CATEGORIES: AIPreferenceCategory[] = [ + 'training', + 'inference', + 'syntheticContent', + 'embedding', +] + +export type TriState = 'allow' | 'deny' | 'unset' + +export type AIPreferenceField = { + allow: boolean + updatedAt: string +} + +export type AIGlobalScope = { + $type: 'community.lexicon.preference.ai#globalScope' +} + +export type AIEntityScope = { + $type: 'community.lexicon.preference.ai#entityScope' + entity: string +} + +export type AICollectionScope = { + $type: 'community.lexicon.preference.ai#collectionScope' + collection: string +} + +export type AIPreferenceScope = + | AIGlobalScope + | AIEntityScope + | AICollectionScope + +export type AIPreferenceSet = { + training?: AIPreferenceField + inference?: AIPreferenceField + syntheticContent?: AIPreferenceField + embedding?: AIPreferenceField +} + +export type AIPreferenceRecord = { + $type: 'community.lexicon.preference.ai' + updatedAt: string + scope: AIPreferenceScope + preferences: AIPreferenceSet +} + +export type AIPreferenceTriStates = Record + +export const DEFAULT_TRI_STATES: AIPreferenceTriStates = { + training: 'unset', + inference: 'unset', + syntheticContent: 'unset', + embedding: 'unset', +} diff --git a/src/state/session/oauth-web-client.ts b/src/state/session/oauth-web-client.ts index 3fcc084df..74d34a4a4 100644 --- a/src/state/session/oauth-web-client.ts +++ b/src/state/session/oauth-web-client.ts @@ -15,7 +15,7 @@ const OAUTH_CLIENT_NAME: string = process.env.EXPO_PUBLIC_OAUTH_CLIENT_NAME || 'Blacksky Community' const OAUTH_SCOPE = - 'atproto transition:generic transition:email transition:chat.bsky identity:handle account:email?action=manage account:status?action=manage' + 'atproto transition:generic transition:email transition:chat.bsky identity:handle account:email?action=manage account:status?action=manage repo:community.lexicon.preference.ai' function isLoopback() { if (typeof window === 'undefined') return false