Files
buzz/mobile/ios/Runner/PushNativeState.swift
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

358 lines
13 KiB
Swift

import BuzzPushKit
import Flutter
import Foundation
import Security
import UserNotifications
final class BuzzOneShotCompletion {
private let lock = NSLock()
private var completion: (() -> Void)?
init(_ completion: @escaping () -> Void) {
self.completion = completion
}
func call() {
lock.lock()
let completion = completion
self.completion = nil
lock.unlock()
completion?()
}
}
enum BuzzPushNotificationResponseCoordinator {
static func handle(
actionIdentifier: String,
userInfo: [AnyHashable: Any],
onTarget: (BuzzPushNavigationTarget) -> Void,
forwardToFlutter: (@escaping () -> Void) -> Void,
completion: @escaping () -> Void
) {
let completionGate = BuzzOneShotCompletion(completion)
defer { completionGate.call() }
if actionIdentifier == UNNotificationDefaultActionIdentifier,
let target = BuzzPushNavigationTarget.decodeIfPresent(from: userInfo)
{
onTarget(target)
}
forwardToFlutter { completionGate.call() }
}
}
enum BuzzPushKeychain {
static let service = "buzz.push.nse.signing"
static func replace(signingKeys: [String: String], accessGroup: String?) throws {
var query = baseQuery(accessGroup: accessGroup)
let deletionStatus = SecItemDelete(query as CFDictionary)
guard deletionStatus == errSecSuccess || deletionStatus == errSecItemNotFound else {
throw NSError(
domain: NSOSStatusErrorDomain, code: Int(deletionStatus),
userInfo: [
NSLocalizedDescriptionKey: SecCopyErrorMessageString(deletionStatus, nil)
?? "Keychain deletion failed" as CFString
]
)
}
for (communityID, privateKeyHex) in signingKeys {
query[kSecAttrAccount as String] = communityID
query[kSecValueData as String] = Data(privateKeyHex.utf8)
query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else {
SecItemDelete(baseQuery(accessGroup: accessGroup) as CFDictionary)
throw NSError(
domain: NSOSStatusErrorDomain, code: Int(status),
userInfo: [
NSLocalizedDescriptionKey: SecCopyErrorMessageString(status, nil)
?? "Keychain write failed" as CFString
]
)
}
query.removeValue(forKey: kSecValueData as String)
query.removeValue(forKey: kSecAttrAccessible as String)
query.removeValue(forKey: kSecAttrAccount as String)
}
}
/// Replaces a shared account session, the organization's unless `account` names the hosted
/// one. Device-only, like the app's own copy.
static func replace(
organizationSession: BuzzOrganizationSession?, accessGroup: String?,
account: String = BuzzOrganizationSession.keychainAccount
) throws {
var query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: BuzzOrganizationSession.keychainService,
kSecAttrAccount as String: account,
]
if let accessGroup, !accessGroup.isEmpty {
query[kSecAttrAccessGroup as String] = accessGroup
}
let deletionStatus = SecItemDelete(query as CFDictionary)
guard deletionStatus == errSecSuccess || deletionStatus == errSecItemNotFound else {
throw keychainError(deletionStatus, fallback: "Keychain deletion failed")
}
guard let organizationSession else { return }
query[kSecValueData as String] = try JSONEncoder().encode(organizationSession)
query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else {
throw keychainError(status, fallback: "Keychain write failed")
}
}
private static func keychainError(_ status: OSStatus, fallback: String) -> NSError {
NSError(
domain: NSOSStatusErrorDomain, code: Int(status),
userInfo: [
NSLocalizedDescriptionKey: SecCopyErrorMessageString(status, nil) ?? fallback as CFString
]
)
}
private static func baseQuery(accessGroup: String?) -> [String: Any] {
var query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
]
if let accessGroup, !accessGroup.isEmpty {
query[kSecAttrAccessGroup as String] = accessGroup
}
return query
}
}
/// Carries replies typed into notifications to Flutter, which sends them, and
/// reports each outcome on the notification side. See
/// docs/adr/0004-notification-reply.md.
final class BuzzNotificationReplyBridge {
/// Longest wait for Flutter to send before the reply counts as not sent.
/// iOS gives a background notification action about 30 seconds.
static let sendTimeout: TimeInterval = 25
static let replyNotSentThread = "buzz.reply-not-sent"
private let buffer = BuzzNotificationReplyBuffer()
/// Keeps each reply until the app reports on it, so a reply the app never
/// finished, even across a relaunch, still becomes a draft.
private let journal = BuzzNotificationReplyJournal(defaults: .standard)
private let selectedCommunityDefaults: UserDefaults?
/// Tells Flutter a reply is waiting; Flutter also takes waiting replies
/// when its handler starts, so a call made before then is harmless.
var notifyFlutter: (() -> Void)?
init(appGroupIdentifier: String?) {
selectedCommunityDefaults = appGroupIdentifier.flatMap(UserDefaults.init(suiteName:))
}
static func registerCategory(with center: UNUserNotificationCenter = .current()) {
let reply = UNTextInputNotificationAction(
identifier: BuzzNotificationReplyContext.actionIdentifier,
title: "Reply",
// The app reads its keychain-held keys to send.
options: [.authenticationRequired],
textInputButtonTitle: "Send",
textInputPlaceholder: ""
)
center.setNotificationCategories([
UNNotificationCategory(
identifier: BuzzNotificationReplyContext.categoryIdentifier,
actions: [reply],
intentIdentifiers: [],
options: []
)
])
}
/// Handles a Reply action. Returns false for any other response.
func handle(
_ response: UNNotificationResponse,
center: UNUserNotificationCenter = .current(),
completion: @escaping () -> Void
) -> Bool {
guard response.actionIdentifier == BuzzNotificationReplyContext.actionIdentifier else {
return false
}
let content = response.notification.request.content
guard let text = (response as? UNTextInputNotificationResponse)?.userText,
let request = BuzzNotificationReplyRequest.make(
id: UUID().uuidString,
text: text,
userInfo: content.userInfo,
threadIdentifier: content.threadIdentifier,
deadline: Date().addingTimeInterval(Self.sendTimeout)
)
else {
completion()
return true
}
let notificationID = response.notification.request.identifier
// Runs on the main queue, like every caller below; ends the task once.
var backgroundTask = UIBackgroundTaskIdentifier.invalid
let endBackgroundTask = {
guard backgroundTask != .invalid else { return }
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = .invalid
}
backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
// iOS requires the task to end before this handler returns; the
// unsent reply is still reported if the app gets the time.
self?.expire(request.id)
endBackgroundTask()
}
journal.record(request.journalArguments)
buffer.add(request) { outcome in
Self.finish(request, outcome: outcome, notificationID: notificationID, center: center) {
DispatchQueue.main.async {
completion()
endBackgroundTask()
}
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + Self.sendTimeout) { [weak self] in
self?.expire(request.id)
}
notifyFlutter?()
return true
}
/// Handles the reply methods on the push channel. Returns false for others.
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) -> Bool {
switch call.method {
case "takePendingNotificationReplies":
// Every buffered reply is in the journal, which also holds any a
// previous launch never finished.
_ = buffer.take()
result(journal.take())
case "markNotificationReplyPublishing":
guard let id = call.arguments as? String else {
result(FlutterError(code: "invalid_arguments", message: "Expected id.", details: nil))
return true
}
journal.markPublishing(id: id)
result(nil)
case "completeNotificationReply":
guard let arguments = call.arguments as? [String: Any],
let id = arguments["id"] as? String,
let sent = arguments["sent"] as? Bool
else {
result(
FlutterError(code: "invalid_arguments", message: "Expected id and sent.", details: nil))
return true
}
let outcome: BuzzNotificationReplyOutcome =
sent
? .sent
: arguments["unknown"] as? Bool == true
? .unknown
: .notSent(draftThreadRootID: arguments["draftThreadRootId"] as? String)
// The app reports only after the reply is sent or its draft is saved.
let recorded = journal.recorded(id: id)
if buffer.complete(id: id, outcome: outcome) {
journal.settle(id: id)
} else {
finishUnbuffered(id: id, outcome: outcome, recorded: recorded) { [journal] in
journal.settle(id: id)
}
}
result(nil)
case "setSelectedCommunity":
BuzzSelectedCommunity.set(call.arguments as? String, in: selectedCommunityDefaults)
result(nil)
default:
return false
}
return true
}
/// Ends a reply at its deadline. It stays in the journal until the app
/// reports on it, so its text still becomes a draft, unless the app may
/// already have published it.
private func expire(_ id: String) {
buffer.expire(id: id, mayHavePublished: journal.isPublishing(id: id))
}
/// Reports a reply this process no longer holds: one an earlier launch was
/// given, or one that expired first. One that may have gone out gets its
/// "Reply may not have sent" notification, which an earlier launch never
/// posted; one that went out after all clears the notice its expiry posted.
/// Settles it once its notice is posted.
private func finishUnbuffered(
id: String, outcome: BuzzNotificationReplyOutcome, recorded: [String: String]?,
settle: @escaping () -> Void
) {
switch outcome {
case .sent:
UNUserNotificationCenter.current().removeDeliveredNotifications(
withIdentifiers: [Self.replyNotSentIdentifier(id)])
case .unknown:
if let request = recorded.flatMap(BuzzNotificationReplyRequest.init(journalArguments:)) {
Self.finish(
request, outcome: .unknown, notificationID: "", center: .current(), done: settle)
return
}
case .notSent:
// Its draft is saved, where its notice (if any) already points.
break
}
settle()
}
private static func replyNotSentIdentifier(_ id: String) -> String {
"buzz.reply-not-sent.\(id)"
}
/// A sent reply clears the notifications it marked read: the notified one
/// and earlier ones in the same conversation. An unsent one is replaced by a
/// "Reply not sent" notification that keeps the typed text and opens its
/// draft; one that may have gone out says so instead, without a draft.
private static func finish(
_ request: BuzzNotificationReplyRequest,
outcome: BuzzNotificationReplyOutcome,
notificationID: String,
center: UNUserNotificationCenter,
done: @escaping () -> Void
) {
guard outcome == .sent else {
let content = UNMutableNotificationContent()
var target = request.target
switch outcome {
case .notSent(let draftThreadRootID):
content.title = "Reply not sent"
if let draftThreadRootID {
target = BuzzPushNavigationTarget(
eventID: target.eventID, communityID: target.communityID,
channelID: target.channelID, threadRootID: draftThreadRootID)
}
default:
content.title = "Reply may not have sent"
}
content.body = request.text
// Grouped apart, so clearing a conversation never removes it.
content.threadIdentifier = Self.replyNotSentThread
content.userInfo = [BuzzPushNavigationTarget.userInfoKey: target.userInfoValue]
center.add(
UNNotificationRequest(
identifier: Self.replyNotSentIdentifier(request.id), content: content, trigger: nil)
) { _ in done() }
return
}
center.getDeliveredNotifications { delivered in
let ids = delivered.compactMap { notification -> String? in
let identifier = notification.request.identifier
let content = notification.request.content
guard
identifier == notificationID
|| request.clears(
threadIdentifier: content.threadIdentifier, userInfo: content.userInfo)
else { return nil }
return identifier
}
center.removeDeliveredNotifications(withIdentifiers: ids)
done()
}
}
}