Commit Graph

3677 Commits

Author SHA1 Message Date
Tom Brow
5825a7a81f feat(mobile): handle Android push wakes (#9804)
Ticket 6 of the [Android push
design](https://github.com/block/buzz/pull/9555), building on [#9558
resolve push wakes](https://github.com/block/buzz/pull/9558). Enrollment
(FCM token registration, ticket 7) landed separately in [#9811 enroll
Android push](https://github.com/block/buzz/pull/9811), which also
carries the Firebase build config, `POST_NOTIFICATIONS` and the
auto-init switch.

## What it does

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

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

## Decisions

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

## Known gaps

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

### Validation

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

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

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

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

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

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

### Screenshots

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

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

## Regressions

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

---------

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

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

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

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

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

### Validation

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

### Regressions

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

---------

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

## What it does

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

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

## Decisions

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

## Regressions

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

## Open questions

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

### Validation

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

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

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 15:04:45 -07:00
Bradley Axen
5884965a47 perf(relay): bound channel- and thread-window aux hops to a day before the oldest target (#9874)
## Summary

Both window aux closures, the channel window and the thread window, now
read their `#e` hops from one day before the window's oldest aux target.
That lets Postgres prune older `events` partitions instead of probing
the community's whole history.

### Channel window

`handle_channel_window_filter` runs two `#e` aux hops for a channel
window: hop 1 fetches the reactions, edits and deletions of the window
rows, and hop 2 fetches the deletions of those aux events. Neither hop
had a lower time bound, so each `#e` GIN probe ran against every
`events` partition in the community's history.

Both hops now read from `since = oldest retained window row's created_at
− 1 day` (`WINDOW_AUX_SINCE_MARGIN_SECS`), which lets Postgres prune the
older partitions. A hop-2 deletion postdates the aux event it deletes,
so one bound covers both hops. An empty window has no bound, and no hops
run for it.

**Why it's safe**
- Ingest rejects events more than ±15 min from the relay clock
(`MAX_TIMESTAMP_DRIFT_SECS`), so an aux event can predate its target by
at most about 30 min. The day of margin covers that, plus data that
reached the store some other way.
- In a sample of about 86.6k aux events across every partition, none was
dated more than 1 day before its target.

**Measured**
- Channel 029f8049: both lookups went from 927 to 230 ms.
- Channel a9cb3f0a: 256 to 46 ms.
- Prod `pg_stat_statements`: hop 2 averages 147 ms over 2.9M calls and
returns 0 rows on average, so most of that time is spent scanning
partitions it can now skip.

**Known risk:** a tighter bound can flip the planner to a worse plan on
busy channels. A 1-hour margin did this in testing. The 1-day margin is
the one that measured well.

### Thread window

`thread_window::query` → `buzz_db` `thread_window_aux` runs the same two
hops. `AuxQuery` gains an optional `since`, which `select_aux` adds as
`created_at >= since`. In a thread window, `rows` holds only replies,
but the root is always a hop-1 target, so the bound is `min(root
created_at, oldest reply) − 1 day`. `select_window` now reads the root's
`MIN(created_at)` in the query that already checked the root exists in
the channel (it used to be `EXISTS`), and returns it as
`ThreadWindow::root_created_at`. Both paths share `window_aux_since`.

**Measured** on the prod reader with `EXPLAIN (ANALYZE, BUFFERS)`, warm,
with the exact `select_aux` SQL: 50-reply windows (51 targets), and an
accessible set of 974 channels (a real user's). Times are execution +
planning ms; rows were identical with and without the bound in every
case:

| Thread | Hop | Unbounded | Bounded |
|---|---|---|---|
| 244d0894: 1570 replies, root Nov 16 | hop 1 | 352 (45.0k buf) | 108
(13.4k buf) |
| 0fdaa9bb: busy channel 638c53ca | hop 1 | 357 (45.0k buf) | 111 (12.5k
buf) |
| 346a47e6: busy channel 029f8049 | hop 1 / hop 2 | 100 / 53 | 45 / 14 |
| f7c2c2f9: root Sep 22, still active | hop 1 / hop 2 | 330 / 53 | 259 /
37 |

With only the thread's own channel accessible, the same cases went 216 →
15, 218 → 21, 76 → 31 (hop 2 35 → 5), and 214 → 151. None of the bounded
plans was worse: they use the Nov partition's `kind_created_at` btree
plus its tags GIN. An old root gains less, because the bound still has
to reach back to the root's month.

Prod `pg_stat_statements` (reader, since Nov 2): the thread aux shape
ran 1.03M calls, averaging 50 ms, 8.5k buffers and 3.9 rows per call,
14.4 h in total. Cost grows by about 4.5 ms and 800 buffers per target:
11 targets averaged 52 ms over 268k calls, and 51 targets averaged 250
ms over 43k calls.

Caveat: I measured with literals, which gives custom plans. If sqlx's
prepared statements switch to a generic plan, partitions are still
pruned, but at execution time rather than at planning time.

### Related issue
N/A. This comes from the structural first-paint investigation of prod
head-read latency. No existing issue or PR found.

### Testing
- New thread test
`thread_window_aux_hops_read_from_a_day_before_the_root`: its only reply
is 2 days newer than the root, so a bound anchored on the replies alone
would fail it. A reaction and a delete-of-reaction dated inside the
bound come back, and ones dated more than a day before the root do not.
Two mutation checks fail as expected: dropping the SQL clause fails on
"hop 1 past the bound", and leaving the root out of the bound fails on
"hop 1 inside the bound".
- New channel test
`channel_window_aux_hops_read_from_a_day_before_the_oldest_row`: a
reaction and a delete-of-reaction dated inside the bound come back, and
ones dated more than a day before the oldest row do not. As a mutation
check, removing `aux_query.since` makes it fail on "hop 1 past the
bound".
- `scripts/postgres-test-run.sh`: `buzz-relay` `api::bridge::` 135/135
pass and `buzz-db` `thread_window|thread::` 28/28 pass. The
workflow-webhook test needs `REDIS_URL` set.
- The Security check fails on a new advisory, RUSTSEC-2026-0592 (`url`
2.5.8, in `Cargo.lock`). This PR doesn't touch dependencies, and main's
run of that workflow at 42dc2a8c5 failed too.
- `cargo fmt --all -- --check` and `cargo clippy -p buzz-db -p
buzz-relay --all-targets -- -D warnings` are clean, and the pre-push
hooks passed.

---------

Signed-off-by: Bradley Axen <baxen@squareup.com>
Signed-off-by: Kalvin Chau <kalvin@block.xyz>
Co-authored-by: Kalvin Chau <kalvin@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 21:22:27 +00:00
klopez4212
8cc7e94392 Refine mobile Messages sections, Duo navigation, and chat typography (#9885)
## Summary

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

## Device review

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

---------

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-23 13:14:05 -08:00
Arthur Garza
a8cc77ac34 fix(mobile): keep a legacy chat color when Set changes only the mode (#9898)
Follow-up to #9894, addressing the review finding there.

## Problem
Some desktop chat colors (for example Cyan `#06b6d4`) have no exact
mobile swatch, so the Appearance picker shows the closest one (Jade).
Tapping **Set** after changing only Light/Dark/System saved Jade's value
(`#22c55e`), and that new color synced to every device.

## Fix
On Set, the saved accent is kept unless the user picked a different
color.

Also adds doc comments to `appearanceModeProvider` and
`AppearanceModeNotifier.setMode`.

## Tests
- The existing mode-only picker test now starts from legacy Cyan and
goes through the real `CommunityThemeNotifier.setPreference`, asserting
the synced preference is unchanged. It fails with the fix reverted.
- `just mobile-check` and `just mobile-test` pass.

## Try it
1. On desktop, set the chat color to a legacy color such as Cyan.
2. On mobile, open Settings → Appearance, change only Light/Dark/System,
tap Set.
3. Desktop and other devices still show Cyan.

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

Signed-off-by: Arthur Garza <arthur.garzajr@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 20:53:23 +00:00
Tom Brow
e600cdbde2 feat(mobile): time channel opens and relay connection recovery (#9858)
Adds two durations to the mobile networking diagnostics, so work on
channel opening and reconnecting has a before and after number from real
use:

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

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

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

### Regressions

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

### Validation

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

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

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

Added tests:

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

Known limits:

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

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-23 12:22:14 -08:00
klopez4212
e802de8777 Give mobile Solo sessions their own settings and actions (#9888)
## Summary

Long-pressing a Solo or channel in the mobile list opens a system menu
anchored to its row (UIKit context menu on iOS and a rounded Android
PopupWindow with leading icons and an anchored scale and fade). Both
menus use Buzz’s Tabler icons. The actions appear in this order when
available: Mark unread (or Mark read), Rename, Move to section (Change
workspace for personal Solos), Archive (or Unarchive). Tapping the
conversation title opens full settings.

Solo settings include Agent, Rename, workspace, members, and
role-specific management actions. Channel settings put Members below the
quick actions, include Huddle, and offer Leave to eligible members,
including co-owners. A sole owner sees Delete channel. DMs retain the
Huddle header shortcut.

## Snapshots

The iOS simulator shows a sample Solo row. The Android screenshot is
from a physical Pixel.

| UIKit context menu on iOS 26.5 | Android system popup on Pixel 10 |
| --- | --- |
| ![Simulator interaction using sample
rows](https://github.com/user-attachments/assets/dddb43e1-4d2b-4737-a3a4-0dff58ed9e63)
| ![Pixel popup cropped to its four
actions](https://github.com/user-attachments/assets/80008353-f717-41aa-a45e-2cedebafa653)
|

Flutter-rendered details previews with sample data. The previous
ellipsis opened a separate settings sheet. The updated Solo details page
includes those controls.

| Previous ellipsis sheet | Updated settings | Updated members and
management |
| --- | --- | --- |
| ![Previous Agent and Workspace
sheet](https://github.com/user-attachments/assets/75c40f2a-0093-4ebc-811e-fe31ea7acc30)
| ![Solo quick actions, agent and
workspace](https://github.com/user-attachments/assets/00a320ac-b106-4a63-9ef3-babddb98ded1)
| ![Solo roster and owner
actions](https://github.com/user-attachments/assets/3c394e74-6ad3-480d-9666-22ecabc98cb2)
|

Long-pressing a message puts Mark unread first in its quick actions.

![Message quick actions with Mark unread
first](https://github.com/user-attachments/assets/4819ad0c-473b-4f2a-b93a-e2cfb66f2e76)

## Testing

The list journey tests exercise the popover from the channel list and
Solo list, shared Solo filing, read-state changes and dismissal. The
title settings tests cover editing, roster, and lifecycle actions.

## Related issue

No matching issue found.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-23 20:19:55 +00:00
morgmart
70bb7b7bec feat(mobile): name blocking agents, leave agents out of DM names (#9875)
## Problem

Two follow-ups to growable DMs (#9153), matching desktop
block/buzz-app#3744:

1. When an agent's add policy blocks a DM, mobile shows a generic error.
The person can't tell which agent blocked it or whose owner to ask.
2. DM names list every member, agents included, so a DM with one person
and their agent reads like a group, and "+N more" mixes agents with
people.

## Change

**Name the blocking agent.** The relay names the agent in that refusal
(#9601). Mobile shows the agent's name: "Only Scout's owner can add it
to a DM." or "Scout can't be added to a DM.", starting with "Couldn't
add them." when adding to an existing DM, and "this agent" when the name
can't be read. Against a relay without #9601, the error is the same as
before.

**Leave agents out of DM names.** A DM's name lists its people and never
its agents, unless no other person is in it (just you and agents), when
it names the agents. "+N more" counts people only. Member counts and
member lists still include agents. The shared DM label feeds the list,
headers, details and Activity. Agent means the profile's existing agent
flag; a profile that hasn't loaded yet counts as a person until it says
otherwise.

## Screenshots

Temporary headless renders with test data, not committed.

### Name the blocking agent

Add people, refused by an agent's owner-only setting:

| | Light | Dark |
|---|---|---|
| Narrow | ![light
narrow](https://github.com/user-attachments/assets/61bfbfe2-5882-456e-8bff-b42f7389aa06)
| ![dark
narrow](https://github.com/user-attachments/assets/d7ac0dca-9081-4cde-a403-cde492d2cf4f)
|
| Wide | ![light
wide](https://github.com/user-attachments/assets/cc9f5a0f-0f3a-4d80-8fc6-0937a2246462)
| ![dark
wide](https://github.com/user-attachments/assets/87b48014-9740-4e17-ad83-f5bac272dda8)
|

### DM names without agents

Ana alone, Ana with two agents (named "Ana", count still 3), and only
the two agents (named by them):

| | Light | Dark |
|---|---|---|
| Narrow | ![light
narrow](https://github.com/user-attachments/assets/b413dbc1-a2bc-4410-8be9-b1a219374349)
| ![dark
narrow](https://github.com/user-attachments/assets/75c9cbc3-432f-45c7-83a4-624f80752b97)
|
| Wide | ![light
wide](https://github.com/user-attachments/assets/ae57c305-f4e4-4e26-8ba0-ecbcd128137e)
| ![dark
wide](https://github.com/user-attachments/assets/a75efc90-6b20-4409-bdd5-682de1f0301f)
|

## Tests

- Blocking agent: an open and an add name the agent, fall back to "this
agent", and leave other refusals as they were.
- DM names: people and agents, only agents, more than three people and
agents, and a profile that hasn't loaded yet.

The lost-reply recovery was taken out after review. It comes back as a
relay change that answers a replayed signed command with its saved
result, so the app can resend the same event instead of guessing from
rosters.

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

---------

Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 12:10:23 -08:00
Tom Brow
6017091936 refactor(mobile): remove the dead per-signer cache sweep (#9902)
## Summary

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

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

## Changes

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

### Added lines

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

## Validation

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

---------

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

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

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

## Changes

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

### Added lines

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

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

## Validation

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

---------

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

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

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

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

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

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

### Related issue

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

### Testing

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

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

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

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

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

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

## Thread cache limits

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

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

## Simulator comparison

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

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

## Cold link to an older thread

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

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

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

## Verification

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

## Try it

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

---------

Signed-off-by: Wes <wesb@block.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
2026-11-23 11:03:49 -07:00
klopez4212
c400c186f3 fix(mobile): align the New menu with desktop (#9883)
## Summary

Match the desktop New menu on mobile. New chat, New channel, and New DM
appear above a divider, with New workspace and its folder icon below.
Remove the Solo and Team headings and keep the action order fixed in
UIKit.

On iOS, fade the search icon and avatar as they move toward New. Restore
them when the menu closes and respect Reduce Motion.

## Testing

- Full Flutter suite passed (5,987 passed, 71 skipped). The Home widget
test covers the menu order, divider, and opacity during opening and
dismissal.
- The focused UIKit simulator check passed for workspace grouping and
selection. The broader native harness stops at an unrelated dismissal
assertion that also fails on the base commit.
- Built, installed, and launched the updated preview on a physical
iPhone Duo.

Related work: #9840.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-23 17:47:38 +00:00
Matt Toohey
c5d480427b fix(deps): bump url to 2.5.9 for RUSTSEC-2026-0592 (#9877)
## Summary

Bumps `url` from 2.5.8 to 2.5.9 in the root `Cargo.lock` so the CI
**Security** job (`cargo-deny check`) passes again.

**What failed.** `Security Domain / Security` fails with `advisories
FAILED` on one error:
[RUSTSEC-2026-0592](https://rustsec.org/advisories/RUSTSEC-2026-0592),
"Stack overflow in `Url::origin()` on nested `blob:` URLs", against `url
2.5.8`. The advisory's fix is `url >= 2.5.9`.

**Why it is not tied to any one PR.** The advisory was published after
the last green `main` run (80131055dc, 2026-11-21). Since then the job
fails the same way on `main` itself (d29c679066, 42dc2a8c58, e03a11f929,
10dd70f152) and on every PR whose changes select the Rust lanes,
whatever the PR changes.

**The change.** `cargo update -p url --precise 2.5.9`:

| Package | Before | After |
|---|---|---|
| `url` | 2.5.8 | 2.5.9 |
| `form_urlencoded` | 1.2.2 | 1.2.3 |

`url` 2.5.9 requires `form_urlencoded` 1.2.3, so two packages is the
smallest lockfile change that resolves. No manifest changes, and no
ignore added to `deny.toml`.

**`desktop/src-tauri/Cargo.lock` is not changed.** It also pins `url`
2.5.8, but CI does not scan it: the Security job runs `cargo-deny check`
at the repository root only, so it is not part of this failure. I left
it for a separate change because touching `desktop/` adds the desktop
JavaScript and Tauri lanes to a PR whose purpose is to unblock `main`,
and I did not build that bump. The same command with `--manifest-path
desktop/src-tauri/Cargo.toml` moves the same two packages (dry run). The
0.X desktop app does call `Url::origin()` on parsed URLs without first
checking the scheme (`link_preview_tags.rs`,
`commands/personas/card.rs`, `relay/profile_avatar.rs`). The inputs I
traced come from the app's own frontend and the user's own agent
profiles; I did not trace every path.

**Behavior change in `url` 2.5.9.** `Url::origin()` on a `blob:` URL now
takes the inner URL's origin only when the inner scheme is `http`,
`https` or `file`; otherwise the origin is opaque. Before, a `blob:` URL
wrapping `ws`, `wss` or `ftp` had a tuple origin.

- Root workspace: one caller, `StrictWorkspace::validate_endpoint` in
`crates/buzz-agent/src/databricks.rs`. Both URLs it compares must start
with `https://`, so a `blob:` URL never reaches `origin()` there.
Nothing depends on the old result.
- No other crate in the root lockfile calls `Url::origin()`: not the
registry crates that depend on `url`, nor the git dependencies
(mesh-llm, sqlx, rust-s3).
- The release also changes parsing outside `origin()`: `^` in a path is
now percent-encoded (`/a^b` becomes `/a%5Eb`), a backslash ends a port
only for special schemes, host handling for `file:` URLs with a
drive-letter path changes, and a quadratic case in `..` handling is
fixed. `form_urlencoded` 1.2.3 clamps an out-of-range start position
where it panicked before. I read these from the crate diffs and did not
audit them against every caller.

**Out of scope.** The other `cargo-deny` output (yanked `async-executor`
and `nostr-sdk`, the unused RUSTSEC-2026-0381 ignore) is warnings. It is
the same before and after this change and does not fail the job.

### Related issue

N/A. No open PR fixes this: I searched open PRs for the advisory ID,
"url 2.5.9", "cargo update -p url", "cargo deny" and dependency
branches. #9874 only mentions the failure in its description.

### Testing

Run locally on macOS, on this branch (10dd70f152 plus the one commit):

- `./bin/cargo-deny check` (cargo-deny 0.19.0, the command the Security
job runs): exit 0, `advisories ok, bans ok, licenses ok, sources ok`.
With `main`'s lockfile restored: exit 1, `advisories FAILED` on that one
error.
- `cargo check --workspace --all-targets --locked --exclude buzz-voice`
(cargo 1.98.1): finished with no errors or warnings. `buzz-voice` is
excluded because its `sherpa-onnx-sys` build script downloads an archive
that fails TLS verification on the workstation used.
- `cargo test --locked -p buzz-core -p buzz-auth -p buzz-agent --lib`:
299, 291 and 550 passed, 0 failed, 1 ignored. These crates hold the
`origin()` caller and the relay URL and NIP-98 URL normalization.

Not run: the rest of the unit suite, the Postgres lane, the relay e2e
binaries, clippy, and the desktop, web and mobile lanes. The branch was
pushed with `--no-verify`, so the local pre-push lanes did not run
either. CI on this PR is the first full run.

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

Signed-off-by: Matt Toohey <contact@matttoohey.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 12:18:28 -05:00
klopez4212
aa5fa129c4 Remember collapsed sidebar sections on mobile (#9879)
Mobile now remembers collapsed Starred, Team, Direct messages, and
custom sections across relaunches. Preferences are local to each account
and community. New sections start expanded.

Fixes [AIDA-2820](https://linear.app/squareup/issue/AIDA-2820).

The Flutter regression test passed for rapid toggles, restoration in a
fresh provider container, and isolation between scopes.

To verify on a phone, collapse Team and one custom section, leave Direct
messages expanded, force-quit Buzz, and reopen the same community. All
three headers should retain their previous state.

---------

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@localhost>
2026-11-23 17:08:25 +00:00
klopez4212
874a5699ba Add inline emoji shortcode suggestions on mobile (#9882)
Show Unicode and community emoji in the mobile composer after a colon
and two shortcode characters. Tap a suggestion or press Tab or Enter to
replace the token at the cursor. Long labels truncate on one line.

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

---------

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
2026-11-23 17:07:50 +00:00
Wes
36ca4f493e fix(mobile): reply to a thread's head in its open page (#9889)
## Summary

On a mobile thread page, replying to the head message pushed another
copy of the same thread. A person who stays in one thread and keeps
replying to its head ends up with a stack of identical pages, and has to
tap Back through each copy.

Replying to the head from any entry point now focuses the composer of
the page that is already open. The entry points are swipe, long-press →
Reply, the inline media reply, and Reply in the image and video viewers.
If the page has no composer, as in an archived thread or for a
non-member, the head offers no Reply. Before this change, the head
pushed a copy of the page that had no composer either. Replies below the
head still open their own branch.

This is the head-Reply half of #9469, rebuilt on current main. The other
half, which handled a notification or link for the thread already in
front, is left out on purpose. It carried every open review finding on
#9469. iOS also shows no foreground banners (mobile has no `willPresent`
handler), so that path needs a tap from Notification Center while the
thread is on screen.

### Related issue

Part of #8641. The notification/link path stays open there. Supersedes
#9469.

### Testing

- The existing swipe journey now asserts that swiping the head and
long-press → Reply both keep one page and focus the composer.
- A new journey opens the head's photo, taps Reply in the viewer, and
asserts that the viewer closes onto the same page with the composer
focused. Reverting only the media path makes it fail.
- Full mobile suite at `233bf230b`, before the viewer journey was added:
5994 passed, 71 skipped. At `ba3ae9a70`, the new journey passes and the
pre-push `mobile-checks` hook passed.

### Recording

iPhone 18 Pro simulator, iOS 27.0, with fictional data. These clips run
the real channel and thread pages inside the widget-test harness, so the
composer focuses but no software keyboard appears. Each one swipes the
thread's top message to reply and then goes Back.

**Before (main):** the swipe pushes a second copy of the thread, and
Back lands in the same thread.


https://github.com/user-attachments/assets/9b226ede-6988-42cf-a17c-eedcbb3edecb

**After (#9889):** the swipe focuses the open thread's composer, and
Back returns to the channel.


https://github.com/user-attachments/assets/c1c6600d-e3ca-4e86-895e-365b4c430ab9

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

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:00:18 -07:00
Wes
0d4fd74ad6 fix(mobile): offer linked identity import when only other backups exist (#9053)
A fresh phone signing into an account linked to identity A gets a
misleading identity-mismatch error when the account has only a backup
for identity B. The existing import option was offered only when the
entire backup list was empty.

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

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

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

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

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

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

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

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

### Related issue

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

### Validation

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

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

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

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

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

### Settings while turning off

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

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

### Regressions

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



### Known limits

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

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 09:35:56 -07:00
Tom Brow
6dbd159676 fix(mobile): keep "+" reactions working when a new message rebuilds the row (#9831)
## Summary

A new message shifts the timeline and can unmount the long-pressed
message row while its actions sheet or emoji picker is open. Then:

- tapping "+" in the actions sheet did nothing, because the picker
opened from the row's dead context (after [#9820 emoji picker
crash](https://github.com/block/buzz/pull/9820), it is a silent no-op
instead of a crash), and
- a pick made after the row went away read through the row's disposed
`WidgetRef`, so the reaction was dropped.

The actions sheet and the timeline "+" pill now capture the page's
`ProviderContainer` and its navigator's context when they open. The
picker opens from the navigator, and reaction dispatch reads through the
container. `toggleReaction` and `armReactionBurst` take a container, and
grouped system rows read through one too. The reactions tray's Add
button keeps working after the row is gone, since its callback holds the
container and navigator it captured at build time.

Reactions are also bound to the community that was active when the
surface opened: the actions sheet and the reaction details tray (Flutter
sheet or native iOS tray) capture it when they open, and the timeline
"+" pill when it is tapped. If a notification switches community
meanwhile, a quick tile, picker pick, tray toggle or tray Add is dropped
instead of being recorded, animated or published as the newly active
account. `ChannelActions.isCommunityValid` now uses the same
`RelayConfig.isSameCommunity` comparison.

Failure notices for these reactions show from the captured navigator's
context, so they still appear when the row is gone.

## Regressions

None expected. The picker attaches to the same navigator as before (the
row's nearest navigator), and the providers read are the same ones, from
the same `ProviderScope`.

## Validation

- New regression tests in `message_actions_row_rebuild_tests.dart`: the
row unmounts before "+" is tapped, and while the native picker is open.
Both failed on main (picker never presented, pick lost) and pass with
the fix. Two more switch community while the sheet is open, then tap a
quick tile or pick from "+", and check nothing is added, recorded or
armed.
- New test in the reaction row combined tests: the row unmounts while
the native reactions tray is open, and its Add still opens the picker.
Another switches community while the tray is open and checks that a tray
toggle and Add are both dropped.
- Automated simulator app test (iOS 27 sim): opened a channel,
long-pressed a message, tapped "+", picked an emoji in the native
picker, and saw the reaction land. Then toggled it off from the
reactions sheet. Live edits and reactions from another client arrived
during the run without issue.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-23 08:43:29 -07:00
klopez4212
2b44717eb3 Request sentence capitalization in the mobile composer (#9881)
The shared mobile message composer now requests sentence capitalization
from the system keyboard. This lets keyboards offer an uppercase first
letter when starting a message or a new sentence, according to the
user's keyboard settings.

Validated with the repository's mobile analysis and test suite using
Flutter 3.47.9.

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
2026-11-23 15:36:54 +00:00
klopez4212
ebbc94cbd4 Offer image and animated avatars for human profiles (#9724)
Human profile setup and editing now offer **Image** and **Animated**.
The human editor hides Emoji through its available modes. The emoji
picker, editing controls and setup default remain in source. Existing
emoji artwork still displays, and agents can still choose Emoji.

Validation: mobile analysis and formatting passed; the complete Flutter
suite passed 5,117 tests (71 skipped). The follow-up restores the Image
→ Animated preview regression test proposed in #9734. The final pre-push
mobile checks passed, including the complete suite. A prior run at this
revision failed in the profile-cache persistence test and passed on
rerun. The crypto package passed all 27 tests.

The iPhone Air preview opened with the existing session. Physical
recording and saving still need human verification. Check setup and
Settings → Edit Photo: only Image and Animated appear, image upload and
animation recording/save work, and agent avatar editing still offers
emoji.

---------

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>
2026-11-23 09:38:56 +00:00
morgmart
10dd70f152 feat(mobile): add people and agents to a DM (#9153)
## Summary

Mobile part of growable DMs. A DM's details page now has an **Add**
action where channels show Edit.

- Adding only agents joins them to this DM with its history. No question
is asked, matching desktop.
- Adding a person asks first. **Include history** adds them to this DM
with its earlier messages. **Start a new DM** opens a DM of the people,
without the agents or history, and the app moves to it. If that DM
already exists, the relay returns it.
- In a DM of just you and your agents, adding a person skips the
question and opens a DM of you and that person. The relay enforces this
too.
- Both choices send kind 41011. Only Include history carries the
`["history","include"]` tag, per the relay's opt-in rule in #9125.
Without the tag, the relay forks.
- iOS shows a native alert. Android uses the standard adaptive dialog.
- The relay's moderation DM shows no Add, recognized by the relay's
NIP-11 signer key. The relay refuses adds there anyway.
- Leave stays as it is. #9125 lets the relay accept a member's own leave
from a DM.

The question is asked before the sheet shows its busy state, so
"Adding…" only appears after a choice.

### Related issue

Depends on #9125 (relay) and pairs with block/buzz-app#2670 (desktop).
Spec: Growable DMs.

### Testing

- New widget tests: agents join with history and no question; adding a
person to a DM of two or more people asks; adding a person to an
agent-only DM opens a new DM without asking; Include history keeps this
DM; Start a new DM sends no tag and opens the new DM; Cancel adds no one
and leaves Add enabled; a DM member sees Add (not Edit) on the details
page and it opens the add sheet; the moderation DM shows no Add.
- `flutter analyze` is clean. The DM sheet, details and confirmation
dialog tests pass on 90d9c56d8 (rebased on main). The iOS alert merged
with main's non-destructive confirm option. The 90d9c56d8 push skipped
the pre-push hook because `flutter analyze` fails on main itself
(`native_media_headers_test.dart` references an undefined
`videoPreviewFrameLoaderProvider`, from #9144); the full channels suite
passed on 9421a7976, and the push hook runs the mobile checks.
- The screenshots below come from a temporary headless widget render
with test data. It is not committed. The iOS native alert can't render
headlessly, so the dialog shots show the Android dialog.

| | Light | Dark |
|---|---|---|
| Details, narrow | ![DM details light
narrow](https://github.com/user-attachments/assets/aae0c1af-752b-4a1e-b57f-da2546b5a096)
| ![DM details dark
narrow](https://github.com/user-attachments/assets/b5606c11-586a-46a7-b45c-69d4408a7549)
|
| Details, wide | ![DM details light
wide](https://github.com/user-attachments/assets/8ad307d0-aa7c-4015-a05c-c73d2e83e92b)
| ![DM details dark
wide](https://github.com/user-attachments/assets/c76fc6c7-8cef-45a6-af74-c18f1815ba82)
|
| Choice, narrow | ![History choice light
narrow](https://github.com/user-attachments/assets/f62e4386-98d4-412c-8dab-80409dbdce0d)
| ![History choice dark
narrow](https://github.com/user-attachments/assets/7c7ec457-df04-468f-bfa3-d708c592c749)
|
| Choice, wide | ![History choice light
wide](https://github.com/user-attachments/assets/16a88fd3-f57f-4295-92c0-9f8f1a94e85e)
| ![History choice dark
wide](https://github.com/user-attachments/assets/ba50e718-956a-4d9f-bff1-8f836e95a491)
|

Not yet done: a human test on a device against a relay running #9125.

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

---------

Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@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: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-22 21:07:55 -08:00
Matt Toohey
e03a11f929 test(ios): check the navigation glass state often instead of once a second (#9786)
## Summary

Fixes a flaky native iOS test,
`RunnerTests.testNavigationGlassMergesAndRestoresInBothDirections`.
Test-only: one file, `mobile/ios/RunnerTests/RunnerTests.swift`.

### Failure

"Mobile Swift Domain / Mobile Swift (Native)" failed on #9780 ([run
44682658228](https://github.com/block/buzz/actions/runs/44682658228/job/136109857758)):

```
mobile/ios/RunnerTests/RunnerTests.swift:83: error: -[RunnerTests.RunnerTests testNavigationGlassMergesAndRestoresInBothDirections] : Asynchronous wait failed: Exceeded timeout of 2 seconds, with unfulfilled expectations: "Expect predicate BLOCKPREDICATE(...)"
```

### Why it is a flake

- #9780 changes only Dart files under `mobile/lib/features/channels` and
one Dart test. Nothing in it reaches `MergingNavigationGlass`.
- The same job passed on another PR minutes later ([run
44683133967](https://github.com/block/buzz/actions/runs/44683133967))
and passes on most pushes to `main`.
- No open PR or commit on `main` already addresses this test. #9260,
#9574 and #9725 touch `RunnerTests.swift` but not this test or its
waits.

### Cause

`setMenuOpen(true)` starts a 0.18 s `UIViewPropertyAnimator`. The test
then waited up to 2 s for both side surfaces to reach alpha 0, using
`XCTNSPredicateExpectation`.

That expectation evaluates its predicate about once a second. The
evidence is in the passing run: the test takes 4.07 s for four waits on
a 0.18 s animation, about 1 s per wait. A 2 s timeout therefore gets one
or two evaluations. RunnerTests runs inside the Flutter app, and when
the app holds the main thread across those evaluations the wait expires
although the animation finished long before. In the failing run the 2 s
timeout was reported 5.2 s after the test started, and the test's three
remaining waits then passed at about 1 s each.

This is inferred from the CI timings and the code. It was not
reproduced.

### Fix

Both waits now use a small `waitUntil` helper in the existing
`XCTestCase` extension. It checks the condition every 10 ms on the main
actor, for up to 10 s (the budget the other RunnerTests callbacks use
since #8678 and #8741). It checks the condition before the deadline on
every pass, so a main-thread stall of any length is followed by one more
check instead of a timeout.

The two conditions and every assertion after them are unchanged. If the
surfaces never merge or restore, the test still fails, at the calling
line. As a side effect the test should take about 0.4 s instead of 4 s.

### Not included


`BuzzPushNotificationResolverTests.testShownMessagesStayShownAcrossCommunitiesFailuresAndBursts`
also failed once on `main` with a 2 s timeout ([run
44682614076](https://github.com/block/buzz/actions/runs/44682614076/job/136109821029)).
It is a different mechanism: an `XCTestExpectation` fulfilled by the
resolver's own completion, across about 145 resolver runs, in the macOS
`swift test` step. The only available change is a longer timeout in a
helper shared by the whole class, and the cause of the slow run is not
established, so it is left out.

### Testing

- **Not compiled against the app and not run on a simulator.** A local
simulator build was started and then abandoned; the machine was heavily
loaded. `swiftc -parse` accepts the file.
- **The Mobile Swift (Native) lane on this PR is the first place the
change compiles and runs.**
- Pushed with `git push --no-verify`.

`buzz-review-completed` is not added: agent review and human testing
(AGENTS.md "Before opening a PR") have not happened.

🤖 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-23 16:04:24 +11:00
Tom Brow
42dc2a8c58 feat(mobile): add screen breadcrumbs to diagnostic reports (#9823)
feat(mobile): add screen breadcrumbs to diagnostic reports
Adds screen breadcrumbs to mobile diagnostic reports, so a hang or error
report shows which screens the person was on before it happened. Today
the only breadcrumbs are foreground and background changes.

## Changes

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

## Regressions

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

## Validation

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

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


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

---------

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

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

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

## Validation

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

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

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

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-22 08:00:17 -08:00
Wes
0e7fd48d41 ci(mobile): run the Mobile Swift Native lane only for native changes (#9847)
## What changes

The Mobile Swift Native job rebuilds the iOS simulator app from scratch.
On the run in #9809, `xcodebuild build-for-testing` took about 19
minutes and RunnerTests took about a minute. That PR changed the pubspec
files, so it would select Native under this filter.

For PRs, select Native for changes to `mobile/ios/`, `mobile/packages/`,
`mobile/assets/`, `mobile/scripts/`, the pubspec files, the Flutter SDK
pin, the four native test scripts, or either CI workflow that configures
it. Changes to the SDK pin or the four native test scripts also select
mobile CI. At GitHub’s 3,000-file listing limit, the selector runs all
suites.

When a PR selects mobile CI and touches none of the Native paths, Mobile
Swift runs the unsigned iOS release build and skips the debug simulator
build and its Apple Silicon linking check (#7646). Dart-only and
Android-only mobile PRs are examples.

Pushes to `main` and `release` run both Swift lanes whenever mobile CI
is selected. A RunnerTest starts the normal Dart entry point in a
Flutter engine. A Dart change that passes PR checks can therefore fail a
simulator test on the merge commit.

## Validation

- The local CI selection suite passed against the pinned
`dorny/paths-filter` action with 83 passes and eight Linux-only skips.
The required-context isolation contract also passed.
- GitHub scheduled both Swift lanes on the initial revision `a34746e6`.
Native passed in 14m35s and Release passed in 6m24s. [CI
run](https://github.com/block/buzz/actions/runs/44863694135)
- To verify hosted Release-only scheduling after merge, check the next
mobile PR that changes none of the Native paths. Mobile Swift should
show Release only, and the required Mobile check should report its
result.

---------

Signed-off-by: Wes <wesb@block.xyz>
Co-authored-by: Gamora <a0291282695a734997579812cc077d006bd2c5a73855019e537a0cddd46887c1@buzz.block.builderlab.xyz>
2026-11-21 16:41:55 -07:00
Bradley Axen
80131055dc Revert "perf(db): stop per-id planning of wide #e reads (#9591)" (#9848)
Reverts #9591 (`perf(db): stop per-id planning of wide #e reads`).
Hiding the `#e` id arrays from the planner made reads in large
communities much slower in prod. This is a straight revert.

## Evidence

- **8 → 9 row cliff on the channel head read with `include_aux`:** 125ms
at 8 rows, 1.4s at 9 rows, about 2.3s at 20 rows.
- **Replica `EXPLAIN ANALYZE`, 20-id aux query:** 130ms with the ids
visible to the planner, 2240ms with them hidden. The hidden plan reads
and discards about 625k rows in `events_p2026_07_08_legacy`.
- **200-id thread page (1,593-reply thread):**

  | ids | plan | exec |
  |---|---|---|
  | visible (this PR) | 78ms | 1,387ms |
  | hidden (#9591) | 10ms | 18,146ms |

  #9591 saves planning time but makes execution about 13x slower.
- **Prod:** #9591 reached bb-block prod with
`main-20261120032502-8d4b301` (2026-11-20 14:48Z).

## Notes

- #9674 used the same trick for thread-window aux reads and had the same
risk. It's now closed.
- Any future change like this should be checked with `EXPLAIN ANALYZE`
on the replica first. A test that runs EXPLAIN against a large community
is a follow-up, not part of this PR.

## Testing

- `cargo test -p buzz-db --lib e_tag`

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

Signed-off-by: Bradley Axen <baxen@squareup.com>
Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
mobile-v1.5.0-rc.7
2026-11-21 10:32:59 -08:00
Tom Brow
7382130948 feat(mobile): count networking events for diagnostics (#9810)
Implements the networking counts in docs/mobile-diagnostic-reporting.md:
every request through the shared HTTP client and every relay connection
event is counted, with backend (host), endpoint (from a fixed list),
outcome and kind of failure, plus a duration for requests and time to
connect.

## Changes

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

### Endpoints

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

### Failure kinds

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

## Validation

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


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

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-21 09:42:22 -08:00
Tom Brow
d1236080eb fix(mobile): bind notification replies to the account they were typed for (#9845)
A notification reply goes out as whatever account its community signs
with when the reply is sent. No sign-in path replaces a community's
account in place today: signing in again as another account adds a new
community, and hosted re-entry refuses a different key. But nothing tied
a reply to the account its notification was for, so a future in-place
credential replacement would let a reply typed for the earlier account
go out as the new one, or land in its drafts.

Each reply is now tied to the account its notification was for:

- The notification service extension records that account in the reply
context, and iOS carries it through the reply journal, so a reply
recovered on a later launch keeps it too.
- The app sends a reply, or keeps it as a draft, only while the
community still signs as that account (the key it signs with). It checks
again after connecting.
- Otherwise the reply ends as lost: iOS shows "Reply not sent" with the
text, and no draft is kept. This is the same path a reply takes when its
community has been removed ([ADR
0004](docs/adr/0004-notification-reply.md), updated here).
- A reply to a notification posted by an earlier build has no recorded
account, so it is checked only by its community, as before.

### Regressions

- A community whose notification snapshot has no account key offers no
reply action. Every signed-in community has one, since the snapshot
falls back to the key derived from its secret.
- No extra work on the send path beyond a key comparison.

### Validation

-
[notification_reply_test.dart](https://github.com/block/buzz/blob/notification-reply-account/mobile/test/features/channels/notification_reply_test.dart):
a live reply for another account and a recovered one for another
community end as lost with their text kept nowhere; a reply whose
community's signing key is replaced while the relay connects (same
community and stored key) is neither sent nor drafted; a reply from an
earlier build without an account is sent.
-
[BuzzNotificationReplyTests.swift](https://github.com/block/buzz/blob/notification-reply-account/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzNotificationReplyTests.swift):
the resolver records the notification's account, lowercased. An empty
account is rejected, and the account survives the journal round trip.
- No simulator run: the reply action needs a real push resolved by the
notification service extension, which the simulator can't receive. The
change is covered at both layers by the tests above, and the iOS app
builds.

---------

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

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

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

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

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

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

### Validation

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

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

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

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

### Regressions

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

---------

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

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

### Regressions

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

### Validation

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

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 15:25:31 -08:00
Tom Brow
2c21174c51 perf(mobile): stop measuring every character of long drafts on iOS (#9825)
On iOS, a long draft in the message composer could freeze the app. In
one case the main thread was blocked for 72 seconds.

Flutter's stylus handwriting support (Scribble) is on by default in
every iOS text field. After each frame whose text layout changed, it
measures the field's text one character at a time, so iOS knows where
each character sits on screen. Every measurement walks the paragraph's
lines, so one pass costs time proportional to the square of the draft's
length, and it runs again after every keystroke. Every sampled stack in
the hang reports sits in `EditableTextState._updateSelectionRects` →
`RenderEditable.getBoxesForSelection` → `getBoxesForRange`.

iOS also uses those character positions for the keyboard trackpad's
two-finger selection (hold Space, add a second finger, drag). So this
keeps handwriting on for drafts up to 2,000 characters and turns it off
past that, on iOS only, in the two fields where messages are written:
the composer and the message edit sheet. Android never takes these
measurements, so it keeps stylus handwriting at any length. The edit
sheet rebuilds only when its draft crosses the cutoff, not on every
keystroke. Whenever a draft crosses the cutoff, any open iPad Scribble
writing gap is closed first, because Flutter ignores iOS closing it once
handwriting is off. This holds even when the field no longer has focus,
since iOS can close the input connection itself (for example on keyboard
dismiss) without Flutter removing the gap.

At 2,000 characters a pass should cost under a millisecond,
extrapolating from the measurements below (cost grows with the square of
the length).

### Validation

One handwriting measurement pass in the running app (iPhone 17 Pro
simulator, debug build), timed in-app with a draft of `the quick brown
fox jumps over` lines:

| Draft length | Before | After |
| --- | --- | --- |
| 23,250 chars | 100 ms | 0 ms |
| 46,502 chars | 360 ms | 0 ms |
| 93,000 chars | 1,376 ms | 0 ms |

Before the fix, this cost was paid on every keystroke. Release builds on
older phones run slower than the simulator on this Mac.

- Added test: [iOS measures each character only of shorter
drafts](https://github.com/block/buzz/blob/brow/mobile-text-layout-hang/mobile/test/features/channels/compose_bar_test.dart)
checks that a short draft still sends iOS its character rectangles, a
draft past the cutoff clears them (iOS would otherwise keep the shorter
draft's), and shortening it again restores them. It also checks that a
draft crossing the cutoff while the composer doesn't have the keyboard
sends nothing, since iOS applies the clear to whichever field is
focused.
- Added test: [iOS closes a Scribble writing gap when a draft gets
long](https://github.com/block/buzz/blob/brow/mobile-text-layout-hang/mobile/test/features/channels/compose_bar_test.dart)
opens a writing gap, pushes the draft past the cutoff, then sends iOS's
own close, and checks that no gap is left in the draft.
- Added test: [Android starts stylus handwriting in a long
draft](https://github.com/block/buzz/blob/brow/mobile-text-layout-hang/mobile/test/features/channels/compose_bar_test.dart)
checks that a stylus tap still starts handwriting past the cutoff on
Android.
- Added test: [iOS closes a Scribble writing gap left after losing
focus](https://github.com/block/buzz/blob/brow/mobile-text-layout-hang/mobile/test/features/channels/message_edit_sheet_test.dart)
opens a writing gap in the edit sheet, has iOS close the input
connection, then pushes the draft past the cutoff (as a late paste
would) and checks that no gap is left.
- Added test: [iOS turns stylus handwriting off only while the edit is
long](https://github.com/block/buzz/blob/brow/mobile-text-layout-hang/mobile/test/features/channels/message_edit_sheet_test.dart)
opens the edit sheet on a long message and shortens it.
- Automated app run on the simulator, signed in to a test community:
typed in the composer, used the edit menu (Select All, Paste), sent a
message, then edited it in the edit sheet and saved.

### Regressions

- In iOS drafts over 2,000 characters, the keyboard trackpad's
two-finger selection and Apple Pencil handwriting stop working, and iOS
may place its autocorrection highlight at the field's corner instead of
over the word. Ordinary cursor movement with the trackpad, selection
handles, the edit menu, dictation and typing are unaffected.
- If a paste pushes a draft past the cutoff and undo brings back the
exact earlier text, Flutter skips resending the unchanged rectangles, so
iOS has none until the next edit or until the field scrolls (which a
long round trip usually does). Flutter offers no public way to force the
resend.
- The channel description and create-agent Instructions fields can also
hold long pastes and still pay this cost on iOS. They aren't in the hang
reports, so they're left for a separate change.

---------

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

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

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

## Screenshots and timing

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

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

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

## Verification

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

## Try it

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

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

---------

Signed-off-by: Wes <wesb@block.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz>
Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz>
Co-authored-by: Mantis <530af7635ef7d0e1a5189d234338db88cb4ef1ede7119b4ebb4fb05c3eafe3b1@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 16:03:27 -07:00
Tom Brow
5f80ee1968 fix(mobile): keep Move to section working after the actions sheet closes (#9814)
Move to section has been failing on mobile: choosing a section, creating
a new one, or removing the channel from its section throws a
`StateError` ("Using ref when a widget is about to or has been
unmounted") and the channel stays where it was.

- **Disposed ref.** The section picker opens from the channel actions
sheet, which closes first. The picker read and wrote sections through
that sheet's `WidgetRef`, which is disposed by the time the user taps a
row. It now uses the page's `ProviderContainer`, which it already used
to listen for desktop's layout lock. Channel details passed its own
`ref` the same way and now goes through the same path.
- **New section never filed the channel.** It created the section, then
looked it up by name in the provider's state, which local edits only
reached after a relay round trip. The notifier now creates the section
and files the channel in one call, by the new section's ID, so a second
section with the same name can't catch it either.
- **Local edits show at once.** `createSection`, `assignChannel` and
`unassignChannel` now emit the notifier's state right away, as
`deleteSection` already did, so a picked or removed channel moves in the
sidebar immediately instead of after the relay echoes the edit.
- The New section dialog disposed its text controller while still
animating out; the dialog now owns its controller.

### Validation

- [Move to section
journey](0147d7a0f2/mobile/test/features/channels/channel_actions_sheet_test.dart):
opens the picker from the actions sheet with the real sections notifier
(storage and relay faked) and checks the shown and saved section after
picking a section, Remove from section, and New section, including when
a section with the new name already exists.
- Automated iOS simulator run (iPhone 17 Pro, signed-in Builderlab
account): long-press a channel, Move to section, then New section (with
a name that already existed), pick an existing section, and Remove from
section. Each move showed in the sidebar immediately and no errors were
logged. The recording shows real channel names, so it is shared
internally rather than here.

### Regressions

None expected. The picker reads the same provider from the same root
scope (mobile has a single `ProviderScope`), through a handle that
outlives the closed sheet. Emitting after local edits rebuilds section
listeners once per edit, which Delete section already did.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 14:51:22 -08:00
Tom Brow
47b00c0b8b fix(mobile): keep error names in Add Members failure text (#9834)
## Summary

When adding members fails, the Add Members sheet shows each member's
error. The text came from `error.toString().replaceFirst('Exception: ',
'')`, which removes the first `Exception: ` anywhere in the text, not
just a leading one. So a relay ACK timeout read "TimeoutEvent <id> not
acknowledged within …" instead of "TimeoutException: Event <id> not
acknowledged within …".

Now a plain `Exception: ` prefix is removed only where it starts the
text or follows a wrapping error's `: `. A relay rejection still shows
as "restricted: …", and an add lost when the app goes to the background
reads "Connection lost before the relay acknowledged the event: App
moved to background" without a nested "Exception: ". Named types such as
`TimeoutException` keep their whole name.

## Validation

- New row in `channel_management_provider_test.dart`: `addMembers` with
one member whose add times out, one the relay rejects and one lost when
the app goes to the background. It checks each text in the
`AddMembersException`.

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

Full-app run on an iOS simulator (signed in, healthy relay): cold start
and session restore, channel list, opening channels and a DM with
history scrolling, channel details and the members list, Add Members
(picker, search, cancel), Settings, and background then foreground. All
passed with no new errors in the device log.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 14:48:58 -08:00
Luke Tornquist
58695fe376 acceptance: read the probe key from a file; dial a connect address (#9773)
## Summary

Follows https://github.com/block/buzz/pull/9771 (merged), which added
the acceptance CronJob.

Some NIP-FI issuers bind each key to one identity. A deployment that
mints a new identity for each run then needs a new key for each run,
written next to the assertion before the probe starts. The probe could
only take its key from an argument or the environment, which a
Kubernetes init container can't set.

- **Probe:** `--private-key-file` (`BUZZ_PRIVATE_KEY_FILE`) reads the
key (hex or nsec) from a file. It conflicts with `--private-key`.
- **Shared read:** the key file and the assertion file use one bounded
reader, `acceptance::read_secret_file`. It needs a regular, non-empty
file under a size cap.
- **Report:** the JSON report now includes `pubkey`, the hex key the
probe ran as. An operator can match a run to the identity that was
minted for it.
- **Chart:** `acceptance.privateKeyFile` is passed as
`--private-key-file`, not as an env var, so a probe that predates the
flag fails instead of running with a new key. Exactly one of it and
`acceptance.privateKeySecret.name` must be set; rendering fails with
neither or both.
- **A new key per run needs an agent assertion** (`nip-fi-agent+jwt`
whose `nostr_owner_pubkey` is a relay member). A members-only relay
refuses a new person key, and an open relay joins it to every auto-join
channel. The README and `values.yaml` say so.
- **Connect address:** `--connect-addr` (`BUZZ_ACCEPTANCE_CONNECT_ADDR`)
dials a plaintext `host:port` for every WebSocket connection and for the
NIP-11 fetch, for a probe that can't reach the relay's public host. The
relay URL still sets the `Host` header, the NIP-42 relay tag and the
NIP-11 `Host`, so the relay serves the same community. On that path,
NIP-11 uses no proxy, follows no redirect and requires a 2xx answer. The
chart passes `acceptance.connectAddr` as `--connect-addr`, not as an env
var, so a probe that predates the flag fails the run instead of checking
the public URL. The default is empty.
`NostrWsConnection::connect_to_addr` now takes upgrade headers, so the
NIP-FI assertion goes on this path too; loadgen passes none. (Folded in
from #9830.)
- **Chart version 0.1.13** with an `artifacthub.io/changes` entry. It
publishes the acceptance CronJob from #9771, the key file and the
connect address.

- **Follow-up test from the #9767 review:** the fake relay gets an
`accept_mismatched` setting, and
`access_control_fails_when_the_relay_accepts_another_keys_write` expects
`access_control` to fail at `pubkey_mismatch_rejected`. A
`pubkey_mismatch_rejected` stage that always returns Ok now fails a
test.

## What got simpler

The assertion reader's inline bounded read is now the shared
`read_secret_file`, so both secret files follow one rule instead of two
copies of it. The probe's four connection call sites now share one
`open` helper, and `connect_to_addr` reuses the same `upgrade_request`
path as `connect_with_headers`.

## Testing

- `e2e_acceptance`:
`the_binary_authenticates_with_the_key_from_its_key_file` passes against
a live relay with the key path in `BUZZ_PRIVATE_KEY_FILE` (the same clap
argument as `--private-key-file`). It checks that the report's `pubkey`
is the file's key, so a probe that ignored the file and made a new key
fails.
- `e2e_acceptance`: `the_binary_exits_2_when_it_cannot_run` covers a bad
key, a bad key file, a missing key file, and both key flags at once.
Each exits 2 with no report and no metrics.
- Existing unit tests cover the shared reader through the assertion file
(missing, empty, oversized, directory, FIFO).
- `connect_addr_dials_the_address_and_keeps_the_relay_url`: the probe
runs at an unresolvable `wss://relay.invalid` with the fake relay's
address. Every upgrade has `Host: relay.invalid` and the assertion's
bearer header, and every AUTH relay tag is `wss://relay.invalid`.
- `nip11_goes_to_the_connect_addr_with_the_relay_host` (`GET
/relay?route=probe`, `Host: relay.invalid:8443`) and
`nip11_at_the_connect_addr_does_not_follow_a_redirect` (a 301 fails
`nip11` with no version).
- `caller_user_agent_replaces_default` now covers `connect_to_addr` too.
- `tests/acceptance_test.yaml`: `acceptance.connectAddr` renders
`--connect-addr <addr>` in the args, and the default args do not have
it. The key file renders as `--private-key-file <path>` in the args,
with neither `BUZZ_PRIVATE_KEY_FILE` nor `BUZZ_PRIVATE_KEY`, a Secret
plus a file fails, and no key source fails.

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



buzz-review-completed

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
chart-v0.1.13
2026-11-20 17:27:04 -05:00
Tyler
7080811831 docs: add VISION_GOVERNANCE for community-governed git (#9618) 2026-11-20 16:30:28 -05: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
Luke Tornquist
930fd29f48 deploy: run buzz-acceptance from the relay image as a chart CronJob (#9771)
## Summary

Builds on #9767 (the `buzz-acceptance` binary, now merged). Based on
main.

- **Image:** the relay image now carries `buzz-acceptance` next to
`buzz-admin` and `buzz-pair-relay`, so no new image or workflow is
needed.
- **Chart:** `acceptance.enabled=true` adds a CronJob that runs the
probe from the relay image.
- Requires `image.tag` or `image.digest`. The chart fails to render
without one, because the default `Chart.AppVersion` image has no probe.
- Every 5 minutes by default, `concurrencyPolicy: Forbid`,
`backoffLimit: 0` (a retry would hide a failure),
`activeDeadlineSeconds: 240`.
- Runs with `acceptance.serviceAccountName` or the namespace default,
never the relay's service account. No token mount, no service links.
- `acceptance.relayUrl` (defaults to `relayUrl`),
`acceptance.stageTimeoutSeconds`.
- `acceptance.privateKeySecret.name` is required. Without a key the
probe would sign with a new key each run: a members-only relay refuses
it, and an open relay joins each new key to every auto-join channel.
- `acceptance.statsdAddr` sends DogStatsD metrics. `$(HOST_IP)` expands
to the node IP, for a node-local agent.
- Every series carries `probe_revision`, the probe's own image
(`image.digest`, else `image.tag`), plus `acceptance.tags`. It does not
identify the relay build a run reached: during a rollout, or with
`acceptance.relayUrl` set, the probe can reach another build.
`acceptance.tags` keys must be canonical (lowercase `[a-z0-9_./-]`,
starting with a letter, not ending in `_`), so the probe-owned and
repeated-key checks see the key Datadog stores.
- NIP-FI: minting an assertion is deployment-specific, so the chart
takes it as a file. `acceptance.extraInitContainers`, `extraVolumes` and
`extraVolumeMounts` let an init container write it, and
`acceptance.assertionFile` points the probe at it. These follow the
existing relay Pod extension points.
- **README:** a new "Acceptance probe" section with an example. The
example gives the minter init container the key Secret, keeps
credentials in a memory `emptyDir`, and says how to size
`activeDeadlineSeconds` against `stageTimeoutSeconds`.
- **Chart version:** bumped once at the top of the stack, in
https://github.com/block/buzz/pull/9773

## What got simpler

The chart no longer has a "no key" mode, so there is one way to give the
probe its identity. The probe reuses the relay image and the chart's
existing CronJob, image-identity, label-guard and extension patterns, so
it adds no new image, no new publish workflow, and no new extension
concept.

## Testing

- `tests/acceptance_test.yaml` (helm-unittest): off by default; the
default render (relay image, `relayUrl`, no key, no metrics, no extra
volumes); a full render with a key Secret, metrics, tags, a
digest-pinned image, and an init-container-minted assertion; the
chart-owned Datadog version label; the required image tag or digest;
`probe_revision` from the probe's image even with another `relayUrl`; no
service account inheritance or token mount; and rejection of a missing
probe key (also with an assertion file), a tag without a key, an
uppercase tag key, a tag key with a space or a trailing `_`, a
probe-owned tag key, a repeated tag key, and a chart-owned pod label.
The init-container test pins the full `initContainers`, `volumes` and
`volumeMounts`.
- CI builds the relay image from the changed `Dockerfile`.
- A kind run installed the chart and ran one Job against the in-cluster
relay: exit 0, all checks passed, no service account token. That run had
no key, no assertion and no statsd, so the key and assertion wiring is
covered by the render tests above only.

## Follow-ups (not in this PR)

- Relay build attribution: the relay does not expose its build id on a
public surface yet, so a run can't name the relay build it reached. A
deploy gate on these metrics stays report-only until it can.
- A canary run against the Rollout's canary Service needs a dial
override that keeps the canonical Host (see #9767).

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




buzz-review-completed

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:07:30 -05:00
Luke Tornquist
af8287d961 Fail CI on new triggers, functions, rules and foreign keys (#9812)
## Summary

Migrations up to `0104` dropped every trigger, function and foreign key.
`docs/database.md` Rules 1 and 2 forbid adding them back, but nothing
enforced that. This PR adds the guard.

- **Migration lint.**
`migrations_after_retirement_add_no_triggers_functions_or_foreign_keys`
scans each migration numbered after `0104`. It fails on `CREATE [OR
REPLACE] FUNCTION | PROCEDURE | TRIGGER | RULE`, `CREATE CONSTRAINT
TRIGGER`, `CREATE EVENT TRIGGER`, `REFERENCES` and `FOREIGN KEY`,
outside `--` comments. The error names the file and line, for example
`migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION`. Nested `/*
*/` comments are skipped. Quoted identifiers and string values are data,
except a string passed to `EXECUTE` or `format(`. Each dollar-quoted
body is scanned as SQL up to its closing delimiter, so DDL run through
`EXECUTE` in a `DO` block is caught, and an apostrophe inside `$$...$$`
cannot hide the rest of the file. It runs in the infra-free `buzz-db
--lib` unit lane.
- **Schema file check.**
`desired_state_schema_layout_is_complete_and_schemabot_shaped` allows
`schema/` files only under `tables/public/`, `types/`, `partitions/` and
`seeds/`, and runs the same scan on every file. A `functions/` or
`triggers/` file, or an inline `REFERENCES` in a table file, fails it.
- **Catalog check.**
`admin_schema_parity_between_desired_state_and_migrations` now asserts
that both bootstrap paths (pgschema + reconcile, and all migrations)
have zero non-internal triggers, event triggers, `public` functions and
procedures, rules and foreign keys. Extension members (pgcrypto) are
excluded. No allowlist is needed: main with all 104 migrations applied
has none of these objects.

Main now has `0105`, which passes the lint. Open PRs that add a
migration only need to renumber to `0106` or later. The two open ones
(https://github.com/block/buzz/pull/9621 and
https://github.com/block/buzz/pull/9690) add no forbidden object.

### What got simpler

- The parity test's per-table trigger comparisons (`events`,
`event_mentions`, and the five tables `0096` unguarded) and its separate
foreign-key check are replaced by one zero-object assertion.
- The scoped-key lint no longer parses foreign keys. None may exist, so
checking that they lead with `community_id` is dead logic.
- `schema/schema.sql` drops its empty `-- functions` and `-- triggers`
sections. Its header and `docs/database.md` stop describing `functions/`
and `triggers/` directories that no longer exist, and the doc's
"remaining triggers stay as a backstop" text now says they are gone.

### Checklist (`docs/database.md`)

- [x] Phase: none. Test and docs change only. No migration and no
runtime code.
- [x] No trigger, function, procedure, rule or foreign key is added.
- [x] No migration mutates rows.
- [x] Rule 4 locations: no schema change. `schema/schema.sql` changes
only comments.

### Related issue

None found.

### Testing

Run on a Linux workstation with PostgreSQL 17 at `b7254f90`, before the
review fixes. CI passed with the first review fixes at `0fed6b1b`.
`9749e618` adds dollar-quote, nested `EXECUTE $tag$` and `$1` cases to
`schema_object_lint_reports_each_construct_with_its_line`, and CI checks
it.

- `cargo fmt --check` and `cargo clippy -p buzz-db --all-targets -D
warnings`: pass.
- `cargo test -p buzz-db --lib` and `cargo nextest run -p buzz-db
--lib`: 223 passed.
- `scripts/postgres-test-run.sh` for
`admin_schema_parity_between_desired_state_and_migrations`,
`migrated_catalog_retires_universal_fences_but_keeps_deletion_guards`
and `pgschema_reapply_keeps_runtime_partitions`: 3 passed.
- Proof the lint can fail: a temporary `migrations/0105_probe.sql` with
a function and a `REFERENCES` column fails the lint with
`migrations/0105_probe.sql:2: CREATE OR REPLACE FUNCTION` and
`migrations/0105_probe.sql:3: REFERENCES`.
- Proof the catalog check can fail: a temporary `0105` that creates
`probe()` fails the parity test with `the migrations leave a trigger,
function, rule or foreign key`, `left: ["function probe()"]`.
- The catalog on main at `9c0bcd62`, with all 104 migrations applied
through psql, has no triggers, functions, foreign keys, rules or event
triggers.

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

---------

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:56:50 -05:00
Tom Brow
bc0b552894 fix(mobile): report failed reaction publishes instead of throwing (#9813)
Tapping a reaction while the relay is disconnected threw an uncaught
`RelayNotConnectedError` (a `StateError`) from
`RelaySessionNotifier.publish`, reported by Sentry from 1.5.0 builds.
Every reaction call site fires `addReaction` or `removeReaction` without
awaiting it, so any publish failure escaped as an unhandled error and
the pill just didn't change.

Now each of those call sites (pill taps, the `+` picker, the long-press
quick-reaction row and grouped system rows) hands its publish to
`reportReactionFailure`, which shows an error notice. It's a toast drawn
above any Flutter route or sheet, including the Android reaction details
sheet. While the native iOS reaction details sheet is open, that sheet
shows the notice itself as an alert, since UIKit covers Flutter's
overlay:

- "Couldn’t add reaction. No connection." (or "remove") when the relay
isn't connected;
- "Reaction not confirmed. Connection lost." or "… The relay didn't
respond." (or "Removal not confirmed. …") when the acknowledgement was
lost or late, since the relay may have accepted it;
- nothing for the relay's `duplicate:` reply to a reaction you already
have (a double tap, or re-picking it from the picker), which is a
success;
- "Couldn’t add reaction. Try again." for anything else. Errors that
aren't relay outcomes (for example the signer failing) still escape
afterwards with their stack, so the uncaught-error handler reports them
as before.

| Before (offline tap) | After (offline tap) |
| --- | --- |
| <img alt="before"
src="https://github.com/user-attachments/assets/7745ec5b-8f54-41a2-ba3d-b8dd599f127c"
width="300"> | <img alt="after"
src="https://github.com/user-attachments/assets/066fba0b-9580-4250-966e-cd0b99831ecc"
width="300"> |

### Regressions

- Successful reactions behave exactly as before: the UI still doesn't
await the publish, and the notice only appears on failure.
- Removing a reaction from a grouped system row publishes every deletion
at once as before, and shows at most one notice if any fail.
- Unexpected local errors reach diagnostics just as they did on main.
- No new state or retries: a failed reaction isn't queued. It's reported
instead of thrown.

### Validation

- Added tests in
[`reaction_row_test.dart`](https://github.com/block/buzz/blob/fix-reaction-publish-stateerror/mobile/test/features/channels/reaction_row_test.dart):
offline add and remove, a lost ack, a duplicate and an unexpected signer
failure, each with the notice it should show (or none), and whether the
error escapes; plus a failed toggle from the reaction details sheet on
Android and iOS.
- Simulator run (iPhone 17 Pro, signed in to a Builderlab community, in
a QA chat): add and remove online through the long-press quick-reaction
row, the `+` picker and the reaction details sheet. The before and after
captures come from builds that force reaction publishes to fail as if
offline (the simulator can't drop its own network). The after build
shows the toast once the quick-reaction sheet has closed.
- A failed removal from the reaction details sheet shows its notice
above the sheet, which stays open. Widget tests cover the Flutter sheet
and the native-sheet `notice` call; a simulator run with a build that
forces removals to fail showed the native alert on the iOS sheet:

After: failed removal in the native reaction details sheet

https://github.com/user-attachments/assets/b8d808f0-e86b-411f-82c0-c3d19a51b231

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-20 15:52:59 -05: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
Will Pfleger
792a9ce563 feat(relay): list and revoke invite links (#9680)
Stack: this PR → #9690

## What this does

Adds listing and revocation for v2 invite links, and makes every reader
of an invite's expiry accept a missing value.

- **`GET /api/invites?limit=&before=`** lists the community's v2
invites, newest first: id, creator, created/expiry/revoked times, uses
and a computed `status` (`active`, `revoked`, `expired`, `exhausted`).
Owner/admin only. The NIP-98 signature covers the full URL including the
query. `limit` defaults to 50 (max 200). `next_before` is an opaque
cursor holding the last row's `created_at` (microseconds) and id, so
paging doesn't depend on that row still existing.
- **`POST /api/invites/revoke`** takes exactly one of `{"id": "<uuid>"}`
or `{"code": "v2...."}`. The code is hashed and looked up only inside
the request's community. v1 and malformed codes get `400
invite_not_revocable`; an invite not in the community gets 404. Revoking
twice returns the first `revoked_at`. Members who already joined stay.
- **Authorization.** Mint, list and revoke share one HTTP admission
helper (tenant bind → NIP-98 via NIP-FI → replay → membership/ban →
NIP-OA owner link → role gate). Revoke's final decision is made in the
write transaction, in the same order as mint: admission lock → actor's
role row `FOR SHARE` → restriction check → invite row `FOR UPDATE`.
Owners and admins can revoke any invite; any other member only one they
created. A removed or restricted actor is refused. Mint now uses the
same role-lock helper.
- **Mint response** now includes `invite_id`.
- **Nullable expiry readers.** Claim, list, the mint response and
operator mint treat a missing `expires_at` as "never expires". The
column is still `NOT NULL` here.
- **Secrets.** No list/revoke response or access-log line contains a
code or its hash; request errors are fixed strings that never echo
input. Revoke logs only `invite_id`. A revoke the database refuses is
logged as denied with its reason.

## Deploy order

A follow-up PR adds links that never expire (`expires_at` nullable).
**It depends on this PR being deployed everywhere first**, so every
serving relay can read a missing expiry before one is written.

## Tests

- DB (`relay_invite/manage_postgres_tests.rs`): revoke by code targets
exactly one of two near-identical invites, idempotent revoke, community
scoping, creator demoted to member can revoke theirs, a member who
didn't create it is refused, a removed creator is refused, a restricted
admin is refused, a demotion holding the role row or a restriction
holding the admission lock makes revoke wait and then refuse with the
row unchanged, a paused claim and a revoke serialize with the member
kept, revoke is refused while the community is quiescing, paging
survives deleting the cursor row, and a row with no expiry is listed,
claimed, kept by the reaper and revocable (on a scratch database with
`NOT NULL` dropped).
- Relay (`invites/postgres_tests/manage_tests.rs`): list/revoke by id
and code end to end, no code or hash in responses, member/non-member
refusals, bad selectors, other-community lookups, query-string signature
binding, malformed requests not echoing a code in responses or access
logs, refused revokes logged as denied, and replayed list/revoke
requests refused.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-11-20 15:48:36 -05:00
Tom Brow
81b4054e5d fix(push-gateway): answer 429, not 404, when the delivery quota is exhausted (#9803)
When an endpoint's delivery quota is exhausted, both authority stores
returned `AuthorityError::Rejected`, so `/v1/deliveries` answered `404
invalid_grant`. NIP-PL already specifies `429 {"error":"rate_limited"}`
for this case.

The 404 matters because the relay treats a 404 on a retry attempt as a
terminal replay and completes the wake, so a throttled wake was silently
dropped. On a first attempt it failed the wake. A 429 takes the relay's
existing retry-with-backoff path instead.

### Change
- Memory and Postgres stores return `RateLimited` on quota exhaustion.
`http.rs` already maps that to `429 rate_limited`.
- The rate-limited attempt still charges no quota and consumes no
auth-event or request-id fence, so the relay's retry with the same
request id is admitted once the window reopens.
- No doc change: NIP-PL and the deployment doc already describe 429.

### Validation
- Memory store: an exhausted quota returns `RateLimited`, leaves replay
rows and the quota counter unchanged, and the same auth event and
request id are admitted after the window.
- Postgres (ignored test, run locally against a temporary database): the
quota-ceiling race test now also asserts the loser is `RateLimited`.
- HTTP: the eleventh delivery under a quota of ten answers `429
{"error":"rate_limited"}` and reaches no transport.
- With the two store lines reverted, all three tests fail.

### Regressions
None expected. Only the quota-exhaustion result changes; grant,
authority and replay failures still collapse to `404 invalid_grant`.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-20 20:28:35 +00:00
Will Pfleger
e21606bf96 feat(cli): leave archived identities out of users get --name (#9752)
`buzz users get --name` now leaves out identities on the relay's NIP-IA
archive list. `--include-archived` brings them back, each marked
`"archived": true`. `--pubkey` lookups always return the profile and
mark it when archived.

- The list is read by `fetch_archived_snapshot`, the same reader as
`buzz agents archived`, so only a kind:13535 event signed by the relay's
NIP-11 `self` key (with the NIP-70 tag) counts. A profile that sets its
own `archived: true` is not marked unless the signed list names it.
- Fail open: if the list can't be read, can't be verified, or takes
longer than 5s, results come back unfiltered with a JSON warning on
stderr. The search never fails because of it.
- Name searches and `--pubkey` lookups read the profiles and the archive
list in parallel. A profile error returns at once as the usual single
JSON error, without waiting for the archive read or printing its
warning. `--owner` with no matching agents returns `[]` straight away.
- Documented in the CLI README.

Out of scope: the relay and `send`/`dm`.

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

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
2026-11-20 20:09:31 +00:00
Tom Brow
51b0ea62be fix(mobile): skip the emoji picker when its opener is gone (#9820)
On iOS, opening the emoji picker from a context that had already been
unmounted threw `StateError('No ProviderScope found')` from
`ProviderScope.containerOf`. It threw after the picker had taken its
one-sheet-at-a-time guard, so every later emoji picker open in that
session was silently refused until the app restarted.

The message actions sheet hits this: its "+" tile opens the picker on
the long-pressed message row's context, which the timeline can rebuild
away while the sheet is open (the reported crash came from a phone in
landscape, tapping "+" in the quick reaction row).

`showEmojiPicker` now returns early, completing the caller's
`onDismiss`, when its context is no longer mounted, and the guard is
never taken. That tap still opens no picker (the message usually stays
on screen, but its row was rebuilt), so the user has to retry, but later
opens keep working.

### Validation

- Added [an iOS picker
test](https://github.com/block/buzz/blob/fix-ios-emoji-picker-dead-context/mobile/test/features/channels/emoji_picker_test.dart)
that opens the picker from a rebuilt-away context, then checks the
caller's dismissal runs and a later open from a live context still
presents the native sheet.
- Ran the fixed build in an iPhone 17 Pro simulator against a live
community: long-pressed a message, tapped "+" in the quick reaction row,
picked an emoji from the native sheet and saw the reaction land; then
repeated on a second message to confirm the picker opens again (with the
first pick under Frequently used). The simulator can't reproduce the
rebuilt-row race itself; the added test covers that.

### Regressions

None expected. The only behavior change is for an opener whose widget is
already gone, which previously threw and blocked the picker. Mounted
callers take exactly the same path as before.

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-20 12:02:49 -08:00
Tom Brow
eae69483fd fix(push-gateway): retry, don't drop, a delivery replayed while its first attempt is in flight (#9802)
The relay gives up on a push gateway delivery call after 2 seconds and
retries the same `request_id` with a fresh NIP-98 event. A gateway send
can take much longer than that: an FCM token mint has a 15 second
deadline, and the APNs and FCM sends each have a 15 second timeout. A
retry that arrived while the first attempt was still sending hit the
request replay fence and got `404 invalid_grant`. The relay reads a 404
on a retry as "the earlier attempt already finished" and completes the
wake. If the first attempt then failed retryably, nothing ever sent the
wake, and the notification was silently lost.

This change makes the gateway tell an in-flight request apart from a
finished one:

- Admission records the request id as in flight. A terminal outcome
marks it finished, and a retryable outcome releases it, as before.
- A replay of an in-flight id now gets `503
{"status":"retry","retry_after_seconds":5}`. Nothing is sent and no
quota is charged, so the relay's existing 503 path retries with backoff.
- A replay of a finished id still gets 404, so the relay's existing
handling of a finished attempt is unchanged.

Postgres gets a `finished` column on
`push_gateway_delivery_request_replays` (gateway migration 0009,
mirrored in relay migration 0105). It defaults to `true`, and the
gateway writes `false` explicitly on admission. Rows written before this
migration, or by an older gateway during a rollout or rollback,
therefore keep today's behavior. The constant default adds the column
without rewriting the table.

### Validation

-
[`replay_while_first_attempt_is_in_flight_is_retried_not_dropped`](3deaefb2b8/crates/buzz-push-gateway/src/http_delivery_tests.rs)
holds a first send open in the transport. It checks that a retry of the
same request gets 503 retry without sending, that the first attempt's
retryable failure releases the id so the next retry sends, and that a
finished id still answers 404.
-
[`replay_of_unfinished_request_is_in_flight_until_it_finishes`](3deaefb2b8/crates/buzz-push-gateway/src/authority.rs)
covers the in-memory store, and
[`unfinished_request_replay_is_in_flight_on_real_postgres`](3deaefb2b8/crates/buzz-push-gateway/src/postgres.rs)
covers Postgres, including that an in-flight replay charges no quota.
- The gateway's Postgres suite, including the desired-state schema
parity test, ran against a local PostgreSQL 17.

### Regressions

- A gateway that crashes mid-send now leaves the request id in flight
until the request expires, so the relay keeps retrying until its attempt
limit (8 attempts, about 10.5 minutes) or the request expiry, whichever
comes first. Before this change it got a 404 and dropped the wake.
- Admission now runs one more indexed primary-key read inside the
transaction that already locks the installation row.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-20 14:37:26 -05:00