diff --git a/package.json b/package.json index 7fd713d6b..818138f9d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.127.4", + "version": "1.128.0", "private": true, "packageManager": "pnpm@11.7.0", "engines": { diff --git a/src/lib/api/__tests__/post-routing.test.ts b/src/lib/api/__tests__/post-routing.test.ts index f9af8adac..7f883d9b5 100644 --- a/src/lib/api/__tests__/post-routing.test.ts +++ b/src/lib/api/__tests__/post-routing.test.ts @@ -17,6 +17,17 @@ jest.mock('#/state/queries/threadgate', () => ({ threadgateAllowUISettingToAllowRecordValue: jest.fn(() => []), })) +// The public write path hashes the record through ESM-only IPLD packages +// that jest cannot load; the CID value is not under test here. +jest.mock( + '@ipld/dag-cbor', + () => ({encode: (v: unknown) => Buffer.from(JSON.stringify(v))}), + {virtual: true}, +) +jest.mock('multiformats/cid', () => ({ + CID: {createV1: () => ({toString: () => 'bafyreifake'})}, +})) + jest.mock('../space-post', () => ({ postToSpace: jest.fn(() => Promise.resolve({uris: ['at://space/post']})), })) @@ -88,6 +99,38 @@ describe('post routing', () => { }) }) +describe('self labels', () => { + beforeEach(() => jest.clearAllMocks()) + + it('publishes a text-only post with its self labels', async () => { + const {agent, applyWrites} = mockAgent() + + await post(agent, queryClient, { + thread: { + posts: [ + { + richtext: {text: 'words only', facets: []}, + shortenedGraphemeLength: 10, + labels: ['porn'], + embed: {}, + }, + ], + postgate: {}, + threadgate: [], + blackskyOnly: false, + } as never, + }) + + const [{writes}] = applyWrites.mock.calls[0] as unknown as [ + {writes: {value: {labels?: unknown}}[]}, + ] + expect(writes[0].value.labels).toEqual({ + $type: 'com.atproto.label.defs#selfLabels', + values: [{val: 'porn'}], + }) + }) +}) + describe('quoting a space post from outside the space', () => { const SPACE_POST = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kabc` const permalink = `https://blacksky.community/profile/did:plc:bob/post/3kabc?space=${encodeURIComponent( diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index f2d61e698..cfccb6477 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -2095,24 +2095,6 @@ function ComposerPills({ const t = useTheme() const {data: isCommunityMember = false} = useCommunityMembership() const homeAppviewOutage = useHomeAppviewOutage() - const media = post.embed.media - const hasMedia = - media?.type === 'images' || - media?.type === 'gallery' || - media?.type === 'gif' || - media?.type === 'video' - const hasLink = !!post.embed.link - - if ( - isReply && - !hasMedia && - !hasLink && - !isForcedBlackskyOnly && - !thread.communityFeedUri && - !thread.communitySpaceUri - ) { - return null - } return ( - {hasMedia || hasLink ? ( - { - dispatch({ - type: 'update_post', - postId: post.id, - postAction: { - type: 'update_labels', - labels: nextLabels, - }, - }) - }} - /> - ) : null} + { + dispatch({ + type: 'update_post', + postId: post.id, + postAction: { + type: 'update_labels', + labels: nextLabels, + }, + }) + }} + /> {(thread.blackskyOnly || thread.communityFeedUri || diff --git a/src/view/com/composer/labels/LabelsBtn.tsx b/src/view/com/composer/labels/LabelsBtn.tsx index 9471dc0d2..4df2625e9 100644 --- a/src/view/com/composer/labels/LabelsBtn.tsx +++ b/src/view/com/composer/labels/LabelsBtn.tsx @@ -109,8 +109,8 @@ function DialogInner({ - Please add any content warning labels that are applicable for the - media you are posting. + Please add any content warning labels that apply to what you are + posting. @@ -162,7 +162,7 @@ function DialogInner({ labels.includes('porn') ? ( {labels.includes('sexual') ? ( - Pictures meant for adults. + Suggestive content meant for adults. ) : labels.includes('nudity') ? ( Artistic or non-erotic nudity. ) : labels.includes('porn') ? ( @@ -204,7 +204,7 @@ function DialogInner({ {labels.includes('graphic-media') ? ( - Media that may be disturbing or inappropriate for some + Content that may be disturbing or inappropriate for some audiences. diff --git a/src/view/com/composer/state/__tests__/composer.test.ts b/src/view/com/composer/state/__tests__/composer.test.ts new file mode 100644 index 000000000..c7e4e4b48 --- /dev/null +++ b/src/view/com/composer/state/__tests__/composer.test.ts @@ -0,0 +1,78 @@ +import {type ComposerImage} from '#/state/gallery' +import { + type ComposerAction, + composerReducer, + createComposerState, +} from '../composer' + +jest.mock('#/state/gallery', () => ({createInitialImages: jest.fn()})) +jest.mock('#/state/queries/threadgate', () => ({ + threadgateRecordToAllowUISetting: jest.fn(() => []), +})) +jest.mock('../video', () => ({ + createVideoState: jest.fn(), + videoReducer: jest.fn(), +})) + +const image = { + source: { + id: 'img-1', + path: 'file://a', + mime: 'image/jpeg', + width: 1, + height: 1, + }, +} as unknown as ComposerImage + +type PostAction = Extract['postAction'] + +function draftAfter(actions: PostAction[]) { + let state = createComposerState({ + initText: undefined, + initMention: undefined, + initImageUris: undefined, + initQuoteUri: undefined, + initInteractionSettings: undefined, + }) + for (const postAction of actions) { + state = composerReducer(state, { + type: 'update_post', + postId: state.thread.posts[0].id, + postAction, + }) + } + return state.thread.posts[0] +} + +describe('composer self labels', () => { + it('keeps labels when the last image is removed', () => { + const post = draftAfter([ + {type: 'embed_add_images', images: [image]}, + {type: 'update_labels', labels: ['porn']}, + {type: 'embed_remove_image', image}, + ]) + + expect(post.embed.media).toBeUndefined() + expect(post.labels).toEqual(['porn']) + }) + + it('keeps labels when the link card is removed', () => { + const post = draftAfter([ + {type: 'embed_add_uri', uri: 'https://example.com'}, + {type: 'update_labels', labels: ['graphic-media']}, + {type: 'embed_remove_link'}, + ]) + + expect(post.embed.link).toBeUndefined() + expect(post.labels).toEqual(['graphic-media']) + }) + + it('keeps labels when a video is removed from a text-only draft', () => { + const post = draftAfter([ + {type: 'update_labels', labels: ['sexual']}, + {type: 'embed_remove_video'}, + ]) + + expect(post.labels).toEqual(['sexual']) + }) +}) diff --git a/src/view/com/composer/state/composer.ts b/src/view/com/composer/state/composer.ts index 3f0684bb1..625ce877b 100644 --- a/src/view/com/composer/state/composer.ts +++ b/src/view/com/composer/state/composer.ts @@ -466,7 +466,6 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } case 'embed_remove_image': { const prevMedia = state.embed.media - let nextLabels = state.labels if (prevMedia?.type === 'images' || prevMedia?.type === 'gallery') { const removedImage = action.image const remainingImages = prevMedia.images.filter(img => { @@ -475,9 +474,6 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { let nextMedia: ImagesMedia | GalleryMedia | undefined if (remainingImages.length === 0) { nextMedia = undefined - if (!state.embed.link) { - nextLabels = [] - } } else { // Re-pick the variant so a gallery that shrinks to <=4 demotes // back to the legacy `app.bsky.embed.images` shape - keeps old @@ -486,7 +482,6 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } return { ...state, - labels: nextLabels, embed: { ...state.embed, media: nextMedia, @@ -537,13 +532,8 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { prevMedia.video.abortController.abort() nextMedia = undefined } - let nextLabels = state.labels - if (!state.embed.link) { - nextLabels = [] - } return { ...state, - labels: nextLabels, embed: { ...state.embed, media: nextMedia, @@ -580,13 +570,8 @@ function postReducer(state: PostDraft, action: PostAction): PostDraft { } } case 'embed_remove_link': { - let nextLabels = state.labels - if (!state.embed.media) { - nextLabels = [] - } return { ...state, - labels: nextLabels, embed: { ...state.embed, link: undefined, -- knotmirror 0.0.1 From 8435782575d16630343623f547700ecb8250bd88 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Wed, 16 Sep 2026 20:24:12 -0400 Subject: [PATCH 2/3] feat(moderation): blur post text for adult content labels The built-in porn, sexual, nudity, graphic-media and gore definitions only blurred media, so a text-only post carrying one of those labels rendered uncovered. They now blur the post content as well, from any source: the built-in definitions are patched at startup and labeler declared definitions get the same content behavior and built-in flags, which also keeps the values self-labelable when the author is a subscribed labeler. Account and profile behaviors are unchanged. --- package.json | 2 +- .../moderation/LabelDialog/blackskyLabels.ts | 8 +- .../__tests__/adult-content-labels.test.ts | 287 ++++++++++++++++++ src/lib/moderation/adult-content-labels.ts | 36 +++ src/state/queries/preferences/moderation.ts | 3 +- src/state/session/moderation.ts | 5 +- 6 files changed, 334 insertions(+), 7 deletions(-) create mode 100644 src/lib/moderation/__tests__/adult-content-labels.test.ts create mode 100644 src/lib/moderation/adult-content-labels.ts diff --git a/package.json b/package.json index 818138f9d..980241c6a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.128.0", + "version": "1.129.0", "private": true, "packageManager": "pnpm@11.7.0", "engines": { diff --git a/src/components/moderation/LabelDialog/blackskyLabels.ts b/src/components/moderation/LabelDialog/blackskyLabels.ts index 51525b3cd..b3f179b84 100644 --- a/src/components/moderation/LabelDialog/blackskyLabels.ts +++ b/src/components/moderation/LabelDialog/blackskyLabels.ts @@ -179,7 +179,7 @@ export const GLOBAL_LABEL_DEFS: ComAtprotoLabelDefs.LabelValueDefinition[] = [ { identifier: 'porn', severity: 'none', - blurs: 'media', + blurs: 'content', defaultSetting: 'hide', adultOnly: true, locales: [ @@ -193,7 +193,7 @@ export const GLOBAL_LABEL_DEFS: ComAtprotoLabelDefs.LabelValueDefinition[] = [ { identifier: 'sexual', severity: 'none', - blurs: 'media', + blurs: 'content', defaultSetting: 'warn', adultOnly: true, locales: [ @@ -207,7 +207,7 @@ export const GLOBAL_LABEL_DEFS: ComAtprotoLabelDefs.LabelValueDefinition[] = [ { identifier: 'nudity', severity: 'none', - blurs: 'media', + blurs: 'content', defaultSetting: 'ignore', adultOnly: false, locales: [ @@ -221,7 +221,7 @@ export const GLOBAL_LABEL_DEFS: ComAtprotoLabelDefs.LabelValueDefinition[] = [ { identifier: 'graphic-media', severity: 'none', - blurs: 'media', + blurs: 'content', defaultSetting: 'warn', adultOnly: true, locales: [ diff --git a/src/lib/moderation/__tests__/adult-content-labels.test.ts b/src/lib/moderation/__tests__/adult-content-labels.test.ts new file mode 100644 index 000000000..0c9ee4b8e --- /dev/null +++ b/src/lib/moderation/__tests__/adult-content-labels.test.ts @@ -0,0 +1,287 @@ +import { + type AppBskyFeedDefs, + type AppBskyLabelerDefs, + type ComAtprotoLabelDefs, + interpretLabelValueDefinitions, + type LabelPreference, + LABELS, + moderatePost, + type ModerationOpts, +} from '@atproto/api' + +import { + configureAdultContentLabelDefs, + withAdultContentBehavior, +} from '../adult-content-labels' + +const AUTHOR = 'did:plc:author' +const LABELER = 'did:plc:labeler' +const URI = `at://${AUTHOR}/app.bsky.feed.post/3ktextonly` +const CID = 'bafyreipost' +const AT = '2026-09-16T00:00:00.000Z' +const ADULT_VALS = [ + 'porn', + 'sexual', + 'nudity', + 'graphic-media', + 'gore', +] as const +const CONTEXTS = [ + 'contentList', + 'contentView', + 'contentMedia', + 'avatar', + 'profileList', + 'profileView', +] as const + +const label = (val: string, src: string): ComAtprotoLabelDefs.Label => ({ + src, + uri: URI, + cid: CID, + val, + cts: AT, +}) + +const textPost = ({ + postLabels = [], + authorLabels = [], +}: { + postLabels?: ComAtprotoLabelDefs.Label[] + authorLabels?: ComAtprotoLabelDefs.Label[] +}): AppBskyFeedDefs.PostView => ({ + $type: 'app.bsky.feed.defs#postView', + uri: URI, + cid: CID, + author: { + did: AUTHOR, + handle: 'author.test', + viewer: {}, + labels: authorLabels, + }, + record: {$type: 'app.bsky.feed.post', text: 'words only', createdAt: AT}, + labels: postLabels, + indexedAt: AT, +}) + +const labelerView = ( + did: string, + defs: Array>, +): AppBskyLabelerDefs.LabelerViewDetailed => ({ + $type: 'app.bsky.labeler.defs#labelerViewDetailed', + uri: `at://${did}/app.bsky.labeler.service/self`, + cid: 'bafyreilabeler', + creator: {did, handle: 'labeler.test'}, + policies: { + labelValues: defs.map(d => d.identifier!), + labelValueDefinitions: defs.map(d => ({ + severity: 'none', + blurs: 'media', + locales: [], + ...d, + })) as ComAtprotoLabelDefs.LabelValueDefinition[], + }, + indexedAt: AT, +}) + +const opts = ({ + labels, + adultContentEnabled = true, + labelDefs = {}, +}: { + labels: Record + adultContentEnabled?: boolean + labelDefs?: ModerationOpts['labelDefs'] +}): ModerationOpts => ({ + userDid: 'did:plc:viewer', + prefs: { + adultContentEnabled, + labels, + labelers: [{did: LABELER, labels}], + mutedWords: [], + hiddenPosts: [], + }, + labelDefs, +}) + +const uiSummary = ( + post: AppBskyFeedDefs.PostView, + moderationOpts: ModerationOpts, +) => { + const mod = moderatePost(post, moderationOpts) + return Object.fromEntries( + CONTEXTS.map(ctx => { + const ui = mod.ui(ctx) + return [ + ctx, + {blur: ui.blur, filter: ui.filter, noOverride: ui.noOverride}, + ] + }), + ) +} + +beforeAll(configureAdultContentLabelDefs) + +describe('configureAdultContentLabelDefs', () => { + it('covers the text of a warned self-labeled post, not only its media', () => { + const mod = moderatePost( + textPost({postLabels: [label('porn', AUTHOR)]}), + opts({labels: {porn: 'warn'}}), + ) + + expect(mod.ui('contentList').blur).toBe(true) + expect(mod.ui('contentView').blur).toBe(true) + expect(mod.ui('contentMedia').blur).toBe(true) + expect(mod.ui('contentList').filter).toBe(false) + }) + + it('filters a hidden self-label out of lists and covers it in the thread', () => { + const mod = moderatePost( + textPost({postLabels: [label('porn', AUTHOR)]}), + opts({labels: {porn: 'hide'}}), + ) + + expect(mod.ui('contentList').filter).toBe(true) + expect(mod.ui('contentView').blur).toBe(true) + }) + + it('leaves an ignored self-label alone', () => { + const mod = moderatePost( + textPost({postLabels: [label('nudity', AUTHOR)]}), + opts({labels: {nudity: 'ignore'}}), + ) + + expect(mod.ui('contentList').blur).toBe(false) + expect(mod.ui('contentView').blur).toBe(false) + expect(mod.ui('contentMedia').blur).toBe(false) + }) + + it('is idempotent and leaves account and profile behaviors untouched', () => { + configureAdultContentLabelDefs() + + for (const val of ADULT_VALS) { + expect(LABELS[val].blurs).toBe('content') + expect(LABELS[val].behaviors.account).toEqual({ + avatar: 'blur', + banner: 'blur', + }) + expect(LABELS[val].behaviors.profile).toEqual({ + avatar: 'blur', + banner: 'blur', + }) + expect(LABELS[val].behaviors.content).toEqual({ + contentMedia: 'blur', + contentList: 'blur', + contentView: 'blur', + }) + } + expect(LABELS.porn.flags).toEqual(['adult']) + expect(LABELS.nudity.flags).toEqual([]) + }) +}) + +describe('withAdultContentBehavior', () => { + const labelerDefs = (val: string, wrap: boolean) => { + const defs = interpretLabelValueDefinitions( + labelerView(LABELER, [{identifier: val}]), + ) + return {[LABELER]: wrap ? withAdultContentBehavior(defs) : defs} + } + + it.each(ADULT_VALS)( + 'covers post text for a labeler that declares %s itself', + val => { + const post = textPost({postLabels: [label(val, LABELER)]}) + const prefs = {[val]: 'warn' as const} + + const patched = moderatePost( + post, + opts({labels: prefs, labelDefs: labelerDefs(val, true)}), + ) + const unpatched = moderatePost( + post, + opts({labels: prefs, labelDefs: labelerDefs(val, false)}), + ) + + expect(unpatched.ui('contentList').blur).toBe(false) + expect(patched.ui('contentList').blur).toBe(true) + expect(patched.ui('contentView').blur).toBe(true) + expect(patched.ui('contentMedia').blur).toBe(true) + }, + ) + + it.each(ADULT_VALS)( + 'keeps %s self-labelable when the author is also a subscribed labeler', + val => { + const post = textPost({postLabels: [label(val, AUTHOR)]}) + const prefs = {[val]: 'warn' as const} + const authorDefs = (wrap: boolean) => { + const defs = interpretLabelValueDefinitions( + labelerView(AUTHOR, [{identifier: val}]), + ) + return {[AUTHOR]: wrap ? withAdultContentBehavior(defs) : defs} + } + + const patched = moderatePost( + post, + opts({labels: prefs, labelDefs: authorDefs(true)}), + ) + const unpatched = moderatePost( + post, + opts({labels: prefs, labelDefs: authorDefs(false)}), + ) + + expect(unpatched.ui('contentList').blur).toBe(false) + expect(patched.ui('contentList').blur).toBe(true) + expect(patched.ui('contentView').blur).toBe(true) + }, + ) + + it('leaves a labeler custom value alone', () => { + const [def] = withAdultContentBehavior( + interpretLabelValueDefinitions( + labelerView(LABELER, [{identifier: 'misogynoir', blurs: 'content'}]), + ), + ) + + expect(def.flags).toContain('no-self') + expect(def.blurs).toBe('content') + expect(def.behaviors.content?.contentMedia).toBeUndefined() + }) + + it.each([ + ['adult content disabled, pref ignore', false, 'ignore' as const], + ['adult content enabled, pref warn', true, 'warn' as const], + ])( + 'matches the built-in account-level decision (%s)', + (_name, adultContentEnabled, pref) => { + const post = textPost({authorLabels: [label('porn', LABELER)]}) + const prefs = {porn: pref} + + const viaLabeler = uiSummary( + post, + opts({ + labels: prefs, + adultContentEnabled, + labelDefs: { + [LABELER]: withAdultContentBehavior( + interpretLabelValueDefinitions( + labelerView(LABELER, [{identifier: 'porn', adultOnly: false}]), + ), + ), + }, + }), + ) + const builtIn = uiSummary( + post, + opts({labels: prefs, adultContentEnabled, labelDefs: {}}), + ) + + expect(viaLabeler).toEqual(builtIn) + expect(viaLabeler.contentList.filter).toBe(!adultContentEnabled) + expect(viaLabeler.contentList.blur).toBe(false) + expect(viaLabeler.avatar.blur).toBe(true) + expect(viaLabeler.profileView.blur).toBe(false) + }, + ) +}) diff --git a/src/lib/moderation/adult-content-labels.ts b/src/lib/moderation/adult-content-labels.ts new file mode 100644 index 000000000..e102bdcf5 --- /dev/null +++ b/src/lib/moderation/adult-content-labels.ts @@ -0,0 +1,36 @@ +import {type InterpretedLabelValueDefinition, LABELS} from '@atproto/api' + +import {SELF_LABELS} from '../moderation' + +const ADULT_LABEL_VALS = [...SELF_LABELS, 'gore'] as const + +function adultLabelVal(identifier: string) { + return ADULT_LABEL_VALS.find(val => val === identifier) +} + +export function applyAdultContentBehavior( + def: InterpretedLabelValueDefinition, +): InterpretedLabelValueDefinition { + const val = adultLabelVal(def.identifier) + if (!val) return def + def.blurs = 'content' + def.flags = [...LABELS[val].flags] + def.behaviors.content = { + ...def.behaviors.content, + contentList: 'blur', + contentView: 'blur', + } + return def +} + +export function configureAdultContentLabelDefs() { + for (const val of ADULT_LABEL_VALS) { + applyAdultContentBehavior(LABELS[val]) + } +} + +export function withAdultContentBehavior( + defs: InterpretedLabelValueDefinition[], +): InterpretedLabelValueDefinition[] { + return defs.map(applyAdultContentBehavior) +} diff --git a/src/state/queries/preferences/moderation.ts b/src/state/queries/preferences/moderation.ts index 55c155dc5..f797d0fb2 100644 --- a/src/state/queries/preferences/moderation.ts +++ b/src/state/queries/preferences/moderation.ts @@ -1,6 +1,7 @@ import {useMemo} from 'react' import {AtpAgent, interpretLabelValueDefinitions} from '@atproto/api' +import {withAdultContentBehavior} from '#/lib/moderation/adult-content-labels' import {isNonConfigurableModerationAuthority} from '#/state/session/additional-moderation-authorities' import {useLabelersDetailedInfoQuery} from '../labeler' import {usePreferencesQuery} from './index' @@ -41,7 +42,7 @@ export function useLabelDefinitionsQuery() { labelDefs: Object.fromEntries( (labelers.data || []).map(labeler => [ labeler.creator.did, - interpretLabelValueDefinitions(labeler), + withAdultContentBehavior(interpretLabelValueDefinitions(labeler)), ]), ), labelers: labelers.data || [], diff --git a/src/state/session/moderation.ts b/src/state/session/moderation.ts index a3f61a924..48a8d013a 100644 --- a/src/state/session/moderation.ts +++ b/src/state/session/moderation.ts @@ -1,6 +1,7 @@ -import {Agent, AtpAgent, BSKY_LABELER_DID} from '@atproto/api' +import {type Agent, AtpAgent, BSKY_LABELER_DID} from '@atproto/api' import {IS_TEST_USER} from '#/lib/constants' +import {configureAdultContentLabelDefs} from '#/lib/moderation/adult-content-labels' import {getNoAppLabelers} from '../preferences/no-app-labelers' import { BLACKSKY_LABELER, @@ -14,6 +15,7 @@ export function configureModerationForGuest() { // Don't add any other global behavior here! switchToBskyAppLabeler() configureAdditionalModerationAuthorities() + configureAdultContentLabelDefs() } export async function configureModerationForAccount( @@ -41,6 +43,7 @@ export async function configureModerationForAccount( } configureAdditionalModerationAuthorities() + configureAdultContentLabelDefs() } function switchToBskyAppLabeler() { -- knotmirror 0.0.1 From c06185ed126e9478f12d7e020da2edf436b11ea1 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Wed, 16 Sep 2026 20:29:07 -0400 Subject: [PATCH 3/3] feat(moderation): let peer mods label public posts The post menu only offered Label post on community posts. It now covers app.bsky.feed.post as well, with permissioned-space records still excluded. Label lookups are pinned to the home appview, and after a label is applied or removed the feed, post, and thread caches refresh once the appview reports the change, or after a bounded wait. --- package.json | 2 +- .../PostControls/PostMenu/PostMenuItems.tsx | 13 +- src/lib/api/__tests__/community-post.test.ts | 19 +- src/lib/api/community-post.ts | 9 + .../queries/__tests__/peer-mod-label.test.tsx | 241 ++++++++++++++++++ src/state/queries/peer-mod-label.ts | 159 +++++++++--- 6 files changed, 406 insertions(+), 37 deletions(-) create mode 100644 src/state/queries/__tests__/peer-mod-label.test.tsx diff --git a/package.json b/package.json index 980241c6a..00cc28070 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.129.0", + "version": "1.130.0", "private": true, "packageManager": "pnpm@11.7.0", "engines": { diff --git a/src/components/PostControls/PostMenu/PostMenuItems.tsx b/src/components/PostControls/PostMenu/PostMenuItems.tsx index a7f700074..17e2c1ee5 100644 --- a/src/components/PostControls/PostMenu/PostMenuItems.tsx +++ b/src/components/PostControls/PostMenu/PostMenuItems.tsx @@ -17,7 +17,10 @@ import {plural} from '@lingui/core/macro' import {useLingui} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' -import {getCommunitySpaceUri} from '#/lib/api/community-post' +import { + getCommunitySpaceUri, + isPeerModLabelableUri, +} from '#/lib/api/community-post' import {isSpaceRecordUri} from '#/lib/api/space-uri' import {getCurrentRoute} from '#/lib/routes/helpers' import {makeProfileLink, postPermalink} from '#/lib/routes/links' @@ -159,13 +162,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 {data: peerModPerms} = useMyPeerModPermissions() const canLabelPost = - !!peerModPerms?.isPeerMod && isCommunityPost && !getCommunitySpaceUri(post) + !!peerModPerms?.isPeerMod && + isPeerModLabelableUri(postUri) && + !getCommunitySpaceUri(post) const [isThreadMuted, muteThread, unmuteThread] = useThreadMuteMutationQueue( post, rootUri, diff --git a/src/lib/api/__tests__/community-post.test.ts b/src/lib/api/__tests__/community-post.test.ts index 775949210..546a62c68 100644 --- a/src/lib/api/__tests__/community-post.test.ts +++ b/src/lib/api/__tests__/community-post.test.ts @@ -1,4 +1,4 @@ -import {getCommunitySpaceUri} from '../community-post' +import {getCommunitySpaceUri, isPeerModLabelableUri} from '../community-post' const post = (communitySpace?: unknown) => ({ @@ -27,3 +27,20 @@ describe(getCommunitySpaceUri, () => { expect(getCommunitySpaceUri(post(communitySpace))).toBeUndefined() }) }) + +describe(isPeerModLabelableUri, () => { + it.each([ + 'at://did:plc:a/app.bsky.feed.post/3k', + 'at://did:plc:a/community.blacksky.feed.post/3k', + ])('accepts %s', uri => { + expect(isPeerModLabelableUri(uri)).toBe(true) + }) + + it.each([ + 'at://did:plc:a/app.bsky.feed.generator/3k', + 'at://did:plc:a/app.bsky.feed.repost/3k', + 'at://did:plc:c/space/community.blacksky.feed/main/did:plc:a/app.bsky.feed.post/3k', + ])('rejects %s', uri => { + expect(isPeerModLabelableUri(uri)).toBe(false) + }) +}) diff --git a/src/lib/api/community-post.ts b/src/lib/api/community-post.ts index 4eb41154a..d6b290b41 100644 --- a/src/lib/api/community-post.ts +++ b/src/lib/api/community-post.ts @@ -1,6 +1,7 @@ import { type AppBskyFeedDefs, AppBskyFeedPost, + AtUri, type BskyAgent, jsonToLex, } from '@atproto/api' @@ -13,6 +14,14 @@ import * as bsky from '#/types/bsky' export const GET_COMMUNITY_POST = 'community.blacksky.feed.getCommunityPost' const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' +const PEER_MOD_LABELABLE_COLLECTIONS = [ + 'app.bsky.feed.post', + COMMUNITY_POST_COLLECTION, +] + +export function isPeerModLabelableUri(uri: string): boolean { + return PEER_MOD_LABELABLE_COLLECTIONS.includes(new AtUri(uri).collection) +} /** * Whether this post is community content — the appview-stored stub, or a diff --git a/src/state/queries/__tests__/peer-mod-label.test.tsx b/src/state/queries/__tests__/peer-mod-label.test.tsx new file mode 100644 index 000000000..9f9b8593a --- /dev/null +++ b/src/state/queries/__tests__/peer-mod-label.test.tsx @@ -0,0 +1,241 @@ +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {act, renderHook, waitFor} from '@testing-library/react-native' + +import { + BLUESKY_FALLBACK_PROXY_HEADER, + BLUESKY_PROXY_HEADER, + HOME_APPVIEW_PINNED_OPTS, +} from '#/lib/constants' + +const mockQueryLabels = jest.fn() +const mockCommunityXrpc = jest.fn() +const mockWarn = jest.fn() +const mockAgent = { + com: {atproto: {label: {queryLabels: mockQueryLabels}}}, +} + +jest.mock('#/lib/api/community', () => ({ + communityXrpc: (...args: unknown[]) => mockCommunityXrpc(...args), +})) +jest.mock('#/logger', () => ({ + logger: {warn: (...args: unknown[]) => mockWarn(...args)}, +})) +jest.mock('#/state/session', () => ({ + useAgent: () => mockAgent, +})) +jest.mock('#/state/queries/community-feed', () => ({ + COMMUNITY_POST_RQKEY: (uri: string) => ['community-post', uri], + RQKEY_ROOT: 'community-feed', + TIMELINE_RQKEY: () => ['community-timeline'], +})) +jest.mock('#/state/queries/post', () => ({ + RQKEY: (uri: string) => ['post', uri], +})) +jest.mock('#/state/queries/post-feed', () => ({RQKEY_ROOT: 'post-feed'})) + +import { + useApplyLabelMutation, + usePostBlackskyLabelsQuery, + useRemoveLabelMutation, +} from '../peer-mod-label' + +const URI = 'at://did:plc:author/app.bsky.feed.post/3kpost' +const CID = 'bafyreipost' +const INTERVAL = 750 +const REQUEST_TIMEOUT = 3000 +const ATTEMPTS = 8 +const RENDER_KEYS = [['post', URI], ['post-feed'], ['post-thread-v2']] + +const labelsResponse = (vals: string[]) => ({ + data: {labels: vals.map(val => ({val, uri: URI, src: 'did:plc:mod'}))}, +}) + +function setup() { + const client = new QueryClient({ + defaultOptions: {queries: {retry: false}}, + }) + const invalidate = jest.spyOn(client, 'invalidateQueries') + const wrapper = ({children}: React.PropsWithChildren) => ( + {children} + ) + return {client, invalidate, wrapper} +} + +const invalidatedKeys = (invalidate: jest.SpyInstance) => + invalidate.mock.calls.map( + ([filters]: [{queryKey?: unknown}]) => filters.queryKey, + ) + +const expectRenderCachesInvalidated = ( + invalidate: jest.SpyInstance, + times: number, +) => { + for (const key of RENDER_KEYS) { + expect( + invalidatedKeys(invalidate).filter( + k => JSON.stringify(k) === JSON.stringify(key), + ), + ).toHaveLength(times) + } +} + +async function applyLabel( + wrapper: React.ComponentType, +) { + const {result} = renderHook(() => useApplyLabelMutation(), {wrapper}) + let pollsWhenResolved = -1 + await act(async () => { + await result.current.mutateAsync({ + subjectUri: URI, + subjectCid: CID, + val: 'porn', + }) + pollsWhenResolved = mockQueryLabels.mock.calls.length + }) + return {result, pollsWhenResolved} +} + +describe('peer-mod label reconciliation', () => { + beforeEach(() => { + jest.useFakeTimers() + jest.clearAllMocks() + mockCommunityXrpc.mockResolvedValue({ok: true}) + BLUESKY_PROXY_HEADER.set(BLUESKY_FALLBACK_PROXY_HEADER) + }) + + afterEach(() => { + jest.useRealTimers() + }) + + it('refreshes the render caches once the appview reports the label', async () => { + const {invalidate, wrapper} = setup() + mockQueryLabels + .mockResolvedValueOnce(labelsResponse([])) + .mockResolvedValueOnce(labelsResponse(['porn'])) + + const {pollsWhenResolved} = await applyLabel(wrapper) + + expect(pollsWhenResolved).toBeLessThanOrEqual(1) + await act(async () => { + await jest.advanceTimersByTimeAsync(0) + }) + expect(mockQueryLabels).toHaveBeenCalledTimes(1) + expectRenderCachesInvalidated(invalidate, 0) + + await act(async () => { + await jest.advanceTimersByTimeAsync(INTERVAL) + }) + + expect(mockQueryLabels).toHaveBeenCalledTimes(2) + expectRenderCachesInvalidated(invalidate, 1) + expect(mockWarn).not.toHaveBeenCalled() + }) + + it('pins every label lookup to the home appview while fallback is active', async () => { + const {wrapper} = setup() + mockQueryLabels.mockResolvedValue(labelsResponse(['porn'])) + + const {result} = renderHook(() => usePostBlackskyLabelsQuery(URI), { + wrapper, + }) + await waitFor(() => expect(result.current.data).toEqual(['porn'])) + await applyLabel(wrapper) + await act(async () => { + await jest.advanceTimersByTimeAsync(0) + }) + + expect(BLUESKY_PROXY_HEADER.get()).toBe(BLUESKY_FALLBACK_PROXY_HEADER) + expect(mockQueryLabels.mock.calls.length).toBeGreaterThanOrEqual(2) + for (const [, opts] of mockQueryLabels.mock.calls as Array< + [unknown, {headers?: unknown}] + >) { + expect(opts.headers).toEqual(HOME_APPVIEW_PINNED_OPTS.headers) + } + }) + + it('gives up after the last attempt and still refreshes', async () => { + const {invalidate, wrapper} = setup() + mockQueryLabels.mockResolvedValue(labelsResponse([])) + + await applyLabel(wrapper) + await act(async () => { + await jest.advanceTimersByTimeAsync(INTERVAL * ATTEMPTS) + }) + + expect(mockQueryLabels).toHaveBeenCalledTimes(ATTEMPTS) + expectRenderCachesInvalidated(invalidate, 1) + expect(mockWarn).toHaveBeenCalledWith( + 'peer-mod label reconcile did not converge', + expect.objectContaining({subjectUri: URI, val: 'porn'}), + ) + }) + + it('survives a rejected lookup and keeps polling', async () => { + const {invalidate, wrapper} = setup() + mockQueryLabels + .mockRejectedValueOnce(new Error('boom')) + .mockResolvedValueOnce(labelsResponse(['porn'])) + + await applyLabel(wrapper) + await act(async () => { + await jest.advanceTimersByTimeAsync(INTERVAL) + }) + + expect(mockQueryLabels).toHaveBeenCalledTimes(2) + expectRenderCachesInvalidated(invalidate, 1) + expect(mockWarn).toHaveBeenCalledWith( + 'peer-mod label reconcile attempt failed', + expect.objectContaining({attempt: 1, message: 'boom'}), + ) + }) + + it('times out a lookup that never settles, even one ignoring its signal', async () => { + const {invalidate, wrapper} = setup() + let stalledSignal: AbortSignal | undefined + mockQueryLabels + .mockImplementationOnce( + (_params: unknown, opts: {signal: AbortSignal}) => { + stalledSignal = opts.signal + return new Promise(() => {}) + }, + ) + .mockResolvedValueOnce(labelsResponse(['porn'])) + + await applyLabel(wrapper) + await act(async () => { + await jest.advanceTimersByTimeAsync(REQUEST_TIMEOUT - 1) + }) + expect(mockQueryLabels).toHaveBeenCalledTimes(1) + expect(stalledSignal?.aborted).toBe(false) + + await act(async () => { + await jest.advanceTimersByTimeAsync(1 + INTERVAL) + }) + + expect(stalledSignal?.aborted).toBe(true) + expect(mockQueryLabels).toHaveBeenCalledTimes(2) + expectRenderCachesInvalidated(invalidate, 1) + expect(mockWarn).toHaveBeenCalledWith( + 'peer-mod label reconcile attempt failed', + expect.objectContaining({attempt: 1, message: 'Timed out after 3000ms'}), + ) + }) + + it('converges on absence after a removal', async () => { + const {invalidate, wrapper} = setup() + mockQueryLabels + .mockResolvedValueOnce(labelsResponse(['porn'])) + .mockResolvedValueOnce(labelsResponse([])) + const {result} = renderHook(() => useRemoveLabelMutation(), {wrapper}) + + await act(async () => { + await result.current.mutateAsync({subjectUri: URI, val: 'porn'}) + }) + await act(async () => { + await jest.advanceTimersByTimeAsync(INTERVAL) + }) + + expect(mockQueryLabels).toHaveBeenCalledTimes(2) + expectRenderCachesInvalidated(invalidate, 1) + }) +}) diff --git a/src/state/queries/peer-mod-label.ts b/src/state/queries/peer-mod-label.ts index a9255cc07..ad62bdd53 100644 --- a/src/state/queries/peer-mod-label.ts +++ b/src/state/queries/peer-mod-label.ts @@ -1,12 +1,23 @@ -import {useCallback} from 'react' -import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' +import {type BskyAgent} from '@atproto/api' +import { + type QueryClient, + useMutation, + useQuery, + useQueryClient, +} from '@tanstack/react-query' import {communityXrpc} from '#/lib/api/community' +import {timeout} from '#/lib/async/timeout' +import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' +import {logger} from '#/logger' import { COMMUNITY_POST_RQKEY, RQKEY_ROOT as COMMUNITY_FEED_RQKEY_ROOT, TIMELINE_RQKEY, } from '#/state/queries/community-feed' +import {RQKEY as postRQKey} from '#/state/queries/post' +import {RQKEY_ROOT as POST_FEED_RQKEY_ROOT} from '#/state/queries/post-feed' +import {postThreadQueryKeyRoot} from '#/state/queries/usePostThread/types' import {useAgent} from '#/state/session' import {BLACKSKY_LABELER} from '#/state/session/additional-moderation-authorities' @@ -14,6 +25,10 @@ const APPLY_METHOD = 'community.blacksky.moderation.applyLabel' const REMOVE_METHOD = 'community.blacksky.moderation.removeLabel' const GET_MY_LABELS_METHOD = 'community.blacksky.moderation.getMyLabels' +const RECONCILE_ATTEMPTS = 8 +const RECONCILE_INTERVAL_MS = 750 +const RECONCILE_REQUEST_TIMEOUT_MS = 3000 + export type ApplyLabelInput = { subjectUri: string subjectCid: string @@ -81,18 +96,97 @@ export function usePostBlackskyLabelsQuery(subjectUri: string | undefined) { 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) + return fetchBlackskyLabelVals(agent, subjectUri) }, }) } +async function fetchBlackskyLabelVals( + agent: BskyAgent, + subjectUri: string, + signal?: AbortSignal, +): Promise { + const res = await agent.com.atproto.label.queryLabels( + {uriPatterns: [subjectUri], sources: [BLACKSKY_LABELER]}, + {...HOME_APPVIEW_PINNED_OPTS, signal}, + ) + return res.data.labels.filter(l => !l.neg).map(l => l.val) +} + +function withDeadline( + run: (signal: AbortSignal) => Promise, + ms: number, +): Promise { + const controller = new AbortController() + let timer: ReturnType | undefined + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => { + controller.abort() + reject(new Error(`Timed out after ${ms}ms`)) + }, ms) + }) + return Promise.race([run(controller.signal), deadline]).finally(() => + clearTimeout(timer), + ) +} + +/** + * Ozone accepting a label event does not mean the appview has ingested it + * yet, so the caches that render this post are refreshed once the appview + * reports the expected state, or after a bounded wait. + */ +export async function reconcileLabelState({ + agent, + queryClient, + subjectUri, + val, + expectPresent, +}: { + agent: BskyAgent + queryClient: QueryClient + subjectUri: string + val: string + expectPresent: boolean +}): Promise { + let converged = false + try { + for (let attempt = 1; attempt <= RECONCILE_ATTEMPTS; attempt++) { + try { + const vals = await withDeadline( + signal => fetchBlackskyLabelVals(agent, subjectUri, signal), + RECONCILE_REQUEST_TIMEOUT_MS, + ) + if (vals.includes(val) === expectPresent) { + converged = true + break + } + } catch (e) { + logger.warn('peer-mod label reconcile attempt failed', { + attempt, + subjectUri, + val, + message: e instanceof Error ? e.message : String(e), + }) + } + if (attempt < RECONCILE_ATTEMPTS) { + await timeout(RECONCILE_INTERVAL_MS) + } + } + } finally { + if (!converged) { + logger.warn('peer-mod label reconcile did not converge', { + subjectUri, + val, + expectPresent, + }) + } + invalidateLabelState(queryClient, subjectUri) + } +} + export function useApplyLabelMutation() { const agent = useAgent() - const invalidate = useInvalidateLabelState() + const queryClient = useQueryClient() return useMutation({ mutationFn: async input => { const res = await communityXrpc(agent, APPLY_METHOD, {body: input}) @@ -101,14 +195,20 @@ export function useApplyLabelMutation() { } }, onSuccess: (_data, input) => { - invalidate(input.subjectUri) + void reconcileLabelState({ + agent, + queryClient, + subjectUri: input.subjectUri, + val: input.val, + expectPresent: true, + }) }, }) } export function useRemoveLabelMutation() { const agent = useAgent() - const invalidate = useInvalidateLabelState() + const queryClient = useQueryClient() return useMutation({ mutationFn: async input => { const res = await communityXrpc(agent, REMOVE_METHOD, {body: input}) @@ -117,27 +217,28 @@ export function useRemoveLabelMutation() { } }, onSuccess: (_data, input) => { - invalidate(input.subjectUri) + void reconcileLabelState({ + agent, + queryClient, + subjectUri: input.subjectUri, + val: input.val, + expectPresent: false, + }) }, }) } -function useInvalidateLabelState() { - const queryClient = useQueryClient() - return useCallback( - (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], - ) +function invalidateLabelState(queryClient: QueryClient, subjectUri: string) { + for (const queryKey of [ + myLabelsRQKey(subjectUri), + postLabelsRQKey(subjectUri), + COMMUNITY_POST_RQKEY(subjectUri), + postRQKey(subjectUri), + TIMELINE_RQKEY(), + [COMMUNITY_FEED_RQKEY_ROOT], + [POST_FEED_RQKEY_ROOT], + [postThreadQueryKeyRoot], + ]) { + void queryClient.invalidateQueries({queryKey}) + } }