mirror of
https://github.com/block/buzz.git
synced 2026-11-27 19:52:31 +00:00
309f5827b1c830f1102cbed0665dfd9b8a65068b
3692 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
309f5827b1 |
fix(push-gateway): keep Android enrollment retryable across replay races and restarts (#9893)
Follow-up to [#9811 enroll Android devices for push](https://github.com/block/buzz/pull/9811), covering the gateway side of its non-blocking review comments. Two enrollment states could make an Android phone discard a key its committed installation still holds, after which its fresh enrollment hits `409 installation_conflict` for the installation's whole lifetime (up to about 30 days of no push). Both now answer in a way the client already treats as "keep the key and retry". - **Enrollment replay racing the original request** ([review comment](https://github.com/block/buzz/pull/9811#discussion_r4648232889)). Enrollment consumed its challenge in one statement and created the installation in another. A client that timed out between them and replayed the same signed request found a spent challenge and no installation, and got `404 not_authorized`. Consuming the challenge and creating the installation are now one transaction. A concurrent replay locks the challenge row before judging its expiry, so it waits even when the challenge expires meanwhile, then returns the installation the first request committed, or enrolls itself if that request rolled back or was cancelled. A request that finds its challenge expired deletes it before answering `404`, so a slower request that read its clock earlier cannot spend it afterwards. A refused creation (`409`) also leaves the challenge unspent. - **Enrollment before the attestation status list loads.** A restarted gateway has no status list until its first refresh (and a list past its grace period is equally unusable), so every Android chain was refused with `401 invalid_attestation`, which the client treats as final. The verifier now reports a missing or stale list as unavailable, and enrollment answers `503 temporarily_unavailable` before spending anything. A listed certificate is still refused. - **NIP-PL** now specifies Android enrollment: the `android_attestation` chain and FCM token request, the `buzz.push.enroll.android.v1` transcript whose SHA-256 is the Keystore attestation challenge, what the gateway checks in the chain, and the SHA256withECDSA signature Android installation calls carry in `assertion`. It also records the two behaviors above, corrects the enrollment body ceiling for the Android chain allowance, names the transcript separator as one LF byte, and says a client stores its installation handle before delegating (replay recovery ends once a delegation extends the installation's expiry). ### Validation Added tests: - [`enrollment_replay_waits_for_an_uncommitted_enrollment`]( |
||
|
|
2f1be86525 |
Apply a confirmed age restriction to Android push wakes (#9925)
Follow-up to [#9804 handle Android push wakes](https://github.com/block/buzz/pull/9804), from its review: a confirmed age restriction now applies to Android push wakes, as it already does on iOS. ## What it does - A new native `AgeRestriction` holds a confirmed restriction for the life of the app process. Like the iOS restriction session, nothing is saved: a later launch starts unrestricted and the age check runs again. - The age gate's purge (`purgeAgeRestrictedNotifications`) now runs on Android. It sets the restriction and cancels every notification Buzz has posted. Restore (`restoreAgeRestrictedNotifications`) clears it. Both were iOS-only before. - On Android the restriction is released only when an age check in the current engine finishes without restricting (allowed, or failing open). The process can outlive the engine, for example after Back from the restricted screen, and a reopened app starts its age state as allowed, so releasing on that first build would lift a restriction the process still holds before the new check answers. A retired check releases nothing. iOS keeps restoring from the push bootstrap as before. - The purge starts as soon as the age check confirms a restriction, not when the restricted screen first draws. The check can answer while Buzz is in the background, where Flutter draws no frames until the user returns, so before this wakes kept posting until then. This also closes the same gap on iOS. The restricted screen still retries a failed purge, and a retry that a resume has replaced stays quiet, so a late failure can't purge again. - While the restriction holds, a push wake is skipped before it fetches anything, the same way as when notifications are turned off. - Every post from a wake (conversations and the generic "New activity") checks the restriction under the same lock the purge takes. So a wake already running when the restriction arrives posts nothing after the purge, and a post already in progress finishes before the purge cancels it. ## Decisions - **Process lifetime, as on iOS.** Wakes run in the app's process, so an in-memory flag covers every wake while the confirming process lives. A wake that starts a fresh process (after the app was killed) is not restricted until the app runs its check again. That matches iOS, where the restriction ends with the process holding its lock. - **No release-config change here.** `BUZZ_AGE_GATING_ENABLED` is still set only for iOS builds, and no build sets the Firebase config yet. Adding either to an Android build is a separate release change. ### Validation Added tests: [`AgeRestrictionTest.kt`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/android/app/src/test/kotlin/xyz/block/buzz/mobile/AgeRestrictionTest.kt) covers restrict, release and a post that is in progress when the restriction arrives. [`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/shared/push/push_bridge_test.dart) now covers the purge and restore calls on iOS and Android. The age gate's outcome table now runs on Android and counts releases: none while the check is pending, one after an adult, error, malformed or timed-out result, none after a minor. [`age_signal_provider_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/features/age_gate/age_signal_provider_test.dart)'s upper-bound table now also checks that a confirmed restriction starts the purge with no widget or frame involved. [`age_gate_app_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/features/age_gate/age_gate_app_test.dart)'s purge retry test now uses the real notifier, with a resume while the first purge is still running. On a Pixel 9a (Android 16), a debug build with a local test relay. A temporary debug hook called the native restrict and release directly, because the phone was locked and Flutter doesn't draw frames behind the lock screen: 1. Allowed: a wake posted the new message. 2. Restrict: the posted notification was removed. 3. While restricted: a wake logged `wake ignored foreground=false restricted=true` and posted nothing. 4. Release: the next wake posted both the message that arrived during the restriction and the new one. The Dart side calling purge and restore is covered by the bridge test above. ## Regressions None expected: without age gating enabled, the restriction is never set on Android. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
9bddaa1b64 |
feat(mobile): keep the message of Dart programmer errors in reports (#9822)
Makes issue titles for Dart programmer errors say what went wrong. Today
the diagnostic filter replaces every error's text, so a `StateError`
report is titled "StateError: Error text removed before sending." and
the issue list can't tell one bad state from another.
## Changes
- **Keep programmer-error text:** for `StateError`, `TypeError`,
`AssertionError` and `UnsupportedError` (which includes
`UnimplementedError`), the filter keeps the first line of the error's
own text, ending at a line feed or carriage return. Developers write
these messages (for example Riverpod's "Bad state: Using "ref" when a
widget is about to or has been unmounted is unsafe."), so they name the
fault. Every other error type still has its text replaced. The text is
kept because of the error's type, whichever code threw it (the app, a
package or the SDK), so the accepted risk is a message that interpolates
a value the URL and key checks miss, such as a short secret or a
fragment of what someone wrote.
- **Text with a URL or a long line is replaced:** where a URL ends in
free text is ambiguous (quotes, spaces, a scheme inside a word), so a
first line gets the fixed wording instead of having its query string
stripped when it contains `://`, a `?` or `#` after a `:` in the same
word (a `mailto:` link has no `//`), or any other `?` or `#` followed by
anything but closing punctuation before the next space. Nullable types
such as `List<String?>` keep a type error readable. Object identity
hashes such as `RenderFlex#1a2b3` are removed first, so Flutter and
Riverpod titles that name an object stay readable. A first line over 200
characters gets it too, since long lines and the lines after the first
usually quote other text such as a response body or a wrapped error.
- **FlutterError stays replaced:** the SDK reports a `FlutterError` as
"AssertionError" because it implements one, so the filter checks the
thrown object itself, and a `FlutterError` is excluded before the
programmer-error check.
- **Spec, ADR and glossary:** the spec, ADR 0007 and CONTEXT.md name the
kept first line and state that accepted risk.
## Validation
New tests cover each kept type keeping only its first line (split by a
line feed or a carriage return), nullable types staying readable, the
fixed wording for text with a URL (including one with an apostrophe, one
inside a word and `mailto:` and `tel:` queries starting with
punctuation), fragments, provider names with and without an argument, or
a long line, `FlutterError` and other errors still replaced, and the
type identifier the SDK installs.
Full-app simulator run at
|
||
|
|
7c5cce1418 |
fix(mobile): pass the relay call to the wake resolver's bounded query (#9950)
## Summary Main no longer analyzes: `RelayHttpQueryClient.sendBounded` gained a required `call` parameter in #9821, while #9804 added a caller in the push wake resolver without it. The two landed separately, so neither PR's CI saw the combination. The wake resolver's request is a `/query` POST, so it passes `RelayCall.query`. Its timeouts become `RelayTimeoutException`, which still extends `TimeoutException`, so the resolver's handling is unchanged. ## Validation - `flutter analyze` on the mobile app is clean. - `flutter test test/shared/push` passes. Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
9f56569f6f |
test(mobile): hold a push wake claim past the deadline instead of timing it (#9919)
## Summary The push wake journey test checked the case where storage is still claiming messages when the wake's budget runs out by giving every claim a 100 ms delay and racing it against a 700 ms budget. On a loaded machine a claim could land just after the 250 ms claim grace, be recorded as shown, and never be returned, so the test's "partial plus rest is everything" check failed intermittently. The test now holds exactly one claim open until the wake has answered, then releases it, and checks: - the held message is not in the wake's notifications; - its community is reported as failed, so the wake is incomplete; - every other message is shown exactly once across this wake and the next. A new `HeldClaimShownMessageStore` test helper holds the claim. No production code changes. ## Validation Test-only change. The rewritten case passed 3 of 3 consecutive runs locally. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
e8a8e4cb6a |
feat(nip-fi): scope disconnects to tokens issued through revoke_through, stored durably (#9917)
## Summary Builds on #9860 (merged as `c0932db19c`). A NIP-FI disconnect command can now carry `revoke_through` (C), an integral NumericDate. With C, the relay refuses and closes only assertions whose verified signed `iat` is at or before C, until `until`. Tokens issued after C are admitted straight away. Without C, the deny covers the whole key, as before. - **Spec:** `docs/nips/NIP-FI.md` adds the `revoke_through` claim and a Deny scope section (admission, close scope, merging, records, the issuer's duty) with a behavioral oracle. The existing deny, command-algorithm, oracle and security text now carry scope. The deny set's storage text is #9860's (shared storage, restored before admission); this PR adds no wire claim or storage schema to the spec. - **Parsing:** a `revoke_through` that is `null`, nonnumeric, fractional or unrepresentable is rejected as `evidence_rejected` before any state changes. - **Verified `iat`:** `VerifiedAssertion::issued_at()` comes from the time-checked `iat`, not from profile evidence. `NipFiSession` records it at registration. - **One predicate:** `DenyScope::covers` compares the full verified instant (fractional `iat` included) against C. It decides admission (WebSocket and HTTP, with asserted key and owner checked separately) and every close scan (root and audio registries, the command route, cross-pod delivery, shadow accounting). - **Merge:** `DenyEntry::merge` takes the later `until`. Whole-key beats a cutoff, two cutoffs merge to the larger C, and expired entries contribute nothing. Activity is read from a clock sampled inside the issuer shard lock, so an entry that expires while a merge waits contributes nothing. A past-`until` command still does its scoped close without changing an active entry. The close scope widens to any stronger active entry, and a poisoned shard closes the whole key. - **Bus:** `NipFiDisconnect.revoke_through` is optional. A message without it means whole-key. - **Durable cutoff (Redis):** the cutoff lives in its own per-issuer hash, `<deny prefix>-revoke-through:<sha256(iss)>`, field `pubkey_hex`, value C. The exact-`until` hash keeps only `secs:nanos`. One accept script merges `until` and scope by the same rule as `DenyEntry::merge` and gives all three keys one expiry. It judges whether the command and the stored entry are still active by Redis `TIME` as it runs, not by the authentication clock. Before any write it checks the target's stored cutoff by restore's rule: a disconnect over an unreadable one returns `unreadable`, `try_claim` fails (`503`), the claim stays unused and nothing is recorded. Restore judges expiry when it merges. Restore reads both hashes in one script and joins them before merging, looking deny keys up in a set (linear at capacity), so a missing cutoff field is a whole-key deny. A cutoff that isn't an integer, or names no deny, is `reason="unreadable"`. As in #9860, one bad record does not hide the others: restore still applies every readable deny (a deny under a malformed cutoff as the whole key; an orphan cutoff adds nothing) and then fails, so admission stays closed. `LoadDenies` and `LoadDeniesError::Unreadable { readable }` now carry `DenyEntry`, and a restore counts a same-`until` scope widening as changed, so it closes the sessions it newly covers. - **Runbook:** `docs/operator-nip-fi-bindings.md` names the cutoff hash and how to clear a bad cutoff. It warns that deleting an orphaned cutoff leaves no deny at all, and that a disconnect over a bad stored cutoff fails until it is cleared. ## Deploy and rollback Deploy this to every relay pod before any issuer sends `revoke_through`. Until then, a pod still on the old build ignores the claim and blocks the whole key, so the agent stays locked out until its old token expires. Rolling a relay back to #9860 is safe. That build reads only the exact-`until` hash, which this PR writes in the same format, so it restores every cutoff as a whole-key deny and never fails its restore on this data. It ignores `revoke_through` in commands and bus messages, and every accept it makes clears the target's stored cutoff, so its whole-key revokes are never narrowed by a cutoff this build stored. All of this only over-blocks: agents wait for their old tokens to expire instead of getting back in at once. ## Testing Behavior tests cover old and fresh tokens at admission and in close scans, redelivery leaving fresh root and audio sessions open, cross-pod delivery, an owner whole-key deny blocking a fresh agent token, same-deadline scope changes in both orders, an expired whole-key entry followed by a cutoff, past-`until` commands, invalid `revoke_through` values, legacy bus messages, fractional `iat` at C and C + 0.5 through real verification, replay-claim waits that cross an entry's expiry, and root/audio handler straddle cases where the signed `iat` differs from registration time. Each of these was checked to fail when the code it guards is broken: - the route's published bus message keeps the cutoff on another pod (fails if `nip_fi_disconnect_message` drops `revoke_through`); - a cutoff command over an active whole-key entry closes a fresh session (fails if the route skips close-scope widening); - a poisoned shard's close scope is whole-key; - shadow `would_close` ends only sessions issued at or before C; - a cutoff in Redis restores as a cutoff (fails if the accept script stops writing the cutoff hash), and #9860's reader, taken from its final head `02627cce`, decodes the same record as a whole-key deny; - #9860's writer, copied verbatim from `02627cce`, writing over a stored cutoff with an equal or shorter `until`, then a fresh restore by this build, gives a whole-key deny; - a full revoke that expires between authentication and its Redis write neither widens a cutoff nor, once stored and expired, overrides one (fails with the authentication clock); - a whole key that is live when restore reads and expired when it merges gives way to the stored cutoff (the load is gated, not slept; fails if restore merges at the pre-read time); - the Redis merge matches `DenyEntry::merge` for whole-over-cutoff, cutoff-over-whole, two cutoffs under a shorter or longer `until`, and an expired whole key (fails if a whole-key write stops clearing the cutoff); - pruning clears an expired entry's cutoff, from a fixture seeded already expired in one atomic step; - a same-`until` scope widening is `Merged`, not `Unchanged` (fails if the change test compares `until` only); - a cutoff that isn't an integer, is out of range or has no deny fails the restore as `unreadable`; - a malformed cutoff leaves its deny restorable as the whole key, an orphan cutoff adds nothing, and a good cutoff still scopes its key, while the load still fails as `unreadable`; - a disconnect over a complete active deny whose stored cutoff is fractional or out of range fails with the claim unused and the index (with scores), exact and cutoff hashes unchanged (fails with the accept script's check removed); the script's bounds are pinned to chrono's range. - through the real Redis load and restore, a readable deny next to a bad record keeps its cutoff: a session issued at C is closed, one issued after C stays open, and admission stays fenced (fails if the partial payload drops scope). --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
61c070d591 |
perf(mobile): derive Active filter activity from the channel list, with no per-channel relay reads (#9832)
The Active section filter needs to know when each channel last had a message. Since #8479 (saved channel section filters) and #9796 (section filter refinements), the app has looked that up with its own relay history read per channel in every section that uses the filter. Since #9885, main caches what the channel list's read and live delivery saw for each channel (its latest post, or that it has none), and looks a channel up only while the list has no cached evidence for that channel. The lookup's own answer is not cached, so it runs again on every resume while that lasts. A failed lookup shows the notice with Retry at once and is also retried automatically up to three times. Channels the list's batched read misses (for example when it fails or hits its deadline) and every channel after a channel list rebuild, which clears the cache, all go through that lookup. With many channels, those reads compete with the channel list's own reads and the read-state sync for the relay's request budget. When they time out or get rate limited, the app shows an "activity couldn't load" notice, and the same pressure can delay other requests such as read-state sync. The channel list already reads each channel's latest messages in one batched request when it loads. This change records the newest message time from that read (self-authored and muted messages included, unlike `lastMessageAt`) and keeps it current from live delivery and from the unread catch-up the list already sends after a reconnect. Where that catch-up starts after posts no read has covered yet (for example, a post that arrived while offline and was read on another device), a separate small request sent after the catch-up asks for the newest one with a single `limit: 1` filter per such channel. It is sent only for channels an Active section is showing, only when the gap could hold a newer post than the one already known (including one the catch-up itself just verified), and without the per-channel websocket fallback, so a failure there leaves only that channel's activity unknown and never delays unread state. A successful refresh replaces a channel's time, so a deleted latest post stops counting, while keeping any newer message that arrived during the read. Only messages whose signature verifies count, and the app verifies only a message that would change a channel's activity. When a channel's latest post is deleted, live or while offline, the app forgets that channel's activity, so it reads as unknown (and stays visible) until the next background list read re-reads it on resume, reconnect or a list change, if an Active section shows it. A channel the last list read missed is asked for again the same way. The Active filter reads that value, so it sends no relay requests of its own. This replaces main's cache together with its fallback lookup, the lookup's retries and Retry. Because the filter can no longer fail on a lookup, the "activity couldn't load" notice is removed too. ### Validation - **Network impact.** Before: one history read for each channel in an Active-filtered section while the list has no cached evidence for that channel, again on each resume while that lasts, with up to three automatic retries plus a manual Retry when it fails. After: no reads of its own. The filter reuses the list's existing batched read. Only for channels an Active section shows, the next background list read asks again for a channel whose latest post was deleted or failed verification, and a reconnect may send the gap read below. - Provider tests check that activity comes from the list read, live delivery and a reconnect's catch-up; ignores a message with a bad signature; includes self-authored messages; counts a future-dated post as now; leaves `lastMessageAt` untouched and sends no extra requests; stays unknown (the channel stays visible) when a read or catch-up fails; survives a same-community rebuild; picks up a post read on another device while offline, including after an offline rebuild resets the unread cursor; drops a deleted latest post on refresh, and forgets it until the next list read on a live deletion or a deletion the catch-up returns; skips the gap read for a channel no Active section shows, or one whose catch-up found a newer verified post; asks again for a channel whose list read had no verifiable post; and keeps a live post that arrives during a refresh. - Simulator run on a signed-in community: set a section to Active (7 days), then backgrounded and resumed the app and pulled to refresh. Inactive channels stayed collapsed under Show more, and no notice appeared. ### Regressions - Signature checks for read and catch-up results run in a background isolate and check only each channel's newest message, so only those messages are copied off the UI isolate. A channel whose newest message fails verification is not updated by that read (unknown after a catch-up or gap read, so it stays visible) instead of falling back to an older one. Unread state from a catch-up is published first; its activity lands once those checks finish. A live message is checked on the UI isolate, and only when it is newer than the known activity. - Channels the batch doesn't cover (for example non-member or archived channels, or a batch that hits its deadline) have unknown activity. The filter fails open for them, so they stay visible, which matches how it treated a failed lookup before. - A catch-up that finds only newer self-authored, muted or already-read messages now republishes the list once, so the filter sees them. Before, it published nothing. - After a reconnect, channels an Active section shows, whose catch-up would skip posts no read has covered, get one `limit: 1` filter each in one small extra request, sent after the unread catch-up. It adds at most one event per such channel, against main's per-channel lookup (with its retries) for every Active channel the list has no cached evidence for. A rate-limit refusal of either request still pauses the session's reads, since the relay's quota covers every request this client makes. - A channel with a gap to read reads as unknown, so it stays visible, until that read answers. - A channel no Active section shows, whose catch-up would skip uncovered posts, reads as unknown until a later catch-up runs while it is shown. - A channel whose catch-up or gap read fails (including a catch-up that fails before sending) reads as unknown, so it shows unfiltered until a later read succeeds. A failed gap read is not retried by itself; the next list read's catch-up asks again, so it adds no retry traffic. - A post dated ahead of the device clock (the relay accepts up to 15 minutes) counts as activity now. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
0966f3fad6 |
feat(mobile): tag escaped relay errors with their call and reason class (#9821)
Makes relay errors that nothing catches readable in diagnostic reports. Today an unhandled relay rejection or timeout arrives with its text removed and a stack that stops at the async error handler, so a report can't say which call failed or why. ## Changes - **Typed call and reason:** relay errors now carry the call (`publish`, `query`, `history`, `subscribe`) and a fixed reason class taken from the relay's reason prefix (`invalid`, `rate-limited`, `restricted`, `auth-required`, `blocked`, `duplicate`, `pow`, `unsupported`, `error`, `timeout`, or `other`). Types: - `RelayEventRejectedException` implements the new `RelayCallError`; - new `RelayTimeoutException` extends `TimeoutException`, and `RelayAckTimeoutError` now extends it; - new `RelayClosedException` replaces the plain `Exception` for a closed history or live subscription, with the same `toString`. - new `RelayQueryException` (a `RelayException` that is also a `RelayCallError`) for a non-2xx `/query` answer, with its reason from the status alone; - a one-shot signed event the relay refuses now fails with a typed rejection, with the same text. Existing `TimeoutException` checks and message helpers behave as before. - **Report tags:** before the filter runs, a report whose error is a `RelayCallError` gets `relay.call` and `relay.reason` tags. The relay's own text is never sent. These reports are also grouped by call and reason on top of the default grouping, so a rate limit and an invalid request from the same code become separate issues. - **Call-site stack:** pending publishes, one-shot signed events, and history and live subscriptions keep the stack where they were created, and errors completed later from timers or socket callbacks use it. A report's stack now reaches the calling code. - **Spec:** one bullet on the tags, the grouping and the stack. ## Validation New tests: - a table of reason prefixes to classes; - error types, fields and the existing message helpers; - relay session cases: a rejected publish's call, reason and calling stack, the timeout types, and closed subscriptions; - reports: tags, the grouping key, no relay text, and non-relay errors untouched. - production refusals through a serialized report: `/query` statuses, snapshot `/query` versus discovery, and one-shot rejections and timeouts with the caller's stack. Full-app run on an iOS simulator (signed in, healthy relay): cold start and session restore, channel list, opening channels and DMs, history back to each channel's start, send, react, edit, thread reply, search, channel details and Add Members, Settings > Send test report, and background then foreground followed by a send and a delete. All passed with no new errors in the device log, and no doubled error names in any logged text. Error paths (timeouts, closed connections, relay rejections) weren't triggered on the healthy relay; the unit tests above cover them. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
c0932db19c |
fix(relay): persist NIP-FI revocations across restarts and bridge shadow to enforce (#9860)
## Summary Stack: this PR → #9917 NIP-FI revocations (deny entries from `POST /api/nip-fi/disconnect`) now survive relay restarts and lost pub/sub subscriptions, and an enforce relay can optionally carry over revocations accepted during the `shadow` period. ## Changes - **Durable deny store (Redis).** Per mode and issuer hash, a sorted set (score = `until` in ms, rounded up) plus a hash holding the exact signed `until`, merged by maximum. One Lua script runs all checks before any write: replay → expiry/capacity → write. Outcomes: claimed, replay (403), full (503, nothing written). Every write and prune also clears the target's field in the issuer's revoke-through cutoff hash, so a full revoke is never narrowed by a cutoff a newer relay version stored. A Redis error is an unknown outcome (503); the issuer sends a fresh command. - **Shared capacity.** `deny_set_capacity` is enforced in Redis, across pods. - **Fail-closed restore.** A pod starts closed to protected admission, refusing as authorization unavailable (HTTP 503 and the matching Nostr denial on root and audio AUTH; `shadow` records it as unavailable). Active deny entries still refuse with 403. Each key's verdict (allowed, denied, unavailable) comes from one read of the deny map, so a restore that starts mid-check is never reported as a revocation. A single consumer task restores by generation: wait for a confirmed subscription, load the stores, apply buffered messages, then reopen. A reconnect, a lag, or a received deny that does not fit the local capacity starts a new generation, so admission reopens only once the active union fits. A restore merges every stored entry first, then closes sessions only for targets it added or extended (also when it fails part-way; a capacity miss or a store error for one issuer or source doesn't end the pass, so every reachable target is still merged or closed and the first failure keeps admission closed), so restoring after a Redis blip doesn't walk every connection once per entry. While a restore keeps failing, the consumer still applies disconnects that arrive, so revoked sessions close while admission stays closed; the retry runs on a fixed one-second deadline that traffic can't push back. A stored deny record that doesn't parse fails the restore rather than being skipped; the issuer's other records are still applied and their sessions closed. Restore failures are counted in `buzz_nip_fi_deny_restore_failures_total{reason}`; a stored record that doesn't decode is counted as `reason="unreadable"`, apart from `store` (Redis unavailable). - **Bridge setting.** `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS` (default false, enforce only) makes an enforce pod also subscribe to the shadow channel and restore the shadow store. - **NIP-FI spec.** Restart behaviour now allows shared storage that is restored before protected connections or HTTP requests are admitted. Disconnects document the unknown-outcome reply: when a relay can't tell whether its shared-storage write applied, it returns `503` `authorization unavailable` and closes no sessions, and the caller retries with a freshly signed command (new `jti`). Added to the step 7 pseudocode, the disconnect response table and the `authorization_unavailable` rejection row. - **Runbook.** New "Revocation during a deploy" section in `docs/operator-nip-fi-bindings.md`: coverage (restarts, not lost Redis data), non-evicting Redis, disconnect responses, capacity, boot behaviour when Redis is unreachable, recovering from an unreadable deny record (`HDEL`), and the shadow → enforce rollout steps. ## Tests - Restart restores denies from the shared store; unavailable store keeps admission closed; consumer reopens only for a live, restored subscription. - Store error returns 503 and the command retries; lost reply returns 503 and needs a fresh command. - Capacity enforced across pods; over-capacity restore stays closed; a capacity miss during the restore handoff or after a successful restore keeps or closes admission. - A restoring deny map refuses as unavailable (503 / bare close), not revoked, at each admission point: WebSocket upgrade, protected HTTP, root AUTH and audio, and when the restore starts during the check. - Restore closes only added or extended targets, still closes them when it fails part-way (a capacity miss, a failing source before a healthy one, and the first-visited issuer failing before a healthy one, and an unreadable record reported as `unreadable`, not `store`), and live delivery of an unchanged entry still closes sessions. A broadcast lag after a restore restores again. During repeated restore failures, delivered disconnects still close their sessions, admission stays closed, and steady traffic doesn't delay the next attempt (run on a paused Tokio clock). - The buzz-pubsub deny-store key and rounding unit tests now run in `just test-unit` and `run-tests.sh`. - Subscribe channels and restore sources follow mode and bridge; config rejects the bridge outside enforce. - Redis-backed (ignored, run in CI's NIP-FI Redis step; each case uses its own store namespace): script checks before writing and keeps exact `until`; expired entries free their slot and a shorter command never lowers a score (`ZADD GT`); bridge restores shadow-period denies on enforce pods; a record with an unreadable key or `until` fails the load while every readable active record after it still loads, and expired entries are still filtered; restore applies a good record past a bad one for the same issuer, closing its sessions and leaving others open, fails as `unreadable` with admission unavailable, and reopens on retry once the record is removed (fixture hashes expire after 60s); an accept with an equal or shorter `until`, and a prune, clear the target's stored cutoff. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: wpfleger <wpfleger@users.noreply.github.com> |
||
|
|
166245b4f9 |
chore(db): accept the activity cache tables before their migration (#9815)
## Summary **What it does.** It tells community deletion that two tables, `channel_heads` and `thread_heads`, may exist. It lists them in `PENDING_SCOPED_TABLES` and `APPROVAL_FORWARD_TABLES`. This release creates no table and changes no schema. With it deployed, deletion accepts both tables whether or not they exist yet. When they exist, it purges their rows and verifies them. It also still executes a deletion that was approved before they appeared. **Why.** #9756 adds these two tables as caches for the `/buzz/v1` activity list. Deletion's catalog check is an exact set. A relay without this change would see them as unknown tables after #9756's migration runs, and community deletion would fail for every community: during the rollout, and again after any rollback. `docs/database.md` ("Adding a tenant-owned `community_id` table", and the table in *What breaks the old relay*) asks for this precursor release. **Order of rollout.** 1. Merge and deploy this PR to every relay, deletion executor and operator CLI. 2. Then merge #9756, which creates the tables (migration 0105) and moves them to `EXPECTED_SCOPED_TABLES`. This PR's release becomes the rollback floor once that migration runs. **This must ship and deploy before #9756.** **What users will notice.** Nothing. **Out of scope.** The tables themselves and everything that uses them are in #9756. ## Testing - `cargo test -p buzz-db -p buzz-deletion` (unit tests, including the list invariants) passes. - Against a local Postgres: `pending_scoped_tables_are_optional_purged_and_verified` passes with both tables on the list. - `approval_before_an_expand_migration_completes` needs S3 and Redis and is outside the Postgres lane, so it runs only where that infrastructure exists. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Jude Edwards <judeedwards@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
e68cd09794 |
feat(search): keep an OpenSearch message index in sync through a Postgres outbox (#9838)
## Summary
This PR keeps a second copy of the message index in OpenSearch. Searches
still run on Postgres. Each searchable message writes a small "index me"
row to a new Postgres table, `search_outbox`, in the same transaction
that stores it. One relay drains that queue into OpenSearch. Writes
never wait on OpenSearch, and if it is down, rows wait in the queue.
```mermaid
sequenceDiagram
participant Client
participant Relay as Relay (admission tx)
participant PG as Postgres
participant Idx as Indexer (1 leader)
participant OS as OpenSearch
Client->>Relay: kind 9 "flamingo"
Relay->>PG: INSERT events + INSERT search_outbox (same tx)
loop every 5s, backing off up to 60s on failure
Idx->>PG: claim ≤500 rows of one community (SKIP LOCKED)
Idx->>PG: re-read those events (+ channel, thread, mentions)
Idx->>OS: one bulk request: upsert docs, delete missing ones
Idx->>PG: DELETE the claimed rows, COMMIT
end
```
- **Turn it on** with `BUZZ_OPENSEARCH_URL` plus
`BUZZ_OPENSEARCH_PREVIEW=true` (optional basic auth: set both or
neither). Without the opt-in, a relay with the URL refuses to start. The
relay refuses to start if migration `0106` has not run. Without the
setting, each insert pays one flag check.
- **Queue** (`migrations/0106`, `search_outbox.rs`): one row per stored
message of kind 9, 40002, 40008, 45001 or 45003. A rolled-back write
takes its row with it. The indexer re-reads each event, so duplicate
rows are harmless.
- **Indexer** (`indexer.rs`): one leader, chosen with a Postgres session
advisory lock. A batch holds its community's write transaction until the
bulk request ends, so deletion can't fence the community mid-batch. HTTP
400/413 skips that community for the pass. Any other failure ends the
pass and backs off. Batches have no byte cap yet, so a cluster with a 10
MiB request limit can reject a full batch; #9862 caps requests at 8 MiB.
- **Index** (`opensearch.rs`): alias `buzz-messages` →
`buzz-messages-v1`, strict mapping, message text indexed but not stored.
Writes require the alias, so they never create an index. Searches filter
on community first and fail rather than return partial hits.
- **Deletion:** community deletion fences and purges the community's
queued `search_outbox` rows with its other rows. It doesn't touch
documents already in the index.
- **Infra:** an opt-in `opensearch` service in docker-compose
(`--profile search`). The CI Postgres job starts OpenSearch 2.19.3. The
−1,895 lines move the Postgres search tests into `tests/search_suite/`,
which now runs against both backends.
### Worth knowing
- **A rejected batch blocks its community.** Rows are claimed oldest
first, so the same batch comes back every pass. Other communities still
drain, but each rejection counts as a failure, so passes slow to 60 s
apart.
- **Text isn't stored in the index,** so a new mapping version needs a
full backfill from Postgres. No backfill exists yet, so messages stored
before the setting aren't indexed.
- **Not for relays with real data yet.** Deletes, edits and account
scrubs don't reach the index until #9862, and nothing purges a deleted
community's documents. Searches never return them, since every hit is
re-read from Postgres, but their words stay in the index. So the relay
requires the `BUZZ_OPENSEARCH_PREVIEW` opt-in, which #9862 removes.
- **Coverage gaps:** each relay queues only what it stores, so set the
URL on every relay.
- **Delay:** up to ~5 s of polling plus a 30 s refresh before a message
is searchable.
### Testing
CI's Postgres job now runs the shared search suite and the outbox sync
tests against a real OpenSearch. For a local run, see
`docs/opensearch-search-deployment.md`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Salman Mohammed <smohammed@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
54e2d25f69 |
chore(deletion): accept the search outbox and backfill tables before they exist (#9871)
## Summary Community deletion checks the database's community-scoped tables against an exact list and fails closed when it finds a table it does not know. The OpenSearch indexing stack that starts at #9838 adds two such tables, `search_outbox` (migration 0106) and `search_backfill` (migration 0107). A relay from before that stack, running after those migrations, would refuse every community deletion with "community deletion catalog drift (missing=, unknown=search_backfill,search_outbox)". That happens in a mixed fleet during the rollout and after a rollback. This PR lists both tables in `PENDING_SCOPED_TABLES` and `APPROVAL_FORWARD_TABLES` in `crates/buzz-db/src/store/deletion.rs`, so a release without the tables already accepts them. Neither table has a foreign key, so purge order does not matter. Nothing else changes: the tables do not exist yet and nothing writes to them. This release must reach every relay, deletion executor and operator CLI before the migrations run. The stack's own copies of this change get dropped when it is rebased onto this. ### Related issue N/A. Prerequisite for #9838 and #9862. ### Testing The existing table-driven tests for pending tables and approval forwarding cover both new entries. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Salman Mohammed <smohammed@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>mobile-v1.6.0-rc.1 |
||
|
|
36e6e4f8e7 |
fix(mobile): apply message edits only from authorized authors (#9887)
## Why Buzz mobile now checks who signed each edit before deciding what to show in a channel or thread. That includes edits to the first message of a thread loaded from local storage. Mobile also preserves the information needed to verify edits after an offline restart and retries missing profile lookups when the app reconnects. The companion relay change is #9886. ## Mechanism Mobile uses the first valid message reference on an edit and shows the newest edit that passes its checks. It accepts edits from the original message’s signer. If the relay signed the original, mobile also accepts edits from the author named by the relay. A verified agent owner can edit the agent’s chat messages (kinds 9 and 40002) and diff messages (kind 40008) in the same channel. **Agent owners.** Mobile verifies the owner named in the agent’s signed profile. The app reads permission when a user opens the channel or thread message menu or the image actions. The native photo viewer also reads permission when it opens and checks again before deleting. These paths and the timeline use the same signed profile to verify the owner. When an agent’s signed profile names an owner, mobile saves the signed event once and reads fields such as the name and avatar from it on restart. If that entry exceeds the 16 KiB limit, mobile saves the display fields alone if they fit. Mobile needs the signed profile to verify the owner. When the app connects, it asks for profiles needed to check edits in the current timeline and retries unresolved lookups on reconnect. The cache skips profiles it has already checked with the relay and public keys the relay recently reported as having no profile. Once mobile loads a newer profile from the relay that no longer names the owner, it stops applying that person’s edits. The next time that person opens the message menu, Edit is absent. In the device test, both changes took effect after restarting the app. **Relay signing key.** While connected, mobile looks up the key if the timeline contains an edit whose signer differs from the original message’s signer and the original has a public key in an `actor` or `p` tag. A mention in a `p` tag can also trigger the lookup. Mobile uses that tagged author only after confirming that the relay signed the original message. Mobile keeps the last key during reconnects and can read it from the saved-message store after an offline restart. If the timeline still needs the key when mobile reconnects, mobile refreshes it so a rotated key can take effect during the same session. A failed request or a response without a key leaves the previous key available. Thread summaries read the key available when they refresh and start no key lookup. ## What changed - Start with `edit_authority.dart` for the profile and key lookups and the permission check that runs when actions open. See `timeline_message.dart` for edit selection and `thread_detail_helpers.dart` for the first message of a thread loaded from local storage. - See `verified_profile_owner.dart` for ownership verification, `profile_snapshot.dart` for storage and restore, `user_cache_provider.dart` for profile refreshes, and `SavedMessageStore.relayAuthor` for the saved relay key. - Tests cover edit selection, owner edits to chat and diff messages, and edits to a saved thread’s first message after replies load. They also cover opening message and image actions, restored profiles without a signed copy and profiles signed by the wrong key, reconnect retries, offline reopening with a large signed profile, and a newly fetched relay key replacing a saved key. Tests also verify that the native photo viewer blocks deletion if permission is withdrawn while it is open, that opening message actions requests a fresh profile when the saved profile names the viewer as owner but lacks a signed copy, and that a tampered saved profile cannot verify ownership. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Stephen Edwards <sedwards@squareup.com> |
||
|
|
ed29172fbb |
fix(mobile): name blocked agents clearly, let owners remove their agent from a DM (#9921)
## Problem Two follow-ups to growable DMs on mobile, matching desktop block/buzz-app#3744: 1. When an agent's add policy blocks a DM, the message names the agent by display name only, so two agents called "Scout" read the same, and it never says whose owner to ask. 2. Once you add your own agent to a DM, you can't take it out. The relay allows it, but mobile hid Remove in every DM. ## Change **Name the blocked agent clearly.** The refusal now uses the app's identity labels for the agent and its owner: - Only its owner can add it, owner known: "Only Morgan can add Scout to a DM." - Only its owner can add it, owner unknown: "Only the owner of Scout can add it to a DM." - No one can add it: "Scout can't be added to a DM." - When adding to an existing DM, all start with "Couldn't add them." - If the name can't be read, it says "this agent". Labels are compared against the people in the DM, so two same-named agents read as "Morgan's Scout", and an agent that shares a person's name reads as "Scout (agent)". The owner is named only when it is verified from the agent's signed profile. **Let owners remove their own agent from a DM.** On a DM member's profile, an agent you verifiably own now has "Remove from DM", confirmed with "Remove from DM?". People never get Remove in a DM, and admin and role actions stay out of DMs, matching the relay rule. ## Screenshots Temporary widget renders with test data, not committed. The refusal render passes the shared wording a known owner and a disambiguated agent label; label resolution itself is covered by the tests below. ### Blocked agent | | Light | Dark | |---|---|---| | Narrow |  |  | | Wide |  |  | ### Remove from DM | | Light | Dark | |---|---|---| | Row, narrow |  |  | | Row, wide |  |  | | Confirm, narrow |  |  | | Confirm, wide |  |  | ## Tests - Wording for every case, plus opening and adding with a verified owner, two same-named agents, an agent sharing a person's name, and owner unknown. - Remove from DM: the owner removes their agent after confirming; no Remove for another person's agent, an unowned agent, or a person. 🤖 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@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: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> |
||
|
|
d4c0729a86 |
fix(mobile): Android push follow-ups from enrollment review (#9892)
Follow-ups from the review of #9811 (Android push enrollment): the review items that were safe to leave for after merge. - **A timed-out gateway call is now aborted.** The 15 s timeout used to abandon the POST while it kept running, so a retry could race the original request at the gateway. The gateway client now sends through `boundedHttpResponse`, which aborts the request at the deadline (and caps the reply size). - **An Android gateway reply the app can't read is reported to diagnostics,** as #9806 does for iOS. Malformed replies (no JSON object, missing fields, or an oversized reply with the expected status) throw `AndroidPushGatewayResponseInvalid`, which `enrollBuzzPush` reports under the push gateway operation. Refusals and transport failures stay unreported, and a refusal keeps its status even when its body is over the cap. - **The delegation sweep after enrollment keeps the enrolling relay while it is still wanted.** It now sweeps with the desired relays plus the enrolling origin, but only while `stillWanted()` holds, so an opt-out that landed during the delegation still sees that delegation revoked. - **Tests for two paths that had none:** an opt-out that lands while the gateway answers the delegation ends the attempt quietly (no lease, delegation revoked, no failure retry), and an opted-out iOS community enrolls nothing. Two other items from the review, both Codex findings on an earlier head of #9811 (reusing a revoked grant after a lost re-delegation; deleting a key after a lost renewal), were already fixed and tested before #9811 merged, so nothing changes here for them. ### Validation Added tests: - [the enrolling relay keeps its delegation before the caller lists it]( |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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 | | --- | --- | |  |  | 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 | | --- | --- | --- | |  |  |  | Long-pressing a message puts Mark unread first in its quick actions.  ## 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> |
||
|
|
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 |  |  | | Wide |  |  | ### 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 |  |  | | Wide |  |  | ## 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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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 ( |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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 |
||
|
|
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> |
||
|
|
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
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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 |
||
|
|
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
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |