mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
Prepared by Brain on Wes’s behalf. ## Summary Reduce startup request amplification and let quota-refused background work recover without changing relay quotas or bypassing the existing Send gate. - Coalesce nest regeneration into one worker plus the latest pending generation. Keep the stale-write fence; bound the archive read so an old workspace cannot strand newer work. - Claim pending channel subscriptions before awaiting setup; cancel removed/unmounted entries and preserve still-owned subscriptions across reconnect handoff. - Recheck extended cooldown deadlines before retry dispatch; distinguish an explicit zero-second hint from a missing hint. - Recover native finite/unread queries within their original caller deadline and a three-retry budget, preserving verified unique events, complete filters and terminal errors. - Pace renderer initial/live-CLOSED REQs at one per 250ms: visible channel and explicitly interactive TTS/read-state/observer owners first, then live-only auxiliaries, then background history. Publication and finite queries bypass this queue. Reconnect replay now promotes explicit interactive owners alongside the visible channel with stable registration-order ties; its existing capped batches and cooldown remain intact. **Scope at `867495426`:** 39 source/test files, including 15 production files (+665/-235) and 24 test/fixture files. The diagnostic recorder, HTTP instrumentation, trace launcher and raw captures are deliberately excluded. No profile reset, grouping, quota increase or new global scheduler. ## Before / after evidence These are observations from instrumented, human-operated development Tauri/Vite runs against a production relay, plus explicitly identified controlled regressions—not a packaged-release startup benchmark. | Measurement | Before | After | Evidence boundary | | --- | --- | --- | --- | | Archive snapshot requests (kind 13535) | 290 | 3 | Recorder-only baseline → nest-only intermediate candidate; unequal 67.436s / 39.273s captures and hydration differences | | Archive responses: HTTP 200 / 429 | 277 / 13 | 3 / 0 | Same baseline/nest-only captures; not a claim that all quota pressure disappeared | | Successful archive responses’ advertised content-length sum | 21,208,505 bytes | 229,695 bytes | Header values, not actual transferred bytes | | 154-channel StrictMode replay | 308 REQs | 154 REQs | Controlled real React hook → real session → mocked Tauri transport regression | | Add one channel while 154 setups are pending | 309 REQs | 155 REQs | Same production-boundary regression; ordinary mount remains 154 → 154 | | Broad renderer request burst / spacing | 110 broad REQs within 10.766ms in pre-drain capture | 250.061ms minimum / 252.131ms median between broad REQ writes in final longer capture | Different attended runs; pacing rather than a universal request-rate cap | | Native unread query outcomes | Baseline: 8 EOSE / 146 quota CLOSED out of 154 queries | Final longer run: all 156 observed queries reach EOSE; eight refused queries each recover after two refusals | Different runs/workloads; query completion, not badge rendering | ### Timing metrics | Observation | Measured value | | --- | ---: | | Baseline’s two accepted chat EVENT socket writes → positive OK | 173.340ms / 85.556ms | | Nest-only intermediate candidate’s two accepted writes → positive OK | 277.854ms / 78.775ms | | Final candidate, short run, accepted chat writes → positive OK | 80.636ms / 77.506ms | | Final candidate, longer run, accepted chat writes → positive OK | 120.712ms / 86.895ms | | Last initial EOSE among 163 observed broad channel registrations, longer run | 64.550s after trace start | | Last EOSE among 156 observed native unread queries, longer run | 73.972s after trace start | | Native retry waits after 3s then 0s hints, longer run | 3000.7–3002.8ms, then 2001.5–2002.6ms | | Renderer finite-query retry after a 2s hint, longer run | 2061.365ms | Both Sends in each final run were accepted, with no recorded negative OK. Every quota-refused query in the longer run subsequently completed the same query. Its two Sends happened early (17.878s and 21.655s), not near the end. These small samples do not support a percentage latency improvement. **Tradeoffs and limits** - 296 background subscriptions imply about 74s of paced registration before extra cooldowns/high-priority work. The longer capture observed 163 registrations; it did not independently enumerate the expected membership set or record a queue-empty marker. - This is not a global 4-REQ/s cap: finite queries, native requests and reconnect replay are outside the drain and still share relay quota. Quota refusals recover rather than disappear. - Socket-write → OK starts after composer submission and any publisher gate wait. No click-to-visible, launch-to-usable or badge-paint latency is claimed. - Native EOSE is not proof of command return, classification, React state application or visible unread badges. Existing per-channel kinds, since floors, limits, h-less routing, unread lease/scope guard and eight-query concurrency remain intact. - The attended measurements belong to the instrumented candidate, not a fresh release run of this fixes-only commit. At the initial packaging checkpoint (`1bf3d060`), eighteen of twenty files were byte-identical; the other two removed diagnostic gate calls and isolated the nest test’s temporary paths. The subsequent interactive priority/reconnect and readiness fixes have controlled hook/session/browser evidence, not another attended voice/performance run. ### Evidence provenance (captures retained locally, not uploaded) | Capture | SHA-256 | | --- | --- | | Baseline `STARTUP_20260921T194814Z_98811.jsonl` | `f4f0a89ad9aea91084bd6a7432510488166de4cbc906600d88c26d557f380994` | | Nest-only `STARTUP_20260921T202610Z_28642.jsonl` | `ce517b02a3f717c36d96b36bb8616e8fa80b03b12b356bacfd40475925ea3f3e` | | Final short `STARTUP_20260922T013628Z_13506.jsonl` | `bfea6f3cf80cd7b7e4e676632a3df2f16271fade5bfa0edec72b7bcbbe7839ff` | | Final longer `STARTUP_20260922T014637Z_15846.jsonl` | `f4abece613d108c4c2fe3cb808e633a0486bdc9993ca92323822dc00c3fae6ec` | Final instrumented build fingerprint: `b0b4fc27d793c3e643f4e10289b5afdb4620ee2e13a8b33fa0595dd3417fd5ca`. All observed dropped-record counters in these final captures were zero. Source manifests and offline correlation analyses are retained locally; no raw captures, profile data or agent sessions are part of this PR. ## Validation Current head: `86749542657a60abdfe82eed5cc576d3e162fe5d`, based on `77729abfb692b25a0f4ec4a69add86af2e32c0dd`. Review follow-ups: - `8842dbd8`: explicit interactive TTS admission using the existing main-window owner, independent of companion/timeline selection. Real-hook/session/IPC coverage with 296 cold owners proves initial and CLOSED priority, unchanged filters/cooldown/pacing, background progress and deduplicated speech. - `8cb088106`: reconnect preserves interactive priority even with no visible channel. Stable ordering among foreground ties; real hook/session reconnect regressions cover cooldown, capped batching, all 297 owners, deduplication and unmount cancellation. Independent reviewer mutation restored the prior replay implementation, failed both reconnect rows, then passed the restored candidate. - `68e76d7c`: read-state and observer reuse interactive priority. Stop and ModelPicker wait on the existing observer owner inside send callbacks, after installing result listeners/deadlines. No new owner, timer or scheduler; inherited CLOSED/fallback/error semantics remain, rather than a new strict EOSE guarantee. The real Stop panel browser probe holds observer IPC across the click and checks observer-before-control order and correlated outcome. ModelPicker component ordering is source-reviewed only. - Mock live admission now replays matching stored history with per-filter time/limit constraints, deduplication, untagged auxiliary channel fallback and authoritative explicit h-tags. Kind-specific fixture admission waits and retry-resolving hover actions fix startup-dependent test setup without weakening event/badge assertions. - `48e9c0dad` and `867495426`: steady-state scroll-prepend setup observes live admission, subsequent head dispatch, successful/idle query completion and initial bottom geometry. Phase-2 genuine-growth and ≤32px anchor assertions are unchanged. This isolates steady-state prepending: it **does not fix or certify production early-scroll/head-reset behavior**. Current validation: - Normal push hooks at `867495426`: **6,582/6,582 renderer tests**, zero failed/skipped/cancelled; lint/static checks, typecheck and differential file-size gate passed. Native source is unchanged from the earlier checkpoint; no new native run is claimed for these renderer/test follow-ups. - E2E build passed at `48e9c0dad` plus the exact subsequently committed test-only delta (spec blob `469be2eed868c677ba80b859cc871208000fee60`). The completed affected-smoke run passed **153/153** across agent-control, badge, entity links, messaging, profile status and scroll history; the full scroll file additionally passed twice (**36/36**). No full CI-smoke pass is claimed from this six-file local run. - Pinky independently reviewed production and test follow-ups, including the final scroll spec blob `469be2eed868c677ba80b859cc871208000fee60`, with no blocking finding. Review is source evidence, not an independent test run. - **Not merge-ready:** new-head required CI must complete, exact-range security review requires authorization, and GitHub currently reports REVIEW_REQUIRED; fresh exact-head reviewer approval is still needed. No approval, dismissal or merge performed. No new packaged/native audio, launch-to-usable or badge-paint observation is claimed. Initial fixes-only checkpoint validation (`1bf3d06024d284a63326fdd353baced0842aeb81`): - Pre-commit formatting hooks passed; worktree clean. - Renderer package hooks: 6,570 tests passed, zero failed/skipped/cancelled; lint/static checks, TypeScript and differential file-size gate passed. - Native package hook passed: default and mesh-enabled all-target Clippy, then the complete native workspace test suite. App library: 3,222 passed / 0 failed / 19 ignored; terminal/integration suites passed. The real nest trigger/stalled-body test passed on macOS. - Independent whole-change source review: no blocking findings at this commit; all 20 file hashes matched the committed blobs and review/validation manifests. - Regression coverage includes real hook/session cancellation, StrictMode/membership re-entry, reconnect ownership, extended/zero cooldowns, burst pacing, auxiliary readiness (including EOSE before IPC settles), native socket refusal/retry/deadline/cancellation, unread fetch/classification and real nest trigger/HTTP/file persistence. - Earlier isolated renderer mutations that started readiness before enqueue or removed auxiliary priority each failed the real presence regression; restored controls passed. No native mutation claim. - Nest fixture uses explicit app-data/nest paths instead of assuming Windows known-folder APIs obey HOME/APPDATA. Windows runtime execution is not claimed; CI/build results remain separate. Originating conversation: buzz://message?channel=46ced308-71df-495d-a144-4ebf08334703&id=bc43c3422a3b0b2141268d0fa149b898421c824992b662aed8b73c4eee50404f No approval or merge recommendation is implied by opening this PR. --------- Signed-off-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz> Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
685 lines
22 KiB
Rust
685 lines
22 KiB
Rust
//! Batched native unread catch-up.
|
|
//!
|
|
//! Native unread catch-up consumes notification membership from the observed-
|
|
//! unread SQLite store rather than serializing renderer-owned sets on every
|
|
//! request. Rust performs every channel REQ over the shared authenticated
|
|
//! session, then classifies the complete successful batch in two passes so a
|
|
//! root learned anywhere in pass one is visible everywhere in pass two.
|
|
|
|
use std::{collections::HashSet, time::Duration};
|
|
|
|
use buzz_core_pkg::kind::{
|
|
KIND_FORUM_COMMENT, KIND_FORUM_POST, KIND_HUDDLE_STARTED, KIND_STREAM_MESSAGE,
|
|
KIND_STREAM_MESSAGE_V2,
|
|
};
|
|
use nostr::Event;
|
|
use serde::{Deserialize, Serialize};
|
|
use tauri::{AppHandle, State};
|
|
use tokio::{sync::Semaphore, task::JoinSet};
|
|
|
|
use crate::{app_state::AppState, native_relay_client::NativeRelayClient};
|
|
|
|
const CATCH_UP_LIMIT: usize = 1_000;
|
|
const ACTIVITY_LIMIT: usize = 100;
|
|
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
|
|
|
|
#[derive(Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub(crate) struct UnreadCatchUpRequest {
|
|
channels: Vec<CatchUpChannel>,
|
|
self_pubkey: String,
|
|
muted_channel_ids: HashSet<String>,
|
|
}
|
|
|
|
#[derive(Clone, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct CatchUpChannel {
|
|
id: String,
|
|
#[serde(rename = "type")]
|
|
channel_type: String,
|
|
name: String,
|
|
read_at: Option<u64>,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub(crate) struct UnreadCatchUpResponse {
|
|
channels: Vec<ChannelResult>,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
#[serde(
|
|
tag = "status",
|
|
rename_all = "camelCase",
|
|
rename_all_fields = "camelCase"
|
|
)]
|
|
enum ChannelResult {
|
|
Success {
|
|
channel_id: String,
|
|
observed_events: Vec<ObservedUnreadEvent>,
|
|
max_trigger: u64,
|
|
activity_rows: Vec<ActivityRow>,
|
|
discovered: DiscoveredRoots,
|
|
},
|
|
Error {
|
|
channel_id: String,
|
|
error: String,
|
|
},
|
|
}
|
|
|
|
#[derive(Clone, PartialEq, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct ObservedUnreadEvent {
|
|
id: String,
|
|
created_at: u64,
|
|
root_id: Option<String>,
|
|
high_priority: bool,
|
|
counts_toward_badge: bool,
|
|
counts_toward_app_badge: bool,
|
|
}
|
|
|
|
#[derive(Clone, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct ActivityRow {
|
|
id: String,
|
|
kind: u16,
|
|
pubkey: String,
|
|
content: String,
|
|
created_at: u64,
|
|
channel_id: String,
|
|
channel_name: String,
|
|
tags: Vec<Vec<String>>,
|
|
}
|
|
|
|
#[derive(Default, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct DiscoveredRoots {
|
|
participated: Vec<String>,
|
|
authored: Vec<String>,
|
|
mentioned: Vec<String>,
|
|
}
|
|
|
|
struct FetchedChannel {
|
|
order: usize,
|
|
channel: CatchUpChannel,
|
|
events: Vec<EventView>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct EventView {
|
|
id: String,
|
|
kind: u16,
|
|
pubkey: String,
|
|
content: String,
|
|
created_at: u64,
|
|
tags: Vec<Vec<String>>,
|
|
}
|
|
|
|
impl From<Event> for EventView {
|
|
fn from(event: Event) -> Self {
|
|
Self {
|
|
id: event.id.to_hex(),
|
|
kind: event.kind.as_u16(),
|
|
pubkey: event.pubkey.to_hex(),
|
|
content: event.content,
|
|
created_at: event.created_at.as_secs(),
|
|
tags: event
|
|
.tags
|
|
.iter()
|
|
.map(|tag| tag.as_slice().to_vec())
|
|
.collect(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub(crate) async fn unread_catch_up(
|
|
request: UnreadCatchUpRequest,
|
|
state: State<'_, AppState>,
|
|
relay_client: State<'_, NativeRelayClient>,
|
|
app: AppHandle,
|
|
) -> Result<UnreadCatchUpResponse, String> {
|
|
let keys = state.signing_keys()?;
|
|
let owner = keys.public_key().to_hex();
|
|
if !owner.eq_ignore_ascii_case(&request.self_pubkey) {
|
|
return Err("unread catch-up identity does not match active scope".to_string());
|
|
}
|
|
let relay_url = crate::relay::relay_ws_url_with_override(&state);
|
|
// The lease must outlive every task below: when the leased session is
|
|
// private (a scope switch landed mid-command), dropping the lease shuts
|
|
// that session down, and a `handle()` clone still held by a running fetch
|
|
// would then be reading a cancelled socket. The `join_next` drain ends
|
|
// before this binding does, so that holds today — keep it that way, and in
|
|
// particular do not move the lease into a task or narrow its scope.
|
|
let session = relay_client.session(relay_url.clone(), keys).await;
|
|
|
|
let (fetched, failures) = fetch_channels(session.handle(), &request).await?;
|
|
|
|
let current_keys = state.signing_keys()?;
|
|
if current_keys.public_key().to_hex() != owner
|
|
|| crate::relay::relay_ws_url_with_override(&state) != relay_url
|
|
{
|
|
return Err("unread catch-up scope changed while fetching".to_string());
|
|
}
|
|
|
|
let membership = crate::observed_unread::load_membership(
|
|
&app,
|
|
&crate::observed_unread::ObservedUnreadScope {
|
|
pubkey: owner,
|
|
relay_url,
|
|
},
|
|
)?;
|
|
let mut channels = classify_batch(&request, fetched, &membership);
|
|
channels.extend(failures);
|
|
Ok(UnreadCatchUpResponse { channels })
|
|
}
|
|
|
|
// Shared production boundary: original per-channel filters, finite requests,
|
|
// and error partitioning. Scope/membership checks remain in the command above.
|
|
async fn fetch_channels(
|
|
session: std::sync::Arc<crate::native_relay_client::RelaySession>,
|
|
request: &UnreadCatchUpRequest,
|
|
) -> Result<(Vec<FetchedChannel>, Vec<ChannelResult>), String> {
|
|
let concurrency = std::sync::Arc::new(Semaphore::new(8));
|
|
let mut pending = JoinSet::new();
|
|
// One command replaces N renderer invokes while the shared session still
|
|
// multiplexes bounded finite REQs on one authenticated socket.
|
|
for (order, channel) in request.channels.iter().cloned().enumerate() {
|
|
let permit = concurrency
|
|
.clone()
|
|
.acquire_owned()
|
|
.await
|
|
.map_err(|error| error.to_string())?;
|
|
let session = std::sync::Arc::clone(&session);
|
|
pending.spawn(async move {
|
|
let _permit = permit;
|
|
let kinds: &[u32] = if channel.channel_type == "dm" {
|
|
&[
|
|
KIND_STREAM_MESSAGE,
|
|
KIND_STREAM_MESSAGE_V2,
|
|
KIND_FORUM_POST,
|
|
KIND_FORUM_COMMENT,
|
|
KIND_HUDDLE_STARTED,
|
|
]
|
|
} else {
|
|
&[
|
|
KIND_STREAM_MESSAGE,
|
|
KIND_STREAM_MESSAGE_V2,
|
|
KIND_FORUM_POST,
|
|
KIND_FORUM_COMMENT,
|
|
]
|
|
};
|
|
let filter = serde_json::json!({
|
|
"kinds": kinds,
|
|
"#h": [channel.id],
|
|
"since": channel.read_at.map_or(0, |value| value.saturating_add(1)),
|
|
"limit": CATCH_UP_LIMIT,
|
|
});
|
|
let result = session.fetch_events(filter, REQUEST_TIMEOUT).await;
|
|
(order, channel, result)
|
|
});
|
|
}
|
|
|
|
let mut fetched = Vec::new();
|
|
let mut failures = Vec::new();
|
|
while let Some(joined) = pending.join_next().await {
|
|
let (order, channel, result) =
|
|
joined.map_err(|error| format!("unread catch-up task failed: {error}"))?;
|
|
match result {
|
|
Ok(events) => fetched.push(FetchedChannel {
|
|
order,
|
|
channel,
|
|
events: events
|
|
.into_iter()
|
|
.take(CATCH_UP_LIMIT)
|
|
.map(EventView::from)
|
|
.collect(),
|
|
}),
|
|
Err(error) => failures.push(ChannelResult::Error {
|
|
channel_id: channel.id,
|
|
error,
|
|
}),
|
|
}
|
|
}
|
|
|
|
fetched.sort_by_key(|item| item.order);
|
|
|
|
Ok((fetched, failures))
|
|
}
|
|
|
|
fn classify_batch(
|
|
request: &UnreadCatchUpRequest,
|
|
fetched: Vec<FetchedChannel>,
|
|
membership: &std::collections::HashMap<String, HashSet<String>>,
|
|
) -> Vec<ChannelResult> {
|
|
let self_pubkey = request.self_pubkey.to_lowercase();
|
|
let mut participated = membership.get("participated").cloned().unwrap_or_default();
|
|
let mut authored = membership.get("authored").cloned().unwrap_or_default();
|
|
let mut mentioned = membership.get("mentioned").cloned().unwrap_or_default();
|
|
|
|
// Pass one is deliberately global, not per-channel: notification validity
|
|
// depends on roots learned from history, while the command observes a batch.
|
|
// Deltas remain attributed to the channel that first discovered each root.
|
|
let mut discoveries = Vec::with_capacity(fetched.len());
|
|
for item in &fetched {
|
|
let mut discovered = DiscoveredRoots::default();
|
|
for event in &item.events {
|
|
if event.pubkey.eq_ignore_ascii_case(&self_pubkey) {
|
|
let reference = thread_reference(&event.tags);
|
|
if let Some(root_id) = reference.root_id {
|
|
if participated.insert(root_id.clone()) {
|
|
discovered.participated.push(root_id);
|
|
}
|
|
} else if authored.insert(event.id.clone()) {
|
|
discovered.authored.push(event.id.clone());
|
|
}
|
|
} else if has_tag_value(&event.tags, "p", &self_pubkey) {
|
|
if let Some(root_id) = thread_reference(&event.tags).root_id {
|
|
if mentioned.insert(root_id.clone()) {
|
|
discovered.mentioned.push(root_id);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
discoveries.push(discovered);
|
|
}
|
|
|
|
let mut outputs = Vec::new();
|
|
let mut all_activity = Vec::new();
|
|
for (item, discovered) in fetched.into_iter().zip(discoveries) {
|
|
let mut observed_events = Vec::new();
|
|
let mut activity_rows = Vec::new();
|
|
let mut max_trigger = 0;
|
|
for event in item.events {
|
|
if event.pubkey.eq_ignore_ascii_case(&self_pubkey)
|
|
|| item
|
|
.channel
|
|
.read_at
|
|
.is_some_and(|read_at| event.created_at <= read_at)
|
|
|| !should_notify(
|
|
&event,
|
|
&self_pubkey,
|
|
request,
|
|
membership,
|
|
&participated,
|
|
&authored,
|
|
)
|
|
{
|
|
continue;
|
|
}
|
|
let reference = thread_reference(&event.tags);
|
|
let broadcast = has_exact_tag(&event.tags, "broadcast", "1");
|
|
let threaded = reference.parent_id.is_some() && !broadcast;
|
|
let high_priority = item.channel.channel_type == "dm"
|
|
|| threaded
|
|
|| broadcast
|
|
|| has_tag_value(&event.tags, "p", &self_pubkey);
|
|
max_trigger = max_trigger.max(event.created_at);
|
|
observed_events.push(ObservedUnreadEvent {
|
|
id: event.id.clone(),
|
|
created_at: event.created_at,
|
|
root_id: if broadcast {
|
|
None
|
|
} else {
|
|
reference.root_id.clone()
|
|
},
|
|
high_priority,
|
|
counts_toward_badge: item.channel.channel_type == "dm" || threaded || high_priority,
|
|
counts_toward_app_badge: item.channel.channel_type == "dm"
|
|
|| (!threaded && high_priority),
|
|
});
|
|
if threaded {
|
|
activity_rows.push(ActivityRow {
|
|
id: event.id,
|
|
kind: event.kind,
|
|
pubkey: event.pubkey,
|
|
content: event.content,
|
|
created_at: event.created_at,
|
|
channel_id: item.channel.id.clone(),
|
|
channel_name: item.channel.name.clone(),
|
|
tags: event.tags,
|
|
});
|
|
}
|
|
}
|
|
all_activity.extend(activity_rows.iter().cloned());
|
|
outputs.push((
|
|
item.channel.id,
|
|
observed_events,
|
|
max_trigger,
|
|
activity_rows,
|
|
discovered,
|
|
));
|
|
}
|
|
|
|
all_activity.sort_by_key(|row| row.created_at);
|
|
let mut seen = HashSet::new();
|
|
all_activity.retain(|row| seen.insert(row.id.clone()));
|
|
if all_activity.len() > ACTIVITY_LIMIT {
|
|
all_activity.drain(..all_activity.len() - ACTIVITY_LIMIT);
|
|
}
|
|
let allowed: HashSet<_> = all_activity.into_iter().map(|row| row.id).collect();
|
|
|
|
outputs
|
|
.into_iter()
|
|
.map(
|
|
|(channel_id, observed_events, max_trigger, mut activity_rows, discovered)| {
|
|
activity_rows.retain(|row| allowed.contains(&row.id));
|
|
ChannelResult::Success {
|
|
channel_id,
|
|
observed_events,
|
|
max_trigger,
|
|
activity_rows,
|
|
discovered,
|
|
}
|
|
},
|
|
)
|
|
.collect()
|
|
}
|
|
|
|
struct ThreadReference {
|
|
parent_id: Option<String>,
|
|
root_id: Option<String>,
|
|
}
|
|
|
|
fn thread_reference(tags: &[Vec<String>]) -> ThreadReference {
|
|
let event_tags: Vec<_> = tags
|
|
.iter()
|
|
.filter(|tag| tag.first().is_some_and(|v| v == "e") && tag.get(1).is_some())
|
|
.collect();
|
|
let root = event_tags
|
|
.iter()
|
|
.find(|tag| tag.get(3).is_some_and(|v| v == "root"));
|
|
let reply = event_tags
|
|
.iter()
|
|
.rev()
|
|
.find(|tag| tag.get(3).is_some_and(|v| v == "reply"));
|
|
let Some(reply) = reply else {
|
|
return ThreadReference {
|
|
parent_id: None,
|
|
root_id: None,
|
|
};
|
|
};
|
|
let parent_id = reply.get(1).cloned();
|
|
ThreadReference {
|
|
root_id: root
|
|
.and_then(|tag| tag.get(1).cloned())
|
|
.or_else(|| parent_id.clone()),
|
|
parent_id,
|
|
}
|
|
}
|
|
|
|
fn should_notify(
|
|
event: &EventView,
|
|
self_pubkey: &str,
|
|
request: &UnreadCatchUpRequest,
|
|
membership: &std::collections::HashMap<String, HashSet<String>>,
|
|
participated: &HashSet<String>,
|
|
authored: &HashSet<String>,
|
|
) -> bool {
|
|
if has_exact_tag(&event.tags, "broadcast", "1") || has_tag_value(&event.tags, "p", self_pubkey)
|
|
{
|
|
return true;
|
|
}
|
|
let event_channel_id = event
|
|
.tags
|
|
.iter()
|
|
.find(|tag| tag.first().is_some_and(|part| part == "h"))
|
|
.and_then(|tag| tag.get(1));
|
|
if event_channel_id.is_some_and(|id| request.muted_channel_ids.contains(id)) {
|
|
return false;
|
|
}
|
|
let reference = thread_reference(&event.tags);
|
|
if reference.parent_id.is_none() {
|
|
return true;
|
|
}
|
|
let Some(root_id) = reference.root_id else {
|
|
return false;
|
|
};
|
|
if membership
|
|
.get("muted_root")
|
|
.is_some_and(|set| set.contains(&root_id))
|
|
{
|
|
return false;
|
|
}
|
|
participated.contains(&root_id)
|
|
|| membership
|
|
.get("followed")
|
|
.is_some_and(|set| set.contains(&root_id))
|
|
|| authored.contains(&root_id)
|
|
}
|
|
|
|
fn has_exact_tag(tags: &[Vec<String>], name: &str, value: &str) -> bool {
|
|
tags.iter().any(|tag| {
|
|
tag.first().is_some_and(|part| part == name) && tag.get(1).is_some_and(|part| part == value)
|
|
})
|
|
}
|
|
|
|
fn has_tag_value(tags: &[Vec<String>], name: &str, value: &str) -> bool {
|
|
tags.iter().any(|tag| {
|
|
tag.first().is_some_and(|part| part == name)
|
|
&& tag
|
|
.get(1)
|
|
.is_some_and(|part| part.eq_ignore_ascii_case(value))
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::collections::HashMap;
|
|
|
|
use super::*;
|
|
|
|
fn event(id: &str, pubkey: &str, created_at: u64, tags: &[&[&str]]) -> EventView {
|
|
EventView {
|
|
id: id.into(),
|
|
kind: 9,
|
|
pubkey: pubkey.into(),
|
|
content: id.into(),
|
|
created_at,
|
|
tags: tags
|
|
.iter()
|
|
.map(|tag| tag.iter().map(|part| (*part).to_string()).collect())
|
|
.collect(),
|
|
}
|
|
}
|
|
|
|
fn request() -> UnreadCatchUpRequest {
|
|
UnreadCatchUpRequest {
|
|
channels: vec![],
|
|
self_pubkey: "self".into(),
|
|
muted_channel_ids: HashSet::new(),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn pass_one_history_changes_later_classification() {
|
|
let req = request();
|
|
let channel = CatchUpChannel {
|
|
id: "ch".into(),
|
|
channel_type: "stream".into(),
|
|
name: "Ch".into(),
|
|
read_at: Some(9),
|
|
};
|
|
let fetched = vec![FetchedChannel {
|
|
order: 0,
|
|
channel,
|
|
events: vec![
|
|
event(
|
|
"self-reply",
|
|
"self",
|
|
10,
|
|
&[&["e", "root", "", "reply"], &["h", "ch"]],
|
|
),
|
|
event(
|
|
"external-reply",
|
|
"other",
|
|
11,
|
|
&[&["e", "root", "", "reply"], &["h", "ch"]],
|
|
),
|
|
],
|
|
}];
|
|
let result = classify_batch(&req, fetched, &HashMap::new());
|
|
let ChannelResult::Success {
|
|
observed_events,
|
|
discovered,
|
|
..
|
|
} = &result[0]
|
|
else {
|
|
panic!("expected success")
|
|
};
|
|
assert_eq!(
|
|
observed_events
|
|
.iter()
|
|
.map(|event| (event.id.as_str(), event.high_priority))
|
|
.collect::<Vec<_>>(),
|
|
[("external-reply", true)]
|
|
);
|
|
assert_eq!(discovered.participated, ["root"]);
|
|
}
|
|
|
|
#[test]
|
|
fn same_second_marker_and_mutes_match_renderer_rules() {
|
|
let req = request();
|
|
let mut membership = HashMap::new();
|
|
membership.insert("muted_root".into(), HashSet::from(["muted".into()]));
|
|
let channel = CatchUpChannel {
|
|
id: "ch".into(),
|
|
channel_type: "stream".into(),
|
|
name: "Ch".into(),
|
|
read_at: Some(10),
|
|
};
|
|
let fetched = vec![FetchedChannel {
|
|
order: 0,
|
|
channel,
|
|
events: vec![
|
|
event("boundary", "other", 10, &[&["h", "ch"]]),
|
|
event(
|
|
"muted",
|
|
"other",
|
|
11,
|
|
&[&["e", "muted", "", "reply"], &["h", "ch"]],
|
|
),
|
|
event(
|
|
"broadcast",
|
|
"other",
|
|
12,
|
|
&[&["broadcast", "1"], &["h", "ch"]],
|
|
),
|
|
],
|
|
}];
|
|
let result = classify_batch(&req, fetched, &membership);
|
|
let ChannelResult::Success {
|
|
observed_events,
|
|
max_trigger,
|
|
..
|
|
} = &result[0]
|
|
else {
|
|
panic!("expected success")
|
|
};
|
|
assert_eq!(
|
|
observed_events
|
|
.iter()
|
|
.map(|event| event.id.as_str())
|
|
.collect::<Vec<_>>(),
|
|
["broadcast"]
|
|
);
|
|
assert_eq!(*max_trigger, 12);
|
|
}
|
|
|
|
/// Pins the SERIALIZED wire contract against `tauriUnreadCatchUp.ts`.
|
|
///
|
|
/// Asserts on serde's OUTPUT, not on `ChannelResult`: the renderer never
|
|
/// sees the Rust type, it sees bytes, through an `invokeTauri<T>` cast
|
|
/// that validates nothing. Every other test here inspects the enum before
|
|
/// serialization and the e2e bridge hand-writes the intended shape, so
|
|
/// without this nothing compares what Rust emits to what TypeScript
|
|
/// declares.
|
|
///
|
|
/// Whole-value rather than a key list, deliberately: a key-set assertion
|
|
/// passes a mutant that drops the variant rename and emits `"Success"`,
|
|
/// which the renderer's `status === "error"` branch silently misreads.
|
|
/// Failure here means the merge loop throws on the first success row and
|
|
/// catch-up yields nothing, silently.
|
|
#[test]
|
|
fn serialized_response_matches_the_typescript_contract() {
|
|
let channels = vec![
|
|
ChannelResult::Success {
|
|
channel_id: "ch".into(),
|
|
observed_events: vec![ObservedUnreadEvent {
|
|
id: "evt".into(),
|
|
created_at: 11,
|
|
root_id: Some("root".into()),
|
|
high_priority: true,
|
|
counts_toward_badge: true,
|
|
counts_toward_app_badge: false,
|
|
}],
|
|
max_trigger: 11,
|
|
activity_rows: vec![ActivityRow {
|
|
id: "evt".into(),
|
|
kind: 9,
|
|
pubkey: "other".into(),
|
|
content: "hi".into(),
|
|
created_at: 11,
|
|
channel_id: "ch".into(),
|
|
channel_name: "Ch".into(),
|
|
tags: vec![vec!["h".into(), "ch".into()]],
|
|
}],
|
|
discovered: DiscoveredRoots {
|
|
participated: vec!["root".into()],
|
|
authored: Vec::new(),
|
|
mentioned: Vec::new(),
|
|
},
|
|
},
|
|
ChannelResult::Error {
|
|
channel_id: "ch-2".into(),
|
|
error: "relay request timed out".into(),
|
|
},
|
|
];
|
|
|
|
let actual = serde_json::to_value(UnreadCatchUpResponse { channels }).unwrap();
|
|
let expected = serde_json::json!({
|
|
"channels": [
|
|
{
|
|
"status": "success",
|
|
"channelId": "ch",
|
|
"observedEvents": [{
|
|
"id": "evt",
|
|
"createdAt": 11,
|
|
"rootId": "root",
|
|
"highPriority": true,
|
|
"countsTowardBadge": true,
|
|
"countsTowardAppBadge": false,
|
|
}],
|
|
"maxTrigger": 11,
|
|
"activityRows": [{
|
|
"id": "evt",
|
|
"kind": 9,
|
|
"pubkey": "other",
|
|
"content": "hi",
|
|
"createdAt": 11,
|
|
"channelId": "ch",
|
|
"channelName": "Ch",
|
|
"tags": [["h", "ch"]],
|
|
}],
|
|
"discovered": {
|
|
"participated": ["root"],
|
|
"authored": [],
|
|
"mentioned": [],
|
|
},
|
|
},
|
|
{
|
|
"status": "error",
|
|
"channelId": "ch-2",
|
|
"error": "relay request timed out",
|
|
},
|
|
]
|
|
});
|
|
|
|
assert_eq!(actual, expected);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "unread_catch_up_recovery_tests.rs"]
|
|
mod recovery_tests;
|