migrate the starter pack writes to the pds client

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Samuel Newman
2026-08-03 23:41:15 +03:00
parent a86590ad4b
commit 3a970a7104
10 changed files with 216 additions and 192 deletions
@@ -21,7 +21,7 @@ import {
optimisticRemoveMatch, optimisticRemoveMatch,
useMatchesPassthroughQuery, useMatchesPassthroughQuery,
} from '#/state/queries/find-contacts' } from '#/state/queries/find-contacts'
import {useAgent, useAppviewClient, useSession} from '#/state/session' import {useAppviewClient, usePdsClient, useSession} from '#/state/session'
import {List, type ListMethods} from '#/view/com/util/List' import {List, type ListMethods} from '#/view/com/util/List'
import {UserAvatar} from '#/view/com/util/UserAvatar' import {UserAvatar} from '#/view/com/util/UserAvatar'
import {OnboardingPosition} from '#/screens/Onboarding/Layout' import {OnboardingPosition} from '#/screens/Onboarding/Layout'
@@ -91,7 +91,7 @@ export function ViewMatches({
const gutter = useGutters([0, 'wide']) const gutter = useGutters([0, 'wide'])
const moderationOpts = useModerationOpts() const moderationOpts = useModerationOpts()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const agent = useAgent() const pdsClient = usePdsClient()
const client = useAppviewClient() const client = useAppviewClient()
const insets = useSafeAreaInsets() const insets = useSafeAreaInsets()
const listRef = useRef<ListMethods>(null) const listRef = useRef<ListMethods>(null)
@@ -127,7 +127,10 @@ export function ViewMatches({
}) })
} }
const uris = await wait(500, bulkWriteFollows(agent, followableDids)) const uris = await wait(
500,
bulkWriteFollows(pdsClient, client, followableDids),
)
for (const did of followableDids) { for (const did of followableDids) {
const uri = uris.get(did) const uri = uris.get(did)
@@ -1,13 +1,14 @@
import {View} from 'react-native' import {View} from 'react-native'
import { import {type AppBskyGraphDefs, type AppBskyGraphStarterpack} from '@atproto/api'
type $Typed,
type AppBskyGraphDefs,
type AppBskyGraphListitem,
type AppBskyGraphStarterpack,
AtUri,
type ComAtprotoRepoApplyWrites,
} from '@atproto/api'
import {TID} from '@atproto/common-web' import {TID} from '@atproto/common-web'
import {type $Typed} from '@atproto/lex'
import {
type AtIdentifierString,
AtUri,
type AtUriString,
type DidString,
toDatetimeString,
} from '@atproto/syntax'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro' import {Trans} from '@lingui/react/macro'
@@ -20,7 +21,7 @@ import {wait} from '#/lib/async/wait'
import {type NavigationProp} from '#/lib/routes/types' import {type NavigationProp} from '#/lib/routes/types'
import {logger} from '#/logger' import {logger} from '#/logger'
import {getAllListMembers} from '#/state/queries/list-members' import {getAllListMembers} from '#/state/queries/list-members'
import {useAgent, useAppviewClient, useSession} from '#/state/session' import {useAppviewClient, usePdsClient, useSession} from '#/state/session'
import {atoms as a, platform, useTheme, web} from '#/alf' import {atoms as a, platform, useTheme, web} from '#/alf'
import {Admonition} from '#/components/Admonition' import {Admonition} from '#/components/Admonition'
import {Button, ButtonText} from '#/components/Button' import {Button, ButtonText} from '#/components/Button'
@@ -29,6 +30,7 @@ import {Loader} from '#/components/Loader'
import * as Toast from '#/components/Toast' import * as Toast from '#/components/Toast'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {useAnalytics} from '#/analytics' import {useAnalytics} from '#/analytics'
import {app, com} from '#/lexicons'
import {CreateOrEditListDialog} from './CreateOrEditListDialog' import {CreateOrEditListDialog} from './CreateOrEditListDialog'
export function CreateListFromStarterPackDialog({ export function CreateListFromStarterPackDialog({
@@ -40,8 +42,8 @@ export function CreateListFromStarterPackDialog({
}) { }) {
const {_} = useLingui() const {_} = useLingui()
const t = useTheme() const t = useTheme()
const agent = useAgent()
const appviewClient = useAppviewClient() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
const ax = useAnalytics() const ax = useAnalytics()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const navigation = useNavigation<NavigationProp>() const navigation = useNavigation<NavigationProp>()
@@ -80,13 +82,14 @@ export function CreateListFromStarterPackDialog({
) )
if (items.length > 0) { if (items.length > 0) {
const listitemWrites: $Typed<ComAtprotoRepoApplyWrites.Create>[] = const listitemWrites: $Typed<com.atproto.repo.applyWrites.Create>[] =
items.map(item => { items.map(item => {
const listitemRecord: $Typed<AppBskyGraphListitem.Record> = { const listitemRecord: $Typed<app.bsky.graph.listitem.Main> = {
$type: 'app.bsky.graph.listitem', $type: 'app.bsky.graph.listitem',
subject: item.subject.did, // the list view is still legacy-typed, so its strings are unbranded
list: listUri, subject: item.subject.did as DidString,
createdAt: new Date().toISOString(), list: listUri as AtUriString,
createdAt: toDatetimeString(new Date()),
} }
return { return {
$type: 'com.atproto.repo.applyWrites#create', $type: 'com.atproto.repo.applyWrites#create',
@@ -98,8 +101,8 @@ export function CreateListFromStarterPackDialog({
const chunks = chunk(listitemWrites, 50) const chunks = chunk(listitemWrites, 50)
for (const c of chunks) { for (const c of chunks) {
await agent.com.atproto.repo.applyWrites({ await pdsClient.call(com.atproto.repo.applyWrites, {
repo: currentAccount.did, repo: currentAccount.did as AtIdentifierString,
writes: c, writes: c,
}) })
} }
@@ -107,10 +110,10 @@ export function CreateListFromStarterPackDialog({
await until( await until(
5, 5,
1e3, 1e3,
(res: {data: {items: unknown[]}}) => res.data.items.length > 0, (res: {items: unknown[]}) => res.items.length > 0,
() => () =>
agent.app.bsky.graph.getList({ appviewClient.call(app.bsky.graph.getList, {
list: listUri, list: listUri as AtUriString,
limit: 1, limit: 1,
}), }),
) )
+42 -52
View File
@@ -1,11 +1,5 @@
import { import {type Client} from '@atproto/lex'
type $Typed, import {type AtUriString, toDatetimeString} from '@atproto/syntax'
type AppBskyActorDefs,
type AppBskyGraphGetStarterPack,
type AtpAgent,
type ComAtprotoRepoApplyWrites,
type Facet,
} from '@atproto/api'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {useMutation} from '@tanstack/react-query' import {useMutation} from '@tanstack/react-query'
@@ -14,7 +8,8 @@ import {until} from '#/lib/async/until'
import {sanitizeDisplayName} from '#/lib/strings/display-names' import {sanitizeDisplayName} from '#/lib/strings/display-names'
import {sanitizeHandle} from '#/lib/strings/handles' import {sanitizeHandle} from '#/lib/strings/handles'
import {enforceLen} from '#/lib/strings/helpers' import {enforceLen} from '#/lib/strings/helpers'
import {useAgent} from '#/state/session' import {useAppviewClient, usePdsClient} from '#/state/session'
import {app, com} from '#/lexicons'
import type * as bsky from '#/types/bsky' import type * as bsky from '#/types/bsky'
export const createStarterPackList = async ({ export const createStarterPackList = async ({
@@ -22,30 +17,27 @@ export const createStarterPackList = async ({
description, description,
descriptionFacets, descriptionFacets,
profiles, profiles,
agent, client,
}: { }: {
name: string name: string
description?: string description?: string
descriptionFacets?: Facet[] descriptionFacets?: app.bsky.richtext.facet.Main[]
profiles: bsky.profile.AnyProfileView[] profiles: bsky.profile.AnyProfileView[]
agent: AtpAgent client: Client
}): Promise<{uri: string; cid: string}> => { }): Promise<{uri: string; cid: string}> => {
if (profiles.length === 0) throw new Error('No profiles given') if (profiles.length === 0) throw new Error('No profiles given')
const list = await agent.app.bsky.graph.list.create( const list = await client.create(app.bsky.graph.list, {
{repo: agent.session!.did}, name,
{ description,
name, descriptionFacets,
description, avatar: undefined,
descriptionFacets, createdAt: toDatetimeString(new Date()),
avatar: undefined, purpose: 'app.bsky.graph.defs#referencelist',
createdAt: new Date().toISOString(), })
purpose: 'app.bsky.graph.defs#referencelist',
},
)
if (!list) throw new Error('List creation failed') if (!list) throw new Error('List creation failed')
await agent.com.atproto.repo.applyWrites({ await client.call(com.atproto.repo.applyWrites, {
repo: agent.session!.did, repo: client.assertDid,
writes: profiles.map(p => createListItem({did: p.did, listUri: list.uri})), writes: profiles.map(p => createListItem({did: p.did, listUri: list.uri})),
}) })
@@ -60,28 +52,27 @@ export function useGenerateStarterPackMutation({
onError: (e: Error) => void onError: (e: Error) => void
}) { }) {
const {_} = useLingui() const {_} = useLingui()
const agent = useAgent() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
return useMutation<{uri: string; cid: string}, Error, void>({ return useMutation<{uri: string; cid: string}, Error, void>({
mutationFn: async () => { mutationFn: async () => {
let profile: AppBskyActorDefs.ProfileViewDetailed | undefined let profile: app.bsky.actor.defs.ProfileViewDetailed | undefined
let profiles: AppBskyActorDefs.ProfileView[] | undefined let profiles: app.bsky.actor.defs.ProfileView[] | undefined
await Promise.all([ await Promise.all([
(async () => { (async () => {
profile = ( profile = await appviewClient.call(app.bsky.actor.getProfile, {
await agent.app.bsky.actor.getProfile({ actor: pdsClient.assertDid,
actor: agent.session!.did, })
})
).data
})(), })(),
(async () => { (async () => {
profiles = ( profiles = (
await agent.app.bsky.actor.searchActors({ await appviewClient.call(app.bsky.actor.searchActors, {
q: encodeURIComponent('*'), q: encodeURIComponent('*'),
limit: 49, limit: 49,
}) })
).data.actors.filter(p => p.viewer?.following) ).actors.filter(p => p.viewer?.following)
})(), })(),
]) ])
@@ -106,23 +97,19 @@ export function useGenerateStarterPackMutation({
const list = await createStarterPackList({ const list = await createStarterPackList({
name: starterPackName, name: starterPackName,
profiles, profiles,
agent, client: pdsClient,
}) })
return await agent.app.bsky.graph.starterpack.create( return await pdsClient.create(app.bsky.graph.starterpack, {
{ name: starterPackName,
repo: agent.session!.did, // `create` returns a plain string uri
}, list: list.uri as AtUriString,
{ createdAt: toDatetimeString(new Date()),
name: starterPackName, })
list: list.uri,
createdAt: new Date().toISOString(),
},
)
}, },
onSuccess: async data => { onSuccess: async data => {
await whenAppViewReady(agent, data.uri, v => { await whenAppViewReady(appviewClient, data.uri, v => {
return typeof v?.data.starterPack.uri === 'string' return typeof v?.starterPack.uri === 'string'
}) })
onSuccess(data) onSuccess(data)
}, },
@@ -138,7 +125,7 @@ function createListItem({
}: { }: {
did: string did: string
listUri: string listUri: string
}): $Typed<ComAtprotoRepoApplyWrites.Create> { }): com.atproto.repo.applyWrites.$InputBody['writes'][number] {
return { return {
$type: 'com.atproto.repo.applyWrites#create', $type: 'com.atproto.repo.applyWrites#create',
collection: 'app.bsky.graph.listitem', collection: 'app.bsky.graph.listitem',
@@ -152,14 +139,17 @@ function createListItem({
} }
async function whenAppViewReady( async function whenAppViewReady(
agent: AtpAgent, client: Client,
uri: string, uri: string,
fn: (res?: AppBskyGraphGetStarterPack.Response) => boolean, fn: (res?: app.bsky.graph.getStarterPack.$OutputBody) => boolean,
) { ) {
await until( await until(
5, // 5 tries 5, // 5 tries
1e3, // 1s delay between tries 1e3, // 1s delay between tries
fn, fn,
() => agent.app.bsky.graph.getStarterPack({starterPack: uri}), () =>
client.call(app.bsky.graph.getStarterPack, {
starterPack: uri as AtUriString,
}),
) )
} }
+11 -3
View File
@@ -8,6 +8,7 @@ import {
type Un$Typed, type Un$Typed,
} from '@atproto/api' } from '@atproto/api'
import {TID} from '@atproto/common-web' import {TID} from '@atproto/common-web'
import {type AtUriString} from '@atproto/syntax'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro' import {Trans} from '@lingui/react/macro'
@@ -26,7 +27,7 @@ import {useSetHasCheckedForStarterPack} from '#/state/preferences/used-starter-p
import {getAllListMembers} from '#/state/queries/list-members' import {getAllListMembers} from '#/state/queries/list-members'
import {preferencesQueryKey} from '#/state/queries/preferences' import {preferencesQueryKey} from '#/state/queries/preferences'
import {RQKEY as profileRQKey} from '#/state/queries/profile' import {RQKEY as profileRQKey} from '#/state/queries/profile'
import {useAgent, useAppviewClient} from '#/state/session' import {useAgent, useAppviewClient, usePdsClient} from '#/state/session'
import {useOnboardingDispatch} from '#/state/shell' import {useOnboardingDispatch} from '#/state/shell'
import { import {
useActiveStarterPack, useActiveStarterPack,
@@ -59,6 +60,7 @@ export function StepFinished() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const agent = useAgent() const agent = useAgent()
const appviewClient = useAppviewClient() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
const requestNotificationsPermission = useRequestNotificationsPermission() const requestNotificationsPermission = useRequestNotificationsPermission()
const activeStarterPack = useActiveStarterPack() const activeStarterPack = useActiveStarterPack()
const setActiveStarterPack = useSetActiveStarterPack() const setActiveStarterPack = useSetActiveStarterPack()
@@ -102,10 +104,15 @@ export function StepFinished() {
await Promise.all([ await Promise.all([
bulkWriteFollows( bulkWriteFollows(
agent, pdsClient,
appviewClient,
[BSKY_APP_ACCOUNT_DID, ...(listItems?.map(i => i.subject.did) ?? [])], [BSKY_APP_ACCOUNT_DID, ...(listItems?.map(i => i.subject.did) ?? [])],
starterPack starterPack
? {uri: starterPack.uri, cid: starterPack.cid} ? // the starter pack view is still legacy-typed
{
uri: starterPack.uri as AtUriString,
cid: starterPack.cid,
}
: undefined, : undefined,
), ),
(async () => { (async () => {
@@ -236,6 +243,7 @@ export function StepFinished() {
queryClient, queryClient,
agent, agent,
appviewClient, appviewClient,
pdsClient,
dispatch, dispatch,
onboardDispatch, onboardDispatch,
activeStarterPack, activeStarterPack,
@@ -14,7 +14,7 @@ import {logger} from '#/logger'
import {updateProfileShadow} from '#/state/cache/profile-shadow' import {updateProfileShadow} from '#/state/cache/profile-shadow'
import {useLanguagePrefs} from '#/state/preferences' import {useLanguagePrefs} from '#/state/preferences'
import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {useAgent, useSession} from '#/state/session' import {useAppviewClient, usePdsClient, useSession} from '#/state/session'
import { import {
OnboardingControls, OnboardingControls,
OnboardingPosition, OnboardingPosition,
@@ -42,7 +42,8 @@ export function StepSuggestedAccounts() {
const t = useTheme() const t = useTheme()
const {gtMobile} = useBreakpoints() const {gtMobile} = useBreakpoints()
const moderationOpts = useModerationOpts() const moderationOpts = useModerationOpts()
const agent = useAgent() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const queryClient = useQueryClient() const queryClient = useQueryClient()
@@ -119,7 +120,10 @@ export function StepSuggestedAccounts() {
followingUri: 'pending', followingUri: 'pending',
}) })
} }
const uris = await wait(1e3, bulkWriteFollows(agent, followableDids)) const uris = await wait(
1e3,
bulkWriteFollows(pdsClient, appviewClient, followableDids),
)
for (const did of followableDids) { for (const did of followableDids) {
const uri = uris.get(did) const uri = uris.get(did)
updateProfileShadow(queryClient, did, { updateProfileShadow(queryClient, did, {
@@ -1,6 +1,7 @@
import {useState} from 'react' import {useState} from 'react'
import {View} from 'react-native' import {View} from 'react-native'
import {type AppBskyGraphDefs, AppBskyGraphStarterpack} from '@atproto/api' import {type AppBskyGraphDefs, AppBskyGraphStarterpack} from '@atproto/api'
import {type AtUriString} from '@atproto/syntax'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro' import {Trans} from '@lingui/react/macro'
@@ -11,7 +12,7 @@ import {isBlockedOrBlocking, isMuted} from '#/lib/moderation/blocked-and-muted'
import {logger} from '#/logger' import {logger} from '#/logger'
import {updateProfileShadow} from '#/state/cache/profile-shadow' import {updateProfileShadow} from '#/state/cache/profile-shadow'
import {getAllListMembers} from '#/state/queries/list-members' import {getAllListMembers} from '#/state/queries/list-members'
import {useAgent, useAppviewClient, useSession} from '#/state/session' import {useAppviewClient, usePdsClient, useSession} from '#/state/session'
import {bulkWriteFollows} from '#/screens/Onboarding/util' import {bulkWriteFollows} from '#/screens/Onboarding/util'
import {AvatarStack} from '#/screens/Search/components/StarterPackCard' import {AvatarStack} from '#/screens/Search/components/StarterPackCard'
import {atoms as a, useBreakpoints, useTheme, web} from '#/alf' import {atoms as a, useBreakpoints, useTheme, web} from '#/alf'
@@ -35,8 +36,8 @@ export function StarterPackCard({
const ax = useAnalytics() const ax = useAnalytics()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {gtPhone} = useBreakpoints() const {gtPhone} = useBreakpoints()
const agent = useAgent()
const appviewClient = useAppviewClient() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const record = view.record const record = view.record
const [isProcessing, setIsProcessing] = useState(false) const [isProcessing, setIsProcessing] = useState(false)
@@ -74,8 +75,9 @@ export function StarterPackCard({
let followUris: Map<string, string> let followUris: Map<string, string>
try { try {
followUris = await bulkWriteFollows(agent, dids, { followUris = await bulkWriteFollows(pdsClient, appviewClient, dids, {
uri: view.uri, // the starter pack view is still legacy-typed
uri: view.uri as AtUriString,
cid: view.cid, cid: view.cid,
}) })
} catch (e) { } catch (e) {
+24 -27
View File
@@ -1,37 +1,34 @@
import {
type $Typed,
type AppBskyGraphFollow,
type AppBskyGraphGetFollows,
type AtpAgent,
type ComAtprotoRepoApplyWrites,
type ComAtprotoRepoStrongRef,
} from '@atproto/api'
import {TID} from '@atproto/common-web' import {TID} from '@atproto/common-web'
import {type $Typed, type Client} from '@atproto/lex'
import {
type AtIdentifierString,
type DidString,
toDatetimeString,
} from '@atproto/syntax'
import chunk from 'lodash.chunk' import chunk from 'lodash.chunk'
import {until} from '#/lib/async/until' import {until} from '#/lib/async/until'
import {app, com} from '#/lexicons'
export async function bulkWriteFollows( export async function bulkWriteFollows(
agent: AtpAgent, pdsClient: Client,
appviewClient: Client,
dids: string[], dids: string[],
via?: ComAtprotoRepoStrongRef.Main, via?: com.atproto.repo.strongRef.Main,
) { ) {
const session = agent.session const did = pdsClient.assertDid
if (!session) { const followRecords: $Typed<app.bsky.graph.follow.Main>[] = dids.map(did => {
throw new Error(`bulkWriteFollows failed: no session`)
}
const followRecords: $Typed<AppBskyGraphFollow.Record>[] = dids.map(did => {
return { return {
$type: 'app.bsky.graph.follow', $type: 'app.bsky.graph.follow',
subject: did, // callers hold plain dids read off legacy-typed views
createdAt: new Date().toISOString(), subject: did as DidString,
createdAt: toDatetimeString(new Date()),
via, via,
} }
}) })
const followWrites: $Typed<ComAtprotoRepoApplyWrites.Create>[] = const followWrites: $Typed<com.atproto.repo.applyWrites.Create>[] =
followRecords.map(r => ({ followRecords.map(r => ({
$type: 'com.atproto.repo.applyWrites#create', $type: 'com.atproto.repo.applyWrites#create',
collection: 'app.bsky.graph.follow', collection: 'app.bsky.graph.follow',
@@ -41,35 +38,35 @@ export async function bulkWriteFollows(
const chunks = chunk(followWrites, 50) const chunks = chunk(followWrites, 50)
for (const chunk of chunks) { for (const chunk of chunks) {
await agent.com.atproto.repo.applyWrites({ await pdsClient.call(com.atproto.repo.applyWrites, {
repo: session.did, repo: did,
writes: chunk, writes: chunk,
}) })
} }
await whenFollowsIndexed(agent, session.did, res => !!res.data.follows.length) await whenFollowsIndexed(appviewClient, did, res => !!res.follows.length)
const followUris = new Map<string, string>() const followUris = new Map<string, string>()
for (const r of followWrites) { for (const r of followWrites) {
followUris.set( followUris.set(
r.value.subject as string, r.value.subject as string,
`at://${session.did}/app.bsky.graph.follow/${r.rkey}`, `at://${did}/app.bsky.graph.follow/${r.rkey}`,
) )
} }
return followUris return followUris
} }
async function whenFollowsIndexed( async function whenFollowsIndexed(
agent: AtpAgent, appviewClient: Client,
actor: string, actor: string,
fn: (res: AppBskyGraphGetFollows.Response) => boolean, fn: (res: app.bsky.graph.getFollows.$OutputBody) => boolean,
) { ) {
await until( await until(
5, // 5 tries 5, // 5 tries
1e3, // 1s delay between tries 1e3, // 1s delay between tries
fn, fn,
() => () =>
agent.app.bsky.graph.getFollows({ appviewClient.call(app.bsky.graph.getFollows, {
actor, actor: actor as AtIdentifierString,
limit: 1, limit: 1,
}), }),
) )
@@ -29,7 +29,7 @@ import {
useContactsMatchesQuery, useContactsMatchesQuery,
useContactsSyncStatusQuery, useContactsSyncStatusQuery,
} from '#/state/queries/find-contacts' } from '#/state/queries/find-contacts'
import {useAgent, useAppviewClient, useSession} from '#/state/session' import {useAppviewClient, usePdsClient, useSession} from '#/state/session'
import {ErrorScreen} from '#/view/com/util/error/ErrorScreen' import {ErrorScreen} from '#/view/com/util/error/ErrorScreen'
import {List} from '#/view/com/util/List' import {List} from '#/view/com/util/List'
import {atoms as a, tokens, useGutters, useTheme} from '#/alf' import {atoms as a, tokens, useGutters, useTheme} from '#/alf'
@@ -370,7 +370,7 @@ function StatusHeader({
}) { }) {
const {_} = useLingui() const {_} = useLingui()
const ax = useAnalytics() const ax = useAnalytics()
const agent = useAgent() const pdsClient = usePdsClient()
const client = useAppviewClient() const client = useAppviewClient()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {currentAccount} = useSession() const {currentAccount} = useSession()
@@ -406,7 +406,10 @@ function StatusHeader({
followCount: didsToFollow.length, followCount: didsToFollow.length,
}) })
const uris = await wait(500, bulkWriteFollows(agent, didsToFollow)) const uris = await wait(
500,
bulkWriteFollows(pdsClient, client, didsToFollow),
)
for (const did of didsToFollow) { for (const did of didsToFollow) {
const uri = uris.get(did) const uri = uris.get(did)
@@ -7,6 +7,7 @@ import {
AtUri, AtUri,
type ModerationOpts, type ModerationOpts,
} from '@atproto/api' } from '@atproto/api'
import {type AtUriString} from '@atproto/syntax'
import {RichText as RichTextAPI} from '@bsky.app/sdk/richtext' import {RichText as RichTextAPI} from '@bsky.app/sdk/richtext'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
@@ -37,7 +38,7 @@ import {
useDeleteStarterPackMutation, useDeleteStarterPackMutation,
useStarterPackQuery, useStarterPackQuery,
} from '#/state/queries/starter-packs' } from '#/state/queries/starter-packs'
import {useAgent, useAppviewClient, useSession} from '#/state/session' import {useAppviewClient, usePdsClient, useSession} from '#/state/session'
import {useSetActiveStarterPack} from '#/state/shell/landing' import {useSetActiveStarterPack} from '#/state/shell/landing'
import {useLoggedOutViewControls} from '#/state/shell/logged-out' import {useLoggedOutViewControls} from '#/state/shell/logged-out'
import { import {
@@ -311,8 +312,8 @@ function Header({
const {_} = useLingui() const {_} = useLingui()
const t = useTheme() const t = useTheme()
const {currentAccount, hasSession} = useSession() const {currentAccount, hasSession} = useSession()
const agent = useAgent()
const appviewClient = useAppviewClient() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const setActiveStarterPack = useSetActiveStarterPack() const setActiveStarterPack = useSetActiveStarterPack()
const {requestSwitchToAccount} = useLoggedOutViewControls() const {requestSwitchToAccount} = useLoggedOutViewControls()
@@ -379,8 +380,9 @@ function Header({
let followUris: Map<string, string> let followUris: Map<string, string>
try { try {
followUris = await bulkWriteFollows(agent, dids, { followUris = await bulkWriteFollows(pdsClient, appviewClient, dids, {
uri: starterPack.uri, // the starter pack view is still legacy-typed
uri: starterPack.uri as AtUriString,
cid: starterPack.cid, cid: starterPack.cid,
}) })
} catch (e) { } catch (e) {
+85 -73
View File
@@ -1,11 +1,10 @@
import { import {
AppBskyFeedDefs, AppBskyFeedDefs,
AppBskyGraphDefs, AppBskyGraphDefs,
type AppBskyGraphGetStarterPack,
AppBskyGraphStarterpack, AppBskyGraphStarterpack,
type AtpAgent,
AtUri,
} from '@atproto/api' } from '@atproto/api'
import {type Client, type LexValue} from '@atproto/lex'
import {AtUri, type AtUriString, toDatetimeString} from '@atproto/syntax'
import {RichText} from '@bsky.app/sdk/richtext' import {RichText} from '@bsky.app/sdk/richtext'
import { import {
type QueryClient, type QueryClient,
@@ -25,8 +24,8 @@ import {
import {invalidateActorStarterPacksQuery} from '#/state/queries/actor-starter-packs' import {invalidateActorStarterPacksQuery} from '#/state/queries/actor-starter-packs'
import {STALE} from '#/state/queries/index' import {STALE} from '#/state/queries/index'
import {invalidateListMembersQuery} from '#/state/queries/list-members' import {invalidateListMembersQuery} from '#/state/queries/list-members'
import {useAgent, useAppviewClient} from '#/state/session' import {useAppviewClient, usePdsClient} from '#/state/session'
import {type app} from '#/lexicons' import {app, com} from '#/lexicons'
import * as bsky from '#/types/bsky' import * as bsky from '#/types/bsky'
const RQKEY_ROOT = 'starter-pack' const RQKEY_ROOT = 'starter-pack'
@@ -56,7 +55,7 @@ export function useStarterPackQuery({
did?: string did?: string
rkey?: string rkey?: string
}) { }) {
const agent = useAgent() const client = useAppviewClient()
return useQuery<AppBskyGraphDefs.StarterPackView>({ return useQuery<AppBskyGraphDefs.StarterPackView>({
queryKey: RQKEY(uri ? {uri} : {did, rkey}), queryKey: RQKEY(uri ? {uri} : {did, rkey}),
@@ -67,10 +66,10 @@ export function useStarterPackQuery({
uri = httpStarterPackUriToAtUri(uri) as string uri = httpStarterPackUriToAtUri(uri) as string
} }
const res = await agent.app.bsky.graph.getStarterPack({ const res = await client.call(app.bsky.graph.getStarterPack, {
starterPack: uri, starterPack: uri as AtUriString,
}) })
return res.data.starterPack return res.starterPack
}, },
enabled: Boolean(uri) || Boolean(did && rkey), enabled: Boolean(uri) || Boolean(did && rkey),
staleTime: STALE.MINUTES.FIVE, staleTime: STALE.MINUTES.FIVE,
@@ -104,12 +103,12 @@ export function useCreateStarterPackMutation({
onError: (e: Error) => void onError: (e: Error) => void
}) { }) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const agent = useAgent()
/* /*
* Facet/mention resolution is an appview job - it resolves handles through * Facet/mention resolution is an appview job - it resolves handles through
* the appview, and the public fallback keeps it working when logged out. * the appview, and the public fallback keeps it working when logged out.
*/ */
const appviewClient = useAppviewClient() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
return useMutation< return useMutation<
{uri: string; cid: string}, {uri: string; cid: string},
@@ -130,30 +129,26 @@ export function useCreateStarterPackMutation({
description, description,
profiles, profiles,
descriptionFacets, descriptionFacets,
agent, client: pdsClient,
}) })
return await agent.app.bsky.graph.starterpack.create( return await pdsClient.create(app.bsky.graph.starterpack, {
{ name,
repo: agent.assertDid, description,
}, descriptionFacets,
{ // `createStarterPackList` returns a plain string uri
name, list: listRes?.uri as AtUriString,
description, feeds: feeds?.map(f => ({uri: f.uri as AtUriString})),
descriptionFacets, createdAt: toDatetimeString(new Date()),
list: listRes?.uri, })
feeds: feeds?.map(f => ({uri: f.uri})),
createdAt: new Date().toISOString(),
},
)
}, },
onSuccess: async data => { onSuccess: async data => {
await whenAppViewReady(agent, data.uri, v => { await whenAppViewReady(appviewClient, data.uri, v => {
return typeof v?.data.starterPack.uri === 'string' return typeof v?.starterPack.uri === 'string'
}) })
await invalidateActorStarterPacksQuery({ await invalidateActorStarterPacksQuery({
queryClient, queryClient,
did: agent.session!.did, did: pdsClient.assertDid,
}) })
onSuccess(data) onSuccess(data)
}, },
@@ -171,8 +166,8 @@ export function useEditStarterPackMutation({
onError: (error: Error) => void onError: (error: Error) => void
}) { }) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const agent = useAgent()
const appviewClient = useAppviewClient() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
return useMutation< return useMutation<
void, void,
@@ -197,25 +192,29 @@ export function useEditStarterPackMutation({
descriptionFacets = rt.facets descriptionFacets = rt.facets
} }
if (!AppBskyGraphStarterpack.isRecord(currentStarterPack.record)) { if (!bsky.isType(app.bsky.graph.starterpack, currentStarterPack.record)) {
throw new Error('Invalid starter pack') throw new Error('Invalid starter pack')
} }
const removedItems = currentListItems.filter( const removedItems = currentListItems.filter(
i => i =>
i.subject.did !== agent.session?.did && i.subject.did !== pdsClient.did &&
!profiles.find(p => p.did === i.subject.did && p.did), !profiles.find(p => p.did === i.subject.did && p.did),
) )
if (removedItems.length !== 0) { if (removedItems.length !== 0) {
const chunks = chunk(removedItems, 50) const chunks = chunk(removedItems, 50)
for (const chunk of chunks) { for (const chunk of chunks) {
await agent.com.atproto.repo.applyWrites({ await pdsClient.call(com.atproto.repo.applyWrites, {
repo: agent.session!.did, repo: pdsClient.assertDid,
writes: chunk.map(i => ({ writes: chunk.map(
$type: 'com.atproto.repo.applyWrites#delete', (
collection: 'app.bsky.graph.listitem', i,
rkey: new AtUri(i.uri).rkey, ): com.atproto.repo.applyWrites.$InputBody['writes'][number] => ({
})), $type: 'com.atproto.repo.applyWrites#delete',
collection: 'app.bsky.graph.listitem',
rkey: new AtUri(i.uri).rkeySafe,
}),
),
}) })
} }
} }
@@ -226,33 +225,44 @@ export function useEditStarterPackMutation({
if (addedProfiles.length > 0) { if (addedProfiles.length > 0) {
const chunks = chunk(addedProfiles, 50) const chunks = chunk(addedProfiles, 50)
for (const chunk of chunks) { for (const chunk of chunks) {
await agent.com.atproto.repo.applyWrites({ await pdsClient.call(com.atproto.repo.applyWrites, {
repo: agent.session!.did, repo: pdsClient.assertDid,
writes: chunk.map(p => ({ writes: chunk.map(
$type: 'com.atproto.repo.applyWrites#create', (
collection: 'app.bsky.graph.listitem', p,
value: { ): com.atproto.repo.applyWrites.$InputBody['writes'][number] => ({
$type: 'app.bsky.graph.listitem', $type: 'com.atproto.repo.applyWrites#create',
subject: p.did, collection: 'app.bsky.graph.listitem',
list: currentStarterPack.list?.uri, value: {
createdAt: new Date().toISOString(), $type: 'app.bsky.graph.listitem',
}, subject: p.did,
})), list: currentStarterPack.list?.uri,
createdAt: new Date().toISOString(),
},
}),
),
}) })
} }
} }
const rkey = parseStarterPackUri(currentStarterPack.uri)!.rkey const rkey = parseStarterPackUri(currentStarterPack.uri)!.rkey
await agent.com.atproto.repo.putRecord({ await pdsClient.call(com.atproto.repo.putRecord, {
repo: agent.session!.did, repo: pdsClient.assertDid,
collection: 'app.bsky.graph.starterpack', collection: 'app.bsky.graph.starterpack',
rkey, rkey,
record: { record: {
$type: 'app.bsky.graph.starterpack',
name, name,
description, description,
descriptionFacets, descriptionFacets,
list: currentStarterPack.list?.uri, list: currentStarterPack.list?.uri,
feeds, /*
* Pre-existing quirk preserved verbatim: the edit path writes whole
* `GeneratorView`s where the lexicon declares `feedItem` refs. lex
* types the raw `putRecord` body as a `LexValue`, which the legacy
* view interface does not structurally satisfy, hence the cast.
*/
feeds: feeds as unknown as LexValue,
createdAt: currentStarterPack.record.createdAt, createdAt: currentStarterPack.record.createdAt,
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
}, },
@@ -260,12 +270,12 @@ export function useEditStarterPackMutation({
}, },
onSuccess: async (_, {currentStarterPack}) => { onSuccess: async (_, {currentStarterPack}) => {
const parsed = parseStarterPackUri(currentStarterPack.uri) const parsed = parseStarterPackUri(currentStarterPack.uri)
await whenAppViewReady(agent, currentStarterPack.uri, v => { await whenAppViewReady(appviewClient, currentStarterPack.uri, v => {
return currentStarterPack.cid !== v?.data.starterPack.cid return currentStarterPack.cid !== v?.starterPack.cid
}) })
await invalidateActorStarterPacksQuery({ await invalidateActorStarterPacksQuery({
queryClient, queryClient,
did: agent.session!.did, did: pdsClient.assertDid,
}) })
if (currentStarterPack.list) { if (currentStarterPack.list) {
await invalidateListMembersQuery({ await invalidateListMembersQuery({
@@ -275,7 +285,7 @@ export function useEditStarterPackMutation({
} }
await invalidateStarterPack({ await invalidateStarterPack({
queryClient, queryClient,
did: agent.session!.did, did: pdsClient.assertDid,
rkey: parsed!.rkey, rkey: parsed!.rkey,
}) })
onSuccess() onSuccess()
@@ -293,35 +303,34 @@ export function useDeleteStarterPackMutation({
onSuccess: () => void onSuccess: () => void
onError: (error: Error) => void onError: (error: Error) => void
}) { }) {
const agent = useAgent() const appviewClient = useAppviewClient()
const pdsClient = usePdsClient()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation({ return useMutation({
mutationFn: async ({listUri, rkey}: {listUri?: string; rkey: string}) => { mutationFn: async ({listUri, rkey}: {listUri?: string; rkey: string}) => {
if (!agent.session) { const did = pdsClient.assertDid
throw new Error(`Requires signed in user`)
}
if (listUri) { if (listUri) {
await agent.app.bsky.graph.list.delete({ await pdsClient.delete(app.bsky.graph.list, {
repo: agent.session.did, repo: did,
rkey: new AtUri(listUri).rkey, rkey: new AtUri(listUri).rkeySafe,
}) })
} }
await agent.app.bsky.graph.starterpack.delete({ await pdsClient.delete(app.bsky.graph.starterpack, {
repo: agent.session.did, repo: did,
rkey, rkey,
}) })
}, },
onSuccess: async (_, {listUri, rkey}) => { onSuccess: async (_, {listUri, rkey}) => {
const uri = createStarterPackUri({ const uri = createStarterPackUri({
did: agent.session!.did, did: pdsClient.assertDid,
rkey, rkey,
}) })
if (uri) { if (uri) {
await whenAppViewReady(agent, uri, v => { await whenAppViewReady(appviewClient, uri, v => {
return Boolean(v?.data?.starterPack) === false return Boolean(v?.starterPack) === false
}) })
} }
@@ -330,11 +339,11 @@ export function useDeleteStarterPackMutation({
} }
await invalidateActorStarterPacksQuery({ await invalidateActorStarterPacksQuery({
queryClient, queryClient,
did: agent.session!.did, did: pdsClient.assertDid,
}) })
await invalidateStarterPack({ await invalidateStarterPack({
queryClient, queryClient,
did: agent.session!.did, did: pdsClient.assertDid,
rkey, rkey,
}) })
onSuccess() onSuccess()
@@ -346,15 +355,18 @@ export function useDeleteStarterPackMutation({
} }
async function whenAppViewReady( async function whenAppViewReady(
agent: AtpAgent, client: Client,
uri: string, uri: string,
fn: (res?: AppBskyGraphGetStarterPack.Response) => boolean, fn: (res?: app.bsky.graph.getStarterPack.$OutputBody) => boolean,
) { ) {
await until( await until(
5, // 5 tries 5, // 5 tries
1e3, // 1s delay between tries 1e3, // 1s delay between tries
fn, fn,
() => agent.app.bsky.graph.getStarterPack({starterPack: uri}), () =>
client.call(app.bsky.graph.getStarterPack, {
starterPack: uri as AtUriString,
}),
) )
} }