mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
On mobile, a text send that failed for almost any reason showed **"Not sent. Community changed."** The composer caught every `StateError` as a community switch, and relay failures such as a briefly disconnected socket (`RelaySession.publish` throws "Relay session is not connected") are also `StateError`s. So a reconnect blip during a send told the user they had switched communities when they hadn't. The community-switch guards in message, forum and channel-action delivery now throw a dedicated `ActiveCommunityChangedError`, and an unconnected publish throws `RelayNotConnectedError`. Both still extend `StateError`, so every existing `on StateError` caller behaves as before. The composer now reports: | Failure | Message | | --- | --- | | Active community changed mid-send | Not sent. Community changed. | | Relay socket not connected | Not sent. No connection. | | Relay never acknowledged the event (ack timeout) | Not confirmed. The relay didn't respond. | | A relay request timed out before the event was published (e.g. a roster lookup) | Not sent. The relay didn't respond. | | Connection lost after the event was sent, before its acknowledgement | Not confirmed. Connection lost. | | Relay rejected the event, or anything else | Not sent: *relay reason or error text* | The two "Not confirmed" cases may still have been accepted by the relay, so they avoid a definite "Not sent" that would invite a duplicate resend. Pending publishes rejected by a disconnect or backgrounding now complete with a typed `RelayAckLostError` instead of a generic exception, and an unacknowledged publish times out with `RelayAckTimeoutError` (still a `TimeoutException`) so it can be told apart from earlier timeouts. The draft is restored in every case, as before. ### Validation - Added [composer widget tests](https://github.com/block/buzz/pull/9156/files#diff-101740841aadcb902d0717f3909debe16073c672e73be74a5b908bf11dfc8782) for each non-community failure (disconnect, timeout before publishing, ack timeout, connection lost before acknowledgement, relay rejection, other `StateError`), checking the snackbar text, that the draft is restored, and whether the message EVENT was sent. The disconnect, timeout and connection-lost cases run through the real relay session (a pending publish rejected by backgrounding, a history request that times out before any message EVENT). The existing community-switch journey goes through the real channel-action guard. - Simulator (iPhone 17 Pro, debug build of this branch signed in to a test community): opened a channel and sent a message; it was delivered and the composer cleared normally. Limitation: the error paths themselves were exercised only by widget tests, since the simulator shares the Mac's network and I couldn't drop the relay connection for it alone. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- 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 ActiveCommunityChangedError {
|
|
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(_sendFailureMessage(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]);
|
|
}
|