Commit Graph

10 Commits

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

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

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

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

### Related issue

None found.

### Testing

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

### Screenshots

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

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

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

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

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

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

---------

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

## Changes

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

## Validation

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


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

---------

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

## Changes

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

## Validation

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


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

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-24 16:29:14 -08:00
Tom Brow
e600cdbde2 feat(mobile): time channel opens and relay connection recovery (#9858)
Adds two durations to the mobile networking diagnostics, so work on
channel opening and reconnecting has a before and after number from real
use:

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

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

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

### Regressions

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

### Validation

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

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

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

Added tests:

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

Known limits:

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

---------

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

## Changes

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

## Regressions

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

## Validation

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

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


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

---------

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

## Changes

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

### Endpoints

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

### Failure kinds

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

## Validation

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


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

---------

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

## Changes

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

## Validation

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

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

## Diagnostics card

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

---------

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

### What's in it

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

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

### Regressions

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

### Validation

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

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

---------

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

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

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

### What's in it

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

### Regressions

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

### Validation

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

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

---------

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

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

### What's in it

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

### Regressions

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

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

### Validation

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

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

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

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

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

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

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

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-18 12:50:45 -08:00