mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
a1e4d69fab26bbbb4264829a0aa78a581b24904b
3577 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
a1e4d69fab |
fix(mobile): end a rendered mention at the composer's suffix boundary
A sent `@Bob's idea` or `@Bob-bot` carries Bob's p tag since picked chips keep their recipient through a following apostrophe, hyphen, slash or punctuation, but the bubble still drew it as plain text: the renderer's trailing boundary was a fixed punctuation set that predates that rule. The message scan and the bubble pattern now end a known name exactly where the composer's `mentionEndsAtBoundary` does, as buzz-app's `mentionBoundary` does (recommendation 3): only a letter, mark, digit or underscore directly after the name continues it, so `@Bobby` holds no Bob, while `@Bob's idea`, `@Bob’s idea`, `@Bob-bot`, `@Bob/Alice` and `@Bob.` render Bob's pill with the suffix as text. `mentionOccurrences` carries the rule as one Unicode class and applies it to the reservation suffix too, so the shorter label still never claims `@Scout (<key>) 2's`. Every reader of the scan follows: the bubble's non-breaking-space pass, inline previews, the edit sheet's seeded chips, draft restoration and the typed exact-name fallback. The bubble's inline pattern uses the same class for known names and keeps the old whitespace-or-punctuation end for unknown tokens, so `@Bob's` with no bound Bob stays text as before. One consequence of the shared rule: a closing `_` directly after a name is a name character, so `_@Bob_` no longer draws a pill, as in buzz-app. Namesake `@Sam (<key>)` rendering and the in-code exclusion are unchanged. Tests: the exact-mentions widget test renders each suffix case with Bob tagged, taps the pill and sees the suffix as text, and sees no Bob in `@Bobby`; the scan test covers the suffixes, letter, digit, mark and underscore continuations and the reservation suffix; the preview test keeps Alice's chip before `'s idea`. All three fail with the old boundary sets. `dart format`, `flutter analyze`, `just file-size-check` and the full mobile `flutter test` suite pass; one run hit an unrelated activity-provider timing test that passes solo. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> |
||
|
|
1996069693 |
fix(mobile): offer the mention chooser while editing a message
The edit sheet was a plain text field: typing ` cc @bo` opened nothing, and the only way to mention someone from an edit was to type the name exactly (scenario 08). The sheet now mounts the composer's `@` chooser with the same rules, as buzz-app's edit box does (recommendation 9): the same trigger, ranking, folded matching, directory search, Space and closing-punctuation selection, suffix boundary, chip binding and focus handling. A pick inserts the same bound `@Label` chip, and the message's existing mentions open as chips, each bound to the person its tags name (`@Name` or `@Name (<key>)` for exactly one tagged person; a name two tagged people share stays text). An edit replaces prose only, following buzz-app's edit rule: the saved edit event carries the tags the edit path wrote before (`h`, `e` and the custom-emoji tags) and never a `p` tag for a pick, so nobody is notified from an edit. Save, Cancel and the sheet layout are otherwise unchanged; the body scrolls so the field, the chooser and the keyboard fit together on a small phone. A hardware Enter keeps inserting a newline while no chooser row is shown. The chooser's state moves out of the composer widget into a shared `_useMentionChooser` hook in `mention_chooser.dart` (query, opening, shown rows, chip insertion and the per-edit tracking that also performs terminator selection); the composer and the new `message_edit_sheet.dart` part both use it, so no rule is copied. The hook exposes the live query for hardware keys that arrive before the next frame. The hardware-key helper takes an optional `send`, which the edit sheet leaves out. Tests: a new edit sheet journey opens a message with an existing Alice mention and sees her chip, types `@bo` and taps Bob into a chip, sees the chooser leave and return with the field's focus, selects `@alice,` with a comma, picks Quinn from a directory search, and saves content with the picks and no `p` tag; an unchanged or emptied edit saves nothing; and the sheet fits a small phone with the keyboard and the chooser open. The journey fails when the sheet stops tracking the query or stops seeding chips. `dart format`, `flutter analyze`, `just file-size-check` and the full mobile `flutter test` suite pass. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> |
||
|
|
e008151c6c |
fix(mobile): close the mention chooser while the composer has no focus
With the chooser open for `@bo`, dragging the keyboard away collapsed the composer to one line but left the chooser row floating above it (scenario 09). The chooser now follows the field's focus, as buzz-app's does (recommendation 8): it hides whenever the text field loses focus, through the keyboard-dismiss drag, the Android back key, a tap elsewhere or Shift+Tab traversal, and comes back when focus returns. The draft, the live query and its rows are untouched while hidden. The composer keeps watching the same candidate and search providers, so a return to the field shows the same rows in the same order without a new directory search, and a search that was running finishes into the hidden rows. The `#channel` chooser lives in the same panel and follows focus the same way. Hardware Tab and Enter accept a row only while the panel is shown. A tap on a chooser row is a touch outside the field, which takes no focus on mobile, so a row still inserts its pick, the search retry still runs, and the outside-channel prompt is unchanged. The edit sheet is unchanged. The composer widget had passed the mobile file-size ceiling, so the expansion spring and the iOS clipboard probe move to `helpers.dart` as `_useComposerExpansionMotion` and `_useComposerClipboardImage`. Tests: the search journey opens `@bo`, unfocuses the field and sees the chooser gone with the draft and caret kept, refocuses and sees Bob then Bobby again with no new search, taps Bob with focus kept and sends him tagged, then checks `#cur` the same way; the Shift+Tab test now expects the chooser to leave with focus and return with the query. The journey fails when the focus gate is removed. `dart format`, `flutter analyze`, `just file-size-check` and the full mobile `flutter test` suite pass; one run hit the known community snapshot timing flake, which passes solo. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> |
||
|
|
38e8f2e1e0 |
fix(mobile): let closing punctuation select an exact mention name
A comma typed straight after `@Bob` or `@Quinn` became part of the query and closed the chooser: `@Bob,` was notified only through the typed-name fallback, and `@Quinn,`, a person outside the channel, was sent with no recipient and no prompt (scenario 06). Closing punctuation typed directly after the query now selects the exact, unique name exactly as Space does (portable mention rules, section 5; recommendation 7), and the typed character stays after the chip in place of the space: `@bob,` becomes a bound Bob chip followed by `,` with no extra space. The selecting characters are buzz-app's `mentionTerminator` set, Space, `.` `,` `!` `?` `;` `:` `)` and the closing quotes `'` `’` `"` `”`, plus `]` and `}` for the brackets a query opens after. `mentionTerminator` in `mention_rules.dart` holds the set; the composer listener applies the same exact-and-unique check it already ran for Space, through the folded name matching, so an ambiguous `@Sam,` and an inexact `@Bo,` are not selected and the character joins the query, and a hyphen is never a terminator. `insertMention` takes the separator to keep after the label, defaulting to the space. A directory-only person goes through the existing chip and outside-channel prompt flow exactly as a tapped pick does: `@Quinn,` is a Quinn chip, and sending meets the prompt. The edit sheet and focus handling are unchanged. Tests: the chip journey selects Bob with each terminator and sends the chip text with Bob tagged, and keeps `@bo,` and `@bob-` unselected; the search journey selects a found Quinn with a comma and sends through the outside-channel prompt as a reference; the namesake tests check that a comma never selects a shared name. Both journeys fail when the terminator set is reduced to Space. `dart format`, `flutter analyze` and the full mobile `flutter test` suite pass; two full runs each hit one unrelated timing flake (relay socket liveness, community snapshot cleanup) that passes solo and alongside the changed tests. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> |
||
|
|
4e4ac3efd8 |
fix(mobile): fold accents when matching mention names
`@jos` listed José María, `@jose` listed nobody and `@josé` listed them again: mobile only lowercased names. Name matching now follows section 3 of the shared mention rules, as buzz-app does (recommendation 6). Each code point is NFKD-normalized, its combining accents (the Combining Diacritical Marks blocks) are removed, it is lowercased and a final `ς` becomes `σ`, so `jose` matches `José`, `fiona` matches `fio` and `jose` matches `jose`, while `ø`, `ł`, `æ`, `ß`, `ı` and the marks of other scripts stay distinct. Words are runs of letters, marks and digits, so a hyphen or apostrophe separates them: `jane` finds `Mary-Jane` and `brien` finds `O'Brien`. The folding lives in `name_match.dart` and drives the chooser, Space selection, multi-word admission, the verified-name matches and the recipient pickers, so `@jose maria` lists José María with no accents typed. The vendored fixture moves from version 1 (95 cases) to version 4 of buzz-app's `mention-rules.fixtures.json` (125 cases), copied unchanged, and the conformance test runs every section, with a new `matching` group. No case is skipped. The rules the newer versions added are implemented too: an exact public key (64 hex in either case, or a complete lowercase or uppercase npub with an optional `nostr:` prefix) matches only its owner, even one with no name, and Space selects that owner; the viewer's own agent whose name continues the query with a new word leads (`Sol 6` for `sol`), and an exact person leads over it; agents from the viewer's other communities follow everyone here; an outside choice's longer name no longer blocks a member's exact name on Space, and a choice's own longer alias is not its own namesake. The search cache's exact-key exemption uses the same `typedPublicKey`. Refutation itself stays lowercase-only on purpose: it reasons about the relay's prefix search, which is out of scope here, so an accented query is a new search rather than a continuation. A refuted query still matches members on the device by folding: after `z` finds nobody, `@zoe` lists the member Zoë without a search. Tests: the compose bar search journey types `@jose maria` and sees José María, and `@zoe` after the `z` refutation sees Zoë; both and seven fixture cases fail when accent stripping is removed. `dart format`, `flutter analyze` and the full mobile `flutter test` suite pass. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> |
||
|
|
c4d3f2072b |
fix(mobile): stop searching the directory while prose is typed
Prose typed after a picked mention no longer runs a name search on every keystroke. The `@` of a bound chip opens no query wherever the caret is, so `@Bob please review the notes` sends nothing to the relay after the pick, and moving the caret through that line sends nothing either. A name character typed against the chip unbinds it first, so `@Bobby` is a query again. Before, only a caret inside the chip was excluded, and every character of the sentence went to `POST /profiles/search`. A typed, unpicked query stops searching once the directory cannot match it, following buzz-app's refuted-prefix rule (Mention rules, section 6): a finished search that found nobody, for a query with a letter or digit, refutes every longer query that continues it. The relay matches names by prefix, so none of those can find anyone. The chooser skips their search, reports nothing pending or failed, and closes. The next finished search replaces the refutation, re-entering the refuted query searches again, and an exact public key or npub is never skipped, since a name prefix cannot refute an author lookup. Searches that found nobody are no longer kept as cached pages. Admission is unchanged: a short query with no local match (`@qu`) still searches so a person outside the channel is found, and a multi-word query that continues no local name (`@jos mar`) still goes to the directory. The 200 ms debounce and one-character minimum stay as they were. Tests: a compose bar journey picks Bob, types a sentence and arrows back through it with zero directory searches, then checks `@qu`, `@jos mar`, `@alice sm` and the `@z` refutation; the search cache test covers the refuted prefix, the key exemption and a later search clearing it. Both guards were shown to fail under mutation. `dart format`, `flutter analyze` and the full mobile `flutter test` suite pass. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> |
||
|
|
2cbdabdae5 |
fix(mobile): bind picked mentions by position and never show a key in the composer
A picked chip is now bound to its recipient by its place in the draft, not by its label. The editor carries each binding across every edit with a selection-aware diff, so deleting the first of two identical chips removes that recipient, text typed before a chip moves it, and a chip stays bound until an edit reaches into it or a letter or digit is typed directly against it. Punctuation, straight and curly apostrophes, a hyphen or a slash after a chip keep it and its recipient (`@Bob's idea`, `@Bob-bot`, `@Bob/Alice`), the same boundary rule buzz-app uses (recommendation 3). Namesakes no longer put a public key in the composer. A picked chip whose name another candidate shares reads the chooser's short label, `@Sam · a1b2`, while the draft text stays `@Sam`; both Sams can be picked and each chip keeps its own key. The sent content qualifies namesakes of different keys as `@Sam (<key>)` so bubbles still tell them apart, except inside code, and each picked Sam gets its own p tag (recommendation 4). The ambiguity refusal for a typed, unpicked `@sam` is unchanged. Drafts persist their bindings as positions (`mentions`), with the saved label-keyed `mention_keys` still read and an unreadable record kept as a tombstone that refuses to send while an `@` remains. The agent prefill and failed-send recovery restore text and bindings in one update. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Matt Toohey <contact@matttoohey.com> |
||
|
|
9152e91fe3 |
fix(mobile): make picked mentions atomic chips bound to their recipient
Picked people (channel members and directory results) now render as
atomic composer chips like agents already did, and the recipient a send
notifies comes from the same occurrence scan that draws the chips.
- Backspace right after a chip removes the trailing space first and the
whole chip second, for people and agents alike; Left and Right step
over a chip as one unit. The agent chip previously broke into plain
`@Scou` on the second Backspace because an undo heuristic mistook any
Backspace landing on earlier typed text for Undo. Undo and Redo are
now detected explicitly through an `Actions` override of
`UndoTextIntent`/`RedoTextIntent` around the field, so the editing
formatter leaves restored values exact and widens real deletions.
- `mentionOccurrences` opens a mention after `(`, `[` and `{` as the
query trigger already did, so `see (@Bob` picked after a bracket
notifies Bob, and the typed exact-member fallback accepts the same
brackets. Draft pruning, rendering and send resolution share it.
- Deleting or editing a chip removes its recipient; text left behind
notifies nobody. Typed, unpicked names keep their existing behaviour,
visible draft text stays `@Label`, and qualified namesake labels still
render as coloured text.
- Person chips use key `composer-person-mention-chip` with semantics
`Mention: <name>` and an `@` prefix; agent chips keep their key, bot
icon and `Agent mention:` semantics. Chip widgets, the editing
formatter and the history action move to `composer_chips.dart`.
Tests: a compose bar journey covers person chip insertion, two-Backspace
removal of person and agent chips, arrow stepping, chip deletion sending
no recipient, bracket-prefixed picks and space-selected names notifying,
and the typed fallback after a bracket; `mention_bindings_test` gains
bracket rows. `flutter analyze`, `dart format` and the full mobile
`flutter test` suite pass.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
|
||
|
|
39ffc3dcc5 |
fix(mobile): keep agent poster up until the iOS video draws (#9688)
On iOS, an animated agent avatar (a preset character with a transparent
video) blinks out for one to three frames right after navigation
settles. Opening a Solo chat blanks the header avatar; going back to
Messages blanks the bestie bubble.
The cause is the hand-off from the still poster to the video. While a
route animates, `PresetAgentAvatar` shows the poster; once it settles it
replaced the poster with a native `AVPlayerLayer`, which draws nothing
until its first video frame arrives. The avatar picker and the
create-agent page already covered this by passing a preloaded poster;
the DM and Solo header and the bestie bubble pass none, so they went
straight to the bare player.
Now every iOS caller gets that hand-off, using its own poster when it
passes none: the poster stays up, below the player, until playback
advances in that showing, then fades out over 160 ms. The poster sits
below the native layer rather than over it, because a Flutter overlay
above a platform view also costs a blank frame when the view first
appears. Each showing starts covered again and waits for playback to
advance from where the player actually is, so coming back to a chat from
a page above it doesn't blink either. The poster is keyed by its URL, so
when the avatar changes to another character (for example a synced
bestie change) it never shows the previous character's poster. Android
is unchanged; it already waits for a presented frame.
### Validation
Measured on an iPhone 17 Pro simulator, recording at 60 fps and checking
the avatar region frame by frame, opening a Solo chat with an animated
agent and going back:
| | Header blank on open | Bubble blank on back |
| --- | --- | --- |
| main, 3 runs | 1 frame every run | 2 to 3 frames every run |
| this PR, 3 runs | none | none |
Before (left) and after (right), slowed 4x: the Solo header on open,
then the bestie bubble on back.
<video
src="https://github.com/user-attachments/assets/4ddf16c0-bb8d-4d77-b53e-84f83ff45e98"
width="480"></video>
Added test: [iOS keeps the poster over a new player until playback
advances](
|
||
|
|
008d72a133 |
test(relay): stop bridge cancel_fixture tests timing out on the first replica connect (#9691)
## Problem All seven tests that share `cancel_fixture` in `crates/buzz-relay/src/api/bridge.rs` got a replica pool with a 1 s `acquire_timeout`. Only `shed_history_read_maps_to_503_on_every_bridge_branch` needs that budget: it holds the replica full and measures how fast a read sheds. sqlx applies `acquire_timeout` to opening connections as well as to waiting for a free one, so the budget also governed the fixture's initial connect and every later acquire that had to open a connection. A transient Postgres stall on the shared CI server therefore failed tests that never hold the replica full. CI showed `connect scratch: PoolTimedOut` at `bridge.rs:10309` in `aborted_history_read_logs_events_already_queued` and `failed_history_read_closes_and_reconnect_replays_the_history` (run 44205074529 shows eight tests finishing together after a ~3 s gap, which is the stall). Pools with sqlx's 30 s default waited the stall out; the 1 s replica did not. No connection leaked and the pool was not too small. The replica's 300 ms database-level `statement_timeout` had the same flaw: migrations and seeding ran under it, so a stall during setup failed `seed community` with 57014. ## Fix (test code only) - The six non-shed tests now use default pool budgets. - Only the shed test asks for the short budget, via `budgeted_reader`. That helper pre-opens all of the reader pool's connections under the 30 s default, and does not ping on acquire, so the 1 s budget covers only the wait for a free connection. - sqlx still pings each connection on release and closes it if the ping fails, so `budgeted_reader` waits until `num_idle()` equals `max_connections` before returning. A fill-and-drain loop (acquire to `max_connections`, drop, re-check) reopens any connection a failed release ping closed, under one 30 s deadline, and panics with the `N of M idle` count if the deadline passes. - The replica's `statement_timeout` is applied after migrations and seeding, and the replica is reopened so new sessions pick it up. - The shed test asserts each shed `/query` case completes in under 10 s, so a silent fallback to the 30 s default fails instead of passing slowly. ## Verification Reproduced locally by pausing the Postgres container for 2 s at random intervals while running `api::bridge::postgres_tests` at CI's 8 threads: `connect scratch: PoolTimedOut` appeared in 1 of 4 runs before the fix and in 0 of 8 after. With the fix, the 62 bridge postgres tests passed at 8 threads against a local Postgres (`--ignored`, including the shed, statement-cancel, and both history-read tests). `cargo fmt` is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: mtoohey <mtoohey@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a406191694 |
Revert "feat(relay): support community-scoped NIP-AR artifacts" (#9689)
Reverts #9650 (squash commit `eebf62b6`), except for migration `0097` and the channel artifact sync fences it added. Community scope adds a relay access gate based on community admission rather than channel membership, a new relay-admin command kind (`9034`) and an operator-run key transition. Its design and NIP-AR text need relay maintainer review before they ship. Two integration gaps also remain: - Media download authorization looks up references only in `events`, so an attachment referenced only by a community artifact is unreadable when media-read enforcement is on. - User erasure retires a community head in the database without signaling live syncs, so members who are already syncing keep the erased copy. The feature can return as a new PR once those are resolved. ## Kept from #9650 - **Migration `0097`, byte for byte.** Published images already include it, and databases that auto-migrated have recorded it. Dropping it would stop those relays from starting. It only adds columns and indexes that the channel code ignores. The declared schema matches that expanded shape and keeps the `(community_id, artifact_id)` primary key, so the operator key transition no longer exists. - **Channel artifact sync fences.** Snapshot and live sends check for a pending resync and for connection cancellation under the queue lock. A reader who loses access, or whose content is redacted, while a frame is in flight therefore receives no further payload. Handler-backed tests cover a resync recorded while a snapshot payload waits for queue room and one recorded after a live head read. ## Compatibility This revert supports databases that applied only migration `0097`, which is all that auto-migration runs. A database that ran #9650's operator contract script, or was bootstrapped from #9650's declared schema, has no `(community_id, artifact_id)` key, so channel artifact writes fail there. Before deploying to such a database, check that `artifact_heads_pkey` is on `(community_id, artifact_id)` and that `artifact_heads` has no rows with `scope = 'community'`; if either check fails, it needs a separate recovery step. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Paul <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@buzz.block.builderlab.xyz> |
||
|
|
db40da87b4 |
feat(relay): add conditional Solo member role updates (#9667)
**Category:** improvement **User Impact:** Solo chat owners can lower the access of any current non-owner, including people and agents. **Problem:** Using invitations to change Solo chat access can restore a removed member, reject a downgrade because of the target’s invitation policy, or show a join notice for a role change. **Solution:** Add signed role updates that require an active member at the expected role when the relay commits the change. A Solo owner can downgrade any current non-owner. Moving a viewer to Participating requires a verified agent, and granting Admin requires ownership of that agent. The relay refreshes signed group state without emitting a join notice. Companion to [block/buzz-app#3704](https://github.com/block/buzz-app/pull/3704). The [app review](https://github.com/block/buzz-app/pull/3704#pullrequestreview-5962147206) identified the need for conditional writes, verified agent identity and live relay validation. [#9592](https://github.com/block/buzz/pull/9592) introduced the atomic removal that uses the same membership lock. <details> <summary>File changes</summary> **crates/buzz-core/src/kind.rs** Register signed Solo role updates as kind 9050. **crates/buzz-db/src/store/channel_members.rs** Authorize the transition under the channel membership lock and commit the active row update and signed event together. **crates/buzz-relay/src/handlers/event.rs** Give the new command a bounded metrics label. **crates/buzz-relay/src/handlers/ingest.rs** Use the shared signed ingest path and require the channel administration scope. **crates/buzz-relay/src/handlers/mod.rs** Register the command handler and its PostgreSQL test. **crates/buzz-relay/src/handlers/solo_member_role.rs** Parse the command, route it to the conditional write, and refresh signed group state after commit. **crates/buzz-relay/src/handlers/solo_member_role_postgres_tests.rs** Exercise human and agent changes, restrictive invitation policy, promotion authorization, stale and removed membership, duplicate receipt, and signed roster updates through the relay’s production ingest path. **docs/solo-mobile-contract.md** Describe the wire format, permitted transitions, and handling when an older relay rejects the command. </details> ### Try it 1. Run the updated relay and the companion app against a disposable Solo chat with a current human and agent. Open **Chat access** as the owner. 2. Lower the human to **Viewing only**. Reopen **Chat access** and confirm the saved role. A role change should produce no join notice. 3. Downgrade an agent with a restrictive invitation policy. Confirm its role changes. Check that **Admin** can be granted only to your own verified agent. 4. Run `solo_owner_edits_active_members_and_publishes_the_new_roster` with PostgreSQL to check that a pending change for a removed member is refused and the signed roster stays clear of that member. ### Validation - The PostgreSQL regression passes at relay commit `405f7d1da`. It covers role and invite-policy enforcement, signed roster refresh, duplicate receipts, and rejection after removal. - The companion app at `a470947dc6` passes 138 administration tests. Its production command builder, validator, and signed roster reader also passed over WebSocket against a local relay backed by PostgreSQL and Redis. A human moved from Admin to Participating to Viewing only, then was removed. The app preflight and relay both refused a further role edit, and the signed roster still excluded the member. - The live check exercised the app’s relay code headlessly. The UI walkthrough is pending. --------- Signed-off-by: Taylor Ho <taylorkmho@gmail.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@feedback.communities.buzz.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> |
||
|
|
fd436af846 |
feat(mobile): add saved channel section filters (#8479)
**Category:** new-feature **User Impact:** Mobile users can filter each channel section by unread or recent activity and save their choices to their account. **Problem:** Mobile sections do not expose the account's saved All, Unreads and Active filters, making long channel lists harder to navigate on mobile. **Solution:** Add per-section view settings with shared sheet chrome, checked choices, inline Active duration and Apply/Cancel. Preserve access to filtered channels through inline recovery and confirm encrypted filter writes on relay readback. **Known desktop and web sync limitation:** Mobile uses the encrypted `channel-filter` record. The separate current desktop and web build reads and writes `channel-workspace-filter` and falls back to the legacy record only before a workspace filter exists. Once the workspace record exists, filter changes are independent across the builds. The interoperability tests below cover the older companion format from [block/buzz-app #1297](https://github.com/block/buzz-app/pull/1297). Current desktop and web interoperability is follow-up work. <details> <summary>File changes</summary> **mobile/README.md** Document section controls, recovery and preference behavior. **mobile/lib/features/channels/channel_filter/channel_filter_activity.dart** Read verified message activity with bounded concurrency and lifecycle/live invalidation. **mobile/lib/features/channels/channel_filter/channel_filter_manager.dart** Preflight, publish and confirm encrypted preference changes, retaining rollback and errors. Skip no-op deletion cleanup and allow best-effort cleanup after local section removal. **mobile/lib/features/channels/channel_filter/channel_filter_provider.dart** Scope preference ownership and cache to the current account and relay. **mobile/lib/features/channels/channel_filter/channel_filter_store.dart** Preserve companion-compatible registers, durations, reset tombstones and unknown fields; define filter predicates and salvage malformed supported-v1 siblings from authenticated relay records. **mobile/lib/features/channels/channels_page.dart** Connect the filter owners and shared sheet header to channel navigation. **mobile/lib/features/channels/channels_page/body.dart** Apply filters using the same readiness predicate as unread highlights, retain the selected channel and expose activity retry. Delete sections locally before best-effort filter cleanup. **mobile/lib/features/channels/channels_page/filters.dart** Provide one draft settings sheet with checked rows, duration, pending guards and retry. Announce retained-draft failures in a visible live region beside the footer. **mobile/lib/features/channels/channels_page/sections.dart** Open section options directly and reveal hidden channels in the existing roster. **mobile/lib/features/channels/channels_provider.dart** Invalidate activity for self-authored and muted messages independently of unread state. **mobile/test/features/channels/channel_filter/channel_filter_test.dart** Cover record preservation, confirmed writes, malformed sibling repair and the actual activity-provider/predicate composition, including future-dated history. **mobile/test/features/channels/channels_page_test.dart** Cover staged saves, cancellation, failed drafts, saved duration and read-only recovery at enlarged text. **mobile/test/features/channels/channels_provider_test.dart** Verify self-authored activity invalidates filters without changing unread timestamps. **mobile/lib/features/channels/channel_sections/channel_sections_provider.dart** Emit local deletion immediately so offline removal updates the list without waiting for a relay event. **mobile/test/features/channels/channels_page_test/filter_feedback_tests.dart** Verify pre-seed unread consistency and offline section deletion through the real section provider and persistent storage, without filter publication. **mobile/test/features/channels/channel_filter/channel_filter_interop_test.dart** Exercise encrypted desktop/mobile golden payloads and crossed writes that converge on one complete winning record. **mobile/test/fixtures/channel_filter_desktop.json** Retain signed, encrypted synthetic-key payloads from the companion desktop implementation and mobile manager for protocol regression coverage. </details> ### Reproduction 1. Open a channel section's options. Select Active and 7 days, then Apply; reopen to see the saved choices checked. 2. Confirm older channels are hidden. Expand Show hidden channels to navigate without clearing the filter. 3. Change a draft and Cancel. Confirm the saved filter remains unchanged. 4. With preferences unavailable, delete an unfiltered custom section. It should disappear and remain deleted locally without publishing a filter reset. 5. Make a filter save fail. The draft should remain selected and the error should be visible beside Retry and exposed as a live region. ### Validation and limits - Follow-up fixes at `f38bf9b273402dd86e93476dde02f468747fa65a`, with main `a93f3282c` integrated. Required pre-push checks passed on that head: 3,742 Flutter tests passed, 16 skipped; four unconfigured-push tests passed. Analyzer, formatting, file-size and branch-skew checks passed. - Repaired v1 metadata now contains exactly `v` and `g`, preserving unknown top-level extensions. The pinned companion at `475e2afef` verified, decrypted and adopted the repaired mobile head without rewriting it. Sort-only Apply preserves late-loaded filters and publishes no filter write; the existing signed-read sheet journey covers this race. - Affected pre-integration journeys/protocol tests: 97 passed. Removing the production fixes produces six failures across unread readiness, offline deletion, malformed siblings, activity classification and accessible failed-save status; sources restored afterward. - Protocol exercise: actual `block/buzz-app` browser-host filter code at `475e2afef` produced the signed NIP-44 desktop golden head; the mobile manager adopted it and published a sibling choice; desktop decrypted/adopted that mobile write and preserved both durations on its next edit. These are production-code exercises with synthetic keys and a fake relay boundary, not two packaged clients exchanging against a live relay. - Whole-record last-write-wins applies to both mode and duration. Preflight preserves observed sibling choices; crossed writes can overwrite an unseen edit, even in another section. Readback checks the requested pair, and refresh adopts the retained winner. Per-section conflict-free merging is not promised. - Supported-v1 malformed siblings are salvaged from the authenticated relay head, with canonical repair published only by an explicit confirmed save. Oversized records and unsupported schema versions remain read-only; display cache never grants repair authority. - Section deletion is local first. Unfiltered sections skip publication; failed cleanup can leave unreachable settings for a never-reused section ID. No offline filter-save queue or automatic cleanup retry is introduced. - Earlier iPhone 17 / iOS 26.5 testing exercised section options, Cancel/reopen and Active/7-day filtering. The normal-flow screenshot below predates these review fixes. Failure-path runtime/screen-reader checks, Android, dark mode, packaged cross-device workflow and human acceptance remain unverified. - Preferences refresh on load/resume/pull-to-refresh; no instant cross-device sync promise. Sort retains its existing asynchronous persistence and is not atomic with the separate filter record. - On `85949bcde`, 5,095 Flutter tests passed with 71 skipped, plus 27 secp256k1 tests. GitHub's required checks cleared. The duration animation was tested on the iPhone 17 simulator against a local relay, and the same animation is included in this head. The separate non-required Codex Security Review run was canceled before publishing a review. ### Screenshots Actual iOS simulator capture, cropped to the section settings surface. | Section view settings | | --- | |  | --------- Signed-off-by: Taylor Ho <taylorkmho@gmail.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
eebf62b61d |
feat(relay): support community-scoped NIP-AR artifacts (#9650)
## Summary NIP-AR clients can store community-scoped artifacts and subscribe to live changes for one exact artifact type. Community and channel artifacts share revision and retry semantics and use separate identity scopes. Community owners and admins can choose whether a type accepts edits from all admitted members or only administrators. This PR combines the protocol from #9638 with the relay implementation. [Protocol]( |
||
|
|
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 |
| --- | --- |
| 
| 
|

### 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
|
||
|
|
44e97e96f4 |
fix(pubsub): round the rate-limit retry hint up from PTTL (#9552)
## Summary The Redis rate limiter built its `retry in Ns` hint from `TTL`, which truncates to whole seconds. With 400 ms left in the window, a denied request was told `retry in 0s`, and a client that sleeps for exactly the hint retried straight into another refusal. This reads `PTTL` and rounds the milliseconds up to whole seconds, so the hint is never 0 while the window is still open. The no-expiry repair path is unchanged. ## Testing - New `rate_limiter::tests::retry_hint_rounds_a_partial_second_up` (`#[ignore = "requires Redis"]`, like the other Redis tests in this crate) seeds an exhausted window with 400 ms left and asserts the denial reports 1 second. Against the old `TTL` code it fails with `left: 0, right: 1`; with this change it passes. - `cargo nextest run -p buzz-pubsub --lib`: 38 passed. Ignored Redis `rate_limiter` and `nip98_replay` tests: 5 passed against a local Redis. - `cargo nextest run -p buzz-relay --lib` with local Postgres and Redis: 1762 passed. The relay `rejection::`/`admission::` lane with `--run-ignored all`: 16 passed. - Pre-push hooks (including rust-tests) passed. CI note: the Redis-backed pubsub tests only run in CI when they are named in `.github/workflows/_ci-relay.yml`, so the new test isn't selected there yet. Adding `or test(/^rate_limiter::tests::/)` to the "Pubsub subscriber reconciliation regression" filter would cover it. I left that out here because this branch can't push workflow file changes. --------- Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz> Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz> |
||
|
|
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> |
||
|
|
b624eb0f20 |
fix(mobile): recover stuck read-state updates and stale Mark Read (#9492)
## Summary Mobile read-state fixes within the current NIP-RS text. - **Stuck pending update.** When the relay refuses a pending update with `invalid: event timestamp too far from server time` and the update is older than the relay's 15-minute window by the device clock, the update is retired. The next pass reads a fresh snapshot and sends a strictly newer successor, journaled before it is sent, unless the relay already holds that update or an own-slot update covering every key in it. The marks come from the journaled local state, so nothing is lost. A refusal of an update that is not old by the device clock reports `ReadStateClockSkewError` and keeps the exact signed bytes. Unknown outcomes (timeouts, lost acknowledgements) still retry the exact bytes. - **Mark Read from the channel actions sheet.** The sheet is the only owner of the action, for custom-section channels too. It marks through the newest message known at the tap (the listed `lastMessageAt` or a newer observed unread event), not the `Channel` captured when the menu opened, so messages arriving after the tap stay unread. With no known message time it only releases forced-unread flags. - **Failed snapshot.** A failed snapshot, during startup or inside a publish, retries with backoff (5 s doubling to 5 min) while connected and on app resume; the retry re-syncs and sends journaled marks. When a publish's own snapshot read succeeds first, the pending retry is cancelled, the backoff resets to 5 s and the superseded snapshot error is cleared. A reconnect still re-syncs as before. The channels list shows a tappable "Unread status isn't syncing" notice while sync is failing. - **Marks in the manager gap.** A mark, seed or forced unread made after a dependency change retired the manager, but before the rebuild, now runs the pending rebuild and reaches the current manager instead of being dropped. The session-wide publishing switch-off after an unsupported-kind or missing-scope refusal is unchanged: marks stay journaled and the next manager (restart, re-authentication or community switch) publishes them. In that state the notice offers no retry and says to sign in again or restart Buzz. ## Tests - `read_state_manager_test.dart`: expired update with only partial coverage is renewed with a newer successor carrying every mark; expired update the relay already holds is retired with no new send; clock-skew refusal keeps the exact update and reports the skew error; failed snapshot retries on the backoff timer and stops after recovery; a snapshot failure inside a publish retries on its own and sends the marks; after an explicit flush whose snapshot read succeeds, no extra snapshot is read and the next failure retries after 5 s, whether the write succeeds or fails. - `channel_actions_sheet_test.dart`: Mark Read covers a message that arrived while the sheet was open; with no known message time it only releases forced unread. - `read_state_provider_test.dart`: a mark made between a community switch and the next manager's build is kept. Each new test fails without its fix. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> |
||
|
|
8d613ce0e8 |
test(relay): refresh the author's membership cache after the stray-h private channel insert (#9640)
Fixes `handlers::ingest::postgres_tests::reaction_and_deletion_h_must_name_the_target_channel`, which fails on main in the PostgreSQL Tests jobs. The test creates its private channel directly in the database after the author has already published, so the per-user membership cache (`is_member_cached`) still holds the author's snapshot from before that channel existed. The author's post to the new channel is then refused with `restricted: not a channel member`. The test now drops the author's cached membership after the insert, so the channel's owner is seen as a member. The test's assertions are unchanged. Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
c18bed1f46 |
fix(mobile): name the cause of account-unavailable sign-in errors (#9628)
## Problem Organization sign-in can fail with `Couldn't sign in (account-unavailable)`. That code covers several different failures, so a screenshot can't tell them apart: - the account server can't be reached at all (DNS, connection, or TLS failure, or a timeout), for example when a required VPN profile isn't applied to the app; - a redirect, since the client doesn't follow redirects, so an access-proxy login page lands here; - a 5xx from the server. ## Change - `BuilderlabAccountClient` records why a request failed as `unavailable`, in `lastUnavailableCause`, and logs it. It follows the existing `lastRejectedRequest` pattern. The cause is one of: - a transport category: `unreachable`, `insecure`, `timedOut` (reusing `transportFailure`), or `network` as the fallback; - the status code, such as `http302`. - `OrganizationSignIn` saves the cause at the moment the exchange fails, so later account requests can't change it. It adds the cause to the failure code, for example `account-unavailable-http302` or `account-unavailable-unreachable`. Each new attempt clears it. - The organization sign-in page now ends its failure message with advice for that cause instead of "Try again.": - unreachable, timeout, TLS failure, redirect: "Check your network or VPN connection, then try again." - a 5xx: "The sign-in service is unavailable. Try again later." - The in-app banner keeps "Try again.": its capsule clips longer messages at default text size, and the existing banner layout test caught that. - Unexpected statuses are classified as soon as the headers arrive, so a slow or oversized error body can't hide the status. | Before | After | |---|---| |  |  | The log line contains only the host, route, and cause. It has no headers, credentials, or response bodies. ## Validation - A new journey test in `organization_sign_in_test.dart` covers an exchange that fails with a 302, a 503, and a client exception, then a successful retry. With the cause capture removed, the test fails (`Expected: 'account-unavailable-http302'`, `Actual: 'account-unavailable'`). - The same test checks the advice for each cause. The internal-build landing tests pass with `--dart-define=BUZZ_DISTRIBUTION=internal`. - The screenshots come from the real `PairingPage` rendered in a scratch widget test with a 390×844 surface, cropped. The scratch test isn't committed. - `just mobile-check` passes, and the full `flutter test` run passes: +5018, 71 skipped. - Not yet done: a device run that reproduces an unreachable account server and captures the new message on screen. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Diem Nguyen <diem@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7cf19b713c |
perf(db): bound deep keyset history pages by the cursor timestamp (#9549)
## Problem `query_events` and `get_channel_window` page history with a composite `(until, before_id)` cursor under `ORDER BY created_at DESC, id ASC`. The cursor predicate was only: ```sql created_at < $u OR (created_at = $u AND id > $bid) ``` PostgreSQL cannot use that OR as the start of an index range, so a page deep in a channel walks the `(community_id, channel_id, created_at DESC, id)` index from the newest row and filters every newer row before it reaches the page. The cost of a page grows with its depth. ## Fix Add the redundant bound `created_at <= $u` next to the OR in both queries (`store/event.rs` and `store/thread.rs`). It does not change which rows match; it gives the planner an `Index Cond` range start at the cursor. This is the same bound the thread window query already carries (`store/thread_window.rs`). `api/bridge.rs` has the pattern only in a test fake that emulates `query_events_on`; the bridge itself routes cursors into these two store functions, so it needs no change. ## EXPLAIN before / after `EXPLAIN (ANALYZE, BUFFERS)` of the `query_events` page shape, `LIMIT 51`, kind 9, by cursor depth. Copy of a real channel (2,277 messages), custom plan, shared buffers hit: | Depth | Before | After | | ---: | ---: | ---: | | 50 | 96 | 96 | | 300 | 311 | 84 | | 1,000 | 969 | 80 | | 1,500 | 1,443 | 92 | | 2,100 | 2,006 | 89 | At depth 2,100: execution 0.709 ms to 0.058 ms, rows removed by filter 2,101 to 42. With a generic plan the after numbers are also flat (80 to 96 buffers at every depth). Synthetic table (one channel with 20,000 kind-9 rows plus 20 other channels of 2,000 each): | Query | Depth | Before | After | | --- | ---: | ---: | ---: | | `query_events`, custom plan | 10,000 | 701 | 11 | | `query_events`, generic plan | 50 | 874 (7.5 ms) | 11 (0.11 ms) | | `query_events`, generic plan | 10,000 | 444 | 11 | | `get_channel_window`, custom plan | 10,000 | 1,006 (2.35 ms) | 312 (0.49 ms) | | `get_channel_window`, custom plan | 19,940 | 1,690 (4.35 ms) | 314 (0.47 ms) | For `get_channel_window` at depth 19,940 the events index scan went from 1,385 buffers and 19,941 rows removed by filter to 9 buffers and 4 rows; the rest of its plan is the thread metadata join, which is unchanged. On the small 2,277-row channel the planner picks a sequential or bitmap scan for the window query, so its plan is unchanged there. ## Tests New Postgres test `store::event::postgres_tests::deep_keyset_pages_read_from_the_cursor`: - Inserts 1,000 kind-9 rows into one channel, two per second, so the cursor lands on same-second ties. - Turns off sequential and bitmap scans for the session, so the small fixture uses the ordered index walk a large channel uses, then reads one 50-row page at depth 900 through both `query_events_on` and `get_channel_window_on`. It asserts each page equals the expected rows and that each read touched at most 150 event rows (summed `seq_tup_read + idx_tup_fetch` over the `events` partitions). - Pages the whole channel through both paths and asserts every row comes back once, in order. Checked by reverting each half of the fix: - `event.rs` bound removed: `events page at depth 900 read 950 rows for 50` - `thread.rs` bound removed: `window page at depth 900 read 1000 rows for 50` - With the fix: passes (5 of 5 under `--stress-count 5`), reading 52 and 53 rows. Runs: - `scripts/postgres-test-run.sh -p buzz-db --lib --tests`: 763 run, 756 passed. The 7 failures were the new test before its final fixture change (it now passes) and 6 that fail the same way on unmodified `main` in my environment because they spawn a host `psql` binary that isn't installed there: `migration_schema_media_prebuild_waits_for_old_transactions_during_creation_and_cleanup`, `script_stops_at_the_first_auth_refusal`, `script_renames_each_planned_channel_once_whatever_its_name`, `desired_event_follow_up_contract_app_only`, `desired_event_follow_up_contract_dual`, `migration_schema_event_follow_up_contract_app_only`. CI's Postgres lane is the authoritative run for those. - On the final head: the new test plus every `channel_window` Postgres test, 9 of 9 passed. - `cargo nextest run -p buzz-db --lib` (no infrastructure): 216 passed. `--test observability_source`: 28 passed. Doc tests: 5 passed. - `scripts/test-postgres-test-discovery.sh`: passed. - Pre-push `rust-tests` lane: passed. ## How to test 1. Run `scripts/postgres-test-run.sh -p buzz-db --lib -E 'test(deep_keyset_pages_read_from_the_cursor)'`. 2. Optionally, in a database with a channel of a few thousand messages, open the channel in a client and scroll back through history. Older pages should load as quickly as the first ones, and no message should be skipped or repeated across page boundaries. ## Related No duplicate PR or issue found. Related: #1787 (keyset index for thread replies) and #6004 (CLI wiring for the composite cursors). Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz> |
||
|
|
11970789eb |
feat(cli)!: consistent channels list/get/search output (type, visibility, labels, real created_at) (#9617)
Closes #6390 ## Summary `buzz channels list`, `get` and `search` each projected kind:39000 channel metadata differently. `list`/`get` dropped the classification tags, so a script couldn't tell a Solo chat from a stream or a private channel from an open one. The three commands also disagreed on field names, defaults and empty values, and `created_at` reported the last-edit time (#6390). All three now print one `ChannelSummary`, with `pubkey` added on `get`: | Field | Source | |---|---| | `channel_id`, `name` | `d`, `name` tags | | `channel_type` | first `t` tag (`stream`, `forum`, `dm`, `workflow`, `system`) | | `visibility` | `open` for `["public"]`, `private` for `["private"]` | | `labels` | the `t` tags after the first, e.g. `["buzz.solo"]` | | `archived` | `["archived","true"]` | | `description` | NIP-29 `about` tag | | `topic`, `purpose`, `ttl_seconds` | `topic`, `purpose`, `ttl` tags | | `created_at` | the channel's `created_at` tag (NIP-CL), or `null` when absent | | `updated_at` | the event's own `created_at`, which is the last metadata change | Compact `list` output (`{channel_id, name}`) is unchanged. ### Breaking output changes These are intentional, and they were discussed with a maintainer before this change: - **`search`:** `about` is renamed `description`, matching `list`/`get` and `create`/`update --description`. - **`list`/`get`/`search`:** `created_at` is now the real creation time. The old value, the last-edit time, moves to the new `updated_at`. - **`list`:** archived channels are hidden by default, as `search` already did. The new `--include-archived` flag shows them. `get --channel <id>` still returns an archived channel. `--limit` (and `--visibility`) count the channels printed: `list` reads past filtered channels, bounded by `MAX_QUERY_PAGES` on the default path and by 10,000 memberships with `--member`. - **Missing values:** they print `null` instead of `""`. This mainly affects `description`. - **`visibility`:** it prints `open`/`private`, the values `--visibility` takes, instead of the raw `public` tag. `search` printed `public` before. No in-repo consumer reads the renamed fields or the `public` value. The benchmarks read `search`'s `channel_type`, `visibility == "private"`, `archived` and `ttl_seconds`, all of which are unchanged. ### Related - Closes #6390. - Overlaps with #5664 and draft #6353, which add type and visibility to `list`/`get`. This PR covers both: it uses `open` like #6353, plus labels, archived, parity and the `created_at` fix. A maintainer may want to close them as superseded. Unlike #6353, it doesn't error on missing or contradictory visibility tags, so one malformed channel can't fail a whole `list`. ### Testing - `cargo test -p buzz-cli`: 699 passed. Clippy is clean. The tests build events from the captured `test-fixtures/solo-creation.json` identity tags and pin the full JSON shape, including the all-`null` case. They also cover the production `listed_channels` and `search_matches` filters: archived hiding, `--visibility`, and search's name and ID requirement and ordering. - An agent ran the changed commands against a live relay: - `get` and `search --exact` return identical fields for the same channel. - Over 2,000 channels, `list` hides 162 archived channels unless `--include-archived` is passed. - `--visibility open` returns only `open` channels. - 1,777 channels have `created_at < updated_at`. - No `description` is `""`. - Compact output is unchanged. - `list --limit 10` and `--member --limit 5` return exactly 10 and 5 non-archived channels, and `--limit 2000` returns 2,000 with none archived. - An independent agent review found no blockers. Its one cheap nit, `get` printing `pubkey: ""`, now prints `null`. - The pre-push workspace `rust-tests` lane was skipped for this push. When the push was made, `origin/main` didn't compile `buzz-db`'s lib tests, which is unrelated to this `crates/buzz-cli`-only diff. That breakage has since been fixed on main, so CI runs the full workspace. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Jemiah Westerman <jemiah@squareup.com> Co-authored-by: Son of Anton <8e0ef2ab02d69a7ac089ef5eca90d1a3fbbdc546f6322dc34d0c4f3deecea7f4@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f04fdef31f |
ci(docker): publish the push gateway only when its inputs change (#9658)
## Why
Every main push that rebuilds the relay image also published a new push
gateway image. A staging environment that promotes each published
`main-<commit UTC>-<7>` gateway image then rolls out identical gateways.
In one 29-hour window, main got 43 image-eligible commits, and only 2 of
them changed the gateway. The gateway crate depends on no other
workspace crate, so the other 41 images could not differ in behavior.
## What
- New `push-gateway-inputs` job in `docker.yml`. It runs
`scripts/push-gateway-image-inputs-changed.sh`. On a main push, the
script reads the `org.opencontainers.image.revision` label of the
current `ghcr.io/block/buzz-push-gateway:main` image. It then compares
the gateway's build inputs at that revision and at HEAD:
`crates/buzz-push-gateway`, `Cargo.toml`, `Cargo.lock`, `.cargo`,
`rust-toolchain.toml`, `Dockerfile.push-gateway`, `.dockerignore`,
`docker.yml` and the script itself. Every other event prints
`build=true`. The step appends the script's output to `$GITHUB_OUTPUT`,
so a failing check fails the run instead of skipping the build.
- `push-gateway-build` and `push-gateway-personal-dev` run only when
those inputs changed. When the build is skipped, `push-gateway-merge` is
skipped too.
- `push-gateway-merge` now moves `:main` in its own step, after
provenance is attested. The first publication sets every other tag. So
`:main`'s source label always names a completed publication, and a
failed attestation is retried on the next run.
- It compares with the published image, not `github.event.before`. Main
runs share one concurrency group, so a newer push replaces a pending
run, and a failed run publishes nothing. In both cases the next run
still sees the gateway change.
- When in doubt, it builds: an unreadable image, an unknown source, or a
source that isn't an ancestor of HEAD.
- `scripts/test-relay-image-eligibility-workflow.sh` pins the job
gating, the decision step, and `:main` moving after attestation. It runs
the script against a fixture repository with `docker` stubbed:
multi-platform and single-platform `:main` at HEAD, a non-main event, a
lookup failure, relay-only, toolchain-only, a gateway change behind a
later relay-only commit, a missing source, and a non-ancestor source. I
checked that each assertion fails when its production line is broken.
## Risk
- A base image update (`rust`, `debian:bookworm-slim`) alone no longer
publishes a new gateway image. The next gateway input change picks it
up. A manual dispatch at a `relay-v*` tag still builds.
- `:main` now moves a few seconds after the other tags on main pushes.
Deployments that follow `main-<commit UTC>-<7>` are unaffected.
- The relay image and its triggers are unchanged.
## Simpler
There are fewer published gateway images, and every one of them changes
the gateway. No new configuration.
## Testing
- `scripts/test-relay-image-eligibility-workflow.sh` passes locally.
Mutations of the script and the job gating fail it.
- `actionlint .github/workflows/docker.yml` passes.
- Checked locally that the `docker buildx imagetools inspect … --format
'{{json .Image}}'` + `jq` read returns the current `:main` gateway
source revision.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
3689241672 |
feat(mobile): reply to a message from its iOS notification (#9439)
On iOS, a notification that shows a channel or DM message now offers
**Reply**. The user types a reply in the notification and sends it
without opening the app.
- The reply goes in a subthread under the notified message (its thread
root is the message's own root, or the message itself when top-level). A
Solo chat takes no thread replies, so there it goes at the chat's top
level.
- It always mentions the notified message's sender, so the person or
agent being answered is notified. Typed `@name` text stays plain, since
a notification has no mention autocomplete.
- It is sent by the app's own send path. iOS starts the Flutter engine
when it wakes the app in the background, and the reply reopens the relay
connection (closed after the background grace period), waiting a bounded
time for it before sending.
- A sent reply marks the conversation read **up to the notified
message** (newer messages stay unread) and clears that notification and
earlier ones from the same conversation.
- An unsent reply (offline, relay error, timeout, a channel the user
isn't in) keeps the typed text as a draft, after any draft already
there, and shows a "Reply not sent" notification that opens the
conversation.
For now only notifications from the community selected in the app offer
Reply: replying must not switch communities, and the app can only reach
the selected one. Forum posts and fallback notifications that show no
message offer none. The design and the options considered are in
`docs/adr/0004-notification-reply.md`.
### Before / after
Long-pressing a message notification (synthetic names and text). Before
has no reply field (captured by sending the notification without its new
reply category, which is how main presents it); after shows one with
Send.
| Before | After |
| --- | --- |
|

|

|
### Demo
With the app backgrounded past the relay grace period, replying from the
notification lands the reply in a subthread under the message:
https://github.com/user-attachments/assets/37df7e28-aa46-4521-938e-8af5faa77b83
### Regressions
Nothing existing changes unless the user taps Reply. Notifications gain
a category and a small reply context in `userInfo`; tapping a
notification still opens the conversation as before. The relay reconnect
only happens for a pending reply and then falls back to the normal
background disconnect, so idle background behavior and network use are
unchanged. Reply failures end in a draft and a "Reply not sent"
notification rather than touching other state.
### Validation
- End to end on an iOS 27 simulator against a real community: with the
app backgrounded past the relay grace period, replied from the
notification; the reply appeared in a subthread under the message,
mentioning its sender. The demo above was recorded before the review
fixes (session hold, community fence, origin-community drafts, composer
draft sync); the same run was repeated on the current head,
|
||
|
|
a5b3dbc00d |
fix(mobile): stop reporting saved images as failed on iOS (#9599)
On iOS, **Save image** in the image viewer reported a failure for a save that worked. It asks only for permission to add photos. With that permission the image landed in Photos, but the app showed "Could not save image" and iOS then asked for full library access. After choosing **Keep Add Only**, every later save did the same: saved, and reported as failed. Now the save reports what actually happened, and add-only permission is all it needs, so iOS never asks for full access. | Before | After | | --- | --- | | <img src="https://github.com/user-attachments/assets/5926b595-6a2d-4382-83e5-89329c009159" alt="Before: full access prompt over a "Could not save image" message" width="300"> | <img src="https://github.com/user-attachments/assets/3b797c3e-43c4-4766-950b-8bef415ae2e0" alt="After: "Saved to Photos" message" width="300"> | Before: https://github.com/user-attachments/assets/e4f88b29-cabc-4c43-9967-d8481e434551 After: https://github.com/user-attachments/assets/ca3631a5-c988-4082-898a-426867788051 ### Cause `photo_manager`'s `saveImage` returns the saved asset, so its iOS code fetches the new asset back after writing it. PhotoKit does not let an add-only app fetch assets: the fetch makes iOS show the full-access prompt and comes back empty, and the plugin reports an error for a write that succeeded. The latest release (3.12.0) has the same code. On iOS the image is now written by a small native saver (`PhotoLibrarySaver`) that creates the asset and reports the result of that write, without reading the library. Android keeps using `photo_manager`, and the permission request is unchanged on both platforms. ### Regressions None expected. - The write is the same PhotoKit creation request the plugin made, with the same original filename, so saved images are unchanged. - Real failures still show "Could not save image": a denied permission, a failed download and a failed write all still surface. - Android and the rest of the app's photo library use (the composer's photo picker) are untouched. ### Validation - Added test: the image actions journey saves on iOS with a photo library that grants add-only access and rejects every read, and expects "Saved to Photos", one write with the downloaded bytes and filename, and an add-only permission request. A failed write then shows "Could not save image". It fails without the fix. - Full mobile suite and the iOS Runner unit tests pass. - Full-app run on an iOS 27 simulator, on a fresh install with no photo permission, comparing this branch with unmodified `main`: - `main`: first save adds the image, shows "Could not save image" and the full-access prompt; a second save after **Keep Add Only** adds another copy and shows the error again. - This branch: first and second saves each add one image and show "Saved to Photos", with no full-access prompt, and only add permission is granted afterwards. - This branch, other paths: **Don't Allow** shows "Could not save image" and saves nothing; saving with full access already granted works; **Share image** still opens the share sheet. - Not covered: a physical device, and Android (its code path is unchanged). --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz> |
||
|
|
493cb4cc13 |
perf(db): stop per-id planning of wide #e reads (#9591)
Thread pages fetch the reactions, edits and deletions of ~200 ids at once. Until a pooled connection has run that `#e` read about five times, Postgres plans it with the values: ~12 ms per plan (one estimate per id per partition) against ~2 ms to run it. Past 8 ids the arrays now go through a scalar subquery, so planning is one estimate (~1.5 ms) and still uses the tags GIN index; narrower reads are unchanged. On an 830-reply local thread, one viewer's full scan drops from 119 to 59 ms p50; with 50 viewers p50 holds at 242 ms, p99 drops from 664 to 413 ms, and the read's planning time falls from 13 s to 0.6 s per minute. --------- Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com> |
||
|
|
bc3afbb293 |
[buzz] fix(ci): link relay image indexes to their source (#9637)
The relay image index includes the qualified Git revision. Add the source repository URL beside it so OCI registry clients and deployment tools can link the image to the exact source commit. The manifest assembly step derives the URL from GitHub Actions' server and repository variables. The release workflow contract checks that the index includes both the source and revision annotations. Signed-off-by: Helen Tian <htian@squareup.com> |
||
|
|
25b58ab98f |
feat(push-gateway): verify Android Key Attestation (#9562)
## What and why Ticket 3 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now verifies Android Key Attestation at enrollment instead of rejecting every Android chain, and rate limits signed installation calls per attested key. Stacked on [#9560](https://github.com/block/buzz/pull/9560) (Android enrollment and FCM wakes). This PR's base is that branch; it will be retargeted once that merges. - **Chain.** It must end at a configured Google attestation root (Google's [published hardware roots](https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate) are built in, pinned by public key), with valid signatures and issuer links, CA issuers above the attestation key certificate, and no SHA-1 signatures. The attestation key certificate itself is exempt from the CA flags, because some factory keyboxes issue it with CA:FALSE and digitalSignature only (Google's Sony Xperia 10 III sample); a Keystore leaf still cannot act as an issuer, since the extension is refused above the leaf. Validity is enforced for Remote Key Provisioning chains; Google tells verifiers to keep trusting the long-expired factory chains, which the revocation list covers instead. The attestation extension must be in the leaf and nowhere else. The leaf key must be EC P-256; it becomes the installation's signing key. - **KeyDescription.** Attestation and KeyMint security levels must be TrustedEnvironment or StrongBox. The challenge must equal SHA-256 of the enrollment transcript. Key properties (generated, EC, P-256, sign-only) and the root of trust come only from the hardware-enforced list. The bootloader must be locked, and the boot state Verified, or SelfSigned with a verified boot key on an operator-configured list. The application id (the one software-enforced value) must name exactly the configured package with a configured signing digest. - **Revocation.** A background task fetches Google's status list at startup and then on its cache lifetime (5 minutes to 1 day), with a 30 second timeout, an 8 MiB size cap, capped exponential backoff and jitter. Any REVOKED or SUSPENDED serial in the chain is rejected. With no list yet, or a list older than the grace period, enrollment fails closed. Enrollment reads an in-memory snapshot and never waits on a fetch. - **Rate limit.** Signed installation calls (delegate, revoke delegation, rotate endpoint, revoke installation, on both platforms) are limited per attested key. A call is counted only after its signature verifies, so forged requests cannot spend another installation's allowance. Counters are in memory per replica, bounded to 100,000 keys. - **Dependencies.** None added. `x509-parser` gains its `verify-aws` feature, which uses the `aws-lc-rs` the crate already depends on. ## Configuration All optional; Android stays off unless the ticket 2 settings are present. Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only, and passed through `deploy/charts/buzz-push-gateway` (disabled by default, schema-checked, covered by `tests/runtime-options.sh`). - `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS`: SHA-256 digests of verified boot keys accepted with a SelfSigned boot state. Empty by default, so a default gateway accepts stock Android only. - `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH`: PEM bundle replacing the built-in roots, for a reviewed root rollout. In the chart, `android.attestationRoots.secretName` and `secretKey` mount it from a Secret; an empty name keeps the built-in roots. - `BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS`: default 604800 (7 days), minimum 3600. - `BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS` and `BUZZ_PUSH_SIGNED_CALL_MAX_CALLS`: defaults 60 and 30. ## Tests - `cargo test -p buzz-push-gateway` (all pass, 18 ignored), `cargo fmt --all --check`, `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings`, and the chart tests (`render.sh`, `release-contract.sh`). - Key Attestation chains are generated in the tests with a test root injected as the configured root, and run through the production verifier. One table rejects: unlocked bootloader, Unverified, Failed, SelfSigned with an unlisted key, boot key only in the software list (two variants), key properties only in the software list, extra key purposes, wrong curve, wrong package, two packages, wrong signing digest, wrong challenge, software-backed key (two variants), unknown root, forged leaf signature, expired provisioned intermediate, extension repeated above the leaf, non-P-256 leaf, a CA:FALSE certificate issuing the attestation key certificate. Another accepts Verified with any boot key, SelfSigned with a listed key, StrongBox and TrustedEnvironment, an expired factory intermediate, and a CA:FALSE, digitalSignature attestation key certificate. Revoked leaf, intermediate and root, a missing list and a stale list are rejected. The status list parser and refresh (backoff, cap, keeping the last list through failures) run against a scripted fake source; no test touches the network. - The per-key rate limit runs through the public router: forged calls do not spend the allowance, the fourth authentic call is refused whatever its kind, and another installation is unaffected. - Break check: disabling the locked-bootloader guard and the rate limit turned `rejected_attestations` and the rate limit test red; restored. ## Not here The app side (ticket 7) generates the Keystore key and sends the chain. The end to end run on a physical Android phone against a test gateway is also still to do. --------- Signed-off-by: Tom Brow <tomb@squareup.com> |
||
|
|
b769d5bee8 |
fix(relay): remove an owner's agents with the owner (#9575)
## What this changes When someone is removed from a community, their agents' live sessions already closed, but the agents kept their own membership rows and could reconnect as members. This PR removes those agents with their owner. - **Cascade.** `delete_member_with_acceptances` locks and deletes the target, then locks and deletes the `join_policy_acceptances` and `relay_members` rows of every member of the same community whose `users.agent_owner_pubkey` is the target and whose role is not `owner`. All of it runs in the same transaction, before the roster snapshot is written. Admin removal (kind 9031), self-leave and `buzz-admin remove-member` all go through it. An agent goes with its owner whatever its role, so an admin who removes a member also removes that member's admin-role agent. A direct 9031 target is still limited to `member` for admins. - **Owner recording.** The relay records a verified NIP-OA owner on every admitted sign-in, whatever the relay mode or `allow_nip_oa_auth`: on WebSocket AUTH, and for HTTP in the shared admission step after the denial checks, so `/events`, `/query`, `/count` and member POSTs all record it in one place. Before, it recorded only on open relays, so on closed relays the cascade and owner bans missed agents added directly. A request refused before recording writes nothing. Once the owner-signed tag is verified and the first admission checks pass, the relay may record the owner even if a final check, a cancellation or a token revocation then refuses the sign-in. The record still can't be changed. Over HTTP, a different stored owner refuses the request with 403 (invite creation keeps its `invite_owner_mismatch` code), and storage trouble refuses it with 503. A recorded owner can also manage the agent (channel management, channel-add policy, invites). - **CLI.** `buzz-admin remove-member` publishes clusterwide disconnects (`ConnControl::DisconnectPubkey`) for the target and its recorded agents on every run, including when the member is already gone. If publication fails or no relay server is subscribed, it exits 6 after the removal commits. Rerunning the same command retries the disconnect. - **Spec.** NIP-FI states the rule. ## Rollout limit An agent is covered only if its owner was recorded before the owner is removed. An agent whose owner was removed before the agent signed in with a NIP-OA tag after deploy, or an agent that never signs in with one, stays a member and needs a manual removal. The relay holds no proof of ownership for those agents, so there is nothing to backfill. Supersedes #6098 and #6078. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
4bf7d8a9b0 |
relay: refuse a reaction or deletion whose h names another channel (#9006)
## Summary A reaction, or a deletion that targets a message, belongs to the target message's channel. The relay works out that channel from the target and stores the event there. But every read and every live delivery matches the event's own channel (`h`) tags. So if a client puts a *different* channel in the `h` tag, the event is stored in one channel and only ever matches another: - No one ever receives it. - It still takes a slot when a client asks for "the latest N events" of the real channel. A catch-up can then return fewer events than exist while it looks complete, because the relay removes the stray event after it applies the limit. This is one of the known gaps in https://github.com/block/buzz-app/pull/2206. The relay now refuses such an event. The rule: | Event's `h` tags | Before | After | |---|---|---| | none | accepted | accepted | | include the target's channel | accepted | accepted | | only other channels | accepted, never delivered | refused | The refusal uses the same "target not found" text as the existing refusals for these kinds. So it tells the sender nothing about where the target is. No first-party client sends a mismatched `h`. buzz-app uses the target message's channel, and desktop, mobile and the SDK send no `h` on reactions. So no current client is affected. ### Details - The check covers kind:7 reactions and kind:5 deletions that name their target with an `e` tag. These are the two kinds whose channel comes from a target. A kind:5 that names an addressable event (`a` tag) is not affected. - The check runs only when the target is in a channel, so a reaction to a global event keeps any `h`. A tag must be the channel's UUID exactly as the relay writes it (lowercase, hyphenated), the same way `#h` filters match. - The check runs after the token, membership and archive checks. If it ran first, it would skip their database reads, and the response time could tell someone who cannot read a private channel whether a guessed `h` names the channel that holds a message. - Events already stored with a stray `h` are not changed. They can still take a slot under the limit. - NOSTR.md now says that an optional `#h` on these kinds must name the target's channel. It also says kind:5 takes its channel from its `#e` target (the old text said it used `#h`). ### Related issue None found. Follow-up to the known gaps listed in https://github.com/block/buzz-app/pull/2206. ### Testing - New `reaction_and_deletion_h_must_name_the_target_channel` test, as a member of the target's channel. A reaction whose `h` names only another channel is refused and not stored. A reaction with no `h`, or with both channels, is accepted, and so is a reaction with any `h` on a global event. A deletion of that reaction is refused and not stored with another channel's `h`. It is accepted with the target's `h` or with no `h`. A non-member's wrong guess still reaches the membership check. On a private channel, a right guess and a wrong guess both end at the same membership denial. - I removed the check, and the test failed. I also moved it back before the membership check, and the test failed. - On a local relay over WebSocket: the same refusals and acceptances, with the same messages, and a reaction to a global event keeps its `h`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Human test: Logan asked to take this to team review without a separate hand test (2026-11-17). buzz-review-completed Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> |
||
|
|
3876720c34 |
buzz-db: drop the five single-table guard triggers (BUZZ-318 phase 2) (#9398)
> [!NOTE] > **Rollout:** #8320 (app guards + catalog expand) is deployed, so the hold is lifted. With `autoMigrate=true`, `0096` runs at startup under a 5s lock timeout, and a failure stops startup. With `BUZZ_AUTO_MIGRATE=false`, deploy this binary first and then run `buzz-admin migrate`. Both orders are safe because the expand tolerates the objects being present or absent. ## What The required stop for `0096` is in `docs/trigger-retirement-deployment.md` (from #9622): a relay build at or after #8320 (`ec778bff`). A build older than that needs the tombstone trigger at startup and readiness. Migration `0096_drop_single_table_guards.sql` drops five triggers and their functions. #8320 moved each invariant into the application writers: | Trigger (table) | Function | |---|---| | `trg_channels_community_id_immutable` (channels) | `channels_community_id_immutable()` | | `communities_deletion_tombstone` (communities) | `enforce_community_tombstone()` | | `community_deletion_request_retargeting_guard` (community_deletion_requests) | `prevent_community_deletion_request_retargeting()` | | `community_deletion_approval_removal_guard` (community_deletion_approvals) | `prevent_community_deletion_approval_removal()` | | `community_deletion_manifest_keys_guard` (community_deletion_manifest_keys) | `protect_community_deletion_manifest_keys()` | Desired state (`schema/`) drops the five functions and four trigger files, plus the channels trigger declaration. The universal write fence on `channels` stays. Both boot paths stay catalog-equivalent: the pgschema-vs-migration parity check now also compares columns, key and FK shapes, and the remaining triggers on all five tables. Executor GUCs stay because `assert_community_write_allowed` still reads them through the universal write fence. `transition_community` and every phase-1 app guard are byte-identical to #8320. `scripts/reconcile-schema-after-pgschema.sql` has no entries for these objects. ## Tests - #8320's six `single_table_guard_*_without_trigger` PG tests no longer need to disable a trigger. They are now plain app-path tests with the same assertions. - New per-test regressions for the desired-template and migration boot paths assert that none of the ten objects exist, including disabled triggers and function overloads. - Deleted assertions that only exercised raw SQL against the triggers: retarget, rewrite and approval mutation, frozen-manifest rewrite, and tombstone DELETE. The app-path coverage for each remains. - The expand regression in #8320 migrates through `0086`, validates serving, readiness and the deletion lifecycle, drops the five guards, then validates again. - Rebased onto main `b568d9bf` after #8696 took `0095`; renumbered to `0096`. Blox gate at `7bda1f45`: fmt, clippy and buzz-db `--lib` pass; the PostgreSQL lane ran 219 tests, all pass. - Gate at `c8bc061c` (on main `051dd2d7`, then numbered `0095`, #9622 folded in): on Blox, `cargo fmt --check`, clippy and the buzz-db `--lib` tests pass. The PostgreSQL lane (migrations, single-table guards, floor retirement, fence and deletion) ran 208 tests: all pass. - Earlier gate at `0840ba49`: CI was green, and the Blox PostgreSQL lane passed 840 of 841 (the one failure, `media_reference_full_query_plans`, is a timing check that fails the same way on main on that host). - The rebase updates main's fence-retirement tests to expect the tombstone trigger gone. ## What got simpler Ten database behavior objects and nine desired-state files are gone (about 150 lines). Each rule has a single owner, the application writer. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
44cdd9feef |
push-gateway: lock expired installations before reaping (#9627)
## What The push gateway reaper deletes expired delegations and then expired installations in two statements. A delegation writer (`upsert_delegation`) that holds the installation lock can commit a new child between them. With the foreign key, the installation delete then fails, and the reap transaction rolls back. This PR locks the expired installations with `FOR UPDATE` first, as every authority mutation does. It then deletes their delegations and the installations by id. A writer that was holding the lock commits first, and the delete sees its child. A later writer finds the parent gone and is rejected. No schema change. This is the code half of #9610. The gateway image with this change must run everywhere before the delegation foreign key is dropped. ## Tests Blox at `20b66f8f`: fmt, clippy, and the push-gateway PostgreSQL tests (15/15) pass. - `reaper_deletes_delegation_committed_while_it_waits`: a writer holds the installation lock and inserts a child. The reaper starts and waits. The writer commits. The reaper deletes both rows. - `delegation_for_missing_installation_is_rejected`: `upsert_delegation` for an unknown installation returns `Rejected` and writes nothing. ## What got simpler The reaper now uses the same lock order as every other authority write. The child delete no longer needs a correlated subquery. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b568d9bf95 |
Retire the 0032 roster trigger in migration 0095 (#8696)
## Summary Migration 0095 drops the 0032 channel roster trigger (`trg_events_guard_channel_roster_snapshot`) and its function (`guard_channel_roster_snapshot()`). The trigger repeats a check that the relay already does in Rust. Every kind:39002 roster writer checks the roster against the channel's membership before it saves it (#8316). Since #8611, no relay requires the trigger at startup. This PR is the last step of the trigger retirement sequence in `docs/database.md`. This PR was split out of #8494 so the migration can roll out by itself. A relay from this PR does not change how it stores or publishes roles, and it has no new startup check. It serves correctly whether or not 0095 has run. #8494 stacks on this PR and must not merge until 0095 has run in every environment. ## Details - **Migration 0095.** `DROP TRIGGER` and `DROP FUNCTION`, with `lock_timeout = '1s'` and `statement_timeout = '5s'` as in 0049. `DROP TRIGGER` takes `ACCESS EXCLUSIVE` on each `events` partition in turn, so event reads and writes block while it runs. A timeout rolls it back with no change, and it can be retried. - **Desired-state schema.** `schema/functions/guard_channel_roster_snapshot.sql` is removed. This was the last trigger on `events`, so `schema/triggers/events.sql` and its include go too, as do the pre-attach trigger drops in `scripts/reconcile-schema-after-pgschema.sql`. - **Operator guide.** #8326 added `docs/trigger-retirement-deployment.md` for migrations 0089–0091. (0092 from #9365 and 0093 from #9560 drop nothing; 0094 from #9598 drops two plain SQL functions and has its own section there.) This PR adds 0095 to it: its row, the two ways an older relay fails, the migrate check, and the parent trigger a pgschema deployment must drop first. The Helm chart README names the required stop and points to that guide. - **Tests.** Tests that compared the trigger with the Rust check, or that disabled the trigger first, now test the Rust check alone. Tests that only exercised the trigger against a simulated pre-#8316 writer are removed. The 0075 invite upgrade test now migrates to 0075 exactly. ## Rollout **Required stop: the stop build in `docs/trigger-retirement-deployment.md`** (a relay build at or after `68785206`, the merge of #8325). That build contains #8316 (the app-side roster check) and #8611 (no startup trigger check), so it covers 0095 too. `relay-v0.3.0` contains #8316 and #8611 but not #8325, so it is no longer enough on its own: any build with 0095 also has 0089–0091. Without the stop, an untagged `main` build between 0032 and #8611 refuses to start once the trigger is gone, and a relay without #8316 can save stale kind:39002 snapshots (`docs/database.md` Rule 5). **Merge gate.** Every push to main publishes relay `:main` images, and the Helm chart defaults to `migrate.autoMigrate=true`. Do not merge this PR until the stop build or later runs on every serving and rollback target. That is the same gate #8326 had for 0089–0091. After that, either way works: - With `autoMigrate=true`, the first relay from this PR applies 0095 at startup. - With `autoMigrate=false`, run `buzz-admin migrate` when convenient. Relays from this PR serve with or without 0095. As with every new migration, an older binary with auto-migration on refuses a database that has 0095 (sqlx `VersionMissing`). A rollback past this release needs auto-migration off (`docs/database.md`). ## What happens next #8494 computes the `member`/`bot` label at read time. The 0032 trigger compares labels with the stored role exactly, so it would refuse those rosters. #8494 adds a startup check that refuses to serve while the trigger is installed. Merge it only after 0095 has run everywhere. ### Testing - `migration_0095_retires_the_roster_trigger`: on a database migrated through 0094, the trigger and function are installed. After the remaining migrations, both are gone, and a raw kind:39002 insert that does not match membership is accepted. It fails if 0095 does not drop them. - `embedded_migrator_contains_consolidated_initial_schema` pins 95 migrations and the 0095 statements, and checks that the desired-state schema no longer installs the function. - `migration_schema_desired_pgschema_reconcile_matches_populated_upgrade`: its fixture drops each retired parent trigger before pgschema runs (pgschema drops partition copies before the parent, which PostgreSQL refuses with 2BP01). It now drops the roster trigger too. - Locally at this head: `cargo check`, `cargo fmt --check`, and 245/245 buzz-db unit tests pass; 760/764 buzz-db Postgres tests pass. The four `event_follow_up_contract` tests fail the same way on `main` locally and pass in CI. CI runs clippy and the full PostgreSQL lane. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c01d3292a1 |
fix(db): hard-delete superseded relay-signed lists (#9586)
## Why
The relay republishes its own lists in full on every change:
- the NIP-43 membership list (kind 13534)
- the NIP-IA archived list (13535)
- NIP-29 group state (39000 metadata, 39001 admins, 39002 members)
Each write soft-deletes the previous head. No reader returns a
soft-deleted row, so each retired copy is dead weight in `events` and
its indexes. On the deployments we measured, these retired copies are
about 40–65% of monthly `events` growth. The NIP-33 path already
hard-deletes superseded NIP-RS read state and mesh status in the
replacing transaction. This PR applies the same rule to the relay-owned
lists.
## What
When a write supersedes a head of kind 13534, 13535, 39000, 39001, or
39002, it deletes the old head instead of soft-deleting it. The delete
runs in the same transaction, under the same scope and lock as before.
The change applies on the 3 paths the relay uses to write these kinds:
- `replace_addressable_event_under_lock` (13535, 39000, 39001, including
`buzz-admin` writes through `replace_addressable_event`). It gates on
the new `hard_deletes_superseded(kind)`. Other kinds on this path (0, 3,
10002, …) keep the soft delete.
- `LockedMemberSnapshot::replace_member_event` (39002).
- `write_nip43_membership_snapshot` (13534).
All 3 paths build their head read and supersede statement with one
function, `replacement_sql(in_channel, hard_delete)`, keyed by
`hard_deletes_superseded(kind)`.
Kind 13535 is now relay-only: ingest rejects a client-submitted 13535
with `restricted: relay-only kind`, as it already does for 13534. NIP-IA
defines 13535 as relay-signed, and every relay, desktop, CLI, and mobile
reader filters on the relay's pubkey. No client in this repository
publishes it.
The 39000–39002 paths already use `superseded_with_mentions_sql!`, so
the old head's mention rows are deleted with it, as before.
The gate checks the kind, not the signer, and every supersede is scoped
to the event's own pubkey. A client-signed 39000–39002 is routed to the
NIP-33 path, which keeps the soft delete. Channel deletion
(`soft_delete_discovery_events`) retires the live heads without a
replacement and still soft-deletes them.
This PR has no migration and no schema change.
## Why this is safe
- **Readers:** relay reads of these kinds filter on `deleted_at IS
NULL`, so a retired head was already invisible. One reader includes
soft-deleted rows: the admin event preview (`get_event_preview`). It
will now report a superseded roster id as absent instead of deleted. A
moderation report against an old version of a channel's metadata (for
example, a name it had before a rename) will show no target content. An
operator can no longer look up an old roster or membership list by id to
audit past membership. `docs/admin/README.md` now documents this for
`GET /api/admin/v1/events/{id}`.
- **Operator repair:** when `buzz-admin`'s group-state reconcile
overwrites a 39000–39002 head, the old row is gone, so an operator can
no longer restore it with `UPDATE … SET deleted_at = NULL`. The relay
rebuilds these lists from `channels` and `channel_members`, so no source
data is lost.
- **Replays:** while the coordinate has a live head, a replay of a
deleted head's id is still rejected, because its `created_at` does not
beat the live head's. With no live head (after channel deletion, for
example), the deleted row no longer makes the replay a duplicate. Only
the relay can submit these events: ingest requires the event's signer to
be the authenticated pubkey, 13534 is relay-only, and the relay's
writers sign a new event on every attempt. The existing tests for
soft-deleted replays seed their own rows and do not change.
- **13534 id uniqueness:** the writer still takes `max(created_at)` over
every stored list. The live head is always the newest, so the next
list's `created_at` still moves past every earlier one.
- **13535 strict stamps (NIP-IA, #9476):** each new archived list is
stamped past the live head, which the writer reads behind the
replacement lock. It never reads retired rows, so deleting them does not
change the next `created_at`.
- **Database objects:** no foreign key references `events`, and none of
these kinds is a push kind. The DELETE runs in the same admitted
community write transaction as the old UPDATE. The only trigger left on
`events` is the BEFORE INSERT kind 39002 roster guard
(`guard_channel_roster_snapshot`), and a DELETE does not fire it.
- **Rolling deploy (docs/database.md Rule 7):** old pods keep
soft-deleting and new pods delete. Both leave exactly one live head per
coordinate, under the same locks.
## Follow-up
Rows that are already soft-deleted stay. Rule 3 does not allow a
migration to delete them. A separate PR will add a
`scripts/maintenance/` repair script: bounded batches, the
community-deletion lock, and a validation query. An operator runs it
after this change is fully rolled out.
Not in this PR: the relay-signed NIP-DV DM visibility snapshot (kind
30622, `publish_dm_visibility_snapshot`) is written on the NIP-33 path
and still soft-deletes its superseded heads. We will measure its share
of `events` growth before we change it.
## QA focus
- **Each roster write keeps exactly one stored row.** Create a channel,
then add and remove members, change roles, and edit the metadata. For
each of 39000, 39001, and 39002, the channel must have exactly one
`events` row (live), not one live row plus retired ones. Do the same for
13534 (relay membership add, remove, and role change) and 13535 (`agents
archive` and unarchive).
- **Other kinds still soft-delete.** Replace a kind 0 profile or kind 3
contact list. The old row must stay, with `deleted_at` set.
- **Mention rows.** After a 39002 or 13535 replacement, `event_mentions`
has no rows for the deleted head's id.
- **Admin event preview.** Opening the id of a replaced roster now shows
the event as absent instead of deleted. Check that this is acceptable in
the admin UI, including a report filed against a channel's metadata
before a rename.
- **13535 `since` cache.** Archive and unarchive several times,
including at the same time. Each new list has a `created_at` later than
the one before. A mobile client that asks `since` its list's
`created_at` + 1 gets the newer list.
- **Client 13535 is rejected.** Publishing a kind 13535 signed by a user
key returns `restricted: relay-only kind`. Archive and unarchive (kinds
9035 and 9036) still work, and the relay still publishes its own 13535.
- **Channel deletion.** Deleting a channel still soft-deletes its live
39000–39002 heads. This path is unchanged.
- **Mixed-version rollout.** With an old and a new relay on one
database, each coordinate keeps exactly one live head. Rows that old
pods soft-deleted stay until the follow-up script runs.
- **Existing soft-deleted rows are not touched.** The disk-space gain
shows only in growth after deploy. The follow-up script cleans up the
backlog.
## Tests
- `only_relay_owned_lists_hard_delete_their_superseded_heads`: checks
the kind set, including the neighbours 13533, 13536, 38999, and 39003,
and negative kinds.
- `superseded_heads_drop_their_mention_rows` (Postgres) now expects the
old head to be gone for the 39002 member snapshot, 13535 (global), and
39000 (in a channel). A kind 3 contact list on the same addressable path
is the control: it must stay soft-deleted.
- `replacement_channel_predicate_is_an_index_condition` (Postgres) now
builds its statements with `replacement_sql`, the same function
production uses, for all 4 scope and retire-mode combinations. Before,
it checked hand-copied SQL. It checks that each `DELETE` seeks by
`channel_id` on every populated partition, as the `UPDATE` does.
- The 39002 and 13534 writers take their statements from
`replacement_sql` and `hard_deletes_superseded`, so the index-condition
test covers each statement production runs.
- `nip_ia_archived_list_is_relay_only` (buzz-core): 13535 is relay-only,
and the 9035 and 9036 requests are not.
- `test_client_submitted_nip_ia_archive_snapshots_are_rejected`
(buzz-test-client e2e, against a running relay): a client-signed 13535
is rejected with `restricted: relay-only kind` over both WebSocket and
HTTP. It shares a helper with the existing 13534 test. Against a relay
built without the 13535 gate, it fails at the WebSocket assertion. The
Relay E2E step in `.github/workflows/_ci-relay.yml` now selects it, next
to the 13534 test.
- `late_owner_link_closes_ownerless_agent_sockets_on_owner_revoke`
(buzz-relay, Postgres) copies selected tables into a private schema. The
13534 writer's supersede now also deletes the old list's
`event_mentions` rows, so the fixture copies `event_mentions` too.
- `every_membership_write_commits_its_list` (Postgres): after each
membership writer runs, the community stores exactly one kind 13534 row.
- `concurrent_archival_publishers_stamp_strictly_increasing_snapshots`
(buzz-relay, Postgres, from #9476) counted the 16 stored kind 13535
rows, superseded ones included. It now pins the head an hour ahead and
asserts that the coordinate stores exactly one row, at the pinned
`created_at` + 16 s. That holds only if each of the 16 publishers stored
exactly one snapshot, one second past the head it replaced. A
same-second replacement leaves the row short of + 16 s, and a publisher
that runs out of attempts still fails its `expect`.
- `a_publisher_that_read_before_an_edit_cannot_replace_it` (buzz-relay,
Postgres) counted retired kind 39000 rows to prove that each publisher
stores a new second. It now asserts that the coordinate stores exactly
one row, at the pinned `created_at` + 2 s. The mutation it guards
against (taking the live `created_at` before the lock) leaves the head
at + 1 s, so the test still catches it.
Commands run:
- `cargo clippy -p buzz-core -p buzz-db -p buzz-relay --all-targets --
-D warnings`
- `cargo test -p buzz-core --lib`
- `cargo nextest run -p buzz-relay --lib`
- `cargo test -p buzz-test-client --test e2e_relay -- --ignored` for the
13534 and 13535 rejection tests, against a local relay built from this
branch
- `cargo test -p buzz-db --lib`
- `cargo test -p buzz-db --test observability_source`
- `scripts/postgres-test-run.sh -p buzz-db -p buzz-relay --lib --tests`
(the CI PostgreSQL lane, run locally)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
8b6bc9beb5 |
Add community-scoped user and agent profile cleanup (#9580)
## Summary
Content, account and media cleanup leave profile records behind. Add
`buzz-admin user-deletions profile-batches` to preview or delete those
records in one community. Preview is the default; explicit `--delete`
applies bounded, retryable transactions.
Every run and retry discovers the human’s current direct agents in that
community. Ownership elsewhere cannot authorize deletion here. If Alice
owns an agent in A but Bob owns it in B, deleting Alice in B preserves
that agent. Each write batch locks and rechecks ownership. All profile
data is removed before identity rows, so an interrupted run resumes
without saved agent keys. The command no longer accepts
`--agent-pubkey`.
The handler removes profile/configuration events and projections,
rebuilds shared archive snapshots with valid signatures, and finally
removes identity rows. Repository announcements/state (30617/30618) and
name mappings remain intact without blocking identity removal; other
authored content still requires prior cleanup. Unresolved dependencies,
changed sources, untrusted signers or excessive plans stop deletion.
This includes historical `replaced-by` references in archive requests
and deltas, even after unarchive removes the current archive row. See
[operator instructions and verification steps](docs/profile-cleanup.md).
Writers must be stopped. Coordinator integration, online admission
fencing, media objects, client caches and final account-erasure
verification remain separate. The command always reports
`account_erasure_complete: false`.
### Related issue
Fixes #9576. Continues the standalone handler pattern from #9363
(content) and #9364 (account). This is an independent PR against main.
### Testing
The latest correction adds a PostgreSQL regression that runs content
cleanup followed by profile preview/delete/retry for human and agent
repository owners. It checks unchanged repository events, mentions, name
mappings and other-community data, and verifies ordinary content still
blocks profile deletion. The merge of main brings in `buzz-deletion
--lib` coverage in the CI unit lane and its fallback, covering the
preview-default parser test without duplicate runs. Account, content,
media and profile command dispatch are all preserved. The
archive-history documentation also now distinguishes planning errors
from printed blockers.
The latest main merge includes the shared dependency-policy correction
from #9609 and the content cleanup lock fix from #9615. On `54bd50299`,
PostgreSQL CI passed 1647 tests and failed 18 because content cleanup
still called the retired SQL lock-key function; this also blocked the
new content→profile regression. The merged upstream fix uses the
existing Rust-built key for both the cleanup lock and the test blocker.
Local test suites and hooks remain skipped at the owner’s request. CI
and review of the updated head are pending. The results below apply to
earlier revisions.
At `92aa9c216`, exercised the rebuilt `buzz-admin` against signed
archive/unarchive events stored in disposable PostgreSQL:
- For kinds 9035 and 8002, test a historical `replaced-by` reference to
the human and then to their owned agent after unarchive.
- Run `profile-batches --pubkey <human> --community <A> --relay-pubkey
<relay>` in preview and `--delete` modes. Both refuse the unresolved
reference; full table dumps remain unchanged.
- Keep that history only in community B. Cleanup in A succeeds,
preserves B, and selects zero work on retry.
- Delete the archive subject in B. Its history is removed while the
replacement identities remain intact.
All four scenarios passed. These are signed database fixtures exercised
through the real CLI; they do not claim live relay admission. The
correction also merges main and preserves content, media and profile
command dispatch.
The initial full database run passed 880/881 tests: the new request
fixture lost its required self-`p` tag during signing. Commit
`ff6689386` preserves that tag; all ten profile regressions now pass.
Further local checks and pre-push hooks were skipped at the owner’s
explicit request. The full corrected database suite has not been rerun;
GitHub CI will validate the new head. At `ff6689386`, the production
code matched the CLI-tested revision; the repository-retention
correction above is newer.
Previous ownership validation follows:
At `090d2a1cf`, exercised the rebuilt `buzz-admin` binary against a
disposable PostgreSQL fixture:
- Run `user-deletions profile-batches --pubkey <human> --community <A>`:
preview left table exports unchanged and selected four profile/identity
mutations.
- Repeat with `--delete --batch-size 2`: all four mutations committed;
retry selected zero work.
- Use the same human and agent keys in another community, with the agent
owned by someone else: only the human was selected, and the agent
remained intact.
This fixture uses placeholder profile signatures and validates
database/CLI behavior. It does not claim live signed-event admission.
The earlier live relay and Desktop results below cover the previous
revision.
Independent agent review covered the previous ownership correction. A
later review found the historical replacement-reference bug; the
historical-reference correction addresses that finding. Fresh review of
this revision is still required. Human command verification has not been
recorded; it is not claimed by the agent-run checks. Follow the local
verification steps in `docs/profile-cleanup.md`; preview must leave data
unchanged, deletion must preserve other-community records, and retry
must select zero work.
<details>
<summary>Historical validation at
|
||
|
|
051dd2d7aa |
fix(sdk): timestamp channel messages with millisecond offsets (#9548)
Kind-9 messages sent through the SDK or `buzz messages send` omit the `ms` tag, so clients break same-second ties by event ID. Capture one clock reading in the shared message builder and use it for both `created_at` and the canonical 0–999 millisecond offset, including direct and nested replies. Validation: both new regressions failed before the fix; the full CLI suite (691 tests) and SDK suite (335 tests) pass. The SDK test checks that the timestamp is pinned before signing; the CLI test captures and verifies signed HTTP submissions for roots and both reply depths. The built CLI also sent direct and nested replies through a managed signer to a live relay; readback confirmed one canonical `ms` tag and correct thread tags on both. Client ordering and human testing remain pending; keep this PR draft. To test manually, run `cargo build -p buzz-cli`, then send several kind-9 messages with `target/debug/buzz messages send --channel <channel> --content <text>` and direct/nested replies using `--reply-to <event-id>`. Inspect their raw events: each should carry exactly one canonical `ms` value, and a client that honors `ms` should display same-second sends in timestamp order. Related: #9541 updates mobile display ordering to consume these offsets. No duplicate producer fix found in the open PR/issue search. Repository-wide validation: `just ci` passed Rust/Tauri Clippy and formatting, then failed mobile analysis at `mobile/test/features/search/search_channels_journey_test.dart:933`: `_RenamingSession.subscribeWithStatus` omits the base method's `resumeSince` parameter. Mobile files are unchanged from the base commit. This unrelated failure remains outside this fix. The first push hook run failed the existing WebSocket throttle test `a_throttled_sign_in_reconnects_with_fresh_evidence` (connection reset during sign-in); a subsequent full CLI rerun and the complete normal push-hook retry passed without source changes. The test uses a kind-20001 event and does not call the changed builder. All required push hooks passed. Signed-off-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> |
||
|
|
3bd121bc15 |
Check product_feedback's community in the writing transaction (#9608)
## Summary Third app-side step of retiring the database foreign keys (after #9399 and #9404). After this, every reference the drop migrations will remove is checked in application code. - **`product_feedback -> communities`:** `product_feedback::insert` now runs in a transaction. It locks the community row `FOR KEY SHARE` and returns `NotFound` when the row is missing. This is the same guarantee the foreign key gives. Any lifecycle state still qualifies. `docs/database.md` says provenance-only tables stay writable while their community is being deleted, and the purge clears their provenance. - **Reader tolerance:** `ProductFeedbackRecord.community_id` is now `Option<Uuid>`. The purge sets `community_id = NULL`, and `list` (used by `buzz-admin list-product-feedback`) failed to decode those rows. The JSON output shows `null` for them. - **One home for reference checks:** `require_workflow` and `require_workflow_run` move from `store/workflow.rs` into `store/reference_check.rs`. The workflow owner and channel checks now reuse `require_user` and `require_optional_channel`, so two duplicate helpers are gone. A new `require_community` joins them. - **Stale comments:** comments that justified behavior by the foreign keys now say what holds both before and after the drop. Touched: the purge order (`deletion.rs`), `command_executor.rs`'s `ensure_user`, the `set_agent_owner` doc, the NIP-43 snapshot lock note (`relay_members.rs`), `attach_scheduled_workflow_run`, and one workflow deletion test. ## Writers and readers checked (RPR #2) `product_feedback.community_id` writers: - `store/product_feedback.rs` `insert`: the only insert. It is now checked. - `store/deletion.rs` `purge_postgres`: sets the column to `NULL`. No check is needed. - `store/relay_admin_actions.rs` status update: does not touch `community_id`. Readers: - `product_feedback::list`: fixed to accept `NULL`. - `store/admin_moderation.rs` inbox queries: already `LEFT JOIN` and accept `NULL`. ## Tests All three tests drop `product_feedback -> communities` in the per-test database first, so a pass proves the application check and not the constraint. - `insert_rejects_missing_community_without_foreign_key`: a community that never existed gets `NotFound` and no row. A fenced community still accepts feedback. An active one accepts it, and a replay returns the same row. - `insert_key_share_locks_community_without_foreign_key`: an insert waits while another transaction holds the community `FOR UPDATE`, then proceeds. - `list_returns_rows_with_cleared_provenance`: a row with `community_id = NULL` is listed with `community_id: None`. ## Not in this PR - The foreign key drop migrations. They come after this PR is deployed (`docs/database.md` expand/contract). - Nothing in the database stops `DELETE FROM communities` on an active community once the community foreign keys are gone. The tombstone trigger rejects it only for inactive communities. Production never hard-deletes communities. This is decided with the drop migrations, since a trigger change conflicts with the no-new-triggers rule. ## What got simpler All in-transaction reference checks now live in one module. Two duplicate helpers were removed. `store/workflow.rs` loses about 80 lines. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
0a05330740 |
buzz-db: stop calling the dropped lock-key function in SQL (#9615)
## Summary Main's user content cleanup still calls the SQL function `community_deletion_lock_key`. Migration `0094` (#9598) drops it. On any database at `0094`, every user-deletion content batch fails with `42883 function community_deletion_lock_key(uuid) does not exist`. #9363 added this caller after #9396 moved the key to Rust. This PR binds the Rust-built key with `hashtextextended($1, 0)`, as every other caller does. - `content_batches/execute.rs`: the batch's exclusive advisory lock uses the Rust key. - `content_batches/safety_postgres_tests.rs`: the test blocker takes the same lock the same way. - `docs/trigger-retirement-deployment.md`: builds from #9363 up to this PR are not valid stops before `0094`. Rebased onto main `e894d75d`. The renumber and the `update_channel` test-call fixes this PR first carried are already on main through #9616, so they are gone from this PR. Deployed relays are unaffected: the deployed build predates #9363. ## Tests The 17 `user_deletion::content_batches` PostgreSQL tests fail on main at `0094` with the error above. This PR makes them pass. ## What got simpler One fewer SQL-side copy of the lock key. Every caller now builds the key in Rust. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>mobile-v1.5.0-rc.2 |
||
|
|
8fb0de8d53 |
Clean up account records and refresh member lists (#9364)
## Summary Add bounded, resumable cleanup for a user’s account records and their current direct agents in each selected community. Preview prints the proposed changes without writing; deletion uses the same selectors through the command and workflow handler. Each run and retry discovers agent ownership again. An agent owned by Alice in one community and Bob in another is cleaned only in Alice’s community. Ownership changes stop the current run, and ownership rows remain available for retries and later handlers. Membership removal rebuilds and signs the current channel lists and community roster in the same transaction as each removal. A failed roster write rolls back that membership removal. The command requires the existing relay signing key when channel or community memberships are present, including users with no channel memberships. Preview does not require a key. The relay, account cleanup and admin reconciliation share the kind 39001/39002 tag builders in `buzz-db`. They preserve the existing identity tags, roster order and role positions. Regular unit-test runs now include `buzz-deletion` through both nextest and the Cargo fallback. **Channel ownership policy:** deletion may remove the last channel owner, including when the human and their agents are all owners. The channel, messages and surviving members remain. A surviving admin can manage the channel and grant ownership. If no owner or admin remains, members can continue normal use, but management recovery requires operator intervention on request. Cleanup does not require a channel ownership handoff or assign a replacement owner. The separate community-owner restriction remains. The content handler now on main advances to account cleanup before the remaining agent stage. Content and account workflow progress goes to stderr so stdout remains one JSON inspection document. The direct account command retains NDJSON stdout. Nullable attribution updates use explicit table and SET clauses so the source-policy guard can inspect them. The handler covers credentials, memberships, read progress, supported personal events and their copies, feedback, and explicit global listener/database-role cleanup. It retains shared records and historical signed lists. Scope files select the human and communities; saved agent keys do not authorize deletion. This remains an offline operator feature: stop relay and external writers before deletion. It does not revoke already-connected sessions. Coordinator integration, remaining handlers and final erasure verification are separate; results always report `account_erasure_complete: false`. The real account workflow still stops at an unimplemented successor. ### Related issue Replaces the account scope of #9354 and #9355 with one focused PR. Those earlier PRs remain intact for reference. Agent cleanup belongs within the business handlers; this change does not integrate the historical standalone agent stage in #8959. ### Testing Exercised the real preview and delete commands in an isolated local relay/database with Alice disconnected and Bob’s desktop app open. Preview left the normalized database dump unchanged. Deletion checks covered all 101 tables and all 30 affected channels; 168 newly signed list events verified. Bob refreshed the member dialog and saw Bob, B1 and Carol, then successfully sent and read a message. A1’s membership in the community where Bob owns it remained intact. The live CLI and desktop evidence above predates the latest follow-up. Independent end-to-end checks at `d45759df2` also verified unchanged preview data, signed channel/community lists after deletion, signing-key preflight, and workflow JSON stdout. The shared-builder follow-up was source-reviewed and formatted; local builds, tests and commit/push hooks were skipped at the author’s request. Validation of the new revision and a repeat of the signed-list end-to-end check are pending. Human testing remains pending. For human verification, use an isolated database and its relay signing key. Preview a community-only member, confirm no writes, then delete and verify the current kind 13534 roster omits them. Run an approved account-stage fixture with `user-deletions run <id> --delete --next-step`; the entire stdout must parse as one JSON document, with batch progress on stderr. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Signed-off-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
a26eacde49 |
perf(mobile): save own thread interest once per unread catch-up (#9614)
iOS was killing the app with watchdog terminations (`0x8BADF00D`, "scene-update watchdog transgression" and "Failed to terminate gracefully") because the main thread spent 5 to 10 seconds in unread catch-up. Symbolicated reports from a 1.4.0-rc.1 user all point at the same stack: `UnreadCatchUp._catchUpUnreadEvents` → `ChannelsNotifier._writeThreadInterestStores` → `jsonEncode` / `SharedPreferences.setString`. For every self-authored event in a catch-up batch whose thread was new to the interest sets, the notifier re-encoded **both** whole root-id sets and wrote both to SharedPreferences. That is quadratic in the batch: a fresh sign-in, whose catch-up returns many of the user's own messages, ran thousands of growing encodes and platform-channel writes on the main thread. Now the catch-up adds the whole batch to the in-memory sets and saves once if anything changed. The live single-event path is unchanged (one write per new thread). ### Regressions None expected. The persisted keys, format and contents are identical; only the number of intermediate writes changes. The storage contract is unchanged: saves were and still are fire-and-forget `setString` calls, so neither version guarantees durability before a process kill. A kill before the save lands now loses the whole batch rather than a prefix of it; a later catch-up can re-add those threads only while they are still after the channel's read timestamp and within the catch-up window. ### Validation - **Writes per catch-up**, 50 own messages across 50 threads: 50 writes per key before, 1 after (new test). - Added test: `unread catch-up saves own thread interest once per batch` (channels_provider_thread_interest_cases.dart). It checks the saved sets and the write count; it fails on the old code. - Full mobile check and test suite pass. - Automated full-app run on an iOS simulator (PR head build, signed in to a real community): cold launch and unread catch-up saved both thread-interest sets; background and foreground; Activity rows and unread dots render; opened a thread and sent a reply, and the participation set grew by one (live path still saves). No errors in the app log. Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
e894d75d26 |
buzz-db: fix main (renumber the function drop to 0094, update_channel test call) (#9616)
## Summary Main has two migrations numbered `0093`: - `0093_push_gateway_installation_platform.sql` from #9560 - `0093_drop_plain_sql_functions.sql` from #9598 The file names differ, so GitHub showed no conflict between the PRs. sqlx applies the first version-93 migration and then rejects the second as a changed migration 93. Every migrate run on main fails, including relay startup with auto-migration on. This PR moves #9598's migration to `0094`: - `git mv migrations/0093_drop_plain_sql_functions.sql migrations/0094_drop_plain_sql_functions.sql`. The SQL is unchanged. - `embedded_migrator_contains_consolidated_initial_schema` now expects 94 migrations, with the function drop at version 94. - The Postgres test is renamed to `migration_0094_drops_plain_sql_functions`. It finds the migration by description, so its logic is unchanged. - `docs/trigger-retirement-deployment.md` now names `0094`. #9560's `0093` keeps its number. It reached main first and may already be applied on deployments that auto-migrate. ## Second break on main: `update_channel` call sites Main's buzz-db lib tests also stopped compiling. #9581 added a `sender` argument to `update_channel`, and #8320's cross-community test (`deletion.rs`) landed in parallel with the old three-argument call. This PR passes the channel creator as the sender. The test only renames an open channel, so the private-to-open rule does not apply. ## Deployments No deployment has applied #9598's `0093`: no image built from main after #9598 has rolled out yet. A database that applied #9560's `0093` applies `0094` next. Do not promote any image built from `4e8f8365` (the #9598 merge) or later until this PR merges. ## What got simpler Nothing. This is a renumber and a test call fix only. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f158fdd9a1 |
feat(relay): name the agent whose add policy refuses a DM (#9601)
## Problem When an agent's add policy refuses a DM open or add (from #9125), the refusal says only that an agent refused. The person can't tell which agent blocked it, so they don't know whose owner to ask. ## Change The DM refusal now ends with `(agent <hex pubkey>)` for the first agent refused, in the order the request named them. For example: `forbidden: policy:owner_only — only the agent owner can add this agent (agent 3f9a…)` The prefix is unchanged, so existing clients that match on `policy:owner_only` or `policy:nobody` keep working. Desktop and mobile follow-ups will show the agent's name. ## Tests - `adding_an_agent_follows_its_add_policy` asserts the full refusal including the agent. - `opening_with_several_agents_follows_their_add_policy` adds a second refusing agent and checks the first one named is reported. - DM Postgres tests: 297/297 passed. Clippy is clean. 🤖 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> |
||
|
|
4e8f836576 |
buzz-db: drop the community_deletion_lock_key and profile_name_fields functions (contract) (#9598)
## Summary Phase 2 of retiring the two remaining plain SQL functions. Phase 1 moved their work into the relay: - #9396 builds the community deletion lock key in Rust (`deletion::community_deletion_lock_key`, locked with `hashtextextended($1, 0)`). - #9397 reads profile names with inline SQL (`PROFILE_NAME_FIELDS` in `buzz-search`). No relay at or after #9397's merge (`279a31da`) calls either function. This PR drops them: - **Migration 0093** runs `DROP FUNCTION community_deletion_lock_key(UUID)` and `DROP FUNCTION profile_name_fields(TEXT)` under a 5s `lock_timeout`, with no `IF EXISTS` and no `CASCADE`. If anything still depends on a function, the migration fails instead. Migrations 0029 and 0064 stay frozen. No database function calls either one any more: 0090 dropped the fence functions, which were the only SQL callers of the lock key. - **Desired state:** removes both `schema/functions/` files and their `schema.sql` includes. Both boot paths stay catalog-equivalent (`admin_schema_parity_between_desired_state_and_migrations`). - **Tests:** - New `migration_0093_drops_plain_sql_functions`. It migrates to 0092, checks that both functions exist and that serving and deletion catalog validation pass, then runs 0093 and checks that both functions are gone and that validation still passes. This covers new code on either side of the drop. - The migration listing test pins 0093's statements and that it has no `CASCADE`. - `desired_state_catalog_has_no_universal_fence_and_still_boots` now asserts that both functions are absent. - Replaces the Rust-vs-SQL lock key parity test with `community_deletion_lock_key_bytes_are_fixed`, a unit test that maps fixed UUIDs (nil, max, and one with hex letters) to their exact keys. Older replicas and the repair-script key in `docs/database.md` build the same string, so a changed prefix or UUID format must fail a test. - Removes two relay test-schema wrappers (`bridge.rs`, `ingest.rs`) that forwarded `community_deletion_lock_key` to `public`. Writers no longer call it, and the wrapper's `CREATE FUNCTION` would fail once the function is gone. - **Docs:** `docs/trigger-retirement-deployment.md` gets a `0093` section with the required stop. ## Deploy gate **Required stop:** any relay build at or after `279a31da` (#9397's merge, which follows #9396). `relay-v0.3.0` does not contain it. A relay older than that which still serves after 0093 fails every write and deletion that takes the community deletion lock, with `42883 community_deletion_lock_key(uuid) does not exist`, and its profile name search fails with `42883 profile_name_fields(text) does not exist`. 0093 takes no table locks and needs no cleanup. Migration number: #8696 and #9398 also propose `0093`. Whichever lands second renumbers. ## Review-Proven Rules - **RPR #2 (every path):** I checked every reference on `main` and at the stop build `279a31da`. At both, only test code reads either function: no boot, readiness, catalog or runtime query depends on them. Serving and deletion catalog validation pass before and after 0093, in the new test. - **RPR #3 (falsifiable):** removing the `profile_name_fields` drop from 0093 turns `migration_0093_drops_plain_sql_functions` red. - **RPR #3 (lock key bytes):** a changed prefix, `.simple()` UUID formatting, or uppercase formatting each turns `community_deletion_lock_key_bytes_are_fixed` red. ## What got simpler Two database functions, their desired-state files, a cross-language parity test and two test-only SQL wrappers are gone. After this PR, the only functions left in `schema/functions/` are trigger functions. ## Validation Blox gate at `95ac71c8`: - `cargo fmt --all --check`, and `cargo clippy -p buzz-db -p buzz-relay --all-targets -D warnings`. - `buzz-db --lib` unit tests: 216/216, including the migration listing test. - `buzz-db` Postgres tests (`migration::`, `deletion::`, `nip_fi_binding::` postgres_tests): 130/130. These include `migration_0093_drops_plain_sql_functions`, `admin_schema_parity_between_desired_state_and_migrations` and `deletion_surface_parity_between_migration_0029_and_schema_sql`. - `buzz-search` `profile_names*` Postgres tests: 4/4, on a fully migrated database where `profile_name_fields` no longer exists. - The two relay tests whose test-schema wrapper this PR removes: 2/2. - Must-fail check: with the `profile_name_fields` drop removed from 0093, `migration_0093_drops_plain_sql_functions` fails. Second Blox gate at `e1b5513a` (the lock key vector test): - `cargo fmt --all --check`, and `cargo clippy -p buzz-db --all-targets -D warnings`. - `buzz-db --lib` unit tests: 217/217. - Must-fail checks: a changed prefix, `.simple()` and uppercase UUID formatting each fail `community_deletion_lock_key_bytes_are_fixed`. The first gate run found that `deletion_surface_parity_between_migration_0029_and_schema_sql` still expected `community_deletion_lock_key` in `schema.sql`. The second commit fixes that. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
66b463fb2f |
fix(deps): clear chrono, humantime and zip advisories from the dependency policy (#9609)
## Summary main's `Security` check (`cargo-deny check`) fails on six new advisories: - RUSTSEC-2026-0545, 0546, 0547, 0548: zip 8.6.0 (fix in zip >= 9.0.5). - RUSTSEC-2026-0543: chrono is unmaintained. - RUSTSEC-2026-0542: humantime is unmaintained (it wraps chrono). This PR adds ignore entries with reasons. It changes only `deny.toml`. ## Why ignore and not upgrade **zip.** zip 8 reaches the graph only through the examples-only `buzz-mesh-smoke` crate, via mesh-llm v0.76.2. mesh-llm builds zip with only the `deflate` feature. It reads archives through `ZipArchive` and copies entries by hand. It never calls `extract`, never decrypts AES entries (`aes-crypto` is off), never enables `legacy-zip`, and never uses `ZipStreamReader`. None of the affected code paths run. mesh-llm v0.79.0 ships zip 9.0.5. But that release removes the `client` feature of `mesh-llm-sdk`, which `buzz-mesh-smoke` and desktop use. A bump needs an SDK migration in both places. That is out of scope for a red-main fix. The new IDs join the existing zip block. Its note said the fix was in "unreleased mesh-llm#2471". That is stale, so the note now names the release and the migration it needs. **chrono / humantime.** Both are unmaintained, not vulnerable. Neither has a maintained release. chrono is a direct workspace dependency of most crates. humantime comes only through `buzz-mesh-smoke` → mesh-llm → hf-xet → xet-runtime. Removing them needs a migration to `time` or `jiff`. ## What got simpler Nothing could. The new ignores are the smallest change that makes the check pass. Identified debt: - The mesh-llm SDK migration to v0.79+ would delete all eight zip ignores. - A chrono → `time`/`jiff` migration would delete both unmaintained ignores. ## Test plan - [x] `cargo-deny check` at this tree: `advisories ok, bans ok, licenses ok, sources ok` (exit 0). - [x] `git diff --check` clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>mobile-v1.5.0-rc.1 |
||
|
|
026b203c64 |
docs: define mobile diagnostic reporting (#9600)
## Summary Records the vocabulary, the two hard-to-reverse decisions and the spec for diagnostic reporting in the mobile app, before any code is written. Nothing here changes behavior. - `CONTEXT.md`: two new terms. **Diagnostic reporting** is sending crash, error and performance data from a mobile installation to a reporting destination. A **reporting destination** is where a build sends it, chosen at build time by whoever distributes the build. - [ADR 0007](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/adr/0007-diagnostic-reporting-follows-the-destination.md): a build reports if, and only if, it was given a reporting destination, whatever kind of build it is. It also lists what a report may and may never carry. - [ADR 0008](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/adr/0008-sentry-for-mobile-diagnostic-reporting.md): the app reports through the Sentry Flutter SDK, with the comparison against Datadog and Bugsnag. - [`docs/mobile-diagnostic-reporting.md`](https://github.com/block/buzz/blob/tomb/mobile-diagnostic-reporting-docs/docs/mobile-diagnostic-reporting.md): the spec for step one. It covers crashes, uncaught errors, error reports for unexpected protocol and decoding failures, and networking measurements by backend and endpoint, all through one reporting module. It sits beside the existing mobile push suppression spec. The term avoids "telemetry" because the repository already uses that word for agent session streams and relay rollout signals. ### Related issue N/A. The Swift Package Manager move that ADR 0008 depends on is #9597. ### Regressions Documentation only. No code, configuration or build changes. ### Validation Checked that every link in the four files resolves within the branch, and that the new glossary anchors match the links that point to them. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz> |
||
|
|
148585c804 |
build(mobile): link iOS plugins through Swift Package Manager (#9597)
## Summary The iOS app stops opting out of Flutter's Swift Package Manager integration. The 19 iOS plugins that ship a Swift package are now linked through it. The three that don't (`google_mlkit_commons`, `google_mlkit_selfie_segmentation` and `open_filex`) keep installing through CocoaPods, which Flutter supports side by side. Why now: - CocoaPods is winding down: its spec repo [becomes read-only on December 2, 2026](https://blog.cocoapods.org/CocoaPods-Specs-Repo/), and plugin releases have started to ship as Swift packages only. Staying opted out pins those plugins at their last CocoaPods release. - The opt-out dates from the Flutter 3.47 upgrade (#8419), which kept the existing CocoaPods integration. With it removed, the app builds and runs as before. What is in the diff: - `pubspec.yaml`: the opt-out is removed. - `project.pbxproj` and `Runner.xcscheme`: the edits Flutter's own tool makes on the first build with the integration on (a local reference to its generated plugin package, and a scheme pre-action that prepares the Flutter framework). They are committed so a build does not dirty the tree. - `Podfile.lock`: only the three CocoaPods plugins and their dependencies remain. No Dart code, plugin version or remote Swift package changes. All 19 packages resolve to local paths in the pub cache, so `Package.resolved` is untouched and builds fetch nothing new. ### Related issue N/A. No existing issue or PR for this was found. ### Regressions - **App behavior:** the same plugin code at the same versions. The 19 plugins are linked statically into the app binary instead of embedded as dynamic frameworks, which leaves fewer libraries to load at launch and a slightly smaller app (numbers below). One resource bundle is lost; see the second accepted tradeoff. - **Extensions:** the notification service extension links no plugins, so it is unchanged. - **Build and release:** CocoaPods is still required for the three remaining plugins, so the Podfile, its post-install steps and the release tooling are unchanged. The first build after this change spends about 17 extra seconds adding the integration. - **Accepted tradeoff, build warning:** Flutter now prints a warning naming the three plugins without Swift packages. It goes away when those plugins add support or are replaced. - **Accepted tradeoff, one privacy manifest dropped:** the app no longer bundles `app_badge_plus`'s privacy manifest, and Xcode prints `Invalid Resource 'Resources': File not found` for it. Version 1.2.10's Swift package looks for `Resources` under its source directory, but the manifest sits at the package root, so the Swift package bundles nothing where the podspec bundled it. This is harmless: that manifest declares only UserDefaults access, and the plugin's single source file never touches UserDefaults. The other 16 plugin privacy manifests are still in the release app. Fixing it means a plugin bump, which is left out of this PR. - **Android:** unaffected. ### Validation Unsigned release build, this branch against unmodified `main`: | | `main` | This branch | | --- | --- | --- | | App size | 87.0 MB | 85.6 MB | | Embedded frameworks | 31 | 12 | Focused existing validation: the three iOS steps CI runs (simulator debug build, the 116 native `RunnerTests`, and the unsigned release build) pass locally. Full-app run on an iOS 27 simulator (iPhone 17 Pro), driven by an agent, with the debug build from this branch installed over an existing signed-in install: - The app stayed signed in and loaded its channel list and message history (keychain, preferences and local storage plugins). - Photo library picker, attaching a photo, and sending a video, which uploaded and played back. - Image viewer, the share sheet, and saving an image to Photos. - The file picker, and the camera and microphone permission prompts. - A link in a message opened in the browser, and a `buzz://` deep link reached the app. Two failures showed up and both reproduce identically on unmodified `main` on the same simulator, so neither comes from this change: a recorded voice note is empty because the host Mac has no microphone, and saving an image adds it to Photos but then reports "Could not save image". Limits: no physical device run. Camera capture, QR scanning, selfie segmentation and biometric prompts cannot be exercised on a simulator. Voice note playback was not exercised. Human testing is waived for this PR under the author's standing policy for mobile changes; the agent-driven run above stands in for it. Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: judge <7615ec4b7ddf99f0bb48e913297f99f8f772d289a1c9ef54e1d906dd55a93ba8@buzz.block.builderlab.xyz> |
||
|
|
6b4a398829 |
feat(push-gateway): enroll Android installations and send FCM wakes (#9560)
## What and why Ticket 2 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now enrolls Android installations and wakes them through FCM, next to the existing iOS path. Builds on [#9557](https://github.com/block/buzz/pull/9557) (platform-neutral `/v1/deliveries` route), now merged. - **Platform.** The enrollment request has no platform field. The gateway derives it from which attestation is present (App Attest object or Android attestation chain) and records it in a new `push_gateway_installations.platform` column (`ios` or `android`). It lives only in gateway state; the relay never sees it. - **Android enrollment transcript.** Key Attestation fixes the challenge at key generation, so the client signs nothing at enrollment and sends no `key_id`. The attestation challenge must equal SHA-256 of a canonical JSON transcript under domain `buzz.push.enroll.android.v1` with `v`, `audience`, `challenge_id`, `challenge`, `endpoint`, `endpoint_epoch` and `expires_at`. The gateway derives the key id as SHA-256 of the attested 65-byte uncompressed P-256 key. A request whose `key_id` presence doesn't match its platform gets 400. The iOS transcript (`buzz.push.enroll.v1`) is unchanged. - **Signed calls.** iOS keeps App Attest assertions. After enrollment, an Android installation signs every call (delegate, revoke delegation, rotate endpoint, revoke installation) with its attested Keystore key: ECDSA P-256, DER, over the same transcript bytes iOS signs. High-S signatures are accepted since Keystore does not normalize. There is no counter; the single-use challenge inside the transcript is the replay protection. - **FCM sender.** HTTP v1, high priority, data-only, compiled-in payload (no relay-supplied bytes), one constant collapse key, TTL from the delivery expiry. OAuth access tokens come from the service account key (RS256 JWT bearer). Outcomes map onto the existing delivery outcome classes and metrics (`push_gateway_fcm_*`). - **Token refresh.** A cached token keeps serving until it expires. Once it is due for refresh, one background task fetches a new one, so a wake never waits on a refresh while a valid token exists. A failed fetch keeps the current token and backs off 5 s before the next attempt. Only a cold cache (no unexpired token) makes a wake wait on the token request, single-flighted. A 401 discards the cached token only if it is still the one FCM refused, so a late 401 can't drop a newer token. - **Retries.** 429 and `QUOTA_EXCEEDED` retry after at least 60 s (FCM's hint if longer). 500, 502, 503 and 504 retry. - **Attestation seam.** Android Key Attestation verification sits behind a trait. Tests use a test-only verifier compiled under `cfg(test)`, so production configuration cannot select it. The production verifier fails closed: a gateway configured for Android starts but rejects every Android enrollment until ticket 3. - **Migration.** Expand-only `ADD COLUMN platform TEXT NOT NULL DEFAULT 'ios' CHECK (...)`: the deployed gateway's inserts stay valid and existing rows become iOS. `SET LOCAL lock_timeout` (5 s) and `statement_timeout` (30 s) bound the table lock wait and the CHECK validation scan. No triggers, functions, foreign keys or backfills. Mirrored as gateway `0007` and relay `0093` plus `schema/tables/public`, per docs/database.md. ## Configuration All four are optional and must be supplied together (a partial set fails startup). Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only. - `BUZZ_PUSH_ANDROID_PACKAGE_NAME` - `BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS` - `BUZZ_PUSH_FCM_PROJECT_ID` - `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH` ## Tests - `cargo test -p buzz-push-gateway` (92 passed, 18 ignored; 94 passed with `personal-dev-app-attest`; iOS rows unchanged), `cargo fmt --check`, `cargo clippy -p buzz-push-gateway -p buzz-db --all-targets -- -D warnings`. - New HTTP tests with a fake FCM sender: Android enroll, delegate, deliver, rotate endpoint and revoke; signed-call rows for wrong key, altered transcript and reused challenge; platform derivation and bad attestations. - Postgres (ignored, run locally): gateway migration test (existing and old-gateway inserts become `ios`, bad value rejected); relay `admin_schema_parity_between_desired_state_and_migrations` now covers `push_gateway_installations` columns, indexes and constraints; the `runtime::migration::postgres_tests` set passes single-threaded. - Break check: making signature verification always succeed turned two tests red (the signed-call rejection rows and the signature unit test); restored. - Token cache tests against a local fake token endpoint with a controlled clock: a due refresh keeps serving the valid token even when it fails; a late 401 does not discard a refreshed token; a queued background refresh honors a foreground failure's backoff. The FCM response table covers 429 with and without an error body, and 502/504 HTML pages. - Android enrollment rows: `key_id` present on Android (400), wrong transcript binding, a 65-byte non-point key, an over-long chain, and exact replay. - Break checks for every new guard (no background refresh, blocking while due, failure dropping the token, unconditional 401 clear, no quota floor, no 502/504 retry, the queued-refresh backoff check, Android requiring `key_id`, skipping the P-256 point check): each turned at least one test red; restored. ## Not here (ticket 3) Real Key Attestation verification (Google roots, revocation list, boot state, boot-key list, app identity). Per-key rate limiting is also left for ticket 3, since it did not fall out of this change. The Helm chart does not pass the Android settings yet. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
ff652ed06c |
perf(mobile): cache and animate custom emoji in the iOS picker (#9479)
The iOS emoji picker's custom emoji downloaded again every time the
picker opened, and animated emoji showed only their first frame.
Now each custom emoji downloads once per install and plays its
animation:
- The native picker gets image bytes from Flutter through the same path
as the rest of the app's images: the in-memory custom emoji cache, then
the persistent media disk cache, then one download through the shared
media HTTP client. Relay media is cached as immutable.
- Swift decodes every frame (no Swift-side cache) and shows the image in
a `UIImageView`, since SwiftUI `Image` draws only the first frame of an
animated `UIImage`. With Reduce Motion on, it shows the first frame,
following the setting live.
- At most four picker downloads run at once, and an emoji scrolled off
screen before its turn never starts. Emoji already saved on disk skip
the queue, so reopening a large set stays instant.
- A picker load joins any download of the same image already in flight
elsewhere in the app. A saved copy that fails to decode is evicted and
downloaded again, and only bytes that decoded are kept in memory.
- Swift decodes at most four emoji at once, including ones from cached
bytes. An emoji whose cell scrolls away gives up its place and stops
decoding between frames, and a cell that leaves the screen keeps only
its first frame.
- Each animation frame keeps its own delay. UIKit spaces animated frames
evenly, so a frame repeats for its share of the loop, and a GIF that
holds its last frame for 3 s still does.
### Why it refetched
The native picker loaded images itself with `URLSession.shared` and an
`NSCache` keyed on the whole request. Every request carried a freshly
signed media auth header, so the key never matched and nothing was
cached on disk.
### Validation
Relay media downloads for the 48 custom emoji matching "nod" (local
relay, iPhone 17 Pro simulator):
| Step | main | this PR |
| --- | --- | --- |
| First open | 48 | 48 |
| Leave and re-enter the channel, reopen | 48 | 0 |
| Relaunch the app, reopen | 48 | 0 |
| Reinstall the app, reopen | not measured | 0 |
Before (main): every reopen downloads again, and animated emoji are
still.
https://github.com/user-attachments/assets/7a43dd6a-61e0-495d-abed-6c11f7d4f965
After (this PR): reopening shows cached emoji immediately, and animated
emoji play.
https://github.com/user-attachments/assets/bf45a5c0-77ef-4501-8843-6f42e15de389
Automated app run: signed in to a local relay, opened a channel,
long-pressed a message, opened the full picker, searched, closed, left
and re-entered the channel, reopened, relaunched and reopened. Repeated
on the final head (
|
||
|
|
1059d81fc2 |
fix(ios): end each bold or strikethrough run at its first closing marker (#9559)
Bold and strikethrough runs in iOS push notification bodies now end at their first closing marker, so a message with two bold runs on one line shows both without their markers. Before, the run's optional group was greedy and stretched to the last marker on the line: | Message | Before | After | | --- | --- | --- | | `option **A** or option **B**` | `option A** or option **B` | `option A or option B` | | `~~x~~ and ~~y~~` | `x~~ and ~~y` | `x and y` | | `**😀** and **b**` | `😀** and **b` | `😀 and b` | The fix makes that group lazy (`(?:.*?\S)??`). Found while reviewing the Dart port in [#9556 Dart notification body](https://github.com/block/buzz/pull/9556), which must match these fixtures. That PR takes the same pattern once this one lands. ### Validation - Added tests: three shared rows in `test-fixtures/notification-body.json`, one per row above. All three fail with the old pattern. - All 70 BuzzPushKit tests pass on macOS, including the other 36 fixture rows, which are unchanged. ### Regressions None expected. The pattern still needs non-space characters right inside both markers and still stays on one line. It now stops at the first closing marker where before it reached for the last one. The output changes only where a one-character run is followed by the same marker later on the line, for example `**a** costs 2**3`, which was `a** costs 23` and is now `a costs 2**3`. Worst-case time for unclosed markers is unchanged (measured during review of the Dart port). Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
50cfc54337 |
Apply the private-to-open rule in update_channel too (#9581)
## Summary - Follow-up to https://github.com/block/buzz/pull/9307, which made the relay refuse to open a private channel that has, or once had, any member other than the sender and the sender's own agents. That rule lived only in the channel metadata edit path (kind:9002). The store's other channel-settings function, `update_channel`, could still open such a channel. - Now both paths apply the same rule, because it runs in the one function that writes channel settings for both. `update_channel` takes the authenticated sender so it can decide the rule. Today only tests call `update_channel`, so nothing user-visible changes; the gap is closed before any real caller arrives. - The user-deletion executor doc now says what the rule needs from a purge: if a purge keeps any of a user's messages in a channel, it must also keep that user's membership row there, marked removed. The relay finds former members only through those rows, so dropping the row would let the channel be opened and its history, those messages included, be made public. ## Details - The check moved out of `apply_channel_metadata_event` into `update_channel_on`, which both paths call. It still runs under the membership lock that a visibility change takes, so members cannot be added between the check and the commit. - One ordering change: a single kind:9002 that opens a private channel with other members, archives it and sets `auto_join` to true now gets the `auto_join` refusal instead of the private-to-open one, because the `auto_join` check now runs first. Both refuse, and nothing is stored either way. - This PR also carries doc-comment wording that was reviewed on https://github.com/block/buzz/pull/9307 but not merged with it: the comments now give the reason, that opening publishes the existing history, so removed members count. - Every call site of `update_channel` is a test, and each now passes the channel owner as sender. ### Related issue Follow-up to https://github.com/block/buzz/pull/9307 (review notes on its store gap and on purge). ### Testing - New Postgres test `update_channel_refuses_opening_a_private_channel_with_other_members`: opening fails for both the owner and the other member as sender, while the other member is current and after they are removed, and the channel stays private. A channel that holds only the owner opens. - The existing kind:9002 test `private_to_open_needs_no_other_members` still passes. Both tests fail when the check is removed. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |