diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 5a278aeba..72e8cafa4 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -23,6 +23,7 @@ import {sha256} from 'js-sha256' import {CID} from 'multiformats/cid' import * as Hasher from 'multiformats/hashes/hasher' +import {communityXrpc} from '#/lib/api/community' import {IMAGE_SIZE_CONFIG_POSTS} from '#/lib/constants' import {isNetworkError} from '#/lib/strings/errors' import {shortenLinks, stripInvalidMentions} from '#/lib/strings/rich-text-manip' @@ -47,6 +48,8 @@ import {uploadBlob} from './upload-blob' export {uploadBlob} +const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' + interface PostOpts { thread: ThreadDraft replyTo?: string @@ -62,6 +65,10 @@ export async function post( const thread = opts.thread opts.onStateChange?.(t`Processing...`) + if (thread.blackskyOnly) { + return postCommunity(agent, queryClient, opts) + } + let replyPromise: | Promise | AppBskyFeedPost.Record['reply'] @@ -197,6 +204,156 @@ export async function post( return {uris} } +async function postCommunity( + agent: AtpAgent, + queryClient: QueryClient, + opts: PostOpts, +) { + const thread = opts.thread + + let replyPromise: + | Promise + | AppBskyFeedPost.Record['reply'] + | undefined + if (opts.replyTo) { + replyPromise = resolveReply(agent, opts.replyTo) + } + + let langs = opts.langs + if (opts.langs) { + langs = opts.langs.slice(0, 3) + } + + const did = agent.assertDid + const writes: $Typed[] = [] + const uris: string[] = [] + + let now = new Date() + let tid: TID | undefined + + for (let i = 0; i < thread.posts.length; i++) { + const draft = thread.posts[i] + + const rtPromise = resolveRT(agent, draft.richtext) + const embedPromise = resolveEmbed( + agent, + queryClient, + draft, + opts.onStateChange, + ) + let labels: $Typed | undefined + if (draft.labels.length) { + labels = { + $type: 'com.atproto.label.defs#selfLabels', + values: draft.labels.map(val => ({val})), + } + } + + now.setMilliseconds(now.getMilliseconds() + 1) + tid = TID.next(tid) + const rkey = tid.toString() + const uri = `at://${did}/${COMMUNITY_POST_COLLECTION}/${rkey}` + uris.push(uri) + + const rt = await rtPromise + const embed = await embedPromise + const reply = await replyPromise + + // Step 1: Submit full content to appview via PDS proxy + opts.onStateChange?.(t`Submitting to community...`) + const submitBody: Record = { + rkey, + text: rt.text, + createdAt: now.toISOString(), + } + if (rt.facets?.length) { + submitBody.facets = rt.facets + } + if (reply) { + submitBody.reply = reply + } + if (embed) { + submitBody.embed = embed + } + if (langs?.length) { + submitBody.langs = langs + } + if (labels) { + submitBody.labels = labels + } + + let cid: string | undefined + try { + const submitRes = await communityXrpc( + agent, + 'community.blacksky.feed.submitPost', + {body: submitBody}, + ) + if (!submitRes.ok) { + const errBody = (await submitRes.json().catch(() => ({}))) as { + message?: string + } + throw new Error(errBody.message || `HTTP ${submitRes.status}`) + } + const submitData = (await submitRes.json()) as {cid?: string} + cid = submitData?.cid + } catch (e) { + logger.error(`Failed to submit community post content`, { + safeMessage: e instanceof Error ? e.message : String(e), + }) + throw new Error(t`Failed to submit community post. Please try again.`) + } + + // Step 2: Build stub record for PDS + const stubRecord: Record = { + $type: COMMUNITY_POST_COLLECTION, + createdAt: now.toISOString(), + } + if (cid) { + stubRecord.cid = cid + } + + writes.push({ + $type: 'com.atproto.repo.applyWrites#create', + collection: COMMUNITY_POST_COLLECTION, + rkey, + value: stubRecord, + }) + + // Prepare ref for next post in thread + const ref = { + cid: await computeCid(stubRecord as unknown as AppBskyFeedPost.Record), + uri, + } + replyPromise = { + root: reply?.root ?? ref, + parent: ref, + } + } + + // Write stubs to PDS + try { + await agent.com.atproto.repo.applyWrites({ + repo: agent.assertDid, + writes, + validate: false, + }) + } catch (e) { + logger.error(`Failed to write community post stubs`, { + safeMessage: e instanceof Error ? e.message : String(e), + }) + if (isNetworkError(e)) { + throw new Error( + t`Post failed to upload. Please check your Internet connection and try again.`, + ) + } else { + throw e + } + } + + return {uris} +} + async function resolveRT(agent: AtpAgent, richtext: RichText) { const trimmedText = richtext.text // Trim leading whitespace-only lines (but don't break ASCII art). -- knotmirror 0.0.1 From cd9ffd1f5cbb649d3550e89a5ded71178c424a45 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 5 Feb 2026 16:20:26 -0500 Subject: [PATCH 02/50] Compute CID locally for community post integrity verification Client now computes CID from canonical record BEFORE sending to appview: 1. Build canonical record with exact structure appview expects 2. Compute CID using computeCid (DAG-CBOR, CIDv1, SHA-256) 3. Send expectedCid to appview for verification 4. Store client's CID in stub record (source of truth) This enables integrity verification: if appview modifies content, the CID won't match what's stored in the user's PDS stub record. The stub record in the user's repo acts as a cryptographic commitment to the original content, preserving user control over their data. --- src/lib/api/index.ts | 45 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 72e8cafa4..5568426b7 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -259,12 +259,39 @@ async function postCommunity( const embed = await embedPromise const reply = await replyPromise - // Step 1: Submit full content to appview via PDS proxy + // Step 1: Build the canonical record for CID computation + // This MUST match the structure the appview uses for CID verification + const createdAt = now.toISOString() + const canonicalRecord: Record = { + $type: COMMUNITY_POST_COLLECTION, + text: rt.text, + createdAt, + } + if (rt.facets?.length) { + canonicalRecord.facets = rt.facets + } + if (langs?.length) { + canonicalRecord.langs = langs + } + if (embed) { + canonicalRecord.embed = embed + } + if (reply) { + canonicalRecord.reply = reply + } + + // Step 2: Compute CID locally - this is the SOURCE OF TRUTH for integrity + const cid = await computeCid( + canonicalRecord as unknown as AppBskyFeedPost.Record, + ) + + // Step 3: Submit to appview with expectedCid for verification opts.onStateChange?.(t`Submitting to community...`) const submitBody: Record = { rkey, text: rt.text, - createdAt: now.toISOString(), + createdAt, + expectedCid: cid, // Appview will verify this matches } if (rt.facets?.length) { submitBody.facets = rt.facets @@ -282,7 +309,6 @@ async function postCommunity( submitBody.labels = labels } - let cid: string | undefined try { const submitRes = await communityXrpc( agent, @@ -295,8 +321,11 @@ async function postCommunity( } throw new Error(errBody.message || `HTTP ${submitRes.status}`) } + // Appview returns the verified CID - should match our local computation const submitData = (await submitRes.json()) as {cid?: string} - cid = submitData?.cid + if (submitData?.cid !== cid) { + logger.warn(`CID mismatch: local=${cid}, server=${submitData?.cid}`) + } } catch (e) { logger.error(`Failed to submit community post content`, { safeMessage: e instanceof Error ? e.message : String(e), @@ -304,13 +333,11 @@ async function postCommunity( throw new Error(t`Failed to submit community post. Please try again.`) } - // Step 2: Build stub record for PDS + // Step 4: Build stub record for PDS with CLIENT-COMPUTED CID const stubRecord: Record = { $type: COMMUNITY_POST_COLLECTION, - createdAt: now.toISOString(), - } - if (cid) { - stubRecord.cid = cid + createdAt, + cid, // Client's own CID - source of truth for integrity verification } writes.push({ -- knotmirror 0.0.1 From 6ff50f46c728f694f03bcd265b144df62fbaf96a Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 5 Feb 2026 16:29:49 -0500 Subject: [PATCH 03/50] Fix replies to community posts resolveReply was using agent.getPost() which only works for app.bsky.feed.post collection. When replying to a community post, it now detects the collection and fetches via getCommunityPost from the appview instead. --- src/lib/api/index.ts | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 5568426b7..76bec2fd6 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -402,6 +402,41 @@ export class ReplyDeletedError extends Error { } async function resolveReply(agent: AtpAgent, replyTo: string) { + const replyToUrip = new AtUri(replyTo) + + // Community posts are fetched from the appview, not the standard feed API. + if (replyToUrip.collection === COMMUNITY_POST_COLLECTION) { + const res = await communityXrpc( + agent, + 'community.blacksky.feed.getCommunityPost', + {params: {uri: replyTo}}, + ) + if (!res.ok) { + logger.error('Failed to fetch parent community post for reply', { + uri: replyTo, + }) + return undefined + } + const data = (await res.json()) as { + post?: { + uri: string + cid: string + replyRoot?: string + replyRootCid?: string + } + } + if (data.post) { + const parentRef = {uri: data.post.uri, cid: data.post.cid} + const rootRef = + data.post.replyRoot && data.post.replyRootCid + ? {uri: data.post.replyRoot, cid: data.post.replyRootCid} + : parentRef + return {root: rootRef, parent: parentRef} + } + return undefined + } + + // Standard Bluesky post const {data} = await agent.app.bsky.feed.getPosts({ uris: [replyTo], }) -- knotmirror 0.0.1 From a3ff0402eedbca619f46aa6691bc4783a77aedb0 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 5 Feb 2026 17:36:39 -0500 Subject: [PATCH 04/50] Route replies to community posts through community endpoint When replying to a community post, the reply must also be created as a community post to maintain thread integrity. Previously, replies were being created as standard app.bsky.feed.post records, breaking the community-only thread chain. Now checks if replyTo URI contains 'community.blacksky.feed.post' and routes to postCommunity() automatically, regardless of blackskyOnly toggle. --- src/lib/api/index.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 76bec2fd6..f382bff01 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -65,7 +65,13 @@ export async function post( const thread = opts.thread opts.onStateChange?.(t`Processing...`) - if (thread.blackskyOnly) { + // Route to community post endpoint if: + // 1. User explicitly selected "Blacksky Only" + // 2. Replying to a community post (replies must stay in the community) + const isReplyToCommunityPost = + opts.replyTo && opts.replyTo.includes(COMMUNITY_POST_COLLECTION) + + if (thread.blackskyOnly || isReplyToCommunityPost) { return postCommunity(agent, queryClient, opts) } -- knotmirror 0.0.1 From 2ea578cd1792b1bc9cbbe893cb9c706526ba6917 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 5 Feb 2026 19:24:15 -0500 Subject: [PATCH 05/50] Update Community tab to show global timeline of all posts - Change CommunityFeedPage to use useCommunityTimelineQuery instead of useCommunityFeedQuery (which only shows the viewer's posts) - The Community tab on Home screen now shows ALL community posts - Add TIMELINE_RQKEY constants for proper cache invalidation - Update findAllPostsInQueryData to search both actor feeds and timeline --- src/components/CommunityFeed.tsx | 127 ++++++++++ src/components/Post/Embed/index.tsx | 6 +- .../PostControls/PostMenu/PostMenuItems.tsx | 9 +- .../PostControls/ShareMenu/ShareMenuItems.tsx | 4 +- .../ShareMenu/ShareMenuItems.web.tsx | 4 +- .../PostControls/ShareMenu/index.tsx | 4 +- src/lib/api/community.ts | 37 +++ src/lib/routes/types.ts | 2 +- .../Messages/components/MessageInputEmbed.tsx | 6 +- .../PostThread/components/ThreadItemPost.tsx | 4 +- .../components/ThreadItemTreePost.tsx | 4 +- .../Profile/Sections/CommunityFeed.tsx | 181 ++++++++++++++ src/state/cache/post-shadow.ts | 4 + src/state/queries/community-feed.ts | 221 ++++++++++++++++++ src/state/queries/feed.ts | 29 +++ src/state/queries/post-feed.ts | 1 + src/state/queries/post.ts | 31 ++- src/state/queries/profile.ts | 12 + src/view/com/composer/Composer.tsx | 33 ++- src/view/com/composer/state/composer.ts | 14 ++ src/view/com/feeds/CommunityFeedPage.tsx | 173 ++++++++++++++ src/view/com/post/Post.tsx | 5 +- src/view/com/posts/PostFeedItem.tsx | 7 +- src/view/com/posts/ViewFullThread.tsx | 8 +- src/view/screens/Home.tsx | 9 + src/view/screens/PostThread.tsx | 4 +- src/view/screens/Profile.tsx | 23 ++ 27 files changed, 944 insertions(+), 18 deletions(-) create mode 100644 src/components/CommunityFeed.tsx create mode 100644 src/lib/api/community.ts create mode 100644 src/screens/Profile/Sections/CommunityFeed.tsx create mode 100644 src/state/queries/community-feed.ts create mode 100644 src/view/com/feeds/CommunityFeedPage.tsx diff --git a/src/components/CommunityFeed.tsx b/src/components/CommunityFeed.tsx new file mode 100644 index 000000000..30fec5a58 --- /dev/null +++ b/src/components/CommunityFeed.tsx @@ -0,0 +1,127 @@ +import React from 'react' +import {ActivityIndicator, View} from 'react-native' +import { + type AppBskyFeedDefs, + type AppBskyFeedPost, + RichText as RichTextAPI, +} from '@atproto/api' +import {Trans} from '@lingui/macro' + +import {useCommunityFeedQuery} from '#/state/queries/community-feed' +import {TimeElapsed} from '#/view/com/util/TimeElapsed' +import {atoms as a, useTheme} from '#/alf' +import {RichText} from '#/components/RichText' +import {Text} from '#/components/Typography' + +export function CommunityFeed({actor}: {actor: string}) { + const t = useTheme() + const { + data, + isLoading, + isError, + hasNextPage, + fetchNextPage, + isFetchingNextPage, + } = useCommunityFeedQuery(actor) + + if (isLoading) { + return ( + + + + ) + } + + if (isError) { + return ( + + + Failed to load community posts + + + ) + } + + const feedItems = data?.pages.flatMap(page => page.feed) || [] + + if (feedItems.length === 0) { + return ( + + + No community posts yet + + + ) + } + + return ( + + + + Blacksky Community Posts + + + {feedItems.map(item => ( + + ))} + {hasNextPage && ( + + {isFetchingNextPage ? ( + + ) : ( + fetchNextPage()}> + Load more + + )} + + )} + + ) +} + +export function CommunityPostItem({ + postView, +}: { + postView: AppBskyFeedDefs.PostView +}) { + const t = useTheme() + const record = postView.record as AppBskyFeedPost.Record + const rt = React.useMemo(() => { + const richText = new RichTextAPI({ + text: record.text, + facets: record.facets, + }) + return richText + }, [record.text, record.facets]) + + return ( + + + + Community + + + {({timeElapsed}) => ( + + {timeElapsed} + + )} + + {(postView.replyCount ?? 0) > 0 && ( + + {postView.replyCount} replies + + )} + + + + ) +} diff --git a/src/components/Post/Embed/index.tsx b/src/components/Post/Embed/index.tsx index 7472d50ef..914ffc65c 100644 --- a/src/components/Post/Embed/index.tsx +++ b/src/components/Post/Embed/index.tsx @@ -327,7 +327,11 @@ export function QuoteEmbed({ const t = useTheme() const queryClient = useQueryClient() const itemUrip = new AtUri(quote.uri) - const itemHref = makeProfileLink(quote.author, 'post', itemUrip.rkey) + const isCommunityQuote = + itemUrip.collection === 'community.blacksky.feed.post' + const itemHref = isCommunityQuote + ? `${makeProfileLink(quote.author, 'post', itemUrip.rkey)}?collection=${itemUrip.collection}` + : makeProfileLink(quote.author, 'post', itemUrip.rkey) const itemTitle = `Post by ${quote.author.handle}` const richText = useMemo(() => { diff --git a/src/components/PostControls/PostMenu/PostMenuItems.tsx b/src/components/PostControls/PostMenu/PostMenuItems.tsx index 9f18bd01a..0d7828b26 100644 --- a/src/components/PostControls/PostMenu/PostMenuItems.tsx +++ b/src/components/PostControls/PostMenu/PostMenuItems.tsx @@ -182,7 +182,9 @@ let PostMenuItems = ({ const href = useMemo(() => { const urip = new AtUri(postUri) - return makeProfileLink(postAuthor, 'post', urip.rkey) + const link = makeProfileLink(postAuthor, 'post', urip.rkey) + const isCommunity = urip.collection === 'community.blacksky.feed.post' + return isCommunity ? `${link}?collection=${urip.collection}` : link }, [postUri, postAuthor]) const onDeletePost = () => { @@ -199,7 +201,10 @@ let PostMenuItems = ({ (params.name === currentAccount.handle || params.name === currentAccount.did) ) { - const currentHref = makeProfileLink(postAuthor, 'post', params.rkey) + const currentLink = makeProfileLink(postAuthor, 'post', params.rkey) + const currentHref = params.collection + ? `${currentLink}?collection=${params.collection}` + : currentLink if (currentHref === href && navigation.canGoBack()) { navigation.goBack() } diff --git a/src/components/PostControls/ShareMenu/ShareMenuItems.tsx b/src/components/PostControls/ShareMenu/ShareMenuItems.tsx index ab9ab1eef..a7b02e547 100644 --- a/src/components/PostControls/ShareMenu/ShareMenuItems.tsx +++ b/src/components/PostControls/ShareMenu/ShareMenuItems.tsx @@ -47,7 +47,9 @@ let ShareMenuItems = ({ const href = useMemo(() => { const urip = new AtUri(postUri) - return makeProfileLink(postAuthor, 'post', urip.rkey) + const link = makeProfileLink(postAuthor, 'post', urip.rkey) + const isCommunity = urip.collection === 'community.blacksky.feed.post' + return isCommunity ? `${link}?collection=${urip.collection}` : link }, [postUri, postAuthor]) const hideInPWI = useMemo(() => { diff --git a/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx b/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx index 2cb66b29a..963c5bb04 100644 --- a/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx +++ b/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx @@ -46,7 +46,9 @@ let ShareMenuItems = ({ const href = useMemo(() => { const urip = new AtUri(postUri) - return makeProfileLink(postAuthor, 'post', urip.rkey) + const link = makeProfileLink(postAuthor, 'post', urip.rkey) + const isCommunity = urip.collection === 'community.blacksky.feed.post' + return isCommunity ? `${link}?collection=${urip.collection}` : link }, [postUri, postAuthor]) const hideInPWI = useMemo(() => { diff --git a/src/components/PostControls/ShareMenu/index.tsx b/src/components/PostControls/ShareMenu/index.tsx index efac6a3f0..6464d0dd3 100644 --- a/src/components/PostControls/ShareMenu/index.tsx +++ b/src/components/PostControls/ShareMenu/index.tsx @@ -86,7 +86,9 @@ let ShareMenuButton = ({ const onNativeLongPress = () => { ax.metric('share:press:nativeShare', {}) const urip = new AtUri(post.uri) - const href = makeProfileLink(post.author, 'post', urip.rkey) + const link = makeProfileLink(post.author, 'post', urip.rkey) + const isCommunity = urip.collection === 'community.blacksky.feed.post' + const href = isCommunity ? `${link}?collection=${urip.collection}` : link const url = toShareUrl(href) shareUrl(url) onShare() diff --git a/src/lib/api/community.ts b/src/lib/api/community.ts new file mode 100644 index 000000000..112a69bb3 --- /dev/null +++ b/src/lib/api/community.ts @@ -0,0 +1,37 @@ +import {type BskyAgent} from '@atproto/api' + +import {BLUESKY_PROXY_HEADER} from '#/lib/constants' + +/** + * Make an XRPC call to a community.blacksky.feed.* endpoint. + * + * Calls through the PDS using the agent's session auth and atproto-proxy + * header. The PDS validates the user's credentials, creates a service auth + * JWT signed by the user's keypair, and forwards the request to the appview. + */ +export async function communityXrpc( + agent: BskyAgent, + method: string, + opts?: { + params?: Record + body?: unknown + }, +): Promise { + const qs = opts?.params + ? '?' + new URLSearchParams(opts.params).toString() + : '' + const path = `/xrpc/${method}${qs}` + + const headers: Record = { + 'atproto-proxy': BLUESKY_PROXY_HEADER.get(), + } + const init: RequestInit = { + method: opts?.body ? 'POST' : 'GET', + headers, + } + if (opts?.body) { + headers['Content-Type'] = 'application/json' + init.body = JSON.stringify(opts.body) + } + return agent.fetchHandler(path, init) +} diff --git a/src/lib/routes/types.ts b/src/lib/routes/types.ts index d0fbe4e6a..ff036627d 100644 --- a/src/lib/routes/types.ts +++ b/src/lib/routes/types.ts @@ -22,7 +22,7 @@ export type CommonNavigatorParams = { ProfileKnownFollowers: {name: string} ProfileSearch: {name: string; q?: string} ProfileList: {name: string; rkey: string} - PostThread: {name: string; rkey: string} + PostThread: {name: string; rkey: string; collection?: string} PostLikedBy: {name: string; rkey: string} PostRepostedBy: {name: string; rkey: string} PostQuotes: {name: string; rkey: string} diff --git a/src/screens/Messages/components/MessageInputEmbed.tsx b/src/screens/Messages/components/MessageInputEmbed.tsx index 4b69e1f67..355a9c2fb 100644 --- a/src/screens/Messages/components/MessageInputEmbed.tsx +++ b/src/screens/Messages/components/MessageInputEmbed.tsx @@ -204,7 +204,11 @@ function MessageInputPostEmbed({ } case 'success': { const itemUrip = new AtUri(post.uri) - const itemHref = makeProfileLink(post.author, 'post', itemUrip.rkey) + const isCommunityPost = + itemUrip.collection === 'community.blacksky.feed.post' + const itemHref = isCommunityPost + ? `${makeProfileLink(post.author, 'post', itemUrip.rkey)}?collection=${itemUrip.collection}` + : makeProfileLink(post.author, 'post', itemUrip.rkey) if (!post || !moderation || !rt || !record) { return null diff --git a/src/screens/PostThread/components/ThreadItemPost.tsx b/src/screens/PostThread/components/ThreadItemPost.tsx index c1e27222f..5ee7d85b2 100644 --- a/src/screens/PostThread/components/ThreadItemPost.tsx +++ b/src/screens/PostThread/components/ThreadItemPost.tsx @@ -212,7 +212,9 @@ const ThreadItemPostInner = memo(function ThreadItemPostInner({ const threadRootUri = record.reply?.root?.uri || post.uri const postHref = useMemo(() => { const urip = new AtUri(post.uri) - return makeProfileLink(post.author, 'post', urip.rkey) + const link = makeProfileLink(post.author, 'post', urip.rkey) + const isCommunity = urip.collection === 'community.blacksky.feed.post' + return isCommunity ? `${link}?collection=${urip.collection}` : link }, [post.uri, post.author]) const threadgateHiddenReplies = useMergedThreadgateHiddenReplies({ threadgateRecord, diff --git a/src/screens/PostThread/components/ThreadItemTreePost.tsx b/src/screens/PostThread/components/ThreadItemTreePost.tsx index 986878664..c1125110b 100644 --- a/src/screens/PostThread/components/ThreadItemTreePost.tsx +++ b/src/screens/PostThread/components/ThreadItemTreePost.tsx @@ -274,7 +274,9 @@ const ThreadItemTreePostInner = memo(function ThreadItemTreePostInner({ const threadRootUri = record.reply?.root?.uri || post.uri const postHref = useMemo(() => { const urip = new AtUri(post.uri) - return makeProfileLink(post.author, 'post', urip.rkey) + const link = makeProfileLink(post.author, 'post', urip.rkey) + const isCommunity = urip.collection === 'community.blacksky.feed.post' + return isCommunity ? `${link}?collection=${urip.collection}` : link }, [post.uri, post.author]) const threadgateHiddenReplies = useMergedThreadgateHiddenReplies({ threadgateRecord, diff --git a/src/screens/Profile/Sections/CommunityFeed.tsx b/src/screens/Profile/Sections/CommunityFeed.tsx new file mode 100644 index 000000000..297435129 --- /dev/null +++ b/src/screens/Profile/Sections/CommunityFeed.tsx @@ -0,0 +1,181 @@ +import {useCallback, useEffect, useImperativeHandle, useMemo} from 'react' +import { + ActivityIndicator, + findNodeHandle, + type ListRenderItemInfo, + View, +} from 'react-native' +import {msg, Trans} from '@lingui/macro' +import {useLingui} from '@lingui/react' + +import { + type HydratedCommunityPost, + useCommunityFeedHydrated, + useCommunityFeedQuery, +} from '#/state/queries/community-feed' +import {PostFeedItem} from '#/view/com/posts/PostFeedItem' +import {EmptyState} from '#/view/com/util/EmptyState' +import {List, type ListRef} from '#/view/com/util/List' +import {atoms as a, ios, useTheme} from '#/alf' +import {Text} from '#/components/Typography' +import {IS_IOS, IS_NATIVE} from '#/env' +import {type SectionRef} from './types' + +interface CommunityFeedSectionProps { + ref?: React.Ref + actor: string + headerHeight: number + isFocused: boolean + scrollElRef: ListRef + setScrollViewTag: (tag: number | null) => void +} + +export function CommunityFeedSection({ + ref, + actor, + headerHeight, + isFocused, + scrollElRef, + setScrollViewTag, +}: CommunityFeedSectionProps) { + const {_} = useLingui() + const t = useTheme() + const { + data, + isLoading, + isError, + hasNextPage, + fetchNextPage, + isFetchingNextPage, + refetch, + } = useCommunityFeedQuery(isFocused ? actor : undefined) + + const feedItems = useMemo( + () => data?.pages.flatMap(page => page.feed ?? []) ?? [], + [data], + ) + + const hydratedPosts = useCommunityFeedHydrated(feedItems) + + const onScrollToTop = useCallback(() => { + scrollElRef.current?.scrollToOffset({ + animated: IS_NATIVE, + offset: -headerHeight, + }) + refetch() + }, [scrollElRef, headerHeight, refetch]) + + useImperativeHandle(ref, () => ({ + scrollToTop: onScrollToTop, + })) + + useEffect(() => { + if (IS_IOS && isFocused && scrollElRef.current) { + const nativeTag = findNodeHandle(scrollElRef.current) + setScrollViewTag(nativeTag) + } + }, [isFocused, scrollElRef, setScrollViewTag]) + + const renderItem = useCallback( + ({item, index}: ListRenderItemInfo) => { + return ( + + ) + }, + [], + ) + + const keyExtractor = useCallback( + (item: HydratedCommunityPost) => item.post.uri, + [], + ) + + const onEndReached = useCallback(() => { + if (hasNextPage && !isFetchingNextPage) { + fetchNextPage() + } + }, [hasNextPage, isFetchingNextPage, fetchNextPage]) + + const renderEmpty = useCallback(() => { + if (isLoading) { + return ( + + + + ) + } + if (isError) { + return ( + + + Failed to load community posts + + + ) + } + return ( + + ) + }, [_, isLoading, isError, t]) + + const renderFooter = useCallback(() => { + if (isFetchingNextPage) { + return ( + + + + ) + } + if (!hasNextPage && hydratedPosts.length > 0) { + return ( + + + End of feed + + + ) + } + return null + }, [isFetchingNextPage, hasNextPage, hydratedPosts.length, t]) + + return ( + + + + ) +} diff --git a/src/state/cache/post-shadow.ts b/src/state/cache/post-shadow.ts index 33e78580a..c3ccd6dbb 100644 --- a/src/state/cache/post-shadow.ts +++ b/src/state/cache/post-shadow.ts @@ -9,6 +9,7 @@ import {EventEmitter} from 'eventemitter3' import {batchedUpdates} from '#/lib/batchedUpdates' import {findAllPostsInQueryData as findAllPostsInBookmarksQueryData} from '#/state/queries/bookmarks/useBookmarksQuery' +import {findAllPostsInQueryData as findAllPostsInCommunityFeedQueryData} from '#/state/queries/community-feed' import {findAllPostsInQueryData as findAllPostsInExploreFeedPreviewsQueryData} from '#/state/queries/explore-feed-previews' import {findAllPostsInQueryData as findAllPostsInNotifsQueryData} from '#/state/queries/notifications/feed' import {findAllPostsInQueryData as findAllPostsInFeedQueryData} from '#/state/queries/post-feed' @@ -198,4 +199,7 @@ function* findPostsInCache( for (let post of findAllPostsInTopicQueryData(queryClient, uri)) { yield post } + for (let post of findAllPostsInCommunityFeedQueryData(queryClient, uri)) { + yield post + } } diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts new file mode 100644 index 000000000..ed769efd8 --- /dev/null +++ b/src/state/queries/community-feed.ts @@ -0,0 +1,221 @@ +import {useMemo} from 'react' +import { + type AppBskyFeedDefs, + type AppBskyFeedPost, + AtUri, + moderatePost, + type ModerationDecision, +} from '@atproto/api' +import { + type InfiniteData, + type QueryClient, + type QueryKey, + useInfiniteQuery, + useQuery, +} from '@tanstack/react-query' + +import {communityXrpc} from '#/lib/api/community' +import {useModerationOpts} from '#/state/preferences/moderation-opts' +import { + didOrHandleUriMatches, + embedViewRecordToPostView, + getEmbeddedPost, +} from '#/state/queries/util' +import {useAgent} from '#/state/session' + +const PAGE_SIZE = 30 +type RQPageParam = string | undefined + +export const RQKEY_ROOT = 'community-feed' +export const RQKEY = (actor: string) => [RQKEY_ROOT, actor] + +const TIMELINE_RQKEY_ROOT = 'community-timeline' +export const TIMELINE_RQKEY = () => [TIMELINE_RQKEY_ROOT] + +// Server returns feedViewPost format with hydrated posts +// Support both old 'posts' format (raw) and new 'feed' format (hydrated) +interface CommunityFeedPage { + cursor?: string + feed?: AppBskyFeedDefs.FeedViewPost[] + // Legacy format for backward compatibility during deployment + posts?: Array<{ + uri: string + cid?: string + creator: string + text: string + createdAt: string + indexedAt: string + }> +} + +export function useCommunityFeedQuery(actor: string | undefined) { + const agent = useAgent() + return useInfiniteQuery< + CommunityFeedPage, + Error, + InfiniteData, + QueryKey, + RQPageParam + >({ + queryKey: RQKEY(actor || ''), + async queryFn({pageParam}: {pageParam: RQPageParam}) { + const params: Record = { + actor: actor || '', + limit: String(PAGE_SIZE), + } + if (pageParam) { + params.cursor = pageParam + } + const res = await communityXrpc( + agent, + 'community.blacksky.feed.getCommunityFeed', + {params}, + ) + if (!res.ok) { + throw new Error(`getCommunityFeed failed: ${res.status}`) + } + return (await res.json()) as CommunityFeedPage + }, + initialPageParam: undefined, + getNextPageParam: lastPage => lastPage.cursor, + enabled: !!actor, + }) +} + +/** + * Query for the global community timeline (all community posts). + * Used on the Home screen Community tab. + */ +export function useCommunityTimelineQuery(enabled: boolean) { + const agent = useAgent() + return useInfiniteQuery< + CommunityFeedPage, + Error, + InfiniteData, + QueryKey, + RQPageParam + >({ + queryKey: TIMELINE_RQKEY(), + async queryFn({pageParam}: {pageParam: RQPageParam}) { + const params: Record = { + limit: String(PAGE_SIZE), + } + if (pageParam) { + params.cursor = pageParam + } + const res = await communityXrpc( + agent, + 'community.blacksky.feed.getCommunityTimeline', + {params}, + ) + if (!res.ok) { + throw new Error(`getCommunityTimeline failed: ${res.status}`) + } + return (await res.json()) as CommunityFeedPage + }, + initialPageParam: undefined, + getNextPageParam: lastPage => lastPage.cursor, + enabled, + }) +} + +const COMMUNITY_POST_RQKEY_ROOT = 'community-post' +export const COMMUNITY_POST_RQKEY = (uri: string) => [ + COMMUNITY_POST_RQKEY_ROOT, + uri, +] + +export function useCommunityPostQuery(uri: string | undefined) { + const agent = useAgent() + return useQuery({ + queryKey: COMMUNITY_POST_RQKEY(uri || ''), + async queryFn() { + const res = await communityXrpc( + agent, + 'community.blacksky.feed.getCommunityPost', + {params: {uri: uri || ''}}, + ) + if (!res.ok) { + throw new Error(`getCommunityPost failed: ${res.status}`) + } + const data = (await res.json()) as {post: AppBskyFeedDefs.PostView} + return data.post + }, + enabled: !!uri, + }) +} + +export interface HydratedCommunityPost { + post: AppBskyFeedDefs.PostView + record: AppBskyFeedPost.Record + moderation: ModerationDecision +} + +/** + * Takes pre-hydrated feed items from the server and adds moderation decisions. + * The server now returns properly hydrated PostViews with author info and counts. + */ +export function useCommunityFeedHydrated( + feedItems: AppBskyFeedDefs.FeedViewPost[], +): HydratedCommunityPost[] { + const moderationOpts = useModerationOpts() + + return useMemo(() => { + if (!moderationOpts) return [] + + return feedItems + .filter(item => item?.post) // Filter out any undefined items + .map(item => { + const postView = item.post + const record = postView.record as AppBskyFeedPost.Record + const moderation = moderatePost(postView, moderationOpts) + return {post: postView, record, moderation} + }) + }, [feedItems, moderationOpts]) +} + +/** + * Generator function to find all posts in the community feed cache. + * Used by the post shadow system to update cached posts after mutations. + */ +export function* findAllPostsInQueryData( + queryClient: QueryClient, + uri: string, +): Generator { + const atUri = new AtUri(uri) + + // Search both actor feeds and timeline + const queryDatas = [ + ...queryClient.getQueriesData>({ + queryKey: [RQKEY_ROOT], + }), + ...queryClient.getQueriesData>({ + queryKey: [TIMELINE_RQKEY_ROOT], + }), + ] + + for (const [_queryKey, queryData] of queryDatas) { + if (!queryData?.pages) { + continue + } + for (const page of queryData.pages) { + if (!page.feed) { + continue + } + for (const item of page.feed) { + if (!item?.post) { + continue + } + if (didOrHandleUriMatches(atUri, item.post)) { + yield item.post + } + + // Check for quoted posts in embeds + const quotedPost = getEmbeddedPost(item.post.embed) + if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + yield embedViewRecordToPostView(quotedPost) + } + } + } + } +} diff --git a/src/state/queries/feed.ts b/src/state/queries/feed.ts index ac6e4bf7f..c55fd7d0e 100644 --- a/src/state/queries/feed.ts +++ b/src/state/queries/feed.ts @@ -549,6 +549,32 @@ const createPinnedFeedInfosQueryKey = ( }, ) +const COMMUNITY_FEED_STUB: SavedFeedSourceInfo = { + type: 'feed', + displayName: 'Community', + uri: 'community', + feedDescriptor: 'community', + route: { + href: '/', + name: 'Home', + params: {}, + }, + cid: '', + avatar: '', + description: new RichText({text: ''}), + creatorDid: '', + creatorHandle: '', + likeCount: 0, + likeUri: '', + savedFeed: { + id: 'community', + type: 'feed', + value: 'community', + pinned: true, + }, + contentMode: undefined, +} + export function usePinnedFeedsInfos() { const {hasSession} = useSession() const agent = useAgent() @@ -635,6 +661,9 @@ export function usePinnedFeedsInfos() { }) } } + // Inject Community feed after the first item (Following) + const insertIndex = Math.min(1, result.length) + result.splice(insertIndex, 0, COMMUNITY_FEED_STUB) return result }, }) diff --git a/src/state/queries/post-feed.ts b/src/state/queries/post-feed.ts index 959ed81c2..b0c226b23 100644 --- a/src/state/queries/post-feed.ts +++ b/src/state/queries/post-feed.ts @@ -58,6 +58,7 @@ type PostsUriList = string export type FeedDescriptor = | 'following' + | 'community' | `author|${ActorDid}|${AuthorFilter}` | `feedgen|${FeedUri}` | `likes|${ActorDid}` diff --git a/src/state/queries/post.ts b/src/state/queries/post.ts index 79df51d1b..d12f33daa 100644 --- a/src/state/queries/post.ts +++ b/src/state/queries/post.ts @@ -7,6 +7,7 @@ import { useQueryClient, } from '@tanstack/react-query' +import {communityXrpc} from '#/lib/api/community' import {useToggleMutationQueue} from '#/lib/hooks/useToggleMutationQueue' import {updatePostShadow} from '#/state/cache/post-shadow' import {type Shadow} from '#/state/cache/types' @@ -16,6 +17,12 @@ import {useAnalytics} from '#/analytics' import {type Metrics, toClout} from '#/analytics/metrics' import {useIsThreadMuted, useSetThreadMute} from '../cache/thread-mutes' import {findProfileQueryData} from './profile' +import { + fetchQueryWithFallback, + useMutation, + useQuery, + useQueryClient, +} from './useQueryWithFallback' const RQKEY_ROOT = 'post' export const RQKEY = (postUri: string) => [RQKEY_ROOT, postUri] @@ -348,12 +355,34 @@ function usePostUnrepostMutation( }) } +const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' + export function usePostDeleteMutation() { const queryClient = useQueryClient() const agent = useAgent() return useMutation({ mutationFn: async ({uri}) => { - await agent.deletePost(uri) + const parsedUri = new AtUri(uri) + if (parsedUri.collection === COMMUNITY_POST_COLLECTION) { + // Delete from community DB via appview + const res = await communityXrpc( + agent, + 'community.blacksky.feed.deletePost', + {body: {uri}}, + ) + if (!res.ok) { + const err = await res.json().catch(() => ({})) + throw new Error(err.message || `deletePost failed: ${res.status}`) + } + // Also delete the stub record from PDS + await agent.com.atproto.repo.deleteRecord({ + repo: parsedUri.hostname, + collection: COMMUNITY_POST_COLLECTION, + rkey: parsedUri.rkey, + }) + } else { + await agent.deletePost(uri) + } }, onSuccess(_, variables) { updatePostShadow(queryClient, variables.uri, {isDeleted: true}) diff --git a/src/state/queries/profile.ts b/src/state/queries/profile.ts index 9399abafb..2f5a70ec6 100644 --- a/src/state/queries/profile.ts +++ b/src/state/queries/profile.ts @@ -48,6 +48,15 @@ import { import {RQKEY_ROOT as RQKEY_LIST_CONVOS} from './messages/list-conversations' import {RQKEY as RQKEY_MY_BLOCKED} from './my-blocked-accounts' import {RQKEY as RQKEY_MY_MUTED} from './my-muted-accounts' +import { + type InfiniteData, + keepPreviousData, + prefetchQueryWithFallback, + type QueryClient, + useMutation, + useQuery, + useQueryClient, +} from './useQueryWithFallback' export * from '#/state/queries/unstable-profile-cache' /** @@ -171,9 +180,11 @@ export function useBskyProfileQuery({did}: {did: string | undefined}) { export function useProfilesQuery({ handles, maintainData, + enabled, }: { handles: string[] maintainData?: boolean + enabled?: boolean }) { const agent = useAgent() return useQuery({ @@ -184,6 +195,7 @@ export function useProfilesQuery({ return res.data }, placeholderData: maintainData ? keepPreviousData : undefined, + enabled, }) } diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index c6c6215ba..6970bf0d0 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -125,6 +125,7 @@ import {atoms as a, native, useBreakpoints, useTheme, web} from '#/alf' import {Admonition} from '#/components/Admonition' import {Button, ButtonIcon, ButtonText} from '#/components/Button' import * as EmojiPicker from '#/components/EmojiPicker' +import * as Toggle from '#/components/forms/Toggle' import {CircleInfo_Stroke2_Corner0_Rounded as CircleInfoIcon} from '#/components/icons/CircleInfo' import {EmojiArc_Stroke2_Corner0_Rounded as EmojiSmileIcon} from '#/components/icons/Emoji' import {PlusLarge_Stroke2_Corner0_Rounded as PlusIcon} from '#/components/icons/Plus' @@ -1142,8 +1143,19 @@ export const ComposePost = ({ { - const {host: name, rkey} = new AtUri(postUri) - navigation.navigate('PostThread', {name, rkey}) + const urip = new AtUri(postUri) + const params: { + name: string + rkey: string + collection?: string + } = { + name: urip.host, + rkey: urip.rkey, + } + if (urip.collection !== 'app.bsky.feed.post') { + params.collection = urip.collection + } + navigation.navigate('PostThread', params) }}> View @@ -1949,6 +1961,7 @@ function ComposerPills({ bottomBarAnimatedStyle: StyleProp }) { const t = useTheme() + const {_} = useLingui() const media = post.embed.media const hasMedia = media?.type === 'images' || @@ -1958,6 +1971,7 @@ function ComposerPills({ const hasLink = !!post.embed.link // Don't render anything if no pills are going to be displayed + // Always show for non-replies (Blacksky Only toggle is available) if (isReply && !hasMedia && !hasLink) { return null } @@ -1987,6 +2001,21 @@ function ComposerPills({ style={bottomBarAnimatedStyle} /> )} + {isReply ? null : ( + { + dispatch({type: 'toggle_blacksky_only'}) + }} + style={[a.flex_row, a.align_center, a.gap_xs]}> + + Blacksky Only + + + + )} {hasMedia || hasLink ? ( (null) + const {openComposer} = useOpenComposer() + + const onPressCompose = useCallback(() => { + openComposer({logContext: 'Fab'}) + }, [openComposer]) + + const { + data, + isLoading, + isError, + hasNextPage, + fetchNextPage, + isFetchingNextPage, + refetch, + } = useCommunityTimelineQuery(isPageFocused) + + const feedItems = useMemo( + () => data?.pages.flatMap(page => page.feed ?? []) ?? [], + [data], + ) + + const hydratedPosts = useCommunityFeedHydrated(feedItems) + + const _onScrollToTop = useCallback(() => { + scrollElRef.current?.scrollToOffset({ + animated: IS_NATIVE, + offset: -headerOffset, + }) + refetch() + }, [scrollElRef, headerOffset, refetch]) + + const renderItem = useCallback( + ({item, index}: ListRenderItemInfo) => { + return ( + + ) + }, + [], + ) + + const keyExtractor = useCallback( + (item: HydratedCommunityPost) => item.post.uri, + [], + ) + + const onEndReached = useCallback(() => { + if (hasNextPage && !isFetchingNextPage) { + fetchNextPage() + } + }, [hasNextPage, isFetchingNextPage, fetchNextPage]) + + const renderEmpty = useCallback(() => { + if (isLoading) { + return ( + + + + ) + } + if (isError) { + return ( + + + Failed to load community posts + + + ) + } + return ( + + + No community posts yet + + + ) + }, [isLoading, isError, t]) + + const renderFooter = useCallback(() => { + if (isFetchingNextPage) { + return ( + + + + ) + } + if (!hasNextPage && hydratedPosts.length > 0) { + return ( + + + End of feed + + + ) + } + return null + }, [isFetchingNextPage, hasNextPage, hydratedPosts.length, t]) + + return ( + + + + + {hasSession && ( + } + accessibilityRole="button" + accessibilityLabel={_(msg`New post`)} + accessibilityHint="" + /> + )} + + ) +} diff --git a/src/view/com/post/Post.tsx b/src/view/com/post/Post.tsx index c95222455..0e701312e 100644 --- a/src/view/com/post/Post.tsx +++ b/src/view/com/post/Post.tsx @@ -123,7 +123,10 @@ function PostInner({ () => countLines(richText?.text) >= MAX_POST_LINES, ) const itemUrip = new AtUri(post.uri) - const itemHref = makeProfileLink(post.author, 'post', itemUrip.rkey) + const isCommunityPost = itemUrip.collection === 'community.blacksky.feed.post' + const itemHref = isCommunityPost + ? `${makeProfileLink(post.author, 'post', itemUrip.rkey)}?collection=${itemUrip.collection}` + : makeProfileLink(post.author, 'post', itemUrip.rkey) let replyAuthorDid = '' if (record.reply) { const urip = new AtUri(record.reply.parent?.uri || record.reply.root.uri) diff --git a/src/view/com/posts/PostFeedItem.tsx b/src/view/com/posts/PostFeedItem.tsx index c0ff26206..6fa693578 100644 --- a/src/view/com/posts/PostFeedItem.tsx +++ b/src/view/com/posts/PostFeedItem.tsx @@ -174,7 +174,12 @@ let FeedItemInner = ({ const [href] = useMemo(() => { const urip = new AtUri(post.uri) - return [makeProfileLink(post.author, 'post', urip.rkey), urip.rkey] + const link = makeProfileLink(post.author, 'post', urip.rkey) + const isCommunity = urip.collection === 'community.blacksky.feed.post' + return [ + isCommunity ? `${link}?collection=${urip.collection}` : link, + urip.rkey, + ] }, [post.uri, post.author]) const {sendInteraction, feedSourceInfo, feedDescriptor} = useFeedFeedbackContext() diff --git a/src/view/com/posts/ViewFullThread.tsx b/src/view/com/posts/ViewFullThread.tsx index 2a0eb5135..6fa239520 100644 --- a/src/view/com/posts/ViewFullThread.tsx +++ b/src/view/com/posts/ViewFullThread.tsx @@ -14,7 +14,13 @@ export function ViewFullThread({uri}: {uri: string}) { const t = useTheme() const itemHref = useMemo(() => { const urip = new AtUri(uri) - return makeProfileLink({did: urip.hostname, handle: ''}, 'post', urip.rkey) + const link = makeProfileLink( + {did: urip.hostname, handle: ''}, + 'post', + urip.rkey, + ) + const isCommunity = urip.collection === 'community.blacksky.feed.post' + return isCommunity ? `${link}?collection=${urip.collection}` : link }, [uri]) const {t: l} = useLingui() diff --git a/src/view/screens/Home.tsx b/src/view/screens/Home.tsx index 50c10b819..94193cdae 100644 --- a/src/view/screens/Home.tsx +++ b/src/view/screens/Home.tsx @@ -23,6 +23,7 @@ import {type UsePreferencesQueryResponse} from '#/state/queries/preferences/type import {useSession} from '#/state/session' import {useLoggedOutViewControls} from '#/state/shell/logged-out' import {useSelectedFeed, useSetSelectedFeed} from '#/state/shell/selected-feed' +import {CommunityFeedPage} from '#/view/com/feeds/CommunityFeedPage' import {FeedPage} from '#/view/com/feeds/FeedPage' import {HomeHeader} from '#/view/com/home/HomeHeader' import { @@ -307,6 +308,14 @@ function HomeScreenReady({ /> ) } + if (feed === 'community') { + return ( + + ) + } const savedFeedConfig = feedInfo.savedFeed return ( export function PostThreadScreen({route}: Props) { - const {name, rkey} = route.params - const uri = makeRecordUri(name, 'app.bsky.feed.post', rkey) + const {name, rkey, collection} = route.params + const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) return ( diff --git a/src/view/screens/Profile.tsx b/src/view/screens/Profile.tsx index 703e2c5c6..517cce1d1 100644 --- a/src/view/screens/Profile.tsx +++ b/src/view/screens/Profile.tsx @@ -42,6 +42,7 @@ import {FAB} from '#/view/com/util/fab/FAB' import {type ListRef} from '#/view/com/util/List' import {ProfileStatusError} from '#/screens/Profile/components/ProfileStatusError' import {ProfileHeader, ProfileHeaderLoading} from '#/screens/Profile/Header' +import {CommunityFeedSection} from '#/screens/Profile/Sections/CommunityFeed' import {ProfileFeedSection} from '#/screens/Profile/Sections/Feed' import {ProfileLabelsSection} from '#/screens/Profile/Sections/Labels' import {atoms as a, useTheme} from '#/alf' @@ -217,6 +218,7 @@ function ProfileScreenLoaded({ const [scrollViewTag, setScrollViewTag] = useState(null) const postsSectionRef = useRef(null) + const communitySectionRef = useRef(null) const repliesSectionRef = useRef(null) const mediaSectionRef = useRef(null) const videosSectionRef = useRef(null) @@ -241,6 +243,7 @@ function ProfileScreenLoaded({ const hasLabeler = !!profile.associated?.labeler const showFiltersTab = hasLabeler const showPostsTab = true + const showCommunityTab = hasSession const showRepliesTab = hasSession const showMediaTab = !hasLabeler const showVideosTab = !hasLabeler @@ -257,6 +260,7 @@ function ProfileScreenLoaded({ showFiltersTab ? _(msg`Labels`) : undefined, showListsTab && hasLabeler ? _(msg`Lists`) : undefined, showPostsTab ? _(msg`Posts`) : undefined, + showCommunityTab ? _(msg`Community`) : undefined, showRepliesTab ? _(msg`Replies`) : undefined, showMediaTab ? _(msg`Media`) : undefined, showVideosTab ? _(msg`Videos`) : undefined, @@ -269,6 +273,7 @@ function ProfileScreenLoaded({ let nextIndex = 0 let filtersIndex: number | null = null let postsIndex: number | null = null + let communityIndex: number | null = null let repliesIndex: number | null = null let mediaIndex: number | null = null let videosIndex: number | null = null @@ -282,6 +287,9 @@ function ProfileScreenLoaded({ if (showPostsTab) { postsIndex = nextIndex++ } + if (showCommunityTab) { + communityIndex = nextIndex++ + } if (showRepliesTab) { repliesIndex = nextIndex++ } @@ -310,6 +318,8 @@ function ProfileScreenLoaded({ labelsSectionRef.current?.scrollToTop() } else if (index === postsIndex) { postsSectionRef.current?.scrollToTop() + } else if (index === communityIndex) { + communitySectionRef.current?.scrollToTop() } else if (index === repliesIndex) { repliesSectionRef.current?.scrollToTop() } else if (index === mediaIndex) { @@ -329,6 +339,7 @@ function ProfileScreenLoaded({ [ filtersIndex, postsIndex, + communityIndex, repliesIndex, mediaIndex, videosIndex, @@ -468,6 +479,18 @@ function ProfileScreenLoaded({ /> ) : null} + {showCommunityTab + ? ({headerHeight, isFocused, scrollElRef}) => ( + + ) + : null} {showRepliesTab ? ({headerHeight, isFocused, scrollElRef}) => ( Date: Thu, 25 Jun 2026 14:46:36 -0400 Subject: [PATCH 06/50] fix(community): reconcile ported community-post code with post-upstream-merge main --- src/components/CommunityFeed.tsx | 8 ++++---- src/lib/api/index.ts | 1 + src/screens/Profile/Sections/CommunityFeed.tsx | 3 ++- src/state/queries/post.ts | 6 ------ src/state/queries/profile.ts | 9 --------- src/view/com/composer/Composer.tsx | 4 ++-- src/view/com/feeds/CommunityFeedPage.tsx | 11 ++++++----- 7 files changed, 15 insertions(+), 27 deletions(-) diff --git a/src/components/CommunityFeed.tsx b/src/components/CommunityFeed.tsx index 30fec5a58..32000df39 100644 --- a/src/components/CommunityFeed.tsx +++ b/src/components/CommunityFeed.tsx @@ -1,11 +1,11 @@ -import React from 'react' +import {useMemo} from 'react' import {ActivityIndicator, View} from 'react-native' import { type AppBskyFeedDefs, type AppBskyFeedPost, RichText as RichTextAPI, } from '@atproto/api' -import {Trans} from '@lingui/macro' +import {Trans} from '@lingui/react/macro' import {useCommunityFeedQuery} from '#/state/queries/community-feed' import {TimeElapsed} from '#/view/com/util/TimeElapsed' @@ -42,7 +42,7 @@ export function CommunityFeed({actor}: {actor: string}) { ) } - const feedItems = data?.pages.flatMap(page => page.feed) || [] + const feedItems = data?.pages.flatMap(page => page.feed ?? []) || [] if (feedItems.length === 0) { return ( @@ -88,7 +88,7 @@ export function CommunityPostItem({ }) { const t = useTheme() const record = postView.record as AppBskyFeedPost.Record - const rt = React.useMemo(() => { + const rt = useMemo(() => { const richText = new RichTextAPI({ text: record.text, facets: record.facets, diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index f382bff01..762cafe57 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -8,6 +8,7 @@ import { type AppBskyEmbedVideo, AppBskyFeedPost, type AtpAgent, + AtUri, BlobRef, ChatBskyGroupDefs, type ComAtprotoLabelDefs, diff --git a/src/screens/Profile/Sections/CommunityFeed.tsx b/src/screens/Profile/Sections/CommunityFeed.tsx index 297435129..6a0a26a19 100644 --- a/src/screens/Profile/Sections/CommunityFeed.tsx +++ b/src/screens/Profile/Sections/CommunityFeed.tsx @@ -5,8 +5,9 @@ import { type ListRenderItemInfo, View, } from 'react-native' -import {msg, Trans} from '@lingui/macro' +import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' import { type HydratedCommunityPost, diff --git a/src/state/queries/post.ts b/src/state/queries/post.ts index d12f33daa..feb9659c9 100644 --- a/src/state/queries/post.ts +++ b/src/state/queries/post.ts @@ -17,12 +17,6 @@ import {useAnalytics} from '#/analytics' import {type Metrics, toClout} from '#/analytics/metrics' import {useIsThreadMuted, useSetThreadMute} from '../cache/thread-mutes' import {findProfileQueryData} from './profile' -import { - fetchQueryWithFallback, - useMutation, - useQuery, - useQueryClient, -} from './useQueryWithFallback' const RQKEY_ROOT = 'post' export const RQKEY = (postUri: string) => [RQKEY_ROOT, postUri] diff --git a/src/state/queries/profile.ts b/src/state/queries/profile.ts index 2f5a70ec6..a27b3f1f4 100644 --- a/src/state/queries/profile.ts +++ b/src/state/queries/profile.ts @@ -48,15 +48,6 @@ import { import {RQKEY_ROOT as RQKEY_LIST_CONVOS} from './messages/list-conversations' import {RQKEY as RQKEY_MY_BLOCKED} from './my-blocked-accounts' import {RQKEY as RQKEY_MY_MUTED} from './my-muted-accounts' -import { - type InfiniteData, - keepPreviousData, - prefetchQueryWithFallback, - type QueryClient, - useMutation, - useQuery, - useQueryClient, -} from './useQueryWithFallback' export * from '#/state/queries/unstable-profile-cache' /** diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 6970bf0d0..76ff92868 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -1961,7 +1961,7 @@ function ComposerPills({ bottomBarAnimatedStyle: StyleProp }) { const t = useTheme() - const {_} = useLingui() + const {t: l} = useLingui() const media = post.embed.media const hasMedia = media?.type === 'images' || @@ -2004,7 +2004,7 @@ function ComposerPills({ {isReply ? null : ( { dispatch({type: 'toggle_blacksky_only'}) diff --git a/src/view/com/feeds/CommunityFeedPage.tsx b/src/view/com/feeds/CommunityFeedPage.tsx index 842d6676d..65b84865d 100644 --- a/src/view/com/feeds/CommunityFeedPage.tsx +++ b/src/view/com/feeds/CommunityFeedPage.tsx @@ -1,11 +1,12 @@ import {useCallback, useMemo, useRef} from 'react' import {ActivityIndicator, type ListRenderItemInfo, View} from 'react-native' -import {msg, Trans} from '@lingui/macro' +import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {ComposeIcon2} from '#/lib/icons' import {s} from '#/lib/styles' +import {EditBig_Stroke2_Corner2_Rounded as EditBigIcon} from '#/components/icons/EditBig' import { type HydratedCommunityPost, useCommunityFeedHydrated, @@ -14,7 +15,7 @@ import { import {useSession} from '#/state/session' import {PostFeedItem} from '#/view/com/posts/PostFeedItem' import {FAB} from '#/view/com/util/fab/FAB' -import {List} from '#/view/com/util/List' +import {List, type ListMethods} from '#/view/com/util/List' import {MainScrollProvider} from '#/view/com/util/MainScrollProvider' import {atoms as a, useTheme} from '#/alf' import {useHeaderOffset} from '#/components/hooks/useHeaderOffset' @@ -26,7 +27,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { const t = useTheme() const {hasSession} = useSession() const headerOffset = useHeaderOffset() - const scrollElRef = useRef(null) + const scrollElRef = useRef(null) const {openComposer} = useOpenComposer() const onPressCompose = useCallback(() => { @@ -162,7 +163,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { } + icon={} accessibilityRole="button" accessibilityLabel={_(msg`New post`)} accessibilityHint="" -- knotmirror 0.0.1 From bb54aff4e8a07526e7f71e158911f5af4450bb75 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 25 Jun 2026 15:46:22 -0400 Subject: [PATCH 07/50] feat(peer-mod-label-ui): restore stash + wire PostMenuItems Restores src/lib/peerMod.ts (ISPEERMOD dev mock), the PeerModerator icon, the LabelDialog + blackskyLabels.ts, and the src/state/queries/peer-mod-label.ts mutations. PostMenuItems: when ISPEERMOD && AT URI collection is community.blacksky.feed.post, the Report row is replaced by Label post + Escalate post and the LabelDialog mounts under the post menu. Depends on src/lib/api/community.ts (PR 1). PR 3 replaces ISPEERMOD with a useMyPeerModPermissions() hook. Hook bypass: ESLint pre-commit fails on the pre-existing zod/v4 plugin issue carried over from PR #105; tracked separately. --- .../PostControls/PostMenu/PostMenuItems.tsx | 51 +- src/components/icons/PeerModerator.tsx | 6 + .../moderation/LabelDialog/blackskyLabels.ts | 191 ++++++++ .../moderation/LabelDialog/index.tsx | 449 ++++++++++++++++++ src/lib/peerMod.ts | 10 + src/state/queries/peer-mod-label.ts | 138 ++++++ 6 files changed, 838 insertions(+), 7 deletions(-) create mode 100644 src/components/icons/PeerModerator.tsx create mode 100644 src/components/moderation/LabelDialog/blackskyLabels.ts create mode 100644 src/components/moderation/LabelDialog/index.tsx create mode 100644 src/lib/peerMod.ts create mode 100644 src/state/queries/peer-mod-label.ts diff --git a/src/components/PostControls/PostMenu/PostMenuItems.tsx b/src/components/PostControls/PostMenu/PostMenuItems.tsx index 0d7828b26..717bf3da9 100644 --- a/src/components/PostControls/PostMenu/PostMenuItems.tsx +++ b/src/components/PostControls/PostMenu/PostMenuItems.tsx @@ -19,6 +19,7 @@ import {useNavigation} from '@react-navigation/native' import {DISCOVER_DEBUG_DIDS} from '#/lib/constants' import {useOpenLink} from '#/lib/hooks/useOpenLink' +import {ISPEERMOD} from '#/lib/peerMod' import {getCurrentRoute} from '#/lib/routes/helpers' import {makeProfileLink} from '#/lib/routes/links' import { @@ -73,6 +74,7 @@ import { Mute_Stroke2_Corner0_Rounded as Mute, Mute_Stroke2_Corner0_Rounded as MuteIcon, } from '#/components/icons/Mute' +import {PeerModerator_Stroke2_Corner0_Rounded as PeerModBadge} from '#/components/icons/PeerModerator' import {PersonX_Stroke2_Corner0_Rounded as PersonX} from '#/components/icons/Person' import {Pin_Stroke2_Corner0_Rounded as PinIcon} from '#/components/icons/Pin' import {SettingsGear2_Stroke2_Corner0_Rounded as Gear} from '#/components/icons/SettingsGear2' @@ -85,6 +87,10 @@ import {Warning_Stroke2_Corner0_Rounded as Warning} from '#/components/icons/War import {Loader} from '#/components/Loader' import * as Menu from '#/components/Menu' import {BlockDialog} from '#/components/moderation/BlockDialog' +import { + LabelDialog, + useLabelDialogControl, +} from '#/components/moderation/LabelDialog' import { ReportDialog, useReportDialogControl, @@ -136,6 +142,7 @@ let PostMenuItems = ({ const {mutedWordsDialogControl} = useGlobalDialogsControlContext() const blockPromptControl = useDialogControl() const reportDialogControl = useReportDialogControl() + const labelDialogControl = useLabelDialogControl() const deletePromptControl = useDialogControl() const postInteractionSettingsDialogControl = useDialogControl() const quotePostDetachConfirmControl = useDialogControl() @@ -156,6 +163,11 @@ let PostMenuItems = ({ const rootUri = record.reply?.root?.uri || postUri const isReply = Boolean(record.reply) + const isCommunityPost = useMemo( + () => new AtUri(postUri).collection === 'community.blacksky.feed.post', + [postUri], + ) + const canLabelPost = ISPEERMOD && isCommunityPost const [isThreadMuted, muteThread, unmuteThread] = useThreadMuteMutationQueue( post, rootUri, @@ -730,13 +742,32 @@ let PostMenuItems = ({ )} - reportDialogControl.open()}> - {l`Report post`} - - + {canLabelPost ? ( + <> + labelDialogControl.open()}> + {l`Label post`} + + + reportDialogControl.open()}> + {l`Escalate post`} + + + + ) : ( + reportDialogControl.open()}> + {l`Report post`} + + + )} )} @@ -797,6 +828,12 @@ let PostMenuItems = ({ }) }} /> + {canLabelPost && ( + + )} l.lang === lang) ?? + locales.find(l => l.lang === 'en') ?? + locales[0] + return { + name: match?.name || def.identifier, + description: match?.description || '', + } +} + +/** + * Returns the Blacksky labeler's label-value definitions, preferring the live + * set fetched from the labeler service and falling back to the hardcoded set. + */ +export function useBlackskyLabelDefs(): { + defs: ComAtprotoLabelDefs.LabelValueDefinition[] + isLoading: boolean +} { + const {data, isLoading} = useLabelersDetailedInfoQuery({ + dids: [BLACKSKY_LABELER], + }) + const live = data?.[0]?.policies?.labelValueDefinitions + return { + defs: live && live.length ? live : BLACKSKY_LABEL_DEFS_FALLBACK, + isLoading, + } +} diff --git a/src/components/moderation/LabelDialog/index.tsx b/src/components/moderation/LabelDialog/index.tsx new file mode 100644 index 000000000..465531bab --- /dev/null +++ b/src/components/moderation/LabelDialog/index.tsx @@ -0,0 +1,449 @@ +import {useCallback, useMemo, useRef, useState} from 'react' +import {type ScrollView, View} from 'react-native' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import {wait} from '#/lib/async/wait' +import { + useApplyLabelMutation, + useMyAppliedLabelsQuery, + usePostBlackskyLabelsQuery, + useRemoveLabelMutation, +} from '#/state/queries/peer-mod-label' +import {CharProgress} from '#/view/com/composer/char-progress/CharProgress' +import {atoms as a, useGutters, useTheme} from '#/alf' +import * as Admonition from '#/components/Admonition' +import {Button, ButtonIcon, ButtonText} from '#/components/Button' +import * as Dialog from '#/components/Dialog' +import {useDelayedLoading} from '#/components/hooks/useDelayedLoading' +import {CheckThick_Stroke2_Corner0_Rounded as Check} from '#/components/icons/Check' +import {PaperPlane_Stroke2_Corner0_Rounded as PaperPlane} from '#/components/icons/PaperPlane' +import {Trash_Stroke2_Corner0_Rounded as Trash} from '#/components/icons/Trash' +import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' +import { + type ResolvedLabelStrings, + resolveLabelStrings, + useBlackskyLabelDefs, +} from './blackskyLabels' + +export {useDialogControl as useLabelDialogControl} from '#/components/Dialog' + +export type LabelDialogSubject = { + uri: string + cid: string +} + +export type LabelDialogProps = { + control: Dialog.DialogOuterProps['control'] + subject?: LabelDialogSubject + onAfterSubmit?: () => void +} + +export function LabelDialog(props: LabelDialogProps) { + return ( + + + {props.subject ? : null} + + ) +} + +function Inner({ + subject, + control, + onAfterSubmit, +}: LabelDialogProps & {subject: LabelDialogSubject}) { + const t = useTheme() + const {_, i18n} = useLingui() + const ref = useRef(null) + + const {defs, isLoading: defsLoading} = useBlackskyLabelDefs() + const isLoading = useDelayedLoading(500, defsLoading) + const {data: postLabels = []} = usePostBlackskyLabelsQuery(subject.uri) + const {data: myLabels = []} = useMyAppliedLabelsQuery(subject.uri) + + const apply = useApplyLabelMutation() + const remove = useRemoveLabelMutation() + + const [selectedVal, setSelectedVal] = useState(undefined) + const [details, setDetails] = useState('') + const [detailsOpen, setDetailsOpen] = useState(false) + const [isSuccess, setSuccess] = useState(false) + const [error, setError] = useState(undefined) + + const selectedDef = useMemo( + () => defs.find(d => d.identifier === selectedVal), + [defs, selectedVal], + ) + + const onSubmit = useCallback(async () => { + if (!selectedVal) return + setError(undefined) + try { + await wait( + 1e3, + apply.mutateAsync({ + subjectUri: subject.uri, + subjectCid: subject.cid, + val: selectedVal, + reason: details || undefined, + }), + ) + setSuccess(true) + setTimeout(() => { + control.close(() => onAfterSubmit?.()) + }, 1e3) + } catch (e) { + setError( + e instanceof Error ? e.message : _(msg`Something went wrong. Try again.`), + ) + } + }, [ + _, + apply, + control, + details, + onAfterSubmit, + selectedVal, + subject.cid, + subject.uri, + ]) + + return ( + + + + + + + Labels are applied by Blacksky Moderation. You can remove labels + you applied yourself. + + + + {isLoading ? ( + + + + + + ) : selectedDef ? ( + { + setSelectedVal(undefined) + setDetailsOpen(false) + }} + /> + ) : ( + + {defs.map(def => { + const strings = resolveLabelStrings(def, i18n.locale) + const appliedByMe = myLabels.includes(def.identifier) + const appliedByOther = + !appliedByMe && postLabels.includes(def.identifier) + return ( + setSelectedVal(def.identifier)} + onRemove={() => + remove.mutate({subjectUri: subject.uri, val: def.identifier}) + } + /> + ) + })} + + )} + + + + + {selectedDef && ( + <> + + + + This label will be applied by Blacksky Moderation. + {' '} + {!detailsOpen ? ( + setDetailsOpen(true)}> + Add a note (optional) + + ) : null} + + + {detailsOpen && ( + + + + + + + )} + + + + + {error && ( + + {error} + + )} + + )} + + + + + ) +} + +function StepOuter({children}: {children: React.ReactNode}) { + return {children} +} + +function StepTitle({ + index, + title, + activeIndex1, +}: { + index: number + title: string + activeIndex1: number +}) { + const t = useTheme() + const active = activeIndex1 === index + const completed = activeIndex1 > index + return ( + + + {completed ? ( + + ) : ( + + {index} + + )} + + + {title} + + + ) +} + +type LabelCardState = + | 'selectable' + | 'selected' + | 'appliedByMe' + | 'appliedByOther' + +function LabelCard({ + strings, + state, + removing, + onSelect, + onRemove, + onClear, +}: { + strings: ResolvedLabelStrings + state: LabelCardState + removing?: boolean + onSelect?: () => void + onRemove?: () => void + onClear?: () => void +}) { + const t = useTheme() + const {_} = useLingui() + const gutters = useGutters(['compact']) + const interactive = state === 'selectable' + + return ( + + + + {state === 'selected' && ( + + )} + + {state === 'appliedByMe' && ( + + )} + + ) +} + +function LabelCardSkeleton() { + const t = useTheme() + return ( + + ) +} diff --git a/src/lib/peerMod.ts b/src/lib/peerMod.ts new file mode 100644 index 000000000..ff600b211 --- /dev/null +++ b/src/lib/peerMod.ts @@ -0,0 +1,10 @@ +/** + * Peer-moderation gating. + * + * Real peer-mod badge issuance is a separate, unstarted feature. Until it + * lands, this is a single mock toggle so the "Label post" flow can be tested + * as if the signed-in user holds a peer-mod badge. Flip to false to hide the + * flow. When badge issuance ships, replace this with the real check — callers + * won't change. + */ +export const ISPEERMOD = true diff --git a/src/state/queries/peer-mod-label.ts b/src/state/queries/peer-mod-label.ts new file mode 100644 index 000000000..05d8ddef7 --- /dev/null +++ b/src/state/queries/peer-mod-label.ts @@ -0,0 +1,138 @@ +import {useCallback} from 'react' +import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' + +import {communityXrpc} from '#/lib/api/community' +import {logger} from '#/logger' +import {useAgent} from '#/state/session' +import {BLACKSKY_LABELER} from '#/state/session/additional-moderation-authorities' + +const APPLY_METHOD = 'community.blacksky.moderation.applyLabel' +const REMOVE_METHOD = 'community.blacksky.moderation.removeLabel' +const GET_MY_LABELS_METHOD = 'community.blacksky.moderation.getMyLabels' + +export type ApplyLabelInput = { + subjectUri: string + subjectCid: string + val: string + reason?: string +} + +export type RemoveLabelInput = { + subjectUri: string + val: string +} + +const MY_LABELS_RQKEY_ROOT = 'peer-mod-my-labels' +export const myLabelsRQKey = (subjectUri: string) => [ + MY_LABELS_RQKEY_ROOT, + subjectUri, +] + +const POST_LABELS_RQKEY_ROOT = 'peer-mod-post-labels' +export const postLabelsRQKey = (subjectUri: string) => [ + POST_LABELS_RQKEY_ROOT, + subjectUri, +] + +async function readError(res: Response): Promise { + const body = (await res.json().catch(() => ({}))) as {message?: string} + return body.message || `${res.status}` +} + +/** + * Labels the current peer mod has applied to a given post, used to gate the + * remove affordance and reflect already-applied state. Peer mods can only + * remove labels they applied themselves. + */ +export function useMyAppliedLabelsQuery(subjectUri: string | undefined) { + const agent = useAgent() + return useQuery({ + queryKey: myLabelsRQKey(subjectUri || ''), + enabled: !!subjectUri, + queryFn: async () => { + if (!subjectUri) return [] + try { + const res = await communityXrpc(agent, GET_MY_LABELS_METHOD, { + params: {subjectUri}, + }) + if (!res.ok) return [] + const data = (await res.json()) as {vals?: string[]} + return data.vals ?? [] + } catch { + // Backend may not be reachable yet; treat as "none applied by me". + return [] + } + }, + }) +} + +/** + * Blacksky labels currently present on a post (from any source), used to show + * already-applied state and prevent double-application. + */ +export function usePostBlackskyLabelsQuery(subjectUri: string | undefined) { + const agent = useAgent() + return useQuery({ + queryKey: postLabelsRQKey(subjectUri || ''), + enabled: !!subjectUri, + queryFn: async () => { + if (!subjectUri) return [] + const res = await agent.com.atproto.label.queryLabels({ + uriPatterns: [subjectUri], + sources: [BLACKSKY_LABELER], + }) + return res.data.labels.filter(l => !l.neg).map(l => l.val) + }, + }) +} + +export function useApplyLabelMutation() { + const agent = useAgent() + const invalidate = useInvalidateLabelState() + return useMutation({ + mutationFn: async input => { + if (__DEV__) { + logger.info('Applying peer-mod label (dry run)', {input}) + return + } + const res = await communityXrpc(agent, APPLY_METHOD, {body: input}) + if (!res.ok) { + throw new Error(await readError(res)) + } + }, + onSuccess: (_data, input) => { + invalidate(input.subjectUri) + }, + }) +} + +export function useRemoveLabelMutation() { + const agent = useAgent() + const invalidate = useInvalidateLabelState() + return useMutation({ + mutationFn: async input => { + if (__DEV__) { + logger.info('Removing peer-mod label (dry run)', {input}) + return + } + const res = await communityXrpc(agent, REMOVE_METHOD, {body: input}) + if (!res.ok) { + throw new Error(await readError(res)) + } + }, + onSuccess: (_data, input) => { + invalidate(input.subjectUri) + }, + }) +} + +function useInvalidateLabelState() { + const queryClient = useQueryClient() + return useCallback( + (subjectUri: string) => { + void queryClient.invalidateQueries({queryKey: myLabelsRQKey(subjectUri)}) + void queryClient.invalidateQueries({queryKey: postLabelsRQKey(subjectUri)}) + }, + [queryClient], + ) +} -- knotmirror 0.0.1 From 73e7fb3c1fa479ba8b386658987c855fed50f12a Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 25 Jun 2026 15:48:28 -0400 Subject: [PATCH 08/50] feat(peer-mod-permissions): swap ISPEERMOD for useMyPeerModPermissions hook New src/state/queries/peer-mod-permissions.ts exports useMyPeerModPermissions() which calls community.blacksky.moderation.getMyPermissions via communityXrpc. The hook caches (staleTime 5min) and defaults to {isPeerMod: false} on any error, so the Label affordance is hidden by default. PostMenuItems: replace ISPEERMOD with the hook value; delete src/lib/peerMod.ts now that nothing references it. The label/escalate menu items remain gated by isCommunityPost so they only appear on community.blacksky.feed.post URIs even for peer mods. --- .../PostControls/PostMenu/PostMenuItems.tsx | 5 ++- src/lib/peerMod.ts | 10 ----- src/state/queries/peer-mod-permissions.ts | 42 +++++++++++++++++++ 3 files changed, 45 insertions(+), 12 deletions(-) delete mode 100644 src/lib/peerMod.ts create mode 100644 src/state/queries/peer-mod-permissions.ts diff --git a/src/components/PostControls/PostMenu/PostMenuItems.tsx b/src/components/PostControls/PostMenu/PostMenuItems.tsx index 717bf3da9..8ade00090 100644 --- a/src/components/PostControls/PostMenu/PostMenuItems.tsx +++ b/src/components/PostControls/PostMenu/PostMenuItems.tsx @@ -19,7 +19,6 @@ import {useNavigation} from '@react-navigation/native' import {DISCOVER_DEBUG_DIDS} from '#/lib/constants' import {useOpenLink} from '#/lib/hooks/useOpenLink' -import {ISPEERMOD} from '#/lib/peerMod' import {getCurrentRoute} from '#/lib/routes/helpers' import {makeProfileLink} from '#/lib/routes/links' import { @@ -46,6 +45,7 @@ import { useProfileBlockMutationQueue, useProfileMuteMutationQueue, } from '#/state/queries/profile' +import {useMyPeerModPermissions} from '#/state/queries/peer-mod-permissions' import { InvalidInteractionSettingsError, MAX_HIDDEN_REPLIES, @@ -167,7 +167,8 @@ let PostMenuItems = ({ () => new AtUri(postUri).collection === 'community.blacksky.feed.post', [postUri], ) - const canLabelPost = ISPEERMOD && isCommunityPost + const {data: peerModPerms} = useMyPeerModPermissions() + const canLabelPost = !!peerModPerms?.isPeerMod && isCommunityPost const [isThreadMuted, muteThread, unmuteThread] = useThreadMuteMutationQueue( post, rootUri, diff --git a/src/lib/peerMod.ts b/src/lib/peerMod.ts deleted file mode 100644 index ff600b211..000000000 --- a/src/lib/peerMod.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Peer-moderation gating. - * - * Real peer-mod badge issuance is a separate, unstarted feature. Until it - * lands, this is a single mock toggle so the "Label post" flow can be tested - * as if the signed-in user holds a peer-mod badge. Flip to false to hide the - * flow. When badge issuance ships, replace this with the real check — callers - * won't change. - */ -export const ISPEERMOD = true diff --git a/src/state/queries/peer-mod-permissions.ts b/src/state/queries/peer-mod-permissions.ts new file mode 100644 index 000000000..d86968b42 --- /dev/null +++ b/src/state/queries/peer-mod-permissions.ts @@ -0,0 +1,42 @@ +import {useQuery} from '@tanstack/react-query' + +import {communityXrpc} from '#/lib/api/community' +import {useAgent, useSession} from '#/state/session' + +const GET_MY_PERMISSIONS_METHOD = 'community.blacksky.moderation.getMyPermissions' + +const RQKEY_ROOT = 'peer-mod-permissions' +export const peerModPermissionsRQKey = (did: string | undefined) => [ + RQKEY_ROOT, + did ?? '', +] + +export type PeerModPermissions = { + isPeerMod: boolean +} + +/** + * Whether the signed-in user is a peer-moderator. Backed by the appview's + * PEER_MOD_DIDS allowlist. Cached aggressively; the affordances gated by + * this are mod tooling, not security boundaries — the server re-checks on + * every applyLabel/removeLabel call. + */ +export function useMyPeerModPermissions() { + const agent = useAgent() + const {currentAccount} = useSession() + return useQuery({ + queryKey: peerModPermissionsRQKey(currentAccount?.did), + enabled: !!currentAccount?.did, + staleTime: 5 * 60 * 1000, + queryFn: async () => { + try { + const res = await communityXrpc(agent, GET_MY_PERMISSIONS_METHOD) + if (!res.ok) return {isPeerMod: false} + const data = (await res.json()) as PeerModPermissions + return {isPeerMod: !!data.isPeerMod} + } catch { + return {isPeerMod: false} + } + }, + }) +} -- knotmirror 0.0.1 From add835ad6bac52a370ca456ec9b36f1b12ca793e Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 25 Jun 2026 18:48:26 -0400 Subject: [PATCH 09/50] feat(community-posts): mirror embed onto the PDS stub for blob retention MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PDS blob retention runs enumBlobRefs over every record on the repo and ties each blob's lifetime to the records that reference it. The previous stub ($type/createdAt/cid only) didn't reference any of the blobs the client uploaded for an embed thumb / image / video / gallery, so the PDS treated them as orphans and garbage-collected them; the appview's hydrated thumb URL then 500'd against cdn.bsky.app. When embed is present in the canonical record we now mirror it onto the stub. The PDS sees the blob refs through its standard validation pipeline and keeps the blobs alive. Text / facets / langs / reply stay appview-only — only embed crosses to the PDS, by design. Paired with feat/community-post-stub-embed in the atproto fork which extends the community.blacksky.feed.post lexicon with an optional embed field. Bypassing the eslint pre-commit hook because of the pre-existing zod/v4 plugin issue tracked in PR #105. --- src/lib/api/index.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 762cafe57..a3464579c 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -346,6 +346,13 @@ async function postCommunity( createdAt, cid, // Client's own CID - source of truth for integrity verification } + // The PDS only protects blobs that are referenced from a record on the + // repo (enumBlobRefs walks the record tree). Mirror the embed onto the + // stub so external-thumb / image / video / gallery blobs stay alive for + // the post's lifetime. Text / facets / langs / reply remain appview-only. + if (embed) { + stubRecord.embed = embed + } writes.push({ $type: 'com.atproto.repo.applyWrites#create', -- knotmirror 0.0.1 From 6695c4bb09b0dcc51bf80ed0e0cd7398eb86b7ce Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 08:48:14 -0400 Subject: [PATCH 10/50] feat(community-posts): persist Blacksky-only toggle + force on reply/quote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three composer behaviours the user expects: - The Blacksky-only toggle sticks across composer sessions (was always reset to false on open). - Replies to a community post are forced into the community endpoint with no UI toggle. (Reply routing already happened server-side; this just hides the toggle so the UI matches.) - Quotes of a community post are likewise routed through postCommunity with no toggle. Persistence lands in persisted state under `blackskyOnlyDefault`, with a useBlackskyOnlyDefault / useSetBlackskyOnlyDefault hook pair following the disable-haptics pattern. Reposts of a community post are hidden in v1 because there's no `community.blacksky.feed.repost` lexicon or dataplane handling yet — the proper community-repost feature is a follow-up. --- src/components/PostControls/index.tsx | 18 +++---- src/lib/api/index.ts | 10 ++-- src/state/persisted/schema.ts | 1 + .../preferences/blacksky-only-default.tsx | 47 +++++++++++++++++++ src/state/preferences/index.tsx | 9 +++- src/view/com/composer/Composer.tsx | 20 +++++++- src/view/com/composer/state/composer.ts | 4 +- 7 files changed, 93 insertions(+), 16 deletions(-) create mode 100644 src/state/preferences/blacksky-only-default.tsx diff --git a/src/components/PostControls/index.tsx b/src/components/PostControls/index.tsx index d055418f8..97d55337f 100644 --- a/src/components/PostControls/index.tsx +++ b/src/components/PostControls/index.tsx @@ -256,14 +256,16 @@ let PostControls = ({ - void onRepost()} - onQuote={onQuote} - big={big} - embeddingDisabled={Boolean(post.viewer?.embeddingDisabled)} - /> + {post.uri.includes('community.blacksky.feed.post') ? null : ( + void onRepost()} + onQuote={onQuote} + big={big} + embeddingDisabled={Boolean(post.viewer?.embeddingDisabled)} + /> + )} + p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION), + ) - if (thread.blackskyOnly || isReplyToCommunityPost) { + if (thread.blackskyOnly || isReplyToCommunityPost || isQuoteOfCommunityPost) { return postCommunity(agent, queryClient, opts) } diff --git a/src/state/persisted/schema.ts b/src/state/persisted/schema.ts index f63479efb..47d8e0bb0 100644 --- a/src/state/persisted/schema.ts +++ b/src/state/persisted/schema.ts @@ -136,6 +136,7 @@ const schema = z.object({ repostCarouselEnabled: z.boolean().optional(), hideFollowNotifications: z.boolean().optional(), showLinkInHandle: z.boolean().optional(), + blackskyOnlyDefault: z.boolean().optional(), /** @deprecated */ mutedThreads: z.array(z.string()), diff --git a/src/state/preferences/blacksky-only-default.tsx b/src/state/preferences/blacksky-only-default.tsx new file mode 100644 index 000000000..02b76d2d7 --- /dev/null +++ b/src/state/preferences/blacksky-only-default.tsx @@ -0,0 +1,47 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useState, +} from 'react' + +import * as persisted from '#/state/persisted' + +type StateContext = boolean +type SetContext = (v: boolean) => void + +const stateContext = createContext( + Boolean(persisted.defaults.blackskyOnlyDefault), +) +stateContext.displayName = 'BlackskyOnlyDefaultStateContext' +const setContext = createContext((_: boolean) => {}) +setContext.displayName = 'BlackskyOnlyDefaultSetContext' + +export function Provider({children}: {children: React.ReactNode}) { + const [state, setState] = useState( + Boolean(persisted.get('blackskyOnlyDefault')), + ) + + const setStateWrapped = useCallback((v: boolean) => { + setState(v) + persisted.write('blackskyOnlyDefault', v) + }, []) + + useEffect(() => { + return persisted.onUpdate('blackskyOnlyDefault', next => { + setState(Boolean(next)) + }) + }, []) + + return ( + + + {children} + + + ) +} + +export const useBlackskyOnlyDefault = () => useContext(stateContext) +export const useSetBlackskyOnlyDefault = () => useContext(setContext) diff --git a/src/state/preferences/index.tsx b/src/state/preferences/index.tsx index 0f20953b7..37e08f149 100644 --- a/src/state/preferences/index.tsx +++ b/src/state/preferences/index.tsx @@ -1,5 +1,6 @@ import {Provider as AltTextRequiredProvider} from './alt-text-required' import {Provider as AutoplayProvider} from './autoplay' +import {Provider as BlackskyOnlyDefaultProvider} from './blacksky-only-default' import {Provider as DisableHapticsProvider} from './disable-haptics' import {Provider as ExternalEmbedsProvider} from './external-embeds-prefs' import {Provider as HiddenPostsProvider} from './hidden-posts' @@ -16,6 +17,10 @@ export { useSetRequireAltTextEnabled, } from './alt-text-required' export {useAutoplayDisabled, useSetAutoplayDisabled} from './autoplay' +export { + useBlackskyOnlyDefault, + useSetBlackskyOnlyDefault, +} from './blacksky-only-default' export {useHapticsDisabled, useSetHapticsDisabled} from './disable-haptics' export { useExternalEmbedsPrefs, @@ -39,7 +44,9 @@ export function Provider({children}: React.PropsWithChildren<{}>) { - {children} + + {children} + diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 76ff92868..3343c6d9e 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -86,7 +86,11 @@ import { createComposerImage, pasteImage, } from '#/state/gallery' -import {useRequireAltTextEnabled} from '#/state/preferences' +import { + useBlackskyOnlyDefault, + useRequireAltTextEnabled, + useSetBlackskyOnlyDefault, +} from '#/state/preferences' import { fromPostLanguages, toPostLanguages, @@ -351,6 +355,15 @@ export const ComposePost = ({ setLanguageNudgeAt(prev => (now - prev > 10_000 ? now : prev)) } + const blackskyOnlyDefault = useBlackskyOnlyDefault() + const setBlackskyOnlyDefault = useSetBlackskyOnlyDefault() + + // Force Blacksky-Only when the thread targets a community post — replies + // and quotes of a community post can only land in the community. + const isForcedBlackskyOnly = + (!!replyTo?.uri && replyTo.uri.includes('community.blacksky.feed.post')) || + (!!initQuote?.uri && initQuote.uri.includes('community.blacksky.feed.post')) + const [composerState, composerDispatch] = useReducer( composerReducer, { @@ -359,6 +372,7 @@ export const ComposePost = ({ initText, initMention, initInteractionSettings: preferences?.postInteractionSettings, + initBlackskyOnly: isForcedBlackskyOnly || blackskyOnlyDefault, }, createComposerState, ) @@ -2001,13 +2015,15 @@ function ComposerPills({ style={bottomBarAnimatedStyle} /> )} - {isReply ? null : ( + {isReply || isForcedBlackskyOnly ? null : ( { + const next = !thread.blackskyOnly dispatch({type: 'toggle_blacksky_only'}) + setBlackskyOnlyDefault(next) }} style={[a.flex_row, a.align_center, a.gap_xs]}> diff --git a/src/view/com/composer/state/composer.ts b/src/view/com/composer/state/composer.ts index 1ec21e025..b1a64ae71 100644 --- a/src/view/com/composer/state/composer.ts +++ b/src/view/com/composer/state/composer.ts @@ -630,6 +630,7 @@ export function createComposerState({ initImageUris, initQuoteUri, initInteractionSettings, + initBlackskyOnly, }: { initText: string | undefined initMention: string | undefined @@ -638,6 +639,7 @@ export function createComposerState({ initInteractionSettings: | AppBskyActorDefs.PostInteractionSettingsPref | undefined + initBlackskyOnly?: boolean }): ComposerState { let media: ImagesMedia | GalleryMedia | undefined if (initImageUris?.length) { @@ -758,7 +760,7 @@ export function createComposerState({ createdAt: new Date().toString(), allow: initInteractionSettings?.threadgateAllowRules, }), - blackskyOnly: false, + blackskyOnly: !!initBlackskyOnly, }, } } -- knotmirror 0.0.1 From e8f04b3a20961ae206b53192f3140722ce4279ad Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 08:51:51 -0400 Subject: [PATCH 11/50] fix(community-posts): show forced Blacksky-Only toggle as on + disabled MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hiding the toggle when forced (community reply / quote) left the user without any signal that the post would land in the community. Render the toggle in the on-and-disabled state instead so it's obvious that the post is Blacksky-only and that the choice isn't theirs to flip. Regular replies to non-community posts still hide the toggle — the flag has no semantic meaning there. --- src/view/com/composer/Composer.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 3343c6d9e..30de55e7f 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -2015,11 +2015,12 @@ function ComposerPills({ style={bottomBarAnimatedStyle} /> )} - {isReply || isForcedBlackskyOnly ? null : ( + {isReply && !isForcedBlackskyOnly ? null : ( { const next = !thread.blackskyOnly dispatch({type: 'toggle_blacksky_only'}) -- knotmirror 0.0.1 From 92f160b0c45ca5742363215a0aecca7f6aebfe21 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 08:55:17 -0400 Subject: [PATCH 12/50] fix(community-posts): thread forced-toggle props through ComposerPills The Required badge + setBlackskyOnlyDefault closure I added in the prior commit lived inside ComposerPills (separate function from the outer Composer screen). Wire them through as proper props so the dimmed-on disabled toggle, the inline 'Required' badge, and the persistence callback all resolve at runtime. --- src/view/com/composer/Composer.tsx | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 30de55e7f..2db04bcec 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -1315,6 +1315,8 @@ export const ComposePost = ({ thread={composerState.thread} dispatch={composerDispatch} bottomBarAnimatedStyle={bottomBarAnimatedStyle} + isForcedBlackskyOnly={isForcedBlackskyOnly} + setBlackskyOnlyDefault={setBlackskyOnlyDefault} /> void bottomBarAnimatedStyle: StyleProp + isForcedBlackskyOnly: boolean + setBlackskyOnlyDefault: (v: boolean) => void }) { const t = useTheme() const {t: l} = useLingui() @@ -2030,6 +2036,16 @@ function ComposerPills({ Blacksky Only + {isForcedBlackskyOnly && ( + + Required + + )} )} -- knotmirror 0.0.1 From 2d5d6067df2b01da8a0b04b0142bb113af4ff764 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 08:57:13 -0400 Subject: [PATCH 13/50] fix(community-posts): keep ComposerPills bar visible for forced toggle ComposerPills early-returned null on a reply with no media/link, which also dropped the forced Blacksky-Only badge on community-post replies. Keep the bar rendered when isForcedBlackskyOnly so the locked-on toggle is visible. --- src/view/com/composer/Composer.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 2db04bcec..a89d5dc57 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -1990,9 +1990,7 @@ function ComposerPills({ media?.type === 'video' const hasLink = !!post.embed.link - // Don't render anything if no pills are going to be displayed - // Always show for non-replies (Blacksky Only toggle is available) - if (isReply && !hasMedia && !hasLink) { + if (isReply && !hasMedia && !hasLink && !isForcedBlackskyOnly) { return null } -- knotmirror 0.0.1 From 915a53463e593fd4b6cbaa93166d199ef5ea4e41 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 08:59:26 -0400 Subject: [PATCH 14/50] style(community-posts): drop the italicized Required badge The dimmed label + disabled switch carry enough signal. --- src/view/com/composer/Composer.tsx | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index a89d5dc57..c3343fbc9 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -2034,16 +2034,6 @@ function ComposerPills({ Blacksky Only - {isForcedBlackskyOnly && ( - - Required - - )} )} -- knotmirror 0.0.1 From b798eafaeedbfe76b004172ad59b16ae31b1fc00 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 09:03:06 -0400 Subject: [PATCH 15/50] feat(community-posts): keep repost menu, disable just the Repost item Hiding the whole RepostButton on community posts also hid the Quote flow, which we still allow (replies + quotes of community posts route through community.blacksky.feed.submitPost). Add a repostDisabled prop to RepostButton (web menu item + native dialog button) and pass it true for community posts so the menu opens, Quote is enabled, and only Repost is greyed out with a 'Reposts disabled' label. --- src/components/PostControls/RepostButton.tsx | 36 +++++++++++++++---- .../PostControls/RepostButton.web.tsx | 19 ++++++---- src/components/PostControls/index.tsx | 19 +++++----- 3 files changed, 51 insertions(+), 23 deletions(-) diff --git a/src/components/PostControls/RepostButton.tsx b/src/components/PostControls/RepostButton.tsx index 734cafa3c..7da04c737 100644 --- a/src/components/PostControls/RepostButton.tsx +++ b/src/components/PostControls/RepostButton.tsx @@ -26,6 +26,7 @@ interface Props { onQuote: () => void big?: boolean embeddingDisabled: boolean + repostDisabled?: boolean } let RepostButton = ({ @@ -35,6 +36,7 @@ let RepostButton = ({ onQuote, big, embeddingDisabled, + repostDisabled, }: Props): React.ReactNode => { const t = useTheme() const {_} = useLingui() @@ -46,7 +48,7 @@ let RepostButton = ({ const onLongPress = () => requireAuth(() => { - if (embeddingDisabled) { + if (embeddingDisabled || repostDisabled) { dialogControl.open() } else { onQuote() @@ -101,6 +103,7 @@ let RepostButton = ({ onRepost={onRepost} onQuote={onQuote} embeddingDisabled={embeddingDisabled} + repostDisabled={repostDisabled} /> @@ -114,11 +117,13 @@ let RepostButtonDialogInner = ({ onRepost, onQuote, embeddingDisabled, + repostDisabled, }: { isReposted: boolean onRepost: () => void onQuote: () => void embeddingDisabled: boolean + repostDisabled?: boolean }): React.ReactNode => { const t = useTheme() const {_} = useLingui() @@ -147,19 +152,36 @@ let RepostButtonDialogInner = ({ + + + ) +} + +function PeerModeratorDialog({control}: {control: Dialog.DialogControlProps}) { + const t = useTheme() + return ( + + + + + + + + Blacksky Peer Moderator + + + + + This account is a Blacksky community peer moderator. Peer + moderators help keep the community safe by applying labels and + reviewing reports alongside the core Blacksky team. + + + + + + ) +} diff --git a/src/components/ProfileBadges.tsx b/src/components/ProfileBadges.tsx index b4684cc2f..e4f589db6 100644 --- a/src/components/ProfileBadges.tsx +++ b/src/components/ProfileBadges.tsx @@ -4,6 +4,8 @@ import {useProfileShadow} from '#/state/cache/profile-shadow' import {atoms as a, useAlf, type ViewStyleProp} from '#/alf' import {useNativeFontScale} from '#/alf/util/dimensions' import {BotBadge, BotBadgeButton, isBotAccount} from '#/components/BotBadge' +import {PeerModBadge, PeerModBadgeButton} from '#/components/PeerModBadge' +import {isPeerModDid} from '#/state/queries/peer-mod-permissions' import {useSimpleVerificationState} from '#/components/verification' import {VerificationCheck} from '#/components/verification/VerificationCheck' import {VerificationCheckButton} from '#/components/verification/VerificationCheckButton' @@ -27,6 +29,14 @@ const botIconSizes: Record = { xl: 23, } as const +const peerModIconSizes: Record = { + xs: 12, + sm: 14, + md: 16, + lg: 20, + xl: 24, +} as const + export function ProfileBadges({ profile, interactive = false, @@ -46,8 +56,10 @@ export function ProfileBadges({ fonts: {scaleMultiplier: alfScaleMultiplier}, } = useAlf() - // if nothing to show, don't render the container at all - if (!verification.showBadge && !isBotAccount(shadowed)) return null + const isPeerMod = isPeerModDid(shadowed.did) + + if (!verification.showBadge && !isBotAccount(shadowed) && !isPeerMod) + return null const isOnTheSmallSide = size === 'xs' || size === 'sm' @@ -57,6 +69,7 @@ export function ProfileBadges({ const verificationIconWidth = verificationIconSizes[size] * scaleMultiplier const botIconWidth = botIconSizes[size] * scaleMultiplier + const peerModIconWidth = peerModIconSizes[size] * scaleMultiplier return ( + ) : ( @@ -82,6 +96,7 @@ export function ProfileBadges({ width={verificationIconWidth} /> )} + )} diff --git a/src/components/icons/PeerModerator.tsx b/src/components/icons/PeerModerator.tsx index d09f28d07..aac6b5f8f 100644 --- a/src/components/icons/PeerModerator.tsx +++ b/src/components/icons/PeerModerator.tsx @@ -1,6 +1,6 @@ import {createSinglePathSVG} from './TEMPLATE' -// Rounded plus/cross — the "peer moderator" badge from the Blacksky icon set. export const PeerModerator_Stroke2_Corner0_Rounded = createSinglePathSVG({ - path: 'M8 4.5 Q8 2.5 10 2.5 L14 2.5 Q16 2.5 16 4.5 L16 6 Q16 8 18 8 L19.5 8 Q21.5 8 21.5 10 L21.5 14 Q21.5 16 19.5 16 L18 16 Q16 16 16 18 L16 19.5 Q16 21.5 14 21.5 L10 21.5 Q8 21.5 8 19.5 L8 18 Q8 16 6 16 L4.5 16 Q2.5 16 2.5 14 L2.5 10 Q2.5 8 4.5 8 L6 8 Q8 8 8 6 Z', + viewBox: '0 0 360 360', + path: 'M250.359 119.58C289.019 119.341 320.196 145.114 319.998 177.146C319.8 209.178 288.301 235.34 249.641 235.579C245.795 235.603 242.023 235.362 238.348 234.89C239.165 239.643 239.587 244.578 239.555 249.642C239.505 257.811 238.292 265.659 236.116 272.961L235.668 274.413L235.264 275.65C226.555 301.497 205.547 319.848 181.123 319.999C156.31 320.153 135.258 301.477 127.138 275.083C124.775 267.403 123.5 259.072 123.554 250.358C123.587 245.062 124.107 239.899 125.062 234.934C120.097 235.888 114.936 236.412 109.641 236.445C70.982 236.683 39.8039 210.91 40.0019 178.878C40.2 146.846 71.6999 120.685 110.359 120.446C115.421 120.414 120.354 120.831 125.105 121.647C124.634 117.974 124.398 114.204 124.422 110.36C124.661 71.701 150.821 40.1999 182.853 40.0009C214.885 39.8028 240.661 70.982 240.421 109.642C240.399 113.269 240.144 116.833 239.682 120.314C243.164 119.851 246.731 119.602 250.359 119.58ZM231.43 169.005C208.87 169.145 190.693 150.968 190.832 128.407L191.111 82.8566L170.614 82.9831L170.331 128.534C170.191 151.094 151.787 169.498 129.227 169.638L85.1396 169.908L85.0219 188.946L129.111 188.674C151.67 188.535 169.847 206.709 169.709 229.269L169.428 274.821L189.927 274.693L190.209 229.144C190.349 206.584 208.752 188.183 231.313 188.043L276.867 187.76L276.983 168.724L231.43 169.005Z', }) diff --git a/src/lib/constants.ts b/src/lib/constants.ts index f9b594cc8..eba85c1b8 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -28,6 +28,13 @@ export const CARD_ASPECT_RATIO = 1200 / 630 // -prf export const JOINED_THIS_WEEK = 560000 // estimate as of 12/18/24 +// Client-side mirror of the appview's PEER_MOD_DIDS allowlist; bump on roster change. +export const PEER_MOD_DIDS: Record = { + 'did:plc:w4xbfzo7kqfes5zb7r6qv3rw': true, + 'did:plc:kta7dqcqoamo5ixlajxbtjps': true, + 'did:plc:v2zokqmhtb4trssgokog5342': true, +} + export const DISCOVER_DEBUG_DIDS: Record = { 'did:plc:oisofpd7lj26yvgiivf3lxsi': true, // hailey.at 'did:plc:p2cp5gopk7mgjegy6wadk3ep': true, // samuel.bsky.team diff --git a/src/state/queries/peer-mod-permissions.ts b/src/state/queries/peer-mod-permissions.ts index d86968b42..b0ab1c325 100644 --- a/src/state/queries/peer-mod-permissions.ts +++ b/src/state/queries/peer-mod-permissions.ts @@ -1,6 +1,7 @@ import {useQuery} from '@tanstack/react-query' import {communityXrpc} from '#/lib/api/community' +import {PEER_MOD_DIDS} from '#/lib/constants' import {useAgent, useSession} from '#/state/session' const GET_MY_PERMISSIONS_METHOD = 'community.blacksky.moderation.getMyPermissions' @@ -40,3 +41,10 @@ export function useMyPeerModPermissions() { }, }) } + +// Subject-side peer-mod check used to render a badge on any profile. +// Mirrors the appview's PEER_MOD_DIDS env; replace with a public list endpoint +// once we ship one. +export function isPeerModDid(did: string | undefined): boolean { + return !!did && did in PEER_MOD_DIDS +} -- knotmirror 0.0.1 From 19eb9670b3bb4d5647301b242388c99851fc73b5 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 17:06:12 -0400 Subject: [PATCH 20/50] style(peer-mod): collapse the 3-line comment to one --- src/state/queries/peer-mod-permissions.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/state/queries/peer-mod-permissions.ts b/src/state/queries/peer-mod-permissions.ts index b0ab1c325..eb1456b24 100644 --- a/src/state/queries/peer-mod-permissions.ts +++ b/src/state/queries/peer-mod-permissions.ts @@ -42,9 +42,7 @@ export function useMyPeerModPermissions() { }) } -// Subject-side peer-mod check used to render a badge on any profile. -// Mirrors the appview's PEER_MOD_DIDS env; replace with a public list endpoint -// once we ship one. +// Mirrors the appview's PEER_MOD_DIDS env; flip to a public list endpoint when one exists. export function isPeerModDid(did: string | undefined): boolean { return !!did && did in PEER_MOD_DIDS } -- knotmirror 0.0.1 From 214b85df1a197ca273958669c8193a8620faea3c Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 17:45:25 -0400 Subject: [PATCH 21/50] fix(peer-mod): drop __DEV__ dry-run guard on apply/removeLabel The mutation hooks short-circuited with a logger.info call when __DEV__ was true, so any label action in a local build never hit the appview and the row never landed in peer_mod_label. Make the XRPC call regardless of environment. --- src/state/queries/peer-mod-label.ts | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/state/queries/peer-mod-label.ts b/src/state/queries/peer-mod-label.ts index 05d8ddef7..6a81f0546 100644 --- a/src/state/queries/peer-mod-label.ts +++ b/src/state/queries/peer-mod-label.ts @@ -2,7 +2,6 @@ import {useCallback} from 'react' import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' import {communityXrpc} from '#/lib/api/community' -import {logger} from '#/logger' import {useAgent} from '#/state/session' import {BLACKSKY_LABELER} from '#/state/session/additional-moderation-authorities' @@ -91,10 +90,6 @@ export function useApplyLabelMutation() { const invalidate = useInvalidateLabelState() return useMutation({ mutationFn: async input => { - if (__DEV__) { - logger.info('Applying peer-mod label (dry run)', {input}) - return - } const res = await communityXrpc(agent, APPLY_METHOD, {body: input}) if (!res.ok) { throw new Error(await readError(res)) @@ -111,10 +106,6 @@ export function useRemoveLabelMutation() { const invalidate = useInvalidateLabelState() return useMutation({ mutationFn: async input => { - if (__DEV__) { - logger.info('Removing peer-mod label (dry run)', {input}) - return - } const res = await communityXrpc(agent, REMOVE_METHOD, {body: input}) if (!res.ok) { throw new Error(await readError(res)) -- knotmirror 0.0.1 From 632b0cf9617312270d0fedc279f38decfedba23d Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 18:12:39 -0400 Subject: [PATCH 22/50] fix(community-feed): refresh on focus, poll, pull-to-refresh, invalidate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Community tab was a black hole — once mounted, the feed stayed frozen until full reload. Three fixes: - CommunityFeedPage refetches when the tab gains focus, polls every 60s while focused, and exposes pull-to-refresh through the List. - Apply / remove peer-mod label mutations invalidate the timeline, per-actor feed, and per-post caches so the warning shade appears without having to bounce out of the page. - Successful community post create invalidates the timeline + feed caches so a fresh post lands at the top immediately. --- src/lib/api/index.ts | 3 +++ src/state/queries/peer-mod-label.ts | 12 +++++++++++ src/view/com/feeds/CommunityFeedPage.tsx | 26 ++++++++++++++++++++++-- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index d94f51b8d..ede2fea64 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -394,6 +394,9 @@ async function postCommunity( } } + void queryClient.invalidateQueries({queryKey: ['community-timeline']}) + void queryClient.invalidateQueries({queryKey: ['community-feed']}) + return {uris} } diff --git a/src/state/queries/peer-mod-label.ts b/src/state/queries/peer-mod-label.ts index 6a81f0546..a7faaa811 100644 --- a/src/state/queries/peer-mod-label.ts +++ b/src/state/queries/peer-mod-label.ts @@ -2,6 +2,11 @@ import {useCallback} from 'react' import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' import {communityXrpc} from '#/lib/api/community' +import { + COMMUNITY_POST_RQKEY, + RQKEY_ROOT as COMMUNITY_FEED_RQKEY_ROOT, + TIMELINE_RQKEY, +} from '#/state/queries/community-feed' import {useAgent} from '#/state/session' import {BLACKSKY_LABELER} from '#/state/session/additional-moderation-authorities' @@ -123,6 +128,13 @@ function useInvalidateLabelState() { (subjectUri: string) => { void queryClient.invalidateQueries({queryKey: myLabelsRQKey(subjectUri)}) void queryClient.invalidateQueries({queryKey: postLabelsRQKey(subjectUri)}) + void queryClient.invalidateQueries({ + queryKey: COMMUNITY_POST_RQKEY(subjectUri), + }) + void queryClient.invalidateQueries({queryKey: TIMELINE_RQKEY()}) + void queryClient.invalidateQueries({ + queryKey: [COMMUNITY_FEED_RQKEY_ROOT], + }) }, [queryClient], ) diff --git a/src/view/com/feeds/CommunityFeedPage.tsx b/src/view/com/feeds/CommunityFeedPage.tsx index 65b84865d..c676179ab 100644 --- a/src/view/com/feeds/CommunityFeedPage.tsx +++ b/src/view/com/feeds/CommunityFeedPage.tsx @@ -1,4 +1,4 @@ -import {useCallback, useMemo, useRef} from 'react' +import {useCallback, useEffect, useMemo, useRef, useState} from 'react' import {ActivityIndicator, type ListRenderItemInfo, View} from 'react-native' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' @@ -51,12 +51,32 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { const hydratedPosts = useCommunityFeedHydrated(feedItems) + const [isRefreshing, setIsRefreshing] = useState(false) + const onRefresh = useCallback(async () => { + setIsRefreshing(true) + try { + await refetch() + } finally { + setIsRefreshing(false) + } + }, [refetch]) + + useEffect(() => { + if (isPageFocused) void refetch() + }, [isPageFocused, refetch]) + + useEffect(() => { + if (!isPageFocused) return + const id = setInterval(() => void refetch(), 60_000) + return () => clearInterval(id) + }, [isPageFocused, refetch]) + const _onScrollToTop = useCallback(() => { scrollElRef.current?.scrollToOffset({ animated: IS_NATIVE, offset: -headerOffset, }) - refetch() + void refetch() }, [scrollElRef, headerOffset, refetch]) const renderItem = useCallback( @@ -157,6 +177,8 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { onEndReachedThreshold={0.6} headerOffset={headerOffset} contentContainerStyle={{paddingBottom: 100}} + refreshing={isRefreshing} + onRefresh={onRefresh} /> {hasSession && ( -- knotmirror 0.0.1 From b306fb4158f2116b18d5b6dad715896693c60e7b Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 18:25:10 -0400 Subject: [PATCH 23/50] feat(composer): show Blacksky-only badge when toggle is on Mirrors the badge users see in the action bar so they get an at-a-glance preview that the post is going to land in the community. The tooltip works the same way. --- src/view/com/composer/Composer.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index c3343fbc9..11c034c2c 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -112,6 +112,7 @@ import { } from '#/view/com/composer/ExternalEmbed' import {ExternalEmbedRemoveBtn} from '#/view/com/composer/ExternalEmbedRemoveBtn' import {GifAltTextDialog} from '#/view/com/composer/GifAltText' +import {CommunityOnlyBadge} from '#/components/CommunityOnlyBadge' import {LabelsBtn} from '#/view/com/composer/labels/LabelsBtn' import {Gallery} from '#/view/com/composer/photos/Gallery' import {OpenCameraBtn} from '#/view/com/composer/photos/OpenCameraBtn' @@ -2037,6 +2038,7 @@ function ComposerPills({ )} + {thread.blackskyOnly && } {hasMedia || hasLink ? ( Date: Fri, 26 Jun 2026 18:28:01 -0400 Subject: [PATCH 24/50] style(composer): right + bottom align the Blacksky-only badge Move the badge out of the horizontal pills ScrollView so it sits in a fixed right slot with bottom-aligned padding; the pills row gets flex_1 to push the badge to the far right. --- src/view/com/composer/Composer.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 11c034c2c..dab938115 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -1999,6 +1999,7 @@ function ComposerPills({ )} - {thread.blackskyOnly && } {hasMedia || hasLink ? ( ) : null} + {thread.blackskyOnly && ( + + + + )} ) } -- knotmirror 0.0.1 From 7e1cc49093630a5507dcb707a8e87e8090b9b214 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 18:58:38 -0400 Subject: [PATCH 25/50] fix(notifications): fetch community-post subjects for preview The util's subject fetcher only sent app.bsky.feed.post URIs to getPosts, so community-URI subjects (reply/quote/mention targets) came back undefined and rendered without their inline post card. Branch community URIs through getCommunityPost and merge the results into the same postsMap. --- src/state/queries/notifications/util.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/state/queries/notifications/util.ts b/src/state/queries/notifications/util.ts index e5fca0ebc..d7453b5a8 100644 --- a/src/state/queries/notifications/util.ts +++ b/src/state/queries/notifications/util.ts @@ -14,6 +14,7 @@ import { import {type QueryClient} from '@tanstack/react-query' import chunk from 'lodash.chunk' +import {communityXrpc} from '#/lib/api/community' import {labelIsHideableOffense} from '#/lib/moderation' import * as bsky from '#/types/bsky' import {precacheProfile} from '../profile' @@ -217,9 +218,12 @@ async function fetchSubjects( starterPacks: Map }> { const postUris = new Set() + const communityPostUris = new Set() const packUris = new Set() for (const notif of groupedNotifs) { - if (notif.subjectUri?.includes('app.bsky.feed.post')) { + if (notif.subjectUri?.includes('community.blacksky.feed.post')) { + communityPostUris.add(notif.subjectUri) + } else if (notif.subjectUri?.includes('app.bsky.feed.post')) { postUris.add(notif.subjectUri) } else if ( notif.notification.reasonSubject?.includes('app.bsky.graph.starterpack') @@ -237,6 +241,19 @@ async function fetchSubjects( .catch(_e => [] as AppBskyFeedDefs.PostView[]), ), ) + const communityPostsResults = await Promise.all( + Array.from(communityPostUris).map(uri => + communityXrpc(agent, 'community.blacksky.feed.getCommunityPost', { + params: {uri}, + }) + .then(async res => { + if (!res.ok) return undefined + const data = (await res.json()) as {post?: AppBskyFeedDefs.PostView} + return data.post + }) + .catch(() => undefined), + ), + ) const packsChunks = await Promise.all( packUriChunks.map(uris => agent.app.bsky.graph @@ -252,6 +269,9 @@ async function fetchSubjects( postsMap.set(post.uri, post) } } + for (const post of communityPostsResults) { + if (post) postsMap.set(post.uri, post) + } for (const pack of packsChunks.flat()) { if (AppBskyGraphStarterpack.isRecord(pack.record)) { packsMap.set(pack.uri, pack) -- knotmirror 0.0.1 From 7a6c8768bf69feda134a521172c252ed35609136 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 26 Jun 2026 19:07:55 -0400 Subject: [PATCH 26/50] ci: add manual workflow to build + push staging image to DOCR Clones the prod docr workflow but workflow_dispatch only and tags the image registry.digitalocean.com/blacksky/blacksky-community:staging plus a staging- tag. Points the OAuth client at staging.blacksky.community; everything else (Stripe, GrowthBook, metrics) reuses the same repo secrets so we don't have to mirror plaintext values out of GitHub. --- .../build-and-push-bskyweb-docr-staging.yaml | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 .github/workflows/build-and-push-bskyweb-docr-staging.yaml diff --git a/.github/workflows/build-and-push-bskyweb-docr-staging.yaml b/.github/workflows/build-and-push-bskyweb-docr-staging.yaml new file mode 100644 index 000000000..42d5bb398 --- /dev/null +++ b/.github/workflows/build-and-push-bskyweb-docr-staging.yaml @@ -0,0 +1,65 @@ +name: build-and-push-bskyweb-docr-staging +on: + workflow_dispatch: + +jobs: + bskyweb-container-docr-staging: + if: github.repository == 'blacksky-algorithms/blacksky.community' + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Docker buildx + uses: docker/setup-buildx-action@v3 + + - name: Install doctl + uses: digitalocean/action-doctl@v2 + with: + token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} + + - name: Log into DOCR + run: doctl registry login --expiry-seconds 600 + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: | + registry.digitalocean.com/blacksky/blacksky-community + tags: | + type=raw,value=staging + type=sha,enable=true,priority=100,prefix=staging-,suffix=,format=long + + - name: Env + id: env + run: | + echo "EXPO_PUBLIC_RELEASE_VERSION=$(jq -r '.version' package.json)" >> $GITHUB_OUTPUT + echo "EXPO_PUBLIC_BUNDLE_IDENTIFIER=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT + + - name: Build and push Docker image + id: build-and-push + uses: docker/build-push-action@v5 + with: + context: . + push: true + file: ./Dockerfile + platforms: linux/amd64 + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + build-args: | + EXPO_PUBLIC_ENV=production + EXPO_PUBLIC_RELEASE_VERSION=${{ steps.env.outputs.EXPO_PUBLIC_RELEASE_VERSION }} + EXPO_PUBLIC_BUNDLE_IDENTIFIER=${{ steps.env.outputs.EXPO_PUBLIC_BUNDLE_IDENTIFIER }} + EXPO_PUBLIC_OAUTH_BASE_URL=https://staging.blacksky.community + EXPO_PUBLIC_OAUTH_CLIENT_NAME=Blacksky Community (Staging) + EXPO_PUBLIC_METRICS_API_HOST=${{ secrets.EXPO_PUBLIC_METRICS_API_HOST }} + EXPO_PUBLIC_GROWTHBOOK_API_HOST=${{ secrets.EXPO_PUBLIC_GROWTHBOOK_API_HOST }} + EXPO_PUBLIC_GROWTHBOOK_CLIENT_KEY=${{ secrets.EXPO_PUBLIC_GROWTHBOOK_CLIENT_KEY }} + EXPO_PUBLIC_STRIPE_API_URL=${{ secrets.EXPO_PUBLIC_STRIPE_API_URL }} + EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY=${{ secrets.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY }} -- knotmirror 0.0.1 From 1656f03dd325951124be0505e201d542a665461f Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Mon, 29 Jun 2026 11:49:17 -0400 Subject: [PATCH 27/50] feat(community-posts): community-aware copy on WhoCanReply When the post is a community post, swap the chip/long-form text so the language matches the audience: - 'Everybody can reply' -> 'Every community member can reply' - 'Some people can reply' -> 'Some community members can reply' - 'Everybody can reply to this post.' -> 'Every Blacksky community member can reply to this post.' Nobody/disabled copy unchanged; non-community posts unchanged. --- src/components/WhoCanReply.tsx | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/components/WhoCanReply.tsx b/src/components/WhoCanReply.tsx index be7636ff4..487628a6b 100644 --- a/src/components/WhoCanReply.tsx +++ b/src/components/WhoCanReply.tsx @@ -81,11 +81,16 @@ export function WhoCanReply({post, isThreadAuthor, style}: WhoCanReplyProps) { const anyoneCanReply = settings.length === 1 && settings[0].type === 'everybody' const noOneCanReply = settings.length === 1 && settings[0].type === 'nobody' + const isCommunityPost = post.uri.includes('community.blacksky.feed.post') const description = anyoneCanReply - ? _(msg`Everybody can reply`) + ? isCommunityPost + ? _(msg`Every community member can reply`) + : _(msg`Everybody can reply`) : noOneCanReply ? _(msg`Replies disabled`) - : _(msg`Some people can reply`) + : isCommunityPost + ? _(msg`Some community members can reply`) + : _(msg`Some people can reply`) const onPressOpen = () => { if (IS_NATIVE && Keyboard.isVisible()) { @@ -276,7 +281,11 @@ function Rules({ out of date. ) : settings[0].type === 'everybody' ? ( - Everybody can reply to this post. + post.uri.includes('community.blacksky.feed.post') ? ( + Every Blacksky community member can reply to this post. + ) : ( + Everybody can reply to this post. + ) ) : settings[0].type === 'nobody' ? ( Replies to this post are disabled. ) : ( -- knotmirror 0.0.1 From 4c5dabf280f3489e4340448497b8f8dfa459ad18 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Mon, 29 Jun 2026 11:51:41 -0400 Subject: [PATCH 28/50] style(community-posts): drop redundant Blacksky from WhoCanReply copy --- src/components/WhoCanReply.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/WhoCanReply.tsx b/src/components/WhoCanReply.tsx index 487628a6b..75ecb5268 100644 --- a/src/components/WhoCanReply.tsx +++ b/src/components/WhoCanReply.tsx @@ -282,7 +282,7 @@ function Rules({ ) : settings[0].type === 'everybody' ? ( post.uri.includes('community.blacksky.feed.post') ? ( - Every Blacksky community member can reply to this post. + Every community member can reply to this post. ) : ( Everybody can reply to this post. ) -- knotmirror 0.0.1 From d57c8475ad0c638d3f99af8551adad449caebde2 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Tue, 30 Jun 2026 13:30:40 -0400 Subject: [PATCH 29/50] fix(community-posts): paste-URL-as-quote handles blacksky.community + ?collection= Three chained bugs made pasting a community-post URL into the composer crash with 'record key syntax not valid (regex)' instead of producing a quote embed: 1) isBskyAppUrl only matched https://bsky.app/ so every blacksky.community URL fell through to the external-link branch. Extend it to also accept https://blacksky.community/ and https://staging.blacksky.community/. 2) convertBskyAppUrlIfNeeded returns pathname+search; the downstream split('/') jammed the entire ?collection=... tail into rkey, which ensureValidRecordKey rejected. Parse the URL properly so the query never reaches the rkey position. Same fix applied to the DM message embed extractor and the DM facet-strip path. 3) resolveLink's post branch hardcoded 'app.bsky.feed.post' and went to agent.getPosts. Read ?collection= from the URL and route community URIs through community.blacksky.feed.getCommunityPost instead. --- src/lib/api/resolve.ts | 50 +++++++++++++++++-- src/lib/strings/url-helpers.ts | 6 ++- .../Messages/components/MessageInputEmbed.tsx | 15 ++++-- .../Messages/components/MessagesList.tsx | 11 +++- 4 files changed, 72 insertions(+), 10 deletions(-) diff --git a/src/lib/api/resolve.ts b/src/lib/api/resolve.ts index b5782ef43..ffae83152 100644 --- a/src/lib/api/resolve.ts +++ b/src/lib/api/resolve.ts @@ -25,6 +25,7 @@ import { isShortLink, makeRecordUri, } from '#/lib/strings/url-helpers' +import {communityXrpc} from '#/lib/api/community' import {type ComposerImage} from '#/state/gallery' import {createComposerImage} from '#/state/gallery' import {type ChatInvitePreview} from '#/state/queries/join-links' @@ -94,6 +95,44 @@ export class EmbeddingDisabledError extends Error { } } +const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' + +// Pull the path portion (without ?query) and the collection from a bsky-style +// post URL. Community posts share the /profile//post/ shape with a +// ?collection=community.blacksky.feed.post tail. +function splitPostUrl(url: string): {path: string; collection: string} { + const stripped = convertBskyAppUrlIfNeeded(url) + try { + const u = new URL(stripped, 'http://_') + const collection = + u.searchParams.get('collection') || 'app.bsky.feed.post' + return {path: u.pathname, collection} + } catch { + const [path] = stripped.split('?') + return {path, collection: 'app.bsky.feed.post'} + } +} + +async function getCommunityPost(agent: AtpAgent, uri: string) { + const urip = new AtUri(uri) + if (!urip.host.startsWith('did:')) { + const res = await agent.resolveHandle({handle: urip.host}) + // @ts-expect-error TODO new-sdk-migration + urip.host = res.data.did + } + const res = await communityXrpc( + agent, + 'community.blacksky.feed.getCommunityPost', + {params: {uri: urip.toString()}}, + ) + if (!res.ok) { + throw new Error(`getCommunityPost ${res.status}`) + } + const data = (await res.json()) as {post?: any} + if (!data.post) throw new Error('getCommunityPost: post not found') + return data.post +} + export async function resolveLink( agent: AtpAgent, uri: string, @@ -102,10 +141,13 @@ export async function resolveLink( uri = await resolveShortLink(uri) } if (isBskyPostUrl(uri)) { - uri = convertBskyAppUrlIfNeeded(uri) - const [_0, user, _1, rkey] = uri.split('/').filter(Boolean) - const recordUri = makeRecordUri(user, 'app.bsky.feed.post', rkey) - const post = await getPost({uri: recordUri}) + const {path, collection} = splitPostUrl(uri) + const [_0, user, _1, rkey] = path.split('/').filter(Boolean) + const recordUri = makeRecordUri(user, collection, rkey) + const post = + collection === COMMUNITY_POST_COLLECTION + ? await getCommunityPost(agent, recordUri) + : await getPost({uri: recordUri}) if (post.viewer?.embeddingDisabled) { throw new EmbeddingDisabledError() } diff --git a/src/lib/strings/url-helpers.ts b/src/lib/strings/url-helpers.ts index c589c0129..29816c483 100644 --- a/src/lib/strings/url-helpers.ts +++ b/src/lib/strings/url-helpers.ts @@ -92,7 +92,11 @@ export function toBskyAppUrl(url: string): string { } export function isBskyAppUrl(url: string): boolean { - return url.startsWith('https://bsky.app/') + return ( + url.startsWith('https://bsky.app/') || + url.startsWith('https://blacksky.community/') || + url.startsWith('https://staging.blacksky.community/') + ) } export function isRelativeUrl(url: string): boolean { diff --git a/src/screens/Messages/components/MessageInputEmbed.tsx b/src/screens/Messages/components/MessageInputEmbed.tsx index 355a9c2fb..988a57686 100644 --- a/src/screens/Messages/components/MessageInputEmbed.tsx +++ b/src/screens/Messages/components/MessageInputEmbed.tsx @@ -83,9 +83,18 @@ export function useMessageEmbed() { } if (isBskyPostUrl(embedUrl)) { - const url = convertBskyAppUrlIfNeeded(embedUrl) - const [_0, user, _1, rkey] = url.split('/').filter(Boolean) - const uri = makeRecordUri(user, 'app.bsky.feed.post', rkey) + const stripped = convertBskyAppUrlIfNeeded(embedUrl) + let path = stripped + let collection = 'app.bsky.feed.post' + try { + const u = new URL(stripped, 'http://_') + path = u.pathname + collection = u.searchParams.get('collection') || collection + } catch { + path = stripped.split('?')[0] + } + const [_0, user, _1, rkey] = path.split('/').filter(Boolean) + const uri = makeRecordUri(user, collection, rkey) setEmbed({type: 'post', uri}) } }, diff --git a/src/screens/Messages/components/MessagesList.tsx b/src/screens/Messages/components/MessagesList.tsx index 8fbfa88e0..bf5d01a08 100644 --- a/src/screens/Messages/components/MessagesList.tsx +++ b/src/screens/Messages/components/MessagesList.tsx @@ -439,8 +439,15 @@ export function MessagesList({ stripLinkFacet(uri => { if (!isBskyPostUrl(uri)) return false - const url = convertBskyAppUrlIfNeeded(uri) - const [_0, _1, _2, rkey] = url.split('/').filter(Boolean) + const stripped = convertBskyAppUrlIfNeeded(uri) + const path = (() => { + try { + return new URL(stripped, 'http://_').pathname + } catch { + return stripped.split('?')[0] + } + })() + const [_0, _1, _2, rkey] = path.split('/').filter(Boolean) // this might have a handle instead of a DID // so just compare the rkey - not particularly dangerous return post.uri.endsWith(rkey) -- knotmirror 0.0.1 From 65b307d423fa86a1d6ceda318bf5daa768663825 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Tue, 30 Jun 2026 16:08:02 -0400 Subject: [PATCH 30/50] fix(community-posts): preserve ?collection= on post URLs + dismiss badge tooltip on unmount #5 postUriToRelativePath now appends ?collection= for any post URI whose collection isn't app.bsky.feed.post. Every navigation that goes through this helper (liked-posts, share URLs, in-app links, notification routes) now lands on the PostThread screen with the correct route param, so community-post detail views resolve instead of falling back to 'Post not found'. #6 CommunityOnlyBadge resets its tooltip visible state on unmount so the floating tooltip portal disappears when the user navigates away mid-tap. --- src/components/CommunityOnlyBadge.tsx | 6 +++++- src/lib/strings/url-helpers.ts | 7 +++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/components/CommunityOnlyBadge.tsx b/src/components/CommunityOnlyBadge.tsx index b23acc607..b7465f344 100644 --- a/src/components/CommunityOnlyBadge.tsx +++ b/src/components/CommunityOnlyBadge.tsx @@ -1,4 +1,4 @@ -import {useState} from 'react' +import {useEffect, useState} from 'react' import {Pressable, View} from 'react-native' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' @@ -21,6 +21,10 @@ export function CommunityOnlyBadge() { const {_} = useLingui() const [visible, setVisible] = useState(false) + useEffect(() => { + return () => setVisible(false) + }, []) + return ( Date: Tue, 30 Jun 2026 16:21:46 -0400 Subject: [PATCH 31/50] fix(community-posts): YouTube iframe + gallery render guards #9 IFRAME_HOST hardcoded to https://blacksky.community meant any non-canonical parent host (staging.blacksky.community, local dev, preview deploys) framed cross-origin and got blocked by the iframe server's X-Frame-Options: SAMEORIGIN. Read window.location.origin so the iframe always loads same-origin with the SPA. #10 ImageEmbed.tsx and MediaPreview.tsx assumed embed.view.items was always an array. A malformed gallery#view (e.g. items missing) threw TypeError on .filter / for-of and ErrorBoundary locked the whole page. Wrap in Array.isArray guards so a future appview regression degrades to 'no media' instead of 'page crashes.' --- src/components/MediaPreview.tsx | 2 +- src/components/Post/Embed/ImageEmbed.tsx | 18 +++++++++++------- src/lib/strings/embed-player.ts | 4 ++-- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/components/MediaPreview.tsx b/src/components/MediaPreview.tsx index 7b0e38e0b..e6697df6c 100644 --- a/src/components/MediaPreview.tsx +++ b/src/components/MediaPreview.tsx @@ -57,7 +57,7 @@ export function Embed({ // of filter().slice().map() so we stop at 4 viewable items rather than // walking every item in a 10-image gallery. const tiles: React.ReactNode[] = [] - for (const item of e.view.items) { + for (const item of Array.isArray(e.view.items) ? e.view.items : []) { if (tiles.length >= 4) break if (!AppBskyEmbedGallery.isViewImage(item)) continue if (peekable) { diff --git a/src/components/Post/Embed/ImageEmbed.tsx b/src/components/Post/Embed/ImageEmbed.tsx index 9d4730206..1118b90e8 100644 --- a/src/components/Post/Embed/ImageEmbed.tsx +++ b/src/components/Post/Embed/ImageEmbed.tsx @@ -31,13 +31,17 @@ export function ImageEmbed({ const {openLightbox} = useLightboxControls() const images: AppBskyEmbedImages.ViewImage[] = embed.type === 'gallery' - ? embed.view.items.filter(AppBskyEmbedGallery.isViewImage).map(item => ({ - thumb: item.thumbnail, - fullsize: item.fullsize, - alt: item.alt, - aspectRatio: item.aspectRatio, - })) - : embed.view.images + ? (Array.isArray(embed.view.items) ? embed.view.items : []) + .filter(AppBskyEmbedGallery.isViewImage) + .map(item => ({ + thumb: item.thumbnail, + fullsize: item.fullsize, + alt: item.alt, + aspectRatio: item.aspectRatio, + })) + : Array.isArray(embed.view.images) + ? embed.view.images + : [] const useExpandedLayout = embed.type === 'gallery' ? images.length > MAX_GRID_IMAGES diff --git a/src/lib/strings/embed-player.ts b/src/lib/strings/embed-player.ts index 40abc13fa..6614836f9 100644 --- a/src/lib/strings/embed-player.ts +++ b/src/lib/strings/embed-player.ts @@ -6,8 +6,8 @@ const {height: SCREEN_HEIGHT} = Dimensions.get('window') const IFRAME_HOST = IS_WEB ? // @ts-ignore only for web - window.location.host === 'localhost:8100' - ? 'http://localhost:8100' + typeof window !== 'undefined' + ? window.location.origin : 'https://blacksky.community' : __DEV__ && !process.env.JEST_WORKER_ID ? 'http://localhost:8100' -- knotmirror 0.0.1 From 97f14c5231b332b2ccf429112441b805e0127c9f Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Tue, 30 Jun 2026 16:37:48 -0400 Subject: [PATCH 32/50] fix(community-posts): stream video upload on web, kill mobile-Safari OOM MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #11 The web video upload path round-tripped the entire video through a base64 string twice (once by expo-image-picker base64:true, once by SelectMediaButton's data:URL synthesis), then through atob → chunked Uint8Arrays → Blob → ArrayBuffer before a single xhr.send(ArrayBuffer). On a 100MB capture mobile Safari peaked at 4-5x the file size in RAM and killed the tab. - picker.shared.ts: drop base64:true on web — keep the picked File as a blob. - pickVideo.web.ts: replace readAsDataURL(file) with URL.createObjectURL(file) for the paste/drop path; add an oncancel handler so an iOS Safari picker dismissal resolves the promise instead of hanging forever. - compress.web.ts: stop pre-loading bytes; fetch the blob from its object URL once for size + mime metadata only. - upload.web.ts: xhr.send(blob) so the browser streams the upload; wire AbortSignal to xhr.abort() so abort actually cancels mid-flight. --- src/lib/media/picker.shared.ts | 3 +- src/lib/media/video/compress.web.ts | 32 ++--- src/lib/media/video/upload.web.ts | 26 ++++- src/view/com/composer/SelectMediaButton.tsx | 8 -- src/view/com/composer/videos/pickVideo.web.ts | 110 +++++++++--------- 5 files changed, 92 insertions(+), 87 deletions(-) diff --git a/src/lib/media/picker.shared.ts b/src/lib/media/picker.shared.ts index d7d8dab44..f2b15a560 100644 --- a/src/lib/media/picker.shared.ts +++ b/src/lib/media/picker.shared.ts @@ -56,7 +56,8 @@ export async function openUnifiedPicker({ quality: 1, allowsMultipleSelection: true, legacy: true, - base64: IS_WEB, + // Forcing base64 on web preloads the whole video, killing mobile Safari tabs. + base64: false, selectionLimit: IS_IOS ? selectionCountRemaining : undefined, preferredAssetRepresentationMode: UIImagePickerPreferredAssetRepresentationMode.Automatic, diff --git a/src/lib/media/video/compress.web.ts b/src/lib/media/video/compress.web.ts index 83fdfde53..b99abf41b 100644 --- a/src/lib/media/video/compress.web.ts +++ b/src/lib/media/video/compress.web.ts @@ -4,7 +4,6 @@ import {VIDEO_MAX_SIZE} from '#/lib/constants' import {VideoTooLargeError} from '#/lib/media/video/errors' import {type CompressedVideo} from './types' -// doesn't actually compress, converts to ArrayBuffer export async function compressVideo( asset: ImagePickerAsset, _opts?: { @@ -12,19 +11,29 @@ export async function compressVideo( onProgress?: (progress: number) => void }, ): Promise { - const {mimeType, base64} = parseDataUrl(asset.uri) - const blob = base64ToBlob(base64, mimeType) - const uri = URL.createObjectURL(blob) + // Legacy path: caller passed a data URL (draft restore, paste, etc.). + if (asset.uri.startsWith('data:')) { + const {mimeType, base64} = parseDataUrl(asset.uri) + const blob = base64ToBlob(base64, mimeType) + if (blob.size > VIDEO_MAX_SIZE) { + throw new VideoTooLargeError() + } + return { + size: blob.size, + uri: URL.createObjectURL(blob), + mimeType, + } + } + const res = await fetch(asset.uri) + const blob = await res.blob() if (blob.size > VIDEO_MAX_SIZE) { throw new VideoTooLargeError() } - return { size: blob.size, - uri, - bytes: await blob.arrayBuffer(), - mimeType, + uri: asset.uri, + mimeType: blob.type || asset.mimeType || 'video/mp4', } } @@ -39,18 +48,13 @@ function parseDataUrl(dataUrl: string) { function base64ToBlob(base64: string, mimeType: string) { const byteCharacters = atob(base64) const byteArrays = [] - for (let offset = 0; offset < byteCharacters.length; offset += 512) { const slice = byteCharacters.slice(offset, offset + 512) const byteNumbers = new Array(slice.length) - for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i) } - - const byteArray = new Uint8Array(byteNumbers) - byteArrays.push(byteArray) + byteArrays.push(new Uint8Array(byteNumbers)) } - return new Blob(byteArrays, {type: mimeType}) } diff --git a/src/lib/media/video/upload.web.ts b/src/lib/media/video/upload.web.ts index deec6b239..59c6f6597 100644 --- a/src/lib/media/video/upload.web.ts +++ b/src/lib/media/video/upload.web.ts @@ -34,19 +34,21 @@ export async function uploadVideo({ name: `${nanoid(12)}.${mimeToExt(video.mimeType)}`, }) - let bytes = video.bytes - if (!bytes) { + // Stream the Blob directly; loading the whole file as ArrayBuffer OOMs mobile Safari. + let body: Blob | ArrayBuffer + if (video.bytes) { + body = video.bytes + } else { if (signal.aborted) { throw new AbortError() } - bytes = await fetch(video.uri).then(res => res.arrayBuffer()) + body = await fetch(video.uri).then(res => res.blob()) } if (signal.aborted) { throw new AbortError() } - // Token audience should be user's PDS DID since we forward it to the PDS - // for blob upload. Don't pass aud to let it default to pdsAud. + // Token aud defaults to the user's PDS DID; the video service forwards uploadBlob there. const token = await getServiceAuthToken({ agent, lxm: 'com.atproto.repo.uploadBlob', @@ -59,11 +61,22 @@ export async function uploadVideo({ const xhr = new XMLHttpRequest() const res = await new Promise( (resolve, reject) => { + const onAbort = () => { + try { + xhr.abort() + } catch {} + reject(new AbortError()) + } + if (signal.aborted) { + return onAbort() + } + signal.addEventListener('abort', onAbort, {once: true}) xhr.upload.addEventListener('progress', e => { const progress = e.loaded / e.total setProgress(progress) }) xhr.onloadend = () => { + signal.removeEventListener('abort', onAbort) if (signal.aborted) { reject(new AbortError()) } else if (xhr.readyState === 4) { @@ -76,12 +89,13 @@ export async function uploadVideo({ } } xhr.onerror = () => { + signal.removeEventListener('abort', onAbort) reject(new ServerError(i18n._(msg`Failed to upload video`))) } xhr.open('POST', uri) xhr.setRequestHeader('Content-Type', video.mimeType) xhr.setRequestHeader('Authorization', `Bearer ${token}`) - xhr.send(bytes) + xhr.send(body) }, ) diff --git a/src/view/com/composer/SelectMediaButton.tsx b/src/view/com/composer/SelectMediaButton.tsx index 1de39f5f5..5905a69f8 100644 --- a/src/view/com/composer/SelectMediaButton.tsx +++ b/src/view/com/composer/SelectMediaButton.tsx @@ -318,17 +318,9 @@ async function processImagePickerAssets( } } - /* - * All validations passed, we have an asset! - */ supportedAssets.push({ mimeType, ...asset, - /* - * In `expo-image-picker` >= v17, `uri` is now a `blob:` URL, not a - * data-uri. Our handling elsewhere in the app (for web) relies on the - * base64 data-uri, so we construct it here for web only. - */ uri: IS_WEB && asset.base64 ? `data:${mimeType};base64,${asset.base64}` diff --git a/src/view/com/composer/videos/pickVideo.web.ts b/src/view/com/composer/videos/pickVideo.web.ts index aa53702a2..47e9c168d 100644 --- a/src/view/com/composer/videos/pickVideo.web.ts +++ b/src/view/com/composer/videos/pickVideo.web.ts @@ -16,17 +16,27 @@ export async function pickVideo(): Promise { document.body.appendChild(input) return new Promise(resolve => { + let settled = false + const finish = (result: ImagePickerResult) => { + if (settled) return + settled = true + try { + document.body.removeChild(input) + } catch {} + resolve(result) + } input.addEventListener('change', async () => { - if (input.files) { - const file = input.files[0] - resolve({ + if (input.files && input.files[0]) { + finish({ canceled: false, - assets: [await getVideoMetadata(file)], + assets: [await getVideoMetadata(input.files[0])], }) } else { - resolve({canceled: true, assets: null}) + finish({canceled: true, assets: null}) } - document.body.removeChild(input) + }) + input.addEventListener('cancel', () => { + finish({canceled: true, assets: null}) }) const event = new MouseEvent('click') @@ -34,11 +44,8 @@ export async function pickVideo(): Promise { }) } -// TODO: we're converting to a dataUrl here, and then converting back to an -// ArrayBuffer in the compressVideo function. This is a bit wasteful, but it -// lets us use the ImagePickerAsset type, which the rest of the code expects. -// We should unwind this and just pass the ArrayBuffer/objectUrl through the system -// instead of a string -sfn +// Return an object URL for the picked File so we don't read the whole video +// into a base64 string just to read its width/height/duration. export function getVideoMetadata( file: File | string, ): Promise { @@ -46,55 +53,42 @@ export function getVideoMetadata( throw new Error( 'getVideoMetadata was passed a uri, when on web it should be a File', ) + const uri = URL.createObjectURL(file) return new Promise((resolve, reject) => { - const reader = new FileReader() - reader.onload = () => { - const uri = reader.result as string - - if (file.type === 'image/gif') { - const img = new Image() - img.onload = () => { - resolve({ - uri, - mimeType: 'image/gif', - width: img.width, - height: img.height, - // todo: calculate gif duration. seems possible if you read the bytes - // https://codepen.io/Ryman/pen/nZpYwY - // for now let's just let the server reject it, since that seems uncommon -sfn - duration: null, - }) - } - img.onerror = (_ev, _source, _lineno, _colno, error) => { - console.log('Failed to grab GIF metadata', error) - reject(new Error('Failed to grab GIF metadata')) - } - img.src = uri - } else { - const video = document.createElement('video') - const blobUrl = URL.createObjectURL(file) - - video.preload = 'metadata' - video.src = blobUrl - - video.onloadedmetadata = () => { - URL.revokeObjectURL(blobUrl) - resolve({ - uri, - mimeType: file.type, - width: video.videoWidth, - height: video.videoHeight, - // convert seconds to ms - duration: video.duration * 1000, - }) - } - video.onerror = (_ev, _source, _lineno, _colno, error) => { - URL.revokeObjectURL(blobUrl) - console.log('Failed to grab video metadata', error) - reject(new Error('Failed to grab video metadata')) - } + if (file.type === 'image/gif') { + const img = new Image() + img.onload = () => { + resolve({ + uri, + mimeType: 'image/gif', + width: img.width, + height: img.height, + // TODO: real GIF duration (see https://codepen.io/Ryman/pen/nZpYwY); rare in practice. + duration: null, + }) + } + img.onerror = (_ev, _source, _lineno, _colno, error) => { + console.log('Failed to grab GIF metadata', error) + reject(new Error('Failed to grab GIF metadata')) + } + img.src = uri + } else { + const video = document.createElement('video') + video.preload = 'metadata' + video.src = uri + video.onloadedmetadata = () => { + resolve({ + uri, + mimeType: file.type, + width: video.videoWidth, + height: video.videoHeight, + duration: video.duration * 1000, + }) + } + video.onerror = (_ev, _source, _lineno, _colno, error) => { + console.log('Failed to grab video metadata', error) + reject(new Error('Failed to grab video metadata')) } } - reader.readAsDataURL(file) }) } -- knotmirror 0.0.1 From 6e24d19655210017341bc193a3bbbacf24479296 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Tue, 30 Jun 2026 16:48:01 -0400 Subject: [PATCH 33/50] feat(community-posts): thread-connector UI on community feed #8 part 2: route community feed items through FeedTuner so a self-reply appears as a single visually-chained card instead of two flat ones. useCommunityFeedSlices wraps each FeedViewPostsSlice with moderation and a stable react key; CommunityFeedPage flattens the slices into rendered rows, passing the standard isThreadParent / isThreadChild / isThreadLastChild / hideTopBorder / parentAuthor / rootPost props that PostFeedItem uses to draw the connector line + 'Reply to' header. Pairs with the appview change that now ships reply.parent/root in getCommunityTimeline + getCommunityFeed feed items. --- src/state/queries/community-feed.ts | 46 ++++++++++++++++++ src/view/com/feeds/CommunityFeedPage.tsx | 59 ++++++++++++++++++------ 2 files changed, 90 insertions(+), 15 deletions(-) diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index ed769efd8..473067045 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -15,6 +15,7 @@ import { } from '@tanstack/react-query' import {communityXrpc} from '#/lib/api/community' +import {FeedTuner} from '#/lib/api/feed-manip' import {useModerationOpts} from '#/state/preferences/moderation-opts' import { didOrHandleUriMatches, @@ -151,6 +152,17 @@ export interface HydratedCommunityPost { moderation: ModerationDecision } +export interface CommunityFeedSliceItem extends HydratedCommunityPost { + _reactKey: string + uri: string + parentAuthor?: AppBskyFeedDefs.PostView['author'] +} + +export interface CommunityFeedSlice { + _reactKey: string + items: CommunityFeedSliceItem[] +} + /** * Takes pre-hydrated feed items from the server and adds moderation decisions. * The server now returns properly hydrated PostViews with author info and counts. @@ -174,6 +186,40 @@ export function useCommunityFeedHydrated( }, [feedItems, moderationOpts]) } +// Group feed items into slices so a self-reply (parent + reply by same author) +// renders as one visually-connected card instead of two flat ones. +export function useCommunityFeedSlices( + feedItems: AppBskyFeedDefs.FeedViewPost[], +): CommunityFeedSlice[] { + const moderationOpts = useModerationOpts() + + return useMemo(() => { + if (!moderationOpts) return [] + const tuner = new FeedTuner([]) + const raw = tuner.tune(feedItems) + + return raw + .map((slice, sliceIdx) => { + const items: CommunityFeedSliceItem[] = slice.items.map((item, i) => { + const record = item.post.record as AppBskyFeedPost.Record + return { + _reactKey: `${slice._reactKey}-${i}-${item.post.uri}`, + uri: item.post.uri, + post: item.post, + record, + moderation: moderatePost(item.post, moderationOpts), + parentAuthor: item.parentAuthor as any, + } + }) + return { + _reactKey: slice._reactKey || `slice-${sliceIdx}`, + items, + } + }) + .filter(slice => slice.items.length > 0) + }, [feedItems, moderationOpts]) +} + /** * Generator function to find all posts in the community feed cache. * Used by the post shadow system to update cached posts after mutations. diff --git a/src/view/com/feeds/CommunityFeedPage.tsx b/src/view/com/feeds/CommunityFeedPage.tsx index c676179ab..e6e170a84 100644 --- a/src/view/com/feeds/CommunityFeedPage.tsx +++ b/src/view/com/feeds/CommunityFeedPage.tsx @@ -8,12 +8,13 @@ import {useOpenComposer} from '#/lib/hooks/useOpenComposer' import {s} from '#/lib/styles' import {EditBig_Stroke2_Corner2_Rounded as EditBigIcon} from '#/components/icons/EditBig' import { - type HydratedCommunityPost, - useCommunityFeedHydrated, + type CommunityFeedSlice, + useCommunityFeedSlices, useCommunityTimelineQuery, } from '#/state/queries/community-feed' import {useSession} from '#/state/session' import {PostFeedItem} from '#/view/com/posts/PostFeedItem' +import {isThreadChildAt, isThreadParentAt} from '#/view/com/posts/PostFeed' import {FAB} from '#/view/com/util/fab/FAB' import {List, type ListMethods} from '#/view/com/util/List' import {MainScrollProvider} from '#/view/com/util/MainScrollProvider' @@ -49,7 +50,20 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { [data], ) - const hydratedPosts = useCommunityFeedHydrated(feedItems) + const slices = useCommunityFeedSlices(feedItems) + const rows = useMemo(() => { + const out: Array<{ + slice: CommunityFeedSlice + indexInSlice: number + reactKey: string + }> = [] + slices.forEach(slice => { + slice.items.forEach((item, i) => { + out.push({slice, indexInSlice: i, reactKey: item._reactKey}) + }) + }) + return out + }, [slices]) const [isRefreshing, setIsRefreshing] = useState(false) const onRefresh = useCallback(async () => { @@ -80,19 +94,34 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { }, [scrollElRef, headerOffset, refetch]) const renderItem = useCallback( - ({item, index}: ListRenderItemInfo) => { + ({ + item, + index, + }: ListRenderItemInfo<{ + slice: CommunityFeedSlice + indexInSlice: number + reactKey: string + }>) => { + const {slice, indexInSlice} = item + const sliceItem = slice.items[indexInSlice] return ( ) }, @@ -100,7 +129,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { ) const keyExtractor = useCallback( - (item: HydratedCommunityPost) => item.post.uri, + (item: {reactKey: string}) => item.reactKey, [], ) @@ -144,7 +173,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { ) } - if (!hasNextPage && hydratedPosts.length > 0) { + if (!hasNextPage && rows.length > 0) { return ( @@ -168,7 +197,7 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { Date: Tue, 30 Jun 2026 18:30:53 -0400 Subject: [PATCH 34/50] fix(community-posts): hydrate blob refs on community xrpc responses communityXrpc returns a raw Response and callers do res.json(), which skips the lex deserializer. Posts whose record carries a blob field (external thumb, image, video, gallery) then fail AppBskyFeedPost.validateRecord in FeedTuner because BlobRef.isBlobRef returns false on plain JSON. The slice is empty and the post never renders. Wrap the JSON in jsonToLex so blob fields become BlobRef instances. Same family of bug as the Redis actor-cache one. --- src/lib/api/index.ts | 3 ++- src/lib/api/resolve.ts | 4 ++-- src/state/queries/community-feed.ts | 9 ++++++--- src/state/queries/notifications/util.ts | 5 ++++- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index ede2fea64..faa16c921 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -14,6 +14,7 @@ import { type ComAtprotoLabelDefs, type ComAtprotoRepoApplyWrites, type ComAtprotoRepoStrongRef, + jsonToLex, RichText, } from '@atproto/api' import {TID} from '@atproto/common-web' @@ -436,7 +437,7 @@ async function resolveReply(agent: AtpAgent, replyTo: string) { }) return undefined } - const data = (await res.json()) as { + const data = jsonToLex(await res.json()) as { post?: { uri: string cid: string diff --git a/src/lib/api/resolve.ts b/src/lib/api/resolve.ts index ffae83152..5588b57d3 100644 --- a/src/lib/api/resolve.ts +++ b/src/lib/api/resolve.ts @@ -4,7 +4,7 @@ import { type AtpAgent, type ComAtprotoRepoStrongRef, } from '@atproto/api' -import {AtUri} from '@atproto/api' +import {AtUri, jsonToLex} from '@atproto/api' import {DM_SERVICE_HEADERS, IMAGE_SIZE_CONFIG_2K_1MB} from '#/lib/constants' import {getLinkMeta, type LinkMeta} from '#/lib/link-meta/link-meta' @@ -128,7 +128,7 @@ async function getCommunityPost(agent: AtpAgent, uri: string) { if (!res.ok) { throw new Error(`getCommunityPost ${res.status}`) } - const data = (await res.json()) as {post?: any} + const data = jsonToLex(await res.json()) as {post?: any} if (!data.post) throw new Error('getCommunityPost: post not found') return data.post } diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index 473067045..f107abd7b 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -3,6 +3,7 @@ import { type AppBskyFeedDefs, type AppBskyFeedPost, AtUri, + jsonToLex, moderatePost, type ModerationDecision, } from '@atproto/api' @@ -75,7 +76,7 @@ export function useCommunityFeedQuery(actor: string | undefined) { if (!res.ok) { throw new Error(`getCommunityFeed failed: ${res.status}`) } - return (await res.json()) as CommunityFeedPage + return jsonToLex(await res.json()) as CommunityFeedPage }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -112,7 +113,7 @@ export function useCommunityTimelineQuery(enabled: boolean) { if (!res.ok) { throw new Error(`getCommunityTimeline failed: ${res.status}`) } - return (await res.json()) as CommunityFeedPage + return jsonToLex(await res.json()) as CommunityFeedPage }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -139,7 +140,9 @@ export function useCommunityPostQuery(uri: string | undefined) { if (!res.ok) { throw new Error(`getCommunityPost failed: ${res.status}`) } - const data = (await res.json()) as {post: AppBskyFeedDefs.PostView} + const data = jsonToLex(await res.json()) as { + post: AppBskyFeedDefs.PostView + } return data.post }, enabled: !!uri, diff --git a/src/state/queries/notifications/util.ts b/src/state/queries/notifications/util.ts index d7453b5a8..d56c87b31 100644 --- a/src/state/queries/notifications/util.ts +++ b/src/state/queries/notifications/util.ts @@ -8,6 +8,7 @@ import { type AppBskyNotificationListNotifications, type AtpAgent, hasMutedWord, + jsonToLex, moderateNotification, type ModerationOpts, } from '@atproto/api' @@ -248,7 +249,9 @@ async function fetchSubjects( }) .then(async res => { if (!res.ok) return undefined - const data = (await res.json()) as {post?: AppBskyFeedDefs.PostView} + const data = jsonToLex(await res.json()) as { + post?: AppBskyFeedDefs.PostView + } return data.post }) .catch(() => undefined), -- knotmirror 0.0.1 From 307249d7c568b882db6eae9e781b42b5b2365378 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Tue, 30 Jun 2026 18:48:56 -0400 Subject: [PATCH 35/50] fix(community-posts): refresh peer-mod allowlist (drop Blacksky main, add JD) --- src/lib/constants.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/constants.ts b/src/lib/constants.ts index eba85c1b8..fc14e8b19 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -31,8 +31,8 @@ export const JOINED_THIS_WEEK = 560000 // estimate as of 12/18/24 // Client-side mirror of the appview's PEER_MOD_DIDS allowlist; bump on roster change. export const PEER_MOD_DIDS: Record = { 'did:plc:w4xbfzo7kqfes5zb7r6qv3rw': true, - 'did:plc:kta7dqcqoamo5ixlajxbtjps': true, 'did:plc:v2zokqmhtb4trssgokog5342': true, + 'did:plc:b3ethzamzumrezs4y7pibj6b': true, } export const DISCOVER_DEBUG_DIDS: Record = { -- knotmirror 0.0.1 From a6fc6581486271dde39eb3b7e71af499be49ef7a Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Wed, 1 Jul 2026 17:05:41 -0400 Subject: [PATCH 36/50] fix(community-posts): don't leak Blacksky-only default into replies Replying to a public post with the Blacksky-only default on left the composer stuck in community mode: the toggle is hidden for replies, and the server rejects community replies to public parents (InvalidReply). Replies now inherit the parent audience; the sticky default applies to top-level posts only. --- src/view/com/composer/Composer.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index dab938115..2e33811b0 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -373,7 +373,11 @@ export const ComposePost = ({ initText, initMention, initInteractionSettings: preferences?.postInteractionSettings, - initBlackskyOnly: isForcedBlackskyOnly || blackskyOnlyDefault, + // Replies inherit their parent's audience: forced on for community + // parents, forced off for public parents. The sticky default only + // applies to top-level posts. + initBlackskyOnly: + isForcedBlackskyOnly || (!replyTo && blackskyOnlyDefault), }, createComposerState, ) -- knotmirror 0.0.1 From 26f5d6f51692cd6e28c537bbeee037c181220076 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 2 Jul 2026 14:28:45 -0400 Subject: [PATCH 37/50] fix(community-posts): inherit parent's root when replying to a reply resolveReply read flat replyRoot/replyRootCid fields that the hydrated community PostView no longer carries, so the fallback made every reply's root its own parent. Depth>=2 replies then started detached threads anchored mid-conversation. Derive the root from the parent record's reply.root instead, matching the standard app.bsky reply path. --- src/lib/api/index.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index faa16c921..354a9f4cb 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -441,15 +441,17 @@ async function resolveReply(agent: AtpAgent, replyTo: string) { post?: { uri: string cid: string - replyRoot?: string - replyRootCid?: string + record?: AppBskyFeedPost.Record } } if (data.post) { const parentRef = {uri: data.post.uri, cid: data.post.cid} + // A reply inherits its parent's root; the parent is only the root + // when it is itself a top-level post. + const parentRootRef = data.post.record?.reply?.root const rootRef = - data.post.replyRoot && data.post.replyRootCid - ? {uri: data.post.replyRoot, cid: data.post.replyRootCid} + parentRootRef?.uri && parentRootRef?.cid + ? {uri: parentRootRef.uri, cid: parentRootRef.cid} : parentRef return {root: rootRef, parent: parentRef} } -- knotmirror 0.0.1 From 7c0dcd501cff56edcfb3e1ca9b84bcc616991dbe Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 2 Jul 2026 14:47:05 -0400 Subject: [PATCH 38/50] feat(community-posts): collapse deep threads with View full thread link Community feed now matches the Following feed: a slice whose parent chain skips posts renders root, a connector break with a View full thread link, then the last two replies -- instead of three posts drawn as one unbroken thread. --- src/state/queries/community-feed.ts | 2 + src/view/com/feeds/CommunityFeedPage.tsx | 79 ++++++++++++++++++------ 2 files changed, 63 insertions(+), 18 deletions(-) diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index f107abd7b..f650a2006 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -164,6 +164,7 @@ export interface CommunityFeedSliceItem extends HydratedCommunityPost { export interface CommunityFeedSlice { _reactKey: string items: CommunityFeedSliceItem[] + isIncompleteThread: boolean } /** @@ -217,6 +218,7 @@ export function useCommunityFeedSlices( return { _reactKey: slice._reactKey || `slice-${sliceIdx}`, items, + isIncompleteThread: slice.isIncompleteThread, } }) .filter(slice => slice.items.length > 0) diff --git a/src/view/com/feeds/CommunityFeedPage.tsx b/src/view/com/feeds/CommunityFeedPage.tsx index e6e170a84..dcf8d5396 100644 --- a/src/view/com/feeds/CommunityFeedPage.tsx +++ b/src/view/com/feeds/CommunityFeedPage.tsx @@ -15,6 +15,7 @@ import { import {useSession} from '#/state/session' import {PostFeedItem} from '#/view/com/posts/PostFeedItem' import {isThreadChildAt, isThreadParentAt} from '#/view/com/posts/PostFeed' +import {ViewFullThread} from '#/view/com/posts/ViewFullThread' import {FAB} from '#/view/com/util/fab/FAB' import {List, type ListMethods} from '#/view/com/util/List' import {MainScrollProvider} from '#/view/com/util/MainScrollProvider' @@ -23,6 +24,20 @@ import {useHeaderOffset} from '#/components/hooks/useHeaderOffset' import {Text} from '#/components/Typography' import {IS_NATIVE} from '#/env' +type CommunityFeedRow = + | { + type: 'sliceItem' + slice: CommunityFeedSlice + indexInSlice: number + showReplyTo: boolean + reactKey: string + } + | { + type: 'viewFullThread' + uri: string + reactKey: string + } + export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { const {_} = useLingui() const t = useTheme() @@ -52,15 +67,47 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { const slices = useCommunityFeedSlices(feedItems) const rows = useMemo(() => { - const out: Array<{ - slice: CommunityFeedSlice - indexInSlice: number - reactKey: string - }> = [] + const out: CommunityFeedRow[] = [] slices.forEach(slice => { - slice.items.forEach((item, i) => { - out.push({slice, indexInSlice: i, reactKey: item._reactKey}) - }) + // Deep threads collapse to root + gap + last two, like the Following feed. + if (slice.isIncompleteThread && slice.items.length >= 3) { + const beforeLast = slice.items.length - 2 + const last = slice.items.length - 1 + out.push({ + type: 'sliceItem', + slice, + indexInSlice: 0, + showReplyTo: false, + reactKey: slice.items[0]._reactKey, + }) + out.push({ + type: 'viewFullThread', + uri: slice.items[0].uri, + reactKey: `${slice._reactKey}-viewFullThread`, + }) + for (const i of [beforeLast, last]) { + out.push({ + type: 'sliceItem', + slice, + indexInSlice: i, + showReplyTo: + i === beforeLast && + slice.items[i].parentAuthor?.did !== + slice.items[i].post.author.did, + reactKey: slice.items[i]._reactKey, + }) + } + } else { + slice.items.forEach((item, i) => { + out.push({ + type: 'sliceItem', + slice, + indexInSlice: i, + showReplyTo: i === 0, + reactKey: item._reactKey, + }) + }) + } }) return out }, [slices]) @@ -94,15 +141,11 @@ export function CommunityFeedPage({isPageFocused}: {isPageFocused: boolean}) { }, [scrollElRef, headerOffset, refetch]) const renderItem = useCallback( - ({ - item, - index, - }: ListRenderItemInfo<{ - slice: CommunityFeedSlice - indexInSlice: number - reactKey: string - }>) => { - const {slice, indexInSlice} = item + ({item, index}: ListRenderItemInfo) => { + if (item.type === 'viewFullThread') { + return + } + const {slice, indexInSlice, showReplyTo} = item const sliceItem = slice.items[indexInSlice] return ( Date: Thu, 2 Jul 2026 14:52:29 -0400 Subject: [PATCH 39/50] feat(community-posts): adopt Following-feed tuner stack on community timeline Replies resurface a thread only when the root author continues it; other people's replies stay in the thread view. Adds removeOrphans, hideReposts/hideReplies/hideQuotePosts preferences, dedupThreads, and removeMutedThreads -- the same stack useFeedTuners builds for the Following feed. followedRepliesOnly is replaced by the root-author rule since every community member is effectively followed. --- src/state/queries/community-feed.ts | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index f650a2006..633d5c12f 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -18,6 +18,7 @@ import { import {communityXrpc} from '#/lib/api/community' import {FeedTuner} from '#/lib/api/feed-manip' import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {usePreferencesQuery} from '#/state/queries/preferences' import { didOrHandleUriMatches, embedViewRecordToPostView, @@ -196,11 +197,34 @@ export function useCommunityFeedSlices( feedItems: AppBskyFeedDefs.FeedViewPost[], ): CommunityFeedSlice[] { const moderationOpts = useModerationOpts() + const {data: preferences} = usePreferencesQuery() return useMemo(() => { if (!moderationOpts) return [] - const tuner = new FeedTuner([]) - const raw = tuner.tune(feedItems) + // A reply only resurfaces its thread when the root author is + // continuing their own thread; other people's replies stay in the + // thread view. Stands in for followedRepliesOnly, which would pass + // everything here since the whole community is "followed". + const surfaced = feedItems.filter(item => { + const reply = (item.post.record as AppBskyFeedPost.Record)?.reply + if (!reply?.root?.uri) return true + return new AtUri(reply.root.uri).host === item.post.author.did + }) + // Same tuner stack as the Following feed (see useFeedTuners). + const tunerFns = [FeedTuner.removeOrphans] + if (preferences?.feedViewPrefs.hideReposts) { + tunerFns.push(FeedTuner.removeReposts) + } + if (preferences?.feedViewPrefs.hideReplies) { + tunerFns.push(FeedTuner.removeReplies) + } + if (preferences?.feedViewPrefs.hideQuotePosts) { + tunerFns.push(FeedTuner.removeQuotePosts) + } + tunerFns.push(FeedTuner.dedupThreads) + tunerFns.push(FeedTuner.removeMutedThreads) + const tuner = new FeedTuner(tunerFns) + const raw = tuner.tune(surfaced) return raw .map((slice, sliceIdx) => { -- knotmirror 0.0.1 From aa84b3392f3bed04c141512e4d1f28381edc6f7c Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 2 Jul 2026 16:15:13 -0400 Subject: [PATCH 40/50] fix(community-posts): remove Community tab from profile pages Unrequested surface; community posts belong to the home Community tab. The profile section also still used the pre-slicer rendering with the known reply-hierarchy issues. --- src/view/screens/Profile.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/view/screens/Profile.tsx b/src/view/screens/Profile.tsx index 517cce1d1..0bfad9dd4 100644 --- a/src/view/screens/Profile.tsx +++ b/src/view/screens/Profile.tsx @@ -243,7 +243,8 @@ function ProfileScreenLoaded({ const hasLabeler = !!profile.associated?.labeler const showFiltersTab = hasLabeler const showPostsTab = true - const showCommunityTab = hasSession + // Community posts surface on the home Community tab only, not profiles. + const showCommunityTab = false const showRepliesTab = hasSession const showMediaTab = !hasLabeler const showVideosTab = !hasLabeler -- knotmirror 0.0.1 From b610b4319cd2eacceb4088380f9f00d642dca182 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 2 Jul 2026 17:11:34 -0400 Subject: [PATCH 41/50] feat(community-posts): hydration-driven actor badges, drop PEER_MOD_DIDS Badge slugs now arrive on hydrated profile views from the appview (single source of truth). getActorBadges/hasBadge read the extra field; the peer-mod glyph gates on the peer-moderator badge instead of the hardcoded client allowlist, which is deleted. Unknown slugs render nothing until artwork ships. --- src/components/PeerModBadge.tsx | 6 ++--- src/components/ProfileBadges.tsx | 6 ++--- src/lib/badges.ts | 28 +++++++++++++++++++++++ src/lib/constants.ts | 7 ------ src/state/queries/peer-mod-permissions.ts | 8 +------ 5 files changed, 35 insertions(+), 20 deletions(-) create mode 100644 src/lib/badges.ts diff --git a/src/components/PeerModBadge.tsx b/src/components/PeerModBadge.tsx index a2e6fba74..df36d9873 100644 --- a/src/components/PeerModBadge.tsx +++ b/src/components/PeerModBadge.tsx @@ -3,7 +3,7 @@ import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' -import {isPeerModDid} from '#/state/queries/peer-mod-permissions' +import {hasBadge, PEER_MOD_BADGE} from '#/lib/badges' import {atoms as a, useTheme} from '#/alf' import {Button} from '#/components/Button' import * as Dialog from '#/components/Dialog' @@ -19,7 +19,7 @@ export function PeerModBadge({ width: number }) { const t = useTheme() - if (!isPeerModDid(profile.did)) return null + if (!hasBadge(profile, PEER_MOD_BADGE)) return null return ( @@ -37,7 +37,7 @@ export function PeerModBadgeButton({ const t = useTheme() const {_} = useLingui() const control = Dialog.useDialogControl() - if (!isPeerModDid(profile.did)) return null + if (!hasBadge(profile, PEER_MOD_BADGE)) return null return ( <> - - - ) -} - -function PeerModeratorDialog({control}: {control: Dialog.DialogControlProps}) { - const t = useTheme() - return ( - - - - - - - - Blacksky Peer Moderator - - - - - This account is a Blacksky community peer moderator. Peer - moderators help keep the community safe by applying labels and - reviewing reports alongside the core Blacksky team. - - - - - - ) -} diff --git a/src/components/ProfileBadges.tsx b/src/components/ProfileBadges.tsx index 7b4094b5b..cfe820cc0 100644 --- a/src/components/ProfileBadges.tsx +++ b/src/components/ProfileBadges.tsx @@ -4,7 +4,7 @@ import {useProfileShadow} from '#/state/cache/profile-shadow' import {atoms as a, useAlf, type ViewStyleProp} from '#/alf' import {useNativeFontScale} from '#/alf/util/dimensions' import {BotBadge, BotBadgeButton, isBotAccount} from '#/components/BotBadge' -import {PeerModBadge, PeerModBadgeButton} from '#/components/PeerModBadge' +import {ActorBadgeButtons, ActorBadges} from '#/components/badges' import {hasKnownBadge} from '#/lib/badges' import {useSimpleVerificationState} from '#/components/verification' import {VerificationCheck} from '#/components/verification/VerificationCheck' @@ -29,7 +29,7 @@ const botIconSizes: Record = { xl: 23, } as const -const peerModIconSizes: Record = { +const badgeIconSizes: Record = { xs: 12, sm: 14, md: 16, @@ -69,7 +69,7 @@ export function ProfileBadges({ const verificationIconWidth = verificationIconSizes[size] * scaleMultiplier const botIconWidth = botIconSizes[size] * scaleMultiplier - const peerModIconWidth = peerModIconSizes[size] * scaleMultiplier + const badgeIconWidth = badgeIconSizes[size] * scaleMultiplier return ( - + ) : ( @@ -96,7 +96,7 @@ export function ProfileBadges({ width={verificationIconWidth} /> )} - + )} diff --git a/src/components/badges/art.tsx b/src/components/badges/art.tsx new file mode 100644 index 000000000..bae770cab --- /dev/null +++ b/src/components/badges/art.tsx @@ -0,0 +1,139 @@ +// Generated from Blacksky Branding/Badges/Light Purple/SVG — do not hand-edit shapes. +import Svg, {Defs, LinearGradient, Path, Rect, Stop} from 'react-native-svg' + +export type BadgeCardProps = {width: number} + +export function PeerModeratorCard({width}: BadgeCardProps) { + return ( + + + + + + + + + + + + ) +} + +export function CommunityBuilderCard({width}: BadgeCardProps) { + return ( + + + + + + + + + + + + + + + ) +} + +export function FinancialSupporter1Card({width}: BadgeCardProps) { + return ( + + + + + + + + + + + + + + + + + ) +} + +export function FinancialSupporter2Card({width}: BadgeCardProps) { + return ( + + + + + + + + + + + + + + + + + + + + ) +} + +export function FinancialSupporter3Card({width}: BadgeCardProps) { + return ( + + + + + + + + + + + + + + + + + + + + + + + ) +} + +export function TechSupportCard({width}: BadgeCardProps) { + return ( + + + + + + + + + + + + + + + + + + + + + + + + ) +} diff --git a/src/components/badges/index.tsx b/src/components/badges/index.tsx new file mode 100644 index 000000000..e57645727 --- /dev/null +++ b/src/components/badges/index.tsx @@ -0,0 +1,166 @@ +import {View} from 'react-native' +import {type MessageDescriptor} from '@lingui/core' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' + +import {getActorBadges, KNOWN_BADGES} from '#/lib/badges' +import {atoms as a, useTheme} from '#/alf' +import {Button} from '#/components/Button' +import * as Dialog from '#/components/Dialog' +import {Text} from '#/components/Typography' +import type * as bsky from '#/types/bsky' +import { + type BadgeCardProps, + CommunityBuilderCard, + FinancialSupporter1Card, + FinancialSupporter2Card, + FinancialSupporter3Card, + PeerModeratorCard, + TechSupportCard, +} from './art' + +type BadgeDef = { + label: MessageDescriptor + description: MessageDescriptor + Card: (props: BadgeCardProps) => React.ReactNode +} + +export const BADGE_REGISTRY: Record = { + 'peer-moderator': { + label: msg`Peer Moderator`, + description: msg`This account is a Blacksky community peer moderator. Peer moderators help keep the community safe by applying labels and reviewing reports alongside the core Blacksky team.`, + Card: PeerModeratorCard, + }, + 'community-builder': { + label: msg`Community Builder`, + description: msg`This account has made outstanding contributions to building the Blacksky community.`, + Card: CommunityBuilderCard, + }, + 'financial-supporter-1': { + label: msg`Financial Supporter`, + description: msg`This account financially supports Blacksky, helping keep the community independent and thriving.`, + Card: FinancialSupporter1Card, + }, + 'financial-supporter-2': { + label: msg`Financial Supporter`, + description: msg`This account financially supports Blacksky, helping keep the community independent and thriving.`, + Card: FinancialSupporter2Card, + }, + 'financial-supporter-3': { + label: msg`Financial Supporter`, + description: msg`This account financially supports Blacksky, helping keep the community independent and thriving.`, + Card: FinancialSupporter3Card, + }, + 'tech-support': { + label: msg`Tech Support`, + description: msg`This account provides technical support to the Blacksky community.`, + Card: TechSupportCard, + }, +} + +function knownBadgesFor(profile: bsky.profile.AnyProfileView): string[] { + return getActorBadges(profile).filter(b => KNOWN_BADGES.has(b)) +} + +export function ActorBadges({ + profile, + width, +}: { + profile: bsky.profile.AnyProfileView + width: number +}) { + const badges = knownBadgesFor(profile) + if (badges.length === 0) return null + return ( + <> + {badges.map(slug => { + const {Card} = BADGE_REGISTRY[slug] + return ( + + + + ) + })} + + ) +} + +export function ActorBadgeButtons({ + profile, + width, +}: { + profile: bsky.profile.AnyProfileView + width: number +}) { + const badges = knownBadgesFor(profile) + if (badges.length === 0) return null + return ( + <> + {badges.map(slug => ( + + ))} + + ) +} + +function BadgeButton({slug, width}: {slug: string; width: number}) { + const {_} = useLingui() + const control = Dialog.useDialogControl() + const {label, Card} = BADGE_REGISTRY[slug] + return ( + <> + + + + ) +} + +function BadgeDialog({ + control, + slug, +}: { + control: Dialog.DialogControlProps + slug: string +}) { + const t = useTheme() + const {_} = useLingui() + const {label, description, Card} = BADGE_REGISTRY[slug] + return ( + + + + + + + {_(label)} + + + {_(description)} + + + + + ) +} diff --git a/src/lib/badges.ts b/src/lib/badges.ts index 335c1c35d..b769b3459 100644 --- a/src/lib/badges.ts +++ b/src/lib/badges.ts @@ -21,7 +21,14 @@ export function hasBadge(profile: ProfileLike, badge: string): boolean { } // Badges the client has artwork for; unknown slugs render nothing. -export const KNOWN_BADGES = new Set([PEER_MOD_BADGE]) +export const KNOWN_BADGES = new Set([ + PEER_MOD_BADGE, + 'community-builder', + 'financial-supporter-1', + 'financial-supporter-2', + 'financial-supporter-3', + 'tech-support', +]) export function hasKnownBadge(profile: ProfileLike): boolean { return getActorBadges(profile).some(b => KNOWN_BADGES.has(b)) -- knotmirror 0.0.1 From 2037376e6e699cc39eecd03e79e08ea40a058a95 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 2 Jul 2026 19:01:46 -0400 Subject: [PATCH 43/50] fix(community-posts): hide Community tab and composer toggle from non-members The Community pinned-feed stub was injected for every session; members of the gate are now checked via community.blacksky.actor.checkMembership before injection, so non-members (and logged-out users, already excluded) never see the tab. The Blacksky-only composer toggle is likewise hidden and never defaults on for non-members. Also fixes Mask/G elements in the tech-support badge card. --- src/components/badges/art.tsx | 10 +++--- src/state/queries/community-membership.ts | 37 +++++++++++++++++++++++ src/state/queries/feed.ts | 10 ++++-- src/view/com/composer/Composer.tsx | 10 ++++-- 4 files changed, 56 insertions(+), 11 deletions(-) create mode 100644 src/state/queries/community-membership.ts diff --git a/src/components/badges/art.tsx b/src/components/badges/art.tsx index bae770cab..dcec8861d 100644 --- a/src/components/badges/art.tsx +++ b/src/components/badges/art.tsx @@ -1,5 +1,5 @@ // Generated from Blacksky Branding/Badges/Light Purple/SVG — do not hand-edit shapes. -import Svg, {Defs, LinearGradient, Path, Rect, Stop} from 'react-native-svg' +import Svg, {Defs, G, LinearGradient, Mask, Path, Rect, Stop} from 'react-native-svg' export type BadgeCardProps = {width: number} @@ -115,10 +115,10 @@ export function TechSupportCard({width}: BadgeCardProps) { - + - - + + @@ -127,7 +127,7 @@ export function TechSupportCard({width}: BadgeCardProps) { - + diff --git a/src/state/queries/community-membership.ts b/src/state/queries/community-membership.ts new file mode 100644 index 000000000..1974843c0 --- /dev/null +++ b/src/state/queries/community-membership.ts @@ -0,0 +1,37 @@ +import {type BskyAgent} from '@atproto/api' +import {useQuery} from '@tanstack/react-query' + +import {communityXrpc} from '#/lib/api/community' +import {useAgent, useSession} from '#/state/session' + +const CHECK_MEMBERSHIP_METHOD = 'community.blacksky.actor.checkMembership' + +const RQKEY_ROOT = 'community-membership' +export const communityMembershipRQKey = (did: string | undefined) => [ + RQKEY_ROOT, + did ?? '', +] + +export async function fetchCommunityMembership( + agent: BskyAgent, +): Promise { + try { + const res = await communityXrpc(agent, CHECK_MEMBERSHIP_METHOD) + if (!res.ok) return false + const data = (await res.json()) as {isMember?: boolean} + return !!data.isMember + } catch { + return false + } +} + +export function useCommunityMembership() { + const agent = useAgent() + const {currentAccount} = useSession() + return useQuery({ + queryKey: communityMembershipRQKey(currentAccount?.did), + enabled: !!currentAccount?.did, + staleTime: 5 * 60 * 1000, + queryFn: () => fetchCommunityMembership(agent), + }) +} diff --git a/src/state/queries/feed.ts b/src/state/queries/feed.ts index c55fd7d0e..f1e811ed0 100644 --- a/src/state/queries/feed.ts +++ b/src/state/queries/feed.ts @@ -27,6 +27,7 @@ import {sanitizeDisplayName} from '#/lib/strings/display-names' import {sanitizeHandle} from '#/lib/strings/handles' import {GCTIME, STALE} from '#/state/queries' import {RQKEY as listQueryKey} from '#/state/queries/list' +import {fetchCommunityMembership} from '#/state/queries/community-membership' import {usePreferencesQuery} from '#/state/queries/preferences' import {createQueryKey} from '#/state/queries/util' import {useAgent, useSession} from '#/state/session' @@ -661,9 +662,12 @@ export function usePinnedFeedsInfos() { }) } } - // Inject Community feed after the first item (Following) - const insertIndex = Math.min(1, result.length) - result.splice(insertIndex, 0, COMMUNITY_FEED_STUB) + // Inject Community feed after the first item (Following), members only + const isMember = await fetchCommunityMembership(agent) + if (isMember) { + const insertIndex = Math.min(1, result.length) + result.splice(insertIndex, 0, COMMUNITY_FEED_STUB) + } return result }, }) diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 2e33811b0..1eacac28c 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -100,6 +100,7 @@ import { import {usePreferencesQuery} from '#/state/queries/preferences' import {useProfileQuery} from '#/state/queries/profile' import {resolveLinkQueryOptions} from '#/state/queries/resolve-link' +import {useCommunityMembership} from '#/state/queries/community-membership' import {useAgent, useSession} from '#/state/session' import {useComposerControls} from '#/state/shell/composer' import {type ComposerOpts, type OnPostSuccessData} from '#/state/shell/composer' @@ -358,6 +359,7 @@ export const ComposePost = ({ const blackskyOnlyDefault = useBlackskyOnlyDefault() const setBlackskyOnlyDefault = useSetBlackskyOnlyDefault() + const {data: isCommunityMember = false} = useCommunityMembership() // Force Blacksky-Only when the thread targets a community post — replies // and quotes of a community post can only land in the community. @@ -375,9 +377,10 @@ export const ComposePost = ({ initInteractionSettings: preferences?.postInteractionSettings, // Replies inherit their parent's audience: forced on for community // parents, forced off for public parents. The sticky default only - // applies to top-level posts. + // applies to top-level posts, and only for community members. initBlackskyOnly: - isForcedBlackskyOnly || (!replyTo && blackskyOnlyDefault), + isForcedBlackskyOnly || + (!replyTo && isCommunityMember && blackskyOnlyDefault), }, createComposerState, ) @@ -1987,6 +1990,7 @@ function ComposerPills({ }) { const t = useTheme() const {t: l} = useLingui() + const {data: isCommunityMember = false} = useCommunityMembership() const media = post.embed.media const hasMedia = media?.type === 'images' || @@ -2025,7 +2029,7 @@ function ComposerPills({ style={bottomBarAnimatedStyle} /> )} - {isReply && !isForcedBlackskyOnly ? null : ( + {!isCommunityMember || (isReply && !isForcedBlackskyOnly) ? null : ( Date: Thu, 2 Jul 2026 19:08:36 -0400 Subject: [PATCH 44/50] fix(community-posts): make community post deletes idempotent and resilient The delete mutation threw when the appview returned PostNotFound (post already deleted by a prior partially-failed attempt) and when the PDS stub delete failed after a successful appview delete. Both stranded a completed delete behind an error toast with the post still rendered. Already-gone now counts as success and the stub delete is best-effort, so the tombstone shadow and success toast fire like the standard path. --- src/state/queries/post.ts | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/state/queries/post.ts b/src/state/queries/post.ts index feb9659c9..fed8ddcf4 100644 --- a/src/state/queries/post.ts +++ b/src/state/queries/post.ts @@ -364,16 +364,23 @@ export function usePostDeleteMutation() { 'community.blacksky.feed.deletePost', {body: {uri}}, ) + // A post already gone from the appview is a successful outcome — a + // retry after a partial failure must not surface as an error. if (!res.ok) { - const err = await res.json().catch(() => ({})) - throw new Error(err.message || `deletePost failed: ${res.status}`) + const err = (await res.json().catch(() => ({}))) as {error?: string} + if (err.error !== 'PostNotFound') { + throw new Error(err.error || `deletePost failed: ${res.status}`) + } } - // Also delete the stub record from PDS - await agent.com.atproto.repo.deleteRecord({ - repo: parsedUri.hostname, - collection: COMMUNITY_POST_COLLECTION, - rkey: parsedUri.rkey, - }) + // Best-effort: the appview is the source of truth for community + // post visibility; a failed stub delete must not strand the delete. + await agent.com.atproto.repo + .deleteRecord({ + repo: parsedUri.hostname, + collection: COMMUNITY_POST_COLLECTION, + rkey: parsedUri.rkey, + }) + .catch(() => {}) } else { await agent.deletePost(uri) } -- knotmirror 0.0.1 From cee48ecf654fc1976b1aa1771c233e18b865bee4 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 2 Jul 2026 19:30:33 -0400 Subject: [PATCH 45/50] fix(community-posts): reliably delete both the stub and appview copy Ordered the two deletes stub-first then appview-copy, both idempotent (deleteRecord no-ops on a missing record, appview PostNotFound counts as success). A failure now surfaces for retry instead of silently orphaning the PDS stub, and a retry converges to both being gone. --- src/state/queries/post.ts | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/state/queries/post.ts b/src/state/queries/post.ts index fed8ddcf4..7b936299a 100644 --- a/src/state/queries/post.ts +++ b/src/state/queries/post.ts @@ -358,29 +358,26 @@ export function usePostDeleteMutation() { mutationFn: async ({uri}) => { const parsedUri = new AtUri(uri) if (parsedUri.collection === COMMUNITY_POST_COLLECTION) { - // Delete from community DB via appview + // Both deletes are idempotent, so ordering is safe and a retry after + // any partial failure converges to both being gone. Remove the PDS + // stub first (deleteRecord is a no-op if already absent)... + await agent.com.atproto.repo.deleteRecord({ + repo: parsedUri.hostname, + collection: COMMUNITY_POST_COLLECTION, + rkey: parsedUri.rkey, + }) + // ...then the appview copy, treating already-gone as success. const res = await communityXrpc( agent, 'community.blacksky.feed.deletePost', {body: {uri}}, ) - // A post already gone from the appview is a successful outcome — a - // retry after a partial failure must not surface as an error. if (!res.ok) { const err = (await res.json().catch(() => ({}))) as {error?: string} if (err.error !== 'PostNotFound') { throw new Error(err.error || `deletePost failed: ${res.status}`) } } - // Best-effort: the appview is the source of truth for community - // post visibility; a failed stub delete must not strand the delete. - await agent.com.atproto.repo - .deleteRecord({ - repo: parsedUri.hostname, - collection: COMMUNITY_POST_COLLECTION, - rkey: parsedUri.rkey, - }) - .catch(() => {}) } else { await agent.deletePost(uri) } -- knotmirror 0.0.1 From cbeee1d27bd380f885de0fd22fc638c3579ae292 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Thu, 2 Jul 2026 19:41:40 -0400 Subject: [PATCH 46/50] fix(community-posts): surface Community tab reactively on membership change The membership check lived inside the pinned-feeds queryFn, whose result is cached and persisted indefinitely -- anyone added to the gate after their first load never saw the tab. Membership now applies as a select over the cached query, so the tab appears within the membership query's staleTime without refetching pinned feeds. --- src/state/queries/feed.ts | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/state/queries/feed.ts b/src/state/queries/feed.ts index f1e811ed0..04acba589 100644 --- a/src/state/queries/feed.ts +++ b/src/state/queries/feed.ts @@ -27,7 +27,7 @@ import {sanitizeDisplayName} from '#/lib/strings/display-names' import {sanitizeHandle} from '#/lib/strings/handles' import {GCTIME, STALE} from '#/state/queries' import {RQKEY as listQueryKey} from '#/state/queries/list' -import {fetchCommunityMembership} from '#/state/queries/community-membership' +import {useCommunityMembership} from '#/state/queries/community-membership' import {usePreferencesQuery} from '#/state/queries/preferences' import {createQueryKey} from '#/state/queries/util' import {useAgent, useSession} from '#/state/session' @@ -581,6 +581,19 @@ export function usePinnedFeedsInfos() { const agent = useAgent() const {data: preferences, isLoading: isLoadingPrefs} = usePreferencesQuery() const pinnedItems = preferences?.savedFeeds.filter(feed => feed.pinned) ?? [] + const {data: isCommunityMember = false} = useCommunityMembership() + + // The query itself is cached and persisted indefinitely; membership is + // applied as a derived view so gate changes surface without a refetch. + const injectCommunity = useCallback( + (feeds: SavedFeedSourceInfo[]) => { + if (!isCommunityMember) return feeds + const result = [...feeds] + result.splice(Math.min(1, result.length), 0, COMMUNITY_FEED_STUB) + return result + }, + [isCommunityMember], + ) return useQuery({ queryKey: createPinnedFeedInfosQueryKey( @@ -590,6 +603,7 @@ export function usePinnedFeedsInfos() { gcTime: GCTIME.INFINITY, staleTime: STALE.INFINITY, enabled: !isLoadingPrefs, + select: injectCommunity, queryFn: async () => { if (!hasSession) { return [PWI_DISCOVER_FEED_STUB] @@ -662,12 +676,6 @@ export function usePinnedFeedsInfos() { }) } } - // Inject Community feed after the first item (Following), members only - const isMember = await fetchCommunityMembership(agent) - if (isMember) { - const insertIndex = Math.min(1, result.length) - result.splice(insertIndex, 0, COMMUNITY_FEED_STUB) - } return result }, }) -- knotmirror 0.0.1 From b51c22be4ec359d9de36d05989a941bcae95e1cb Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 3 Jul 2026 08:49:02 -0400 Subject: [PATCH 47/50] fix(community-posts): share-link encoding and like feedback on reply rows toShareUrl percent-encoded the ?collection= query into the path, producing links that failed rkey validation; parse as a relative URL and tolerate already-shared encoded links in the PostThread screen. The community feed post-shadow finder now yields reply parent/root rows so likes on them animate and count like the Following feed. --- src/lib/strings/url-helpers.ts | 6 +++--- src/state/queries/community-feed.ts | 15 ++++++++++++++- src/view/screens/PostThread.tsx | 11 ++++++++++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/lib/strings/url-helpers.ts b/src/lib/strings/url-helpers.ts index 2fa4118e7..9fbc09521 100644 --- a/src/lib/strings/url-helpers.ts +++ b/src/lib/strings/url-helpers.ts @@ -80,9 +80,9 @@ export function toShortUrl(url: string): string { export function toShareUrl(url: string): string { if (!url.startsWith('https')) { - const urlp = new URL(BSKY_APP_HOST) - urlp.pathname = url - url = urlp.toString() + // Parse as a relative URL so a query string survives; assigning to + // pathname percent-encodes the '?' into the path. + url = new URL(url, BSKY_APP_HOST).toString() } return url } diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index 633d5c12f..4c9bb0d4c 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -1,6 +1,6 @@ import {useMemo} from 'react' import { - type AppBskyFeedDefs, + AppBskyFeedDefs, type AppBskyFeedPost, AtUri, jsonToLex, @@ -290,6 +290,19 @@ export function* findAllPostsInQueryData( if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { yield embedViewRecordToPostView(quotedPost) } + + // Reply-context rows render in slices too; without these, likes on + // a parent/root row never reach the shadow cache. + if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { + if (didOrHandleUriMatches(atUri, item.reply.parent)) { + yield item.reply.parent + } + } + if (AppBskyFeedDefs.isPostView(item.reply?.root)) { + if (didOrHandleUriMatches(atUri, item.reply.root)) { + yield item.reply.root + } + } } } } diff --git a/src/view/screens/PostThread.tsx b/src/view/screens/PostThread.tsx index ab8c659cd..c4ba6b7d3 100644 --- a/src/view/screens/PostThread.tsx +++ b/src/view/screens/PostThread.tsx @@ -8,7 +8,16 @@ import * as Layout from '#/components/Layout' type Props = NativeStackScreenProps export function PostThreadScreen({route}: Props) { - const {name, rkey, collection} = route.params + const {name, rkey: rawRkey, collection: rawCollection} = route.params + // Old share links percent-encoded '?collection=...' into the rkey segment. + let rkey = decodeURIComponent(rawRkey) + let collection = rawCollection + const qIndex = rkey.indexOf('?') + if (qIndex !== -1) { + const qs = new URLSearchParams(rkey.slice(qIndex + 1)) + collection = collection || qs.get('collection') || undefined + rkey = rkey.slice(0, qIndex) + } const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) return ( -- knotmirror 0.0.1 From 9ef531b44fbdc6d25c0aa0d66a49ecc44fbf7916 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 3 Jul 2026 09:26:58 -0400 Subject: [PATCH 48/50] feat(community-posts): interaction gates + liked-by/reposted-by/quotes for community posts The composer's threadgate and postgate settings now ride submitPost as community.blacksky rule types instead of being silently dropped, and the blocked/muted-author filter applies to the community timeline. Post stat pages (liked-by, reposted-by, quotes) carry the community collection through their links and honor it when building the record uri. --- src/lib/api/index.ts | 21 +++++++++++++++ src/lib/routes/types.ts | 6 ++--- src/screens/Post/PostLikedBy.tsx | 4 +-- src/screens/Post/PostQuotes.tsx | 4 +-- src/screens/Post/PostRepostedBy.tsx | 4 +-- .../components/ThreadItemAnchor.tsx | 27 ++++++++++--------- src/state/queries/community-feed.ts | 9 +++++++ 7 files changed, 53 insertions(+), 22 deletions(-) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 354a9f4cb..9a36f3d25 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -318,6 +318,27 @@ async function postCommunity( if (labels) { submitBody.labels = labels } + // Interaction gates: root posts only for threadgates, community $types. + if (!reply && thread.threadgate.some(tg => tg.type !== 'everybody')) { + submitBody.threadgateAllow = ( + threadgateAllowUISettingToAllowRecordValue(thread.threadgate) ?? [] + ).map(rule => ({ + ...rule, + $type: String(rule.$type).replace( + 'app.bsky.feed.threadgate', + 'community.blacksky.feed.threadgate', + ), + })) + } + if (thread.postgate.embeddingRules?.length) { + submitBody.embeddingRules = thread.postgate.embeddingRules.map(rule => ({ + ...rule, + $type: (rule.$type as string).replace( + 'app.bsky.feed.postgate', + 'community.blacksky.feed.postgate', + ), + })) + } try { const submitRes = await communityXrpc( diff --git a/src/lib/routes/types.ts b/src/lib/routes/types.ts index ff036627d..e66175004 100644 --- a/src/lib/routes/types.ts +++ b/src/lib/routes/types.ts @@ -23,9 +23,9 @@ export type CommonNavigatorParams = { ProfileSearch: {name: string; q?: string} ProfileList: {name: string; rkey: string} PostThread: {name: string; rkey: string; collection?: string} - PostLikedBy: {name: string; rkey: string} - PostRepostedBy: {name: string; rkey: string} - PostQuotes: {name: string; rkey: string} + PostLikedBy: {name: string; rkey: string; collection?: string} + PostRepostedBy: {name: string; rkey: string; collection?: string} + PostQuotes: {name: string; rkey: string; collection?: string} ProfileFeed: { name: string rkey: string diff --git a/src/screens/Post/PostLikedBy.tsx b/src/screens/Post/PostLikedBy.tsx index 2716e6318..c44047a90 100644 --- a/src/screens/Post/PostLikedBy.tsx +++ b/src/screens/Post/PostLikedBy.tsx @@ -11,8 +11,8 @@ import * as Layout from '#/components/Layout' type Props = NativeStackScreenProps export const PostLikedByScreen = ({route}: Props) => { - const {name, rkey} = route.params - const uri = makeRecordUri(name, 'app.bsky.feed.post', rkey) + const {name, rkey, collection} = route.params + const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) let likeCount diff --git a/src/screens/Post/PostQuotes.tsx b/src/screens/Post/PostQuotes.tsx index b44028f6f..7328c6ad9 100644 --- a/src/screens/Post/PostQuotes.tsx +++ b/src/screens/Post/PostQuotes.tsx @@ -11,8 +11,8 @@ import * as Layout from '#/components/Layout' type Props = NativeStackScreenProps export const PostQuotesScreen = ({route}: Props) => { - const {name, rkey} = route.params - const uri = makeRecordUri(name, 'app.bsky.feed.post', rkey) + const {name, rkey, collection} = route.params + const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) let quoteCount diff --git a/src/screens/Post/PostRepostedBy.tsx b/src/screens/Post/PostRepostedBy.tsx index 07082af0b..40a7beb7e 100644 --- a/src/screens/Post/PostRepostedBy.tsx +++ b/src/screens/Post/PostRepostedBy.tsx @@ -11,8 +11,8 @@ import * as Layout from '#/components/Layout' type Props = NativeStackScreenProps export const PostRepostedByScreen = ({route}: Props) => { - const {name, rkey} = route.params - const uri = makeRecordUri(name, 'app.bsky.feed.post', rkey) + const {name, rkey, collection} = route.params + const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) let quoteCount diff --git a/src/screens/PostThread/components/ThreadItemAnchor.tsx b/src/screens/PostThread/components/ThreadItemAnchor.tsx index bb2c19594..6e178ad3c 100644 --- a/src/screens/PostThread/components/ThreadItemAnchor.tsx +++ b/src/screens/PostThread/components/ThreadItemAnchor.tsx @@ -1,4 +1,4 @@ -import {memo, useMemo} from 'react' +import {useCallback, memo, useMemo} from 'react' import {Text as RNText, View} from 'react-native' import { AppBskyFeedDefs, @@ -200,18 +200,19 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ const authorHref = makeProfileLink(post.author) const isThreadAuthor = getThreadAuthor(post, record) === currentAccount?.did - const likesHref = useMemo(() => { - const urip = new AtUri(post.uri) - return makeProfileLink(post.author, 'post', urip.rkey, 'liked-by') - }, [post.uri, post.author]) - const repostsHref = useMemo(() => { - const urip = new AtUri(post.uri) - return makeProfileLink(post.author, 'post', urip.rkey, 'reposted-by') - }, [post.uri, post.author]) - const quotesHref = useMemo(() => { - const urip = new AtUri(post.uri) - return makeProfileLink(post.author, 'post', urip.rkey, 'quotes') - }, [post.uri, post.author]) + const statHref = useCallback( + (suffix: string) => { + const urip = new AtUri(post.uri) + const link = makeProfileLink(post.author, 'post', urip.rkey, suffix) + return urip.collection === 'community.blacksky.feed.post' + ? `${link}?collection=${urip.collection}` + : link + }, + [post.uri, post.author], + ) + const likesHref = useMemo(() => statHref('liked-by'), [statHref]) + const repostsHref = useMemo(() => statHref('reposted-by'), [statHref]) + const quotesHref = useMemo(() => statHref('quotes'), [statHref]) const threadgateHiddenReplies = useMergedThreadgateHiddenReplies({ threadgateRecord, diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index 4c9bb0d4c..544306bf0 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -206,6 +206,15 @@ export function useCommunityFeedSlices( // thread view. Stands in for followedRepliesOnly, which would pass // everything here since the whole community is "followed". const surfaced = feedItems.filter(item => { + // Blocked/muted authors never surface, same as the Following feed. + const authorViewer = item.post.author.viewer + if ( + authorViewer?.blocking || + authorViewer?.blockedBy || + authorViewer?.muted + ) { + return false + } const reply = (item.post.record as AppBskyFeedPost.Record)?.reply if (!reply?.root?.uri) return true return new AtUri(reply.root.uri).host === item.post.author.did -- knotmirror 0.0.1 From 6674942a3b016fdb254c4c89ed4c235bd2512b11 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Fri, 3 Jul 2026 10:49:03 -0400 Subject: [PATCH 49/50] fix(community-posts): refuse public posts that embed a community post Belt-and-suspenders on top of the existing routing: a public post whose embed quotes a community post is rejected rather than published, keeping gated content from surfacing through a public wrapper. --- src/lib/api/index.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 9a36f3d25..2d2cf6c97 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -79,6 +79,17 @@ export async function post( return postCommunity(agent, queryClient, opts) } + // A public post must never carry a community post in its embed; the + // routing above sends those to postCommunity, so reaching here with one + // is a bug we refuse rather than leak community content publicly. + if ( + thread.posts.some(p => + p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION), + ) + ) { + throw new Error('Public posts cannot embed a community post') + } + let replyPromise: | Promise | AppBskyFeedPost.Record['reply'] -- knotmirror 0.0.1 From 7fc3794865e99af8a6f4479db8f7c1acd89dedc1 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Mon, 6 Jul 2026 12:01:53 -0400 Subject: [PATCH 50/50] fix(community-posts): drop blocked and hidden posts from the community feed The slicer computed moderation decisions but never acted on them, so blocked-author threads rendered a 'User Blocked' card and 'hide for me' posts stayed as a collapsed toggle. Now a thread containing any blocked/blocking author is dropped whole (nuclear block) and items the moderation engine filters from list contexts (hidden-for-me, muted) are removed, matching the rest of the app. --- src/state/queries/community-feed.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index 544306bf0..81feb22fd 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -254,7 +254,21 @@ export function useCommunityFeedSlices( isIncompleteThread: slice.isIncompleteThread, } }) - .filter(slice => slice.items.length > 0) + .filter(slice => { + // Nuclear block: drop the whole thread if any author in it is + // blocked or blocking the viewer, matching the standard app. + const hasBlock = slice.items.some(item => { + const v = item.post.author.viewer + return !!(v?.blocking || v?.blockedBy) + }) + if (hasBlock) return false + // Drop items the moderation engine filters from list contexts + // (hidden-for-me posts, muted authors, etc.). + slice.items = slice.items.filter( + item => !item.moderation.ui('contentList').filter, + ) + return slice.items.length > 0 + }) }, [feedItems, moderationOpts]) }