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>
277 lines
9.8 KiB
Dart
277 lines
9.8 KiB
Dart
part of '../compose_bar.dart';
|
|
|
|
Future<void> _sendTextOnlyDraft({
|
|
required BuildContext context,
|
|
required _MarkdownEditingController controller,
|
|
required ObjectRef<Map<String, MentionCandidate>> mentionMap,
|
|
required ObjectRef<int> draftRevision,
|
|
required int submittedDraftRevision,
|
|
required FocusNode focusNode,
|
|
required VoidCallback clearComposer,
|
|
required Future<void> Function() addMentionedNonMembers,
|
|
required _ComposeDraftPayload payload,
|
|
required _OutgoingMentions outgoing,
|
|
required ComposeBarOnSend onSend,
|
|
required ScaffoldMessengerState? messenger,
|
|
}) async {
|
|
TextEditingValue? clearedDraftText;
|
|
Map<String, MentionCandidate>? clearedDraftMentions;
|
|
int? clearedDraftRevision;
|
|
|
|
void restoreClearedDraft() {
|
|
if (!context.mounted ||
|
|
clearedDraftText == null ||
|
|
clearedDraftMentions == null ||
|
|
clearedDraftRevision == null ||
|
|
draftRevision.value != clearedDraftRevision) {
|
|
return;
|
|
}
|
|
mentionMap.value
|
|
..clear()
|
|
..addAll(clearedDraftMentions);
|
|
controller.value = clearedDraftText;
|
|
focusNode.requestFocus();
|
|
}
|
|
|
|
try {
|
|
await addMentionedNonMembers();
|
|
// A draft that changed while adding ran is not the draft the user sent.
|
|
// Keep it and send nothing.
|
|
if (context.mounted && draftRevision.value != submittedDraftRevision) {
|
|
messenger?.showFeedbackSnackBar(
|
|
const SnackBar(content: Text('Not sent. Message changed.')),
|
|
kind: ToastKind.error,
|
|
);
|
|
return;
|
|
}
|
|
// Clear before optimistic insertion so the outgoing row and draft never
|
|
// appear simultaneously during the send transition.
|
|
if (context.mounted) {
|
|
clearedDraftText = controller.value;
|
|
clearedDraftMentions = Map<String, MentionCandidate>.of(mentionMap.value);
|
|
clearComposer();
|
|
clearedDraftRevision = draftRevision.value;
|
|
}
|
|
await onSend(
|
|
payload.content,
|
|
outgoing.pubkeys,
|
|
mediaTags: [...payload.mediaTags, ...outgoing.referenceTags],
|
|
);
|
|
} on StateError {
|
|
restoreClearedDraft();
|
|
_reportSendCancelledByCommunitySwitch(messenger);
|
|
} catch (error) {
|
|
// The caller runs unawaited, so surface publish failures and restore the
|
|
// sent draft unless the user has already started a new one.
|
|
restoreClearedDraft();
|
|
messenger?.showFeedbackSnackBar(
|
|
SnackBar(content: Text(_composeSendErrorMessage(error))),
|
|
kind: ToastKind.error,
|
|
);
|
|
}
|
|
}
|
|
|
|
void _useComposeDraftLifecycle({
|
|
required BuildContext context,
|
|
required ObjectRef<_ComposerVoiceNote> voiceNote,
|
|
required ObjectRef<Map<String, MentionCandidate>> mentionMap,
|
|
required WidgetRef ref,
|
|
required _MarkdownEditingController controller,
|
|
required String draftKey,
|
|
required String channelId,
|
|
required String? threadHeadId,
|
|
required String draftIdentity,
|
|
required ObjectRef<int> draftRevision,
|
|
required ObjectRef<String?> prefillText,
|
|
required ValueNotifier<List<_PendingAttachment>> attachments,
|
|
required ObjectRef<int> uploadGeneration,
|
|
required ObjectRef<UploadCancellationToken?> activeUploadCancellation,
|
|
required ValueNotifier<int> uploadingCount,
|
|
required ValueNotifier<bool> isSending,
|
|
required ValueNotifier<_AttachmentSurface> attachmentSurface,
|
|
required ValueNotifier<String?> uploadError,
|
|
required _IOSAttachmentPopoverController iosAttachmentPopover,
|
|
required VoidCallback onDraftIdentityChanged,
|
|
}) {
|
|
// Retire the old listener before restoring another scope's text: replacement
|
|
// effects can run before the previous effect's cleanup.
|
|
final owner = useMemoized(Object.new, [draftKey, draftIdentity]);
|
|
final currentOwner = useRef(owner)..value = owner;
|
|
final lastDraftIdentity = useRef<String?>(null);
|
|
useEffect(() {
|
|
final identity = '$draftIdentity\u0000$draftKey';
|
|
final shouldHydrate = lastDraftIdentity.value != identity;
|
|
final identityChanged =
|
|
lastDraftIdentity.value != null && lastDraftIdentity.value != identity;
|
|
lastDraftIdentity.value = identity;
|
|
final saved = ref.read(composeDraftsProvider.notifier).draftFor(draftKey);
|
|
void restoreBindings(ComposeDraft? draft) {
|
|
mentionMap.value
|
|
..clear()
|
|
..addAll({
|
|
for (final entry
|
|
in (draft?.mentionKeys ?? <String, String>{}).entries)
|
|
entry.key: MentionCandidate(
|
|
pubkey: entry.value,
|
|
displayName: entry.key,
|
|
requiresRevalidation: true,
|
|
),
|
|
});
|
|
}
|
|
|
|
if (shouldHydrate) restoreBindings(saved);
|
|
if (identityChanged) {
|
|
prefillText.value = null;
|
|
draftRevision.value += 1;
|
|
onDraftIdentityChanged();
|
|
uploadGeneration.value += 1;
|
|
activeUploadCancellation.value?.cancel();
|
|
activeUploadCancellation.value = null;
|
|
uploadingCount.value = 0;
|
|
isSending.value = false;
|
|
attachmentSurface.value = _AttachmentSurface.closed;
|
|
uploadError.value = null;
|
|
unawaited(iosAttachmentPopover.dispose());
|
|
final staleAttachments = attachments.value;
|
|
attachments.value = const [];
|
|
unawaited(_deleteOwnedAttachments(staleAttachments));
|
|
controller.text = saved?.text ?? '';
|
|
} else if (saved != null && controller.text.isEmpty) {
|
|
controller.text = saved.text;
|
|
}
|
|
|
|
var lastPersistedText = controller.text;
|
|
var lastBindings = <String, String>{
|
|
for (final e in mentionMap.value.entries) e.key: e.value.pubkey,
|
|
};
|
|
void persistDraft() {
|
|
if (!identical(currentOwner.value, owner)) return;
|
|
final text = controller.text;
|
|
// An untouched agent prefill is not a draft.
|
|
if (text == prefillText.value) return;
|
|
if (text != lastPersistedText) {
|
|
// Prune before the atomic snapshot, not in a later editor listener.
|
|
// Code formatting hides a binding without deleting its literal.
|
|
final retained = mentionOccurrences(
|
|
text.replaceAll('`', ' '),
|
|
mentionMap.value.keys,
|
|
).map((range) => range.label).toSet();
|
|
// Whole-record taint has no literal to prune. Removing every @ is a
|
|
// safe reset; unrelated edits must not turn lost keys into name lookup.
|
|
mentionMap.value.removeWhere(
|
|
(label, _) =>
|
|
label.isEmpty ? !text.contains('@') : !retained.contains(label),
|
|
);
|
|
}
|
|
final bindings = <String, String>{
|
|
for (final e in mentionMap.value.entries) e.key: e.value.pubkey,
|
|
};
|
|
if (text == lastPersistedText && mapEquals(bindings, lastBindings)) {
|
|
return;
|
|
}
|
|
lastBindings = bindings;
|
|
lastPersistedText = text;
|
|
draftRevision.value += 1;
|
|
ref
|
|
.read(composeDraftsProvider.notifier)
|
|
.save(
|
|
key: draftKey,
|
|
channelId: channelId,
|
|
threadHeadId: threadHeadId,
|
|
text: text,
|
|
mentionKeys: bindings,
|
|
);
|
|
}
|
|
|
|
controller.addListener(persistDraft);
|
|
// Another writer, such as a failed quick send from Siri, can save this
|
|
// draft while the composer is open; show its text rather than overwrite
|
|
// it with the next keystroke. Own saves match lastPersistedText.
|
|
final external = ref.listenManual(
|
|
composeDraftsProvider.select(
|
|
(drafts) => drafts.where((d) => d.key == draftKey).firstOrNull,
|
|
),
|
|
(_, saved) {
|
|
if (!identical(currentOwner.value, owner)) return;
|
|
if (saved == null ||
|
|
((saved.text == lastPersistedText ||
|
|
saved.text == controller.text) &&
|
|
mapEquals(saved.mentionKeys, lastBindings))) {
|
|
return;
|
|
}
|
|
// A newer draft: an ordinary send that fails must not restore over it.
|
|
// Text and the keys its mentions are bound to change together.
|
|
draftRevision.value += 1;
|
|
lastPersistedText = saved.text;
|
|
lastBindings = Map.of(saved.mentionKeys);
|
|
restoreBindings(saved);
|
|
if (controller.text != saved.text) controller.text = saved.text;
|
|
},
|
|
);
|
|
return () {
|
|
controller.removeListener(persistDraft);
|
|
external.close();
|
|
};
|
|
}, [controller, draftKey, draftIdentity, onDraftIdentityChanged]);
|
|
_useComposerShareDelivery(
|
|
context: context,
|
|
ref: ref,
|
|
draftKey: draftKey,
|
|
controller: controller,
|
|
attachments: attachments,
|
|
draftRevision: draftRevision,
|
|
voiceNote: voiceNote,
|
|
uploadError: uploadError,
|
|
);
|
|
}
|
|
|
|
// Report aggregate work independently of rebuilds, including sub-frame failures.
|
|
void _useComposerBusy({
|
|
required ValueNotifier<bool> isSending,
|
|
required ValueNotifier<int> uploadingCount,
|
|
required ValueNotifier<int> preparingAttachments,
|
|
required bool isDraft,
|
|
required ValueChanged<bool>? onChanged,
|
|
}) {
|
|
final busyCallback = useRef(onChanged);
|
|
busyCallback.value = onChanged;
|
|
useEffect(() {
|
|
var active = true;
|
|
void reportCurrent() {
|
|
if (!active) return;
|
|
busyCallback.value?.call(
|
|
isSending.value ||
|
|
uploadingCount.value > 0 ||
|
|
(isDraft && preparingAttachments.value > 0),
|
|
);
|
|
}
|
|
|
|
void reportBusy() {
|
|
// Scope changes can reset the composer from a build-time effect.
|
|
// Ordinary operation completions still release the parent immediately.
|
|
if (SchedulerBinding.instance.schedulerPhase ==
|
|
SchedulerPhase.persistentCallbacks) {
|
|
WidgetsBinding.instance.addPostFrameCallback((_) => reportCurrent());
|
|
} else {
|
|
reportCurrent();
|
|
}
|
|
}
|
|
|
|
final sources = [isSending, uploadingCount, preparingAttachments];
|
|
for (final source in sources) {
|
|
source.addListener(reportBusy);
|
|
}
|
|
return () {
|
|
active = false;
|
|
for (final source in sources) {
|
|
source.removeListener(reportBusy);
|
|
}
|
|
// Disposal can happen during a parent build. Release after that frame.
|
|
final callback = busyCallback.value;
|
|
WidgetsBinding.instance.addPostFrameCallback(
|
|
(_) => callback?.call(false),
|
|
);
|
|
};
|
|
}, [isSending, uploadingCount, preparingAttachments, isDraft]);
|
|
}
|