Replace getAgent() with reading agent (#4243)

* Replace getAgent() with agent

* Replace {agent} with agent
zio/stable
dan 2024-05-28 16:37:51 +01:00 committed by GitHub
parent 8a2f43c218
commit 9bd411c151
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
74 changed files with 400 additions and 438 deletions

View File

@ -36,7 +36,7 @@ export function SubmitView({
}) { }) {
const t = useTheme() const t = useTheme()
const {_} = useLingui() const {_} = useLingui()
const {getAgent} = useAgent() const agent = useAgent()
const [details, setDetails] = React.useState<string>('') const [details, setDetails] = React.useState<string>('')
const [submitting, setSubmitting] = React.useState<boolean>(false) const [submitting, setSubmitting] = React.useState<boolean>(false)
const [selectedServices, setSelectedServices] = React.useState<string[]>([ const [selectedServices, setSelectedServices] = React.useState<string[]>([
@ -62,7 +62,7 @@ export function SubmitView({
} }
const results = await Promise.all( const results = await Promise.all(
selectedServices.map(did => selectedServices.map(did =>
getAgent() agent
.withProxy('atproto_labeler', did) .withProxy('atproto_labeler', did)
.createModerationReport(report) .createModerationReport(report)
.then( .then(
@ -92,7 +92,7 @@ export function SubmitView({
selectedServices, selectedServices,
onSubmitComplete, onSubmitComplete,
setError, setError,
getAgent, agent,
]) ])
return ( return (

View File

@ -102,7 +102,7 @@ function SubmitStep({
const t = useTheme() const t = useTheme()
const [details, setDetails] = useState('') const [details, setDetails] = useState('')
const control = Dialog.useDialogContext() const control = Dialog.useDialogContext()
const {getAgent} = useAgent() const agent = useAgent()
const { const {
mutate: submit, mutate: submit,
@ -124,7 +124,7 @@ function SubmitStep({
reason: details, reason: details,
} satisfies ComAtprotoModerationCreateReport.InputSchema } satisfies ComAtprotoModerationCreateReport.InputSchema
await getAgent().createModerationReport(report) await agent.createModerationReport(report)
} }
}, },
onSuccess: () => { onSuccess: () => {

View File

@ -7,7 +7,7 @@ export function useRichText(text: string): [RichTextAPI, boolean] {
const [prevText, setPrevText] = React.useState(text) const [prevText, setPrevText] = React.useState(text)
const [rawRT, setRawRT] = React.useState(() => new RichTextAPI({text})) const [rawRT, setRawRT] = React.useState(() => new RichTextAPI({text}))
const [resolvedRT, setResolvedRT] = React.useState<RichTextAPI | null>(null) const [resolvedRT, setResolvedRT] = React.useState<RichTextAPI | null>(null)
const {getAgent} = useAgent() const agent = useAgent()
if (text !== prevText) { if (text !== prevText) {
setPrevText(text) setPrevText(text)
setRawRT(new RichTextAPI({text})) setRawRT(new RichTextAPI({text}))
@ -19,7 +19,7 @@ export function useRichText(text: string): [RichTextAPI, boolean] {
async function resolveRTFacets() { async function resolveRTFacets() {
// new each time // new each time
const resolvedRT = new RichTextAPI({text}) const resolvedRT = new RichTextAPI({text})
await resolvedRT.detectFacets(getAgent()) await resolvedRT.detectFacets(agent)
if (!ignore) { if (!ignore) {
setResolvedRT(resolvedRT) setResolvedRT(resolvedRT)
} }
@ -28,7 +28,7 @@ export function useRichText(text: string): [RichTextAPI, boolean] {
return () => { return () => {
ignore = true ignore = true
} }
}, [text, getAgent]) }, [text, agent])
const isResolving = resolvedRT === null const isResolving = resolvedRT === null
return [resolvedRT ?? rawRT, isResolving] return [resolvedRT ?? rawRT, isResolving]
} }

View File

@ -202,14 +202,14 @@ function AppealForm({
const {gtMobile} = useBreakpoints() const {gtMobile} = useBreakpoints()
const [details, setDetails] = React.useState('') const [details, setDetails] = React.useState('')
const isAccountReport = 'did' in subject const isAccountReport = 'did' in subject
const {getAgent} = useAgent() const agent = useAgent()
const {mutate, isPending} = useMutation({ const {mutate, isPending} = useMutation({
mutationFn: async () => { mutationFn: async () => {
const $type = !isAccountReport const $type = !isAccountReport
? 'com.atproto.repo.strongRef' ? 'com.atproto.repo.strongRef'
: 'com.atproto.admin.defs#repoRef' : 'com.atproto.admin.defs#repoRef'
await getAgent() await agent
.withProxy('atproto_labeler', label.src) .withProxy('atproto_labeler', label.src)
.createModerationReport({ .createModerationReport({
reasonType: ComAtprotoModerationDefs.REASONAPPEAL, reasonType: ComAtprotoModerationDefs.REASONAPPEAL,

View File

@ -7,22 +7,22 @@ import {
import {FeedAPI, FeedAPIResponse} from './types' import {FeedAPI, FeedAPIResponse} from './types'
export class AuthorFeedAPI implements FeedAPI { export class AuthorFeedAPI implements FeedAPI {
getAgent: () => BskyAgent agent: BskyAgent
params: GetAuthorFeed.QueryParams params: GetAuthorFeed.QueryParams
constructor({ constructor({
getAgent, agent,
feedParams, feedParams,
}: { }: {
getAgent: () => BskyAgent agent: BskyAgent
feedParams: GetAuthorFeed.QueryParams feedParams: GetAuthorFeed.QueryParams
}) { }) {
this.getAgent = getAgent this.agent = agent
this.params = feedParams this.params = feedParams
} }
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
const res = await this.getAgent().getAuthorFeed({ const res = await this.agent.getAuthorFeed({
...this.params, ...this.params,
limit: 1, limit: 1,
}) })
@ -36,7 +36,7 @@ export class AuthorFeedAPI implements FeedAPI {
cursor: string | undefined cursor: string | undefined
limit: number limit: number
}): Promise<FeedAPIResponse> { }): Promise<FeedAPIResponse> {
const res = await this.getAgent().getAuthorFeed({ const res = await this.agent.getAuthorFeed({
...this.params, ...this.params,
cursor, cursor,
limit, limit,

View File

@ -10,27 +10,27 @@ import {FeedAPI, FeedAPIResponse} from './types'
import {createBskyTopicsHeader, isBlueskyOwnedFeed} from './utils' import {createBskyTopicsHeader, isBlueskyOwnedFeed} from './utils'
export class CustomFeedAPI implements FeedAPI { export class CustomFeedAPI implements FeedAPI {
getAgent: () => BskyAgent agent: BskyAgent
params: GetCustomFeed.QueryParams params: GetCustomFeed.QueryParams
userInterests?: string userInterests?: string
constructor({ constructor({
getAgent, agent,
feedParams, feedParams,
userInterests, userInterests,
}: { }: {
getAgent: () => BskyAgent agent: BskyAgent
feedParams: GetCustomFeed.QueryParams feedParams: GetCustomFeed.QueryParams
userInterests?: string userInterests?: string
}) { }) {
this.getAgent = getAgent this.agent = agent
this.params = feedParams this.params = feedParams
this.userInterests = userInterests this.userInterests = userInterests
} }
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
const contentLangs = getContentLanguages().join(',') const contentLangs = getContentLanguages().join(',')
const res = await this.getAgent().app.bsky.feed.getFeed( const res = await this.agent.app.bsky.feed.getFeed(
{ {
...this.params, ...this.params,
limit: 1, limit: 1,
@ -48,11 +48,11 @@ export class CustomFeedAPI implements FeedAPI {
limit: number limit: number
}): Promise<FeedAPIResponse> { }): Promise<FeedAPIResponse> {
const contentLangs = getContentLanguages().join(',') const contentLangs = getContentLanguages().join(',')
const agent = this.getAgent() const agent = this.agent
const isBlueskyOwned = isBlueskyOwnedFeed(this.params.feed) const isBlueskyOwned = isBlueskyOwnedFeed(this.params.feed)
const res = agent.session const res = agent.session
? await this.getAgent().app.bsky.feed.getFeed( ? await this.agent.app.bsky.feed.getFeed(
{ {
...this.params, ...this.params,
cursor, cursor,

View File

@ -3,14 +3,14 @@ import {AppBskyFeedDefs, BskyAgent} from '@atproto/api'
import {FeedAPI, FeedAPIResponse} from './types' import {FeedAPI, FeedAPIResponse} from './types'
export class FollowingFeedAPI implements FeedAPI { export class FollowingFeedAPI implements FeedAPI {
getAgent: () => BskyAgent agent: BskyAgent
constructor({getAgent}: {getAgent: () => BskyAgent}) { constructor({agent}: {agent: BskyAgent}) {
this.getAgent = getAgent this.agent = agent
} }
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
const res = await this.getAgent().getTimeline({ const res = await this.agent.getTimeline({
limit: 1, limit: 1,
}) })
return res.data.feed[0] return res.data.feed[0]
@ -23,7 +23,7 @@ export class FollowingFeedAPI implements FeedAPI {
cursor: string | undefined cursor: string | undefined
limit: number limit: number
}): Promise<FeedAPIResponse> { }): Promise<FeedAPIResponse> {
const res = await this.getAgent().getTimeline({ const res = await this.agent.getTimeline({
cursor, cursor,
limit, limit,
}) })

View File

@ -27,7 +27,7 @@ export const FALLBACK_MARKER_POST: AppBskyFeedDefs.FeedViewPost = {
} }
export class HomeFeedAPI implements FeedAPI { export class HomeFeedAPI implements FeedAPI {
getAgent: () => BskyAgent agent: BskyAgent
following: FollowingFeedAPI following: FollowingFeedAPI
discover: CustomFeedAPI discover: CustomFeedAPI
usingDiscover = false usingDiscover = false
@ -36,24 +36,24 @@ export class HomeFeedAPI implements FeedAPI {
constructor({ constructor({
userInterests, userInterests,
getAgent, agent,
}: { }: {
userInterests?: string userInterests?: string
getAgent: () => BskyAgent agent: BskyAgent
}) { }) {
this.getAgent = getAgent this.agent = agent
this.following = new FollowingFeedAPI({getAgent}) this.following = new FollowingFeedAPI({agent})
this.discover = new CustomFeedAPI({ this.discover = new CustomFeedAPI({
getAgent, agent,
feedParams: {feed: PROD_DEFAULT_FEED('whats-hot')}, feedParams: {feed: PROD_DEFAULT_FEED('whats-hot')},
}) })
this.userInterests = userInterests this.userInterests = userInterests
} }
reset() { reset() {
this.following = new FollowingFeedAPI({getAgent: this.getAgent}) this.following = new FollowingFeedAPI({agent: this.agent})
this.discover = new CustomFeedAPI({ this.discover = new CustomFeedAPI({
getAgent: this.getAgent, agent: this.agent,
feedParams: {feed: PROD_DEFAULT_FEED('whats-hot')}, feedParams: {feed: PROD_DEFAULT_FEED('whats-hot')},
userInterests: this.userInterests, userInterests: this.userInterests,
}) })

View File

@ -7,22 +7,22 @@ import {
import {FeedAPI, FeedAPIResponse} from './types' import {FeedAPI, FeedAPIResponse} from './types'
export class LikesFeedAPI implements FeedAPI { export class LikesFeedAPI implements FeedAPI {
getAgent: () => BskyAgent agent: BskyAgent
params: GetActorLikes.QueryParams params: GetActorLikes.QueryParams
constructor({ constructor({
getAgent, agent,
feedParams, feedParams,
}: { }: {
getAgent: () => BskyAgent agent: BskyAgent
feedParams: GetActorLikes.QueryParams feedParams: GetActorLikes.QueryParams
}) { }) {
this.getAgent = getAgent this.agent = agent
this.params = feedParams this.params = feedParams
} }
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
const res = await this.getAgent().getActorLikes({ const res = await this.agent.getActorLikes({
...this.params, ...this.params,
limit: 1, limit: 1,
}) })
@ -36,7 +36,7 @@ export class LikesFeedAPI implements FeedAPI {
cursor: string | undefined cursor: string | undefined
limit: number limit: number
}): Promise<FeedAPIResponse> { }): Promise<FeedAPIResponse> {
const res = await this.getAgent().getActorLikes({ const res = await this.agent.getActorLikes({
...this.params, ...this.params,
cursor, cursor,
limit, limit,

View File

@ -7,22 +7,22 @@ import {
import {FeedAPI, FeedAPIResponse} from './types' import {FeedAPI, FeedAPIResponse} from './types'
export class ListFeedAPI implements FeedAPI { export class ListFeedAPI implements FeedAPI {
getAgent: () => BskyAgent agent: BskyAgent
params: GetListFeed.QueryParams params: GetListFeed.QueryParams
constructor({ constructor({
getAgent, agent,
feedParams, feedParams,
}: { }: {
getAgent: () => BskyAgent agent: BskyAgent
feedParams: GetListFeed.QueryParams feedParams: GetListFeed.QueryParams
}) { }) {
this.getAgent = getAgent this.agent = agent
this.params = feedParams this.params = feedParams
} }
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
const res = await this.getAgent().app.bsky.feed.getListFeed({ const res = await this.agent.app.bsky.feed.getListFeed({
...this.params, ...this.params,
limit: 1, limit: 1,
}) })
@ -36,7 +36,7 @@ export class ListFeedAPI implements FeedAPI {
cursor: string | undefined cursor: string | undefined
limit: number limit: number
}): Promise<FeedAPIResponse> { }): Promise<FeedAPIResponse> {
const res = await this.getAgent().app.bsky.feed.getListFeed({ const res = await this.agent.app.bsky.feed.getListFeed({
...this.params, ...this.params,
cursor, cursor,
limit, limit,

View File

@ -16,7 +16,7 @@ const POST_AGE_CUTOFF = 60e3 * 60 * 24 // 24hours
export class MergeFeedAPI implements FeedAPI { export class MergeFeedAPI implements FeedAPI {
userInterests?: string userInterests?: string
getAgent: () => BskyAgent agent: BskyAgent
params: FeedParams params: FeedParams
feedTuners: FeedTunerFn[] feedTuners: FeedTunerFn[]
following: MergeFeedSource_Following following: MergeFeedSource_Following
@ -26,29 +26,29 @@ export class MergeFeedAPI implements FeedAPI {
sampleCursor = 0 sampleCursor = 0
constructor({ constructor({
getAgent, agent,
feedParams, feedParams,
feedTuners, feedTuners,
userInterests, userInterests,
}: { }: {
getAgent: () => BskyAgent agent: BskyAgent
feedParams: FeedParams feedParams: FeedParams
feedTuners: FeedTunerFn[] feedTuners: FeedTunerFn[]
userInterests?: string userInterests?: string
}) { }) {
this.getAgent = getAgent this.agent = agent
this.params = feedParams this.params = feedParams
this.feedTuners = feedTuners this.feedTuners = feedTuners
this.userInterests = userInterests this.userInterests = userInterests
this.following = new MergeFeedSource_Following({ this.following = new MergeFeedSource_Following({
getAgent: this.getAgent, agent: this.agent,
feedTuners: this.feedTuners, feedTuners: this.feedTuners,
}) })
} }
reset() { reset() {
this.following = new MergeFeedSource_Following({ this.following = new MergeFeedSource_Following({
getAgent: this.getAgent, agent: this.agent,
feedTuners: this.feedTuners, feedTuners: this.feedTuners,
}) })
this.customFeeds = [] this.customFeeds = []
@ -60,7 +60,7 @@ export class MergeFeedAPI implements FeedAPI {
this.params.mergeFeedSources.map( this.params.mergeFeedSources.map(
feedUri => feedUri =>
new MergeFeedSource_Custom({ new MergeFeedSource_Custom({
getAgent: this.getAgent, agent: this.agent,
feedUri, feedUri,
feedTuners: this.feedTuners, feedTuners: this.feedTuners,
userInterests: this.userInterests, userInterests: this.userInterests,
@ -73,7 +73,7 @@ export class MergeFeedAPI implements FeedAPI {
} }
async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
const res = await this.getAgent().getTimeline({ const res = await this.agent.getTimeline({
limit: 1, limit: 1,
}) })
return res.data.feed[0] return res.data.feed[0]
@ -167,7 +167,7 @@ export class MergeFeedAPI implements FeedAPI {
} }
class MergeFeedSource { class MergeFeedSource {
getAgent: () => BskyAgent agent: BskyAgent
feedTuners: FeedTunerFn[] feedTuners: FeedTunerFn[]
sourceInfo: ReasonFeedSource | undefined sourceInfo: ReasonFeedSource | undefined
cursor: string | undefined = undefined cursor: string | undefined = undefined
@ -175,13 +175,13 @@ class MergeFeedSource {
hasMore = true hasMore = true
constructor({ constructor({
getAgent, agent,
feedTuners, feedTuners,
}: { }: {
getAgent: () => BskyAgent agent: BskyAgent
feedTuners: FeedTunerFn[] feedTuners: FeedTunerFn[]
}) { }) {
this.getAgent = getAgent this.agent = agent
this.feedTuners = feedTuners this.feedTuners = feedTuners
} }
@ -245,7 +245,7 @@ class MergeFeedSource_Following extends MergeFeedSource {
cursor: string | undefined, cursor: string | undefined,
limit: number, limit: number,
): Promise<AppBskyFeedGetTimeline.Response> { ): Promise<AppBskyFeedGetTimeline.Response> {
const res = await this.getAgent().getTimeline({cursor, limit}) const res = await this.agent.getTimeline({cursor, limit})
// run the tuner pre-emptively to ensure better mixing // run the tuner pre-emptively to ensure better mixing
const slices = this.tuner.tune(res.data.feed, { const slices = this.tuner.tune(res.data.feed, {
dryRun: false, dryRun: false,
@ -257,27 +257,27 @@ class MergeFeedSource_Following extends MergeFeedSource {
} }
class MergeFeedSource_Custom extends MergeFeedSource { class MergeFeedSource_Custom extends MergeFeedSource {
getAgent: () => BskyAgent agent: BskyAgent
minDate: Date minDate: Date
feedUri: string feedUri: string
userInterests?: string userInterests?: string
constructor({ constructor({
getAgent, agent,
feedUri, feedUri,
feedTuners, feedTuners,
userInterests, userInterests,
}: { }: {
getAgent: () => BskyAgent agent: BskyAgent
feedUri: string feedUri: string
feedTuners: FeedTunerFn[] feedTuners: FeedTunerFn[]
userInterests?: string userInterests?: string
}) { }) {
super({ super({
getAgent, agent,
feedTuners, feedTuners,
}) })
this.getAgent = getAgent this.agent = agent
this.feedUri = feedUri this.feedUri = feedUri
this.userInterests = userInterests this.userInterests = userInterests
this.sourceInfo = { this.sourceInfo = {
@ -295,7 +295,7 @@ class MergeFeedSource_Custom extends MergeFeedSource {
try { try {
const contentLangs = getContentLanguages().join(',') const contentLangs = getContentLanguages().join(',')
const isBlueskyOwned = isBlueskyOwnedFeed(this.feedUri) const isBlueskyOwned = isBlueskyOwnedFeed(this.feedUri)
const res = await this.getAgent().app.bsky.feed.getFeed( const res = await this.agent.app.bsky.feed.getFeed(
{ {
cursor, cursor,
limit, limit,

View File

@ -14,12 +14,12 @@ const SERVICE_DID = (serviceUrl?: string) =>
: 'did:web:api.bsky.app' : 'did:web:api.bsky.app'
async function registerPushToken( async function registerPushToken(
getAgent: () => BskyAgent, agent: BskyAgent,
account: SessionAccount, account: SessionAccount,
token: Notifications.DevicePushToken, token: Notifications.DevicePushToken,
) { ) {
try { try {
await getAgent().api.app.bsky.notification.registerPush({ await agent.api.app.bsky.notification.registerPush({
serviceDid: SERVICE_DID(account.service), serviceDid: SERVICE_DID(account.service),
platform: devicePlatform, platform: devicePlatform,
token: token.data, token: token.data,
@ -47,7 +47,7 @@ async function getPushToken(skipPermissionCheck = false) {
} }
export function useNotificationsRegistration() { export function useNotificationsRegistration() {
const {getAgent} = useAgent() const agent = useAgent()
const {currentAccount} = useSession() const {currentAccount} = useSession()
React.useEffect(() => { React.useEffect(() => {
@ -60,13 +60,13 @@ export function useNotificationsRegistration() {
// According to the Expo docs, there is a chance that the token will change while the app is open in some rare // According to the Expo docs, there is a chance that the token will change while the app is open in some rare
// cases. This will fire `registerPushToken` whenever that happens. // cases. This will fire `registerPushToken` whenever that happens.
const subscription = Notifications.addPushTokenListener(async newToken => { const subscription = Notifications.addPushTokenListener(async newToken => {
registerPushToken(getAgent, currentAccount, newToken) registerPushToken(agent, currentAccount, newToken)
}) })
return () => { return () => {
subscription.remove() subscription.remove()
} }
}, [currentAccount, getAgent]) }, [currentAccount, agent])
} }
export function useRequestNotificationsPermission() { export function useRequestNotificationsPermission() {

View File

@ -24,7 +24,7 @@ export function Deactivated() {
const {gtMobile} = useBreakpoints() const {gtMobile} = useBreakpoints()
const onboardingDispatch = useOnboardingDispatch() const onboardingDispatch = useOnboardingDispatch()
const {logout} = useSessionApi() const {logout} = useSessionApi()
const {getAgent} = useAgent() const agent = useAgent()
const [isProcessing, setProcessing] = React.useState(false) const [isProcessing, setProcessing] = React.useState(false)
const [estimatedTime, setEstimatedTime] = React.useState<string | undefined>( const [estimatedTime, setEstimatedTime] = React.useState<string | undefined>(
@ -37,11 +37,11 @@ export function Deactivated() {
const checkStatus = React.useCallback(async () => { const checkStatus = React.useCallback(async () => {
setProcessing(true) setProcessing(true)
try { try {
const res = await getAgent().com.atproto.temp.checkSignupQueue() const res = await agent.com.atproto.temp.checkSignupQueue()
if (res.data.activated) { if (res.data.activated) {
// ready to go, exchange the access token for a usable one and kick off onboarding // ready to go, exchange the access token for a usable one and kick off onboarding
await getAgent().refreshSession() await agent.refreshSession()
if (!isSessionDeactivated(getAgent().session?.accessJwt)) { if (!isSessionDeactivated(agent.session?.accessJwt)) {
onboardingDispatch({type: 'start'}) onboardingDispatch({type: 'start'})
} }
} else { } else {
@ -61,7 +61,7 @@ export function Deactivated() {
setEstimatedTime, setEstimatedTime,
setPlaceInQueue, setPlaceInQueue,
onboardingDispatch, onboardingDispatch,
getAgent, agent,
]) ])
React.useEffect(() => { React.useEffect(() => {

View File

@ -66,14 +66,14 @@ function DialogInner() {
const control = Dialog.useDialogContext() const control = Dialog.useDialogContext()
const [details, setDetails] = useState('') const [details, setDetails] = useState('')
const {gtMobile} = useBreakpoints() const {gtMobile} = useBreakpoints()
const {getAgent} = useAgent() const agent = useAgent()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {mutate, isPending} = useMutation({ const {mutate, isPending} = useMutation({
mutationFn: async () => { mutationFn: async () => {
if (!currentAccount) if (!currentAccount)
throw new Error('No current account, should be unreachable') throw new Error('No current account, should be unreachable')
await getAgent().createModerationReport({ await agent.createModerationReport({
reasonType: ComAtprotoModerationDefs.REASONAPPEAL, reasonType: ComAtprotoModerationDefs.REASONAPPEAL,
subject: { subject: {
$type: 'com.atproto.admin.defs#repoRef', $type: 'com.atproto.admin.defs#repoRef',

View File

@ -79,7 +79,7 @@ export function MessagesList({
footer?: React.ReactNode footer?: React.ReactNode
}) { }) {
const convoState = useConvoActive() const convoState = useConvoActive()
const {getAgent} = useAgent() const agent = useAgent()
const flatListRef = useAnimatedRef<FlatList>() const flatListRef = useAnimatedRef<FlatList>()
@ -265,7 +265,7 @@ export function MessagesList({
const onSendMessage = useCallback( const onSendMessage = useCallback(
async (text: string) => { async (text: string) => {
let rt = new RichText({text}, {cleanNewlines: true}) let rt = new RichText({text}, {cleanNewlines: true})
await rt.detectFacets(getAgent()) await rt.detectFacets(agent)
rt = shortenLinks(rt) rt = shortenLinks(rt)
// filter out any mention facets that didn't map to a user // filter out any mention facets that didn't map to a user
@ -288,7 +288,7 @@ export function MessagesList({
facets: rt.facets, facets: rt.facets,
}) })
}, },
[convoState, getAgent, hasScrolled, setHasScrolled], [convoState, agent, hasScrolled, setHasScrolled],
) )
// -- List layout changes (opening emoji keyboard, etc.) // -- List layout changes (opening emoji keyboard, etc.)

View File

@ -47,7 +47,7 @@ export function StepFinished() {
const [saving, setSaving] = React.useState(false) const [saving, setSaving] = React.useState(false)
const {mutateAsync: overwriteSavedFeeds} = useOverwriteSavedFeedsMutation() const {mutateAsync: overwriteSavedFeeds} = useOverwriteSavedFeedsMutation()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
const gate = useGate() const gate = useGate()
const finishOnboarding = React.useCallback(async () => { const finishOnboarding = React.useCallback(async () => {
@ -70,12 +70,12 @@ export function StepFinished() {
try { try {
await Promise.all([ await Promise.all([
bulkWriteFollows( bulkWriteFollows(
getAgent, agent,
suggestedAccountsStepResults.accountDids.concat(BSKY_APP_ACCOUNT_DID), suggestedAccountsStepResults.accountDids.concat(BSKY_APP_ACCOUNT_DID),
), ),
// these must be serial // these must be serial
(async () => { (async () => {
await getAgent().setInterestsPref({tags: selectedInterests}) await agent.setInterestsPref({tags: selectedInterests})
/* /*
* In the reduced onboading experiment, we'll rely on the default * In the reduced onboading experiment, we'll rely on the default
@ -98,7 +98,7 @@ export function StepFinished() {
* (mimics old behavior) * (mimics old behavior)
*/ */
if ( if (
IS_PROD_SERVICE(getAgent().service.toString()) && IS_PROD_SERVICE(agent.service.toString()) &&
!otherFeeds.length !otherFeeds.length
) { ) {
otherFeeds.push({ otherFeeds.push({
@ -124,8 +124,8 @@ export function StepFinished() {
const {imageUri, imageMime} = profileStepResults const {imageUri, imageMime} = profileStepResults
if (imageUri && imageMime) { if (imageUri && imageMime) {
const blobPromise = uploadBlob(getAgent(), imageUri, imageMime) const blobPromise = uploadBlob(agent, imageUri, imageMime)
await getAgent().upsertProfile(async existing => { await agent.upsertProfile(async existing => {
existing = existing ?? {} existing = existing ?? {}
const res = await blobPromise const res = await blobPromise
if (res.data.blob) { if (res.data.blob) {
@ -156,7 +156,7 @@ export function StepFinished() {
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
}), }),
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: profileRQKey(getAgent().session?.did ?? ''), queryKey: profileRQKey(agent.session?.did ?? ''),
}), }),
]).catch(e => { ]).catch(e => {
logger.error(e) logger.error(e)
@ -176,7 +176,7 @@ export function StepFinished() {
setSaving, setSaving,
overwriteSavedFeeds, overwriteSavedFeeds,
track, track,
getAgent, agent,
gate, gate,
queryClient, queryClient,
]) ])

View File

@ -43,13 +43,12 @@ export function StepInterests() {
state.interestsStepResults.selectedInterests.map(i => i), state.interestsStepResults.selectedInterests.map(i => i),
) )
const onboardDispatch = useOnboardingDispatch() const onboardDispatch = useOnboardingDispatch()
const {getAgent} = useAgent() const agent = useAgent()
const {isLoading, isError, error, data, refetch, isFetching} = useQuery({ const {isLoading, isError, error, data, refetch, isFetching} = useQuery({
queryKey: ['interests'], queryKey: ['interests'],
queryFn: async () => { queryFn: async () => {
try { try {
const {data} = const {data} = await agent.app.bsky.unspecced.getTaggedSuggestions()
await getAgent().app.bsky.unspecced.getTaggedSuggestions()
return data.suggestions.reduce( return data.suggestions.reduce(
(agg, s) => { (agg, s) => {
const {tag, subject, subjectType} = s const {tag, subject, subjectType} = s

View File

@ -66,11 +66,8 @@ export function aggregateInterestItems(
return Array.from(new Set(results)).slice(0, 20) return Array.from(new Set(results)).slice(0, 20)
} }
export async function bulkWriteFollows( export async function bulkWriteFollows(agent: BskyAgent, dids: string[]) {
getAgent: () => BskyAgent, const session = agent.session
dids: string[],
) {
const session = getAgent().session
if (!session) { if (!session) {
throw new Error(`bulkWriteFollows failed: no session`) throw new Error(`bulkWriteFollows failed: no session`)
@ -89,19 +86,15 @@ export async function bulkWriteFollows(
value: r, value: r,
})) }))
await getAgent().com.atproto.repo.applyWrites({ await agent.com.atproto.repo.applyWrites({
repo: session.did, repo: session.did,
writes: followWrites, writes: followWrites,
}) })
await whenFollowsIndexed( await whenFollowsIndexed(agent, session.did, res => !!res.data.follows.length)
getAgent,
session.did,
res => !!res.data.follows.length,
)
} }
async function whenFollowsIndexed( async function whenFollowsIndexed(
getAgent: () => BskyAgent, agent: BskyAgent,
actor: string, actor: string,
fn: (res: AppBskyGraphGetFollows.Response) => boolean, fn: (res: AppBskyGraphGetFollows.Response) => boolean,
) { ) {
@ -110,7 +103,7 @@ async function whenFollowsIndexed(
1e3, // 1s delay between tries 1e3, // 1s delay between tries
fn, fn,
() => () =>
getAgent().app.bsky.graph.getFollows({ agent.app.bsky.graph.getFollows({
actor, actor,
limit: 1, limit: 1,
}), }),

View File

@ -36,7 +36,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
const [state, dispatch] = React.useReducer(reducer, initialState) const [state, dispatch] = React.useReducer(reducer, initialState)
const submit = useSubmitSignup({state, dispatch}) const submit = useSubmitSignup({state, dispatch})
const {gtMobile} = useBreakpoints() const {gtMobile} = useBreakpoints()
const {getAgent} = useAgent() const agent = useAgent()
const { const {
data: serviceInfo, data: serviceInfo,
@ -77,7 +77,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
try { try {
dispatch({type: 'setIsLoading', value: true}) dispatch({type: 'setIsLoading', value: true})
const res = await getAgent().resolveHandle({ const res = await agent.resolveHandle({
handle: createFullHandle(state.handle, state.userDomain), handle: createFullHandle(state.handle, state.userDomain),
}) })
@ -115,7 +115,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) {
state.serviceDescription?.phoneVerificationRequired, state.serviceDescription?.phoneVerificationRequired,
state.userDomain, state.userDomain,
submit, submit,
getAgent, agent,
]) ])
const onBackPress = React.useCallback(() => { const onBackPress = React.useCallback(() => {

View File

@ -25,7 +25,7 @@ const stateContext = React.createContext<StateContext>({
}) })
export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) { export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) {
const {getAgent} = useAgent() const agent = useAgent()
const enabled = isDiscoverFeed(feed) && hasSession const enabled = isDiscoverFeed(feed) && hasSession
const queue = React.useRef<Set<string>>(new Set()) const queue = React.useRef<Set<string>>(new Set())
const history = React.useRef< const history = React.useRef<
@ -35,7 +35,7 @@ export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) {
>(new WeakSet()) >(new WeakSet())
const sendToFeedNoDelay = React.useCallback(() => { const sendToFeedNoDelay = React.useCallback(() => {
const proxyAgent = getAgent().withProxy( const proxyAgent = agent.withProxy(
// @ts-ignore TODO need to update withProxy() to support this key -prf // @ts-ignore TODO need to update withProxy() to support this key -prf
'bsky_fg', 'bsky_fg',
// TODO when we start sending to other feeds, we need to grab their DID -prf // TODO when we start sending to other feeds, we need to grab their DID -prf
@ -50,7 +50,7 @@ export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) {
.catch((e: any) => { .catch((e: any) => {
logger.warn('Failed to send feed interactions', {error: e}) logger.warn('Failed to send feed interactions', {error: e})
}) })
}, [getAgent]) }, [agent])
const sendToFeed = React.useMemo( const sendToFeed = React.useMemo(
() => () =>

View File

@ -58,13 +58,13 @@ export function ConvoProvider({
convoId, convoId,
}: Pick<ConvoParams, 'convoId'> & {children: React.ReactNode}) { }: Pick<ConvoParams, 'convoId'> & {children: React.ReactNode}) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
const events = useMessagesEventBus() const events = useMessagesEventBus()
const [convo] = useState( const [convo] = useState(
() => () =>
new Convo({ new Convo({
convoId, convoId,
agent: getAgent(), agent,
events, events,
}), }),
) )

View File

@ -43,11 +43,11 @@ export function MessagesEventBusProviderInner({
}: { }: {
children: React.ReactNode children: React.ReactNode
}) { }) {
const {getAgent} = useAgent() const agent = useAgent()
const [bus] = React.useState( const [bus] = React.useState(
() => () =>
new MessagesEventBus({ new MessagesEventBus({
agent: getAgent(), agent,
}), }),
) )

View File

@ -23,7 +23,7 @@ export function useActorAutocompleteQuery(
limit?: number, limit?: number,
) { ) {
const moderationOpts = useModerationOpts() const moderationOpts = useModerationOpts()
const {getAgent} = useAgent() const agent = useAgent()
prefix = prefix.toLowerCase().trim() prefix = prefix.toLowerCase().trim()
if (prefix.endsWith('.')) { if (prefix.endsWith('.')) {
@ -36,7 +36,7 @@ export function useActorAutocompleteQuery(
queryKey: RQKEY(prefix || ''), queryKey: RQKEY(prefix || ''),
async queryFn() { async queryFn() {
const res = prefix const res = prefix
? await getAgent().searchActorsTypeahead({ ? await agent.searchActorsTypeahead({
q: prefix, q: prefix,
limit: limit || 8, limit: limit || 8,
}) })
@ -57,7 +57,7 @@ export type ActorAutocompleteFn = ReturnType<typeof useActorAutocompleteFn>
export function useActorAutocompleteFn() { export function useActorAutocompleteFn() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const moderationOpts = useModerationOpts() const moderationOpts = useModerationOpts()
const {getAgent} = useAgent() const agent = useAgent()
return React.useCallback( return React.useCallback(
async ({query, limit = 8}: {query: string; limit?: number}) => { async ({query, limit = 8}: {query: string; limit?: number}) => {
@ -69,7 +69,7 @@ export function useActorAutocompleteFn() {
staleTime: STALE.MINUTES.ONE, staleTime: STALE.MINUTES.ONE,
queryKey: RQKEY(query || ''), queryKey: RQKEY(query || ''),
queryFn: () => queryFn: () =>
getAgent().searchActorsTypeahead({ agent.searchActorsTypeahead({
q: query, q: query,
limit, limit,
}), }),
@ -86,7 +86,7 @@ export function useActorAutocompleteFn() {
moderationOpts || DEFAULT_MOD_OPTS, moderationOpts || DEFAULT_MOD_OPTS,
) )
}, },
[queryClient, moderationOpts, getAgent], [queryClient, moderationOpts, agent],
) )
} }

View File

@ -14,12 +14,12 @@ export function useActorSearch({
query: string query: string
enabled?: boolean enabled?: boolean
}) { }) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<AppBskyActorDefs.ProfileView[]>({ return useQuery<AppBskyActorDefs.ProfileView[]>({
staleTime: STALE.MINUTES.ONE, staleTime: STALE.MINUTES.ONE,
queryKey: RQKEY(query || ''), queryKey: RQKEY(query || ''),
async queryFn() { async queryFn() {
const res = await getAgent().searchActors({ const res = await agent.searchActors({
q: query, q: query,
}) })
return res.data.actors return res.data.actors

View File

@ -8,12 +8,12 @@ const RQKEY_ROOT = 'app-passwords'
export const RQKEY = () => [RQKEY_ROOT] export const RQKEY = () => [RQKEY_ROOT]
export function useAppPasswordsQuery() { export function useAppPasswordsQuery() {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
staleTime: STALE.MINUTES.FIVE, staleTime: STALE.MINUTES.FIVE,
queryKey: RQKEY(), queryKey: RQKEY(),
queryFn: async () => { queryFn: async () => {
const res = await getAgent().com.atproto.server.listAppPasswords({}) const res = await agent.com.atproto.server.listAppPasswords({})
return res.data.passwords return res.data.passwords
}, },
}) })
@ -21,7 +21,7 @@ export function useAppPasswordsQuery() {
export function useAppPasswordCreateMutation() { export function useAppPasswordCreateMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation< return useMutation<
ComAtprotoServerCreateAppPassword.OutputSchema, ComAtprotoServerCreateAppPassword.OutputSchema,
Error, Error,
@ -29,7 +29,7 @@ export function useAppPasswordCreateMutation() {
>({ >({
mutationFn: async ({name, privileged}) => { mutationFn: async ({name, privileged}) => {
return ( return (
await getAgent().com.atproto.server.createAppPassword({ await agent.com.atproto.server.createAppPassword({
name, name,
privileged, privileged,
}) })
@ -45,10 +45,10 @@ export function useAppPasswordCreateMutation() {
export function useAppPasswordDeleteMutation() { export function useAppPasswordDeleteMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {name: string}>({ return useMutation<void, Error, {name: string}>({
mutationFn: async ({name}) => { mutationFn: async ({name}) => {
await getAgent().com.atproto.server.revokeAppPassword({ await agent.com.atproto.server.revokeAppPassword({
name, name,
}) })
}, },

View File

@ -147,7 +147,7 @@ export function getAvatarTypeFromUri(uri: string) {
export function useFeedSourceInfoQuery({uri}: {uri: string}) { export function useFeedSourceInfoQuery({uri}: {uri: string}) {
const type = getFeedTypeFromUri(uri) const type = getFeedTypeFromUri(uri)
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
staleTime: STALE.INFINITY, staleTime: STALE.INFINITY,
@ -156,10 +156,10 @@ export function useFeedSourceInfoQuery({uri}: {uri: string}) {
let view: FeedSourceInfo let view: FeedSourceInfo
if (type === 'feed') { if (type === 'feed') {
const res = await getAgent().app.bsky.feed.getFeedGenerator({feed: uri}) const res = await agent.app.bsky.feed.getFeedGenerator({feed: uri})
view = hydrateFeedGenerator(res.data.view) view = hydrateFeedGenerator(res.data.view)
} else { } else {
const res = await getAgent().app.bsky.graph.getList({ const res = await agent.app.bsky.graph.getList({
list: uri, list: uri,
limit: 1, limit: 1,
}) })
@ -174,7 +174,7 @@ export function useFeedSourceInfoQuery({uri}: {uri: string}) {
export const useGetPopularFeedsQueryKey = ['getPopularFeeds'] export const useGetPopularFeedsQueryKey = ['getPopularFeeds']
export function useGetPopularFeedsQuery() { export function useGetPopularFeedsQuery() {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyUnspeccedGetPopularFeedGenerators.OutputSchema, AppBskyUnspeccedGetPopularFeedGenerators.OutputSchema,
Error, Error,
@ -184,7 +184,7 @@ export function useGetPopularFeedsQuery() {
>({ >({
queryKey: useGetPopularFeedsQueryKey, queryKey: useGetPopularFeedsQueryKey,
queryFn: async ({pageParam}) => { queryFn: async ({pageParam}) => {
const res = await getAgent().app.bsky.unspecced.getPopularFeedGenerators({ const res = await agent.app.bsky.unspecced.getPopularFeedGenerators({
limit: 10, limit: 10,
cursor: pageParam, cursor: pageParam,
}) })
@ -196,10 +196,10 @@ export function useGetPopularFeedsQuery() {
} }
export function useSearchPopularFeedsMutation() { export function useSearchPopularFeedsMutation() {
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async (query: string) => { mutationFn: async (query: string) => {
const res = await getAgent().app.bsky.unspecced.getPopularFeedGenerators({ const res = await agent.app.bsky.unspecced.getPopularFeedGenerators({
limit: 10, limit: 10,
query: query, query: query,
}) })
@ -241,7 +241,7 @@ const pinnedFeedInfosQueryKeyRoot = 'pinnedFeedsInfos'
export function usePinnedFeedsInfos() { export function usePinnedFeedsInfos() {
const {hasSession} = useSession() const {hasSession} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const {data: preferences, isLoading: isLoadingPrefs} = usePreferencesQuery() const {data: preferences, isLoading: isLoadingPrefs} = usePreferencesQuery()
const pinnedItems = preferences?.savedFeeds.filter(feed => feed.pinned) ?? [] const pinnedItems = preferences?.savedFeeds.filter(feed => feed.pinned) ?? []
@ -264,8 +264,8 @@ export function usePinnedFeedsInfos() {
const pinnedFeeds = pinnedItems.filter(feed => feed.type === 'feed') const pinnedFeeds = pinnedItems.filter(feed => feed.type === 'feed')
let feedsPromise = Promise.resolve() let feedsPromise = Promise.resolve()
if (pinnedFeeds.length > 0) { if (pinnedFeeds.length > 0) {
feedsPromise = getAgent() feedsPromise = agent.app.bsky.feed
.app.bsky.feed.getFeedGenerators({ .getFeedGenerators({
feeds: pinnedFeeds.map(f => f.value), feeds: pinnedFeeds.map(f => f.value),
}) })
.then(res => { .then(res => {
@ -279,8 +279,8 @@ export function usePinnedFeedsInfos() {
// Get all lists. This currently has to be done individually. // Get all lists. This currently has to be done individually.
const pinnedLists = pinnedItems.filter(feed => feed.type === 'list') const pinnedLists = pinnedItems.filter(feed => feed.type === 'list')
const listsPromises = pinnedLists.map(list => const listsPromises = pinnedLists.map(list =>
getAgent() agent.app.bsky.graph
.app.bsky.graph.getList({ .getList({
list: list.value, list: list.value,
limit: 1, limit: 1,
}) })

View File

@ -14,7 +14,7 @@ const fetchDidQueryKey = (handleOrDid: string) => [didQueryKeyRoot, handleOrDid]
export function useFetchHandle() { export function useFetchHandle() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return React.useCallback( return React.useCallback(
async (handleOrDid: string) => { async (handleOrDid: string) => {
@ -22,23 +22,23 @@ export function useFetchHandle() {
const res = await queryClient.fetchQuery({ const res = await queryClient.fetchQuery({
staleTime: STALE.MINUTES.FIVE, staleTime: STALE.MINUTES.FIVE,
queryKey: fetchHandleQueryKey(handleOrDid), queryKey: fetchHandleQueryKey(handleOrDid),
queryFn: () => getAgent().getProfile({actor: handleOrDid}), queryFn: () => agent.getProfile({actor: handleOrDid}),
}) })
return res.data.handle return res.data.handle
} }
return handleOrDid return handleOrDid
}, },
[queryClient, getAgent], [queryClient, agent],
) )
} }
export function useUpdateHandleMutation() { export function useUpdateHandleMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async ({handle}: {handle: string}) => { mutationFn: async ({handle}: {handle: string}) => {
await getAgent().updateHandle({handle}) await agent.updateHandle({handle})
}, },
onSuccess(_data, variables) { onSuccess(_data, variables) {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@ -50,7 +50,7 @@ export function useUpdateHandleMutation() {
export function useFetchDid() { export function useFetchDid() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return React.useCallback( return React.useCallback(
async (handleOrDid: string) => { async (handleOrDid: string) => {
@ -60,13 +60,13 @@ export function useFetchDid() {
queryFn: async () => { queryFn: async () => {
let identifier = handleOrDid let identifier = handleOrDid
if (!identifier.startsWith('did:')) { if (!identifier.startsWith('did:')) {
const res = await getAgent().resolveHandle({handle: identifier}) const res = await agent.resolveHandle({handle: identifier})
identifier = res.data.did identifier = res.data.did
} }
return identifier return identifier
}, },
}) })
}, },
[queryClient, getAgent], [queryClient, agent],
) )
} }

View File

@ -16,13 +16,13 @@ export type InviteCodesQueryResponse = Exclude<
undefined undefined
> >
export function useInviteCodesQuery() { export function useInviteCodesQuery() {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
staleTime: STALE.MINUTES.FIVE, staleTime: STALE.MINUTES.FIVE,
queryKey: [inviteCodesQueryKeyRoot], queryKey: [inviteCodesQueryKeyRoot],
queryFn: async () => { queryFn: async () => {
const res = await getAgent() const res = await agent.com.atproto.server
.com.atproto.server.getAccountInviteCodes({}) .getAccountInviteCodes({})
.catch(e => { .catch(e => {
if (cleanError(e) === 'Bad token scope') { if (cleanError(e) === 'Bad token scope') {
return null return null

View File

@ -31,12 +31,12 @@ export function useLabelerInfoQuery({
did?: string did?: string
enabled?: boolean enabled?: boolean
}) { }) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
enabled: !!did && enabled !== false, enabled: !!did && enabled !== false,
queryKey: labelerInfoQueryKey(did as string), queryKey: labelerInfoQueryKey(did as string),
queryFn: async () => { queryFn: async () => {
const res = await getAgent().app.bsky.labeler.getServices({ const res = await agent.app.bsky.labeler.getServices({
dids: [did as string], dids: [did as string],
detailed: true, detailed: true,
}) })
@ -46,26 +46,26 @@ export function useLabelerInfoQuery({
} }
export function useLabelersInfoQuery({dids}: {dids: string[]}) { export function useLabelersInfoQuery({dids}: {dids: string[]}) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
enabled: !!dids.length, enabled: !!dids.length,
queryKey: labelersInfoQueryKey(dids), queryKey: labelersInfoQueryKey(dids),
queryFn: async () => { queryFn: async () => {
const res = await getAgent().app.bsky.labeler.getServices({dids}) const res = await agent.app.bsky.labeler.getServices({dids})
return res.data.views as AppBskyLabelerDefs.LabelerView[] return res.data.views as AppBskyLabelerDefs.LabelerView[]
}, },
}) })
} }
export function useLabelersDetailedInfoQuery({dids}: {dids: string[]}) { export function useLabelersDetailedInfoQuery({dids}: {dids: string[]}) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
enabled: !!dids.length, enabled: !!dids.length,
queryKey: labelersDetailedInfoQueryKey(dids), queryKey: labelersDetailedInfoQueryKey(dids),
gcTime: 1000 * 60 * 60 * 6, // 6 hours gcTime: 1000 * 60 * 60 * 6, // 6 hours
staleTime: STALE.MINUTES.ONE, staleTime: STALE.MINUTES.ONE,
queryFn: async () => { queryFn: async () => {
const res = await getAgent().app.bsky.labeler.getServices({ const res = await agent.app.bsky.labeler.getServices({
dids, dids,
detailed: true, detailed: true,
}) })
@ -76,7 +76,7 @@ export function useLabelersDetailedInfoQuery({dids}: {dids: string[]}) {
export function useLabelerSubscriptionMutation() { export function useLabelerSubscriptionMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
async mutationFn({did, subscribe}: {did: string; subscribe: boolean}) { async mutationFn({did, subscribe}: {did: string; subscribe: boolean}) {
@ -87,9 +87,9 @@ export function useLabelerSubscriptionMutation() {
}).parse({did, subscribe}) }).parse({did, subscribe})
if (subscribe) { if (subscribe) {
await getAgent().addLabeler(did) await agent.addLabeler(did)
} else { } else {
await getAgent().removeLabeler(did) await agent.removeLabeler(did)
} }
}, },
onSuccess() { onSuccess() {

View File

@ -3,20 +3,20 @@ import {useMutation} from '@tanstack/react-query'
import {useAgent} from '#/state/session' import {useAgent} from '#/state/session'
export function useLikeMutation() { export function useLikeMutation() {
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async ({uri, cid}: {uri: string; cid: string}) => { mutationFn: async ({uri, cid}: {uri: string; cid: string}) => {
const res = await getAgent().like(uri, cid) const res = await agent.like(uri, cid)
return {uri: res.uri} return {uri: res.uri}
}, },
}) })
} }
export function useUnlikeMutation() { export function useUnlikeMutation() {
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async ({uri}: {uri: string}) => { mutationFn: async ({uri}: {uri: string}) => {
await getAgent().deleteLike(uri) await agent.deleteLike(uri)
}, },
}) })
} }

View File

@ -16,7 +16,7 @@ const RQKEY_ROOT = 'list-members'
export const RQKEY = (uri: string) => [RQKEY_ROOT, uri] export const RQKEY = (uri: string) => [RQKEY_ROOT, uri]
export function useListMembersQuery(uri: string) { export function useListMembersQuery(uri: string) {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyGraphGetList.OutputSchema, AppBskyGraphGetList.OutputSchema,
Error, Error,
@ -27,7 +27,7 @@ export function useListMembersQuery(uri: string) {
staleTime: STALE.MINUTES.ONE, staleTime: STALE.MINUTES.ONE,
queryKey: RQKEY(uri), queryKey: RQKEY(uri),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().app.bsky.graph.getList({ const res = await agent.app.bsky.graph.getList({
list: uri, list: uri,
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor: pageParam, cursor: pageParam,

View File

@ -40,7 +40,7 @@ export interface ListMembersip {
*/ */
export function useDangerousListMembershipsQuery() { export function useDangerousListMembershipsQuery() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<ListMembersip[]>({ return useQuery<ListMembersip[]>({
staleTime: STALE.MINUTES.FIVE, staleTime: STALE.MINUTES.FIVE,
queryKey: RQKEY(), queryKey: RQKEY(),
@ -51,7 +51,7 @@ export function useDangerousListMembershipsQuery() {
let cursor let cursor
let arr: ListMembersip[] = [] let arr: ListMembersip[] = []
for (let i = 0; i < SANITY_PAGE_LIMIT; i++) { for (let i = 0; i < SANITY_PAGE_LIMIT; i++) {
const res = await getAgent().app.bsky.graph.listitem.list({ const res = await agent.app.bsky.graph.listitem.list({
repo: currentAccount.did, repo: currentAccount.did,
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor, cursor,
@ -92,7 +92,7 @@ export function getMembership(
export function useListMembershipAddMutation() { export function useListMembershipAddMutation() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation< return useMutation<
{uri: string; cid: string}, {uri: string; cid: string},
@ -103,7 +103,7 @@ export function useListMembershipAddMutation() {
if (!currentAccount) { if (!currentAccount) {
throw new Error('Not logged in') throw new Error('Not logged in')
} }
const res = await getAgent().app.bsky.graph.listitem.create( const res = await agent.app.bsky.graph.listitem.create(
{repo: currentAccount.did}, {repo: currentAccount.did},
{ {
subject: actorDid, subject: actorDid,
@ -151,7 +151,7 @@ export function useListMembershipAddMutation() {
export function useListMembershipRemoveMutation() { export function useListMembershipRemoveMutation() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation< return useMutation<
void, void,
@ -163,7 +163,7 @@ export function useListMembershipRemoveMutation() {
throw new Error('Not logged in') throw new Error('Not logged in')
} }
const membershipUrip = new AtUri(membershipUri) const membershipUrip = new AtUri(membershipUri)
await getAgent().app.bsky.graph.listitem.delete({ await agent.app.bsky.graph.listitem.delete({
repo: currentAccount.did, repo: currentAccount.did,
rkey: membershipUrip.rkey, rkey: membershipUrip.rkey,
}) })

View File

@ -21,7 +21,7 @@ const RQKEY_ROOT = 'list'
export const RQKEY = (uri: string) => [RQKEY_ROOT, uri] export const RQKEY = (uri: string) => [RQKEY_ROOT, uri]
export function useListQuery(uri?: string) { export function useListQuery(uri?: string) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<AppBskyGraphDefs.ListView, Error>({ return useQuery<AppBskyGraphDefs.ListView, Error>({
staleTime: STALE.MINUTES.ONE, staleTime: STALE.MINUTES.ONE,
queryKey: RQKEY(uri || ''), queryKey: RQKEY(uri || ''),
@ -29,7 +29,7 @@ export function useListQuery(uri?: string) {
if (!uri) { if (!uri) {
throw new Error('URI not provided') throw new Error('URI not provided')
} }
const res = await getAgent().app.bsky.graph.getList({ const res = await agent.app.bsky.graph.getList({
list: uri, list: uri,
limit: 1, limit: 1,
}) })
@ -49,7 +49,7 @@ export interface ListCreateMutateParams {
export function useListCreateMutation() { export function useListCreateMutation() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<{uri: string; cid: string}, Error, ListCreateMutateParams>( return useMutation<{uri: string; cid: string}, Error, ListCreateMutateParams>(
{ {
async mutationFn({ async mutationFn({
@ -77,10 +77,10 @@ export function useListCreateMutation() {
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
} }
if (avatar) { if (avatar) {
const blobRes = await uploadBlob(getAgent(), avatar.path, avatar.mime) const blobRes = await uploadBlob(agent, avatar.path, avatar.mime)
record.avatar = blobRes.data.blob record.avatar = blobRes.data.blob
} }
const res = await getAgent().app.bsky.graph.list.create( const res = await agent.app.bsky.graph.list.create(
{ {
repo: currentAccount.did, repo: currentAccount.did,
}, },
@ -89,7 +89,7 @@ export function useListCreateMutation() {
// wait for the appview to update // wait for the appview to update
await whenAppViewReady( await whenAppViewReady(
getAgent, agent,
res.uri, res.uri,
(v: AppBskyGraphGetList.Response) => { (v: AppBskyGraphGetList.Response) => {
return typeof v?.data?.list.uri === 'string' return typeof v?.data?.list.uri === 'string'
@ -116,7 +116,7 @@ export interface ListMetadataMutateParams {
} }
export function useListMetadataMutation() { export function useListMetadataMutation() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation< return useMutation<
{uri: string; cid: string}, {uri: string; cid: string},
@ -133,7 +133,7 @@ export function useListMetadataMutation() {
} }
// get the current record // get the current record
const {value: record} = await getAgent().app.bsky.graph.list.get({ const {value: record} = await agent.app.bsky.graph.list.get({
repo: currentAccount.did, repo: currentAccount.did,
rkey, rkey,
}) })
@ -143,13 +143,13 @@ export function useListMetadataMutation() {
record.description = description record.description = description
record.descriptionFacets = descriptionFacets record.descriptionFacets = descriptionFacets
if (avatar) { if (avatar) {
const blobRes = await uploadBlob(getAgent(), avatar.path, avatar.mime) const blobRes = await uploadBlob(agent, avatar.path, avatar.mime)
record.avatar = blobRes.data.blob record.avatar = blobRes.data.blob
} else if (avatar === null) { } else if (avatar === null) {
record.avatar = undefined record.avatar = undefined
} }
const res = ( const res = (
await getAgent().com.atproto.repo.putRecord({ await agent.com.atproto.repo.putRecord({
repo: currentAccount.did, repo: currentAccount.did,
collection: 'app.bsky.graph.list', collection: 'app.bsky.graph.list',
rkey, rkey,
@ -159,7 +159,7 @@ export function useListMetadataMutation() {
// wait for the appview to update // wait for the appview to update
await whenAppViewReady( await whenAppViewReady(
getAgent, agent,
res.uri, res.uri,
(v: AppBskyGraphGetList.Response) => { (v: AppBskyGraphGetList.Response) => {
const list = v.data.list const list = v.data.list
@ -184,7 +184,7 @@ export function useListMetadataMutation() {
export function useListDeleteMutation() { export function useListDeleteMutation() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation<void, Error, {uri: string}>({ return useMutation<void, Error, {uri: string}>({
mutationFn: async ({uri}) => { mutationFn: async ({uri}) => {
@ -195,7 +195,7 @@ export function useListDeleteMutation() {
let cursor let cursor
let listitemRecordUris: string[] = [] let listitemRecordUris: string[] = []
for (let i = 0; i < 100; i++) { for (let i = 0; i < 100; i++) {
const res = await getAgent().app.bsky.graph.listitem.list({ const res = await agent.app.bsky.graph.listitem.list({
repo: currentAccount.did, repo: currentAccount.did,
cursor, cursor,
limit: 100, limit: 100,
@ -226,20 +226,16 @@ export function useListDeleteMutation() {
// apply in chunks // apply in chunks
for (const writesChunk of chunk(writes, 10)) { for (const writesChunk of chunk(writes, 10)) {
await getAgent().com.atproto.repo.applyWrites({ await agent.com.atproto.repo.applyWrites({
repo: currentAccount.did, repo: currentAccount.did,
writes: writesChunk, writes: writesChunk,
}) })
} }
// wait for the appview to update // wait for the appview to update
await whenAppViewReady( await whenAppViewReady(agent, uri, (v: AppBskyGraphGetList.Response) => {
getAgent, return !v?.success
uri, })
(v: AppBskyGraphGetList.Response) => {
return !v?.success
},
)
}, },
onSuccess() { onSuccess() {
invalidateMyLists(queryClient) invalidateMyLists(queryClient)
@ -253,22 +249,18 @@ export function useListDeleteMutation() {
export function useListMuteMutation() { export function useListMuteMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {uri: string; mute: boolean}>({ return useMutation<void, Error, {uri: string; mute: boolean}>({
mutationFn: async ({uri, mute}) => { mutationFn: async ({uri, mute}) => {
if (mute) { if (mute) {
await getAgent().muteModList(uri) await agent.muteModList(uri)
} else { } else {
await getAgent().unmuteModList(uri) await agent.unmuteModList(uri)
} }
await whenAppViewReady( await whenAppViewReady(agent, uri, (v: AppBskyGraphGetList.Response) => {
getAgent, return Boolean(v?.data.list.viewer?.muted) === mute
uri, })
(v: AppBskyGraphGetList.Response) => {
return Boolean(v?.data.list.viewer?.muted) === mute
},
)
}, },
onSuccess(data, variables) { onSuccess(data, variables) {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@ -280,24 +272,20 @@ export function useListMuteMutation() {
export function useListBlockMutation() { export function useListBlockMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {uri: string; block: boolean}>({ return useMutation<void, Error, {uri: string; block: boolean}>({
mutationFn: async ({uri, block}) => { mutationFn: async ({uri, block}) => {
if (block) { if (block) {
await getAgent().blockModList(uri) await agent.blockModList(uri)
} else { } else {
await getAgent().unblockModList(uri) await agent.unblockModList(uri)
} }
await whenAppViewReady( await whenAppViewReady(agent, uri, (v: AppBskyGraphGetList.Response) => {
getAgent, return block
uri, ? typeof v?.data.list.viewer?.blocked === 'string'
(v: AppBskyGraphGetList.Response) => { : !v?.data.list.viewer?.blocked
return block })
? typeof v?.data.list.viewer?.blocked === 'string'
: !v?.data.list.viewer?.blocked
},
)
}, },
onSuccess(data, variables) { onSuccess(data, variables) {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
@ -308,7 +296,7 @@ export function useListBlockMutation() {
} }
async function whenAppViewReady( async function whenAppViewReady(
getAgent: () => BskyAgent, agent: BskyAgent,
uri: string, uri: string,
fn: (res: AppBskyGraphGetList.Response) => boolean, fn: (res: AppBskyGraphGetList.Response) => boolean,
) { ) {
@ -317,7 +305,7 @@ async function whenAppViewReady(
1e3, // 1s delay between tries 1e3, // 1s delay between tries
fn, fn,
() => () =>
getAgent().app.bsky.graph.getList({ agent.app.bsky.graph.getList({
list: uri, list: uri,
limit: 1, limit: 1,
}), }),

View File

@ -14,12 +14,12 @@ export function useUpdateActorDeclaration({
}) { }) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async (allowIncoming: 'all' | 'none' | 'following') => { mutationFn: async (allowIncoming: 'all' | 'none' | 'following') => {
if (!currentAccount) throw new Error('Not logged in') if (!currentAccount) throw new Error('Not logged in')
const result = await getAgent().api.com.atproto.repo.putRecord({ const result = await agent.api.com.atproto.repo.putRecord({
repo: currentAccount.did, repo: currentAccount.did,
collection: 'chat.bsky.actor.declaration', collection: 'chat.bsky.actor.declaration',
rkey: 'self', rkey: 'self',
@ -64,13 +64,13 @@ export function useUpdateActorDeclaration({
// for use in the settings screen for testing // for use in the settings screen for testing
export function useDeleteActorDeclaration() { export function useDeleteActorDeclaration() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async () => { mutationFn: async () => {
if (!currentAccount) throw new Error('Not logged in') if (!currentAccount) throw new Error('Not logged in')
// TODO(sam): remove validate: false once PDSes have the new lexicon // TODO(sam): remove validate: false once PDSes have the new lexicon
const result = await getAgent().api.com.atproto.repo.deleteRecord({ const result = await agent.api.com.atproto.repo.deleteRecord({
repo: currentAccount.did, repo: currentAccount.did,
collection: 'chat.bsky.actor.declaration', collection: 'chat.bsky.actor.declaration',
rkey: 'self', rkey: 'self',

View File

@ -11,12 +11,12 @@ const RQKEY_ROOT = 'convo'
export const RQKEY = (convoId: string) => [RQKEY_ROOT, convoId] export const RQKEY = (convoId: string) => [RQKEY_ROOT, convoId]
export function useConvoQuery(convo: ChatBskyConvoDefs.ConvoView) { export function useConvoQuery(convo: ChatBskyConvoDefs.ConvoView) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
queryKey: RQKEY(convo.id), queryKey: RQKEY(convo.id),
queryFn: async () => { queryFn: async () => {
const {data} = await getAgent().api.chat.bsky.convo.getConvo( const {data} = await agent.api.chat.bsky.convo.getConvo(
{convoId: convo.id}, {convoId: convo.id},
{headers: DM_SERVICE_HEADERS}, {headers: DM_SERVICE_HEADERS},
) )
@ -30,7 +30,7 @@ export function useConvoQuery(convo: ChatBskyConvoDefs.ConvoView) {
export function useMarkAsReadMutation() { export function useMarkAsReadMutation() {
const optimisticUpdate = useOnMarkAsRead() const optimisticUpdate = useOnMarkAsRead()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async ({ mutationFn: async ({
@ -42,7 +42,7 @@ export function useMarkAsReadMutation() {
}) => { }) => {
if (!convoId) throw new Error('No convoId provided') if (!convoId) throw new Error('No convoId provided')
await getAgent().api.chat.bsky.convo.updateRead( await agent.api.chat.bsky.convo.updateRead(
{ {
convoId, convoId,
messageId, messageId,

View File

@ -18,11 +18,11 @@ export function useGetConvoForMembers({
onError?: (error: Error) => void onError?: (error: Error) => void
}) { }) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async (members: string[]) => { mutationFn: async (members: string[]) => {
const {data} = await getAgent().api.chat.bsky.convo.getConvoForMembers( const {data} = await agent.api.chat.bsky.convo.getConvoForMembers(
{members: members}, {members: members},
{headers: DM_SERVICE_HEADERS}, {headers: DM_SERVICE_HEADERS},
) )
@ -44,16 +44,13 @@ export function useGetConvoForMembers({
* Gets the conversation ID for a given DID. Returns null if it's not possible to message them. * Gets the conversation ID for a given DID. Returns null if it's not possible to message them.
*/ */
export function useMaybeConvoForUser(did: string) { export function useMaybeConvoForUser(did: string) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
queryKey: RQKEY(did), queryKey: RQKEY(did),
queryFn: async () => { queryFn: async () => {
const convo = await getAgent() const convo = await agent.api.chat.bsky.convo
.api.chat.bsky.convo.getConvoForMembers( .getConvoForMembers({members: [did]}, {headers: DM_SERVICE_HEADERS})
{members: [did]},
{headers: DM_SERVICE_HEADERS},
)
.catch(() => ({success: null})) .catch(() => ({success: null}))
if (convo.success) { if (convo.success) {

View File

@ -17,13 +17,13 @@ export function useLeaveConvo(
}, },
) { ) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async () => { mutationFn: async () => {
if (!convoId) throw new Error('No convoId provided') if (!convoId) throw new Error('No convoId provided')
const {data} = await getAgent().api.chat.bsky.convo.leaveConvo( const {data} = await agent.api.chat.bsky.convo.leaveConvo(
{convoId}, {convoId},
{headers: DM_SERVICE_HEADERS, encoding: 'application/json'}, {headers: DM_SERVICE_HEADERS, encoding: 'application/json'},
) )

View File

@ -27,12 +27,12 @@ export const RQKEY = ['convo-list']
type RQPageParam = string | undefined type RQPageParam = string | undefined
export function useListConvosQuery() { export function useListConvosQuery() {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery({ return useInfiniteQuery({
queryKey: RQKEY, queryKey: RQKEY,
queryFn: async ({pageParam}) => { queryFn: async ({pageParam}) => {
const {data} = await getAgent().api.chat.bsky.convo.listConvos( const {data} = await agent.api.chat.bsky.convo.listConvos(
{cursor: pageParam}, {cursor: pageParam},
{headers: DM_SERVICE_HEADERS}, {headers: DM_SERVICE_HEADERS},
) )

View File

@ -21,13 +21,11 @@ export function useMuteConvo(
}, },
) { ) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async ({mute}: {mute: boolean}) => { mutationFn: async ({mute}: {mute: boolean}) => {
if (!convoId) throw new Error('No convoId provided') if (!convoId) throw new Error('No convoId provided')
const agent = getAgent()
if (mute) { if (mute) {
const {data} = await agent.api.chat.bsky.convo.muteConvo( const {data} = await agent.api.chat.bsky.convo.muteConvo(
{convoId}, {convoId},

View File

@ -13,7 +13,7 @@ export const RQKEY = () => [RQKEY_ROOT]
type RQPageParam = string | undefined type RQPageParam = string | undefined
export function useMyBlockedAccountsQuery() { export function useMyBlockedAccountsQuery() {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyGraphGetBlocks.OutputSchema, AppBskyGraphGetBlocks.OutputSchema,
Error, Error,
@ -23,7 +23,7 @@ export function useMyBlockedAccountsQuery() {
>({ >({
queryKey: RQKEY(), queryKey: RQKEY(),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().app.bsky.graph.getBlocks({ const res = await agent.app.bsky.graph.getBlocks({
limit: 30, limit: 30,
cursor: pageParam, cursor: pageParam,
}) })

View File

@ -16,7 +16,7 @@ export const RQKEY = (filter: MyListsFilter) => [RQKEY_ROOT, filter]
export function useMyListsQuery(filter: MyListsFilter) { export function useMyListsQuery(filter: MyListsFilter) {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<AppBskyGraphDefs.ListView[]>({ return useQuery<AppBskyGraphDefs.ListView[]>({
staleTime: STALE.MINUTES.ONE, staleTime: STALE.MINUTES.ONE,
queryKey: RQKEY(filter), queryKey: RQKEY(filter),
@ -24,8 +24,8 @@ export function useMyListsQuery(filter: MyListsFilter) {
let lists: AppBskyGraphDefs.ListView[] = [] let lists: AppBskyGraphDefs.ListView[] = []
const promises = [ const promises = [
accumulate(cursor => accumulate(cursor =>
getAgent() agent.app.bsky.graph
.app.bsky.graph.getLists({ .getLists({
actor: currentAccount!.did, actor: currentAccount!.did,
cursor, cursor,
limit: 50, limit: 50,
@ -39,8 +39,8 @@ export function useMyListsQuery(filter: MyListsFilter) {
if (filter === 'all-including-subscribed' || filter === 'mod') { if (filter === 'all-including-subscribed' || filter === 'mod') {
promises.push( promises.push(
accumulate(cursor => accumulate(cursor =>
getAgent() agent.app.bsky.graph
.app.bsky.graph.getListMutes({ .getListMutes({
cursor, cursor,
limit: 50, limit: 50,
}) })
@ -52,8 +52,8 @@ export function useMyListsQuery(filter: MyListsFilter) {
) )
promises.push( promises.push(
accumulate(cursor => accumulate(cursor =>
getAgent() agent.app.bsky.graph
.app.bsky.graph.getListBlocks({ .getListBlocks({
cursor, cursor,
limit: 50, limit: 50,
}) })

View File

@ -13,7 +13,7 @@ export const RQKEY = () => [RQKEY_ROOT]
type RQPageParam = string | undefined type RQPageParam = string | undefined
export function useMyMutedAccountsQuery() { export function useMyMutedAccountsQuery() {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyGraphGetMutes.OutputSchema, AppBskyGraphGetMutes.OutputSchema,
Error, Error,
@ -23,7 +23,7 @@ export function useMyMutedAccountsQuery() {
>({ >({
queryKey: RQKEY(), queryKey: RQKEY(),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().app.bsky.graph.getMutes({ const res = await agent.app.bsky.graph.getMutes({
limit: 30, limit: 30,
cursor: pageParam, cursor: pageParam,
}) })

View File

@ -47,7 +47,7 @@ export function RQKEY() {
} }
export function useNotificationFeedQuery(opts?: {enabled?: boolean}) { export function useNotificationFeedQuery(opts?: {enabled?: boolean}) {
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const moderationOpts = useModerationOpts() const moderationOpts = useModerationOpts()
const threadMutes = useMutedThreads() const threadMutes = useMutedThreads()
@ -73,7 +73,7 @@ export function useNotificationFeedQuery(opts?: {enabled?: boolean}) {
if (!page) { if (!page) {
page = ( page = (
await fetchPage({ await fetchPage({
getAgent, agent,
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor: pageParam, cursor: pageParam,
queryClient, queryClient,

View File

@ -45,7 +45,7 @@ const apiContext = React.createContext<ApiContext>({
export function Provider({children}: React.PropsWithChildren<{}>) { export function Provider({children}: React.PropsWithChildren<{}>) {
const {hasSession} = useSession() const {hasSession} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const moderationOpts = useModerationOpts() const moderationOpts = useModerationOpts()
const threadMutes = useMutedThreads() const threadMutes = useMutedThreads()
@ -112,7 +112,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
return { return {
async markAllRead() { async markAllRead() {
// update server // update server
await getAgent().updateSeenNotifications( await agent.updateSeenNotifications(
cacheRef.current.syncedAt.toISOString(), cacheRef.current.syncedAt.toISOString(),
) )
@ -127,7 +127,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
isPoll, isPoll,
}: {invalidate?: boolean; isPoll?: boolean} = {}) { }: {invalidate?: boolean; isPoll?: boolean} = {}) {
try { try {
if (!getAgent().session) return if (!agent.session) return
if (AppState.currentState !== 'active') { if (AppState.currentState !== 'active') {
return return
} }
@ -142,7 +142,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
// count // count
const {page, indexedAt: lastIndexed} = await fetchPage({ const {page, indexedAt: lastIndexed} = await fetchPage({
getAgent, agent,
cursor: undefined, cursor: undefined,
limit: 40, limit: 40,
queryClient, queryClient,
@ -192,7 +192,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
} }
}, },
} }
}, [setNumUnread, queryClient, moderationOpts, threadMutes, getAgent]) }, [setNumUnread, queryClient, moderationOpts, threadMutes, agent])
checkUnreadRef.current = api.checkUnread checkUnreadRef.current = api.checkUnread
return ( return (

View File

@ -23,7 +23,7 @@ const MS_2DAY = MS_1HR * 48
// = // =
export async function fetchPage({ export async function fetchPage({
getAgent, agent,
cursor, cursor,
limit, limit,
queryClient, queryClient,
@ -31,7 +31,7 @@ export async function fetchPage({
threadMutes, threadMutes,
fetchAdditionalData, fetchAdditionalData,
}: { }: {
getAgent: () => BskyAgent agent: BskyAgent
cursor: string | undefined cursor: string | undefined
limit: number limit: number
queryClient: QueryClient queryClient: QueryClient
@ -39,7 +39,7 @@ export async function fetchPage({
threadMutes: string[] threadMutes: string[]
fetchAdditionalData: boolean fetchAdditionalData: boolean
}): Promise<{page: FeedPage; indexedAt: string | undefined}> { }): Promise<{page: FeedPage; indexedAt: string | undefined}> {
const res = await getAgent().listNotifications({ const res = await agent.listNotifications({
limit, limit,
cursor, cursor,
}) })
@ -56,7 +56,7 @@ export async function fetchPage({
// we fetch subjects of notifications (usually posts) now instead of lazily // we fetch subjects of notifications (usually posts) now instead of lazily
// in the UI to avoid relayouts // in the UI to avoid relayouts
if (fetchAdditionalData) { if (fetchAdditionalData) {
const subjects = await fetchSubjects(getAgent, notifsGrouped) const subjects = await fetchSubjects(agent, notifsGrouped)
for (const notif of notifsGrouped) { for (const notif of notifsGrouped) {
if (notif.subjectUri) { if (notif.subjectUri) {
notif.subject = subjects.get(notif.subjectUri) notif.subject = subjects.get(notif.subjectUri)
@ -140,7 +140,7 @@ export function groupNotifications(
} }
async function fetchSubjects( async function fetchSubjects(
getAgent: () => BskyAgent, agent: BskyAgent,
groupedNotifs: FeedNotification[], groupedNotifs: FeedNotification[],
): Promise<Map<string, AppBskyFeedDefs.PostView>> { ): Promise<Map<string, AppBskyFeedDefs.PostView>> {
const uris = new Set<string>() const uris = new Set<string>()
@ -152,9 +152,7 @@ async function fetchSubjects(
const uriChunks = chunk(Array.from(uris), 25) const uriChunks = chunk(Array.from(uris), 25)
const postsChunks = await Promise.all( const postsChunks = await Promise.all(
uriChunks.map(uris => uriChunks.map(uris =>
getAgent() agent.app.bsky.feed.getPosts({uris}).then(res => res.data.posts),
.app.bsky.feed.getPosts({uris})
.then(res => res.data.posts),
), ),
) )
const map = new Map<string, AppBskyFeedDefs.PostView>() const map = new Map<string, AppBskyFeedDefs.PostView>()

View File

@ -117,7 +117,7 @@ export function usePostFeedQuery(
f => f.pinned && f.value === 'following', f => f.pinned && f.value === 'following',
) ?? -1 ) ?? -1
const enableFollowingToDiscoverFallback = followingPinnedIndex === 0 const enableFollowingToDiscoverFallback = followingPinnedIndex === 0
const {getAgent} = useAgent() const agent = useAgent()
const lastRun = useRef<{ const lastRun = useRef<{
data: InfiniteData<FeedPageUnselected> data: InfiniteData<FeedPageUnselected>
args: typeof selectArgs args: typeof selectArgs
@ -155,7 +155,7 @@ export function usePostFeedQuery(
feedDesc, feedDesc,
feedParams: params || {}, feedParams: params || {},
feedTuners, feedTuners,
getAgent, agent,
// Not in the query key because they don't change: // Not in the query key because they don't change:
userInterests, userInterests,
// Not in the query key. Reacting to it switching isn't important: // Not in the query key. Reacting to it switching isn't important:
@ -173,7 +173,7 @@ export function usePostFeedQuery(
* moderations happen later, which results in some posts being shown and * moderations happen later, which results in some posts being shown and
* some not. * some not.
*/ */
if (!getAgent().session) { if (!agent.session) {
assertSomePostsPassModeration(res.feed) assertSomePostsPassModeration(res.feed)
} }
@ -397,50 +397,50 @@ function createApi({
feedParams, feedParams,
feedTuners, feedTuners,
userInterests, userInterests,
getAgent, agent,
enableFollowingToDiscoverFallback, enableFollowingToDiscoverFallback,
}: { }: {
feedDesc: FeedDescriptor feedDesc: FeedDescriptor
feedParams: FeedParams feedParams: FeedParams
feedTuners: FeedTunerFn[] feedTuners: FeedTunerFn[]
userInterests?: string userInterests?: string
getAgent: () => BskyAgent agent: BskyAgent
enableFollowingToDiscoverFallback: boolean enableFollowingToDiscoverFallback: boolean
}) { }) {
if (feedDesc === 'following') { if (feedDesc === 'following') {
if (feedParams.mergeFeedEnabled) { if (feedParams.mergeFeedEnabled) {
return new MergeFeedAPI({ return new MergeFeedAPI({
getAgent, agent,
feedParams, feedParams,
feedTuners, feedTuners,
userInterests, userInterests,
}) })
} else { } else {
if (enableFollowingToDiscoverFallback) { if (enableFollowingToDiscoverFallback) {
return new HomeFeedAPI({getAgent, userInterests}) return new HomeFeedAPI({agent, userInterests})
} else { } else {
return new FollowingFeedAPI({getAgent}) return new FollowingFeedAPI({agent})
} }
} }
} else if (feedDesc.startsWith('author')) { } else if (feedDesc.startsWith('author')) {
const [_, actor, filter] = feedDesc.split('|') const [_, actor, filter] = feedDesc.split('|')
return new AuthorFeedAPI({getAgent, feedParams: {actor, filter}}) return new AuthorFeedAPI({agent, feedParams: {actor, filter}})
} else if (feedDesc.startsWith('likes')) { } else if (feedDesc.startsWith('likes')) {
const [_, actor] = feedDesc.split('|') const [_, actor] = feedDesc.split('|')
return new LikesFeedAPI({getAgent, feedParams: {actor}}) return new LikesFeedAPI({agent, feedParams: {actor}})
} else if (feedDesc.startsWith('feedgen')) { } else if (feedDesc.startsWith('feedgen')) {
const [_, feed] = feedDesc.split('|') const [_, feed] = feedDesc.split('|')
return new CustomFeedAPI({ return new CustomFeedAPI({
getAgent, agent,
feedParams: {feed}, feedParams: {feed},
userInterests, userInterests,
}) })
} else if (feedDesc.startsWith('list')) { } else if (feedDesc.startsWith('list')) {
const [_, list] = feedDesc.split('|') const [_, list] = feedDesc.split('|')
return new ListFeedAPI({getAgent, feedParams: {list}}) return new ListFeedAPI({agent, feedParams: {list}})
} else { } else {
// shouldnt happen // shouldnt happen
return new FollowingFeedAPI({getAgent}) return new FollowingFeedAPI({agent})
} }
} }

View File

@ -16,7 +16,7 @@ const RQKEY_ROOT = 'liked-by'
export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri]
export function useLikedByQuery(resolvedUri: string | undefined) { export function useLikedByQuery(resolvedUri: string | undefined) {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyFeedGetLikes.OutputSchema, AppBskyFeedGetLikes.OutputSchema,
Error, Error,
@ -26,7 +26,7 @@ export function useLikedByQuery(resolvedUri: string | undefined) {
>({ >({
queryKey: RQKEY(resolvedUri || ''), queryKey: RQKEY(resolvedUri || ''),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().getLikes({ const res = await agent.getLikes({
uri: resolvedUri || '', uri: resolvedUri || '',
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor: pageParam, cursor: pageParam,

View File

@ -16,7 +16,7 @@ const RQKEY_ROOT = 'post-reposted-by'
export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri]
export function usePostRepostedByQuery(resolvedUri: string | undefined) { export function usePostRepostedByQuery(resolvedUri: string | undefined) {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyFeedGetRepostedBy.OutputSchema, AppBskyFeedGetRepostedBy.OutputSchema,
Error, Error,
@ -26,7 +26,7 @@ export function usePostRepostedByQuery(resolvedUri: string | undefined) {
>({ >({
queryKey: RQKEY(resolvedUri || ''), queryKey: RQKEY(resolvedUri || ''),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().getRepostedBy({ const res = await agent.getRepostedBy({
uri: resolvedUri || '', uri: resolvedUri || '',
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor: pageParam, cursor: pageParam,

View File

@ -68,12 +68,12 @@ export type ThreadModerationCache = WeakMap<ThreadNode, ModerationDecision>
export function usePostThreadQuery(uri: string | undefined) { export function usePostThreadQuery(uri: string | undefined) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<ThreadNode, Error>({ return useQuery<ThreadNode, Error>({
gcTime: 0, gcTime: 0,
queryKey: RQKEY(uri || ''), queryKey: RQKEY(uri || ''),
async queryFn() { async queryFn() {
const res = await getAgent().getPostThread({uri: uri!}) const res = await agent.getPostThread({uri: uri!})
if (res.success) { if (res.success) {
return responseToThreadNodes(res.data.thread) return responseToThreadNodes(res.data.thread)
} }

View File

@ -14,11 +14,11 @@ const RQKEY_ROOT = 'post'
export const RQKEY = (postUri: string) => [RQKEY_ROOT, postUri] export const RQKEY = (postUri: string) => [RQKEY_ROOT, postUri]
export function usePostQuery(uri: string | undefined) { export function usePostQuery(uri: string | undefined) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<AppBskyFeedDefs.PostView>({ return useQuery<AppBskyFeedDefs.PostView>({
queryKey: RQKEY(uri || ''), queryKey: RQKEY(uri || ''),
async queryFn() { async queryFn() {
const res = await getAgent().getPosts({uris: [uri!]}) const res = await agent.getPosts({uris: [uri!]})
if (res.success && res.data.posts[0]) { if (res.success && res.data.posts[0]) {
return res.data.posts[0] return res.data.posts[0]
} }
@ -31,7 +31,7 @@ export function usePostQuery(uri: string | undefined) {
export function useGetPost() { export function useGetPost() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useCallback( return useCallback(
async ({uri}: {uri: string}) => { async ({uri}: {uri: string}) => {
return queryClient.fetchQuery({ return queryClient.fetchQuery({
@ -40,13 +40,13 @@ export function useGetPost() {
const urip = new AtUri(uri) const urip = new AtUri(uri)
if (!urip.host.startsWith('did:')) { if (!urip.host.startsWith('did:')) {
const res = await getAgent().resolveHandle({ const res = await agent.resolveHandle({
handle: urip.host, handle: urip.host,
}) })
urip.host = res.data.did urip.host = res.data.did
} }
const res = await getAgent().getPosts({ const res = await agent.getPosts({
uris: [urip.toString()!], uris: [urip.toString()!],
}) })
@ -58,7 +58,7 @@ export function useGetPost() {
}, },
}) })
}, },
[queryClient, getAgent], [queryClient, agent],
) )
} }
@ -127,7 +127,7 @@ function usePostLikeMutation(
const {currentAccount} = useSession() const {currentAccount} = useSession()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const postAuthor = post.author const postAuthor = post.author
const {getAgent} = useAgent() const agent = useAgent()
return useMutation< return useMutation<
{uri: string}, // responds with the uri of the like {uri: string}, // responds with the uri of the like
Error, Error,
@ -154,7 +154,7 @@ function usePostLikeMutation(
? toClout(post.likeCount + post.repostCount + post.replyCount) ? toClout(post.likeCount + post.repostCount + post.replyCount)
: undefined, : undefined,
}) })
return getAgent().like(uri, cid) return agent.like(uri, cid)
}, },
onSuccess() { onSuccess() {
track('Post:Like') track('Post:Like')
@ -165,11 +165,11 @@ function usePostLikeMutation(
function usePostUnlikeMutation( function usePostUnlikeMutation(
logContext: LogEvents['post:unlike']['logContext'], logContext: LogEvents['post:unlike']['logContext'],
) { ) {
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {postUri: string; likeUri: string}>({ return useMutation<void, Error, {postUri: string; likeUri: string}>({
mutationFn: ({likeUri}) => { mutationFn: ({likeUri}) => {
logEvent('post:unlike', {logContext}) logEvent('post:unlike', {logContext})
return getAgent().deleteLike(likeUri) return agent.deleteLike(likeUri)
}, },
onSuccess() { onSuccess() {
track('Post:Unlike') track('Post:Unlike')
@ -238,7 +238,7 @@ export function usePostRepostMutationQueue(
function usePostRepostMutation( function usePostRepostMutation(
logContext: LogEvents['post:repost']['logContext'], logContext: LogEvents['post:repost']['logContext'],
) { ) {
const {getAgent} = useAgent() const agent = useAgent()
return useMutation< return useMutation<
{uri: string}, // responds with the uri of the repost {uri: string}, // responds with the uri of the repost
Error, Error,
@ -246,7 +246,7 @@ function usePostRepostMutation(
>({ >({
mutationFn: post => { mutationFn: post => {
logEvent('post:repost', {logContext}) logEvent('post:repost', {logContext})
return getAgent().repost(post.uri, post.cid) return agent.repost(post.uri, post.cid)
}, },
onSuccess() { onSuccess() {
track('Post:Repost') track('Post:Repost')
@ -257,11 +257,11 @@ function usePostRepostMutation(
function usePostUnrepostMutation( function usePostUnrepostMutation(
logContext: LogEvents['post:unrepost']['logContext'], logContext: LogEvents['post:unrepost']['logContext'],
) { ) {
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {postUri: string; repostUri: string}>({ return useMutation<void, Error, {postUri: string; repostUri: string}>({
mutationFn: ({repostUri}) => { mutationFn: ({repostUri}) => {
logEvent('post:unrepost', {logContext}) logEvent('post:unrepost', {logContext})
return getAgent().deleteRepost(repostUri) return agent.deleteRepost(repostUri)
}, },
onSuccess() { onSuccess() {
track('Post:Unrepost') track('Post:Unrepost')
@ -271,10 +271,10 @@ function usePostUnrepostMutation(
export function usePostDeleteMutation() { export function usePostDeleteMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {uri: string}>({ return useMutation<void, Error, {uri: string}>({
mutationFn: async ({uri}) => { mutationFn: async ({uri}) => {
await getAgent().deletePost(uri) await agent.deletePost(uri)
}, },
onSuccess(data, variables) { onSuccess(data, variables) {
updatePostShadow(queryClient, variables.uri, {isDeleted: true}) updatePostShadow(queryClient, variables.uri, {isDeleted: true})

View File

@ -30,15 +30,13 @@ const preferencesQueryKeyRoot = 'getPreferences'
export const preferencesQueryKey = [preferencesQueryKeyRoot] export const preferencesQueryKey = [preferencesQueryKeyRoot]
export function usePreferencesQuery() { export function usePreferencesQuery() {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
staleTime: STALE.SECONDS.FIFTEEN, staleTime: STALE.SECONDS.FIFTEEN,
structuralSharing: replaceEqualDeep, structuralSharing: replaceEqualDeep,
refetchOnWindowFocus: true, refetchOnWindowFocus: true,
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
queryFn: async () => { queryFn: async () => {
const agent = getAgent()
if (agent.session?.did === undefined) { if (agent.session?.did === undefined) {
return DEFAULT_LOGGED_OUT_PREFERENCES return DEFAULT_LOGGED_OUT_PREFERENCES
} else { } else {
@ -75,11 +73,11 @@ export function usePreferencesQuery() {
export function useClearPreferencesMutation() { export function useClearPreferencesMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async () => { mutationFn: async () => {
await getAgent().app.bsky.actor.putPreferences({preferences: []}) await agent.app.bsky.actor.putPreferences({preferences: []})
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -89,7 +87,7 @@ export function useClearPreferencesMutation() {
} }
export function usePreferencesSetContentLabelMutation() { export function usePreferencesSetContentLabelMutation() {
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation< return useMutation<
@ -98,7 +96,7 @@ export function usePreferencesSetContentLabelMutation() {
{label: string; visibility: LabelPreference; labelerDid: string | undefined} {label: string; visibility: LabelPreference; labelerDid: string | undefined}
>({ >({
mutationFn: async ({label, visibility, labelerDid}) => { mutationFn: async ({label, visibility, labelerDid}) => {
await getAgent().setContentLabelPref(label, visibility, labelerDid) await agent.setContentLabelPref(label, visibility, labelerDid)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -109,7 +107,7 @@ export function usePreferencesSetContentLabelMutation() {
export function useSetContentLabelMutation() { export function useSetContentLabelMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async ({ mutationFn: async ({
@ -121,7 +119,7 @@ export function useSetContentLabelMutation() {
visibility: LabelPreference visibility: LabelPreference
labelerDid?: string labelerDid?: string
}) => { }) => {
await getAgent().setContentLabelPref(label, visibility, labelerDid) await agent.setContentLabelPref(label, visibility, labelerDid)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -132,11 +130,11 @@ export function useSetContentLabelMutation() {
export function usePreferencesSetAdultContentMutation() { export function usePreferencesSetAdultContentMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, unknown, {enabled: boolean}>({ return useMutation<void, unknown, {enabled: boolean}>({
mutationFn: async ({enabled}) => { mutationFn: async ({enabled}) => {
await getAgent().setAdultContentEnabled(enabled) await agent.setAdultContentEnabled(enabled)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -147,11 +145,11 @@ export function usePreferencesSetAdultContentMutation() {
export function usePreferencesSetBirthDateMutation() { export function usePreferencesSetBirthDateMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, unknown, {birthDate: Date}>({ return useMutation<void, unknown, {birthDate: Date}>({
mutationFn: async ({birthDate}: {birthDate: Date}) => { mutationFn: async ({birthDate}: {birthDate: Date}) => {
await getAgent().setPersonalDetails({birthDate: birthDate.toISOString()}) await agent.setPersonalDetails({birthDate: birthDate.toISOString()})
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -162,7 +160,7 @@ export function usePreferencesSetBirthDateMutation() {
export function useSetFeedViewPreferencesMutation() { export function useSetFeedViewPreferencesMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, unknown, Partial<BskyFeedViewPreference>>({ return useMutation<void, unknown, Partial<BskyFeedViewPreference>>({
mutationFn: async prefs => { mutationFn: async prefs => {
@ -170,7 +168,7 @@ export function useSetFeedViewPreferencesMutation() {
* special handling here, merged into `feedViewPrefs` above, since * special handling here, merged into `feedViewPrefs` above, since
* following was previously called `home` * following was previously called `home`
*/ */
await getAgent().setFeedViewPrefs('home', prefs) await agent.setFeedViewPrefs('home', prefs)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -181,11 +179,11 @@ export function useSetFeedViewPreferencesMutation() {
export function useSetThreadViewPreferencesMutation() { export function useSetThreadViewPreferencesMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, unknown, Partial<ThreadViewPreferences>>({ return useMutation<void, unknown, Partial<ThreadViewPreferences>>({
mutationFn: async prefs => { mutationFn: async prefs => {
await getAgent().setThreadViewPrefs(prefs) await agent.setThreadViewPrefs(prefs)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -196,11 +194,11 @@ export function useSetThreadViewPreferencesMutation() {
export function useOverwriteSavedFeedsMutation() { export function useOverwriteSavedFeedsMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, unknown, AppBskyActorDefs.SavedFeed[]>({ return useMutation<void, unknown, AppBskyActorDefs.SavedFeed[]>({
mutationFn: async savedFeeds => { mutationFn: async savedFeeds => {
await getAgent().overwriteSavedFeeds(savedFeeds) await agent.overwriteSavedFeeds(savedFeeds)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -211,7 +209,7 @@ export function useOverwriteSavedFeedsMutation() {
export function useAddSavedFeedsMutation() { export function useAddSavedFeedsMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation< return useMutation<
void, void,
@ -219,7 +217,7 @@ export function useAddSavedFeedsMutation() {
Pick<AppBskyActorDefs.SavedFeed, 'type' | 'value' | 'pinned'>[] Pick<AppBskyActorDefs.SavedFeed, 'type' | 'value' | 'pinned'>[]
>({ >({
mutationFn: async savedFeeds => { mutationFn: async savedFeeds => {
await getAgent().addSavedFeeds(savedFeeds) await agent.addSavedFeeds(savedFeeds)
track('CustomFeed:Save') track('CustomFeed:Save')
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
@ -231,11 +229,11 @@ export function useAddSavedFeedsMutation() {
export function useRemoveFeedMutation() { export function useRemoveFeedMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, unknown, Pick<AppBskyActorDefs.SavedFeed, 'id'>>({ return useMutation<void, unknown, Pick<AppBskyActorDefs.SavedFeed, 'id'>>({
mutationFn: async savedFeed => { mutationFn: async savedFeed => {
await getAgent().removeSavedFeeds([savedFeed.id]) await agent.removeSavedFeeds([savedFeed.id])
track('CustomFeed:Unsave') track('CustomFeed:Unsave')
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
@ -247,7 +245,7 @@ export function useRemoveFeedMutation() {
export function useReplaceForYouWithDiscoverFeedMutation() { export function useReplaceForYouWithDiscoverFeedMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async ({ mutationFn: async ({
@ -258,10 +256,10 @@ export function useReplaceForYouWithDiscoverFeedMutation() {
discoverFeedConfig: AppBskyActorDefs.SavedFeed | undefined discoverFeedConfig: AppBskyActorDefs.SavedFeed | undefined
}) => { }) => {
if (forYouFeedConfig) { if (forYouFeedConfig) {
await getAgent().removeSavedFeeds([forYouFeedConfig.id]) await agent.removeSavedFeeds([forYouFeedConfig.id])
} }
if (!discoverFeedConfig) { if (!discoverFeedConfig) {
await getAgent().addSavedFeeds([ await agent.addSavedFeeds([
{ {
type: 'feed', type: 'feed',
value: PROD_DEFAULT_FEED('whats-hot'), value: PROD_DEFAULT_FEED('whats-hot'),
@ -269,7 +267,7 @@ export function useReplaceForYouWithDiscoverFeedMutation() {
}, },
]) ])
} else { } else {
await getAgent().updateSavedFeeds([ await agent.updateSavedFeeds([
{ {
...discoverFeedConfig, ...discoverFeedConfig,
pinned: true, pinned: true,
@ -286,11 +284,11 @@ export function useReplaceForYouWithDiscoverFeedMutation() {
export function useUpdateSavedFeedsMutation() { export function useUpdateSavedFeedsMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, unknown, AppBskyActorDefs.SavedFeed[]>({ return useMutation<void, unknown, AppBskyActorDefs.SavedFeed[]>({
mutationFn: async feeds => { mutationFn: async feeds => {
await getAgent().updateSavedFeeds(feeds) await agent.updateSavedFeeds(feeds)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
@ -302,11 +300,11 @@ export function useUpdateSavedFeedsMutation() {
export function useUpsertMutedWordsMutation() { export function useUpsertMutedWordsMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async (mutedWords: AppBskyActorDefs.MutedWord[]) => { mutationFn: async (mutedWords: AppBskyActorDefs.MutedWord[]) => {
await getAgent().upsertMutedWords(mutedWords) await agent.upsertMutedWords(mutedWords)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -317,11 +315,11 @@ export function useUpsertMutedWordsMutation() {
export function useUpdateMutedWordMutation() { export function useUpdateMutedWordMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async (mutedWord: AppBskyActorDefs.MutedWord) => { mutationFn: async (mutedWord: AppBskyActorDefs.MutedWord) => {
await getAgent().updateMutedWord(mutedWord) await agent.updateMutedWord(mutedWord)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,
@ -332,11 +330,11 @@ export function useUpdateMutedWordMutation() {
export function useRemoveMutedWordMutation() { export function useRemoveMutedWordMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation({ return useMutation({
mutationFn: async (mutedWord: AppBskyActorDefs.MutedWord) => { mutationFn: async (mutedWord: AppBskyActorDefs.MutedWord) => {
await getAgent().removeMutedWord(mutedWord) await agent.removeMutedWord(mutedWord)
// triggers a refetch // triggers a refetch
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: preferencesQueryKey, queryKey: preferencesQueryKey,

View File

@ -15,7 +15,7 @@ export function useProfileFeedgensQuery(
opts?: {enabled?: boolean}, opts?: {enabled?: boolean},
) { ) {
const enabled = opts?.enabled !== false const enabled = opts?.enabled !== false
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyFeedGetActorFeeds.OutputSchema, AppBskyFeedGetActorFeeds.OutputSchema,
Error, Error,
@ -25,7 +25,7 @@ export function useProfileFeedgensQuery(
>({ >({
queryKey: RQKEY(did), queryKey: RQKEY(did),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().app.bsky.feed.getActorFeeds({ const res = await agent.app.bsky.feed.getActorFeeds({
actor: did, actor: did,
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor: pageParam, cursor: pageParam,

View File

@ -15,7 +15,7 @@ const RQKEY_ROOT = 'profile-followers'
export const RQKEY = (did: string) => [RQKEY_ROOT, did] export const RQKEY = (did: string) => [RQKEY_ROOT, did]
export function useProfileFollowersQuery(did: string | undefined) { export function useProfileFollowersQuery(did: string | undefined) {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyGraphGetFollowers.OutputSchema, AppBskyGraphGetFollowers.OutputSchema,
Error, Error,
@ -25,7 +25,7 @@ export function useProfileFollowersQuery(did: string | undefined) {
>({ >({
queryKey: RQKEY(did || ''), queryKey: RQKEY(did || ''),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().app.bsky.graph.getFollowers({ const res = await agent.app.bsky.graph.getFollowers({
actor: did || '', actor: did || '',
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor: pageParam, cursor: pageParam,

View File

@ -26,7 +26,7 @@ export function useProfileFollowsQuery(
limit: PAGE_SIZE, limit: PAGE_SIZE,
}, },
) { ) {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyGraphGetFollows.OutputSchema, AppBskyGraphGetFollows.OutputSchema,
Error, Error,
@ -37,7 +37,7 @@ export function useProfileFollowsQuery(
staleTime: STALE.MINUTES.ONE, staleTime: STALE.MINUTES.ONE,
queryKey: RQKEY(did || ''), queryKey: RQKEY(did || ''),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().app.bsky.graph.getFollows({ const res = await agent.app.bsky.graph.getFollows({
actor: did || '', actor: did || '',
limit: limit || PAGE_SIZE, limit: limit || PAGE_SIZE,
cursor: pageParam, cursor: pageParam,

View File

@ -11,7 +11,7 @@ export const RQKEY = (did: string) => [RQKEY_ROOT, did]
export function useProfileListsQuery(did: string, opts?: {enabled?: boolean}) { export function useProfileListsQuery(did: string, opts?: {enabled?: boolean}) {
const enabled = opts?.enabled !== false const enabled = opts?.enabled !== false
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyGraphGetLists.OutputSchema, AppBskyGraphGetLists.OutputSchema,
Error, Error,
@ -21,7 +21,7 @@ export function useProfileListsQuery(did: string, opts?: {enabled?: boolean}) {
>({ >({
queryKey: RQKEY(did), queryKey: RQKEY(did),
async queryFn({pageParam}: {pageParam: RQPageParam}) { async queryFn({pageParam}: {pageParam: RQPageParam}) {
const res = await getAgent().app.bsky.graph.getLists({ const res = await agent.app.bsky.graph.getLists({
actor: did, actor: did,
limit: PAGE_SIZE, limit: PAGE_SIZE,
cursor: pageParam, cursor: pageParam,

View File

@ -52,7 +52,7 @@ export function useProfileQuery({
staleTime?: number staleTime?: number
}) { }) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<AppBskyActorDefs.ProfileViewDetailed>({ return useQuery<AppBskyActorDefs.ProfileViewDetailed>({
// WARNING // WARNING
// this staleTime is load-bearing // this staleTime is load-bearing
@ -62,7 +62,7 @@ export function useProfileQuery({
refetchOnWindowFocus: true, refetchOnWindowFocus: true,
queryKey: RQKEY(did ?? ''), queryKey: RQKEY(did ?? ''),
queryFn: async () => { queryFn: async () => {
const res = await getAgent().getProfile({actor: did ?? ''}) const res = await agent.getProfile({actor: did ?? ''})
return res.data return res.data
}, },
placeholderData: () => { placeholderData: () => {
@ -77,31 +77,31 @@ export function useProfileQuery({
} }
export function useProfilesQuery({handles}: {handles: string[]}) { export function useProfilesQuery({handles}: {handles: string[]}) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery({ return useQuery({
staleTime: STALE.MINUTES.FIVE, staleTime: STALE.MINUTES.FIVE,
queryKey: profilesQueryKey(handles), queryKey: profilesQueryKey(handles),
queryFn: async () => { queryFn: async () => {
const res = await getAgent().getProfiles({actors: handles}) const res = await agent.getProfiles({actors: handles})
return res.data return res.data
}, },
}) })
} }
export function usePrefetchProfileQuery() { export function usePrefetchProfileQuery() {
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const prefetchProfileQuery = useCallback( const prefetchProfileQuery = useCallback(
async (did: string) => { async (did: string) => {
await queryClient.prefetchQuery({ await queryClient.prefetchQuery({
queryKey: RQKEY(did), queryKey: RQKEY(did),
queryFn: async () => { queryFn: async () => {
const res = await getAgent().getProfile({actor: did || ''}) const res = await agent.getProfile({actor: did || ''})
return res.data return res.data
}, },
}) })
}, },
[queryClient, getAgent], [queryClient, agent],
) )
return prefetchProfileQuery return prefetchProfileQuery
} }
@ -117,7 +117,7 @@ interface ProfileUpdateParams {
} }
export function useProfileUpdateMutation() { export function useProfileUpdateMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, ProfileUpdateParams>({ return useMutation<void, Error, ProfileUpdateParams>({
mutationFn: async ({ mutationFn: async ({
profile, profile,
@ -131,7 +131,7 @@ export function useProfileUpdateMutation() {
| undefined | undefined
if (newUserAvatar) { if (newUserAvatar) {
newUserAvatarPromise = uploadBlob( newUserAvatarPromise = uploadBlob(
getAgent(), agent,
newUserAvatar.path, newUserAvatar.path,
newUserAvatar.mime, newUserAvatar.mime,
) )
@ -141,12 +141,12 @@ export function useProfileUpdateMutation() {
| undefined | undefined
if (newUserBanner) { if (newUserBanner) {
newUserBannerPromise = uploadBlob( newUserBannerPromise = uploadBlob(
getAgent(), agent,
newUserBanner.path, newUserBanner.path,
newUserBanner.mime, newUserBanner.mime,
) )
} }
await getAgent().upsertProfile(async existing => { await agent.upsertProfile(async existing => {
existing = existing || {} existing = existing || {}
if (typeof updates === 'function') { if (typeof updates === 'function') {
existing = updates(existing) existing = updates(existing)
@ -169,7 +169,7 @@ export function useProfileUpdateMutation() {
return existing return existing
}) })
await whenAppViewReady( await whenAppViewReady(
getAgent, agent,
profile.did, profile.did,
checkCommitted || checkCommitted ||
(res => { (res => {
@ -271,7 +271,7 @@ function useProfileFollowMutation(
profile: Shadow<AppBskyActorDefs.ProfileViewDetailed>, profile: Shadow<AppBskyActorDefs.ProfileViewDetailed>,
) { ) {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation<{uri: string; cid: string}, Error, {did: string}>({ return useMutation<{uri: string; cid: string}, Error, {did: string}>({
mutationFn: async ({did}) => { mutationFn: async ({did}) => {
@ -287,7 +287,7 @@ function useProfileFollowMutation(
followeeClout: toClout(profile.followersCount), followeeClout: toClout(profile.followersCount),
followerClout: toClout(ownProfile?.followersCount), followerClout: toClout(ownProfile?.followersCount),
}) })
return await getAgent().follow(did) return await agent.follow(did)
}, },
onSuccess(data, variables) { onSuccess(data, variables) {
track('Profile:Follow', {username: variables.did}) track('Profile:Follow', {username: variables.did})
@ -298,12 +298,12 @@ function useProfileFollowMutation(
function useProfileUnfollowMutation( function useProfileUnfollowMutation(
logContext: LogEvents['profile:unfollow']['logContext'], logContext: LogEvents['profile:unfollow']['logContext'],
) { ) {
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {did: string; followUri: string}>({ return useMutation<void, Error, {did: string; followUri: string}>({
mutationFn: async ({followUri}) => { mutationFn: async ({followUri}) => {
logEvent('profile:unfollow', {logContext}) logEvent('profile:unfollow', {logContext})
track('Profile:Unfollow', {username: followUri}) track('Profile:Unfollow', {username: followUri})
return await getAgent().deleteFollow(followUri) return await agent.deleteFollow(followUri)
}, },
}) })
} }
@ -359,10 +359,10 @@ export function useProfileMuteMutationQueue(
function useProfileMuteMutation() { function useProfileMuteMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {did: string}>({ return useMutation<void, Error, {did: string}>({
mutationFn: async ({did}) => { mutationFn: async ({did}) => {
await getAgent().mute(did) await agent.mute(did)
}, },
onSuccess() { onSuccess() {
queryClient.invalidateQueries({queryKey: RQKEY_MY_MUTED()}) queryClient.invalidateQueries({queryKey: RQKEY_MY_MUTED()})
@ -372,10 +372,10 @@ function useProfileMuteMutation() {
function useProfileUnmuteMutation() { function useProfileUnmuteMutation() {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useMutation<void, Error, {did: string}>({ return useMutation<void, Error, {did: string}>({
mutationFn: async ({did}) => { mutationFn: async ({did}) => {
await getAgent().unmute(did) await agent.unmute(did)
}, },
onSuccess() { onSuccess() {
queryClient.invalidateQueries({queryKey: RQKEY_MY_MUTED()}) queryClient.invalidateQueries({queryKey: RQKEY_MY_MUTED()})
@ -440,14 +440,14 @@ export function useProfileBlockMutationQueue(
function useProfileBlockMutation() { function useProfileBlockMutation() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation<{uri: string; cid: string}, Error, {did: string}>({ return useMutation<{uri: string; cid: string}, Error, {did: string}>({
mutationFn: async ({did}) => { mutationFn: async ({did}) => {
if (!currentAccount) { if (!currentAccount) {
throw new Error('Not signed in') throw new Error('Not signed in')
} }
return await getAgent().app.bsky.graph.block.create( return await agent.app.bsky.graph.block.create(
{repo: currentAccount.did}, {repo: currentAccount.did},
{subject: did, createdAt: new Date().toISOString()}, {subject: did, createdAt: new Date().toISOString()},
) )
@ -461,7 +461,7 @@ function useProfileBlockMutation() {
function useProfileUnblockMutation() { function useProfileUnblockMutation() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation<void, Error, {did: string; blockUri: string}>({ return useMutation<void, Error, {did: string; blockUri: string}>({
mutationFn: async ({blockUri}) => { mutationFn: async ({blockUri}) => {
@ -469,7 +469,7 @@ function useProfileUnblockMutation() {
throw new Error('Not signed in') throw new Error('Not signed in')
} }
const {rkey} = new AtUri(blockUri) const {rkey} = new AtUri(blockUri)
await getAgent().app.bsky.graph.block.delete({ await agent.app.bsky.graph.block.delete({
repo: currentAccount.did, repo: currentAccount.did,
rkey, rkey,
}) })
@ -489,7 +489,7 @@ export function precacheProfile(
} }
async function whenAppViewReady( async function whenAppViewReady(
getAgent: () => BskyAgent, agent: BskyAgent,
actor: string, actor: string,
fn: (res: AppBskyActorGetProfile.Response) => boolean, fn: (res: AppBskyActorGetProfile.Response) => boolean,
) { ) {
@ -497,7 +497,7 @@ async function whenAppViewReady(
5, // 5 tries 5, // 5 tries
1e3, // 1s delay between tries 1e3, // 1s delay between tries
fn, fn,
() => getAgent().app.bsky.actor.getProfile({actor}), () => agent.app.bsky.actor.getProfile({actor}),
) )
} }

View File

@ -24,7 +24,7 @@ export function useResolveUriQuery(uri: string | undefined): UriUseQueryResult {
export function useResolveDidQuery(didOrHandle: string | undefined) { export function useResolveDidQuery(didOrHandle: string | undefined) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<string, Error>({ return useQuery<string, Error>({
staleTime: STALE.HOURS.ONE, staleTime: STALE.HOURS.ONE,
@ -34,7 +34,7 @@ export function useResolveDidQuery(didOrHandle: string | undefined) {
// Just return the did if it's already one // Just return the did if it's already one
if (didOrHandle.startsWith('did:')) return didOrHandle if (didOrHandle.startsWith('did:')) return didOrHandle
const res = await getAgent().resolveHandle({handle: didOrHandle}) const res = await agent.resolveHandle({handle: didOrHandle})
return res.data.did return res.data.did
}, },
initialData: () => { initialData: () => {

View File

@ -25,7 +25,7 @@ export function useSearchPostsQuery({
sort?: 'top' | 'latest' sort?: 'top' | 'latest'
enabled?: boolean enabled?: boolean
}) { }) {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyFeedSearchPosts.OutputSchema, AppBskyFeedSearchPosts.OutputSchema,
Error, Error,
@ -35,7 +35,7 @@ export function useSearchPostsQuery({
>({ >({
queryKey: searchPostsQueryKey({query, sort}), queryKey: searchPostsQueryKey({query, sort}),
queryFn: async ({pageParam}) => { queryFn: async ({pageParam}) => {
const res = await getAgent().app.bsky.feed.searchPosts({ const res = await agent.app.bsky.feed.searchPosts({
q: query, q: query,
limit: 25, limit: 25,
cursor: pageParam, cursor: pageParam,

View File

@ -8,7 +8,7 @@ const suggestedFeedsQueryKeyRoot = 'suggestedFeeds'
export const suggestedFeedsQueryKey = [suggestedFeedsQueryKeyRoot] export const suggestedFeedsQueryKey = [suggestedFeedsQueryKeyRoot]
export function useSuggestedFeedsQuery() { export function useSuggestedFeedsQuery() {
const {getAgent} = useAgent() const agent = useAgent()
return useInfiniteQuery< return useInfiniteQuery<
AppBskyFeedGetSuggestedFeeds.OutputSchema, AppBskyFeedGetSuggestedFeeds.OutputSchema,
Error, Error,
@ -19,7 +19,7 @@ export function useSuggestedFeedsQuery() {
staleTime: STALE.HOURS.ONE, staleTime: STALE.HOURS.ONE,
queryKey: suggestedFeedsQueryKey, queryKey: suggestedFeedsQueryKey,
queryFn: async ({pageParam}) => { queryFn: async ({pageParam}) => {
const res = await getAgent().app.bsky.feed.getSuggestedFeeds({ const res = await agent.app.bsky.feed.getSuggestedFeeds({
limit: 10, limit: 10,
cursor: pageParam, cursor: pageParam,
}) })

View File

@ -33,7 +33,7 @@ const suggestedFollowsByActorQueryKey = (did: string) => [
export function useSuggestedFollowsQuery() { export function useSuggestedFollowsQuery() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const moderationOpts = useModerationOpts() const moderationOpts = useModerationOpts()
const {data: preferences} = usePreferencesQuery() const {data: preferences} = usePreferencesQuery()
@ -49,7 +49,7 @@ export function useSuggestedFollowsQuery() {
queryKey: suggestedFollowsQueryKey, queryKey: suggestedFollowsQueryKey,
queryFn: async ({pageParam}) => { queryFn: async ({pageParam}) => {
const contentLangs = getContentLanguages().join(',') const contentLangs = getContentLanguages().join(',')
const res = await getAgent().app.bsky.actor.getSuggestions( const res = await agent.app.bsky.actor.getSuggestions(
{ {
limit: 25, limit: 25,
cursor: pageParam, cursor: pageParam,
@ -94,11 +94,11 @@ export function useSuggestedFollowsQuery() {
} }
export function useSuggestedFollowsByActorQuery({did}: {did: string}) { export function useSuggestedFollowsByActorQuery({did}: {did: string}) {
const {getAgent} = useAgent() const agent = useAgent()
return useQuery<AppBskyGraphGetSuggestedFollowsByActor.OutputSchema, Error>({ return useQuery<AppBskyGraphGetSuggestedFollowsByActor.OutputSchema, Error>({
queryKey: suggestedFollowsByActorQueryKey(did), queryKey: suggestedFollowsByActorQueryKey(did),
queryFn: async () => { queryFn: async () => {
const res = await getAgent().app.bsky.graph.getSuggestedFollowsByActor({ const res = await agent.app.bsky.graph.getSuggestedFollowsByActor({
actor: did, actor: did,
}) })
return res.data return res.data

View File

@ -268,17 +268,10 @@ export function useRequireAuth() {
) )
} }
export function useAgent(): {getAgent: () => BskyAgent} { export function useAgent(): BskyAgent {
const agent = React.useContext(AgentContext) const agent = React.useContext(AgentContext)
if (!agent) { if (!agent) {
throw Error('useAgent() must be below <SessionProvider>.') throw Error('useAgent() must be below <SessionProvider>.')
} }
return React.useMemo( return agent
() => ({
getAgent() {
return agent
},
}),
[agent],
)
} }

View File

@ -90,7 +90,7 @@ export const ComposePost = observer(function ComposePost({
imageUris: initImageUris, imageUris: initImageUris,
}: Props) { }: Props) {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const {data: currentProfile} = useProfileQuery({did: currentAccount!.did}) const {data: currentProfile} = useProfileQuery({did: currentAccount!.did})
const {isModalActive} = useModals() const {isModalActive} = useModals()
const {closeComposer} = useComposerControls() const {closeComposer} = useComposerControls()
@ -260,7 +260,7 @@ export const ComposePost = observer(function ComposePost({
let postUri let postUri
try { try {
postUri = ( postUri = (
await apilib.post(getAgent(), { await apilib.post(agent, {
rawText: richtext.text, rawText: richtext.text,
replyTo: replyTo?.uri, replyTo: replyTo?.uri,
images: gallery.images, images: gallery.images,

View File

@ -8,7 +8,7 @@ import {ComposerOpts} from 'state/shell/composer'
export function useExternalLinkFetch({}: { export function useExternalLinkFetch({}: {
setQuote: (opts: ComposerOpts['quote']) => void setQuote: (opts: ComposerOpts['quote']) => void
}) { }) {
const {getAgent} = useAgent() const agent = useAgent()
const [extLink, setExtLink] = useState<apilib.ExternalEmbedDraft | undefined>( const [extLink, setExtLink] = useState<apilib.ExternalEmbedDraft | undefined>(
undefined, undefined,
) )
@ -22,7 +22,7 @@ export function useExternalLinkFetch({}: {
return cleanup return cleanup
} }
if (!extLink.meta) { if (!extLink.meta) {
getLinkMeta(getAgent(), extLink.uri).then(meta => { getLinkMeta(agent, extLink.uri).then(meta => {
if (aborted) { if (aborted) {
return return
} }
@ -41,7 +41,7 @@ export function useExternalLinkFetch({}: {
}) })
} }
return cleanup return cleanup
}, [extLink, getAgent]) }, [extLink, agent])
return {extLink, setExtLink} return {extLink, setExtLink}
} }

View File

@ -31,7 +31,7 @@ export function useExternalLinkFetch({
) )
const getPost = useGetPost() const getPost = useGetPost()
const fetchDid = useFetchDid() const fetchDid = useFetchDid()
const {getAgent} = useAgent() const agent = useAgent()
useEffect(() => { useEffect(() => {
let aborted = false let aborted = false
@ -59,7 +59,7 @@ export function useExternalLinkFetch({
}, },
) )
} else if (isBskyCustomFeedUrl(extLink.uri)) { } else if (isBskyCustomFeedUrl(extLink.uri)) {
getFeedAsEmbed(getAgent(), fetchDid, extLink.uri).then( getFeedAsEmbed(agent, fetchDid, extLink.uri).then(
({embed, meta}) => { ({embed, meta}) => {
if (aborted) { if (aborted) {
return return
@ -77,7 +77,7 @@ export function useExternalLinkFetch({
}, },
) )
} else if (isBskyListUrl(extLink.uri)) { } else if (isBskyListUrl(extLink.uri)) {
getListAsEmbed(getAgent(), fetchDid, extLink.uri).then( getListAsEmbed(agent, fetchDid, extLink.uri).then(
({embed, meta}) => { ({embed, meta}) => {
if (aborted) { if (aborted) {
return return
@ -95,7 +95,7 @@ export function useExternalLinkFetch({
}, },
) )
} else { } else {
getLinkMeta(getAgent(), extLink.uri).then(meta => { getLinkMeta(agent, extLink.uri).then(meta => {
if (aborted) { if (aborted) {
return return
} }
@ -137,7 +137,7 @@ export function useExternalLinkFetch({
}) })
} }
return cleanup return cleanup
}, [extLink, setQuote, getPost, fetchDid, getAgent]) }, [extLink, setQuote, getPost, fetchDid, agent])
return {extLink, setExtLink} return {extLink, setExtLink}
} }

View File

@ -27,7 +27,7 @@ export const snapPoints = ['90%']
export function Component() { export function Component() {
const pal = usePalette('default') const pal = usePalette('default')
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const {_} = useLingui() const {_} = useLingui()
const [stage, setStage] = useState<Stages>(Stages.InputEmail) const [stage, setStage] = useState<Stages>(Stages.InputEmail)
const [email, setEmail] = useState<string>(currentAccount?.email || '') const [email, setEmail] = useState<string>(currentAccount?.email || '')
@ -45,12 +45,12 @@ export function Component() {
setError('') setError('')
setIsProcessing(true) setIsProcessing(true)
try { try {
const res = await getAgent().com.atproto.server.requestEmailUpdate() const res = await agent.com.atproto.server.requestEmailUpdate()
if (res.data.tokenRequired) { if (res.data.tokenRequired) {
setStage(Stages.ConfirmCode) setStage(Stages.ConfirmCode)
} else { } else {
await getAgent().com.atproto.server.updateEmail({email: email.trim()}) await agent.com.atproto.server.updateEmail({email: email.trim()})
await getAgent().resumeSession(getAgent().session!) await agent.resumeSession(agent.session!)
Toast.show(_(msg`Email updated`)) Toast.show(_(msg`Email updated`))
setStage(Stages.Done) setStage(Stages.Done)
} }
@ -75,11 +75,11 @@ export function Component() {
setError('') setError('')
setIsProcessing(true) setIsProcessing(true)
try { try {
await getAgent().com.atproto.server.updateEmail({ await agent.com.atproto.server.updateEmail({
email: email.trim(), email: email.trim(),
token: confirmationCode.trim(), token: confirmationCode.trim(),
}) })
await getAgent().resumeSession(getAgent().session!) await agent.resumeSession(agent.session!)
Toast.show(_(msg`Email updated`)) Toast.show(_(msg`Email updated`))
setStage(Stages.Done) setStage(Stages.Done)
} catch (e) { } catch (e) {

View File

@ -35,12 +35,12 @@ export type Props = {onChanged: () => void}
export function Component(props: Props) { export function Component(props: Props) {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const { const {
isLoading, isLoading,
data: serviceInfo, data: serviceInfo,
error: serviceInfoError, error: serviceInfoError,
} = useServiceQuery(getAgent().service.toString()) } = useServiceQuery(agent.service.toString())
return isLoading || !currentAccount ? ( return isLoading || !currentAccount ? (
<View style={{padding: 18}}> <View style={{padding: 18}}>
@ -71,7 +71,7 @@ export function Inner({
const {closeModal} = useModalControls() const {closeModal} = useModalControls()
const {mutateAsync: updateHandle, isPending: isUpdateHandlePending} = const {mutateAsync: updateHandle, isPending: isUpdateHandlePending} =
useUpdateHandleMutation() useUpdateHandleMutation()
const {getAgent} = useAgent() const agent = useAgent()
const [error, setError] = useState<string>('') const [error, setError] = useState<string>('')
@ -111,7 +111,7 @@ export function Inner({
await updateHandle({ await updateHandle({
handle: newHandle, handle: newHandle,
}) })
await getAgent().resumeSession(getAgent().session!) await agent.resumeSession(agent.session!)
closeModal() closeModal()
onChanged() onChanged()
} catch (err: any) { } catch (err: any) {
@ -129,7 +129,7 @@ export function Inner({
closeModal, closeModal,
updateHandle, updateHandle,
serviceInfo, serviceInfo,
getAgent, agent,
]) ])
// rendering // rendering

View File

@ -37,7 +37,7 @@ export const snapPoints = isAndroid ? ['90%'] : ['45%']
export function Component() { export function Component() {
const pal = usePalette('default') const pal = usePalette('default')
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const {_} = useLingui() const {_} = useLingui()
const [stage, setStage] = useState<Stages>(Stages.RequestCode) const [stage, setStage] = useState<Stages>(Stages.RequestCode)
const [isProcessing, setIsProcessing] = useState<boolean>(false) const [isProcessing, setIsProcessing] = useState<boolean>(false)
@ -46,7 +46,6 @@ export function Component() {
const [error, setError] = useState<string>('') const [error, setError] = useState<string>('')
const {isMobile} = useWebMediaQueries() const {isMobile} = useWebMediaQueries()
const {closeModal} = useModalControls() const {closeModal} = useModalControls()
const agent = getAgent()
const onRequestCode = async () => { const onRequestCode = async () => {
if ( if (

View File

@ -62,7 +62,7 @@ export function Component({
const {_} = useLingui() const {_} = useLingui()
const listCreateMutation = useListCreateMutation() const listCreateMutation = useListCreateMutation()
const listMetadataMutation = useListMetadataMutation() const listMetadataMutation = useListMetadataMutation()
const {getAgent} = useAgent() const agent = useAgent()
const activePurpose = useMemo(() => { const activePurpose = useMemo(() => {
if (list?.purpose) { if (list?.purpose) {
@ -157,7 +157,7 @@ export function Component({
{cleanNewlines: true}, {cleanNewlines: true},
) )
await richText.detectFacets(getAgent()) await richText.detectFacets(agent)
richText = shortenLinks(richText) richText = shortenLinks(richText)
// filter out any mention facets that didn't map to a user // filter out any mention facets that didn't map to a user
@ -229,7 +229,7 @@ export function Component({
listMetadataMutation, listMetadataMutation,
listCreateMutation, listCreateMutation,
_, _,
getAgent, agent,
]) ])
return ( return (

View File

@ -31,7 +31,7 @@ export function Component({}: {}) {
const pal = usePalette('default') const pal = usePalette('default')
const theme = useTheme() const theme = useTheme()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const {removeAccount} = useSessionApi() const {removeAccount} = useSessionApi()
const {_} = useLingui() const {_} = useLingui()
const {closeModal} = useModalControls() const {closeModal} = useModalControls()
@ -45,7 +45,7 @@ export function Component({}: {}) {
setError('') setError('')
setIsProcessing(true) setIsProcessing(true)
try { try {
await getAgent().com.atproto.server.requestAccountDelete() await agent.com.atproto.server.requestAccountDelete()
setIsEmailSent(true) setIsEmailSent(true)
} catch (e: any) { } catch (e: any) {
setError(cleanError(e)) setError(cleanError(e))
@ -63,7 +63,7 @@ export function Component({}: {}) {
try { try {
// inform chat service of intent to delete account // inform chat service of intent to delete account
const {success} = await getAgent().api.chat.bsky.actor.deleteAccount( const {success} = await agent.api.chat.bsky.actor.deleteAccount(
undefined, undefined,
{ {
headers: DM_SERVICE_HEADERS, headers: DM_SERVICE_HEADERS,
@ -72,7 +72,7 @@ export function Component({}: {}) {
if (!success) { if (!success) {
throw new Error('Failed to inform chat service of account deletion') throw new Error('Failed to inform chat service of account deletion')
} }
await getAgent().com.atproto.server.deleteAccount({ await agent.com.atproto.server.deleteAccount({
did: currentAccount.did, did: currentAccount.did,
password, password,
token, token,

View File

@ -41,7 +41,7 @@ export function Component({
onSuccess?: () => void onSuccess?: () => void
}) { }) {
const pal = usePalette('default') const pal = usePalette('default')
const {getAgent} = useAgent() const agent = useAgent()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {_} = useLingui() const {_} = useLingui()
const [stage, setStage] = useState<Stages>( const [stage, setStage] = useState<Stages>(
@ -64,7 +64,7 @@ export function Component({
setError('') setError('')
setIsProcessing(true) setIsProcessing(true)
try { try {
await getAgent().com.atproto.server.requestEmailConfirmation() await agent.com.atproto.server.requestEmailConfirmation()
setStage(Stages.ConfirmCode) setStage(Stages.ConfirmCode)
} catch (e) { } catch (e) {
setError(cleanError(String(e))) setError(cleanError(String(e)))
@ -77,11 +77,11 @@ export function Component({
setError('') setError('')
setIsProcessing(true) setIsProcessing(true)
try { try {
await getAgent().com.atproto.server.confirmEmail({ await agent.com.atproto.server.confirmEmail({
email: (currentAccount?.email || '').trim(), email: (currentAccount?.email || '').trim(),
token: confirmationCode.trim(), token: confirmationCode.trim(),
}) })
await getAgent().resumeSession(getAgent().session!) await agent.resumeSession(agent.session!)
Toast.show(_(msg`Email verified`)) Toast.show(_(msg`Email verified`))
closeModal() closeModal()
onSuccess?.() onSuccess?.()

View File

@ -470,7 +470,7 @@ function ProfileScreenLoaded({
} }
function useRichText(text: string): [RichTextAPI, boolean] { function useRichText(text: string): [RichTextAPI, boolean] {
const {getAgent} = useAgent() const agent = useAgent()
const [prevText, setPrevText] = React.useState(text) const [prevText, setPrevText] = React.useState(text)
const [rawRT, setRawRT] = React.useState(() => new RichTextAPI({text})) const [rawRT, setRawRT] = React.useState(() => new RichTextAPI({text}))
const [resolvedRT, setResolvedRT] = React.useState<RichTextAPI | null>(null) const [resolvedRT, setResolvedRT] = React.useState<RichTextAPI | null>(null)
@ -485,7 +485,7 @@ function useRichText(text: string): [RichTextAPI, boolean] {
async function resolveRTFacets() { async function resolveRTFacets() {
// new each time // new each time
const resolvedRT = new RichTextAPI({text}) const resolvedRT = new RichTextAPI({text})
await resolvedRT.detectFacets(getAgent()) await resolvedRT.detectFacets(agent)
if (!ignore) { if (!ignore) {
setResolvedRT(resolvedRT) setResolvedRT(resolvedRT)
} }
@ -494,7 +494,7 @@ function useRichText(text: string): [RichTextAPI, boolean] {
return () => { return () => {
ignore = true ignore = true
} }
}, [text, getAgent]) }, [text, agent])
const isResolving = resolvedRT === null const isResolving = resolvedRT === null
return [resolvedRT ?? rawRT, isResolving] return [resolvedRT ?? rawRT, isResolving]
} }

View File

@ -30,7 +30,7 @@ export function DisableEmail2FADialog({
const t = useTheme() const t = useTheme()
const {gtMobile} = useBreakpoints() const {gtMobile} = useBreakpoints()
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {getAgent} = useAgent() const agent = useAgent()
const [stage, setStage] = useState<Stages>(Stages.Email) const [stage, setStage] = useState<Stages>(Stages.Email)
const [confirmationCode, setConfirmationCode] = useState<string>('') const [confirmationCode, setConfirmationCode] = useState<string>('')
@ -41,7 +41,7 @@ export function DisableEmail2FADialog({
setError('') setError('')
setIsProcessing(true) setIsProcessing(true)
try { try {
await getAgent().com.atproto.server.requestEmailUpdate() await agent.com.atproto.server.requestEmailUpdate()
setStage(Stages.ConfirmCode) setStage(Stages.ConfirmCode)
} catch (e) { } catch (e) {
setError(cleanError(String(e))) setError(cleanError(String(e)))
@ -55,12 +55,12 @@ export function DisableEmail2FADialog({
setIsProcessing(true) setIsProcessing(true)
try { try {
if (currentAccount?.email) { if (currentAccount?.email) {
await getAgent().com.atproto.server.updateEmail({ await agent.com.atproto.server.updateEmail({
email: currentAccount!.email, email: currentAccount!.email,
token: confirmationCode.trim(), token: confirmationCode.trim(),
emailAuthFactor: false, emailAuthFactor: false,
}) })
await getAgent().resumeSession(getAgent().session!) await agent.resumeSession(agent.session!)
Toast.show(_(msg`Email 2FA disabled`)) Toast.show(_(msg`Email 2FA disabled`))
} }
control.close() control.close()

View File

@ -13,17 +13,17 @@ export function Email2FAToggle() {
const {currentAccount} = useSession() const {currentAccount} = useSession()
const {openModal} = useModalControls() const {openModal} = useModalControls()
const disableDialogCtrl = useDialogControl() const disableDialogCtrl = useDialogControl()
const {getAgent} = useAgent() const agent = useAgent()
const enableEmailAuthFactor = React.useCallback(async () => { const enableEmailAuthFactor = React.useCallback(async () => {
if (currentAccount?.email) { if (currentAccount?.email) {
await getAgent().com.atproto.server.updateEmail({ await agent.com.atproto.server.updateEmail({
email: currentAccount.email, email: currentAccount.email,
emailAuthFactor: true, emailAuthFactor: true,
}) })
await getAgent().resumeSession(getAgent().session!) await agent.resumeSession(agent.session!)
} }
}, [currentAccount, getAgent]) }, [currentAccount, agent])
const onToggle = React.useCallback(() => { const onToggle = React.useCallback(() => {
if (!currentAccount) { if (!currentAccount) {

View File

@ -21,11 +21,10 @@ export function ExportCarDialog({
}) { }) {
const {_} = useLingui() const {_} = useLingui()
const t = useTheme() const t = useTheme()
const {getAgent} = useAgent() const agent = useAgent()
const [loading, setLoading] = React.useState(false) const [loading, setLoading] = React.useState(false)
const download = React.useCallback(async () => { const download = React.useCallback(async () => {
const agent = getAgent()
if (!agent.session) { if (!agent.session) {
return // shouldnt ever happen return // shouldnt ever happen
} }
@ -49,7 +48,7 @@ export function ExportCarDialog({
setLoading(false) setLoading(false)
control.close() control.close()
} }
}, [_, control, getAgent]) }, [_, control, agent])
return ( return (
<Dialog.Outer control={control}> <Dialog.Outer control={control}>