Commit Graph

2841 Commits

Author SHA1 Message Date
Tom Brow
f260ad7f95 fix(ios): use the shared glass capsule for thread titles (#8150)
The iOS thread header currently renders an unbacked “Thread” label over
scrolling messages. Supply the channel display name as its subtitle so
the header uses the same two-line glass capsule as channel
conversations. The title remains noninteractive and inherits the shared
sizing, truncation, text scaling, and accessibility behavior.

Channel and DM display names update with channel metadata; missing
metadata keeps the capsule without inventing a subtitle. App-bar
construction moves into a sibling file to keep the thread page within
the file-size limit.

### Validation

- [CI run](https://github.com/block/buzz/actions/runs/37654016581):
mobile tests, native iOS build, and all other executed jobs passed. The
overall workflow reports a GitHub internal server error; GitHub rejected
a retry. Required checks passed or were skipped.
- [Codex
review](https://github.com/block/buzz/pull/8150#issuecomment-6042500880)
completed without major findings on the current head.

- Mobile dependency setup, formatting, file-size checks, and analysis
passed.
- Full mobile suite: 3,039 tests passed, four skipped; all three
unconfigured-push tests passed.
- Widget regressions exercise real thread-page native parameters for
channel/DM labels, renames, missing metadata, and disabled title
interaction.
- Native iOS 26.5 simulator check confirms the shared capsule renders
“Thread” above “engineering,” with a single noninteractive accessibility
header. Before/after captures use synthetic content.

[Before/after simulator
captures](https://github.com/block/buzz/pull/8150#issuecomment-6042451532)

### Post-merge validation

During the mobile release baking period, open threads in channels and
DMs on a device, including long channel names and larger text settings;
verify the bubble stays clear of Back and has no tap action.

Human app-test confirmation is not applicable under the standing Buzz
mobile exception.

buzz-review-completed

Signed-off-by: Tom Brow <tomb@block.xyz>
2026-10-07 20:05:03 +00:00
Luke Tornquist
6d07a29137 perf(relay): bound fleet usage metrics collection (#7176)
## Why

The usage poller pays memory and query costs proportional to community
count even when per-community emission is disabled. Every pod loads the
full host map, and the leader materializes all per-community aggregates
before suppressing their labels. That makes telemetry collection itself
a scaling constraint.

## What changed

- Fleet-only usage metrics are now the default. `all` remains available
as an explicit rollback mode.
- In fleet-only mode, the poller skips the community host map and all
community-sized query results.
- Exact community counting is replaced with the PostgreSQL planner's
table-size estimate.
- Stock totals are collected as one fixed row, scanning each stock table
once per hour.
- 1d/7d/30d active-user totals come from one bounded 30-day scan per
day.
- Fleet database snapshots run only on a proved read replica, with a
telemetry-specific freshness budget and server-side statement timeouts.
If no such replica is available, the collection is skipped; it never
falls back to the writer.
- Successful fixed-row snapshots are cached and re-emitted on each poll
tick, so gauges stay scrape-visible without raising query frequency.
- `buzz_usage_snapshot_available{family}` reports whether the latest due
refresh of that family succeeded. After a skipped or failed refresh, the
last values stay visible (with `buzz_usage_snapshot_age_seconds`) but
the family reads unavailable until a 60-second retry succeeds.
- The `all` rollback collector publishes the same availability gauges,
so dashboards gated on availability keep working during a rollback.
- Each due refresh outcome is applied by `apply_stock_refresh` /
`apply_activity_refresh`, the single production mapping from `Ok(Some)`
/ `Ok(None)` / `Err` to cache, availability, skip counter, and retry;
the regression test drives that mapping directly.
- `buzz_usage_snapshot_age_seconds` is emitted in the `all` rollback
too, so age-based alerts keep firing through a rollback.
- Every fleet telemetry attempt that completes lands in
`buzz_db_route_decision`; a query error on a proved reader records
`skipped/replica_error`. An attempt abandoned at the relay deadline
records no route decision and appears only as
`buzz_usage_query_skipped_total{reason="timeout"}`. The shared
`proved_reader` warnings no longer claim "routing to writer", because
the telemetry caller never does (serving callers still record their
writer decision in the route counter).
- The PostgreSQL production-method matrix now exercises
`usage_fleet_stock_snapshot`, so the new `reader/maintenance` pool pair
is proven to be emitted by a real Db method.
- Each fleet collection, reader proof included, runs under a relay-side
`tokio::time::timeout` (10s stock, 20s activity, both above their
server-side `statement_timeout`). A reader that stops answering expires
into the same failure mapping with
`buzz_usage_query_skipped_total{reason="timeout"}`, so it cannot stall
the leader's poller, hold the advisory lock past a liveness check, or
leave a frozen snapshot reporting available.
- Fleet telemetry reader checkouts (`ReaderOperation::Maintenance`) opt
into SQLx `close_on_drop` before their first post-acquire await, so an
abandoned collection's connection is closed within SQLx's 5s
`CLOSE_ON_DROP_TIMEOUT` instead of going through the unbounded
return-to-pool ping while it holds a slot in the reader pool that
serving reads share. Serving reads keep pooled reuse; the cost is one
reader reconnect per fleet refresh.
- On leader demotion, cached snapshots and availability are cleared, and
a fresh collection is forced after the lock is reacquired.
- Fleet-only mode passes no host map to the worker-snapshot storage
emitter. It therefore omits community attribution instead of reporting
every byte as `buzz_storage_unmapped_community_bytes`.
- Lifetime stored-message and active-channel totals are no longer
queried in fleet-only mode. Event throughput remains available through
the existing stored-event counter.
- No test-selector changes: main's `config::tests::` selector in `just
test-unit` and the `run-tests.sh unit` fallback already runs the new
replica-budget config test, and the new fleet schedule, availability,
and storage tests run through the existing bin `tests::` and
`storage_sweep::tests::` selectors.
- Added seeded PostgreSQL contract tests and operator docs covering
rollout, rollback, availability, the no-replica behavior, and leader
election.

No migrations, tables, indexes, or new persistent storage are added.

### What got simpler

The relay-side storage half of the original branch (totals-only S3
listing and `buzz_storage_community_breakdown_available`) was dropped.
Main moved S3 listing out of the relay in #7543 and #7845, so that code
was dead on arrival. The rework adds no storage code path; it only gates
attribution on the presence of a host map.

## Risk

Medium. The default changes which telemetry is emitted:

- In fleet-only mode, `buzz_communities_estimated` replaces the exact
`buzz_communities_total`.
- `buzz_total_messages` and `buzz_total_active_channels` are not
refreshed in fleet-only mode (also called out in the rollout steps of
`docs/usage-metrics.md`).
- Deployments without a verified reader (including local compose and
single-node self-hosts) skip database-derived fleet snapshots instead of
querying the writer, and report both families unavailable.
- Multi-pod dashboards must filter database and storage series to
`buzz_usage_poller_is_leader == 1`.

Setting `BUZZ_USAGE_METRICS_PER_COMMUNITY=all` restores the legacy
collector for temporary rollback.

## Verification

At head `1879ee3aedf4227942120a3b521c8d35fc7839fe` (tree `78477e74`;
merges main `da651ad6`; the PR's diff against main is byte-identical to
`1613823f`'s, minus the Justfile and `run-tests.sh` selector lines that
main's `config::tests::` selector now subsumes):

- On Blox: `cargo fmt --all -- --check` and `cargo clippy -p buzz-db -p
buzz-relay --all-targets -- -D warnings` pass. Relay bin `tests::`
34/34, `config::tests::` 55/55, `storage_sweep::tests::` 10/10 and
`store::usage::tests` pass, as do the four `fleet_` and lock PostgreSQL
tests that use scratch databases, including
`abandoned_fleet_collection_releases_its_reader_slot`.
- Against a freshly migrated PostgreSQL database:
`store::usage::postgres_tests::` 14/14,
`storage_sweep::postgres_tests::` and `buzz-db --test
observability_source` 14/14 pass. The new reader code passes main's
crate-wide typed-acquisition and serving-table policy checks.
- E2E at `1613823f` is reused for this head. It ran in an isolated relay
against a real PostgreSQL primary and streaming standby. In 2/2 runs a
stock read went dark mid-result; the deadline abandoned it at about 10s,
the reader pool's active and size counts dropped to zero about 1s later,
and a fresh activity read and the scheduled stock retry succeeded on new
backends while the dark session stayed open. The `all`-mode and
healthy-replica controls also passed. Main's merged changes are on the
writer path and in startup step timing, and touch none of the reader
checkout, the `close_on_drop` seam, the fleet poller or the deadlines.

At head `1613823fa8ef1a423bc1a499c57bc40d692fcd4f` (tree `12bc6d1b`;
test/docs-only on top of `57749418`), on a Blox workstation:

- `cargo fmt --all -- --check` and `cargo clippy -p buzz-db -p
buzz-relay --all-targets -- -D warnings` pass. Relay bin `tests::` 34/34
pass.
- New PostgreSQL test
`abandoned_fleet_collection_releases_its_reader_slot`: a one-slot reader
pool behind a loopback proxy that goes dark mid-session; the collection
is cut at a deadline, then a later acquire must succeed in under 8s on a
fresh connection. The dark call runs on a fresh `Db` with a cold Aurora
capability cache, so the first post-acquire await is the capability
probe. It passes in 3.4s. With `close_on_drop` removed, or moved below
the probe await, it fails with `PoolTimedOut` after the 15s acquire
timeout. The other three `fleet_` PostgreSQL tests that use scratch
databases pass.
- `each_fleet_family_is_abandoned_at_its_own_deadline` now has an outer
timeout: replacing the stock deadline with a bare `.await` fails it
(`Elapsed`) instead of hanging.

At head `fd194ec79d6c6796d6764564de225ad56485cfc7` (tree `79e94727`,
main merged at `932228936`), on a Blox workstation:

- `cargo fmt --all -- --check` and `cargo clippy -p buzz-relay -p
buzz-db --all-targets -- -D warnings` pass.
- Relay bin `tests::` nextest selection: 27/27 pass (plus
`store::usage::tests`), including
`fleet_refresh_outcomes_drive_availability_through_production_mapping`
and the new `stalled_fleet_collection_times_out_into_failed_refresh`
(paused time: two never-completing collections are abandoned at exactly
10s + 20s; both families read unavailable with cached values kept,
`reason="timeout"` skips, retry scheduled; the next tick runs and
recovers; no route decision is recorded for an abandoned attempt) and
`each_fleet_family_is_abandoned_at_its_own_deadline`. Compile-time
asserts keep each deadline above its `statement_timeout`.
- Falsifiability: replacing the stock deadline with a bare `.await`
makes the new test fail (the tick stalls); swapping the two deadlines
fails the per-family test; deleting `schedule.mark_stock_failure(now)`
from the `Ok(None)` arm fails the mapping test. Trees restored and
re-verified.
- At `970414db`: CI PostgreSQL Tests 809/809 including the
production-method matrix with `reader/maintenance`; Unit Tests ran
`finish_usage_read_records_every_attempt_in_route_decisions`.
- `just ci` / `just test` at `5b18914a` on Blox: not green for
environmental reasons (`mobile-check` could not reach pub.dev;
`_ensure-services` failed so service-backed suites did not run;
`buzz-acp git_bootstrap` fails identically on `origin/main`). PostgreSQL
and integration coverage comes from GitHub CI at this head.

E2E at the previous head `0a01e5f22` (isolated relay, real Postgres
primary plus streaming replica, worker storage snapshot, desktop
frontend in relay mode): with no reader, both families report
skipped/unavailable and route `skipped/disabled` (no writer queries);
fleet-only storage emits totals without `buzz_community_storage_*` or
unmapped bytes; `all` mode reports both availability gauges `1` with
per-community storage series; with a fresh replica, both fleet paths
route `replica/fresh` on `reader/maintenance` acquisitions; desktop
send/receive works. The cached success → due failure → recovery
transition was not reached live (hourly/daily cadence); it is covered by
the seam test above.

The original branch also recorded live verification at `aa3e7023`,
before this rework: reduced-idle cache re-emission, two-relay leader
takeover with demoted availability clearing, the no-reader skip with
60-second retry, `all` rollback restoring per-community series, and a
desktop smoke test. Those runs predate the availability and storage
changes and are not claimed for this head.

## Linear tracking

Related work: BUZZ-167.

---------

Signed-off-by: tornquist <tornquist@squareup.com>
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
2026-10-07 15:46:18 -04:00
Tom Brow
c96d707f6e fix(ios): let channel titles use available navigation space (#8137)
Channel titles could truncate while space remained between the
navigation buttons. The title was sized before inheriting its displayed
fonts, and longer names also hit a fixed 240-point cap.

Use Auto Layout and stack views for the title, subtitle, avatar, and
presence indicator. UIKit now updates the layout when fonts change
without resetting the title frame. The navigation bar constrains the
bubble between its buttons; short names remain compact and long names
use the available space before truncating.

[Before/after simulator
captures](https://github.com/block/buzz/pull/8137#issuecomment-6041101824)

### Validation

- All 97 native iOS tests passed on an iPhone 17 Pro running iOS 26.5.
Coverage includes inherited text size, increasing and decreasing text
size, 320/393/600-point widths, right-to-left avatar placement, presence
indicators, and title accessibility/taps.
- Exercised the production native header in the simulator and captured
the full channel name with its member count after the refactor. No
relay/community connection was needed.
- [CI passed for the Auto Layout
refactor](https://github.com/block/buzz/actions/runs/37644234496),
including mobile tests, Android debug, iOS simulator, native pagination
accessibility, and unsigned iOS release builds. Mobile push checks also
passed.
- The earlier broad local gate hit ACP deadline and desktop subprocess
timing failures; all failed tests passed on retry, including the
complete serialized ACP suite. Remaining checks and builds passed.
- Agent review completed. Human app-test confirmation is not applicable
under the author's standing Buzz mobile exception.

### Post-merge validation

During the mobile release baking period, exercise long channel names at
default and larger text sizes on narrow and wide screens; verify Back,
Huddle, and title taps remain accessible and do not overlap.

buzz-review-completed

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
2026-10-07 09:24:39 -07:00
Luke Tornquist
da651ad672 buzz-db: purge retention-free deletions in the app and index mentions in the event transaction (#8128)
## Summary

Part 1a of removing database objects that exist only in migrations. This
PR moves into the app the work two migration-only triggers do today. It
doesn't drop anything.

On migration-built databases (production), `purge_soft_deleted_nip_rs`
(0009/0011) and `purge_soft_deleted_buzz_mesh_status` (0019) turn a
NIP-09 soft delete of a NIP-RS read-state event (kind 30078) or a
mesh-status heartbeat (kind 30003) into a hard delete, and delete its
mentions. `schema/schema.sql` has neither trigger, so on desired-state
databases (CI) those rows remain as soft-deleted. The two schemas behave
differently today.

Changes:
- `soft_delete_by_coordinate` and
`soft_delete_event_and_update_thread_in_tx` now hard-delete matching
NIP-RS and mesh-status rows and their `event_mentions` rows in the same
transaction, before the generic soft delete. The classification
predicate is the same one the 0011 and 0019 triggers use.
- `insert_event_with_serving_write_guard` now indexes mentions inside
the event transaction, under a savepoint, instead of after commit. A
mention failure still only logs a warning. A concurrent deletion can no
longer leave a mention row behind, and `guard_event_mention_live` will
no longer be needed. The other post-commit `insert_mentions` callers
write kinds 48101 and 13534 and a test helper, never 30078.
- Both soft-delete `UPDATE`s exclude the same predicate (`AND NOT
COALESCE(..., false)`). A retention-free row is either purged or left
live, never soft-deleted, even when a replacement races the deletion
under READ COMMITTED. The purge runs only for kinds 30078 and 30003.
- While the 0011 hard-delete fence is still installed, the purge sets
the transaction-local `buzz.nip_rs_hard_delete` opt-in. 1b removes it,
along with the fence.

**Rollout:** the triggers stay in place on purpose. Pods still running
N-1 during a deploy depend on them. A follow-up (1b) will add a
migration that drops the 5 functions and 5 triggers, remove the
`buzz.nip_rs_hard_delete` opt-in code, and add the catalog-parity test.
1b should merge only after this PR is deployed everywhere.

**What got simpler:** once 1b lands, NIP-RS and mesh deletion will
follow one rule owned by the app, the same on both schemas, and the
hidden trigger work will be gone. This PR adds about 130 lines to
`event.rs`. A known gap for 1b: the replace path's Rust mesh classifier
is stricter than the SQL predicate, and 1b has to make one of them
authoritative before the triggers are dropped. 1b will then delete 5
triggers and 5 functions, plus the opt-in plumbing in `replaceable.rs`
and `deletion.rs`.

### Related issue

BUZZ-175, BUZZ-177 (Linear).

### Testing

Blox, head `a2dac90646ca64fb3f961ffda292e3da976deffc`:
- `cargo fmt --check`, `clippy -D warnings` (`buzz-db`, `buzz-relay`),
and test discovery: all pass.
- New tests: 4 of 4 pass.
- `nip09_deletion_purges_retention_free_rows_and_mentions`,
desired-state and `migration_schema_` variants. On the migration schema,
a 13-shape table checks that the app and the triggers classify each
shape the same way. A separate case covers a mesh row with a NULL
`d_tag`.
-
`coordinate_deletion_racing_nip_rs_replacement_never_soft_deletes_read_state`,
a deterministic lock interleaving.
- `serving_write_guard_insert_indexes_mentions_in_event_transaction`:
mentions are indexed in the event's own transaction (checked via
`xmin`), and a mention failure leaves the event live.
- Falsification: the race test fails against the pre-fix `event.rs`. The
mention test fails with the merge-base post-commit `runtime/mod.rs`.
Both NULL-`d_tag` variants fail with `COALESCE` removed.
- `buzz-db` PostgreSQL lane (`scripts/postgres-test-run.sh -p buzz-db
--lib --tests`): **409 of 409 passed** in an unscoped run. One box hangs
on `writer_pool_rejects_non_read_committed_database_default` (an
environment issue; it also hangs there at merge-base), and there 408 of
408 others passed.
- E2E against a real relay on both schemas: 18 of 18 signed deletion
cases, the serving-write mention path (success, pre-commit invisibility,
isolated failure, recovery), and browser mention, send, reload and
delete.
- CI at `a2dac906`: all checks pass. The `PostgreSQL Tests` lane needed
one rerun: the first attempt hit a known flaky test,
`replica_fence::sample_writer_waits_for_shared_floor_lock_before_sampling_time`,
which fails the same way on `main` at `001290a34`.

buzz-review-completed (agent review and agent E2E complete; human test
waived by Luke Tornquist)

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
2026-10-07 10:26:39 -04:00
Luke Tornquist
e097c42996 feat(relay): time post-metrics-bind startup steps (#8132)
## Summary

Relay pods on large deployments can take over 5 minutes to open their
health port, and right now nothing shows which startup step is slow.
Startup timing ends at `metrics_bind`, and the slow work all happens
after it.

This PR times every startup step from Postgres connect through public
listener bind. It does not change startup behavior.

- Each step logs `Startup phase started` and `Startup phase finished`,
with `phase`, `elapsed_ms`, and `status` (`succeeded` / `degraded` /
`failed`, the same values `buzz_process_lifecycle` records use).
- Gauge `buzz_startup_phase_current{phase}` is `1` while a step runs and
`0` after it ends. A pod that is still starting shows exactly which step
it is on.
- Gauge `buzz_startup_phase_seconds{phase}` records each finished step's
duration.
- The startup NIP-43 membership reconcile logs `NIP-43 startup
reconciliation progress` every 5,000 communities, with `done`, `total`,
`republished`, `failed`, and `elapsed_ms`.

These are gauges rather than counters on purpose. Each value is written
once per boot, and a monotonic-counter scrape drops a series' first
sample, so a one-shot counter never shows up.

## Contract change

`deploy/charts/buzz/README.md` ("Early-startup telemetry contract") said
the early lifecycle phases are log-only. That still holds: `crypto_init`
through `metrics_bind` are unchanged and emit no metrics.

The README now also documents the post-bind steps. The guard in
`boot_lifecycle.rs` now allows exactly the two `buzz_startup_phase_*`
families. It still rejects any other startup, boot, or lifecycle family,
and it also rejects any exported label value that names an early phase.

## Design

- `crates/buzz-relay/src/startup_steps.rs` adds a closed `StartupStep`
vocabulary (18 steps) and a `StepTimer` guard.
- A step ends exactly once:
  - `finish()` → `succeeded`
  - `degrade()` then `finish()` → `degraded` (a non-fatal error branch)
- dropped without finishing → `failed` (covers `?` early returns and
panics)
- The NIP-43 and large-roster reconciles now return `ReconcileSummary {
repaired, failed }`. A sweep where any item fails ends its step
`degraded`, and the final log line includes the `failed` count. NIP-FI
warm ends `degraded` when any issuer did not warm. The deprecated
`reconcile_nip43_membership_snapshots` wrapper still returns `repaired`.
- Steps that are disabled by config (migrate, audit connect, NIP-FI
warm, git probe, NIP-43 reconcile) are not timed, so their series never
appear.
- The gauges are set once, so they age out after the existing gauge idle
timeout (2700 s with default intervals; logged as `idle_timeout_secs`).
A step that runs longer than that loses its `_current` series. The
README says so.
- Progress logging runs only for the `Bootstrap` reconcile. The 60 s
maintenance sweep stays quiet.

## What got simpler

Little got simpler in the code: this mostly adds instrumentation. One CI
gap closed along the way: the 54 `config` tests and the 9 non-ignored
`boot_lifecycle` tests, which ran in no CI lane, now run in `test-unit`.
The instrumentation is scoped as small as I could make it, and it is the
evidence needed for the follow-up that should delete code: moving the
per-community NIP-43 reconcile off the pre-bind path, after which the
900 s startup-probe override can go back to the chart default.

## Testing

- `startup_steps` unit tests (`DebuggingRecorder`):
  - a running step is current and has no duration
  - a finished step clears current and records its elapsed time
  - dropped and degraded steps clear current and record a duration
- log capture: `finish`, `degrade`+`finish`, drop, and panic each emit
exactly one `Startup phase finished` record with the right `status`.
Mutating `degrade()` to a no-op and removing the ends-once guard makes
these tests fail.
- the vocabulary is unique and shares no names with the early lifecycle
phases
- Tests that capture logs or check callsite interest now share
`test_support::tracing_dispatch_lock()`. These are the `startup_steps`
helpers, two `telemetry` tests, and the `config` and `bridge`
log-capture helpers. tracing-core caches each callsite's interest across
the whole process. Without the lock, the new panic test lost its record
in 60 of 150 parallel runs of `telemetry:: startup_steps:: config::`.
With the lock it failed 0 of 300. Removing the lock from `gauges()`
brings the failures back (53 of 100 runs).
- `nip43_progress_logs_every_interval_inside_the_startup_sweep_only`
checks the cadence at 79,942 communities (15 progress lines, none at the
start or end) and table-tests that the maintenance sweep never logs
progress.
-
`boot_lifecycle::successful_main_emits_complete_lifecycle_and_reports_current_startup_step`
boots the real relay binary against a TCP peer that never speaks
Postgres. It asserts that `/metrics` shows
`buzz_startup_phase_current{phase="db_connect"} 1` and no finished-step
durations, and that no early phase leaks into metrics.

- **CI routing.** `just test-unit` picks relay tests by hand-maintained
filter. Before this PR, CI's filters selected none of the
`startup_steps`, `telemetry`, `config` or non-ignored `boot_lifecycle`
tests above; the NIP-43 cadence test is picked up by the existing
`handlers::side_effects::tests::` clause. Its infra-free relay stanza
now selects `startup_steps::tests::`, `telemetry::tests::` and
`config::tests::` (anchored so `nip_fi_config` is not selected twice),
and a new `cargo nextest run -p buzz-relay --test boot_lifecycle` line
runs the non-ignored `boot_lifecycle` tests (they spawn the real binary
and need no Postgres or Redis; the Postgres cases stay `#[ignore]`d).
`scripts/run-tests.sh` mirrors both, running `telemetry` and `config`
single-threaded because they mutate process env.

### Manual check

1. `just relay` (or run `buzz-relay` against local Postgres and Redis).
2. Once the relay is up: `curl -s localhost:9102/metrics | grep
buzz_startup_phase`. Every step that ran has a `_seconds` value, and
every `_current` value is 0.
3. In the relay logs, `"Startup phase finished"` lines show each step's
`elapsed_ms`.

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
2026-10-07 10:15:43 -04:00
Tom Brow
bd1ff00e48 release: push gateway chart 0.3.5 (#8141)
Publish gateway chart 0.3.5 through the normal immutable release
workflow. This release includes Deployment metadata annotations from
[#8136](https://github.com/block/buzz/pull/8136), while preserving
chart-owned policy markers and existing default manifests.

Only the chart version and release notes change. The gateway binary
appVersion remains 0.1.0.

### Validation

Full gateway chart render suite and release-contract validation passed.
The feature's full repository validation and exact-head owner review
passed before merge. Publication will be verified from the OCI registry
before advancing the wrapper dependency.

`buzz-review-completed`: Agent validation passed; automated DCO finding
was reconciled against the signed exact-head commit and green DCO check.
Tom confirmed the human-testing rule is inapplicable to this chart-only
release; personal testing is not claimed.

Signed-off-by: Tom Brow <tomb@block.xyz>
push-chart-v0.3.5
2026-10-06 20:09:38 -07:00
Tom Brow
9f5a25a41e feat(push): support Deployment metadata annotations (#8136)
Consumers currently need a Kustomize patch to place secret-reloader
annotations on the gateway Deployment. Add optional
`deploymentAnnotations` so they can express that configuration through
Helm values.

The setting applies only to Deployment metadata. The chart's
release-namespace and external-network-policy annotations remain
reserved and cannot be overridden.

### Validation

Full gateway chart render suite passes, including schema rejection of
reserved keys and non-string values, preservation of external-policy
ownership markers, and unchanged Pod annotations and migration hooks.
Repository-wide `just ci` passed with `RUST_TEST_THREADS=1`. The first
parallel run failed five unrelated timing/transport tests; all five
passed isolated reruns and the full serialized run completed
successfully.

`buzz-review-completed`: Codex review is clean on the current commit and
agent render validation exercises the change. Tom confirmed the
repository human-testing requirement does not apply to this chart-only
change; personal human testing is not claimed.

Signed-off-by: Tom Brow <tomb@block.xyz>
2026-10-06 19:31:43 -07:00
Bartok
b9e851d7be fix(buzz-pair): install rustls ring CryptoProvider before WSS (#7998)
## Summary

- `buzz-pair` panics on any `wss://` relay (including the documented
default `wss://relay.damus.io`) because no rustls `CryptoProvider` is
installed. `ws://` is unaffected.
- Sibling binaries already install ring explicitly
(`crates/buzz-cli/src/lib.rs`) and take a direct `rustls` dep with the
`ring` feature so a unified release build can still select a provider.
- This applies the same two-line pattern to `buzz-pairing-cli`: direct
`rustls` dep (`ring` + `std`) and `install_default()` at the top of
`main()`, before any connection.

Fixes #7927.

## Test plan

- [x] Diff matches the established `buzz-cli` install pattern (same dep
features, same `let _ =` swallow on double-install).
- [x] `cargo build -p buzz-pairing-cli` and `buzz-pair source --relay
wss://relay.damus.io` reaches "Waiting for target" without the rustls
panic.
- [x] `buzz-pair test-vectors` still exits 0 (no WSS, install is a
no-op).

---------

Signed-off-by: Bartok9 <259807879+Bartok9@users.noreply.github.com>
2026-10-06 14:50:21 -07:00
chiller
5ff83d82f8 fix(desktop): address workflow deletions at the workflow's actual owner (#2669)
Fixes #2671.

## Problem

Deleting an agent-created workflow from the desktop app appears to
succeed, but the workflow keeps running and stays in the list. Since
workflows are commonly created by agents, this makes most workflows
undeletable from the UI.

## Root Cause

`delete_workflow` builds the NIP-09 `a`-tag coordinate with the
**caller's** pubkey:

```rust
let builder = events::build_workflow_delete(&workflow_id, &current_pubkey_hex(&state)?)?;
```

kind:30620 is addressable by `(author, d-tag)`. For an agent-created
workflow, `30620:<caller>:<workflow-id>` names a record that does not
exist. The relay accepts the kind:5 (a self-addressed delete always
passes validation) and deletes nothing; the UI reports success.

Observed live: a delete of an agent-owned workflow produced
`["a","30620:<human-pubkey>:<workflow-uuid>"]` while the kind:30620
event is authored by the agent — the coordinate can never match.

## Fix

Fetch the workflow's kind:30620 event first (the same `#d` query
`update_workflow` already uses) and build the coordinate from the
event's author. Relay-side validation already authorizes the owning
human for agent-authored coordinates via `is_agent_owner`. Deleting an
unknown workflow id now surfaces `workflow not found` instead of
silently publishing an unmatchable delete.

This is the client half of the fix. The relay half is #2242: today the
relay executes a-tag deletions scoped by the delete's signer, so a
human-signed delete of an agent workflow still no-ops server-side.
Without this change, #2242 alone won't help desktop users, because the
client addresses a record that doesn't exist. Together they make delete
work end to end.

Related but deliberately not included: deleted workflows leaving their
kind:30620 event queryable (ghost list entries) is #2390, with a
relay-side fix open in #1340.

## Validation

- `cargo test` in `desktop/src-tauri`: 1617 passed, 0 failed, 14
ignored.
- `cargo clippy --all-targets` and `cargo fmt --check`: clean.
- Live repro against the hosted relay: the stock client's kind:5 for an
agent-owned workflow named the signer in the coordinate; the relay
returned `accepted: true` and the workflow remained live and kept
firing.
- With the fix: the delete event carries
`30620:<agent-pubkey>:<workflow-id>`; an owner-signed deletion of that
exact coordinate was verified to remove the workflow record.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-10-06 14:24:15 -07:00
Junchao Yan
003770cb79 fix(buzz-acp): bound sibling-gate lookup failures instead of caching them (#7216)
## Summary

Fixes #5450. Supersedes #5459 (see "Related issue").

In `owner-only` / `allowlist` respond modes, the inbound author gate
admits a sibling agent (same owner, proven by the NIP-OA auth tag on its
kind:0) only after `check_sibling_via_profile` fetches that profile over
REST (`POST /query`, 2 s timeout). The boolean result of that lookup was
cached in `OwnerCache` **for the process lifetime, unconditionally** —
so a timeout, a network error, or a non-2xx response was cached as "not
a sibling". One relay blip at first contact and the agent silently
ignores that teammate bot until restart. The owner never hits this path
(`author == owner` short-circuits with no network call), which is
exactly the observed shape: agents keep answering their owner while
dropping every agent-to-agent mention.

Two things kept it invisible: the author-gate drop was logged at `debug`
(hidden by the default filter), and `RestClient::request_with_retry`
returned non-retriable HTTP statuses (401/403/500) with no log line at
all.

### What changed (`crates/buzz-acp`)

- **Tri-state verdict.** `check_sibling_via_profile` returns
`SiblingVerdict::{Sibling, NotSibling, Indeterminate}`. Only a *fetched*
profile yields a cacheable verdict. A failed query, a malformed body, or
a missing kind:0 (not published, or not yet replicated to this relay) is
`Indeterminate` — nothing was attested.
- **Bounded per-author retry instead of retry-per-event.** An
indeterminate lookup fails closed for the current event and arms a retry
deadline: 5 s, doubling per consecutive failure to a 60 s cap
(`SIBLING_RETRY_BASE` / `SIBLING_RETRY_MAX`). Events inside the deadline
are denied with no relay call; expiry re-arms exactly one lookup; a
proven verdict replaces the deadline. This matters because the lookup
awaits inline in the sole inbound-event loop — an unthrottled retry
under a persistent `/query` outage lets one chatty sibling stall ingress
for the owner too. With the backoff, a dead relay costs at most one
inline lookup per author per minute.
- **No wholesale cache clear at capacity.** Replacing an author already
present never evicts. A new author at the 256-entry cap evicts exactly
one entry — the longest-expired retry record if any, else an arbitrary
entry — so proven verdicts and the other authors' backoff tiers (their
`failures` counters) survive saturation.
- **Diagnosability.** The author-gate drop logs at INFO;
`request_with_retry` WARNs on non-retriable HTTP statuses.

### Reviewer notes

- Fail-closed security posture is unchanged: an unverifiable author is
still dropped. Only what is *remembered* about that author changes.
- A fetched profile with no verifying owner attestation is still a
cached `NotSibling`, so a stranger spamming an owner-only channel
doesn't cost a REST round-trip per message. A *missing* profile is
retried under the backoff, which removes the need to restart a harness
after a sibling's profile is published late.
- When no expired retry record exists, the single eviction victim is an
arbitrary map entry rather than LRU; per-entry access timestamps didn't
seem worth it for a cap the fleet sits far below. Happy to change if
you'd prefer it prefer throttled entries over proven ones.

### Related issue

- Fixes #5450.
- #5459 by @whyihaveyou introduced the tri-state verdict and the
no-cache-on-indeterminate rule for the same bug. It has been open
without review since 2026-08-10 and is now conflicting with `main`; it
also retries the inline lookup on every event and leaves the wholesale
`map.clear()` in place. This PR carries the same first half and adds the
bounded retry and eviction behaviour that came out of review on our fork
(yjc801/buzz#112). Credit for the diagnosis and the verdict design goes
to that PR.

### Testing

Nine regression tests in `author_gate_tests` bind the production seam
(`is_owner_or_sibling` → `check_sibling_via_profile`) against loopback
`/query` stubs:

- unreachable relay ⇒ denied, **not** cached as a verdict
- missing profile (`[]`) ⇒ denied, not cached, throttled under the
backoff
- fetched profile without a verifying tag ⇒ denied and cached `false`
- kind:0 carrying a real `compute_auth_tag` attestation ⇒ admitted and
cached `true`
- flaky relay (500 until healed): a burst inside the deadline makes
**no** relay calls, expiry re-queries once, recovery caches the proven
verdict and ends throttling
- backoff sequence 5 → 10 → cap, tracked per author
- re-arming one author's deadline in a full cache keeps the other 255
proven verdicts
- a new author at capacity displaces an expired record first, then
exactly one entry
- with two expired records at capacity, only the longest-expired is
evicted and the survivor keeps its backoff tier

`cargo test -p buzz-acp`: all unit and lifecycle tests pass on this
branch; `cargo clippy -p buzz-acp --all-targets` and `cargo fmt --check`
clean. Commit is DCO-signed.

Live context that led here: on a hosted relay whose REST endpoint
flapped for a day, every local agent that restarted with an empty cache
stopped answering its teammates within hours while still answering the
owner; two agents sat online with zero turns. Not live-verified post-fix
upstream — verified by the tests above and by the fork's review rounds.

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

Signed-off-by: Junchao Yan <yjc801@gmail.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-06 15:14:04 -06:00
Tyler
1a2ddf9eaa feat(relay): private read-state accessory API (#7906)
Buzz BFF: Private read-state accessory API (`/buzz/v1`)
2026-10-06 16:12:03 -04:00
Salman Mohammed
46dcc01873 fix(acp): keep agent-to-agent thread replies in the thread (#8124)
## Summary
When an agent @mentions another agent inside a thread,
`resolve_reply_anchor` returned `None`, so the receiving agent's
`<context>` had no `--reply-to` instruction. A harness that follows the
base prompt literally then posted its reply at the channel top level.

Agent↔agent turns in a thread now anchor to the triggering event. The
reply stays in the thread and can still nest (the reason #1281 left
these turns unanchored). Top-level agent↔agent turns and all
human-facing turns are unchanged.

Native steering keeps the running turn's `<context>`, so a message
steered into a turn anchored to its trigger would be answered under that
trigger too. The prompt task now records whether its anchor is the
trigger, next to its DM classification (`PromptDmClassification` →
`PromptRouting`). The steer guard refuses native steering into a channel
thread turn whose anchor is the trigger, or not yet recorded. That
message takes the cancel+merge path, whose re-prompt carries its own
`<context>`.

Behavior change: a same-thread follow-up that arrives before the running
turn's prompt is formatted (for example during `session/new`) now
cancels and merges instead of steering natively, because the anchor is
not known yet. Once the prompt is formatted, follow-ups to human-facing
thread turns steer natively as before.

### Related issue
Fixes #8122

### Testing
- `cargo test -p buzz-acp -- --test-threads=1` (BUZZ_* env cleared):
1046 passed. `cargo clippy -p buzz-acp --all-targets -D warnings` clean.
Pre-push workspace `rust-tests` hook passed.
- New regressions, each confirmed to fail when its guard is removed:
- `human_follow_up_to_agent_thread_turn_cancels_and_merges`: a real
dispatched turn with agent profiles served by the relay fixture. A human
message in the same thread is not steered natively.
- `test_human_merged_into_agent_thread_turn_anchors_to_root`: the merged
re-prompt anchors to the thread root.
- `channel_same_thread_follow_up_during_prompt_steers_natively` /
`..._during_setup_cancels_and_merges`.
- Live local (`buzz-relay` + `buzz-acp` at this head + `buzz-pi-acp`;
agent B is a CLI identity with a NIP-OA auth tag):
- B @mentions A in a human-rooted thread → A's `<context>` says
`--reply-to <B's event>`, and the reply nests under B. On `main` the
`<context>` had no reply instruction.
- B asks A to `sleep 30` then reply; while A works, the human @mentions
A in the same thread → `control signal sent to in-flight task`
(cancel+merge), the re-prompt says `--reply-to <root>`, and both replies
land at the thread root.

---------

Signed-off-by: Leo <a3812943bac59c128e311ca05f83bf91113f179bb6fa9ca96c3d8efe15c330e6@buzz.block.builderlab.xyz>
Co-authored-by: Leo <a3812943bac59c128e311ca05f83bf91113f179bb6fa9ca96c3d8efe15c330e6@buzz.block.builderlab.xyz>
2026-10-06 18:31:37 +00:00
Tom Brow
c6dd587e2a release: push gateway chart 0.3.4 (#8126)
Publish push gateway chart 0.3.4 through the normal chart release
workflow. The chart version and implementation were merged in
[#8113](https://github.com/block/buzz/pull/8113); this release PR
records the release notes and triggers the immutable chart tag and OCI
publisher.

Publication is authorized. The pending security review of #8113 is a
blocker for pinning the chart in the later infrastructure PR, not for
this publication. No gateways or relays are activated.

### Validation

The merged implementation passed the complete chart render suite, chart
CI, and all 14 local wrapper tests. This release changes only the
changelog; chart contents are unchanged from the validated
implementation. Published OCI contents and digest will be verified after
publication.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
push-chart-v0.3.4
2026-10-06 11:05:10 -07:00
Tom Brow
73a2a05c97 feat(push): support platform-managed gateway runtime pods (#8113)
Platform-owned service meshes need runtime pod identity and a
replacement network policy without patching rendered gateway manifests.
Add runtime-only pod labels, service account and shutdown-grace
settings, plus an explicit named replacement-policy mode. Migration
isolation remains independent; the default render is unchanged.

Chart 0.3.4 publication and live deployment verification follow in the
separate release and deployment work.

### Validation

Added tests cover runtime-only settings, reserved selector labels,
minimum shutdown grace, replacement-policy acknowledgement and
conflicting settings. The complete chart render suite and
release-contract tests pass. Default rendering matches the current main
chart byte-for-byte. Repository-wide `just ci` reached unit tests but
failed in existing buzz-acp tests outside this chart change. Live mesh
behavior has not been exercised.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
2026-10-06 10:48:39 -07:00
Will Pfleger
001290a34d chore(release): release Buzz Desktop version 0.5.27 (#8125)
## Buzz Desktop release v0.5.27

- **Frozen main:** `af5bb0af488784c3707e99c87e0675a729711a6e`
- **Reviewed candidate:** `7a2fb3cc2d401e91e67d9819741d9025278cbec0`
- **Previous desktop release:** `desktop-v0.5.26`
- **Proposed immutable tag:** `desktop-v0.5.27`

This PR may be **squash merged** after the Desktop Release Candidate
check and all protected-branch checks pass. Merging authorizes
publication of the exact reviewed candidate; later or unrelated changes
on `main` cannot alter it.

The checked-in changelog accounts for every non-merge commit in the
release range. The Desktop tag points to the reviewed candidate commit,
not the later squash commit. Publication remains bound to that immutable
candidate tag.

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Release Automation <release-automation@users.noreply.github.com>
2026-10-06 13:31:05 -04:00
tbedor-square2
403c19f673 fix(desktop): show OpenAI-compatible endpoint settings in the baked-env UI (#8117)
## Summary

`is_safe_to_reveal` (`desktop/src-tauri/src/managed_agents/env_vars.rs`)
is the single default-deny allowlist for showing baked env values. It
lists `DATABRICKS_HOST`/`DATABRICKS_MODEL`/`DATABRICKS_MODEL_FILTER` but
not their OpenAI-compatible counterparts, so a build that bakes
`OPENAI_COMPAT_BASE_URL`, `OPENAI_COMPAT_MODEL`, `OPENAI_COMPAT_API`
shows them as `••••••`.

Adds those three non-secret settings to the allowlist: an endpoint URL,
a model id, and an `auto|chat|responses` enum. **No secret is revealed:
`OPENAI_COMPAT_API_KEY` is deliberately not added and remains masked.**

### Related issue

None found.

### Testing

- New test
`baked_env_openai_compat_endpoint_is_unmasked_but_key_stays_masked`
covers the three revealed settings and asserts the API key stays masked;
`baked_env_allowlist_is_case_insensitive` extended.
- `cargo test --lib baked_env` in `desktop/src-tauri`: 11 passed. `cargo
fmt` clean.
- Not exercised in the running desktop UI.

Signed-off-by: Tom Bedor <tbedor@squareup.com>
Co-authored-by: Tom Bedor <tbedor@squareup.com>
2026-10-06 12:07:26 -05:00
tbedor-square2
1e2281fd45 feat(buzz-agent): send User-Agent on LLM requests (#8116)
## Summary

`buzz-agent` builds its LLM `reqwest::Client` without a User-Agent, and
reqwest sends none by default, so OpenAI-compatible providers that
identify clients by product token see buzz-agent as an anonymous caller.

This sets `User-Agent: buzz-agent/<crate version>` on the shared LLM
client in `crates/buzz-agent/src/llm.rs`. The version is
`CARGO_PKG_VERSION`, the same value `agentInfo` reports over ACP. No
request body or endpoint changes.

Open point: the crate version is the workspace version (`0.1.0`), so
every build reports the same version. A per-build version would need the
desktop to pass one through at spawn time; this PR does not do that.

### Related issue

None found.

### Testing

- The test stub now captures the `User-Agent` request header; new
`llm_requests_carry_buzz_agent_user_agent` asserts
`buzz-agent/<version>` on a Chat Completions POST.
- Verified red without the `.user_agent(...)` line (`left: None`), green
with it.
- `cargo test -p buzz-agent --lib llm::tests`: 194 passed. `cargo fmt`
clean; the one clippy warning is pre-existing (`hints.rs:33`).
- Not exercised in a built desktop app.

Signed-off-by: Tom Bedor <tbedor@squareup.com>
Co-authored-by: Tom Bedor <tbedor@squareup.com>
2026-10-06 12:07:15 -05:00
Will Pfleger
af5bb0af48 docs(changelog): remove hand-written Unreleased section (#8123)
`CHANGELOG.md` is written entirely by `scripts/desktop_release.py`, but
#7692 hand-added a `## [Unreleased]` section at the top. `generate` puts
each new release block directly under `# Changelog`, which leaves `##
[Unreleased]` sandwiched between the new block and the previous release.
`validate` reads a release block up to the next `## v` heading, so it
pulls the Unreleased lines into the new block and fails with `changelog
block is not deterministic for recorded candidate base`. Every `just
release-desktop` run is blocked until the section is gone.

This removes the section. Its only entry (#7692, `036215636`) is already
in the generated v0.5.27 changelog block, so nothing is lost.

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
2026-10-06 16:06:37 +00:00
Will Pfleger
9c6fa14aa0 feat(desktop): offer Claude effort levels in agent edit and create (#8059)
Claude Code agents now get a thinking-effort dropdown in the agent Edit
and Create dialogs, matching the one buzz-agent and Codex agents already
have.

## Behavior
- **Where levels come from:** Claude effort levels come from the Claude
model data for the model that will actually run after Save, resolved in
order: explicit model, then inherited default (linked definition or
global), then adapter default. Stored Claude session levels are not
used, because the stored session data does not record which model
produced them.
- **Edit:** for an agent linked to a definition, effort follows the
definition's model, which stays authoritative. Save never sends a model
for linked agents.
- **Create:** effort is offered for local agents only and is stored on
the instance. Allowed levels are recomputed on every render, so
collapsing Advanced and then switching to a model without effort (e.g.
Haiku) drops effort from the request. Non-local effort is rejected
before any create side effects.
- **Persistence:** `create_managed_agent` sets the picked effort when it
builds the record and drops stale effort env aliases. Its body runs over
any Tauri runtime, so a mock-app test drives the real create path and
reads the record back from disk. That test runs in a child process with
temp app-data and nest folders, and a test-only switch turns keychain
use off so agent keys stay inline in the temp agent file and the OS
keychain is never touched.
- **Observer store:** live session-config captures are written to the
store before the dialog refreshes; archived captures are read-only.
- **Codex:** its existing session-native effort picker is unchanged.

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
2026-10-06 08:58:50 -06:00
Luke Tornquist
d0fd96fca6 BUZZ-175: Route serving event writes through the tenant lock (#7828)
## Summary

Route every serving event write through one community-admitted
transaction entry point. `Db::begin_event_write_transaction(community)`
is now the only `Db` constructor for event-write transactions: it takes
the shared community admission lock before returning, so callers that
use it cannot take domain or row locks ahead of tenant admission, and a
quiescing community rejects the write at entry. Database triggers and
commit-time fences remain the authoritative backstop.

This migrates normal, replaceable, roster, relay membership, reaction,
reminder, admin-delete, push-owned, artifact-accept, huddle-join
(48101), workflow-deletion, and command-executor event writes. Coupled
mention writes stay in the same transaction; pool-level
`insert_mentions` now opens its own admitted transaction.

**Review fixes (since `950d5f6`):**
- The unguarded event-write constructor is gone. Removed with it: the
deprecated `begin_transaction` alias, the test-only replica-floor
constructor, and `begin_community_write_transaction` (now identical to
the single constructor). Artifact accept, the huddle join, and both
workflow-deletion paths now admit before any domain or row lock;
`persist_command_event` no longer hand-rolls `guard_transaction`;
read-only `query_artifacts` no longer opens an event-write transaction.
- `insert_channel_head_checked` is now `insert_canvas_head_checked`: it
rejects non-canvas kinds before opening a transaction and always takes
the coordinate lock.
- Source policy now also scans `buzz-relay`: any function that hands a
transaction to an event-write helper must have opened it through the
admitted constructor. The scan drops each `#[cfg(test)]` item instead of
stopping at the first one: it tracks brace depth and ends the item on a
line ending in `;` or `}` (ignoring a trailing `//` comment, even after
a string that contains `//`), with a column-0 `}` as fallback. Fixtures
pin a unit struct, a multi-line static, a `const { … }` block, a struct
with fields, a module, and one-line items with trailing comments,
including after `"https://…"` and `"ws://…"` strings; a raw opener after
each must still be flagged. Known limit: braces inside string or char
literals or comments are still counted, and only `//` trailing comments
are recognized, so a test-only item with unbalanced braces in a literal
or comment, or with a trailing `/* */`, would hide what follows; none
exists today. The scan checks that admission is present; the per-path
PostgreSQL tests pin that it comes before domain locks.
- `just test-unit` (and the non-nextest fallback in
`scripts/run-tests.sh`) now runs `buzz-db --test observability_source`.
Before this, no CI job ran these source-policy tests: the unit lane ran
`buzz-db --lib` only and the PostgreSQL lane runs only ignored tests.
- Renamed or removed since `950d5f6`: `begin_transaction`,
`begin_community_write_transaction`, and the replica-floor test
constructor are gone; `insert_channel_head_checked` →
`insert_canvas_head_checked`; test helper `quiesce_community_for_tests`
now delegates to `main`'s `set_deletion_state`, which reads the real
`deletion_fence_generation` instead of hard-coding `'0'`;
`runtime::insert_mentions` is pinned to the admitted constructor by
`pool_level_insert_mentions_opens_the_tenant_local_chokepoint`.

**What got simpler:** four transaction constructors collapse to one, and
the hand-rolled admission guard is deleted. The compiler rejects callers
of the removed constructors, but a transaction opened from `Db::pool()`
can still reach the public `*_in_transaction` helpers; only the
source-policy scan and the database fences catch that until BUZZ-254.

**Behavior note:** #7932 made `insert_event` skip the transaction for
kinds that are not listener mentions. Every serving event write now has
to run in a transaction that holds the community admission lock, so
`insert_event` always opens the admitted transaction again. `main`'s
`soft_delete_event_and_update_thread` / `_in_tx` split and its
removal-marker guard are kept; the outer function now opens the admitted
transaction.

### Related issue

[BUZZ-175](https://linear.app/squareup/issue/BUZZ-175). Caller-migration
stage following #7706 (merged); rebased onto `main` at `5173fad66`.
Follow-up: [BUZZ-254](https://linear.app/squareup/issue/BUZZ-254) makes
event-write helpers require a type-level admitted transaction.

**Known debt, out of scope:** `create_channel`, `update_channel`, and
`insert_thread_metadata` write channel and thread rows (not events)
outside the admitted constructor.

### Testing

At `efe4a94623dd69973780a3c39f16dd972cf7cb76` on a cloud workstation:
fmt; `buzz-db` clippy (all targets, `-D warnings`);
`observability_source` 14/14; `just --dry-run test-unit` includes the
new step. Reverting just the end-of-item check to an earlier rule makes
a trailing-comment fixture fail.

At `eaf190ae59d1595741c3d19dc4c23ce492b5f4d4` (the commit after it only
changes this test file, `Justfile`, and `scripts/run-tests.sh`): full
GitHub CI green; on the workstation, clippy for `buzz-db` and
`buzz-relay`, ordinary `buzz-db` 154/154, `just test-unit` green, and
the PostgreSQL lane 805 of 806 (exception below). An end-to-end run
against a local relay and the built desktop app covered artifact accept,
huddle join, and workflow deletion for both a healthy and a quiescing
community, plus p-tag reaction rollback and replay of the same signed
event.

New tests: one fenced-community test per migrated path (artifact accept,
huddle join, both workflow deletions) puts the community into
`quiescing`, holds the lock the path takes next, and asserts rejection
at entry with nothing stored; a DB-free test pins the non-canvas
rejection.

Exceptions:
-
`runtime::postgres_tests::writer_pool_rejects_non_read_committed_database_default`
hangs on that workstation's local Postgres 16 at both this head and an
earlier `main` base, `f0eb5575f` (2/2 runs each). The test, `Db::new`,
and the pool setup are unchanged by this PR, and the test passes in
GitHub CI. Live traces put the hang in the client, not the database: the
1 s acquire timeout stops firing after sqlx's `after_connect` rejection
path under tokio's `current_thread` runtime. No database lock waits were
observed.
- Two `observability_source` assertions were already failing on `main`,
unnoticed because no CI job ran that test binary: a stale
`fetch_optional` pin after #8005, and lease-seam attribution that now
lives in the `bounded_serving_lease_sql` helper. Both are corrected
here, and the binary now runs in `just test-unit`.

Generated with Codex

---------

Signed-off-by: tornquist <tornquist@squareup.com>
Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
2026-10-06 10:24:41 -04:00
Logan Johnson
9322289364 feat(mobile): follow the portable mention rules, including DMs (#8102)
🤖
## Summary
The mobile app's @mention chooser now follows the same rules as the
desktop app (buzz-app). The same typed text finds the same people in the
same order on both apps, and sending works the same way.

- **Same matching and order.** Mobile uses the shared mention rules and
runs their shared test cases. A multi-word search such as `@Mary J`
still searches the community directory, so it can find "Mary Jane" even
when she is not in the channel.
- **DMs can mention people outside the DM.** The chooser marks them "not
in DM". Nobody can be added to a DM, so the message sends without a
prompt. Outside people go out as references, so they are not notified.
This matches buzz-app #510.
- **Channels still ask.** In a stream or forum, mentioning someone
outside the channel asks "Invite" or "Do nothing" before the message
sends. A channel with no type tag counts as a stream.
- **Sessions do not search the directory.** Only session members appear.
- **A failed directory search stays visible.** The chooser shows the
error and a Retry button. Before, it closed.
- **Search results stay in their community.** If you switch communities
while a search runs, its people and its error do not show in the new
community. The search starts again there.
- **A failed send check keeps the draft.** Before a message with a
mention sends, the app checks who is in the channel. If that check
fails, the message stays in the compose bar and a notice offers Retry.
Before, nothing was sent and nothing was shown.
- **Invite stays in its community.** If you switch communities while the
"Invite" question is open, Invite adds nobody.

### Screenshots
The real compose bar widget, rendered by Flutter's test renderer with
the app's fonts and theme. The data is sample data. These are not device
captures.

| DM: outside person is "not in DM" | Stream: outside person is "not in
channel" |
|---|---|
| <img width="320" alt="DM chooser"
src="https://github.com/user-attachments/assets/0e884518-2386-4cd1-9f19-16661aaa194e"
/> | <img width="320" alt="Stream chooser"
src="https://github.com/user-attachments/assets/5395e4e1-032e-459b-98c6-0126c060c4d9"
/> |

| Stream: send asks first | Session: members only | Search failed: Retry
|
|---|---|---|
| <img width="260" alt="Stream ask on send"
src="https://github.com/user-attachments/assets/2b988257-3c6a-445d-acfa-fca47b9752fe"
/> | <img width="260" alt="Session chooser"
src="https://github.com/user-attachments/assets/e193551f-f5bf-41d9-aa29-bc8665c643f9"
/> | <img width="260" alt="Search failed with Retry"
src="https://github.com/user-attachments/assets/e8c4b9bb-067e-4fe9-9fdd-4e5691bc66be"
/> |

### Details
- `mobile/lib/shared/mentions/mention_rules.dart` holds the rules: query
syntax, match tiers, sort order, Space selection of an exact unique
name, stable rows while results arrive, and `p` and `mention` tags. A
`p` tag notifies the person. A `mention` tag is a reference and does not
notify.
- `mobile/test/shared/mentions/mention-rules.fixtures.json` is an exact
copy of the buzz-app fixture file. `mention_rules_test.dart` runs every
case.
- Known difference: desktop gives the directory to a channel with an
unknown explicit type (not stream, forum, DM or session). Mobile does
not. No such type exists today.

### Related issue
None found. Desktop counterpart: block/buzz-app#510. #7513 also edits
`send_message_provider.dart` and may conflict.

### Testing
`just mobile-install mobile-check mobile-test` passes: analyze clean,
2998 tests pass on `49c44653` (before rebase). The pre-push hook ran
`just mobile-check && just mobile-test` again on the rebased head
`de1ca080` and passed.

Each review fix was mutation-checked: removing the fix makes its new
test fail.

---------

Signed-off-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-10-05 18:54:49 -04:00
Logan Johnson
166d383ca7 feat(mobile): read web app catch-up marks for unread state (#8103)
🤖

## Summary
The web and desktop app (`buzz-app`) saves a "caught up" mark when you
scroll to the bottom of a channel and stay there, and another one for a
thread. Mobile did not understand these marks. It relied on the separate
per-message read marks that `buzz-app` also kept. `buzz-app` is about to
stop keeping those per-message marks under the "caught up" mark
(block/buzz-app#590), to save space in the synced read state.

With this change, mobile reads the "caught up" marks with the same rules
as `buzz-app`:
- `activity:<channel>` reads ordinary top-level messages up to its time.
It does not read thread replies, mentions, broadcasts or DM messages,
because reaching the bottom of the channel does not prove you saw those.
- `thread-activity:<root>` reads the replies in that thread up to its
time.

So a message you read in `buzz-app` stays read on mobile: in the app
badge, the channel list unread state, the "new messages" divider when
you open a channel, and the Mark read / Mark unread action.

Mobile does not write these marks. It only reads them.

### Related issue
None found. Companion to block/buzz-app#590. The old desktop app in this
repo is intentionally not changed.

### Testing
- New badge tests: `activity:` clears an ordinary top-level message, and
does not clear a mention, a thread reply or a DM. `thread-activity:`
clears replies in its own thread only. The two "clears" tests fail
without this change.
- New tests for the per-message read check and the "ordinary message"
rule.
- `flutter analyze`, `dart format` check and the full mobile test suite
pass locally.
- Not yet exercised on a device.

---------

Signed-off-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-10-05 18:52:59 -04:00
Will Pfleger
1e67395fd1 docs(identity): tighten enterprise adapter contract (#8069)
Tightens `docs/enterprise-identity-adapter.md` to define the enterprise
adapter contract implemented by kgoose in
[cash-server#132770](https://github.com/squareup/cash-server/pull/132770)
and the Buzz Desktop client in
[buzz-app#562](https://github.com/block/buzz-app/pull/562).

- Requires canonical `wss://host[:port]` relay URLs with a lowercase
scheme, the lowercase ASCII (A-label) host form with no trailing dot,
the default port omitted, and no trailing slash, path, query, or
fragment. Adapters MUST configure relays in canonical form, compare
`relay_url` against that exact form, and reject unknown relays with 403
`authorization_denied`.
- Requires NIP-98 proof freshness of at most 60 seconds old and at most
5 seconds in the future, with the proof bound to the endpoint, method,
and exact request body.
- Rejects content-encoded request bodies with 400 `invalid_request`.
- Caps assertions at `exp - iat <= 300` seconds and the adapter session
expiry, requires `typ` `nip-fi+jwt`, and validates the echoed
`nostr_pubkey`.
- Defines refusal and retry handling: Clients MUST retry 429 and 503
with bounded backoff whatever the `error` code. Clients MUST treat any
other status, a 400/401/403/413 response with a contract-undefined code,
or a rejected `200` response including one it cannot parse, as a
refusal: keep the session, show it as refused, and not retry
automatically. Network failures retry with bounded backoff.

This tightens the enterprise adapter contract restored in
[#8064](https://github.com/block/buzz/pull/8064).

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: Alia <d32955ad69077062930cc46cfe2df30ca9aaf6f8e76422681265e9e9af704d78@buzz.block.builderlab.xyz>
mobile-v0.20.0-rc.1
2026-10-05 15:39:13 -04:00
Tom Brow
c9143ed8f7 chore(push): release gateway chart 0.3.3 (#8107)
Prepares publication of the Buzz push gateway chart 0.3.3, including the
optional migration Pod annotations already merged in #8105. This PR adds
release notes only; chart templates, values, and schema are unchanged
from the reviewed implementation.

Merging the `push-chart-release/0.3.3` branch triggers the normal
release workflow: create `push-chart-v0.3.3`, validate the chart, then
publish `oci://ghcr.io/block/buzz/charts/buzz-push-gateway:0.3.3`. Keep
this PR in draft until publication is explicitly authorized. It does not
deploy a gateway.

### Validation

Focused migration annotation renders, release contract checks, and local
chart packaging pass. The merged implementation passed chart CI and
Jude's automated review in #8105. The earlier repository-wide local
`just ci` run failed in unchanged ACP tests; it was not rerun for
release notes. The registry manifest digest can only be verified after
publication.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
push-chart-v0.3.3
2026-10-05 12:23:27 -07:00
Carlos Jimenez
fcf5f044b3 fix(desktop): use object-scale-down for inline markdown images (#4686)
Fixes #4384.

A dim-less markdown image with no cached decode gets
`DEFAULT_IMAGE_RESERVE = { height: 256, width: 384 }` and
`useFixedReserveBox: true` in `resolveImageReserveBox`. The frame is
that big on first view, and the inline `<img>` uses `object-contain`
which scales UP to fill the frame — so a 46×20 shields badge renders
as a giant blurry block. The same message renders at the natural
size on the second view because `rememberDecodedImageDimensions`
populates the cache, but the inconsistency between first and
subsequent view is the bug.

Switches `object-contain` → `object-scale-down` on
`ProgressiveImage.tsx`'s shared `IMAGE_CLASS`. Both `object-contain`
and `object-scale-down` scale down to fit, but only
`object-scale-down` also refuses to scale up — a small image now sits
centered in the reserve box on first view, never upscaled. The
layout-shift guarantee for large images is preserved (they still
scale down to fit the reserve), matching the issue's stated
constraint.

Chose option 2 ("Alternatively/minimally") from the issue over
option 1 because:

- It's a one-class-name change with zero new state, zero new
  effects, and zero risk to the existing layout-shift guarantee
  that the surrounding `useFrozenImageReserve` is explicitly
  designed to preserve.
- Option 1 (collapse the frame on decode) is the issue author's
  preferred direction but requires deciding whether the layout
  shift is acceptable *shrink*-only — a direction question that
  should be confirmed with the maintainer first. The issue
  explicitly says "Happy to open a PR for option 1 if the
  direction is acceptable" — that's the sign-off step, not
  this PR.

If maintainers want the full first-view-equals-second-view
behavior, option 1 is a follow-up that builds on this base.

Not added: a regression test. The current desktop test infra
(`desktop/src/shared/ui/markdown/markdown.test.mjs` and
siblings) doesn't cover `ProgressiveImage` directly; a
DOM-style snapshot would need a new test harness. The change
is one CSS class name; the visual regression is plain to
eyeball in the screenshots CI already captures.

Verified:
- `pnpm check` (biome + file-sizes + px-text + pubkey-truncation) —
clean
- `npx tsc --noEmit` — clean

Signed-off-by: kushaim <carlossilvajimenez@gmail.com>
Co-authored-by: kushaim <carlossilvajimenez@gmail.com>
2026-10-05 11:54:35 -07:00
benthecarman
964b556a42 fix(desktop): detect Kimi Code in its default install path (#3700)
## Summary

By default on linux kimi is installed at `~/.kimi-code/bin/kimi` and
this was not detected automatically. This now fixes it by adding this
path to the detection

### Related issue

 N/A

### Testing

Before it did not appear / did not detect. Now it does :)

Signed-off-by: benthecarman <benthecarman@live.com>
2026-10-05 18:50:18 +00:00
Logan Johnson
0a070dfd3f fix(acp): steer mid-turn DM follow-ups natively again (#8058)
🤖
## Summary
Some agents can take a new message into a turn that is already running.
This is called "native steering": the agent keeps working and folds the
new message in, instead of stopping and starting over.

#6132 made this safer in channels: a message is steered in only when it
belongs where the running turn will reply. In a channel, each top-level
message gets its own reply thread, so a second top-level message must
not be steered into a turn that replies in the first one's thread.

That rule also ran in DMs, where it does not fit. In a DM, a top-level
message is answered at the top of the conversation, not in a new thread.
So every top-level DM message replies in the same place. But the rule
treated each one as its own thread. As a result, **every DM follow-up
sent while the agent was working cancelled and restarted the turn**,
instead of being steered in as it was before #6132.

Now:
- **DMs:** a follow-up is steered natively when it replies in the same
place as the running turn: both top-level, or both in the same thread. A
thread reply during a top-level DM turn (or the reverse) still takes the
cancel-and-restart path, because the running turn would reply in the
wrong place.
- **Channels:** unchanged from #6132.

## Details
- The queue now records each running turn's reply route: its thread root
(or none) and its reply thread. One function,
`ReplyRoute::accepts_steer`, decides whether a new message may be
steered in. It compares thread roots in DMs and reply threads in
channels.
- The DM rule mirrors how the prompt is built: a top-level DM's
`<context>` has no `--reply-to` target, and a threaded DM's target is in
its thread.
- The steer decision must agree with how the running turn's prompt was
written. The prompt task records whether it writes the prompt as a DM,
and the steer decision reads that recorded value. So if channel metadata
was missing when the turn started (the prompt then uses the normal
channel form) and loads later, the DM rule is not applied to that turn.
- The prompt task records this value as soon as channel metadata
resolves, before session setup. A follow-up sent during a slow
`session/new` is steered in, as on main. When an `initial_message` setup
prompt runs first, the value is recorded after that setup turn, because
the setup prompt reads the same steer mailbox.
- Before the value is recorded, the steer decision uses the listener's
own channel classification. A channel the listener knows is not a DM is
always written in channel form, so the channel rule applies at once,
exactly as on main. A DM, or a channel whose type is not resolved, takes
the cancel-and-restart path until the value is recorded.

### Related issue
Follow-up to #6132 (merged). Found in review after merge. No separate
issue.

### Testing
- New tests drive DM messages through the listener's real steer decision
with a running turn. A second top-level DM message is steered natively
with no cancel. A DM thread reply during a top-level DM turn is not
steered and takes cancel-and-restart.
- Direct tests of the steer rule cover channel and DM cases: same
thread, different thread, top-level after top-level, and top-level mixed
with thread replies.
- With the DM rule disabled, the DM rule test and the top-level DM
listener test fail.
- Listener tests also cover a DM turn whose prompt was written as a
channel (top-level follow-up is not steered) and a DM follow-up that
arrives before the value is recorded (not steered).
- Production-path tests dispatch a real turn through `dispatch_pending`
and `run_prompt_task` to an agent that holds at `session/new` or
`session/prompt`, then send a follow-up through the real listener. A
top-level DM follow-up during the prompt or during `session/new` is
steered with no cancel. A DM follow-up before an `initial_message` setup
turn is not steered. A same-thread channel follow-up during setup is
steered with no cancel.
- Mutation checks: each fails its test. They are: not recording the
value in `run_prompt_task`, passing a detached value from dispatch, not
recording it before session setup, recording it before an
`initial_message` turn, and removing the known-channel rule for the
unrecorded case.
- `cargo test -p buzz-acp` passes on the rebased head, with the
timing-sensitive `acp::tests` run alone (`--test-threads=1`; this PR
does not change them, and they fail only under full parallel load on
this laptop). `cargo clippy -p buzz-acp --tests -D warnings` and `just
desktop-tauri-clippy` are clean.

---------

Signed-off-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-10-05 14:43:21 -04:00
Tom Brow
fd885b5530 feat(push): support migration pod annotations (#8105)
Allow operators to configure migration Pod annotations independently of
runtime Pod annotations. This lets clusters with automatic sidecar
injection opt the migration Job out without changing the gateway
Deployment or Helm hook metadata.

The new string-map setting defaults to empty. Chart version 0.3.3 is
prepared here; publication requires a separate approved chart release
PR.

### Validation

The full chart render suite and focused migration annotation tests pass.
Tests verify unchanged default resources and hooks, independent runtime
annotations, and rejection of non-string annotation values. Independent
agent review found no blockers. Repository-wide `just ci` exited 1 in
unchanged `buzz-acp` tests: idle/stdout keepalive timing and steering
assertions (one failure in the first group, four in the second).
Subsequent recipes were not reached. No rerun or unrelated code fix was
attempted. Human testing remains pending.

Signed-off-by: Tom Brow <tomb@block.xyz>
2026-10-05 11:39:20 -07:00
klopez4212
5173fad660 feat(pairing): enter desktop codes on mobile (#8085)
## Summary
Enter a desktop-only, random six-digit code on mobile to pair without a
desktop confirmation click. Verification uses the encrypted session,
limits guesses to five, and never treats the QR-derived transcript as
approval. Older clients retain desktop confirmation.

Adds digit-only error shakes and native haptics, a separate biometrics
choice, and a direct community-icon arrival animation. Fixes dropped
early offers and resets completed pairing so reopening or signing out
cannot get stuck.

### Related issue
Related: #8060; no duplicate code-entry PR found.
<img width="780" height="1688" alt="01-enter-code"
src="https://github.com/user-attachments/assets/a99ced3e-4305-4ac6-a6cc-d598ced423e7"
/>
<img width="780" height="1688" alt="02-incorrect-code"
src="https://github.com/user-attachments/assets/19cdb109-1f10-40a9-a661-1d7ba89c81c1"
/>
<img width="780" height="1688" alt="03-biometrics"
src="https://github.com/user-attachments/assets/af1b2924-9ab6-4d1a-b4b1-fccfdf446404"
/>
<img width="780" height="1688" alt="04-community-loading"
src="https://github.com/user-attachments/assets/84145d82-843a-4c25-aef7-6492fc241d4b"
/>
<img width="897" height="388" alt="05-desktop-code"
src="https://github.com/user-attachments/assets/d8a2e469-7e42-466a-988f-bab6b1df85fc"
/>

### Release order
Deploy the updated pairing relay first, then desktop, then mobile. The
relay now allows eight events per connection (seven for a successful
fifth guess plus room for cancellation), with a corresponding bounded
delivery budget. Existing clients remain supported; older client
combinations keep desktop confirmation.

### Testing
- 103 mobile pairing tests, 270 core tests, 51 relay integration tests,
and the new real-relay fifth-guess flow passed.
- The real-relay regression verifies proof, decrypted identity import,
and completion after four wrong guesses. Restoring the old six-event cap
makes it fail.
- A paused-clock desktop regression confirms slow readiness cannot
extend the visible QR beyond protocol expiry. Mobile regression covers
typing before negotiation completes.
- Core/pair-relay Clippy and full native desktop Clippy/workspace tests
passed. Mobile analysis passed; broad mobile runs each hit an unrelated
failure (a gateway-script timeout and a native-menu missing-plugin
error), and both affected test files passed separately.
- Repository-wide Rust testing exhausted local disk space while
compiling unrelated packages. The final push omitted that
resource-blocked hook and avoided repeating the desktop/mobile runs
above; hosted CI remains required.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-05 13:42:39 -04:00
Luke Tornquist
7f6ffd5ee5 fix(db): enumerate only active communities for maintenance (#8061)
Fixes #7558. Supersedes #7630.

The SQL predicate here comes from #7630 by @olympusbuildz, who is
credited as co-author on the commit. This PR keeps that fix unchanged
and adds the lifecycle fixtures and worker-path coverage the fix needed.

## Problem

`community_hosts_with_operation` ran `SELECT id, host FROM communities`
with no filter. After a whole-community deletion, the `communities` row
stays behind as a `tombstone` until retention expires, which is by
design. But the NIP-43 maintenance sweep kept handing that community to
`publish_nip43_membership_list`. The community write fence rejected the
write, so the relay logged `NIP-43 membership reconciliation failed`
about every 60s, indefinitely, for every deleted community.

## Change

The helper is split by caller purpose:

- `active_community_hosts` (maintenance) and `bootstrap_community_hosts`
filter to `archived_at IS NULL AND deleted_at IS NULL AND deletion_state
= 'active'`. That's the same active-community predicate already used in
`community.rs` and `deletion.rs`.
- `usage_community_hosts` still enumerates every row, exactly as on
main.

The startup large-roster reconciliation query
(`list_large_channel_rosters_needing_reconciliation`) joined
`communities` without any lifecycle filter, so it gets the same active
predicate on its `JOIN communities`.

Tombstone rows aren't modified.

### Caller impact

| Caller | Enumeration | Effect |
|---|---|---|
| NIP-43 maintenance sweep (`side_effects.rs`) | active | Stops trying
fenced writes and logging warnings forever. This is the bug fix. |
| NIP-43 bootstrap reconciliation | active | Same as maintenance, at
startup. |
| Push-wake worker (`push_runtime.rs`) | active | Stops claiming wakes
for these communities. Archived communities are unreachable through host
resolution; quiescing, fenced and tombstone writes are DB-fenced. Wakes
already queued for an archived community aren't delivered late after
unarchive, because claim and send both re-check `expires_at`. |
| Startup large-roster reconciliation (`side_effects.rs`, kind 39002) |
active | Stops rewriting roster snapshots for archived communities and
attempting fenced writes for deleting or tombstoned ones. |
| Usage-metrics host map (`main.rs`) | all rows | Unchanged.
Per-community labels, fleet totals and storage attribution keep covering
the same rows as the unfiltered usage count queries. |

## Tests

#7630's test tombstoned a row with a plain `UPDATE`. On current main,
the `enforce_community_tombstone` trigger from migration 0029 rejects
that unless the transaction carries the deletion-executor GUCs. The
fixtures here set those GUCs the way the executor does.

- `buzz-db`
`store::usage::postgres_tests::test_community_hosts_excludes_archived_and_deleted_communities`
sets up active, archived, quiescing, fenced and tombstoned fixtures.
Across two sweeps it checks that `active_community_hosts` (maintenance)
and `bootstrap_community_hosts` both return only the active community,
and that `usage_community_hosts` still returns all five. It also checks
that the tombstone row still exists with `deleted_at` set.
- `buzz-relay`
`handlers::side_effects::tests::postgres_tests::maintenance_sweep_skips_archived_and_deleted_communities`
is the worker-path regression. It runs
`reconcile_nip43_membership_snapshots_with_purpose(Maintenance)` three
times against the same five fixtures. It checks that
`buzz_nip43_membership_reconciliation_failures_total` stays at 0, the
active community gets exactly one membership snapshot, the four
non-active communities get no maintenance write, and the tombstone row
is still there.
- `buzz-db`
`store::channel_members::postgres_tests::large_roster_reconciliation_skips_archived_and_deleted_communities`
seeds a channel whose roster has diverged from its live relay-authored
kind-39002 snapshot in each of the five fixture communities. Only the
active community's channel may be returned.

All three tests are `#[ignore = "requires Postgres"]` inside
`postgres_tests::`, so the PostgreSQL CI lane picks them up through its
existing structural filter.

## What got simpler

The background writers share one definition of "community eligible for
maintenance": the same active predicate the rest of the store uses.
Usage metrics keep their existing semantics, so this PR changes no
metric. One enumeration helper is added (`active_community_hosts`), and
the old `community_hosts_with_operation` indirection is gone. The
executor-GUC lifecycle fixture lives once in `test_support` and is
shared by both DB tests instead of being duplicated.

---------

Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Olympusbuildz <Olympus.roots@outlook.com>
2026-10-05 13:25:21 -04:00
klopez4212
8746bfebff Polish iOS header glass and scroll-edge blur (#8097)
Wrap channel and DM titles in native glass and remove the
temporary-channel clock. Apply a soft status-area fade across iPhone
navigation, and fade the large title with scroll progress and fade in
the centered title, with Reduce Motion support.

Validation: mobile formatting/analysis and the full mobile suite passed.
Native iOS 26/27 simulator checks covered actual text opacity, header
resizing, quick reversal, and restored heading position; signed iPhone
build, installation, and launch succeeded. `just ci` was blocked by disk
exhaustion during Rust compilation.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-05 11:55:11 -04:00
klopez4212
46e60206a4 fix(mobile): fill and stabilize content-aware loading placeholders (#8083)
Fill mobile loading views across the screen and use known image, video,
voice-note, and file shapes in message placeholders. Freeze each loading
cycle’s layout so arriving metadata cannot reshuffle the shimmer just
before content appears; preserve cached Home and forum content during
reconnects.

Validation: mobile analysis and full test suite passed (2,752 passed, 4
skipped), plus 3 unconfigured-push tests and file-size checks. Installed
and launched the loading changes on Pixel 10 before the latest main
merge. Full `just ci` was stopped during desktop checks due to low disk
space.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-05 11:26:48 -04:00
klopez4212
f0eb5575ff fix(mobile): polish photo carousels and video viewer controls (#8079)
## Summary
- Keep neighboring carousel photos visible, add page-change haptics, and
reuse appearance-style dots with native iOS glass and grouped actions.
- Refine full-screen video controls with fading transport, cycling
speeds, pinch-to-zoom, and double-tap reset before swipe-to-dismiss.

### Related issue
N/A. Checked recent open PRs; repository issue search was unavailable.

### Testing
- Mobile analysis/format checks, file-size guards, and full Flutter
suite passed (2,680 tests; 4 skipped).
- Built, installed, and manually verified on the connected iPhone.
- `just ci` was attempted but blocked fetching a Rust dependency because
this Mac could not connect to GitHub.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: klopez4212 <klopez4212@gmail.com>
2026-10-04 17:17:46 +01:00
klopez4212
5f2d801b8f fix(mobile): align Android conversation headers and reactions (#8082)
## Summary
Align Android channel and DM headers with iOS: centered, tappable titles
with presence or member counts and no avatars. Keep conversation
navigation frosted through keyboard and scroll changes, and run the
typing shimmer left to right.

Add an Android reaction details sheet with All/emoji tabs, swipe
navigation, and compact rows aligned to the tab gutters. Native iOS
reaction presentation is unchanged.

### Related issue
None found.

### Testing
- Mobile analysis, formatting, file-size checks, and full mobile tests
passed.
- Android debug build installed and launched on Pixel 10.
- Full `just ci` could not complete: disk space exhausted while fetching
an unrelated Rust dependency.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-04 16:49:12 +01:00
klopez4212
75a4efd0ca fix(mobile): unify sheet sections and bottom spacing (#8081)
## Summary
Use rounded, grouped rows consistently across mobile sheets and menus,
including Members and list pickers. Keep sheet content above the system
gesture area with 4dp of extra bottom padding on Android and iOS.

### Related issue
No duplicate found; related member-picker work: #4051.

### Testing
- Mobile analysis, formatting, file-size checks, and full mobile test
suite pass.
- Android build installed and launched on Pixel 10.
- Before/after Members previews use sample data (attached below).
- Full `just ci` stopped during Rust compilation because local disk
space ran out.

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-04 16:20:01 +01:00
klopez4212
03f24a69bf feat(mobile): add iOS Liquid Glass tabs and quick actions (#8080)
## Summary

Use native Liquid Glass for the iOS tab bar and expanding + menu,
preserving the existing Lucide icons, icon-only layout, badges,
accessibility labels, and tab interactions. The + uses black-tinted
glass with white controls; the selected tab has a subtle theme accent
(6% blended into the existing selection color). Android retains its
current styling.

### Related issue

No duplicate issue found. Related prior navigation work: #7281 (closed).
This change covers the tab bar and quick actions; it does not add
page-to-page navigation-bar morphing.

### Testing

- `just mobile-check` passed (formatting, analysis, and file-size
checks).
- `just mobile-test` passed: 2,678 tests passed, 4 skipped; the separate
unconfigured-push suite also passed all 3 tests.
- Widget coverage verifies native glass parameters, black + tint,
original icons, icon-only layout, tab selection, badges, and quick-menu
open/close behavior.
- Signed Release iOS build installed and launched on a physical iPhone;
the final glass and tint styling was reviewed on device. No final-app
screenshot was captured.
- Full `just ci` was attempted but stopped during desktop compilation as
available disk space dropped to 3.5 GiB. The complete repository-wide
gate is not locally verified; hosted CI remains pending.

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-04 14:24:09 +01:00
klopez4212
d2da104d94 feat(mobile): add animated community switcher (#8076)
## Summary

Replace the community switch sheet with a two-column picker. Selection
enlarges the avatar, waits with the voice-note loader for destination
channel content and layout to settle, then follows a curved path into
the header.

Cache raster icons at a maximum 512-pixel size and accept only
resource-free emoji SVGs. Cancel timed-out or disposed downloads without
delaying content readiness. Animate Edit badges in place, and open Add
Community on the pairing welcome page. Community removal lives only in
the switcher’s Edit mode. Keep the flow shared across Android/iOS, with
native iOS controls and removal confirmation, and clear navigation
backgrounds at rest.

### Related issue

Related to #8070 (community icon refresh/caching).

### Testing

- 122 focused Flutter regression tests and seven native iOS tests passed
after merging the latest navigation changes from `main`. Earlier feature
build installed and launched on a physical iPhone.
- Full mobile pre-push checks passed; regression coverage includes
gradient rendering, rejected/oversized icons, bounded persisted raster
decoding, SVG resource rejection and cache migration, timeout/disposal
cancellation, disconnected destination channels, degraded unread-history
settlement, and switching while icons refresh. Full `just ci` stopped
during Rust checks for low disk space. Hosted CI remains required.
- [Grid and Edit
previews](https://github.com/block/buzz/pull/8076#issuecomment-5977838957).

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-04 14:11:39 +01:00
klopez4212
05d1714912 fix(mobile): manage channel members from profile sheets (#8078)
Keep member administration reachable when small channels omit “See all.”
Tapping a member now opens profile-sheet rows to make a channel admin,
change an admin to member, or remove the person with confirmation, using
the existing grouped list style.

Actions follow the live roster, respect channel permissions, prevent
duplicate submissions, and surface failures. Existing guests can become
members or admins; owners, self, archived channels, and DMs do not
expose these controls.

Validation: mobile analysis, formatting, file-size checks, and the full
mobile suite passed. Release iOS build installed and launched on a
physical iPhone. Full repository `just ci` was previously stopped for
low disk space during desktop compilation.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-04 11:39:13 +01:00
klopez4212
a14107ab2e fix(mobile): refine iOS navigation and conversation details (#8075)
Fix iOS navigation title taps and truncation, theme-aware blur
(including chats opened at the newest message), and the search focus
animation with a plain, correctly spaced Cancel button.

Simplify DM details and header actions, move profile descriptions below
names, and remove redundant Settings/Add Community titles and
unnecessary “See all” links.

Validation: mobile analysis, formatting, file-size checks, and the full
mobile test suite passed in pre-push hooks; Release iOS build installed
and launched on a physical iPhone. Full `just ci` was stopped during
unrelated desktop compilation due to low disk space. Native XCTest
additions have not been run locally.

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-04 10:36:59 +01:00
Will Pfleger
e982f70fba docs: restore enterprise identity adapter contract with relay assertion (#8064)
🤖 Restores `docs/enterprise-identity-adapter.md`, the vendor-neutral
HTTP contract between Buzz Desktop and an enterprise identity adapter,
and adds the request that turns an adapter session into a NIP-FI relay
assertion.

The login, code exchange, session check, transport, and privacy sections
are byte-for-byte the text from the head of #7715 (`4ef08e23`). Buzz
Desktop's enterprise login client
([buzz-app#525](https://github.com/block/buzz-app/pull/525)) already
calls those routes.

The new **Relay assertion** section defines `POST
/v1/identity/assertions`:

- **Request:** a JSON body with `relay_url` and `nostr_pubkey`. The
adapter session goes in `Authorization: Bearer`, and a NIP-98 proof
signed by that key, bound to the endpoint URL, method, and exact body
hash, goes in `Nostr-Authorization`. Clients and adapters must not log
either header's value.
- **Response:** `assertion`, `nostr_pubkey`, and `expires_at`. Under
this contract an assertion lives at most 5 minutes and never outlives
the adapter session; that cap is the adapter contract's rule, not a
relay constant. The assertion's `typ` and `aud` rules point to NIP-FI.
The assertion key must be the key that signs the NIP-42 relay login.
- **Denials:** a table of status, error code, meaning, and the client
action for each. A missing session is 401 `session_required`; missing or
repeated proof headers, a repeated `Authorization` header, multiple
session credential kinds, malformed bodies, and unknown fields are 400
`invalid_request`. 401s clear the session and return to login; 403
`authorization_denied` keeps the session and disconnects from that relay
without automatic retry; other 403s, 400, and 413 keep the session and
show the error without retry; 429, 503, and network failures retry with
bounded backoff. Adapters may return `session_required` for any invalid,
expired, or revoked credential, and clients handle both 401 codes
identically.

Agent keys are out of scope and need a separate design.

Related:
[cash-server#132756](https://github.com/squareup/cash-server/pull/132756)
implements this contract in kgoose.

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-10-03 15:12:15 -04:00
klopez4212
6cf4582002 Use native iOS navigation bars with large titles and avatars (#8052)
## Summary

Use UIKit navigation bars across iOS pages, with large titles that
collapse into the toolbar on scroll and a light native blur. Home uses
the active community name as its title and shows community and profile
avatars with centered emoji and stable loading, without flashing back to
icons. Channel headers retain the member count, tap-to-settings title,
and Huddle action. Their ultra-thin native material has a soft lower
edge and stays visible at the timeline bottom. The hidden title-layout
scroll view has its automatic edge effects disabled so it cannot add a
second backdrop.

| Expanded Home | Scrolled Home | Settings |
| --- | --- | --- |
| <img
src="https://raw.githubusercontent.com/block/buzz/47a77d3ff1d30fc74f7488c1a4427e41bbb85c4e/pr-8052--home.png"
alt="home" width="240"> | <img
src="https://raw.githubusercontent.com/block/buzz/47a77d3ff1d30fc74f7488c1a4427e41bbb85c4e/pr-8052--scrolled.png"
alt="scrolled" width="240"> | <img
src="https://raw.githubusercontent.com/block/buzz/47a77d3ff1d30fc74f7488c1a4427e41bbb85c4e/pr-8052--settings.png"
alt="settings" width="240"> |

Channel title, member count, and Huddle control:

<img
src="https://raw.githubusercontent.com/block/buzz/47a77d3ff1d30fc74f7488c1a4427e41bbb85c4e/pr-8052--channel.png"
alt="Channel navigation" width="280">

### Related issue

No matching open issue found.

### Testing

- Added causal regressions for Profile/Edit Photo native titles,
metrics-only collapse changes, and native-header suppression throughout
channel/thread reaction and action backdrops. Each regression fails when
its corresponding fix is removed.

- Mobile formatting and analysis passed. Full mobile test rerun passed:
2,622 tests, 4 skipped, plus 3 push-disabled build tests.
- Native iPhone Air regression passed: repeated title expansion/collapse
and scroll material behavior.
- Navigation and blur were accepted on the connected iPhone using the
existing profile. Simulator snapshots use real community data. The
subsequent review fixes have widget coverage; fresh physical-device
verification of Profile states, Dynamic Type changes, and message
backdrops is pending.
- Full repository `just ci` was blocked by local disk exhaustion while
compiling Rust dependencies.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-03 18:10:03 +01:00
klopez4212
33f54de2dd feat(mobile): organize community and profile settings (#8056)
## Summary

Move Invite, Appearance, and Remove community into a **Community
settings** section in the community-avatar sheet, above the existing
switcher. Keep the sheet untitled and use circle-minus for removal.

Personal Settings groups **Set status** and **Copy public key (npub)**
above an untitled card containing **Display name**, **Profile
description**, and **Edit photo**. Remove the leading icons from status,
public key, and Send identity to desktop; keep the latter in its own
untitled card. Remove the avatar status badge and top Edit action, and
rename the Theme page to **Appearance**. Opening the presence chip
triggers selection haptics; copying plays native iOS success feedback
and confirms with “Public key (npub) copied.”

### Testing

- Mobile formatting, analysis, and file-size checks passed.
- 111 affected widget tests passed; all 48 settings tests passed again
after the final labels and icon changes.
- Final release build installed and launched on a physical iPhone in the
separate Buzz Community preview, retaining its existing test account.
- Full repository `just ci` was blocked by local disk exhaustion during
Rust compilation. The full mobile suite passed (2,609 passed, four
skipped), plus three push-unconfigured tests. The presence and copy
feedback passed focused widget tests and analysis, including native iOS
success-channel coverage.

### Snapshots

Light and dark Flutter widget renders with fixture data. Images are
GitHub attachments, not committed to the repository. The
personal-settings snapshots precede the final “(npub)” label
clarification.

| Surface | Light | Dark |
| --- | --- | --- |
| Community sheet | <img
src="https://github.com/user-attachments/assets/d52a192e-bd40-4263-ac2d-05d589c7ebf2"
width="280" alt="Community sheet, light"> | <img
src="https://github.com/user-attachments/assets/8756ebe9-b6d4-4920-8fb7-1cb7ee8ef778"
width="280" alt="Community sheet, dark"> |
| Personal settings | <img
src="https://github.com/user-attachments/assets/962b98bd-e4cf-4cd1-8948-69b349390ceb"
width="280" alt="Personal settings, light"> | <img
src="https://github.com/user-attachments/assets/223bb0a8-e10e-43b1-83ea-e0955af4627a"
width="280" alt="Personal settings, dark"> |
| Appearance | <img
src="https://github.com/user-attachments/assets/334ba797-55cb-47ce-b677-0befafb7659b"
width="280" alt="Appearance, light"> | <img
src="https://github.com/user-attachments/assets/79b62503-d476-4dbc-8c75-8cee0ee37e98"
width="280" alt="Appearance, dark"> |

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-10-03 10:06:05 +01:00
Will Pfleger
8af2d91f37 refactor(relay): bind HTTP tenants through one shadow-aware helper (#8062)
Adds `bind_tenant()`, a single helper that resolves the community from
the request `Host` and records the NIP-FI shadow verdict when binding
fails. Ten protected HTTP handlers previously duplicated the Host lookup
and called `observe_unbound` in their own failure branches, so each one
had to remember the observer call. Moving those ten handlers onto the
helper makes recording the verdict part of binding itself, and
`observe_unbound` becomes private to the shadow module. Each caller
keeps its existing rejection response, so Off/Enforce behavior is
unchanged.

`bind_community()` stays directly callable. Routes exempt from NIP-FI
(invite claim, webhooks, NIP-05 and NIP-11 metadata) keep using it, and
the WebSocket and audio upgrades record their own verdicts before they
bind. A new protected HTTP handler should bind through `bind_tenant()`.

🤖 Authored by Duncan (agent) on behalf of Will.

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-10-02 19:16:28 -04:00
Will Pfleger
df3f28a2c4 feat(relay): add NIP-FI shadow mode for HTTP, WebSocket and admin (#8034)
Stack: this PR → #8062

🤖 Follows #8028 (merged).

Adds `BUZZ_NIP_FI_MODE=shadow`. The relay loads and validates the full
enforce configuration (issuers, communities, lifetimes, command
issuers), evaluates NIP-FI evidence wherever enforce would decide, and
records what enforce would have done, while every request, upgrade and
session behaves exactly as in `off`. The one approved exception is admin
disconnect: shadow verifies the command and returns `200`, where Off has
no verifier and returns `503`. It lets an operator measure the
would-deny rate, including Hosts missing from `BUZZ_NIP_FI_COMMUNITIES`,
before switching to `enforce`.

- **Mode predicates.** `NipFiMode` gains `is_off`, `restricts`,
`evaluates`, `enforces`, `denies_unconditionally` and `observes_only`,
built on two exhaustive `match` bases (`restricts`, `evaluates`);
`is_off` is a `matches!` and the rest derive from the bases, so a new
mode cannot silently fall into one side. Every call site uses them,
including the Git membership-lookup failure from #8005, which uses
`restricts()` so shadow keeps Off's body. A test scans each crate's
`src/` and fails on any `NipFiMode::<variant>` in production code
outside the predicate definitions and the env parser, which catches
`==`, `matches!` on any number of lines, `if let` and or-patterns.
- **Startup.** Shadow goes through enforce's path, so every enforce
startup refusal applies, including the required connection lifetime.
Missing-setting errors name the configured mode through one formatter
(`mode_requires`); the enforce text is byte-identical. Shadow builds the
assertion verifier and claims command replays under its own Redis
prefix, both through the production `AppState::new`.
- **HTTP and Blossom.** `admit_nip_fi_http` keeps Off's result in shadow
and additionally replays enforce in enforce's order: first the router
guard's steps (community, then assertion), then the handler's steps
(NIP-98, pairing, deny set) on the same NIP-98 proof, through
`evaluate_enforce_steps`, which enforce shares. A Host mapped in config
but missing from the communities table, with a valid assertion, records
an admit, because enforce's guard passes and its 404 is not a NIP-FI
denial. A dev-mode `X-Pubkey` identity is marked unsigned and is never
an enforce proof, so shadow records it as a `nip98` would-deny. On
bridge and Blossom routes, the strict proof check (payload tag, Blossom
`Strict`) runs as a separate pure check that consumes no replay entry
and records on its own series, so it never counts as an admission
verdict. Shadow records exactly one verdict for every identity,
community or credential refusal enforce would make, with Off's status,
body and challenge unchanged: bridge, workflows, Blossom, Git transport
and settings, GIF search and share, and invite minting record the
`community` would-deny when the Host is unmapped. Git's missing or
malformed credentials still reject before any database work, and shadow
records the enforce verdict for that failed proof. The router guard
stays transparent in shadow.
- **WebSocket, root and audio.** The upgrade check evaluates the
attached assertion once. An upgrade enforce would refuse records that
would-deny; otherwise the assertion goes into a shadow-only session
object and the upgrade returns as in Off. The assertion never reaches
the connection, the identity registries, the admission gate, terminal
frames or cancellation. Each session records at most one admission
verdict. **Pairing** is recorded on both ingresses right after a valid
NIP-42 proof, before ordinary relay policy, where enforce pairs: a key
mismatch or claimless assertion is a `pairing` denial. **The deny-set
check** runs where enforce runs it, after registration: a hit is a
`deny_set` denial, and a clean read keeps the session pending and
registered. **The admit** is recorded only when the connection is
actually admitted: on root at the AUTH commit, after ordinary policy; on
audio when the participant join transaction commits, after relay
membership, channel membership, the final ban and membership decision,
mesh routing and the join's own checks, and before publication. A NIP-42
failure, which comes before pairing, and any refusal between pairing and
the admit (ordinary policy, mesh, or a join refusal inside the join
transaction) retires the observer when the refusal is decided, before
any refusal frame, rollback or cleanup is awaited, so it leaves no
record even if the deadline passes during that cleanup. A record-only
deadline task, armed at upgrade with enforce's
`compute_session_deadline`, records `expired` when enforce would have
closed an admitted session. If the deadline passes while the session is
still pending, that is its single admission verdict, a denial with
`stage=deadline`, and a later AUTH records nothing. A deny for the key
(admin or cross-pod) records `revoked` on an admitted session; if it
arrives after the deny-set check but before the admit, including a deny
refused for capacity, the session keeps a pending-revocation mark and
records the admit followed by exactly one `revoked` end, matching
enforce's phase-independent close, and the deadline cannot take that
end. The phase, the mark and retirement change together under one
session lock. Each session records at most one end. The session holds
the socket's cancellation token for recording only: once the socket is
cancelled, no transition records anything, even while connection
references remain (a cancel fence; the token never feeds a close
action). Upgrade would-denies carry the ingress route, `ws` or `audio`.
- **Admin disconnect.** Shadow verifies the command and records the deny
entry, so later admissions record would-denies, but closes no session;
the response stays `{"disconnected": true}`. Shadow publishes cross-pod
on its own channel, `buzz:nip-fi:shadow-disconnect`, which only shadow
pods subscribe to, so no enforce pod (including older builds that know
only `buzz:nip-fi:disconnect`) acts on a shadow command. Shadow pods
also keep listening on `buzz:nip-fi:disconnect`, so their deny record
includes enforce's real disconnects. Shadow claims command replays under
`buzz:nip-fi:shadow-command:{hash}`: replays are still rejected within
shadow, and a shadow accept never uses up the enforce claim. Enforce and
Off keep the same channel, keys and close behavior.
- **NIP-11.** Shadow serves the same document as enforce, including
`limitation.federated_identity`, because clients only attach evidence to
a relay that advertises it.

## Recording

| Series | Labels | One increment per |
|---|---|---|
| `buzz_nip_fi_shadow_total` | `route` (`http`, `ws`, `audio`), `stage`,
`outcome`, `community` | decision enforce would make: an HTTP admission,
a refused upgrade, a session's NIP-FI AUTH decision, or its deadline
passing before AUTH (`stage=deadline`) |
| `buzz_nip_fi_shadow_strict_proof_total` | `route` (`bridge`,
`blossom`), `outcome` (`pass`, `rejected`), `community` | strict NIP-98
side check |
| `buzz_nip_fi_shadow_session_end_total` | `route` (`ws`, `audio`),
`reason` (`expired`, `revoked`), `community` | admitted session enforce
would have ended (admitted sessions only) |
| `buzz_nip_fi_shadow_disconnect_total` | `route` (`admin`,
`cross_pod`), `outcome` | disconnect-path event, in place of the real
disconnect, lag, capacity and poison counters |

`community` is the configured canonical URI or `unmapped`, never the raw
`Host`; an unmapped or empty Host records `stage=community,
outcome=unavailable`. A shadow pod never moves an enforce disconnect or
failure counter. Strict-proof rates use their own `pass + rejected`
total, and session-end rates divide by the `admit` count for the same
route. There is no per-verdict `info` log; a would-deny writes a `debug`
line with no token, claim or issuer. The pre-existing enforce `debug`
line for the proven NIP-98 key is shared and also fires in shadow. Admin
commands rejected for a bad header, body or proof, a replay, or a
dependency error record no shadow verdict; only capacity rejection is
counted.

## Not observed

- Handler-side path-validation exits: an invalid Git owner or repo name
on default-branch, a media path that is not a valid hash, and a Git pack
URL with a query string record nothing from the handler. The router
guard still records what enforce would refuse at the guard (for example
a missing assertion), because enforce refuses those requests before it
validates the path.
- A refusal that is not a NIP-FI decision, such as a tenant-binding 404
behind a passing guard, or an ordinary WebSocket refusal after pairing
(a ban, membership or join refusal before admission).

## Follow-ups

- A bounded `route` label per HTTP surface (bridge, Blossom, Git, …) on
`buzz_nip_fi_shadow_total`; today every HTTP verdict carries
`route=http`.
- One shared helper for the ten copied `observe_unbound` recording
hooks, stacked on this PR.

The shadow recorder and session suites and the root pairing witness run
in `just test-unit` and the `scripts/run-tests.sh` fallback; the
`AppState::new` shadow witness, which exercises the command verifier
against real Redis, runs in the `external_infra_redis` lane. NIP-FI env
tests recover a poisoned env lock so one panic cannot cascade.

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Signed-off-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
2026-10-02 18:32:17 -04:00
Luke Tornquist
fe9e2409a0 BUZZ-175: Add application-owned writer lock foundations (#7706)
## Summary

Buzz is moving database invariants from triggers and foreign keys into
application-owned transaction protocols. This PR adds the first
transition foundations while preserving all current database backstops.

- Add a shared community-write lock for single-community writer
transactions, and make deletion lifecycle transitions take the matching
exclusive lock. A supported serving transaction never spans communities.
- Add shared event-writer and exclusive replica-probe lock ordering
around the existing heartbeat publication model.
- Document the supported writer contract, reviewed backfill path, and
transition gates.
- Keep one replica-floor publication concept and remove an unrelated
reconciliation-script edit found during review. This narrows the change
rather than adding parallel protocols.

The blast radius is limited to new opt-in writer helpers plus lock
acquisition in deletion and replica probing. Existing trigger and GUC
enforcement remains authoritative, so callers can migrate in later pull
requests.

### Related issue

[BUZZ-175](https://linear.app/squareup/issue/BUZZ-175). This is the
first implementation slice from the OSC migration plan.

### Testing

No manual testing. CI covers the Rust checks and database tests added
here.

Generated with [Codex](https://openai.com/codex)

---------

Signed-off-by: tornquist <tornquist@squareup.com>
Co-authored-by: Codex <noreply@openai.com>
2026-10-02 16:53:09 -04:00
klopez4212
ea143ea64b feat(mobile): native iOS message menus and reaction sheets (#8055) 2026-10-02 20:59:05 +01:00
Will Pfleger
5a4b2d3dcc fix(desktop): show readable Claude Code model names and descriptions (#8053)
Claude Code agents' model dropdown showed raw IDs (`opus[1m]`,
`claude-fable-5-1[1m]`, `haiku`) and its effort choices showed
`low`/`xhigh`. Claude Code's ACP adapter labels config options and
choices with `name`, but Buzz read `displayName`, which no adapter
sends.

**Adapter labels and descriptions**
- `normalize_agent_models` reads `name`, keeps each model's
`description`, and uses the model option's `currentValue` as the agent's
default model (ahead of the unstable `currentModelId`).
- `parse_config_options` / `parse_option_values` read `name` for option
and choice labels, so effort shows "Low"/"Xhigh".
- The create (`PersonaModelCombobox`) and edit (`PersonaDropdownField`)
model pickers show the description as a muted second line, through both
option builders (`modelDropdownOptions` and
`buildTemplateModelDropdownOptions`).

**Generated names for full Claude model IDs**
- Claude Code's own names drop versions ("Sonnet" for
`claude-sonnet-5`). The desktop's Databricks label grammar already
parses a bare Claude ID once its wrapper is removed, so that body parse
is exposed as `generateBareModelLabel`; Databricks entry points and
outputs are unchanged.
- For the `claude` runtime, `claudeCodeModelLabel` formats full IDs and
keeps a `[1m]` suffix as "(1M context)". Short names (`opus`, `haiku`,
`opus[1m]`), unknown bracket suffixes, and IDs containing any non-ASCII
character keep the adapter's name.
- This applies to the model dropdowns in the create and edit dialogs and
the Agent defaults editor. The "Default model (…)" row appears in the
edit dialog and the Agent defaults editor; the create dialog still
requires an explicit model and shows no Default row. Model labels on
agent cards are unchanged.
- In the edit dialog, the Default row keeps the discovered label (e.g.
"Default model (Opus)") unless a global default model is set, in which
case it shows that model. When the adapter's default is its own
`default` entry (e.g. "Default (recommended)"), the row reads plain
"Default model" and keeps that entry's description.

**`models` debug command**
- The harness's readable `models` output reads option and choice labels
from `name` and the option id from `id` (falling back to `configId`), so
it no longer prints raw IDs for Claude Code. JSON output is unchanged.

| Model ID | Before | After |
|---|---|---|
| `opus[1m]` | `opus[1m]` | Opus · Opus with 1M context · … |
| `claude-fable-5-1[1m]` | `claude-fable-5-1[1m]` | Claude Fable 5.1 (1M
context) · Fable 5.1 · … |
| `claude-sonnet-5` | `claude-sonnet-5` | Claude Sonnet 5 · Sonnet 5 · …
|
| `claude-sonnet-4-6` | `claude-sonnet-4-6` | Claude Sonnet 4.6 ·
Previous Sonnet version |
| `claude-sonnet-4-6[1m]` | `claude-sonnet-4-6[1m]` | Claude Sonnet 4.6
(1M context) · Sonnet 4.6 for long sessions · … |
| `haiku` | `haiku` | Haiku · Haiku 4.5 · … |

🤖

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-10-02 19:28:59 +00:00
Will Pfleger
cc528dbe05 feat(agents): request summarized Claude thinking and label empty rows (#8051)
Claude Code agents on Opus showed Thinking rows that opened to nothing.
Opus returns no readable thinking unless Claude Code is asked for
summaries, and Buzz never asked. Sonnet returns readable thinking either
way.

**Request summaries from Claude Code.** `session_new_full` now adds
`_meta.claudeCode.options.extraArgs: {"thinking-display": "summarized"}`
for the Claude adapter. claude-agent-acp spreads `extraArgs` into the
CLI's arguments; 0.36.1, 0.60.0 and 0.66.0 all read the same shape. The
value is merged into the existing `_meta`, so `systemPrompt` and
`sessionTitle` are kept. `session_new_full` is the only place Buzz sends
`session/new`, so agent sessions and model discovery both get it.

**Only for a CLI that accepts the flag.** `--thinking-display` first
shipped in Claude Code 2.1.94, and older CLIs exit on unknown flags,
which would fail every session start. When the adapter is spawned, Buzz
runs `$CLAUDE_CODE_EXECUTABLE --version` once with a 5-second limit,
reading at most 256 bytes of output and killing its whole process group
on timeout, and sends the flag only on 2.1.94 or newer. The flag is left
off, and sessions start exactly as before, when:

- the CLI is older than 2.1.94;
- `CLAUDE_CODE_EXECUTABLE` is unset (the adapter then runs its own
bundled CLI, which Buzz can't inspect) or empty;
- the binary hangs, fails, or prints anything other than a clean
`major.minor.patch` version;
- `BUZZ_ACP_LAUNCH_PREFIX` is set, since the wrapper can change which
CLI the adapter actually runs.

 The result is logged once at debug level.

**Label rows that still have no text.** A Thinking row whose text is
empty or only whitespace keeps its header and shows a muted "No readable
reasoning tokens", with nothing to expand. This covers models or CLIs
that still return no readable thinking. If text arrives later in the
same row, it renders as an expandable section as before.
`ThoughtActivity` is the only component that draws Thinking rows.

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
2026-10-02 18:46:47 +00:00
Logan Johnson
133fb98692 fix(acp): steer running turns with edited mentions (#6132)
🤖
## Summary
Some agents can take a new message into a turn that is already running.
This is called "native steering." Before this PR, an edit that arrived
during a turn always cancelled the turn and started it again. Now the
edit is steered into the running turn, like any other new message. The
steered edit still points at the original message and its thread, so the
agent replies in the right place.

- The steer text carries the edit's route: `Edit of: …`, plus the
original's thread root.
- **Steer only within the same reply thread.** A native steer keeps the
running turn's `<context>`, so the reply goes where that `<context>`
points. The queue now records each running turn's reply thread. A
message is steered natively only when it replies in that same thread.
Under channel sessions one session spans threads, so an edit for another
thread (or another top-level message) takes the cancel-and-restart path.
Its re-prompt carries the message's own full `<context>`, with channel,
project, and profile data. The same rule applies to ordinary steered
messages, which had the same gap before this PR.
- **Per-thread sessions:** the edit steers only a turn running in the
same session as its original message. An edit in thread A is never added
to a turn running in thread B. If no turn is running in that session,
the edit waits in the queue as its own item.
- **Channel sessions** (the default): the channel has one session. A
running turn receives the edit natively only when the edit replies in
that turn's thread.
- If native steering is not available, or the transport fails or the
agent rejects the steer, the existing cancel-and-restart fallback runs.
If the agent returns another error, or the turn has already finished,
the edit goes back to the queue for normal delivery. In every case the
queued edit keeps its route.

## Details
- #4741 looks up the original message once, before the edit is queued.
This PR passes that stored route to the existing steer path, and uses
the same session the edit was queued under. No new lookup or preparation
step is needed.
- Removal, re-add, and fallback all use the existing lifecycle for
withheld steers.

### Stack
**3 of 3**. #6131 is merged; this PR is now based on `main`.

### Related issue
Part of #2540 (fixed by #6131). This PR adds the running-turn behavior.

### Testing
- `cargo test -p buzz-acp --all-targets` passes. The one test that fails
when the git setting `nostr.keyfile` is set is described in #4741.
- Tests check that the steer text carries the original's route, and that
the listener gives the steer path the same route and session it queues.
- End-to-end tests send a routed edit through the listener's steer
decision under channel sessions. An edit in the running turn's thread,
and an edit of the running top-level message, steer natively with no
cancel. An edit for thread B during a thread-A turn, and an edit of
another top-level message, send no native steer and take cancel+merge.
Removing the same-thread check makes both cross-thread tests fail.

---------

Signed-off-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-10-02 13:24:22 -04:00
Alex Rosenzweig
4f51b9e101 fix(mcp): support Goose discovery handshake (#8037)
## Summary

Goose 1.52 starts MCP connections with `server/discover`. `buzz-dev-mcp`
rejects that request with `ExpectedInitializeRequest`, preventing Goose
from loading its Buzz tools.

Upgrade the tool server to rmcp 3.4.1 and adopt the renamed SDK types.
Subprocess tests exercise discovery and legacy initialization, tool
listing, file reads/edits, invalid arguments, connection survival, and
EOF shutdown. Include the server in both Rust unit-test runners and make
the cancellation regression approve its shell call before testing
cancellation.

The native agent retains its independent rmcp 1.x client. Cargo also
unifies the existing 3.x dependency used by the mesh smoke harness.

## Validation

- Normal `git push` passed all hooks, including Rust tests, Tauri
checks, and repository policy checks.
- `just ci` passed on the final stack: repository checks, Rust and Tauri
tests/lint, desktop tests/build, web build, and mobile checks/tests.
- MCP: 78 existing tests and two subprocess lifecycle tests passed; the
discovery regression fails with the old SDK.
- All 54 native-agent regressions passed on the final stack, including
cancellation of a real MCP shell process.
- Previously exercised unmodified Goose 1.52 and 1.47 with Sandpit and
the real tool server. Allowed workspace operations and permitted network
traffic succeeded; disallowed file and network operations were denied.
- Live staging desktop check with Goose 1.52: the reply appeared in
Buzz, an allowed request returned HTTP 200, and a disallowed request
returned CONNECT 403.

## Stack

1. **#8042 → `main`**: deterministic handoff regression.
2. **This PR → #8042**: Goose MCP discovery compatibility.

Merge the lower PR first, then retarget this PR to `main`. This diff
contains only the compatibility change and its tests; the relay build
repair is already on `main` in #8036.

---------

Signed-off-by: Alex Rosenzweig <arosenzweig@squareup.com>
2026-10-02 11:24:25 -05:00