Skip to content

Commit bad9d26

Browse files
browclaude
andauthored
fix(mobile): push every message in your own Solo chats (#8615)
## Summary Mobile push only covered Solo chats through explicit mentions. Solo chats are private streams rather than DMs, and the push lease subscribed channel-wide only to DMs. Agent replies in your own Solo chats therefore never woke the phone. The lease now subscribes channel-wide to the viewer's own joined, unarchived Solo chats, using the same predicate as the Solo tab, including older unlabelled Solo chats listed in the encrypted Solo record. Self-authored messages stay excluded through the existing lease ignores. Muted Solo chats stay out of the lease, like muted channels, so they push only on mention. The lease waits while the Solo record loads so an unresolved record never drops legacy Solo chats. If that record fails with no cached copy, DM and mention updates proceed without the legacy chats, which the Solo tab cannot list either, and they return when it recovers. Solo chats created by someone else still push only on mention, matching how they appear in the channel list. A lease is bounded by its channel count (750), by the relay's advertised plaintext and content sizes, and by NIP-44's 65535-byte plaintext ceiling. DMs always stay, as before. Solo chats fill the remaining room most recent first, sized with the publisher's own lease encoding, the exact NIP-44 payload length and the largest endpoint the relay accepts. Sizes are computed rather than built, so a relay's advertised limits never drive an allocation. Solo chats beyond the room push only on mention instead of failing the lease update or publication, and Notifications settings says how many. A relay too small even for DMs and mentions fails push setup visibly instead of saving a lease it would reject. Publication accepts only endpoint grants in the gateway's JSON-safe alphabet, so the sizing assumption holds. Thread replies outside DMs still do not push unless they mention you. That is a separate gap. ### Related issue None found. ### Validation - Added test: the desired lease includes joined DMs and the viewer's own Solo chats, and includes legacy Solo chats from the Solo record, and excludes archived and muted Solo chats, other people's Solo chats, and unlabelled private streams. It fails without the fix. - Added test: the sync provider holds the desired lease while the Solo record loads, proceeds without legacy chats if the record fails, and adds them once it arrives. It fails if loading is treated as empty or if a failure blocks updates. - Added tests: over the channel count, and over each size limit (relay plaintext, relay content, NIP-44 plaintext), the lease keeps every DM and exactly the newest Solo chats, reports the rest as omitted, and is accepted by `publishBuzzDevPushLease` with a grant at the relay's endpoint limit, while a max-length grant that JSON would escape is rejected as not a gateway grant. A relay advertising a 2^50-byte endpoint limit is sized without allocating. Each row fails if its guard is removed. - Added test: a relay whose content or plaintext limit cannot fit even the lease without Solo chats rejects that lease at publication, and the provider fails setup instead of saving it. It fails if the guard is removed. - Added test: the NIP-44 payload length matches real encryption at every padding boundary up to 65535 bytes. - Added test: Notifications settings shows "Older Solo chats notify only on mention" with the omitted count. It fails without the row. - Mobile lint and the full mobile test suite pass. - Not exercised end to end on a device. A signed dev build was installed on a test iPhone against a personal dev relay, but the phone's dev identity owns no assistant there, so the device could not create a Solo chat without exporting its key. This will be validated in dogfood. The relay matcher already handles channel-wide `#h` leases for DMs, and Solo messages use the same kind and scoping. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 4ff02bf commit bad9d26

10 files changed

Lines changed: 604 additions & 49 deletions

File tree

‎mobile/lib/features/settings/settings_page.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import '../../shared/clipboard_utils.dart';
1515
import '../../shared/success_haptic.dart';
1616
import '../../shared/push/push_relay_capability_provider.dart';
1717
import '../../shared/push/push_bootstrap.dart';
18+
import '../../shared/push/push_subscription_provider.dart';
1819
import '../../shared/relay/relay.dart';
1920
import '../../shared/utils/string_utils.dart';
2021
import '../pairing/pairing_provider.dart';

‎mobile/lib/features/settings/settings_page/notifications_section.dart‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ class _NotificationsSection extends ConsumerWidget {
2525
return const SizedBox.shrink();
2626
}
2727
final canToggle = hasCapability || community.pushNotificationsEnabled;
28+
final omittedSoloChats = community.pushNotificationsEnabled
29+
? ref.watch(pushSubscriptionSyncProvider).value ?? 0
30+
: 0;
2831

2932
void setEnabled(bool enabled) {
3033
unawaited(
@@ -72,6 +75,14 @@ class _NotificationsSection extends ConsumerWidget {
7275
],
7376
),
7477
),
78+
if (omittedSoloChats > 0)
79+
AppListRow(
80+
key: const ValueKey('push-solo-coverage'),
81+
title: 'Older Solo chats notify only on mention',
82+
subtitle: omittedSoloChats == 1
83+
? '1 chat is past this relay’s notification limit.'
84+
: '$omittedSoloChats chats are past this relay’s notification limit.',
85+
),
7586
],
7687
);
7788
}

‎mobile/lib/shared/crypto/nip44.dart‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,15 @@ String nip44Decrypt(Uint8List conversationKey, String payloadBase64) {
8888
return _unpad(padded);
8989
}
9090

91+
/// Length of the base64 payload [nip44Encrypt] returns for a plaintext of
92+
/// [plaintextBytes] UTF-8 bytes, or null when NIP-44 cannot encrypt it.
93+
int? nip44PayloadLength(int plaintextBytes) {
94+
if (plaintextBytes < 1 || plaintextBytes > 65535) return null;
95+
// version(1) || nonce(32) || length(2) || padded || mac(32)
96+
final payload = 1 + 32 + 2 + _calcPaddedLen(plaintextBytes) + 32;
97+
return 4 * ((payload + 2) ~/ 3);
98+
}
99+
91100
// ── Padding ─────────────────────────────────────────────────────────────────
92101

93102
int _calcPaddedLen(int unpaddedLen) {

‎mobile/lib/shared/push/dev_push_lease.dart‎

Lines changed: 54 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,51 @@ const _maxSafeJsonInteger = 9007199254740991;
1616
const _maxLeaseLifetimeSeconds = 2592000;
1717
const _lowercaseHex64Pattern = r'^[0-9a-f]{64}$';
1818
const _installationIdPattern = r'^[0-9a-f]{32}$';
19+
// The gateway's `<key id>.<base64url>` grant grammar, which JSON never escapes.
20+
const _endpointGrantPattern = r'^[A-Za-z0-9_.-]+$';
21+
22+
/// Whether an active lease carrying [subscriptions] fits [descriptor]'s
23+
/// plaintext and content limits with any endpoint grant and generation it
24+
/// accepts. Sizes are computed, not built, since the limits come from the relay.
25+
bool buzzPushSubscriptionsFitLease(
26+
BuzzPushLeaseDescriptor descriptor,
27+
List<BuzzPushSubscription> subscriptions,
28+
) {
29+
final withoutEndpoint = utf8
30+
.encode(
31+
_activeLeasePlaintext(
32+
descriptor: descriptor,
33+
endpoint: '',
34+
generation: _maxSafeJsonInteger,
35+
subscriptions: subscriptions,
36+
),
37+
)
38+
.length;
39+
// Publication accepts only grants JSON never escapes, so one at the endpoint
40+
// limit adds exactly it.
41+
final plaintext = withoutEndpoint + descriptor.maxEndpointLength;
42+
final content = nip44PayloadLength(plaintext);
43+
return plaintext <= descriptor.maxPlaintextLength &&
44+
content != null &&
45+
content <= descriptor.maxContentLength;
46+
}
47+
48+
String _activeLeasePlaintext({
49+
required BuzzPushLeaseDescriptor descriptor,
50+
required String endpoint,
51+
required int generation,
52+
required List<BuzzPushSubscription> subscriptions,
53+
}) => jsonEncode(<String, dynamic>{
54+
'v': 1,
55+
'origin': descriptor.origin,
56+
'transport': descriptor.transport,
57+
'endpoint': endpoint,
58+
'generation': generation,
59+
'active': true,
60+
'subscriptions': [
61+
for (final subscription in subscriptions) subscription.toJson(),
62+
],
63+
});
1964

2065
class BuzzPushLeaseDescriptor {
2166
final String origin;
@@ -331,18 +376,12 @@ Future<BuzzPushLeasePublication> publishBuzzDevPushLease({
331376
throw const FormatException('Endpoint grant is already expired');
332377
}
333378

334-
final plaintextMap = <String, dynamic>{
335-
'v': 1,
336-
'origin': descriptor.origin,
337-
'transport': descriptor.transport,
338-
'endpoint': grant.endpointGrant,
339-
'generation': effectiveLeaseGeneration,
340-
'active': true,
341-
'subscriptions': [
342-
for (final subscription in subscriptions) subscription.toJson(),
343-
],
344-
};
345-
final plaintext = jsonEncode(plaintextMap);
379+
final plaintext = _activeLeasePlaintext(
380+
descriptor: descriptor,
381+
endpoint: grant.endpointGrant,
382+
generation: effectiveLeaseGeneration,
383+
subscriptions: subscriptions,
384+
);
346385
if (utf8.encode(plaintext).length > descriptor.maxPlaintextLength) {
347386
throw const FormatException('lease plaintext exceeds the advertised limit');
348387
}
@@ -513,6 +552,9 @@ void _validateGrant(
513552
'Endpoint grant violates the advertised endpoint limit',
514553
);
515554
}
555+
if (!RegExp(_endpointGrantPattern).hasMatch(grant.endpointGrant)) {
556+
throw const FormatException('Endpoint grant is not a gateway grant');
557+
}
516558
if (grant.endpointEpoch <= 0) {
517559
throw const FormatException('Endpoint grant epoch is invalid');
518560
}

‎mobile/lib/shared/push/push_subscription.dart‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ const buzzPushMaxSubscriptions = 16;
1212
const buzzPushMaxIgnoreFilters = 8;
1313
const buzzPushHellthreadParticipantLimit = 20;
1414

15+
/// Channels one lease can follow channel-wide after its self-directed
16+
/// subscription, and muted channels its ignores can cover after the
17+
/// self-authored ignore.
18+
const buzzPushMaxChannelWideChannels =
19+
(buzzPushMaxSubscriptions - 1) * buzzPushChannelChunkSize;
20+
const buzzPushMaxMutedChannels =
21+
(buzzPushMaxIgnoreFilters - 1) * buzzPushChannelChunkSize;
22+
1523
const _supportedNotificationClasses = {'default'};
1624
const _filterKeys = {'kinds', 'authors', '#p', '#h', '#e'};
1725
final _exactHexPattern = RegExp(r'^[0-9a-f]{64}$');

‎mobile/lib/shared/push/push_subscription_provider.dart‎

Lines changed: 111 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,68 +4,159 @@ import '../../features/channels/channel.dart';
44
import '../../features/channels/channel_mutes/channel_mutes_provider.dart';
55
import '../../features/channels/channels_provider.dart';
66
import '../auth/auth.dart';
7+
import '../me/me_sync.dart';
78
import '../relay/relay_provider.dart';
9+
import 'dev_push_lease.dart';
810
import 'push_subscription.dart';
911
import 'push_relay_capability_provider.dart';
1012
import 'push_setup_recovery.dart';
1113

1214
/// Keeps the persisted desired lease and the App Group snapshot aligned with
1315
/// the active identity, joined channels, and mute state. This is desired client
1416
/// policy only. Relay-accepted authority is introduced by lease publication.
15-
final pushSubscriptionSyncProvider = FutureProvider.autoDispose<void>((
17+
///
18+
/// Yields how many Solo chats the lease had no room for.
19+
final pushSubscriptionSyncProvider = FutureProvider.autoDispose<int>((
1620
ref,
1721
) async {
1822
try {
1923
if (ref.watch(authProvider).value?.status != AuthStatus.authenticated) {
20-
return;
24+
return 0;
2125
}
2226
final active = ref.watch(activeCommunityProvider).value;
27+
final descriptor = ref.watch(currentRelayPushDescriptorProvider).value;
2328
if (active == null ||
2429
!active.pushNotificationsEnabled ||
25-
ref.watch(currentRelayPushDescriptorProvider).value == null) {
26-
return;
30+
descriptor == null) {
31+
return 0;
2732
}
2833
final channels = ref.watch(channelsProvider).value;
2934
final mutes = ref.watch(channelMutesProvider);
3035
if (channels == null || !mutes.isReady) {
31-
return;
36+
return 0;
3237
}
3338

34-
final subscriptions = desiredBuzzPushSubscriptions(
39+
// Legacy Solo chats are listed only in the Solo record. Wait while it
40+
// loads so an unresolved record never drops them. If it fails without a
41+
// cached copy, keep DMs and mentions current; the Solo tab cannot list
42+
// those chats either, and recovery republishes them.
43+
final soloRecord = ref.watch(meGroupsProvider);
44+
if (soloRecord.isLoading && !soloRecord.hasValue) return 0;
45+
46+
final desired = desiredBuzzPushSubscriptions(
3547
community: active,
48+
descriptor: descriptor,
3649
channels: channels,
50+
legacySoloChannelIds: soloRecord.value?.channels ?? const [],
3751
mutedChannelIds: [
3852
for (final entry in mutes.store.channels.entries)
3953
if (entry.value.muted) entry.key,
4054
],
4155
);
42-
if (subscriptions == null) return;
56+
if (desired == null) return 0;
4357
await ref
4458
.read(communityListProvider.notifier)
45-
.updateDesiredPushSubscriptions(active.id, subscriptions);
59+
.updateDesiredPushSubscriptions(active.id, desired.subscriptions);
60+
return desired.omittedSoloChats;
4661
} catch (error, stack) {
4762
reportPushSetupError('subscription synchronization', error, stack);
4863
rethrow;
4964
}
5065
}, retry: pushSetupRetry);
5166

52-
List<BuzzPushSubscription>? desiredBuzzPushSubscriptions({
67+
/// The desired lease, and how many Solo chats it had no room for.
68+
({List<BuzzPushSubscription> subscriptions, int omittedSoloChats})?
69+
desiredBuzzPushSubscriptions({
5370
required Community community,
71+
required BuzzPushLeaseDescriptor descriptor,
5472
required Iterable<Channel> channels,
5573
required Iterable<String> mutedChannelIds,
74+
Iterable<String> legacySoloChannelIds = const [],
5675
}) {
5776
final pubkey = community.pubkey ?? pubkeyFromNsec(community.nsec);
5877
if (pubkey == null || pubkey.isEmpty) return null;
59-
return buildDesiredBuzzPushSubscriptions(
60-
myPubkey: pubkey,
61-
channelIds: [
62-
// Activity surfaces channel-wide traffic only for joined DM channels.
63-
// Other message kinds enter the inbox through an exact #p mention or
64-
// participant-thread tag, so subscribing to every joined channel would
65-
// over-notify compared with the product predicate.
66-
for (final channel in channels)
67-
if (channel.isDm && channel.isMember && !channel.isArchived) channel.id,
68-
],
69-
mutedChannelIds: mutedChannelIds,
78+
final muted = {for (final id in mutedChannelIds) id.toLowerCase()};
79+
final candidates = _channelWideCandidates(
80+
pubkey: pubkey,
81+
channels: channels,
82+
muted: muted,
83+
legacySoloChannelIds: legacySoloChannelIds,
84+
);
85+
List<BuzzPushSubscription> lease(int soloCount) =>
86+
buildDesiredBuzzPushSubscriptions(
87+
myPubkey: pubkey,
88+
channelIds: [...candidates.dms, ...candidates.solos.take(soloCount)],
89+
mutedChannelIds: mutedChannelIds,
90+
);
91+
92+
// Each Solo chat only adds bytes, so keep the most recent ones that fit.
93+
var fitting = candidates.solos.length;
94+
if (!buzzPushSubscriptionsFitLease(descriptor, lease(fitting))) {
95+
// Without Solo chats only DMs and mentions remain. A relay too small for
96+
// those cannot carry push, so fail setup rather than save a lease that
97+
// publication would reject.
98+
if (!buzzPushSubscriptionsFitLease(descriptor, lease(0))) {
99+
throw const FormatException(
100+
'The relay push limits are too small for a lease.',
101+
);
102+
}
103+
var low = 0;
104+
var high = fitting - 1;
105+
while (low < high) {
106+
final mid = (low + high + 1) ~/ 2;
107+
if (buzzPushSubscriptionsFitLease(descriptor, lease(mid))) {
108+
low = mid;
109+
} else {
110+
high = mid - 1;
111+
}
112+
}
113+
fitting = low;
114+
}
115+
return (
116+
subscriptions: lease(fitting),
117+
omittedSoloChats: candidates.omitted + candidates.solos.length - fitting,
118+
);
119+
}
120+
121+
/// Channel-wide traffic pushes only for joined DMs and the viewer's own Solo
122+
/// chats, which are conversations with them. Other channels push through an
123+
/// exact #p mention, so subscribing to every joined channel would over-notify.
124+
///
125+
/// DMs always stay, as before. Solo chats follow most recent first, within the
126+
/// lease's channel counts; the rest push only on mention.
127+
({List<String> dms, List<String> solos, int omitted}) _channelWideCandidates({
128+
required String pubkey,
129+
required Iterable<Channel> channels,
130+
required Set<String> muted,
131+
required Iterable<String> legacySoloChannelIds,
132+
}) {
133+
bool isMuted(String id) => muted.contains(id.toLowerCase());
134+
final joined = [
135+
for (final channel in channels)
136+
if (channel.isMember && !channel.isArchived) channel,
137+
];
138+
final dms = [
139+
for (final channel in joined)
140+
if (channel.isDm) channel.id,
141+
];
142+
// Muted Solo chats stay out, like muted channels, so they push only on
143+
// mention.
144+
final ordered = [
145+
for (final channel in joined)
146+
if (!channel.isDm &&
147+
!isMuted(channel.id) &&
148+
channel.isPersonalChat(pubkey, legacySoloChannelIds))
149+
channel,
150+
]..sort(_mostRecentFirst);
151+
final room =
152+
buzzPushMaxChannelWideChannels - dms.where((id) => !isMuted(id)).length;
153+
final solos = [for (final solo in ordered.take(room < 0 ? 0 : room)) solo.id];
154+
return (dms: dms, solos: solos, omitted: ordered.length - solos.length);
155+
}
156+
157+
int _mostRecentFirst(Channel a, Channel b) {
158+
final byRecency = (b.lastMessageAt ?? b.createdAt).compareTo(
159+
a.lastMessageAt ?? a.createdAt,
70160
);
161+
return byRecency != 0 ? byRecency : a.id.compareTo(b.id);
71162
}

‎mobile/test/features/settings/settings_page_test.dart‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import 'package:buzz/shared/theme/theme.dart';
1212
import 'package:buzz/shared/push/push_bridge.dart';
1313
import 'package:buzz/shared/push/dev_push_lease.dart';
1414
import 'package:buzz/shared/push/push_relay_capability_provider.dart';
15+
import 'package:buzz/shared/push/push_subscription_provider.dart';
1516
import 'package:buzz/shared/relay/app_lifecycle_provider.dart';
1617
import 'package:buzz/shared/widgets/app_list.dart';
1718
import 'package:buzz/shared/widgets/app_list_card.dart';
@@ -170,6 +171,8 @@ void main() {
170171
savedPrefsProvider.overrideWithValue(prefs),
171172
activeCommunityProvider.overrideWith((ref) async => community),
172173
currentRelayPushDescriptorProvider.overrideWith((ref) => capability),
174+
// The lease had no room for 12 older Solo chats.
175+
pushSubscriptionSyncProvider.overrideWith((ref) async => 12),
173176
appLifecycleProvider.overrideWith(_SettingsLifecycleNotifier.new),
174177
buzzPushAuthorizationStatusReaderProvider.overrideWithValue(
175178
() async => BuzzPushAuthorizationStatus.authorized,
@@ -191,6 +194,14 @@ void main() {
191194
findsOneWidget,
192195
);
193196
expect(tester.widget<Switch>(find.byType(Switch)).value, isTrue);
197+
expect(
198+
find.text('Older Solo chats notify only on mention'),
199+
findsOneWidget,
200+
);
201+
expect(
202+
find.text('12 chats are past this relay’s notification limit.'),
203+
findsOneWidget,
204+
);
194205
debugDefaultTargetPlatformOverride = null;
195206
});
196207

‎mobile/test/shared/crypto/nip44_interop_test.dart‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,22 @@ void main() {
1818
'{"version":1,"theme":"catppuccin-latte","accent":"#f97316","followSystem":false}',
1919
);
2020
});
21+
22+
test('predicts the encrypted payload length at every padding boundary', () {
23+
final key = getConversationKey(
24+
'0000000000000000000000000000000000000000000000000000000000000001',
25+
'79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
26+
);
27+
for (final length in [
28+
1, 32, 33, 256, 257, 4096, 4097, 32768, 32769, 65535, //
29+
]) {
30+
expect(
31+
nip44PayloadLength(length),
32+
nip44Encrypt(key, 'x' * length).length,
33+
reason: '$length bytes',
34+
);
35+
}
36+
expect(nip44PayloadLength(0), isNull);
37+
expect(nip44PayloadLength(65536), isNull);
38+
});
2139
}

‎mobile/test/shared/push/push_root_isolation_test.dart‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -423,8 +423,9 @@ const _descriptor = BuzzPushLeaseDescriptor(
423423
executorPubkey: 'pubkey',
424424
transport: 'apns',
425425
maxLeaseTtlSeconds: 3600,
426-
maxContentLength: 4096,
427-
maxPlaintextLength: 4096,
426+
// The relay's NIP-11 limits, which fit a DM lease at the endpoint limit.
427+
maxContentLength: 65536,
428+
maxPlaintextLength: 32768,
428429
maxEndpointLength: 2048,
429430
maxStringLength: 512,
430431
);

0 commit comments

Comments
 (0)