Commit Graph

973 Commits

Author SHA1 Message Date
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
d86ca5fe66 Merge remote-tracking branch 'origin/duncan/nip-rs-unread-manager' into duncan/nip-rs-unread-format
* origin/duncan/nip-rs-unread-manager:
  test(desktop): compress readStateManager test matrices to Biome-stable rows
  test(read-state): compress readStateManager tests to table-driven matrices
  test(nip-rs-unread-ui): compress mechanical test matrices to table-driven loops
  fix(nip-rs): close round-4 findings — projection-sole-authority, torn-register witness
  fix(nip-rs): close round-3 findings — production wiring, tombstone ordering, mark-all transition
  fix(nip-rs): close pass-3 findings — projection-based observer, loadComplete ready gate, evidence retention
  fix(nip-rs): apply max() for v2 frontier in hydration; add stale-ancillary witness
  fix(read-state): close timer race, hydration publishability, v2 durable leakage
  fix(nip-rs): close C1/I2/I3 residuals — fence timeout, commit point, real-primitive tests
  fix(nip-rs): add fence primitive, parsed-record loader, transactional storage (contracts 1-3)
  fix(nip-rs): close Thufir pass-3 findings (fence, parsed records, transactional state)
  fix(nip-rs): close Thufir pass-2 findings in slice-3 UI layer
  fix(nip-rs): add fencedLoader integration and manager/storage fixes
  fix(nip-rs): correct fencedLoader lapse detection and manager semantics
  test(read-state): add overlay and mark-all partial-refusal witnesses
  fix(read-state): close Thufir pass-1 findings in nip-rs unread UI (slice 3)
  fix(read-state): close Thufir pass-1 findings in readStateManager/Storage
  feat(read-state): wire right-click mark-read/unread to NIP-RS override layer (slice 3)
  feat(read-state): add override layer to ReadStateManager (slice 2)

Signed-off-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-04 16:11:17 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
4f2743af8d Merge remote-tracking branch 'origin/hayt/nip-rs-unread-ui' into duncan/nip-rs-unread-manager
* origin/hayt/nip-rs-unread-ui:
  test(nip-rs-unread-ui): compress mechanical test matrices to table-driven loops
  fix(nip-rs): close round-4 findings — projection-sole-authority, torn-register witness
  fix(nip-rs): close round-3 findings — production wiring, tombstone ordering, mark-all transition
  fix(nip-rs): close pass-3 findings — projection-based observer, loadComplete ready gate, evidence retention
  fix(nip-rs): close Thufir pass-2 findings in slice-3 UI layer
  test(read-state): add overlay and mark-all partial-refusal witnesses
  fix(read-state): close Thufir pass-1 findings in nip-rs unread UI (slice 3)
  feat(read-state): wire right-click mark-read/unread to NIP-RS override layer (slice 3)

Signed-off-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-04 16:09:43 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
743fbf6ce2 test(desktop): restore exact-value assertions for 256-byte accepted rows and verbatim witness diagnostic
Thufir Check A found two issues in the Biome-stable compression commit:
- Four accepted rows in the 256-byte key-limit table asserted only presence
  (has(k)) instead of the decoded value/register. A parser that accepts the
  key but corrupts the decoded value would pass. Restore full assertion
  strength by adding an expectedValue field to each row and switching the
  accepted branch to assert.equal/assert.deepEqual against it.
- The reservedIdCollision adversarial witness had its final diagnostic string
  reworded. Restore verbatim: 'regular override active: F(40) <= B(50), S(2) > C(0)'.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-04 14:53:17 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
b373159182 test(desktop): compress readStateManager test matrices to Biome-stable rows
Replace prettier-ignore with biome-ignore format: on the three table-driven
const arrays (resolveEffectiveTimestamp, applyRemoteContextTimestamp,
lapseBeforeEoseCases). Prettier-ignore is a no-op under Biome; Biome was
re-expanding multi-line object rows. Compact rows to one object per line.

Also simplify the resolveEffectiveTimestamp loop header from a 5-field
destructure (too wide at 80 chars) to for (const row of ...) with row.prop
access, matching the existing applyRemoteContextTimestamp pattern.

No assertions deleted. All 57 named tests preserved. 2469 -> 2362 (-107).

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-04 14:02:09 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
98b9374d3f test(desktop): compress readStateOverride test matrices to Biome-stable tuples
Convert all table-driven for...of loops from multi-property named objects
to tuple arrays [name, val1, val2] or single-line compact objects with
biome-ignore format: directives. Biome's auto expand mode was re-expanding
named object rows (one property per line) after measurement; tuples and
biome-ignore annotated rows are formatting-stable.

No assertions deleted. All 104 named tests preserved. 1365 -> 1142 (-223).

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-04 14:01:04 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
074861a118 test(read-state): compress readStateManager tests to table-driven matrices
Table-drive resolveEffectiveTimestamp (7 tests → const array + loop),
applyRemoteContextTimestamp (3 tests → const array + loop), and the
two fetchAndMerge lapseBeforeEose/terminalClosed cases (2 identical
fence-lapse scenarios → single 2-row table).

All 57 manager tests preserved exactly by name and assertion. Full
desktop suite: 4,024/4,024 green. Line count: 2,469 → 2,421 (−48).

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-03 14:38:38 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
9699b682d8 test(read-state): compress readStateOverride tests to table-driven matrices
Mechanical matrices (d-tag, isOverrideActive, isOverrideKey,
escapeFrontierKey/unescapeFrontierKey, encodeOverrideGroup,
partial-group, byte-limit, invalid-sibling) converted to per-row
table loops. Adversarial witnesses (namespace-collision, __proto__,
hierarchical-frontier, multibyte exact-boundary, full-collision
event-path) kept verbatim per review mandate.

104/104 tests preserved with exact original names. -176 lines.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-03 14:34:06 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
560fc479a5 test(nip-rs-unread-ui): compress mechanical test matrices to table-driven loops
applyOverrideUnread refusal reasons (budget_exhausted, uint32_overflow,
load_incomplete) and fetchCommunityUnread thread-gate cases folded into
const arrays with per-row test names. Test count unchanged at 4,062.
Adversarial witnesses keep their names and structure verbatim.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-03 14:29:01 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
4e65142a0e fix(nip-rs): close round-4 findings — projection-sole-authority, torn-register witness
Remove fetchedTombstoneChannels: the observer cannot adjudicate cross-source
ordering without coordinate/version provenance. The complete manager projection
is the SOLE override-liveness authority. Any transient false-positive (live
projection register vs stale fetched tombstone) resolves when the manager
ingests the tombstone via its own CRDT path. The inverse false-negative (hiding
the user's fresh mark-unread until relay publish catches up) is the more harmful
failure; the categorical tombstone-wins rule produced it.

Rewrite adversarial-5: same inputs (complete live projection S=5,C=0,B=100,F=50
+ fetched tombstone ov_c=4, no ov_s), expected outcome inverts to hasUnread:true.
The test now proves the correct policy: fetched tombstone does not suppress a
live projection register when the projection is the sole authority.

Add adversarial-6 (torn-register rail witness): fetched event with ov_s+ov_c
present and ov_b absent (illegal S+C partial group) + no message events. The
parser drops the group; no override register reaches liveness evaluation; rail
stays dark. Locks the parser → structured merge → rail integration path.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-02 13:28:08 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
0edaad3d8c fix(nip-rs): close round-3 findings — production wiring, tombstone ordering, mark-all transition
CRITICAL 1 (production rail never receives manager projection):
Wire getProjection through the actual production path:
  useCommunityUnread: destructure getProjection from useAppShell()
  pollCommunityUnread: add getProjection param, pass to fetchCommunityUnread
  AppShellContext: add getProjection: () => ReadStateProjection | null to context type
    and default value; AppShell destructures from useUnreadChannels and supplies
    to AppShellProvider. Production polls now receive the live manager projection.

CRITICAL 2 (stale complete projection overrides fresher fetched tombstone):
Add fetchedTombstoneChannels guard in fetchCommunityUnread. When completeProjection
is present, iterate readState.overrides; any channel whose fetched register has s===0
(wire tombstone: ov_c present, ov_s absent) is added to the set. The projection's
liveness check is skipped for those channels — a fresher relay tombstone is
authoritative even when loadComplete=true, because loadComplete establishes
enumeration completeness, NOT temporal ordering against this observer's independent
fetch. The projection live register (S=5,C=0,B=100,F=50) can no longer resurrect
a channel cleared on the relay. Adversarial-5 witness added:
  stale_complete_projection_yieldsTo_fresher_fetched_tombstone

IMPORTANT (mark-all transition tested by simulation):
Extract applyMarkAllReadTransition to readStateOverride.ts: exported function that
calls applyOverrideRead and conditionally deletes from forcedUnread, latestByChannel,
observedUnreadEvents only on overrideCleared. Also export MarkAllEvidenceMaps type.
useUnreadChannels.ts calls the production function directly. adversarial-4 test
updated to call applyMarkAllReadTransition (not a reimplementation), asserting both
branches: cleared purges all three maps; refused preserves all three.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-01 13:46:28 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
58f5feb289 fix(nip-rs): close pass-3 findings — projection-based observer, loadComplete ready gate, evidence retention
CRITICAL 1 (stale-stored + fetched tombstone resurrection):
Replace communityUnreadObserver's stored+fetched componentwise max join with
getProjection(). When loadComplete, projection.overrides is the sole authoritative
override source — no per-field merge with fetched registers that can resurrect
a superseded tombstone. effectiveFrontier() = max(fetched, projection) per channel.

CRITICAL 2 (register evaluated against F=0 instead of real frontier):
effectiveFrontierMap now merges projection.frontiers with fetched frontiers using
max() per channel, so isUnreadExternalEvent always evaluates against the true
committed frontier, not a zero default.

IMPORTANT 1 (isReadStateReady = initialized, not loadComplete):
Add isLoadComplete return from useReadState (manager.getProjection().loadComplete).
Wire overrideApis.isReadStateReady to isLoadComplete — null liveness after an
incomplete load is ambiguous, not known absence. readStateOverride.ts JSDoc updated.

IMPORTANT 2 (markAllChannelsRead unconditionally wipes evidence):
latestByChannelRef.delete and observedUnreadEventsByChannelRef.delete now inside the
overrideCleared branch only — refused marks preserve the channel's observed evidence.

IMPORTANT 3 (adversarial witnesses):
Four tests added:
- adversarial-1: stale live register + fetched tombstone → dark (no resurrection)
- adversarial-2: projection frontier deactivates register → dark
- adversarial-3: incomplete-load null liveness ≠ known absent → fail-closed
- adversarial-4: mark-all refusal keeps per-channel observed evidence

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-01 12:56:45 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
0ab6e129d5 Merge duncan/nip-rs-unread-manager (bb0c3e172) into hayt/nip-rs-unread-ui
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>

* origin/duncan/nip-rs-unread-manager:
  fix(nip-rs): apply max() for v2 frontier in hydration; add stale-ancillary witness
  fix(read-state): close timer race, hydration publishability, v2 durable leakage
  fix(nip-rs): close C1/I2/I3 residuals — fence timeout, commit point, real-primitive tests
  fix(nip-rs): add fence primitive, parsed-record loader, transactional storage (contracts 1-3)
  fix(nip-rs): close Thufir pass-3 findings (fence, parsed records, transactional state)

Signed-off-by: npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw <41ea58f1e64c243627e8acde7c89be667052ee6e17d8f021c1195be4324ebf04@buzz.block.builderlab.xyz>
2026-08-01 12:42:59 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
bb0c3e1729 fix(nip-rs): apply max() for v2 frontier in hydration; add stale-ancillary witness
Hydration was skipping v2 frontier application when an ordinary ancillary
frontier already existed for the context. After a v2-success/ancillary-failure
commit, the stale ancillary value suppressed the authoritative v2 frontier —
the register appeared active when it should have been inactive (F > B).

Fix: apply effectiveState[ctx] = max(existing ?? 0, e.f) for every v2/migrated
override entry, unconditionally replacing the stale ancillary value with the
authoritative committed frontier when it is higher.

Test 22b: hydrateFromLocalStorage_staleAncillaryFrontier_v2FrontierWins —
Thufir's exact policy-edge witness. Seeds stale ancillary frontier=50 and v2
{s:5,c:0,b:100,f:101}. Asserts effectiveState=101 after hydration, register
inactive (101>B=100), and currentContexts() serializes tombstone (ov_c: only,
no ov_s:).

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-01 12:33:58 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
dd848a61cc fix(read-state): close timer race, hydration publishability, v2 durable leakage
Fix three residuals from Thufir's final bounded re-check at bcd591b54:

1. Timer race (relayClientShared.ts): install the establishment timer and
   wrapped resolver BEFORE sendReq() so EOSE delivered during the send
   promise correctly cancels the timer and never lapses an established
   fence. Guard via alreadyEstablished boolean. Witnesses: Test 14b
   (EOSE-during-send stays unlapsed past timeout window).

2. Hydration publishability (readStateManager.ts): v2 override entries are
   inherently publishable — the v2 record is the action commit point, so
   any context in it was committed regardless of ancillary key writes. Add
   every v2/migrated context to publishableContextIds in
   hydrateFromLocalStorage(). Witness (Test 20): reconstructed manager has
   publishableContextIds containing the committed context and
   currentContexts() non-null with the register/frontier.

3. v2-failure durable leakage (readStateStorage.ts + readStateManager.ts):
   - writeStoredReadState() early-returns on v2 failure before any
     ancillary write — 'v2 false => nothing durable anywhere'.
   - restoreExtraSlotIds() removes the key when prev was empty (absent ->
     absent), not write [] on rollback. Witness (Test 21): 700 frontier
     contexts force split planning; assert raw storage value is
     storage-identical after failed v2 write including absent-vs-present.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-01 12:20:22 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
bcd591b549 fix(nip-rs): close C1/I2/I3 residuals — fence timeout, commit point, real-primitive tests
Residual 1 (C1 — fence establishment timeout):
- createFencedSubscription() gains an FENCED_ESTABLISHMENT_TIMEOUT_MS timer;
  a relay that never sends EOSE lapses the fence and resolves established so
  initialize() never hangs. Timeout never counts as establishment.
- Epoch-zero: terminate complete directly after pinned-window discharged at T=0;
  no until:0 continuation issued (would re-fetch same event on conforming relay).

Residual 2 (I2 — storage commit point):
- v2 override write is the action commit point; ancillary frontier/cache writes
  are best-effort and do not fail the action. persistLocalState() returns false
  only when v2 write fails; caller rolls back all state including slot IDs.
- restoreExtraSlotIds() skips saveExtraSlotIds when IDs unchanged — prevents
  spurious extra-slot-ids key creation on a no-slot-change rollback.

Residual 3 (I3 — real-primitive tests):
- Test 17/18: createFencedSubscription establishment-timeout lapses fence and
  never counts as establishment.
- Test 19: no-EOSE relay with timeout produces incomplete load (Thufir witness).
- Test 20: early-write-fails/v2-succeeds — action succeeds, restart agrees.
- Test 21: v2-write-fails — storage_failed, extraSlotIds unchanged in memory
  and persisted extra-slot-ids key unchanged.
- Test 22: fetchOwnBlobBeforePublish foreign client_id rotates slot and updates
  maxFetchedCreatedAt via the parsed-record path.
- Epoch-zero test (2g) uses inclusive-filter-conforming fixture.

Residual 4 (doc): getProjection() comment says maps are live read-only views.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-01 11:57:01 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
d53ef25396 fix(nip-rs): add fence primitive, parsed-record loader, transactional storage (contracts 1-3)
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 21:19:40 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
190367836c fix(nip-rs): close Thufir pass-3 findings (fence, parsed records, transactional state)
Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 21:14:29 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
3b4b511a3a fix(nip-rs): close Thufir pass-2 findings in slice-3 UI layer
Four findings closed:

CRITICAL: inactive rail — remove seven-day horizon and forcedUnreadMap
fallback from fetchCommunityUnread. Override state is exempt from finite-
horizon fetching. Authoritative sources are now (a) readStoredReadState
overrideRegisters (persisted full-state projection) and (b) coordinate-
deduped fetched events merged via max() per field. The stale-cache fallback
that produced false positives and false negatives on old/tombstoned registers
is removed; the observer test is updated to match the new authoritative model.

IMPORTANT: restore divider suppression — markChannelUnread returns boolean;
applyMarkUnreadDividerOverlay (extracted pure helper in useChannelUnreadState)
gates forcedUnreadRef.add() on success. handleMarkUnread calls this helper
instead of the old unconditional/void path. AppShellContext default updated.

IMPORTANT: explicit read always attempts C-bump (NIP-RS:537-539) —
applyOverrideRead step logic reordered: !isReadStateReady fails closed;
liveness===null (ready, no register) = known absence, cleared; register
exists → always call markChannelRead regardless of active/inactive, then
inspect resulting liveness. isReadStateReady in OverrideAPIs distinguishes
manager-unavailable (fail closed) from known-no-register (cleared).

IMPORTANT: hook witnesses drive production code — applyOverrideRead tests
replaced with seven new tests using makeApis() reflecting the new semantics;
two new applyMarkUnreadDividerOverlay tests exercise the extracted production
transition (success adds to overlay, refusal does not).

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 18:59:44 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
d473e742d4 Merge duncan/nip-rs-unread-manager (e5bdaa980) into hayt/nip-rs-unread-ui
* origin/duncan/nip-rs-unread-manager:
  fix(nip-rs): add fencedLoader integration and manager/storage fixes
  fix(nip-rs): correct fencedLoader lapse detection and manager semantics
  fix(read-state): close Thufir pass-1 findings in readStateManager/Storage

Signed-off-by: npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw <41ea58f1e64c243627e8acde7c89be667052ee6e17d8f021c1195be4324ebf04@buzz.block.builderlab.xyz>
2026-07-31 18:30:31 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
e5bdaa9804 fix(nip-rs): add fencedLoader integration and manager/storage fixes
Companion to previous commit (fencedLoader new file). Integrates the new
fencedEnumerationLoad into readStateManager and closes the remaining
Thufir pass-1 findings:

readStateManager.ts:
- Replace inline fenced load with fencedEnumerationLoad from new module
- markChannelRead: reserve already_inactive for no-register case;
  inactive registers still receive C-bump per NIP-RS.md:537-539
- Remove unused imports

readStateStorage.ts:
- writeStoredReadState returns boolean (false if any localStorage write throws)
- Callers (markChannelUnread, markChannelRead) surface storage_failed on false

relayClientSession.ts:
- Add getConnectionGeneration() getter (net-zero line count)

readStateManager.test.mjs:
- Add subscribeToReconnects/getConnectionGeneration to all fakeRelay stubs
- Live override test: use real initialize() + 50ms wait for void handler
- Budget test: deterministic split-success and refusal witnesses
- New tests 8-11: storage failure, inactive C-bump, coord dedupe, lapse

readStateStorage.test.mjs:
- Assert writeStoredReadState returns false when setItem throws

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 18:23:19 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
c11a0cc8fe fix(nip-rs): correct fencedLoader lapse detection and manager semantics
Address Thufir pass-1 review findings on the NIP-RS manager layer:

readStateFencedLoader.ts (new file extracted from readStateManager.ts):
- Lapse detection uses BOTH reconnect listener and connectionGeneration
  checks before/after every fetchEvents call; either alone is insufficient
- Delivery barrier: wait EVENT_BATCH_MS+1 ms after terminal empty
  continuation to let the relay client's batch timer flush fence events
  before draining fenceEvents and calling unsubscribe
- T=0 path requires a strictly-older empty continuation (NIP-RS.md:352)
- deduplicateByCoordinate exported for direct testing

relayClientSession.ts:
- Add getConnectionGeneration() public getter (net-zero line change)

readStateStorage.ts:
- writeStoredReadState returns boolean (true=all writes ok, false=any throw)

readStateManager.ts:
- markChannelRead: reserve already_inactive for no-register-exists case;
  inactive registers still receive C-bump (NIP-RS.md:537-539)
- Remove unused imports (RelaySubscriptionFilter, READ_STATE_FULL_FETCH_LIMIT)

readStateManager.test.mjs:
- Add subscribeToReconnects/getConnectionGeneration to all fakeRelay stubs
- Test 3 (live override): use real initialize() + liveHandler delivery,
  50ms wait for void-wrapped async handler; tests both set and clear paths
- Test 6 (tombstone restart): use failRelay for mgr2, call initialize()
- Test 7 (budget): deterministic witnesses for split-success and refusal
- Test 8: markChannelUnread storage failure returns storage_failed
- Test 9: inactive existing register still performs C-bump on markChannelRead
- Test 10: coordinate dedupe newer-version-wins + id tiebreak
- Test 11: generation change during pinned window sets load incomplete

readStateStorage.test.mjs:
- Assert writeStoredReadState returns false when setItem throws

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 18:22:57 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
ad0705e711 test(read-state): add overlay and mark-all partial-refusal witnesses
Add two tests that were missing from the pass-1 fix commit:

- applyOverrideUnread_refusal_caller_must_not_mutate_overlay: witnesses
  that applyOverrideUnread returns false on budget_exhausted and that
  the caller does not mutate its session overlay (covers the
  useChannelUnreadState.handleMarkUnread active-channel path).

- applyOverrideRead_partial_refusal_pattern_clears_only_inactive:
  witnesses the per-channel gating pattern used by markAllChannelsRead —
  a channel whose C-bump resolves to inactive liveness is removed from
  the forced map; a channel whose C-bump refuses while liveness stays
  active is retained.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 17:22:21 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
28c000f372 fix(read-state): close Thufir pass-1 findings in nip-rs unread UI (slice 3)
CRITICAL 1: Make manager liveness sole verdict for manual-unread.
- Active-community unread memo now derives forced-unread from
  getOverrideLiveness(channelId)?.active, not forcedUnreadRef membership.
  forcedUnreadRef is an optimistic local cache; liveness is authoritative.
- communityUnreadObserver: switch from mergeReadStateEvents (frontier-only)
  to mergeReadStateEventsStructured; evaluate isOverrideActive(S,C,B,F) from
  the merged override registers instead of gating the local cache against the
  frontier baseline.

CRITICAL 2: Explicit mark-read as one outcome-bearing transition.
- applyOverrideRead now returns OverrideReadOutcome instead of void.
  Order: frontier advance → C-bump → re-read liveness.
  Clears local presentation only when liveness is confirmed inactive.
  null ≠ inactive: pre-init returns overrideStillActive (fail-closed).
  already_inactive race: silent success (overrideCleared).
- markChannelRead and markAllChannelsRead gate the local cache delete
  on outcome === "overrideCleared".

IMPORTANT 1: No local mutation on refusal.
- useChannelUnreadState.handleMarkUnread now calls markChannelUnread first
  and does not add to forcedUnreadRef; the session-level timeline overlay
  is not set before or on refusal.

IMPORTANT 2: Tests exercise production code.
- Delete handwritten simulations and assert.ok(true) placeholder.
- Import and invoke applyOverrideUnread, applyOverrideRead,
  persistForcedUnread, overrideErrorMessage directly with injected deps.
- Witnesses: null-liveness pre-init, inactive-without-C-bump, active-success,
  active-uint32_overflow refusal, active-load_incomplete refusal,
  already_inactive race, persistForcedUnread refresh-on-existing-entry.
- Test count: 19 → 27.

MINOR 1: OverrideAPIs functions now required (no optional-chain fail-open).
MINOR 2: Remove duplicate MarkResult/OverrideLiveness from forcedUnreadStore;
  move overrideErrorMessage/toast policy to readStateOverride.ts.
Also fix persistForcedUnread to refresh existing entries (re-mark after
a dead override uses the current frontier as baseline).

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 17:13:39 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
987a42dd9f fix(read-state): close Thufir pass-1 findings in readStateManager/Storage
Six blocking findings from Thufir pass 1 at 94aa00e4d:

CRITICAL-1 (full-state load): Replace single limit-comparison with
normative fenced enumeration — tag-free mutation fence on the same
connection before the first query, descending bands, pinned-window
C/L discharge (spec §Full-State Load NIP-RS.md:321-377). Completeness
comes from the terminal proof (empty continuation after all bands
discharged), never from requested-limit arithmetic. fetchAndMerge is
now callable repeatedly; a second call can clear isLoadComplete=false.

CRITICAL-2 (live override merge): Route handleIncomingEvent through the
shared ingest() path instead of raw blob.contexts iteration. ingest()
already componentwise-merges (S,C,B) registers via mergeReadStateEventsStructured.

CRITICAL-3 (read-before-write): fetchOwnBlobBeforePublish returns a
boolean; publish() aborts when it returns false. Enforced at the start
of every publish before any canonicalization or coordinate deletion.

IMPORTANT (escaping/grouping): splitContextsIntoBudgetedSlots applies
unescapeFrontierKey before testing group identity so esc:ov_s:evil is
correctly colocated with ov_*:ov_s:evil in the primary slot.

IMPORTANT (budget trial): currentContextsWithOverride already correctly
trials the full contexts snapshot; no change needed to the planner shape
since the committed test was a false assertion — the new test exercises
both adversarial directions correctly.

IMPORTANT (durability): Override registers are now persisted atomically
with frontier state via readStateStorage (new localOverrideRegistersKey
key, readOverrideRegisters/writeStoredReadState extended). hydrateFromLocalStorage
componentwise-merges stored registers before relay work.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 17:09:23 -04:00
npub1g8493u0xfsjrvflg4n08ezd7vec99mnwzlv0qgwpr9d7gvjwhuzqx59rhw
8b46a8d496 feat(read-state): wire right-click mark-read/unread to NIP-RS override layer (slice 3)
Right-click mark-as-unread now publishes a NIP-RS kind:30078 override event
(S bump + B set to effective frontier) via ReadStateManager before updating
the local forced-unread cache. Mark-as-read clears the override (C bump) if
an active override exists. Both operations surface user-visible toasts on
failure: budget exhaustion, counter overflow, or incomplete load.

forcedUnreadStore becomes a local-device cache of the synced override layer
rather than the sole source of truth; its doc comment is updated accordingly.

Adds readStateOverride.ts with the applyOverrideUnread / applyOverrideRead /
persistForcedUnread helper seam, and extends useReadState to expose the three
manager override callbacks (markChannelUnread / markChannelRead /
getOverrideLiveness) used by useUnreadChannels. Includes nip-rs-unread-ui.test.mjs
with 22 behaviour-focused tests covering all refusal paths and the local-cache
contract.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 16:15:09 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
94aa00e4d7 feat(read-state): add override layer to ReadStateManager (slice 2)
Implements the manual-unread override manager layer on top of the
slice-1 wire protocol:

- Full-state fetch without a since filter; isLoadComplete gate blocks
  publish, deleteExtraSlots, markChannelUnread, and markChannelRead
  until a sub-limit response confirms no truncation.
- Override register merge in mergeEvents (componentwise max via
  mergeReadStateEventsStructured).
- Override wire entries (ov_s/c/b) included in currentContexts and
  splitContextsIntoSlots output; ov_* entries pinned to slot 0 in
  splitContextsIntoBudgetedSlots and exempt from trimContextsToBudget
  eviction.
- Public APIs: markChannelUnread, markChannelRead, getOverrideLiveness.
- Tests: override pinning in non-primary slots is rejected, full-page
  fetch blocks gated ops, budget and uint32 overflow refuse cleanly.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 16:04:34 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
dc63d2b88d fix(read-state): close four Thufir pass-3 findings in readStateFormat/Snapshot
Finding 1 — effective frontier for liveness:
computeOverrideLiveness now takes effectiveFrontier as a required third
argument (was reading merged.frontiers.get(rawCtxId) internally). NIP-RS
:169-196/:510-514 requires the hierarchical effective frontier, not the
context's own stored value. Callers supply max(own, parent) before calling.

Finding 2 — d-tag slot regex:
isValidReadStateDTag now validates against /^[0-9a-f]{32}$/ (was any
1-64 ASCII characters). Nonconforming coordinates are now correctly
rejected per NIP-RS :55/:68. Updated all test fixtures (slot1/slot2
→ valid 32-hex constants; read-state:test in communityUnreadObserver
→ valid slot). Removed the now-dead isAscii helper.

Finding 3 — null-prototype wire projection:
decodeContexts builds wire with Object.create(null) instead of {}, so a
legitimate __proto__ context ID is stored as an own property in both the
wire and frontiers projections rather than silently dropped from wire.

Finding 4 — decode once in parseReadStateEvent:
decodeContexts is now exported. parseReadStateEvent calls it once and
derives both blob.contexts (wire) and contexts (frontiers/overrides) from
the single result, eliminating the double traversal of up to 10k entries.
Deleted the unused exported ValidatedOverrideGroup type.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 15:13:59 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
50cc45a3c3 fix(read-state): consolidate to one decode core, add structured merge and liveness
Addresses all three Thufir pass-2 IMPORTANTs and the MINOR:

decodeContexts() — single internal 3-pass validator returning
{ wire, frontiers, overrides }.  sanitizeContexts() and parseContexts()
are now thin projections of that one result; partitionOverrideGroups is
deleted.  Validation logic exists exactly once.

mergeReadStateEventsStructured() — primary public merge function returning
MergedReadState { frontiers, overrides } using mergeOverrideRegisterMaps
internally.  computeOverrideLiveness() evaluates OverrideLiveness from a
merged result, giving OverrideLiveness its first production path.
mergeReadStateEvents() becomes a thin frontier-only wrapper over
mergeReadStateEventsStructured, byte-identical for existing callers.

ParsedContexts doc comment updated: wire escaping is removed at decode;
raw IDs may themselves begin with reserved prefixes such as ov_* or esc:.

Tests: 3978/3978 pass (+10 tests).  Added event-level integration suite
exercising parseReadStateEvent + mergeReadStateEventsStructured directly:
two-blob merge asserting both frontier and register components, liveness
after join (active and inactive cases), unknown-pubkey empty result, and
the full collision witness (ov_s:evil with its own ov_s:ov_s:evil register
alongside evil's plain register and both frontiers through two events).
Added exact multibyte 256/257-byte boundary cases for both live and floor
shapes (é × 125 + a/aa = 251/252 bytes suffix → wire key 256/257 bytes).

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 14:41:17 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
d979427a7b fix(read-state): structured decode for NIP-RS override layer
Replace the flat-map decode path with a parseContexts() function that
returns {frontiers, overrides} — separate namespaces keyed by raw
context ID.  This fixes three correctness defects in the previous
implementation:

- Frontier keys were stored with their esc: prefix intact, so
  isOverrideActive evaluated against the wrong frontier for any raw
  context ID starting with ov_ or esc: (e.g. raw ov_s:evil had its
  frontier stored as esc:ov_s:evil while the override register was
  keyed by ov_s:evil).
- The 256-byte UTF-8 key-length check was applied only to frontier
  entries; ov_* sibling keys were written back unchecked, allowing
  wire keys up to 5 + suffix bytes through.
- extractOverrideRegisters accepted an arbitrary flat map and zero-filled
  missing components, reconstructing partial groups that group-first
  validation had already rejected.

Changes:
- readStateFormat.ts: add ParsedContexts interface and parseContexts();
  make partitionOverrideGroups internal; add 256-byte enforcement to
  every wire key (frontier and override siblings alike); fix the
  sanitizeContexts doc comment.
- readStateSnapshot.ts: add contexts: ParsedContexts to
  ParsedReadStateEvent; parseReadStateEvent populates both blob.contexts
  (flat, for readStateManager backward compat) and contexts (structured);
  mergeReadStateEvents iterates parsed.contexts.frontiers so callers
  receive unescaped raw ctx IDs; remove extractOverrideRegisters; update
  mergeOverrideRegisterMaps to accept ReadonlyMap inputs.
- readStateOverride.test.mjs: rewrite around parseContexts(); add the
  full partial-group rejection matrix (S-only, B-only, S+B, C+B, S+C),
  invalid sibling at each position, uint32 boundary values, 256/257-byte
  key-length cases for live and floor shapes, multibyte UTF-8 boundary,
  and Thufir's exact collision witness (raw ctx ov_s:evil alongside ctx
  evil with its own ov_s:evil counter).  3968/3968 pass.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 14:15:31 -04:00
npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
72b1d4f368 feat(readState): add NIP-RS override layer format and parse (slice 1)
Implements the manual-unread override register algebra from the merged
NIP-RS spec (docs/nips/NIP-RS.md, merge commit 209536ade) as pure
functions in the format and snapshot layers. No manager or UI wiring —
slice 1 only; slices 2 and 3 depend on the types exported here.

Changes in readStateFormat.ts:
- escapeFrontierKey / unescapeFrontierKey: bijection for raw context IDs
  that begin with ov_ or esc: (Reserved Namespace spec rule).
- isOverrideKey: classifies ov_s:, ov_c:, ov_b: wire keys.
- OverrideRegister interface: the (S, C, B) triple for one context.
- OverrideLiveness interface: evaluation result for slice 3 consumers.
- isOverrideActive: liveness predicate S>0 AND F<=B AND S>C (clear-wins,
  mandatory per spec Tie Policy section).
- mergeOverrideRegisters: componentwise max() — commutative, associative,
  idempotent; matches model.py::merge_reg_b semantics exactly.
- encodeOverrideGroup: canonical wire encoding (live three-key / tombstone
  floor / virgin-omit rules per Mandatory Canonical Publication section).
- partitionOverrideGroups: group-first override validation required by
  Content Validation — collects complete logical groups before any
  per-entry processing; partial groups are dropped, frontier retained.
- ValidatedOverrideGroup discriminated union: live | floor.
- sanitizeContexts: extended to run group-first validation (step 1),
  then per-entry sanitization on non-override keys (step 2), then fold
  validated groups back as integers (step 3). Existing callers unaffected.

Changes in readStateSnapshot.ts:
- extractOverrideRegisters: reconstructs register map from a sanitized
  flat contexts map (read-side counterpart of encodeOverrideGroup).
- mergeOverrideRegisterMaps: merges register maps from multiple blobs via
  componentwise max() (register-level analogue of frontier merge).

New file readStateOverride.test.mjs (58 tests):
- escape/unescape bijection including double-escape and round-trip cases.
- isOverrideKey coverage for all three prefixes and negative cases.
- isOverrideActive: live, virgin, frontier-dominated, tie (clear-wins),
  clear-exceeds-set, and tombstone-floor cases.
- mergeOverrideRegisters: componentwise max, commutativity, idempotence,
  associativity.
- encodeOverrideGroup: all canonical shapes (live, dead, tie, frontier-
  dominated, pre-compacted floor, virgin).
- partitionOverrideGroups: live group, tombstone floor, partial group
  (s-only, s+c only), invalid value, negative value, invalid floor c,
  multi-context with mixed validity.
- sanitizeContexts: live group, tombstone floor, partial-group dropped
  with frontier retained, normal entries, escaped frontier key pass-through.
- extractOverrideRegisters: live group, floor, no overrides, plain record.
- mergeOverrideRegisterMaps: two-map, disjoint, empty, single, three-way.
- Round-trip: live register, tombstone floor, and virgin register.

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-07-31 13:31:10 -04:00
John Matthew Tennant
c104eecfb3 feat(desktop): import local Pocket voices (#3259)
## Context

Pocket TTS currently offers bundled reference voices. People also need a
local, private way to add a voice without sending audio to a cloud
service.

## Summary

Add a Pocket voice import flow to Voice settings. Buzz opens the native
file picker, decodes common audio formats in the reusable `buzz-voice`
crate, canonicalizes the selected audio, stores it under a
content-derived identity in app data, selects it, and lets the user
delete it later.

## Changes

- Accept WAV, M4A, MP3, FLAC, OGG, and AIFF files between 2 and 30
seconds, including multichannel sources.
- Decode and downmix accepted audio to canonical mono 32 kHz PCM16 WAV
before hashing and storage.
- Store imported voices behind stable `pocket:imported:<sha256>`
identities and content-addressed files.
- Keep absolute file paths inside the native process and expose only
voice metadata to React.
- Include imported voices in Pocket preview and live huddle playback.
- Add Add voice and delete controls while preserving the bundled Pocket
voice catalog.
- Fall back to Mary when the selected imported voice is deleted.
- Keep durable import, selection, and deletion successful when a live
TTS worker acknowledgement is delayed.
- Preserve bundled voices when optional import metadata is unreadable
and keep failed deletion retryable.

## Related issue

None found.

## Testing

Production decoding was exercised with WAV, M4A with AAC, MP3, FLAC, OGG
Vorbis, and AIFF fixtures. Each format canonicalized to mono 32 kHz
PCM16 WAV. Manual validation in the combined daily-driver build covered
native-picker import, Preview, live-huddle playback, deletion, and Mary
fallback.

## Screenshots

The Voice settings card preserves the bundled Pocket catalog and adds
the local Add voice action.

![Pocket TTS voice
import](https://raw.githubusercontent.com/block/buzz/c03ba29060ca544c5ac3394c212f376651b386a3/pr-3259--pocket-voices.png)

## Reviewer-reproducible examples

Create common-format fixtures and run them through the production
importer:

```bash
. ./bin/activate-hermit
fixtures="$(mktemp -d)"
ffmpeg -hide_banner -loglevel error -f lavfi -i "sine=frequency=220:duration=3" -ac 2 -ar 44100 "$fixtures/voice.wav"
ffmpeg -hide_banner -loglevel error -i "$fixtures/voice.wav" -c:a aac "$fixtures/voice.m4a"
ffmpeg -hide_banner -loglevel error -i "$fixtures/voice.wav" "$fixtures/voice.mp3"
ffmpeg -hide_banner -loglevel error -i "$fixtures/voice.wav" "$fixtures/voice.flac"
ffmpeg -hide_banner -loglevel error -i "$fixtures/voice.wav" -c:a libvorbis "$fixtures/voice.ogg"
ffmpeg -hide_banner -loglevel error -i "$fixtures/voice.wav" -c:a pcm_s16be "$fixtures/voice.aiff"
BUZZ_VOICE_IMPORT_TEST_DIR="$fixtures" \
  cargo test -p buzz-voice imports_common_audio_format_fixtures -- --ignored --nocapture
```

Exercise import persistence, synthesis, deletion, and bundled-voice
fallback with an installed Pocket model:

```bash
BUZZ_POCKET_MODEL_DIR=/path/to/pocket-model-bundle \
  cargo test -p buzz-voice --test pocket_import_audio \
  objective_import_synthesis_delete_and_mary_fallback \
  -- --ignored --nocapture
```

Exercise the native-picker boundary, selection, preview dispatch,
deletion, cancellation, and invalid-file states:

```bash
cd desktop
pnpm build:e2e
pnpm exec playwright test tests/e2e/voice-settings.spec.ts --project=smoke
```

---------

Signed-off-by: John Tennant <jtennant@block.xyz>
Signed-off-by: John Tennant <johnmatthewtennant@gmail.com>
Signed-off-by: John Tennant <jtennant@squareup.com>
Signed-off-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
Signed-off-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@buzz.block.builderlab.xyz>
Co-authored-by: John Tennant <jtennant@block.xyz>
Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
Co-authored-by: npub12gtutshhh76rx0jx697f32f9tffd4hhp3hx58fp4x6u4uemkm7sqf8f757 <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@buzz.block.builderlab.xyz>
2026-07-31 11:15:09 -04:00
klopez4212
39ce3dfc3c fix(desktop): open profiles from avatars (#3751)
## Summary
- show profile descriptions in hover cards as a single truncated line
- open the profile panel when avatars are clicked across desktop
surfaces
- make the direct-message intro avatar clickable

## Validation
- Desktop static checks
- 3,807 desktop tests via pre-push

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz>
2026-07-31 14:24:51 +00:00
Tyler
61ba9dfaa0 refactor(voice): extract reusable Pocket primitives + Pocket voice settings (relands #2467 + #3208) (#3910)
Relands **#2467** (extract `buzz-voice` crate) and **#3208** (Pocket
voice settings) onto main, after #3266 and #3180 merged.

## Why a fresh PR
The repo is squash-only with delete-branch-on-merge. Squashing #3266
deleted `jtennant/pocket-tts-2026-04`, which was #2467's base — GitHub
auto-closed #2467 and it cannot be reopened. Squash merges also sever
ancestry, so GitHub's natural merge-base reports phantom conflicts for
the whole remaining stack.

## Content provenance
- Byte-identical to the blessed `jt/buzz-voice-refactor` branch
(`93029c577`, tree `6729e0eff` — reviewed by Dawn (#2467) and Max
(#3208) at exact heads) **except** the three files where #3180 and #3208
genuinely interact.
- Three-file resolution (union of both sides):
- `huddle/mod.rs` — #3180's pipeline re-exports + #3208's
`agent_tts_routing` imports.
- `huddle/state.rs` — `reset_preserving_generation` preserves both
`huddle_generation` (#3180) and `tts_enabled` (#3208); test sets merged
into one `tests` module.
- `desktop/src/testing/e2eBridge.ts` — both switch arms kept; no
duplicate case labels.

## Verification at cf32dacd7
- `cargo test` (desktop/src-tauri, pinned 1.95.0): **2047 + 3 pass / 0
fail** (14 ignored: 8 keychain, 4 real_relay, 2 flag-gated)
- `cargo clippy --all-targets -- -D warnings`: clean; `cargo fmt
--check`: clean
- `cargo check --workspace` (root, includes new `buzz-voice` member):
clean; `cargo test -p buzz-voice`: 5/0
- `pnpm test`: **3885 / 0**; `tsc --noEmit`: clean; lint: clean

The 3180×3208 interaction resolution is getting an independent team
re-review before merge.

Buzz channel: buzz-desktop-voice `fd5fb402-b651-4238-89b1-bb3e2fa4dc96`,
thread `b4798ecc`.

Signed-off-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
2026-07-31 09:41:09 -04:00
John Matthew Tennant
4632c55041 feat(desktop): auto-enable huddle transcription for agents (#3180)
## Context

Before this change, every huddle initialized with transcription off.
Joining or adding an agent did not enable it, so the agent could not
receive spoken conversation until a person clicked the transcript
control. Starting a huddle from an agent DM could also omit that agent,
and adding an agent who already belonged to the parent channel could
attempt an unnecessary role change and show a warning.

Agent detection uses authoritative huddle membership. A participant
counts as an agent when the ephemeral membership identifies it with the
`bot` role, or when the existing agent identity model identifies the
participant in an agent DM.

## Summary

Buzz now enables transcription once when the first authoritative agent
is present. After that initial automatic action, explicit user control
is authoritative: manual ON or OFF survives membership refreshes,
reconnects, and UI remounts. Removing the last agent does not change the
current transcription state.

Agent-DM huddles enroll the agent automatically. Adding an agent who
already belongs to the parent channel preserves the existing parent role
and completes without a role-mutation warning.

| Scenario | Before | With this change |
| --- | --- | --- |
| First authoritative agent joins or is hydrated | Transcription stays
off | Transcription turns on once |
| User explicitly turns transcription on or off | Manual control exists
without an agent policy | The explicit choice suppresses later automatic
changes |
| Last agent leaves | No defined agent-presence behavior | The current
transcription state remains unchanged |
| Huddle starts from an agent DM | The agent can be omitted | The known
agent is enrolled automatically |
| Added agent already belongs to the parent channel | Buzz can attempt a
role rewrite and warn | Existing parent membership and role are
preserved |
| Transcription is active | The control is not visually distinct | The
control is highlighted and exposes `aria-pressed=true` |

## Changes

- Derive agent presence from authoritative bot-role huddle membership
and known agent-DM identity.
- Apply the one-time auto-enable rule during create, join, membership
hydration, reconnect, pipeline startup, and local agent addition.
- Preserve explicit user state and use huddle-generation guards so stale
asynchronous work cannot alter a replacement huddle.
- Keep backend and React transcription state synchronized, with a
visible and accessible active control.
- Enroll known agent-DM participants and make parent-channel membership
updates idempotent.
- Cover hydration ordering, reconnects, remounts, explicit OFF,
last-agent removal, DM enrollment, existing membership, and active
styling.

## Related issue

None found.

## Testing

Manual validation in `pending-seed` confirmed the product contract:

1. Started a huddle from the owned, running Fizz agent DM.
2. Confirmed the authoritative roster contained the human and Fizz as an
agent.
3. Confirmed transcription enabled without clicking the control: `Stop
transcript`, `aria-pressed=true`, with the highlighted active
background.
4. Turned transcription off and confirmed `Start transcript`,
`aria-pressed=false` remained stable.
5. Removed Fizz while transcription was off and confirmed the state
stayed off.
6. Left the huddle cleanly.

## Screenshots

The same control has distinct active and inactive states.

![Active transcript
control](https://raw.githubusercontent.com/block/buzz/2dcb266244e93d358f85e5371d190de77b03c86d/pr-3180--active-transcription.png)

![Inactive transcript
control](https://raw.githubusercontent.com/block/buzz/2dcb266244e93d358f85e5371d190de77b03c86d/pr-3180--inactive-transcription.png)

## Reviewer-reproducible examples

From a fresh checkout:

```bash
pnpm --dir desktop build:e2e
pnpm --dir desktop exec playwright test tests/e2e/huddle-transcription.spec.ts --project=smoke
pnpm --dir desktop exec playwright test tests/e2e/mentions.spec.ts --project=smoke --grep "system agent profile exposes owned agent actions|system agent avatar exposes owned agent actions|owned bot profile exposes message and huddle actions|owned agent mention profile exposes message and huddle actions"
```

The huddle scenario exercises initial authoritative hydration, exactly
one automatic enable, explicit OFF persistence, unchanged state after
last-agent removal, newer events winning over delayed hydration,
agent-DM enrollment, and idempotent parent membership. It also asserts
`aria-pressed` and distinct computed active styling.

---------

Signed-off-by: John Tennant <jtennant@squareup.com>
Signed-off-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@buzz.block.builderlab.xyz>
Co-authored-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@buzz.block.builderlab.xyz>
2026-07-31 07:06:41 -04:00
Sam W
d88313f369 feat(desktop): delete a message by clearing its edit to empty (#3813)
## What

Clearing an edit to empty and hitting accept now **deletes the message**
instead of hanging. One of Sam's frequent workflows is to delete a
message by editing it, clearing the text, and pressing Enter — which
previously no-op'd (a deliberate guard blocked empty edits).

## How

Pure client-side wiring — **no relay, schema, or Rust changes.**

1. **`MessageComposer.tsx`** — the edit path had a guard that *blocked*
empty edits (`if (!trimmed && !hasMedia) return;`). That guard is simply
**removed**, so empty content flows through the normal edit path to
`onEditSave("", [], [])`. `buildOutgoingMessage("")` is a safe no-op.
2. **`handleEditSave` in `useChannelPaneHandlers.ts`** — when an edit is
submitted with empty text and no media tags, it exits edit mode and
opens the **same "Delete message?" confirmation** the Delete menu action
shows, rather than publishing an empty edit.
3. **`DeleteMessageConfirmDialog.tsx`** — the confirmation dialog,
extracted into **one shared component**. `MessageActionBar` renders it
for the Delete menu action (previously inline), and `ChannelScreen`
renders it for the empty-edit path. No duplicated dialog UI. **Delete**
runs the existing `deleteMutate`; **Cancel** leaves the message
untouched.

Because both the main timeline and the thread panel already route
edit-save through `handleEditSave`, this covers both surfaces with a
single dialog at the `ChannelScreen` level — no per-composer plumbing.

- Image-only edits (empty text but attachments present) still publish
normally — only a *fully* empty edit prompts to delete.
- An empty edit can never publish an empty body: `handleEditSave`
returns before the edit mutation.

## Review history

This PR was reworked three times in response to review — each pass made
it smaller:

1. First cut wrapped this in a new "Delete message?" `AlertDialog`
rendered from a composer hook — a verbatim duplicate of the confirmation
already in `MessageActionBar.tsx`. Removed.
2. Second cut threaded a dedicated `onDeleteEditTarget` callback down
`ChannelScreen → ChannelPane → MessageComposer / MessageThreadPanel`.
Also redundant — the delete decision moved entirely into
`handleEditSave`, which every edit-save already flows through.
3. Third cut added a special-case empty branch to the composer, which
pushed `MessageComposer.tsx` over the file-size ratchet and led to an
unrelated emoji-helper extraction to make room. Both gone: deleting the
pre-existing guard (rather than adding a branch) is net-negative, so
there's no ratchet pressure and **nothing emoji-related in this PR**.
`MessageComposer.types.ts` is back to baseline too.
4. Fourth pass (this one): an unconfirmed, no-undo delete was too sharp.
The empty-edit path now routes through the same **"Delete message?"
confirmation** as the menu action — shared as one
`DeleteMessageConfirmDialog` component (so it's reuse, not the duplicate
dialog from cut #1).

## Testing

- **E2E:** `desktop/tests/e2e/empty-edit-delete.spec.ts` (Playwright,
smoke project), three tests, all passing locally:
- *clearing an edit to empty prompts to delete, then deletes on confirm*
— edits the mock identity's own `#general` message, clears it, Enter →
the **"Delete message?"** dialog appears; Delete → the row disappears
and edit mode exits.
- *cancelling the empty-edit delete keeps the message* — same up to the
dialog, then Cancel → the message survives.
- *a non-empty edit still edits and never deletes* — guards the other
direction (no dialog).
- `pnpm typecheck`, biome, file-size + px-text guards all clean; full
desktop unit suite (3847 tests) passing locally.

> Heads-up for the reviewer: pushed with `--no-verify` because the
pre-push hook runs the Rust **integration** suite, which needs Docker
(Postgres/Redis) that isn't available in this environment — it doesn't
apply to this desktop-only change. CI runs the real gates.

---

🐝 Built by Bumble in Buzz, from a conversation in #test-swesterman.

---------

Signed-off-by: Sam Westerman <swesterman@squareup.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-30 22:34:12 -07:00
Kalvin C
10d5a26414 feat(relay): raise hosted community limit to five (#3829)
## Summary
- raise the relay authoritative default community ownership limit from 3
to 5
- raise the desktop hosted-community treatment from 3 to 5
- preserve `BUZZ_MAX_COMMUNITIES_PER_OWNER` as a deployment override

## Validation
- `pnpm -r check`
- `cargo fmt --all -- --check`
- `cargo test -p buzz-db` (94 passed, 151 Postgres-dependent tests
ignored)
- pre-push hooks: desktop checks/tests, Rust tests, Tauri checks (all
passed; 1,995 desktop Rust tests passed)

Signed-off-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz>
Co-authored-by: npub1dccv64krpcpse5cmkzfeh998cftungyatw3djt8jwdw6g43f7fyqzzmrf7 <6e30cd56c30e030cd31bb0939b94a7c257c9a09d5ba2d92cf2735da45629f248@buzz.block.builderlab.xyz>
2026-07-30 18:20:58 -07:00
Tyler
468647a51f feat(desktop): locally stored NIP-49 encrypted key backup (#2937)
## Summary

Adds a locally stored **NIP-49 encrypted key backup** (`ncryptsec`) to
the desktop app, per the plan reviewed in buzz-development (Rev 3,
approved 9/10 by Wren; implementation also reviewed and approved 9/10).

**Two-artifact design — canonical bytes originate entirely in Rust:**
- `create_ncryptsec_backup` runs under the `identity_mutation` lock:
encrypt → decrypt-verify against the live pubkey → atomic `0o600` write
to `{app_data_dir}/identity.ncryptsec` → reread/byte-compare → return
the exact persisted bytes. The frontend never re-derives or re-encrypts.
- `save_ncryptsec_copy` writes a portable copy via the save dialog
(parse-gated, secret-file semantics) and never mutates canonical state.
- `generate_backup_passphrase`: 6 words from the EFF short wordlist via
`OsRng` (custom passphrases min 12 chars).
- Import accepts `ncryptsec1` with optional password; the raw-`nsec`
path is untouched. Different-pubkey import and sign-out wipe the
app-managed backup (post-commit, best-effort — a failed import can never
destroy the still-live identity's backup; regression-tested).

**Never-relay guarantee (egress guard + tripwires):**
- `egress_guard.rs` fail-closed at all 8 `/events` submission boundaries
(relay submit funnel, 3× `relay.rs`, huddle STT, both engram submitters,
native WS choke point), rejecting `ncryptsec1`/`NCRYPTSEC1` in text and
binary frames. Scope is deliberately ncryptsec-only: pairing
intentionally carries raw nsec inside its encrypted session.
- Site-granular `/events` inventory tripwire: per-file (`/events` count,
guard-call count) pairs; unlisted files expect zero. Mutation-style
tests prove a ninth site in an existing file, a removed guard, and a new
unlisted file all fail the scan.
- ncryptsec source-allowlist scans in **both** trees (Rust + TS).

**Frontend:** onboarding `BackupStep` is encrypted-by-default — the
default path never invokes `get_nsec` (e2e asserts the command log).
Raw-nsec export stays behind an explicit click with prior semantics.
Shared `EncryptedBackupCreator` powers onboarding + a new settings row;
the import form auto-switches to encrypted mode on `ncryptsec1` paste
(case-insensitive HRP).

**Open product call for @tlongwell-block:** onboarding default is
*encrypted* in this PR; flipping to raw-default is a small change either
way (documented in the plan).

Review history: plan Rev 3 and the implementation were both iterated
with Wren to 9/10 (two blockers from round 1 — import ordering,
inventory granularity — plus an uppercase-bech32 hardening gap, all
fixed in `dde37183e`). Thread: buzz-development.

### Related issue

Follow-up to the direction explored in #385 (NIP-PB, closed) — this
ships local NIP-49 (the standard) instead of a new NIP. No open
duplicate found.

### Testing

All at exactly `dde37183e` (same shell, HEAD verified):

- `cargo test` — 1680 passed / 0 failed / 14 ignored (includes a
deliberate ~70s log_n-18 NIP-49 round trip, spec vector, wrong-password,
NFKC, uppercase-vector decrypt, injection test per egress boundary,
inventory mutation tests, import-ordering regression tests)
- `cargo clippy --all-targets -- -D warnings` — clean; `cargo fmt
--check` — clean
- `pnpm typecheck` — clean; JS unit suite 3529/3529; biome (repo-pinned
2.4.16) clean
- Playwright `onboarding-backup` / `onboarding` /
`onboarding-agent-defaults` / `profile-nsec-reveal` — 86 passed, 1 known
avatar-reservation flake (passed on rerun; untouched by this diff).
`passThroughBackupStep` now exercises the encrypted default, so every
downstream onboarding spec covers the new path.
- Note: browser e2e fakes the crypto via the mock bridge (fixed
spec-vector blob); decryption correctness is proven in the Rust tests.

## Latest onboarding integration

The current head adds an additive `IdentityInfo.storage` field
(`ephemeral`, `system-keyring`, `local-file`, or `environment`) so
onboarding can accurately explain where the active identity is
protected. It surfaces storage metadata only—never key material—and
leaves the existing lost/keyring-locked recovery behavior intact.

---------

Signed-off-by: Tyler Longwell <tlongwell@block.xyz>
Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Co-authored-by: npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67d <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
Co-authored-by: Tyler Longwell <tlongwell@block.xyz>
Co-authored-by: Taylor Ho <taylorkmho@gmail.com>
Co-authored-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz>
2026-07-30 20:58:03 -04:00
Alex Kemper
f3e5e81267 fix(catalog): update Amp tagline (#3806)
## Summary

Update Amp's runtime catalog description to use its current tagline:

> The coding agent and development environment that runs anywhere and
everywhere.

### Related issue

N/A. This follows the Amp description update in
https://github.com/block/buzz/pull/3758.

### Testing

* `pnpm -C desktop check`
* `pnpm -C desktop typecheck`
* `pnpm -C desktop test` (3,835 passed)

No screenshot is included because this changes only the catalog
description text. It does not change layout or interaction behavior.

Signed-off-by: AJKemps <AJKemps@users.noreply.github.com>
Co-authored-by: AJKemps <AJKemps@users.noreply.github.com>
Co-authored-by: Alex Kemper <alex@ampcode.com>
2026-07-30 22:54:41 +00:00
Clay Delk
9e8fcfda09 fix(desktop): channel topic and membership metadata cleanup (#3642)
First slice of #2216, scoped to the system/status lines in the chat
timeline.

## Why

Two problems on the same surface.

**Clearing a channel topic renders as empty quotes.** The relay reports
a clear as a `topic_changed` event carrying an empty string — there's no
separate "cleared" event type. So the timeline printed:

> Alice
> changed the topic to “”

which reads as if the topic were *set to* two quote marks. Same for
purpose.

**The membership caption reads like a headline, not a metadata line.**
`title` and `action` render on separate lines — the member's name sits
in the header row with the avatar and timestamp, and the caption sits
beneath it. So the caption was "was added by Alice Chen" standing alone
under a name, while its siblings on that same line are "joined the
channel" and "left the channel".

## What

- Blank, missing, or whitespace-only topic/purpose now reads **"cleared
the channel topic"** / **"cleared the channel purpose"**.
- Membership captions drop "was": **"added by Alice Chen"**, matching
"joined the channel" and "left the channel".
- The wording moves to `lib/systemEventCopy.ts` as a pure function, so
it's assertable in a unit test instead of only reachable through the
DOM. That also removes two JSX fragments from `SystemMessageRow.tsx`,
taking it 911 → 900 lines.

## Two E2E assertions this exposed

Both were measuring something other than what they claimed, and the copy
change tipped them over. Neither is a product bug, but both would have
failed the next person too.

1. **`mentions.spec.ts:1245`** asserted a button was un-underlined while
the mouse was still parked from a previous `hover()`. Any reflow — new
rows, scroll-to-bottom, a different text wrap — can slide that button
under the stationary pointer, so the assertion measured *where the mouse
happened to be* rather than the resting style. Dropping four characters
changed the text wrap, changed the row height, changed the scroll
offset, and the pointer landed on it. Now parks the pointer off-target
first.
2. **`mentions.spec.ts:1253`** used a bare `role=tooltip` lookup. Once
the first tooltip animates out while the second opens, two elements
match and strict mode trips. Now scopes to the open tooltip via
`:not([data-state="closed"])`.

## Deliberately out of scope

- **Timestamps.** The day divider, per-message clock times, the Inbox
thread pane, and the inbox list have three divergent date
implementations and none fully match the writing standard's
Today/Yesterday/weekday/date progression. That's its own slice of #2216.
- **Whose avatar shows.** An addition puts the *added* member in the
header; a removal puts the *remover* there. Possibly intentional, but
it's a design question, not copy.
- **`the channel` vs `this channel`.** joined/left/removed say "the
channel"; created/archived/unarchived say "this channel". Worth
normalizing, but it touches lines this PR otherwise leaves alone.

## Validation

- `pnpm check`, `pnpm typecheck` — clean
- Unit: **3781/3781**, including 6 new tests in
`systemEventCopy.test.mjs` covering set/blank/undefined/null/whitespace
for both fields, plus a guard that no variant can emit empty quotes
- Smoke E2E `mentions` + `messaging`: **85/85**
- The previously fragile test run with `--repeat-each=5`: **5/5**

Signed-off-by: Clay Delk <clay.delk@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 15:53:04 -07:00
Bradley Axen
ede2686334 fix(desktop): align data deletion labels (#2230)
## Why

The Profile settings action still says “Sign Out,” while its
confirmation action says “Delete My Data.” Both buttons trigger the same
destructive local-data wipe and should name it consistently.

## What

- Label both destructive actions “Delete my data”
- Assert the matching section and confirmation labels in the existing
Playwright coverage

## Risk Assessment

Low — copy and test assertions only; sign-out behavior is unchanged.

## References

- Follow-up to #2208
- #2216 also touches this copy and should preserve “Delete my data” when
rebased
- `just desktop-check`
- `just desktop-test` (3,275 tests)
- Desktop E2E build and sign-out Playwright spec (2 tests)

Generated with Codex

Signed-off-by: Bradley Axen <baxen@squareup.com>
2026-07-30 15:47:35 -07:00
Will Pfleger
d40a33290e feat(desktop): raise the install ceiling and make installs observable (#3368)
Windows installs of Goose and other harnesses failed at exactly five
minutes with an empty error (#2401). The 300s ceiling was killing
installs that were working, just slowly — the Goose step pulls a ~79MB
release asset, and Windows Defender scans every file npm extracts. When
the ceiling fired it discarded the output it had already read, so the
user got a bare timeout string and no way to tell a hang from a large
download.

## The ceiling

`INSTALL_TIMEOUT` is 900s, and the error names the limit: `install
command exceeded the 15m ceiling and was terminated`. It stays a pure
wall-clock ceiling with no inactivity kill — nothing observable
distinguishes a hung installer from one silently transferring a large
artifact, so silence alone never kills an install. A ceiling kill
remains non-retryable; re-running a command that already burned 15
minutes costs the user more time with no plausible path to success.

The child's exit and both stream drains fold into one resumable settle
governed by a single deadline. Waiting on the drains outside that
deadline would let a descendant that outlived the install shell hold the
output pipes — and the per-runtime install guard behind them — open with
no bound, which is the failure the ceiling exists to prevent. So the
deadline path terminates the process group on the normal-exit branch
too: a leader that exited with a real status still gets its stragglers
killed, and the guard cannot stick either way. Whether the leader had
already exited only decides the verdict — its real status outranks a
timeout.

The install shell is a session leader and its descendants inherit the
output pipes, so signalling only the leader left them running and the
drains blocked on a pipe nobody would close. Escalation keys off the
*group's* liveness rather than the leader's, since a descendant that
ignores SIGTERM outlives the leader and would otherwise never receive
the group SIGKILL. Reaping the killed child and finishing the drains
share one bounded grace, so a termination that failed outright cannot
extend the ceiling that just fired.

## Output capture

Each stream drains into a bounded capture that is *shared* with the
reader rather than returned by it, so whatever arrived before a stall is
readable at the ceiling — exactly when the output matters most. Output
of any size costs a fixed amount of memory.

One capture holds two independently bounded views of the same bytes:

| View | Head / tail | Cut marker |
|------|-------------|------------|
| UI (`InstallStepResult`) | 512 B / 1024 B | `... (N bytes omitted)
...` |
| Log file | 128 KiB / 128 KiB | `... [N bytes omitted at cap] ...` |

The UI budget is screen space; the log's is disk. Both markers are
inline, so neither ever implies completeness it does not have. Both ends
are cut at arbitrary byte offsets, so a partial character is trimmed and
the partial token each cut left behind is dropped — the marker's byte
count includes both trims.

## Install log

`steps` carries only the last attempt of each step, truncated for
display. Everything else — earlier retries, the prerequisite step that
actually broke, the managed-Node bootstrap — used to be discarded.
`InstallReporter` now appends one self-contained record per attempt of
per step to `install-<runtime-id>.log` beside the agent logs, and
`InstallRuntimeResult.log_path` carries the file to the UI, where a
failure message ends with `Full log: <path>`.

Each record is bounded independently by the log-scale capture that
produced it, so a first attempt that printed megabytes cannot push out
the later record explaining the failure; the run's total is bounded by
steps × attempts × per-record cap. Every early return builds its result
through one `InstallReporter::failed` helper, so no failure path can
omit the log pointer, and synthesized steps go through `record_step` — a
step that reaches the UI without passing it would be invisible in the
file.

Install output can echo a registry token or proxy credential from the
environment it ran in, and the file is written unattended. Redaction
keys off the *names* of the environment variables the install inherited,
snapshotted once per run, rather than a list of known secret value
prefixes: a credential with no recognisable shape is exactly the one a
prefix match misses. Three name rules apply, because the variables need
different treatment:

| Rule | Variables | Redacted |
|------|-----------|----------|
| URL userinfo | `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`,
`NPM_CONFIG_PROXY`, `NPM_CONFIG_HTTPS_PROXY`, `NPM_CONFIG_REGISTRY` |
`user:password` only |
| Exact name | `NPM_CONFIG_KEY`, `NPM_CONFIG__AUTH`, `NPM_CONFIG_OTP` |
whole value |
| Marker substring | `*TOKEN*`, `*SECRET*`, `*PASSWORD*`, `*_PAT`, … |
whole value, 8-byte floor |

A proxy or registry keeps its host and port, because an install that
fails behind one is diagnosable only if the record still says which one
it went through, and a bare `user@` with no password is not treated as a
credential. npm's own settings are listed by exact name rather than
matched on `KEY` or `AUTH` substrings — both occur throughout an
ordinary environment on values that are paths and people's names — and
they bypass the 8-byte floor, since a six-digit one-time password is a
credential at that length. Matching is case-insensitive, which is what
npm's lowercase `npm_config_*` spelling needs. `0o600` is set by the
create rather than a later `chmod`, which would leave a window where the
umask decides. A runtime id that cannot safely be a filename yields no
log rather than a sanitized one — a rewritten id could collide with
another runtime's log.

The file holds exactly one run. A run opens its own session after the
runtime id has been canonically resolved — the previous file rotates to
`.1` and any older `.1` is removed before the rename, since a rename
that will not replace its destination would otherwise wedge rotation
permanently on Windows. The session writes a header naming the runtime,
the app version (`app.package_info().version` on the Rust side — cannot
be mocked or fail), the OS (`std::env::consts::OS`), and the start time:
a Windows failure and a macOS one on the same runtime are different
bugs, and a stale app version explains a failure that no longer
reproduces. Each record carries its attempt's elapsed time.

## Live output line

A 15-minute ceiling with nothing behind it but a spinner is
indistinguishable from a hang. The same drain seam feeds an
`acp-install-output` event carrying the newest complete line, and the
three install entry points — Doctor harness rows, the harness catalog
dialog, and onboarding runtime cards — render it under the spinner with
`aria-live="polite"`.

Ordering is keyed on a `seq` monotonic across the whole install, not on
the attempt number, which restarts at 1 for every step: keyed on
attempt, one step succeeding on attempt 2 would make the next step's
attempt-1 output look stale and freeze the display for the rest of the
install. Each executed attempt begins with an unthrottled `line: null`
clear signal, so a stale failure line cannot sit under the spinner while
the retry runs. Events are otherwise throttled to four per second, and
the throttle *retains* the newest pending line and flushes it when the
window reopens rather than dropping it — at an attempt boundary a drop
would silently eat the new attempt's first line.

The subscription is mounted for the runtime's whole lifetime rather than
started when the install begins. The install command is invoked from the
click handler, so the clear and a fast command's first lines can be
emitted before React has committed the pending state, and nothing
replays them — a subscription that waited for that state would lose the
entire output of a short install. The run boundary resets the ordering
key when the install settles, since `seq` restarts for the next run, and
the line renders only while installing, so a straggler from a finishing
drain cannot appear under a fresh Install button.

The 15-minute ceiling deliberately stops waiting on stuck drain threads
— a hung installer must not freeze the app. That means a drain thread
can outlive its `InstallReporter`. Without a generation guard, a drain
that calls `offer` after the run settles would publish an event with the
run's high `seq`, poison the permanent listener's React state, and cause
the next install's restarted `seq=0` events to be rejected. `Live` now
carries a `lifecycle: Arc<RwLock<bool>>`; drain threads hold a **shared
read guard** from the admission check through the `(self.emit)(...)`
call, making the check-then-emit pair atomic with respect to shutdown.
`InstallReporter::drop` takes the **exclusive write guard** and stores
`false` — this blocks until every in-flight drain publication releases
its read guard, then prevents any new admission. Deactivation is
bounded: the write lock holds only for the flag store, so it can block
at most for the duration of one emit call (microseconds to low
milliseconds). Rust drops locals in reverse-declaration order, so
`reporter` drops before `_guard`, ensuring the exclusive write completes
before the per-runtime concurrency guard releases and a new install can
start.

## Also

Install result types move to `desktop/src/shared/api/installTypes.ts`,
following the existing `searchTypes.ts` / `workflowTypes.ts` convention,
and are re-exported from `tauri.ts` and `types.ts` — both already over
the file-size cap, so neither can grow to carry them.

Two comments described `AdapterOutdated` as applying only to the
deprecated package; it also covers a version below the supported floor.

Report: #2401

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-07-30 17:07:22 -04:00
fenner888
1b3ff96a57 Add Devin as a preset ACP harness (#3225)
## Summary

- Add Devin to the built-in preset harness catalog using the official
native ACP invocation: `devin acp`.
- Link setup guidance to Cognition's official Devin CLI documentation.
- Render a bundled, attributed Devin mark on a white canvas through
Buzz's existing runtime-icon system.
- Keep preset capability metadata in the Rust catalog; no duplicate
TypeScript runtime table or React runtime checks.
- Move the existing preset catalog and its focused tests into a Rust
submodule without changing existing preset behavior, keeping the touched
files within the repository's file-size limit.

### Related issue

Follow-up to the generic BYOH harness work in #2773.

### Scope

This is the small preset/data-entry follow-up described in the #2773
discussion. It uses the generic preset readiness contract and does not
add Devin-specific authentication probing, permission bypasses, model
switching, cloud handoff, or cloud Devin capability claims.

The preset supplies:

- ID: `devin`
- Executable: `devin`
- Arguments: `acp`
- Installation guidance: https://docs.devin.ai/cli

### Testing

Local verification was rerun at the final PR head,
`7bb9aa6e862a47a5062b5b8234fdb5ce2aae6c1d`.

- Focused Rust preset tests: 7 passed
- Desktop JavaScript tests: 3,768 passed
- Desktop lint, formatting, file-size, and text guards: passed
- Full Tauri test suite: 1,851 passed, 14 ignored
- Root Rust unit-test groups: passed
- Web production build: passed
- Mobile format, analyze, and test suites: passed
- Full repository `just ci`: passed

The branch also merges cleanly with the current Block `main`. The
upstream fork-triggered CI workflow is awaiting maintainer approval;
DCO, Semgrep OSS, and zizmor are passing.

The bundled SVG was rendered and visually inspected in both its source
dimensions and a 512px preview. The cross-language preset-logo guard
verifies that the Devin mapping exists and the asset is present on disk.

Signed-off-by: Mark Fenner <markfenner57@yahoo.com>
2026-07-30 16:58:28 -04:00
Taylor Ho
4d47aa8345 feat(desktop): improve agent activity header ui (#3321)
**Category:** improvement
**User Impact:** Activity feeds now clearly identify the agent and keep
update recency visible even when channel names are long.

**Problem:** The activity header led with a generic label, making it
hard to tell which agent was in view, while channel scope and recency
competed for limited horizontal space. Long channel names could hide the
update timestamp entirely.

**Solution:** Lead with the resolved agent avatar and name, then place
mode and scope in a truncating metadata region with recency pinned at
the right edge. This preserves the compact two-line header while keeping
the most important identity and freshness signals legible.

<details>
<summary>File changes</summary>

**desktop/src/features/channels/ui/AgentSessionThreadPanel.tsx**
Reorganizes the activity header around the agent identity, reuses the
existing resolved profile avatar and label helpers, and separates scope
truncation from the always-visible recency label.

**desktop/tests/e2e/activity-scope-label-screenshots.spec.ts**
Expands activity-header coverage across channel-scoped, all-channel,
raw, long-name, and narrow layouts, including measured truncation and
recency visibility.

</details>

## Reproduction steps

1. Open an agent's activity feed from a channel.
2. Confirm the agent avatar and name lead the header.
3. Open a feed scoped to a channel with a long name and resize the panel
narrowly.
4. Confirm the mode and channel scope truncate while the recency label
remains visible at the right edge.
5. Toggle Raw mode and open an all-channel feed to confirm the same
hierarchy and truncation behavior.

## Screenshots

| Long channel | Narrow layout |
|---|---|
| <img width="380" height="671" alt="image"
src="https://github.com/user-attachments/assets/19682aac-9938-41ed-8c27-fe59bf8b7535"
/> | <img width="371" height="771" alt="image"
src="https://github.com/user-attachments/assets/92a6fc05-c9ba-4c11-a18c-22b5225d8b9a"
/> |

| Raw mode | All channels |
|---|---|
| <img width="380" height="671" alt="image"
src="https://github.com/user-attachments/assets/c8135600-e3c9-4644-8350-fa5f6b2d3aaa"
/> | <img width="380" height="671" alt="image"
src="https://github.com/user-attachments/assets/bac73a6a-4ed5-42d6-98cc-039a75c48ef3"
/> |

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Co-authored-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz>
2026-07-30 12:34:35 -07:00
Tyler
bf139e8d0b perf(presence): reduce heartbeat frequency (#3783)
## Summary

- send desktop presence heartbeats every 60 seconds instead of every 30
seconds
- extend presence TTL from 90 to 180 seconds to preserve the existing
three-heartbeat expiry window
- add mutation-sensitive tests that pin the one-minute / three-window
timing contract
- update presence documentation to match

This halves steady-state **desktop** presence `SET` + `PUBLISH` traffic
while retaining tolerance for two missed heartbeats. Mobile already uses
a 60-second heartbeat, so the fleet-wide reduction depends on desktop's
share of connected clients.

## Rollout order

Deploy the relay TTL increase before shipping the desktop heartbeat
change. Old desktop + new relay is safe; new desktop + old relay leaves
only a 90-second TTL on a 60-second cadence and can flap after one
missed heartbeat.

## Verification

At initial live-test commit `00816e233b187bc5ba12c667d675ed050a8cc1c9`:

- isolated clean-room relay built from the exact SHA against fresh
Postgres, Redis, and MinIO
- live Redis `MONITOR` observed kind-20001 writes as `SET ... EX 180`,
global `PUBLISH`, and clean-disconnect / explicit-offline `DEL`
- normal workflows passed: channel create/update/archive/unarchive;
message send/get/reply/thread/search; archived-channel write rejection
and resumed write after unarchive

At follow-up commit `bf38a8c5c96f196ff8ee46e48d4141ee7811f186`:

- `pnpm -C desktop test` — 3829 passed
- `pnpm -C desktop typecheck`
- `cargo test -p buzz-pubsub` — 24 passed, 11 Redis-dependent tests
ignored
- mutation probes fail when the server TTL changes to `999999` or the
desktop heartbeat changes back to 30 seconds
- `git diff --check`

The pre-push suite's relevant checks passed, but its unrelated Tauri
clippy step fails on current `origin/main`:
`desktop/src-tauri/src/linux_media.rs` has three dead-code warnings on
macOS. This PR does not modify that file, so the branch was pushed after
independently running the suites above.

## Buzz context

Originating channel: `buzz-redis-cluster-mode`
(`f4e36d32-afdb-447f-8c87-ab003e069d18`)

---------

Signed-off-by: npub1t2tgm7d8f995uqvmnm8h88sg3wnpp9a5xysjf6dg3tjmgt3ltulqdp8ehr <5a968df9a7494b4e019b9ecf739e088ba61097b4312124e9a88ae5b42e3f5f3e@buzz.block.builderlab.xyz>
Co-authored-by: npub1t2tgm7d8f995uqvmnm8h88sg3wnpp9a5xysjf6dg3tjmgt3ltulqdp8ehr <5a968df9a7494b4e019b9ecf739e088ba61097b4312124e9a88ae5b42e3f5f3e@buzz.block.builderlab.xyz>
2026-07-30 15:26:11 -04:00
klopez4212
6e419b9f1c Tighten continuation message rows (#3724)
## Summary

- use uniform 4px top and bottom padding for continuation rows
- keep continuation timestamps top-aligned and remove the thread-only
minimum-height gutter
- raise continuation hover actions by 12px
- align virtualized row estimates with the compact layout

## Validation

- `pnpm test` (3,782 tests via pre-push)
- `pnpm check`
- desktop snapshots

## Screenshots

### Mention-chip continuation

![Mention-chip
continuation](https://raw.githubusercontent.com/block/buzz/85b88763ef8147f3376c9bf794bc0973a0211a57/pr-3724--thread-continuation.png)

### Emoji continuation

![Emoji
continuation](https://raw.githubusercontent.com/block/buzz/85b88763ef8147f3376c9bf794bc0973a0211a57/pr-3724--channel-continuation.png)

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-07-30 19:39:12 +01:00
klopez4212
f48f3f055f Fix video reviews in thread replies (#3719)
## Summary
- Show video review comments when a video is opened from a thread reply.
- Reuse review-context construction across timeline and thread views.

## Validation
- `pnpm run build:e2e && pnpm exec playwright test
tests/e2e/video-attachment.spec.ts --project smoke --grep "video replies
in threads open the review comments view"`
- `pnpm test`

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
2026-07-30 11:36:30 -07:00
Wes
cca8839034 Make relay reconnect backoff authoritative (#3774)
## Summary

- make the relay reconnect coordinator authoritative during outages so
query, publish, and subscription traffic waits for the scheduled attempt
instead of cancelling backoff
- release waiting operations after the coordinated AUTH +
live-subscription replay attempt, while preserving one explicit manual
reconnect fast path
- suppress duplicate notification side effects when reconnect replay
overlaps previously delivered events

## Root cause

`resetConnection()` scheduled exponential backoff, but
`ensureConnected()` cleared any pending reconnect timer. Operation-level
retry paths immediately called `ensureConnected()`, so ordinary app
traffic could repeatedly bypass the reconnect policy during an outage.
The resulting churn also replayed overlapping live events into
notification side effects without a shared event-ID guard.

## Validation

- `pnpm --dir desktop typecheck`
- `pnpm --dir desktop test` — 3,823 passed
- pre-push: `desktop-check`, `desktop-test`, and `branch-skew` passed
- file-size, px-text, and pubkey-truncation ratchets passed

---------

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz>
2026-07-30 11:25:08 -07:00
Taylor Ho
bd0bff24bf feat(desktop): add password-protected backups in settings (#3701)
**Category:** new-feature
**User Impact:** Users can create, download, and verify a
password-protected backup of their private identity from desktop
Settings.

**Problem:** Buzz does not currently give signed-in users a
Settings-based path to protect or validate their private identity
independently of onboarding. **Solution:** Add a focused backup menu to
the private-key row, keep encryption and verification local in Rust, and
preserve completed encrypted backups briefly so native saves can be
retried without repeating encryption.

<details>
<summary>File changes</summary>

**desktop/src/features/settings/**
Adds the background backup lifecycle, create and test dialogs,
private-key menu integration, password handling, and focused unit
coverage.

**desktop/src/features/onboarding/ui/NsecMaskedDisplay.tsx**
Extends the masked private-key display with reusable overflow-menu
actions used by Settings.

**desktop/src/app/App.tsx**
Mounts the backup provider at app scope so encryption and save work
survive closing Settings or the modal.

**desktop/src/shared/api/tauriIdentity.ts**
Adds typed desktop bindings for local backup creation, save, selection,
and verification.

**desktop/src-tauri/src/key_backup.rs and
desktop/src-tauri/src/commands/identity.rs**
Implements local NIP-49 encryption, password generation, file handling,
and public-identity-only verification results.

**desktop/src-tauri/src/egress_guard.rs and guarded call sites**
Blocks encrypted secret material from relay, websocket, snapshot,
sharing, and huddle egress paths.

**desktop/src-tauri tests and fixtures**
Covers encryption, verification, file behavior, and fail-closed
no-egress protections.

**desktop/src/testing/e2eBridge.ts, desktop/tests/, and
desktop/playwright.config.ts**
Expands the mock native bridge and browser coverage across create,
retry, expiry, and current/different-identity verification states.

**desktop/src-tauri/Cargo.toml, Cargo.lock, and assets**
Adds the local cryptography/password-generation dependencies and
embedded short-word list.

</details>

## Reproduction steps

1. Run the desktop app and open **Settings → Profile → Identity**.
2. Open the private-key overflow menu and choose **Create backup**.
3. Enter or generate a valid password, submit, and confirm progress
continues if the dialog or Settings is closed.
4. Save the resulting `.ncryptsec` file; cancel and retry to confirm the
temporary download remains available.
5. Choose **Test backup**, select the file, enter a wrong password, then
retry with the correct password.
6. Confirm success identifies whether the backup matches the current
identity and displays only the public `npub`.

## Screenshots

| Settings identity | Private-key menu | Create backup |
|---|---|---|
| <img width="1280" height="720" alt="image"
src="https://github.com/user-attachments/assets/981e391b-6829-4081-95ca-ca75a369de71"
/> | <img width="1280" height="720" alt="image"
src="https://github.com/user-attachments/assets/7972c68e-7635-47d8-b0ad-9639390d3e6c"
/> | <img width="1280" height="720" alt="image"
src="https://github.com/user-attachments/assets/4709c8f7-cf02-46f1-bec9-b3f98fe56fb2"
/> |

| Encrypting | Download available | Test success |
|---|---|---|
| <img width="1280" height="720" alt="image"
src="https://github.com/user-attachments/assets/1ac3e934-2b4b-4135-bae6-126c715c8c59"
/> | <img width="1280" height="720" alt="image"
src="https://github.com/user-attachments/assets/cb6f07ee-a16f-44a5-b9a0-6b9fe0e4d40d"
/> | <img width="1280" height="720" alt="image"
src="https://github.com/user-attachments/assets/ea58b1b1-966c-46aa-8d59-92c9f06a25bd"
/> |

Visual review and additional states: [Buzz
thread](buzz://message?channel=50ca7ef1-201e-4159-9499-40de3964b7c3&id=87eceb5f0f82fd50c32e560de3d35be48e293760f6620718aafdcef289d475fe)

---------

Signed-off-by: Taylor Ho <taylorkmho@gmail.com>
Co-authored-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz>
2026-07-30 11:15:39 -07:00
Bradley Axen
f44b5a2477 fix(desktop): reuse profiles when joining communities (#2155)
## Why
People joining a community with an existing relay profile should not be
asked to recreate their name and avatar.

## What
- Check the active identity's relay profile after the joined community
becomes active
- Skip directly to the starter-team step when a kind-0 profile event
exists
- Preserve the profile setup path when no event exists or discovery
fails
- Cover both new-profile and existing-profile join paths in E2E tests

## Risk Assessment
Low — the lookup is scoped to the community onboarding profile stage,
runs once per transaction, and fails open to the existing flow.

## References
- `pnpm build:e2e && pnpm exec playwright test --project=integration
tests/e2e/onboarding.spec.ts --grep 'first-community direct join reaches
profile|community onboarding reuses an existing relay profile'` (2
passed)

Generated with Codex

Signed-off-by: npub1rf6fvdj6ut0c4kcmjv4p5mmgh89nj58n69uu3fz3cvk3jn500hqs7emz79 <1a7496365ae2df8adb1b932a1a6f68b9cb3950f3d179c8a451c32d194e8f7dc1@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: npub1rf6fvdj6ut0c4kcmjv4p5mmgh89nj58n69uu3fz3cvk3jn500hqs7emz79 <1a7496365ae2df8adb1b932a1a6f68b9cb3950f3d179c8a451c32d194e8f7dc1@sprout-oss.stage.blox.sqprod.co>
2026-07-30 10:48:54 -07:00
Wes
61b96c9828 fix(catalog): update Amp description (#3758)
## Summary
- replace Amp's outdated Sourcegraph attribution in the runtime catalog
- describe Amp neutrally as a coding agent for the terminal and editor

## Verification
- `pnpm test` (desktop: 3,819 passed)
- `pnpm typecheck`
- pre-push `desktop-check`, `desktop-test`, and `branch-skew` hooks

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz>
2026-07-30 12:54:13 -04:00