Skip to content

Commit a61239f

Browse files
authored
fix(mobile): avoid opening empty threads on message tap (#7756)
Tapping a mobile channel message with no replies currently opens an empty thread. Only enable message-row thread navigation when the existing thread summary reports replies, including replies known to the relay but not loaded locally. Long-press → Reply still starts a new thread. Added widget tests for zero replies, loaded replies, relay-only replies, and starting a thread through Reply. The zero-reply test failed before the fix and passes afterward. Validation: all 227 channel-page tests, the full mobile pre-push checks, and all PR CI checks passed. The full repository gate failed in unchanged Rust ACP timing tests (idle reset, keepalive, and steering deadlines); this PR changes only mobile Dart files. No duplicate open PR or issue found. --------- Signed-off-by: Tom Brow <[email protected]>
1 parent 5079c77 commit a61239f

23 files changed

Lines changed: 6889 additions & 269 deletions

‎.github/workflows/_ci-relay.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -587,7 +587,7 @@ jobs:
587587
./scripts/start-relay-for-tests.sh --no-build
588588
- name: Relay E2E tests
589589
run: |
590-
cargo test -p buzz-test-client --test e2e_persona --test e2e_team_catalog --test e2e_nostr_interop --test e2e_project -- --ignored --nocapture
590+
cargo test -p buzz-test-client --test e2e_persona --test e2e_team_catalog --test e2e_nostr_interop --test e2e_thread_roots --test e2e_project -- --ignored --nocapture
591591
cargo test -p buzz-test-client --test e2e_relay invite -- --ignored --nocapture
592592
cargo test -p buzz-test-client --test e2e_relay nip43_membership_snapshots_are_rejected -- --ignored --nocapture
593593
cargo test -p buzz-test-client --test e2e_relay nip29_departure_wire -- --ignored --nocapture

‎crates/buzz-db/src/store/thread.rs‎

Lines changed: 393 additions & 83 deletions
Large diffs are not rendered by default.

‎crates/buzz-relay/src/api/bridge.rs‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ use crate::state::AppState;
2121

2222
use super::{api_error, internal_error, not_found};
2323

24+
mod thread_roots;
25+
2426
pub(crate) async fn enforce_http_admission(
2527
state: &AppState,
2628
tenant: &TenantContext,
@@ -1185,10 +1187,30 @@ async fn query_events_authed(
11851187
let mut events: Vec<Value> = Vec::new();
11861188
let mut handled: std::collections::HashSet<usize> = std::collections::HashSet::new();
11871189

1190+
let ownership_targets: usize = raw_filters
1191+
.iter()
1192+
.zip(&filters)
1193+
.filter(|(raw, _)| extension_flag(raw, "resolve_thread_roots"))
1194+
.map(|(_, filter)| filter.ids.as_ref().map_or(0, |ids| ids.len()))
1195+
.sum();
1196+
if ownership_targets > 100 {
1197+
return Err(api_error(
1198+
StatusCode::BAD_REQUEST,
1199+
"resolve_thread_roots permits at most 100 targets per request",
1200+
));
1201+
}
1202+
// Resolve reply owners from retained thread metadata, including tombstones.
1203+
for (idx, (raw, filter)) in raw_filters.iter().zip(filters.iter()).enumerate() {
1204+
if extension_flag(raw, "resolve_thread_roots") {
1205+
events.extend(thread_roots::query(state, tenant, filter, &accessible_channels).await?);
1206+
handled.insert(idx);
1207+
}
1208+
}
1209+
11881210
// Channel-window filters (`top_level: true`) — the GUI read-model surface.
11891211
// Dispatched first: a window filter is never a feed/thread/catchall query.
11901212
for (idx, (raw, filter)) in raw_filters.iter().zip(filters.iter()).enumerate() {
1191-
if !extension_flag(raw, "top_level") {
1213+
if handled.contains(&idx) || !extension_flag(raw, "top_level") {
11921214
continue;
11931215
}
11941216
handle_channel_window_filter(
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
//! Metadata-only recovery after a reply deletion whose live recount was missed.
2+
3+
use axum::{http::StatusCode, Json};
4+
use buzz_core::{kind::KIND_THREAD_SUMMARY, TenantContext};
5+
use nostr::{EventBuilder, Filter, Kind, Tag};
6+
use serde_json::Value;
7+
use uuid::Uuid;
8+
9+
use super::{api_error, extract_channel_from_filter, internal_error};
10+
use crate::state::AppState;
11+
12+
type QueryError = (StatusCode, Json<Value>);
13+
14+
fn request_channel(filter: &Filter) -> Result<Uuid, QueryError> {
15+
let channel = extract_channel_from_filter(filter).ok_or_else(|| {
16+
api_error(
17+
StatusCode::BAD_REQUEST,
18+
"resolve_thread_roots requires exactly one #h channel",
19+
)
20+
})?;
21+
if !filter.kinds.as_ref().is_some_and(|kinds| {
22+
kinds.len() == 1 && kinds.contains(&Kind::Custom(KIND_THREAD_SUMMARY as u16))
23+
}) {
24+
return Err(api_error(
25+
StatusCode::BAD_REQUEST,
26+
"resolve_thread_roots requires kinds [39005]",
27+
));
28+
}
29+
if !filter
30+
.ids
31+
.as_ref()
32+
.is_some_and(|ids| !ids.is_empty() && ids.len() <= 100)
33+
{
34+
return Err(api_error(
35+
StatusCode::BAD_REQUEST,
36+
"resolve_thread_roots requires 1 to 100 target ids",
37+
));
38+
}
39+
Ok(channel)
40+
}
41+
42+
/// Return signed root summaries from retained, channel-scoped reply metadata.
43+
pub(super) async fn query(
44+
state: &AppState,
45+
tenant: &TenantContext,
46+
filter: &Filter,
47+
accessible_channels: &[Uuid],
48+
) -> Result<Vec<Value>, QueryError> {
49+
let channel = request_channel(filter)?;
50+
if !accessible_channels.contains(&channel) {
51+
return Ok(Vec::new());
52+
}
53+
let ids = filter
54+
.ids
55+
.iter()
56+
.flatten()
57+
.map(|id| id.as_bytes().to_vec())
58+
.collect::<Vec<_>>();
59+
let summaries = state
60+
.db
61+
.resolve_thread_root_summaries(tenant.community(), channel, &ids)
62+
.await
63+
.map_err(|e| internal_error(&format!("thread ownership summaries: {e}")))?;
64+
let mut events = Vec::with_capacity(summaries.len());
65+
for (root, summary) in summaries {
66+
let root_hex = hex::encode(root);
67+
let channel_hex = channel.to_string();
68+
let tags = [
69+
["e", root_hex.as_str()],
70+
["d", root_hex.as_str()],
71+
["h", channel_hex.as_str()],
72+
]
73+
.into_iter()
74+
.map(Tag::parse)
75+
.collect::<Result<Vec<_>, _>>()
76+
.map_err(|e| internal_error(&format!("thread summary tags: {e}")))?;
77+
let content = serde_json::json!({
78+
"reply_count": summary.reply_count,
79+
"descendant_count": summary.descendant_count,
80+
"last_reply_at": summary.last_reply_at.map(|t| t.timestamp()),
81+
"participants": summary.participants.iter().map(hex::encode).collect::<Vec<_>>(),
82+
});
83+
let event = EventBuilder::new(
84+
Kind::Custom(KIND_THREAD_SUMMARY as u16),
85+
content.to_string(),
86+
)
87+
.tags(tags)
88+
.sign_with_keys(&state.relay_keypair)
89+
.map_err(|e| internal_error(&format!("thread summary signing: {e}")))?;
90+
events.push(
91+
serde_json::to_value(event)
92+
.map_err(|e| internal_error(&format!("thread summary serialization: {e}")))?,
93+
);
94+
}
95+
Ok(events)
96+
}
97+
98+
#[cfg(test)]
99+
mod tests {
100+
use super::*;
101+
102+
fn filter(ids: usize) -> Filter {
103+
serde_json::from_value(serde_json::json!({
104+
"kinds": [39005], "#h": ["11111111-1111-4111-8111-111111111111"],
105+
"ids": (0..ids).map(|id| format!("{id:064x}")).collect::<Vec<_>>()
106+
}))
107+
.expect("valid filter")
108+
}
109+
110+
#[test]
111+
fn ownership_request_requires_bounded_ids_and_explicit_scope() {
112+
assert!(request_channel(&filter(1)).is_ok());
113+
assert!(request_channel(&filter(100)).is_ok());
114+
assert!(request_channel(&filter(0)).is_err());
115+
assert!(request_channel(&filter(101)).is_err());
116+
let mut wrong_kind = filter(1);
117+
wrong_kind.kinds = Some([Kind::TextNote].into_iter().collect());
118+
assert!(request_channel(&wrong_kind).is_err());
119+
let mut unscoped = filter(1);
120+
unscoped.generic_tags.clear();
121+
assert!(request_channel(&unscoped).is_err());
122+
}
123+
}
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
//! Tombstone-aware ownership recovery through the authenticated Nostr bridge.
2+
//! Run against a local development relay with `--ignored`.
3+
4+
use nostr::{Event, EventBuilder, Keys, Kind, Tag};
5+
use serde_json::{json, Value};
6+
7+
fn url() -> String {
8+
std::env::var("RELAY_URL")
9+
.unwrap_or_else(|_| "ws://localhost:3000".into())
10+
.replace("ws://", "http://")
11+
.replace("wss://", "https://")
12+
}
13+
14+
async fn post(keys: &Keys, event: &Event) {
15+
let response = reqwest::Client::new()
16+
.post(format!("{}/events", url()))
17+
.header("X-Pubkey", keys.public_key().to_hex())
18+
.json(event)
19+
.send()
20+
.await
21+
.expect("event request");
22+
assert!(
23+
response.status().is_success(),
24+
"event status {}",
25+
response.status()
26+
);
27+
let body: Value = response.json().await.expect("event response");
28+
assert_eq!(body["accepted"], true, "event rejected: {body}");
29+
}
30+
31+
async fn query(keys: &Keys, filter: Value) -> Vec<Event> {
32+
let response = reqwest::Client::new()
33+
.post(format!("{}/query", url()))
34+
.header("X-Pubkey", keys.public_key().to_hex())
35+
.json(&vec![filter])
36+
.send()
37+
.await
38+
.expect("query request");
39+
assert!(
40+
response.status().is_success(),
41+
"query status {}",
42+
response.status()
43+
);
44+
response.json().await.expect("signed event array")
45+
}
46+
47+
async fn channel(keys: &Keys, private: bool) -> String {
48+
let id = uuid::Uuid::new_v4().to_string();
49+
let event = EventBuilder::new(Kind::Custom(9007), "")
50+
.tags([
51+
Tag::parse(["h", &id]).unwrap(),
52+
Tag::parse(["name", &format!("thread-roots-{id}")]).unwrap(),
53+
Tag::parse(["channel_type", "stream"]).unwrap(),
54+
Tag::parse(["visibility", if private { "private" } else { "open" }]).unwrap(),
55+
])
56+
.sign_with_keys(keys)
57+
.unwrap();
58+
post(keys, &event).await;
59+
id
60+
}
61+
62+
fn request(channel: &str, target: &Event) -> Value {
63+
json!({"kinds": [39005], "ids": [target.id.to_hex()], "#h": [channel], "resolve_thread_roots": true})
64+
}
65+
66+
#[tokio::test]
67+
#[ignore]
68+
async fn deleted_reply_roots_are_recovered_without_content_or_scope_leaks() {
69+
let owner = Keys::generate();
70+
let outsider = Keys::generate();
71+
let other_channel = channel(&owner, false).await;
72+
let bounded_filter = json!({
73+
"kinds": [39005], "#h": [&other_channel], "resolve_thread_roots": true,
74+
"ids": (0..60).map(|id| format!("{id:064x}")).collect::<Vec<_>>()
75+
});
76+
let oversized = reqwest::Client::new()
77+
.post(format!("{}/query", url()))
78+
.header("X-Pubkey", owner.public_key().to_hex())
79+
.json(&vec![bounded_filter.clone(), bounded_filter])
80+
.send()
81+
.await
82+
.expect("bounded batch");
83+
assert_eq!(
84+
oversized.status(),
85+
reqwest::StatusCode::BAD_REQUEST,
86+
"the target cap applies across filters, not just within each filter"
87+
);
88+
for deletion_kind in [5, 9005] {
89+
let channel_id = channel(&owner, true).await;
90+
let root = EventBuilder::new(Kind::Custom(9), "root")
91+
.tags([Tag::parse(["h", &channel_id]).unwrap()])
92+
.sign_with_keys(&owner)
93+
.unwrap();
94+
post(&owner, &root).await;
95+
let reply = EventBuilder::new(Kind::Custom(9), "deleted secret payload")
96+
.tags([
97+
Tag::parse(["h", &channel_id]).unwrap(),
98+
Tag::parse(["e", &root.id.to_hex(), "", "reply"]).unwrap(),
99+
])
100+
.sign_with_keys(&owner)
101+
.unwrap();
102+
post(&owner, &reply).await;
103+
let deletion = EventBuilder::new(Kind::Custom(deletion_kind), "")
104+
.tags([
105+
Tag::parse(["h", &channel_id]).unwrap(),
106+
Tag::parse(["e", &reply.id.to_hex()]).unwrap(),
107+
])
108+
.sign_with_keys(&owner)
109+
.unwrap();
110+
post(&owner, &deletion).await;
111+
112+
let ordinary = query(
113+
&owner,
114+
json!({"kinds":[9],"ids":[reply.id.to_hex()],"#h":[channel_id]}),
115+
)
116+
.await;
117+
assert!(
118+
ordinary.is_empty(),
119+
"ordinary history must exclude the deleted payload"
120+
);
121+
let summaries = query(&owner, request(&channel_id, &reply)).await;
122+
assert_eq!(summaries.len(), 1, "metadata must survive deletion");
123+
let summary = &summaries[0];
124+
summary.verify().expect("relay signature");
125+
assert_eq!(summary.kind, Kind::Custom(39005));
126+
assert!(summary
127+
.tags
128+
.iter()
129+
.any(|tag| tag.as_slice() == ["e", &root.id.to_hex()]));
130+
let counts: Value = serde_json::from_str(&summary.content).unwrap();
131+
assert_eq!(counts["reply_count"], 0);
132+
assert_eq!(counts["descendant_count"], 0);
133+
assert!(!summary.content.contains("deleted secret payload"));
134+
135+
assert!(
136+
query(&owner, request(&other_channel, &reply))
137+
.await
138+
.is_empty(),
139+
"wrong channel must not leak ownership"
140+
);
141+
assert!(
142+
query(&outsider, request(&channel_id, &reply))
143+
.await
144+
.is_empty(),
145+
"private channel membership is required"
146+
);
147+
}
148+
}

‎docs/nips/NIP-CW.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,3 +205,25 @@ A client with neither an authenticated transport nor a verifiable relay identity
205205
- **NIP-50** and relay-side search: sibling precedent — a relay-computed view requested through extended filter fields, invisible to relays that do not implement it.
206206
- **NIP-98**: Authenticates the HTTP query surface Buzz serves windows on.
207207
- **NIP-11**: Names the relay identity that signs overlays and the natural place to advertise support.
208+
209+
## Recovering summaries after deletion
210+
211+
The HTTP bridge additionally supports `resolve_thread_roots: true` with
212+
`kinds: [39005]`, exactly one accessible `#h` channel, and 1–100 full event
213+
`ids`. The IDs identify target replies, including soft-deleted replies,
214+
not the IDs of the returned summary events. The request permits at most
215+
100 targets across all such filters.
216+
217+
The relay resolves ownership from retained thread metadata on the writer,
218+
checks both target and root channel scope, and returns one signed
219+
`kind:39005` summary per distinct owning root, including zero counts.
220+
It returns no original target content, author, or signature. Missing or
221+
non-reply targets and inaccessible channels produce no summaries.
222+
These reads use the writer so deletion recovery does not depend on
223+
replica replay or the delivery of a live summary. No bounds event is returned.
224+
225+
Clients use this bounded metadata operation when a deletion target has
226+
left their reply cache. Ordinary event queries exclude tombstones and
227+
cannot perform this recovery. This extension requires a supporting relay;
228+
clients must not interpret an unsupported/empty response as proof that an
229+
unknown target's thread is empty.

‎mobile/lib/features/channels/channel_detail_page.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ import '../profile/user_profile_sheet.dart';
7676
import 'small_avatar.dart';
7777
import 'sticky_date_header.dart';
7878
import 'thread_detail_page.dart';
79+
import 'thread_replies_provider.dart';
7980
import 'timeline_message.dart';
8081

8182
part 'channel_detail_page/message_list.dart';

0 commit comments

Comments
 (0)