Skip to content

Commit c6e3fe7

Browse files
wpfleger96Duncan
andauthored
feat(workflows): reply in-thread from send_message action (#6178)
The `send_message` workflow action could only post new top-level channel messages. This adds a `reply_in_thread` option so a `message_posted` workflow can reply in the triggering message's thread, plus a `trigger_is_reply` filter variable so a workflow can fire only on top-level messages. Every NIP-10 thread-marker reader in the tree now routes through one shared parser and one collapse rule in `buzz-core`, deleting four hand-rolled copies that had drifted on id-validity and marker semantics. ## What changed - **Schema** (`crates/buzz-workflow/src/schema.rs`): new `reply_in_thread: bool` (serde default `false`) on `ActionDef::SendMessage`. `validate()` rejects `reply_in_thread: true` on `schedule`/`webhook` triggers — they carry no message to reply to. - **Executor** (`crates/buzz-workflow/src/executor.rs`): threads `reply_to: Option<&str>` (the trigger `message_id`) through `ActionSink::send_message` when `reply_in_thread` is set; errors clearly if the trigger has no `message_id`. `resolve_step_templates` carries the new field. Adds `trigger_is_reply` (boolean) to the eval context. - **Relay sink** (`crates/buzz-relay/src/workflow_sink.rs`): when `reply_to` is set, resolves parent/root/depth from the known trigger event, persists real thread metadata instead of the hardcoded top-level `depth: 0`, and pushes the live kind:39005 thread-summary overlay after insert so subscribed desktops update the root's reply badge without refetching — matching the human ingest path. Emits the same NIP-10 `e`-tag shape as `buzz_sdk::builders::thread_tags`: a single `["e", id, "", "reply"]` tag for a direct reply (parent == root), and the `root` + `reply` pair only when nested — so every writer produces one wire shape per reply kind. - **Ingest resolver** (`crates/buzz-relay/src/handlers/ingest.rs`): new `resolve_relay_reply_thread_meta` + `ReplyAncestry`. Unlike the client-facing `resolve_nip10_thread_meta` (which validates client-supplied tags), this computes root/depth from the known parent and enforces the same same-channel and depth-limit invariants. When the parent has no `thread_metadata` row, both resolvers share `derive_ancestry_from_parent_tags`, which applies `ThreadMarkers::resolve()`: a marked nested parent remains depth 2, while a root-only, malformed, or unmarked parent is top-level and starts its reply thread at itself. Both the client resolver and the parent-ancestor fallback now read markers via the shared parser instead of hand-scanning `e`-tags. - **Shared NIP-10 parser** (`crates/buzz-core/src/nip10.rs`): `parse_thread_markers` reads an event's `root`/`reply` markers, honoring a marker only when its event id is exactly 64 ASCII-hex characters. `ThreadMarkers::resolve()` is the single definition of the (root, reply) → (root_id, parent_id) collapse: `root`+`reply` as-is, `reply`-only → `(reply, reply)`, a lone `root` or neither → top-level. A slice-based `parse_thread_markers_from_parts` entry point serves consumers holding raw JSON tag arrays. Relay ingest, the workflow `trigger_is_reply` predicate, ACP anchoring, and the CLI reply resolver all call these, so they cannot drift on marker, id-validity, or collapse semantics. - **ACP** (`crates/buzz-acp/src/queue.rs`): `parse_thread_tags` delegates marker parsing and collapse to `buzz_core::nip10`, keeping only its local `p`-tag mention collection. This fixes a parity gap with ingest: a malformed non-64-hex marker id is no longer counted as a thread link, and a lone `root` marker is now top-level rather than being treated as root == parent. - **CLI** (`crates/buzz-cli/src/commands/messages.rs`): `find_root_from_tags` routes its JSON tags through the shared slice parser and collapse rule. CLI replies to root-only, malformed, or unmarked parents now correctly start at that immediate parent; reply-only and root+reply parent ancestry remain intact. - **Trigger context** (`crates/buzz-workflow/src/lib.rs`): `build_trigger_context` derives `is_reply` solely from a valid NIP-10 `reply` marker (no DB hit). A lone `root` marker is top-level to ingest, so it does not count; neither does a `reply` marker whose event id is malformed, nor a bare/unmarked `e`-tag (mentions, quotes). - **Desktop** (`workflowFormTypes.ts`, `WorkflowStepCard.tsx`): `replyInThread` form field with YAML round-trip, and a "Reply to triggering message in thread" checkbox shown only for message-based triggers. Switching to `schedule` or `webhook` clears the option on every step before serialization, so a value hidden behind an action change cannot resurrect when the action is switched back. The form parser also requires `reply_in_thread` to be a boolean and refuses `reply_in_thread: true` under an ineligible trigger, falling back to YAML mode rather than silently normalizing a backend-invalid definition. ## Usage ```yaml trigger: on: message_posted filter: trigger_is_reply == false steps: - id: auto_reply action: send_message text: "pre-written reply text" reply_in_thread: true ``` --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent c63ac74 commit c6e3fe7

15 files changed

Lines changed: 1606 additions & 182 deletions

File tree

‎crates/buzz-acp/src/queue.rs‎

Lines changed: 69 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -875,48 +875,31 @@ pub struct ThreadTags {
875875

876876
/// Parse NIP-10 thread tags from a Nostr event.
877877
///
878-
/// Detection logic (per research doc §4c):
879-
/// - Find an `e` tag with `root` marker → its value is `root_event_id`
880-
/// - Find an `e` tag with `reply` marker → its value is `parent_event_id`
881-
/// - If only `reply` marker found (direct reply to root), root == parent
882-
/// - `p` tags → mentioned pubkeys
878+
/// Marker parsing and the (root, reply) → (root, parent) collapse are delegated
879+
/// to [`buzz_core::nip10`] so ACP anchoring reads ancestry exactly as relay
880+
/// ingest does. Only `p`-tag mention collection is local to ACP.
883881
///
884-
/// NOTE: Only handles NIP-10 marker-based format (preferred). The deprecated
885-
/// positional format (no markers, `["e", id, relay_url]`) is not supported —
886-
/// Buzz always generates marker-based tags (see relay messages.rs:762-783).
882+
/// Consequences of sharing the resolver:
883+
/// - A malformed (non-64-hex) marker id is ignored, never a thread link —
884+
/// restoring parity with ingest (ACP previously counted it).
885+
/// - A lone `root` marker (no `reply`) is top-level, not a reply — again
886+
/// matching ingest.
887887
pub fn parse_thread_tags(event: &Event) -> ThreadTags {
888-
let mut root = None;
889-
let mut reply = None;
890-
let mut mentions = Vec::new();
891-
892-
for tag in event.tags.iter() {
893-
let parts = tag.as_slice();
894-
match parts.first().map(|s| s.as_str()) {
895-
Some("e") if parts.len() >= 4 => {
896-
let id = &parts[1];
897-
let marker = &parts[3];
898-
match marker.as_str() {
899-
"root" => root = Some(id.clone()),
900-
"reply" => reply = Some(id.clone()),
901-
_ => {}
902-
}
903-
}
904-
Some("p") if parts.len() >= 2 => {
905-
mentions.push(parts[1].clone());
906-
}
907-
_ => {}
908-
}
909-
}
910-
911-
// For direct replies to root: single "reply" tag, no "root" tag.
912-
// In that case, root == parent.
913-
let (root_event_id, parent_event_id) = match (root, reply) {
914-
(Some(r), Some(p)) => (Some(r), Some(p)),
915-
(Some(r), None) => (Some(r.clone()), Some(r)),
916-
(None, Some(p)) => (Some(p.clone()), Some(p)),
917-
(None, None) => (None, None),
888+
let markers = buzz_core::nip10::parse_thread_markers(&event.tags);
889+
let (root_event_id, parent_event_id) = match markers.resolve() {
890+
Some((root, parent)) => (Some(root), Some(parent)),
891+
None => (None, None),
918892
};
919893

894+
let mentions = event
895+
.tags
896+
.iter()
897+
.filter_map(|tag| {
898+
let parts = tag.as_slice();
899+
(parts.len() >= 2 && parts[0] == "p").then(|| parts[1].clone())
900+
})
901+
.collect();
902+
920903
ThreadTags {
921904
root_event_id,
922905
parent_event_id,
@@ -3192,28 +3175,31 @@ mod tests {
31923175
#[test]
31933176
fn test_parse_thread_tags_direct_reply() {
31943177
// Direct reply to root: single "reply" tag.
3178+
let root = "a".repeat(64);
31953179
let event = make_event_with_tags(
31963180
"reply to root",
3197-
vec![vec!["e".into(), "abc123".into(), "".into(), "reply".into()]],
3181+
vec![vec!["e".into(), root.clone(), "".into(), "reply".into()]],
31983182
);
31993183
let tags = parse_thread_tags(&event);
3200-
assert_eq!(tags.root_event_id.as_deref(), Some("abc123"));
3201-
assert_eq!(tags.parent_event_id.as_deref(), Some("abc123"));
3184+
assert_eq!(tags.root_event_id.as_deref(), Some(root.as_str()));
3185+
assert_eq!(tags.parent_event_id.as_deref(), Some(root.as_str()));
32023186
}
32033187

32043188
#[test]
32053189
fn test_parse_thread_tags_nested_reply() {
32063190
// Nested reply: root + reply tags.
3191+
let root = "a".repeat(64);
3192+
let parent = "b".repeat(64);
32073193
let event = make_event_with_tags(
32083194
"nested reply",
32093195
vec![
3210-
vec!["e".into(), "root123".into(), "".into(), "root".into()],
3211-
vec!["e".into(), "parent456".into(), "".into(), "reply".into()],
3196+
vec!["e".into(), root.clone(), "".into(), "root".into()],
3197+
vec!["e".into(), parent.clone(), "".into(), "reply".into()],
32123198
],
32133199
);
32143200
let tags = parse_thread_tags(&event);
3215-
assert_eq!(tags.root_event_id.as_deref(), Some("root123"));
3216-
assert_eq!(tags.parent_event_id.as_deref(), Some("parent456"));
3201+
assert_eq!(tags.root_event_id.as_deref(), Some(root.as_str()));
3202+
assert_eq!(tags.parent_event_id.as_deref(), Some(parent.as_str()));
32173203
}
32183204

32193205
#[test]
@@ -3231,15 +3217,36 @@ mod tests {
32313217
}
32323218

32333219
#[test]
3234-
fn test_parse_thread_tags_root_only() {
3235-
// Only root marker, no reply marker — root == parent.
3220+
fn test_parse_thread_tags_root_only_is_top_level() {
3221+
// Only a `root` marker, no `reply` — top-level, matching ingest. A lone
3222+
// `root` tag does not anchor a reply (behavior change from the old
3223+
// hand-rolled parser, which treated root == parent here).
3224+
let root = "a".repeat(64);
32363225
let event = make_event_with_tags(
3237-
"reply",
3238-
vec![vec!["e".into(), "root123".into(), "".into(), "root".into()]],
3226+
"root only",
3227+
vec![vec!["e".into(), root, "".into(), "root".into()]],
32393228
);
32403229
let tags = parse_thread_tags(&event);
3241-
assert_eq!(tags.root_event_id.as_deref(), Some("root123"));
3242-
assert_eq!(tags.parent_event_id.as_deref(), Some("root123"));
3230+
assert!(tags.root_event_id.is_none());
3231+
assert!(tags.parent_event_id.is_none());
3232+
}
3233+
3234+
#[test]
3235+
fn test_parse_thread_tags_malformed_id_is_not_a_thread_link() {
3236+
// A non-64-hex marker id is ignored — parity with relay ingest, which
3237+
// never treats a malformed id as a thread link.
3238+
let event = make_event_with_tags(
3239+
"malformed marker",
3240+
vec![vec![
3241+
"e".into(),
3242+
"garbage".into(),
3243+
"".into(),
3244+
"reply".into(),
3245+
]],
3246+
);
3247+
let tags = parse_thread_tags(&event);
3248+
assert!(tags.root_event_id.is_none());
3249+
assert!(tags.parent_event_id.is_none());
32433250
}
32443251

32453252
#[test]
@@ -3312,7 +3319,7 @@ mod tests {
33123319
"yes go ahead",
33133320
vec![vec![
33143321
"e".into(),
3315-
"root123".into(),
3322+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
33163323
"".into(),
33173324
"reply".into(),
33183325
]],
@@ -3330,7 +3337,9 @@ mod tests {
33303337

33313338
let prompt = format_prompt(&batch, &FormatPromptArgs::default()).join("\n\n");
33323339
assert!(prompt.contains("Scope: thread"));
3333-
assert!(prompt.contains("Thread root: root123"));
3340+
assert!(prompt.contains(
3341+
"Thread root: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3342+
));
33343343
}
33353344

33363345
#[test]
@@ -3340,7 +3349,7 @@ mod tests {
33403349
"yes go ahead",
33413350
vec![vec![
33423351
"e".into(),
3343-
"root123".into(),
3352+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
33443353
"".into(),
33453354
"reply".into(),
33463355
]],
@@ -3645,7 +3654,7 @@ mod tests {
36453654
"sounds good, do it",
36463655
vec![vec![
36473656
"e".into(),
3648-
"root123".into(),
3657+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
36493658
"".into(),
36503659
"reply".into(),
36513660
]],
@@ -3698,7 +3707,9 @@ mod tests {
36983707
);
36993708
// Thread structural info should be present.
37003709
assert!(
3701-
prompt.contains("Thread root: root123"),
3710+
prompt.contains(
3711+
"Thread root: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3712+
),
37023713
"DM reply should include thread root"
37033714
);
37043715
// Thread context should be included.
@@ -3712,7 +3723,7 @@ mod tests {
37123723
"follow up",
37133724
vec![vec![
37143725
"e".into(),
3715-
"root123".into(),
3726+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
37163727
"".into(),
37173728
"reply".into(),
37183729
]],
@@ -5310,7 +5321,7 @@ mod tests {
53105321
"reply in thread",
53115322
vec![vec![
53125323
"e".into(),
5313-
"root123".into(),
5324+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
53145325
"".into(),
53155326
"reply".into(),
53165327
]],

‎crates/buzz-cli/src/commands/messages.rs‎

Lines changed: 63 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -14,36 +14,45 @@ use buzz_sdk::mentions::{
1414

1515
/// Extract the thread root event ID from a Nostr tag array.
1616
///
17-
/// Parses `"e"` tags with NIP-10 markers:
18-
/// - If a `"root"` marker exists, returns that event ID.
19-
/// - Otherwise, if only a `"reply"` marker exists, returns the reply target
20-
/// (a direct reply's parent IS the root, and nested replies need that root
21-
/// to thread correctly).
22-
/// - If no thread markers exist, returns `None` (parent is a top-level message,
23-
/// so it is itself the root).
17+
/// Delegates marker parsing and collapse to [`buzz_core::nip10`] (shared with
18+
/// relay ingest and ACP) so id-validity, marker selection, and top-level
19+
/// classification cannot drift:
20+
/// - A `root`+`reply` parent returns its root event ID.
21+
/// - A `reply`-only parent returns the reply target (a direct reply's parent IS
22+
/// the root).
23+
/// - A root-only or marker-less parent returns `None` (it is top-level and its
24+
/// own root).
2425
fn find_root_from_tags(tags: &serde_json::Value) -> Option<String> {
25-
fn valid_event_id(s: &str) -> bool {
26-
s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit())
27-
}
28-
let arr = tags.as_array()?;
29-
let mut root = None;
30-
let mut reply = None;
31-
for tag in arr {
32-
let Some(parts) = tag.as_array() else {
33-
continue;
34-
};
35-
if parts.len() >= 4 && parts[0].as_str() == Some("e") {
36-
// Defensively ignore malformed marker values so a bad tag on the
37-
// parent event can't block the reply — fall back to root == parent.
38-
let id = parts[1].as_str().filter(|s| valid_event_id(s));
39-
match (parts[3].as_str(), id) {
40-
(Some("root"), Some(id)) => root = Some(id.to_string()),
41-
(Some("reply"), Some(id)) => reply = Some(id.to_string()),
42-
_ => {}
43-
}
44-
}
45-
}
46-
root.or(reply)
26+
let parts: Vec<Vec<String>> = tags
27+
.as_array()?
28+
.iter()
29+
.filter_map(|tag| {
30+
tag.as_array().map(|a| {
31+
a.iter()
32+
.map(|v| v.as_str().unwrap_or("").to_string())
33+
.collect()
34+
})
35+
})
36+
.collect();
37+
buzz_core::nip10::parse_thread_markers_from_parts(parts.iter().map(Vec::as_slice))
38+
.resolve()
39+
.map(|(root, _)| root)
40+
}
41+
42+
fn thread_ref_from_parent_tags(
43+
parent_eid: nostr::EventId,
44+
parent_event_id: &str,
45+
tags: &serde_json::Value,
46+
) -> Result<ThreadRef, CliError> {
47+
let root_eid = match find_root_from_tags(tags) {
48+
Some(root_hex) if root_hex != parent_event_id => parse_event_id(&root_hex)?,
49+
_ => parent_eid,
50+
};
51+
52+
Ok(ThreadRef {
53+
root_event_id: root_eid,
54+
parent_event_id: parent_eid,
55+
})
4756
}
4857

4958
/// Build a `ThreadRef` for a reply, given the immediate parent's event ID.
@@ -80,14 +89,7 @@ fn thread_ref_from_event(event_id: &str, event: &serde_json::Value) -> Result<Th
8089
.get("tags")
8190
.cloned()
8291
.unwrap_or(serde_json::Value::Null);
83-
let root_event_id = match find_root_from_tags(&tags) {
84-
Some(root_hex) if root_hex != event_id => parse_event_id(&root_hex)?,
85-
_ => parent_eid,
86-
};
87-
Ok(ThreadRef {
88-
root_event_id,
89-
parent_event_id: parent_eid,
90-
})
92+
thread_ref_from_parent_tags(parent_eid, event_id, &tags)
9193
}
9294

9395
/// Resolve the channel UUID for an event by querying for it via POST /query.
@@ -1057,7 +1059,8 @@ mod tests {
10571059
channel_id_from_event, cmd_get_thread, event_mention_pubkeys, find_root_from_tags,
10581060
match_profiles_by_name, merge_message_mentions, missing_members,
10591061
normalize_explicit_mentions, parse_member_pubkeys, resolve_names_to_pubkeys,
1060-
resolve_thread_target, thread_ref_from_event, BuzzClient, CliError, Uuid,
1062+
resolve_thread_target, thread_ref_from_event, thread_ref_from_parent_tags, BuzzClient,
1063+
CliError, Uuid,
10611064
};
10621065
use buzz_sdk::mentions::{
10631066
extract_at_mentions_with_known, extract_at_names, match_names_to_profiles, MentionProfile,
@@ -1132,7 +1135,7 @@ mod tests {
11321135
let channel = "123e4567-e89b-12d3-a456-426614174000";
11331136
let other_channel = "123e4567-e89b-12d3-a456-426614174001";
11341137
let selected = json!({
1135-
"tags": [["h", channel], ["e", ID_A, "", "root"]]
1138+
"tags": [["h", channel], ["e", ID_A, "", "root"], ["e", ID_B, "", "reply"]]
11361139
});
11371140

11381141
assert!(resolve_thread_target(
@@ -1171,6 +1174,23 @@ mod tests {
11711174
assert_eq!(find_root_from_tags(&tags).as_deref(), Some(ID_A));
11721175
}
11731176

1177+
#[test]
1178+
fn root_marker_without_reply_is_top_level() {
1179+
let tags = json!([["e", ID_A, "", "root"], ["p", PUBKEY],]);
1180+
assert!(find_root_from_tags(&tags).is_none());
1181+
}
1182+
1183+
#[test]
1184+
fn root_only_parent_starts_cli_reply_thread_at_parent() {
1185+
let tags = json!([["e", ID_A, "", "root"]]);
1186+
let parent = nostr::EventId::from_hex(ID_B).expect("valid parent id");
1187+
1188+
let thread_ref = thread_ref_from_parent_tags(parent, ID_B, &tags).expect("thread ref");
1189+
1190+
assert_eq!(thread_ref.parent_event_id, parent);
1191+
assert_eq!(thread_ref.root_event_id, parent);
1192+
}
1193+
11741194
#[test]
11751195
fn reply_only_falls_back_to_reply_target() {
11761196
// Direct reply to a top-level message — the parent's only e-tag is a
@@ -1194,14 +1214,16 @@ mod tests {
11941214
}
11951215

11961216
#[test]
1197-
fn malformed_tags_are_skipped() {
1217+
fn malformed_tags_are_skipped_and_root_only_is_top_level() {
1218+
// Invalid entries are ignored, leaving a valid root-only marker; the
1219+
// shared collapse rule still classifies that parent as top-level.
11981220
let tags = json!([
11991221
"not-an-array",
12001222
["e"],
12011223
["e", "short"],
12021224
["e", ID_A, "", "root"],
12031225
]);
1204-
assert_eq!(find_root_from_tags(&tags).as_deref(), Some(ID_A));
1226+
assert!(find_root_from_tags(&tags).is_none());
12051227
}
12061228

12071229
#[test]

‎crates/buzz-core/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ pub mod invite;
2626
pub mod kind;
2727
/// Network utilities — SSRF-safe IP classification.
2828
pub mod network;
29+
/// NIP-10 thread-marker parsing — shared `root`/`reply` marker resolver.
30+
pub mod nip10;
2931
/// Agent observer frame helpers.
3032
pub mod observer;
3133
/// NIP-AB device pairing — crypto primitives, message types, and errors.

0 commit comments

Comments
 (0)