mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
Ticket 5 of the [Android push design](https://github.com/block/buzz/pull/9555). It builds on [#9556 Dart body formatter](https://github.com/block/buzz/pull/9556), now merged. Native posting, the 2 s generic notification, the foreground check and FCM are ticket 6 and are not here. ## What it does `resolvePushWake` is the Dart half of an Android push wake. A wake carries no content, so it means "sync now": the function reads the saved communities, signs a `/query` to each relay (the same NIP-98 request the app uses), fetches what is newer than the last shown message, applies the same eligibility rules as the iOS resolver, and returns every eligible unshown message with title, body (ticket 4's formatter), conversation id, navigation target and category (direct message or mention). It is plain Dart: no Flutter UI and no Riverpod app state, so a headless engine can run it. - Eligibility is a port of the iOS `PushLeaseMatcher`, applied to the same subscriptions the app already syncs: self-authored messages and muted DMs are ignored (mutes reach the subscriptions for DMs only, as on iOS), and a message tagging more than 20 people is dropped. Only joined DMs and `#p` mentions notify. - Results are bounded: newest 20 overall, newest 8 per conversation. Messages cut by the caps are still recorded as shown, so a later wake does not bring them back. - `PushWakeRunner` runs one wake at a time per process. A wake that arrives mid-run sets a rerun flag, and every waiting caller gets one result with the notifications of every pass. ## Decisions - **Shown record.** One empty marker file per message, created exclusively. That is atomic across isolates and processes with no lock, and the foreground app can write the same record through the same `claim`. The newest time is the maximum of the marker names, so it can never move backwards (a separate cursor file would lose updates between concurrent writers). Markers older than 15 minutes before the newest are deleted. The app's other stores don't fit: `shared_preferences` has no atomic read-modify-write across isolates, and secure storage has none either. File locks were avoided because POSIX locks are per process, and the app and the background engine share a process. - **Claim before post.** `claim` is the post decision, so a message is returned at most once. If native posting then fails, the message is not offered again, as on iOS. - **Claim oldest first.** Each claim can advance the newest time, and claim rejects anything more than 15 minutes older, so messages are claimed oldest first. A wake cut short leaves only messages newer than everything it claimed, which the next fetch still covers. - **Fetch window.** Fetches start 15 minutes before the newest shown message, the same reorder window the iOS cache uses, and claim rejects anything older. With no record yet, the fetch looks back 15 minutes only, so a new install or community doesn't dump history. - **Timeouts.** 3 s per fetch request, 1.5 s for the sender and channel name lookup (which runs after messages are claimed, so a slow lookup costs only names), 5 s overall from entry, well under the ~8 s native watchdog. On expiry it returns what it has. `PushWakeResult.incomplete` lists communities that couldn't be read; with no notifications it tells the caller to use its generic fallback. Communities that failed record nothing, so the next wake retries them. - **Paging.** A relay answers each filter's newest `limit` events, so a page filled by messages that can't notify could hide an eligible one. A subscription whose 50-event page comes back full is read again below its oldest event, up to 5 pages per community; a community that stops at the cap, or whose later page fails, is reported incomplete and keeps what it read. A page over the 4 MiB cap is asked for again with half the events. - **Fresh reads.** Message filters ask for `"consistency": "strong"`, so a wake for a message that has just arrived isn't answered by a replica that lacks it. That costs one writer read per community per wake. - **Deadline.** The 5 s budget runs from entry, reading the community list included, and no request may outlast it. Claims already running get 250 ms to finish, and what a community claimed before the deadline is still returned. - **Thread target.** A reply opens its direct parent's thread, as the in-app inbox does; a broadcast reply opens the channel. - **Transport.** HTTP `/query` rather than a WebSocket: one round trip per community, no connection to keep, and the same request the iOS resolver sends. ## Regressions Nothing existing changes: the new files are not referenced by app code yet, so there is no runtime effect until ticket 6 wires them in. Bugs stay inside the new wake path. ## Open questions - Organization-protected relays need a federated-identity header, which the iOS extension gets from a shared session. The headless path sends none yet, so such a community is reported as failed. Wiring it belongs with ticket 6 or 7. - Before ticket 6 calls this: the notifications setting is read only at entry, where iOS rechecks before posting; and Solo chat titles get a `#` where iOS and the app show none. A wake the deadline cuts short claims oldest first, so it can show older messages and leave the newest for another wake that nothing prompts (each winning claim lists the store directory again, so a long offline backlog on slow storage is where this bites). Ticket 6 can rerun when a wake is incomplete but returned notifications, or batch the claims: oldest first, all markers created before one listing that checks and prunes, cap overflow still recorded. A claim that storage never answers can still be lost after the 250 ms grace. - First-wake baseline: with no shown record yet, a wake looks back only 15 minutes, so a phone's first wake after a longer outage (still inside the relay's delivery window) can miss the message that caused it and report complete. Ticket 7 owns the fix: write a bounded baseline at enrollment, before wakes are turned on. - A wake reads the community snapshot at entry; rechecking the saved community, identity and push preference just before posting is on ticket 6's list, before ticket 7 turns wakes on. - Sender names come only from profiles their authors signed. Channel titles come from kind 39000 events whose id and signature check out, but nothing yet checks that the signing key is the relay's, because the community record has no relay key. That check belongs with ticket 7's enrollment work, which learns the relay key. Until then a relay could only mislabel a notification the user is already entitled to. ### Validation Added tests: - `push_wake_journey_test.dart`: journeys against a fake relay (only `/query` over HTTP is fake): DM and mention notify; self-authored, muted, hellthread, unrelated and text-less messages don't; already shown doesn't repeat; several messages across two conversations after one wake; a missed wake recovered by the next; a catch-up after a quiet spell returns messages more than 15 minutes apart; several communities, including a wake stopped partway by a failed claim whose leftover message is far newer than the one claimed; per-conversation and overall caps without resurfacing; slow, silent and unreachable relays return inside the budget and recover on the next wake; two wakes in different "isolates" never notify twice; the app recording a message during a run is respected; a wake mid-run reruns once and loses or repeats nothing, and is reported incomplete when no budget is left to rerun. - The journeys now also cover: an eligible DM and mention behind a page of messages that can't notify; an oversized page retried at half size; a relay past the page cap, and a later page failing, both leaving the community unfinished; message reads pinned to the writer; reply and broadcast-reply tap targets; unsigned or forged names falling back to short keys; a community list that never loads, and storage that stalls one community's claim, both ending at the budget. - `shown_message_store_test.dart`: concurrent claims, the reorder window, future-dated messages, pruning. Break checks: removing the hellthread rule fails the first journey; making marker creation non-exclusive fails the concurrent-claim test and the two-isolate journey; claiming newest first fails the catch-up and partial-wake steps; dropping the skipped-rerun flag fails the rerun journey. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
233 lines
7.0 KiB
Dart
233 lines
7.0 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
|
|
import '../../shared/relay/thread_reference.dart';
|
|
import 'feed_item.dart';
|
|
|
|
/// Inbox filters, mirroring desktop's `InboxFilter` in
|
|
/// `desktop/src/features/home/lib/inbox.ts`.
|
|
enum InboxFilter {
|
|
all,
|
|
mention,
|
|
dm,
|
|
thread,
|
|
needsAction,
|
|
activity,
|
|
agentActivity,
|
|
reminders,
|
|
drafts,
|
|
}
|
|
|
|
/// Category ordering used to pick the label for a grouped conversation.
|
|
/// Mirrors desktop's `categoryPriority`.
|
|
int categoryPriority(String category) {
|
|
return switch (category) {
|
|
'needs_action' => 0,
|
|
'mention' => 1,
|
|
'agent_activity' => 2,
|
|
_ => 3,
|
|
};
|
|
}
|
|
|
|
/// Validated, lowercase thread IDs shared with timeline navigation.
|
|
({String? parentId, String? rootId}) threadReferenceOf(
|
|
List<List<String>> tags,
|
|
) => parseThreadReference(tags);
|
|
|
|
/// A thread reply also sent to the channel: it has a parent and the
|
|
/// broadcast tag. [isThreadReply] excludes it.
|
|
bool isChannelSentReply(List<List<String>> tags) =>
|
|
threadReferenceOf(tags).parentId != null && isBroadcastReply(tags);
|
|
|
|
/// A thread reply that is not broadcast — desktop's `isThreadReply`.
|
|
bool isThreadReply(List<List<String>> tags) {
|
|
return threadReferenceOf(tags).parentId != null && !isBroadcastReply(tags);
|
|
}
|
|
|
|
/// Stable conversation identity: `rootId ?? parentId ?? event.id`, except
|
|
/// ordinary (non-thread) DM messages, which group by DM channel identity so
|
|
/// one DM conversation renders as one row. Mirrors desktop's
|
|
/// `getInboxConversationId`.
|
|
String inboxConversationId(
|
|
List<List<String>> tags,
|
|
String eventId, {
|
|
String? dmChannelId,
|
|
}) {
|
|
final thread = threadReferenceOf(tags);
|
|
final threadId = thread.rootId ?? thread.parentId;
|
|
if (dmChannelId != null) return 'dm:$dmChannelId';
|
|
if (threadId != null) return threadId;
|
|
return eventId;
|
|
}
|
|
|
|
/// One conversation-grouped inbox row. Mirrors desktop's `InboxItem`.
|
|
@immutable
|
|
class InboxItem {
|
|
/// Stable conversation identity for the thread group.
|
|
final String conversationId;
|
|
|
|
/// Representative (latest) event id.
|
|
final String id;
|
|
|
|
/// Representative (latest) feed item.
|
|
final FeedItem item;
|
|
|
|
/// All events grouped into this conversation, unordered.
|
|
final List<FeedItem> groupItems;
|
|
|
|
/// Distinct categories present in the group, priority-sorted.
|
|
final List<String> categories;
|
|
|
|
final bool isActionRequired;
|
|
final int latestActivityAt;
|
|
|
|
const InboxItem({
|
|
required this.conversationId,
|
|
required this.id,
|
|
required this.item,
|
|
required this.groupItems,
|
|
required this.categories,
|
|
required this.isActionRequired,
|
|
required this.latestActivityAt,
|
|
});
|
|
|
|
/// Root id if any grouped event carries thread-reply tags.
|
|
String? get threadRootId {
|
|
for (final candidate in [item, ...groupItems]) {
|
|
if (isThreadReply(candidate.tags)) {
|
|
return threadReferenceOf(candidate.tags).rootId;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// The event the row should deep-link to: the oldest grouped event that
|
|
/// [isRead] rejects (oldest unread), falling back to the latest event.
|
|
FeedItem deepLinkTarget(bool Function(FeedItem event) isRead) {
|
|
FeedItem? oldestUnread;
|
|
for (final candidate in groupItems) {
|
|
if (isRead(candidate)) continue;
|
|
if (oldestUnread == null ||
|
|
candidate.createdAt < oldestUnread.createdAt) {
|
|
oldestUnread = candidate;
|
|
}
|
|
}
|
|
if (oldestUnread != null) return oldestUnread;
|
|
return item;
|
|
}
|
|
}
|
|
|
|
/// Contextual row label — desktop's `getInboxTypeLabel`:
|
|
/// "DM from X" / "Mentioned in" / "Needs action in" / "Thread in" / "... in".
|
|
({String text, String? channelLabel}) inboxTypeLabel(
|
|
InboxItem item, {
|
|
required String? channelName,
|
|
required bool isDm,
|
|
required String senderLabel,
|
|
}) {
|
|
if (isDm) {
|
|
return (
|
|
text: senderLabel.isNotEmpty ? 'DM from $senderLabel' : 'DM',
|
|
channelLabel: null,
|
|
);
|
|
}
|
|
|
|
// Label the event the row displays. A group can hold an older mention and
|
|
// a newer plain reply; the row shows the reply, so it must not say
|
|
// "Mentioned in". [InboxItem.categories] still drives filtering.
|
|
final category = item.item.category;
|
|
if (category == 'mention') {
|
|
return (
|
|
text: channelName != null ? 'Mentioned in' : 'Mentioned',
|
|
channelLabel: channelName,
|
|
);
|
|
}
|
|
if (category == 'needs_action') {
|
|
return (
|
|
text: channelName != null ? 'Needs action in' : 'Needs action',
|
|
channelLabel: channelName,
|
|
);
|
|
}
|
|
if (item.threadRootId != null) {
|
|
return (
|
|
text: channelName != null ? 'Thread in' : 'Thread',
|
|
channelLabel: channelName,
|
|
);
|
|
}
|
|
|
|
final headline = item.item.headline;
|
|
return (
|
|
text: channelName != null ? '$headline in' : headline,
|
|
channelLabel: channelName,
|
|
);
|
|
}
|
|
|
|
/// Whether [item] matches [filter] — desktop's `matchesInboxFilter`.
|
|
/// `reminders` and `drafts` are separate surfaces and never match here.
|
|
bool matchesInboxFilter(InboxItem item, InboxFilter filter) {
|
|
return switch (filter) {
|
|
InboxFilter.all => true,
|
|
InboxFilter.dm => item.conversationId.startsWith('dm:'),
|
|
InboxFilter.thread => [
|
|
item.item,
|
|
...item.groupItems,
|
|
].any((i) => isThreadReply(i.tags)),
|
|
InboxFilter.mention => item.categories.contains('mention'),
|
|
InboxFilter.needsAction => item.categories.contains('needs_action'),
|
|
InboxFilter.activity => item.categories.contains('activity'),
|
|
InboxFilter.agentActivity => item.categories.contains('agent_activity'),
|
|
InboxFilter.reminders || InboxFilter.drafts => false,
|
|
};
|
|
}
|
|
|
|
/// Group raw feed items into conversation rows sorted by latest activity.
|
|
/// [isDmChannel] identifies DM channels so their ordinary top-level messages
|
|
/// collapse into one row per DM conversation. Mirrors desktop's
|
|
/// `buildInboxItems`.
|
|
List<InboxItem> buildInboxItems(
|
|
Iterable<FeedItem> feedItems, {
|
|
bool Function(String channelId)? isDmChannel,
|
|
}) {
|
|
final groups = <String, List<FeedItem>>{};
|
|
for (final item in feedItems) {
|
|
final channelId = item.channelId;
|
|
final dmChannelId =
|
|
channelId != null && (isDmChannel?.call(channelId) ?? false)
|
|
? channelId
|
|
: null;
|
|
final key = inboxConversationId(
|
|
item.tags,
|
|
item.id,
|
|
dmChannelId: dmChannelId,
|
|
);
|
|
groups.putIfAbsent(key, () => []).add(item);
|
|
}
|
|
|
|
final rows = <InboxItem>[];
|
|
for (final entry in groups.entries) {
|
|
final items = entry.value;
|
|
var latest = items.first;
|
|
var latestActivityAt = 0;
|
|
for (final item in items) {
|
|
if (item.createdAt > latest.createdAt) latest = item;
|
|
if (item.createdAt > latestActivityAt) latestActivityAt = item.createdAt;
|
|
}
|
|
final categories = items.map((i) => i.category).toSet().toList()
|
|
..sort((a, b) => categoryPriority(a).compareTo(categoryPriority(b)));
|
|
|
|
rows.add(
|
|
InboxItem(
|
|
conversationId: entry.key,
|
|
id: latest.id,
|
|
item: latest,
|
|
groupItems: List.unmodifiable(items),
|
|
categories: List.unmodifiable(categories),
|
|
isActionRequired: categories.contains('needs_action'),
|
|
latestActivityAt: latestActivityAt,
|
|
),
|
|
);
|
|
}
|
|
|
|
rows.sort((a, b) => b.latestActivityAt.compareTo(a.latestActivityAt));
|
|
return rows;
|
|
}
|