Files
buzz/mobile/lib/shared/read_state/thread_follows_format.dart
Will Pfleger 890824f072 feat(read-state): sync mark read, channel mark unread and thread follows (#9501)
Reading, mark read, whole-channel mark unread and thread follow choices
now sync across a person's installations. This PR specifies the rules in
NIP-RS and implements them in the mobile app.

## Spec (`docs/nips/NIP-RS.md`)

- Defines *catch-up* and *displayed*.
- A catch-up advances the channel's own frontier (top-level messages) or
`thread:<root>`. `activity:` and `thread-activity:` become read-only
legacy keys.
- Explicit mark read is synchronized state. A first explicit read of a
message with no override group writes only its `msg:` frontier. Display,
dwell, scroll, catch-up and mention visibility create no `msg:` entries.
- Only whole-channel override groups are published, merged and cleared
with the counter. Readers ignore peer `msg:` and `thread:` groups.
- Single-message and thread mark unread stay on the device. They end
once the merged frontier covering them passes their baseline, from any
installation, or on display, catch-up or explicit read. The section also
states clearing scope, the accepted concurrency limitation and capacity.
- When the merged override union no longer fits the primary, the client
rewrites the primary compactly from the groups its last published
primary carried, each canonical against current frontiers. It never
omits merged groups or tombstone floors that primary carried, and
override actions fail visibly.
- Adds Buzz Thread Follow Choices: `thread-follows:<32hex>` coordinates,
validation, three-state verdict, last-writer merge with ties going to
unfollow, publication and recovery, legacy import at `at = 0`, and
capacity.

## Mobile

- Catch-up writes the main frontier. A flat timeline reads up to the
newest top-level message it reached.
- Explicit mark read publishes. Passive `msg:` marks stay on the device.
- Whole-channel mark unread publishes an override group and merges peer
groups. An explicit read or catch-up clears it, even when no frontier
moves. The action fails visibly at the uint32 limit or when the primary
is full. A synced clear the primary can't carry is rolled back, and the
channel view reports it once while the failure stands.
- Device-local message and Inbox unread overrides record a baseline and
clear when a covering frontier passes it, including one merged from a
peer.
- Thread follows move from local storage to the synced `thread-follows:`
slots. They share the read-state `client_id`, journal, `created_at`
sequence, snapshot and live subscription, and spill across up to 16
slots with stable placement. An unreadable coordinate marks follow state
incomplete and blocks this installation's follow publication.
- Follow and unfollow are refused on every cold start of the writer
until its first complete recovery of its own state succeeds and every
owned follow head is readable. Cached follows show at once. A refused
tap changes nothing and shows "Follow choices are not ready. Connect and
try again." Reads, catch-up and both kinds of mark unread are not gated.
- A follow tap is accepted only once journaled. The accepted own head,
pending edits and the exact in-flight packet are kept apart, so a retry
or restore never drops or re-attributes an edit.
- Pre-sync local follows are imported at `at = 0` after a complete
merge, once their channel is known from a relay event. An imported key
is settled, and its legacy copy retired, only when the journal write the
import awaited covered it and that entry is still current.
- An explicit unfollow suppresses ordinary replies at live and catch-up
admission. A change in follow choices drops the unread replies already
counted for an unfollowed thread. A newly followed thread re-runs
catch-up only for its own channel.
- A reading clear refused because the view hasn't completely loaded is
retried after the next complete snapshot, including when publishing was
shut off at the time. The view also counts as not completely loaded
while the live subscription is reconnecting, so a read made while the
phone is offline can't erase a newer unread mark set on another device.
Offline, whole-channel mark unread is still refused, with a message.
- Read-state events, including live ones, are verified with native
libsecp256k1 before they are used.
- A pending unread packet is counted as published only when no newer own
head outranks it. When a newer head supersedes it, a successor is built
above that head from the saved intent, and a late echo of a replaced
packet doesn't overwrite what was published.
- When the merged unread state overfills the primary and the compact
fallback can't carry a pending mark, the packet stays pending and the
"read state full" error shows. Other queued reads and follows in the
same flush still publish.
- When this installation's own unread record can't be decoded, only the
unread step is held: that record isn't overwritten, its pending marks
stay queued and the sync error shows. Other queued reads and follows in
the same flush still publish.
- The sync notice stays up after an unsupported refusal until a new
session. Offline, it can't be tapped and says it will retry when back
online.
- Two-device fixtures against an in-memory relay cover channel
round-trips and clears, stray message groups, the first explicit message
read, the primary cap, follow propagation, same-second and
backward-clock follow publication, legacy import, retry after a failed
publish, unreadable coordinates and slot packing. Recovery fixtures
cover the startup gate, journal failures during flush, interleaved
legacy imports, and restore of an older journal.

## Relay

- Conforming `thread-follows:<32 hex>` records get the NIP-RS treatment:
a replaced record is purged, and a stale resend of an older one is
refused. Records with a mismatched `t` tag keep ordinary
replaceable-event behavior.

## Known gap

- An unread packet held for capacity can age past the relay's timestamp
window. The relay then refuses it, and the refusal path retires it
without the capacity check, so the error clears and other installations
don't get that mark. The mark stays on the device.

Related:
[block/buzz-app#3552](https://github.com/block/buzz-app/pull/3552)

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Signed-off-by: Will Pfleger <wpfleger@squareup.com>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
2026-11-19 17:02:58 -05:00

186 lines
6.1 KiB
Dart

import 'dart:convert';
import '../relay/nostr_models.dart';
import 'read_state_format.dart';
/// Synced thread follow choices (NIP-RS, Buzz Thread Follow Choices): each
/// installation publishes its own explicit follows and unfollows in its own
/// `thread-follows:<slot>` coordinates, and readers merge every slot.
const threadFollowsDTagPrefix = 'thread-follows:';
const threadFollowsTag = 'thread-follows';
/// At most this many own follow coordinates per installation.
const threadFollowsMaxSlots = 16;
final _slotId = RegExp(r'^[0-9a-f]{32}$');
final _threadKey = RegExp(r'^[^:]+:[0-9a-f]{64}$');
/// The wire key of a thread: `<channel-id>:<root-event-id>`.
String threadFollowKey(String channelId, String rootId) => '$channelId:$rootId';
/// The root event id of a [threadFollowKey].
String threadFollowRoot(String key) => key.substring(key.lastIndexOf(':') + 1);
/// The channel id of a [threadFollowKey].
String threadFollowChannel(String key) =>
key.substring(0, key.lastIndexOf(':'));
bool isValidThreadFollowKey(String key) => _threadKey.hasMatch(key);
/// One explicit choice: follow or unfollow, at the time of the action.
typedef ThreadFollowChoice = ({bool follow, int at});
/// The merge rule: the greater `at` wins; on equal `at`, unfollow wins.
ThreadFollowChoice mergeThreadFollowChoices(
ThreadFollowChoice a,
ThreadFollowChoice b,
) {
if (a.at != b.at) return a.at > b.at ? a : b;
return a.follow ? b : a;
}
/// The slot id of a follow coordinate's `d` tag, or null when the event is
/// not a valid follow coordinate (and so must be ignored).
String? threadFollowsSlotOf(NostrEvent event) {
final dTags = [
for (final tag in event.tags)
if (tag.isNotEmpty && tag[0] == 'd') tag,
];
if (dTags.length != 1 || dTags.single.length < 2) return null;
final d = dTags.single[1];
if (!d.startsWith(threadFollowsDTagPrefix)) return null;
final slot = d.substring(threadFollowsDTagPrefix.length);
return _slotId.hasMatch(slot) ? slot : null;
}
/// One decoded follow coordinate. [entries] keeps each entry's raw object so
/// its author can carry unknown fields unchanged; [extra] does the same for
/// unknown top-level fields.
class ThreadFollowsBlob {
final String clientId;
final Map<String, Map<String, Object?>> entries;
final Map<String, Object?> extra;
const ThreadFollowsBlob({
required this.clientId,
required this.entries,
this.extra = const {},
});
Map<String, ThreadFollowChoice> get choices => {
for (final MapEntry(:key, :value) in entries.entries)
key: (follow: value['follow'] as bool, at: value['at'] as int),
};
/// Deterministic plaintext: sorted thread keys, so an unchanged slot
/// encodes to the same bytes.
String encode() => jsonEncode({
...extra,
'v': 1,
'client_id': clientId,
'threads': {
for (final key in entries.keys.toList()..sort()) key: entries[key],
},
});
}
/// Decodes [plaintext], or returns null when the coordinate is unreadable:
/// its entries are then unknown, not absent.
ThreadFollowsBlob? decodeThreadFollowsBlob(String plaintext) {
final Object? parsed;
try {
parsed = jsonDecode(plaintext);
} catch (_) {
return null;
}
final record = asStringObjectMap(parsed);
if (record == null || record['v'] != 1) return null;
final clientId = record['client_id'];
if (clientId is! String) return null;
final threads = asStringObjectMap(record['threads']);
if (threads == null) return null;
final entries = <String, Map<String, Object?>>{};
for (final MapEntry(:key, :value) in threads.entries) {
final entry = asStringObjectMap(value);
final at = entry?['at'];
if (!isValidThreadFollowKey(key) ||
entry == null ||
entry['follow'] is! bool ||
at is! int ||
at < 0 ||
at > 4294967295) {
return null;
}
entries[key] = Map.unmodifiable(entry);
}
return ThreadFollowsBlob(
clientId: clientId,
entries: entries,
extra: {
for (final MapEntry(:key, :value) in record.entries)
if (key != 'v' && key != 'client_id' && key != 'threads') key: value,
},
);
}
/// Places [keys] into follow slots of at most [maxBytes] plaintext each,
/// keeping every key in the slot it already occupies in [previous] and
/// filling the rest first-fit. Throws [StateError] past
/// [threadFollowsMaxSlots] slots.
List<Set<String>> packThreadFollowKeys(
Map<String, Map<String, Object?>> entries, {
required String clientId,
List<Set<String>> previous = const [],
List<Map<String, Object?>> extras = const [],
int maxBytes = readStatePlaintextBytes,
}) {
// Each slot is measured with its own unknown fields; new slots have none.
int size(Set<String> keys, int index) => utf8
.encode(
ThreadFollowsBlob(
clientId: clientId,
entries: {for (final key in keys) key: entries[key]!},
extra: index < extras.length ? extras[index] : const {},
).encode(),
)
.length;
int cost(String key) =>
utf8.encode(jsonEncode(key)).length +
1 +
utf8.encode(jsonEncode(entries[key])).length;
final slots = [
for (final old in previous) {...old.where(entries.containsKey)},
];
if (slots.isEmpty) slots.add({});
// Exact compact JSON sizes, adding each entry and its comma without
// re-encoding whole slots.
final sizes = [
for (var index = 0; index < slots.length; index++)
size(slots[index], index),
];
final assigned = {for (final slot in slots) ...slot};
for (final key
in entries.keys.where((k) => !assigned.contains(k)).toList()..sort()) {
final bytes = cost(key);
var placed = false;
for (var index = 0; index < slots.length; index++) {
final extra = bytes + (slots[index].isEmpty ? 0 : 1);
if (sizes[index] + extra <= maxBytes) {
slots[index].add(key);
sizes[index] += extra;
placed = true;
break;
}
}
if (!placed) {
sizes.add(size({}, slots.length) + bytes);
slots.add({key});
}
}
if (slots.length > threadFollowsMaxSlots ||
sizes.any((size) => size > maxBytes)) {
throw StateError('Thread follow choices exceed their slot capacity');
}
return slots;
}