mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
Adds a **Message my Bestie** action for Siri and Shortcuts. Siri asks
what to say, confirms with the Bestie's name ("Send “…” to Astra?"), and
posts the message in your DM with the Bestie, without opening Buzz. The
Bestie's reply arrives as a normal notification, in the same DM the Home
star opens.
This is the iOS 16+ App Shortcut from [ADR
0005](https://github.com/block/buzz/blob/mobile-siri-bestie-dm/docs/adr/0005-quick-send-uses-the-system-send-message-action.md).
Follow-ups, not in this PR: the iOS 27 `messages.sendMessage` schema
intent, naming other recipients, a separate "Start a chat with my
Bestie" intent for a new Solo chat, and opening Buzz with a draft when a
send fails.
### How it works
- The App Intent runs without opening the app and hands the text to Dart
over a method channel. It waits up to 20 s for Home to say it is ready,
and runs one send at a time.
- A background launch already starts the Flutter engine and builds Home
([ADR
0004](https://github.com/block/buzz/blob/mobile-siri-bestie-dm/docs/adr/0004-background-work-runs-in-the-app-engine.md)
records the measurement). So a small `QuickSendHost`, which the app
hands Home as an invisible background widget, takes the send. Nothing is
reimplemented natively.
- Before confirming, Swift asks Dart for the saved Bestie's pubkey and
name; the send then goes to exactly that agent, so a choice this phone
hasn't synced yet is caught at the confirmation.
- The send reuses the Home star's lookup for the Bestie DM (opening it
with the relay's find-or-create DM command when it isn't loaded) and
posts with the same `SendMessage` the composer uses.
- If Buzz has been in the background past its 5 s grace period, the
relay session has closed its socket. The send reopens it, then lets the
normal background pause start over.
- A message the relay rate-limits is retried (up to 3 tries); the relay
turned it away, so a retry can't duplicate it. Any other failure isn't
retried, since the message might have landed.
- The confirmation is pinned to the community and account it was shown
in: if Buzz switches either before the message goes out, the send is
refused.
- If the send fails, or Buzz can't tell whether it landed (no answer
from the relay), the message is saved as the Bestie DM's composer draft,
after any draft already there, and Siri says so ("Buzz isn't sure that
sent. Check your Bestie DM before trying again." when the outcome is
unknown). A successful send leaves the draft alone. Limits: if the DM
can't be found or opened, there is nowhere to save it and Siri says the
message wasn't saved, and the app being killed mid-send isn't covered.
- Refusals (no Bestie, offline, empty or too long, switched community)
come back as a short message Siri reads.
### Regressions
- Nothing existing changes behavior: the host only answers this method
channel, and the action does nothing until someone runs it. Its bugs
stay inside the quick send path.
- The Home star's DM lookup moved into `cachedBestieConversation`
unchanged, so the star behaves as before.
- A composer that is open on screen now shows a draft another writer
saved for it (here, a failed quick send) instead of overwriting it with
the next keystroke. It listens without rebuilding, and its own saves are
ignored.
- A background wake pays the cost of starting the app's Dart code, which
iOS already does for this launch.
### Before / after
| Before: no Buzz actions in Shortcuts | After |
| --- | --- |
| <img width="300" alt="Shortcuts Library before"
src="https://github.com/user-attachments/assets/b0870e3d-2823-4c7d-be0e-a242a3fdafd7">
| <img width="300" alt="Shortcuts Library after, listing Buzz Dev under
Apps"
src="https://github.com/user-attachments/assets/8c092006-76b9-4313-a401-68189f5674cf">
|
| Asks what to say | Confirms (names the Bestie) | Sent |
| --- | --- | --- |
| <img width="250" alt="Prompt"
src="https://github.com/user-attachments/assets/a2eaf44a-5287-48b6-9c5a-2aaefc90c0a8">
| Shows "Send “…” to *Bestie's name*?" (capture omitted: it shows an
internal agent name) | <img width="250" alt="Sent"
src="https://github.com/user-attachments/assets/07fe66e3-4480-4d06-be52-623416e567b8">
|
The DM result and a demo video show internal names, so they're shared
internally rather than here.
### Testing
- Added test, `quick_send_test.dart` journey: Home reports ready; Siri's
Bestie lookup is refused with no Bestie, then returns the chosen
Bestie's pubkey and name; a send confirmed for another community is
refused; an empty send is refused without publishing; a send while Buzz
is backgrounded and its socket closed reconnects, opens the DM with the
Bestie, survives a rate-limited first try, posts the message in that DM
tagged to the Bestie, and hands the session back to its background
pause; a second send goes to the same DM and leaves the person's draft
there as it was; a send whose answer is lost is reported as unsure and
kept in that draft after the person's own text, with its mentions; a
socket that drops just before the message goes out keeps it too; leaving
Home reports unready. Removing the rate-limit retry, the community check
or the draft save fails it.
- Extended the composer's share-delivery journey: a draft saved by
another writer while the composer is open shows in the composer and
survives the next keystroke, and survives an ordinary send that was
pending when it arrived and then fails. Removing the composer's listener
or its revision bump fails it.
- iPhone 17 Pro simulator (iOS 27), Builderlab community with a Bestie,
automated with AXe:
- Cold: Buzz terminated, ran the action from Shortcuts, the confirmation
named the Bestie, "Sent.", and the message was in the Bestie DM with its
reply. No Solo chat was created.
- Warm: Buzz in the background for 10 s, ran it again, "Sent.", same DM.
- At-risk flows: sent a typed message from the DM composer, went back to
Home, and the Home star reopened the same DM.
- `just mobile-check mobile-test` passes.
buzz-review-completed
---------
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
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 '../activity/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();
|
|
}
|
|
}
|