diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md index e383313452..c951650eb1 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.md +++ b/.github/ISSUE_TEMPLATE/bug-report.md @@ -4,6 +4,10 @@ about: Report a reproducible bug in Buzz labels: bug --- +> [!IMPORTANT] +> Do not include security vulnerabilities in a public issue. [Report them +> privately through a GitHub security advisory](https://github.com/block/buzz/security/advisories/new). + **Describe the bug** A clear and concise description of what the bug is. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 0086358db1..67bfbe0ce4 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1 +1,5 @@ blank_issues_enabled: true +contact_links: + - name: Report a security vulnerability + url: https://github.com/block/buzz/security/advisories/new + about: Report security vulnerabilities privately to the Buzz maintainers. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59b9a73ec9..8016766812 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,6 +87,10 @@ jobs: scripts/test-mobile-release-candidate-publisher.sh - name: Mobile worktree identity contract run: scripts/test-mobile-worktree-overrides.sh + - name: Rust cache contract + run: | + scripts/test-rust-cache-contract.sh + scripts/test-rust-cache-contract-regressions.sh - name: File size policy run: just file-size-check @@ -101,7 +105,7 @@ jobs: steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: save-if: ${{ github.event_name != 'pull_request' }} - name: Format check @@ -123,8 +127,9 @@ jobs: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - uses: rui314/setup-mold@9c9c13bf4c3f1adef0cc596abc155580bcb04444 # v1 - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: + key: sherpa-cache-v1 save-if: ${{ github.event_name != 'pull_request' }} - name: Install cargo-nextest uses: taiki-e/install-action@0fd46367812ee04360509b4169d9f659d6892bb2 # v2.79.15 @@ -147,7 +152,7 @@ jobs: fetch-depth: 2 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - uses: rui314/setup-mold@9c9c13bf4c3f1adef0cc596abc155580bcb04444 # v1 - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: workspaces: desktop/src-tauri save-if: ${{ github.event_name != 'pull_request' }} @@ -340,7 +345,7 @@ jobs: key: relay-artifacts-${{ runner.os }}-${{ hashFiles('crates/**', 'migrations/**', 'Dockerfile', 'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', '.cargo/config.toml', '.github/workflows/ci.yml') }} - uses: rui314/setup-mold@9c9c13bf4c3f1adef0cc596abc155580bcb04444 # v1 if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 if: steps.relay-artifacts-cache.outputs.cache-hit != 'true' with: workspaces: | @@ -674,6 +679,19 @@ jobs: VALUES ('00000000-0000-4000-8000-00000000c0de', 'localhost:3000') ON CONFLICT (lower(host)) DO NOTHING ;" + - name: Replaceable persistence PostgreSQL tests + # Transaction, concurrency, and mention-index coverage for the + # replaceable-event store seam. These tests require real Postgres and + # are ignored by the infrastructure-free unit-test job. + run: | + filter='package(buzz-db) and test(/tests::(parameterized_|concurrent_parameterized_)/)' + cargo nextest run \ + --archive-file target/ci/backend-integration-tests.tar.zst \ + -E "${filter}" \ + --run-ignored ignored-only + env: + DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz + TEST_DATABASE_URL: postgres://buzz:${{ env.BUZZ_TEST_POSTGRES_PASSWORD }}@localhost:5432/buzz - name: Start relay run: | chmod +x ./target/ci/buzz-relay @@ -763,7 +781,7 @@ jobs: steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: save-if: ${{ github.event_name != 'pull_request' }} # Reuse the relay + git-credential-nostr built by Desktop E2E Relay @@ -952,7 +970,7 @@ jobs: steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: key: cross-${{ matrix.target }} save-if: ${{ github.event_name != 'pull_request' }} @@ -993,7 +1011,7 @@ jobs: # toolchain (1.95.0 + clippy via profile = default) comes from the # repo-root rust-toolchain.toml, which the runner's preinstalled rustup # honors on demand; the host triple already is x86_64-pc-windows-msvc. - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: workspaces: | . @@ -1070,7 +1088,7 @@ jobs: steps: - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: workspaces: desktop/src-tauri save-if: ${{ github.event_name != 'pull_request' }} diff --git a/.github/workflows/mesh-lifecycle.yml b/.github/workflows/mesh-lifecycle.yml index b5f9660dfe..c699439980 100644 --- a/.github/workflows/mesh-lifecycle.yml +++ b/.github/workflows/mesh-lifecycle.yml @@ -55,7 +55,7 @@ jobs: - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: save-if: ${{ github.event_name != 'pull_request' }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cc8147515a..187604fcf4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -511,7 +511,7 @@ jobs: - uses: cashapp/activate-hermit@cea9af7913204a965fd488637a8d1811bba2e616 # v1 - - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2.9.1 with: workspaces: desktop/src-tauri lookup-only: true diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index db0aea637f..0247b570a2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,6 +6,10 @@ get from zero to a merged pull request. If you have questions that aren't answered here, [open an issue](https://github.com/block/buzz/issues/new). +If you believe you found a security vulnerability, do not open a public issue. +Follow our [security policy](SECURITY.md) to submit a private vulnerability +report instead. + --- ## Table of Contents diff --git a/SECURITY.md b/SECURITY.md index 45202b10fb..add36efee4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,16 +2,25 @@ ## Reporting a Vulnerability -**Please do not report security vulnerabilities through public GitHub issues.** +**Do not report security vulnerabilities through a public GitHub issue, pull +request, discussion, or other public channel.** -If you discover a security vulnerability in Buzz, please report it by emailing -**buzz@block.xyz**. Include as much detail as possible: +Use GitHub's private vulnerability reporting form instead: + +**[Report a vulnerability privately](https://github.com/block/buzz/security/advisories/new)** + +Submitting the form starts a private security advisory with the Buzz +maintainers. Use that advisory for vulnerability details, follow-up questions, +and coordinated remediation. Include as much detail as possible: - A description of the vulnerability and its potential impact - Steps to reproduce or a proof-of-concept (if available) - The affected version(s) or commit range - Any suggested mitigations you've identified +If GitHub's private reporting form is unavailable to you, email +**buzz@block.xyz** and do not include vulnerability details in a public issue. + You will receive an acknowledgment within **48 hours**. We aim to provide a full response — including a timeline for a fix — within **7 days** of initial contact. We'll keep you informed as we work toward a resolution. @@ -121,4 +130,6 @@ We use `cargo audit` in CI to scan for known vulnerabilities in dependencies. ## Disclosure Policy We follow [coordinated disclosure](https://en.wikipedia.org/wiki/Coordinated_vulnerability_disclosure). -Reporters will be credited unless they request anonymity. +We use the private advisory to coordinate validation, remediation, and +disclosure with the reporter. Reporters will be credited unless they request +anonymity. diff --git a/crates/buzz-db/src/channel.rs b/crates/buzz-db/src/channel.rs index 109a9367d7..a1890adb56 100644 --- a/crates/buzz-db/src/channel.rs +++ b/crates/buzz-db/src/channel.rs @@ -625,7 +625,7 @@ pub async fn lock_member_snapshot( // this key before INSERT; migration 0032 then takes the membership key in // the INSERT trigger. Taking both in that order avoids mixed-version // duplicate heads without introducing a lock-order inversion. - let replacement_lock = crate::event_replacement_lock_key( + let replacement_lock = crate::replaceable::event_replacement_lock_key( community_id, 39002, relay_pubkey, diff --git a/crates/buzz-db/src/event.rs b/crates/buzz-db/src/event.rs index 5d682d7843..dcfc97c844 100644 --- a/crates/buzz-db/src/event.rs +++ b/crates/buzz-db/src/event.rs @@ -6,7 +6,7 @@ use chrono::{DateTime, Utc}; use nostr::Event; -use sqlx::{PgPool, Postgres, QueryBuilder, Row, Transaction}; +use sqlx::{PgConnection, PgPool, Postgres, QueryBuilder, Row, Transaction}; use uuid::Uuid; use buzz_core::kind::{ @@ -275,6 +275,30 @@ pub async fn insert_event( community_id: CommunityId, event: &Event, channel_id: Option, +) -> Result<(StoredEvent, bool)> { + let mut connection = pool.acquire().await?; + insert_event_on(&mut connection, community_id, event, channel_id).await +} + +/// Insert a Nostr event in a caller-owned PostgreSQL transaction. +/// +/// This is the transaction-composition seam for callers that must keep the +/// event insert open while performing related work. The caller owns commit or +/// rollback. +pub async fn insert_event_in_transaction( + tx: &mut Transaction<'_, Postgres>, + community_id: CommunityId, + event: &Event, + channel_id: Option, +) -> Result<(StoredEvent, bool)> { + insert_event_on(tx.as_mut(), community_id, event, channel_id).await +} + +async fn insert_event_on( + connection: &mut PgConnection, + community_id: CommunityId, + event: &Event, + channel_id: Option, ) -> Result<(StoredEvent, bool)> { let kind_u16 = event.kind.as_u16(); let kind_u32 = u32::from(kind_u16); @@ -317,7 +341,7 @@ pub async fn insert_event( .bind(channel_id) .bind(d_tag.as_deref()) .bind(not_before) - .execute(pool) + .execute(connection) .await?; let was_inserted = result.rows_affected() > 0; @@ -1607,6 +1631,31 @@ mod tests { id } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn event_insert_in_existing_transaction_rolls_back_with_caller() { + let pool = setup_pool().await; + let community_uuid = make_test_community(&pool).await; + let community = CommunityId::from_uuid(community_uuid); + let event = make_text_event("caller-owned transaction"); + + let mut tx = pool.begin().await.expect("begin event insert transaction"); + let (_, was_inserted) = insert_event_in_transaction(&mut tx, community, &event, None) + .await + .expect("insert event in caller transaction"); + assert!(was_inserted); + tx.rollback().await.expect("roll back event insert"); + + let persisted: i64 = + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id = $1 AND id = $2") + .bind(community_uuid) + .bind(event.id.as_bytes().as_slice()) + .fetch_one(&pool) + .await + .expect("count rolled-back event"); + assert_eq!(persisted, 0); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn event_insert_ttl_trigger_handles_permanent_ephemeral_duplicate_and_activation_race() { diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 3ff230f950..cbce6d3753 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -8,6 +8,21 @@ //! - Events table is partitioned by month on `created_at`. //! - No FK references to partitioned tables. //! - Uses `sqlx::query()` (runtime) not `sqlx::query!()` (compile-time). +//! +//! ## Runtime and store ownership +//! This crate intentionally keeps database runtime and Buzz domain persistence +//! together while maintaining an internal boundary between them: +//! +//! - Runtime concerns own pool construction, writer/replica routing, transaction +//! creation, session invariants, metrics, and health support. +//! - Store concerns own domain-specific SQL, row mapping, locking, mutation +//! rules, indexes, and focused persistence tests. +//! +//! Transaction-required store operations accept [`sqlx::Transaction`] so their +//! composition requirement is visible in the type. Private connection helpers +//! are reserved for SQL primitives that are valid on any same-session +//! connection. New domains should prove this boundary incrementally instead of +//! exposing raw pools or introducing broad store traits. /// Explicit deployment-global admin report reads. pub mod admin_moderation; @@ -45,6 +60,8 @@ pub mod reaction; pub mod relay_invite; /// Relay-level membership persistence (NIP-43). pub mod relay_members; +/// Replaceable-event persistence and coordinate locking. +pub mod replaceable; /// Replica freshness fence for keyset-cursor read routing. pub mod replica_fence; /// Thread metadata persistence. @@ -68,37 +85,12 @@ use uuid::Uuid; use buzz_core::{CommunityId, StoredEvent}; -pub(crate) fn event_replacement_lock_key( - community_id: CommunityId, - kind: i32, - pubkey: &[u8], - coordinate: Option<&[u8]>, -) -> i64 { - let mut hash: u64 = 0xcbf29ce484222325; - let kind_bytes = kind.to_le_bytes(); - for bytes in [ - community_id.as_uuid().as_bytes().as_slice(), - kind_bytes.as_slice(), - pubkey, - ] { - for byte in bytes { - hash ^= *byte as u64; - hash = hash.wrapping_mul(0x100000001b3); - } - } - if let Some(coordinate) = coordinate { - for byte in coordinate { - hash ^= *byte as u64; - hash = hash.wrapping_mul(0x100000001b3); - } - } - hash as i64 -} - /// Extract p-tag mentions from an event and insert into the `event_mentions` table. /// -/// Called after event insertion. Failures are logged but do not block event storage. -/// Uses `INSERT ... ON CONFLICT DO NOTHING` so duplicate inserts are silently skipped. +/// This pool-owning wrapper propagates failures to its caller. Replacement writes +/// use the transaction-bound helper below so event storage and mention indexing +/// commit or roll back together. Duplicate inserts are silently skipped with +/// `INSERT ... ON CONFLICT DO NOTHING`. pub async fn insert_mentions( pool: &PgPool, community_id: CommunityId, @@ -4875,7 +4867,7 @@ impl Db { .ok_or(DbError::InvalidTimestamp(created_at_secs))?; // Collisions only cause extra serialization; they cannot change behavior. - let lock_key = event_replacement_lock_key( + let lock_key = replaceable::event_replacement_lock_key( community_id, kind_i32, pubkey_bytes.as_slice(), @@ -5058,8 +5050,12 @@ impl Db { let kind_i32 = buzz_core::kind::KIND_NIP43_MEMBERSHIP_LIST as i32; let pubkey_bytes = relay_keypair.public_key().to_bytes(); - let lock_key = - event_replacement_lock_key(community_id, kind_i32, pubkey_bytes.as_slice(), None); + let lock_key = replaceable::event_replacement_lock_key( + community_id, + kind_i32, + pubkey_bytes.as_slice(), + None, + ); let mut tx = self.pool.begin().await?; @@ -5166,243 +5162,6 @@ impl Db { member_count, )) } - - /// Atomically replace a NIP-33 parameterized replaceable event (kind 30000–39999). - /// - /// Keeps only the event with the highest `created_at` per `(kind, pubkey, d_tag)`. - /// Same-second ties are broken by lowest event `id` (deterministic ordering). - /// The entire check → retire old payload → insert runs in a single transaction - /// with an advisory lock to prevent concurrent-insert races. NIP-RS read-state - /// coordinates hard-delete the superseded payload and preserve a compact - /// ordering watermark. Buzz mesh status coordinates also hard-delete their - /// superseded heartbeat payload because only the live head has product - /// value; other NIP-33 kinds retain soft-deleted history. - /// - /// **Channel policy:** NIP-33 replacement keys on `(kind, pubkey, d_tag)` globally — - /// `channel_id` is NOT part of the replacement key. This matches the Nostr spec: - /// an author's parameterized replaceable event is a single global resource identified - /// by its d-tag, regardless of which channel it was submitted to. The `channel_id` - /// parameter is stored on the new row for query scoping but does not affect replacement. - /// - /// Note: `replace_addressable_event()` keys on `channel_id` because it serves - /// relay-signed NIP-29 group metadata (kind 39000–39002) where the relay is the - /// author and channel_id distinguishes groups. User-submitted NIP-33 events use - /// this function instead, where the author's pubkey + d-tag is the natural key. - #[datastore_span(name = "replace_parameterized_event", system = "postgresql")] - pub async fn replace_parameterized_event( - &self, - community_id: CommunityId, - event: &nostr::Event, - d_tag: &str, - channel_id: Option, - ) -> Result<(StoredEvent, bool)> { - let kind_i32 = buzz_core::kind::event_kind_i32(event); - let pubkey_bytes = event.pubkey.to_bytes(); - let created_at_secs = event.created_at.as_secs() as i64; - let created_at = chrono::DateTime::from_timestamp(created_at_secs, 0) - .ok_or(DbError::InvalidTimestamp(created_at_secs))?; - - let lock_key = event_replacement_lock_key( - community_id, - kind_i32, - pubkey_bytes.as_slice(), - Some(d_tag.as_bytes()), - ); - - let mut tx = self.pool.begin().await?; - - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(lock_key) - .execute(&mut *tx) - .await?; - - let d_tag_count = event - .tags - .iter() - .filter(|tag| tag.as_slice().first().is_some_and(|part| part == "d")) - .count(); - let has_exact_d_tag = event.tags.iter().any(|tag| { - let parts = tag.as_slice(); - parts.len() >= 2 && parts[0] == "d" && parts[1] == d_tag - }); - let read_state_t_tag_count = event - .tags - .iter() - .filter(|tag| { - let parts = tag.as_slice(); - parts.len() == 2 && parts[0] == "t" && parts[1] == "read-state" - }) - .count(); - let is_nip_rs = kind_i32 == buzz_core::kind::KIND_READ_STATE as i32 - && d_tag_count == 1 - && has_exact_d_tag - && d_tag.strip_prefix("read-state:").is_some_and(|slot| { - slot.len() == 32 - && slot - .bytes() - .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) - }) - && read_state_t_tag_count == 1; - let is_buzz_mesh_status = kind_i32 == buzz_core::kind::KIND_BOOKMARK_SET as i32 - && d_tag.starts_with("buzz-mesh-member-status:") - && event.tags.iter().any(|tag| { - let parts = tag.as_slice(); - parts.len() == 2 && parts[0] == "k" && parts[1] == "buzz-mesh-status" - }); - let hard_delete_superseded = is_nip_rs || is_buzz_mesh_status; - - // Check the live head and, for NIP-RS, the compact historical ordering - // watermark. The watermark remains after a NIP-09 coordinate deletion, - // preventing a previously accepted signed blob from being resurrected. - let existing: Option<(chrono::DateTime, Vec)> = sqlx::query_as( - "SELECT created_at, id FROM events \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL \ - ORDER BY created_at DESC, id ASC LIMIT 1", - ) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(d_tag) - .fetch_optional(&mut *tx) - .await?; - let watermark: Option<(chrono::DateTime, Vec)> = if is_nip_rs { - sqlx::query_as( - "SELECT created_at, event_id FROM parameterized_event_watermarks \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4", - ) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(d_tag) - .fetch_optional(&mut *tx) - .await? - } else { - None - }; - - // Stale-write protection: reject if either durable ordering source - // dominates the incoming tuple. Equal timestamps use lowest event id. - let incoming_id = event.id.as_bytes().as_slice(); - let dominated = - existing - .iter() - .chain(watermark.iter()) - .any(|(accepted_ts, accepted_id)| { - created_at < *accepted_ts - || (created_at == *accepted_ts && incoming_id >= accepted_id.as_slice()) - }); - if dominated { - tx.rollback().await?; - let received_at = chrono::Utc::now(); - return Ok(( - StoredEvent::with_received_at(event.clone(), received_at, channel_id, false), - false, - )); - } - - if existing.is_some() { - if is_nip_rs { - // Migration 0011 rejects regex-coordinate hard deletes from - // pre-fix writers. Authorize only this corrected NIP-RS delete, - // transaction-locally so pooled connections cannot leak it. - sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") - .execute(&mut *tx) - .await?; - } - let statement = if hard_delete_superseded { - "DELETE FROM events \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" - } else { - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" - }; - sqlx::query(statement) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(d_tag) - .execute(&mut *tx) - .await?; - - if hard_delete_superseded { - if let Some((_, existing_id)) = &existing { - // Event first, mentions second: migration 0009's live-event - // fence uses this global lock order to avoid deadlocks. - sqlx::query( - "DELETE FROM event_mentions WHERE community_id = $1 AND event_id = $2", - ) - .bind(community_id.as_uuid()) - .bind(existing_id) - .execute(&mut *tx) - .await?; - } - } - } - - // Insert the new event inside the transaction. - let sig_bytes = event.sig.serialize(); - let tags_json = serde_json::to_value(&event.tags)?; - let received_at = chrono::Utc::now(); - - let insert_result = sqlx::query( - "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag, not_before) \ - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) \ - ON CONFLICT DO NOTHING", - ) - .bind(community_id.as_uuid()) - .bind(event.id.as_bytes().as_slice()) - .bind(pubkey_bytes.as_slice()) - .bind(created_at) - .bind(kind_i32) - .bind(&tags_json) - .bind(&event.content) - .bind(sig_bytes.as_slice()) - .bind(received_at) - .bind(channel_id) - .bind(d_tag) - .bind(event::extract_not_before(event)) - .execute(&mut *tx) - .await?; - - let was_inserted = insert_result.rows_affected() > 0; - if !was_inserted { - tx.rollback().await?; - return Ok(( - StoredEvent::with_received_at(event.clone(), received_at, channel_id, false), - false, - )); - } - - if is_nip_rs { - sqlx::query( - "INSERT INTO parameterized_event_watermarks \ - (community_id, kind, pubkey, d_tag, created_at, event_id) \ - VALUES ($1, $2, $3, $4, $5, $6) \ - ON CONFLICT (community_id, kind, pubkey, d_tag) DO UPDATE SET \ - created_at = EXCLUDED.created_at, event_id = EXCLUDED.event_id", - ) - .bind(community_id.as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(d_tag) - .bind(created_at) - .bind(incoming_id) - .execute(&mut *tx) - .await?; - } - - tx.commit().await?; - - // Mentions are a denormalized index — safe outside the transaction. - if let Err(e) = crate::insert_mentions(&self.pool, community_id, event, channel_id).await { - tracing::warn!(event_id = %event.id, "Failed to insert mentions: {e}"); - } - - Ok(( - StoredEvent::with_received_at(event.clone(), received_at, channel_id, true), - true, - )) - } } /// A full API token record. @@ -6014,6 +5773,456 @@ mod tests { assert_eq!(live, 0, "watermark must block stale resurrection"); } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn nip_rs_transaction_operation_restores_hard_delete_opt_in() { + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + + let db = setup_db().await; + let community = CommunityId::from_uuid(make_community(&db.pool).await); + let keys = Keys::generate(); + let base = Timestamp::now().as_secs(); + let replace_d_tag = format!("read-state:{}", "b".repeat(32)); + let victim_d_tag = format!("read-state:{}", "c".repeat(32)); + let event = |d_tag: &str, content: &str, timestamp: u64| { + EventBuilder::new( + Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16), + content, + ) + .tags(vec![ + Tag::parse(["d", d_tag]).expect("d tag"), + Tag::parse(["t", "read-state"]).expect("t tag"), + ]) + .custom_created_at(Timestamp::from(timestamp)) + .sign_with_keys(&keys) + .expect("sign read state") + }; + let old = event(&replace_d_tag, "old", base); + let new = event(&replace_d_tag, "new", base + 1); + let victim = event(&victim_d_tag, "victim", base); + + assert!( + db.replace_parameterized_event(community, &old, &replace_d_tag, None) + .await + .expect("insert old head") + .1 + ); + assert!( + db.replace_parameterized_event(community, &victim, &victim_d_tag, None) + .await + .expect("insert victim head") + .1 + ); + + let mut tx = db + .begin_transaction() + .await + .expect("begin caller transaction"); + let result = db + .replace_parameterized_event_in_transaction( + &mut tx, + community, + &new, + &replace_d_tag, + None, + replaceable::ParameterizedReplacePrecondition::Unconditional, + ) + .await + .expect("replace inside caller transaction"); + assert_eq!( + result.status, + replaceable::ParameterizedReplaceStatus::Inserted + ); + + let leaked: Option = sqlx::query_scalar( + "SELECT NULLIF(current_setting('buzz.nip_rs_hard_delete', true), '')", + ) + .fetch_one(&mut *tx) + .await + .expect("read hard-delete opt-in after replacement"); + assert_ne!(leaked.as_deref(), Some("on")); + + let unauthorized = sqlx::query( + "DELETE FROM events WHERE community_id=$1 AND kind=30078 \ + AND pubkey=$2 AND d_tag=$3 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(keys.public_key().to_bytes()) + .bind(&victim_d_tag) + .execute(&mut *tx) + .await; + assert!( + unauthorized.is_err(), + "replacement opt-in must not authorize later caller SQL" + ); + tx.rollback().await.expect("roll back caller transaction"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn parameterized_replacement_in_existing_transaction_honors_revision_and_rollback() { + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + + let db = setup_db().await; + let community = CommunityId::from_uuid(make_community(&db.pool).await); + let keys = Keys::generate(); + let d_tag = format!("transactional-project-{}", Uuid::new_v4().simple()); + let base = Timestamp::now().as_secs(); + let event = |content: &str, timestamp: u64| { + EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_PROJECT as u16), content) + .tags(vec![Tag::parse(["d", d_tag.as_str()]).expect("d tag")]) + .custom_created_at(Timestamp::from(timestamp)) + .sign_with_keys(&keys) + .expect("sign project") + }; + let old = event("old", base); + let new = event("new", base + 1); + + assert!( + db.replace_parameterized_event(community, &old, &d_tag, None) + .await + .expect("insert old head") + .1 + ); + + let mut tx = db.begin_transaction().await.expect("begin replacement tx"); + let outcome = db + .replace_parameterized_event_in_transaction( + &mut tx, + community, + &new, + &d_tag, + None, + replaceable::ParameterizedReplacePrecondition::ExpectedRevision( + old.id.as_bytes().as_slice(), + ), + ) + .await + .expect("replace inside caller transaction"); + assert_eq!( + outcome.status, + replaceable::ParameterizedReplaceStatus::Inserted + ); + tx.rollback().await.expect("roll back replacement tx"); + + let live_id: Vec = sqlx::query_scalar( + "SELECT id FROM events WHERE community_id=$1 AND kind=$2 AND pubkey=$3 \ + AND d_tag=$4 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(buzz_core::kind::KIND_PROJECT as i32) + .bind(keys.public_key().to_bytes()) + .bind(&d_tag) + .fetch_one(&db.pool) + .await + .expect("load live head after rollback"); + assert_eq!(live_id, old.id.as_bytes().to_vec()); + + let mut tx = db + .begin_transaction() + .await + .expect("begin stale revision tx"); + let mismatch = db + .replace_parameterized_event_in_transaction( + &mut tx, + community, + &new, + &d_tag, + None, + replaceable::ParameterizedReplacePrecondition::ExpectedRevision( + [0x42; 32].as_slice(), + ), + ) + .await + .expect("evaluate stale revision"); + assert_eq!( + mismatch.status, + replaceable::ParameterizedReplaceStatus::RevisionMismatch + ); + tx.rollback().await.expect("roll back stale revision tx"); + + let missing_d_tag = format!("missing-project-{}", Uuid::new_v4().simple()); + let missing = EventBuilder::new( + Kind::Custom(buzz_core::kind::KIND_PROJECT as u16), + "missing", + ) + .tags(vec![ + Tag::parse(["d", missing_d_tag.as_str()]).expect("missing d tag") + ]) + .custom_created_at(Timestamp::from(base + 2)) + .sign_with_keys(&keys) + .expect("sign missing project"); + let mut tx = db + .begin_transaction() + .await + .expect("begin missing revision tx"); + let missing_result = db + .replace_parameterized_event_in_transaction( + &mut tx, + community, + &missing, + &missing_d_tag, + None, + replaceable::ParameterizedReplacePrecondition::ExpectedRevision( + [0x24; 32].as_slice(), + ), + ) + .await + .expect("evaluate missing revision"); + assert_eq!( + missing_result.status, + replaceable::ParameterizedReplaceStatus::RevisionMissing + ); + tx.rollback().await.expect("roll back missing revision tx"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn parameterized_replacement_rolls_back_when_mention_indexing_fails() { + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + + let admin = PgPool::connect(&admin_url().await) + .await + .expect("connect admin"); + let (pool, scratch_name) = create_scratch_db(&admin, "atomic_parameterized").await; + let db = Db::from_pool(pool.clone()); + let community = CommunityId::from_uuid(make_community(&pool).await); + let keys = Keys::generate(); + let mentioned = Keys::generate().public_key().to_hex(); + let d_tag = format!("mention-project-{}", Uuid::new_v4().simple()); + let tags = || { + vec![ + Tag::parse(["d", d_tag.as_str()]).expect("d tag"), + Tag::parse(["p", mentioned.as_str()]).expect("p tag"), + ] + }; + let base = Timestamp::now().as_secs(); + let old = EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_PROJECT as u16), "old") + .tags(tags()) + .custom_created_at(Timestamp::from(base)) + .sign_with_keys(&keys) + .expect("sign old project"); + let new = EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_PROJECT as u16), "new") + .tags(tags()) + .custom_created_at(Timestamp::from(base + 1)) + .sign_with_keys(&keys) + .expect("sign new project"); + + assert!( + db.replace_parameterized_event(community, &old, &d_tag, None) + .await + .expect("insert old project") + .1 + ); + sqlx::query( + "CREATE FUNCTION reject_test_mention() RETURNS trigger AS $$ \ + BEGIN RAISE EXCEPTION 'injected mention failure'; END; \ + $$ LANGUAGE plpgsql", + ) + .execute(&pool) + .await + .expect("create failure function"); + sqlx::query( + "CREATE TRIGGER reject_test_mention BEFORE INSERT ON event_mentions \ + FOR EACH ROW EXECUTE FUNCTION reject_test_mention()", + ) + .execute(&pool) + .await + .expect("install failure injection"); + + let mut tx = db + .begin_transaction() + .await + .expect("begin caller transaction"); + let error = db + .replace_parameterized_event_in_transaction( + &mut tx, + community, + &new, + &d_tag, + None, + replaceable::ParameterizedReplacePrecondition::Unconditional, + ) + .await + .expect_err("mention failure must fail replacement"); + assert!(error.to_string().contains("injected mention failure")); + + let probe: i32 = sqlx::query_scalar("SELECT 1") + .fetch_one(&mut *tx) + .await + .expect("inner failure must leave caller transaction usable"); + assert_eq!(probe, 1); + + let live_id: Vec = sqlx::query_scalar( + "SELECT id FROM events WHERE community_id=$1 AND kind=$2 AND pubkey=$3 \ + AND d_tag=$4 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(buzz_core::kind::KIND_PROJECT as i32) + .bind(keys.public_key().to_bytes()) + .bind(&d_tag) + .fetch_one(&mut *tx) + .await + .expect("load live project after failed indexing"); + assert_eq!(live_id, old.id.as_bytes().to_vec()); + let new_rows: i64 = + sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(new.id.as_bytes().as_slice()) + .fetch_one(&mut *tx) + .await + .expect("count rolled-back project"); + assert_eq!(new_rows, 0); + tx.commit().await.expect("commit usable caller transaction"); + + drop_scratch_db(&admin, pool, &scratch_name).await; + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn parameterized_duplicate_restores_live_head_inside_caller_transaction() { + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + + let db = setup_db().await; + let community = CommunityId::from_uuid(make_community(&db.pool).await); + let keys = Keys::generate(); + let d_tag = format!("duplicate-project-{}", Uuid::new_v4().simple()); + let base = Timestamp::now().as_secs(); + let event = |content: &str, timestamp: u64| { + EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_PROJECT as u16), content) + .tags(vec![Tag::parse(["d", d_tag.as_str()]).expect("d tag")]) + .custom_created_at(Timestamp::from(timestamp)) + .sign_with_keys(&keys) + .expect("sign project") + }; + let old = event("old-live-head", base); + let duplicate = event("soft-deleted-duplicate", base + 1); + + assert!( + db.replace_parameterized_event(community, &duplicate, &d_tag, None) + .await + .expect("insert future duplicate") + .1 + ); + sqlx::query("UPDATE events SET deleted_at=NOW() WHERE community_id=$1 AND id=$2") + .bind(community.as_uuid()) + .bind(duplicate.id.as_bytes().as_slice()) + .execute(&db.pool) + .await + .expect("soft-delete duplicate row"); + + let mut seed_tx = db + .begin_transaction() + .await + .expect("begin seed transaction"); + let (_, was_inserted) = + event::insert_event_in_transaction(&mut seed_tx, community, &old, None) + .await + .expect("insert older live head"); + assert!(was_inserted); + seed_tx.commit().await.expect("commit older live head"); + + let mut tx = db + .begin_transaction() + .await + .expect("begin caller transaction"); + let result = db + .replace_parameterized_event_in_transaction( + &mut tx, + community, + &duplicate, + &d_tag, + None, + replaceable::ParameterizedReplacePrecondition::Unconditional, + ) + .await + .expect("evaluate soft-deleted duplicate"); + assert_eq!( + result.status, + replaceable::ParameterizedReplaceStatus::Duplicate + ); + + let live_id: Vec = sqlx::query_scalar( + "SELECT id FROM events WHERE community_id=$1 AND kind=$2 AND pubkey=$3 \ + AND d_tag=$4 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(buzz_core::kind::KIND_PROJECT as i32) + .bind(keys.public_key().to_bytes()) + .bind(&d_tag) + .fetch_one(&mut *tx) + .await + .expect("caller transaction remains usable after duplicate"); + assert_eq!(live_id, old.id.as_bytes().to_vec()); + tx.rollback().await.expect("roll back caller transaction"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn concurrent_parameterized_replacement_keeps_deterministic_head() { + use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp}; + + let db = setup_db().await; + let community = CommunityId::from_uuid(make_community(&db.pool).await); + let keys = Keys::generate(); + let d_tag = format!("concurrent-project-{}", Uuid::new_v4().simple()); + let created_at = Timestamp::now().as_secs(); + let event = |content: &str, timestamp: u64| { + EventBuilder::new(Kind::Custom(buzz_core::kind::KIND_PROJECT as u16), content) + .tags(vec![Tag::parse(["d", d_tag.as_str()]).expect("d tag")]) + .custom_created_at(Timestamp::from(timestamp)) + .sign_with_keys(&keys) + .expect("sign project") + }; + let first = event("first", created_at); + let second = event("second", created_at); + let expected = if first.id.as_bytes() < second.id.as_bytes() { + &first + } else { + &second + }; + + let (first_result, second_result) = tokio::join!( + db.replace_parameterized_event(community, &first, &d_tag, None), + db.replace_parameterized_event(community, &second, &d_tag, None), + ); + let first_inserted = first_result.expect("first concurrent writer").1; + let second_inserted = second_result.expect("second concurrent writer").1; + assert!( + first_inserted || second_inserted, + "at least one concurrent writer must insert", + ); + + let live_ids: Vec> = sqlx::query_scalar( + "SELECT id FROM events WHERE community_id=$1 AND kind=$2 AND pubkey=$3 \ + AND d_tag=$4 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(buzz_core::kind::KIND_PROJECT as i32) + .bind(keys.public_key().to_bytes()) + .bind(&d_tag) + .fetch_all(&db.pool) + .await + .expect("load concurrent live head"); + assert_eq!(live_ids, vec![expected.id.as_bytes().to_vec()]); + + assert!( + !db.replace_parameterized_event(community, expected, &d_tag, None) + .await + .expect("replay winning event") + .1, + "replaying the live event must be idempotent", + ); + let stale = event("stale", created_at.saturating_sub(1)); + assert!( + !db.replace_parameterized_event(community, &stale, &d_tag, None) + .await + .expect("submit stale event") + .1, + "an older event must not replace the live head", + ); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn mesh_status_replacement_keeps_one_physical_row() { diff --git a/crates/buzz-db/src/replaceable.rs b/crates/buzz-db/src/replaceable.rs new file mode 100644 index 0000000000..aa57a51666 --- /dev/null +++ b/crates/buzz-db/src/replaceable.rs @@ -0,0 +1,417 @@ +//! Replaceable-event persistence and coordinate locking. + +use buzz_core::{CommunityId, StoredEvent}; +use buzz_datastore_tracing::datastore_span; +use chrono::{DateTime, Utc}; +use sqlx::{Acquire, Postgres, Transaction}; +use uuid::Uuid; + +use crate::{Db, DbError, Result}; + +/// Result category for a parameterized-replaceable event write. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ParameterizedReplaceStatus { + /// The incoming event was inserted as the coordinate's live head. + Inserted, + /// The exact event was already accepted. + Duplicate, + /// A newer event, or lower-ID same-second event, already dominates it. + Superseded, + /// A requested current revision has no live coordinate head. + RevisionMissing, + /// The live coordinate head differs from the requested revision. + RevisionMismatch, + /// An exact replay was required, but the event is not the live head. + ReplayOnlyMiss, +} + +/// Structural precondition for a parameterized-replaceable write. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ParameterizedReplacePrecondition<'a> { + /// Apply normal NIP-33 ordering without a revision precondition. + Unconditional, + /// Require the live head to match this validated event ID. + ExpectedRevision(&'a [u8]), + /// Accept only an exact live-head replay and perform no mutation otherwise. + ExactReplayOnly, +} + +/// Result of a transaction-bound parameterized-replaceable event write. +#[derive(Clone, Debug)] +pub struct ParameterizedReplaceResult { + /// Stored representation of the submitted event. + pub event: StoredEvent, + /// Whether and why the coordinate accepted the event. + pub status: ParameterizedReplaceStatus, +} + +impl ParameterizedReplaceResult { + fn new( + event: &nostr::Event, + received_at: DateTime, + channel_id: Option, + status: ParameterizedReplaceStatus, + ) -> Self { + Self { + event: StoredEvent::with_received_at( + event.clone(), + received_at, + channel_id, + status == ParameterizedReplaceStatus::Inserted, + ), + status, + } + } +} + +/// Derive the transaction-scoped advisory-lock key for an event coordinate. +/// +/// Hash collisions only add serialization; the SQL predicates still determine +/// which rows are read or changed. +pub(crate) fn event_replacement_lock_key( + community_id: CommunityId, + kind: i32, + pubkey: &[u8], + coordinate: Option<&[u8]>, +) -> i64 { + let mut hash: u64 = 0xcbf29ce484222325; + let kind_bytes = kind.to_le_bytes(); + for bytes in [ + community_id.as_uuid().as_bytes().as_slice(), + kind_bytes.as_slice(), + pubkey, + ] { + for byte in bytes { + hash ^= *byte as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + } + if let Some(coordinate) = coordinate { + for byte in coordinate { + hash ^= *byte as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + } + hash as i64 +} + +/// Replace a parameterized event in a caller-owned transaction. +/// +/// This function acquires a transaction-scoped advisory lock but never commits +/// or rolls back the outer transaction. The typed precondition can require the +/// current live head to have an exact event ID or restrict the operation to an +/// idempotent replay. +async fn replace_parameterized_event_in_transaction_impl( + tx: &mut Transaction<'_, Postgres>, + community_id: CommunityId, + event: &nostr::Event, + d_tag: &str, + channel_id: Option, + precondition: ParameterizedReplacePrecondition<'_>, +) -> Result { + let kind_i32 = buzz_core::kind::event_kind_i32(event); + let pubkey_bytes = event.pubkey.to_bytes(); + let created_at_secs = event.created_at.as_secs() as i64; + let created_at = DateTime::from_timestamp(created_at_secs, 0) + .ok_or(DbError::InvalidTimestamp(created_at_secs))?; + let received_at = Utc::now(); + + let lock_key = event_replacement_lock_key( + community_id, + kind_i32, + pubkey_bytes.as_slice(), + Some(d_tag.as_bytes()), + ); + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(lock_key) + .execute(&mut **tx) + .await?; + + let d_tag_count = event + .tags + .iter() + .filter(|tag| tag.as_slice().first().is_some_and(|part| part == "d")) + .count(); + let has_exact_d_tag = event.tags.iter().any(|tag| { + let parts = tag.as_slice(); + parts.len() >= 2 && parts[0] == "d" && parts[1] == d_tag + }); + let read_state_t_tag_count = event + .tags + .iter() + .filter(|tag| { + let parts = tag.as_slice(); + parts.len() == 2 && parts[0] == "t" && parts[1] == "read-state" + }) + .count(); + let is_nip_rs = kind_i32 == buzz_core::kind::KIND_READ_STATE as i32 + && d_tag_count == 1 + && has_exact_d_tag + && d_tag.strip_prefix("read-state:").is_some_and(|slot| { + slot.len() == 32 + && slot + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) + }) + && read_state_t_tag_count == 1; + let is_buzz_mesh_status = kind_i32 == buzz_core::kind::KIND_BOOKMARK_SET as i32 + && d_tag.starts_with("buzz-mesh-member-status:") + && event.tags.iter().any(|tag| { + let parts = tag.as_slice(); + parts.len() == 2 && parts[0] == "k" && parts[1] == "buzz-mesh-status" + }); + let hard_delete_superseded = is_nip_rs || is_buzz_mesh_status; + + let existing: Option<(DateTime, Vec)> = sqlx::query_as( + "SELECT created_at, id FROM events \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL \ + ORDER BY created_at DESC, id ASC LIMIT 1", + ) + .bind(community_id.as_uuid()) + .bind(kind_i32) + .bind(pubkey_bytes.as_slice()) + .bind(d_tag) + .fetch_optional(&mut **tx) + .await?; + let watermark: Option<(DateTime, Vec)> = if is_nip_rs { + sqlx::query_as( + "SELECT created_at, event_id FROM parameterized_event_watermarks \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4", + ) + .bind(community_id.as_uuid()) + .bind(kind_i32) + .bind(pubkey_bytes.as_slice()) + .bind(d_tag) + .fetch_optional(&mut **tx) + .await? + } else { + None + }; + + let incoming_id = event.id.as_bytes().as_slice(); + if existing + .as_ref() + .is_some_and(|(_, existing_id)| existing_id.as_slice() == incoming_id) + || watermark + .as_ref() + .is_some_and(|(_, event_id)| event_id.as_slice() == incoming_id) + { + return Ok(ParameterizedReplaceResult::new( + event, + received_at, + channel_id, + ParameterizedReplaceStatus::Duplicate, + )); + } + + if precondition == ParameterizedReplacePrecondition::ExactReplayOnly { + return Ok(ParameterizedReplaceResult::new( + event, + received_at, + channel_id, + ParameterizedReplaceStatus::ReplayOnlyMiss, + )); + } + + if let ParameterizedReplacePrecondition::ExpectedRevision(expected_revision) = precondition { + let status = match existing.as_ref() { + None => Some(ParameterizedReplaceStatus::RevisionMissing), + Some((_, existing_id)) if existing_id.as_slice() != expected_revision => { + Some(ParameterizedReplaceStatus::RevisionMismatch) + } + Some(_) => None, + }; + if let Some(status) = status { + return Ok(ParameterizedReplaceResult::new( + event, + received_at, + channel_id, + status, + )); + } + } + + let dominated = existing + .iter() + .chain(watermark.iter()) + .any(|(accepted_ts, accepted_id)| { + created_at < *accepted_ts + || (created_at == *accepted_ts && incoming_id >= accepted_id.as_slice()) + }); + if dominated { + return Ok(ParameterizedReplaceResult::new( + event, + received_at, + channel_id, + ParameterizedReplaceStatus::Superseded, + )); + } + + let mut savepoint = tx.begin().await?; + if existing.is_some() { + let previous_nip_rs_hard_delete: Option = if is_nip_rs { + sqlx::query_scalar( + "SELECT NULLIF(current_setting('buzz.nip_rs_hard_delete', true), '')", + ) + .fetch_one(&mut *savepoint) + .await? + } else { + None + }; + if is_nip_rs { + sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', 'on', true)") + .execute(&mut *savepoint) + .await?; + } + let statement = if hard_delete_superseded { + "DELETE FROM events \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" + } else { + "UPDATE events SET deleted_at = NOW() \ + WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL" + }; + sqlx::query(statement) + .bind(community_id.as_uuid()) + .bind(kind_i32) + .bind(pubkey_bytes.as_slice()) + .bind(d_tag) + .execute(&mut *savepoint) + .await?; + + if is_nip_rs { + let previous_value = previous_nip_rs_hard_delete.as_deref().unwrap_or_default(); + sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete', $1, true)") + .bind(previous_value) + .execute(&mut *savepoint) + .await?; + } + + if hard_delete_superseded { + if let Some((_, existing_id)) = &existing { + sqlx::query("DELETE FROM event_mentions WHERE community_id = $1 AND event_id = $2") + .bind(community_id.as_uuid()) + .bind(existing_id) + .execute(&mut *savepoint) + .await?; + } + } + } + + let sig_bytes = event.sig.serialize(); + let tags_json = serde_json::to_value(&event.tags)?; + let insert_result = sqlx::query( + "INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag, not_before) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) \ + ON CONFLICT DO NOTHING", + ) + .bind(community_id.as_uuid()) + .bind(incoming_id) + .bind(pubkey_bytes.as_slice()) + .bind(created_at) + .bind(kind_i32) + .bind(&tags_json) + .bind(&event.content) + .bind(sig_bytes.as_slice()) + .bind(received_at) + .bind(channel_id) + .bind(d_tag) + .bind(crate::event::extract_not_before(event)) + .execute(&mut *savepoint) + .await?; + + if insert_result.rows_affected() == 0 { + savepoint.rollback().await?; + return Ok(ParameterizedReplaceResult::new( + event, + received_at, + channel_id, + ParameterizedReplaceStatus::Duplicate, + )); + } + + if is_nip_rs { + sqlx::query( + "INSERT INTO parameterized_event_watermarks \ + (community_id, kind, pubkey, d_tag, created_at, event_id) \ + VALUES ($1, $2, $3, $4, $5, $6) \ + ON CONFLICT (community_id, kind, pubkey, d_tag) DO UPDATE SET \ + created_at = EXCLUDED.created_at, event_id = EXCLUDED.event_id", + ) + .bind(community_id.as_uuid()) + .bind(kind_i32) + .bind(pubkey_bytes.as_slice()) + .bind(d_tag) + .bind(created_at) + .bind(incoming_id) + .execute(&mut *savepoint) + .await?; + } + + crate::insert_mentions_in_transaction(&mut savepoint, community_id, event, channel_id).await?; + savepoint.commit().await?; + + Ok(ParameterizedReplaceResult::new( + event, + received_at, + channel_id, + ParameterizedReplaceStatus::Inserted, + )) +} + +impl Db { + /// Replace a NIP-33 event inside a caller-owned transaction. + /// + /// The caller owns commit or rollback. Requiring [`Transaction`] here and + /// in the internal state machine makes the advisory-lock contract explicit. + pub async fn replace_parameterized_event_in_transaction( + &self, + tx: &mut Transaction<'_, Postgres>, + community_id: CommunityId, + event: &nostr::Event, + d_tag: &str, + channel_id: Option, + precondition: ParameterizedReplacePrecondition<'_>, + ) -> Result { + replace_parameterized_event_in_transaction_impl( + tx, + community_id, + event, + d_tag, + channel_id, + precondition, + ) + .await + } + + /// Atomically replace a NIP-33 parameterized replaceable event. + /// + /// Replacement keys on `(kind, pubkey, d_tag)` across channels. The + /// highest timestamp wins; same-second ties use the lowest event ID. + #[datastore_span(name = "replace_parameterized_event", system = "postgresql")] + pub async fn replace_parameterized_event( + &self, + community_id: CommunityId, + event: &nostr::Event, + d_tag: &str, + channel_id: Option, + ) -> Result<(StoredEvent, bool)> { + let mut tx = self.pool.begin().await?; + let result = self + .replace_parameterized_event_in_transaction( + &mut tx, + community_id, + event, + d_tag, + channel_id, + ParameterizedReplacePrecondition::Unconditional, + ) + .await?; + let was_inserted = result.status == ParameterizedReplaceStatus::Inserted; + if was_inserted { + tx.commit().await?; + } else { + tx.rollback().await?; + } + Ok((result.event, was_inserted)) + } +} diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 8fdea4b3c0..bbfcd8ecfe 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -393,6 +393,83 @@ const WINDOW_AUX_DELETE_KINDS: [u32; 2] = [ buzz_core::kind::KIND_NIP29_DELETE_EVENT, ]; +/// Page size for one aux-closure hop. Matches the DB clamp +/// (`buzz_db::DEFAULT_MAX_PAGE_LIMIT`) so each page is one full query. +const AUX_PAGE_LIMIT: i64 = buzz_db::DEFAULT_MAX_PAGE_LIMIT; +/// Upper bound on pages drained per hop: 64k aux events referencing one page +/// of rows is far past any real thread; past it we log and stop rather than +/// loop forever against a pathological write pattern. +const AUX_MAX_PAGES: usize = 64; + +fn build_aux_query( + community: buzz_core::CommunityId, + target_ids: Vec, + kinds: &[u32], +) -> buzz_db::EventQuery { + let mut query = buzz_db::EventQuery::for_community(community); + query.kinds = Some(kinds.iter().map(|kind| *kind as i32).collect()); + query.e_tags = Some(target_ids); + query +} + +/// Where an aux hop reads from: the window path pins the request's proved +/// read session; the thread path takes the routed display-read fast path. +enum AuxReader<'a> { + Session(&'a mut buzz_db::ReadSession), + Routed(&'a buzz_db::Db, &'static str), + #[cfg(test)] + Fake(&'a mut (dyn FnMut(&buzz_db::EventQuery) -> Vec + Send)), +} + +impl AuxReader<'_> { + async fn fetch( + &mut self, + query: &buzz_db::EventQuery, + ) -> buzz_db::Result> { + match self { + AuxReader::Session(session) => session.query_events(query).await, + AuxReader::Routed(db, path) => db.query_events_routed(path, query).await, + #[cfg(test)] + AuxReader::Fake(fetch) => Ok(fetch(query)), + } + } +} + +/// Drain every event matching `query`, walking the `(created_at, id)` keyset +/// cursor `query_events` already orders by until a short page. An aux hop +/// over a reaction-heavy page can exceed a single page clamp, and because +/// results are newest-first a one-shot query silently drops the *oldest* +/// edits and deletions — rendering original or deleted content, not merely +/// losing decoration. +async fn query_all_pages( + mut query: buzz_db::EventQuery, + page_limit: i64, + reader: &mut AuxReader<'_>, +) -> buzz_db::Result> { + query.limit = Some(page_limit); + let mut events = Vec::new(); + for _ in 0..AUX_MAX_PAGES { + let page = reader.fetch(&query).await?; + let next = if page.len() as i64 >= page_limit { + page.last().map(|se| (se.event.created_at, se.event.id)) + } else { + None + }; + events.extend(page); + let Some((created_at, id)) = next else { + return Ok(events); + }; + query.until = chrono::DateTime::from_timestamp(created_at.as_secs() as i64, 0); + query.before_id = Some(id.to_bytes().to_vec()); + } + tracing::warn!( + pages = AUX_MAX_PAGES, + events = events.len(), + "aux closure hop exceeded page cap; returning truncated closure" + ); + Ok(events) +} + /// Serve one `top_level: true` channel-window filter on the bridge `/query` /// path (docs/bridge-channel-window.md). Appends, in order: row events, the /// aux closure (`include_aux`), `39005` thread-summary overlays @@ -496,14 +573,15 @@ async fn handle_channel_window_filter( std::collections::HashSet::new(); let mut hop_ids = row_ids_hex.clone(); for hop_kinds in [&WINDOW_AUX_KINDS[..], &WINDOW_AUX_DELETE_KINDS[..]] { - let mut aux_query = buzz_db::EventQuery::for_community(tenant.community()); - aux_query.kinds = Some(hop_kinds.iter().map(|k| *k as i32).collect()); - aux_query.e_tags = Some(std::mem::take(&mut hop_ids)); - aux_query.limit = Some(1000); - let aux_events = session - .query_events(&aux_query) - .await - .map_err(|e| internal_error(&format!("window aux error: {e}")))?; + let aux_query = + build_aux_query(tenant.community(), std::mem::take(&mut hop_ids), hop_kinds); + let aux_events = query_all_pages( + aux_query, + AUX_PAGE_LIMIT, + &mut AuxReader::Session(&mut session), + ) + .await + .map_err(|e| internal_error(&format!("window aux error: {e}")))?; for se in aux_events { if !seen_aux.insert(se.event.id) { continue; @@ -1203,6 +1281,8 @@ async fn query_events_authed( .await .map_err(|e| internal_error(&format!("thread query error: {e}")))?; + let mut thread_row_ids = Vec::with_capacity(thread_replies.len() + 1); + thread_row_ids.push(root_hex.to_string()); for reply in thread_replies { let se = reply.stored_event; if !event_in_accessible_channel(&se, &accessible_channels) { @@ -1214,10 +1294,45 @@ async fn query_events_authed( if !buzz_core::filter::reader_authorized_for_event(&se.event, &authed_pubkey_hex) { continue; } + thread_row_ids.push(se.event.id.to_hex()); if let Ok(v) = serde_json::to_value(&se.event) { events.push(v); } } + + if extension_flag(raw, "include_aux") && !thread_row_ids.is_empty() { + let mut seen_aux = std::collections::HashSet::new(); + let mut hop_ids = thread_row_ids; + for hop_kinds in [&WINDOW_AUX_KINDS[..], &WINDOW_AUX_DELETE_KINDS[..]] { + let aux_query = + build_aux_query(tenant.community(), std::mem::take(&mut hop_ids), hop_kinds); + let aux_events = query_all_pages( + aux_query, + AUX_PAGE_LIMIT, + &mut AuxReader::Routed(&state.db, "bridge_thread_aux"), + ) + .await + .map_err(|e| internal_error(&format!("thread aux query error: {e}")))?; + for se in aux_events { + if !seen_aux.insert(se.event.id) + || !event_in_accessible_channel(&se, &accessible_channels) + || !buzz_core::filter::reader_authorized_for_event( + &se.event, + &authed_pubkey_hex, + ) + { + continue; + } + hop_ids.push(se.event.id.to_hex()); + if let Ok(value) = serde_json::to_value(&se.event) { + events.push(value); + } + } + if hop_ids.is_empty() { + break; + } + } + } handled.insert(idx); } @@ -2373,6 +2488,113 @@ mod tests { assert!(!has_mixed_search_filters(&filters)); } + #[test] + fn thread_aux_query_targets_root_and_replies() { + let tenant = fresh_tenant("relay.example"); + let targets = vec!["root".to_string(), "reply".to_string()]; + let query = build_aux_query(tenant.community(), targets.clone(), &WINDOW_AUX_KINDS); + + assert_eq!(query.e_tags, Some(targets)); + assert_eq!( + query.kinds, + Some(WINDOW_AUX_KINDS.iter().map(|kind| *kind as i32).collect()) + ); + assert_eq!(query.limit, None); + assert_eq!(query.until, None); + assert_eq!(query.before_id, None); + } + + fn aux_event(keys: &Keys, created_at: u64, content: &str) -> buzz_core::StoredEvent { + let ev = EventBuilder::new(Kind::Custom(7), content) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(keys) + .unwrap(); + buzz_core::StoredEvent::new(ev, None) + } + + /// Carl/#6572: a one-shot `limit=1000` aux query is newest-first, so the + /// oldest reactions/edits/deletions past the clamp vanished. The paged + /// drain must walk the keyset cursor until a short page and return every + /// event exactly once. + #[tokio::test] + async fn query_all_pages_drains_past_the_page_clamp() { + let keys = Keys::generate(); + // Newest-first store: 5 events, two sharing a second so the id + // tiebreak is exercised. + let mut store = [ + aux_event(&keys, 50, "e"), + aux_event(&keys, 40, "d1"), + aux_event(&keys, 40, "d2"), + aux_event(&keys, 30, "c"), + aux_event(&keys, 10, "a"), + ]; + store.sort_by(|l, r| { + r.event + .created_at + .cmp(&l.event.created_at) + .then(l.event.id.cmp(&r.event.id)) + }); + let expected: Vec<_> = store.iter().map(|se| se.event.id).collect(); + let mut calls = Vec::new(); + + let tenant = fresh_tenant("relay.example"); + let query = build_aux_query(tenant.community(), vec!["root".into()], &WINDOW_AUX_KINDS); + let mut fetch = |q: &buzz_db::EventQuery| { + calls.push((q.limit, q.until, q.before_id.clone())); + // Emulate `query_events_on`: `created_at < until OR + // (created_at = until AND id > before_id)`, newest-first, limit. + let page: Vec<_> = store + .iter() + .filter(|se| match (q.until, q.before_id.as_deref()) { + (Some(until), Some(before)) => { + let ts = se.event.created_at.as_secs() as i64; + ts < until.timestamp() + || (ts == until.timestamp() + && se.event.id.as_bytes().as_slice() > before) + } + _ => true, + }) + .take(q.limit.unwrap() as usize) + .cloned() + .collect(); + page + }; + let events = query_all_pages(query, 2, &mut AuxReader::Fake(&mut fetch)) + .await + .unwrap(); + + assert_eq!( + events.iter().map(|se| se.event.id).collect::>(), + expected + ); + assert_eq!(calls.len(), 3, "2 full pages + 1 short page"); + assert!(calls.iter().all(|(limit, _, _)| *limit == Some(2))); + assert_eq!(calls[0].1, None); + // Second page resumes from the last row of the first (ts 40, larger id). + assert_eq!(calls[1].1.unwrap().timestamp(), 40); + assert_eq!( + calls[1].2.as_deref(), + Some(store[1].event.id.as_bytes().as_slice()) + ); + assert_eq!(calls[2].1.unwrap().timestamp(), 30); + } + + #[tokio::test] + async fn query_all_pages_stops_at_one_short_page() { + let tenant = fresh_tenant("relay.example"); + let query = build_aux_query(tenant.community(), vec!["root".into()], &WINDOW_AUX_KINDS); + let mut calls = 0; + let mut fetch = |_q: &buzz_db::EventQuery| { + calls += 1; + Vec::new() + }; + let events = query_all_pages(query, 1000, &mut AuxReader::Fake(&mut fetch)) + .await + .unwrap(); + assert!(events.is_empty()); + assert_eq!(calls, 1); + } + #[test] fn bridge_search_mode_extension_defaults_to_full_text() { assert_eq!( diff --git a/crates/buzz-relay/src/handlers/command_executor.rs b/crates/buzz-relay/src/handlers/command_executor.rs index d8569a7a86..007db43ffd 100644 --- a/crates/buzz-relay/src/handlers/command_executor.rs +++ b/crates/buzz-relay/src/handlers/command_executor.rs @@ -105,8 +105,9 @@ async fn persist_command_event( event: &Event, channel_id_override: Option, ) -> Result { - let channel_id = channel_id_override.or_else(|| extract_channel_id(event)); + use buzz_db::replaceable::{ParameterizedReplacePrecondition, ParameterizedReplaceStatus}; + let channel_id = channel_id_override.or_else(|| extract_channel_id(event)); let mut tx = db .begin_transaction() .await @@ -118,22 +119,8 @@ async fn persist_command_event( IngestError::Rejected(format!("restricted: community writes are fenced: {error}")) })?; - // INSERT with ON CONFLICT DO NOTHING — idempotency guard. - let id_bytes = event.id.as_bytes(); - let pubkey_bytes = event.pubkey.to_bytes(); - let sig_bytes = event.sig.serialize(); - let tags_json = serde_json::to_value(&event.tags) - .map_err(|e| IngestError::Internal(format!("error: serialize tags: {e}")))?; - let kind_i32 = event.kind.as_u16() as i32; - let created_at_secs = event.created_at.as_secs() as i64; - let created_at = chrono::DateTime::from_timestamp(created_at_secs, 0).ok_or_else(|| { - IngestError::Rejected(format!("invalid: bad timestamp {created_at_secs}")) - })?; - let received_at = chrono::Utc::now(); - - // Extract d_tag for parameterized replaceable kinds (NIP-33). let d_tag = buzz_db::event::extract_d_tag(event); - if let Some(ref d_tag) = d_tag { + if let Some(d_tag) = d_tag.as_deref() { if d_tag.len() > buzz_db::event::D_TAG_MAX_LEN { return Err(IngestError::Rejected(format!( "invalid: d tag too long ({} bytes, max {})", @@ -142,130 +129,81 @@ async fn persist_command_event( ))); } - // Command kinds normally use plain insert semantics, but workflow - // definitions are NIP-33 events. Serialize writers for the same - // coordinate and reject stale writes before executing the domain - // mutation, otherwise old updates can overwrite newer workflow state. - let lock_key = { - let mut h: u64 = 0xcbf29ce484222325; - for b in tenant.community().as_uuid().as_bytes() { - h ^= *b as u64; - h = h.wrapping_mul(0x100000001b3); - } - for b in kind_i32.to_le_bytes() { - h ^= b as u64; - h = h.wrapping_mul(0x100000001b3); - } - for b in pubkey_bytes.as_slice() { - h ^= *b as u64; - h = h.wrapping_mul(0x100000001b3); - } - for b in d_tag.as_bytes() { - h ^= *b as u64; - h = h.wrapping_mul(0x100000001b3); - } - h as i64 + let kind = event.kind.as_u16() as i32; + let (expected_revision, revision_error) = match parse_expected_workflow_revision( + kind, + extract_tag(event, "expected-revision").as_deref(), + ) { + Ok(expected_revision) => (expected_revision, None), + Err(error) => (None, Some(error)), }; - - sqlx::query("SELECT pg_advisory_xact_lock($1)") - .bind(lock_key) - .execute(tx.as_mut()) - .await - .map_err(|e| IngestError::Internal(format!("error: lock event coordinate: {e}")))?; - - let existing: Option<(chrono::DateTime, Vec)> = sqlx::query_as( - "SELECT created_at, id FROM events \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL \ - ORDER BY created_at DESC, id ASC LIMIT 1", - ) - .bind(tenant.community().as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(d_tag) - .fetch_optional(tx.as_mut()) - .await - .map_err(|e| IngestError::Internal(format!("error: query event coordinate: {e}")))?; - - let incoming_id = event.id.as_bytes().as_slice(); - if existing - .as_ref() - .is_some_and(|(_, existing_id)| existing_id.as_slice() == incoming_id) - { - return Ok(PersistResult::Duplicate); - } - - let expected_revision = extract_tag(event, "expected-revision"); - validate_workflow_revision( - kind_i32, - expected_revision.as_deref(), - existing.as_ref().map(|(_, id)| id.as_slice()), - )?; - if let Some((existing_ts, existing_id)) = existing { - let dominated = created_at < existing_ts - || (created_at == existing_ts && incoming_id >= existing_id.as_slice()); - if dominated { - if kind_i32 == KIND_WORKFLOW_DEF as i32 && expected_revision.is_some() { - return Err(IngestError::Rejected( - "conflict: workflow update was superseded; refresh and try again".into(), - )); - } - return Ok(PersistResult::Duplicate); - } - - sqlx::query( - "UPDATE events SET deleted_at = NOW() \ - WHERE community_id = $1 AND kind = $2 AND pubkey = $3 AND d_tag = $4 AND deleted_at IS NULL", + let precondition = if revision_error.is_some() { + ParameterizedReplacePrecondition::ExactReplayOnly + } else if let Some(expected_revision) = expected_revision.as_deref() { + ParameterizedReplacePrecondition::ExpectedRevision(expected_revision) + } else { + ParameterizedReplacePrecondition::Unconditional + }; + let result = db + .replace_parameterized_event_in_transaction( + &mut tx, + tenant.community(), + event, + d_tag, + channel_id, + precondition, ) - .bind(tenant.community().as_uuid()) - .bind(kind_i32) - .bind(pubkey_bytes.as_slice()) - .bind(d_tag) - .execute(tx.as_mut()) .await - .map_err(|e| IngestError::Internal(format!("error: replace old event: {e}")))?; - } + .map_err(|e| { + IngestError::Internal(format!("error: replace parameterized event: {e}")) + })?; + + return match result.status { + ParameterizedReplaceStatus::Inserted => Ok(PersistResult::Inserted(tx)), + ParameterizedReplaceStatus::Duplicate => Ok(PersistResult::Duplicate), + ParameterizedReplaceStatus::Superseded + if kind == KIND_WORKFLOW_DEF as i32 && expected_revision.is_some() => + { + Err(IngestError::Rejected( + "conflict: workflow update was superseded; refresh and try again".into(), + )) + } + ParameterizedReplaceStatus::Superseded => Ok(PersistResult::Duplicate), + ParameterizedReplaceStatus::RevisionMissing => Err(IngestError::Rejected( + "conflict: workflow revision does not exist".into(), + )), + ParameterizedReplaceStatus::RevisionMismatch => Err(IngestError::Rejected( + "conflict: workflow changed since it was loaded".into(), + )), + ParameterizedReplaceStatus::ReplayOnlyMiss => match revision_error { + Some(error) => Err(error), + None => Err(IngestError::Internal( + "error: replay-only replacement lacked a revision error".into(), + )), + }, + }; } - let result = sqlx::query( - r#" - INSERT INTO events (community_id, id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id, d_tag) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) - ON CONFLICT DO NOTHING - "#, - ) - .bind(tenant.community().as_uuid()) - .bind(id_bytes.as_slice()) - .bind(pubkey_bytes.as_slice()) - .bind(created_at) - .bind(kind_i32) - .bind(&tags_json) - .bind(&event.content) - .bind(sig_bytes.as_slice()) - .bind(received_at) - .bind(channel_id) - .bind(d_tag.as_deref()) - .execute(tx.as_mut()) - .await - .map_err(|e| IngestError::Internal(format!("error: insert event: {e}")))?; - - if result.rows_affected() == 0 { - // Duplicate — rollback (implicit on drop) and signal idempotent success. - Ok(PersistResult::Duplicate) - } else { + let (_, was_inserted) = + buzz_db::event::insert_event_in_transaction(&mut tx, tenant.community(), event, channel_id) + .await + .map_err(|e| IngestError::Internal(format!("error: insert event: {e}")))?; + if was_inserted { Ok(PersistResult::Inserted(tx)) + } else { + Ok(PersistResult::Duplicate) } } -fn validate_workflow_revision( +fn parse_expected_workflow_revision( kind: i32, expected_revision: Option<&str>, - existing_id: Option<&[u8]>, -) -> Result<(), IngestError> { +) -> Result>, IngestError> { if kind != KIND_WORKFLOW_DEF as i32 { - return Ok(()); + return Ok(None); } - let expected_id = expected_revision + expected_revision .map(|expected| { let id = hex::decode(expected).map_err(|_| { IngestError::Rejected("invalid: bad expected workflow revision".into()) @@ -277,18 +215,7 @@ fn validate_workflow_revision( } Ok(id) }) - .transpose()?; - - match (expected_id.as_deref(), existing_id) { - (None, _) => Ok(()), - (Some(_), None) => Err(IngestError::Rejected( - "conflict: workflow revision does not exist".into(), - )), - (Some(expected), Some(existing)) if expected != existing => Err(IngestError::Rejected( - "conflict: workflow changed since it was loaded".into(), - )), - (Some(_), Some(_)) => Ok(()), - } + .transpose() } /// Extract all `p` tag values (hex pubkeys) from an event. @@ -425,7 +352,7 @@ async fn handle_dm_open( .await .map_err(|e| IngestError::Internal(format!("error: db open_dm: {e}")))?; - // Commit: event + mutation succeeded atomically. + // Finalize the idempotency record after the separate mutation succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; @@ -586,7 +513,7 @@ async fn handle_dm_add_member( .await .map_err(|e| IngestError::Internal(format!("error: db open_dm: {e}")))?; - // Commit: event + mutation succeeded atomically. + // Finalize the idempotency record after the separate mutation succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; @@ -691,7 +618,7 @@ async fn handle_dm_hide( .await .map_err(|e| IngestError::Internal(format!("error: db hide_dm: {e}")))?; - // Commit: event + mutation succeeded atomically. + // Finalize the idempotency record after the separate mutation succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; @@ -994,7 +921,7 @@ async fn handle_workflow_trigger( .await .map_err(|e| IngestError::Internal(format!("error: db create_workflow_run: {e}")))?; - // Commit: event + run creation succeeded atomically. + // Finalize the idempotency record after the separate run creation succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; @@ -1169,7 +1096,7 @@ async fn handle_approval_grant( )); } - // Commit: event + approval update succeeded atomically. + // Finalize the idempotency record after the separate approval update succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; @@ -1280,7 +1207,7 @@ async fn handle_approval_deny( )); } - // Commit: event + approval denial succeeded atomically. + // Finalize the idempotency record after the separate approval denial succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; @@ -1489,57 +1416,40 @@ mod tests { .expect("workflow event") } - fn rejection_message(result: Result<(), IngestError>) -> String { + fn rejection_message(result: Result>, IngestError>) -> String { match result { Err(IngestError::Rejected(message)) => message, Err(IngestError::AuthFailed(message)) => panic!("unexpected auth failure: {message}"), Err(IngestError::Internal(message)) => panic!("unexpected internal failure: {message}"), - Ok(()) => panic!("expected revision validation to fail"), + Ok(_) => panic!("expected revision parsing to fail"), } } #[test] - fn workflow_revision_accepts_create_and_matching_update() { - let existing = [0x42; 32]; - assert!(validate_workflow_revision(KIND_WORKFLOW_DEF as i32, None, None).is_ok()); - assert!(validate_workflow_revision( - KIND_WORKFLOW_DEF as i32, - Some(&hex::encode(existing)), - Some(&existing), - ) - .is_ok()); + fn workflow_revision_parser_accepts_create_and_valid_update() { + let revision = [0x42; 32]; + assert_eq!( + parse_expected_workflow_revision(KIND_WORKFLOW_DEF as i32, None) + .expect("tagless workflow"), + None + ); + assert_eq!( + parse_expected_workflow_revision( + KIND_WORKFLOW_DEF as i32, + Some(&hex::encode(revision)), + ) + .expect("valid revision"), + Some(revision.to_vec()) + ); } #[test] - fn workflow_revision_rejects_stale_and_malformed_updates() { - let existing = [0x42; 32]; - let stale = [0x24; 32]; - assert_eq!( - rejection_message(validate_workflow_revision( - KIND_WORKFLOW_DEF as i32, - Some(&hex::encode(stale)), - Some(&existing), - )), - "conflict: workflow changed since it was loaded", - ); - assert!( - validate_workflow_revision(KIND_WORKFLOW_DEF as i32, None, Some(&existing)).is_ok(), - "tagless legacy workflow updates remain compatible during rollout", - ); + fn workflow_revision_parser_rejects_malformed_values() { for malformed in ["not-hex", "42"] { assert_eq!( - rejection_message(validate_workflow_revision( + rejection_message(parse_expected_workflow_revision( KIND_WORKFLOW_DEF as i32, Some(malformed), - Some(&existing), - )), - "invalid: bad expected workflow revision", - ); - assert_eq!( - rejection_message(validate_workflow_revision( - KIND_WORKFLOW_DEF as i32, - Some(malformed), - None, )), "invalid: bad expected workflow revision", ); @@ -1547,14 +1457,11 @@ mod tests { } #[test] - fn workflow_revision_rejects_update_for_missing_coordinate() { + fn revision_tag_does_not_change_other_command_kinds() { assert_eq!( - rejection_message(validate_workflow_revision( - KIND_WORKFLOW_DEF as i32, - Some(&hex::encode([0x42; 32])), - None, - )), - "conflict: workflow revision does not exist", + parse_expected_workflow_revision(KIND_DM_OPEN as i32, Some("not-hex")) + .expect("non-workflow revision tag"), + None ); } @@ -1567,6 +1474,25 @@ mod tests { let created_at = Timestamp::now().as_secs(); let create = workflow_event(&keys, workflow_id, created_at, None, "create"); + let missing_revision = hex::encode([0x24; 32]); + let missing_revision_update = workflow_event( + &keys, + Uuid::new_v4(), + created_at, + Some(&missing_revision), + "missing-revision", + ); + let error = match persist_command_event(&db, &tenant, &missing_revision_update, None).await + { + Err(error) => error, + Ok(_) => panic!("missing revision must not create a workflow"), + }; + assert!(matches!( + error, + IngestError::Rejected(ref message) + if message == "conflict: workflow revision does not exist" + )); + let PersistResult::Inserted(tx) = persist_command_event(&db, &tenant, &create, None) .await .expect("persist create") @@ -1621,6 +1547,23 @@ mod tests { PersistResult::Duplicate )); + let stale_revision_update = workflow_event( + &keys, + workflow_id, + created_at + 1, + Some(&create_revision), + "stale-revision", + ); + let error = match persist_command_event(&db, &tenant, &stale_revision_update, None).await { + Err(error) => error, + Ok(_) => panic!("stale revision must not replace the current workflow"), + }; + assert!(matches!( + error, + IngestError::Rejected(ref message) + if message == "conflict: workflow changed since it was loaded" + )); + let error = match persist_command_event(&db, &tenant, &dominated_update, None).await { Err(error) => error, Ok(_) => panic!("distinct dominated CAS update must not report duplicate success"), @@ -1632,8 +1575,55 @@ mod tests { )); } - #[test] - fn revision_tag_does_not_change_other_command_kinds() { - assert!(validate_workflow_revision(KIND_DM_OPEN as i32, Some("not-hex"), None).is_ok()); + #[tokio::test] + #[ignore = "requires Postgres"] + async fn workflow_persistence_replays_legacy_malformed_revision_before_validation() { + let (db, tenant) = persistence_test_context().await; + let keys = Keys::generate(); + let workflow_id = Uuid::new_v4(); + let created_at = Timestamp::now().as_secs(); + let legacy = workflow_event( + &keys, + workflow_id, + created_at, + Some("not-hex"), + "legacy-malformed", + ); + + let mut tx = db.begin_transaction().await.expect("begin legacy seed"); + let (_, was_inserted) = buzz_db::event::insert_event_in_transaction( + &mut tx, + tenant.community(), + &legacy, + extract_channel_id(&legacy), + ) + .await + .expect("seed legacy workflow event"); + assert!(was_inserted); + tx.commit().await.expect("commit legacy seed"); + + assert!(matches!( + persist_command_event(&db, &tenant, &legacy, None) + .await + .expect("exact legacy replay must remain idempotent"), + PersistResult::Duplicate + )); + + let distinct = workflow_event( + &keys, + workflow_id, + created_at + 1, + Some("not-hex"), + "distinct-malformed", + ); + let error = match persist_command_event(&db, &tenant, &distinct, None).await { + Err(error) => error, + Ok(_) => panic!("distinct malformed revision must remain rejected"), + }; + assert!(matches!( + error, + IngestError::Rejected(ref message) + if message == "invalid: bad expected workflow revision" + )); } } diff --git a/desktop/playwright.config.ts b/desktop/playwright.config.ts index ff8a0e7703..be15c75587 100644 --- a/desktop/playwright.config.ts +++ b/desktop/playwright.config.ts @@ -38,6 +38,7 @@ export default defineConfig({ "**/invites-settings-screenshots.spec.ts", "**/messaging.spec.ts", "**/message-feedback-snapshots.spec.ts", + "**/message-copy-link.spec.ts", "**/custom-emoji.spec.ts", "**/profile-custom-emoji-status.spec.ts", "**/custom-emoji-ui.spec.ts", @@ -86,6 +87,9 @@ export default defineConfig({ "**/home-collapsed-top-chrome.spec.ts", "**/top-chrome-zoom-clearance.spec.ts", "**/thread-unread.spec.ts", + "**/thread-load-failure.spec.ts", + "**/project-conversation-load-failure.spec.ts", + "**/huddle-thread-load-failure.spec.ts", "**/workspace-rail.spec.ts", "**/community-rail.spec.ts", "**/boot-splash.spec.ts", @@ -99,6 +103,7 @@ export default defineConfig({ "**/scroll-history.spec.ts", "**/channel-dense-second-reach.spec.ts", "**/channel-window-mock-paging.spec.ts", + "**/channel-head-restart.spec.ts", "**/live-broadcast-reply-timeline.spec.ts", "**/markdown-parse-cache.spec.ts", "**/overscroll-boundary.spec.ts", diff --git a/desktop/src-tauri/src/app_state.rs b/desktop/src-tauri/src/app_state.rs index 7c41f6bfe2..9cbb4444ab 100644 --- a/desktop/src-tauri/src/app_state.rs +++ b/desktop/src-tauri/src/app_state.rs @@ -194,8 +194,8 @@ pub fn build_app_state() -> AppState { identity_storage: AtomicU8::new(identity_storage as u8), http_client: reqwest::Client::builder() .resolve("localhost", std::net::SocketAddr::from(([127, 0, 0, 1], 0))) - .pool_idle_timeout(std::time::Duration::from_secs(10)) - .pool_max_idle_per_host(1) + .pool_idle_timeout(std::time::Duration::from_secs(300)) + .pool_max_idle_per_host(2) .build() .unwrap_or_else(|_| reqwest::Client::new()), media_fetch_client: build_media_fetch_client().expect( diff --git a/desktop/src-tauri/src/channel_head_cache.rs b/desktop/src-tauri/src/channel_head_cache.rs new file mode 100644 index 0000000000..f84c534d30 --- /dev/null +++ b/desktop/src-tauri/src/channel_head_cache.rs @@ -0,0 +1,432 @@ +//! Persistent native cache for recently visited channel head pages. +//! +//! The cache is a paint accelerator only: the renderer always replaces a +//! hydrated page with an authoritative relay response after subscribing. + +use std::{ + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; + +use rusqlite::{params, Connection, OptionalExtension, Transaction}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use tauri::{AppHandle, Manager, State}; + +const SCHEMA_VERSION: i64 = 1; +const CHANNELS_PER_SCOPE_CAP: i64 = 32; +const ROW_BYTES_CAP: usize = 1024 * 1024; + +/// Serializes cache mutations on the blocking pool. +#[derive(Default)] +pub(crate) struct ChannelHeadCacheStore { + write_lock: Arc>, +} + +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ChannelHeadScope { + pub(crate) pubkey: String, + pub(crate) relay_url: String, +} + +impl ChannelHeadScope { + fn key(&self) -> String { + format!( + "{}:{}", + self.pubkey.trim().to_ascii_lowercase(), + self.relay_url.trim().trim_end_matches('/') + ) + } +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub(crate) struct ChannelHeadEntry { + channel_id: String, + events: Vec, + saved_at: i64, + last_visited_at: i64, +} + +fn db_path(app: &AppHandle) -> Result { + let dir = app + .path() + .app_data_dir() + .map_err(|error| format!("resolve channel-head cache data dir: {error}"))?; + std::fs::create_dir_all(&dir) + .map_err(|error| format!("create channel-head cache data dir: {error}"))?; + Ok(dir.join("channel-head-cache.db")) +} + +fn create_schema(conn: &Connection) -> Result<(), String> { + conn.execute_batch( + "CREATE TABLE schema_meta(version INTEGER NOT NULL); + INSERT INTO schema_meta(version) VALUES(1); + CREATE TABLE channel_head( + scope TEXT NOT NULL, + channel_id TEXT NOT NULL, + events_json TEXT NOT NULL, + row_count INTEGER NOT NULL, + saved_at INTEGER NOT NULL, + last_visited_at INTEGER NOT NULL, + PRIMARY KEY(scope, channel_id) + );", + ) + .map_err(|error| format!("initialize channel-head cache db: {error}")) +} + +fn open_db(path: &Path) -> Result { + let conn = + Connection::open(path).map_err(|error| format!("open channel-head cache db: {error}"))?; + conn.pragma_update(None, "busy_timeout", 5_000) + .map_err(|error| format!("configure channel-head cache db: {error}"))?; + conn.pragma_update(None, "journal_mode", "WAL") + .map_err(|error| format!("configure channel-head cache WAL: {error}"))?; + + let has_schema_meta: bool = conn + .query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_meta')", + [], + |row| row.get(0), + ) + .map_err(|error| format!("inspect channel-head cache schema: {error}"))?; + if !has_schema_meta { + create_schema(&conn)?; + return Ok(conn); + } + + let version = conn + .query_row("SELECT version FROM schema_meta LIMIT 1", [], |row| { + row.get::<_, i64>(0) + }) + .optional() + .map_err(|error| format!("read channel-head cache schema: {error}"))?; + let has_channel_head: bool = conn + .query_row( + "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='channel_head')", + [], + |row| row.get(0), + ) + .map_err(|error| format!("inspect channel-head cache table: {error}"))?; + if version != Some(SCHEMA_VERSION) || !has_channel_head { + conn.execute_batch("DROP TABLE IF EXISTS channel_head; DROP TABLE IF EXISTS schema_meta;") + .map_err(|error| format!("reset channel-head cache schema: {error}"))?; + create_schema(&conn)?; + } + Ok(conn) +} + +async fn run_blocking(task: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> Result + Send + 'static, +{ + tauri::async_runtime::spawn_blocking(task) + .await + .map_err(|error| format!("channel-head cache db task failed: {error}"))? +} + +fn load_from_path( + path: &Path, + scope: &ChannelHeadScope, + limit: u32, +) -> Result, String> { + let conn = open_db(path)?; + let mut statement = conn + .prepare( + "SELECT channel_id, events_json, saved_at, last_visited_at + FROM channel_head WHERE scope=?1 + ORDER BY last_visited_at DESC, saved_at DESC, channel_id ASC LIMIT ?2", + ) + .map_err(|error| format!("prepare channel-head cache load: {error}"))?; + let rows = statement + .query_map(params![scope.key(), i64::from(limit)], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, i64>(2)?, + row.get::<_, i64>(3)?, + )) + }) + .map_err(|error| format!("query channel-head cache: {error}"))?; + let mut entries = Vec::new(); + for row in rows { + let (channel_id, events_json, saved_at, last_visited_at) = + row.map_err(|error| format!("read channel-head cache row: {error}"))?; + let events = match serde_json::from_str(&events_json) { + Ok(events) => events, + Err(error) => { + eprintln!("skipping corrupt channel-head cache row {channel_id}: {error}"); + continue; + } + }; + entries.push(ChannelHeadEntry { + channel_id, + events, + saved_at, + last_visited_at, + }); + } + Ok(entries) +} + +fn store_in_transaction( + transaction: &Transaction<'_>, + scope: &str, + channel_id: &str, + events_json: &str, + row_count: usize, + now: i64, +) -> Result<(), String> { + let last_visited_at: i64 = transaction + .query_row( + "SELECT COALESCE(MAX(last_visited_at), ?2 - 1) + 1 FROM channel_head WHERE scope=?1", + params![scope, now], + |row| row.get(0), + ) + .map_err(|error| format!("advance channel-head cache visit clock: {error}"))?; + transaction + .execute( + "INSERT INTO channel_head(scope, channel_id, events_json, row_count, saved_at, last_visited_at) + VALUES(?1, ?2, ?3, ?4, ?5, ?6) + ON CONFLICT(scope, channel_id) DO UPDATE SET + events_json=excluded.events_json, + row_count=excluded.row_count, + saved_at=excluded.saved_at, + last_visited_at=excluded.last_visited_at", + params![scope, channel_id, events_json, row_count as i64, now, last_visited_at], + ) + .map_err(|error| format!("store channel-head cache row: {error}"))?; + transaction + .execute( + "DELETE FROM channel_head WHERE rowid IN ( + SELECT rowid FROM channel_head WHERE scope=?1 + ORDER BY last_visited_at DESC, saved_at DESC, channel_id ASC + LIMIT -1 OFFSET ?2 + )", + params![scope, CHANNELS_PER_SCOPE_CAP], + ) + .map_err(|error| format!("prune channel-head cache: {error}"))?; + Ok(()) +} + +fn store_at( + path: &Path, + scope: &ChannelHeadScope, + channel_id: &str, + events: &[Value], + now: i64, +) -> Result<(), String> { + let events_json = serde_json::to_string(events) + .map_err(|error| format!("encode channel-head cache row: {error}"))?; + let mut conn = open_db(path)?; + let transaction = conn + .transaction() + .map_err(|error| format!("begin channel-head cache store: {error}"))?; + if events_json.len() > ROW_BYTES_CAP { + transaction + .execute( + "DELETE FROM channel_head WHERE scope=?1 AND channel_id=?2", + params![scope.key(), channel_id], + ) + .map_err(|error| format!("drop oversized channel-head cache row: {error}"))?; + } else { + store_in_transaction( + &transaction, + &scope.key(), + channel_id, + &events_json, + events.len(), + now, + )?; + } + transaction + .commit() + .map_err(|error| format!("commit channel-head cache store: {error}")) +} + +/// Loads the most recently visited channel heads for one identity and relay. +#[tauri::command] +pub(crate) async fn channel_head_cache_load( + scope: ChannelHeadScope, + limit: u32, + app: AppHandle, +) -> Result, String> { + let path = db_path(&app)?; + run_blocking(move || load_from_path(&path, &scope, limit)).await +} + +/// Stores one raw channel-window response, dropping payloads above one MiB. +#[tauri::command] +pub(crate) async fn channel_head_cache_store( + scope: ChannelHeadScope, + channel_id: String, + events: Vec, + app: AppHandle, + store: State<'_, ChannelHeadCacheStore>, +) -> Result<(), String> { + let path = db_path(&app)?; + let write_lock = Arc::clone(&store.write_lock); + run_blocking(move || { + let _guard = write_lock.lock().map_err(|error| error.to_string())?; + store_at( + &path, + &scope, + &channel_id, + &events, + chrono::Utc::now().timestamp(), + ) + }) + .await +} + +/// Clears all persisted channel heads for one identity and relay. +#[tauri::command] +pub(crate) async fn channel_head_cache_clear( + scope: ChannelHeadScope, + app: AppHandle, + store: State<'_, ChannelHeadCacheStore>, +) -> Result<(), String> { + let path = db_path(&app)?; + let write_lock = Arc::clone(&store.write_lock); + run_blocking(move || { + let _guard = write_lock.lock().map_err(|error| error.to_string())?; + let conn = open_db(&path)?; + conn.execute("DELETE FROM channel_head WHERE scope=?1", [scope.key()]) + .map_err(|error| format!("clear channel-head cache scope: {error}"))?; + Ok(()) + }) + .await +} + +pub(crate) fn flush(app: &AppHandle) { + if let Ok(path) = db_path(app) { + if let Ok(conn) = open_db(&path) { + let _ = conn.execute_batch("PRAGMA wal_checkpoint(PASSIVE);"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scope() -> ChannelHeadScope { + ChannelHeadScope { + pubkey: "PK".into(), + relay_url: "wss://relay/".into(), + } + } + + #[test] + fn serialized_entry_matches_typescript_contract() { + let actual = serde_json::to_value(ChannelHeadEntry { + channel_id: "general".into(), + events: vec![serde_json::json!({"id":"event"})], + saved_at: 42, + last_visited_at: 43, + }) + .unwrap(); + let expected = serde_json::json!({ + "channelId":"general", + "events":[{"id":"event"}], + "savedAt":42, + "lastVisitedAt":43 + }); + assert_eq!(actual, expected); + + let decoded: ChannelHeadScope = serde_json::from_value(serde_json::json!({ + "pubkey":"PK", "relayUrl":"wss://relay/" + })) + .unwrap(); + assert_eq!(decoded, scope()); + assert_eq!(decoded.key(), "pk:wss://relay"); + } + + #[test] + fn enforces_lru_and_payload_caps() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("channel-head-cache.db"); + for index in 0..=CHANNELS_PER_SCOPE_CAP { + store_at( + &path, + &scope(), + &format!("channel-{index:02}"), + &[serde_json::json!({"index":index})], + 1_000 + index, + ) + .unwrap(); + } + let entries = load_from_path(&path, &scope(), 100).unwrap(); + assert_eq!(entries.len(), CHANNELS_PER_SCOPE_CAP as usize); + assert_eq!(entries.first().unwrap().channel_id, "channel-32"); + assert!(!entries.iter().any(|entry| entry.channel_id == "channel-00")); + + let oversized = vec![Value::String("x".repeat(ROW_BYTES_CAP))]; + store_at(&path, &scope(), "channel-32", &oversized, 2_000).unwrap(); + let count: i64 = open_db(&path) + .unwrap() + .query_row( + "SELECT COUNT(*) FROM channel_head WHERE channel_id='channel-32'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(count, 0); + } + + #[test] + fn skips_corrupt_rows_without_blanketing_good_entries() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("channel-head-cache.db"); + store_at( + &path, + &scope(), + "good-channel", + &[serde_json::json!({"id":"good-event"})], + 1_000, + ) + .unwrap(); + let conn = open_db(&path).unwrap(); + conn.execute( + "INSERT INTO channel_head VALUES(?1, 'bad-channel', 'not-json', 1, 1001, 1001)", + [scope().key()], + ) + .unwrap(); + drop(conn); + + let entries = load_from_path(&path, &scope(), 12).unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].channel_id, "good-channel"); + assert_eq!( + entries[0].events, + vec![serde_json::json!({"id":"good-event"})] + ); + } + + #[test] + fn schema_mismatch_recreates_cache() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("channel-head-cache.db"); + let conn = open_db(&path).unwrap(); + conn.execute("UPDATE schema_meta SET version=99", []) + .unwrap(); + conn.execute( + "INSERT INTO channel_head VALUES('scope','channel','[]',0,1,1)", + [], + ) + .unwrap(); + drop(conn); + + let reset = open_db(&path).unwrap(); + let version: i64 = reset + .query_row("SELECT version FROM schema_meta", [], |row| row.get(0)) + .unwrap(); + let rows: i64 = reset + .query_row("SELECT COUNT(*) FROM channel_head", [], |row| row.get(0)) + .unwrap(); + assert_eq!(version, SCHEMA_VERSION); + assert_eq!(rows, 0); + } +} diff --git a/desktop/src-tauri/src/commands/messages.rs b/desktop/src-tauri/src/commands/messages.rs index 31559777d2..1e221b6bd1 100644 --- a/desktop/src-tauri/src/commands/messages.rs +++ b/desktop/src-tauri/src/commands/messages.rs @@ -13,7 +13,7 @@ use crate::{ events, managed_agents::{find_managed_agent_mut, load_managed_agents, ManagedAgentRecord}, models::{ - FeedItemInfo, FeedMeta, FeedResponse, FeedSections, SearchResponse, + FeedItemCategory, FeedItemInfo, FeedMeta, FeedResponse, FeedSections, SearchResponse, SendChannelMessageResponse, ThreadRepliesResponse, }, nostr_convert, @@ -138,14 +138,14 @@ pub async fn get_feed( let mentions: Vec = mention_events .iter() .map(|ev| { - let mut item = feed_item_from_event(ev, "mentions"); + let mut item = feed_item_from_event(ev, FeedItemCategory::Mention); apply_link_preview_suppression(&mut item.tags, &item.id, &suppressed_mentions); item }) .collect(); let needs_action: Vec = approval_events .iter() - .map(|ev| feed_item_from_event(ev, "needs_action")) + .map(|ev| feed_item_from_event(ev, FeedItemCategory::NeedsAction)) .collect(); let total = (mentions.len() + needs_action.len()) as u64; @@ -236,22 +236,11 @@ fn search_messages_limit(limit: Option) -> u32 { limit.unwrap_or(20).min(500) } -/// Fetch the full reply subtree under a thread root, server-side. -/// -/// Unlike the channel timeline (which the desktop assembles from its local -/// cache by grouping on `e`-root tags), this walks `thread_metadata` on the -/// relay via `get_thread_replies`, so a thread renders complete even when its -/// replies fell outside the channel cold-load window. Results are chronological -/// (oldest first) and are the *replies* under the root (depth >= 1); the root -/// event itself is NOT returned (the relay query keys on `root_event_id`, and a -/// root row has no `root_event_id`). Callers already hold the root — it is the -/// open thread head — so this closes the descendant gap without re-fetching it. +/// Fetch the reply subtree and its auxiliary events under a thread root. /// /// Paging is forward keyset on `(created_at, event_id)`: pass the `next_cursor` /// from a previous page back as `cursor` to fetch the next batch. The event-id -/// tiebreak is required because replies routinely share a `created_at` second; -/// a timestamp-only cursor would skip every tied reply past the page limit. -/// `next_cursor` is `Some` only when a full page was returned. +/// tiebreak prevents same-second replies from being skipped. #[tauri::command] pub async fn get_thread_replies( root_event_id: String, @@ -275,8 +264,12 @@ pub async fn get_thread_replies( // A full page implies there may be more; hand back the last event's // composite key as the next cursor (the DB returns replies strictly after // it, tiebroken by event_id so same-second replies are not skipped). - let next_cursor = if events.len() as u32 >= cap { - events.last().map(|ev| crate::models::ThreadCursor { + let reply_events: Vec<_> = events + .iter() + .filter(|event| TIMELINE_KINDS.contains(&(event.kind.as_u16() as u32))) + .collect(); + let next_cursor = if reply_events.len() as u32 >= cap { + reply_events.last().map(|ev| crate::models::ThreadCursor { created_at: ev.created_at.as_secs() as i64, event_id: ev.id.to_hex(), }) @@ -295,21 +288,9 @@ pub async fn get_thread_replies( }) } -/// Build the relay `/query` filter for the server-side thread-subtree read. -/// -/// The relay routes a filter to `get_thread_replies` purely off a single `#e` -/// (root) tag plus `depth_limit` — kind is NOT part of that routing or the -/// underlying DB query (it keys on `root_event_id`). Yet `kinds` is still -/// required here: the bridge runs the p-gate (`p_gated_filters_authorized`) on -/// every filter *before* routing, and a kindless filter "could match" a p-gated -/// kind, so the gate demands a `#p` tag we don't send -> HTTP 403 -/// `restricted: p-gated kinds require #p tag`, before the thread query ever -/// runs. Carrying non-p-gated [`TIMELINE_KINDS`] makes the filter provably -/// un-p-gated so it clears the gate. `build_channel_messages_before_filter` is -/// the sibling that already does this, which is why the dense-second channel -/// pager was never gated and this reader was. Extracted so a unit test can pin -/// that `kinds` is present (the e2e mock does not model p-gating, so only a -/// unit test guards this contract). +/// Build the relay `/query` filter for a thread-subtree read. +/// `kinds` is required to prove the filter cannot match p-gated events; without +/// it, relay authorization rejects this otherwise kindless query. fn build_thread_replies_filter( root_event_id: &str, channel_id: Option<&str>, @@ -324,6 +305,7 @@ fn build_thread_replies_filter( // defaults it to a deep-but-bounded value so nested replies aren't dropped. filter.insert("depth_limit".to_string(), serde_json::json!(depth_limit)); filter.insert("limit".to_string(), serde_json::json!(cap)); + filter.insert("include_aux".to_string(), serde_json::json!(true)); if let Some(cid) = channel_id { filter.insert("#h".to_string(), serde_json::json!([cid])); } @@ -414,28 +396,13 @@ pub async fn get_channel_messages_before( }) } -#[tauri::command] -pub async fn get_event(event_id: String, state: State<'_, AppState>) -> Result { - let events = query_relay( - &state, - &[serde_json::json!({ - "ids": [event_id], - "kinds": [0, 1, 3, 5, 7, 9, 30078, 40002, 40003, 40008, 40099, 40100, 45001, 45003, buzz_core_pkg::kind::KIND_HUDDLE_STARTED], - "limit": 1 - })], - ) - .await?; - - let ev = events - .first() - .ok_or_else(|| "event not found".to_string())?; - serde_json::to_string(ev).map_err(|e| format!("serialize event: {e}")) -} +mod event_batch; +pub use event_batch::{get_event, get_events}; // ── Writes ────────────────────────────────────────────────────────────────── mod thread_ref; -use thread_ref::resolve_thread_ref; +use thread_ref::{resolve_thread_ref, thread_ref}; #[tauri::command] #[allow(clippy::too_many_arguments)] @@ -443,6 +410,7 @@ pub async fn send_channel_message( channel_id: String, content: String, parent_event_id: Option, + root_event_id: Option, media_tags: Option>>, emoji_tags: Option>>, mention_tags: Option>>, @@ -483,6 +451,9 @@ pub async fn send_channel_message( if sent_from_thread_tag.is_some() && kind_num != buzz_core_pkg::kind::KIND_STREAM_MESSAGE { return Err("sent-from-thread provenance requires a stream message".into()); } + if root_event_id.is_some() && parent_event_id.is_none() { + return Err("root_event_id requires parent_event_id".into()); + } let mut resolved_root: Option = None; @@ -498,8 +469,14 @@ pub async fn send_channel_message( let parent_id = parent_event_id .as_deref() .ok_or("forum comment requires parent_event_id")?; - let thread_ref = - resolve_thread_ref(parent_id, &state, &relay_base, Some(&signing_keys)).await?; + let thread_ref = thread_ref( + parent_id, + root_event_id.as_deref(), + &state, + &relay_base, + Some(&signing_keys), + ) + .await?; resolved_root = Some(thread_ref.root_event_id.to_hex()); events::build_forum_comment( channel_uuid, @@ -513,8 +490,14 @@ pub async fn send_channel_message( _ => { let thread_ref = match parent_event_id.as_deref() { Some(pid) => { - let tr = - resolve_thread_ref(pid, &state, &relay_base, Some(&signing_keys)).await?; + let tr = thread_ref( + pid, + root_event_id.as_deref(), + &state, + &relay_base, + Some(&signing_keys), + ) + .await?; resolved_root = Some(tr.root_event_id.to_hex()); Some(tr) } @@ -968,7 +951,7 @@ fn tags_to_vec(ev: &nostr::Event) -> Vec> { ev.tags.iter().map(|t| t.as_slice().to_vec()).collect() } -fn feed_item_from_event(ev: &nostr::Event, category: &str) -> FeedItemInfo { +fn feed_item_from_event(ev: &nostr::Event, category: FeedItemCategory) -> FeedItemInfo { let channel_id = channel_id_from_tags(ev); FeedItemInfo { id: ev.id.to_hex(), @@ -980,7 +963,7 @@ fn feed_item_from_event(ev: &nostr::Event, category: &str) -> FeedItemInfo { channel_name: String::new(), channel_type: None, tags: tags_to_vec(ev), - category: category.to_string(), + category, } } #[cfg(test)] diff --git a/desktop/src-tauri/src/commands/messages/event_batch.rs b/desktop/src-tauri/src/commands/messages/event_batch.rs new file mode 100644 index 0000000000..1bb5174868 --- /dev/null +++ b/desktop/src-tauri/src/commands/messages/event_batch.rs @@ -0,0 +1,128 @@ +use std::collections::HashSet; + +use tauri::State; + +use crate::{app_state::AppState, relay::query_relay}; + +// The relay clamps a single filter to this many events. Keep exact-ID reads in +// chunks so a large workflow list cannot silently lose late presentations. +const EVENT_QUERY_CHUNK_SIZE: usize = 1_000; + +const GET_EVENT_KINDS: [u32; 15] = [ + 0, + 1, + 3, + 5, + 7, + 9, + 30078, + 40002, + 40003, + 40008, + 40099, + 40100, + 45001, + 45003, + buzz_core_pkg::kind::KIND_HUDDLE_STARTED, +]; + +#[tauri::command] +pub async fn get_event(event_id: String, state: State<'_, AppState>) -> Result { + let events = query_relay( + &state, + &[serde_json::json!({ + "ids": [event_id], + "kinds": GET_EVENT_KINDS, + "limit": 1 + })], + ) + .await?; + + let event = events + .first() + .ok_or_else(|| "event not found".to_string())?; + serde_json::to_string(event).map_err(|error| format!("serialize event: {error}")) +} + +/// Resolve many exact event IDs in relay-sized chunks. Callers still validate +/// event kind, channel scope, and requested ID before using presentation data. +fn normalized_event_id_chunks(event_ids: Vec) -> Vec> { + let mut seen_ids = HashSet::new(); + let event_ids = event_ids + .into_iter() + .map(|event_id| event_id.trim().to_ascii_lowercase()) + .filter(|event_id| event_id.len() == 64 && event_id.chars().all(|c| c.is_ascii_hexdigit())) + .filter(|event_id| seen_ids.insert(event_id.clone())) + .collect::>(); + event_ids + .chunks(EVENT_QUERY_CHUNK_SIZE) + .map(<[String]>::to_vec) + .collect() +} + +#[tauri::command] +pub async fn get_events( + event_ids: Vec, + state: State<'_, AppState>, +) -> Result, String> { + let event_id_chunks = normalized_event_id_chunks(event_ids); + if event_id_chunks.is_empty() { + return Ok(Vec::new()); + } + + let mut events_by_id = std::collections::HashMap::new(); + for event_ids in event_id_chunks { + let events = query_relay( + &state, + &[serde_json::json!({ + "ids": event_ids, + "kinds": GET_EVENT_KINDS, + "limit": event_ids.len() + })], + ) + .await?; + for event in events { + events_by_id.entry(event.id).or_insert(event); + } + } + + events_by_id + .into_values() + .map(|event| { + serde_json::to_value(event).map_err(|error| format!("serialize event: {error}")) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keeps_exact_relay_ceiling_in_one_chunk() { + let chunks = normalized_event_id_chunks( + (0..EVENT_QUERY_CHUNK_SIZE) + .map(|index| format!("{index:064x}")) + .collect(), + ); + + assert_eq!(chunks.len(), 1); + assert_eq!(chunks[0].len(), EVENT_QUERY_CHUNK_SIZE); + } + + #[test] + fn normalizes_deduplicates_and_keeps_ids_beyond_relay_ceiling() { + let last_id = format!("{:064x}", EVENT_QUERY_CHUNK_SIZE); + let mut event_ids = (0..=EVENT_QUERY_CHUNK_SIZE) + .map(|index| format!("{index:064X}")) + .collect::>(); + event_ids.extend(["not-an-event-id".to_string(), format!(" {last_id} ")]); + + let chunks = normalized_event_id_chunks(event_ids); + + assert_eq!(chunks.iter().map(Vec::len).sum::(), 1_001); + assert_eq!(chunks.len(), 2); + assert_eq!(chunks[0].len(), EVENT_QUERY_CHUNK_SIZE); + assert_eq!(chunks[1], [last_id]); + } +} diff --git a/desktop/src-tauri/src/commands/messages/thread_ref.rs b/desktop/src-tauri/src/commands/messages/thread_ref.rs index 97a03fdad5..8ec82beebb 100644 --- a/desktop/src-tauri/src/commands/messages/thread_ref.rs +++ b/desktop/src-tauri/src/commands/messages/thread_ref.rs @@ -1,4 +1,4 @@ -use nostr::EventId; +use nostr::{EventId, Keys}; use crate::{ app_state::AppState, @@ -6,6 +6,38 @@ use crate::{ relay::{query_relay_at, query_relay_at_with_keys}, }; +/// Build a thread reference from a renderer-supplied root and parent. +/// +/// Both IDs are parsed before signing. This path intentionally performs no +/// relay query: the renderer supplies a root only when the parent is already +/// present in its cache and the root can be read from that event's NIP-10 tags. +pub(super) fn provided_thread_ref( + root_event_id: &str, + parent_event_id: &str, +) -> Result { + let root_event_id = + EventId::from_hex(root_event_id).map_err(|e| format!("invalid root event ID: {e}"))?; + let parent_event_id = + EventId::from_hex(parent_event_id).map_err(|e| format!("invalid parent event ID: {e}"))?; + Ok(events::ThreadRef { + root_event_id, + parent_event_id, + }) +} + +pub(super) async fn thread_ref( + parent_event_id: &str, + root_event_id: Option<&str>, + state: &AppState, + api_base_url: &str, + signing_keys: Option<&Keys>, +) -> Result { + match root_event_id { + Some(root_event_id) => provided_thread_ref(root_event_id, parent_event_id), + None => resolve_thread_ref(parent_event_id, state, api_base_url, signing_keys).await, + } +} + /// Fetch a parent event and extract the thread root from its NIP-10 e-tags. /// /// Reads through the explicit `api_base_url` the calling command resolved — diff --git a/desktop/src-tauri/src/commands/messages_tests.rs b/desktop/src-tauri/src/commands/messages_tests.rs index c0ad03d936..627e632643 100644 --- a/desktop/src-tauri/src/commands/messages_tests.rs +++ b/desktop/src-tauri/src/commands/messages_tests.rs @@ -171,6 +171,7 @@ fn thread_replies_filter_carries_non_p_gated_kinds_to_clear_the_gate() { assert_eq!(filter["#e"], serde_json::json!(["root-hex"])); assert_eq!(filter["depth_limit"], serde_json::json!(64)); assert_eq!(filter["#h"], serde_json::json!(["channel-1"])); + assert_eq!(filter["include_aux"], serde_json::json!(true)); } #[test] @@ -224,3 +225,54 @@ fn legacy_managed_agent_auth_tag_skips_self_attestation() { assert_eq!(tag, None); } + +#[test] +fn provided_thread_ref_validates_and_preserves_root_and_parent() { + let root = "11".repeat(32); + let parent = "22".repeat(32); + let thread_ref = thread_ref::provided_thread_ref(&root, &parent) + .expect("valid 64-hex event ids should be accepted"); + assert_eq!(thread_ref.root_event_id.to_hex(), root); + assert_eq!(thread_ref.parent_event_id.to_hex(), parent); + assert!(thread_ref::provided_thread_ref("not-hex", &parent).is_err()); +} + +/// `FeedItem.category` is a wire contract with the desktop frontend +/// (`desktop/src/shared/api/types.ts`). The frontend routes notification +/// sounds, titles, mute-bypass, and inbox labels off these exact strings, so +/// the serialized form must stay singular `mention` — not the plural section +/// name `mentions` used by `FeedSections` and the `--types` filter. +#[test] +fn feed_item_category_serializes_to_frontend_contract() { + let cases = [ + (FeedItemCategory::Mention, "mention"), + (FeedItemCategory::NeedsAction, "needs_action"), + (FeedItemCategory::Activity, "activity"), + (FeedItemCategory::AgentActivity, "agent_activity"), + ]; + for (category, expected) in cases { + let value = serde_json::to_value(category).expect("category should serialize"); + assert_eq!(value, serde_json::Value::String(expected.to_string())); + } +} + +#[test] +fn feed_item_from_event_carries_singular_mention_category() { + let pubkey = Keys::generate().public_key().to_hex(); + let event = build_managed_agent_channel_message( + uuid::Uuid::new_v4(), + "hey @you", + None, + std::slice::from_ref(&pubkey), + &[], + ) + .expect("message should build") + .sign_with_keys(&Keys::generate()) + .expect("message should sign"); + + let item = feed_item_from_event(&event, FeedItemCategory::Mention); + let json = serde_json::to_value(&item).expect("feed item should serialize"); + + assert_eq!(json["category"], "mention"); + assert_eq!(json["id"], event.id.to_hex()); +} diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 71a5eb3806..613040b809 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ mod app_menu; mod app_state; mod archive; mod builderlab; +mod channel_head_cache; mod commands; mod deep_link; mod egress_guard; @@ -234,6 +235,7 @@ pub fn run() { .manage(archive::sync::ArchiveSyncState::default()) .manage(native_relay_client::NativeRelayClient::default()) .manage(observed_unread::ObservedUnreadStore::default()) + .manage(channel_head_cache::ChannelHeadCacheStore::default()) .setup(move |app| { let app_handle = app.handle().clone(); #[cfg(target_os = "macos")] @@ -650,6 +652,7 @@ pub fn run() { add_reaction, remove_reaction, get_event, + get_events, show_native_notification, #[cfg(target_os = "macos")] macos_notifications::take_pending_activations, @@ -724,6 +727,9 @@ pub fn run() { unread_catch_up::unread_catch_up, observed_unread::observed_unread_open_scope, observed_unread::observed_unread_ingest, + channel_head_cache::channel_head_cache_load, + channel_head_cache::channel_head_cache_store, + channel_head_cache::channel_head_cache_clear, list_personas, create_persona, update_persona, diff --git a/desktop/src-tauri/src/managed_agents/runtime_commands.rs b/desktop/src-tauri/src/managed_agents/runtime_commands.rs index c0e55184b1..135224d01d 100644 --- a/desktop/src-tauri/src/managed_agents/runtime_commands.rs +++ b/desktop/src-tauri/src/managed_agents/runtime_commands.rs @@ -137,86 +137,91 @@ pub fn put_managed_agent_runtime_lifecycle( Ok(status) } +// Keep disk, process, and mutex work off the main thread so opening members cannot stall the UI. #[tauri::command] -pub fn list_managed_agent_runtimes( +pub async fn list_managed_agent_runtimes( app: AppHandle, ) -> Result, String> { - // This command is polled whenever the members sidebar opens and refetched - // on every status event — load the per-row status inputs once, outside - // the locks, instead of hitting disk per row while holding them. - let personas = load_personas(&app).unwrap_or_default(); - let global = load_global_agent_config(&app).unwrap_or_default(); - let state = app.state::(); - let _transition = state - .managed_agent_runtime_transition - .lock() - .map_err(|e| e.to_string())?; - let _store = state - .managed_agents_store_lock - .lock() - .map_err(|e| e.to_string())?; - let mut records = load_managed_agents(&app)?; - let mut runtimes = state - .managed_agent_processes - .lock() - .map_err(|e| e.to_string())?; - let exited_keys: Vec<_> = runtimes - .iter_mut() - .filter_map(|(key, runtime)| match runtime.child.try_wait() { - Ok(Some(_)) | Err(_) => Some(key.clone()), - Ok(None) => None, - }) - .collect(); - let records_changed = !exited_keys.is_empty(); - let mut statuses = Vec::new(); - for key in exited_keys { - runtimes.remove(&key); - super::remove_agent_runtime_receipt(&app, &key); - state.clear_agent_session_cache(&key); - if let Some(record) = records + tokio::task::spawn_blocking(move || { + // This command is polled whenever the members sidebar opens and refetched + // on every status event — load the per-row status inputs once, outside + // the locks, instead of hitting disk per row while holding them. + let personas = load_personas(&app).unwrap_or_default(); + let global = load_global_agent_config(&app).unwrap_or_default(); + let state = app.state::(); + let _transition = state + .managed_agent_runtime_transition + .lock() + .map_err(|e| e.to_string())?; + let _store = state + .managed_agents_store_lock + .lock() + .map_err(|e| e.to_string())?; + let mut records = load_managed_agents(&app)?; + let mut runtimes = state + .managed_agent_processes + .lock() + .map_err(|e| e.to_string())?; + let exited_keys: Vec<_> = runtimes .iter_mut() - .find(|record| record.pubkey.eq_ignore_ascii_case(&key.pubkey)) - { - record.updated_at = crate::util::now_iso(); - record.last_stopped_at = Some(record.updated_at.clone()); - let status = status_for_with( + .filter_map(|(key, runtime)| match runtime.child.try_wait() { + Ok(Some(_)) | Err(_) => Some(key.clone()), + Ok(None) => None, + }) + .collect(); + let records_changed = !exited_keys.is_empty(); + let mut statuses = Vec::new(); + for key in exited_keys { + runtimes.remove(&key); + super::remove_agent_runtime_receipt(&app, &key); + state.clear_agent_session_cache(&key); + if let Some(record) = records + .iter_mut() + .find(|record| record.pubkey.eq_ignore_ascii_case(&key.pubkey)) + { + record.updated_at = crate::util::now_iso(); + record.last_stopped_at = Some(record.updated_at.clone()); + let status = status_for_with( + &app, + record, + &key, + None, + None, + StatusInputs { + personas: &personas, + global: &global, + }, + ); + emit_status(&app, &status); + statuses.push(status); + } + } + statuses.extend(runtimes.iter().filter_map(|(key, runtime)| { + let record = records + .iter() + .find(|record| record.pubkey.eq_ignore_ascii_case(&key.pubkey))?; + Some(status_for_with( &app, record, - &key, - None, + key, + Some(runtime), None, StatusInputs { personas: &personas, global: &global, }, - ); - emit_status(&app, &status); - statuses.push(status); + )) + })); + drop(runtimes); + // Records are only mutated above when a runtime exited — skip the store + // rewrite on the common nothing-changed poll. + if records_changed { + save_managed_agents(&app, &records)?; } - } - statuses.extend(runtimes.iter().filter_map(|(key, runtime)| { - let record = records - .iter() - .find(|record| record.pubkey.eq_ignore_ascii_case(&key.pubkey))?; - Some(status_for_with( - &app, - record, - key, - Some(runtime), - None, - StatusInputs { - personas: &personas, - global: &global, - }, - )) - })); - drop(runtimes); - // Records are only mutated above when a runtime exited — skip the store - // rewrite on the common nothing-changed poll. - if records_changed { - save_managed_agents(&app, &records)?; - } - Ok(statuses) + Ok(statuses) + }) + .await + .map_err(|e| format!("spawn_blocking failed: {e}"))? } pub(crate) fn start_managed_agent_runtime_pair_lazy( @@ -572,6 +577,18 @@ pub async fn reconcile_managed_agent_runtimes( mod tests { use super::*; + #[test] + fn list_managed_agent_runtimes_returns_a_future() { + fn assert_async_command(_command: F) + where + F: Fn(AppHandle) -> Fut, + Fut: std::future::Future, String>>, + { + } + + assert_async_command(list_managed_agent_runtimes); + } + fn payload( relay_url: &str, lifecycle: ManagedAgentRuntimeLifecycle, diff --git a/desktop/src-tauri/src/models.rs b/desktop/src-tauri/src/models.rs index 768b2ad7db..9693f1563a 100644 --- a/desktop/src-tauri/src/models.rs +++ b/desktop/src-tauri/src/models.rs @@ -178,6 +178,22 @@ pub struct ChannelMembersResponse { pub next_cursor: Option, } +/// Per-item classification of a home feed entry. +/// +/// This is the wire contract for `FeedItem.category` in the desktop frontend +/// (`desktop/src/shared/api/types.ts`). It is distinct from the plural +/// *section* vocabulary (`mentions`, `needs_action`, …) used by +/// [`FeedSections`] and the `--types` filter: a mention item lives in the +/// `mentions` section but carries the singular `mention` category. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum FeedItemCategory { + Mention, + NeedsAction, + Activity, + AgentActivity, +} + #[derive(Serialize, Deserialize)] pub struct FeedItemInfo { pub id: String, @@ -190,7 +206,7 @@ pub struct FeedItemInfo { #[serde(default)] pub channel_type: Option, pub tags: Vec>, - pub category: String, + pub category: FeedItemCategory, } #[derive(Serialize, Deserialize)] diff --git a/desktop/src-tauri/src/relay.rs b/desktop/src-tauri/src/relay.rs index bd3fefb125..f408ef2afd 100644 --- a/desktop/src-tauri/src/relay.rs +++ b/desktop/src-tauri/src/relay.rs @@ -16,6 +16,19 @@ const DEFAULT_RELAY_WS_URL: &str = "ws://localhost:3000"; // classifier keys on. Extracted to a const so a test can pin that contract. const MALFORMED_RESPONSE_MESSAGE: &str = "relay returned malformed response: not valid JSON"; +// Per-request deadline for the `POST /query` HTTP bridge, covering both the +// header exchange and full body consumption. The shared `http_client` sets no +// client-level timeout — deliberately, because it is also used for long-running +// STT/TTS model downloads, builderlab auth, and the media proxy — so a stalled +// or half-open `/query` connection would otherwise leave the request pending +// forever, hanging the caller (e.g. a thread-history load that never resolves +// and shows a permanent skeleton). A per-request timeout scoped to `/query` +// bounds that without affecting the client's other users. A timeout surfaces +// through `classify_request_error` as the stable `"relay unreachable: request +// timed out"` string. Set above the 25s WS history timeout so a slow-but-live +// relay is not cut off before the WebSocket path would be. +const QUERY_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + fn configured_env_var(name: &str) -> Option { std::env::var(name) .ok() @@ -167,6 +180,22 @@ pub(crate) fn classify_request_error(e: &reqwest::Error) -> String { } } +/// Preserve a body-consumption timeout as the stable connectivity classification. +/// +/// `send()` resolves once response headers arrive, so a body that stalls past +/// the request deadline trips the timeout during body consumption rather than +/// at `send()`. That is a connectivity failure, not a malformed body or a plain +/// status error. Both body-consumption paths — the 2xx `parse_json_response` +/// and the non-2xx `relay_error_message` — route their consumption error +/// through this one helper so a stalled body can never be classified as +/// "request timed out" on one path while the other buries it under a malformed +/// or status label. Returns `Some("relay unreachable: request timed out")` for +/// a timeout; `None` otherwise, leaving the caller to apply its own non-timeout +/// label. +fn classify_body_timeout(e: &reqwest::Error) -> Option { + e.is_timeout().then(|| classify_request_error(e)) +} + /// Detect responses that were intercepted by a captive portal or auth proxy. /// /// Returns `Some(msg)` when the response clearly did not come from the relay: @@ -230,10 +259,16 @@ pub(crate) async fn parse_json_response( // "relay unreachable:" bucket so it surfaces loudly instead of being treated // as a transient unreachable-relay condition. The reqwest error detail is // dropped because it contains the raw URL. - response - .json::() - .await - .map_err(|_| MALFORMED_RESPONSE_MESSAGE.to_string()) + // + // A body-consumption timeout is the exception: `send()` resolves once + // headers arrive, so a body that stalls past the request deadline trips the + // timeout HERE rather than at send(). That is a connectivity failure, not a + // malformed body, so route it through `classify_body_timeout` — the same + // helper the non-2xx error-body path uses — to preserve the stable + // "relay unreachable: request timed out" label. + response.json::().await.map_err(|e| { + classify_body_timeout(&e).unwrap_or_else(|| MALFORMED_RESPONSE_MESSAGE.to_string()) + }) } /// Extract the `retry in Ns` hint from a rate-limit error string. @@ -264,7 +299,21 @@ pub async fn relay_error_message(response: reqwest::Response) -> String { } // Real relay error: extract the structured message field if available. - let body = response.text().await.unwrap_or_default(); + // `text()` consumes the body, which — like the 2xx path — can trip the + // request deadline if the relay sends status headers then stalls the body. + // Preserve that timeout as the stable connectivity classification via the + // shared helper instead of letting `unwrap_or_default` swallow it into a + // bare status label. A non-timeout body error still degrades to an empty + // body → status-only message, exactly as before. + let body = match response.text().await { + Ok(body) => body, + Err(e) => { + if let Some(timeout) = classify_body_timeout(&e) { + return timeout; + } + String::new() + } + }; // 429 Too Many Requests → typed `relay rate-limited:` prefix so the TS // client can activate the rate-limit gate without confusing it with a @@ -328,22 +377,15 @@ pub async fn query_relay_at( let body_bytes = serde_json::to_vec(filters).map_err(|e| format!("filter serialization failed: {e}"))?; let auth = build_nip98_auth_header(&Method::POST, &url, &body_bytes, state)?; - - let response = state - .http_client - .post(&url) - .header("Authorization", auth) - .header("Content-Type", "application/json") - .body(body_bytes) - .send() - .await - .map_err(|e| classify_request_error(&e))?; - - if !response.status().is_success() { - return Err(relay_error_message(response).await); - } - - parse_json_response(response).await + send_query_request( + &state.http_client, + &url, + &auth, + None, + body_bytes, + QUERY_REQUEST_TIMEOUT, + ) + .await } pub async fn query_relay_at_with_keys( @@ -358,11 +400,38 @@ pub async fn query_relay_at_with_keys( let body_bytes = serde_json::to_vec(filters).map_err(|e| format!("filter serialization failed: {e}"))?; let auth = build_nip98_auth_header_for_keys(keys, &Method::POST, &url, &body_bytes)?; - let mut request = state - .http_client - .post(&url) + send_query_request( + &state.http_client, + &url, + &auth, + auth_tag, + body_bytes, + QUERY_REQUEST_TIMEOUT, + ) + .await +} + +/// Issue an authenticated `POST /query` and parse the response, applying the +/// per-request `timeout` that bounds a stalled or half-open relay connection. +/// +/// Both `/query` builders funnel through this one helper so the timeout can +/// never be applied to one builder and dropped from the other, and so a test +/// can drive the real send/timeout/classify path with a short deadline against +/// a stalled loopback. A timeout surfaces through `classify_request_error` as +/// the stable `"relay unreachable: request timed out"` string. +async fn send_query_request( + http_client: &reqwest::Client, + url: &str, + auth: &str, + auth_tag: Option<&str>, + body_bytes: Vec, + timeout: std::time::Duration, +) -> Result, String> { + let mut request = http_client + .post(url) .header("Authorization", auth) - .header("Content-Type", "application/json"); + .header("Content-Type", "application/json") + .timeout(timeout); if let Some(tag) = auth_tag { request = request.header("x-auth-tag", tag); } @@ -611,384 +680,4 @@ pub async fn submit_signed_event_with_keys( // ── Tests ─────────────────────────────────────────────────────────────────── #[cfg(test)] -mod tests { - use super::{ - build_profile_event, classify_intercepted_response, effective_agent_relay_url, - extract_retry_in_hint, parse_command_response, relay_http_base_url, - MALFORMED_RESPONSE_MESSAGE, - }; - use serde::Deserialize; - - // ── extract_retry_in_hint ──────────────────────────────────────────────── - - #[test] - fn extracts_hint_from_429_body() { - assert_eq!( - extract_retry_in_hint(r#"{"error":"rate-limited: quota exceeded; retry in 4s"}"#), - Some(4) - ); - } - - #[test] - fn extracts_hint_when_no_json_wrapper() { - assert_eq!(extract_retry_in_hint("retry in 30s"), Some(30)); - } - - #[test] - fn returns_none_when_no_hint_present() { - assert_eq!( - extract_retry_in_hint(r#"{"error":"rate-limited: quota exceeded"}"#), - None - ); - assert_eq!(extract_retry_in_hint(""), None); - } - - #[test] - fn overlong_digit_string_returns_none() { - // A digit sequence that exceeds u64::MAX cannot be parsed; the function - // must return None (→ caller uses the default) rather than panicking. - assert_eq!( - extract_retry_in_hint("retry in 99999999999999999999999s"), - None - ); - } - - // ── relay_error_message: hint capping ──────────────────────────────────── - // - // Verify that an oversized relay hint is capped in the returned message - // string, not just inside `activate_rate_limit()`. This guarantees every - // consumer — including the TS gate via `applyTauriRateLimitIfNeeded` — - // receives the capped value rather than the raw untrusted relay value. - - #[tokio::test] - async fn oversized_hint_is_capped_in_relay_error_message_string() { - use crate::relay_admission::{reset_rate_limit_gate, MAX_HINT_SECONDS, TEST_SERIAL}; - use std::io::{Read as _, Write as _}; - - let _serial = TEST_SERIAL.lock().await; - reset_rate_limit_gate(); - - // Use a std::net listener on a std::thread — the same pattern as the - // relay_admission loopback tests. This avoids two races that cause CI - // failures with tokio::net + into_std(): - // 1. No request read: the client is still sending when the response - // arrives → hyper `UnexpectedMessage`/`Canceled` under load. - // 2. into_std() leaves the socket in nonblocking mode → write_all - // may return WouldBlock and silently drop the response. - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - - // Serve a 429 with a hint far exceeding MAX_HINT_SECONDS (300). - let oversized = 1_000_000u64; - let body = format!(r#"{{"error":"rate-limited: quota exceeded; retry in {oversized}s"}}"#); - let body_len = body.len(); - std::thread::spawn(move || { - if let Ok((mut stream, _)) = listener.accept() { - // Read the request first so the client finishes sending before - // we write the response — mirrors relay_admission.rs pattern. - let mut buf = [0u8; 4096]; - let _ = stream.read(&mut buf); - let response = format!( - "HTTP/1.1 429 Too Many Requests\r\nContent-Type: application/json\r\nContent-Length: {body_len}\r\nConnection: close\r\n\r\n{body}" - ); - let _ = stream.write_all(response.as_bytes()); - let _ = stream.flush(); - } - }); - - let client = reqwest::Client::new(); - let response = client - .get(format!("http://{addr}/")) - .send() - .await - .expect("request must succeed"); - - let msg = super::relay_error_message(response).await; - - // The message must embed the CAPPED hint, not the raw 1 000 000. - assert_eq!( - msg, - format!("relay rate-limited: retry in {MAX_HINT_SECONDS}s"), - "relay_error_message must embed the capped hint, not the raw untrusted value" - ); - assert!( - !msg.contains(&oversized.to_string()), - "raw oversized hint must not appear in the message string" - ); - reset_rate_limit_gate(); - } - - // ── effective_agent_relay_url: legacy pin ignored ───────────────────────── - - #[test] - fn stored_relay_pin_is_ignored() { - // Zero-touch cutover (#2122): a creation-era per-record relay pin is - // parsed and persisted but never consulted — the workspace relay wins. - assert_eq!( - effective_agent_relay_url("wss://relay.other.com", "wss://staging.example.com"), - "wss://staging.example.com" - ); - } - - #[test] - fn empty_relay_resolves_to_workspace() { - // A never-set record resolves to the active workspace relay at read-time, - // so a stale stored default can never make it load-bearing. - assert_eq!( - effective_agent_relay_url("", "wss://staging.example.com"), - "wss://staging.example.com" - ); - } - - #[test] - fn whitespace_only_relay_resolves_to_workspace() { - // Whitespace-only behaves identically — no value survives. - assert_eq!( - effective_agent_relay_url(" ", "wss://staging.example.com"), - "wss://staging.example.com" - ); - } - - // ── relay_http_base_url scheme conversion ──────────────────────────────── - - #[test] - fn loopback_ws_localhost_preserves_authority() { - // Tenant host-binding keys off the HTTP Host/authority. The desktop must - // not rewrite localhost to 127.0.0.1, or local dev HTTP calls target a - // different unmapped community than the WebSocket URL. - assert_eq!( - relay_http_base_url("ws://localhost:3000"), - "http://localhost:3000" - ); - } - - #[test] - fn loopback_trailing_slash_removed_authority_preserved() { - assert_eq!( - relay_http_base_url("ws://localhost:3000/"), - "http://localhost:3000" - ); - } - - #[test] - fn remote_wss_host_unchanged() { - assert_eq!( - relay_http_base_url("wss://relay.example.com"), - "https://relay.example.com" - ); - } - - #[test] - fn loopback_ipv4_literal_unchanged() { - assert_eq!( - relay_http_base_url("ws://127.0.0.1:3000"), - "http://127.0.0.1:3000" - ); - } - - #[test] - fn localhost_substring_host_unchanged() { - assert_eq!( - relay_http_base_url("ws://localhost.evil.com:3000"), - "http://localhost.evil.com:3000" - ); - } - - #[test] - fn loopback_wss_localhost_preserves_authority() { - assert_eq!( - relay_http_base_url("wss://localhost:3000"), - "https://localhost:3000" - ); - } - - // ── classify_intercepted_response ──────────────────────────────────────── - - #[test] - fn intercepted_cloudflare_host_returns_some() { - let result = classify_intercepted_response("sqprod.cloudflareaccess.com", "text/html"); - assert!(result.is_some()); - let msg = result.unwrap(); - assert!( - msg.starts_with("relay unreachable:"), - "should have unreachable prefix" - ); - assert!(msg.contains("Cloudflare"), "should mention Cloudflare"); - } - - #[test] - fn intercepted_cloudflare_apex_host_returns_some() { - // The apex domain itself should also match. - let result = classify_intercepted_response("cloudflareaccess.com", "application/json"); - assert!(result.is_some()); - let msg = result.unwrap(); - assert!(msg.starts_with("relay unreachable:")); - assert!(msg.contains("Cloudflare")); - } - - #[test] - fn intercepted_non_cloudflare_html_returns_some() { - let result = - classify_intercepted_response("proxy.corporate.example", "text/html; charset=utf-8"); - assert!(result.is_some()); - let msg = result.unwrap(); - assert!(msg.starts_with("relay unreachable:")); - } - - #[test] - fn normal_relay_json_returns_none() { - let result = classify_intercepted_response("relay.myapp.example.com", "application/json"); - assert!(result.is_none()); - } - - #[test] - fn content_type_case_insensitive() { - // Uppercase content-type must still be detected. - let result = classify_intercepted_response("proxy.example.com", "TEXT/HTML"); - assert!(result.is_some()); - assert!(result.unwrap().starts_with("relay unreachable:")); - } - - #[test] - fn evil_suffix_does_not_match_cloudflare() { - // A host whose suffix happens to contain the Cloudflare string but is - // not actually a subdomain must NOT match. - let result = classify_intercepted_response( - "notcloudflareaccess.com.evil.example", - "application/json", - ); - assert!( - result.is_none(), - "false suffix match should not trigger Cloudflare branch" - ); - } - - // classify_request_error requires a real reqwest::Error (not publicly - // constructable) — tested indirectly through integration; skipped here. - - // ── parse_json_response malformed-body contract ────────────────────────── - - #[test] - fn malformed_response_message_stays_off_unreachable_bucket() { - // A reached-but-malformed 2xx body is not a connectivity failure. If this - // message ever regains the "relay unreachable:" prefix, the frontend - // classifier would misroute it as unreachable — pin that it never does. - assert!( - !MALFORMED_RESPONSE_MESSAGE.starts_with("relay unreachable:"), - "malformed-response message must not match the unreachable prefix" - ); - } - - // ── parse_command_response ─────────────────────────────────────────────── - - #[derive(Debug, Deserialize, PartialEq)] - struct ChannelCreated { - channel_id: String, - } - - #[test] - fn parse_command_response_decodes_typed_payload() { - let msg = r#"response:{"channel_id":"abc123"}"#; - let parsed: ChannelCreated = parse_command_response(msg).expect("should parse"); - assert_eq!( - parsed, - ChannelCreated { - channel_id: "abc123".to_string() - } - ); - } - - #[test] - fn parse_command_response_accepts_raw_json_fallback() { - // Backward-compat: relays that emit raw JSON (no prefix) still work. - let msg = r#"{"channel_id":"abc"}"#; - let parsed: ChannelCreated = parse_command_response(msg).expect("fallback parse"); - assert_eq!( - parsed, - ChannelCreated { - channel_id: "abc".to_string() - } - ); - } - - #[test] - fn parse_command_response_rejects_invalid_prefixed_json() { - let msg = "response:not-json"; - let result: Result = parse_command_response(msg); - assert!(result.is_err()); - assert!(result.unwrap_err().contains("response parse failed")); - } - - #[test] - fn parse_command_response_rejects_garbage() { - let msg = "totally not json or response"; - let result: Result = parse_command_response(msg); - assert!(result.is_err()); - } - - // ── build_profile_event ────────────────────────────────────────────────── - - /// Generate a valid NIP-OA auth tag JSON string signed by a fresh owner key - /// and addressed to `agent_keys`. - /// - /// Uses `nostr_compat` (nostr 0.36) for the owner keys because - /// `buzz_sdk_pkg::nip_oa::compute_auth_tag` expects nostr 0.36 types. - /// The agent pubkey is bridged via hex encoding. - fn make_valid_auth_tag(agent_keys: &nostr::Keys) -> String { - let owner_keys = nostr::Keys::generate(); - let agent_pubkey_hex = agent_keys.public_key().to_hex(); - let agent_compat_pubkey = - nostr::PublicKey::from_hex(&agent_pubkey_hex).expect("valid hex pubkey should parse"); - buzz_sdk_pkg::nip_oa::compute_auth_tag(&owner_keys, &agent_compat_pubkey, "") - .expect("compute_auth_tag should not fail with distinct keys") - } - - #[test] - fn profile_event_with_valid_auth_tag() { - let agent_keys = nostr::Keys::generate(); - let tag_json = make_valid_auth_tag(&agent_keys); - let event = build_profile_event(&agent_keys, "TestBot", None, Some(&tag_json)) - .expect("should succeed with a valid auth tag"); - - // Exactly one "auth" tag must be present. - let auth_tags: Vec<_> = event - .tags - .iter() - .filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("auth")) - .collect(); - assert_eq!(auth_tags.len(), 1, "expected exactly 1 auth tag"); - - // Must be a kind:0 (Metadata) event. - assert_eq!(event.kind, nostr::Kind::Metadata); - } - - #[test] - fn profile_event_without_auth_tag() { - let agent_keys = nostr::Keys::generate(); - let event = build_profile_event(&agent_keys, "TestBot", None, None) - .expect("should succeed without an auth tag"); - - // No "auth" tags should be present. - let auth_tags: Vec<_> = event - .tags - .iter() - .filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("auth")) - .collect(); - assert_eq!(auth_tags.len(), 0, "expected no auth tags"); - - assert_eq!(event.kind, nostr::Kind::Metadata); - } - - #[test] - fn profile_event_rejects_invalid_auth_tag() { - let agent_keys = nostr::Keys::generate(); - // Structurally valid JSON array but with a bogus signature — verification must fail. - let bad_json = format!(r#"["auth","{}","","{}"]"#, "a".repeat(64), "b".repeat(128)); - let result = build_profile_event(&agent_keys, "TestBot", None, Some(&bad_json)); - assert!(result.is_err(), "should reject an invalid auth tag"); - assert!( - result.unwrap_err().contains("verification failed"), - "error message should mention verification failure" - ); - } -} +mod tests; diff --git a/desktop/src-tauri/src/relay/tests.rs b/desktop/src-tauri/src/relay/tests.rs new file mode 100644 index 0000000000..4ae3924932 --- /dev/null +++ b/desktop/src-tauri/src/relay/tests.rs @@ -0,0 +1,615 @@ +//! Unit tests for the relay HTTP/command bridge helpers. +//! Extracted from `relay.rs` to keep that module under the file-size ratchet. + +use super::{ + build_profile_event, classify_intercepted_response, effective_agent_relay_url, + extract_retry_in_hint, parse_command_response, relay_http_base_url, MALFORMED_RESPONSE_MESSAGE, +}; +use serde::Deserialize; + +// ── extract_retry_in_hint ──────────────────────────────────────────────── + +#[test] +fn extracts_hint_from_429_body() { + assert_eq!( + extract_retry_in_hint(r#"{"error":"rate-limited: quota exceeded; retry in 4s"}"#), + Some(4) + ); +} + +#[test] +fn extracts_hint_when_no_json_wrapper() { + assert_eq!(extract_retry_in_hint("retry in 30s"), Some(30)); +} + +#[test] +fn returns_none_when_no_hint_present() { + assert_eq!( + extract_retry_in_hint(r#"{"error":"rate-limited: quota exceeded"}"#), + None + ); + assert_eq!(extract_retry_in_hint(""), None); +} + +#[test] +fn overlong_digit_string_returns_none() { + // A digit sequence that exceeds u64::MAX cannot be parsed; the function + // must return None (→ caller uses the default) rather than panicking. + assert_eq!( + extract_retry_in_hint("retry in 99999999999999999999999s"), + None + ); +} + +// ── relay_error_message: hint capping ──────────────────────────────────── +// +// Verify that an oversized relay hint is capped in the returned message +// string, not just inside `activate_rate_limit()`. This guarantees every +// consumer — including the TS gate via `applyTauriRateLimitIfNeeded` — +// receives the capped value rather than the raw untrusted relay value. + +#[tokio::test] +async fn oversized_hint_is_capped_in_relay_error_message_string() { + use crate::relay_admission::{reset_rate_limit_gate, MAX_HINT_SECONDS, TEST_SERIAL}; + use std::io::{Read as _, Write as _}; + + let _serial = TEST_SERIAL.lock().await; + reset_rate_limit_gate(); + + // Use a std::net listener on a std::thread — the same pattern as the + // relay_admission loopback tests. This avoids two races that cause CI + // failures with tokio::net + into_std(): + // 1. No request read: the client is still sending when the response + // arrives → hyper `UnexpectedMessage`/`Canceled` under load. + // 2. into_std() leaves the socket in nonblocking mode → write_all + // may return WouldBlock and silently drop the response. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + + // Serve a 429 with a hint far exceeding MAX_HINT_SECONDS (300). + let oversized = 1_000_000u64; + let body = format!(r#"{{"error":"rate-limited: quota exceeded; retry in {oversized}s"}}"#); + let body_len = body.len(); + std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + // Read the request first so the client finishes sending before + // we write the response — mirrors relay_admission.rs pattern. + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + let response = format!( + "HTTP/1.1 429 Too Many Requests\r\nContent-Type: application/json\r\nContent-Length: {body_len}\r\nConnection: close\r\n\r\n{body}" + ); + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + } + }); + + let client = reqwest::Client::new(); + let response = client + .get(format!("http://{addr}/")) + .send() + .await + .expect("request must succeed"); + + let msg = super::relay_error_message(response).await; + + // The message must embed the CAPPED hint, not the raw 1 000 000. + assert_eq!( + msg, + format!("relay rate-limited: retry in {MAX_HINT_SECONDS}s"), + "relay_error_message must embed the capped hint, not the raw untrusted value" + ); + assert!( + !msg.contains(&oversized.to_string()), + "raw oversized hint must not appear in the message string" + ); + reset_rate_limit_gate(); +} + +// ── effective_agent_relay_url: legacy pin ignored ───────────────────────── + +#[test] +fn stored_relay_pin_is_ignored() { + // Zero-touch cutover (#2122): a creation-era per-record relay pin is + // parsed and persisted but never consulted — the workspace relay wins. + assert_eq!( + effective_agent_relay_url("wss://relay.other.com", "wss://staging.example.com"), + "wss://staging.example.com" + ); +} + +#[test] +fn empty_relay_resolves_to_workspace() { + // A never-set record resolves to the active workspace relay at read-time, + // so a stale stored default can never make it load-bearing. + assert_eq!( + effective_agent_relay_url("", "wss://staging.example.com"), + "wss://staging.example.com" + ); +} + +#[test] +fn whitespace_only_relay_resolves_to_workspace() { + // Whitespace-only behaves identically — no value survives. + assert_eq!( + effective_agent_relay_url(" ", "wss://staging.example.com"), + "wss://staging.example.com" + ); +} + +// ── relay_http_base_url scheme conversion ──────────────────────────────── + +#[test] +fn loopback_ws_localhost_preserves_authority() { + // Tenant host-binding keys off the HTTP Host/authority. The desktop must + // not rewrite localhost to 127.0.0.1, or local dev HTTP calls target a + // different unmapped community than the WebSocket URL. + assert_eq!( + relay_http_base_url("ws://localhost:3000"), + "http://localhost:3000" + ); +} + +#[test] +fn loopback_trailing_slash_removed_authority_preserved() { + assert_eq!( + relay_http_base_url("ws://localhost:3000/"), + "http://localhost:3000" + ); +} + +#[test] +fn remote_wss_host_unchanged() { + assert_eq!( + relay_http_base_url("wss://relay.example.com"), + "https://relay.example.com" + ); +} + +#[test] +fn loopback_ipv4_literal_unchanged() { + assert_eq!( + relay_http_base_url("ws://127.0.0.1:3000"), + "http://127.0.0.1:3000" + ); +} + +#[test] +fn localhost_substring_host_unchanged() { + assert_eq!( + relay_http_base_url("ws://localhost.evil.com:3000"), + "http://localhost.evil.com:3000" + ); +} + +#[test] +fn loopback_wss_localhost_preserves_authority() { + assert_eq!( + relay_http_base_url("wss://localhost:3000"), + "https://localhost:3000" + ); +} + +// ── classify_intercepted_response ──────────────────────────────────────── + +#[test] +fn intercepted_cloudflare_host_returns_some() { + let result = classify_intercepted_response("sqprod.cloudflareaccess.com", "text/html"); + assert!(result.is_some()); + let msg = result.unwrap(); + assert!( + msg.starts_with("relay unreachable:"), + "should have unreachable prefix" + ); + assert!(msg.contains("Cloudflare"), "should mention Cloudflare"); +} + +#[test] +fn intercepted_cloudflare_apex_host_returns_some() { + // The apex domain itself should also match. + let result = classify_intercepted_response("cloudflareaccess.com", "application/json"); + assert!(result.is_some()); + let msg = result.unwrap(); + assert!(msg.starts_with("relay unreachable:")); + assert!(msg.contains("Cloudflare")); +} + +#[test] +fn intercepted_non_cloudflare_html_returns_some() { + let result = + classify_intercepted_response("proxy.corporate.example", "text/html; charset=utf-8"); + assert!(result.is_some()); + let msg = result.unwrap(); + assert!(msg.starts_with("relay unreachable:")); +} + +#[test] +fn normal_relay_json_returns_none() { + let result = classify_intercepted_response("relay.myapp.example.com", "application/json"); + assert!(result.is_none()); +} + +#[test] +fn content_type_case_insensitive() { + // Uppercase content-type must still be detected. + let result = classify_intercepted_response("proxy.example.com", "TEXT/HTML"); + assert!(result.is_some()); + assert!(result.unwrap().starts_with("relay unreachable:")); +} + +#[test] +fn evil_suffix_does_not_match_cloudflare() { + // A host whose suffix happens to contain the Cloudflare string but is + // not actually a subdomain must NOT match. + let result = + classify_intercepted_response("notcloudflareaccess.com.evil.example", "application/json"); + assert!( + result.is_none(), + "false suffix match should not trigger Cloudflare branch" + ); +} + +// classify_request_error requires a real reqwest::Error (not publicly +// constructable) — tested indirectly through integration; skipped here. + +// ── /query per-request timeout → classified error ──────────────────────── +// +// A stalled `/query` connection (headers never arrive) must not hang the +// caller forever. Both production `/query` builders funnel through +// `send_query_request`, which owns the per-request `.timeout(...)`; this test +// drives that exact helper against a loopback server that accepts the +// connection but never responds. It asserts two things the frontend depends +// on: (1) the helper returns instead of hanging, and (2) the failure is the +// stable `"relay unreachable: request timed out"` classified string. +// +// The outer `tokio::time::timeout` is the regression guard: if the production +// `.timeout(...)` is ever removed from `send_query_request`, this call would +// hang forever, so the guard fires and the test fails fast rather than +// stalling CI. A short 200ms deadline keeps the happy path fast. +#[tokio::test] +async fn stalled_query_request_times_out_with_classified_error() { + use std::io::Read as _; + use std::time::Duration; + + // A listener that accepts the connection and then holds it open without + // ever writing a response — the "headers never arrive" stall. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + // Drain the request but deliberately never respond, then hold + // the socket until the client aborts on its own timeout. + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + std::thread::sleep(Duration::from_secs(2)); + } + }); + + let client = reqwest::Client::new(); + let url = format!("http://{addr}/query"); + let result = tokio::time::timeout( + Duration::from_secs(5), + super::send_query_request( + &client, + &url, + "Nostr test-auth", + None, + b"[]".to_vec(), + Duration::from_millis(200), + ), + ) + .await + .expect( + "send_query_request must honor its per-request timeout and resolve within 5s; \ + if this guard fires, the production .timeout(...) was lost", + ); + + let err = result.expect_err("a stalled /query must surface an error, not succeed"); + assert_eq!( + err, "relay unreachable: request timed out", + "a timed-out /query must surface the stable classified string" + ); + + let _ = handle.join(); +} + +// ── /query body-stall timeout → classified error (not malformed) ───────── +// +// `send()` resolves once response headers arrive, so a relay that returns a +// valid 2xx JSON header block and then stalls the body trips the request +// deadline inside `response.json()` — the branch the pre-header stall above +// cannot reach. That is a connectivity failure, not a malformed body, so it +// must surface the stable "relay unreachable: request timed out" string rather +// than the malformed-response bucket. This drives `send_query_request` against +// a loopback that writes headers promising a body it never sends. +#[tokio::test] +async fn stalled_response_body_times_out_with_classified_error() { + use std::io::{Read as _, Write as _}; + use std::time::Duration; + + // Accept, drain the request, write a complete 2xx JSON header block that + // promises a body (Content-Length), then send nothing and hold the socket + // — the "headers arrive, body stalls" half-open case. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + let _ = stream.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 64\r\n\r\n", + ); + let _ = stream.flush(); + // Never write the promised body; hold past the client deadline. + std::thread::sleep(Duration::from_secs(2)); + } + }); + + let client = reqwest::Client::new(); + let url = format!("http://{addr}/query"); + let result = tokio::time::timeout( + Duration::from_secs(5), + super::send_query_request( + &client, + &url, + "Nostr test-auth", + None, + b"[]".to_vec(), + Duration::from_millis(200), + ), + ) + .await + .expect( + "send_query_request must honor its per-request timeout through body \ + consumption and resolve within 5s", + ); + + let err = result.expect_err("a stalled response body must surface an error, not succeed"); + assert_eq!( + err, "relay unreachable: request timed out", + "a body-stall timeout must surface the classified timeout string, not the \ + malformed-response bucket" + ); + + let _ = handle.join(); +} + +// ── /query non-2xx body-stall timeout → classified error (not status) ──── +// +// The 2xx path is not the only body-consuming path. A relay that returns a +// non-success status (500, 429, …) routes through `relay_error_message`, which +// consumes the body via `text()` to extract the structured error field. If the +// relay sends the status headers and then stalls the promised body, that +// consumption trips the same request deadline — and it must surface the stable +// "relay unreachable: request timed out" classification, not a bare +// "relay returned 500" that hides the connectivity failure. This drives +// `send_query_request` against a loopback that writes 500 headers promising a +// body it never sends. +#[tokio::test] +async fn stalled_error_response_body_times_out_with_classified_error() { + use std::io::{Read as _, Write as _}; + use std::time::Duration; + + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + // 500 status headers promising a body (Content-Length) that never + // arrives — the "error headers arrive, body stalls" half-open case. + let _ = stream.write_all( + b"HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: 64\r\n\r\n", + ); + let _ = stream.flush(); + std::thread::sleep(Duration::from_secs(2)); + } + }); + + let client = reqwest::Client::new(); + let url = format!("http://{addr}/query"); + let result = tokio::time::timeout( + Duration::from_secs(5), + super::send_query_request( + &client, + &url, + "Nostr test-auth", + None, + b"[]".to_vec(), + Duration::from_millis(200), + ), + ) + .await + .expect( + "send_query_request must honor its per-request timeout through error-body \ + consumption and resolve within 5s", + ); + + let err = result.expect_err("a stalled error-response body must surface an error, not succeed"); + assert_eq!( + err, "relay unreachable: request timed out", + "a non-2xx body-stall timeout must surface the classified timeout string, not the \ + status bucket" + ); + + let _ = handle.join(); +} + +// ── /query non-stalled 500 → status message (timeout preservation is scoped) ─ +// +// The timeout preservation above must not swallow genuine relay errors: a 500 +// whose body arrives promptly still surfaces as "relay returned 500". This +// pins that `classify_body_timeout` only fires on an actual timeout, so the +// error-classification path stays intact for live relay failures. +#[tokio::test] +async fn non_stalled_error_response_yields_status_message() { + use std::io::{Read as _, Write as _}; + use std::time::Duration; + + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let handle = std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + // A complete 500 with a non-JSON body delivered immediately. + let body = "internal error"; + let response = format!( + "HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()); + let _ = stream.flush(); + } + }); + + let client = reqwest::Client::new(); + let url = format!("http://{addr}/query"); + let result = tokio::time::timeout( + Duration::from_secs(5), + super::send_query_request( + &client, + &url, + "Nostr test-auth", + None, + b"[]".to_vec(), + Duration::from_millis(200), + ), + ) + .await + .expect("a promptly-served 500 must resolve well within 5s"); + + let err = result.expect_err("a 500 must surface an error, not succeed"); + assert_eq!( + err, "relay returned 500 Internal Server Error", + "a non-stalled 500 must keep its status classification, not be reclassified as a timeout" + ); + + let _ = handle.join(); +} + +// ── parse_json_response malformed-body contract ────────────────────────── + +#[test] +fn malformed_response_message_stays_off_unreachable_bucket() { + // A reached-but-malformed 2xx body is not a connectivity failure. If this + // message ever regains the "relay unreachable:" prefix, the frontend + // classifier would misroute it as unreachable — pin that it never does. + assert!( + !MALFORMED_RESPONSE_MESSAGE.starts_with("relay unreachable:"), + "malformed-response message must not match the unreachable prefix" + ); +} + +// ── parse_command_response ─────────────────────────────────────────────── + +#[derive(Debug, Deserialize, PartialEq)] +struct ChannelCreated { + channel_id: String, +} + +#[test] +fn parse_command_response_decodes_typed_payload() { + let msg = r#"response:{"channel_id":"abc123"}"#; + let parsed: ChannelCreated = parse_command_response(msg).expect("should parse"); + assert_eq!( + parsed, + ChannelCreated { + channel_id: "abc123".to_string() + } + ); +} + +#[test] +fn parse_command_response_accepts_raw_json_fallback() { + // Backward-compat: relays that emit raw JSON (no prefix) still work. + let msg = r#"{"channel_id":"abc"}"#; + let parsed: ChannelCreated = parse_command_response(msg).expect("fallback parse"); + assert_eq!( + parsed, + ChannelCreated { + channel_id: "abc".to_string() + } + ); +} + +#[test] +fn parse_command_response_rejects_invalid_prefixed_json() { + let msg = "response:not-json"; + let result: Result = parse_command_response(msg); + assert!(result.is_err()); + assert!(result.unwrap_err().contains("response parse failed")); +} + +#[test] +fn parse_command_response_rejects_garbage() { + let msg = "totally not json or response"; + let result: Result = parse_command_response(msg); + assert!(result.is_err()); +} + +// ── build_profile_event ────────────────────────────────────────────────── + +/// Generate a valid NIP-OA auth tag JSON string signed by a fresh owner key +/// and addressed to `agent_keys`. +/// +/// Uses `nostr_compat` (nostr 0.36) for the owner keys because +/// `buzz_sdk_pkg::nip_oa::compute_auth_tag` expects nostr 0.36 types. +/// The agent pubkey is bridged via hex encoding. +fn make_valid_auth_tag(agent_keys: &nostr::Keys) -> String { + let owner_keys = nostr::Keys::generate(); + let agent_pubkey_hex = agent_keys.public_key().to_hex(); + let agent_compat_pubkey = + nostr::PublicKey::from_hex(&agent_pubkey_hex).expect("valid hex pubkey should parse"); + buzz_sdk_pkg::nip_oa::compute_auth_tag(&owner_keys, &agent_compat_pubkey, "") + .expect("compute_auth_tag should not fail with distinct keys") +} + +#[test] +fn profile_event_with_valid_auth_tag() { + let agent_keys = nostr::Keys::generate(); + let tag_json = make_valid_auth_tag(&agent_keys); + let event = build_profile_event(&agent_keys, "TestBot", None, Some(&tag_json)) + .expect("should succeed with a valid auth tag"); + + // Exactly one "auth" tag must be present. + let auth_tags: Vec<_> = event + .tags + .iter() + .filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("auth")) + .collect(); + assert_eq!(auth_tags.len(), 1, "expected exactly 1 auth tag"); + + // Must be a kind:0 (Metadata) event. + assert_eq!(event.kind, nostr::Kind::Metadata); +} + +#[test] +fn profile_event_without_auth_tag() { + let agent_keys = nostr::Keys::generate(); + let event = build_profile_event(&agent_keys, "TestBot", None, None) + .expect("should succeed without an auth tag"); + + // No "auth" tags should be present. + let auth_tags: Vec<_> = event + .tags + .iter() + .filter(|t| t.as_slice().first().map(|s| s.as_str()) == Some("auth")) + .collect(); + assert_eq!(auth_tags.len(), 0, "expected no auth tags"); + + assert_eq!(event.kind, nostr::Kind::Metadata); +} + +#[test] +fn profile_event_rejects_invalid_auth_tag() { + let agent_keys = nostr::Keys::generate(); + // Structurally valid JSON array but with a bogus signature — verification must fail. + let bad_json = format!(r#"["auth","{}","","{}"]"#, "a".repeat(64), "b".repeat(128)); + let result = build_profile_event(&agent_keys, "TestBot", None, Some(&bad_json)); + assert!(result.is_err(), "should reject an invalid auth tag"); + assert!( + result.unwrap_err().contains("verification failed"), + "error message should mention verification failure" + ); +} diff --git a/desktop/src-tauri/src/shutdown.rs b/desktop/src-tauri/src/shutdown.rs index 17ca7a7bb3..b1548c6937 100644 --- a/desktop/src-tauri/src/shutdown.rs +++ b/desktop/src-tauri/src/shutdown.rs @@ -20,6 +20,7 @@ pub(crate) fn shut_down_app(app: &tauri::AppHandle, shutdown_done: &std::sync::a if !shutdown_done.swap(true, Ordering::SeqCst) { prevent_sleep::release(&app.state::().prevent_sleep); crate::observed_unread::flush(app); + crate::channel_head_cache::flush(app); app.state::() .shutdown_all(); if let Err(error) = shutdown_managed_agents(app) { diff --git a/desktop/src/app/App.tsx b/desktop/src/app/App.tsx index bfaf2ba200..bdb26c1930 100644 --- a/desktop/src/app/App.tsx +++ b/desktop/src/app/App.tsx @@ -63,6 +63,7 @@ import { CommunityChangeOverlay } from "@/features/communities/ui/CommunityChang import { setAvatarProfileSyncQueryClient } from "@/features/profile/avatarProfileSync"; import { EncryptedBackupProvider } from "@/features/settings/EncryptedBackupProvider"; import { createBuzzQueryClient } from "@/shared/api/queryClient"; +import { hydrateChannelHeads } from "@/features/messages/lib/channelHeadCache"; import { useIdentityQuery } from "@/shared/api/hooks"; import { isSharedIdentity as isSharedIdentityCmd } from "@/shared/api/tauri"; import { getProfile } from "@/shared/api/tauriProfiles"; @@ -213,8 +214,30 @@ function CommunitySwitchGate() { ); } -function CommunityQueryProvider({ children }: { children: ReactNode }) { - const [queryClient] = useState(createBuzzQueryClient); +function CommunityQueryProvider({ + children, + pubkey, + relayUrl, +}: { + children: ReactNode; + pubkey: string | null; + relayUrl: string | null; +}) { + // Seeding persisted channel heads is part of constructing the client, not a + // gate in front of the app: the splash, AppReady, and relay preconnect mount + // immediately, and only the channel query waits on the cache load (see + // channelHeadHydration). It must start here rather than in an effect — + // React Query fires a child's queryFn when it subscribes, before any parent + // effect runs — and StrictMode's dev-only double initializer just issues one + // redundant read on a discarded client. The provider is keyed on the + // community, so one client maps to one {pubkey, relayUrl} scope. + const [queryClient] = useState(() => { + const client = createBuzzQueryClient(); + if (pubkey && relayUrl) { + void hydrateChannelHeads(client, { pubkey, relayUrl }); + } + return client; + }); useEffect(() => setAvatarProfileSyncQueryClient(queryClient), [queryClient]); @@ -601,7 +624,11 @@ function CommunityApp({ }, [communityApplied]); if (appContent === null && (!transaction || isEnteringCurtain)) { appContent = communityApplied ? ( - + diff --git a/desktop/src/app/navigation/navigationGuard.test.mjs b/desktop/src/app/navigation/navigationGuard.test.mjs new file mode 100644 index 0000000000..4fb72329b7 --- /dev/null +++ b/desktop/src/app/navigation/navigationGuard.test.mjs @@ -0,0 +1,100 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +const target = { + kind: "channel-message", + channelId: "general", + messageId: "message-a", + threadRootId: "thread-a", +}; + +const { allowNavigation, registerNavigationGuard, traverseHistory } = + await import("./navigationGuard.ts"); + +test("all navigation consults the registered boundary guard", () => { + let received; + const unregister = registerNavigationGuard((nextTarget) => { + received = nextTarget; + return false; + }); + + assert.equal(allowNavigation(target), false); + assert.deepEqual(received, target); + unregister(); + assert.equal(allowNavigation(target), true); +}); + +test("guarded history traversal blocks before mutating history", () => { + let received; + let backCalls = 0; + const unregister = registerNavigationGuard((nextTarget) => { + received = nextTarget; + return false; + }); + + assert.equal( + traverseHistory( + { + back: () => { + backCalls += 1; + }, + forward: () => {}, + }, + "back", + ), + false, + ); + assert.deepEqual(received, { kind: "history", direction: "back" }); + assert.equal(backCalls, 0); + unregister(); +}); + +test("guarded history traversal invokes the selected direction when allowed", () => { + let forwardCalls = 0; + + assert.equal( + traverseHistory( + { + back: () => {}, + forward: () => { + forwardCalls += 1; + }, + }, + "forward", + ), + true, + ); + assert.equal(forwardCalls, 1); +}); + +test("unregistering the newer guard restores the prior live guard", () => { + const unregisterFirst = registerNavigationGuard(() => false); + const unregisterSecond = registerNavigationGuard(() => true); + + assert.equal(allowNavigation(target), true); + unregisterSecond(); + assert.equal(allowNavigation(target), false); + unregisterFirst(); + assert.equal(allowNavigation(target), true); +}); + +test("stale cleanup cannot unregister a newer guard", () => { + const unregisterFirst = registerNavigationGuard(() => false); + const unregisterSecond = registerNavigationGuard(() => true); + + unregisterFirst(); + assert.equal(allowNavigation(target), true); + unregisterSecond(); + assert.equal(allowNavigation(target), true); +}); + +test("duplicate callback registrations clean up by registration identity", () => { + const sharedGuard = () => false; + const unregisterFirst = registerNavigationGuard(sharedGuard); + const unregisterSecond = registerNavigationGuard(sharedGuard); + + unregisterFirst(); + assert.equal(allowNavigation(target), false); + unregisterSecond(); + assert.equal(allowNavigation(target), true); +}); diff --git a/desktop/src/app/navigation/navigationGuard.ts b/desktop/src/app/navigation/navigationGuard.ts new file mode 100644 index 0000000000..5ff853720b --- /dev/null +++ b/desktop/src/app/navigation/navigationGuard.ts @@ -0,0 +1,54 @@ +export type GuardedNavigation = + | { + kind: "history"; + direction: "back" | "forward"; + } + | { + kind: "route"; + href: string; + } + | { + kind: "channel-message"; + channelId: string; + messageId: string; + threadRootId: string | null; + } + | { + kind: "forum-post"; + channelId: string; + postId: string; + replyId: string | null; + }; + +type NavigationGuard = (target: GuardedNavigation) => boolean; + +type GuardRegistration = { + guard: NavigationGuard; +}; + +const activeGuards: GuardRegistration[] = []; + +export function allowNavigation(target: GuardedNavigation): boolean { + return activeGuards.at(-1)?.guard(target) ?? true; +} + +export function traverseHistory( + history: Pick, + direction: "back" | "forward", +): boolean { + if (!allowNavigation({ kind: "history", direction })) { + return false; + } + + history[direction](); + return true; +} + +export function registerNavigationGuard(guard: NavigationGuard): () => void { + const registration = { guard }; + activeGuards.push(registration); + return () => { + const index = activeGuards.lastIndexOf(registration); + if (index >= 0) activeGuards.splice(index, 1); + }; +} diff --git a/desktop/src/app/navigation/useAppNavigation.ts b/desktop/src/app/navigation/useAppNavigation.ts index c4776564e3..7a21f0dfbe 100644 --- a/desktop/src/app/navigation/useAppNavigation.ts +++ b/desktop/src/app/navigation/useAppNavigation.ts @@ -7,6 +7,11 @@ import { } from "@tanstack/react-router"; import { openSearchHitWithNavigation } from "@/app/navigation/searchHitNavigation"; +import { + allowNavigation, + type GuardedNavigation, + traverseHistory, +} from "@/app/navigation/navigationGuard"; import type { SearchHit } from "@/shared/api/types"; type NavigationBehavior = { @@ -30,6 +35,7 @@ export function useAppNavigation() { state?: Record; }, behavior: NavigationBehavior = {}, + guardedTarget?: GuardedNavigation, ) => { const nextLocation = router.buildLocation(next as never); @@ -37,6 +43,14 @@ export function useAppNavigation() { return false; } + if ( + !allowNavigation( + guardedTarget ?? { kind: "route", href: nextLocation.href }, + ) + ) { + return false; + } + await navigate({ ...next, replace: behavior.replace, @@ -256,8 +270,8 @@ export function useAppNavigation() { thread?: string; threadRootId?: string | null; }, - ) => - commitNavigation( + ) => { + return commitNavigation( { to: "/channels/$channelId", params: { @@ -282,7 +296,16 @@ export function useAppNavigation() { replace: options?.replace, resetScroll: options?.messageId ? true : undefined, }, - ), + options?.messageId + ? { + kind: "channel-message", + channelId, + messageId: options.messageId, + threadRootId: options.threadRootId ?? null, + } + : undefined, + ); + }, [commitNavigation], ); @@ -307,8 +330,8 @@ export function useAppNavigation() { replace?: boolean; replyId?: string; }, - ) => - commitNavigation( + ) => { + return commitNavigation( { to: "/channels/$channelId/posts/$postId", params: { @@ -322,7 +345,14 @@ export function useAppNavigation() { replace: options?.replace, resetScroll: false, }, - ), + { + kind: "forum-post", + channelId, + postId, + replyId: options?.replyId ?? null, + }, + ); + }, [commitNavigation], ); @@ -340,7 +370,7 @@ export function useAppNavigation() { const closeSettings = React.useCallback(() => { if (canGoBack) { - router.history.back(); + traverseHistory(router.history, "back"); return; } @@ -349,7 +379,7 @@ export function useAppNavigation() { const closeWorkflowDetail = React.useCallback(() => { if (canGoBack) { - router.history.back(); + traverseHistory(router.history, "back"); return; } @@ -359,7 +389,7 @@ export function useAppNavigation() { const closeForumPost = React.useCallback( (channelId: string) => { if (canGoBack) { - router.history.back(); + traverseHistory(router.history, "back"); return; } diff --git a/desktop/src/app/navigation/useBackForwardControls.ts b/desktop/src/app/navigation/useBackForwardControls.ts index e5513247d5..717e62153e 100644 --- a/desktop/src/app/navigation/useBackForwardControls.ts +++ b/desktop/src/app/navigation/useBackForwardControls.ts @@ -8,6 +8,7 @@ import { isTauri } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; import { matchBackForwardChord } from "@/app/navigation/backForwardChords"; +import { traverseHistory } from "@/app/navigation/navigationGuard"; import { isMacPlatform } from "@/shared/lib/platform"; import { trimMapToSize } from "@/shared/lib/trimMapToSize"; @@ -59,7 +60,7 @@ export function useBackForwardControls() { return; } - router.history.back(); + traverseHistory(router.history, "back"); }, [canGoBack, router.history]); const goForward = React.useCallback(() => { @@ -67,7 +68,7 @@ export function useBackForwardControls() { return; } - router.history.forward(); + traverseHistory(router.history, "forward"); }, [canGoForward, router.history]); const handleKeyDown = React.useEffectEvent((event: KeyboardEvent) => { diff --git a/desktop/src/app/routes/WorkflowsRouteScreen.tsx b/desktop/src/app/routes/WorkflowsRouteScreen.tsx index 193695f0cd..8c476b2863 100644 --- a/desktop/src/app/routes/WorkflowsRouteScreen.tsx +++ b/desktop/src/app/routes/WorkflowsRouteScreen.tsx @@ -18,6 +18,7 @@ export function WorkflowsRouteScreen({ onEditorPaneChange, }: WorkflowsRouteScreenProps) { const { + closeWorkflowDetail, goDuplicateWorkflow, goEditWorkflow, goNewWorkflow, @@ -26,11 +27,11 @@ export function WorkflowsRouteScreen({ } = useAppNavigation(); const closeEditor = React.useCallback(() => { if (editor?.hasOrigin) { - window.history.back(); + closeWorkflowDetail(); return; } void goWorkflows({ replace: true }); - }, [editor?.hasOrigin, goWorkflows]); + }, [closeWorkflowDetail, editor?.hasOrigin, goWorkflows]); const channelsQuery = useChannelsQuery(); const channels = channelsQuery.data ?? []; const memberChannels = channels.filter((channel) => channel.isMember); diff --git a/desktop/src/app/useAppShellLifecycleEffects.ts b/desktop/src/app/useAppShellLifecycleEffects.ts index 969bf67ca6..71db052369 100644 --- a/desktop/src/app/useAppShellLifecycleEffects.ts +++ b/desktop/src/app/useAppShellLifecycleEffects.ts @@ -42,33 +42,13 @@ export function useAppShellLifecycleEffects({ React.useEffect(() => { let isCancelled = false; - - const startPreconnect = () => { - if (isCancelled) { - return; + void relayClient.preconnect().catch((error) => { + if (!isCancelled) { + console.error("Failed to preconnect to relay", error); } - - void relayClient.preconnect().catch((error) => { - if (!isCancelled) { - console.error("Failed to preconnect to relay", error); - } - }); - }; - - if ("requestIdleCallback" in window) { - const idleId = window.requestIdleCallback(startPreconnect, { - timeout: 1_500, - }); - return () => { - isCancelled = true; - window.cancelIdleCallback(idleId); - }; - } - - const timeoutId = globalThis.setTimeout(startPreconnect, 250); + }); return () => { isCancelled = true; - globalThis.clearTimeout(timeoutId); }; }, []); diff --git a/desktop/src/features/agents/ui/OtherSetupAgentMarker.tsx b/desktop/src/features/agents/ui/OtherSetupAgentMarker.tsx index e653943469..19ef31bd75 100644 --- a/desktop/src/features/agents/ui/OtherSetupAgentMarker.tsx +++ b/desktop/src/features/agents/ui/OtherSetupAgentMarker.tsx @@ -1,7 +1,6 @@ import { Cloud } from "lucide-react"; import { cn } from "@/shared/lib/cn"; -import { Badge } from "@/shared/ui/badge"; const OTHER_SETUP_LABEL = "From another Buzz setup"; @@ -13,18 +12,14 @@ export function OtherSetupAgentMarker({ testId?: string; }) { return ( - + ); } diff --git a/desktop/src/features/channels/ui/ChannelPane.tsx b/desktop/src/features/channels/ui/ChannelPane.tsx index bccc163ed4..4086a4e1c1 100644 --- a/desktop/src/features/channels/ui/ChannelPane.tsx +++ b/desktop/src/features/channels/ui/ChannelPane.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import { toast } from "sonner"; import { Hash, LogIn } from "lucide-react"; import { AnimatePresence } from "motion/react"; import { useAppNavigation } from "@/app/navigation/useAppNavigation"; @@ -13,6 +14,7 @@ import { useRelaySelfQuery } from "@/features/moderation/hooks"; import { DropZoneOverlay } from "@/features/messages/ui/ComposerAttachments"; import { MessageThreadPanel } from "@/features/messages/ui/MessageThreadPanel"; import { MessageThreadPanelSkeleton } from "@/features/messages/ui/MessageThreadPanelSkeleton"; +import { ThreadRepliesErrorCard } from "@/features/messages/ui/MessageThreadReplyState"; import { MessageTimeline, type MessageTimelineHandle, @@ -23,6 +25,7 @@ import { hasOtherDmParticipant, } from "@/features/channels/lib/dmHuddleMembers"; import { buildVideoReviewPresentationByMessageId } from "@/features/messages/lib/videoReviewContext"; +import { isThreadReply } from "@/features/messages/lib/threading"; import { useComposerHeightPadding } from "@/features/messages/ui/useComposerHeightPadding"; import { UserProfilePanel } from "@/features/profile/ui/UserProfilePanel"; import { AgentSessionThreadPanel } from "@/features/channels/ui/AgentSessionThreadPanel"; @@ -95,6 +98,8 @@ export const ChannelPane = React.memo(function ChannelPane({ welcomeKickoffSettingUp = false, messages, threadSummaries, + huddleThreadRepliesError = false, + onRetryHuddleThreadReplies, firstUnreadMessageId = null, unreadCount = 0, canResetThreadPanelWidth, @@ -151,6 +156,8 @@ export const ChannelPane = React.memo(function ChannelPane({ threadHeadMessage, threadMessages, threadMessagesPending = false, + threadMessagesError = false, + onRetryThreadReplies, threadPanelWidthPx, threadScrollTargetId, threadTypingPubkeys, @@ -220,11 +227,7 @@ export const ChannelPane = React.memo(function ChannelPane({ isActiveWelcomeChannel, currentPubkey ?? null, ); - const isEditInThread = - editTarget != null && - threadHeadMessage != null && - (editTarget.id === threadHeadMessage.id || - threadMessages.some((entry) => entry.message.id === editTarget.id)); + const isEditInThread = editTarget?.isThreadReply === true; const mainEditTarget = editTarget && !isEditInThread ? editTarget : null; const threadEditTarget = editTarget && isEditInThread ? editTarget : null; const findLastOwnEditable = React.useCallback( @@ -247,23 +250,7 @@ export const ChannelPane = React.memo(function ChannelPane({ }, [onEdit, currentPubkey], ); - const handleEditLastOwnMainMessage = React.useCallback((): boolean => { - const target = findLastOwnEditable(messages); - if (!target || !onEdit) return false; - onEdit(target); - return true; - }, [findLastOwnEditable, messages, onEdit]); - const handleEditLastOwnThreadMessage = React.useCallback((): boolean => { - if (!onEdit) return false; - const scope: TimelineMessage[] = []; - if (threadHeadMessage) scope.push(threadHeadMessage); - for (const entry of threadMessages) scope.push(entry.message); - const target = findLastOwnEditable(scope); - if (!target) return false; - onEdit(target); - return true; - }, [findLastOwnEditable, onEdit, threadHeadMessage, threadMessages]); const timeoutState = useTimeoutState(); // A moderation DM (1:1 with the relay identity) is read-only for the member; // only DMs pay for the NIP-11 `self` lookup. Fails open: no `relaySelf` → @@ -461,6 +448,81 @@ export const ChannelPane = React.memo(function ChannelPane({ useFocusThreadDrawer, onCloseThread, ); + const pendingMainEditRef = React.useRef(null); + const editTargetRef = React.useRef(editTarget); + editTargetRef.current = editTarget; + const pendingMainEditContextRef = React.useRef({ + channelId: activeChannel?.id ?? null, + threadId: threadHeadMessage?.id ?? null, + }); + const pendingMainEditContext = { + channelId: activeChannel?.id ?? null, + threadId: threadHeadMessage?.id ?? null, + }; + const previousPendingContext = pendingMainEditContextRef.current; + if ( + previousPendingContext.channelId !== pendingMainEditContext.channelId || + (previousPendingContext.threadId !== null && + pendingMainEditContext.threadId !== null && + previousPendingContext.threadId !== pendingMainEditContext.threadId) + ) { + pendingMainEditRef.current = null; + } + pendingMainEditContextRef.current = pendingMainEditContext; + const handleRoutedEdit = React.useCallback( + (message: TimelineMessage): boolean => { + const currentEditTarget = editTargetRef.current; + if ( + currentEditTarget && + currentEditTarget.id !== message.id && + currentEditTarget.isThreadReply !== isThreadReply(message.tags ?? []) + ) { + pendingMainEditRef.current = null; + toast.info("Finish or cancel your edit first."); + return false; + } + if (currentEditTarget?.id === message.id) { + pendingMainEditRef.current = null; + onEdit?.(message); + return true; + } + if ( + !isThreadReply(message.tags ?? []) && + (isSinglePanelView || useFocusThreadDrawer) + ) { + pendingMainEditRef.current = message; + onCloseThread(); + return true; + } + onEdit?.(message); + return Boolean(onEdit); + }, + [isSinglePanelView, onCloseThread, onEdit, useFocusThreadDrawer], + ); + const handleEditLastOwnMainMessage = React.useCallback((): boolean => { + const target = findLastOwnEditable( + mainTimelineEntries.map((entry) => entry.message), + ); + return target ? handleRoutedEdit(target) : false; + }, [findLastOwnEditable, handleRoutedEdit, mainTimelineEntries]); + const handleEditLastOwnThreadMessage = React.useCallback((): boolean => { + const scope: TimelineMessage[] = []; + if (threadHeadMessage) scope.push(threadHeadMessage); + for (const entry of threadMessages) scope.push(entry.message); + const target = findLastOwnEditable(scope); + return target ? handleRoutedEdit(target) : false; + }, [ + findLastOwnEditable, + handleRoutedEdit, + threadHeadMessage, + threadMessages, + ]); + React.useEffect(() => { + const pendingMainEdit = pendingMainEditRef.current; + if (!pendingMainEdit || isSinglePanelView || channelIsCovered) return; + pendingMainEditRef.current = null; + onEdit?.(pendingMainEdit); + }, [channelIsCovered, isSinglePanelView, onEdit]); const { changeThreadViewMode, layoutScrollTargetId, resolveScrollTarget } = useThreadViewModeSwitch({ activeThreadHeadId: threadHeadMessage?.id ?? null, @@ -508,6 +570,7 @@ export const ChannelPane = React.memo(function ChannelPane({ useFocusThreadDrawer ? ( @@ -542,7 +605,6 @@ export const ChannelPane = React.memo(function ChannelPane({ data-testid="channel-shared-header-backdrop" /> ) : null} - {!isSinglePanelView ? (
{isHuddleTranscript ? null : header} + {isHuddleTranscript && huddleThreadRepliesError ? ( +
+ +
+ ) : null}
) : null} - {/* * `AnimatePresence` keeps the focus thread drawer mounted through its exit * animation — without it the drawer's own existence condition @@ -808,7 +874,7 @@ export const ChannelPane = React.memo(function ChannelPane({ onCancelReply={onCancelThreadReply} onClose={onCloseThread} onDelete={onDelete} - onEdit={onEdit} + onEdit={handleRoutedEdit} onEditLastOwnMessage={handleEditLastOwnThreadMessage} onEditSave={onEditSave} onFollowThread={onFollowThread} @@ -833,6 +899,8 @@ export const ChannelPane = React.memo(function ChannelPane({ widthPx={threadPanelWidthPx} threadReplies={threadMessages} threadRepliesPending={threadMessagesPending} + threadRepliesError={threadMessagesError} + onRetryThreadReplies={onRetryThreadReplies} threadUnreadCount={threadUnreadCounts?.get( threadHeadMessage.id, )} diff --git a/desktop/src/features/channels/ui/ChannelPane.types.ts b/desktop/src/features/channels/ui/ChannelPane.types.ts index 760ef58073..0296822168 100644 --- a/desktop/src/features/channels/ui/ChannelPane.types.ts +++ b/desktop/src/features/channels/ui/ChannelPane.types.ts @@ -1,13 +1,12 @@ import type * as React from "react"; import type { BotActivityAgent } from "@/features/channels/ui/BotActivityBar"; import type { ChannelAgentSessionAgent } from "@/features/channels/ui/useChannelAgentSessions"; -import type { ImetaMedia } from "@/features/messages/lib/imetaMediaMarkdown"; +import type { MessageComposerEditTarget } from "@/features/messages/ui/MessageComposer.types"; import type { MainTimelineEntry } from "@/features/messages/lib/threadPanel"; import type { ChannelWindowThreadSummary } from "@/features/messages/lib/channelWindowStore"; import type { TimelineMessage } from "@/features/messages/types"; import type { TypingIndicatorEntry } from "@/features/messages/useChannelTyping"; import type { UserProfileLookup } from "@/features/profile/lib/identity"; -import type { DraftMentionRef } from "@/features/messages/lib/useDrafts"; import type { ProfilePanelTab, ProfilePanelView, @@ -37,13 +36,7 @@ export type ChannelPaneProps = { botTypingEntries: TypingIndicatorEntry[]; channelManagementOpen?: boolean; currentPubkey?: string; - editTarget?: { - author: string; - body: string; - id: string; - imetaMedia?: ImetaMedia[]; - mentionRefs?: DraftMentionRef[]; - } | null; + editTarget?: MessageComposerEditTarget | null; fetchOlder?: () => Promise; header?: React.ReactNode; hasOlderMessages?: boolean; @@ -65,6 +58,14 @@ export type ChannelPaneProps = { welcomeKickoffSettingUp?: boolean; messages: TimelineMessage[]; threadSummaries?: ReadonlyMap; + /** + * A Huddle transcript flattens summarized reply subtrees into the chat + * timeline. When one of those subtree loads fails, this reports the aggregate + * failure so the transcript can surface a non-destructive retry alert instead + * of silently presenting a partial conversation as complete. + */ + huddleThreadRepliesError?: boolean; + onRetryHuddleThreadReplies?: () => void; firstUnreadMessageId?: string | null; unreadCount?: number; canResetThreadPanelWidth: boolean; @@ -170,6 +171,8 @@ export type ChannelPaneProps = { threadAllMessages: TimelineMessage[]; threadMessages: MainTimelineEntry[]; threadMessagesPending?: boolean; + threadMessagesError?: boolean; + onRetryThreadReplies?: () => void; threadPanelWidthPx: number; threadTypingPubkeys: string[]; threadReplyTargetMessage: TimelineMessage | null; diff --git a/desktop/src/features/channels/ui/ChannelScreen.tsx b/desktop/src/features/channels/ui/ChannelScreen.tsx index 6254afd8c7..240a9ad70c 100644 --- a/desktop/src/features/channels/ui/ChannelScreen.tsx +++ b/desktop/src/features/channels/ui/ChannelScreen.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import { useQueryClient } from "@tanstack/react-query"; import { useAppShell } from "@/app/AppShellContext"; import { useAppNavigation } from "@/app/navigation/useAppNavigation"; import { useActiveChannelHeader } from "@/features/channels/useActiveChannelHeader"; @@ -16,7 +17,6 @@ import { } from "@/features/channels/readState/readStateFormat"; import { ChannelScreenEmptyState } from "@/features/channels/ui/ChannelScreenEmptyState"; import { ChannelScreenHeader } from "@/features/channels/ui/ChannelScreenHeader"; -import { ChannelPane } from "@/features/channels/ui/ChannelScreenLazyViews"; import { WelcomeAgentCreateDialog } from "@/features/channels/ui/WelcomeAgentCreateDialog"; import { ForumChannelContent } from "@/features/channels/ui/ForumChannelContent"; import { MembersSidebar } from "@/features/channels/ui/MembersSidebar"; @@ -44,7 +44,11 @@ import { import { buildMessageComposerEditTarget } from "@/features/messages/lib/draftMentionRefs"; import { formatTimelineMessages } from "@/features/messages/lib/formatTimelineMessages"; import { DeleteMessageConfirmDialog } from "@/features/messages/ui/DeleteMessageConfirmDialog"; -import { getThreadReference } from "@/features/messages/lib/threading"; +import { + getThreadReference, + isThreadReply, +} from "@/features/messages/lib/threading"; +import { hasPersistedHydratedChannel } from "@/features/messages/lib/channelHeadCache"; import { resolveTimelineLoadingLatch, selectTimelineLoadingState, @@ -78,10 +82,13 @@ import { useChannelAgentSessions } from "./useChannelAgentSessions"; import { useMessageProfiles } from "./useMessageProfiles"; import { useChannelPanelHistoryState } from "./useChannelPanelHistoryState"; import { useChannelProfilePanel } from "./useChannelProfilePanel"; +import { useChannelTargetReset } from "./useChannelTargetReset"; import { useChannelRouteTarget } from "./useChannelRouteTarget"; import { useChannelOpenReadState } from "./useChannelOpenReadState"; import { useChannelUnreadState } from "./useChannelUnreadState"; import type { ChannelScreenProps } from "./ChannelScreen.types"; +import { GuardedChannelPane } from "./GuardedChannelPane"; +import { useNavigationGuard } from "./useNavigationGuard"; const EMPTY_RELAY_EVENTS: RelayEvent[] = []; export function ChannelScreen({ activeChannel, @@ -95,6 +102,7 @@ export function ChannelScreen({ targetMessageEvents, targetMessageId, }: ChannelScreenProps) { + const queryClient = useQueryClient(); const { goHome } = useAppNavigation(); const { activeCommunity } = useCommunities(); const { @@ -165,11 +173,15 @@ export function ChannelScreen({ const activeChannelId = activeChannel?.id ?? null; const isHuddleTranscript = useIsHuddleTranscript(activeChannelId); const relaySelfPubkey = useRelaySelfQuery(activeChannel !== null).data; + const requireThreadEditResolutionRef = React.useRef<() => boolean>( + () => true, + ); const effectiveOpenThreadHeadId = useHuddleThreadIsolation({ closeThread: setOpenThreadHeadId, isHuddleTranscript, openThreadHeadId, optimisticOpenThreadHeadId, + requireThreadEditResolutionRef, }); const isNotifiedForEffectiveThread = effectiveOpenThreadHeadId != null @@ -242,7 +254,12 @@ export function ChannelScreen({ const deleteMessageMutation = useDeleteMessageMutation(activeChannel); const editMessageMutation = useEditMessageMutation(activeChannel); const joinChannelMutation = useJoinChannelMutation(activeChannelId); - const { resolvedMessages, threadSummaries } = useHuddleChannelMessages({ + const { + resolvedMessages, + threadSummaries, + threadRepliesError: huddleThreadRepliesError, + onRetryThreadReplies: onRetryHuddleThreadReplies, + } = useHuddleChannelMessages({ activeChannel, isHuddleTranscript, messages: messagesQuery.data ?? EMPTY_RELAY_EVENTS, @@ -459,8 +476,10 @@ export function ChannelScreen({ }); const editTargetMessage = React.useMemo( () => - timelineMessages.find((message) => message.id === editTargetId) ?? null, - [editTargetId, timelineMessages], + timelineMessages.find((message) => message.id === editTargetId) ?? + threadPanelData.messages.find((message) => message.id === editTargetId) ?? + null, + [editTargetId, threadPanelData.messages, timelineMessages], ); const [emptyDeleteId, setEmptyDeleteId] = React.useState(null); const { @@ -472,6 +491,7 @@ export function ChannelScreen({ handleEditSave, handleExpandThreadReplies, handleOpenThread, + requireThreadEditResolution, handleSendMessage, handleSendToChannel, handleSendThreadReply, @@ -481,6 +501,8 @@ export function ChannelScreen({ deleteMessageMutation, editMessageMutation, editTargetId, + editTargetIsThreadReply: + editTargetMessage !== null && isThreadReply(editTargetMessage.tags ?? []), expandedThreadReplyIds, getFirstReplyIdForMessage, getReplyDescendantIdsForMessage, @@ -499,6 +521,7 @@ export function ChannelScreen({ threadReplyTargetId, toggleReactionMutation, }); + requireThreadEditResolutionRef.current = requireThreadEditResolution; const effectiveToggleReaction = React.useMemo( () => activeChannel && !activeChannel.archivedAt && activeChannel.isMember @@ -574,6 +597,7 @@ export function ChannelScreen({ openAgentSessionPubkey, openThreadHeadId: effectiveOpenThreadHeadId, profilePanelPubkey, + requireThreadEditResolution, setChannelManagementOpen, setExpandedThreadReplyIds, setOpenAgentSessionChannelId, @@ -587,6 +611,7 @@ export function ChannelScreen({ useChannelProfilePanel({ closeAgentSession: handleCloseAgentSession, openProfilePanel, + requireThreadEditResolution, setChannelManagementOpen, setExpandedThreadReplyIds, setOpenThreadHeadId, @@ -607,7 +632,12 @@ export function ChannelScreen({ isPlaceholderData: messagesQuery.isPlaceholderData, dataLength: messagesQuery.data?.length ?? null, }, - hasSettledThisChannel, + // A persisted head only counts as hydrated when it has rows to paint + // (channelHeadCache.ts), so this bypass never settles onto an empty + // placeholder while the authoritative refresh is still in flight. + hasSettledThisChannel || + (activeChannelId !== null && + hasPersistedHydratedChannel(queryClient, activeChannelId)), ); const { settledChannelId, isLoading: isTimelineLoading } = resolveTimelineLoadingLatch( @@ -622,28 +652,19 @@ export function ChannelScreen({ timelineMessages, isTimelineLoading, ); - const resetComposerTargets = React.useCallback( - (_channelId: string | null) => { - setExpandedThreadReplyIds(new Set()); - setThreadScrollTargetId(null); - setThreadReplyTargetId(null); - setEditTargetId(null); - }, - [], - ); - const handleThreadScrollTargetResolved = React.useCallback(() => { - setThreadScrollTargetId(null); - }, []); - const handleTargetReached = React.useCallback(() => { - clearMessageRouteTarget({ replace: true }); - }, [clearMessageRouteTarget]); - React.useEffect(() => { - resetComposerTargets(activeChannelId); - }, [activeChannelId, resetComposerTargets]); + useChannelTargetReset({ + activeChannelId, + setEditTargetId, + setExpandedThreadReplyIds, + setThreadReplyTargetId, + setThreadScrollTargetId, + }); + useNavigationGuard(requireThreadEditResolution); const mainTimelineTargetMessageId = useChannelRouteTarget({ activeChannel, activeChannelId, closeAgentSession: handleCloseAgentSession, + requireThreadEditResolution, setEditTargetId, setExpandedThreadReplyIds, setOpenThreadHeadId, @@ -702,6 +723,7 @@ export function ChannelScreen({ enabled: !isSinglePanelView, }); const handleManageChannel = React.useCallback(() => { + if (!requireThreadEditResolution()) return; if (activeChannel?.channelType === "forum") { openGlobalChannelManagement(); return; @@ -721,6 +743,7 @@ export function ChannelScreen({ activeChannel?.channelType, channelManagementOpen, openGlobalChannelManagement, + requireThreadEditResolution, setChannelManagementOpen, setOpenThreadHeadId, handleCloseAgentSession, @@ -831,7 +854,7 @@ export function ChannelScreen({ /> } > - + setThreadScrollTargetId(null) } onThreadPanelResizeStart={handleThreadPanelResizeStart} - onTargetReached={handleTargetReached} + onTargetReached={() => + clearMessageRouteTarget({ replace: true }) + } onToggleReaction={effectiveToggleReaction} openAgentSessionChannelId={openAgentSessionChannelId} openAgentSessionPubkey={openAgentSessionPubkey} @@ -947,6 +974,10 @@ export function ChannelScreen({ threadHeadMessage={displayedThreadHeadMessage} threadMessages={displayedThreadMessages} threadMessagesPending={threadRepliesQuery.isPending} + threadMessagesError={threadRepliesQuery.isError} + onRetryThreadReplies={() => { + void threadRepliesQuery.refetch(); + }} threadPanelWidthPx={threadPanelWidthPx} threadTypingPubkeys={threadTypingPubkeys} threadReplyTargetMessage={displayedThreadReplyTargetMessage} diff --git a/desktop/src/features/channels/ui/FocusThreadDrawer.tsx b/desktop/src/features/channels/ui/FocusThreadDrawer.tsx index 1aaad0e609..410f2d8672 100644 --- a/desktop/src/features/channels/ui/FocusThreadDrawer.tsx +++ b/desktop/src/features/channels/ui/FocusThreadDrawer.tsx @@ -11,6 +11,7 @@ import { cn } from "@/shared/lib/cn"; type FocusThreadDrawerProps = { channelName: string; children: React.ReactNode; + hasActiveEdit: boolean; onClose: () => void; }; @@ -139,6 +140,7 @@ const REDUCED_MOTION_TRANSITION = { duration: 0.12, ease: "linear" } as const; export function FocusThreadDrawer({ channelName, children, + hasActiveEdit, onClose, }: FocusThreadDrawerProps) { const prefersReducedMotion = useReducedMotion(); @@ -149,6 +151,14 @@ export function FocusThreadDrawer({ React.useEffect(() => { function handleEscape(event: KeyboardEvent) { if (event.key !== "Escape") return; + const target = event.target; + if ( + hasActiveEdit && + target instanceof Node && + drawerRef.current?.contains(target) + ) { + return; + } event.preventDefault(); event.stopImmediatePropagation(); onClose(); @@ -158,7 +168,7 @@ export function FocusThreadDrawer({ return () => { window.removeEventListener("keydown", handleEscape, { capture: true }); }; - }, [onClose]); + }, [hasActiveEdit, onClose]); React.useLayoutEffect(() => { previousFocusRef.current = diff --git a/desktop/src/features/channels/ui/GuardedChannelPane.tsx b/desktop/src/features/channels/ui/GuardedChannelPane.tsx new file mode 100644 index 0000000000..2e9455a1e5 --- /dev/null +++ b/desktop/src/features/channels/ui/GuardedChannelPane.tsx @@ -0,0 +1,9 @@ +import type * as React from "react"; + +import { ChannelPane } from "./ChannelScreenLazyViews"; + +export function GuardedChannelPane( + props: React.ComponentProps, +) { + return ; +} diff --git a/desktop/src/features/channels/ui/MembersSidebar.tsx b/desktop/src/features/channels/ui/MembersSidebar.tsx index 70c7bf10a8..562f890c0f 100644 --- a/desktop/src/features/channels/ui/MembersSidebar.tsx +++ b/desktop/src/features/channels/ui/MembersSidebar.tsx @@ -70,6 +70,7 @@ import { useMembersSidebarActions } from "./useMembersSidebarActions"; import { useMembersSidebarModeration } from "./useMembersSidebarModeration"; const MEMBER_ADD_RESULT_LIMIT = 50; const MEMBER_SEARCH_MIN_QUERY_LENGTH = 2; +const MEMBER_ROW_ESTIMATE_PX = 60; type AddMemberSearchCandidate = UserSearchResult & { isManagedAgent?: boolean; isMember?: boolean; @@ -141,9 +142,6 @@ export function MembersSidebar({ relayUrl, }: MembersSidebarProps) { const channelId = channel?.id ?? null; - const managedAgentRuntimesQuery = useManagedAgentRuntimesQuery({ - enabled: open, - }); const queryClient = useQueryClient(); const searchInputRef = React.useRef(null); const [searchQuery, setSearchQuery] = React.useState(""); @@ -470,6 +468,18 @@ export function MembersSidebar({ ), [managedAgentsQuery.data], ); + const hasLocalManagedMember = React.useMemo( + () => + [...bots, ...archived].some( + (member) => + managedAgentByPubkey.get(normalizePubkey(member.pubkey))?.backend + .type === "local", + ), + [archived, bots, managedAgentByPubkey], + ); + const managedAgentRuntimesQuery = useManagedAgentRuntimesQuery({ + enabled: open && Boolean(relayUrl) && hasLocalManagedMember, + }); const controllableManagedBots = React.useMemo( () => bots.flatMap((member) => { @@ -636,57 +646,62 @@ export function MembersSidebar({ ? managedAgentPairAction(managedAgentRuntime) : undefined; return ( -
- { - void changeRoleMutation.mutateAsync({ pubkey: m.pubkey, role }); - }} - onEditRespondTo={memberIsBot ? setEditRespondToAgent : undefined} - onManagedAgentAction={(agent) => { - void handleAgentLifecycleAction(agent, managedAgentRuntime); - }} - onOpenProfile={handleOpenProfile} - onRemoveMember={handleRemoveMember} - onTimeout={onTimeout} - onUnban={onUnban} - onUntimeout={onUntimeout} - onViewActivity={ - onViewActivity - ? (pubkey: string) => { - onOpenChange(false); - onViewActivity(pubkey); - } - : undefined - } - pairAction={pairAction} - presenceStatus={ - memberPresenceQuery.data?.[member.pubkey.toLowerCase()] ?? null - } - profileAvatarUrl={memberProfile?.avatarUrl ?? null} - showOtherSetupMarker={showOtherSetupMarker} - viewerIsOwner={viewerIsOwner} - /> + { + void changeRoleMutation.mutateAsync({ pubkey: m.pubkey, role }); + }} + onEditRespondTo={memberIsBot ? setEditRespondToAgent : undefined} + onManagedAgentAction={(agent) => { + void handleAgentLifecycleAction(agent, managedAgentRuntime); + }} + onOpenProfile={handleOpenProfile} + onRemoveMember={handleRemoveMember} + onTimeout={onTimeout} + onUnban={onUnban} + onUntimeout={onUntimeout} + onViewActivity={ + onViewActivity + ? (pubkey: string) => { + onOpenChange(false); + onViewActivity(pubkey); + } + : undefined + } + pairAction={pairAction} + presenceStatus={ + memberPresenceQuery.data?.[member.pubkey.toLowerCase()] ?? null + } + profileAvatarUrl={memberProfile?.avatarUrl ?? null} + showOtherSetupMarker={showOtherSetupMarker} + viewerIsOwner={viewerIsOwner} + /> + ); + } + + function renderDeferredMemberCard( + member: ChannelMember, + memberIsBot: boolean, + ) { + return ( +
+ {renderMemberCard(member, memberIsBot)}
); } @@ -771,7 +786,7 @@ export function MembersSidebar({ {normalizedSearchQuery ? (
{filteredActiveMembers.map((member) => - renderMemberCard(member, isBot(member)), + renderDeferredMemberCard(member, isBot(member)), )} {canAddMembers ? ( <> @@ -815,6 +830,7 @@ export function MembersSidebar({ ) : filteredActiveMembers.length > 0 ? ( member.pubkey} items={filteredActiveMembers} renderItem={(member) => @@ -858,7 +874,7 @@ export function MembersSidebar({ data-testid="members-sidebar-archived-list" > {filteredArchivedMembers.map((member) => - renderMemberCard(member, isBot(member)), + renderDeferredMemberCard(member, isBot(member)), )} {filteredArchivedMembers.length === 0 ? (

diff --git a/desktop/src/features/channels/ui/useChannelAgentSessions.ts b/desktop/src/features/channels/ui/useChannelAgentSessions.ts index 20c561e798..8dd22bb94a 100644 --- a/desktop/src/features/channels/ui/useChannelAgentSessions.ts +++ b/desktop/src/features/channels/ui/useChannelAgentSessions.ts @@ -39,6 +39,7 @@ type UseChannelAgentSessionsOptions = { openAgentSessionPubkey: string | null; openThreadHeadId: string | null; profilePanelPubkey?: string | null; + requireThreadEditResolution: () => boolean; setChannelManagementOpen: (open: boolean) => void; setExpandedThreadReplyIds: (value: Set) => void; setOpenAgentSessionChannelId: PanelValueSetter; @@ -173,6 +174,7 @@ export function useChannelAgentSessions({ openAgentSessionPubkey, openThreadHeadId, profilePanelPubkey = null, + requireThreadEditResolution, setChannelManagementOpen, setExpandedThreadReplyIds, setOpenAgentSessionChannelId, @@ -209,6 +211,7 @@ export function useChannelAgentSessions({ const openAgentSession = React.useCallback( (pubkey: string, channelId?: string | null) => { + if (!requireThreadEditResolution()) return; if (!isAgentSessionOpen) { returnTarget.capture( resolveAgentSessionReturnTarget({ @@ -234,6 +237,7 @@ export function useChannelAgentSessions({ isAgentSessionOpen, openThreadHeadId, profilePanelPubkey, + requireThreadEditResolution, returnTarget, setChannelManagementOpen, setExpandedThreadReplyIds, diff --git a/desktop/src/features/channels/ui/useChannelProfilePanel.ts b/desktop/src/features/channels/ui/useChannelProfilePanel.ts index 61e9211480..1a35666478 100644 --- a/desktop/src/features/channels/ui/useChannelProfilePanel.ts +++ b/desktop/src/features/channels/ui/useChannelProfilePanel.ts @@ -7,6 +7,7 @@ import type { ProfilePanelOpenOptions } from "@/shared/context/ProfilePanelConte type UseChannelProfilePanelOptions = { closeAgentSession: () => void; openProfilePanel: (pubkey: string, options?: ProfilePanelOpenOptions) => void; + requireThreadEditResolution: () => boolean; setChannelManagementOpen: (open: boolean) => void; setExpandedThreadReplyIds: (value: Set) => void; setOpenThreadHeadId: (value: string | null) => void; @@ -18,6 +19,7 @@ type UseChannelProfilePanelOptions = { export function useChannelProfilePanel({ closeAgentSession, openProfilePanel, + requireThreadEditResolution, setChannelManagementOpen, setExpandedThreadReplyIds, setOpenThreadHeadId, @@ -30,6 +32,7 @@ export function useChannelProfilePanel({ const handleOpenProfilePanel = React.useCallback( (pubkey: string, options?: ProfilePanelOpenOptions) => { + if (!requireThreadEditResolution()) return; setOpenThreadHeadId(null); setExpandedThreadReplyIds(new Set()); setThreadScrollTargetId(null); @@ -41,6 +44,7 @@ export function useChannelProfilePanel({ [ closeAgentSession, openProfilePanel, + requireThreadEditResolution, setChannelManagementOpen, setExpandedThreadReplyIds, setOpenThreadHeadId, diff --git a/desktop/src/features/channels/ui/useChannelRouteTarget.ts b/desktop/src/features/channels/ui/useChannelRouteTarget.ts index 0dc4b0e4d6..39e8a6688d 100644 --- a/desktop/src/features/channels/ui/useChannelRouteTarget.ts +++ b/desktop/src/features/channels/ui/useChannelRouteTarget.ts @@ -56,6 +56,7 @@ export function useChannelRouteTarget({ activeChannel, activeChannelId, closeAgentSession, + requireThreadEditResolution, setEditTargetId, setExpandedThreadReplyIds, setOpenThreadHeadId, @@ -68,6 +69,7 @@ export function useChannelRouteTarget({ activeChannel: Channel | null; activeChannelId: string | null; closeAgentSession: () => void; + requireThreadEditResolution: () => boolean; setEditTargetId: React.Dispatch>; setExpandedThreadReplyIds: React.Dispatch>>; setOpenThreadHeadId: PanelValueSetter; @@ -115,13 +117,14 @@ export function useChannelRouteTarget({ } if (!targetMessage.parentId) { + if (!requireThreadEditResolution()) { + return; + } closeAgentSession(); - // Root message links should open the reply panel for that root. The - // timeline scroll/highlight target alone is not enough: root links have - // no parent/thread metadata, so the reply-only branch below cannot infer - // a thread head. setProfilePanelPubkey(null, { replace: true }); setEditTargetId(null); + // Root message links open the reply panel. Navigation is refused before + // this route target is accepted when another composer owns a dirty edit. setOpenThreadHeadId(targetMessage.id, { replace: true }); setThreadReplyTargetId(targetMessage.id); setThreadScrollTargetId(null); @@ -141,6 +144,9 @@ export function useChannelRouteTarget({ if (!routeTarget) { return; } + if (!requireThreadEditResolution()) { + return; + } closeAgentSession(); // Replace so the deep-link entry itself carries the opened thread — @@ -156,6 +162,7 @@ export function useChannelRouteTarget({ activeChannel, activeChannelId, closeAgentSession, + requireThreadEditResolution, setEditTargetId, setExpandedThreadReplyIds, setOpenThreadHeadId, diff --git a/desktop/src/features/channels/ui/useChannelTargetReset.ts b/desktop/src/features/channels/ui/useChannelTargetReset.ts new file mode 100644 index 0000000000..83e1343db6 --- /dev/null +++ b/desktop/src/features/channels/ui/useChannelTargetReset.ts @@ -0,0 +1,30 @@ +import * as React from "react"; + +export function useChannelTargetReset({ + activeChannelId, + setEditTargetId, + setExpandedThreadReplyIds, + setThreadReplyTargetId, + setThreadScrollTargetId, +}: { + activeChannelId: string | null; + setEditTargetId: (id: string | null) => void; + setExpandedThreadReplyIds: (ids: Set) => void; + setThreadReplyTargetId: (id: string | null) => void; + setThreadScrollTargetId: (id: string | null) => void; +}) { + React.useEffect(() => { + // The channel identity is intentionally the reset trigger. + void activeChannelId; + setExpandedThreadReplyIds(new Set()); + setThreadScrollTargetId(null); + setThreadReplyTargetId(null); + setEditTargetId(null); + }, [ + activeChannelId, + setEditTargetId, + setExpandedThreadReplyIds, + setThreadReplyTargetId, + setThreadScrollTargetId, + ]); +} diff --git a/desktop/src/features/channels/ui/useHuddleChannelMessages.ts b/desktop/src/features/channels/ui/useHuddleChannelMessages.ts index 2a90971dde..5a3a7c4041 100644 --- a/desktop/src/features/channels/ui/useHuddleChannelMessages.ts +++ b/desktop/src/features/channels/ui/useHuddleChannelMessages.ts @@ -66,5 +66,13 @@ export function useHuddleChannelMessages({ [huddleThreadReplies.events, isHuddleTranscript, resolvedChannelMessages], ); - return { resolvedMessages, threadSummaries }; + return { + resolvedMessages, + threadSummaries, + // A summarized reply subtree failing must not leave the transcript reading + // as complete: surface the aggregate failure so the consumer can show a + // non-destructive retry alert alongside the rows that did load. + threadRepliesError: isHuddleTranscript && huddleThreadReplies.isError, + onRetryThreadReplies: huddleThreadReplies.refetch, + }; } diff --git a/desktop/src/features/channels/ui/useHuddleThreadIsolation.test.mjs b/desktop/src/features/channels/ui/useHuddleThreadIsolation.test.mjs new file mode 100644 index 0000000000..f75bc04b70 --- /dev/null +++ b/desktop/src/features/channels/ui/useHuddleThreadIsolation.test.mjs @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { resolveHuddleOpenThreadHeadId } from "./useHuddleThreadIsolation.ts"; + +test("huddle transcripts synchronously hide URL thread state", () => { + assert.equal( + resolveHuddleOpenThreadHeadId({ + isHuddleTranscript: true, + openThreadHeadId: "url-thread", + optimisticOpenThreadHeadId: undefined, + }), + null, + ); +}); + +test("an optimistic null overrides the URL thread until navigation settles", () => { + assert.equal( + resolveHuddleOpenThreadHeadId({ + isHuddleTranscript: false, + openThreadHeadId: "url-thread", + optimisticOpenThreadHeadId: null, + }), + null, + ); + assert.equal( + resolveHuddleOpenThreadHeadId({ + isHuddleTranscript: false, + openThreadHeadId: "url-thread", + optimisticOpenThreadHeadId: undefined, + }), + "url-thread", + ); +}); diff --git a/desktop/src/features/channels/ui/useHuddleThreadIsolation.ts b/desktop/src/features/channels/ui/useHuddleThreadIsolation.ts index c32c809a88..b794ce87be 100644 --- a/desktop/src/features/channels/ui/useHuddleThreadIsolation.ts +++ b/desktop/src/features/channels/ui/useHuddleThreadIsolation.ts @@ -5,20 +5,43 @@ type HuddleThreadIsolationOptions = { isHuddleTranscript: boolean; openThreadHeadId: string | null; optimisticOpenThreadHeadId: string | null | undefined; + requireThreadEditResolutionRef: React.RefObject<() => boolean>; }; +export function resolveHuddleOpenThreadHeadId({ + isHuddleTranscript, + openThreadHeadId, + optimisticOpenThreadHeadId, +}: Pick< + HuddleThreadIsolationOptions, + "isHuddleTranscript" | "openThreadHeadId" | "optimisticOpenThreadHeadId" +>): string | null { + if (isHuddleTranscript) return null; + return optimisticOpenThreadHeadId === undefined + ? openThreadHeadId + : optimisticOpenThreadHeadId; +} + export function useHuddleThreadIsolation({ closeThread, isHuddleTranscript, openThreadHeadId, optimisticOpenThreadHeadId, + requireThreadEditResolutionRef, }: HuddleThreadIsolationOptions): string | null { React.useEffect(() => { if (!isHuddleTranscript || openThreadHeadId === null) return; + if (!requireThreadEditResolutionRef.current()) return; closeThread(null); - }, [closeThread, isHuddleTranscript, openThreadHeadId]); - if (isHuddleTranscript) return null; - return optimisticOpenThreadHeadId === undefined - ? openThreadHeadId - : optimisticOpenThreadHeadId; + }, [ + closeThread, + isHuddleTranscript, + openThreadHeadId, + requireThreadEditResolutionRef, + ]); + return resolveHuddleOpenThreadHeadId({ + isHuddleTranscript, + openThreadHeadId, + optimisticOpenThreadHeadId, + }); } diff --git a/desktop/src/features/channels/ui/useNavigationGuard.ts b/desktop/src/features/channels/ui/useNavigationGuard.ts new file mode 100644 index 0000000000..bda71513c0 --- /dev/null +++ b/desktop/src/features/channels/ui/useNavigationGuard.ts @@ -0,0 +1,10 @@ +import * as React from "react"; + +import { registerNavigationGuard } from "@/app/navigation/navigationGuard"; + +export function useNavigationGuard(requireThreadEditResolution: () => boolean) { + React.useLayoutEffect( + () => registerNavigationGuard(() => requireThreadEditResolution()), + [requireThreadEditResolution], + ); +} diff --git a/desktop/src/features/channels/useChannelPaneHandlers.ts b/desktop/src/features/channels/useChannelPaneHandlers.ts index f9c57f6656..465a0a6b61 100644 --- a/desktop/src/features/channels/useChannelPaneHandlers.ts +++ b/desktop/src/features/channels/useChannelPaneHandlers.ts @@ -1,4 +1,5 @@ import * as React from "react"; +import { toast } from "sonner"; import type { useDeleteMessageMutation, @@ -24,6 +25,7 @@ export function useChannelPaneHandlers({ deleteMessageMutation, editMessageMutation, editTargetId, + editTargetIsThreadReply, expandedThreadReplyIds, getFirstReplyIdForMessage, getReplyDescendantIdsForMessage, @@ -45,6 +47,7 @@ export function useChannelPaneHandlers({ deleteMessageMutation: ReturnType; editMessageMutation: ReturnType; editTargetId: string | null; + editTargetIsThreadReply: boolean; expandedThreadReplyIds: ReadonlySet; getFirstReplyIdForMessage: (messageId: string) => string | null; getReplyDescendantIdsForMessage: (messageId: string) => string[]; @@ -74,6 +77,8 @@ export function useChannelPaneHandlers({ const editTargetIdRef = React.useRef(editTargetId); editTargetIdRef.current = editTargetId; + const editTargetIsThreadReplyRef = React.useRef(editTargetIsThreadReply); + editTargetIsThreadReplyRef.current = editTargetIsThreadReply; const expandedThreadReplyIdsRef = React.useRef(expandedThreadReplyIds); expandedThreadReplyIdsRef.current = expandedThreadReplyIds; @@ -117,7 +122,16 @@ export function useChannelPaneHandlers({ setThreadReplyTargetId(openThreadHeadIdRef.current); }, [setThreadReplyTargetId]); + const requireThreadEditResolution = React.useCallback(() => { + if (!editTargetIsThreadReplyRef.current) return true; + toast.info("Finish or cancel your edit before leaving the thread."); + return false; + }, []); + const handleCloseThread = React.useCallback(() => { + if (!requireThreadEditResolution()) { + return; + } deferPanelState(() => { onOptimisticOpenThreadHeadIdChange(null); setOpenThreadHeadId(null); @@ -128,6 +142,7 @@ export function useChannelPaneHandlers({ }, [ deferPanelState, onOptimisticOpenThreadHeadIdChange, + requireThreadEditResolution, setExpandedThreadReplyIds, setOpenThreadHeadId, setThreadReplyTargetId, @@ -135,6 +150,8 @@ export function useChannelPaneHandlers({ ]); const handleCancelEdit = React.useCallback(() => { + editTargetIdRef.current = null; + editTargetIsThreadReplyRef.current = false; setEditTargetId(null); }, [setEditTargetId]); @@ -198,6 +215,7 @@ export function useChannelPaneHandlers({ const handleOpenThread = React.useCallback( (message: { id: string }) => { + if (!requireThreadEditResolution()) return; if (openThreadHeadIdRef.current === message.id) { deferPanelState(() => { onOptimisticOpenThreadHeadIdChange(null); @@ -222,6 +240,7 @@ export function useChannelPaneHandlers({ [ deferPanelState, onOptimisticOpenThreadHeadIdChange, + requireThreadEditResolution, setEditTargetId, setExpandedThreadReplyIds, setOpenThreadHeadId, @@ -413,6 +432,7 @@ export function useChannelPaneHandlers({ handleEditSave, handleExpandThreadReplies, handleOpenThread, + requireThreadEditResolution, handleSendMessage, handleSendToChannel, handleSendThreadReply, diff --git a/desktop/src/features/channels/useUnreadChannels.ts b/desktop/src/features/channels/useUnreadChannels.ts index b956b672d0..984d69ff89 100644 --- a/desktop/src/features/channels/useUnreadChannels.ts +++ b/desktop/src/features/channels/useUnreadChannels.ts @@ -784,13 +784,8 @@ export function useUnreadChannels( relayClient, ]); - // Unread = inactive channels, plus any channel manually marked unread this - // session. A manually marked active channel must remain visible as unread - // until the user explicitly marks it read again. - // High-priority unread = DMs or channels with a mention/broadcast newer - // than the read marker. Forced-unread channels are dot tier only (not - // high-priority). Both sets share identical deps and always invalidate - // together, so they are computed in a single memo. + // Derive unread and high-priority projections together so they invalidate + // from the same read-state snapshot. const rawUnread = // biome-ignore lint/correctness/useExhaustiveDependencies: readStateVersion and latestVersion are intentional invalidation signals React.useMemo(() => { @@ -841,7 +836,7 @@ export function useUnreadChannels( if (!isForcedUnread) continue; unread.add(channel.id); topLevelUnread.add(channel.id); - counts.set(channel.id, 1); + if (channel.channelType === "dm") counts.set(channel.id, 1); unreadChannelNotificationCount += 1; continue; } @@ -863,13 +858,17 @@ export function useUnreadChannels( observedEvents, readAtForObservedEvent, ); - counts.set(channel.id, badgeCount); - unreadChannelNotificationCount += + const appBadgeCount = nativeProjection?.appBadgeCount ?? countUnreadAppBadgeObservedEvents( observedEvents, readAtForObservedEvent, ); + counts.set( + channel.id, + channel.channelType === "dm" ? badgeCount : appBadgeCount, + ); + unreadChannelNotificationCount += appBadgeCount; // DM channels: any unread DM is high-priority. if (channel.channelType === "dm") { diff --git a/desktop/src/features/communities/useCommunities.tsx b/desktop/src/features/communities/useCommunities.tsx index e0a1001788..f30353af72 100644 --- a/desktop/src/features/communities/useCommunities.tsx +++ b/desktop/src/features/communities/useCommunities.tsx @@ -19,7 +19,8 @@ import { import { removeSelfProfileCachesForRelay } from "@/features/profile/lib/selfProfileStorage"; import { removeUserLabelCacheForRelay } from "@/features/profile/lib/userLabelStorage"; import { removeChannelSnapshotForRelay } from "@/features/channels/channelSnapshot"; -import { removeMessageSnapshotsForRelay } from "@/features/messages/lib/messageSnapshot"; +import { clearChannelHeadCache } from "@/shared/api/tauriChannelHeadCache"; +import { getIdentity } from "@/shared/api/tauriIdentity"; import { clearSavedCommunitySnapshot } from "@/features/agents/activeAgentTurnsStore"; import { clearCommunityDestinations, @@ -234,7 +235,16 @@ function useCommunitiesInternal(): UseCommunitiesReturn { removeSelfProfileCachesForRelay(removed.relayUrl); removeUserLabelCacheForRelay(removed.relayUrl); removeChannelSnapshotForRelay(removed.relayUrl); - removeMessageSnapshotsForRelay(removed.relayUrl); + void getIdentity() + .then((identity) => + clearChannelHeadCache({ + pubkey: identity.pubkey, + relayUrl: removed.relayUrl, + }), + ) + .catch((error) => { + console.warn("Failed to clear persisted channel heads", error); + }); clearSavedCommunitySnapshot(id); removeCommunityDestination(id); diff --git a/desktop/src/features/communities/useCommunityInit.ts b/desktop/src/features/communities/useCommunityInit.ts index 5493a47b1e..c565ee0f7b 100644 --- a/desktop/src/features/communities/useCommunityInit.ts +++ b/desktop/src/features/communities/useCommunityInit.ts @@ -84,7 +84,12 @@ async function resetCommunityState({ } type CommunityInitResult = - | { isReady: true; needsSetup: false; appliedKey: string } + | { + isReady: true; + needsSetup: false; + appliedKey: string; + identityPubkey: string | null; + } | { isReady: false; needsSetup: true; @@ -342,6 +347,7 @@ export function useCommunityInit( isReady: true, needsSetup: false, appliedKey: communityKey, + identityPubkey, }); } } diff --git a/desktop/src/features/home/ui/InboxDetailPane.tsx b/desktop/src/features/home/ui/InboxDetailPane.tsx index 9192c64952..373ef80f45 100644 --- a/desktop/src/features/home/ui/InboxDetailPane.tsx +++ b/desktop/src/features/home/ui/InboxDetailPane.tsx @@ -461,6 +461,7 @@ function InboxMessageDetailPane({ author: editTarget.authorLabel, body: editTarget.content, id: editTarget.id, + isThreadReply: false, imetaMedia: imetaMediaFromTags(editTarget.tags), ...editMentionState, } diff --git a/desktop/src/features/messages/combineThreadRepliesResults.test.mjs b/desktop/src/features/messages/combineThreadRepliesResults.test.mjs new file mode 100644 index 0000000000..47beb1c7a8 --- /dev/null +++ b/desktop/src/features/messages/combineThreadRepliesResults.test.mjs @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { combineThreadRepliesResults } from "./useThreadReplies.ts"; + +const CHANNEL_A = "a".repeat(64); +const CHANNEL_B = "b".repeat(64); + +function event(id, createdAt) { + return { + id, + pubkey: "c".repeat(64), + kind: 9, + created_at: createdAt, + content: "reply", + tags: [], + sig: "sig", + }; +} + +function ok(data) { + return { + data, + isPending: false, + isError: false, + error: null, + refetch: () => { + throw new Error("a successful subtree must not be refetched"); + }, + }; +} + +function failed(refetch) { + return { + data: undefined, + isPending: false, + isError: true, + error: new Error("subtree load failed"), + refetch, + }; +} + +function pending() { + return { + data: undefined, + isPending: true, + isError: false, + error: null, + refetch: () => {}, + }; +} + +test("aggregates events across roots in chronological order", () => { + const combined = combineThreadRepliesResults([ + ok([event(CHANNEL_A, 200)]), + ok([event(CHANNEL_B, 100)]), + ]); + assert.deepEqual( + combined.events.map((e) => e.created_at), + [100, 200], + ); + assert.equal(combined.isPending, false); + assert.equal(combined.isError, false); + assert.equal(combined.error, null); +}); + +test("a failed subtree surfaces aggregate error and never silently drops", () => { + // The load-bearing contract: one failed root among successful roots must make + // the aggregate report isError so the consumer can surface a failure instead + // of presenting a partial transcript as complete. + const combined = combineThreadRepliesResults([ + ok([event(CHANNEL_A, 100)]), + failed(() => {}), + ]); + assert.equal(combined.isError, true); + assert.ok(combined.error instanceof Error); + // Successful rows still contribute their events (non-destructive). + assert.equal(combined.events.length, 1); +}); + +test("isPending reflects any still-loading root", () => { + const combined = combineThreadRepliesResults([ok([]), pending()]); + assert.equal(combined.isPending, true); +}); + +test("refetch re-runs only the failed subtrees, not the successful ones", () => { + let failedRefetched = 0; + const combined = combineThreadRepliesResults([ + ok([event(CHANNEL_A, 100)]), + failed(() => { + failedRefetched += 1; + }), + ]); + // ok().refetch throws if called, so a partial-success refetch that touched + // every query would throw here; it must only touch the failed one. + combined.refetch(); + assert.equal(failedRefetched, 1); +}); + +test("all-success aggregate reports no error", () => { + const combined = combineThreadRepliesResults([ok([]), ok([])]); + assert.equal(combined.isError, false); + assert.equal(combined.error, null); +}); diff --git a/desktop/src/features/messages/hooks.ts b/desktop/src/features/messages/hooks.ts index 8b457a7adf..d28f292608 100644 --- a/desktop/src/features/messages/hooks.ts +++ b/desktop/src/features/messages/hooks.ts @@ -24,6 +24,12 @@ import { refreshChannelWindowMessages, } from "@/features/messages/lib/projectChannelWindow"; import { reconcileChannelWindowMessages } from "@/features/messages/lib/channelWindowReconciliation"; +import { + channelHeadCacheScope, + channelHeadHydration, + consumeHydratedChannel, +} from "@/features/messages/lib/channelHeadCache"; +import { storeChannelHeadCache } from "@/shared/api/tauriChannelHeadCache"; import { mergeMessages, mergeTimelineCacheMessages, @@ -85,6 +91,18 @@ type MessageQueryContext = { const CHANNEL_TIMELINE_KINDS = new Set(CHANNEL_TIMELINE_CONTENT_KINDS); const CHANNEL_AUX_KINDS = new Set(CHANNEL_AUX_EVENT_KINDS); +export function resolveCachedReplyRootId( + parentEventId: string, + messageCaches: readonly RelayEvent[][], +): string | null { + for (const messages of messageCaches) { + if (messages.some((event) => event.id === parentEventId)) { + return resolveReplyRootId(parentEventId, messages); + } + } + return null; +} + export function createOptimisticMessage( channelId: string, content: string, @@ -257,18 +275,30 @@ export function reconcileFetchedChannelWindow( emptyChannelWindowStore(); const next = replaceNewestChannelWindow(current, page); queryClient.setQueryData(windowKey, next); + const scope = channelHeadCacheScope(queryClient); + if (scope) { + void storeChannelHeadCache(scope, channelId, events).catch((error) => { + console.warn("Failed to persist channel head", channelId, error); + }); + } return reconcileChannelWindowMessages(next, previousMessages); } export function useChannelMessagesQuery(channel: Channel | null) { const queryClient = useQueryClient(); const queryKey = channelMessagesKey(channel?.id ?? "none"); - return useQuery({ enabled: channel !== null && channel.channelType !== "forum", queryKey, queryFn: async ({ signal }) => { if (!channel) throw new Error("No channel selected."); + // Persisted heads seed asynchronously; wait for that seed so a channel + // opened during boot takes the hydrated path instead of racing it with + // a cold relay fetch. + await channelHeadHydration(queryClient); + if (consumeHydratedChannel(queryClient, channel.id)) { + return queryClient.getQueryData(queryKey) ?? []; + } const previousMessages = queryClient.getQueryData(queryKey) ?? []; const events = await getChannelWindowEvents(channel.id); @@ -393,36 +423,45 @@ export function useChannelSubscription(channel: Channel | null) { }); }); + // The live subscription starts at "now", so it cannot close the gap + // between the last page snapshot and subscription establishment. Always + // refresh once subscription setup settles — on success because freshness + // alone is not proof that no relay events landed in that interval, and on + // failure because a hydrated channel has no other authoritative fetch: + // the relay window endpoint may be healthy even when the live socket is + // not, and the reconnect listener above re-syncs when it recovers. + const refreshAfterSubscribe = (outcome: string) => { + if (isDisposed) return; + void refreshNewestWindow().catch((error) => { + if (!isDisposed) { + console.error( + `Failed to refresh channel window after ${outcome}`, + channelId, + error, + ); + } + }); + }; relayClient .subscribeToChannelLive(channelId, (event) => { if (!isDisposed) { appendMessage(event); } }) - .then((dispose) => { - if (isDisposed) { - void dispose(); - return; - } - - cleanup = dispose; - // The live subscription starts at "now", so it cannot close the gap - // between the last page snapshot and subscription establishment. Always - // refresh after the subscription is active; freshness alone is not a - // proof that no relay events landed in that interval. - void refreshNewestWindow().catch((error) => { - if (!isDisposed) { - console.error( - "Failed to refresh channel window after subscribing", - channelId, - error, - ); + .then( + (dispose) => { + if (isDisposed) { + void dispose(); + return; } - }); - }) - .catch((error) => { - console.error("Failed to subscribe to channel", channelId, error); - }); + cleanup = dispose; + refreshAfterSubscribe("subscribing"); + }, + (error) => { + console.error("Failed to subscribe to channel", channelId, error); + refreshAfterSubscribe("subscription failure"); + }, + ); return () => { isDisposed = true; @@ -538,6 +577,17 @@ export function useSendMessageMutation( queryClient.getQueryData( channelMessagesKey(effectiveChannel.id), ) ?? []; + const threadCaches = queryClient + .getQueriesData({ + queryKey: ["thread-replies", effectiveChannel.id], + }) + .flatMap(([, events]) => (events ? [events] : [])); + const suppliedRootEventId = parentEventId + ? resolveCachedReplyRootId(parentEventId, [ + cachedMessages, + ...threadCaches, + ]) + : null; const result = await sendChannelMessage( effectiveChannel.id, content, @@ -549,6 +599,9 @@ export function useSendMessageMutation( mentionTags, linkPreviewTags, sentFromThreadTag, + undefined, + undefined, + suppliedRootEventId, ); // Build tags matching relay-emitted shape: h, author p, mention ps, reply es, imeta, emoji. @@ -559,7 +612,7 @@ export function useSendMessageMutation( effectiveChannel.id, identity.pubkey, parentEventId, - resolveReplyRootId(parentEventId, cachedMessages), + result.rootEventId ?? parentEventId, recipientPubkeys, ) : []; @@ -630,11 +683,17 @@ export function useSendMessageMutation( } const queryKey = channelMessagesKey(effectiveChannel.id); - await queryClient.cancelQueries({ queryKey }); + const windowKey = channelWindowKey(effectiveChannel.id); + // The rendered timeline is projected from the channel-window cache. Cancel + // both reads before snapshotting either cache so an older window response + // cannot replace the optimistic row between onMutate and onSuccess. + await Promise.all([ + queryClient.cancelQueries({ queryKey }), + queryClient.cancelQueries({ queryKey: windowKey }), + ]); const previousMessages = queryClient.getQueryData(queryKey) ?? []; - const windowKey = channelWindowKey(effectiveChannel.id); const previousWindow = queryClient.getQueryData(windowKey); const optimisticMessage = createOptimisticMessage( diff --git a/desktop/src/features/messages/lib/channelHeadCache.test.mjs b/desktop/src/features/messages/lib/channelHeadCache.test.mjs new file mode 100644 index 0000000000..9fc62331f8 --- /dev/null +++ b/desktop/src/features/messages/lib/channelHeadCache.test.mjs @@ -0,0 +1,382 @@ +import assert from "node:assert/strict"; +import { after, afterEach, before, mock, test } from "node:test"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { JSDOM } from "jsdom"; +import React from "react"; +import { + consumeHydratedChannel, + hasPersistedHydratedChannel, + hydrateChannelHeads, +} from "./channelHeadCache.ts"; +import { channelMessagesKey } from "./messageQueryKeys.ts"; +import { + reconcileFetchedChannelWindow, + useChannelMessagesQuery, + useChannelSubscription, +} from "../hooks.ts"; +import { relayClient } from "../../../shared/api/relayClient.ts"; +const dom = new JSDOM("", { + url: "http://localhost", +}); +const channel = { + id: "channel-a", + name: "general", + channelType: "stream", + visibility: "open", + description: "", + topic: null, + purpose: null, + memberCount: 1, + memberPubkeys: [], + lastMessageAt: null, + archivedAt: null, + participants: [], + participantPubkeys: [], + isMember: true, + ttlSeconds: null, + ttlDeadline: null, +}; +let channelWindowCalls = 0; +let channelWindowEvents = []; + +before(() => { + Object.assign(globalThis, { + document: dom.window.document, + HTMLElement: dom.window.HTMLElement, + IS_REACT_ACT_ENVIRONMENT: true, + window: dom.window, + }); +}); + +afterEach(async () => { + const { cleanup } = await import("@testing-library/react"); + cleanup(); +}); + +after(() => dom.window.close()); +const channelId = "channel-a"; +const root = { + id: "a".repeat(64), + pubkey: "b".repeat(64), + created_at: 10, + kind: 40002, + tags: [["h", channelId]], + content: "persisted", + sig: "", +}; +const replacement = { + ...root, + id: "c".repeat(64), + created_at: 11, + content: "relay", +}; +function bounds() { + return { + id: "d".repeat(64), + pubkey: "e".repeat(64), + created_at: 12, + kind: 39006, + tags: [ + ["h", channelId], + ["d", `${channelId}:head`], + ], + content: JSON.stringify({ has_more: false, next_cursor: null }), + sig: "", + }; +} +function install(entries, { loadDelayMs = 0 } = {}) { + channelWindowCalls = 0; + channelWindowEvents = [replacement, bounds()]; + window.localStorage.clear(); + window.__TAURI_INTERNALS__ = { + invoke: async (command) => { + if (command === "channel_head_cache_load") { + if (loadDelayMs > 0) { + await new Promise((resolve) => setTimeout(resolve, loadDelayMs)); + } + return entries; + } + if (command === "get_channel_window") { + channelWindowCalls += 1; + return channelWindowEvents; + } + return null; + }, + }; +} + +async function mountChannelQuery(client) { + const { renderHook, waitFor } = await import("@testing-library/react"); + const view = renderHook(() => useChannelMessagesQuery(channel), { + wrapper: ({ children }) => + React.createElement(QueryClientProvider, { client }, children), + }); + await waitFor(() => assert.equal(view.result.current.isSuccess, true)); + return view; +} +test("mount fetches cold and prefetched channels but consumes hydrated data", async () => { + install([]); + const coldClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const coldView = await mountChannelQuery(coldClient); + assert.equal(channelWindowCalls, 1); + + install([]); + const prefetchedClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + prefetchedClient.setQueryData(channelMessagesKey(channelId), [root], { + updatedAt: 0, + }); + const prefetchedView = await mountChannelQuery(prefetchedClient); + assert.equal(channelWindowCalls, 1); + + install([ + { channelId, events: [root, bounds()], savedAt: 1, lastVisitedAt: 1 }, + ]); + const hydratedClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + await hydrateChannelHeads(hydratedClient, { + pubkey: "f".repeat(64), + relayUrl: "wss://relay", + }); + const hydratedView = await mountChannelQuery(hydratedClient); + assert.equal(channelWindowCalls, 0); + assert.deepEqual(hydratedView.result.current.data, [root]); + + await hydratedClient.invalidateQueries({ + queryKey: channelMessagesKey(channelId), + exact: true, + refetchType: "active", + }); + assert.equal(channelWindowCalls, 1); + assert.deepEqual(hydratedClient.getQueryData(channelMessagesKey(channelId)), [ + replacement, + ]); + hydratedView.unmount(); + coldView.unmount(); + prefetchedView.unmount(); + coldClient.clear(); + prefetchedClient.clear(); + hydratedClient.clear(); +}); + +test("hydrates stale data and consumes its mount gate once", async () => { + install([ + { channelId, events: [root, bounds()], savedAt: 1, lastVisitedAt: 1 }, + ]); + const client = new QueryClient(); + await hydrateChannelHeads(client, { + pubkey: "f".repeat(64), + relayUrl: "wss://relay", + }); + assert.deepEqual(client.getQueryData(channelMessagesKey(channelId)), [root]); + assert.equal( + client.getQueryState(channelMessagesKey(channelId)).dataUpdatedAt, + 0, + ); + assert.equal(consumeHydratedChannel(client, channelId), true); + assert.equal(consumeHydratedChannel(client, channelId), false); +}); +test("authoritative refresh deletes a vanished hydrated row", async () => { + install([ + { channelId, events: [root, bounds()], savedAt: 1, lastVisitedAt: 1 }, + ]); + const client = new QueryClient(); + await hydrateChannelHeads(client, { + pubkey: "f".repeat(64), + relayUrl: "wss://relay", + }); + const next = reconcileFetchedChannelWindow( + client, + channelId, + [replacement, bounds()], + client.getQueryData(channelMessagesKey(channelId)), + new AbortController().signal, + ); + assert.deepEqual( + next.map((e) => e.id), + [replacement.id], + ); +}); +test("drops malformed entries independently", async () => { + install([ + { channelId: "bad", events: [root], savedAt: 1, lastVisitedAt: 2 }, + { channelId, events: [root, bounds()], savedAt: 1, lastVisitedAt: 1 }, + ]); + const client = new QueryClient(); + await hydrateChannelHeads(client, { + pubkey: "f".repeat(64), + relayUrl: "wss://relay", + }); + assert.equal(client.getQueryData(channelMessagesKey("bad")), undefined); + assert.deepEqual(client.getQueryData(channelMessagesKey(channelId)), [root]); +}); + +test("a channel mounted during a slow cache load still takes the hydrated path", async () => { + // Carl/#6572 (1): the app no longer waits for the cache before mounting, so + // the channel query must itself wait for the seed instead of racing it with + // a cold relay fetch. + install( + [{ channelId, events: [root, bounds()], savedAt: 1, lastVisitedAt: 1 }], + { loadDelayMs: 150 }, + ); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + void hydrateChannelHeads(client, { + pubkey: "f".repeat(64), + relayUrl: "wss://relay", + }); + const view = await mountChannelQuery(client); + assert.equal(channelWindowCalls, 0); + assert.deepEqual(view.result.current.data, [root]); + view.unmount(); + client.clear(); +}); +test("a bounds-only persisted head is not hydrated", async () => { + // Carl/#6572 (3): zero rows paint nothing, so the channel must take the + // cold path and hold its skeleton rather than flash the empty-channel intro. + install([{ channelId, events: [bounds()], savedAt: 1, lastVisitedAt: 1 }]); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + await hydrateChannelHeads(client, { + pubkey: "f".repeat(64), + relayUrl: "wss://relay", + }); + assert.equal(client.getQueryData(channelMessagesKey(channelId)), undefined); + assert.equal(hasPersistedHydratedChannel(client, channelId), false); + const view = await mountChannelQuery(client); + assert.equal(channelWindowCalls, 1); + assert.deepEqual(view.result.current.data, [replacement]); + view.unmount(); + client.clear(); +}); + +test("a hydrated channel still revalidates when live subscription setup fails", async () => { + // Carl/#6572 (2): the hydrated path skips get_channel_window on mount, so + // the post-subscribe refresh is its only authoritative fetch. A rejected + // subscribe must trigger it too, or the channel stays stale all session. + install([ + { channelId, events: [root, bounds()], savedAt: 1, lastVisitedAt: 1 }, + ]); + mock.method(relayClient, "subscribeToReconnects", () => () => {}); + mock.method(relayClient, "subscribeToChannelLive", () => + Promise.reject(new Error("socket down")), + ); + const consoleError = mock.method(console, "error", () => {}); + try { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + await hydrateChannelHeads(client, { + pubkey: "f".repeat(64), + relayUrl: "wss://relay", + }); + const { renderHook, waitFor } = await import("@testing-library/react"); + const view = renderHook( + () => { + useChannelSubscription(channel); + return useChannelMessagesQuery(channel); + }, + { + wrapper: ({ children }) => + React.createElement(QueryClientProvider, { client }, children), + }, + ); + await waitFor(() => assert.equal(channelWindowCalls, 1)); + await waitFor(() => + assert.deepEqual(view.result.current.data, [replacement]), + ); + view.unmount(); + client.clear(); + } finally { + mock.restoreAll(); + } + assert.ok( + consoleError.mock.calls.some( + (call) => call.arguments[0] === "Failed to subscribe to channel", + ), + ); +}); + +test("a live subscription that settles before a slow cache load still revalidates", async () => { + // Carl/#6572 re-review: the query is parked on the hydration gate with no + // data yet, so an invalidation issued now dedupes onto that in-flight fetch + // (cancelRefetch only cancels when data exists). The seed then lands and the + // queryFn returns the persisted snapshot — zero authoritative fetches. + install( + [{ channelId, events: [root, bounds()], savedAt: 1, lastVisitedAt: 1 }], + { loadDelayMs: 150 }, + ); + mock.method(relayClient, "subscribeToReconnects", () => () => {}); + mock.method(relayClient, "subscribeToChannelLive", () => + Promise.resolve(async () => {}), + ); + try { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + void hydrateChannelHeads(client, { + pubkey: "f".repeat(64), + relayUrl: "wss://relay", + }); + const { renderHook, waitFor } = await import("@testing-library/react"); + const view = renderHook( + () => { + useChannelSubscription(channel); + return useChannelMessagesQuery(channel); + }, + { + wrapper: ({ children }) => + React.createElement(QueryClientProvider, { client }, children), + }, + ); + await waitFor(() => assert.equal(channelWindowCalls, 1)); + await waitFor(() => + assert.deepEqual(view.result.current.data, [replacement]), + ); + view.unmount(); + client.clear(); + } finally { + mock.restoreAll(); + } +}); + +test("a cold channel with an immediate live subscription fetches the window once", async () => { + // The post-subscribe refresh must still dedupe onto a cold relay fetch that + // is already in flight; only the hydration-parked fetch needs sequencing. + install([]); + mock.method(relayClient, "subscribeToReconnects", () => () => {}); + mock.method(relayClient, "subscribeToChannelLive", () => + Promise.resolve(async () => {}), + ); + try { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const { renderHook, waitFor } = await import("@testing-library/react"); + const view = renderHook( + () => { + useChannelSubscription(channel); + return useChannelMessagesQuery(channel); + }, + { + wrapper: ({ children }) => + React.createElement(QueryClientProvider, { client }, children), + }, + ); + await waitFor(() => + assert.deepEqual(view.result.current.data, [replacement]), + ); + await waitFor(() => assert.equal(view.result.current.isFetching, false)); + assert.equal(channelWindowCalls, 1); + view.unmount(); + client.clear(); + } finally { + mock.restoreAll(); + } +}); diff --git a/desktop/src/features/messages/lib/channelHeadCache.ts b/desktop/src/features/messages/lib/channelHeadCache.ts new file mode 100644 index 0000000000..0927b40b2c --- /dev/null +++ b/desktop/src/features/messages/lib/channelHeadCache.ts @@ -0,0 +1,110 @@ +import type { QueryClient } from "@tanstack/react-query"; +import { + loadChannelHeadCache, + type ChannelHeadScope, +} from "@/shared/api/tauriChannelHeadCache"; +import { channelMessagesKey, channelWindowKey } from "./messageQueryKeys"; +import { parseChannelWindowResponse } from "./channelWindowResponse"; +import { + type ChannelWindowStore, + emptyChannelWindowStore, + replaceNewestChannelWindow, +} from "./channelWindowStore"; +import { reconcileChannelWindowMessages } from "./channelWindowReconciliation"; +import type { RelayEvent } from "@/shared/api/types"; +const hydrations = new WeakMap>(); +const hydratedChannels = new WeakMap>(); +const persistedHydratedChannels = new WeakMap>(); +const cacheScopes = new WeakMap(); +export function isChannelHeadCacheEnabled(): boolean { + if (typeof window === "undefined") return false; + if (import.meta.env?.VITE_BUZZ_CHANNEL_HEAD_CACHE === "off") return false; + return window.localStorage.getItem("buzz-channel-head-cache") !== "off"; +} +export function channelHeadCacheScope( + queryClient: QueryClient, +): ChannelHeadScope | null { + return cacheScopes.get(queryClient) ?? null; +} +/** + * Resolves once persisted heads have been seeded into this client (or + * immediately when no hydration was started). The channel query awaits this so + * it never races the cache load with a cold relay fetch, while the rest of the + * app mounts without waiting on the optional paint cache. + */ +export function channelHeadHydration(queryClient: QueryClient): Promise { + return hydrations.get(queryClient) ?? Promise.resolve(); +} +export function consumeHydratedChannel( + queryClient: QueryClient, + channelId: string, +): boolean { + const channels = hydratedChannels.get(queryClient); + if (!channels?.delete(channelId)) return false; + if (channels.size === 0) hydratedChannels.delete(queryClient); + return true; +} +export function hasPersistedHydratedChannel( + queryClient: QueryClient, + channelId: string, +): boolean { + return persistedHydratedChannels.get(queryClient)?.has(channelId) ?? false; +} +export function hydrateChannelHeads( + queryClient: QueryClient, + scope: ChannelHeadScope, +): Promise { + const hydration = seedChannelHeads(queryClient, scope).catch((error) => { + console.warn("Failed to hydrate persisted channel heads", error); + }); + hydrations.set(queryClient, hydration); + return hydration; +} +async function seedChannelHeads( + queryClient: QueryClient, + scope: ChannelHeadScope, +): Promise { + if (!isChannelHeadCacheEnabled()) return; + cacheScopes.set(queryClient, scope); + const entries = await loadChannelHeadCache(scope, 12); + const hydrated = new Set(); + for (const entry of entries) { + try { + const page = parseChannelWindowResponse( + entry.events, + entry.channelId, + null, + ); + // A bounds-only head has nothing to paint; let it take the cold path so + // the skeleton holds until the relay answers instead of flashing the + // empty-channel intro over rows that are still revalidating. + if (page.rows.length === 0) continue; + const windowKey = channelWindowKey(entry.channelId); + const messagesKey = channelMessagesKey(entry.channelId); + // Merge, don't replace: the app mounts while this load is in flight, so + // the live subscription may already have overlaid events on this store. + const window = replaceNewestChannelWindow( + queryClient.getQueryData(windowKey) ?? + emptyChannelWindowStore(), + page, + ); + const messages = reconcileChannelWindowMessages( + window, + queryClient.getQueryData(messagesKey) ?? [], + ); + queryClient.setQueryData(windowKey, window, { updatedAt: 0 }); + queryClient.setQueryData(messagesKey, messages, { updatedAt: 0 }); + hydrated.add(entry.channelId); + } catch (error) { + console.warn( + "Ignoring invalid persisted channel head", + entry.channelId, + error, + ); + } + } + if (hydrated.size > 0) { + hydratedChannels.set(queryClient, hydrated); + persistedHydratedChannels.set(queryClient, new Set(hydrated)); + } +} diff --git a/desktop/src/features/messages/lib/composerMessageLinkNode.test.mjs b/desktop/src/features/messages/lib/composerMessageLinkNode.test.mjs index 3695275762..57212aeafe 100644 --- a/desktop/src/features/messages/lib/composerMessageLinkNode.test.mjs +++ b/desktop/src/features/messages/lib/composerMessageLinkNode.test.mjs @@ -19,6 +19,7 @@ const CHANNEL_MESSAGE_ID = "a".repeat(64); const CHANNEL_MESSAGE_HREF = `buzz://channel/${CHANNEL_ID}/${CHANNEL_MESSAGE_ID}`; const OWNER = "a".repeat(64); const REPO_HREF = `buzz://repo?owner=${OWNER}&d=buzz-world`; +const PROJECT_HREF = `buzz://project?owner=${OWNER}&d=buzz-world`; const ISSUE_ID = "b".repeat(64); const ISSUE_HREF = `buzz://issue?id=${ISSUE_ID}&owner=${OWNER}&d=buzz-world`; const PR_ID = "c".repeat(64); @@ -188,6 +189,10 @@ test("markdown parsing stops message links before emphasis delimiters", () => { assert.deepEqual(token.meta, { channelName: "general", href: HREF }); }); +function renderedChipLabel(rendered) { + return `${rendered[2][2]}${rendered[3]}`; +} + test("composer node uses the sent-message chip presentation", () => { const node = { attrs: { channelName: "general", href: HREF }, @@ -209,7 +214,44 @@ test("composer node uses the sent-message chip presentation", () => { assert.equal(rendered[1]["data-buzz-link"], ""); // Channel label only — no event hash, so the chip does not change width when // the draft is sent and the rendered chip resolves its metadata. - assert.equal(rendered[2], "general"); + assert.match(rendered[1].class, /wrapping-inline-chip/); + assert.match(rendered[2][1].class, /inline-chip-leading-fragment/); + assert.equal(renderedChipLabel(rendered), "general"); +}); + +test("composer node truncates and preserves grapheme-safe leading fragments", () => { + const render = ComposerMessageLinkNode.configure({ + resolveChannelName: () => undefined, + }).config.renderHTML; + assert.ok(render); + + const longName = `relay-${"observability".repeat(5)}`; + const longRendered = render.call( + { options: { resolveChannelName: () => undefined } }, + { + node: { attrs: { channelName: longName, href: HREF } }, + HTMLAttributes: {}, + }, + ); + assert.equal(renderedChipLabel(longRendered), `${longName.slice(0, 47)}…`); + + for (const [label, expectedLeading] of [ + ["🇺🇸channel", "🇺🇸chan"], + ["e\u0301quipe", "e\u0301quip"], + ["relaytoolsobservabilityconsole-main", "relay"], + [" leading-space", ""], + ]) { + const rendered = render.call( + { options: { resolveChannelName: () => undefined } }, + { + node: { attrs: { channelName: label, href: HREF } }, + HTMLAttributes: {}, + }, + ); + assert.equal(rendered[2][2], expectedLeading); + assert.match(rendered[2][1].class, /inline-chip-with-icon/); + assert.equal(renderedChipLabel(rendered), label); + } }); test("composer node renders channel and entity chip presentations", () => { @@ -227,24 +269,29 @@ test("composer node renders channel and entity chip presentations", () => { const channel = render(CHANNEL_HREF); assert.equal(channel[1]["data-channel-deep-link"], ""); assert.match(channel[1].class, /inline-chip-icon-channel/); - assert.equal(channel[2], "general"); + assert.equal(renderedChipLabel(channel), "general"); const repo = render(REPO_HREF); assert.equal(repo[1]["data-buzz-link-kind"], "repo"); assert.match(repo[1].class, /inline-chip-icon-repo/); - assert.equal(repo[2], "buzz-world"); + assert.equal(renderedChipLabel(repo), "buzz-world"); + + const project = render(PROJECT_HREF); + assert.equal(project[1]["data-buzz-link-kind"], "project"); + assert.match(project[1].class, /inline-chip-icon-project/); + assert.equal(renderedChipLabel(project), "buzz-world"); const issue = render(ISSUE_HREF); assert.equal(issue[1]["data-buzz-link-kind"], "issue"); assert.match(issue[1].class, /inline-chip-icon-issue/); // Repository name only — the rendered chip never widens into the issue // title, so the composer must not widen into the event hash either. - assert.equal(issue[2], "buzz-world"); + assert.equal(renderedChipLabel(issue), "buzz-world"); const pullRequest = render(PR_HREF); assert.equal(pullRequest[1]["data-buzz-link-kind"], "pr"); assert.match(pullRequest[1].class, /inline-chip-icon-pr/); - assert.equal(pullRequest[2], "buzz-world"); + assert.equal(renderedChipLabel(pullRequest), "buzz-world"); }); test("markdown rendering stores identity in attributes, not visible id text", () => { diff --git a/desktop/src/features/messages/lib/composerMessageLinkNode.ts b/desktop/src/features/messages/lib/composerMessageLinkNode.ts index 9587c312ca..59b15c78ba 100644 --- a/desktop/src/features/messages/lib/composerMessageLinkNode.ts +++ b/desktop/src/features/messages/lib/composerMessageLinkNode.ts @@ -12,8 +12,11 @@ import { } from "@/shared/lib/entityLink"; import { inlineChipIconClasses, + inlineChipLeadingEnd, type InlineChipIconKind, MENTION_CHIP_BASE_CLASSES, + truncateInlineChipLabel, + WRAPPING_INLINE_CHIP_CLASSES, } from "@/shared/ui/mentionChip"; import { buildChannelLink, parseChannelLink } from "./channelLink"; import { getMessageLinkLabel } from "./messageLinkLabel"; @@ -285,6 +288,38 @@ function composerLinkPresentation( }; } +function wrappingComposerChipContent( + label: string, + icon: InlineChipIconKind, +): { leading: [string, Record, string]; remainder: string } { + const leadingEnd = inlineChipLeadingEnd(label); + if (!leadingEnd) { + return { + leading: [ + "span", + { + "aria-hidden": "true", + class: `inline-chip-leading-fragment ${inlineChipIconClasses(icon)}`, + }, + "", + ], + remainder: label, + }; + } + + return { + leading: [ + "span", + { + "aria-hidden": "true", + class: `inline-chip-leading-fragment ${inlineChipIconClasses(icon)}`, + }, + label.slice(0, leadingEnd), + ], + remainder: label.slice(leadingEnd), + }; +} + export const ComposerMessageLinkNode = Node.create({ name: COMPOSER_MESSAGE_LINK_NODE_NAME, @@ -328,11 +363,16 @@ export const ComposerMessageLinkNode = String(node.attrs.channelName ?? ""), this.options.resolveChannelName, ); + const visibleLabel = truncateInlineChipLabel(presentation.label); + const content = wrappingComposerChipContent( + visibleLabel, + presentation.icon, + ); return [ "span", mergeAttributes(HTMLAttributes, { "aria-label": presentation.ariaLabel, - class: `${MENTION_CHIP_BASE_CLASSES} ${inlineChipIconClasses(presentation.icon)} cursor-text`, + class: `${MENTION_CHIP_BASE_CLASSES} ${WRAPPING_INLINE_CHIP_CLASSES} ${inlineChipIconClasses(presentation.icon)} cursor-text`, "data-buzz-link": "", "data-channel-name": presentation.channelName, "data-composer-buzz-link": "", @@ -340,7 +380,8 @@ export const ComposerMessageLinkNode = ...presentation.dataAttributes, title: presentation.ariaLabel, }), - presentation.label, + content.leading, + content.remainder, ]; }, diff --git a/desktop/src/features/messages/lib/draftMentionRefs.test.mjs b/desktop/src/features/messages/lib/draftMentionRefs.test.mjs index 87ec604464..ac1ed2d8c3 100644 --- a/desktop/src/features/messages/lib/draftMentionRefs.test.mjs +++ b/desktop/src/features/messages/lib/draftMentionRefs.test.mjs @@ -69,6 +69,37 @@ test("edit target preserves tagged identities while profiles are unavailable", ( assert.deepEqual(target.unresolvedMentionPubkeys, [ALICE, BOB]); }); +test("edit target records semantic thread ownership", () => { + const root = buildMessageComposerEditTarget( + message("Root", [["h", "channel-id"]]), + undefined, + () => false, + ); + const reply = buildMessageComposerEditTarget( + message("Reply", [ + ["h", "channel-id"], + ["e", "root-id", "", "root"], + ["e", "root-id", "", "reply"], + ]), + undefined, + () => false, + ); + + const broadcastReply = buildMessageComposerEditTarget( + message("Broadcast reply", [ + ["h", "channel-id"], + ["e", "root-id", "", "reply"], + ["broadcast", "1"], + ]), + undefined, + () => false, + ); + + assert.equal(root.isThreadReply, false); + assert.equal(reply.isThreadReply, true); + assert.equal(broadcastReply.isThreadReply, false); +}); + test("edit target separates resolved refs from identities missing profiles", () => { const target = buildMessageComposerEditTarget( message("Please review this, @Alice and @Bob.", [ diff --git a/desktop/src/features/messages/lib/draftMentionRefs.ts b/desktop/src/features/messages/lib/draftMentionRefs.ts index 65c7a68fec..7aebf86b2f 100644 --- a/desktop/src/features/messages/lib/draftMentionRefs.ts +++ b/desktop/src/features/messages/lib/draftMentionRefs.ts @@ -1,5 +1,6 @@ import { hasMention } from "@/features/messages/lib/hasMention"; import { imetaMediaFromTags } from "@/features/messages/lib/imetaMediaMarkdown"; +import { isThreadReply } from "@/features/messages/lib/threading"; import type { DraftMentionRef } from "@/features/messages/lib/useDrafts"; import type { TimelineMessage } from "@/features/messages/types"; import type { MessageComposerEditTarget } from "@/features/messages/ui/MessageComposer.types"; @@ -95,6 +96,7 @@ export function buildMessageComposerEditTarget( author: message.author, body: message.body, id: message.id, + isThreadReply: isThreadReply(message.tags ?? []), imetaMedia: imetaMediaFromTags(message.tags), ...mentionState, }; diff --git a/desktop/src/features/messages/lib/messageSnapshot.test.mjs b/desktop/src/features/messages/lib/messageSnapshot.test.mjs deleted file mode 100644 index a188f51da0..0000000000 --- a/desktop/src/features/messages/lib/messageSnapshot.test.mjs +++ /dev/null @@ -1,199 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import { - mergeHistoryOverSnapshot, - messageSnapshotKey, - readMessageSnapshot, - removeMessageSnapshotsForRelay, - writeMessageSnapshot, -} from "./messageSnapshot.ts"; - -if (typeof globalThis.window === "undefined") { - const storage = new Map(); - globalThis.window = { - localStorage: { - getItem: (key) => storage.get(key) ?? null, - setItem: (key, value) => storage.set(key, value), - removeItem: (key) => storage.delete(key), - key: (index) => [...storage.keys()][index] ?? null, - get length() { - return storage.size; - }, - }, - }; -} - -function makeEvent(overrides = {}) { - return { - id: `event-${Math.random().toString(36).slice(2)}`, - pubkey: "pubkey-1", - created_at: 1_700_000_000, - kind: 9, - tags: [["h", "chan-1"]], - content: "hello", - sig: "sig", - ...overrides, - }; -} - -const RELAY = "wss://relay.example.com"; - -function clearRelay(relayUrl = RELAY) { - removeMessageSnapshotsForRelay(relayUrl); -} - -test("messageSnapshotKey: normalizes trailing slash and case", () => { - assert.equal( - messageSnapshotKey("WSS://Relay.Example.com/", "chan-1"), - messageSnapshotKey("wss://relay.example.com", "chan-1"), - ); -}); - -test("read after write returns the persisted events", () => { - clearRelay(); - const events = [makeEvent({ id: "a" }), makeEvent({ id: "b" })]; - writeMessageSnapshot(RELAY, "chan-1", events); - assert.deepEqual(readMessageSnapshot(RELAY, "chan-1"), events); -}); - -test("read for an unknown channel returns null", () => { - clearRelay(); - assert.equal(readMessageSnapshot(RELAY, "chan-never"), null); -}); - -test("read returns null for malformed JSON", () => { - window.localStorage.setItem( - messageSnapshotKey(RELAY, "chan-bad"), - "not-json{{{", - ); - assert.equal(readMessageSnapshot(RELAY, "chan-bad"), null); -}); - -test("read returns null for a wrong-version payload", () => { - window.localStorage.setItem( - messageSnapshotKey(RELAY, "chan-v2"), - JSON.stringify({ version: 2, updatedAt: 1, events: [makeEvent()] }), - ); - assert.equal(readMessageSnapshot(RELAY, "chan-v2"), null); -}); - -test("pending optimistic events are not persisted", () => { - clearRelay(); - const settled = makeEvent({ id: "settled" }); - writeMessageSnapshot(RELAY, "chan-1", [ - settled, - makeEvent({ id: "optimistic", pending: true }), - ]); - assert.deepEqual(readMessageSnapshot(RELAY, "chan-1"), [settled]); -}); - -test("write with only pending events persists nothing", () => { - clearRelay(); - writeMessageSnapshot(RELAY, "chan-1", [makeEvent({ pending: true })]); - assert.equal(readMessageSnapshot(RELAY, "chan-1"), null); -}); - -test("snapshot keeps only the newest slice of a long timeline", () => { - clearRelay(); - const events = Array.from({ length: 200 }, (_, i) => - makeEvent({ id: `event-${i}`, created_at: 1_700_000_000 + i }), - ); - writeMessageSnapshot(RELAY, "chan-1", events); - const persisted = readMessageSnapshot(RELAY, "chan-1"); - assert.equal(persisted.length, 80); - assert.equal(persisted[persisted.length - 1].id, "event-199"); - assert.equal(persisted[0].id, "event-120"); -}); - -test("per-relay channel cap evicts the least recently written snapshot", () => { - clearRelay(); - for (let i = 0; i < 21; i++) { - writeMessageSnapshot(RELAY, `chan-${i}`, [makeEvent({ id: `e-${i}` })]); - } - // chan-0 was written first (oldest updatedAt tie broken by insertion) — - // with 21 channels, at least one of the earliest must be evicted and the - // newest retained. - assert.notEqual(readMessageSnapshot(RELAY, "chan-20"), null); - const retained = Array.from({ length: 21 }, (_, i) => - readMessageSnapshot(RELAY, `chan-${i}`), - ).filter((snapshot) => snapshot !== null); - assert.equal(retained.length, 20); -}); - -test("remove clears every snapshot for that relay only", () => { - clearRelay(); - clearRelay("wss://other.example.com"); - writeMessageSnapshot(RELAY, "chan-1", [makeEvent({ id: "keep-other" })]); - writeMessageSnapshot("wss://other.example.com", "chan-1", [ - makeEvent({ id: "other" }), - ]); - removeMessageSnapshotsForRelay(RELAY); - assert.equal(readMessageSnapshot(RELAY, "chan-1"), null); - assert.notEqual( - readMessageSnapshot("wss://other.example.com", "chan-1"), - null, - ); -}); - -test("write is tolerant of storage failures", () => { - const original = window.localStorage.setItem; - window.localStorage.setItem = () => { - throw new Error("quota exceeded"); - }; - try { - assert.doesNotThrow(() => - writeMessageSnapshot(RELAY, "chan-1", [makeEvent()]), - ); - } finally { - window.localStorage.setItem = original; - } -}); - -test("cold snapshot load: merge keeps snapshot-only rows and widens aux backfill to them", () => { - const snapshotOnly = makeEvent({ id: "ghost", created_at: 1_700_000_000 }); - const fresh = makeEvent({ id: "fresh", created_at: 1_700_000_100 }); - const { merged, auxBackfillWindow } = mergeHistoryOverSnapshot({ - cached: undefined, - snapshot: [snapshotOnly], - history: [fresh], - }); - assert.deepEqual( - merged.map((event) => event.id), - ["ghost", "fresh"], - ); - assert.ok(auxBackfillWindow.some((event) => event.id === "ghost")); - assert.ok(auxBackfillWindow.some((event) => event.id === "fresh")); -}); - -test("warm load: aux backfill stays scoped to the fresh window", () => { - const cached = makeEvent({ id: "cached", created_at: 1_700_000_000 }); - const fresh = makeEvent({ id: "fresh", created_at: 1_700_000_100 }); - const { merged, auxBackfillWindow } = mergeHistoryOverSnapshot({ - cached: [cached], - snapshot: [makeEvent({ id: "stale-snapshot" })], - history: [fresh], - }); - assert.ok(merged.some((event) => event.id === "cached")); - assert.deepEqual( - auxBackfillWindow.map((event) => event.id), - ["fresh"], - ); -}); - -test("cold load without a snapshot backfills the fresh window only", () => { - const fresh = makeEvent({ id: "fresh" }); - const { merged, auxBackfillWindow } = mergeHistoryOverSnapshot({ - cached: undefined, - snapshot: null, - history: [fresh], - }); - assert.deepEqual( - merged.map((event) => event.id), - ["fresh"], - ); - assert.deepEqual( - auxBackfillWindow.map((event) => event.id), - ["fresh"], - ); -}); diff --git a/desktop/src/features/messages/lib/messageSnapshot.ts b/desktop/src/features/messages/lib/messageSnapshot.ts deleted file mode 100644 index d4a183c2ff..0000000000 --- a/desktop/src/features/messages/lib/messageSnapshot.ts +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Per-channel persisted message snapshots. - * - * A channel revisited after its React-Query cache entry is gone (app restart, - * gcTime expiry, community remount) goes fully cold and holds a skeleton for a - * relay round trip. This module persists the newest slice of each channel's - * timeline so a revisit can paint instantly from the snapshot while the - * history fetch revalidates behind it — the same stale-then-revalidate pattern - * the sidebar's channelSnapshot uses for the channel list. - * - * Keyed per relay URL + channel id so one relay's messages never bleed into - * another. Bounded two ways: only the newest MAX_EVENTS_PER_SNAPSHOT events - * per channel, and only the MAX_CHANNELS_PER_RELAY most recently written - * channels per relay (older ones are evicted LRU on write). - */ - -import { mergeTimelineHistoryMessages } from "@/features/messages/lib/messageQueryKeys"; -import { normalizeRelayUrl } from "@/features/profile/lib/selfProfileStorage"; -import type { RelayEvent } from "@/shared/api/types"; -import { setLocalStorageItemWithRecovery } from "@/shared/lib/localStorageQuota"; - -const STORAGE_KEY_PREFIX = "buzz-channel-messages.v1"; - -// Newest events kept per channel. The trailing slice of the sorted timeline -// cache, so recent auxiliary events (reactions/edits) ride along with the -// content rows they decorate. -const MAX_EVENTS_PER_SNAPSHOT = 80; - -const MAX_CHANNELS_PER_RELAY = 20; - -export function messageSnapshotKey(relayUrl: string, channelId: string) { - return `${STORAGE_KEY_PREFIX}:${normalizeRelayUrl(relayUrl)}:${channelId}`; -} - -type SnapshotPayload = { - version: 1; - updatedAt: number; - events: RelayEvent[]; -}; - -function parseSnapshotPayload(json: unknown): SnapshotPayload | null { - if (typeof json !== "object" || json === null) return null; - const obj = json as Record; - if (obj.version !== 1 || !Array.isArray(obj.events)) return null; - const updatedAt = - typeof obj.updatedAt === "number" && Number.isFinite(obj.updatedAt) - ? obj.updatedAt - : 0; - return { version: 1, updatedAt, events: obj.events as RelayEvent[] }; -} - -/** - * Reads the persisted message snapshot for a channel, or null when absent or - * malformed. - */ -export function readMessageSnapshot( - relayUrl: string, - channelId: string, -): RelayEvent[] | null { - try { - const raw = window.localStorage.getItem( - messageSnapshotKey(relayUrl, channelId), - ); - if (!raw) return null; - const parsed = parseSnapshotPayload(JSON.parse(raw)); - if (!parsed || parsed.events.length === 0) return null; - return parsed.events; - } catch { - return null; - } -} - -function relayPrefix(relayUrl: string) { - return `${STORAGE_KEY_PREFIX}:${normalizeRelayUrl(relayUrl)}:`; -} - -function collectKeysWithPrefix(prefix: string): string[] { - const keys: string[] = []; - for (let i = 0; i < window.localStorage.length; i++) { - const key = window.localStorage.key(i); - if (key?.startsWith(prefix)) { - keys.push(key); - } - } - return keys; -} - -function evictOldestSnapshots(prefix: string, keepingKey: string) { - const others = collectKeysWithPrefix(prefix).filter( - (key) => key !== keepingKey, - ); - if (others.length < MAX_CHANNELS_PER_RELAY) { - return; - } - - const byAge = others - .map((key) => { - let updatedAt = 0; - try { - const parsed = parseSnapshotPayload( - JSON.parse(window.localStorage.getItem(key) ?? ""), - ); - updatedAt = parsed?.updatedAt ?? 0; - } catch { - // Malformed entries sort oldest and get evicted first. - } - return { key, updatedAt }; - }) - .sort((a, b) => a.updatedAt - b.updatedAt); - - for (const { key } of byAge.slice( - 0, - others.length - (MAX_CHANNELS_PER_RELAY - 1), - )) { - window.localStorage.removeItem(key); - } -} - -/** - * Persists the newest slice of a channel's timeline. Pending optimistic events - * are dropped (they have no relay identity to revalidate against). Skips the - * write when unchanged so live-append churn does not re-serialize an identical - * snapshot. Non-fatal on storage failure (e.g. quota exceeded). - */ -export function writeMessageSnapshot( - relayUrl: string, - channelId: string, - events: RelayEvent[], -): void { - try { - const persistable = events - .filter((event) => !event.pending) - .slice(-MAX_EVENTS_PER_SNAPSHOT); - if (persistable.length === 0) { - return; - } - - const key = messageSnapshotKey(relayUrl, channelId); - const previous = window.localStorage.getItem(key); - if (previous) { - const parsed = parseSnapshotPayload(JSON.parse(previous)); - if ( - parsed && - JSON.stringify(parsed.events) === JSON.stringify(persistable) - ) { - return; - } - } - - evictOldestSnapshots(relayPrefix(relayUrl), key); - setLocalStorageItemWithRecovery( - key, - JSON.stringify({ - version: 1, - updatedAt: Date.now(), - events: persistable, - } satisfies SnapshotPayload), - ); - } catch { - // Storage access failures are non-fatal. - } -} - -/** - * Merge a fresh history window over the in-memory cache — or, when cold, over - * the persisted snapshot — and pick the window aux backfill must cover. - * - * The snapshot can hold events older than the fetch window; dropping them on - * settle would visibly shrink an already-painted timeline, so the merge keeps - * them. But a kept snapshot row deleted/edited while the app was closed never - * reappears in any history fetch (the relay soft-deletes), so its tombstone or - * edit is only reachable by `#e` over that row's id — cold snapshot loads must - * therefore backfill over the merged timeline, not just the fresh window. - * Otherwise the ghost paints, and the post-settle snapshot rewrite persists it - * forever. - */ -export function mergeHistoryOverSnapshot(input: { - cached: RelayEvent[] | undefined; - snapshot: RelayEvent[] | null; - history: RelayEvent[]; -}): { merged: RelayEvent[]; auxBackfillWindow: RelayEvent[] } { - const usedSnapshot = !input.cached && input.snapshot !== null; - const merged = mergeTimelineHistoryMessages( - input.cached ?? input.snapshot ?? [], - input.history, - ); - return { merged, auxBackfillWindow: usedSnapshot ? merged : input.history }; -} - -/** - * Removes every channel message snapshot for a relay. Called when a community - * is removed. - */ -export function removeMessageSnapshotsForRelay(relayUrl: string): void { - try { - for (const key of collectKeysWithPrefix(relayPrefix(relayUrl))) { - window.localStorage.removeItem(key); - } - } catch { - // Storage access failures are non-fatal. - } -} diff --git a/desktop/src/features/messages/lib/projectChannelWindow.test.mjs b/desktop/src/features/messages/lib/projectChannelWindow.test.mjs index 14ec110add..618f3fc991 100644 --- a/desktop/src/features/messages/lib/projectChannelWindow.test.mjs +++ b/desktop/src/features/messages/lib/projectChannelWindow.test.mjs @@ -363,3 +363,56 @@ test("test_pageless_live_projection_preserves_cached_timeline", () => { assert.deepEqual(contents(harness), ["initial", "live"]); assert.equal(harness.client.getQueryData(harness.messagesKey)[0], cached[0]); }); + +test("test_concurrent_refreshes_after_seeded_snapshot_share_one_authoritative_fetch", async () => { + // Subscribe settlement and a reconnect can both call the helper while the + // channel query is still parked on its hydration-seeded snapshot. Both wake + // on the same promise; the second invalidation must join the first + // authoritative fetch, not cancel and replace it (Max/Wren, #6572 review). + const harness = createHarness(); + const seeded = event("seeded", 100); + harness.client.setQueryData(harness.messagesKey, [seeded], { updatedAt: 0 }); + const requests = []; + const observer = new QueryObserver(harness.client, { + queryKey: harness.messagesKey, + queryFn: async ({ signal }) => { + const previousMessages = harness.client.getQueryData(harness.messagesKey); + let resolveFetch; + const fetch = new Promise((resolve) => { + resolveFetch = resolve; + }); + requests.push({ resolveFetch, signal }); + const events = await fetch; + return reconcileFetchedChannelWindow( + harness.client, + harness.channelId, + events, + previousMessages, + signal, + ); + }, + }); + const unsubscribe = observer.subscribe(() => {}); + try { + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(requests.length, 1); + const first = refreshChannelWindowMessages( + harness.client, + harness.channelId, + ); + const second = refreshChannelWindowMessages( + harness.client, + harness.channelId, + ); + requests[0].resolveFetch(wirePage([seeded])); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(requests.length, 2); + requests[1].resolveFetch(wirePage([event("gap", 110), seeded])); + await Promise.all([first, second]); + assert.equal(requests.length, 2); + assert.equal(requests[1].signal.aborted, false); + assert.deepEqual(contents(harness), ["seeded", "gap"]); + } finally { + unsubscribe(); + } +}); diff --git a/desktop/src/features/messages/lib/projectChannelWindow.ts b/desktop/src/features/messages/lib/projectChannelWindow.ts index 81ef3de42d..b16187ce18 100644 --- a/desktop/src/features/messages/lib/projectChannelWindow.ts +++ b/desktop/src/features/messages/lib/projectChannelWindow.ts @@ -7,6 +7,7 @@ import { type ChannelWindowStore, } from "./channelWindowStore"; import { reconcileChannelWindowMessages } from "./channelWindowReconciliation"; +import { channelHeadHydration } from "./channelHeadCache"; /** Keep the rendered timeline cache aligned with its authoritative window. */ export function projectChannelWindowMessages( @@ -26,10 +27,27 @@ export async function refreshChannelWindowMessages( queryClient: QueryClient, channelId: string, ) { - await queryClient.invalidateQueries({ - queryKey: channelMessagesKey(channelId), - exact: true, - refetchType: "active", - }); + const queryKey = channelMessagesKey(channelId); + // Sequence behind persisted-head hydration. While the channel query is parked + // on that gate it has no data, so TanStack would dedupe this invalidation + // onto it — and that fetch returns the seeded snapshot, never asking the + // relay. A seeded query is recognisable by data at `dataUpdatedAt` 0; let its + // snapshot fetch settle (consuming the mount gate) before invalidating, so + // the refetch is a distinct authoritative window fetch. Concurrent callers + // (subscribe settlement + reconnect) wake on the same promise, so the seeded + // branch must join an authoritative fetch already in flight rather than + // cancel and replace it. Cold and warm channels carry no such marker and + // dedupe/cancel exactly as before. + await channelHeadHydration(queryClient); + const query = queryClient.getQueryCache().find({ queryKey, exact: true }); + const seeded = + query?.state.data !== undefined && query.state.dataUpdatedAt === 0; + if (seeded) { + await query.promise?.catch(() => {}); + } + await queryClient.invalidateQueries( + { queryKey, exact: true, refetchType: "active" }, + { cancelRefetch: !seeded }, + ); projectChannelWindowMessages(queryClient, channelId); } diff --git a/desktop/src/features/messages/lib/sendChannelBinding.test.mjs b/desktop/src/features/messages/lib/sendChannelBinding.test.mjs index 421799d373..bfe66afcff 100644 --- a/desktop/src/features/messages/lib/sendChannelBinding.test.mjs +++ b/desktop/src/features/messages/lib/sendChannelBinding.test.mjs @@ -24,6 +24,7 @@ import test from "node:test"; import { createOptimisticMessage, + resolveCachedReplyRootId, resolveEffectiveChannel, resolveSendChannel, resolveThreadReplyTarget, @@ -322,3 +323,23 @@ test("resolveThreadReplyTarget_nullContext_noLiveRefs_returnsNull", () => { assert.strictEqual(result, null); }); + +test("resolveCachedReplyRootId sends only roots proven by a cached parent", () => { + const rootId = "1".repeat(64); + const parentId = "2".repeat(64); + const parent = { + id: parentId, + pubkey: IDENTITY.pubkey, + kind: 9, + created_at: 1, + content: "parent", + tags: [ + ["e", rootId, "", "root"], + ["e", rootId, "", "reply"], + ], + sig: "", + }; + + assert.equal(resolveCachedReplyRootId(parentId, [[], [parent]]), rootId); + assert.equal(resolveCachedReplyRootId(parentId, [[], []]), null); +}); diff --git a/desktop/src/features/messages/lib/threadPanel.ts b/desktop/src/features/messages/lib/threadPanel.ts index ebc1b35ae7..6dc1190910 100644 --- a/desktop/src/features/messages/lib/threadPanel.ts +++ b/desktop/src/features/messages/lib/threadPanel.ts @@ -542,3 +542,59 @@ export function buildThreadPanelData( expandedReplyIds, ); } + +function hasLaterVisibleSibling( + entries: readonly MainTimelineEntry[], + entryIndex: number, +): boolean { + const depth = entries[entryIndex]?.message.depth; + if (depth == null) { + return false; + } + + for (let index = entryIndex + 1; index < entries.length; index += 1) { + const nextDepth = entries[index].message.depth; + if (nextDepth <= depth) { + return nextDepth === depth; + } + } + + return false; +} + +/** + * Depths at which a vertical thread-branch guide should continue past `message` + * because an ancestor on its path still has a later visible sibling. Pure so + * the branch-guide geometry is unit-tested without the panel. + */ +export function getActiveContinuationDepths({ + ancestors, + entries, + index, + message, +}: { + ancestors: readonly { index: number; message: TimelineMessage }[]; + entries: readonly MainTimelineEntry[]; + index: number; + message: TimelineMessage; +}): number[] { + const depths: number[] = []; + + for (const ancestor of ancestors) { + if (ancestor.message.depth === 0) { + continue; + } + + const childDepth = ancestor.message.depth + 1; + const pathChild = + message.depth === childDepth + ? { index, message } + : ancestors.find((candidate) => candidate.message.depth === childDepth); + + if (pathChild && hasLaterVisibleSibling(entries, pathChild.index)) { + depths.push(ancestor.message.depth); + } + } + + return depths; +} diff --git a/desktop/src/features/messages/lib/threadReplyHighlight.test.mjs b/desktop/src/features/messages/lib/threadReplyHighlight.test.mjs new file mode 100644 index 0000000000..bad72b3339 --- /dev/null +++ b/desktop/src/features/messages/lib/threadReplyHighlight.test.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { selectThreadRowHighlight } from "./threadReplyHighlight.ts"; + +// The hovered branch spans rows in the half-open range (startIndex, endIndex]. +const branch = { id: "b", depth: 1, startIndex: 2, endIndex: 5 }; + +test("row-highlight: null branch highlights nothing", () => { + assert.deepEqual( + selectThreadRowHighlight({ + branch: null, + index: 3, + messageId: "x", + messageDepth: 2, + showGuides: true, + }), + { + isBranchOwner: false, + isInsideBranch: false, + isDirectChild: false, + lineDepths: undefined, + }, + ); +}); + +test("row-highlight: the branch owner is flagged but is not inside its own range", () => { + const h = selectThreadRowHighlight({ + branch, + index: 2, + messageId: "b", + messageDepth: 1, + showGuides: true, + }); + assert.equal(h.isBranchOwner, true); + // startIndex is excluded, so the owner row itself is not "inside". + assert.equal(h.isInsideBranch, false); + assert.equal(h.lineDepths, undefined); +}); + +test("row-highlight: a direct child inside the branch draws the guide line", () => { + const h = selectThreadRowHighlight({ + branch, + index: 3, + messageId: "c", + messageDepth: 2, + showGuides: true, + }); + assert.equal(h.isInsideBranch, true); + assert.equal(h.isDirectChild, true); + assert.deepEqual(h.lineDepths, [1]); +}); + +test("row-highlight: a deeper descendant is inside but not a direct child", () => { + const h = selectThreadRowHighlight({ + branch, + index: 4, + messageId: "d", + messageDepth: 3, + showGuides: true, + }); + assert.equal(h.isInsideBranch, true); + assert.equal(h.isDirectChild, false); +}); + +test("row-highlight: a row past endIndex is outside the branch", () => { + const h = selectThreadRowHighlight({ + branch, + index: 6, + messageId: "e", + messageDepth: 2, + showGuides: true, + }); + assert.equal(h.isInsideBranch, false); +}); + +test("row-highlight: guides suppressed → no line depths even inside the branch", () => { + const h = selectThreadRowHighlight({ + branch, + index: 3, + messageId: "c", + messageDepth: 2, + showGuides: false, + }); + assert.equal(h.isInsideBranch, true); + assert.equal(h.lineDepths, undefined); +}); diff --git a/desktop/src/features/messages/lib/threadReplyHighlight.ts b/desktop/src/features/messages/lib/threadReplyHighlight.ts new file mode 100644 index 0000000000..0ce446daec --- /dev/null +++ b/desktop/src/features/messages/lib/threadReplyHighlight.ts @@ -0,0 +1,45 @@ +/** + * The hovered collapse-branch range, or null when nothing is hovered. Rows whose + * index falls inside `(startIndex, endIndex]` belong to the branch. + */ +export type HighlightedThreadBranch = { + id: string; + depth: number; + startIndex: number; + endIndex: number; +} | null; + +/** Per-row branch-highlight flags derived from the hovered collapse branch. */ +export type ThreadRowHighlight = { + isBranchOwner: boolean; + isInsideBranch: boolean; + isDirectChild: boolean; + lineDepths: number[] | undefined; +}; + +/** + * Which highlight decorations a reply row shows for the hovered collapse branch. + * Pure so the index-range logic is unit-testable without rendering the panel. + */ +export function selectThreadRowHighlight({ + branch, + index, + messageId, + messageDepth, + showGuides, +}: { + branch: HighlightedThreadBranch; + index: number; + messageId: string; + messageDepth: number; + showGuides: boolean; +}): ThreadRowHighlight { + const isBranchOwner = branch?.id === messageId; + const isInsideBranch = + branch != null && index > branch.startIndex && index <= branch.endIndex; + const isDirectChild = + isInsideBranch && branch != null && messageDepth === branch.depth + 1; + const lineDepths = + showGuides && isInsideBranch && branch ? [branch.depth] : undefined; + return { isBranchOwner, isInsideBranch, isDirectChild, lineDepths }; +} diff --git a/desktop/src/features/messages/lib/timelineSnapshot.test.mjs b/desktop/src/features/messages/lib/timelineSnapshot.test.mjs index a0374fbe2b..5334d58875 100644 --- a/desktop/src/features/messages/lib/timelineSnapshot.test.mjs +++ b/desktop/src/features/messages/lib/timelineSnapshot.test.mjs @@ -14,6 +14,7 @@ import { selectLatestMessageKey, selectTimelineBodySurface, selectTimelineIntroSurface, + selectThreadRepliesSurface, } from "./timelineSnapshot.ts"; // Local-midnight unix-second timestamps so isSameDay (local time) is stable @@ -399,6 +400,126 @@ test("deferred-render: keys the empty decision off the live count, not deferred" assert.equal(selectDeferredListRenderState(0, 1), "pending"); }); +// ── selectThreadRepliesSurface ────────────────────────────────────────────── +// PR-1 defect 2: a terminal thread-load error must NEVER be presented as the +// authoritative "No replies in this branch yet" empty state. These pin the +// paint precedence that gates that in MessageThreadPanel. + +test("thread-surface: pending query paints the skeleton", () => { + assert.equal( + selectThreadRepliesSurface({ + isPending: true, + isError: false, + renderState: "empty", + }), + "skeleton", + ); +}); + +test("thread-surface: terminal error with no data paints error, never empty", () => { + // The core false-empty guard: the load failed (isError) and there is nothing + // cached (renderState "empty"). This MUST be "error" so the UI shows + // "Couldn't load replies" + Retry instead of an authoritative empty thread. + const surface = selectThreadRepliesSurface({ + isPending: false, + isError: true, + renderState: "empty", + }); + assert.equal(surface, "error"); + assert.notEqual(surface, "empty"); +}); + +test("thread-surface: page-2 failure with no committed rows never claims empty", () => { + // A later-page fetch rejects the whole attempt; partial rows are never + // committed, so the deferred+live lists are empty and isError is set. The + // surface must be "error", never "empty" — the thread is not known-empty. + assert.equal( + selectThreadRepliesSurface({ + isPending: false, + isError: true, + renderState: "empty", + }), + "error", + ); +}); + +test("thread-surface: cached rows stay visible even under a load error", () => { + // An error with cached replies (renderState "list") keeps painting the rows + // non-destructively rather than blanking them for the error card. + assert.equal( + selectThreadRepliesSurface({ + isPending: false, + isError: true, + renderState: "list", + }), + "list", + ); +}); + +test("thread-surface: successful empty load paints the empty state", () => { + // No error, genuinely no replies → the real empty affordance is correct. + assert.equal( + selectThreadRepliesSurface({ + isPending: false, + isError: false, + renderState: "empty", + }), + "empty", + ); +}); + +test("thread-surface: retry success renders the reply list", () => { + // After a Retry re-fetch succeeds, isError clears and rows commit + // (renderState "list") → the list body paints, replacing the error card. + assert.equal( + selectThreadRepliesSurface({ + isPending: false, + isError: false, + renderState: "list", + }), + "list", + ); +}); + +test("thread-surface: streaming-in rows paint nothing (pending), not empty", () => { + assert.equal( + selectThreadRepliesSurface({ + isPending: false, + isError: false, + renderState: "pending", + }), + "pending", + ); +}); + +test("thread-surface: huddle transcripts collapse non-list surfaces to pending", () => { + // Huddle transcripts flatten replies into the chat timeline, so they never + // show the skeleton/error/empty affordances — only the list body or nothing. + for (const isError of [false, true]) { + for (const renderState of ["empty", "pending"]) { + assert.equal( + selectThreadRepliesSurface({ + isPending: false, + isError, + renderState, + isHuddleTranscript: true, + }), + "pending", + ); + } + } + // The list body still paints for a transcript with rows. + assert.equal( + selectThreadRepliesSurface({ + isPending: false, + isError: false, + renderState: "list", + isHuddleTranscript: true, + }), + "list", + ); +}); + test("timeline-body-surface: loading and deferred-pending both paint the single static skeleton", () => { assert.equal( selectTimelineBodySurface({ diff --git a/desktop/src/features/messages/lib/timelineSnapshot.ts b/desktop/src/features/messages/lib/timelineSnapshot.ts index 3bfd934947..4e23fb2245 100644 --- a/desktop/src/features/messages/lib/timelineSnapshot.ts +++ b/desktop/src/features/messages/lib/timelineSnapshot.ts @@ -209,6 +209,74 @@ export function selectTimelineBodySurface({ return renderState; } +/** + * Which surface the thread-reply body should paint, in strict precedence. + * + * Extracted as a pure function so the load-bearing invariant — a terminal fetch + * error must NEVER be shown as the "empty" (no-replies) state — is unit-tested + * without a DOM. The precedence mirrors the JSX branch order in + * `MessageThreadPanel`: + * + * 1. "skeleton" → the query is still pending (first load, no cache) + * 2. "list" → the deferred snapshot has rows; paint them (even under a + * later error, cached replies stay visible non-destructively) + * 3. "error" → the load terminally failed and there is nothing to show; + * paint "Couldn't load replies" + Retry, never the empty state + * 4. "empty" → the load succeeded and the branch is genuinely empty + * 5. "pending" → deferred is empty but the live list has content; paint + * nothing yet (rows are streaming in on the deferred commit) + * + * Huddle transcripts flatten replies into the chat timeline and never show the + * skeleton/error/empty affordances, so their non-list surfaces collapse to + * "pending" (render nothing). + */ +export type ThreadRepliesSurface = + | "skeleton" + | "list" + | "error" + | "empty" + | "pending"; + +export function selectThreadRepliesSurface({ + isPending, + isError, + renderState, + isHuddleTranscript = false, +}: { + isPending: boolean; + isError: boolean; + renderState: DeferredListRenderState; + isHuddleTranscript?: boolean; +}): ThreadRepliesSurface { + const surface = resolveThreadRepliesSurface({ + isPending, + isError, + renderState, + }); + return isHuddleTranscript && surface !== "list" ? "pending" : surface; +} + +function resolveThreadRepliesSurface({ + isPending, + isError, + renderState, +}: { + isPending: boolean; + isError: boolean; + renderState: DeferredListRenderState; +}): ThreadRepliesSurface { + if (isPending) { + return "skeleton"; + } + if (renderState === "list") { + return "list"; + } + if (isError) { + return "error"; + } + return renderState; +} + export type TimelineMessageDelta = "prepend" | "append" | "replace" | "none"; export function classifyTimelineMessageDelta({ diff --git a/desktop/src/features/messages/ui/MessageActionBar.tsx b/desktop/src/features/messages/ui/MessageActionBar.tsx index 11163aa8c7..9c490edb07 100644 --- a/desktop/src/features/messages/ui/MessageActionBar.tsx +++ b/desktop/src/features/messages/ui/MessageActionBar.tsx @@ -18,7 +18,6 @@ import { toast } from "sonner"; import { buildMessageLink } from "@/features/messages/lib/messageLink"; import { EmojiPicker } from "@/features/custom-emoji/ui/EmojiPicker"; -import { useCustomEmoji } from "@/features/custom-emoji/hooks"; import { getThreadReference } from "@/features/messages/lib/threading"; import { ReportMessageDialog } from "@/features/moderation/ui/ReportMessageDialog"; import { MessageModerationMenuItems } from "@/features/moderation/ui/MessageModerationMenuItems"; @@ -26,15 +25,9 @@ import type { TimelineMessage, TimelineReaction, } from "@/features/messages/types"; -import { - recordQuickReactionEmoji, - useQuickReactionEmojis, -} from "@/features/messages/ui/useQuickReactionEmojis"; -import { reactionEmojiUrl } from "@/shared/api/customEmoji"; +import { recordQuickReactionEmoji } from "@/features/messages/ui/useQuickReactionEmojis"; import { cn } from "@/shared/lib/cn"; import { copyTextToClipboard } from "@/shared/lib/clipboard"; -import { emojiDisplayName } from "@/shared/lib/emojiName"; -import { rewriteRelayUrl } from "@/shared/lib/mediaUrl"; import { KIND_HUDDLE_STARTED } from "@/shared/constants/kinds"; import { Button } from "@/shared/ui/button"; import { HashArrowIn } from "@/shared/ui/icons"; @@ -53,6 +46,32 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip"; const ACTION_BUTTON_CLASS = "h-8 w-8 rounded-full p-0"; const ACTION_ICON_CLASS = "!h-4 !w-4"; +/** Copying a message link is offered from both the hover action bar and the + * More menu; both paths share this exact link-building + toast behavior. */ +function copyMessageLink(channelId: string, message: TimelineMessage) { + const { rootId } = getThreadReference(message.tags ?? []); + const link = buildMessageLink({ + channelId, + messageId: message.id, + threadRootId: rootId, + }); + copyTextToClipboard(link, "Link copied to clipboard"); +} + +/** Gate shared by every copy-link surface: pending sends have no delivered + * event to link to, huddle system rows aren't linkable, and callers without + * a channelId (e.g. inbox preview rows) can't build the link. */ +function canCopyMessageLink( + message: TimelineMessage, + channelId: string | null | undefined, +): channelId is string { + return ( + !message.pending && + message.kind !== KIND_HUDDLE_STARTED && + Boolean(channelId) + ); +} + function MoreActionsMenu({ channelId, message, @@ -143,7 +162,7 @@ function MoreActionsMenu({ {onEdit ? ( { + onSelect={() => { editJustSelectedRef.current = true; onEdit(message); }} @@ -242,17 +261,11 @@ function MoreActionsMenu({ ) : null} - {hasCopyActions && channelId ? ( + {canCopyMessageLink(message, channelId) ? ( { - const { rootId } = getThreadReference(message.tags ?? []); - const link = buildMessageLink({ - channelId, - messageId: message.id, - threadRootId: rootId, - }); - copyTextToClipboard(link, "Link copied to clipboard"); + copyMessageLink(channelId, message); }} > @@ -316,51 +329,6 @@ function MoreActionsMenu({ ); } -function QuickReactionButton({ - customEmojiUrl, - emoji, - onSelect, -}: { - customEmojiUrl?: string; - emoji: string; - onSelect: (emoji: string) => void; -}) { - const displayName = emojiDisplayName(emoji); - const mediaUrl = customEmojiUrl ? rewriteRelayUrl(customEmojiUrl) : null; - - return ( - - - - - {displayName} - - ); -} - -function isCustomEmojiShortcode(emoji: string) { - return emoji.startsWith(":") && emoji.endsWith(":"); -} - export const MessageActionBar = React.memo(function MessageActionBar({ channelId, message, @@ -404,20 +372,6 @@ export const MessageActionBar = React.memo(function MessageActionBar({ }) { const [isReactionPickerOpen, setIsReactionPickerOpen] = React.useState(false); const [isDropdownOpen, setIsDropdownOpen] = React.useState(false); - const customEmoji = useCustomEmoji(); - const quickReactionEmojis = useQuickReactionEmojis(4, customEmoji); - const quickReactionItems = React.useMemo( - () => - quickReactionEmojis - .map((emoji) => ({ - customEmojiUrl: reactionEmojiUrl(emoji, customEmoji), - emoji, - })) - .filter( - (item) => !isCustomEmojiShortcode(item.emoji) || item.customEmojiUrl, - ), - [customEmoji, quickReactionEmojis], - ); const hasReplyAction = Boolean(onReply); const hasReactionAction = Boolean(onReactionSelect); @@ -482,22 +436,6 @@ export const MessageActionBar = React.memo(function MessageActionBar({ >

- {hasReactionAction && quickReactionItems.length > 0 ? ( - <> -
- {quickReactionItems.map(({ customEmojiUrl, emoji }) => ( - - ))} -
-
- - ) : null} - {hasReactionAction ? ( ) : null} + {canCopyMessageLink(message, channelId) ? ( + + + + + Copy link + + ) : null} + {hasMoreMenuActions ? ( void; threadUnreadCount?: number; threadReplyUnreadCounts?: ReadonlyMap; threadTypingPubkeys: string[]; @@ -131,57 +138,6 @@ type MessageThreadPanelProps = ThreadPanelLayoutProps & { const EMPTY_THREAD_REPLIES: MainTimelineEntry[] = []; const THREAD_PANEL_SUMMARY_INDENT_OFFSET_REM = 0; -function hasLaterVisibleSibling( - entries: readonly MainTimelineEntry[], - entryIndex: number, -): boolean { - const depth = entries[entryIndex]?.message.depth; - if (depth == null) { - return false; - } - - for (let index = entryIndex + 1; index < entries.length; index += 1) { - const nextDepth = entries[index].message.depth; - if (nextDepth <= depth) { - return nextDepth === depth; - } - } - - return false; -} - -function getActiveContinuationDepths({ - ancestors, - entries, - index, - message, -}: { - ancestors: readonly { index: number; message: TimelineMessage }[]; - entries: readonly MainTimelineEntry[]; - index: number; - message: TimelineMessage; -}): number[] { - const depths: number[] = []; - - for (const ancestor of ancestors) { - if (ancestor.message.depth === 0) { - continue; - } - - const childDepth = ancestor.message.depth + 1; - const pathChild = - message.depth === childDepth - ? { index, message } - : ancestors.find((candidate) => candidate.message.depth === childDepth); - - if (pathChild && hasLaterVisibleSibling(entries, pathChild.index)) { - depths.push(ancestor.message.depth); - } - } - - return depths; -} - export function MessageThreadPanel({ channel, channelId, @@ -233,6 +189,8 @@ export function MessageThreadPanel({ videoReviewPresentation, threadReplies, threadRepliesPending = false, + threadRepliesError = false, + onRetryThreadReplies, threadUnreadCount, threadReplyUnreadCounts, threadTypingPubkeys, @@ -629,199 +587,187 @@ export function MessageThreadPanel({ className={cn(THREAD_PANEL_MESSAGE_GUTTER_CLASS, "pb-3 pt-0")} data-testid="message-thread-replies" > - {threadRepliesPending && !isHuddleTranscript ? ( -
- - -
- ) : repliesRenderState === "list" ? ( - visibleThreadHeadSummary ? ( + (
- + +
- ) : ( -
- {threadReplyRenderItems.map((item) => { - const { - collapseDepthGuideActions, - connectsToVisibleChild, - continuationDepths, - entry, - index, - isContinuation, - } = item; - const showUnreadDivider = - index > 0 && entry.message.id === firstUnreadReplyId; - const isHighlightedBranchOwner = - highlightedBranch?.id === entry.message.id; - const isInsideHighlightedBranch = - highlightedBranch != null && - index > highlightedBranch.startIndex && - index <= highlightedBranch.endIndex; - const isDirectChildOfHighlightedBranch = - isInsideHighlightedBranch && - highlightedBranch != null && - index > highlightedBranch.startIndex && - index <= highlightedBranch.endIndex && - entry.message.depth === highlightedBranch.depth + 1; - const highlightedLineDepths = - shouldShowThreadBranchGuides && - isInsideHighlightedBranch && - highlightedBranch - ? [highlightedBranch.depth] - : undefined; - return ( -
- {showUnreadDivider ? : null} - + visibleThreadHeadSummary ? ( +
+ +
+ ) : ( +
+ {threadReplyRenderItems.map((item) => { + const { + collapseDepthGuideActions, + connectsToVisibleChild, + continuationDepths, + entry, + index, + isContinuation, + } = item; + const showUnreadDivider = + index > 0 && entry.message.id === firstUnreadReplyId; + const highlight = selectThreadRowHighlight({ + branch: highlightedBranch, + index, + messageId: entry.message.id, + messageDepth: entry.message.depth, + showGuides: shouldShowThreadBranchGuides, + }); + return ( +
- {entry.summary ? ( - + {showUnreadDivider ? : null} + - ) : null} -
- ); - })} -
- ) - ) : repliesRenderState === "empty" && !isHuddleTranscript ? ( - // Only show the empty state when the thread is GENUINELY empty. - // Keying off `deferredThreadReplies` would flash "No replies" for a - // frame while a non-empty list streams in on the deferred commit. -
-

- No replies in this branch yet -

-

- Reply in the thread to continue this branch. -

-
- ) : // "pending": deferred list is empty but the live list has content — - // rows are streaming in on the deferred commit. Paint nothing rather - // than flashing the empty state. - null} + {entry.summary ? ( + + ) : null} +
+ ); + })} +
+ ) + } + />
diff --git a/desktop/src/features/messages/ui/MessageThreadReplyState.test.mjs b/desktop/src/features/messages/ui/MessageThreadReplyState.test.mjs new file mode 100644 index 0000000000..f70143f87b --- /dev/null +++ b/desktop/src/features/messages/ui/MessageThreadReplyState.test.mjs @@ -0,0 +1,162 @@ +/** + * Mount regressions for the thread reply region, wired through the + * panel-owned ThreadReplyRegion dispatcher. + * + * Bug this pins: a terminal thread-replies fetch error used to fall through to + * the "No replies in this branch yet" empty card, silently presenting a broken + * load as an authoritative empty branch with no recovery. The fix maps a + * terminal error to the retry card and NEVER the empty card, and routes the + * Retry button back to the query's refetch. + * + * Why this component, and why raw inputs: ThreadReplyRegion now owns BOTH the + * surface selection (selectThreadRepliesSurface, also unit-tested against its + * 8-case matrix in timelineSnapshot.test.mjs) AND the surface→content dispatch. + * MessageThreadPanel passes only its raw query/render state — the pending/error + * flags and the deferred vs. live reply counts — so there is no precomputed + * `surface` prop at the panel boundary to statically mis-set. This file mounts + * ThreadReplyRegion and drives the real raw-state→surface→content mapping, so a + * false-empty regression cannot land at either the selection or the dispatch + * with these tests green. Mounting the full panel is infeasible in node:test + * (its Tiptap composer / React Query stack is unavailable, see + * MessageComposerAutoSend.test.mjs); the render callbacks keep that heavy + * construction in the panel and out of this cheap mount. + * + * CI surface: pnpm test (node:test with @testing-library/react over JSDOM). + */ + +import assert from "node:assert/strict"; +import { after, afterEach, before, test } from "node:test"; + +import { JSDOM } from "jsdom"; + +const dom = new JSDOM("", { + url: "http://localhost", +}); + +before(() => { + Object.assign(globalThis, { + document: dom.window.document, + HTMLElement: dom.window.HTMLElement, + IS_REACT_ACT_ENVIRONMENT: true, + window: dom.window, + }); + dom.window.matchMedia = () => ({ + matches: false, + addEventListener() {}, + removeEventListener() {}, + }); +}); + +afterEach(async () => { + const { cleanup } = await import("@testing-library/react"); + cleanup(); +}); + +after(() => dom.window.close()); + +// Sentinels for the two heavy branches the panel owns. If ThreadReplyRegion +// ever routes error/empty/pending through a render callback, these appear where +// a card is expected and the assertions catch it. +const SKELETON_MARK = "SKELETON_BRANCH_MARKER"; +const LIST_MARK = "LIST_BRANCH_MARKER"; + +async function renderRegion(props) { + const { createElement } = await import("react"); + const { render } = await import("@testing-library/react"); + const { ThreadReplyRegion } = await import("./MessageThreadReplyState.tsx"); + return render( + createElement(ThreadReplyRegion, { + isPending: false, + isError: false, + deferredCount: 0, + liveCount: 0, + renderSkeleton: () => createElement("div", null, SKELETON_MARK), + renderList: () => createElement("div", null, LIST_MARK), + ...props, + }), + ); +} + +test("terminal error renders the retry card, never the empty card", async () => { + const { screen } = await import("@testing-library/react"); + // Raw terminal-failure state: not pending, load errored, nothing to show. + await renderRegion({ isError: true, onRetry: () => {} }); + + const card = screen.getByTestId("message-thread-replies-error"); + assert.ok(card, "a terminal error must render the error card"); + // The card appears asynchronously (after the query/retry lifecycle), so it + // must be an alert live region or a screen-reader user never hears it. + assert.equal( + card.getAttribute("role"), + "alert", + "the async error card must be an alert live region for assistive tech", + ); + assert.equal( + document.body.textContent.includes("No replies in this branch yet"), + false, + "a terminal error must NEVER render the empty state", + ); +}); + +test("Retry button invokes the supplied refetch callback", async () => { + const { fireEvent, screen } = await import("@testing-library/react"); + let retryCount = 0; + await renderRegion({ + isError: true, + onRetry: () => { + retryCount += 1; + }, + }); + + fireEvent.click(screen.getByTestId("message-thread-replies-retry")); + + assert.equal(retryCount, 1, "clicking Retry must call the refetch callback"); +}); + +test("genuine empty surface renders the empty card, not the error card", async () => { + const { screen } = await import("@testing-library/react"); + // Load succeeded (no error), branch is genuinely empty. + await renderRegion({}); + + assert.ok( + document.body.textContent.includes("No replies in this branch yet"), + "a genuine empty branch must render the empty card", + ); + assert.equal( + screen.queryByTestId("message-thread-replies-error"), + null, + "a genuine empty branch must NOT render the error card", + ); +}); + +test("pending surface paints nothing", async () => { + // Deferred snapshot is empty but the live list has content: rows are + // streaming in on the deferred commit, so paint nothing yet. + const { container } = await renderRegion({ deferredCount: 0, liveCount: 1 }); + + assert.equal( + container.textContent, + "", + "the pending surface must render nothing while rows stream in", + ); +}); + +test("skeleton surface renders the panel's skeleton branch", async () => { + const { container } = await renderRegion({ isPending: true }); + + assert.equal( + container.textContent, + SKELETON_MARK, + "the skeleton surface must render the panel's skeleton branch", + ); +}); + +test("list surface renders the panel's list branch", async () => { + const { container } = await renderRegion({ deferredCount: 1, liveCount: 1 }); + + assert.equal( + container.textContent, + LIST_MARK, + "the list surface must render the panel's list branch", + ); +}); diff --git a/desktop/src/features/messages/ui/MessageThreadReplyState.tsx b/desktop/src/features/messages/ui/MessageThreadReplyState.tsx new file mode 100644 index 0000000000..a13d46286e --- /dev/null +++ b/desktop/src/features/messages/ui/MessageThreadReplyState.tsx @@ -0,0 +1,127 @@ +import type { ReactNode } from "react"; + +import { + selectDeferredListRenderState, + selectThreadRepliesSurface, +} from "@/features/messages/lib/timelineSnapshot"; +import { Button } from "@/shared/ui/button"; + +/** + * Terminal empty/error states for the thread reply region. + * + * These are the two non-list, non-loading outcomes of a thread-reply load. They + * live here (rather than inline in `MessageThreadPanel`) so the load-bearing + * distinction between them stays legible: a genuinely empty branch and a failed + * fetch look similar but must never be confused — see `selectThreadRepliesSurface`. + */ + +/** + * A terminal load failure. This must NEVER be painted as the empty state — that + * silently presents a broken fetch as an authoritative "no replies" and offers + * no recovery. Any cached replies still render via the panel's "list" branch, so + * this only surfaces when the failed load left nothing to show. + * + * `role="alert"` (implicit `aria-live="assertive"`, `aria-atomic="true"`) makes + * the asynchronous failure audible to assistive tech: the card appears only after + * the query/retry lifecycle reaches a terminal error, so without a live region a + * screen-reader user parked in the composer never learns the load failed or that + * Retry became available. + */ +export function ThreadRepliesErrorCard({ onRetry }: { onRetry?: () => void }) { + return ( +
+

+ Couldn't load replies +

+

+ The thread history didn't load. Check your connection and try + again. +

+ {onRetry ? ( + + ) : null} +
+ ); +} + +/** + * A branch that genuinely has no replies (the load succeeded and returned none). + * Only ever painted off the committed render state, never the raw deferred list, + * so it can't flash while a non-empty list streams in on the deferred commit. + */ +export function ThreadRepliesEmptyCard() { + return ( +
+

+ No replies in this branch yet +

+

+ Reply in the thread to continue this branch. +

+
+ ); +} + +/** + * The single paint decision for the thread reply region. This unit owns BOTH + * the surface selection (`selectThreadRepliesSurface`, keyed off the same raw + * query/render state the panel already holds) AND the surface→content dispatch. + * Fusing them here removes the last falsifiable seam: the panel passes only its + * raw state — pending/error flags, the deferred vs. live reply counts, and the + * huddle-transcript flag — so there is no precomputed `surface` prop at the + * panel boundary to statically mis-set (e.g. a stray `surface="empty"` that would + * silently restore the false-empty bug on every fetch failure). The load-bearing + * invariant holds by construction: a terminal fetch "error" renders the retry + * card and NEVER the "empty" "No replies" state, while "pending" paints nothing + * (rows stream in on the deferred commit). + * + * The two heavy branches take render callbacks so the panel keeps ownership of + * its skeleton and list construction (Tiptap/React-Query bound, not mountable in + * node:test) without dragging them into this component. The mount test drives + * the real raw-state→surface→content mapping through this exported unit, so both + * the selection and the dispatch are covered under a cheap mount. + */ +export function ThreadReplyRegion({ + isPending, + isError, + deferredCount, + liveCount, + isHuddleTranscript = false, + onRetry, + renderSkeleton, + renderList, +}: { + isPending: boolean; + isError: boolean; + deferredCount: number; + liveCount: number; + isHuddleTranscript?: boolean; + onRetry?: () => void; + renderSkeleton: () => ReactNode; + renderList: () => ReactNode; +}) { + const surface = selectThreadRepliesSurface({ + isPending, + isError, + renderState: selectDeferredListRenderState(deferredCount, liveCount), + isHuddleTranscript, + }); + if (surface === "skeleton") return <>{renderSkeleton()}; + if (surface === "list") return <>{renderList()}; + if (surface === "error") return ; + if (surface === "empty") return ; + return null; +} diff --git a/desktop/src/features/messages/ui/MessageTimeline.tsx b/desktop/src/features/messages/ui/MessageTimeline.tsx index df9af09e67..fa8bb4e9f6 100644 --- a/desktop/src/features/messages/ui/MessageTimeline.tsx +++ b/desktop/src/features/messages/ui/MessageTimeline.tsx @@ -863,8 +863,12 @@ const MessageTimelineBase = React.forwardRef<
(null); const rafRef = React.useRef(null); + const suppressRightClickUpdatesRef = React.useRef(false); const trayRef = React.useRef(null); const [trayWidth, setTrayWidth] = React.useState(0); + const cancelScheduledUpdate = React.useCallback(() => { + if (rafRef.current === null) return; + window.cancelAnimationFrame(rafRef.current); + rafRef.current = null; + }, []); + const updatePosition = React.useCallback(() => { - if (!editor || disabled || !editor.isEditable || !editor.isFocused) { + if ( + suppressRightClickUpdatesRef.current || + !editor || + disabled || + !editor.isEditable || + !editor.isFocused + ) { setPosition(null); return; } @@ -127,44 +140,66 @@ export function SelectionFormattingTray({ }, [disabled, editor, trayWidth]); const scheduleUpdate = React.useCallback(() => { - if (rafRef.current !== null) { - window.cancelAnimationFrame(rafRef.current); + if (suppressRightClickUpdatesRef.current) { + cancelScheduledUpdate(); + setPosition(null); + return; } + cancelScheduledUpdate(); rafRef.current = window.requestAnimationFrame(() => { rafRef.current = null; updatePosition(); }); - }, [updatePosition]); + }, [cancelScheduledUpdate, updatePosition]); React.useEffect(() => { + suppressRightClickUpdatesRef.current = false; + if (!editor) { + cancelScheduledUpdate(); setPosition(null); return; } + const editorDom = editor.view.dom; const hide = () => setPosition(null); + const handleContextMenu = () => { + suppressRightClickUpdatesRef.current = true; + cancelScheduledUpdate(); + setPosition(null); + }; + const clearSuppression = () => { + suppressRightClickUpdatesRef.current = false; + scheduleUpdate(); + }; + const handlePointerDown = (event: PointerEvent) => { + if (event.button === 0) clearSuppression(); + }; scheduleUpdate(); editor.on("selectionUpdate", scheduleUpdate); editor.on("transaction", scheduleUpdate); editor.on("focus", scheduleUpdate); editor.on("blur", hide); + editorDom.addEventListener("contextmenu", handleContextMenu); + editorDom.addEventListener("pointerdown", handlePointerDown); + editorDom.addEventListener("keydown", clearSuppression); window.addEventListener("resize", scheduleUpdate); window.addEventListener("scroll", scheduleUpdate, true); return () => { - if (rafRef.current !== null) { - window.cancelAnimationFrame(rafRef.current); - rafRef.current = null; - } + cancelScheduledUpdate(); editor.off("selectionUpdate", scheduleUpdate); editor.off("transaction", scheduleUpdate); editor.off("focus", scheduleUpdate); editor.off("blur", hide); + editorDom.removeEventListener("contextmenu", handleContextMenu); + editorDom.removeEventListener("pointerdown", handlePointerDown); + editorDom.removeEventListener("keydown", clearSuppression); window.removeEventListener("resize", scheduleUpdate); window.removeEventListener("scroll", scheduleUpdate, true); }; - }, [editor, scheduleUpdate]); + }, [cancelScheduledUpdate, editor, scheduleUpdate]); React.useLayoutEffect(() => { if (!position || !trayRef.current) return; diff --git a/desktop/src/features/messages/useThreadReplies.test.mjs b/desktop/src/features/messages/useThreadReplies.test.mjs index 48896c5c51..53399cd2f3 100644 --- a/desktop/src/features/messages/useThreadReplies.test.mjs +++ b/desktop/src/features/messages/useThreadReplies.test.mjs @@ -1,30 +1,15 @@ import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; import test from "node:test"; -import { collectThreadAuxMessageIds } from "./useThreadReplies.ts"; - -const ROOT_ID = "1".repeat(64); -const REPLY_ID = "2".repeat(64); - -function reply(id = REPLY_ID) { - return { - id, - pubkey: "a".repeat(64), - kind: 9, - created_at: 1_700_000_000, - content: "reply", - tags: [["e", ROOT_ID]], - sig: "sig", - }; -} - -test("thread aux hydration includes the root when there are no replies", () => { - assert.deepEqual(collectThreadAuxMessageIds(ROOT_ID, []), [ROOT_ID]); -}); - -test("thread aux hydration includes and deduplicates root and reply ids", () => { - assert.deepEqual( - collectThreadAuxMessageIds(ROOT_ID, [reply(), reply(ROOT_ID)]), - [ROOT_ID, REPLY_ID], +test("thread replies trust the relay-provided aux closure", async () => { + const source = await readFile( + new URL("./useThreadReplies.ts", import.meta.url), + "utf8", ); + assert.doesNotMatch( + source, + /withThreadAux|fetchStructuralAuxForMessages|fetchAuxEventsByReference/, + ); + assert.match(source, /replies\.push\(\.\.\.response\.events\)/); }); diff --git a/desktop/src/features/messages/useThreadReplies.ts b/desktop/src/features/messages/useThreadReplies.ts index bb1c2909b6..4d602348f9 100644 --- a/desktop/src/features/messages/useThreadReplies.ts +++ b/desktop/src/features/messages/useThreadReplies.ts @@ -5,76 +5,16 @@ import { useQueryClient, } from "@tanstack/react-query"; -import { - collectMessageIdsForAuxBackfill, - fetchStructuralAuxForMessages, -} from "@/features/messages/lib/auxBackfill"; import { threadRepliesKey, sortMessages, } from "@/features/messages/lib/messageQueryKeys"; -import { relayClient } from "@/shared/api/relayClient"; -import { buildChannelReactionAuxFilter } from "@/shared/api/relayChannelFilters"; import { getThreadReplies } from "@/shared/api/tauri"; import type { Channel, RelayEvent, ThreadCursor } from "@/shared/api/types"; const THREAD_PAGE_LIMIT = 200; const MAX_THREAD_PAGES = 500; -/** - * Append the structural aux closure (edits/deletions) for the fetched replies. - * The server thread-subtree query resolves deletions itself but omits - * kind:40003 edits, so a bare refetch would render every edited reply with its - * original text. Best-effort: an aux failure logs and returns the replies - * unadorned rather than failing the whole thread load. - */ -async function fetchThreadAuxBestEffort( - label: string, - channelId: string, - fetchAux: () => Promise, -): Promise { - try { - return await fetchAux(); - } catch (error) { - console.error( - `Failed to backfill thread reply ${label} for channel`, - channelId, - error, - ); - return []; - } -} - -export function collectThreadAuxMessageIds( - threadRootId: string, - replies: RelayEvent[], -): string[] { - return [ - ...new Set([threadRootId, ...collectMessageIdsForAuxBackfill(replies)]), - ]; -} - -async function withThreadAux( - channelId: string, - threadRootId: string, - replies: RelayEvent[], -): Promise { - const messageIds = collectThreadAuxMessageIds(threadRootId, replies); - const [structuralAux, reactions] = await Promise.all([ - fetchThreadAuxBestEffort("structural aux", channelId, () => - fetchStructuralAuxForMessages(channelId, messageIds), - ), - fetchThreadAuxBestEffort("reactions", channelId, () => - relayClient.fetchAuxEventsByReference( - channelId, - messageIds, - buildChannelReactionAuxFilter, - ), - ), - ]); - return sortMessages([...replies, ...structuralAux, ...reactions]); -} - async function loadThreadReplies( queryClient: QueryClient, channelId: string, @@ -92,12 +32,11 @@ async function loadThreadReplies( }); replies.push(...response.events); if (!response.nextCursor) { - const fetched = await withThreadAux(channelId, rootId, replies); const current = queryClient.getQueryData(queryKey) ?? []; const receivedInFlight = current.filter( (event) => !idsAtStart.has(event.id), ); - return sortMessages([...fetched, ...receivedInFlight]); + return sortMessages([...replies, ...receivedInFlight]); } cursor = response.nextCursor; } @@ -128,6 +67,39 @@ export function useThreadReplies( }); } +/** + * Aggregate a set of per-root thread-reply query results into one view for a + * multi-root consumer. Pure over the results array so the load-bearing + * error-surfacing contract is unit-testable without a live QueryClient. + * + * `isError`/`error` expose aggregate terminal failure so a consumer never + * silently drops a failed reply subtree — the same false-empty class the + * single-root panel guards against. `error` carries the first failed subtree's + * error; `refetch` re-runs only the failed queries so a partial success is not + * needlessly re-fetched. + */ +export function combineThreadRepliesResults( + results: readonly { + data?: RelayEvent[]; + isPending: boolean; + isError: boolean; + error: unknown; + refetch: () => unknown; + }[], +) { + return { + events: sortMessages(results.flatMap((result) => result.data ?? [])), + isPending: results.some((result) => result.isPending), + isError: results.some((result) => result.isError), + error: results.find((result) => result.isError)?.error ?? null, + refetch: () => { + for (const result of results) { + if (result.isError) void result.refetch(); + } + }, + }; +} + /** * Load every summarized reply subtree for a channel-style Huddle transcript. * Ordinary channels keep replies in their thread panels; Huddles flatten those @@ -148,9 +120,6 @@ export function useThreadRepliesForRoots( staleTime: 0, gcTime: 60 * 60 * 1_000, })), - combine: (results) => ({ - events: sortMessages(results.flatMap((result) => result.data ?? [])), - isPending: results.some((result) => result.isPending), - }), + combine: combineThreadRepliesResults, }); } diff --git a/desktop/src/features/notifications/lib/sound.test.mjs b/desktop/src/features/notifications/lib/sound.test.mjs index dfa9c84060..ef3cc8d4cd 100644 --- a/desktop/src/features/notifications/lib/sound.test.mjs +++ b/desktop/src/features/notifications/lib/sound.test.mjs @@ -1,7 +1,57 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { shouldPlayNotificationSound } from "./sound.ts"; +import { + KIND_APPROVAL_REQUEST, + KIND_STREAM_MESSAGE_V2, + KIND_JOB_ACCEPTED, +} from "../../../shared/constants/kinds.ts"; +import { shouldPlayNotificationSound, slotForFeedKind } from "./sound.ts"; + +test("routes each feed category to its own sound slot", () => { + assert.equal(slotForFeedKind(KIND_STREAM_MESSAGE_V2, "mention"), "mention"); + assert.equal( + slotForFeedKind(KIND_APPROVAL_REQUEST, "needs_action"), + "needs_action", + ); + assert.equal( + slotForFeedKind(KIND_STREAM_MESSAGE_V2, "activity"), + "needs_action", + ); + assert.equal( + slotForFeedKind(KIND_STREAM_MESSAGE_V2, "agent_activity"), + "needs_action", + ); +}); + +test("agent job kinds pick their slot for non-mention categories", () => { + assert.equal( + slotForFeedKind(KIND_JOB_ACCEPTED, "agent_activity"), + "job_accepted", + ); +}); + +test("a mention outranks the agent job kind that carried it", () => { + assert.equal(slotForFeedKind(KIND_JOB_ACCEPTED, "mention"), "mention"); +}); + +test("unknown category falls back to needs_action and warns", () => { + const warnings = []; + const originalWarn = console.warn; + console.warn = (...args) => warnings.push(args.join(" ")); + try { + // The backend once emitted the plural section name here; the fallback + // keeps the user alerted while the warning keeps the drift visible. + assert.equal( + slotForFeedKind(KIND_STREAM_MESSAGE_V2, "mentions"), + "needs_action", + ); + } finally { + console.warn = originalWarn; + } + assert.equal(warnings.length, 1); + assert.match(warnings[0], /unknown feed item category "mentions"/); +}); test("silences notifications from Huddle backing channels", () => { const silentChannelIds = new Set(["active-huddle"]); diff --git a/desktop/src/features/notifications/lib/sound.ts b/desktop/src/features/notifications/lib/sound.ts index 1e9ccb3839..3371658a3b 100644 --- a/desktop/src/features/notifications/lib/sound.ts +++ b/desktop/src/features/notifications/lib/sound.ts @@ -1,5 +1,4 @@ import { - KIND_APPROVAL_REQUEST, KIND_JOB_ACCEPTED, KIND_JOB_ERROR, KIND_JOB_PROGRESS, @@ -115,6 +114,17 @@ export function resolveSlotSound( return prefs.sounds[slot]; } +/** + * Pick the sound slot for a home-feed item. + * + * `category` is the backend's per-item classification (`FeedItemCategory` in + * `desktop/src-tauri/src/models.rs`). A mention always wins — being addressed + * directly outranks whatever kind of event carried it, including agent job + * events. Every other known category maps explicitly; anything else falls + * back to `needs_action` so a contract drift costs the user the wrong sound + * rather than a missed alert — and warns so the drift is visible to + * developers instead of silently masquerading as intended. + */ export function slotForFeedKind( kind: number, category: FeedItemCategory, @@ -124,8 +134,20 @@ export function slotForFeedKind( if (kind === KIND_JOB_PROGRESS) return "job_progress"; if (kind === KIND_JOB_RESULT) return "job_result"; if (kind === KIND_JOB_ERROR) return "job_error"; - if (kind === KIND_APPROVAL_REQUEST) return "needs_action"; - return "needs_action"; + + switch (category) { + case "needs_action": + case "activity": + case "agent_activity": + return "needs_action"; + default: { + const unexpected: never = category; + console.warn( + `[notifications] unknown feed item category ${JSON.stringify(unexpected)} for kind ${kind}; falling back to needs_action`, + ); + return "needs_action"; + } + } } export function shouldPlayNotificationSound( diff --git a/desktop/src/features/profile/hooks.ts b/desktop/src/features/profile/hooks.ts index f174d50408..d46d27df9e 100644 --- a/desktop/src/features/profile/hooks.ts +++ b/desktop/src/features/profile/hooks.ts @@ -284,8 +284,8 @@ export function useUserProfileQuery(pubkey?: string) { // Per-pubkey resolution cache backing `useUsersBatchQuery`'s delta fetch. // `summary: null` records a relay-confirmed miss so unknown pubkeys aren't -// re-requested every page. Entries older than the hook's 60s staleTime are -// treated as unresolved and refetched. +// re-requested every page. Entries older than the hook's 10-minute staleTime +// are treated as unresolved and refetched. export type UsersBatchEntry = { summary: UserProfileSummary | null; fetchedAt: number; @@ -301,7 +301,8 @@ export const usersBatchEntryKey = (pubkey: string) => [ * run re-fetches these profiles from the relay. Must be called anywhere a * specific profile (or a containing `users-batch` query) is invalidated — * otherwise the re-run resolves from the still-fresh-looking entry and - * renders the stale name/avatar for up to the entry's 60s freshness window. + * renders the stale name/avatar for up to the entry's 10-minute freshness + * window. * Synchronous, so callers can evict before awaiting aggregate invalidations. */ export function evictUsersBatchEntries( @@ -351,7 +352,7 @@ export function useUsersBatchQuery( const entry = queryClient.getQueryData( usersBatchEntryKey(pubkey), ); - if (entry && now - entry.fetchedAt < 60_000) { + if (entry && now - entry.fetchedAt < 10 * 60_000) { if (entry.summary) profiles[pubkey] = entry.summary; else missing.push(pubkey); } else { @@ -384,7 +385,7 @@ export function useUsersBatchQuery( relayUrl, normalizedPubkeys, ), - staleTime: 60_000, + staleTime: 10 * 60_000, gcTime: 5 * 60 * 1_000, }); diff --git a/desktop/src/features/projects/ui/ProjectConversationPanel.tsx b/desktop/src/features/projects/ui/ProjectConversationPanel.tsx index 59f3264b02..11344ea574 100644 --- a/desktop/src/features/projects/ui/ProjectConversationPanel.tsx +++ b/desktop/src/features/projects/ui/ProjectConversationPanel.tsx @@ -279,7 +279,11 @@ export function ProjectConversationPanel({ scrollTargetId={scrollTargetId} threadHead={panelData.threadHead} threadReplies={panelData.visibleReplies} - threadRepliesPending={false} + threadRepliesPending={threadRepliesQuery.isPending} + threadRepliesError={threadRepliesQuery.isError} + onRetryThreadReplies={() => { + void threadRepliesQuery.refetch(); + }} threadTypingPubkeys={[]} widthPx={widthPx} />, diff --git a/desktop/src/features/projects/ui/ProjectsAgentPromptPage.tsx b/desktop/src/features/projects/ui/ProjectsAgentPromptPage.tsx index 9a465d3da0..f667fcd2a2 100644 --- a/desktop/src/features/projects/ui/ProjectsAgentPromptPage.tsx +++ b/desktop/src/features/projects/ui/ProjectsAgentPromptPage.tsx @@ -37,6 +37,7 @@ import { } from "@/features/messages/lib/useRichTextEditor"; import { FormattingToolbar } from "@/features/messages/ui/FormattingToolbar"; import { MessageThreadTranscript } from "@/features/messages/ui/MessageThreadTranscript"; +import { ThreadRepliesErrorCard } from "@/features/messages/ui/MessageThreadReplyState"; import type { TimelineMessage } from "@/features/messages/types"; import { useThreadRepliesForRoots } from "@/features/messages/useThreadReplies"; import { useProfileQuery, useUsersBatchQuery } from "@/features/profile/hooks"; @@ -363,6 +364,9 @@ export function ConversationThread({ profiles={profiles} renderAfterMessage={renderSubmittedContext} /> + {threadReplies.isError ? ( + + ) : null} {agentWorking.working ? (
diff --git a/desktop/src/features/sidebar/ui/SidebarSection.tsx b/desktop/src/features/sidebar/ui/SidebarSection.tsx index 1a6403fb24..0c99eaf16d 100644 --- a/desktop/src/features/sidebar/ui/SidebarSection.tsx +++ b/desktop/src/features/sidebar/ui/SidebarSection.tsx @@ -79,7 +79,10 @@ function UnreadCountBadge({ data-testid={`channel-unread-${channelName}`} > {formatUnreadCount(count)} - new comment{count === 1 ? "" : "s"} + + {" "} + unread notification{count === 1 ? "" : "s"} + ); } @@ -255,6 +258,7 @@ export function ChannelMenuButton({ label, isActive, hasUnread, + unreadCount = 0, activeWorking, isMuted, dmParticipants, @@ -354,7 +358,13 @@ export function ChannelMenuButton({ )} /> ) : null} - {hasThreadUnread ? ( + {!isActive && channel.channelType !== "dm" && unreadCount > 0 ? ( + + ) : hasThreadUnread ? ( ) : null} diff --git a/desktop/src/features/workflows/ui/WorkflowAuthorPicker.tsx b/desktop/src/features/workflows/ui/WorkflowAuthorPicker.tsx new file mode 100644 index 0000000000..bcf0b209ff --- /dev/null +++ b/desktop/src/features/workflows/ui/WorkflowAuthorPicker.tsx @@ -0,0 +1,361 @@ +import { Check, LoaderCircle, Search } from "lucide-react"; +import * as React from "react"; + +import { useChannelMembersQuery } from "@/features/channels/hooks"; +import { useRelayMembersQuery } from "@/features/community-members/hooks"; +import { + useFlattenedUserSearchResults, + useInfiniteUserSearchQuery, + useUsersBatchQuery, +} from "@/features/profile/hooks"; +import { resolveUserLabel } from "@/features/profile/lib/identity"; +import { cn } from "@/shared/lib/cn"; +import { truncatePubkey } from "@/shared/lib/pubkey"; +import { Input } from "@/shared/ui/input"; +import { UserAvatar } from "@/shared/ui/UserAvatar"; +import { + enrichAuthorCandidates, + filterAuthorCandidatePage, + mergeAuthorCandidateSources, + nextWorkflowAuthorIndex, + parseDirectAuthorInput, + type WorkflowAuthorCandidate, +} from "./workflowAuthorCandidates"; + +const PAGE_SIZE = 50; + +export function WorkflowAuthorPicker({ + channelId, + disabled, + id, + onChange, + onEscape, + value, +}: { + channelId?: string | null; + disabled?: boolean; + id: string; + onChange: (pubkey: string) => void; + onEscape?: () => void; + value: string; +}) { + const pickerRef = React.useRef(null); + const optionRefs = React.useRef(new Map()); + const [query, setQuery] = React.useState(""); + const [activeIndex, setActiveIndex] = React.useState(null); + const [columnCount, setColumnCount] = React.useState(2); + const trimmedQuery = query.trim(); + const deferredQuery = React.useDeferredValue(trimmedQuery); + const normalizedValue = parseDirectAuthorInput(value); + const channelMembersQuery = useChannelMembersQuery(channelId ?? null); + const relayMembersQuery = useRelayMembersQuery(true); + const directoryQuery = useInfiniteUserSearchQuery(deferredQuery, { + allowEmpty: true, + limit: PAGE_SIZE, + }); + const directoryResults = useFlattenedUserSearchResults(directoryQuery.data); + const directPubkey = parseDirectAuthorInput(deferredQuery); + + const baseCandidates = React.useMemo( + () => + mergeAuthorCandidateSources([ + normalizedValue ? [{ pubkey: normalizedValue }] : [], + directPubkey ? [{ pubkey: directPubkey }] : [], + channelMembersQuery.data ?? [], + relayMembersQuery.data ?? [], + directoryResults, + ]), + [ + channelMembersQuery.data, + directPubkey, + directoryResults, + normalizedValue, + relayMembersQuery.data, + ], + ); + const candidatePage = React.useMemo( + () => + filterAuthorCandidatePage( + baseCandidates, + deferredQuery, + directPubkey, + PAGE_SIZE, + ), + [baseCandidates, deferredQuery, directPubkey], + ); + const profileQuery = useUsersBatchQuery( + candidatePage.map(({ pubkey }) => pubkey), + ); + const candidates = React.useMemo( + () => + enrichAuthorCandidates(candidatePage, profileQuery.data?.profiles ?? {}), + [candidatePage, profileQuery.data?.profiles], + ); + const visibleCandidates = candidates; + const listId = `${id}-list`; + + React.useEffect(() => { + if (activeIndex !== null && activeIndex >= visibleCandidates.length) { + setActiveIndex( + visibleCandidates.length > 0 ? visibleCandidates.length - 1 : null, + ); + } + }, [activeIndex, visibleCandidates.length]); + + React.useEffect(() => { + const picker = pickerRef.current; + if (!picker) return; + const updateColumnCount = () => + setColumnCount(picker.clientWidth >= 544 ? 3 : 2); + updateColumnCount(); + const observer = new ResizeObserver(updateColumnCount); + observer.observe(picker); + return () => observer.disconnect(); + }, []); + + React.useEffect(() => { + if (activeIndex === null) return; + const candidate = visibleCandidates[activeIndex]; + if (!candidate) return; + optionRefs.current + .get(candidate.pubkey) + ?.scrollIntoView({ block: "nearest", inline: "nearest" }); + }, [activeIndex, visibleCandidates]); + + const loading = + (channelMembersQuery.isLoading || + relayMembersQuery.isLoading || + directoryQuery.isLoading) && + visibleCandidates.length === 0; + const failed = + channelMembersQuery.isError || + relayMembersQuery.isError || + directoryQuery.isError; + + function moveActive(delta: number) { + setActiveIndex((current) => + nextWorkflowAuthorIndex(current, delta, visibleCandidates.length), + ); + } + + return ( +
+
+ + { + setQuery(event.target.value); + setActiveIndex(null); + }} + onKeyDown={(event) => { + const currentQuery = event.currentTarget.value.trim(); + const delta = + event.key === "ArrowDown" + ? columnCount + : event.key === "ArrowUp" + ? -columnCount + : event.key === "ArrowRight" + ? 1 + : event.key === "ArrowLeft" + ? -1 + : 0; + if (delta) { + event.preventDefault(); + moveActive(delta); + } else if ( + event.key === "Enter" && + currentQuery === deferredQuery && + visibleCandidates[activeIndex ?? 0] + ) { + event.preventDefault(); + const candidate = visibleCandidates[activeIndex ?? 0]; + onChange( + candidate.pubkey === normalizedValue ? "" : candidate.pubkey, + ); + } else if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + if (query) { + setQuery(""); + setActiveIndex(null); + } else { + onEscape?.(); + } + } + }} + placeholder="Search people or paste a public key…" + role="combobox" + spellCheck={false} + value={query} + /> +
+ +
{ + const list = event.currentTarget; + if ( + list.scrollHeight - list.scrollTop - list.clientHeight < 64 && + directoryQuery.hasNextPage && + !directoryQuery.isFetchingNextPage + ) { + void directoryQuery.fetchNextPage(); + } + }} + role="listbox" + > + {visibleCandidates.map((candidate, index) => ( + { + setActiveIndex(null); + onChange( + candidate.pubkey === normalizedValue ? "" : candidate.pubkey, + ); + }} + optionRef={(node) => { + if (node) optionRefs.current.set(candidate.pubkey, node); + else optionRefs.current.delete(candidate.pubkey); + }} + selected={candidate.pubkey === normalizedValue} + /> + ))} + {loading ? ( +

+ Loading authors… +

+ ) : visibleCandidates.length === 0 ? ( +

+ {failed ? "Couldn’t load authors." : "No authors found."} +

+ ) : null} + {failed ? ( + + ) : null} + {directoryQuery.hasNextPage ? ( + + ) : null} +
+
+ ); +} + +function AuthorOption({ + active, + candidate, + disabled, + id, + onSelect, + optionRef, + selected, +}: { + active: boolean; + candidate: WorkflowAuthorCandidate; + disabled?: boolean; + id: string; + onSelect: () => void; + optionRef: (node: HTMLButtonElement | null) => void; + selected: boolean; +}) { + const label = resolveUserLabel({ + fallbackName: candidate.displayName, + profiles: { + [candidate.pubkey]: { + displayName: candidate.displayName, + avatarUrl: candidate.avatarUrl, + nip05Handle: candidate.nip05Handle, + ownerPubkey: candidate.ownerPubkey, + isAgent: candidate.isAgent, + }, + }, + pubkey: candidate.pubkey, + }); + return ( + + ); +} diff --git a/desktop/src/features/workflows/ui/WorkflowCard.tsx b/desktop/src/features/workflows/ui/WorkflowCard.tsx index 48ce8d2db6..8556424f87 100644 --- a/desktop/src/features/workflows/ui/WorkflowCard.tsx +++ b/desktop/src/features/workflows/ui/WorkflowCard.tsx @@ -24,14 +24,20 @@ import { getWorkflowActionTiles, getWorkflowCardLabel, getWorkflowTriggerEmoji, + getWorkflowTriggerConfig, getWorkflowTriggerType, } from "./workflowDefinition"; import { StatusEmoji } from "@/features/user-status/ui/StatusEmoji"; +import type { WorkflowCardAuthorPresentation } from "./useWorkflowListAuthorPresentations"; +import type { WorkflowMessagePresentation } from "./useWorkflowListMessagePresentations"; +import { workflowTriggerDescription } from "./workflowTriggerDescription"; type WorkflowCardProps = { workflow: Workflow; + authorPresentation?: WorkflowCardAuthorPresentation; channelName?: string; isTogglingEnabled?: boolean; + messagePresentation?: WorkflowMessagePresentation; onView: (workflow: Workflow) => void; onTrigger: (workflowId: string) => void; onToggleEnabled: (workflow: Workflow) => void; @@ -189,8 +195,10 @@ function ActionTileStack({ export function WorkflowCard({ workflow, + authorPresentation, channelName, isTogglingEnabled = false, + messagePresentation, onView, onTrigger, onToggleEnabled, @@ -201,7 +209,17 @@ export function WorkflowCard({ const [triggerAnimationSequence, setTriggerAnimationSequence] = React.useState(0); const isEnabled = getWorkflowEnabled(workflow.definition); - const cardLabel = getWorkflowCardLabel(workflow.definition); + const configuredTrigger = getWorkflowTriggerConfig(workflow.definition); + const cardLabel = getWorkflowCardLabel(workflow.definition, { + triggerDescription: configuredTrigger + ? workflowTriggerDescription(configuredTrigger, { + authorLabel: authorPresentation?.label ?? undefined, + authorLoading: authorPresentation?.loading, + messageLabel: messagePresentation?.messageLabel ?? undefined, + messageLoading: messagePresentation?.messageLoading, + }) + : undefined, + }); const triggerType = getWorkflowTriggerType(workflow.definition); const actionTiles = getWorkflowActionTiles(workflow.definition); const triggerEmoji = getWorkflowTriggerEmoji(workflow.definition); diff --git a/desktop/src/features/workflows/ui/WorkflowDialog.tsx b/desktop/src/features/workflows/ui/WorkflowDialog.tsx index 3f8655a3aa..198e0fe91c 100644 --- a/desktop/src/features/workflows/ui/WorkflowDialog.tsx +++ b/desktop/src/features/workflows/ui/WorkflowDialog.tsx @@ -557,6 +557,13 @@ export function WorkflowDialog({ { + if ( + event.target instanceof HTMLElement && + event.target.closest("[data-workflow-filter-picker-search]") + ) { + event.preventDefault(); + return; + } if (formBuilderRef.current?.closeInspector()) { event.preventDefault(); event.stopPropagation(); diff --git a/desktop/src/features/workflows/ui/WorkflowFormBuilder.tsx b/desktop/src/features/workflows/ui/WorkflowFormBuilder.tsx index 58e4b4a960..8ac97402aa 100644 --- a/desktop/src/features/workflows/ui/WorkflowFormBuilder.tsx +++ b/desktop/src/features/workflows/ui/WorkflowFormBuilder.tsx @@ -30,8 +30,10 @@ import { Switch } from "@/shared/ui/switch"; import { Textarea } from "@/shared/ui/textarea"; import { reactionConditionValue } from "./workflowReactionCondition"; import { WorkflowTriggerConditions } from "./WorkflowTriggerConditions"; +import { WorkflowRichTriggerDescription } from "./WorkflowRichTriggerDescription"; +import { useWorkflowTriggerPresentation } from "./useWorkflowTriggerPresentation"; +import { compactWorkflowTriggerDescription } from "./workflowTriggerDescription"; import { workflowStepDescription } from "./workflowStepDescription"; -import { workflowTriggerDescription } from "./workflowTriggerDescription"; import { WorkflowScheduleFields } from "./WorkflowScheduleFields"; import { WorkflowStepCard } from "./WorkflowStepCard"; import { @@ -67,12 +69,14 @@ function TriggerConfigFields({ trigger, onConditionDraftsChange, onUpdate, + workflowChannelId, }: { conditionDrafts: ParsedConditionExpression[] | null; disabled?: boolean; trigger: TriggerConfig; onConditionDraftsChange: (drafts: ParsedConditionExpression[] | null) => void; onUpdate: (trigger: TriggerConfig) => void; + workflowChannelId?: string | null; }) { switch (trigger.on) { case "message_posted": @@ -94,6 +98,7 @@ function TriggerConfigFields({ } triggerType={trigger.on} value={reactionConditionValue(trigger)} + workflowChannelId={workflowChannelId} /> ); case "webhook": @@ -220,7 +225,7 @@ function WorkflowNode({ terminal, title, }: { - description: string; + description: React.ReactNode; disabled?: boolean; icon?: React.ReactNode; label: string; @@ -614,10 +619,23 @@ export const WorkflowFormBuilder = React.forwardRef< ) ?.value.trim(); }, [formState.trigger]); - const triggerDescription = workflowTriggerDescription(formState.trigger); - const visibleTriggerDescription = triggerEmoji - ? "Reaction added" - : triggerDescription; + const triggerPresentation = useWorkflowTriggerPresentation( + formState.trigger, + workflowChannelId, + ); + const triggerDescription = triggerPresentation.description; + const compactTriggerDescription = compactWorkflowTriggerDescription( + triggerDescription, + triggerEmoji, + ); + const visibleTriggerDescription = ( + + ); const TriggerIcon = { diff_posted: GitPullRequest, message_posted: MessageSquare, @@ -889,6 +907,7 @@ export const WorkflowFormBuilder = React.forwardRef< > {selectedNode.type === "trigger" ? ( -
+
) : selectedStep ? ( diff --git a/desktop/src/features/workflows/ui/WorkflowMessagePicker.tsx b/desktop/src/features/workflows/ui/WorkflowMessagePicker.tsx new file mode 100644 index 0000000000..6639d85b0f --- /dev/null +++ b/desktop/src/features/workflows/ui/WorkflowMessagePicker.tsx @@ -0,0 +1,469 @@ +import { useInfiniteQuery, useQueries, useQuery } from "@tanstack/react-query"; +import { Check, LoaderCircle, Search } from "lucide-react"; +import * as React from "react"; + +import { parseChannelWindowResponse } from "@/features/messages/lib/channelWindowResponse"; +import { useUsersBatchQuery } from "@/features/profile/hooks"; +import { + resolveUserLabel, + type UserProfileLookup, +} from "@/features/profile/lib/identity"; +import { useSearchMessagesQuery } from "@/features/search/hooks"; +import { getChannelWindowEvents } from "@/shared/api/channelWindow"; +import { getEventById } from "@/shared/api/tauri"; +import type { ChannelPageCursor } from "@/shared/api/types"; +import { cn } from "@/shared/lib/cn"; +import { Input } from "@/shared/ui/input"; +import { UserAvatar } from "@/shared/ui/UserAvatar"; +import { + mergeMessageCandidateSources, + normalizeMessageEventId, + type WorkflowMessageCandidate, + validatedWorkflowMessageCandidate, + validateWorkflowMessageSearchResults, +} from "./workflowMessageCandidates"; + +const PAGE_SIZE = 25; + +function truncateContent(content: string | null): string { + const normalized = content?.trim().replaceAll(/\s+/g, " ") ?? ""; + if (!normalized) return "No message body"; + return normalized.length > 120 + ? `${normalized.slice(0, 117)}...` + : normalized; +} + +function formatTimestamp(unixSeconds: number | null): string | null { + if (unixSeconds === null) return null; + return new Intl.DateTimeFormat(undefined, { + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + }).format(new Date(unixSeconds * 1_000)); +} + +export function WorkflowMessagePicker({ + channelId, + disabled, + id, + onChange, + onEscape, + value, +}: { + channelId?: string | null; + disabled?: boolean; + id: string; + onChange: (messageId: string) => void; + onEscape?: () => void; + value: string; +}) { + const optionRefs = React.useRef(new Map()); + const [query, setQuery] = React.useState(""); + const [activeIndex, setActiveIndex] = React.useState(null); + const trimmedQuery = query.trim(); + const deferredQuery = React.useDeferredValue(trimmedQuery); + const normalizedQuery = deferredQuery.toLowerCase(); + const selectedId = normalizeMessageEventId(value); + const directId = normalizeMessageEventId(query); + const lookupId = directId ?? selectedId; + + const historyQuery = useInfiniteQuery({ + enabled: Boolean(channelId), + initialPageParam: null as ChannelPageCursor | null, + queryKey: ["workflow-message-picker", channelId], + queryFn: async ({ pageParam }) => { + if (!channelId) throw new Error("Choose a channel first."); + return parseChannelWindowResponse( + await getChannelWindowEvents(channelId, pageParam, PAGE_SIZE), + channelId, + pageParam, + ); + }, + getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined, + staleTime: 30_000, + }); + const searchQuery = useSearchMessagesQuery(deferredQuery, { + channelId: channelId ?? undefined, + enabled: Boolean(channelId && normalizedQuery && !directId), + limit: 30, + minimumQueryLength: 1, + }); + const exactQuery = useQuery({ + enabled: Boolean(channelId && lookupId), + queryKey: ["workflow-message-picker-exact", channelId, lookupId], + queryFn: () => getEventById(lookupId ?? ""), + retry: false, + staleTime: 60_000, + }); + + const selectedFallback = selectedId + ? [{ id: selectedId, pubkey: null, content: null, createdAt: null }] + : []; + const directFallback = directId + ? [{ id: directId, pubkey: null, content: null, createdAt: null }] + : []; + const historyCandidates = React.useMemo( + () => + (historyQuery.data?.pages ?? []).flatMap((page) => + page.rows.flatMap(({ event }) => { + const candidate = channelId + ? validatedWorkflowMessageCandidate(event, { channelId }) + : null; + return candidate ? [candidate] : []; + }), + ), + [channelId, historyQuery.data?.pages], + ); + const searchHitIds = React.useMemo( + () => [ + ...new Set( + (searchQuery.data?.hits ?? []).flatMap((hit) => { + const eventId = normalizeMessageEventId(hit.eventId); + return eventId ? [eventId] : []; + }), + ), + ], + [searchQuery.data?.hits], + ); + const searchEventQueries = useQueries({ + queries: searchHitIds.map((eventId) => ({ + enabled: Boolean(channelId), + queryKey: ["workflow-message-picker-search-event", channelId, eventId], + queryFn: () => getEventById(eventId), + retry: false, + staleTime: 60_000, + })), + }); + const searchCandidates = validateWorkflowMessageSearchResults( + searchHitIds.map((requestedId, index) => ({ + requestedId, + event: searchEventQueries[index]?.data, + })), + channelId ?? "", + ); + const exactCandidate = React.useMemo(() => { + if (!channelId || !lookupId) return null; + return validatedWorkflowMessageCandidate(exactQuery.data, { + channelId, + requestedId: lookupId, + }); + }, [channelId, exactQuery.data, lookupId]); + const allCandidates = React.useMemo(() => { + // Preserve the relay-provided history/search order. Exact lookups and raw-ID + // fallbacks only fill gaps; selecting an existing row must not move it. + return mergeMessageCandidateSources([ + historyCandidates, + searchCandidates, + exactCandidate ? [exactCandidate] : [], + selectedFallback, + directFallback, + ]); + }, [ + directFallback, + exactCandidate, + historyCandidates, + searchCandidates, + selectedFallback, + ]); + const visibleCandidates = React.useMemo(() => { + if (directId) return allCandidates.filter(({ id }) => id === directId); + if (!normalizedQuery) return allCandidates; + return allCandidates.filter( + (candidate) => + candidate.id.includes(normalizedQuery) || + candidate.content?.toLowerCase().includes(normalizedQuery), + ); + }, [allCandidates, directId, normalizedQuery]); + const profilePubkeys = React.useMemo( + () => [ + ...new Set( + visibleCandidates.flatMap(({ pubkey }) => (pubkey ? [pubkey] : [])), + ), + ], + [visibleCandidates], + ); + const profilesQuery = useUsersBatchQuery(profilePubkeys); + const listId = `${id}-list`; + + React.useEffect(() => { + if (activeIndex !== null && activeIndex >= visibleCandidates.length) { + setActiveIndex( + visibleCandidates.length > 0 ? visibleCandidates.length - 1 : null, + ); + } + }, [activeIndex, visibleCandidates.length]); + React.useEffect(() => { + if (activeIndex === null) return; + const candidate = visibleCandidates[activeIndex]; + if (!candidate) return; + optionRefs.current + .get(candidate.id) + ?.scrollIntoView({ block: "nearest", inline: "nearest" }); + }, [activeIndex, visibleCandidates]); + + const searchEventsFetching = searchEventQueries.some( + ({ isFetching }) => isFetching, + ); + const searchEventsFailed = searchEventQueries.some(({ isError }) => isError); + const loading = + (historyQuery.isLoading || + searchQuery.isFetching || + searchEventsFetching || + exactQuery.isFetching) && + visibleCandidates.length === 0; + const failed = + historyQuery.isError || + searchQuery.isError || + searchEventsFailed || + exactQuery.isError; + const invalidDirectResult = Boolean( + directId && lookupId === directId && exactQuery.data && !exactCandidate, + ); + + return ( +
+
+ + { + setQuery(event.target.value); + setActiveIndex(null); + }} + onKeyDown={(event) => { + const currentQuery = event.currentTarget.value.trim(); + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); + if (visibleCandidates.length > 0) { + setActiveIndex((current) => { + const startingIndex = current ?? -1; + return ( + (startingIndex + + (event.key === "ArrowDown" ? 1 : -1) + + visibleCandidates.length) % + visibleCandidates.length + ); + }); + } + } else if (event.key === "Enter") { + const currentDirectId = normalizeMessageEventId(currentQuery); + if (currentQuery !== deferredQuery && !currentDirectId) return; + const candidate = currentDirectId + ? allCandidates.find(({ id }) => id === currentDirectId) + : visibleCandidates[activeIndex ?? 0]; + if (!candidate) return; + event.preventDefault(); + if (invalidDirectResult) return; + onChange(candidate.id === selectedId ? "" : candidate.id); + } else if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + if (query) { + setQuery(""); + setActiveIndex(null); + } else { + onEscape?.(); + } + } + }} + placeholder={ + channelId + ? "Search messages or paste a message ID…" + : "Choose a channel first" + } + role="combobox" + spellCheck={false} + value={query} + /> + {historyQuery.isFetching || + searchQuery.isFetching || + searchEventsFetching || + exactQuery.isFetching ? ( + + ) : null} +
+ {invalidDirectResult ? ( +

+ That message is not available in this channel. +

+ ) : null} +
{ + const list = event.currentTarget; + if ( + !normalizedQuery && + list.scrollHeight - list.scrollTop - list.clientHeight < 64 && + historyQuery.hasNextPage && + !historyQuery.isFetchingNextPage + ) { + void historyQuery.fetchNextPage(); + } + }} + role="listbox" + > + {visibleCandidates.map((candidate, index) => ( + { + setActiveIndex(null); + if (!invalidDirectResult) { + onChange(candidate.id === selectedId ? "" : candidate.id); + } + }} + optionRef={(node) => { + if (node) optionRefs.current.set(candidate.id, node); + else optionRefs.current.delete(candidate.id); + }} + profiles={profilesQuery.data?.profiles} + selected={candidate.id === selectedId} + /> + ))} + {loading ? ( +

+ Loading messages… +

+ ) : visibleCandidates.length === 0 ? ( +

+ {failed + ? "Couldn’t load messages." + : normalizedQuery + ? "No messages found." + : "No messages yet."} +

+ ) : null} + {failed ? ( + + ) : null} + {!normalizedQuery && historyQuery.hasNextPage ? ( + + ) : null} +
+
+ ); +} + +function MessageOption({ + active, + candidate, + disabled, + id, + onSelect, + optionRef, + profiles, + selected, +}: { + active: boolean; + candidate: WorkflowMessageCandidate; + disabled?: boolean; + id: string; + onSelect: () => void; + optionRef: (node: HTMLButtonElement | null) => void; + profiles?: UserProfileLookup; + selected: boolean; +}) { + const author = candidate.pubkey + ? resolveUserLabel({ profiles, pubkey: candidate.pubkey }) + : "Selected message"; + const profile = candidate.pubkey + ? profiles?.[candidate.pubkey.toLowerCase()] + : undefined; + const timestamp = formatTimestamp(candidate.createdAt); + return ( + + ); +} diff --git a/desktop/src/features/workflows/ui/WorkflowRichTriggerDescription.tsx b/desktop/src/features/workflows/ui/WorkflowRichTriggerDescription.tsx new file mode 100644 index 0000000000..50eb5ef672 --- /dev/null +++ b/desktop/src/features/workflows/ui/WorkflowRichTriggerDescription.tsx @@ -0,0 +1,53 @@ +import { LoaderCircle } from "lucide-react"; + +import { UserAvatar } from "@/shared/ui/UserAvatar"; +import { splitWorkflowAuthorDescription } from "./workflowTriggerDescription"; + +export function WorkflowRichTriggerDescription({ + avatarUrl, + description, + label, + loading, +}: { + avatarUrl?: string | null; + description: string; + label?: string | null; + loading?: boolean; +}) { + if (loading) { + return ( + + {description} + + + ); + } + + const segments = label + ? splitWorkflowAuthorDescription(description, label) + : null; + if (!label || !segments) return description; + + const { prefix, suffix } = segments; + return ( + + {prefix ? {prefix} : null} + + + {label} + {suffix ? ` ${suffix}` : ""} + + + ); +} diff --git a/desktop/src/features/workflows/ui/WorkflowTriggerConditions.tsx b/desktop/src/features/workflows/ui/WorkflowTriggerConditions.tsx index 39caec253a..78f6e30606 100644 --- a/desktop/src/features/workflows/ui/WorkflowTriggerConditions.tsx +++ b/desktop/src/features/workflows/ui/WorkflowTriggerConditions.tsx @@ -3,8 +3,12 @@ import * as React from "react"; import { cn } from "@/shared/lib/cn"; import { Input } from "@/shared/ui/input"; +import { UserAvatar } from "@/shared/ui/UserAvatar"; import { Tabs, TabsList, TabsTrigger } from "@/shared/ui/tabs"; +import { WorkflowAuthorPicker } from "./WorkflowAuthorPicker"; import { WorkflowEmojiField } from "./WorkflowEmojiField"; +import { WorkflowMessagePicker } from "./WorkflowMessagePicker"; +import { useWorkflowTriggerPresentation } from "./useWorkflowTriggerPresentation"; import { FieldLabel } from "./workflowFormPrimitives"; import { buildConditionExpressions, @@ -45,12 +49,81 @@ function compact(value: string): string { : `${trimmed.slice(0, 11)}…${trimmed.slice(-6)}`; } +function fieldUsesFullHeightPicker(field: string): boolean { + return field === "trigger_author" || field === "trigger_message_id"; +} + function fieldPlaceholder(field: string): string { if (field === "trigger_author") return "64-character hex pubkey"; if (field === "trigger_message_id") return "64-character hex event ID"; return "e.g. deploy"; } +function ExclusionStrike() { + return ( +
) : ( -
+
{fields.map((field) => { const existing = conditions.find( (condition) => condition.field === field.value, @@ -179,8 +279,32 @@ export function WorkflowTriggerConditions({ const summary = existing ? `${OPERATOR_LABELS[condition.operator]}${condition.value ? ` ${compact(condition.value)}` : ""}` : "Any"; + const authorSummary = + existing && + field.value === "trigger_author" && + triggerPresentation.pubkey && + triggerPresentation.label + ? triggerPresentation.label + : null; + const messageSummary = + existing && + field.value === "trigger_message_id" && + triggerPresentation.messageId && + triggerPresentation.messageLabel + ? triggerPresentation.messageLabel + .trim() + .replaceAll(/\s+/g, " ") + : null; return ( -
+
{expanded ? ( -
+
Match
@@ -258,6 +417,51 @@ export function WorkflowTriggerConditions({ } value={condition.value} /> + ) : field.value === "trigger_author" ? ( + collapsePicker(field.value)} + onChange={(pubkey) => + updateConditions( + pubkey + ? [ + ...conditions.filter( + (item) => item.field !== field.value, + ), + { ...condition, value: pubkey }, + ] + : conditions.filter( + (item) => item.field !== field.value, + ), + ) + } + value={condition.value} + /> + ) : field.value === "trigger_message_id" ? ( + collapsePicker(field.value)} + onChange={(messageId) => + updateConditions( + messageId + ? [ + ...conditions.filter( + (item) => item.field !== field.value, + ), + { ...condition, value: messageId }, + ] + : conditions.filter( + (item) => item.field !== field.value, + ), + ) + } + value={condition.value} + /> ) : (
) ) : null} - {existing ? ( + {existing && !fieldUsesFullHeightPicker(field.value) ? (