import { AppBskyEmbedImages, AppBskyEmbedRecordWithMedia, AppBskyEmbedVideo, AppBskyFeedPost, AppBskyFeedRepost, AppBskyFeedDefs, moderateProfile, type Agent, type ModerationOpts } from '@atproto/api'; import { Jetstream, JetstreamV1, type LiveV1Opts, type websocketTransport } from '@bsky/jetstream'; import { openCache, type GraphCache, type GraphSnapshot } from './cache.js'; import { encodeThumbhash, mediaAssetKey } from './media-identity.js'; import { WALL_SNAPSHOT_MAX_AGE, type WallSnapshot } from './wall-snapshot.js'; import { contentModeration } from './content-moderation.js'; import { defaultContentSettings, type ContentSettings } from './content-settings.js'; import { createRepostRecurrence } from './repost-recurrence.js'; import { DEFAULT_JETSTREAM, FIREHOSE_INSTANCES, normalizeJetstreamEndpoint } from './jetstream-settings.js'; import { sharedJetstreamTransport } from './shared-jetstream.js'; import { applyPostInteractions, readPostCounts, type PostCounts, type PostInteractionChanges } from './post-counts.js'; export type MediaItem = { id: string; uri: string; author: string; authorAvatar?: string; authorNotFollowed?: boolean; post?: { cid: string; authorDid: string; authorFollowing?: string; likeUri?: string; repostUri?: string; bookmarked: boolean; counts?: PostCounts; }; text: string; kind: 'image' | 'video'; src: string; poster?: string; width: number; height: number; alt: string; thumbhash?: string; cached?: boolean; liveArrival?: boolean; provisional?: boolean; blob?: { did: string; cid: string }; warnings?: string[]; sensitive?: boolean; repostedBy?: string; repostedByDid?: string; repostedByAvatar?: string; }; export type InteractionUpdate = | { kind: 'post'; uri: string; cid: string; changes: PostInteractionChanges; } | { kind: 'actor'; did: string; following?: string | null; muted?: boolean; blocking?: string | null; }; type Callbacks = { items: (items: MediaItem[]) => void; status: (message: string) => void; connections?: (open: number) => void; error: (message: string) => void; graph: (snapshot: GraphSnapshot, persistent: boolean) => void; moderation?: (moderation: ModerationOpts) => void; }; type Post = AppBskyFeedDefs.PostView; type Pending = { cid: string; attempts: number; next: number }; type FeedSettings = ContentSettings & { includeReposts?: boolean }; const JETSTREAM_BATCH_SIZE = 150; type Repost = { uri: string; cid: string; by: AppBskyFeedDefs.ReasonRepost['by']; time: number; eventUri?: string; }; type Admission = ReturnType['admission']>; type Stored = { post: Post; items: MediaItem[]; time: number; validated: boolean; liveArrival?: boolean; reason?: Repost; admission: Admission; reasonAdmission?: Admission; }; function safeUrl(value: string | undefined): string | undefined { if (!value) return undefined; try { const url = new URL(value); return url.protocol === 'https:' ? url.href : undefined; } catch { return undefined; } } function profileAvatar(profile: Post['author'], moderation: ModerationOpts) { const decision = moderateProfile(profile, moderation).ui('avatar'); return decision.filter || decision.blur ? undefined : safeUrl(profile.avatar); } export function extractMedia( post: Post, moderation: ModerationOpts, settings = defaultContentSettings(), revealed = false ): MediaItem[] { const policy = contentModeration(post, moderation, settings); if (policy.hidden) return []; const record = AppBskyFeedPost.validateRecord(post.record); if (!record.success) return []; const outer = AppBskyEmbedRecordWithMedia.validateView(post.embed); const embed: unknown = outer.success ? outer.value.media : post.embed; const counts = readPostCounts(post); const base = { uri: post.uri, author: post.author.handle, authorAvatar: profileAvatar(post.author, moderation), text: record.value.text, post: { cid: post.cid, authorDid: post.author.did, authorFollowing: post.author.viewer?.following, likeUri: post.viewer?.like, repostUri: post.viewer?.repost, bookmarked: post.viewer?.bookmarked ?? false, ...(counts && { counts }) }, warnings: !revealed && policy.warnings.length ? policy.warnings : undefined, sensitive: policy.sensitive || undefined }; const recordWithMedia = AppBskyEmbedRecordWithMedia.validateMain(record.value.embed); const originalImages = AppBskyEmbedImages.validateMain( recordWithMedia.success ? recordWithMedia.value.media : record.value.embed ); const images = AppBskyEmbedImages.validateView(embed); if (images.success) { return images.value.images.flatMap((image, index) => { const src = safeUrl(image.fullsize); if (!src) return []; return [ { ...base, id: `${post.uri}#image-${index}`, kind: 'image' as const, src, poster: safeUrl(image.thumb), alt: image.alt, blob: originalImages.success && originalImages.value.images[index] ? { did: post.author.did, cid: originalImages.value.images[index].image.ref.toString() } : undefined, width: image.aspectRatio?.width || 1, height: image.aspectRatio?.height || 1 } ]; }); } const video = AppBskyEmbedVideo.validateView(embed); if (video.success) { const embed = video.value; const src = safeUrl(embed.playlist); if (!src) return []; return [ { ...base, id: `${post.uri}#video`, kind: 'video', src, poster: safeUrl(embed.thumbnail), alt: embed.alt ?? '', width: embed.aspectRatio?.width || 1, height: embed.aspectRatio?.height || 1 } ]; } return []; } export function startFeed( agent: Agent, callbacks: Callbacks, cacheFactory = openCache, transportFactory?: typeof websocketTransport, initialSettings: FeedSettings = defaultContentSettings(), initialJetstream?: string ) { let settings = initialSettings; let jetstreamEndpoint = normalizeJetstreamEndpoint(initialJetstream) ?? DEFAULT_JETSTREAM; const revealed = new Set(); const postOverrides = new Map< string, Map['changes']> >(); const actorOverrides = new Map< string, Omit, 'kind' | 'did'> >(); let interactionPending = false; let graphSyncedAt = 0; const controller = new AbortController(); const { signal } = controller; let cache: GraphCache | undefined; let moderation: ModerationOpts | undefined; let follows = new Set(); const profiles = new Map(); let blocks = new Set(); let ready = false; let hasCachedGraph = false; let freshModeration = false; let freshGraph = false; let restorationPending = false; let saveTimer: ReturnType | undefined; let saveTask = Promise.resolve(); let lastWallPayload = ''; let lastWallSavedAt = 0; let revalidationTask: Promise | undefined; const cachedTouches = new Map(); let historyAllowed = true; let draining = false; let refreshTask: Promise | undefined; let interval: ReturnType | undefined; let flushTimer: ReturnType | undefined; const streams = new Map(); const connected = new Set(); let reportedConnections = 0; const reportConnections = () => { if (reportedConnections === connected.size) return; reportedConnections = connected.size; callbacks.connections?.(reportedConnections); }; const liveStatus = () => { reportConnections(); if (!ready) return; const waiting = streams.size - connected.size; status( waiting ? `Reconnecting live feed… (${connected.size}/${streams.size} subscriptions connected)` : follows.size ? 'Live media feed' : 'Follow people on Bluesky to see their media' ); }; const pending = new Map(); const touched = new Set(); const stored = new Map(); const reposts = new Map(); const postUri = /^at:\/\/did:[^/]+\/app\.bsky\.feed\.post\/[^/]+$/; const repostUri = (uri: string, did: string) => uri.startsWith(`at://${did}/app.bsky.feed.repost/`) && /^[^/]+$/.test(uri.slice(`at://${did}/app.bsky.feed.repost/`.length)); const account = agent.did; const recurrence = createRepostRecurrence(account ?? ''); const report = (error: unknown) => { if (!signal.aborted) callbacks.error(error instanceof Error ? error.message : String(error)); }; const status = (message: string) => { if (!signal.aborted) callbacks.status(message); }; const suppressed = (did: string) => blocks.has(did) || actorOverrides.get(did)?.muted === true || !!actorOverrides.get(did)?.blocking; const eligible = (did: string) => follows.has(did) && !suppressed(did); const overlayProfile = (profile: T): T => { const override = actorOverrides.get(profile.did); if (!override) return profile; return { ...profile, viewer: { ...profile.viewer, ...(override.following !== undefined ? { following: override.following ?? undefined } : {}), ...(override.muted !== undefined ? { muted: override.muted } : {}), ...(override.blocking !== undefined ? { blocking: override.blocking ?? undefined } : {}) } }; }; const overlayGraph = (snapshot: GraphSnapshot): GraphSnapshot => { const next = new Set(snapshot.blocks); const nextFollows = new Set(snapshot.follows); for (const [did, override] of actorOverrides) { if (override.following) nextFollows.add(did); else if (override.following === null) nextFollows.delete(did); if (override.blocking) next.add(did); else if (override.blocking === null) next.delete(did); } return { ...snapshot, follows: [...nextFollows], blocks: [...next] }; }; const saveGraph = (snapshot: GraphSnapshot) => { if (!cache || !account) return; const target = cache; saveTask = saveTask.then(() => target.save(account, snapshot)).catch(report); return saveTask; }; const validReposts = (uri: string, cid?: string) => [...reposts.values()] .filter((value) => { if ( value.uri !== uri || (cid && value.cid !== cid) || !eligible(value.by.did) || !moderation ) return false; return [value.by, profiles.get(value.by.did)].every((profile) => { if (!profile) return true; profile = overlayProfile(profile); const viewer = profile.viewer; if ( viewer?.muted || viewer?.mutedByList || viewer?.blocking || viewer?.blockedBy || viewer?.blockingByList ) return false; const decision = moderateProfile(profile, moderation!); return !(['contentList', 'profileList'] as const).some((context) => { const ui = decision.ui(context); return ui.filter || ui.blur; }); }); }) .sort((a, b) => b.time - a.time); const rememberRepost = (uri: string, value: Repost) => { reposts.delete(uri); reposts.set(uri, { ...value, eventUri: uri }); if (reposts.size > 2000) reposts.delete(reposts.keys().next().value!); }; const persist = () => { if (!cache || !account || !moderation) return; if ( !interactionPending && (!freshModeration || !freshGraph || restorationPending || [...stored.values()].some((entry) => !entry.validated)) ) return; const snapshot: WallSnapshot = { posts: [...stored.values()] .filter((entry) => entry.validated && entry.items.length && eligible(entry.post.author.did)) .sort((a, b) => b.time - a.time || a.post.uri.localeCompare(b.post.uri)) .slice(0, 100) .map((entry) => entry.post), moderation, savedAt: Date.now() }; interactionPending = false; const payload = JSON.stringify({ posts: snapshot.posts, moderation: snapshot.moderation }); if (payload === lastWallPayload && Date.now() - lastWallSavedAt < 60 * 60_000) return; lastWallPayload = payload; lastWallSavedAt = Date.now(); const target = cache; saveTask = saveTask .then(() => target.saveWall(account, snapshot)) .catch((error) => { lastWallPayload = ''; report(error); }); }; const scheduleSave = () => { if (!freshModeration || signal.aborted) return; if (saveTimer !== undefined) return; saveTimer = setTimeout(() => { saveTimer = undefined; persist(); }, 10_000); }; const emit = () => { if (signal.aborted || !moderation) return; const ordered = [...stored.values()].sort( (a, b) => b.time - a.time || a.post.uri.localeCompare(b.post.uri) ); for (const entry of ordered.slice(500)) stored.delete(entry.post.uri); callbacks.items( ordered .slice(0, 500) .flatMap((entry) => entry.items) .slice(0, 300) ); if (interactionPending) persist(); scheduleSave(); }; const accept = (post: Post, validated = true, fromStream = false) => { if (signal.aborted || !moderation) return; const changes = postOverrides.get(post.uri)?.get(post.cid); post = { ...post, author: overlayProfile(post.author) }; if (changes) post = applyPostInteractions(post, changes); const reasons = validReposts(post.uri, post.cid); const direct = eligible(post.author.did); if ( suppressed(post.author.did) || post.author.viewer?.mutedByList || post.author.viewer?.blockingByList || post.author.viewer?.blockedBy || (!direct && !reasons.length) ) { stored.delete(post.uri); return; } const originalTime = Date.parse(post.indexedAt) || 0; if (!post.uri.startsWith(`at://${post.author.did}/app.bsky.feed.post/`)) return; const previous = stored.get(post.uri); const liveArrival = fromStream || previous?.liveArrival; const media = extractMedia(post, moderation, settings, revealed.has(post.uri)); const candidate = settings.includeReposts && media.length ? reasons[0] : undefined; const admitted = candidate && recurrence.accept( post.uri, candidate.eventUri!, candidate.time, settings.repostCooldownHours ?? 0 ) ? candidate : undefined; const retained = previous?.reason && reasons.find( (reason) => reason.eventUri === previous.reason?.eventUri && reason.time === previous.reason?.time && previous.reasonAdmission && recurrence.isCurrent(post.uri, previous.reasonAdmission) ); const latest = settings.includeReposts ? (admitted ?? retained) : undefined; const visible = direct || !!latest; const promoted = admitted && (admitted.eventUri !== previous?.reason?.eventUri || admitted.time !== previous?.reason?.time); const reasonAdmission = latest ? !promoted && previous?.reasonAdmission ? previous.reasonAdmission : recurrence.admission(post.uri, latest.eventUri, latest.time) : undefined; const admission = previous?.items.length && !promoted ? previous.admission : latest && (!direct || latest.time > originalTime) ? reasonAdmission! : recurrence.admission(post.uri); const items = (visible ? media : []).map((item) => { const old = previous?.items.find((value) => mediaAssetKey(value) === mediaAssetKey(item)); return { ...item, authorNotFollowed: (freshGraph && validated && !!latest && !follows.has(post.author.did) && post.author.did !== account) || undefined, sensitive: !direct || latest ? true : item.sensitive, repostedBy: latest && (!direct || latest.time > originalTime) ? latest.by.handle : undefined, repostedByDid: latest && (!direct || latest.time > originalTime) ? latest.by.did : undefined, repostedByAvatar: latest && (!direct || latest.time > originalTime) ? profileAvatar(overlayProfile(profiles.get(latest.by.did) ?? latest.by), moderation!) : undefined, cached: !validated || old?.cached || undefined, liveArrival: old ? old.liveArrival : liveArrival, provisional: !validated || !freshModeration || !freshGraph || undefined, thumbhash: old?.thumbhash }; }); stored.delete(post.uri); const outer = AppBskyEmbedRecordWithMedia.validateView(post.embed); const embed = outer.success ? outer.value.media : post.embed; if ( AppBskyEmbedImages.validateView(embed).success || AppBskyEmbedVideo.validateView(embed).success ) { const time = Math.max(direct ? originalTime : 0, latest?.time ?? 0); stored.set(post.uri, { post, items, time: !promoted && previous?.items.length && visible ? previous.time : Number.isFinite(time) ? time : 0, validated, liveArrival, reason: latest, admission, reasonAdmission }); } }; const schedule = (delay = 150) => { if (signal.aborted || !ready || draining || flushTimer !== undefined || !pending.size) return; flushTimer = setTimeout(() => { flushTimer = undefined; void drain(); }, delay); }; const drain = async () => { if (signal.aborted || !ready || draining) return; draining = true; try { const batch = [...pending].filter(([, value]) => value.next <= Date.now()).slice(0, 25); if (!batch.length) return; let posts: Post[] = []; try { const response = await agent.app.bsky.feed.getPosts( { uris: batch.map(([uri]) => uri) }, { signal } ); posts = response.data.posts; } catch (error) { report(error); } if (signal.aborted) return; const hydrated = new Map(posts.map((post) => [post.uri, post])); for (const [uri, value] of batch) { if (pending.get(uri) !== value) continue; const post = hydrated.get(uri); if (post && post.cid === value.cid) { pending.delete(uri); accept(post, true, true); } else if (++value.attempts >= 4) { pending.delete(uri); } else { value.next = Date.now() + 500 * 2 ** value.attempts; } } emit(); } catch (error) { report(error); } finally { draining = false; schedule(250); } }; const reconcile = () => { if (!account) return; const dids = [...follows].filter(eligible).sort(); const groups = new Map(); for (let i = 0; i < dids.length; i += JETSTREAM_BATCH_SIZE) { const group = dids .slice(i, i + JETSTREAM_BATCH_SIZE) .filter((did): did is `did:${string}:${string}` => /^did:[a-z0-9]+:.+$/.test(did)); if (group.length) groups.set(group.join(','), group); } for (const [key, stream] of streams) { if (!groups.has(key)) { stream.abort(); streams.delete(key); connected.delete(key); } } for (const [key, group] of groups) { if (streams.has(key) || signal.aborted) continue; const stream = new AbortController(); streams.set(key, stream); void (async () => { let cursor: number | undefined; let retries = 0; while (!stream.signal.aborted) { try { const disconnected = () => { if (streams.get(key) === stream) { connected.delete(key); liveStatus(); } }; const connection = { idleTimeoutMs: 5 * 60_000, onConnect: () => { if (stream.signal.aborted || streams.get(key) !== stream) return; connected.add(key); retries = 0; liveStatus(); }, onDisconnect: disconnected, onReconnect: disconnected }; const options = { dids: group, collections: ['app.bsky.feed.post', 'app.bsky.feed.repost'], signal: stream.signal, cursor: { load: async () => cursor, save: async (seq) => { cursor = seq; } }, liveTransport: transportFactory ? transportFactory(connection) : sharedJetstreamTransport(account, connection), onError: (error) => { if (!stream.signal.aborted) report(error); } } satisfies LiveV1Opts; const events = FIREHOSE_INSTANCES.some(({ endpoint }) => endpoint === jetstreamEndpoint) ? new JetstreamV1(jetstreamEndpoint).live({ ...options, liveTransport: { stream: (getUrl, signal, opts) => options.liveTransport.stream( () => { // firehose.stream uses the v1 filters and cursor with its own path. const url = new URL(getUrl()); url.pathname = '/tap'; url.searchParams.set('kind', 'commit'); return url.href; }, signal, opts ) } }) : new Jetstream(jetstreamEndpoint).live({ ...options, kinds: ['commit'] }); for await (const event of events) { if (signal.aborted || stream.signal.aborted) break; if (cursor !== undefined && event.seq <= cursor) continue; cursor = event.seq; if (!connected.has(key)) { connected.add(key); liveStatus(); } if (event.kind !== 'commit' || !eligible(event.did)) continue; const collection = event.commit.collection; if (collection !== 'app.bsky.feed.post' && collection !== 'app.bsky.feed.repost') continue; const uri = `at://${event.did}/${collection}/${event.commit.rkey}`; if (!ready && historyAllowed) { if (touched.size >= 2000) historyAllowed = false; else touched.add(uri); } if (collection === 'app.bsky.feed.repost') { reposts.delete(uri); if (event.commit.operation !== 'delete') { const record = AppBskyFeedRepost.validateRecord(event.commit.record); if ( record.success && postUri.test(record.value.subject.uri) && Number.isFinite(Date.parse(record.value.createdAt)) ) { const { subject, createdAt } = record.value; rememberRepost(uri, { uri: subject.uri, cid: subject.cid, by: profiles.get(event.did) ?? { did: event.did, handle: event.did }, time: Date.parse(createdAt) }); if (pending.size >= 500) pending.delete(pending.keys().next().value!); pending.set(subject.uri, { cid: subject.cid, attempts: 0, next: 0 }); schedule(); } } remoderate(); continue; } for (const [key, value] of reposts) if (value.uri === uri) reposts.delete(key); if (cachedTouches.has(uri)) cachedTouches.set(uri, true); revealed.delete(uri); stored.delete(uri); pending.delete(uri); if (event.commit.operation !== 'delete') { if (pending.size >= 500) pending.delete(pending.keys().next().value!); pending.set(uri, { cid: event.commit.cid, attempts: 0, next: 0 }); schedule(); } if (ready) emit(); } } catch (error) { if (!stream.signal.aborted) report(error); } finally { if (streams.get(key) === stream) connected.delete(key); } if (stream.signal.aborted) break; liveStatus(); await new Promise((resolve) => { const finish = () => { clearTimeout(timer); stream.signal.removeEventListener('abort', finish); resolve(); }; const timer = setTimeout(finish, Math.min(30_000, 1000 * 2 ** Math.min(retries++, 5))); stream.signal.addEventListener('abort', finish, { once: true }); }); } })(); } liveStatus(); }; const loadGraph = async (): Promise => { const followProfiles = new Map(); const paginate = async (kind: 'follows' | 'blocks') => { const result = new Set(); const cursors = new Set(); let cursor: string | undefined; do { signal.throwIfAborted(); const data = kind === 'follows' ? ( await agent.app.bsky.graph.getFollows( { actor: account!, limit: 100, cursor }, { signal } ) ).data : (await agent.app.bsky.graph.getBlocks({ limit: 100, cursor }, { signal })).data; const profiles = 'follows' in data ? data.follows : data.blocks; for (const profile of profiles) { result.add(profile.did); if (kind === 'follows') followProfiles.set(profile.did, { ...profile, $type: 'app.bsky.actor.defs#profileViewBasic' }); } cursor = data.cursor; if (cursor && cursors.has(cursor)) throw new Error('Graph pagination repeated a cursor'); if (cursor) cursors.add(cursor); } while (cursor); return [...result]; }; const [follows, blocks] = await Promise.all([paginate('follows'), paginate('blocks')]); profiles.clear(); for (const [did, profile] of followProfiles) profiles.set(did, profile); return { follows, blocks, syncedAt: Date.now() }; }; const remoderate = () => { for (const [uri, value] of reposts) { if (!eligible(value.by.did) || blocks.has(value.uri.split('/')[2])) reposts.delete(uri); } const snapshot = Array.from(stored.values()); for (const entry of snapshot) accept(entry.post, entry.validated); for (const uri of pending.keys()) { if (!eligible(uri.split('/')[2]) && !validReposts(uri, pending.get(uri)?.cid).length) pending.delete(uri); } reconcile(); emit(); }; const refresh = async () => { const graphTask = loadGraph() .then(async (snapshot) => { signal.throwIfAborted(); snapshot = overlayGraph(snapshot); graphSyncedAt = snapshot.syncedAt; hasCachedGraph = true; freshGraph = true; follows = new Set(snapshot.follows); blocks = new Set(snapshot.blocks); for (const value of reposts.values()) value.by = profiles.get(value.by.did) ?? value.by; remoderate(); callbacks.graph(snapshot, cache!.persistent); await saveGraph(snapshot); }) .catch((error) => { report(error); if (!hasCachedGraph) throw error; }); const prefsTask = (async () => { const preferences = await agent.getPreferences(); const labelDefs = await agent.getLabelDefinitions(preferences.moderationPrefs); signal.throwIfAborted(); agent.configureLabelers(preferences.moderationPrefs.labelers.map((labeler) => labeler.did)); revealed.clear(); moderation = { userDid: account, prefs: preferences.moderationPrefs, labelDefs }; callbacks.moderation?.(moderation); freshModeration = true; remoderate(); })(); const results = await Promise.allSettled([graphTask, prefsTask]); for (const result of results) if (result.status === 'rejected') throw result.reason; const candidates = [...stored.values()].filter((entry) => !eligible(entry.post.author.did)); for (let index = 0; index < candidates.length && !signal.aborted; index += 25) { const batch = candidates.slice(index, index + 25); const response = await agent.app.bsky.feed.getPosts( { uris: batch.map((entry) => entry.post.uri) }, { signal } ); if (signal.aborted) return; const posts = new Map(response.data.posts.map((post) => [post.uri, post])); for (const entry of batch) { const uri = entry.post.uri; if (stored.get(uri) !== entry || pending.has(uri)) continue; const post = posts.get(uri); if (post?.cid === entry.post.cid) accept(post); else { stored.delete(uri); for (const [key, value] of reposts) if (value.uri === uri && value.cid === entry.post.cid) reposts.delete(key); } } emit(); } }; const revalidate = async (uris: string[]) => { try { for (let index = 0; index < uris.length && !signal.aborted; index += 25) { const batch = uris.slice(index, index + 25); try { const response = await agent.app.bsky.feed.getPosts({ uris: batch }, { signal }); if (signal.aborted) return; const posts = new Map(response.data.posts.map((post) => [post.uri, post])); for (const uri of batch) { if (cachedTouches.get(uri) || stored.get(uri)?.validated) continue; const post = posts.get(uri); if (post) accept(post); else stored.delete(uri); } emit(); } catch (error) { report(error); } } } finally { cachedTouches.clear(); restorationPending = false; scheduleSave(); } }; const startup = Promise.resolve().then(async () => { try { if (!account) throw new Error('Sign in before starting the feed'); status('Loading follow graph and moderation…'); cache = await cacheFactory(); signal.throwIfAborted(); try { let [snapshot, wall] = await Promise.all([ cache.load(account).catch((error) => { report(error); return null; }), cache.loadWall(account).catch((error) => { report(error); return null; }) ]); signal.throwIfAborted(); if (snapshot) { const original = snapshot; snapshot = overlayGraph(snapshot); graphSyncedAt = snapshot.syncedAt; if (JSON.stringify(original) !== JSON.stringify(snapshot)) void saveGraph(snapshot); hasCachedGraph = true; follows = new Set(snapshot.follows); blocks = new Set(snapshot.blocks); callbacks.graph(snapshot, cache.persistent); if ( wall && wall.moderation.userDid === account && Date.now() - wall.savedAt <= WALL_SNAPSHOT_MAX_AGE && wall.savedAt <= Date.now() + 60_000 ) { moderation = wall.moderation; callbacks.moderation?.(moderation); agent.configureLabelers(moderation.prefs.labelers.map((labeler) => labeler.did)); for (const post of wall.posts.slice(0, 100)) accept(post, false); const items = [...stored.values()].flatMap((entry) => entry.items); const hashes = await cache .loadThumbhashes(account, items.map(mediaAssetKey)) .catch((error) => { report(error); return {}; }); signal.throwIfAborted(); for (const item of items) { const hash = (hashes as Record)[mediaAssetKey(item)]; if (hash) item.thumbhash = encodeThumbhash(hash); } emit(); for (const uri of stored.keys()) cachedTouches.set(uri, false); } reconcile(); if (cachedTouches.size) { restorationPending = true; revalidationTask = revalidate([...cachedTouches.keys()]); } } } catch (error) { report(error); } let refreshFailed = false; try { await refresh(); } catch (error) { if (!moderation || !hasCachedGraph) throw error; refreshFailed = true; report(error); status('Showing cached media; refresh failed'); } signal.throwIfAborted(); if (!refreshFailed) status('Loading recent media…'); let cursor: string | undefined; const cursors = new Set(); try { for (let page = 0; page < 8 && historyAllowed && freshModeration; page++) { const response = await agent.app.bsky.feed.getTimeline( { limit: 100, cursor }, { signal } ); signal.throwIfAborted(); if (!historyAllowed) break; for (const entry of response.data.feed) { if (touched.has(entry.post.uri)) continue; if (!entry.reason) accept(entry.post); else { const reason = AppBskyFeedDefs.validateReasonRepost(entry.reason); if (!reason.success || !eligible(reason.value.by.did)) continue; const { uri, by, indexedAt } = reason.value; if ( !uri || !repostUri(uri, by.did) || touched.has(uri) || !postUri.test(entry.post.uri) || !Number.isFinite(Date.parse(indexedAt)) ) continue; const strongref = AppBskyFeedRepost.validateRecord({ $type: 'app.bsky.feed.repost', subject: { uri: entry.post.uri, cid: entry.post.cid }, createdAt: indexedAt }); if (!strongref.success) continue; rememberRepost(uri, { uri: entry.post.uri, cid: entry.post.cid, by, time: Date.parse(indexedAt) }); accept(entry.post); } } emit(); cursor = response.data.cursor; if ( !cursor || cursors.has(cursor) || [...stored.values()].reduce((n, entry) => n + entry.items.length, 0) >= 300 ) break; cursors.add(cursor); } } catch (error) { report(error); } signal.throwIfAborted(); ready = true; touched.clear(); schedule(); if (!refreshFailed) liveStatus(); interval = setInterval(() => { if (refreshTask || signal.aborted) return; refreshTask = refresh() .catch(report) .finally(() => { refreshTask = undefined; }); }, 5 * 60_000); } catch (error) { report(error); stop(); } }); function stop() { if (signal.aborted) return; if (saveTimer !== undefined) clearTimeout(saveTimer); persist(); controller.abort(); if (interval !== undefined) clearInterval(interval); if (flushTimer !== undefined) clearTimeout(flushTimer); for (const stream of streams.values()) stream.abort(); streams.clear(); connected.clear(); reportConnections(); pending.clear(); stored.clear(); reposts.clear(); touched.clear(); void Promise.allSettled([startup, refreshTask, revalidationTask, saveTask]) .then(() => cache?.close()) .catch(() => {}); } return Object.assign(stop, { markDisplayed(uri: string) { const entry = stored.get(uri); if (!signal.aborted && entry?.items.length) { const { admission } = entry; recurrence.markDisplayed(uri, admission.eventUri, admission.time, admission); } }, reconcileInteraction(update: InteractionUpdate) { if (signal.aborted) return; if (update.kind === 'post') { let versions = postOverrides.get(update.uri); if (!versions) postOverrides.set(update.uri, (versions = new Map())); versions.set(update.cid, { ...versions.get(update.cid), ...update.changes }); } else { const { did, kind: _kind, ...changes } = update; actorOverrides.set(did, { ...actorOverrides.get(did), ...changes }); if (update.following !== undefined) { if (update.following) follows.add(did); else follows.delete(did); } if (update.blocking !== undefined) { if (update.blocking) blocks.add(did); else blocks.delete(did); } if (update.following !== undefined || update.blocking !== undefined) { if (hasCachedGraph && cache) { const snapshot = { follows: [...follows], blocks: [...blocks], syncedAt: graphSyncedAt }; callbacks.graph(snapshot, cache.persistent); void saveGraph(snapshot); } } } interactionPending = true; remoderate(); }, updateSettings(next: FeedSettings) { settings = next; revealed.clear(); remoderate(); }, setJetstreamEndpoint(value?: string) { const next = normalizeJetstreamEndpoint(value) ?? DEFAULT_JETSTREAM; if (signal.aborted || next === jetstreamEndpoint) return; jetstreamEndpoint = next; // Cursors belong to the old instance; start fresh subscriptions on the new one. for (const stream of streams.values()) stream.abort(); streams.clear(); connected.clear(); reconcile(); }, revealPost(uri: string) { const entry = stored.get(uri); if (!entry?.validated || !freshGraph || !freshModeration) return; if (revealed.size >= 500) revealed.delete(revealed.values().next().value!); revealed.add(uri); accept(entry.post); emit(); } }); }