mirror of
https://github.com/block/buzz.git
synced 2026-11-24 02:02:07 +00:00
On iOS, a notification that shows a channel or DM message now offers
**Reply**. The user types a reply in the notification and sends it
without opening the app.
- The reply goes in a subthread under the notified message (its thread
root is the message's own root, or the message itself when top-level). A
Solo chat takes no thread replies, so there it goes at the chat's top
level.
- It always mentions the notified message's sender, so the person or
agent being answered is notified. Typed `@name` text stays plain, since
a notification has no mention autocomplete.
- It is sent by the app's own send path. iOS starts the Flutter engine
when it wakes the app in the background, and the reply reopens the relay
connection (closed after the background grace period), waiting a bounded
time for it before sending.
- A sent reply marks the conversation read **up to the notified
message** (newer messages stay unread) and clears that notification and
earlier ones from the same conversation.
- An unsent reply (offline, relay error, timeout, a channel the user
isn't in) keeps the typed text as a draft, after any draft already
there, and shows a "Reply not sent" notification that opens the
conversation.
For now only notifications from the community selected in the app offer
Reply: replying must not switch communities, and the app can only reach
the selected one. Forum posts and fallback notifications that show no
message offer none. The design and the options considered are in
`docs/adr/0004-notification-reply.md`.
### Before / after
Long-pressing a message notification (synthetic names and text). Before
has no reply field (captured by sending the notification without its new
reply category, which is how main presents it); after shows one with
Send.
| Before | After |
| --- | --- |
|

|

|
### Demo
With the app backgrounded past the relay grace period, replying from the
notification lands the reply in a subthread under the message:
https://github.com/user-attachments/assets/37df7e28-aa46-4521-938e-8af5faa77b83
### Regressions
Nothing existing changes unless the user taps Reply. Notifications gain
a category and a small reply context in `userInfo`; tapping a
notification still opens the conversation as before. The relay reconnect
only happens for a pending reply and then falls back to the normal
background disconnect, so idle background behavior and network use are
unchanged. Reply failures end in a draft and a "Reply not sent"
notification rather than touching other state.
### Validation
- End to end on an iOS 27 simulator against a real community: with the
app backgrounded past the relay grace period, replied from the
notification; the reply appeared in a subthread under the message,
mentioning its sender. The demo above was recorded before the review
fixes (session hold, community fence, origin-community drafts, composer
draft sync); the same run was repeated on the current head, 9b9c8b0, and
the reply again appeared in the subthread with no "Reply not sent"
notification.
- Human testing is waived for this repo's mobile client; the simulator
run above replaces it. Not yet exercised on a physical device or on a
cold launch (app not running).
- Added tests: a Dart journey covering top-level, in-thread and Solo
replies, another community (draft kept in that community), a failed
send, a channel the user isn't in (draft appended), a reply arriving
while running, an unreachable relay, and a community switch while
connecting (not sent, draft kept in the reply's community); a
relay-session test that a background-work hold keeps the grace
disconnect off, including one already waiting on cleanup, until released
or its limit; a composer step showing a draft appended elsewhere appears
in the mounted composer and survives its next edit; a relay-session test
for reconnecting a paused session and timing out (fails without the
fix); Swift tests for reply context encoding, NIP-10 root parsing
aligned with the app, and request validation.
- `relay_session.dart` was at its 1200-line cap, so the background
connect lives in a new part file and three existing test hooks moved
unchanged into another.
- Full `mobile-test`, `mobile-check` and BuzzPushKit `swift test` pass.
---------
Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
224 lines
7.4 KiB
Dart
224 lines
7.4 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
import '../relay/relay.dart';
|
|
import '../theme/theme_provider.dart';
|
|
|
|
const _draftsPrefsKey = 'compose_drafts_v1';
|
|
const _maxDrafts = 50;
|
|
|
|
/// A locally persisted, unsent composer draft.
|
|
///
|
|
/// Mobile has no durable relay-backed draft store (desktop keeps drafts
|
|
/// locally too), so drafts are device-local by design: the inbox Drafts
|
|
/// filter reflects what this device's composer has in flight.
|
|
@immutable
|
|
class ComposeDraft {
|
|
/// `<channelId>` for channel composers, `<channelId>:<threadHeadId>` for
|
|
/// thread composers.
|
|
final String key;
|
|
final String channelId;
|
|
final String? threadHeadId;
|
|
final String text;
|
|
|
|
/// Literal picker labels bound to exact keys, never authorization metadata.
|
|
/// An empty key/value is a malformed-record tombstone; send must refuse it.
|
|
final Map<String, String> mentionKeys;
|
|
final int updatedAt; // unix seconds
|
|
|
|
const ComposeDraft({
|
|
required this.key,
|
|
required this.channelId,
|
|
required this.threadHeadId,
|
|
required this.text,
|
|
required this.updatedAt,
|
|
this.mentionKeys = const {},
|
|
});
|
|
|
|
Map<String, dynamic> toJson() => {
|
|
'key': key,
|
|
'channel_id': channelId,
|
|
if (threadHeadId != null) 'thread_head_id': threadHeadId,
|
|
'text': text,
|
|
'mention_keys': mentionKeys,
|
|
'updated_at': updatedAt,
|
|
};
|
|
|
|
static ComposeDraft? fromJson(Object? raw) {
|
|
if (raw is! Map<String, dynamic>) return null;
|
|
final key = raw['key'];
|
|
final channelId = raw['channel_id'];
|
|
final text = raw['text'];
|
|
final updatedAt = raw['updated_at'];
|
|
if (key is! String || channelId is! String || text is! String) return null;
|
|
if (text.trim().isEmpty) return null;
|
|
final bindings = raw['mention_keys'];
|
|
final mentionKeys = <String, String>{};
|
|
if (raw.containsKey('mention_keys')) {
|
|
if (bindings is! Map<String, dynamic>) {
|
|
mentionKeys[''] = '';
|
|
} else {
|
|
final labels = <String>{};
|
|
for (final entry in bindings.entries) {
|
|
if (!labels.add(entry.key.toLowerCase())) mentionKeys[''] = '';
|
|
final value = entry.value;
|
|
mentionKeys[entry.key] =
|
|
entry.key.isNotEmpty &&
|
|
value is String &&
|
|
RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(value)
|
|
? value.toLowerCase()
|
|
: '';
|
|
}
|
|
}
|
|
}
|
|
return ComposeDraft(
|
|
key: key,
|
|
channelId: channelId,
|
|
threadHeadId: raw['thread_head_id'] is String
|
|
? raw['thread_head_id'] as String
|
|
: null,
|
|
mentionKeys: Map.unmodifiable(mentionKeys),
|
|
text: text,
|
|
updatedAt: updatedAt is int ? updatedAt : 0,
|
|
);
|
|
}
|
|
}
|
|
|
|
String composeDraftKey(String channelId, {String? threadHeadId}) =>
|
|
threadHeadId == null ? channelId : '$channelId:$threadHeadId';
|
|
|
|
/// SharedPreferences-backed store of unsent composer drafts, newest first.
|
|
///
|
|
/// Drafts are plaintext, so persistence is namespaced by community (relay)
|
|
/// and account pubkey: switching community or account rebuilds this provider
|
|
/// against that identity's own store and can never surface another
|
|
/// identity's draft text.
|
|
class ComposeDraftsNotifier extends Notifier<List<ComposeDraft>> {
|
|
late String _prefsKey;
|
|
|
|
@override
|
|
List<ComposeDraft> build() {
|
|
// Rebuild (and re-read the identity-scoped store) whenever the active
|
|
// community or the derived account pubkey changes.
|
|
final config = ref.watch(relayConfigProvider);
|
|
final pubkey = ref.watch(myPubkeyProvider) ?? 'anon';
|
|
_prefsKey = _storeKey(config.baseUrl, pubkey);
|
|
return _readStore(config, pubkey);
|
|
}
|
|
|
|
static String _storeKey(String origin, String pubkey) =>
|
|
'$_draftsPrefsKey:$origin:$pubkey';
|
|
|
|
List<ComposeDraft> _readStore(RelayConfig config, String pubkey) {
|
|
final prefs = ref.read(savedPrefsProvider);
|
|
final raw = readMigratedPref<String>(
|
|
prefs,
|
|
canonicalKey: _storeKey(config.baseUrl, pubkey),
|
|
legacyKey: _storeKey(config.storedOrigin, pubkey),
|
|
read: prefs.getString,
|
|
write: prefs.setString,
|
|
);
|
|
if (raw == null) return const [];
|
|
try {
|
|
final decoded = jsonDecode(raw);
|
|
if (decoded is! List) return const [];
|
|
final drafts = decoded
|
|
.map(ComposeDraft.fromJson)
|
|
.whereType<ComposeDraft>()
|
|
.toList();
|
|
drafts.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
|
return drafts;
|
|
} catch (_) {
|
|
return const [];
|
|
}
|
|
}
|
|
|
|
/// Adds [text] after any draft at [key] in the store of the community at
|
|
/// [config], which need not be the selected one. Another community's
|
|
/// store is written without being loaded here, so its text never appears
|
|
/// in this community. Completes once it's saved.
|
|
Future<void> append({
|
|
required RelayConfig config,
|
|
required String key,
|
|
required String channelId,
|
|
String? threadHeadId,
|
|
required String text,
|
|
}) {
|
|
final pubkey = pubkeyFromNsec(config.nsec) ?? 'anon';
|
|
final selected = _storeKey(config.baseUrl, pubkey) == _prefsKey;
|
|
final drafts = selected ? state : _readStore(config, pubkey);
|
|
final existing = drafts.where((d) => d.key == key).firstOrNull;
|
|
final existingText = existing?.text.trimRight() ?? '';
|
|
final draft = ComposeDraft(
|
|
key: key,
|
|
channelId: channelId,
|
|
threadHeadId: threadHeadId,
|
|
text: existingText.isEmpty ? text : '$existingText\n\n$text',
|
|
mentionKeys: existing?.mentionKeys ?? const {},
|
|
updatedAt: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
|
);
|
|
final next = [draft, ...drafts.where((d) => d.key != key)];
|
|
final kept = next.length > _maxDrafts ? next.sublist(0, _maxDrafts) : next;
|
|
if (!selected) return _write(_storeKey(config.baseUrl, pubkey), kept);
|
|
state = List.unmodifiable(kept);
|
|
return _write(_prefsKey, kept);
|
|
}
|
|
|
|
/// Persist [text] for the composer identified by [key]. Empty text removes
|
|
/// the draft.
|
|
void save({
|
|
required String key,
|
|
required String channelId,
|
|
String? threadHeadId,
|
|
required String text,
|
|
Map<String, String> mentionKeys = const {},
|
|
}) {
|
|
if (text.trim().isEmpty) {
|
|
remove(key);
|
|
return;
|
|
}
|
|
final existing = state.where((d) => d.key == key).firstOrNull;
|
|
if (existing?.text == text &&
|
|
mapEquals(existing?.mentionKeys, mentionKeys)) {
|
|
return;
|
|
}
|
|
final draft = ComposeDraft(
|
|
key: key,
|
|
channelId: channelId,
|
|
threadHeadId: threadHeadId,
|
|
text: text,
|
|
mentionKeys: Map.unmodifiable(mentionKeys),
|
|
updatedAt: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
|
);
|
|
final next = [draft, ...state.where((d) => d.key != key)];
|
|
_persist(next.length > _maxDrafts ? next.sublist(0, _maxDrafts) : next);
|
|
}
|
|
|
|
void remove(String key) {
|
|
if (!state.any((d) => d.key == key)) return;
|
|
_persist([...state.where((d) => d.key != key)]);
|
|
}
|
|
|
|
/// Read text and selected identities from the same persisted snapshot.
|
|
ComposeDraft? draftFor(String key) =>
|
|
state.where((d) => d.key == key).firstOrNull;
|
|
|
|
String? textFor(String key) => draftFor(key)?.text;
|
|
|
|
void _persist(List<ComposeDraft> drafts) {
|
|
state = List.unmodifiable(drafts);
|
|
_write(_prefsKey, drafts);
|
|
}
|
|
|
|
Future<void> _write(String prefsKey, List<ComposeDraft> drafts) => ref
|
|
.read(savedPrefsProvider)
|
|
.setString(prefsKey, jsonEncode([for (final d in drafts) d.toJson()]));
|
|
}
|
|
|
|
final composeDraftsProvider =
|
|
NotifierProvider<ComposeDraftsNotifier, List<ComposeDraft>>(
|
|
ComposeDraftsNotifier.new,
|
|
);
|