Commit Graph

274 Commits

Author SHA1 Message Date
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
klopez4212
921a05a379 fix(mobile): host Duo long-press menus in native sheets (#9536)
## Summary

On unfolded Duo landscape, channel/DM actions and Solo details now open
in a UIKit sheet above the app’s native controls, while retaining Buzz’s
Flutter tiles, member rows, and grouped cards. Content drags take
priority over sheet dragging; the native top bar still supports
dismissal.

The presentation-only engine starts only when an eligible sheet is
presented, without account, camera, audio, or storage plugins. It is
destroyed on dismissal; other iPhones pay no second-engine launch cost.
The main app retains live permissions and actions, and the native sheet
dismisses before opening follow-up screens. Cover-display and portrait
postures retain the existing bottom sheet. Pending avatar requests are
abandoned on dismissal, including after the display wait expires; the
display timeout alone lets the download finish and cache. Confirmed
lifecycle actions retire the invisible owner route before waiting for
the relay.

### Related issue

Follow-up to #8568. No duplicate sheet PR found.

### Testing

- `just mobile-install mobile-check mobile-test`: clean analysis; 4,900
Flutter tests passed (71 skipped), plus gateway/package checks.
- Mobile file-size and diff checks passed.
- Earlier signed device preview built, installed, and launched; owner
confirmed its scrolling. The later lazy-start and lifecycle fixes have
not been rechecked on the device.
- Unsigned iOS release build passed for `4ed94c6eb4` (Xcode 116.7s).
- Journeys cover bridge permissions, copy/close callbacks, the content
renderer, full profile-to-DM return, and reopening the list during a
held archive. Avatar tests cover immediate cancellation, display timeout
followed by cancellation, and timeout followed by completion and cache
reuse; regression probes fail with the fixes disabled. UIKit drag
handling still lacks automated interaction coverage.

### Snapshots

Actual Flutter sheet contents at 540×580 points with sample data. These
show the content layout; they do not show UIKit’s surrounding sheet or
its animation.

| Surface | Light | Dark |
| --- | --- | --- |
| Solo details | ![Solo details,
light](https://github.com/user-attachments/assets/43251c76-11c6-48d0-9be5-b242329234e6)
| ![Solo details,
dark](https://github.com/user-attachments/assets/ba03cac5-e890-4036-a4fd-337ed1a78a85)
|
| Channel actions | ![Channel actions,
light](https://github.com/user-attachments/assets/88c37da0-53cb-48d9-9c07-8c547e1502d9)
| ![Channel actions,
dark](https://github.com/user-attachments/assets/4bd9956d-9a65-498e-81c5-6da74939ffc9)
|

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-16 19:14:38 +00:00
Wes
7b8066fb94 fix(mobile): keep the relay session across auth reloads (#9543)
## Summary

`RelaySessionNotifier.build()` watched the whole `authProvider` but only
read the signed-in status. Every `ref.invalidate(authProvider)`
therefore rebuilt the session: the socket and all live subscriptions
were dropped, and every screen resubscribed and republished presence and
read state at once. An invite join invalidates auth twice for the same
identity (3 sockets in about half a second), and each community switch
does it again, producing a REQ burst the relay answers with `CLOSED
rate-limited`.

The session now watches only `(status, community.pubkey)` via `select`,
so it still rebuilds when the user signs in or out, or switches identity
while signed in. Relay URL and signing key changes continue to rebuild
through `relayConfigProvider`, which is unchanged.

### Related issue

None found.

### Testing

- New regression test in `relay_session_test.dart`: with a connected
socket and a live subscription, two auth invalidations for the same
identity keep 1 socket, 0 disposes, `connected` status and a working
subscription; a pubkey change then rebuilds to a second socket, and
signing out disposes it.
- The test fails on `main` without the fix (`Expected: an object with
length of <1>`) and passes with it.
- `just mobile-install mobile-check mobile-test`: format clean, `flutter
analyze` no issues, 4909 tests passed (71 skipped), plus the
native-secp256k1 package suite (27 passed).
### Before and after: first-launch invite join (simulator)

Captured on a freshly erased iPhone 17 simulator with a one-use invite
for each run, counting relay traffic for this identity in the first 5 s
after launch. Before is `main` at `1a5c6939c`; after is this branch at
`8beda6aea`.

| | Before | After |
|---|---|---|
| Relay sockets opened during the join | 3 | **1** |
| Relay frames in the first 5 s | 72 | 57 |
| `OK false` for kinds 20001/30078 | 2 | **0** |
| REQs refused with `quota_exceeded` | 16 | 6 |
| Message posted after the join arrives live | yes | yes, on the same
socket |

The session rebuild is fixed: the join keeps one socket and its
subscriptions. The original target of fewer than 50 frames in 5 s is not
met. The remaining burst is about 31 separate single-document kind 30078
reads (`limit:1`, `authors` = self) at about +1.1 s, and all 6 remaining
`quota_exceeded` refusals are among them. Those reads don't come from
session rebuilds, so they'll be handled in a separate change rather than
in this PR.

- Not yet done: a run on a physical device of the first-launch join
flow.

Signed-off-by: Wes <wesb@block.xyz>
Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz>
2026-11-16 12:12:09 -07:00
Will Pfleger
df21064800 feat(auth): tolerate client clocks up to 120 s off (#9485)
Lets clients whose clocks are up to 120 s off sign in to NIP-FI
communities and stay connected.

**Relay**
- NIP-42 AUTH and NIP-98 HTTP Auth accept `created_at` within ±120 s,
using a shared `buzz_auth::TIMESTAMP_TOLERANCE_SECS`. This covers relay
login, audio admission, bridge, admin, invites, NIP-FI policy and Git.
- `DEFAULT_REPLAY_TTL_SECS` goes from 120 to 250 s: a 2 × 120 s window,
plus 1 s for the inclusive whole-second bounds, plus a 9 s budget for
the clock difference between relay pods. A compile-time assert checks
the arithmetic. The 9 s is an operational assumption about NTP-synced
pods, and the doc comment says so. No `deploy/` override exists.
- Media (kind 24242):
- Both modes accept `created_at` up to 120 s in the future and an
`expiration` greater than `now − 120`.
  - Strict: the 120 s age limit and the 60 s lifetime cap.
  - Permissive: keeps its 3600 s age allowance and has no lifetime cap.
- `buzz-auth` and `buzz-media` read the time through a `wall_now()` that
tests can pin (a `#[cfg(test)]` thread-local), so boundary tests are
exact.
- Git transport: comments only. It still reuses one proof per session,
so the reuse window now matches ±120 s.

**CLI**
- The desktop-provider lane asks the desktop app for the assertion every
time and keeps no copy, so the desktop's cache owns each token's
deadline. It looks the token up again after signing and sends that one,
so a provider may hand out a new token on every call.
- The direct-mint cache sets its deadline to `min(request_start + (exp −
iat), receipt + (exp − local_now))`, on a monotonic clock.
`request_start` is when the attempt that got the reply was sent, not the
start of the retry loop.
- An assertion with no local lifetime left is never returned or sent.
The cache asks again, up to 3 times, then fails with an auth error that
points at the computer's clock. An assertion without a readable `iat` is
refused. `iat` may be fractional (a NumericDate); the lifetime is
`max(0, floor(exp − iat))` whole seconds.

**Cache reuse (CLI, Flutter, iOS):** each cached token records when it
arrived on both the monotonic and the wall clock. It is reused only
while `max(monotonic elapsed, wall elapsed)` since arrival is under its
budget (`refresh point − receipt`, on the monotonic clock). A negative
wall elapsed counts as 0. The monotonic clocks used here stop while the
device sleeps, so the wall clock ends reuse after a sleep; setting the
wall clock back can't stretch a token, because the monotonic bound still
applies.

**Mobile**
- Flutter `HostedRelayAuth`: the same lifetime rule, on a monotonic
clock, for async acquisition and for the synchronous `cachedHeaders`
media path. A token with no local lifetime left is never sent: issuance
is retried up to 3 times, then fails as `unavailable`. A token without a
readable `iat` fails as `invalidResponse`.
- Flutter refusal hint: the account client reads `Date` when a 403's
headers arrive, before the body (`boundedHttpResponse` gains an
`onHeaders` callback). The 403 stays `AccountFailure.denied` even if its
body is then lost, late or too large. The hint is stored with the
refusal it explains (`HostedRelayAuth.failureClockHint`), cleared when
that community next gets a token or the account session changes, and
left alone by other communities' issuance. The account client records a
403's hint only for the acquisition whose own request was refused
(`BuilderlabAccountClient.observingRefusals`), so an unrelated account
call, such as the organization key backup, never supplies a sign-in's
hint. When the offset is over 115 s, the reconnect and organization
banners add "Your device's clock looks about N minutes off, which can
cause this. Check your date and time settings."
- iOS `BuzzRelayAssertionIssuer`: the same lifetime rule, on
`systemUptime`. An assertion without a readable `iat` is refused.
- iOS push enrollment: a new grant's window starts 120 s in the past, so
`not_before = now − 120` and `expires_at = now − 120 + lifetime`. A fast
phone then neither signs a `not_before` the gateway hasn't reached nor
goes over its 30-day maximum. A resumed journal resubmits the
installation expiry it already attested, byte for byte. The delegation,
which is signed fresh each time, expires at the earlier of that expiry
and `not_before + lifetime`, so a journal written by an older client on
a fast phone still gets a grant the gateway accepts. The saved grant
records the delegation's expiry.
- Flutter and iOS already sign a fresh proof with a `nonce` on every
issuer attempt, so their retries needed no change.

**Specs:** NIP-FA proof bounds (120 s old / 120 s future), plus NIP-FI
Git (`±120s`), media freshness, the media read residual and the media
trace row.

`desktop/` is untouched.

Not exercised live: Git clone/push, audio join and push delivery with a
skewed client clock.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-16 12:17:14 -05:00
klopez4212
a82d596fc2 mobile: show account communities in the switcher and sync saved destinations (#9262)
## Summary

Switch Community currently shows only device-saved communities, leaving
account destinations behind a separate Find step. It now merges saved
communities with supported account destinations directly, keeps Add
Community, and removes the redundant Find action from that Add route.
Initial onboarding and identity recovery keep their discovery entry.
Find lists supported account addresses before hosted identity setup;
hosted selection still performs binding, backup, and admission, while
external selection opens the existing identity flow.

Mobile also saves QR/address additions and explicit removals through
Builder Lab's existing known-communities account APIs. A per-account
local journal retries transient failures, survives restarts, pauses in
the background, and fences requests against account changes. External
secure addresses use the existing self-hosted entry flow; account
destinations never imply membership or bypass admission. Remote list
omissions do not delete local identities.

Explicit additions store an account owner and revision atomically with
local credentials. Legacy/unclaimed destinations remain local-only until
explicitly added while signed in; signing into another account never
claims retained destinations. Restart reconciliation lets a committed
re-add supersede an older removal even if the retry-journal write
failed. Local deletion and its credential-free account-removal intent
commit in one storage write, independent of the account-only retry
journal. Removing one of several local identities owned by the same
account at an address retains its account destination until that
account’s last identity is removed. Another account’s saved identity
does not block removal or lose its credentials during recovery. Offline
edits retain the stored account subject without treating it as network
authorization. Discovery-only intent survives browser callbacks, app
restart, and retry. Onboarding recovery controls have a Material
ancestor in the actual route. Pending status is fenced to the current
subject; interrupted older removals offer explicit local completion, and
denied requests offer browser reauthentication. Same-host ports have
distinct labels and confirmations, and unsupported hosted ports are
excluded.

This changes the mobile client and its public-build CI test list only:
no relay endpoints, events, migrations, or backend deployment.

### Related issue

No duplicate found among open known-communities/switcher issues and PRs.
Related picker editing work: #6632 (renaming communities).

### Testing

Validated after merging main (`02535e1b53`) at
`c4ee037f7e710962f176540abf88d26e98c2823c`. Wes’s follow-up fixes cover
push-revocation commit ordering, same-account removal confirmation, and
recovery after completed hosted admission. The merge also preserves
main’s toolbar and session protections; a test override now accepts the
updated relay subscription parameter.

- Formatting, static analysis, and differential file-size checks pass.
- Prior full CI and security review passed on `3adb117aae`; security
checks also passed on `cf3836ecb`. Fresh CI and security review are
required for this head.
- Mutation checks fail when either the initiating-account removal guard
or the rendered-status subject fence is removed; both guards were
restored before final validation.
- CI explicitly runs the public-only account discovery and
synchronization journeys.
- Added journeys cover paused removal across A→B, offline restart,
journal read/write failures, duplicate local identities in either
removal order, delayed status reads across accounts, real browser
handoff after denial, unbound external discovery, and local same-host
port removal.
- Earlier journeys cover pairing acknowledgement and restart after
journal-write failure, same-subject setup completion, offline/rejected
removal with reopen/retry, and fresh external-only/mixed account entry.
- Regression coverage includes discovery deduplication and retry, hosted
and external selection, Add without Find, account-only removal, shared
authentication/removal persistence, restart recovery, latest-intent
ordering, account changes, and retry pause/resume.
- `just mobile-check`, `just file-size-check`, and `just mobile-test`:
4,954 default-build tests passed (71 skipped), plus 27 crypto-package
tests.
- Full public-account suite: 5,012 passed, 12 skipped, one pre-existing
failure in `fullscreen_onboarding_test.dart` ("Home stays hidden until
community choice and admission"). The same assertion was reproduced on
clean base `8cce12f591`: expected both communities imported, actual only
the selected community.
- Follow-up regression journeys cover both A/B same-address removal
orderings, recovery preserving B’s saved key, the production onboarding
widget composition, and retained discovery intent with callback/retry
plus normal-sign-in controls.
- Native/live-account and human testing remain outstanding. The tests
use fake network/storage boundaries; live account API behavior,
cross-device synchronization, native accessibility, and
timeout/late-server-commit ordering still require integration
verification.

- The three expanded recovery/removal journeys pass and each fails when
the corresponding fix is removed. A durably journaled revocation now
finishes the confirmed removal even if the account changes during
journaling; pre-journal account mismatches still abort. Confirmation
copy counts only same-account identities. Explicit account recovery
retires a completed join target while preserving in-progress targets.

### Preview

Sample-data Flutter widget renders: saved-only and combined lists. These
illustrate the picker layout, not a device session or live account sync.

| Saved-only | Combined |
| --- | --- |
| ![Saved-only
picker](https://github.com/user-attachments/assets/eeadbd28-5ef0-4bc1-a381-8fdf71563144)
| ![Combined
picker](https://github.com/user-attachments/assets/58080884-82c2-4538-8d9d-54eb95218d81)
|

### Manual verification

1. Sign into a public account with a community saved on another device.
Open Switch Community; verify it appears alongside local choices and
Add.
2. Select a hosted and an external community; verify the existing
identity/admission flow opens. Add should not offer Find again.
3. Add a community by QR/address, then check the account list on
desktop. Remove it on mobile and verify the account entry disappears
while other devices retain their local credentials.
4. Repeat removal offline, restart, then reconnect/resume. Verify the
queued removal reaches the account service without switching identities.
5. On a fresh device, verify external-only and mixed account lists offer
external entry. Check two ports on the same host remain distinguishable.
6. Sign out of account A and into B; retained A destinations must not
upload to B. Explicitly add a B destination and verify it syncs.
7. Reject or interrupt account removal; verify visible pending/failure
status. A denied session must open browser sign-in through “Sign in
again” and retry after exchange; setup-required accounts retain their
setup action.
8. Keep two local identities owned by the same account at one address;
removing the first must keep the account entry, and removing the last
must queue account removal. Repeat with A and B at that address;
removing A must preserve B’s saved credentials and still sync A’s
removal.
9. Restart offline with a stored account, add/remove an external
community, then reconnect as the same account and verify convergence.
Explicit sign-out must not claim new local-only entries.


10. Start Find my communities, restart during browser authentication,
then return or retry. External destinations must appear before hosted
identity setup; normal sign-in must retain its identity checks.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
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@localhost>
2026-11-15 15:07:56 -08:00
Tom Brow
02535e1b53 perf(mobile): stop replaying stored read state on every resume (#9090)
Every time the mobile app reconnects (for example after more than 5
seconds in the background), the read-state live subscription asked the
relay for up to 500 stored read-state events. That re-downloaded every
read-state slot on the account, then the snapshot fetched the same
events again right after. On a heavy account (28 slots) that replay
alone was about 1.4 MB per resume.

The live subscription now uses `limit: 0`, so it only delivers changes.
It still opens before the snapshot, so the snapshot covers anything
published in between.

The subscription can also go live after `subscribe` has returned: on a
cold start with slow AUTH, `subscribe` returns on its 500 ms fallback
before the REQ is registered, after a transient CLOSED (rate limit,
capacity) the session reopens it on the same socket, and a reconnect
replays it. With `limit: 0` nothing replays marks published in that gap,
so the manager reads the snapshot every time the subscription reports
ready, as the channel list's `limit: 0` subscription already does.

The session keeps live subscriptions across reconnects and replays them
on the new socket, so a reconnect no longer resubscribes: the replay's
ready reads the snapshot, once per reconnect. The manager opens a new
subscription only after losing one (a terminal CLOSED or a failed
subscribe), on the next reconnect.

All snapshot reads outside a publish go through one sync loop.
Initialize and each ready ask that loop for a snapshot. A request made
before the current pass starts its read joins that read, and a request
made during the read runs one more pass, so a ready can't be swallowed
by a read already in flight. This needs no generation or
ready-transition checks, at the cost of an occasional extra read (for
example a cold start whose ready lands after the 500 ms fallback, when
the first read has already started).

Snapshot reads are numbered in start order, including a publish's own
read, and only a read newer than every settled one decides whether the
last snapshot succeeded. An older read finishing late cannot clear the
retry a newer failed read needs. A failed read waits for the next
trigger: the publish it schedules, which reads the snapshot in full
after a failure, or a later ready, resume or reconnect.

A publish with nothing to send skips its snapshot ([#9093 skip redundant
publish](https://github.com/block/buzz/pull/9093)) only when the last
snapshot succeeded, so after a failed resume snapshot the next publish
still retries it. A publish snapshot now notifies readers of the marks
it merged, since unchanged slots publish nothing whose echo would.

### Accepted gap

If the snapshot fails (timeout, discovery or HTTP error) on a device
with no local journal, read state stays local until the next successful
snapshot, which every resume, reconnect, subscription recovery and
publish retries. Falling back to a stored replay on failure would close
the gap, but it adds a late subscription path for a rare failure that
already heals on its own.

### Validation

- Added test: `live subscription replays nothing and opens before the
snapshot`. It fails without the change (`limit` 500).
- Added test: `a clean reconnect through the real session replays one
REQ and reads the snapshot once, and a lost subscription is reopened`
drives the real `RelaySessionNotifier` with a recording socket: the
connected listener runs, then the session's replay, then EOSE. It fails
against the previous revision of this PR (two `l-2` REQs and two
snapshot reads per reconnect). After a terminal CLOSED, the next
reconnect opens a new subscription and reads the snapshot.
- Added test: `readies during a held snapshot read share one more read`.
- Added test: `a mark published while the live subscription retries is
read once it recovers` puts the subscription into retry, lets another
device publish a mark, then reports it ready. It fails without the read
on ready.
- Added test: `a failed late-ready read is retried by the next publish`.
It fails without the retry.
- Added test: `a reconnect while the first snapshot downloads is not
swallowed by the cold-start connect` lets the cold-start connect queue
behind initialize, then reconnects while the first read is still
downloading and has a peer publish a mark. It fails against the previous
revision of this PR (the queued pass swallowed the reconnect) and passes
with the sync loop.
- Added test: `an older snapshot finishing late keeps a newer failed
read's retry` holds a publish's snapshot read, fails a newer read, then
lets the older one finish. It fails against the previous revision of
this PR (the older success cleared the retry) and passes with the read
ordering.
- Added test: `a mark published before a slow cold-start REQ goes live
is read then` lets `subscribe` return before ready, publishes a mark,
then reports ready. It fails without the read on ready.
- `a publish after a failed snapshot retries it, then skips again`
replaces the earlier skipped-publish test and fails without the snapshot
check. It also checks that the retried snapshot's new marks notify
readers, which fails without the notify.
- Read-state suite (95 tests), `flutter analyze` and the full mobile
suite pass.
- iPhone 12 mini, Profile build with [#9089 gzip
snapshot](https://github.com/block/buzz/pull/9089) applied, Home
backgrounded 12 s and resumed, websocket bytes received in the 15 s
after resume:

| | Websocket in | Read-state replay |
| --- | --- | --- |
| Before (gzip fix only) | 2,087 KB | 1,458 KB (28 events) |
| After (gzip fix + this) | 575 KB | none |

The table counts websocket bytes only. Each resume reads the read-state
snapshot once over HTTP, before and after this change.

Automated app run on the same phone: Home, a large channel and search
resumed after the reconnect grace period, with no read-state errors
logged. Read marks were not compared across devices.

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

---------

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>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:09:18 -07:00
Tom Brow
1a5c6939c5 perf(mobile): save the open-channel directory and catch it up (#9513)
Search and invite recovery read a community's open-channel directory
(every open, listed channel's kind 39000 metadata) from the relay, and
match names on the device. Until now the app kept that directory in
memory for 30 seconds only, so every search session after that, and the
first search after every launch, downloaded the whole directory again.
This follows [#9466 directory-only search
load](https://github.com/block/buzz/pull/9466) and [#9457 directory
keeps message times](https://github.com/block/buzz/pull/9457), which
made each of those downloads cheaper; this one makes most of them
unnecessary.

Now the directory is saved in a file per community and account, next to
the image cache, and search reads it from there:

- **What's saved.** Only the latest revision of each open, listed,
non-DM channel. The relay's directory read also returns the user's own
private, unlisted and DM channels; those are never held or saved as the
directory, and a channel whose latest revision is no longer discoverable
drops out.
- **First read.** The first time search opens, the app downloads the
whole directory, as before, and saves it.
- **Catch-up.** When search opens later, it shows the saved copy at
once. At most once a minute, it asks the relay in the background only
for directory changes since the newest saved one, or since the last read
started by the device clock if that is earlier (less a minute of
overlap), and merges them in. The relay can stamp a busy channel's
metadata minutes ahead of wall time, so the newest saved stamp alone
could skip channels created meanwhile. A catch-up that brings back
nothing new saves nothing and leaves the list alone, and a search opened
while a background read is still running shares it rather than starting
another.
- **Offline open.** A search opened before the session connects shows
the saved copy and runs its check on the next connect.
- **Daily full read.** Once the last full read is a day old (or dated in
the future, by a clock since set back), the next check downloads the
whole directory in the background and replaces the saved copy, which
drops channels that became private or unlisted or were deleted. A
catch-up can't see those: the relay never serves them to a non-member.
- **Gone on open.** Opening a saved result that the relay no longer
serves (private or deleted) drops it from the directory at once, and no
directory read already in flight (background check, list refresh or
Retry) brings it back. A restore from disk never overrides a full read
already running, and a background read never displaces one.
- **Invite recovery** still downloads the whole directory, as on main:
it needs fresh memberships, and its read also refreshes the saved copy.
- **Cleanup.** Signing out of a community, replacing its account, or
leaving it deletes the file.

The saved events omit signatures (the relay signed them; the copy is a
cache of what it served). The file's JSON is encoded and decoded off the
UI isolate, and an unavailable caches directory (or one that takes over
3 seconds) just means no saved copy. A file that is unreadable, from
another version, or over 20,000 channels or 16 MiB is discarded and read
again from the relay. There is no relay change. `CONTEXT.md` gains an
"Open-channel directory" entry.

### Validation

| Workflow (small community, 63 open channels) | Directory bytes before
| Directory bytes after |
| --- | --- | --- |
| First search after install | 39.5 KB (2 requests) | 39.5 KB (2
requests) |
| Search again 2 minutes later | 39.5 KB (2 requests) | 0.6 KB (2
requests) |
| Relaunch, then search | 39.5 KB (2 requests) | 0.6 KB (2 requests) |

Measured on an iOS simulator signed in to a test community, with a
temporary local counter on each relay query response (not part of this
PR), main at
[6974237](69742376a9)
vs this branch. The full read grows with the number of open channels
(about 600 bytes each); the catch-up grows only with what changed.
Search results were identical on both builds, and opening an unjoined
result from the saved directory still showed its preview with Join.

Tests:

- A journey test drives the real channel list against a fake relay that
honors `since`, with a real file and a fake clock: the first reader
saves the directory without signatures; more readers within a minute ask
nothing; a minute later a reader asks only for changes since the newest
saved one less a minute; after a relaunch the saved copy serves at once
and the catch-up starts from it; a channel that turned private stays
until the daily full read replaces the copy; the search status never
shows loading for the background reads; a catch-up of only held events
leaves the list identical and the file unwritten; a second search a
minute into a slow full read shares it; and opening a channel the relay
no longer serves drops it, even with a read in flight. Each guard was
checked by breaking it: removing the once-a-minute limit, dropping
`since`, never doing the full read, merging the full read instead of
replacing, removing the drop-on-open, the no-change check, the shared
in-flight read, or the in-flight drop fence each fail the test.
- Focused cases against the same fake relay and real file, each checked
by breaking its guard: member-only private, unlisted and DM metadata is
never saved, and a saved channel that turns private drops out on
catch-up; a catch-up starts no later than the last read's start, across
a relaunch, so a channel created after a burst-stamped one is found; a
full read or check dated in the future by a clock set back is due; a
search opened before the session connects checks on connect; a restore
leaves a running full read's status alone and is not displaced by a
catch-up; a list or Retry full read in flight does not bring back a
channel dropped on open.
- Storage tests: the round trip omits signatures; unusable data is
discarded; a directory over the bounds leaves no stale copy; a closed
store neither reads nor writes; cleanup keeps only each community's
current account and its save in progress.
- The community test now also checks that replacing an account deletes
the old account's saved directory (fails without the cleanup call).
- Full mobile test suite and `flutter analyze` pass.

No visible change, so no screenshots: the same results appear, just
without a download on later searches.

### Regressions

- A channel that turns private or is deleted can still appear in search
for up to a day, until the daily full read, unless you open it (the
first open in a session asks the relay, drops it at once, and the relay
withholds its content). A channel already previewed earlier in the same
session reopens from its cached details without asking the relay, so it
stays until the daily read or a relaunch. Before, it disappeared from
the next search at least 30 seconds later.
- A channel that turns unlisted can also appear in search for up to a
day. Opening it does not drop it, and its content stays readable,
because the relay serves an unlisted open channel to anyone who names
it.
- A channel created while search is open appears the next time search
opens, not while it stays open. That was already the case within the
30-second window.
- The saved file costs some disk per community (about 30 KB for 63
channels, roughly 0.5 KB per channel), deleted on sign-out or leaving.

---------

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-15 12:31:58 -07:00
Tom Brow
5b92e02e2a fix(mobile): sign out from Settings in every build, keeping keys on the device (#9421)
Public and Nostr-only builds had no way to sign out. The only route was
Switch community → Edit, remove every community, then tap Back to get a
"Sign out of BuilderLab?" prompt. Removing a community that way also
deletes its key from the phone, even when the user never exported or
backed it up.

Settings now ends with **Sign out** in every build (internal builds
already had it). After confirming:

- Each community's key is first copied into this device's saved
identities, the same thing internal Sign out already did. Sign-in offers
them again, so signing out never destroys a key that may exist nowhere
else. If saving fails, nothing is removed.
- In a public build, the Builderlab session ends next, before anything
is removed. The Sign in landing that follows never shows the old
session, and nothing started there can be cancelled by it. If the
session or a pending browser sign-in can't be cleared, including a saved
session not yet restored after launch, Sign out stops with an error and
keeps every community. Ending the session never waits behind a pending
account request, such as a stalled session check at launch, and no such
request can restore the session once it finishes later. This path never
shows the hosted setup page over Settings. The removed communities'
push-lease tombstones still publish afterwards: the outbox authenticates
them with the push-stop credential the session leaves behind for 10
minutes, including a saved session that was never restored (an offline
launch), even when a first cleanup attempt failed partway.
- Every community is removed, the active one last, so removing the
others never switches to (and connects) another community on the way
out.
- A Sign out failure now shows its error in Settings. The row used
Settings' outer context, so the snackbar went to the page underneath.

Nothing else changes: the switcher, per-community Remove and the
onboarding landing's Back → "Sign out of BuilderLab?" path behave as
before. Internal Sign out keeps its behavior (one community, key kept,
the landing then ends the organization session). The only new UI is one
row at the bottom of Settings.

| Before | After |
| --- | --- |
| <img width="300" alt="before"
src="https://github.com/user-attachments/assets/f49f7869-3401-4e05-aa7b-debe7a7d425c">
| <img width="300" alt="after"
src="https://github.com/user-attachments/assets/99731c6a-035e-447b-987a-7fa0d8e767cc">
|

Demo (public build, simulator): Sign out → confirm → back at the Buzz
landing, signed out of Builderlab.


https://github.com/user-attachments/assets/da64082b-3b73-46d0-8578-771fca7dec22

### Validation

- Added tests: `settings_sign_out_test.dart`, a Settings journey with
two communities whose keys aren't backed up. Cancelling keeps
everything. Confirming removes both (active last) and both keys end up
in saved identities. The root swaps Settings for the real
`OnboardingAppEntry` as the app does. The authenticated root is wrapped
in the real `HostedAppGate`, and no route may be pushed while Sign out
runs. In a public build it fails three ways, each showing the error in
Settings and removing nothing: a saved session that isn't restored yet
can't be deleted, a restored one can't be deleted, and a pending browser
sign-in can't be cleared. Then, with revocations held pending, the
landing appears with the session already gone and no "Signed in as", and
releasing the revocations changes nothing. It runs in the default lane
and in the CI public-build lane (added to `_ci-clients.yml`). Confirmed
it fails when the key save is removed, when the session ends after the
landing appears, when sign-out goes through the flow's published stages,
when a failed clear is detected only by a missing in-memory session,
when a browser cleanup failure is swallowed, and when the error goes to
the page underneath.
- `organization_relay_auth_test.dart`: a push stop still gets an
assertion after signing out a saved session that was never restored,
including a failed cleanup followed by a successful retry (fails without
the fix).
- Sign-out never waits on a pending account request: the Settings
journey holds `/v1/auth/me` during the final sign-out and checks that
its later completion restores nothing (without the fix, Sign out stalls
and both communities stay). `builderlab_account_test.dart` covers a
session check already pending, one that starts while the session is
being deleted, an exchange queued before the sign-out, and an account
request during the removal that must not share the credential with the
notification extension again.
- Focused existing validation: `internal_build_entry_test.dart` with the
internal-build defines passes.
- Full `just mobile-test` (4,848 passed, 74 skipped) and `just
mobile-check` are clean.
- Automated app run at
([d36150c](d36150ccaf)):
fresh iPhone 17 Pro simulator, public-build Debug signed in to a
Builderlab community. Opened Settings from the community menu (Sign out
is the last row), confirmed Sign out, and landed on the Buzz landing
(Scan a QR code / sign in with email) with no community and no
Builderlab session, and no hosted setup page in between. The screens
match the demo above, which was recorded at an earlier head. Re-signing
in through Builderlab wasn't exercised in the simulator; the journey
test covers the saved identities that sign-in offers. Later commits
change only session-clearing internals, and the tests above cover them.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-15 19:31:04 +00:00
Tom Brow
a4cac9a2d1 fix(mobile): slide a closing chat away instead of cutting to the list (#9511)
On iPhone, tapping back from a chat (or finishing a back swipe) cut
straight to the chat list with no slide. This affects every chat opened
in a compact conversation pane: Home channels and DMs, Solo chats,
Search and Inbox.

### Cause

Since the nested conversation navigator landed, popping a detail clears
the pane's selection when the pop starts (Flutter reports the removed
page right away, before the reverse transition). The pane then put the
detail navigator offstage and stopped its tickers in that same frame, so
the reverse slide ran invisibly and the list appeared at once.

### Fix

The pane counts mounted detail routes. A popped route keeps its content
mounted until its reverse transition ends, so the detail stays onstage
and ticking until then. The selection still clears at the start of the
pop, so nothing else about the pop changes (the list is uncovered and
its toolbar returns as before).

### Regressions

- Wide layouts (iPad, Duo) are unchanged: their detail was always
onstage.
- No extra rebuilds: the count drives only the detail's visibility and
tickers, so opening or switching chats builds the chat screen as often
as before (checked with a build-count test in compact and wide layouts).
- Reopening a chat while the previous one slides away behaves as before:
the new chat covers the list.

### Validation

- Added steps to the existing iPhone back test: the chat is still on
screen mid-pop after the back button and after a completed back swipe,
then gone once settled; reopening mid-pop shows the reopened chat. The
mid-pop step fails without the fix.
- Full mobile suite, analyze and format. One unrelated media-placeholder
test (`message_skeleton_geometry_test.dart`) failed once while two iOS
builds loaded the machine, and passed on rerun.
- Simulator run (iPhone 17 Pro, debug build, signed-in test community):
Home list, open a Solo chat, back button, reopen, back swipe. Before on
the left, after on the right.


https://github.com/user-attachments/assets/a5b88c2b-dc86-4345-8a88-29142a0bf7dc




buzz-review-completed

---------

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-15 08:20:01 -08:00
Tom Brow
11ea8c928e perf(mobile): skip avatar URL parsing for non-HTTP URLs (#9448)
Every avatar build checks its URL: `parseAnimatedAvatarUrl` scans for
the `#buzz-anim=` fragment and parses both halves, and
`usesInsetAgentArtwork` also runs `Uri.tryParse` and a regex. For an
ordinary URL that's a few microseconds. Some profile pictures are
`data:image/png;base64,...` URLs, though, and those cost about 0.7 ms
per check for 100 KB on a Mac, because the fragment search and `Uri`
normalization read the whole string. Channel screens, the native
navigation bar payload and the DM header portrait run these checks on
every build, so a channel with such members pays for them frame after
frame.

Both functions can only answer yes for an HTTP(S) URL, so they now first
look at the first six characters and return early unless the URL starts
with `http:` or `https:` (in any case). A data URL is turned away
without reading the rest of it. The authority is still checked by `Uri`
as before, which also accepts backslashes there (`https:\\host`).

### Validation

Added test pinning the answers this check must keep: an `https://`
preset poster is inset artwork in any case and with backslash
authorities (`https:\\`, `https:/\`, `https:\/`), while `http://`, a
leading space, a data URL, an empty string and null are not; an animated
avatar URL still is. Existing animated avatar tests (including a
data-URL poster with a `#buzz-anim=` fragment) pass; full mobile test
suite and `flutter analyze` pass.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build), opening a channel whose members include two data-URL
avatars (100 KB and 150 KB): over the first 7 seconds, the CPU profile
spent 69 ms in these checks before this change and none with it (0 of
647 samples).

### Regressions

None expected. Every URL the new check turns away already got the same
answer before: `_isHttpUrl` and the preset check both need scheme `http`
or `https`, which `Uri` only reports for a string that starts with
`http:` or `https:` (it lowercases the scheme, so case doesn't matter,
and a leading space already parsed to no scheme). Reviewers compared the
old and new functions on several thousand generated URLs (case,
whitespace, IDN, punycode, backslash forms) and found no differences.

---------

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-13 14:40:11 -08:00
Tom Brow
5e52fa9831 perf(mobile): download the identity archive list only when it changed (#9445)
Every reconnect refetches the community's identity archive list (kind
13535) so the agent pickers stay current. On Block's Builderlab that
list is about 228 KB, and it is downloaded again on every resume even
though it rarely changes.

The provider now remembers the last verified list per community and
relay authority, and asks the relay only for a newer one (`since` the
known list's `created_at` plus one). When nothing newer exists it reuses
the known list, as the same set instance so watchers (mention
candidates, search, the Agents page, channel details, the members sheet)
don't rebuild. A newer list replaces it after the same verification as
before. A list that fails any check, including its signature, yields no
archived identities and drops the remembered one.

### Validation

Provider tests: a refresh with an unchanged list sends `since`, keeps
the known set and leaves the hidden set's listeners untouched; a newer
list replaces it and becomes the new baseline; every invalid list (wrong
signer, missing `-` marker, bad signature) starting from a warm cache
drops the remembered list, so a following empty answer hides nobody.
Each new step fails with its fix reverted. The existing verification,
community-switch and deadline tests pass with the relay fake now
honoring `since`. Full mobile test suite (4803 passed) and `flutter
analyze` pass.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build), a resume after 60 s in the background downloaded the 228
KB list each time before this change.

### Regressions

**Accepted tradeoff: a same-second list can be missed.** The cursor
assumes each list the relay publishes is stamped strictly later than the
previous one. The relay nearly always does this
(`publish_nipia_archival_list` stamps past the current head and
republishes on drift), but two lists published within one second can
share a `created_at`, and NIP-IA then keeps the one with the lower id.
If the app already holds the other one, it misses the replacement until
a later list arrives (the next archive or unarchive) or the app
restarts. Meanwhile a just-archived or just-unarchived agent can show
wrongly in pickers and search, never in history. We accept this for the
bandwidth and resume-time win; a relay follow-up that stamps each list
under the replacement lock and makes the rule a NIP-IA MUST removes the
case.

The same bound applies if a relay's database is restored to an older
list: the app keeps its newer one until the relay publishes a list newer
than it, or the app restarts.

A failed or timed-out fetch still hides nobody, as before.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-13 14:40:06 -08:00
Tom Brow
99e65b6c22 perf(mobile): read channel bot roles from the member list (#9451)
Every channel view read the channel's member roster (kind 39002) twice:
once for the member list (`channelMembersProvider`) and once for bot
roles (`channelBotPubkeysProvider`, which feeds agent mention styling).
Both sent the same `kinds:[39002] #d:[channel] limit:1` query, and both
re-ran it on every roster update. Screens that show messages from
several channels did this per channel: opening Activity read 10 rosters
twice each.

Bot roles now come from `channelMembersProvider`, so each channel's
roster is fetched once. While the relay is disconnected, bot roles now
come from the member list's last loaded roster instead of going empty,
so agent mentions keep their styling offline.

### Validation

New test: watching both the member list and bot roles for a channel
fetches the roster once and both report the bot. It fails without this
change (two fetches). The existing bot-role tests (live updates,
subscription cleanup, working bots) pass unchanged. The channel page
test for a bot-role replay used a fixed member list alongside live bot
roles, which can no longer differ; it now reads both from its fake
relay. Full mobile test suite and `flutter analyze` pass.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build), opening Activity right after launch read 10 channel
rosters once each (25.7 KB) instead of twice (51.5 KB), and opening a
channel read its roster once instead of twice. Agent messages kept their
agent styling. The same automated run covered cold start, opening and
scrolling Activity, scrolling the home list, opening
buzz-mobile-tomb-review (a channel with agent members) and returning
home.

### Regressions

None expected. Bot roles now refresh when the member list does (on
roster updates and after a reconnect) rather than on every relay session
state change, which only drops redundant refetches.

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-13 14:33:41 -08:00
Tom Brow
b6db61faa0 perf(mobile): stop rebuilding the native nav bar on every scrolled frame (#9458)
On iOS, `FrostedAppBar` built its native `IosNavigationBar` inside the
`ValueListenableBuilder` for the page's scroll offset, so every scrolled
frame rebuilt the bar. Each rebuild `jsonEncode`s the whole native
payload to see whether it changed, and that payload carries the header's
avatars: base64 image data, and the data URLs of people whose profile
picture is one (100 KB or more each). The bar already follows the offset
itself, through its own listener that sends `scroll` to UIKit, so none
of that work was needed.

The bar is now built once per `FrostedAppBar` build, outside the offset
builder. Scrolling still rebuilds the positioned frame around it (its
height follows the large title), but passes the same bar widget, so
Flutter skips it.

### Validation

New test: scrolling a `FrostedScaffold` page leaves the same
`IosNavigationBar` instance in the tree. It fails without this change.

Full mobile test suite, `flutter analyze` and the file-size check pass.

On the iPhone 12 mini (profile build, Builderlab), opening a busy
channel whose header shows member avatars, and scrolling history with 10
swipes (about 30 seconds):

| | `IosNavigationBar.build` (CPU samples) | BUILD total | LAYOUT total
| UI frame time total |
| --- | --- | --- | --- | --- |
| Before | 1,581 ms | 3,304 ms | 3,514 ms | 7,013 ms |
| After | 0 ms (no samples) | 591 ms | 748 ms | 4,718 ms |

The remaining long frames (up to 130 ms) are older history loading in,
and are the same before and after. The automated run covered a cold
start, search, opening the channel from a search result, and scrolling
its history.

### Regressions

None expected. The bar's inputs don't depend on the offset; only the
frame's height and animation duration do, and those still update per
frame.

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-13 13:40:53 -08:00
Tom Brow
93bbd452a7 perf(mobile): keep verified-name batches open as people are added (#9450)
Verified names are read in subscriptions of up to 128 people. Each time
someone new was tracked, the batches were rebuilt from the whole tracked
list, so the last partial batch got a new identity, was closed, and was
reopened with everyone in it plus the newcomer. Profiles show up a few
at a time (search results, channel members, mentions), so the same
records were read again and again. Past 1,024 tracked people, each
newcomer evicts the oldest, which shifts every batch boundary, so every
batch was closed and all 1,024 records were read again.

Now an open batch stays open as long as all its people are still
tracked. Newly tracked people get a batch of their own. A batch that
loses someone to eviction, or that the relay retried, is replaced as
before, and so is a batch whose person was evicted and tracked again
before the batch was re-checked, so their check mark and cached name are
re-read. Once four batches are smaller than 128, the next addition
merges the smallest of them with the newcomers until they fill a batch
(at least one, so no fifth small batch appears). The subscription count
stays within four of the minimum, and a merge re-reads at most 128 plus
the largest small batch.

People already checked also stay checked while a newcomer's batch opens;
before, the reopened batch briefly unchecked them.

### Validation

New tests: tracking one more person opens a batch with only that person,
and the people already checked stay checked throughout; with four small
batches of 64 open, one more person merges two of them into a full batch
and leaves the other two open; a large addition past four small batches
still retires one; tracking one more person at the 1,024 limit re-reads
only the batch that lost the oldest person; a person evicted and tracked
again before the sync is re-read and checked; and a re-tracked person
keeps their verified name when the cached-name limit trims it. Existing
batch, eviction, retry and reconnect tests pass unchanged (one comment
updated). Full mobile test suite and `flutter analyze` pass.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build of e2fb02c), opening search and typing "presence" after
opening a channel and a thread: verified-name reads went from 21
subscriptions and 328 KB before this change to 11 and 88 KB with it
(counted per subscription opened; the first revision measured the same
way gave 11 and 90 KB).

The same automated run covered cold start, opening the-squad and one of
its threads, search with the People filter, opening buzz-mobile's
details and scrolling its full 86-person member list, and a 60 s
background then resume (the resync re-read 2 batches, 65 KB). Names
rendered throughout.

### Regressions

Up to four more open subscriptions while small batches accumulate, each
held open by the relay like the existing ones. A community with under
128 tracked people now has up to five instead of one. No merge policy
reads less than the old slicing on every sequence of additions. In a
model of 3,000 random tracking sequences, this one read more records
than the old code in about 1 sequence in 500, by at most a quarter.

---------

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>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-13 13:40:36 -08:00
Tom Brow
9fc2b33320 perf(mobile): read only changed custom emoji sets on reconnect (#9446)
Once anything has read the custom emoji palette (opening any channel
does), every reconnect refetches every member's kind 30030 emoji set. On
Block's Builderlab that is 123 sets, about 1 MB, on every resume, though
the sets rarely change. The provider also watched the whole session
state, not just its status.

The palette now keeps the sets it has read per author and, on a
reconnect, asks only for sets written since shortly before the previous
read (`since` reaching back `relayCrossDeviceSkewSeconds`, the window
the unread catch-up already uses for events other devices write). A
newer set replaces the known one for its author, with the relay's order
for a same-second tie (the lower event id wins); the palette is the
union as before, recomputed only when a set changes, so a reconnect that
brings nothing new republishes the identical list and rebuilds nothing.
A community or account switch (a new relay client) starts over with a
full read.

Two side benefits: the loaded palette stays visible while disconnected
(before, it was empty until the full read finished, so `:shortcode:`s in
visible messages briefly showed as text on resume), and the palette no
longer refetches on every reconnect attempt during backoff, only on
status changes.

### Validation

Added test: the first read has no `since`; a reconnect with nothing new
sends a `since` and keeps the palette as the identical list; a new
member's set and a replaced set both arrive in the window and update it;
a same-second replacement wins with a lower id and is ignored with a
higher one. It fails without this change. Existing emoji picker tests
pass; full mobile test suite and `flutter analyze` pass.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build): after opening a channel, a resume after 60 s in the
background downloaded the 1 MB of sets again (kind 30030, 123 events).
With this change the same resume sent the read with a `since` and got no
events back, so the 1 MB was not downloaded again; the first read when
opening the channel is unchanged (123 sets, 1 MB).

### Regressions

A set removed with a NIP-09 deletion (rather than replaced) stays in the
palette until the app restarts, since a deletion isn't a newer set. Buzz
clients edit a set by replacing it (desktop removes a shortcode by
republishing the set), so that only affects other clients, and desktop's
emoji directory keeps deleted sets the same way. A set written by a
device whose clock is more than 30 minutes behind is missed until
restart, the same bound the unread catch-up accepts.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-13 13:40:32 -08:00
Tom Brow
a540e7bd30 perf(mobile): don't refetch profiles that are already on the wire (#9447)
`UserCacheNotifier.preload` skipped profiles already queued but not ones
already on the wire. Opening a channel preloads the same people from
several places (compose bar, DM header, member list); a preload that
arrives while the first batch is in flight queues those people again,
and the next batch downloads their profiles a second time. On Block's
Builderlab, opening one channel sent the same 77-author kind 0 request
twice, 521 KB each.

A preload now leaves out profiles whose batch is in flight and waits for
that batch instead. Only profiles that are neither cached, queued nor in
flight start a new batch.

### Validation

Added test: while a batch for `a` and `b` is on the wire, preloads for
`b` and for `b, c` send one more request, for `c` only, and all three
preloads complete once their profiles arrive. It fails without this
change (the second request asks for `b` again). Existing user cache
tests pass; full mobile test suite and `flutter analyze` pass.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build), opening two channels in a row: before this change the
second channel downloaded its 77 members' profiles twice (1,019 KB of
kind 0 events), and the first downloaded its 43 twice (50 KB). With it,
each downloaded them once: 509 KB and 25 KB.

### Regressions

None expected. A caller whose profiles are in flight now waits for that
batch instead of a new one, so it resolves no later than before; a
failed in-flight batch reports failure to it, as its own batch would
have.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-13 13:39:51 -08:00
Tom Brow
d1a8c3607d perf(mobile): use HTTP/2 on Android through app-wide Cronet engines (#9435)
Follows #8897 (iOS HTTP/2), now on main.

## What

Android gets the same app-wide shared sessions as iOS, backed by Cronet
(`cronet_http`) instead of `NSURLSession`:

- One Cronet engine per traffic class (API, media), so requests to a
host multiplex over one HTTP/2 connection and gzip is inflated natively,
off the Dart isolate.
- HTTP/2 on, HTTP cache off, QUIC off. QUIC would be a separate behavior
change, and `cronet_http`'s changelog lists DNS failures with QUIC on
cellular.
- Streamed uploads (media and voice notes) stay on `dart:io` on Android:
`CronetClient` reads a request body into memory before sending it, which
would break upload progress and copy large attachments in full.
- If no Cronet provider is available (no Google Play services), the
engine fails to build and the app keeps `dart:io`, as today.
- Transport error classification covers Cronet failures alongside
`NSURLSession` ones, so invite and pairing errors keep their friendly
messages.

## Measurements

Android emulator (API 36, arm64), profile builds of this branch and
main, signed in to the Feedback community. 8 cold starts per build,
alternating builds in blocks of 4. Times are for relay `/query` requests
started in the first 8 s.

| | main (`dart:io`) | this branch (Cronet) |
|---|---|---|
| First query response | 6.99 s | 1.99 s |
| Startup burst settled | 8.36 s | 2.78 s |
| Burst after the first connection | 1.44 s | 0.77 s |
| Query latency after the first connection, median / p90 | 165 / 1567 ms
| 106 / 158 ms |

**Unexplained stall:** most of main's startup gap is a ~5 s stall before
its first response on every cold start. Its cause is unconfirmed; my
guess is `dart:io` loading its CA store on the emulator, which HTTP/2
itself wouldn't fix, so the first two rows likely overstate the win on
real devices. The rows after the first connection exclude the stall and
are the fairer comparison. I also tried emulated EDGE throttling, but
the emulator's throttle did not slow its traffic, so there are no
slow-link numbers yet.

## Regressions

None found. Devices without Play services keep `dart:io`. Cleartext
`http://` requests keep the handle's own `dart:io` client, as on iOS.

## Testing

- Full mobile suite passes (`flutter test`, 4784 tests).
- Automated app run on the emulator: onboarding, Feedback nsec import,
channel and DM list load, and 16 cold starts with request timing. Media
loading wasn't separately exercised.
- No visible UI change, so no screenshots.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-13 13:33:58 -08:00
Wes
59ae028a36 fix(mobile): require Builderlab consent for existing identities (#8823)
Existing mobile identities entering the Builderlab hosted flow now
require confirmation before the app reserves the account’s identity
slot, binds the identity, or uploads its secret key. Cancelling leaves
saved community keys usable and allows another identity to be selected,
including after restart. Imported keys remain tentative until approval;
paired keys remain safely retained outside the account slot.

The confirmation shows the receiving account’s verified email and public
key, explains that Builderlab can decrypt the backup and signed-in
account users can recover it, and discloses that the app cannot change
the linked identity later. **Cancel setup** stops future work without
claiming to undo earlier binding or an upload whose acknowledgement was
lost. The user can sign out; missing account identification blocks
confirmation. Browser-initiated binding uses **Link and continue**, with
explicit bind-only wording and no upload.

Fresh keys generated in the current hosted attempt use ordinary
onboarding without an extra backup prompt. Interrupted attempts without
a confirmed backup ask again; approval is deliberately not persisted or
carried across retries, cancellation, restart, account changes, or a
replaced flow. Confirmed matching backup receipts skip the backup
prompt. Cloud recovery and organization-managed backup are separate
flows and are not changed here; this PR does not resolve server-side
consent or recovery-authorization policy.

Updated against main through `ce42853982` (#9418). Integration commit
`dfb29fe5e7` includes the landed Hickory security fix and the shared
workflow-test/runner repair. The consent implementation is unchanged
from Carl’s reviewed `e11025ebed`; the CI merge preserves its configured
public consent journeys.

Validation at `e11025ebed`: 96 focused tests across eight files passed
with public hosted domains configured; Flutter analysis passed. In an
isolated source/Git/build copy, removing pre-adoption consent, bypassing
the upload gate, and removing stale-confirmation checks each failed the
consent journeys; restoring the code passed. Carl’s independent source
review found no blockers. Mandatory hooks and hosted mobile CI passed,
including both consent journeys in the configured public lane.

Integration validation at `dfb29fe5e7`: 99 focused tests passed; one
additional fullscreen-onboarding test failed its background
community-admission assertion. An isolated clean-main control at
`ce42853982` reproduces the same failure with the same expected/actual
values. All consent journeys passed. Required commit and push hooks
passed, including mobile analysis and the broader default mobile suite.
Hosted CI is green at `dfb29fe5e7` ([run
43320753801](https://github.com/block/buzz/actions/runs/43320753801)).
Security and the previously failing Rust/workflow gates now pass. The
Mobile Checks log confirms both consent journeys executed successfully;
that run has no pending checks.

Review follow-up `ac9ac9be35`, integrated with main `279a31daac` at
current head `1acfd2dff6`, is test-only: the browser journey now
restores a saved account key without a receipt, cancels without binding,
restarts and requires explicit approval before `/verify`. Both consent
journeys passed again after integration using the updated CI settings.
Disabling only the production bind gate in an isolated source/Git/build
copy now fails the added step; restoring it passes. Mandatory
commit/push hooks passed. Hosted CI is green at `1acfd2dff6` ([run
43343333843](https://github.com/block/buzz/actions/runs/43343333843));
no failing or pending checks remain. The Mobile Checks log confirms both
consent journeys executed successfully, including the extended
browser-binding journey. Carl’s latest review on `dfb29fe5e7` found no
production blockers; its recommended test gap is addressed by this
follow-up.

Native-device and human acceptance have not been recorded here; the
author’s ready-for-review setting is preserved.

Try it: with two saved self-hosted keys, connect to Builderlab, select
A, cancel, restart, then select B. Check the receiving account and key
before approval. Repeat with an imported/paired key and a browser bind
link; cancel must not reserve or bind the new selection. After an
interrupted upload, cancellation must describe that earlier effects may
remain. Confirm that ordinary brand-new onboarding has no extra backup
step.

---------

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
2026-11-13 11:55:32 -07:00
Tom Brow
a2d4ba0267 feat(mobile): use HTTP/2 on iOS through app-wide URLSessions (#8897)
On iOS, Buzz's HTTP traffic now uses HTTP/2. Dart's `dart:io` client
speaks only HTTP/1.1, so every feature's client opened its own
connections to the relay, which sits behind Cloudflare and offers
HTTP/2. On a slow link those extra handshakes, and the HTTP/1.1
head-of-line queueing, are a large share of cold-start time.

### What changes

- iOS HTTP goes through two app-wide `NSURLSession`s via
[cupertino_http](https://pub.dev/packages/cupertino_http)
(`lib/shared/http/app_http_client.dart`): one for API traffic (relay
queries, NIP-11, account, admission, pairing) and one for media
(image/video/voice downloads and uploads). Requests to a host multiplex
over one connection per session. Media has its own session so image
bytes can't starve queries on a shared HTTP/2 connection: in prototype
measurements with a single shared session, the channel-list batch query
finished *later* than on HTTP/1.1.
- Callers keep owning and closing their clients; on iOS `close()` leaves
the shared session open. Both sessions are ephemeral with no URL cache
and no cookies, so apart from the protocol (and native gzip, inflated
off the Dart isolate) behavior matches `dart:io`.
- Android, and tests, keep `http.Client()` unchanged, including
`http.runWithClient` overrides.
- Because closing a client no longer cancels a request on a shared
session, the relay query client (both `/query` posts and bounded
snapshot reads) and the dev push-lease fetch abort their request on
timeout instead.
- Non-`https` requests (`http://` media and community icons from other
clients, local dev relays) stay on the handle's own `dart:io` client,
because App Transport Security would block cleartext loads through
URLSession. An HTTPS URL that redirects to `http://` is the one case
that newly fails on iOS (URLSession follows the redirect and ATS blocks
the downgrade); we accept that rather than follow redirects in Dart.
- URLSession failures arrive as `NSErrorClientException`, not
`SocketException`, so pairing and invite-join error messages now also
recognize `NSURLErrorDomain` offline, TLS and timeout codes.
- cupertino_http 3.0.1+ requires native_toolchain_c 0.19 and hooks 2.x,
so `buzz_secp256k1` moves to those. Its build hook compiles unchanged.

### What gets better, and what doesn't get worse

- **Better:** on a slow link, requests reuse one warm connection per
session instead of paying TCP+TLS setup each time, so they complete
where `main` times out (see the table). On Wi-Fi, small queries are
slightly faster.
- **Not worse:** request semantics, caching (none) and cookies (none)
match `dart:io`; Android and tests are untouched; timed-out requests are
aborted so they can't keep using bandwidth on the shared connection;
offline errors keep their friendly messages. The accepted regression is
HTTPS-to-HTTP redirects on iOS, above.

WebSockets stay on `dart:io`. Android (Cronet) is a possible follow-up
using the same seam.

### Validation

Added tests: shared-session handles don't close the session; off iOS the
transport honors `http.runWithClient`; NSURLError code classification;
timed-out relay queries and bounded snapshot reads abort their request;
cleartext requests stay off the shared session.

Focused existing validation: full mobile suite (the only failures are 11
push/notification tests that fail identically on `main` on the same
machine), `flutter analyze`, `buzz_secp256k1` package tests (27/27), and
an iOS release build.

On-device A/B on an iPhone 12 mini against the internal prod relay over
WARP, comparing cold starts of `main` and this branch (profile builds
with local-only request timing, 3 cold starts each):

| | `main` | this branch |
|---|---|---|
| Wi-Fi: first query done (median) | 0.31s | 0.25s |
| Wi-Fi: small-query latency (median) | 0.22s | 0.18s |
| NLC Edge: requests completed in 90s | 0, 0, 0 (29–30 failed) | 12, 14,
16 (5–7 failed) |
| NLC Edge: first request done | never | 6.3–7.0s |

On Wi-Fi the two are about even. Under Edge, every HTTP/1.1 request on
`main` hit its timeout while still opening a connection, and each retry
started a fresh TCP+TLS handshake. The branch reuses one connection, so
queries complete. Connection counts weren't measured on the device,
since no proxy was in the path.

Cold-cache demo on an iOS simulator (this branch, app caches and cached
prefs wiped before launch): avatars, community icons, channel lists,
public channel images, a DM image and custom emoji, video playback,
reactions, and an image and video upload with progress all load. The DM
image and clip are synthetic test media.


https://github.com/user-attachments/assets/039d1a25-46f2-4e0e-b147-f96d0cfabd40

buzz-review-completed (agent review and device validation done; the
human-test step is not applicable under Tom's standing exception for
mobile changes)

---------

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>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:48:58 -08:00
Tom Brow
41587e0284 feat(mobile): render messages with gpt_markdown 1.3.4 plusparse (#8945)
Message Markdown on mobile moves from gpt_markdown 1.2.1's legacy regex
pipeline to the CommonMark parser that 1.3 added ("plusparse"). Before
this, passing `inlineComponents` (now deprecated, removed in 2.0.0) kept
every message on the legacy pipeline.

### What changes for users

Rendering moves closer to desktop (react-markdown + remark-gfm):

- `_italic_` and `__bold__` work, backslash escapes and HTML entities
decode, and `[a [b] c](url)` labels are correct.
- Inline code follows CommonMark pairing: `"```npm install```"` in a
sentence is inline code, and four-backtick fences work.
- Setext headings, reference links, footnotes, `~~~` fences, `1)` lists
and CommonMark list/quote continuation render.
- HTML comments are hidden, as on desktop.
- `\[`, `\]`, `\(` and `\)` stay literal, as on desktop. Plusparse
hard-codes them as LaTeX delimiters, so they're written as entities
before rendering.
- Side effect: an unfenced `__init__` now renders as bold "init", and a
line over `---` becomes a heading, same as desktop.

Device benchmark (iPhone SE, profile build, 600 synthetic messages, 3
launches per build): scrolling spends 9% less time building, and frames
with more than 8 ms of build drop from 63 to 22. Jumping onto unbuilt
messages is 11% cheaper, and raster time is unchanged.

App size: the release app grows about 4.6 MB uncompressed (80.6 to 85.2
MB), mostly Dart code from the new math and highlighting packages.

### Before and after

Synthetic messages that reproduce differences found in real channel
history, rendered through `MessageContent` on main and on this branch:


![01-escaped-brackets-in-code](https://raw.githubusercontent.com/block/buzz/49600d2f9b87c2c41fd1bcac450efd345de0d0db/pr-8945--01-escaped-brackets-in-code.png)


![02-inline-triple-backticks](https://raw.githubusercontent.com/block/buzz/49600d2f9b87c2c41fd1bcac450efd345de0d0db/pr-8945--02-inline-triple-backticks.png)


![03-four-backtick-fence](https://raw.githubusercontent.com/block/buzz/49600d2f9b87c2c41fd1bcac450efd345de0d0db/pr-8945--03-four-backtick-fence.png)


![04-entities](https://raw.githubusercontent.com/block/buzz/49600d2f9b87c2c41fd1bcac450efd345de0d0db/pr-8945--04-entities.png)


![05-stars-and-underscores](https://raw.githubusercontent.com/block/buzz/49600d2f9b87c2c41fd1bcac450efd345de0d0db/pr-8945--05-stars-and-underscores.png)


![06-ordered-list-paren](https://raw.githubusercontent.com/block/buzz/49600d2f9b87c2c41fd1bcac450efd345de0d0db/pr-8945--06-ordered-list-paren.png)


![07-setext-heading](https://raw.githubusercontent.com/block/buzz/49600d2f9b87c2c41fd1bcac450efd345de0d0db/pr-8945--07-setext-heading.png)


![08-dunder](https://raw.githubusercontent.com/block/buzz/49600d2f9b87c2c41fd1bcac450efd345de0d0db/pr-8945--08-dunder.png)

### Demo

A scroll through synthetic messages covering common formatting
(headings, lists, quotes, links, highlighted code, a table, a task list,
escapes), recorded on an iPhone 17 Pro simulator running this branch:


https://github.com/user-attachments/assets/bdc9680c-d20b-41ec-8e1a-a5b51c602f9d

### How

- Mentions, custom emoji and `#channel` tokens are `InlinePattern`s.
Links go through `inlineLinkBuilder` into the existing `_buildLink`, so
chips, media links and taps are unchanged.
- Removed workarounds the parser makes unnecessary:
  - the render-path escape shielding from #8925
- the `_MarkdownEscapeMd`, `_MarkdownLabelEntityMd` and `_MessageLinkMd`
components
  - the zero-width prefix before a leading `#channel`

Plain-text previews and gallery helpers keep their own escape handling.
`normalizeBareLinks` stays because attachment and gallery detection
depend on its output. Bubble segmentation unescapes a link destination
itself before its imeta lookup, since content no longer arrives
shielded.
- Kept desktop parity where plusparse differs from GFM:
- a table typed directly under a caption line gets a blank line inserted
before it, since plusparse can't start a table mid-paragraph
- `> [!NOTE]` quotes render as quotes (`alertBuilder` returns
`asBlockQuote()`), since desktop has no alerts
- `mapMarkdownProse` now ends an unclosed backtick run at its paragraph.
Before, it could pair with a run in a later block and flip code and
prose for the rest of the message.
- Synthesized autolink labels escape backslashes instead of using
`&#92;`, which the parser leaves undecoded in a URL-shaped label.
- Repo/PR/issue chips keep their own semantics node.
- Forum card previews clip at their 120 px cap instead of overflowing:
blocks now lay out as a column.
- Pinned to exactly 1.3.4. 1.4.0 renders HTML by default and themes
through the separate `material_ui` package, which would need a theme
bridge.

### Validation

- Full mobile suite passes and analyze is clean at 78b9c1a6d0.
- All of #8925's and #8940's backslash-escape cases pass on the new
parser, including the strike-across-lines case that used to be a known
limitation.
- Real-message diff: 2,259 recent messages from 13 busy channels,
rendered through `MessageContent` on main and on this branch. 29
differed in text or styling. On inline and fenced code, the branch
matched desktop's parser (remark-gfm) in 23 of them and main in 7. The
review found the three parity gaps above, now fixed. The rest are
CommonMark behavior that desktop shares.
- Added tests, each confirmed to fail without its fix:
  - a leading `#channel` renders as a link, not a heading
  - a table under its caption renders as a table
  - an alert-marker quote stays a quote
  - an unclosed backtick run doesn't flip later code
- the transcript tests detect a rendered link by its style; the old
`LinkButton` check passed even with autolink on
- Automated simulator run (iPhone 17 Pro, iOS 27, debug build, signed in
to a Builderlab community): channel list, two channels with history
scrolled back several pages (mentions, link previews, thread summaries,
images), an agent Solo chat with long agent messages, and the inbox. No
rendering errors or layout breaks; the Solo chat screen also matched
main's build side by side.

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

---------

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>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:06:50 -07:00
Kalvin C
3c0adc1882 fix(mobile): qualify every namesake mention and keep authored mention casing (#9325)
## problem

When a message mentions two different identities that share a display
name, the mobile composer qualified only the later selection as `@Name
(<64-hex>)` and left the first one bare. A qualified occurrence denies
the plain name on render, so the first mention rendered as plain text on
mobile and desktop. `MessageContent` also displayed every mention in the
lowercased binding key rather than its authored spelling.

## change

- `mention_bindings.dart`:
- `selectedMentionLabel` qualifies a selection whenever another selected
identity shares its name, without regard to case.
- `namesakeRequalifications` and `renameMentions` qualify earlier plain
selections. Each occurrence keeps its authored spelling, and occurrences
in code stay as typed.
- `compose_bar/helpers.dart` and `compose_bar_widget.dart`:
- Selecting a namesake qualifies earlier same-name mentions before the
new label is inserted, keeping the caret in place.
- Occurrences inside code that the composer styles are skipped:
single-backtick spans and closed triple-backtick fences, found by the
same walk the editor uses to draw them. A key whose occurrence stays in
code remains bound beside its qualified label, so its recipient still
sends.
- `agent_mention_prefill.dart`: automatic addressing qualifies every
same-name agent it inserts.
- `message_content.dart`: mentions render in their authored spelling,
and bindings still resolve case-insensitively.
- `docs/mention-editor.md`: describes the behavior, including that
Markdown code forms the composer does not style (tilde fences, indented
code) are qualified like prose.

## tests

- `mention_bindings_test.dart`: requalification, spelling preservation
and code exclusion.
- Composer journeys:
  - picker selections qualify both namesakes and send both keys;
- styled code (fences, list fences, spans, spans after bold or italics)
stays as typed while surrounding prose is qualified;
  - a selection left only in code keeps its recipient;
  - automatic prefill of two same-name agents qualifies both.
- `message_content_exact_mentions_test.dart`: authored casing with
case-insensitive resolution.
- `just mobile-check mobile-test` passes.
- Real relay: composed bodies exchanged through a local relay render as
correctly targeted chips in desktop and in Flutter `MessageContent`.

---------

Signed-off-by: Kalvin Chau <kalvin@block.xyz>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: goose-wayne <ae6b377e5b6d090ee22558d19246413a5731628a127e25371111badfd4861535@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@buzz.block.builderlab.xyz>
2026-11-12 19:11:37 -08:00
Tom Brow
bf3bdd0eae fix(mobile): match browser GIF timing in the iOS reaction sheet (#9437)
The two follow-ups from the pre-review of [#9432 GIF frame
timing](https://github.com/block/buzz/pull/9432), rebased onto main now
that it has landed.

**iOS reaction details sheet.** The sheet decodes custom emoji natively
(`NativeMessageImageLoader.decode`) and timed each frame as `max(0.02,
delay)`, so with [#9432 GIF frame
timing](https://github.com/block/buzz/pull/9432) a GIF with 0 or 1 cs
delays plays at 100 ms per frame in the timeline chip but 20 ms per
frame in the sheet opened from it. The decoder now shows frames of 10 ms
or less for 100 ms, as browsers and `MediaImageProvider` do, and keeps
longer frames as written. The 20 ms floor goes with it: browsers keep 11
to 19 ms frames as written too.

**Provider-level test.** The existing tests call
`withBrowserFrameTiming` directly, so removing the provider's call to it
left the suite green. A new test resolves a GIF through
`MediaImageProvider` with a mock HTTP client and pumps the scheduler's
app frames at explicit timestamps: the 10 ms first frame is still
showing at 50 ms and is replaced at 100 ms.

### Regressions

None expected. The sheet already summed the frame delays into one
`UIImage.animatedImage` duration, so only the per-frame value changes,
and only for frames of 10 ms or less, which ran at 20 ms before. Still
images and longer frames decode as before. The Dart test drives frame
callbacks with explicit timestamps rather than waiting on wall-clock
time.

### Validation

Added tests: `NativeMessageImageLoaderDecodeTests` in RunnerTests (a 0,
1, 2, 5 cs GIF decodes to a 0.27 s animation; a one-frame GIF stays
still) and `withBrowserFrameTiming is applied to the frames
MediaImageProvider plays` in `media_image_test.dart`, which fails when
the provider's call is removed (the second frame shows at 50 ms).

Full mobile suite: 4,780 tests passed. `flutter analyze`: no issues.
RunnerTests `NativeMessageImageLoaderDecodeTests` and
`NativeReactionDetailsTests`: all five pass on an iPhone 17 simulator
(Xcode build-for-testing of the Debug simulator app). No full-app run:
the change is one delay value in a decoder and is covered by the unit
tests above.

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@sprout-oss.stage.blox.sqprod.co>
2026-11-13 02:01:12 +00:00
Kalvin C
0bbcf3e7c2 fix(mobile): play short-delay animation frames at browser speed (#9432)
Some animated custom emoji play far faster on mobile than on desktop.

Browsers show any animation frame with a delay of 10 ms or less for 100
ms. Firefox started this ([bug
207059](https://bugzilla.mozilla.org/show_bug.cgi?id=207059)). Chromium
copied it (decoder comment: "use a duration of 100 ms for any frames
that specify a duration of <= 10 ms"), and so did WebKit ([changeset
73295](https://trac.webkit.org/changeset/73295/webkit)). Flutter uses
the delay as written
([flutter/flutter#130684](https://github.com/flutter/flutter/issues/130684)),
so a GIF with 0 or 1 centisecond delays runs at the display refresh rate
on mobile and at 10 fps on desktop.

`MediaImageProvider` now wraps multi-frame codecs so frames of 10 ms or
less get 100 ms. Every other frame keeps its own delay. Still images are
passed through unchanged. Custom emoji, avatars and attachments all
render through this provider.

**Tests:** `flutter test test/shared/relay/media_image_test.dart` passes
(24/24), and `flutter analyze` reports no issues on the changed files.
The new test decodes a GIF with delays of 0, 1, 2 and 5 cs and expects
100, 100, 20 and 50 ms. It fails when the wrapper is removed.

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

Signed-off-by: Kalvin Chau <kalvin@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:43:04 -08:00
Tom Brow
8f3f4e266a test(mobile): run push tests without a gateway dart-define (#9423)
A plain `cd mobile && flutter test` failed 11 push and notification
tests on a clean checkout of main, while CI passed. Agents running the
full suite kept reporting them as "pre-existing, also fails on main",
which hides real regressions in the same files.

### Root cause

Push is gated on the compile-time `BUZZ_PUSH_GATEWAY_URL` define
(`Env.pushGatewayConfigured`, since [#7261 configurable
gateway](https://github.com/block/buzz/pull/7261) made the gateway
optional). Without it the app is a push-less build:
`readBuzzPushEndpointGrants()` returns no grants and
`buzzPushLifecycleEnabled()` is false. CI's mobile shards, `just
mobile-test` and the lefthook pre-push lane (which runs `just
mobile-test`) all pass
`--dart-define=BUZZ_PUSH_GATEWAY_URL=https://push.example`; a bare
`flutter test` passes nothing. Each of the 11 was checked against that:

- `notification_toggle_test` (5 cases) and
`push_lease_revocation_outbox_test` "hosted relay assertion": no
endpoint grants without a gateway (`Bad state: No element` at the grant
lookup, `No endpoint grant exists for push lease tombstone`).
- `push_bridge_test` "reads and exposes persisted endpoint grants" and
"debug enrollment carries the configured relay and gateway URLs": the
bridge returns `[]` before calling native (`Expected: an object with
length of <1>, Actual: []`).
- `push_bootstrap_test` "default push requires relay capability" and
"new community starts registration": the lifecycle is disabled, so
registration never starts (`Expected <1>, Actual <0>`).
- `push_bridge_test` "development push gateway matches the compiled
configuration": a stale test. It expected a `https://push.buzz.xyz`
default that [#7261 configurable
gateway](https://github.com/block/buzz/pull/7261) removed from the app;
under CI's define both sides equal `push.example`, so it could never
fail there.

The same files pass on the same Mac with the define, so nothing is
environmental. The `Unexpected native call
takePendingNotificationResponse` log is unrelated noise: the toggle
test's native mock didn't answer that call, which logs (and is caught)
in CI too.

### Fix

Tests get the gateway from a test hook instead of the define.
`Env.pushGatewayUrl` becomes a getter over the compiled value with a
`@visibleForTesting` `debugPushGatewayUrlOverride` (the same pattern as
`debugUriStreamOverride`), and `test/flutter_test_config.dart` sets it
for every test file. `push_unconfigured_build_test` sets it to `''`, so
it runs in the main suite instead of being skipped there and run
separately. CI, the Justfile, `scripts/flake-check.mjs` and the
AGENTS/README check commands drop the define, so CI, `just mobile-test`,
pre-push and a bare `flutter test` run the same thing.

I chose this over documenting a canonical command because the define
can't be made automatic: `flutter test` has no config file for defines,
so any doc fix still leaves the obvious command red. A test hook makes
every invocation agree.

The stale test is replaced by one in the push-less file that binds the
production read: with the override cleared, `Env.pushGatewayUrl` must
equal the compiled `BUZZ_PUSH_GATEWAY_URL`. Now that CI compiles without
the define, it fails if the app regains a built-in gateway default,
which the old test never could. The toggle test's mock answers
`takePendingNotificationResponse` with no pending response.

What gets better: one test mode everywhere, and the push-less tests run
in every run. Nothing gets worse: production reads the same compiled
value (the override is never set outside tests, and an `aot-snapshot`
probe shows AOT still folds the getter to the compiled constant and
drops push-only code when the define is absent), and every test still
runs in the push-capable mode CI used before.

### Validation

- On a fresh origin/main worktree with the Hermit toolchain, a bare
`flutter test` failed exactly these 11; the same files passed on the
same machine with the define.
- After the fix, the pre-push `just mobile-check` and `just mobile-test`
(now a bare `flutter test` plus the recipe and secp256k1 checks) pass,
with the push-less tests running instead of skipped.
`scripts/flake-check.test.mjs` passes.
- Falsifiability: re-adding a `defaultValue` to the compiled gateway
fails the new no-default test, and removing `flutter_test_config.dart`
brings back the other 10 failures.
- Unrelated: an earlier full run also failed `community_provider_test`
"discard orphan snapshots and image caches", which waits 500 ms for a
background directory delete. The Mac was running other full suites at
the time; the file passed 8 of 8 runs alone, with and without the
define. It is not touched here.

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-12 16:19:10 -08:00
Tom Brow
5bfbda4c33 fix(mobile): never pop Home when archiving from channel settings (#9387)
Archive, Leave, Unarchive and Delete in channel settings wait for the
relay, then close the settings sheet by popping whatever route is on top
of the root navigator. If the user closes the sheet themselves during
that wait (for example: long-press a chat on Home, Archive, confirm,
then tap the close button), that pop lands on Home instead. The
navigator ends up empty: a blank white or black screen with no controls
and no way back short of killing the app.

### Change

- **Close only the route that offered the action.** (Main has since
gained the same guard; after merging main, this part of the diff is a
comment plus the tests below.) After the action completes, the settings
sheet or page closes itself only if it is still on top, with its "close
the conversation too" result, as before. If the user opened something
over it meanwhile (for example a member's profile), it stays open under
that route, which keeps working. If the user already dismissed it,
nothing is popped. The sheet still closes on its own after a successful
archive.
- **Home can no longer be popped.** The app's root route refuses pops. A
stray pop that reaches it is reported through `FlutterError.reportError`
(which fails widget tests) and ignored, so no other caller can leave an
empty navigator either. Local-history pops on the root route (a drawer
or persistent bottom sheet) still close normally. The root route still
rebuilds from the current auth state, so sign-in and sign-out
transitions are unchanged.

### What changes for the user

Only the case where a settings action finishes after the user moved on:

- Settings dismissed mid-flight: before, the completion popped whatever
was on top (Home, the conversation, a thread or a profile). Now nothing
is popped.
- Something opened over settings mid-flight: before, the completion
popped that new route and left settings open. Now that route stays, and
settings stays open under it, as on main. That settings page shows the
channel as it was before the action (for example still offering Archive
after an archive, or a channel that is gone after Delete or Leave), as
on main. Settings following lifecycle changes is part of the follow-up
below.
- Delete or Leave from the pushed settings page, then back out before
the relay answers: before, the stray pop happened to close the
conversation. Now the conversation stays open until the user leaves it
(Leave and Archive show the read-only notice; a deleted conversation
keeps showing its last state). Closing it reliably needs the
conversation to notice its channel is gone, which is a follow-up.

Pops that reach Home were always a bug and are now refused. Every other
pop (sheets, pushed pages, system back above Home) takes the same path
as before.

### Validation

Added tests:
- Channel actions sheet journey: confirm Archive with the relay call
still pending, close the sheet, then let the archive finish. Home stays.
A second pass leaves the sheet open and checks it closes by itself once
the archive completes. Fails on the old code with Home popped.
- Conversation journey: open settings from a conversation, confirm
Archive with the relay call pending, open a member's profile, then let
the archive finish. The profile stays open and current, and its Message
action still opens the DM. Fails if the completion pops the top route,
and fails if it removes the covered settings page (the profile loses the
context it navigates from).
- Root route: normal push and pop still work, a drawer on Home closes on
back, and popping Home is refused, reported, and Home stays on screen.

Full mobile test suite and `mobile-check` pass, including after merging
main.

Automated app run at
[c158c17](c158c1793d)
on an iOS 27 simulator (iPhone 17 Pro, debug build, public Builderlab
community): long-press a solo chat on Home, archive it from the settings
sheet, and confirm the sheet closes by itself with the channel list
intact. Then the race: confirm Archive and immediately drag the sheet
closed while the archive is in flight. Home stays intact with the chat
archived, and no refused-pop error is logged. Limitation: AXe taps don't
reach the native glass close button on the simulator, so the run
dismissed the sheet with the drag gesture, which takes the same route
pop.

buzz-review-completed

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:06:45 -08:00
Michael Fransen
2636e986a0 fix(mobile): build channel section rows lazily (#9401)
## Summary

Improve scrolling performance in the Messages channel list by building
Solo and Team rows only as needed. Sections currently mount all their
rows as one scroll item, which causes long UI stalls with large channel
lists.

In manual iPhone runs with 500 channels, maximum observed Flutter UI
work fell from **65.5 ms to 4.2 ms** after adding lazy rows to a build
with header isolation (#9400). The tester reported much smoother
scrolling. This was an exploratory comparison with different gestures,
not a controlled benchmark of this independent branch.

Use stable channel keys and retain section controls, sorting, and
collapse animations. Clip the sliver extent during collapse so the
animation does not mount the entire section. The shared transition
supports downward vertical lists.

This is an independent production-only change. Test fixtures and
diagnostic instrumentation are excluded; regression checks were run
locally and are not included in this PR.

### Related issue

Related: #5911 addresses scrolling behavior inside conversations. This
change addresses eager row mounting in the Messages channel inventory.
No matching open PR or issue was identified in the focused duplicate
search.

### Testing

On a physical iPhone with 500 channels against an isolated local relay,
maximum Flutter UI work fell from 65.5 ms to 4.2 ms after adding lazy
rows to a build that already isolated header rebuilds. The tester
reported much smoother scrolling. Gestures differed between runs, so
this is not a controlled benchmark or an isolated measurement of this
branch on its own. The device run preceded the refresh onto current
main.

Local-only regression journeys passed 12 tests on this independent
branch. They cover page laziness and updates, variable-height rows,
large text, the last row, collapse reversal, reduced motion, and
semantics. These checks are excluded from the commit.

Smaller visible jumps remain under investigation; this PR does not claim
to resolve them.

Generated with Codex

---------

Signed-off-by: Michael Fransen <mfransen@squareup.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Karl <9e8471f7b792e46c9c100840959dc71c660786c79c2a3165dbcaf58f52c4266e@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>
2026-11-12 12:56:43 -08:00