Commit Graph

299 Commits

Author SHA1 Message Date
Tom Brow
c4c97119c3 fix(mobile): end a refused push opt-out in a visible failure with Retry (#9854)
## Summary

Turning push notifications off could stay stuck forever. If the relay
kept rejecting the opt-out tombstone,
`setPushNotificationsEnabled(false)` swallowed the rejection, and the
push bootstrap retried the tombstone on every connect, including after
restarts. Settings showed the switch off the whole time, while the relay
still held the lease.
[docs/mobile-push-suppression.md](https://github.com/block/buzz/blob/main/docs/mobile-push-suppression.md)
(rule 29) asks for the opposite: a bounded pending state, then a clear
warning that notifications may continue, with no automatic retry, and
the relay's actual setting on the next sync.

- **Bounded pending.** An opt-out ends about 10 seconds after the tap,
across every step (capability lookup, connect, authenticate, publish).
While it runs, the row says "Turning off…" and the switch is held, so
Off, On, Off can't race the first attempt.
- **Definite vs. maybe stored.** A one-shot publish now says whether the
relay could have seen the event: a refusal, or a failure before the
EVENT went out, is definite; a lost acknowledgment after it went out is
not.
- **Refused: back to the confirmed setting.** When the relay never
stored the tombstone, the saved setting goes back to On (the confirmed
lease) and Settings shows "Could not confirm that notifications were
turned off. Notifications may continue." with a **Retry** below it. The
warning lasts for this app run; after a restart, Settings just shows On.
- **Maybe stored: kept as a guard, then read back.** When the
acknowledgment was lost, the saved opt-out stays as a guard (no lease or
enrollment is published, and the community stays in the iOS notification
snapshot), while Settings shows the confirmed On with the same warning.
On the next sync, the app reads its own lease from the relay: an
inactive lease or none confirms Off; an active one turns the switch back
On and keeps the warning. A read that fails changes nothing and is tried
again on the next connect. The read asks the relay for strong
consistency, so a lagging replica can't answer with the lease the
tombstone replaced. It fails if the active community changes while it
waits, and it settles only the opt-out it was started for, so a Retry
made during the read stays pending.
- **No flash on success.** Settings reads the community from the
community list, which changes in the same step as each opt-out result.
The active-community projection trails it by a keychain read, which
could show an accepted opt-out as failed for a frame.
- **Explicit retry only.** Retry, or turning the switch off again, makes
one attempt at a new generation. The bootstrap's automatic tombstone
retry is removed.

The warning is announced to screen readers when it appears, and Retry
has its own label. This applies to every platform: the opt-out path is
shared.

### Related issue

None found.

### Testing

- The Settings recovery journey covers a refusal restoring On with the
warning, a restart that drops the warning and makes no attempt, an
attempt that never answers (held switch, then the deadline, kept as a
guard), a restart that keeps that warning, and a Retry that succeeds. It
runs with loading, absent and failed capability, and on a small phone at
text scale 2.
- The toggle journey, with the real push bootstrap, covers a refusal (a
reconnect neither retries nor reads), an unanswered attempt and a lease
that's still active: the read on reconnect, a failed read that changes
nothing, then Off or On from what the relay holds.
- One-shot publish rows: a relay that stalls at authentication fails as
never sent; one that stalls at OK, or closes after the EVENT, fails as
maybe stored, all by the deadline.
- Lease reader rows: the exact strong-read filter, an empty answer, and
a community switch during the descriptor fetch or the query. A provider
row holds a read while a Retry fails unanswered: the old read leaves the
new opt-out pending.
- A widget test with slow secure storage checks every frame of an
accepted opt-out for the warning.
- A relay database test reads back the author's inactive replacement
lease with the filter the app uses, and the lease decryption is checked
against the member's own and forged events.

### Screenshots

After the relay refuses the opt-out (no relay push capability, so the
toggle is reachable only because push is on).

| Before | After |
| --- | --- |
| <img
src="https://raw.githubusercontent.com/block/buzz/d2e3c753b3068a68728199096bf30e45e8948af7/pr-9854--before.png"
width="300" alt="Before: switch shows off while notifications may
continue"> | <img
src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--after.png"
width="300" alt="After: switch back on, with the warning and Retry below
it"> |

At text scale 2 on a small phone, Retry sits below the warning:

<img
src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--after-large-text.png"
width="250" alt="Large text: warning readable, Retry below it">

While an opt-out attempt is in flight (new), the switch is held:

<img
src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--turning-off.png"
width="300" alt="Notifications row with the subtitle Turning off and the
switch held">

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-25 10:41:15 -05:00
Tom Brow
298543f555 fix(mobile): report a push wake claim it stopped waiting for (#9931)
## What

An Android push wake that runs out of time can leave a claim still
running. If that claim then wins, the message is recorded as shown but
was never returned. No later wake finds it, so the user is never told.
This makes the wake report that case, and the native handler shows its
generic notification for it.

- `resolvePushWake` tracks the message each community is claiming. After
the claim grace it sets `PushWakeResult.unreported` when a claim is
still running for a message with something to show (a message whose body
is empty would not be returned anyway). It is read in the same
synchronous step as the claimed-message snapshot, so a claim that
finishes before the snapshot is returned, and one that finishes after it
is counted.
- `PushWakeRunner` reports `unreported` when any pass does, because a
message lost in one pass stays lost.
- The channel payload carries `unreported`. The native handler posts the
named notifications, and the generic notification beside them, silently
when something already alerted. If the user already cleared the generic
card this wake posted at 2 seconds, it stays cleared. The generic is
marked as standing in for a lost message, so later wakes, which clear an
unmarked generic as before, leave it until the user clears it. A later
wake that re-posts the generic keeps the mark.
- It stays separate from `incomplete`, which means a later wake retries.
Folding the two would show the generic beside named notifications on
every retryable partial wake.
- `ShownMessageStore.claim` documents that a caller that stops waiting
for a claim must report it. A claim that later returns false still costs
one unnecessary generic notification, which is accepted.

The realistic trigger is storage that stalls after the claim marker is
created, during the watermark and prune I/O in
`DirectoryShownMessageStore.claim` (a pre-existing finding from the
review of the Android wake handler). The store's order is unchanged. The
marker has to come first for atomicity, and this signal turns the stall
into a generic notification instead of silence.

## Validation

- The push-wake journey test's stalled-storage step now asserts
`unreported`, and a stalled claim for a message with an empty body
asserts it is not set. A wake cut short in the name lookup, outside any
claim, asserts it is not set and still returns its messages. The runner
step asserts that a message lost in one pass is still reported after a
clean rerun. The channel payload test covers both values.
- Forcing the signal off fails the stalled-storage step.
- `WakeNotifierGenericTest` (instrumented) drives the generic
notification against the real notification manager on a Pixel 9a: an
unmarked card clears on a clean wake, a kept card survives clean wakes
and a later 2-second re-post, and a card the user cleared before the
result is not posted again. Each step waits for the state it expects, a
re-post check waits for a newer post, and checks that nothing changed
run after a barrier notification. Its two updates wait 700 ms first, so
Android's update rate limit can't drop them on quick reruns (12
back-to-back runs passed). Removing the cleared-card check, or dropping
the mark on re-post, fails it.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-25 06:27:18 +00:00
Tom Brow
2f1be86525 Apply a confirmed age restriction to Android push wakes (#9925)
Follow-up to [#9804 handle Android push
wakes](https://github.com/block/buzz/pull/9804), from its review: a
confirmed age restriction now applies to Android push wakes, as it
already does on iOS.

## What it does

- A new native `AgeRestriction` holds a confirmed restriction for the
life of the app process. Like the iOS restriction session, nothing is
saved: a later launch starts unrestricted and the age check runs again.
- The age gate's purge (`purgeAgeRestrictedNotifications`) now runs on
Android. It sets the restriction and cancels every notification Buzz has
posted. Restore (`restoreAgeRestrictedNotifications`) clears it. Both
were iOS-only before.
- On Android the restriction is released only when an age check in the
current engine finishes without restricting (allowed, or failing open).
The process can outlive the engine, for example after Back from the
restricted screen, and a reopened app starts its age state as allowed,
so releasing on that first build would lift a restriction the process
still holds before the new check answers. A retired check releases
nothing. iOS keeps restoring from the push bootstrap as before.
- The purge starts as soon as the age check confirms a restriction, not
when the restricted screen first draws. The check can answer while Buzz
is in the background, where Flutter draws no frames until the user
returns, so before this wakes kept posting until then. This also closes
the same gap on iOS. The restricted screen still retries a failed purge,
and a retry that a resume has replaced stays quiet, so a late failure
can't purge again.
- While the restriction holds, a push wake is skipped before it fetches
anything, the same way as when notifications are turned off.
- Every post from a wake (conversations and the generic "New activity")
checks the restriction under the same lock the purge takes. So a wake
already running when the restriction arrives posts nothing after the
purge, and a post already in progress finishes before the purge cancels
it.

## Decisions

- **Process lifetime, as on iOS.** Wakes run in the app's process, so an
in-memory flag covers every wake while the confirming process lives. A
wake that starts a fresh process (after the app was killed) is not
restricted until the app runs its check again. That matches iOS, where
the restriction ends with the process holding its lock.
- **No release-config change here.** `BUZZ_AGE_GATING_ENABLED` is still
set only for iOS builds, and no build sets the Firebase config yet.
Adding either to an Android build is a separate release change.

### Validation

Added tests:
[`AgeRestrictionTest.kt`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/android/app/src/test/kotlin/xyz/block/buzz/mobile/AgeRestrictionTest.kt)
covers restrict, release and a post that is in progress when the
restriction arrives.
[`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/shared/push/push_bridge_test.dart)
now covers the purge and restore calls on iOS and Android. The age
gate's outcome table now runs on Android and counts releases: none while
the check is pending, one after an adult, error, malformed or timed-out
result, none after a minor.


[`age_signal_provider_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/features/age_gate/age_signal_provider_test.dart)'s
upper-bound table now also checks that a confirmed restriction starts
the purge with no widget or frame involved.
[`age_gate_app_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/features/age_gate/age_gate_app_test.dart)'s
purge retry test now uses the real notifier, with a resume while the
first purge is still running.

On a Pixel 9a (Android 16), a debug build with a local test relay. A
temporary debug hook called the native restrict and release directly,
because the phone was locked and Flutter doesn't draw frames behind the
lock screen:

1. Allowed: a wake posted the new message.
2. Restrict: the posted notification was removed.
3. While restricted: a wake logged `wake ignored foreground=false
restricted=true` and posted nothing.
4. Release: the next wake posted both the message that arrived during
the restriction and the new one.

The Dart side calling purge and restore is covered by the bridge test
above.

## Regressions

None expected: without age gating enabled, the restriction is never set
on Android.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-24 22:14:05 -08:00
Tom Brow
9bddaa1b64 feat(mobile): keep the message of Dart programmer errors in reports (#9822)
Makes issue titles for Dart programmer errors say what went wrong. Today
the diagnostic filter replaces every error's text, so a `StateError`
report is titled "StateError: Error text removed before sending." and
the issue list can't tell one bad state from another.

## Changes

- **Keep programmer-error text:** for `StateError`, `TypeError`,
`AssertionError` and `UnsupportedError` (which includes
`UnimplementedError`), the filter keeps the first line of the error's
own text, ending at a line feed or carriage return. Developers write
these messages (for example Riverpod's "Bad state: Using "ref" when a
widget is about to or has been unmounted is unsafe."), so they name the
fault. Every other error type still has its text replaced. The text is
kept because of the error's type, whichever code threw it (the app, a
package or the SDK), so the accepted risk is a message that interpolates
a value the URL and key checks miss, such as a short secret or a
fragment of what someone wrote.
- **Text with a URL or a long line is replaced:** where a URL ends in
free text is ambiguous (quotes, spaces, a scheme inside a word), so a
first line gets the fixed wording instead of having its query string
stripped when it contains `://`, a `?` or `#` after a `:` in the same
word (a `mailto:` link has no `//`), or any other `?` or `#` followed by
anything but closing punctuation before the next space. Nullable types
such as `List<String?>` keep a type error readable. Object identity
hashes such as `RenderFlex#1a2b3` are removed first, so Flutter and
Riverpod titles that name an object stay readable. A first line over 200
characters gets it too, since long lines and the lines after the first
usually quote other text such as a response body or a wrapped error.
- **FlutterError stays replaced:** the SDK reports a `FlutterError` as
"AssertionError" because it implements one, so the filter checks the
thrown object itself, and a `FlutterError` is excluded before the
programmer-error check.
- **Spec, ADR and glossary:** the spec, ADR 0007 and CONTEXT.md name the
kept first line and state that accepted risk.

## Validation

New tests cover each kept type keeping only its first line (split by a
line feed or a carriage return), nullable types staying readable, the
fixed wording for text with a URL (including one with an apostrophe, one
inside a word and `mailto:` and `tel:` queries starting with
punctuation), fragments, provider names with and without an argument, or
a long line, `FlutterError` and other errors still replaced, and the
type identifier the SDK installs.


Full-app simulator run at 6a0d9d4: cold start and session restore, the
channel list, opening channels and scrolling history, opening an image,
a DM, search, channel details, sending, reacting to, editing and
deleting a message, backgrounding and resuming, and Settings > Send test
report (sent, with no error) all passed, with no crashes or uncaught
errors. A thread reply didn't post during the run, which overlapped
relay rate limiting. This change only touches report filtering, which
isn't on the send path.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-24 22:12:17 -08:00
Tom Brow
9f56569f6f test(mobile): hold a push wake claim past the deadline instead of timing it (#9919)
## Summary

The push wake journey test checked the case where storage is still
claiming messages when the wake's budget runs out by giving every claim
a 100 ms delay and racing it against a 700 ms budget. On a loaded
machine a claim could land just after the 250 ms claim grace, be
recorded as shown, and never be returned, so the test's "partial plus
rest is everything" check failed intermittently.

The test now holds exactly one claim open until the wake has answered,
then releases it, and checks:

- the held message is not in the wake's notifications;
- its community is reported as failed, so the wake is incomplete;
- every other message is shown exactly once across this wake and the
next.

A new `HeldClaimShownMessageStore` test helper holds the claim. No
production code changes.

## Validation

Test-only change. The rewritten case passed 3 of 3 consecutive runs
locally.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-24 18:03:25 -08:00
Tom Brow
0966f3fad6 feat(mobile): tag escaped relay errors with their call and reason class (#9821)
Makes relay errors that nothing catches readable in diagnostic reports.
Today an unhandled relay rejection or timeout arrives with its text
removed and a stack that stops at the async error handler, so a report
can't say which call failed or why.

## Changes

- **Typed call and reason:** relay errors now carry the call (`publish`,
`query`, `history`, `subscribe`) and a fixed reason class taken from the
relay's reason prefix (`invalid`, `rate-limited`, `restricted`,
`auth-required`, `blocked`, `duplicate`, `pow`, `unsupported`, `error`,
`timeout`, or `other`). Types:
  - `RelayEventRejectedException` implements the new `RelayCallError`;
- new `RelayTimeoutException` extends `TimeoutException`, and
`RelayAckTimeoutError` now extends it;
- new `RelayClosedException` replaces the plain `Exception` for a closed
history or live subscription, with the same `toString`.
- new `RelayQueryException` (a `RelayException` that is also a
`RelayCallError`) for a non-2xx `/query` answer, with its reason from
the status alone;
- a one-shot signed event the relay refuses now fails with a typed
rejection, with the same text.
Existing `TimeoutException` checks and message helpers behave as before.
- **Report tags:** before the filter runs, a report whose error is a
`RelayCallError` gets `relay.call` and `relay.reason` tags. The relay's
own text is never sent. These reports are also grouped by call and
reason on top of the default grouping, so a rate limit and an invalid
request from the same code become separate issues.
- **Call-site stack:** pending publishes, one-shot signed events, and
history and live subscriptions keep the stack where they were created,
and errors completed later from timers or socket callbacks use it. A
report's stack now reaches the calling code.
- **Spec:** one bullet on the tags, the grouping and the stack.

## Validation

New tests:
- a table of reason prefixes to classes;
- error types, fields and the existing message helpers;
- relay session cases: a rejected publish's call, reason and calling
stack, the timeout types, and closed subscriptions;
- reports: tags, the grouping key, no relay text, and non-relay errors
untouched.
- production refusals through a serialized report: `/query` statuses,
snapshot `/query` versus discovery, and one-shot rejections and timeouts
with the caller's stack.


Full-app run on an iOS simulator (signed in, healthy relay): cold start
and session restore, channel list, opening channels and DMs, history
back to each channel's start, send, react, edit, thread reply, search,
channel details and Add Members, Settings > Send test report, and
background then foreground followed by a send and a delete. All passed
with no new errors in the device log, and no doubled error names in any
logged text. Error paths (timeouts, closed connections, relay
rejections) weren't triggered on the healthy relay; the unit tests above
cover them.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-24 16:29:14 -08:00
Stephen Edwards
36e6e4f8e7 fix(mobile): apply message edits only from authorized authors (#9887)
## Why

Buzz mobile now checks who signed each edit before deciding what to show
in a channel or thread. That includes edits to the first message of a
thread loaded from local storage. Mobile also preserves the information
needed to verify edits after an offline restart and retries missing
profile lookups when the app reconnects.

The companion relay change is #9886.

## Mechanism

Mobile uses the first valid message reference on an edit and shows the
newest edit that passes its checks. It accepts edits from the original
message’s signer. If the relay signed the original, mobile also accepts
edits from the author named by the relay. A verified agent owner can
edit the agent’s chat messages (kinds 9 and 40002) and diff messages
(kind 40008) in the same channel.

**Agent owners.** Mobile verifies the owner named in the agent’s signed
profile. The app reads permission when a user opens the channel or
thread message menu or the image actions. The native photo viewer also
reads permission when it opens and checks again before deleting. These
paths and the timeline use the same signed profile to verify the owner.

When an agent’s signed profile names an owner, mobile saves the signed
event once and reads fields such as the name and avatar from it on
restart. If that entry exceeds the 16 KiB limit, mobile saves the
display fields alone if they fit. Mobile needs the signed profile to
verify the owner. When the app connects, it asks for profiles needed to
check edits in the current timeline and retries unresolved lookups on
reconnect. The cache skips profiles it has already checked with the
relay and public keys the relay recently reported as having no profile.
Once mobile loads a newer profile from the relay that no longer names
the owner, it stops applying that person’s edits. The next time that
person opens the message menu, Edit is absent. In the device test, both
changes took effect after restarting the app.

**Relay signing key.** While connected, mobile looks up the key if the
timeline contains an edit whose signer differs from the original
message’s signer and the original has a public key in an `actor` or `p`
tag. A mention in a `p` tag can also trigger the lookup. Mobile uses
that tagged author only after confirming that the relay signed the
original message.

Mobile keeps the last key during reconnects and can read it from the
saved-message store after an offline restart. If the timeline still
needs the key when mobile reconnects, mobile refreshes it so a rotated
key can take effect during the same session. A failed request or a
response without a key leaves the previous key available. Thread
summaries read the key available when they refresh and start no key
lookup.

## What changed

- Start with `edit_authority.dart` for the profile and key lookups and
the permission check that runs when actions open. See
`timeline_message.dart` for edit selection and
`thread_detail_helpers.dart` for the first message of a thread loaded
from local storage.
- See `verified_profile_owner.dart` for ownership verification,
`profile_snapshot.dart` for storage and restore,
`user_cache_provider.dart` for profile refreshes, and
`SavedMessageStore.relayAuthor` for the saved relay key.
- Tests cover edit selection, owner edits to chat and diff messages, and
edits to a saved thread’s first message after replies load. They also
cover opening message and image actions, restored profiles without a
signed copy and profiles signed by the wrong key, reconnect retries,
offline reopening with a large signed profile, and a newly fetched relay
key replacing a saved key. Tests also verify that the native photo
viewer blocks deletion if permission is withdrawn while it is open, that
opening message actions requests a fresh profile when the saved profile
names the viewer as owner but lacks a signed copy, and that a tampered
saved profile cannot verify ownership.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Stephen Edwards <sedwards@squareup.com>
2026-11-24 10:34:52 -05:00
Tom Brow
d4c0729a86 fix(mobile): Android push follow-ups from enrollment review (#9892)
Follow-ups from the review of #9811 (Android push enrollment): the
review items that were safe to leave for after merge.

- **A timed-out gateway call is now aborted.** The 15 s timeout used to
abandon the POST while it kept running, so a retry could race the
original request at the gateway. The gateway client now sends through
`boundedHttpResponse`, which aborts the request at the deadline (and
caps the reply size).
- **An Android gateway reply the app can't read is reported to
diagnostics,** as #9806 does for iOS. Malformed replies (no JSON object,
missing fields, or an oversized reply with the expected status) throw
`AndroidPushGatewayResponseInvalid`, which `enrollBuzzPush` reports
under the push gateway operation. Refusals and transport failures stay
unreported, and a refusal keeps its status even when its body is over
the cap.
- **The delegation sweep after enrollment keeps the enrolling relay
while it is still wanted.** It now sweeps with the desired relays plus
the enrolling origin, but only while `stillWanted()` holds, so an
opt-out that landed during the delegation still sees that delegation
revoked.
- **Tests for two paths that had none:** an opt-out that lands while the
gateway answers the delegation ends the attempt quietly (no lease,
delegation revoked, no failure retry), and an opted-out iOS community
enrolls nothing.

Two other items from the review, both Codex findings on an earlier head
of #9811 (reusing a revoked grant after a lost re-delegation; deleting a
key after a lost renewal), were already fixed and tested before #9811
merged, so nothing changes here for them.

### Validation

Added tests:
- [the enrolling relay keeps its delegation before the caller lists
it](157d6d4759/mobile/test/shared/push/android_push_authority_test.dart):
the sweep keeps a still-wanted relay that the desired list doesn't show
yet, and revokes a delegation whose community opted out while it was in
flight.
- [turning push off while it delegates ends the attempt
quietly](157d6d4759/mobile/test/features/settings/android_notifications_test.dart):
production bootstrap, opt-out while the delegation response is held.
- [only a gateway reply the app cannot read is
reported](157d6d4759/mobile/test/shared/push/push_bridge_android_test.dart)
and [a gateway call that times out is aborted, not
abandoned](157d6d4759/mobile/test/shared/push/push_bridge_android_test.dart).
- [a community that opted out enrolls
nothing](157d6d4759/mobile/test/shared/push/push_bridge_test.dart)
(iOS).
- [an unavailable gateway keeps the journal and a refusal clears
it](157d6d4759/mobile/test/shared/push/android_push_authority_test.dart):
now also with refusal bodies over the 64 KiB cap.

Each test was checked to fail with its guard removed.

No device or full-app run: every change is on the Android push gateway
path (which needs a gateway-configured Android build) or is a test, and
the behavior changed is timeout, malformed-reply and race handling that
the tests above drive directly against the production authority and
bootstrap.

### Regressions

- iOS is unchanged apart from the new test; the abort and diagnostics
changes are Android-only code.
- `boundedHttpResponse` gains an optional `timeout` that defaults to its
old 30 s, so existing callers behave as before.
- Gateway replies are capped at 64 KiB. Gateway responses are small JSON
objects, so an oversized reply with the expected status is itself a
defect and is reported. An oversized refusal is handled as that refusal
(a 503 stays retryable, a 403 discards the pending enrollment).

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 16:25:19 -08:00
Tom Brow
5825a7a81f feat(mobile): handle Android push wakes (#9804)
Ticket 6 of the [Android push
design](https://github.com/block/buzz/pull/9555), building on [#9558
resolve push wakes](https://github.com/block/buzz/pull/9558). Enrollment
(FCM token registration, ticket 7) landed separately in [#9811 enroll
Android push](https://github.com/block/buzz/pull/9811), which also
carries the Firebase build config, `POST_NOTIFICATIONS` and the
auto-init switch.

## What it does

A data-only FCM message wakes the app with no content. This PR turns
that wake into notifications natively, with no UI:

- `PushWakeService` (a `FirebaseMessagingService`) treats both a message
and the deleted-messages callback as "sync now".
- If the app is in the foreground it does nothing. Otherwise it starts a
headless Flutter engine on `androidPushWakeMain`, which runs ticket 5's
`resolvePushWake` and hands the notifications back to native code to
post.
- If nothing has been posted after 2 s, a generic "New activity"
notification appears in the "Other" channel. The real result replaces it
silently, or removes it when there is nothing to show. An 8 s native
watchdog ends a run whose Dart side hangs.
- One run per process. A wake that arrives mid-run joins it and sets the
rerun flag from ticket 5.
- Channels: Direct messages, Mentions, Other. Each conversation is one
`MessagingStyle` notification, grouped under the app. Existing messages
in a conversation are recovered from the active notification so a new
wake appends instead of replacing.
- Tapping opens the conversation through the existing push deep-link
path (`pendingPushNotificationLink`), for a cold start and for a running
app. This also turns on the cold-start tap handoff for Android, which
was iOS-only.
- The headless path sends the NIP-FI header that org-protected relays
need, using the same `HostedRelayAuth` as the foreground app (background
mode: a fresh assertion per wake that never records foreground
failures). `resolvePushWake` gets one optional `relayHeaders` hook for
it.

## Decisions

- **Firebase config is build-time and never committed.**
`BUZZ_FIREBASE_APP_ID`, `BUZZ_FIREBASE_API_KEY`,
`BUZZ_FIREBASE_PROJECT_ID` and `BUZZ_FIREBASE_SENDER_ID` become string
resources (no google-services plugin or JSON file). All four or none: a
partial set fails the build, and a build with none works but has no push
wake. Documented in `mobile/README.md`.
- **The wake only reads the saved account session.** Its account clients
share the foreground app's record, so they never save, replace or delete
it. A rejected credential is dropped from the wake's memory only, which
keeps a sign-in that finished mid-wake.
- **No FCM token before enrollment.** Firebase Messaging's auto-init is
off, so a configured build does not register with Firebase at launch.
Ticket 7 requests the token when the app enrolls.
- **Notifications disabled means the wake is skipped entirely**, so
nothing is claimed as shown and the next wake after the user re-enables
them still delivers.
- **Debug hook.** Debug builds include an exported receiver that runs
the same code path as the FCM service, for testing without Firebase.

## Known gaps

- The foreground app does not yet write the shown-message record, so a
message already read in the app can notify again after the app is
backgrounded. This needs its own ticket.
- `PushWakeService` is now the app's only messaging service, so it
should hand `onNewToken` to the registration plugin from [#9811 enroll
Android push](https://github.com/block/buzz/pull/9811). It doesn't yet.
- Follow-ups now that enrollment is on main: real FCM wakes run one at a
time and never join a run; a blocked or silent "Other" channel mutes a
slow DM; a stale generic can make one message alert twice; NIP-FI
issuance can use the whole wake budget; a consumed tap replays after
process death; cold engine start registers every plugin.
- Follow-ups from review:
- A confirmed age restriction isn't applied to Android wakes, and the
Android purge doesn't cancel posted notifications.
- One unreadable entry, or a throw from `notify`, sends the whole batch,
already recorded as shown, to the generic notification.
- The foreground check can lag about 700 ms behind the app becoming
visible.
- There is no group summary, so below Android 16 several conversations
show as separate cards.
- On API 24 and 25 the notifications have no priority or defaults, so
they don't sound.
- A stall delivering the result over the channel can still use up the 1
s reserve before the watchdog.
- A shown-message claim writes its marker before its watermark and prune
I/O, so a stall past the 250 ms claim grace loses the message (from
[#9558 Dart
wake-to-notifications](https://github.com/block/buzz/pull/9558)).
- A live tap during cold start can be handled before the startup tap,
and the tap's target is carried in extras any app can send.
- The native side has no JVM tests yet, although `app/src/test/kotlin`
exists and CI runs it. A payload-contract test for
`WakeNotification.fromDart` and a test of the production
`_headlessRelayHeaders` wiring are follow-ups. The device runs below
cover the native side, and the Dart side (payload shape, joined runs,
header hook, cold-start tap) has tests.

### Validation

Run on a Pixel 9a (Android 17) against a local fake relay with test data
only, using a profile (AOT) build with the debug hook, since debug (JIT)
builds start the Dart engine in 4 to 5 s and say little about real
latency. Timings come from the `BuzzPushWake` log tags, measured from
the start of the wake.

| Scenario | Result |
| --- | --- |
| Cold wake, process killed, one DM | Notification posted at 2.0 s
(engine 0.9 s, Dart ready 1.8 s), three runs within 0.1 s of each other
|
| Wake while the process is warm | Posted at 0.4 s |
| Two conversations in one wake | One grouped notification card, each
conversation its own `MessagingStyle`, posted at 2.1 s |
| Relay answers in 2.4 s | Generic "New activity" at 2.0 s, replaced by
the real notification at 5.8 s, generic removed, replacement did not
beep (the system's `notification_alert` event shows no sound for it,
while the generic did beep) |
| Relay answers in 3.5 s (over the 3 s request limit) | Generic stays at
5.0 s, nothing is claimed |
| Next wake after that, relay healthy | Real notification at 0.4 s and
the stale generic is gone (the case fixed in `c786957`) |
| Relay accepts the connection and never answers | Dart's own 3 s
request timeout ends the wake at 5.0 s as incomplete, generic stays |
| App in the foreground | Wake ignored, no notification; after
backgrounding, the next wake delivers |
| Tap, app running in background | The existing deep-link provider
receives the right community, channel and message; notification
dismisses |
| Tap, process killed | Same |
| 10 wakes in a row, debug build, app process kept alive | Network
threads stay at 3 and total threads flat (53 to 58). Before the switch
to dart:io, each wake left about 2 Cronet threads behind (3 to 11 over 5
wakes) |

An earlier run on an Android 36 emulator gave the same behavior.

Not exercised: the FCM service itself (it is not exported and there is
no Firebase config), so the deleted-messages callback was not triggered,
though it calls the same entry as the debug hook. The 8 s native
watchdog was not reached: a hung relay is always ended earlier by Dart's
request timeout, and only a hung Dart isolate would trigger it. NIP-FI
against an org-protected relay is covered only by unit tests. The tap
was checked up to the deep-link provider, not to the chat screen,
because the fake relay does not serve the channel list the app needs to
open it.

On a debug (JIT) build the main thread is busy for several seconds
starting the engine, so the 2 s generic timer, which runs on that
thread, fired at 5.3 s.

Added tests:
[`android_push_wake_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/android_push_wake_test.dart)
covers the native payload, joined and sequential wakes, the relay header
hook, and a community whose headers fail.
[`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/push_bridge_test.dart)
covers the Android cold-start tap.

### Screenshots

Before: no notification (nothing handles wakes). After, with test data,
on the Pixel 9a (two conversations grouped) and on the emulator (one
conversation after a cold wake):

<img
src="https://github.com/user-attachments/assets/d3d98784-fecc-4757-a867-0a93d5a210a5"
width="300" alt="Two conversations grouped on a Pixel"> <img
src="https://github.com/user-attachments/assets/1e7fea3c-7f72-4f8d-90d1-8c289cf1b740"
width="300" alt="One conversation after a cold wake on an emulator">

## Regressions

- Adds the `POST_NOTIFICATIONS` permission and the Firebase Messaging
and `lifecycle-process` dependencies, so the Android build and APK grow.
The runtime permission prompt is not part of this PR.
- Debug builds ship an exported broadcast receiver that can trigger a
wake. Release builds do not include it.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost:3000>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 16:43:08 -07:00
Tom Brow
07dfdbc60c perf(mobile): keep large images in the disk cache (#9906)
The mobile image disk cache never saved a file over 5 MB. A
full-resolution photo posted in a channel (12.5 MB in one case) was
therefore downloaded again on every cold start, and again whenever it
left the in-memory image cache.

This drops the per-file cap. Each download is already capped at 20 MiB,
and the cache's 250 MB byte budget evicts least recently used files, so
a large photo can take at most 8% of the budget before eviction handles
it. Overlapping saves of one URL now wait for each other, so the second
replaces the first file instead of leaving an untracked copy behind.

Making large files cacheable makes three existing edge cases bigger, so
this also:

- **Bounds each eviction pass.** One large image saved into a cache full
of small files could evict about 2,000 of them in one UI-isolate pass
(100 to 300 ms of frame gaps). Each pass now deletes at most 256 files
and schedules the next until the cache is back in budget.
- **Publishes saves atomically.** A save writes beside the file and
renames over it, so a reader during a refresh sees the old image or the
new one, never part of the new file.
- **Cleans up interrupted saves.** A failed write deletes its partial
file, and files the index doesn't track (a save cut short by the app
exiting) are deleted in the background once the cache opens (so the
first image doesn't wait for the directory listing). A file left
untracked within a session waits for that next open.
- **Retires a disposed cache's eviction.** Switching away from a
community and back reopens its cache on the same directory. The old
cache's scheduled eviction pass, which more passes make likelier, could
then save its stale index over the new one and drop newer saves.
Disposing now stops that cache's eviction and lets its saves in progress
finish, and its index drops any later write, such as a late read marking
a file used. The reopened cache opens only once the old one has closed.
If that takes over 3 s, the images waiting meanwhile skip the disk, and
later ones use it once the close finishes.

Timeline images can't use the relay's thumbnail instead: thumbnails are
at most 320 px on their longer side, well below a timeline image's width
on a 2x or 3x phone.

### Validation

- The [disk cache journey
test](https://github.com/block/buzz/blob/mobile-large-image-cache/mobile/test/shared/relay/media_disk_cache_test.dart)
now loads a 12 MiB image, then shows it from disk on an offline
relaunch, and a background refresh that returns a large image replaces
the saved copy instead of deleting it.
- The disk cache eviction test now also saves one URL twice at once and
checks that only one file stays on disk. Two decode sizes of one image
can save concurrently, and before this change each save created its own
file.
- The same test now drains a large save into a full cache over several
capped passes with no later reads, deletes untracked and partial files
on relaunch, and checks that concurrent reads during repeated refreshes
only ever see a whole image. It also disposes a cache without waiting,
as the app does, with a save and a read in progress, reopens and saves,
lets the old cache's scheduled pass run, and checks that every save
survives a relaunch.
- A further step holds the old cache's close past a shortened wait: the
reopened cache misses at first, then reads from disk once that close
finishes, and a relaunch finds both caches' saves.
- Removing any one of these makes the test fail: the wait for a closing
cache, the open once a slow close finishes, dispose waiting for saves,
the retired index's eviction and deletion checks, the sweep's 5 s
margin, and close waiting for the sweep. The closed index's write checks
fail the test only as a set, since each covers for the others, and the
check on single deletes has no test. The atomic rename has no reliable
failing test: removing it fails the refresh step in only some runs.

### Regressions

- **Disk:** the budget is unchanged at 250 MB per community and account.
Large photos now count against it, so fewer small images may fit before
eviction, which costs at most a re-download of the least recently used
ones.
- **Memory:** unchanged. The cache writes bytes the app already holds
after decoding, and a read loads one file, as before.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 15:10:46 -07:00
Tom Brow
9a9d579460 feat(mobile): resolve push wakes into notifications in Dart (#9558)
Ticket 5 of the [Android push
design](https://github.com/block/buzz/pull/9555). It builds on [#9556
Dart body formatter](https://github.com/block/buzz/pull/9556), now
merged. Native posting, the 2 s generic notification, the foreground
check and FCM are ticket 6 and are not here.

## What it does

`resolvePushWake` is the Dart half of an Android push wake. A wake
carries no content, so it means "sync now": the function reads the saved
communities, signs a `/query` to each relay (the same NIP-98 request the
app uses), fetches what is newer than the last shown message, applies
the same eligibility rules as the iOS resolver, and returns every
eligible unshown message with title, body (ticket 4's formatter),
conversation id, navigation target and category (direct message or
mention). It is plain Dart: no Flutter UI and no Riverpod app state, so
a headless engine can run it.

- Eligibility is a port of the iOS `PushLeaseMatcher`, applied to the
same subscriptions the app already syncs: self-authored messages and
muted DMs are ignored (mutes reach the subscriptions for DMs only, as on
iOS), and a message tagging more than 20 people is dropped. Only joined
DMs and `#p` mentions notify.
- Results are bounded: newest 20 overall, newest 8 per conversation.
Messages cut by the caps are still recorded as shown, so a later wake
does not bring them back.
- `PushWakeRunner` runs one wake at a time per process. A wake that
arrives mid-run sets a rerun flag, and every waiting caller gets one
result with the notifications of every pass.

## Decisions

- **Shown record.** One empty marker file per message, created
exclusively. That is atomic across isolates and processes with no lock,
and the foreground app can write the same record through the same
`claim`. The newest time is the maximum of the marker names, so it can
never move backwards (a separate cursor file would lose updates between
concurrent writers). Markers older than 15 minutes before the newest are
deleted. The app's other stores don't fit: `shared_preferences` has no
atomic read-modify-write across isolates, and secure storage has none
either. File locks were avoided because POSIX locks are per process, and
the app and the background engine share a process.
- **Claim before post.** `claim` is the post decision, so a message is
returned at most once. If native posting then fails, the message is not
offered again, as on iOS.
- **Claim oldest first.** Each claim can advance the newest time, and
claim rejects anything more than 15 minutes older, so messages are
claimed oldest first. A wake cut short leaves only messages newer than
everything it claimed, which the next fetch still covers.
- **Fetch window.** Fetches start 15 minutes before the newest shown
message, the same reorder window the iOS cache uses, and claim rejects
anything older. With no record yet, the fetch looks back 15 minutes
only, so a new install or community doesn't dump history.
- **Timeouts.** 3 s per fetch request, 1.5 s for the sender and channel
name lookup (which runs after messages are claimed, so a slow lookup
costs only names), 5 s overall from entry, well under the ~8 s native
watchdog. On expiry it returns what it has. `PushWakeResult.incomplete`
lists communities that couldn't be read; with no notifications it tells
the caller to use its generic fallback. Communities that failed record
nothing, so the next wake retries them.
- **Paging.** A relay answers each filter's newest `limit` events, so a
page filled by messages that can't notify could hide an eligible one. A
subscription whose 50-event page comes back full is read again below its
oldest event, up to 5 pages per community; a community that stops at the
cap, or whose later page fails, is reported incomplete and keeps what it
read. A page over the 4 MiB cap is asked for again with half the events.
- **Fresh reads.** Message filters ask for `"consistency": "strong"`, so
a wake for a message that has just arrived isn't answered by a replica
that lacks it. That costs one writer read per community per wake.
- **Deadline.** The 5 s budget runs from entry, reading the community
list included, and no request may outlast it. Claims already running get
250 ms to finish, and what a community claimed before the deadline is
still returned.
- **Thread target.** A reply opens its direct parent's thread, as the
in-app inbox does; a broadcast reply opens the channel.
- **Transport.** HTTP `/query` rather than a WebSocket: one round trip
per community, no connection to keep, and the same request the iOS
resolver sends.

## Regressions

Nothing existing changes: the new files are not referenced by app code
yet, so there is no runtime effect until ticket 6 wires them in. Bugs
stay inside the new wake path.

## Open questions

- Organization-protected relays need a federated-identity header, which
the iOS extension gets from a shared session. The headless path sends
none yet, so such a community is reported as failed. Wiring it belongs
with ticket 6 or 7.
- Before ticket 6 calls this: the notifications setting is read only at
entry, where iOS rechecks before posting; and Solo chat titles get a `#`
where iOS and the app show none. A wake the deadline cuts short claims
oldest first, so it can show older messages and leave the newest for
another wake that nothing prompts (each winning claim lists the store
directory again, so a long offline backlog on slow storage is where this
bites). Ticket 6 can rerun when a wake is incomplete but returned
notifications, or batch the claims: oldest first, all markers created
before one listing that checks and prunes, cap overflow still recorded.
A claim that storage never answers can still be lost after the 250 ms
grace.
- First-wake baseline: with no shown record yet, a wake looks back only
15 minutes, so a phone's first wake after a longer outage (still inside
the relay's delivery window) can miss the message that caused it and
report complete. Ticket 7 owns the fix: write a bounded baseline at
enrollment, before wakes are turned on.
- A wake reads the community snapshot at entry; rechecking the saved
community, identity and push preference just before posting is on ticket
6's list, before ticket 7 turns wakes on.
- Sender names come only from profiles their authors signed. Channel
titles come from kind 39000 events whose id and signature check out, but
nothing yet checks that the signing key is the relay's, because the
community record has no relay key. That check belongs with ticket 7's
enrollment work, which learns the relay key. Until then a relay could
only mislabel a notification the user is already entitled to.

### Validation

Added tests:
- `push_wake_journey_test.dart`: journeys against a fake relay (only
`/query` over HTTP is fake): DM and mention notify; self-authored,
muted, hellthread, unrelated and text-less messages don't; already shown
doesn't repeat; several messages across two conversations after one
wake; a missed wake recovered by the next; a catch-up after a quiet
spell returns messages more than 15 minutes apart; several communities,
including a wake stopped partway by a failed claim whose leftover
message is far newer than the one claimed; per-conversation and overall
caps without resurfacing; slow, silent and unreachable relays return
inside the budget and recover on the next wake; two wakes in different
"isolates" never notify twice; the app recording a message during a run
is respected; a wake mid-run reruns once and loses or repeats nothing,
and is reported incomplete when no budget is left to rerun.
- The journeys now also cover: an eligible DM and mention behind a page
of messages that can't notify; an oversized page retried at half size; a
relay past the page cap, and a later page failing, both leaving the
community unfinished; message reads pinned to the writer; reply and
broadcast-reply tap targets; unsigned or forged names falling back to
short keys; a community list that never loads, and storage that stalls
one community's claim, both ending at the budget.
- `shown_message_store_test.dart`: concurrent claims, the reorder
window, future-dated messages, pruning.

Break checks: removing the hellthread rule fails the first journey;
making marker creation non-exclusive fails the concurrent-claim test and
the two-isolate journey; claiming newest first fails the catch-up and
partial-wake steps; dropping the skipped-rerun flag fails the rerun
journey.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 15:04:45 -07:00
klopez4212
8cc7e94392 Refine mobile Messages sections, Duo navigation, and chat typography (#9885)
## Summary

- Organize mobile Messages into configurable flat sections. See All
keeps the list and its search position when opening a conversation, and
supports side-by-side browsing on an unfolded Duo.
- Use the same 16-point Messages gutter in booklet and open Duo layouts.
The regular iPhone uses 20 points. Align navigation actions and use
native inline titles on See All.
- Update mobile typography and spacing across chat rows, message
bubbles, drafts, and the composer. Render code proportionally to the
17-point message body.

## Device review

Compare the leading edges of the section headings and channel icons in
Messages on the open Duo and in booklet mode. Open See All and check
that its rows follow the same column.

---------

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-23 13:14:05 -08:00
Tom Brow
e600cdbde2 feat(mobile): time channel opens and relay connection recovery (#9858)
Adds two durations to the mobile networking diagnostics, so work on
channel opening and reconnecting has a before and after number from real
use:

- **Channel open** (`channelOpen`): from asking for a channel's newest
history to the messages being shown, or to the failure that stopped it
(including a refusal on the live subscription, or one a thread screen
reports, which counts as a failed open with no duration when it comes
before the history was asked for). Only a channel's first load counts; a
catch-up after a reconnect is not an open. An open cut short by a lost
connection keeps its clock, so the wait for the reconnect counts. An
open that spans a move to the background, or starts there, is not
counted, since it measured the time away, and a return after leaving the
channel or after the background is a new open. An open the member backed
out of still counts, since the load took that long, unless they left
while a lost connection was still reconnecting, before its history was
asked for again; after a failed open a retry counts as a new one. A
refusal that arrives after a move to the background is not counted
either: whether a refusal can count is fixed when the load starts. An
open is filed under the member whose relay it ran on, and not counted
when the app has since moved to another member.
- **Relay recovery** (`relayRecovery`): from the last frame a lost
connection delivered to the next authenticated connection. Starting at
the last frame means the time it took to notice a dead socket counts
too, which the existing connect duration misses. The app cannot see
pongs, so a quiet connection is taken to have been alive until two ping
intervals (60 s) before the loss, and idle time does not inflate the
number by more than that: an idle connection that closes cleanly can
read up to a minute, since a clean close and a missed ping look the same
to the app. Failed attempts in between are part of one recovery. A loss
in the background or followed by a move to the background, and a loss
carried across a community switch, are not counted. A loss in the first
seconds after a return from a brief stay in the background can reach
back to before the stay, by at most that same minute.

Both durations run on a monotonic clock, so a correction of the device's
clock during an open or an outage does not inflate a sample or make it
negative.

Both go through the existing `network.event` count and
`network.duration` distribution with their endpoint name, like the other
networking events.

### Regressions

None expected. These add no requests: each is one counted event per
channel open or per recovered connection, recorded where the app already
counts connection events.

### Validation

Read from a profile build on an iPhone 12 mini against a hosted relay,
with a local log of each event:

- Seven channel opens after a cold start: `channelOpen` read 0.36 to
1.48 s per open, each matching the time from the history request to its
response in the request log.
- Three Wi-Fi drops of about 22 s with a channel open: `relayRecovery`
read 30.1, 47.0 and 30.4 s, each spanning the drop, the time until the
dead socket was noticed, and the reconnect. `relayConnection` alone read
0.28 to 0.36 s for the same reconnects, so the new duration is what
shows the time lost to the dead socket.

That run also covered the flows this touches: cold start, opening
channels with back navigation, and losing and regaining the network with
a channel open. Every open and every reconnect completed.

Added tests:

-
[relay_network_counts_test.dart](mobile/test/shared/relay/relay_network_counts_test.dart):
recovery is timed from the last frame, at most two ping intervals back,
spans failed attempts, is not moved by a device clock set forward or
back during the outage, and is not counted for the background or a
community switch; existing journeys now expect a recovery after each
loss.
-
[channel_open_timing_test.dart](mobile/test/features/channels/channel_open_timing_test.dart):
an open is timed once, to its history being shown; a reconnect catch-up
is not an open; an open spanning a reconnect keeps its start; a member
change during the open, or an open started after the app moved to
another member, records nothing; backing out still records it; a return
after leaving starts a new clock; an open spanning a stay in the
background, or started there, records nothing; a live refusal records a
failed open, once, with its time when the member already backed out and
with no duration when it comes before the history request; a refused
retry after a failed open is a new open; a refusal on reconnect ends an
open cut short by the lost connection with its full wait, or with no
duration if the app was in the background meanwhile; a refusal that
arrives before the history is asked for counts in the foreground and
records nothing after a move to the background; a refusal reported by a
thread screen ends a first open as one refused open, timed once the
history was asked for, records nothing after a move to the background,
and is not another open once the channel has loaded; a device clock set
forward or back during an open does not move its time; a relay deadline
is a timeout.

Known limits:

- The device run predates the final review commits, which changed which
opens are counted (background, member switch, refusals) and moved both
durations to a monotonic clock, not where an open or recovery starts or
ends.
- iOS Siri Quick Send tells the relay session the app is back in the
foreground while it sends. A Quick Send to a DM whose messages were
never loaded this run can count one open, and a connection lost during
the send can count a recovery. Both are true first-load and recovery
times, at most one open per DM per run. Moving Quick Send onto the
background-work hold would remove both, which changes Quick Send and is
left out of this PR.
- When a saved page of a channel is already on screen, `channelOpen`
measures how long fresh history took rather than how long the member
waited to see anything, and it ends when the messages are handed to the
screen, not at the first frame that draws them.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-23 12:22:14 -08:00
Tom Brow
6017091936 refactor(mobile): remove the dead per-signer cache sweep (#9902)
## Summary

The media cache and saved channel-directory sweeps kept, for each saved
community, only the files of its current signer, and deleted the files
of any other account under the same community id. That state came only
from the same-relay credential replacement removed in #9896. Community
ids are random, and every remaining path that rewrites a saved
community's key keeps the same key (hosted reconnect refuses a different
one). So no community can change signer anymore, and the per-signer
cleanup is dead.

This deletes it. The sweep now keeps whole community directories by id
and deletes the directories of removed communities, as before.

## Changes

- `MediaDiskCache.removeOrphans` takes the retained community ids and no
longer sweeps signer subdirectories.
- Delete `OpenChannelDirectoryStorage.removeOrphans`. Its only job was
deleting other signers' files; a removed community's directory still
goes with its community directory.
- Delete the tests and assertions that covered signer replacement.

### Added lines

- The new, shorter `MediaDiskCache.removeOrphans` body and doc comment.
- The provider's retained set: community ids that have a signer, the
same communities the old map kept.
- Two doc comment rewordings that no longer mention replaced accounts.
- The media cache test's removal check, rewritten for the new signature.

## Validation

- Full mobile test suite, analyze, format and file-size checks pass.
- No user-visible change, so no screenshots.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-23 11:53:37 -08:00
Tom Brow
18e4b37d97 refactor(mobile): remove unused CommunityListNotifier.addCommunity (#9896)
## Summary

`CommunityListNotifier.addCommunity` has no callers in the app.
Communities are saved through the auth flow
(`authenticateWithCommunity`), so the method, including its same-relay
credential replacement branch, is dead code that tests kept alive.

This deletes the method and the test that covered it. Tests that used it
only for setup now seed `CommunityStorage` before building the provider
container, which is how the app loads communities at startup.

## Changes

- Delete `addCommunity` and its now-unused import.
- Delete the `addCommunity adds to list` test.
- Trim the two credential replacement tests to the startup sweep and
removal coverage they also held, and delete the storage helper only they
used. The trimmed tests still seed a retired signer's channel-directory
file at startup, and check that the saved-message scope is cleared while
the active community still holds a removed account.
- `community_entry_requirements_test` keeps only the authentication
path; the community addition variant tested the deleted method.

### Added lines

Ignoring whitespace the diff is +99/-282. The added lines are:

- `await communityStorage.save(...)` in place of each removed
`addCommunity(...)` setup call.
- `createContainer()` and the initial list read, moved below the seeded
communities so the notifier loads them.
- Reindentation in `community_entry_requirements_test` after removing
its outer loop.
- In the startup sweep and saved-message purge tests: a
channel-directory seed helper with its assertions, and a listener that
checks the saved-message scope during removal. These keep coverage of
the provider's per-signer directory sweep and the scope's
retained-identity guard, which the replacement assertions used to
provide.

## Validation

- Full mobile test suite, analyze, format and file-size checks pass.
- No user-visible change, so no screenshots; the deleted code had no
production caller.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-23 10:59:39 -08:00
Arthur Garza
4a440b5932 fix(mobile): keep Light/Dark/System on each device (#9894)
## Summary

Light/Dark/System was saved in the synced per-community theme
preference. A mode picked on one device, or carried over from an old
setting, followed the account to every other device. A user could end up
on Light without ever choosing it on that phone.

Brightness depends on the device (its OS setting, time of day), so
mobile now keeps the mode on the device:

- New `appearanceModeProvider` saves the mode in SharedPreferences under
`buzz-appearance-mode.v1`. It defaults to System.
- `App` reads the mode from that provider. The age-restricted path still
uses System.
- The Appearance picker starts from the device mode. **Set** saves the
mode locally and syncs only the chat color. The synced `theme` and
`followSystem` are written back unchanged, so the wire format stays the
same and other clients are unaffected.

The Buzz 1.0 desktop app (block/buzz-app) already keeps the mode per
device (`appearance.mode`, default System), so this brings mobile in
line. The deprecated 0.X desktop app is unchanged.

**Accepted tradeoff:** after updating, every mobile user starts on
System, including people who picked Light or Dark on purpose. They need
to pick it again once. This one-time reset is what fixes accounts stuck
on a carried-over Light setting. Seeding from the synced value would
keep them stuck.

### Related issue

None found. Came from an internal discussion about mobile defaulting to
Light.

### Testing

- `dart format`, `flutter analyze`, and the full `flutter test` suite
pass.
- New `test/shared/theme/appearance_mode_provider_test.dart`: covers the
System default even when the old synced or legacy settings are pinned,
reading and saving the mode, and unknown values.
- Picker tests: the mode is saved locally, the synced `theme` and
`followSystem` are kept, and Close discards changes.
- Not yet exercised on a device.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Arthur Garza <arthur.garzajr@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:38:16 -06:00
Wes
8c7f1c9e78 Cache recently opened mobile thread replies (#9844)
## What changes

Recently opened mobile threads show saved replies in the timeline while
relay history loads, including after an offline cold start. The thread
keeps the visible reply in place when relay history takes over. Relay
history supplies paging and reply counts. Until then, rows shown only
from disk are excluded from read marking and nested navigation. Live
rows remain interactive. After a fetch fails, a link can land on a saved
reply while the app retries. A manual scroll supersedes a pending link
jump. A deleted thread head keeps the reply status and Retry visible.

Thread pages use the existing app-private cache, keyed by channel and
outermost thread root. A completed scan supplies signed replies and
auxiliary events. Before saving, the app reuses a loaded signed root
when available. It queries the relay's primary database for a missing
root and for rows that need verification based on observed mutations or
the prior saved page. An additive table in the existing SQLite cache
records exact pruned IDs by thread. A restart retains that evidence and
an ordinary new reply uses the completed scan. The table is added
alongside existing saved channel pages and follows their scope, purge
and eviction rules. A channel-only prune skips the table allocation. At
SQLite’s page cap, a thread prune can reclaim space using the cache’s
existing eviction order. The cache verifies events before replacing a
page and retains the prior page if an applicable edit or deletion fails
verification.

A saved root lets its link open offline when the channel cache holds
only newer messages. Channel and identity purges include thread pages.
Live edits and deletions remove affected saved rows whether the thread
is open or closed. A confirmed thread query refusal marks the channel
unavailable, clears the thread and announces the change. An empty legacy
history response can also mean refusal, so it leaves a confirmed denial
in place until channel history verifies access. A deletion from relay
history or the saved page can also suppress the thread head.

## Thread cache limits

The app attempts a save once per thread open, with up to 200 replies
plus the root. The save makes at most one extra request, and a loaded
root with no affected edit targets can skip it even if the thread has
new replies. A first-time edit that the client has never seen can be
delayed by replica lag. If a live edit targets a reply that never
reached the saved page, the in-memory record is lost on app restart. A
reopen during replica lag can then save its earlier text. Evicting a
page also evicts its comparison evidence.

Bigger threads still load all their replies online. An oversized initial
scan clears the old saved page. Replies that arrive during a visit
become eligible for saving on the next online visit. If an attempt fails
or a live update retires it, the next attempt is on reopen. Links that
identify only a nested parent still use the existing channel lookup.

## Simulator comparison

iPhone 17e, iOS 27.0, debug build, same joined channel and seeded
40-reply thread. A local probe measured from dispatching the deep link
on a cold launch to the first reply appearing in the widget tree. The
offline runs used a stopped fixture relay. The candidate had opened the
thread once online before measurement. It retains the existing 250 ms
delay before starting a disk preview on a connected session. [Simulator
screenshots](https://github.com/block/buzz/pull/9844#issuecomment-7053182318)

| Reopen | `f9b18c7f3` | `49a071cad` |
| --- | ---: | ---: |
| Online, four runs per build | 978 ms median (915–990 ms) | 922 ms
median (903–1,143 ms) |
| Offline, three runs per build | No replies within 8 seconds in any run
| 832 ms median (810–856 ms) |

## Cold link to an older thread

I added 55 newer channel messages and verified in SQLite that the saved
channel page held 50 messages and omitted the thread root. One cold run
per condition on the same iPhone 17e fixture measured the first reply
after dispatch. The bounded build carried only a lint cleanup into the
published commit.

| Condition | Previous PR head `9756f89ed` | Bounded build `34067e50b` |
| --- | ---: | ---: |
| Online | 1,451 ms | 1,432 ms |
| Relay stopped | Opened the channel. No thread replies within 8
seconds. | Opened the thread and showed saved replies in 1,276 ms. |

The two regression tests fail on `9756f89ed` and pass with the fix. The
cache test reproduces an observed edit followed by a scan that returns
pre-edit text. The provider tests also check the one-attempt budget
across refresh and the 200-reply cutoff.

## Verification

- `just mobile-install mobile-check mobile-test file-size-check` passed
at `49a071cad`. 5,909 Flutter tests passed with 71 skipped, and all 27
crypto package tests passed.
- Widget regressions cover saved-to-relay handoff, unread and count
gating, live deletion, offline link arrival order, and refusal
semantics. The simulator comparison used synthetic data. Device-level
VoiceOver and TalkBack announcement behavior remains unverified.
- The open offline thread switched to live history after the relay
restarted. With the thread and channel then closed, a live edit and
deletion removed the two stale saved rows and retained all 38 other
replies in the cache.
- The iPhone 17e build at `30bf26781` reopened a seeded 24-reply thread
from a cold link in 1,105 ms online and 995 ms with the relay stopped,
one run each. The channel reply count also opened the saved thread with
the relay stopped. After scrolling back in the offline thread and
restarting the relay, the same replies stayed in place and the saved
label switched to the live reply count.
- At `dca8250fa`, the normal mobile pre-push and file-size checks
passed. The two SQLite page-cap regressions failed against `30bf26781`
and passed with the fix. The simulator timings below the original
comparison are from `30bf26781`.
- Local SQLite tests cover restart with a previously saved edit, restart
after live pruning removes the final row, rejection of a replacement
containing an invalid edit, a deletion that survives replacement, zero
extra writer requests when new replies arrive without edits, and
targeted pruning at the SQLite page cap. Widget tests cover saved-link
landing under the production retry policy and Retry beside a deleted
head. Both failed on the earlier head and passed with the fix.

## Try it

1. Open a populated thread from its reply count while connected and let
its replies load. Copy its link.
2. Force-quit, turn on airplane mode and reopen from the channel reply
count and from the link. Confirm that the saved replies appear in the
existing thread timeline.
3. Scroll away from Latest, then reconnect with the thread still open.
Confirm the visible reply stays in place, the live count replaces the
saved label, and read state follows the live replies.

---------

Signed-off-by: Wes <wesb@block.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
2026-11-23 11:03:49 -07:00
klopez4212
874a5699ba Add inline emoji shortcode suggestions on mobile (#9882)
Show Unicode and community emoji in the mobile composer after a colon
and two shortcode characters. Tap a suggestion or press Tab or Enter to
replace the token at the cursor. Long labels truncate on one line.

Tested on iPhone Duo and with iOS and Android composer widget tests. The
final label truncation was validated locally.

---------

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
2026-11-23 17:07:50 +00:00
Wes
0d4fd74ad6 fix(mobile): offer linked identity import when only other backups exist (#9053)
A fresh phone signing into an account linked to identity A gets a
misleading identity-mismatch error when the account has only a backup
for identity B. The existing import option was offered only when the
entire backup list was empty.

Offer the same import option whenever the linked identity has no listed
backup. Import still rejects a different key, requires the existing
backup-consent step, and prohibits creating a replacement identity. This
fallback does not change account bindings or automatically recover a
private key that was never backed up.

Updated against main `6dbd159676908806109f23d1964159d96a35760a`,
preserving the consent flow added since the original PR.

Validation:
- Both focused files passed with public Builderlab onboarding enabled:
67 tests. The journey covers empty and unrelated backups, wrong-key
rejection, and matching-key import after “Back up and continue.”
- In an isolated source tree with separate Git metadata and build
output, restoring the old production condition failed the
unrelated-backup journey (`blocked` instead of `setupIdentity`).
Restoring the fix passed all 42 journeys; restored source hashes match
the PR.
- Wes exercised the original preview's transition to the import screen
on November 4. This conflict repair preserves that production change; no
new device run was performed. That native evidence covers the screen
transition, not a completed real-account key import.
- Required pre-push checks passed, including mobile formatting/analysis,
the hook's mobile and crypto test suites, and file-size checks. [GitHub
CI passed](https://github.com/block/buzz/actions/runs/45211217031) on
`14e45a26e9873e75846e9a052f70bffd13139f6d`, including public-build tests
and the Android build. The conflict/consent review finding is addressed
in this revision.

Existing-user backup enrollment and automatic fresh-device recovery are
separate from this narrowly scoped fallback fix.

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
2026-11-23 09:50:12 -07:00
Tom Brow
2e3bebe9b6 feat(mobile): enroll Android devices for push (#9811)
## Summary

Ticket 7 of the [Android push
plan](https://github.com/block/buzz/blob/main/PLANS/ANDROID_PUSH.md).
Android phones can now enroll with the push gateway and publish a relay
lease, through the same shared push layer iOS uses. The wake handling
side is ticket 6, [#9804 Android push wake
handling](https://github.com/block/buzz/pull/9804).

- The phone gets an FCM token, then generates a sign-only P-256 Keystore
key whose attestation challenge is the SHA-256 of the enrollment
transcript. The chain goes to the gateway at enrollment. Every later
installation call (delegate, rotate endpoint, revoke delegation, revoke
installation) is signed with that key over the transcript bytes the
gateway builds.
- A rotated FCM token rotates the endpoint. Signing out revokes the
delegation and the installation. The first enrollment waits a short
random time.
- Android 13+ asks for the notification permission at the same point iOS
does. Declining keeps the app working.
- A phone that cannot attest (no hardware attestation, unlocked
bootloader, unlisted boot key) keeps working, and Settings says push is
unavailable on this phone.
- The relay lease keeps the fixed `transport` value iOS sends.
- Firebase config is the same build-time setting [#9804 Android push
wake handling](https://github.com/block/buzz/pull/9804) adds: four
`BUZZ_FIREBASE_*` environment variables become the string resources
Firebase reads. Nothing is committed, and builds without them still work
(push reports unavailable). The Gradle hunks (permission, config block,
`firebase-messaging` dependency) are copied from that PR verbatim so the
two merge cleanly, including its `lifecycle-process` line, which this PR
does not use.
- The token and permission calls use their own `buzz/push_registration`
channel, because Android's notification-open handler from that PR
already owns `buzz/push` and a channel has one native handler.
- The gateway gets an `enroll_android` transcript vector so Dart and
Rust agree on the exact bytes.

Enrollment state is journaled before each network attempt, so a lost
response resumes with byte-identical requests instead of leaving an
orphaned installation.

### Related issue

None found. Builds on [#9560 enroll Android
installations](https://github.com/block/buzz/pull/9560) and [#9562
verify Key Attestation](https://github.com/block/buzz/pull/9562).

### Validation

Journey tests cover first enrollment, a second relay, reuse and renewal,
lost responses, token rotation, an installation the gateway dropped, a
lost Keystore key, a phone that cannot attest, and sign-out revocation,
against a fake gateway that keeps the real gateway's semantics.
Transcripts replay the shared vectors byte for byte. A settings journey
checks the Notifications row and the unavailable row on Android, and a
resume table checks the FCM token refresh: it runs while the relay
reconnects, but not when push is off or the relay doesn't offer push.

On a physical Pixel 9a (debug build, a local test gateway on a local
Postgres, reached over `adb reverse`), the real Keystore key and
hardware attestation chain enrolled and delegated, and the gateway
accepted the attestation. The same session then ran: a signed delivery
authorized against the delegation, endpoint rotation and re-delegation
at the next epoch, rotating back, delegation revocation, installation
revocation, and re-enrolling the same FCM token afterwards.

The notification prompt appears when registration starts, before the
token is fetched:

<img
src="https://github.com/user-attachments/assets/2aed92fe-20c1-4658-b990-51c3f3c96120"
width="270" alt="Android notification permission prompt">

Not validated on the device: the FCM wake itself (the local gateway has
no credentials to call FCM, so the delivery was authorized and then
failed at the FCM hop), lease publication to a relay, and the in-app
unavailable row, which only the widget tests exercise. A relay-backed
run needs a signed-in test community on the phone.

### Settings while turning off

Turning notifications off sends a relay tombstone. Until the relay
accepts it, the row now says so, on both platforms. An Android build
without a gateway also keeps a saved opt-in visible so it can still be
turned off; once off, the row goes away. These are rendered from the
Settings journey test.

| | Before | After |
|---|---|---|
| Android build without a gateway, saved opt-in | <img
src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--01-before-config-less.png"
width="270" alt="Before: no Notifications row"> | <img
src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--02-after-config-less.png"
width="270" alt="After: Notifications row with the switch on"> |
| After turning off, relay has not accepted yet | <img
src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--03-before-turning-off.png"
width="270" alt="Before: plain off switch"> | <img
src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--04-after-turning-off.png"
width="270" alt="After: Turning off. Notifications may continue until
this finishes."> |

### Regressions

- iOS enrollment is unchanged: the shared bridge only branches to the
Dart authority on Android. iOS gains the pending opt-out subtitle, and
its opt-out now also tombstones after a gateway change using the saved
lease id.
- The Android app gains the `firebase-messaging` dependency and a
`POST_NOTIFICATIONS` permission. Backups exclude the push preferences
file.



### Known limits

- An FCM token rotation while the app is running is picked up on the
next resume or launch, because the wake service owns the single
messaging service. It could call into the registration plugin once both
Android push PRs merge.
- After an endpoint rotation, only the active community's lease is
republished. Other enabled communities' grants are void until each is
opened, the same way their leases lapse at grant expiry today.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 09:35:56 -07:00
Tom Brow
42dc2a8c58 feat(mobile): add screen breadcrumbs to diagnostic reports (#9823)
feat(mobile): add screen breadcrumbs to diagnostic reports
Adds screen breadcrumbs to mobile diagnostic reports, so a hang or error
report shows which screens the person was on before it happened. Today
the only breadcrumbs are foreground and background changes.

## Changes

- **Observers:** one `DiagnosticScreenTrail` is shared by an observer on
the root navigator and one on each conversation pane's nested navigator,
where channels, threads, search and activity open. A breadcrumb is left
on push, replace, and when a page is shown again after a pop, a frame
later and only for the page that ends up visible.
- **The screen the person is on:** a route that hosts a pane with a page
open past its first (a phone conversation over the channel list, or a
wide conversation beside it) is named by that page. So closing a
full-screen cover, such as a huddle, over an open channel records
`channel`, not `channelList`.
- **No repeats:** a screen equal to the last one is skipped. A pane host
and its pane's empty first page both name the host, and wide Settings
sections all show Settings, so these leave one crumb. The empty first
page still gives Home its crumb after sign-in.
- **Names come from a fixed list owned by the app:**
`lib/diagnostic_screens.dart` maps page widgets to names such as
`channelList`, `channel`, `thread`, `settings` or `addCommunity`, and
reaches the observers through `diagnosticScreenClassifierProvider`,
which the root scope overrides. Any other page is `other`. Route
settings and page content are never read, so no channel name, ID or text
can reach a breadcrumb.
- **Dialogs, sheets and menus are skipped:** popup routes leave nothing,
and the Duo channel sheet, which is a page route, opts out with
`DiagnosticSheetRoute`.
- **Filter:** adds a `navigation` category to the breadcrumb list. A
navigation breadcrumb leaves with only its screen name, and it is
dropped if that name isn't on the list.
- **No destination:** a build without a reporting destination does
nothing; the observers don't even inspect routes.
- **Spec:** the breadcrumb list, user story 7, and the out-of-scope line
about behavior data.

## Regressions

- **Architecture:** the screen list lives with the app, so `shared/`
gains no imports from features. The shared conversation pane's import
closure is unchanged from main.
- **Performance:** the route walk costs well under a millisecond per
navigation (28 to 155 µs measured, against 58 to 143 ms for the push
frame). Rebuild counts are unchanged with reporting on and off, and
nothing new goes over the network.
- **Confined to reporting builds:** in a build without a destination the
observers return before touching a route.

## Validation

New tests in
[`diagnostic_navigation_test.dart`](https://github.com/block/buzz/blob/tomb/mobile-diag-screen-breadcrumbs/mobile/test/shared/diagnostics/diagnostic_navigation_test.dart):
- the app's list, including `addCommunity` for adding a community and an
unlisted page;
- a root journey: a route whose settings carry an ID records only the
plain name, a dialog and a sheet route leave nothing, and two pops at
once leave only where they end;
- a phone journey with the real pane: Home once, channel, thread and
back, a cover closing back onto the open channel, closing the channel,
and a page with its own pane named once;
- a wide Settings pane where changing sections adds nothing;
- a build with no reporting destination.

Plus filter rows for nameless, unlisted and valid navigation
breadcrumbs.


Full-app run on an iOS simulator at 85a72de, signed in to a test
community: channel list, a channel and its details page, a message's
actions sheet, a thread and back, Search, Activity, Agents, Settings and
its status sheet, the identity-to-desktop confirmation, and the
community switcher's Add Community page. Every flow opened and closed
normally with no Flutter exceptions or error screens.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-22 09:10:13 -08:00
Tom Brow
d29c679066 fix(mobile): keep error names in send, upload and invite failure text (#9855)
## Summary

The compose bar's send error, the upload error and the invite page's
error removed the first `Exception: ` anywhere in an error's text, not
just a leading one. A `TimeoutException` read "Timeout..." and a wrapped
error lost part of its text.

They now share the helper Add Members already uses: only a plain
`Exception`'s leading prefix is removed, a relay rejection shows its
message verbatim, a lost acknowledgement drops the prefix only from its
cause, and named types such as `TimeoutException` keep their whole name.
The helper moves to `shared/relay/relay_error_text.dart`; Add Members
behaves as before.

## Validation

- New `relay_error_text_test.dart` covers a plain `Exception`, a
`TimeoutException`, a named error whose message contains `Exception: `,
a relay rejection and a lost acknowledgement. The `TimeoutException` and
named-error rows fail with the old `replaceFirst`.

No screenshots: the change only affects text after a failed send, upload
or invite, which can't be triggered on demand against a real relay.

Full-app run on an iOS simulator (signed in, healthy relay): cold start
and session restore, channel list, opening a channel, sending a message,
the attachment button, Settings, and background then foreground. All
passed with no new errors in the device log. The invite page isn't
offered to the test account.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-22 08:00:17 -08:00
Tom Brow
7382130948 feat(mobile): count networking events for diagnostics (#9810)
Implements the networking counts in docs/mobile-diagnostic-reporting.md:
every request through the shared HTTP client and every relay connection
event is counted, with backend (host), endpoint (from a fixed list),
outcome and kind of failure, plus a duration for requests and time to
connect.

## Changes

- **HTTP:** `newAppHttpClient` returns a counting wrapper, and the relay
HTTP query client wraps its own transport the same way. A failure status
is counted at its headers, a transport failure when it happens, and a
success once its body ends or its reader stops (duration is still time
to headers). A caller deadline noted with `noteHttpDeadline` makes a
request still waiting for headers or still reading its body a timeout;
the invite mint now notes its deadline too. Requests the app cancels are
not counted, and a throwing reporter never changes a request's result. A
request counts only for the member who started it, and is dropped if it
finishes while anyone else, or no one, is signed in. Only failed
requests leave a breadcrumb, so successes don't push useful entries out
of the SDK's buffer.
- **Backend names:** only the app's own hosts are named (relays this run
has used, the build's Builderlab origin and hosted relay domains, the
push gateway). Any other host, such as a remote image's, is counted as
`external`.
- **Relay:** the session counts connected (with time to connect),
disconnected or a failed attempt (once per attempt), reconnect attempts,
history queries (EOSE, CLOSED, timeout), publishes (OK true or false,
ack timeout) and live subscriptions closed by the relay. Queries and
publishes still unanswered when the socket drops are counted as
disconnected. A refused protected upgrade is counted before its renewal,
and the relay's authorization denial makes the following close an auth
refusal. Intentional disconnects (background pause, sign-out, community
switch) are not counted. The session's debug hooks moved to
`relay_session_test_hooks.dart` to stay under the file-size limit.
- **Install ID on counts:** metrics carry scope attributes but not scope
tags, so startup also sets `install.id` as an attribute, and the filter
allows it.
- **Spec:** marks counts as implemented and records that the destination
can filter counts by member, so the log-line fallback isn't needed.

### Endpoints

`relayConnection`, `relayReconnect`, `relayQuery`, `relayPublish`,
`relaySubscription`, `relayHttpQuery` (`/query`, `/count`,
`/profiles/search`), `relayInfo` (GET of a server's root),
`mediaDownload`, `mediaUpload`, `communityAdmission`,
`builderlabAccount`, `otherHttp`.

### Failure kinds

| Source | Kind |
|---|---|
| 401, 403 | `authRefused` |
| 408, abort before headers, timeouts | `timeout` |
| 429 | `rateLimited` |
| 5xx | `serverError` |
| Other 4xx | `clientError` (new) |
| No network | `offline` |
| Host unreachable | `unreachable` |
| TLS failure | `insecure` |
| Connection closed or reset (including ECONNRESET) | `disconnected` |
| Relay `rate-limited:` / `query timed out` | `rateLimited` / `timeout`
|
| Other relay refusal prefixes (`restricted:`, `auth-required:`,
`invalid:`, ...) | `relayRefused` |
| Anything else | `relayError` or `other` (new) |

## Validation

New tests:
- `counted_http_client_test.dart`: status and endpoint tables, transport
failure kinds (the error still reaches the caller and nothing is
reported as an error), a closed client, a throwing reporter, success
settled at body end, deadlines before headers and mid-body, requests
held across a member switch and a sign-out, and remote media hosts
counted as external.
- `relay_network_counts_test.dart`: connect, disconnect, reconnect, auth
refusal, queries, publishes, CLOSED, operations lost with the socket, a
refused protected upgrade before renewal, the relay's authorization
denial, and another member's session counting nothing.


Full-app run on an iOS simulator at b7c03702d (signed in, healthy
relay): cold start and session restore, channel list and avatars,
history scrolled back to a channel's start, image viewer, image and
video upload with thumbnail and playback, search, channel details, DMs,
sending, Settings, and backgrounding for about 30 s then a send after
resume. No new app errors, and no stream errors in the device log. Not
covered: invite creation (the test community offers no invite tools) and
a request that actually hits a deadline, which the unit tests above
cover.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-21 09:42:22 -08:00
Tom Brow
52cbc61131 fix(mobile): name identity-link mention pills from their key (#9841)
Follow-up to [#9699 mention
typing](https://github.com/block/buzz/pull/9699), fixing two identity
problems found in its review.

**Identity-link pills name the key they open.** An edit writes each
mention as an identity link, `[@Name](nostr:npub1…)`, and every message
from any client draws such a link as a pill. Mobile showed the label
written in the link, so `[@Wes](nostr:<mallory>)` drew an ordinary
`@Wes` pill that opened Mallory's profile, and two namesakes in an
edited message both read `Scout`. The pill now shows the name its key
resolves to in the channel (with the namesake qualifier and agent icon),
as buzz-app's `ProfileMention` already does. The written label shows
only when the key has no name on this device (no profile, directory or
roster name), never a compact npub in its place. This holds whether or
not the link's key is also tagged. A pill requests its key's profile
when uncached, so a written label gives way to the key's name once it
loads.

Edits carry no `p` tag, so an identity-link pill resolves its own key.
In channel, thread and forum rows the pill watches that one key's
channel label (with the namesake qualifier and agent icon) and requests
the key's profile when it builds, so only links that actually draw a
pill cost a lookup, whatever Markdown surrounds them. Inbox and search
previews draw identity links the same way, taking keys from the preview
pieces they render. These keys never feed the text bindings, so plain
`@Name` text still binds only through signed tags.

**Typed names group the way the text scan reads them.** The composer
grouped the roster by `toLowerCase` while the scan folds names with
`foldMentionLabel`. With members `Sam` and `ſam`, typing `@ſam` sent
Sam's `p` tag. Grouping, lookup and the send-time key qualifier now all
fold, so namesakes under folding fail as ambiguous, as other namesakes
already do.

**Linked lookups stay current and bounded.** Pills and preview rows
request their keys through the profile cache's revalidation path. A name
restored from the last launch is revalidated, so a renamed key's link
shows its current name. A lookup that fails while offline is retried
once the relay reconnects, including when the reconnect comes while that
lookup is still on the wire. A key the relay says has no profile is not
asked for again for five minutes, and the cache remembers at most 1,000
such keys per community. Previews keep tilde and quoted code fences
literal and read blockquotes as the full message does, and load only the
links on lines they draw. Editing a message folds historical names the
way the scan does, so a name two tagged people share under folding seeds
no chip. Rendering binds signed names by the same fold, so with signed
`Sam` and `ſam` a plain `@Sam` stays text instead of drawing Sam's pill.

Desktop (buzz-app) already names identity-link chips from the key and
needs no change.

### Validation

Rows add no per-message work: message bodies are no longer scanned for
links. Each drawn identity-link pill adds one label watch for its own
key.

Added tests:
- [Channel page journey
step](mobile/test/features/channels/channel_detail_page_test.dart): an
edited message linking `[@Wes]` to Mallory's key draws `Mallory`, and
two edited `Scout` namesakes draw distinct qualified labels, through the
real channel row.
- [Channel page journey
step](mobile/test/features/channels/channel_detail_page_test.dart): a
link to a key with no name here keeps its written label.
- [Preview identity
link](mobile/test/features/channels/message_content/preview_text_test.dart):
an inbox/search preview shows the key's resolved name, or the written
label when unknown.
- [Preview
keys](mobile/test/features/channels/message_content/preview_text_test.dart):
a preview loads only links it draws (not ones in code or past its line
limit), including labels with brackets.

Full-app run (iOS simulator, debug build, signed in to a test
community): posted a message with a spoofed identity link, a link to a
key with no profile here, and a link inside inline code. The spoofed
link drew the key's real name as a pill and opened that person's
profile; the unknown key kept its written label; the code span stayed
raw. The same message drew matching pills in search results and in the
thread view.
- [Channel row
loads](mobile/test/features/channels/channel_detail_page_test.dart): a
row requests profiles only for links it draws as pills, not ones in a
quoted code fence or an HTML comment.
- [Folded chip
qualifiers](mobile/test/features/channels/compose_bar_test/exact_mention_tests.dart):
picked `@Sam` and `@ſam` chips both carry their keys on send.
- [Ambiguous typed names
table](mobile/test/features/channels/compose_bar_test/exact_mention_tests.dart):
`Sam` and `ſam` in either roster order now refuse `@ſam` as ambiguous.

- [Restart and reconnect
journey](mobile/test/features/channels/channel_detail_page_test.dart): a
restored old name and an offline first lookup both resolve after the
relay reconnects, on the same mounted pills, and a key with no profile
is not requested again.
- [Preview
fences](mobile/test/features/channels/message_content/preview_text_test.dart):
tilde and quoted fences keep links and Markdown literal and load no
keys.
- [Overtaken
lookup](mobile/test/shared/profile/user_cache_provider_test.dart): a
reconnect during a link's failing lookup asks once more after it
settles.
- [Folded signed
names](mobile/test/features/channels/message_content_exact_mentions_test.dart):
signed `Sam` and `ſam` in either tag order leave `@Sam` as text in the
message and its preview.
- [Folded edit
chips](mobile/test/features/channels/message_edit_sheet_test.dart):
`Sam` and `ſam` tagged in either order open as text, with no chip.
- [Non-member
labels](mobile/test/shared/identity_names/identity_names_test.dart): a
non-member labels the same with or without the roster shortcut,
including names shaped like qualifiers.

### Regressions

- **Performance:** rows do no new scanning; each drawn identity-link
pill adds one label watch. A non-member whose name can't collide no
longer re-resolves the whole roster.
- **Mention semantics:** unchanged for tagged mentions and plain text.
Only identity-link pills change, from the written label to the key's
resolved name.
- **Composer:** names that differ only under Unicode folding (`ſ`/`s`,
`µ`/`μ`, final `ς`/`σ`) are now one name when matching typed text, so a
typed one between two such members asks for a pick instead of silently
choosing one. Picked chips are unaffected.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz>
2026-11-20 17:21:54 -08:00
Tom Brow
8a3912f151 fix(mobile): fence notification replies by the clock and settle ones whose community is gone (#9668)
Follow-up to #9439 (iOS notification reply), which merged before these
non-blocking review points landed.

- **Publish fence checks the clock.** `mayPublish` now compares
`DateTime.now()` with the publish deadline as well as the timer flag,
before and after writing the publishing mark. After a suspension, a
pending lookup can finish before the overdue timer callback runs;
without the clock check the reply could publish past its deadline, after
iOS already showed "Reply not sent".
- **A recovered reply whose community is gone settles.** If the
community was removed, or the user signed out, before the relaunch,
`_keepDraft` used to throw, so the reply stayed in the native journal
(with its text in `UserDefaults`) and was retried on every launch. It
now keeps no draft and the reply is settled as not sent.
- **Doc fix:** `SendMessage`'s `mayPublish` is asked after signing and
after the optimistic local message is shown; the doc now says so.
- **Test fix:** the resume test asserts the EVENT frame reached the
original socket before `onAppResumed`, so the injected OK can't pass it
on its own.

### Regressions

None expected. The clock check can only refuse a publish the timer would
also refuse moments later. A recovered reply for a missing community now
drops its text instead of keeping it forever in a journal no launch can
drain; there is no community left to show it in.

### Validation

-
[notification_reply_test.dart](https://github.com/block/buzz/blob/notification-reply-fence-followup/mobile/test/features/channels/notification_reply_test.dart):
the recovered reply for a missing community now expects to be settled.
-
[relay_reconnect_resume_test.dart](https://github.com/block/buzz/blob/notification-reply-fence-followup/mobile/test/shared/relay/relay_reconnect_resume_test.dart):
asserts the EVENT frame before resume.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 15:25:31 -08:00
Wes
f9b18c7f3a Cache recently opened mobile channel pages (#9809)
## What changed

Previously opened channels can show their newest saved page after a cold
launch, including offline. The same timeline provider combines the saved
page with live edits, deletions, and optimistic sends. When the relay
has loaded history, its timeline takes over and older-page navigation
becomes available. The chat labels saved messages until relay history
takes over. If a connected refresh fails, the chat offers Retry and
keeps the saved-message label visible during the retry.

- Keep verified relay events in a disposable, app-private SQLite cache
per community and signing identity on iOS and Android. Close SQLite
connections after each operation.
- Cap the main file at 45 MiB to leave room for a rollback journal
within the 100 MB per-community limit. Evict least-recently opened pages
and retry once when SQLite reaches the physical limit.
- Omit an oversized relay page as a whole so the cache cannot show a
message without an edit or deletion from the same response. Keep
readable pages available when only the recency write fails.
- Purge on leave, deletion, explicit channel access refusal, and
writer-confirmed loss of a known membership. Expired sessions leave the
cache intact. SQLite secure deletion clears removed payloads after
commit. A durable marker covers interrupted purges. Account switches and
removal retire old saves.
- Keep message-link lookups valid across the first connection. An access
refusal still discards a late result.
- After a confirmed leave or delete, record a durable cache purge before
refreshing the channel list. Disk cleanup runs in the background and the
refresh skips redundant writer confirmation for that channel.
- For joined, unarchived channels, remove stale saved rows on
channel-tagged deletions or edits the app receives while the
conversation is closed. Reuse deletions from the existing reconnect
catch-up.
- Give an already-connected relay one 250 ms head start before reading
the saved page. Offline opens start the read immediately.

## Screenshots and timing

[iPhone 17e simulator
captures](https://github.com/block/buzz/pull/9809#issuecomment-7050704433)
show the same seeded chat before the cache, with saved messages while
offline, and after the relay returns. In the debug capture run, the
baseline `9c0bcd623` showed no messages within 8 seconds. The updated
build `2cb28eda` showed the target saved message **752 ms** after the
tap.

For a first online open on the same simulator, the baseline and the
instrumented `2cb28eda` build took **449 ms** and **441 ms** median from
tap to target message. Each build had four measured opens after one
warm-up. The ranges were 437–481 ms and 414–447 ms.

In the earlier paired debug simulator experiment on `6e113d83`, the 250
ms preview delay reduced median first online open from **507 ms to 452
ms** across 15 measured opens per build. In the delay build, seeded
offline opens took **488–557 ms** across the two channel medians, and
reopens in the same app session took **174–245 ms**. All 20 offline
opens and reopens showed the target message.

## Verification

- The mobile pre-push gate and file-size check passed for `6650ebad`.
Regression tests cover oversized pages, session expiry versus channel
revocation, live mutations during preview, paging after relay history
loads, writer-confirmed membership loss, closed-chat edits and
deletions, the saved-message label across Retry and history takeover,
links held across first connect, and interrupted or overlapping purges.
- The host SQLite probe interrupted eviction, relay-key rotation, and a
synthetic table rewrite. All three reopened with a clean integrity
check. The largest observed database and journal footprint was 93.84 MB.
- Physical iPhone suspension, airplane-mode reopen, and profile-mode
timing are pending.

## Try it

1. While connected, open a populated channel and let its newest page
save.
2. Force-quit, turn on airplane mode, and reopen the same channel. The
saved page should appear.
3. Reconnect. The relay's newest page should take over without
duplicating messages.

A saved page can still show stale rows while the phone stays offline,
for a live edit missed while the app was stopped, for an archived or
unjoined public channel, or for a NIP-09 deletion without a channel tag.
Reconnect catch-up covers the deletions returned by its bounded unread
query. A direct online open refreshes the page. Offline thread replies
are separate follow-up work.

---------

Signed-off-by: Wes <wesb@block.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz>
Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 16:03:27 -07:00
Matt Toohey
2074adaa85 fix(mobile): bring @mention typing in line with buzz-app (#9699)
## Summary

The mobile composer's @mention typing was an older port of the mention
rules that [block/buzz-app](https://github.com/block/buzz-app) follows
(`src/bundled/mentions/README.md` there), and it trailed buzz-app in
nine places. Most of them came from one difference: mobile tied a picked
person to the `@Label` text and looked for that text again at send time,
while buzz-app keeps the recipient on an atomic chip. Several of the
gaps meant a picked person was silently not notified.

This PR fixes all nine. Every change is in `mobile/`; no relay, CLI or
desktop code is touched, and the event payloads mobile writes keep the
same shape.

### Commits

| Commit | Fixes | What it changes |
|---|---|---|
| 9152e91fe | 1, 2 | Picked people are atomic chips, as agents already
were. The recipient comes from the chips, so a pick after `(`, `[` or
`{` notifies. Backspace removes the trailing space, then the whole chip;
arrows step over a chip. |
| 2cbdabdae | 3, 4 | A chip is bound to its recipient by its position in
the draft and keeps it through punctuation, apostrophes, hyphens and
slashes. Namesake chips read `@Sam · a1b2`, and the draft text never
holds a public key. |
| c4d3f2072 | 5 | A chip's `@` never opens a query, so prose typed after
a pick sends no directory searches. A query that found nobody refutes
every longer query that continues it. |
| 4e4ac3efd | 6 | Name matching folds accents, full-width letters and
ligatures, and breaks words on hyphens and apostrophes. The vendored
contract fixture moves from version 1 to version 4, and all 125 cases
pass. |
| 38e8f2e1e | 7 | Closing punctuation (`. , ! ? ; :`, `)`, `]`, `}` and
closing quotes) selects an exact, unique name as Space does, and the
character stays after the chip. |
| e008151c6 | 8 | The chooser is shown only while the text field has
focus. The query and its rows are kept while hidden, so refocusing shows
the same rows without a new search. |
| 199606969 | 9 | The edit sheet mounts the composer's chooser through a
shared hook. A pick inserts a chip, and the saved edit adds no `p` tag.
|
| a1e4d69fa | 3 | The message renderer ends a mention where the composer
does, so a sent `@Honey's report` draws Honey's pill with the suffix as
text. |
| bf34af139 | 2 | iOS reports one Backspace as two editing updates
(select the character, then delete the selection). The controller
recognises that pair and removes the whole chip and its binding. |

### How to read the videos

Each video has three columns that follow the same numbered steps with
the same people and the same typed text: mobile before this PR on the
left, mobile on this branch in the middle, and buzz-app on the right.
The bar across the top names the current step, and a column that
finishes a step early holds its frame until the others catch up.

The dark panel on each phone is a readout added for the recording. Its
`p tags (notified)` line shows who a sent message would notify, and
`directory searches sent` counts requests to the directory. The readout
under the buzz-app composer shows the same facts.

### 1. A mention picked after a bracket keeps its recipient

`see (@Honey) please` went out with nobody notified, because the
send-time scan did not accept the brackets the chooser did. The
recipient now comes from the chip, and the typed-name fallback accepts
`(`, `[` and `{` too.


https://github.com/user-attachments/assets/b1f1c76b-b991-4f90-9079-a435c4475c2b

### 2. People mentions are atomic chips

A second Backspace used to leave plain `@Hone` (and `@Scou` for the
agent), which sent with no recipient. Now the first Backspace removes
the trailing space and the second removes the whole chip, and the arrow
keys step over a chip as one unit.


https://github.com/user-attachments/assets/a198656c-d735-46a7-a954-9e0aa4af7dc3

### 3. A suffix after a mention keeps the recipient

`@Honey's report` and `@Honey-bot is back` notified nobody. A chip now
survives an apostrophe (straight or curly), a hyphen, a slash or
punctuation typed against it, and the sent bubble draws the pill with
the suffix as text. Only a letter, mark, digit or underscore typed
against the chip unbinds it.


https://github.com/user-attachments/assets/c481110d-1633-4c01-9810-a8d750ce2ae2

### 4. No raw public key in the composer

Picking two people with the same name filled the draft with two
64-character keys. Each pick is now a chip with a short label, the draft
text stays `@Honey`, and each namesake gets their own `p` tag. The key
suffixes on the labels differ between the apps only because each
recording generated its own keys.


https://github.com/user-attachments/assets/4f56cddd-a96f-43cb-820b-511eb965a77b

### 5. No directory search while typing prose

Every character of a sentence typed after a pick was sent to the
directory as a name search: 20 searches in this clip. The count now
stays at 1, the same as buzz-app. A short query with no local match
still searches, so a person outside the channel is still found.


https://github.com/user-attachments/assets/3575b2cf-e3a6-42f1-9779-6e1401f00dfc

### 6. Accent folding and contract fixture version 4

`@jose` could not find José María, so `@jose maria` went out as plain
text. Names now fold accents, the row stays listed, and the pick is a
chip that notifies José María. The vendored fixture is version 4 of the
shared contract, copied unchanged, with no case skipped.


https://github.com/user-attachments/assets/362f6b4b-a09c-4f69-910e-8903408be77e

### 7. Closing punctuation selects an exact name

A comma typed straight after `@Honey` or `@Outside Person` joined the
query and closed the chooser; for a person outside the channel the
message went out with no recipient and no prompt. The comma now selects
the exact name, and Send shows the outside-channel prompt, where Invite
adds the person and sends with their `p` tag.


https://github.com/user-attachments/assets/b43a0663-489f-4ae3-ae36-7a2a92443f9e

### 8. The chooser follows the field's focus

Dragging the keyboard away collapsed the composer but left the chooser
row floating above it. The chooser now hides when the field loses focus
and returns with the same rows when focus comes back. Step 1 of the
mobile columns is sped up three times, because the on-screen keyboard is
slow to drive in the simulator.


https://github.com/user-attachments/assets/2ce0093d-03d0-4792-9b05-fb28980830fc

### 9. The chooser works in the edit sheet

The edit sheet was a plain text field with no chooser. It now uses the
composer's chooser with the same rules, and existing mentions open as
chips. The saved edit adds no `p` tag, matching buzz-app's rule that an
edit notifies nobody.


https://github.com/user-attachments/assets/e54d5620-ae2d-49b5-8cce-99536b8d81db

### Known gaps left for follow-up

- **Typed, unpicked names.** Mobile still notifies a typed name that
equals exactly one member and refuses to send an ambiguous one. buzz-app
does not do either, and the shared contract has not settled which is
right.
- **Directory-only names selected before the search finishes.** Space or
closing punctuation selects a directory-only name as soon as it is in
the ranked rows. buzz-app waits until that query's search has finished.
This predates the PR for Space and now also applies to punctuation.
- **Undo does not restore a chip.** After a letter typed against a chip
unbinds it, Undo restores the text but not the chip. iOS shake-to-undo
also bypasses the new undo detection.
- **Edits drop existing tags.** The timeline reads mention tags from the
edit event, so editing a message that already tagged someone still loses
that pill. Carrying the original tags through an edit is a separate
change.
- **`_@Name_` italics.** `_` now counts as a name character, as in
buzz-app, so `_@Honey_` no longer draws a pill.

### Related issue

N/A. None found; #9008 made the relay's name search accent-insensitive,
and fix 6 does the same for matching on the device.

### Testing

- `dart format`, `flutter analyze`, `just file-size-check` and the full
mobile `flutter test` suite passed on every commit. Two timing-sensitive
tests unrelated to mentions (relay socket liveness, community snapshot
cleanup) each failed once under full-suite load and passed solo.
- Each fix has a widget-test journey through the real composer, chooser
and send path, and each was shown to fail with its fix removed. The
shared contract fixture runs in full.
- The videos are harness recordings on an iPhone 17 simulator (iOS
27.2): the real channel page, composer, chooser, edit sheet and send
path on an in-memory relay, not the app against a live community. The
buzz-app column is a headless WebKit recording of buzz-app's fixture
pages.
- Android and physical devices were not exercised.
- The branch was pushed with `--no-verify`, so the pre-push lanes did
not run locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Matt Toohey <contact@matttoohey.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-20 21:12:49 +00:00
Tom Brow
0636d21479 feat(mobile): report push gateway replies the app cannot read (#9806)
Reports push gateway replies the app cannot read, the last explicit
error report from [the diagnostic reporting
spec](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md)
still missing.

The gateway is called from native code (`BuzzDevPushEnrollmentDriver`),
and Dart used to see every native failure as one code. Native now fails
with its own `gateway_response_invalid` code when a reply does not match
the gateway's protocol (bad JSON, a 2xx status other than the one the
gateway sends for that call, or a challenge, installation or delegation
reply with missing or invalid fields), carrying no text from the reply.
Dart reports that as a push gateway response error and rethrows as
before.

- **Not reported:** status mismatches (including 4xx and 5xx), timeouts
and offline failures, which the spec counts as routine; local-state
failures such as an App Attest key mismatch; and a plausible challenge
that has already expired by the device's clock, since a phone whose
clock runs fast would otherwise report on every retry. An expiry no real
challenge could have (zero, negative or a relative TTL) is still
reported. Local enrollment logs keep the fixed name of the failing
route.
- **Attribution:** the report goes through the signing member, so an
enrollment that finishes after a community switch names no one else.

## Validation

- `push_bridge_test.dart`: an unreadable reply is reported once and
enrollment still fails; routine native codes report nothing.
- `BuzzDevPushEnrollmentDriverTests`: bad JSON and an unexpected 2xx
fail as an unreadable reply; a 503 stays a status mismatch; a plausible
but expired challenge is not an unreadable reply, while an expiry of 0,
-1 or 300 is.
- `notification_toggle_test.dart`: an unreadable reply during the
notification journey files one report while the member matches and none
after it changes.

Full-app run on an iPhone 17 Pro simulator at 6de2998: startup and
session restore, channel list, opening a channel, sending, Settings and
the notifications toggle, and background and foreground. With the
gateway pointed at a local server that answers 200 with HTML, enrollment
failed with `gateway_response_invalid`, retries backed off, and the app
stayed usable. Not covered: receiving a real push.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 12:51:49 -08:00
Tom Brow
ec1b786ef0 fix(mobile): diagnostic reporting follow-ups (#9808)
Follow-ups to the mobile diagnostic reporting work in
docs/mobile-diagnostic-reporting.md.

## Changes

- **Install ID repair:** if the install ID file holds something that
isn't text, the app now replaces it with a new ID, as it already does
for an empty file. Before, every report went out without an install ID.
A read that fails (for example, no file descriptor free) still keeps the
file, so a passing error never replaces a good ID.
- **Clock-window refusals are not reported as errors:** the spec treats
relay refusals for a timestamp outside the relay's clock window as
expected (counting them is still pending). The app only recognized one
of the relay's wordings ("timestamp too far from server time"), so
refusals for canvas events, relay-admin commands, leave requests and
observer frames were reported as invalid requests. The five wordings are
matched from the start of the reason, so unrelated `invalid:` reasons
that mention a timestamp, such as the feedback timestamp overflow or one
that echoes a value, are still reported.
- **Diagnostics card:** rows get subtitles, and the divider indent
matches the neighbouring Settings cards.
- **Comments:** explain why push stop gates its current-identity request
on the community key, and correct a test comment about who drops a
repeated error object.

## Validation

New tests cover:
- member attribution on relay sessions, including a missing key and an
answer that arrives after the member changed;
- push stop reports while signed out;
- reporter wiring for hosted admission and the self-hosted probe;
- frames the socket can't decode;
- a table of relay refusal reasons, each either reported or not, for
both `OK` and `CLOSED`;
- an install ID file whose reads fail keeps its ID.

Full-app run on an iPhone 17 Pro simulator at 61b04f6: startup, channel
list, sending and reacting, Settings, the Diagnostics card and Send test
report, and install ID repair (a file that isn't valid UTF-8 and an
empty file each got a new ID that stayed the same on the next launch).
Not covered: a relay clock-window refusal, which the live relay would
not produce.

## Diagnostics card

| Before | After |
| --- | --- |
| ![Diagnostics card
before](https://github.com/user-attachments/assets/b8fa7100-3efd-4c36-ac4d-006d487f4902)
| ![Diagnostics card after, with row
subtitles](https://github.com/user-attachments/assets/9ca7e95b-6061-4efa-b476-d7bb4c113a9b)
|

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 12:49:57 -08:00
klopez4212
9c0bcd6239 Align Duo chat headers, inset Home selections, and fix received photo-stack swipes (#9795)
- In unfolded Duo portrait, place the live chat avatar and name together
beside Back. Align the Messages and Activity headers with the status
controls and keep the filters full width.
- Center the stacked avatar and chat title over the sticky date with the
Duo rail on either side.
- Give Home selections rounder corners and a shared 12-point outer
gutter for channels, DMs, and Solo chats. Preserve icon and label
alignment.
- Mirror drag distance and flick velocity for received photo stacks so a
rightward swipe advances the stack.

The combined release preview was installed and checked on a physical
Duo. Widget tests cover the portrait header geometry, filter width, and
return to landscape.

### Portrait layout references

Cropped headers from the earlier Duo preview used as the design
reference.

![Messages header in unfolded
portrait](https://github.com/user-attachments/assets/93fa0134-81c8-406e-90a9-9d3711b0bdc0)

![Left-aligned chat chip in unfolded
portrait](https://github.com/user-attachments/assets/e79a9337-7d31-4871-96c3-9cb0300437cf)

### Simulator snapshots

The fixtures use sample content and a 76-point right rail inset.

![Stacked avatar and title aligned with the sticky
date](https://github.com/user-attachments/assets/1b9b409d-5fa6-4f79-8444-9927e2bee59e)

![Received photo stack during a rightward
swipe](https://github.com/user-attachments/assets/383be530-31df-4238-b6e4-62ecc2f299e0)

---------

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz>
2026-11-20 18:09:43 +00:00
klopez4212
14e5ea7cc4 Mobile: refine section filters and ordering in Messages (#9796)
## Summary

Give Messages sections a common options sheet for sorting, filtering and
ordering. Active sections let people choose a time window. Channel and
DM sections can reveal filtered rows in place with **Show more** and
collapse them with **Show fewer**. Reordering saves a device-local order
for the current account and community.

Failed activity lookups keep affected channels visible. The recovery
toast offers Retry and dismisses when activity loads. On iOS the sheet
dims the Messages header along with the list.

### Related work

#9707 explores a count-based disclosure. This change uses the section’s
unread or activity filter.

### iOS snapshots

| Section options with an active filter | Reorder sections |
| --- | --- |
| ![Section options with a 30-day activity
window](https://github.com/user-attachments/assets/4b0fd306-f7ba-4466-aeca-18627bc05c57)
| ![Reorder sheet with draggable Solo, project, Team and Direct messages
rows](https://github.com/user-attachments/assets/3a3f1429-6334-4c8e-a535-630ae860376c)
|

### Rename a section

Tap the emoji beside the name to open the picker. Set saves both fields,
including an emoji-only change.

![Rename section with a new emoji
selected](https://github.com/user-attachments/assets/840bf926-f29f-435e-87de-2470d32ac64c)

### Activity recovery and section order

Unfiled Solo chats support local **Show more** and **Show fewer**,
including offline. Failed activity lookups retry automatically up to
three times with jittered backoff while Messages is visible and
connected. **Retry** stays available after that budget is exhausted. The
notice dismisses on recovery.

Reorder supports drag handles and keyboard arrow keys. Saving preserves
the position of an empty Starred section and checks for a newer order.
Each signing identity has its own saved order per relay.

### Testing

Exercised filtering, reorder and dismissal in the iOS simulator. The
preview was also tested on iPhone Air. At `6135e314f3`, Flutter analysis
and the full pre-push mobile checks passed (5,613 tests passed, 71
skipped). Widget regressions cover offline Solo disclosure, retry
exhaustion, route visibility, keyboard reorder, large text, and editor
cancellation.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-20 17:20:08 +00:00
Tom Brow
e2bbd8430c feat(mobile): report explicit diagnostic errors (#9673)
Step one of [mobile diagnostic
reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md),
second piece: the explicit error reports the spec lists, through the
reporter added in [#9613 diagnostic reporting
module](https://github.com/block/buzz/pull/9613). A build without a
destination (every build from this repository alone) still reports
nothing.

### What's in it

Each report carries its `operation` tag, the error's type and stack
trace, and no error text (the filter replaces it).

- **Event subscriber (`eventSubscriber`):** a subscriber that throws
while the relay session delivers a buffered batch is reported, and the
rest of the batch is still delivered. In a build without a destination
the error still surfaces as uncaught, so it fails the test that hit it
and prints in development, as before. Before, one throw dropped the rest
of the batch, and those events never came back because their delivery
keys were already recorded.
- **Relay frames (`relayFrame`):** a frame the socket can't decode, or
whose body isn't a JSON array, is reported instead of silently skipped.
- **Relay queries (`relayQuery`):** an HTTP query body that can't be
decoded, including the read-state snapshot.
- **Invalid-request rejections (`relayRejection`):** an `OK false` or
`CLOSED` whose reason starts with `invalid:`, reported as a fixed
`RelayInvalidRequest` with no relay text, including an `OK` with no
pending publish (a typing indicator, or a reply after a timeout).
Refusals the app handles as expected outcomes (an archived channel, an
Unarchive of a channel that is no longer archived, an open channel name
that is taken, an agent whose `policy:` refuses being added, a sole
owner's Leave refused as the last owner, a guest's Add Members refused
because only members can add people, an event whose timestamp is outside
the relay's window, so a wrong device clock does not report every
publish) are left out. The long-lived relay session, the short-lived
sockets (hosted admission, the self-hosted probe, one-shot publishes
such as agent registration and push tombstones) and the account
assertion requests made for a community's key (relay access and push
stop assertions) report frames and rejections the same way, except while
reports name a member other than the key they sign with. A removed or
inactive community's tombstone, or the probe of a community being
joined, then reports nothing rather than naming the wrong member. With
no member set (first run, or after the last community is removed) it
reports under the install identifier.
- **Account responses (`accountResponse`):** a Builderlab account
response that isn't a JSON object, or a 2xx exchange or `/v1/auth/me`
response missing its credential, subject or expiry. Non-2xx statuses are
expected outcomes and aren't reported.
- **Push gateway responses (`pushGatewayResponse`):** a malformed push
capability descriptor from the relay. A relay that leaves
`supported_extensions` out or sends none has no push and isn't reported,
and a fetch that finishes after a community switch has begun isn't
reported either, since it would name the next member. Push gateway
replies aren't reported yet.
- **Stored data (`storedData`):** a saved community list that can't be
read back.
- **Member on switch:** switching communities now looks the new member
up in storage, not in the provider's list, which can still be the
previous one while it reloads after sign-in. It reads storage before
tearing anything down, so a failed read leaves the switch unchanged and
retryable.
- **Filter:** also drops a report's additional data (`extra`). Nothing
sets it today.
- The spec's status line now says what is implemented.
- Event delivery moves from `relay_session.dart` into a part file,
unchanged apart from the subscriber guard, so the session stays under
its size limit.

### Regressions

None expected: each change only adds a report where an error was already
caught or skipped. The one behavior change is that a throwing event
subscriber no longer costs the rest of its batch.

### Validation

Added tests for each report site (relay session, socket frames, one-shot
publishes, read-state snapshot, closed-reason policy, account client,
push descriptor and capability provider, community storage), for the
relay session (member changed mid-request), one-shot sockets and
assertion requests reporting nothing while another member is set and
reporting with none set, for the member on switch and a switch whose
read fails then retries, and for the filter dropping additional data and
leaving a message-less event without one.

Full-app run on an iPhone 17 Pro simulator at b4f05ad (debug build, no
reporting destination): signed-in launch and channel list, scrolling
history in several channels, a thread, sending a message and a reaction,
search, switching communities and back, background and foreground with
live updates afterwards, and kill and relaunch with saved communities
restored. No regressions and no exceptions from the changed code.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 09:09:29 -08:00
Tom Brow
03d09e20e3 fix(mobile): keep the agent poster over a failed iOS player (#9693)
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-20 09:09:25 -08:00
klopez4212
d647c9fd98 Refine iOS composer and transcribe recordings into drafts (#9574)
Refine the iOS composer with 40-point glass controls, native attachment
menus, persistent emoji access, and selected-text formatting. The mic
now transcribes recordings on device into an editable, unsent draft;
Dictation has no five-minute recording cap or timer label, and its
waveform fills the space between the controls. Voice note remains
available in attachments with its five-minute cap. Unsupported devices
fail before recording, and audio is retained until the draft is durably
saved. Stopped dictation remains recoverable across editor teardown;
failed retention and cleanup can be retried. Recovered transcripts are
inserted only once across navigation or restart, preserving live exact
mention bindings.

Preserve selection handles over glass with animated avatars. Reduce the
conversation fade to 100 points above the keyboard and transition
continuously to 180 as the keyboard closes, without a first-frame jump
when opening; Home is unchanged.

Validation: 5,117 mobile tests and 27 crypto tests pass; analysis
passes. Prior native suite on iPhone 16/iOS 26.5: 119 pass, one
pre-existing expected failure, zero unexpected failures. Physical Air
preview approved; simulator selection/dragging and attachment flows
exercised. Fixed the native navigation test's timing race and a
community-cache cleanup test that checked a parent directory before its
asynchronous removal completed. Repository-wide `just ci` previously
stopped in unchanged `buzz-test-client` load-generator tests; new-head
hosted checks are pending.

Snapshots: production composer in an iPhone Air simulator fixture with
fictional conversation text; Photos snapshot retained from the
attachment preview.

| Composer | Attachments | Photos |
| --- | --- | --- |
| ![Keyboard-up
composer](https://github.com/user-attachments/assets/b7c8f0a4-25f8-4ca2-b8ae-11e18655e64a)
| ![Native attachment
menu](https://github.com/user-attachments/assets/5eaf5259-8e04-4da7-93f5-1b2eccab3c3c)
|
![Photos](https://github.com/user-attachments/assets/a6216b7d-5eaf-482c-b587-6052825b88fc)
|

---------

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
2026-11-20 16:35:20 +00:00
Tom Brow
34c8f5c7a5 feat(mobile): add Dart notification body formatter (#9556)
Adds a pure Dart function, `notificationBody`, that turns a message's
Markdown content into the plain-text notification body defined by [ADR
0002](https://github.com/block/buzz/blob/main/docs/adr/0002-notification-message-text.md).
It is a port of the Swift `BuzzPushNotificationResolver.previewBody` in
`BuzzPushKit`, which today is the only implementation.

Android notifications will be built from the app's Dart code, as in the
[Android push design](https://github.com/block/buzz/pull/9555), and will
reuse this function so the body reads the same on both platforms.
Nothing calls it yet and the Swift side is unchanged.

Notes on the port:

- The cap stays at 256 UTF-16 code units, the same as iOS (the fixtures
set `maxLength` to 256).
- Dart's regex engine differs from the ICU one the Swift code uses
(`\s`, `.` and `$`), so the patterns spell those out to keep identical
results. Trimming also matches Swift's `whitespacesAndNewlines`, which
trims U+200B and keeps U+FEFF, where Dart's `trim` does the opposite for
both.
- Truncation counts whole characters (extended grapheme clusters) via
`package:characters`.

### Validation

- A table-driven test runs every case in
`test-fixtures/notification-body.json` (47 cases) and checks the
fixture's `maxLength` against the function's cap.
- Added tests: 8 rows in the shared fixture pin the ICU details the port
must match. U+000B and U+0085 beside a marker keep it, U+000B and U+000C
inside a run keep its markers, U+200B is trimmed at the edges and
doesn't count toward the cap, and U+FEFF at the edges is kept. The Swift
fixture test runs them too and passes them unchanged.
- Proved falsifiable: with code-span and fence handling disabled, 18
fixture cases fail; restored, all pass.
- `just mobile-install mobile-check mobile-test` passes.

### Regressions

None: new code that nothing calls yet. The Swift formatter is untouched.
Its fixture test now also runs the 8 new rows and passes them unchanged.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 00:40:40 -05:00
Matt Toohey
5e8fa368a4 fix(mobile): hand message action menu scrolling off to sheet dismissal (#9760)
## Summary

On mobile, the message action menu is a modal bottom sheet whose body
scrolls when the actions overflow (long menus, large text sizes). Before
this change, dragging down inside the body only scrolled or bounced the
content: the sheet itself could be pulled down only by its handle. Now a
downward drag in the body carries on into pulling the sheet down once
the content reaches its top, in the same touch, and the sheet can be
dismissed that way.

- **Handoff in both directions.** Drag updates are split between the
content and the existing modal route. Dragging down past the top of the
content moves the sheet; reversing without lifting restores the sheet
first and then scrolls the content again.
- **Release policy is the stock sheet's.** If the finger has displaced
the sheet at release, downward velocity strictly above 700 px/s closes
it; otherwise it closes when it has been pulled more than half its
height, and settles open if not. Where the gesture began, and whether it
scrolled content on the way to the top, does not matter.
- **Guards against accidental dismissal:**
  - a release with the sheet not displaced by the finger never closes;
- ballistic and programmatic scrolling cannot start a sheet drag, so a
content fling that reaches the top after the finger lifted stops there;
  - carried scroll momentum is not added to the release velocity;
- a slow return across the top that pulls the sheet less than half way
settles open;
  - an upward release velocity keeps the sheet open.
- **Unchanged:** handle and barrier behaviour, reactions, cancellation
recovery, reduced motion, and the action/focus contracts.

The handoff lives in a shared widget,
`mobile/lib/shared/widgets/modal_scroll_handoff.dart`;
`message_actions.dart` changes by three lines to use it.
`docs/mobile-message-action-scroll.md` records the design contract and a
manual native checklist.

### Related issue

N/A. None found (searched issues and PRs for the message action menu
dismissal and scroll).

### Testing

Run at `558a79710`:

- `just mobile-check`: passed (format; analyze: no issues).
- `just mobile-test`: passed (5462 Flutter tests, 71 skipped; 27 crypto
tests).
- `just file-size-check`: passed.
- Restoring the previous release rule fails 12 of the updated tests,
including all four message action journey variants.

Coverage: the message action journey (2x text scale, iOS and Android
platform settings) drives the production sheet with timed pointer
events; the shared widget tests cover the release table at several
scroll offsets, pointer flicks on both platforms, parity with the stock
sheet drag around both thresholds, trailing bounce on short menus,
cancellation and interruption.

**Simulator recordings.** Both videos are side-by-side captures from the
iPhone 17 simulator (iOS 27.2, text size `accessibility-large` so the
menu overflows). Each side replays the same touch script.

Scroll-to-dismiss handoff. Left: base (`9bcb3e45a`), the body only
bounces and the sheet never moves. Right: branch at `23c31e2e1`, the
same touches pull the sheet down, restore it on reversal, and dismiss it
on a slow drag past half and on a flick.


https://github.com/user-attachments/assets/09b0cfc2-ed61-4822-8b35-b80d0f47e830

Scroll up slightly, then swipe down hard. Left: `23c31e2e1`, the menu
settles back open after both swipes. Right: `558a79710` (branch head),
the same touches close it, as a new touch and without lifting; the final
slow return across the top stays open on both sides.


https://github.com/user-attachments/assets/068faff4-a4d4-478f-aaf4-fc65c644632f

**Limits of this validation:**

- The touches were scripted synthetic touch events (linear motion, exact
timing), not a human finger.
- Both sides ran a dummy-data harness that calls the production
`showMessageActions` for a placeholder message, not the real channel
page. The harness is not part of this PR.
- Android, a physical device, VoiceOver and reduced motion were not
exercised natively; they are covered by widget tests only.
- The right side of the first video was built from `23c31e2e1`, one
commit before the branch head. `558a79710` changes only releases with a
fast downward velocity after content was scrolled. The gestures in that
video are slow or held releases and gestures that start at the top,
which resolve the same way under both rules; this follows from the
release rule and was not re-recorded.
- A human has not yet confirmed the behaviour by hand.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Matt Toohey <contact@matttoohey.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 14:41:01 +11:00
Wes
8827f986e4 mobile: follow desktop's unified sidebar workspaces (#9745)
Mobile Home now reads desktop's unified sidebar from block/buzz-app#3791
and shows the same workspaces, filings, icons and section order as the
desktop sidebar. It is read-only while a unified record exists.

## What changed

- **Reads desktop's records.** Mobile reads `channel-workspaces` and
`channel-workspace-sort`. Until the unified record exists, it falls back
to the legacy `channel-sections` and Solo groups, merging them the way
desktop imports them (`expandWorkspaceRecord`,
`importWorkspaceFallback`, `mergeLegacyWorkspaces`). Sort follows
desktop's `meta.g` registers.
- **Layout.** Sections are Starred, then the workspaces, Team, Solo and
Direct messages, in desktop's `sectionOrder`. A workspace holds Team
channels and Solo chats alike, and shows its icon: Unicode emoji as
text, `:shortcode:` as the community's custom emoji, and nothing for an
unknown shortcode.
- **Read-only lock.** While a unified record exists, mobile hides
rename, delete, move, New project and sort edits, and never publishes
the legacy records desktop would ignore. That includes:
  - an edit queued before the lock;
- a unified head arriving during a relay rate-limit wait (`mayPublish`);
  - a Team publish whose preflight read failed;
- a New project or workspace pick opened before the lock (the chat is
still created, without the filing).
- **Recovery.** A foreground refresh with a pending legacy sort still
applies a missed unified head.
- **No All/Solo/Team filter.** Desktop removed its tabs in #3791, since
workspaces now hold Solo and team chats together, so Home drops its
chips too. The Messages header keeps its title and actions and no longer
collapses on scroll.
- **Filters.** The Unreads filter uses Solo's own unread state for Solo
rows.
- **NIP-44.** Decryption accepts the extended length prefix for payloads
over 65535 bytes. A nostr-tools vector is included.

## Tests

- `workspace_layout_interop_test.dart`: a table generated by running
desktop's TypeScript from buzz-app `main` (11 layouts and 10 invalid
records). It checks that mobile computes the same sections, assignments
and order.
- `sidebar_workspaces_journey_test.dart`: Home runs on the real sections
and sort notifiers over the relay fixture. It starts on legacy sections,
receives desktop's signed heads live, then checks the order, filings,
icon, read-only sheet and Unreads. It also checks that only the filter
choice is published.
- `unified_sidebar_records_test.dart`: Team and sort publish nothing
once a unified head is seen: before an edit, while one waits, or past a
failed preflight.
- `project_creation_test.dart`: the unified layout arrives while a
workspace is being named. Nothing is written, and nothing is left to
resume.

- `solo_creation_tags_test.dart` and `me_sync_test.dart`: a project
picked or a filing queued before the lock doesn't stop a new Solo chat
from being created.

Each new guard was mutation-checked: removing it fails its test.
`flutter analyze` is clean and `flutter test` passes (5450).

## Not in this PR (open questions)

- **Forums** stay hidden on Home, as before. Desktop shows them, so a
forum filed into a workspace or starred on desktop doesn't appear on
mobile. Should mobile add a Forums section?
- **Filters** still use the legacy `channel-filter` record. Desktop
prefers `channel-workspace-filter`.
- **Solo creation without a unified record** still writes the legacy
Solo groups, as before.
- **Empty workspaces** are shown, as on desktop. Mobile rejects a
unified record that carries `meta` without `filings`; desktop never
writes that shape.
- Built-in titles now match desktop: "Team" (was "Channels") and "Direct
messages" (was "DMs").

## How to test

1. On desktop (buzz-app with #3791), create two workspaces, give one an
emoji icon, and file a Team channel and a Solo chat into it. Reorder the
sections.
2. Open mobile Home in the same community. The sections, order, icon and
filings should match desktop.
3. Open a workspace's options. You should see only Sort (disabled) and
Show. Long-press a channel: there's no "Move to section…".
4. There is no All/Solo/Team filter row under the Messages title.
5. Change the order on desktop. Mobile should follow live, or after you
foreground the app.

Screenshots are in the comment below.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-19 18:49:12 -07:00
Tom Brow
9bcb3e45a4 perf(mobile): hash upload payloads in bounded worker chunks (#9747)
Follow-up to #9736, which moved upload hashing off the UI isolate with
`compute`.

`compute(_sha256Hex, bytes)` copies the whole prepared payload into the
worker while the uploader keeps the original for the PUT. For a 100 MiB
attachment that adds about 100 MiB to peak memory before the first
request.

This streams the payload to a worker isolate in 1 MiB chunks, with one
chunk in flight at a time (the worker acks each chunk before the next is
sent). Each chunk is copied with `TransferableTypedData.fromList` on its
own slice, since sending a `sublistView` would copy the whole backing
buffer. The digest, the `X-SHA-256` header, the signed Blossom `x` tag
and the cancellation checks are unchanged.

### Validation

In a 100 MiB AOT probe, peak RSS was 114 MiB hashing inline, 214 MiB
with the whole-buffer `compute` handoff, and 141 MiB with acked 1 MiB
chunks, at about the same hash time (611 / 622 / 614 ms).

Added tests in `mobile/test/shared/relay/media_upload_test.dart`: the
worker digest matches `crypto.sha256` for a 2 MiB + 123 byte payload,
sends three chunks with at most 1 MiB in flight, and handles an empty
payload.

### Regressions

- UI responsiveness: the hash still runs off the UI isolate. The UI
isolate now does one 1 MiB slice copy per chunk instead of one full
copy.
- Latency: hash time is about the same as with `compute` in the probe.
Small uploads pay one isolate spawn, as before.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
2026-11-19 22:21:26 +00:00
Will Pfleger
890824f072 feat(read-state): sync mark read, channel mark unread and thread follows (#9501)
Reading, mark read, whole-channel mark unread and thread follow choices
now sync across a person's installations. This PR specifies the rules in
NIP-RS and implements them in the mobile app.

## Spec (`docs/nips/NIP-RS.md`)

- Defines *catch-up* and *displayed*.
- A catch-up advances the channel's own frontier (top-level messages) or
`thread:<root>`. `activity:` and `thread-activity:` become read-only
legacy keys.
- Explicit mark read is synchronized state. A first explicit read of a
message with no override group writes only its `msg:` frontier. Display,
dwell, scroll, catch-up and mention visibility create no `msg:` entries.
- Only whole-channel override groups are published, merged and cleared
with the counter. Readers ignore peer `msg:` and `thread:` groups.
- Single-message and thread mark unread stay on the device. They end
once the merged frontier covering them passes their baseline, from any
installation, or on display, catch-up or explicit read. The section also
states clearing scope, the accepted concurrency limitation and capacity.
- When the merged override union no longer fits the primary, the client
rewrites the primary compactly from the groups its last published
primary carried, each canonical against current frontiers. It never
omits merged groups or tombstone floors that primary carried, and
override actions fail visibly.
- Adds Buzz Thread Follow Choices: `thread-follows:<32hex>` coordinates,
validation, three-state verdict, last-writer merge with ties going to
unfollow, publication and recovery, legacy import at `at = 0`, and
capacity.

## Mobile

- Catch-up writes the main frontier. A flat timeline reads up to the
newest top-level message it reached.
- Explicit mark read publishes. Passive `msg:` marks stay on the device.
- Whole-channel mark unread publishes an override group and merges peer
groups. An explicit read or catch-up clears it, even when no frontier
moves. The action fails visibly at the uint32 limit or when the primary
is full. A synced clear the primary can't carry is rolled back, and the
channel view reports it once while the failure stands.
- Device-local message and Inbox unread overrides record a baseline and
clear when a covering frontier passes it, including one merged from a
peer.
- Thread follows move from local storage to the synced `thread-follows:`
slots. They share the read-state `client_id`, journal, `created_at`
sequence, snapshot and live subscription, and spill across up to 16
slots with stable placement. An unreadable coordinate marks follow state
incomplete and blocks this installation's follow publication.
- Follow and unfollow are refused on every cold start of the writer
until its first complete recovery of its own state succeeds and every
owned follow head is readable. Cached follows show at once. A refused
tap changes nothing and shows "Follow choices are not ready. Connect and
try again." Reads, catch-up and both kinds of mark unread are not gated.
- A follow tap is accepted only once journaled. The accepted own head,
pending edits and the exact in-flight packet are kept apart, so a retry
or restore never drops or re-attributes an edit.
- Pre-sync local follows are imported at `at = 0` after a complete
merge, once their channel is known from a relay event. An imported key
is settled, and its legacy copy retired, only when the journal write the
import awaited covered it and that entry is still current.
- An explicit unfollow suppresses ordinary replies at live and catch-up
admission. A change in follow choices drops the unread replies already
counted for an unfollowed thread. A newly followed thread re-runs
catch-up only for its own channel.
- A reading clear refused because the view hasn't completely loaded is
retried after the next complete snapshot, including when publishing was
shut off at the time. The view also counts as not completely loaded
while the live subscription is reconnecting, so a read made while the
phone is offline can't erase a newer unread mark set on another device.
Offline, whole-channel mark unread is still refused, with a message.
- Read-state events, including live ones, are verified with native
libsecp256k1 before they are used.
- A pending unread packet is counted as published only when no newer own
head outranks it. When a newer head supersedes it, a successor is built
above that head from the saved intent, and a late echo of a replaced
packet doesn't overwrite what was published.
- When the merged unread state overfills the primary and the compact
fallback can't carry a pending mark, the packet stays pending and the
"read state full" error shows. Other queued reads and follows in the
same flush still publish.
- When this installation's own unread record can't be decoded, only the
unread step is held: that record isn't overwritten, its pending marks
stay queued and the sync error shows. Other queued reads and follows in
the same flush still publish.
- The sync notice stays up after an unsupported refusal until a new
session. Offline, it can't be tapped and says it will retry when back
online.
- Two-device fixtures against an in-memory relay cover channel
round-trips and clears, stray message groups, the first explicit message
read, the primary cap, follow propagation, same-second and
backward-clock follow publication, legacy import, retry after a failed
publish, unreadable coordinates and slot packing. Recovery fixtures
cover the startup gate, journal failures during flush, interleaved
legacy imports, and restore of an older journal.

## Relay

- Conforming `thread-follows:<32 hex>` records get the NIP-RS treatment:
a replaced record is purged, and a stale resend of an older one is
refused. Records with a mismatched `t` tag keep ordinary
replaceable-event behavior.

## Known gap

- An unread packet held for capacity can age past the relay's timestamp
window. The relay then refuses it, and the refusal path retires it
without the capacity check, so the error clears and other installations
don't get that mark. The mark stays on the device.

Related:
[block/buzz-app#3552](https://github.com/block/buzz-app/pull/3552)

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Signed-off-by: Will Pfleger <wpfleger@squareup.com>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
2026-11-19 17:02:58 -05:00
Wes
f7496607a8 fix(mobile): hash upload payloads off the UI isolate (#9736)
## Summary

Move SHA-256 for prepared mobile uploads to a worker isolate with
Flutter's `compute`, at all payload sizes. The same digest feeds the
`X-SHA-256` header and Blossom authorization. The existing cancellation
check runs before each HTTP send, including after the worker returns.

### Related issue

No matching open issue or PR found.

### Testing

- `just mobile-install mobile-check mobile-test` passed, including
`flutter analyze` and the full Flutter suite.
- The upload regression verifies that a 2 MiB attachment's `X-SHA-256`
header matches the request body's digest.
- The composer widget tests wait for the worker while exercising send,
progress, cancellation, and error handling.
- On Apple M3 Ultra, a host Flutter test ran the production
prepared-byte upload path with a stub HTTP transport. Median delay to a
queued main-isolate timer over three runs:

  | Payload | Before | After |
  | --- | ---: | ---: |
  | 50 MiB | 330 ms | 3.6 ms |
  | 100 MiB | 644 ms | 7.5 ms |

At 100 MiB, the patched isolate serviced at least 40 callbacks from a 16
ms timer before HTTP send. The baseline serviced zero. Both produced the
same hash. This measures host isolate responsiveness.

### Manual check

On a phone, attach a large file in a test conversation. Tap Send and
immediately scroll the conversation. Scrolling should stay responsive
during upload preparation. Open or download the completed attachment and
verify that it matches the original.

Signed-off-by: Wes <wesb@block.xyz>
Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz>
2026-11-19 14:34:30 -07:00
klopez4212
42b89f9b5f fix(mobile): align Huddle cards and preserve conversation navigation (#9713)
Hide generated private Huddle rooms from mobile channel lists, including
cached rooms and older rooms with creator-matched creation receipts.
Ended Huddle cards keep **View** available while membership is unknown.
Known non-members see disabled **Ended**. Unknown membership is checked
with the relay before opening history, and explicit access denials clear
cached transcript rows. Opening history never joins audio. Known members
can reopen loaded history offline. Already-authorized history stays
mounted through a disconnect or transient revalidation failure while the
route remains open; reconnects recheck access, and explicit denial
clears it. Rooms without sufficient evidence remain visible.

Match desktop card colours, borders, 20-point corners, elapsed duration,
participant avatars and ended-call icon. Active cards retain headphones
and mobile tap targets. Replace the minimized Huddle's full-app UIKit
background with Flutter clipping: the native background caused the
two-pane iOS conversation to appear blank even though its messages were
loaded and scrollable. The owner reproduced the failure and confirmed
the Flutter surface restores the timeline on iPhone Duo.

Lifecycle updates share one live subscription and merge into history.
Start/end discovery has its own query budget and survives a failed
participant-history read; avatar rosters use revision and admission
metadata for same-second reconnects. Explicit denials propagate without
trying a fallback transport. Creation receipts coalesce overlapping list
refreshes and reconcile after the list loads, retain verified
classifications in scoped snapshots, and stop sending batches after a
community switch. Removed the unused native backdrop and bottom-corner
options.

Validation on `7f1a278dbe`: 5,133 Flutter tests plus 27 companion tests
passed (71 skipped), analyzer and file-size checks passed, and the iOS
release build passed. The updated Buzz Huddles preview is installed on
iPhone Duo. The phone locked before launch, so the exact-revision native
journey is still pending. Regressions cover cached-history denial,
live-only lifecycle events across recovery, busy-call discovery,
same-second rejoining, slow and overlapping receipt lookups, cached
classifications, community switching, and HTTP denial with a transient
WS failure configured. Both transport-denial and overlapping-refresh
regressions were verified failing before the fixes. Tom’s follow-up from
#9719 adds held-revalidation, known-member offline reopen and
partial-roster failure coverage. The original blank-screen fix was
verified by the owner on iPhone Duo; this review revision still needs
their on-device minimized-Huddle/two-pane and VoiceOver checks. The
surface retains Flutter's existing 24-point shape instead of
iOS-adaptive concentric corners.

### Snapshots

Synthetic widget previews; no private conversation data.

| Active | Ended | Dark mode |
| --- | --- | --- |
| ![Active
Huddle](https://github.com/user-attachments/assets/9abbeb94-e55c-4991-bd56-e2a78a5915a0)
| ![Ended
Huddle](https://github.com/user-attachments/assets/f3d7c3c1-57d2-4ae2-a669-17c64d0e214e)
| ![Dark
Huddle](https://github.com/user-attachments/assets/b0ff47d1-708d-46b8-9082-e57076053ae0)
|

![Large
text](https://github.com/user-attachments/assets/87a63108-3773-4317-990d-f3d7c7412bbd)

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-19 18:46:30 +00:00
Tom Brow
7361326717 fix(mobile): keep glass controls mounted and the wide thread push parallax (#9726)
Fixes three regressions that #9717 (Duo chat switching) introduced.

**Glass controls blank when anything covers their route.** #9717 gated
`IosGlassNavigationButton` and `IosGlassNavigationAction` on
`useNativeRouteControlsVisible`, so every glass control (Home's filter
chips, glass Back, Close, Done) unmounted under any dialog, alert or
modal sheet and during every push, pop and back swipe, then came back as
a new platform view near the end of the transition. This drops the gate
from those two widgets, which restores their behaviour from before
#9717. The problem #9717 targets is unaffected: under Search and
Activity sheets the hook already returns true and the opaque backing
hides the controls. Home's gate, the Channels route sync and
`IosMessageCreateButton` keep the hook.

**The visibility hook rebuilt its host on every animation frame.** It
subscribed to the route's animation values but only reads whether the
covering animation is at zero and whether the route is reversing. It now
uses `useListenableSelector` on those two booleans, so a host rebuilds
only when visibility can change.

**A wide thread push lost the outgoing chat's slide.** For an immediate
wide selection, `_ConversationDetailRoute.buildTransitions` returned its
child directly, which also discarded the secondary animation that moves
the chat left when a thread is pushed over it. It now builds the
platform transition with a completed primary animation, so selection
stays immediate and the covered chat keeps its parallax.

### Regressions

- Glass controls go back to staying mounted under covering routes, as
they did before #9717. Platform-view bleed under non-sheet routes is
therefore the pre-#9717 behaviour, not new.
- No change to compact navigation or to the Search and Activity sheet
composition.

### Validation

Added tests:
-
[native_route_controls_test.dart](fb0d16ef56/mobile/test/shared/widgets/native_route_controls_test.dart):
glass controls stay mounted, with the same channels, under a dialog and
keep receiving appearance updates, while only the create control
unmounts and returns; glass controls stay mounted with no platform-view
churn across a modal bottom sheet; the `bottomUp=false` composition case
keeps the glass views; the hook rebuilds its host a small constant
number of times across a full push and pop.
-
[adaptive_conversation_pane_test.dart](fb0d16ef56/mobile/test/shared/widgets/adaptive_conversation_pane_test.dart):
in the wide layout, the covered chat has moved left 150 ms into a thread
push on iOS.

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-19 18:09:17 +00:00
klopez4212
bf1cd5500d fix(mobile): stabilize Duo chat switching and sheet layering (#9717)
## Summary

Selecting a chat or channel in the expanded conversation layout now
switches immediately, while opening a deeper thread keeps its navigation
animation. The selected chat reuses the native iOS header and blur
surface so switching conversations does not flash; each conversation
still owns its own editor and timeline state.

Search and Activity now slide as opaque sheets over stationary native
controls, revealing them progressively on dismissal. Activity keeps its
existing title styling with Close in the Duo rail; expanded Search gains
top spacing. Compact navigation and the transparent toast composition
path are preserved.

## Validation

- Final head `bd92c40e86`: full mobile suite 5,132 passed, 71 skipped;
27 crypto tests passed. Required push checks passed.
- Native iOS suite: 115 passed. Formatting and analysis clean.
- Header-retention regression fails with the retention key removed and
passes after restoration.
- Recorded repeated native-header switches in a wide iPad simulator
fixture, plus Search/Activity transition checks in the Duo simulator.
- Owner verified both sheet motion and chat switching on the physical
Duo. The final ordinary-iPad Activity guard is covered separately by
tests.

## Snapshots

Synthetic chat fixture using the actual conversation-pane routes and
UIKit header on an iPad simulator. These illustrate two consecutive
selections; they are not screenshots of the owner's chats or the Duo
rail geometry. Recorded transition frames were also inspected for
continuous blur.

| Design selected | Mobile selected |
| --- | --- |
| ![Design
selected](https://github.com/user-attachments/assets/cf15641e-b1ee-47a1-aed4-0d20d0cadf0e)
| ![Mobile
selected](https://github.com/user-attachments/assets/c047ad37-3c86-4eb1-9cca-aeb9ec599499)
|

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-19 17:56:11 +00:00
klopez4212
68d367cf23 fix(mobile): align channel indicators and Duo section menus (#9703)
Align the mobile channel-list indicators to one trailing column. The
unread dot stays at the right, with the temporary clock and mute
indicator to its left when present. Duo's native menus for built-in and
custom sections now place their ellipsis in the same 20-point slot while
preserving the full 44-point tap target and native menu behavior.

Validation: full mobile suite (5,098 passed, 71 skipped), 27 crypto
tests, clean Flutter analysis, native UIKit menu geometry/hit-target
checks, and a successful iOS release build. Installed on iPhone Air and
Duo using existing saved state; inspected the Duo's native section-menu
placement. Regression coverage checks row alignment, clock ordering,
native bridge geometry, and the full menu hit area.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-19 16:38:55 +00:00
Tom Brow
39ffc3dcc5 fix(mobile): keep agent poster up until the iOS video draws (#9688)
On iOS, an animated agent avatar (a preset character with a transparent
video) blinks out for one to three frames right after navigation
settles. Opening a Solo chat blanks the header avatar; going back to
Messages blanks the bestie bubble.

The cause is the hand-off from the still poster to the video. While a
route animates, `PresetAgentAvatar` shows the poster; once it settles it
replaced the poster with a native `AVPlayerLayer`, which draws nothing
until its first video frame arrives. The avatar picker and the
create-agent page already covered this by passing a preloaded poster;
the DM and Solo header and the bestie bubble pass none, so they went
straight to the bare player.

Now every iOS caller gets that hand-off, using its own poster when it
passes none: the poster stays up, below the player, until playback
advances in that showing, then fades out over 160 ms. The poster sits
below the native layer rather than over it, because a Flutter overlay
above a platform view also costs a blank frame when the view first
appears. Each showing starts covered again and waits for playback to
advance from where the player actually is, so coming back to a chat from
a page above it doesn't blink either. The poster is keyed by its URL, so
when the avatar changes to another character (for example a synced
bestie change) it never shows the previous character's poster. Android
is unchanged; it already waits for a presented frame.

### Validation

Measured on an iPhone 17 Pro simulator, recording at 60 fps and checking
the avatar region frame by frame, opening a Solo chat with an animated
agent and going back:

| | Header blank on open | Bubble blank on back |
| --- | --- | --- |
| main, 3 runs | 1 frame every run | 2 to 3 frames every run |
| this PR, 3 runs | none | none |

Before (left) and after (right), slowed 4x: the Solo header on open,
then the bestie bubble on back.

<video
src="https://github.com/user-attachments/assets/4ddf16c0-bb8d-4d77-b53e-84f83ff45e98"
width="480"></video>

Added test: [iOS keeps the poster over a new player until playback
advances](2b172d1b68/mobile/test/shared/widgets/preset_agent_avatar_test.dart),
covering a first showing, a return to the route, and a change of
character while the video is showing.

### Regressions

- No extra work: the poster image was already loaded for the transition,
and the video plays exactly as before.
- During the 160 ms fade, poster and video overlap. They show the same
character, so the fade reads as a single image, as it already did in the
avatar picker.
- If the video never starts playing, the poster just stays up, which is
what callers showed before the video was ready anyway.





buzz-review-completed

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-18 19:57:44 -08:00
Tom Brow
b544fcea4a feat(mobile): add a diagnostics test report and test crash to Settings (#9676)
A way to check that a build's diagnostic reporting works end to end, per
[mobile diagnostic
reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md).
A build with a reporting destination shows a Diagnostics card in
Settings with **Send test report** and **Test crash**. A build without
one, which includes every build from this repository alone, never shows
it and still reports nothing.

| Before | After |
| --- | --- |
| ![Settings bottom,
before](https://github.com/user-attachments/assets/92fdef05-8d63-43db-8df1-32ccb92105c8)
| ![Settings bottom with the Diagnostics
card](https://github.com/user-attachments/assets/a205ab18-ed1e-49d5-8e34-88e29e4c91fa)
|

![Test crash
confirmation](https://github.com/user-attachments/assets/335eb362-3a61-4c8c-8b32-44de548cf788)

### What's in it

- The reporter gains `reporting` (whether the build has a destination),
`sendTestReport()` and `crashForTest()`. The do-nothing reporter returns
false and does nothing.
- **Send test report** sends a fixed `DiagnosticTestError` tagged with a
new `testReport` operation. It passes through the same filter as every
report.
- **Test crash** asks for confirmation, then crashes in native code
through the SDK, so native crash reports can be checked too. The report
goes out the next time the app opens.
- The spec gains a "A way to check a build" decision.

### Regressions

None expected: builds without a destination render Settings exactly as
before.

### Validation

Added widget tests for the card being absent without reporting, sending
a test report, and the crash happening only once confirmed, plus a test
of what a sent test report contains and one that a second tap sends a
second report. The screenshots come from simulator builds of main and
this branch, both with the same placeholder destination.

A full-app simulator run at dec267f (placeholder destination) passed:
channel list, opening and scrolling a channel, search, the other
Settings sections, two test reports (a toast each time), cancelling Test
crash, confirming it (a native crash in the Sentry SDK) and relaunching
signed in.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-18 14:48:25 -08:00
Tom Brow
bf9ce1432e feat(mobile): add diagnostic reporting module with crash capture (#9613)
Step one of [mobile diagnostic
reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md),
first piece: the reporting module, plus capture of crashes and uncaught
errors.

A build given a `BUZZ_SENTRY_DSN` now reports native crashes, Flutter
framework errors and uncaught asynchronous Dart errors to that Sentry
project, attributed to the signed-in member's public key. A build
without one (every build made from this repository alone) uses a
do-nothing reporter and never initializes the SDK, as [ADR
0007](https://github.com/block/buzz/blob/main/docs/adr/0007-diagnostic-reporting-follows-the-destination.md)
requires. A destination the SDK cannot parse is treated as none, so a
configuration mistake never stops the app from starting.

### What's in it

- **One interface** in `mobile/lib/shared/diagnostics/`: report an
error, count a networking event, leave a breadcrumb, and set the member.
It has a Sentry-backed and a do-nothing implementation. Only this folder
imports the SDK. The explicit error reports and the networking counts
that use it come in the next PRs.
- **Startup** wraps `runBuzzApp` and installs the SDK's crash and error
handlers only when a usable destination is set: one with an HTTP(S)
host, a public key and a project, which the native SDKs also require. On
Android, the manifest removes the SDK's startup performance provider,
which would otherwise run before that check.
- **Member:** set from the active community's key, changed when the
account switches, cleared on sign-out. Adding the Builderlab origin and
account subject is left to a later PR. Every report also carries a
random per-install identifier the app creates on first launch, as its
own `install.id` tag, signed in or not, so a device's reports can be
matched to its members. It lives in a file that device backups and
transfers skip, so a phone restored from another gets its own: on
Android in the app's files directory, excluded in both backup rule sets;
on iOS in an Application Support folder that a small native call marks
as excluded from backup (not the caches folder, which iOS can clear when
storage runs low). Set on the SDK scope, it also reaches native crash
and hang reports. With no member set (before sign-in or after sign-out),
the SDK also fills the report's user with its own random per-install
identifier, on Dart and native reports alike.
- **One filter** runs on every Dart report, breadcrumb and count before
it leaves the device:
- It replaces every error's own text with fixed wording, since an error
can quote its input, a server's response body or a URL. The error keeps
its type, mechanism type and stack trace.
- It drops what the SDK adds about the failing platform call
(`mechanism.data`) and the failing widget (`flutter_error_details`),
which can quote what is on screen.
- It removes URL query strings and fragments, and keeps only tags and
count attributes on the allowed list.
- It drops every breadcrumb except networking events and the SDK's
foreground/background entries.
- **SDK options:** personal data, screenshots, view hierarchy, replay
and tracing stay off. The SDK's session records stay on, for a
crash-free rate. A session begins each time the app starts or returns
after 30 seconds or more in the background; the SDK sends a record when
it begins, an update each time an error is counted, and a last one when
it ends, carrying the start time, error count, outcome, time from start
to end, release, environment and the random per-install identifier.
Native auto-breadcrumbs, Android's network-change breadcrumbs (VPN
state, signal strength, bandwidth; turned off in the manifest, since the
Flutter bridge leaves them on), Cocoa's network breadcrumbs (which keep
each request's query and reach native crash reports) and print
breadcrumbs are off. With print breadcrumbs on, the SDK would replace
`debugPrint` in non-debug builds with one that prints nothing.
- **Main-thread hangs:** iOS app hang tracking, Android ANR detection
and iOS watchdog-termination tracking are set on explicitly, at the
SDK's default thresholds. iOS reports the main thread blocked, fully or
mostly, for 2 s or more while the app is active, including freezes it
recovers from; a hang still going when the system kills the app is sent
on the next launch as a fatal hang, and watchdog-termination tracking
reports a foreground run that ended with nothing else to explain it.
Android reports only system-declared ANRs: on Android 11 and later, the
most recent one that ended the process (read on the next launch, when
the system kept a thread dump); before 11, after 5 s once the system
marks the app not responding. So recoverable freezes are reported on
iOS, and on Android only before 11 once the system marks the app not
responding. Dart runs on the main thread, so blocking Dart work shows up
with the main thread's stack; Dart frames need the Dart debug symbols at
the destination, as crashes do. The spec now has a bullet and a user
story for this.
- **What the filter does not cover:** native crashes and app hangs are
captured and sent by the native SDKs, which never call the Dart filter.
They carry stack traces and, for a native exception, its reason text. No
app code puts content in a native exception today. The spec now says
this.
- **Reporting never blocks the app or reaches it with an error:** every
call returns at once, and a failure inside reporting is dropped with a
`debugPrint`.

### Regressions

None for builds without a destination, which includes every build from
this repository: they run the same startup with one extra synchronous
check, and the SDK is never initialized. The SDK still adds to the app's
binary size on both platforms.

With a destination, the first frame waits for the SDK to start, native
SDK included, and for the install ID to be read from (or, on first
launch, written to) a small file. On a debug simulator build the first
frame came about 0.3 s later (median of 6 cold launches: 768 ms with a
destination, 431 ms without), measured before the install ID was added.
Device builds will differ. Uncaught errors still reach Flutter's default
handling, and the SDK sends in the background.

### Validation

Added tests (`test/shared/diagnostics/diagnostic_reporting_test.dart`):
- A table of inputs run through the production Sentry options callbacks:
SDK HTTP and navigation breadcrumbs are dropped, network breadcrumbs
keep only their four attributes, URLs lose their query string and
fragment, unknown tags and count attributes are dropped, and the privacy
and breadcrumb options stay off.
- Errors sent through a real SDK hub, with the SDK's own platform-error
processor and Flutter error integration, into an in-memory transport:
for a parse failure, a bad argument, a server response and a platform
failure, the serialized event keeps the type and stack but none of the
error's text; a real framework build error leaves out the widget text.
- A release-mode check that `debugPrint` keeps printing with reporting
on.
- A build with no destination, one the SDK cannot parse, one without a
public key or one without an HTTP(S) host starts the do-nothing reporter
and the SDK stays disabled.
- Reporting calls whose SDK calls throw, either synchronously or
asynchronously, never reach the caller.
- Hang detection is on and its thresholds equal the SDK's defaults.
- An installation keeps one install ID across launches, a new
installation gets a new one, and the filter keeps the `install.id` tag.
- Signing in, switching accounts and signing out change the member that
later reports are attributed to.

I checked that each guard is real by removing it: the print-breadcrumb
setting, the destination check, the error-text replacement, the
`mechanism.data` and `flutter_error_details` removal, the
network-breadcrumb setting, the dropped-failure catch and the tag filter
each made a test fail.

End to end on an iPhone 17 Pro simulator, with a local server standing
in as the destination and a throwaway probe (not committed) that made an
HTTPS request with a secret in its query, then raised an uncaught Dart
error and a framework error with secrets in their text, then crashed
natively:
- All four reports arrived (two Dart, one framework, one native crash on
the next launch), and none of the secrets appeared in any envelope.
- Dart reports carried only the foreground/background breadcrumb; the
native crash carried none.
- As a control, a build with Cocoa's network breadcrumbs switched back
on put the request's secret query and fragment into the native crash
report, so that setting is what keeps them out.
- `debugPrint` lines still appeared in the device log.

Hangs, on a fresh iPhone 17 Pro simulator with no debugger attached and
the same local server: a throwaway probe busy-looped the main isolate
for 5 s after the first frame. The SDK sent an `App Hang Fully Blocked`
event ("App hanging between 5.7 and 6.5 seconds", mechanism `AppHang`)
carrying the main thread's stack: Flutter engine frames around 12 frames
of Dart code. This was a debug build, where Dart is compiled just in
time, so those frames have no image to symbolicate against; in release
builds they fall in the app's compiled Dart framework and need its debug
symbols at the destination.

Install ID, rechecked after moving it to its own file, on a fresh
simulator with the same local server, launched twice with a probe that
raised a Dart error and then crashed natively: both Dart errors and the
native crash carried the same `install.id`, while the signed-out user
was the SDK's own identifier. The ID file was in the backup-excluded
`Library/Application Support/Diagnostics` folder, not in the app's
preferences.

The merged Android debug manifest has neither of the SDK's startup
providers and has the network-change setting off. The NDK preload
provider is still merged in, but it does nothing unless its own manifest
flag is set, and it isn't.

Full mobile suite passes. Dart errors are captured in the main Flutter
engine only; the iOS sheets that start their own engine are out of scope
for this PR (native crashes while they are open are still caught), as
the spec now says. iOS simulator and Android debug builds with a
destination set both build; on iOS the SDK resolves through Swift
Package Manager.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-18 12:50:45 -08:00
Diem Nguyen
c18bed1f46 fix(mobile): name the cause of account-unavailable sign-in errors (#9628)
## Problem

Organization sign-in can fail with `Couldn't sign in
(account-unavailable)`. That code covers several different failures, so
a screenshot can't tell them apart:

- the account server can't be reached at all (DNS, connection, or TLS
failure, or a timeout), for example when a required VPN profile isn't
applied to the app;
- a redirect, since the client doesn't follow redirects, so an
access-proxy login page lands here;
- a 5xx from the server.

## Change

- `BuilderlabAccountClient` records why a request failed as
`unavailable`, in `lastUnavailableCause`, and logs it. It follows the
existing `lastRejectedRequest` pattern. The cause is one of:
- a transport category: `unreachable`, `insecure`, `timedOut` (reusing
`transportFailure`), or `network` as the fallback;
  - the status code, such as `http302`.
- `OrganizationSignIn` saves the cause at the moment the exchange fails,
so later account requests can't change it. It adds the cause to the
failure code, for example `account-unavailable-http302` or
`account-unavailable-unreachable`. Each new attempt clears it.

- The organization sign-in page now ends its failure message with advice
for that cause instead of "Try again.":
- unreachable, timeout, TLS failure, redirect: "Check your network or
VPN connection, then try again."
  - a 5xx: "The sign-in service is unavailable. Try again later."
- The in-app banner keeps "Try again.": its capsule clips longer
messages at default text size, and the existing banner layout test
caught that.
- Unexpected statuses are classified as soon as the headers arrive, so a
slow or oversized error body can't hide the status.

| Before | After |
|---|---|
|
![Before](https://github.com/user-attachments/assets/17a2a3ac-a488-46b3-9995-1bd95a529f60)
|
![After](https://github.com/user-attachments/assets/3813d1e9-7dc4-4726-9f40-ace57ed12d7a)
|

The log line contains only the host, route, and cause. It has no
headers, credentials, or response bodies.

## Validation

- A new journey test in `organization_sign_in_test.dart` covers an
exchange that fails with a 302, a 503, and a client exception, then a
successful retry. With the cause capture removed, the test fails
(`Expected: 'account-unavailable-http302'`, `Actual:
'account-unavailable'`).
- The same test checks the advice for each cause. The internal-build
landing tests pass with `--dart-define=BUZZ_DISTRIBUTION=internal`.
- The screenshots come from the real `PairingPage` rendered in a scratch
widget test with a 390×844 surface, cropped. The scratch test isn't
committed.
- `just mobile-check` passes, and the full `flutter test` run passes:
+5018, 71 skipped.
- Not yet done: a device run that reproduces an unreachable account
server and captures the new message on screen.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Diem Nguyen <diem@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:34:49 -08:00
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
Tom Brow
ff652ed06c perf(mobile): cache and animate custom emoji in the iOS picker (#9479)
The iOS emoji picker's custom emoji downloaded again every time the
picker opened, and animated emoji showed only their first frame.

Now each custom emoji downloads once per install and plays its
animation:

- The native picker gets image bytes from Flutter through the same path
as the rest of the app's images: the in-memory custom emoji cache, then
the persistent media disk cache, then one download through the shared
media HTTP client. Relay media is cached as immutable.
- Swift decodes every frame (no Swift-side cache) and shows the image in
a `UIImageView`, since SwiftUI `Image` draws only the first frame of an
animated `UIImage`. With Reduce Motion on, it shows the first frame,
following the setting live.
- At most four picker downloads run at once, and an emoji scrolled off
screen before its turn never starts. Emoji already saved on disk skip
the queue, so reopening a large set stays instant.
- A picker load joins any download of the same image already in flight
elsewhere in the app. A saved copy that fails to decode is evicted and
downloaded again, and only bytes that decoded are kept in memory.
- Swift decodes at most four emoji at once, including ones from cached
bytes. An emoji whose cell scrolls away gives up its place and stops
decoding between frames, and a cell that leaves the screen keeps only
its first frame.
- Each animation frame keeps its own delay. UIKit spaces animated frames
evenly, so a frame repeats for its share of the loop, and a GIF that
holds its last frame for 3 s still does.

### Why it refetched

The native picker loaded images itself with `URLSession.shared` and an
`NSCache` keyed on the whole request. Every request carried a freshly
signed media auth header, so the key never matched and nothing was
cached on disk.

### Validation

Relay media downloads for the 48 custom emoji matching "nod" (local
relay, iPhone 17 Pro simulator):

| Step | main | this PR |
| --- | --- | --- |
| First open | 48 | 48 |
| Leave and re-enter the channel, reopen | 48 | 0 |
| Relaunch the app, reopen | 48 | 0 |
| Reinstall the app, reopen | not measured | 0 |

Before (main): every reopen downloads again, and animated emoji are
still.


https://github.com/user-attachments/assets/7a43dd6a-61e0-495d-abed-6c11f7d4f965

After (this PR): reopening shows cached emoji immediately, and animated
emoji play.


https://github.com/user-attachments/assets/bf45a5c0-77ef-4501-8843-6f42e15de389

Automated app run: signed in to a local relay, opened a channel,
long-pressed a message, opened the full picker, searched, closed, left
and re-entered the channel, reopened, relaunched and reopened. Repeated
on the final head (359fdc8) with a warm cache: 0 downloads across open,
re-entering the channel and relaunch, all emoji rendered. The run used
the simulator only; device and hosted-relay behavior were not exercised.

Added tests:

- `media_disk_cache_test.dart`: encoded bytes for a native surface
download once, survive a relaunch, and bytes that never decode are not
saved.
- `emoji_picker_test.dart`: the native sheet's `mediaBytes` call returns
authorized bytes, a second call makes no request, and a cancelled call
fails.
- `emoji_picker_test.dart`: at most four loads run at once, a queued
load cancelled before it starts never downloads, and a saved emoji
doesn't wait for a slot.
- `media_disk_cache_test.dart`: a damaged saved copy (including a
truncated PNG) is evicted and downloaded again.
- `media_image_test.dart`: encoded-bytes requests share one download
with simultaneous image loads, and only decoded bytes reach observers.

- `NativeMessageImageLoaderTests.swift`: a GIF with uneven delays keeps
each frame's share, a cancelled decode returns nothing, and the decode
gate admits four in order and drops a cancelled waiter.

Removed `NativeEmojiRedirectPolicyTests` and the native concurrency test
along with the Swift loader they covered.

### Regressions

- Network: fewer requests. Cold loads keep the old picker's
four-at-a-time limit, so on a slow HTTP/1.1 origin queued requests don't
time out waiting for a connection. Downloads use the shared media HTTP
client, the same one other app images use, which on iOS now runs over
HTTP/2 since [#8897 iOS
HTTP/2](https://github.com/block/buzz/pull/8897).
- Memory: the picker keeps no image cache of its own. Each view decodes,
downsampled to 84 px and at most four at a time, from bytes Flutter
already holds in memory or on disk.
- Disk: emoji go into the existing 250 MB LRU media cache.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-17 09:04:38 -08:00