Files
buzz/mobile/test/shared/me/me_chat_creation_test.dart
Tom Brow 3689241672 feat(mobile): reply to a message from its iOS notification (#9439)
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 |
| --- | --- |
|
![before](https://raw.githubusercontent.com/block/buzz/df800599173cf3436af4d2c738447396a632fac7/pr-9439--before.png)
|
![after](https://raw.githubusercontent.com/block/buzz/df800599173cf3436af4d2c738447396a632fac7/pr-9439--after.png)
|

### 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>
2026-11-18 16:15:28 +00:00

374 lines
12 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter_test/flutter_test.dart';
import 'package:buzz/shared/crypto/event_signing.dart';
import 'package:buzz/shared/me/me_chat_title.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:buzz/shared/me/me_chat_creation.dart';
import 'package:buzz/shared/me/me_sync.dart';
import 'package:buzz/shared/relay/relay.dart';
void main() {
test('first-message title follows desktop plain-text rules', () {
for (final (message, title) in [
(' Plan\n my trip ', 'Plan my trip'),
('@Alice help me', '@Alice help me'),
(
'buzz://message?channel=source Plan the next step',
'Plan the next step',
),
('buzz://message?channel=source', 'Chat'),
('### Heading', 'Heading'),
('🐝' * 90, '🐝' * 80),
('> Ship it Friday\n>\n> ok?\n\nSummarize this', 'Summarize this'),
('> Ship it Friday\n> ok?\n\n', 'Ship it Friday ok?'),
]) {
expect(startingMeChatTitle(message), title);
}
});
test(
'accepted first message survives a lost acknowledgement and restart',
() async {
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final owner = nostr.Keys.generate();
final agent = nostr.Keys.generate().public;
final relay = _MessageRelay();
final config = RelayConfig(
baseUrl: 'https://relay.test',
nsec: owner.nsec,
);
MeSync service() => MeSync(relay, config, prefs: prefs);
final message = NostrEvent.fromJson(
signNostrEvent(
kind: 9,
content: 'Plan my trip',
tags: [
['h', 'chat'],
['p', agent],
],
secretKey: owner.secret,
).toMap(),
);
final intent = MeChatCreation(
'chat',
'Plan my trip',
agent,
initialMessage: message,
);
Future<String> send(MeChatCreation intent) => intent.complete(
service(),
findChannel: () async => 'chat',
createChannel: () async => throw StateError('already created'),
hasAgent: () async => true,
addAgent: () async => throw StateError('already joined'),
isPlaced: () async => true,
place: () async => throw StateError('already placed'),
);
await expectLater(send(intent), throwsStateError);
await prefs.reload();
final pending = MeChatCreation.pending(service())!;
expect(pending.initialMessage?.toJson(), message.toJson());
expect(
prefs.getString(MeChatCreation.storageKey(service())),
isNot(contains('Plan my trip')),
);
await expectLater(
MeChatCreation('chat', intent.name, agent).save(service()),
throwsStateError,
);
expect(await send(pending), 'chat');
expect(relay.attempts, [message.id, message.id]);
expect(relay.messages.length, 1);
expect(MeChatCreation.pending(service()), isNull);
},
);
for (final accepted in [false, true]) {
test(
'expired first message resumes without duplication: accepted=$accepted',
() async {
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final owner = nostr.Keys.generate();
final relay = _MessageRelay();
final sync = MeSync(
relay,
RelayConfig(baseUrl: 'https://relay.test', nsec: owner.nsec),
prefs: prefs,
);
final old = NostrEvent.fromJson(
signNostrEvent(
kind: 9,
content: 'Yesterday’s draft',
tags: [
['h', 'chat'],
['p', 'agent'],
],
secretKey: owner.secret,
createdAt: DateTime.now().millisecondsSinceEpoch ~/ 1000 - 86400,
).toMap(),
);
if (accepted) relay.messages[old.id] = old;
final intent = MeChatCreation(
'chat',
'Yesterday’s draft',
'agent',
initialMessage: old,
);
Future<String> run(MeChatCreation intent) => intent.complete(
sync,
findChannel: () async => 'chat',
createChannel: () async => throw StateError('already created'),
hasAgent: () async => true,
addAgent: () async => throw StateError('already joined'),
isPlaced: () async => true,
place: () async => throw StateError('already placed'),
);
if (!accepted) {
await expectLater(run(intent), throwsStateError);
await prefs.reload();
final pending = MeChatCreation.pending(sync)!;
expect(pending.initialMessage!.id, isNot(old.id));
expect(pending.initialMessage!.content, old.content);
expect(pending.initialMessage!.pubkey, owner.public);
expect(pending.initialMessage!.tags, old.tags);
expect(await run(pending), 'chat');
expect(relay.attempts.toSet(), {pending.initialMessage!.id});
} else {
expect(await run(intent), 'chat');
expect(relay.attempts, isEmpty);
}
expect(relay.messages.length, 1);
expect(MeChatCreation.pending(sync), isNull);
},
);
}
test(
'retry confirms persistence after a failed cached journal write',
() async {
SharedPreferences.setMockInitialValues({});
final store = _FailingStore();
final previousStore = SharedPreferencesStorePlatform.instance;
SharedPreferencesStorePlatform.instance = store;
addTearDown(
() => SharedPreferencesStorePlatform.instance = previousStore,
);
final prefs = await SharedPreferences.getInstance();
final sync = MeSync(
RelaySessionNotifier(),
RelayConfig(
baseUrl: 'https://relay.test',
nsec: nostr.Keys.generate().nsec,
),
prefs: prefs,
);
const intent = MeChatCreation('id', 'Name', 'agent');
var reachedRelay = false;
Future<String> run() => intent.complete<String>(
sync,
findChannel: () async {
reachedRelay = true;
await prefs.reload();
expect(MeChatCreation.pending(sync)?.id, intent.id);
return null;
},
createChannel: () async => throw StateError('Simulated process stop'),
hasAgent: () async => false,
addAgent: () async {},
isPlaced: () async => false,
place: () async {},
);
await expectLater(run(), throwsStateError);
expect(reachedRelay, isFalse);
expect(
MeChatCreation.pending(sync)?.id,
intent.id,
); // Failed write remains cached.
await expectLater(run(), throwsStateError);
expect(reachedRelay, isTrue);
await prefs.reload();
expect(MeChatCreation.pending(sync)?.id, intent.id);
},
);
test('missing durable storage blocks every relay side effect', () async {
final sync = MeSync(
RelaySessionNotifier(),
RelayConfig(
baseUrl: 'https://relay.test',
nsec: nostr.Nip19.encode(
prefix: nostr.Nip19Prefix.nsec,
data: '0' * 63 + '1',
),
),
);
var touchedRelay = false;
await expectLater(
const MeChatCreation('id', 'Name', 'agent').complete<String>(
sync,
findChannel: () async {
touchedRelay = true;
return null;
},
createChannel: () async => 'id',
hasAgent: () async => false,
addAgent: () async {},
isPlaced: () async => false,
place: () async {},
),
throwsStateError,
);
expect(touchedRelay, isFalse);
});
test(
'discard preserves partial relay state and permits a different intent offline',
() async {
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final config = RelayConfig(
baseUrl: 'https://relay.test',
nsec: nostr.Nip19.encode(
prefix: nostr.Nip19Prefix.nsec,
data: '0' * 63 + '1',
),
);
final online = MeSync(RelaySessionNotifier(), config, prefs: prefs);
const intent = MeChatCreation('old', 'Old', 'revoked-agent');
await intent.save(online);
final offline = MeSync(
RelaySessionNotifier(),
config,
prefs: prefs,
connected: false,
);
await expectLater(
const MeChatCreation('wrong', 'Old', 'revoked-agent').discard(offline),
throwsStateError,
);
expect(MeChatCreation.pending(offline)?.id, 'old');
await intent.discard(offline);
expect(MeChatCreation.pending(offline), isNull);
await const MeChatCreation('new', 'New', 'other-agent').save(online);
expect(MeChatCreation.pending(online)?.id, 'new');
},
);
for (final crashAfter in [0, 1, 2, 3]) {
test('restart resumes the same chat after boundary $crashAfter', () async {
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final config = RelayConfig(
baseUrl: 'https://relay.test',
nsec: nostr.Nip19.encode(
prefix: nostr.Nip19Prefix.nsec,
data: '0' * 63 + '1',
),
);
MeSync service() => MeSync(RelaySessionNotifier(), config, prefs: prefs);
const intent = MeChatCreation(
'same-id',
'Private name',
'agent',
project: 'mobile',
);
var created = false, member = false, placed = false, crash = true;
final writes = [0, 0, 0];
void boundary(int point) {
expect(MeChatCreation.pending(service())?.id, intent.id);
if (crash && crashAfter == point) throw StateError('process stopped');
}
Future<String> run(MeSync sync, MeChatCreation intent) =>
intent.complete<String>(
sync,
findChannel: () async {
boundary(0);
return created ? intent.id : null;
},
createChannel: () async {
created = true;
writes[0]++;
boundary(1);
return intent.id;
},
hasAgent: () async => member,
addAgent: () async {
member = true;
writes[1]++;
boundary(2);
},
isPlaced: () async => placed,
place: () async {
placed = true;
writes[2]++;
boundary(3);
},
);
await expectLater(run(service(), intent), throwsStateError);
final restarted = service();
final pending = MeChatCreation.pending(restarted)!;
expect(pending.name, intent.name);
expect(pending.agent, intent.agent);
expect(pending.project, intent.project);
await expectLater(
MeChatCreation(
intent.id,
intent.name,
intent.agent,
project: 'other',
).save(restarted),
throwsStateError,
);
expect(
prefs.getString(MeChatCreation.storageKey(restarted)),
isNot(contains(intent.name)),
);
crash = false;
expect(await run(restarted, pending), intent.id);
expect(writes, [1, 1, 1]);
expect(MeChatCreation.pending(restarted), isNull);
final other = MeSync(
RelaySessionNotifier(),
RelayConfig(baseUrl: 'https://other.test', nsec: config.nsec),
prefs: prefs,
);
expect(MeChatCreation.pending(other), isNull);
});
}
}
class _FailingStore extends InMemorySharedPreferencesStore {
_FailingStore() : super.empty();
bool failNext = true;
@override
Future<bool> setValue(String valueType, String key, Object value) async {
if (failNext && key.startsWith('flutter.me-chat-creation:')) {
failNext = false;
return false;
}
return super.setValue(valueType, key, value);
}
}
class _MessageRelay extends RelaySessionNotifier {
final messages = <String, NostrEvent>{};
final attempts = <String>[];
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async => [
for (final message in messages.values)
if (filter.ids!.contains(message.id)) message,
];
@override
Future<NostrEvent> publish(
NostrEvent event, {
Duration timeout = const Duration(seconds: 8),
Future<bool> Function()? mayPublish,
}) async {
attempts.add(event.id);
messages[event.id] = event;
if (attempts.length == 1) throw StateError('Acknowledgement lost');
return event;
}
}