@@ -27,9 +27,16 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
2727 final Map <String , int > _timestamps = {};
2828 final Map <String , int > _snapshotAt = {};
2929 final List <String > _seenIds = [];
30+ // Keys the live subscription asks for. Only tracked keys are subscribed:
31+ // a community's presence heartbeats arrive many times a second.
32+ final Set <String > _subscribedKeys = {};
3033 void Function ()? _presenceUnsub;
3134 Timer ? _poll;
3235 Timer ? _queued;
36+ Timer ? _resubscribe;
37+ int _nextSubscription = 0 ;
38+ int _activeSubscription = 0 ;
39+ bool _subscribeAttempted = false ;
3340 int _generation = 0 ;
3441 int _epoch = 0 ;
3542 bool _querying = false ;
@@ -53,6 +60,9 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
5360 _timestamps.clear ();
5461 _snapshotAt.clear ();
5562 _seenIds.clear ();
63+ _subscribedKeys.clear ();
64+ _activeSubscription = 0 ;
65+ _subscribeAttempted = false ;
5666 _pending
5767 ..clear ()
5868 ..addAll (_tracked);
@@ -63,11 +73,13 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
6373 _poll? .cancel ();
6474 _queued? .cancel ();
6575 _queued = null ;
76+ _resubscribe? .cancel ();
77+ _resubscribe = null ;
6678 });
6779 if (sessionState.status == SessionStatus .connected &&
6880 lifecycle == AppLifecycleState .resumed) {
6981 _poll = Timer .periodic (const Duration (seconds: 60 ), (_) {
70- if (_presenceUnsub == null ) {
82+ if (_presenceUnsub == null || ! _subscribedKeys. containsAll (_tracked) ) {
7183 unawaited (_subscribe (generation));
7284 } else if (! _querying) {
7385 _pending.addAll (_tracked);
@@ -82,10 +94,32 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
8294
8395 /// Request initial presence for exact keys. Repeated render calls coalesce.
8496 void track (List <String > pubkeys) {
97+ var added = false ;
8598 for (final key in pubkeys.map ((key) => key.trim ().toLowerCase ())) {
86- if (key.isNotEmpty && _tracked.add (key)) _pending.add (key);
99+ if (key.isNotEmpty && _tracked.add (key)) {
100+ _pending.add (key);
101+ added = true ;
102+ }
103+ }
104+ // While live (the poll runs only then), new keys are read once the
105+ // subscription covers them, so no live event falls between the snapshot
106+ // and the subscription.
107+ if (added && (_poll? .isActive ?? false )) {
108+ _queueResubscribe (_generation);
109+ } else {
110+ _schedule (_generation);
87111 }
88- _schedule (_generation);
112+ }
113+
114+ void _queueResubscribe (int generation) {
115+ _resubscribe ?? = Timer (Duration .zero, () {
116+ _resubscribe = null ;
117+ // Without a subscription, the next poll opens one with every key.
118+ if (generation == _generation &&
119+ (_presenceUnsub != null || ! _subscribeAttempted)) {
120+ unawaited (_subscribe (generation));
121+ }
122+ });
89123 }
90124
91125 void _schedule (int generation) {
@@ -105,39 +139,64 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
105139 }
106140
107141 Future <void > _subscribe (int generation) async {
108- if (_opening || generation != _generation) return ;
142+ if (_opening ||
143+ generation != _generation ||
144+ _tracked.isEmpty ||
145+ (_presenceUnsub != null && _subscribedKeys.containsAll (_tracked))) {
146+ return ;
147+ }
109148 _opening = true ;
110- _retrying = false ;
149+ _subscribeAttempted = true ;
150+ final keys = _tracked.toList ()..sort ();
151+ final subscription = ++ _nextSubscription;
111152 var closed = false ;
153+ // The subscription being replaced keeps delivering until this one opens.
154+ bool current () =>
155+ generation == _generation &&
156+ ! closed &&
157+ subscription == _activeSubscription;
112158 try {
113159 final unsub = await ref
114160 .read (relaySessionProvider.notifier)
115161 .subscribeWithStatus (
116- const NostrFilter (kinds: [EventKind .presenceUpdate], limit: 0 ),
162+ NostrFilter (
163+ kinds: const [EventKind .presenceUpdate],
164+ authors: keys,
165+ limit: 0 ,
166+ ),
117167 (event) {
118- if (generation == _generation && ! closed && ! _retrying) {
119- _handlePresenceEvent (event);
120- }
168+ if (current () && ! _retrying) _handlePresenceEvent (event);
121169 },
122170 onStatusChanged: (status) {
123- if (generation != _generation || closed ) return ;
171+ if (! current () ) return ;
124172 _retrying = status == RelaySubscriptionStatus .retrying;
125173 _invalidateSnapshot ();
126174 if (! _retrying) _schedule (generation);
127175 },
128176 onClosed: (_) {
129177 if (generation != _generation || closed) return ;
130178 closed = true ;
179+ if (subscription != _activeSubscription) return ;
131180 _presenceUnsub? .call ();
132181 _presenceUnsub = null ;
182+ _subscribedKeys.clear ();
133183 _invalidateSnapshot ();
134184 },
135185 );
136186 if (generation != _generation || closed) {
137187 unsub ();
138188 return ;
139189 }
190+ final previous = _presenceUnsub;
191+ _activeSubscription = subscription;
192+ _retrying = false ;
140193 _presenceUnsub = unsub;
194+ _subscribedKeys
195+ ..clear ()
196+ ..addAll (keys);
197+ previous? .call ();
198+ // Keys tracked while this one opened need a wider subscription.
199+ if (! _subscribedKeys.containsAll (_tracked)) _queueResubscribe (generation);
141200 _schedule (generation);
142201 } catch (error) {
143202 if (generation == _generation) {
0 commit comments