mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +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>
235 lines
8.1 KiB
Dart
235 lines
8.1 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter/widgets.dart';
|
|
import 'package:flutter_hooks/flutter_hooks.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
import '../../shared/me/default_agent.dart';
|
|
import '../../shared/profile/user_cache_provider.dart';
|
|
import '../../shared/relay/relay.dart';
|
|
import '../../shared/drafts/compose_drafts_provider.dart';
|
|
import 'bestie_conversation.dart';
|
|
import 'channel.dart';
|
|
import 'channel_management_provider.dart';
|
|
import 'send_message_provider.dart';
|
|
|
|
const _quickSendChannel = MethodChannel('buzz/quick_send');
|
|
|
|
/// A quick send Buzz turned down, with a reason Siri reads out.
|
|
class _QuickSendRefused implements Exception {
|
|
const _QuickSendRefused(this.message);
|
|
final String message;
|
|
}
|
|
|
|
/// Answers quick sends from Siri and Shortcuts while Home is mounted.
|
|
///
|
|
/// iOS can run a quick send with Buzz in the background; the app still
|
|
/// builds Home then, so this leaf is where the send gets the community's
|
|
/// session and the Bestie's DM. It tells the platform once it can take sends.
|
|
class QuickSendHost extends HookConsumerWidget {
|
|
const QuickSendHost({super.key});
|
|
|
|
@override
|
|
Widget build(BuildContext context, WidgetRef ref) {
|
|
// Keeps the Bestie choice loaded for a send that arrives in the background.
|
|
ref.watch(defaultAgentProvider);
|
|
useEffect(() {
|
|
_quickSendChannel.setMethodCallHandler((call) async {
|
|
try {
|
|
return switch ((call.method, call.arguments)) {
|
|
('bestie', _) => await _bestie(ref),
|
|
(
|
|
'send',
|
|
{
|
|
'text': final String text,
|
|
'bestie': final String to,
|
|
'scope': final String scope,
|
|
},
|
|
) =>
|
|
await _quickSend(ref, text.trim(), to, scope),
|
|
_ => throw MissingPluginException(),
|
|
};
|
|
} on _QuickSendRefused catch (failure) {
|
|
throw PlatformException(code: 'failed', message: failure.message);
|
|
} on MissingPluginException {
|
|
rethrow;
|
|
} catch (failure) {
|
|
debugPrint('Quick send failed: $failure');
|
|
throw PlatformException(
|
|
code: 'failed',
|
|
message: "Buzz couldn't send that. Open Buzz to try again.",
|
|
);
|
|
}
|
|
});
|
|
unawaited(_quickSendChannel.invokeMethod<void>('ready'));
|
|
return () {
|
|
_quickSendChannel.setMethodCallHandler(null);
|
|
unawaited(_quickSendChannel.invokeMethod<void>('unready'));
|
|
};
|
|
}, const []);
|
|
return const SizedBox.shrink();
|
|
}
|
|
}
|
|
|
|
/// The Bestie a quick send will go to, named so the person can confirm it.
|
|
///
|
|
/// This is the saved choice, which may predate a change made on another
|
|
/// device that this one hasn't synced; naming it lets the person catch that.
|
|
Future<Map<String, String?>> _bestie(WidgetRef ref) async {
|
|
// Captured first: a switch during the awaits must not pair this
|
|
// community's scope with another's Bestie.
|
|
final scope = _scope(ref);
|
|
final bestie = await ref
|
|
.read(defaultAgentProvider.future)
|
|
.timeout(const Duration(seconds: 10));
|
|
if (bestie == null) {
|
|
throw const _QuickSendRefused('Choose a Bestie in Buzz first.');
|
|
}
|
|
if (ref.read(userCacheProvider)[bestie] == null) {
|
|
// Briefly: Siri can say "your Bestie" rather than keep the person waiting.
|
|
await ref
|
|
.read(userCacheProvider.notifier)
|
|
.preload([bestie])
|
|
.timeout(const Duration(seconds: 2), onTimeout: () => false);
|
|
}
|
|
_ensureScope(ref, scope);
|
|
return {
|
|
'pubkey': bestie,
|
|
'name': ref.read(userCacheProvider)[bestie]?.label,
|
|
'scope': scope,
|
|
};
|
|
}
|
|
|
|
/// The account and community a confirmed Bestie belongs to.
|
|
String _scope(WidgetRef ref) =>
|
|
'${ref.read(relayConfigProvider).baseUrl} ${ref.read(myPubkeyProvider)}';
|
|
|
|
/// Refuses a send whose confirmation was for another account or community.
|
|
void _ensureScope(WidgetRef ref, String scope) {
|
|
if (_scope(ref) != scope) {
|
|
throw const _QuickSendRefused(
|
|
'Buzz switched communities. Try again to confirm the new Bestie.',
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Posts [content] in the direct conversation with [bestie].
|
|
///
|
|
/// When the send fails or Buzz can't tell whether it landed, the message is
|
|
/// kept as that DM's composer draft so it isn't lost.
|
|
Future<void> _quickSend(
|
|
WidgetRef ref,
|
|
String content,
|
|
String bestie,
|
|
String scope,
|
|
) async {
|
|
_ensureScope(ref, scope);
|
|
// Bound to this community: each refuses to act after a switch.
|
|
final actions = ref.read(channelActionsProvider);
|
|
final send = ref.read(sendMessageProvider);
|
|
final drafts = ref.read(composeDraftsProvider.notifier);
|
|
if (content.isEmpty) throw const _QuickSendRefused('Say a message.');
|
|
if (utf8.encode(content).length > 8192) {
|
|
throw const _QuickSendRefused('That message is too long.');
|
|
}
|
|
var dm = cachedBestieConversation(ref, bestie);
|
|
// After its background grace period the session has closed the socket.
|
|
// Reopen it for this send, then let the background pause start over.
|
|
final session = ref.read(relaySessionProvider.notifier);
|
|
final paused = switch (ref.read(appLifecycleProvider)) {
|
|
AppLifecycleState.paused || AppLifecycleState.detached => true,
|
|
_ => false,
|
|
};
|
|
if (paused) session.onAppResumed();
|
|
try {
|
|
if (!await _connected(ref)) {
|
|
if (dm == null) {
|
|
throw const _QuickSendRefused(
|
|
"Buzz couldn't reach your community, so your message wasn't saved.",
|
|
);
|
|
}
|
|
_ensureScope(ref, scope);
|
|
_keepDraft(drafts, dm, content);
|
|
throw const _QuickSendRefused(
|
|
"Buzz couldn't reach your community. Your message is a draft in "
|
|
'your Bestie DM.',
|
|
);
|
|
}
|
|
_ensureScope(ref, scope);
|
|
try {
|
|
dm ??= await actions.openDm(pubkeys: [bestie], waitForChannelList: false);
|
|
} catch (failure) {
|
|
debugPrint('Quick send lookup failed: $failure');
|
|
throw const _QuickSendRefused(
|
|
"Buzz couldn't open your Bestie DM, so your message wasn't saved.",
|
|
);
|
|
}
|
|
for (var attempt = 1; ; attempt++) {
|
|
try {
|
|
await send(channelId: dm.id, content: content, channel: dm);
|
|
return;
|
|
} catch (failure) {
|
|
// Catching up after a reconnect can use the relay's write quota. The
|
|
// relay turned that message away, so sending again can't duplicate
|
|
// it; any other failure might have landed and isn't retried.
|
|
final limited = '$failure'.contains('rate-limited:');
|
|
if (limited && attempt < 3) continue;
|
|
debugPrint('Quick send failed: $failure');
|
|
// A switch mid-send means this account's drafts are no longer here.
|
|
_ensureScope(ref, scope);
|
|
_keepDraft(drafts, dm, content);
|
|
throw _QuickSendRefused(
|
|
limited
|
|
? "Buzz couldn't send that yet. Your message is a draft in your "
|
|
'Bestie DM.'
|
|
: "Buzz isn't sure that sent. Check your Bestie DM before "
|
|
'trying again.',
|
|
);
|
|
}
|
|
}
|
|
} finally {
|
|
if (paused && ref.read(appLifecycleProvider) != AppLifecycleState.resumed) {
|
|
session.onAppPaused();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Keeps [content] in [dm]'s composer draft, after any text already there.
|
|
void _keepDraft(ComposeDraftsNotifier drafts, Channel dm, String content) {
|
|
final key = composeDraftKey(dm.id);
|
|
final before = drafts.draftFor(key);
|
|
drafts.save(
|
|
key: key,
|
|
channelId: dm.id,
|
|
text: before == null ? content : '${before.text}\n\n$content',
|
|
mentionKeys: before?.mentionKeys ?? const {},
|
|
);
|
|
}
|
|
|
|
/// Waits briefly for the relay session a cold background launch is opening.
|
|
Future<bool> _connected(WidgetRef ref) async {
|
|
if (ref.read(relaySessionProvider).status == SessionStatus.connected) {
|
|
return true;
|
|
}
|
|
final connected = Completer<void>();
|
|
final subscription = ref.listenManual(
|
|
relaySessionProvider.select((s) => s.status),
|
|
(_, status) {
|
|
if (status == SessionStatus.connected && !connected.isCompleted) {
|
|
connected.complete();
|
|
}
|
|
},
|
|
fireImmediately: true,
|
|
);
|
|
try {
|
|
await connected.future.timeout(const Duration(seconds: 10));
|
|
return true;
|
|
} on TimeoutException {
|
|
return false;
|
|
} finally {
|
|
subscription.close();
|
|
}
|
|
}
|