Skip to content
This repository was archived by the owner on Sep 14, 2026. It is now read-only.

Commit 3e90361

Browse files
maikunariclaude
andcommitted
fix(cli): preserve attachments on buzz messages edit
buzz messages edit stripped every attachment off a message. build_edit emitted only h + e tags, and the desktop render/cache overlay reads an edit with zero imeta tags as "attachments cleared" (intentional, so deliberate removal works). The CLI never carried imeta forward, so an agent fixing a typo silently deleted its own screenshots. Desktop was fixed in block#755; the CLI was never brought along. Fix at the builder + CLI, not the overlay: - build_edit (buzz-sdk) gains a media_tags parameter and emits imeta via the same imeta_tags() helper build_message uses. - buzz messages edit gains --file (replace attachments, uploaded like messages send) and --no-media (clear). With neither flag it fetches the target event and carries its existing imeta tags forward, so edits stop losing attachments by default. The single event fetch already done to resolve the channel id is reused to read the carry-forward imeta, so no extra relay round-trip. A failed fetch aborts before signing, so an attachment-wiping edit can never be published on error. Closes block#3022 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: Mike Sewell <[email protected]>
1 parent f53bbd1 commit 3e90361

5 files changed

Lines changed: 259 additions & 15 deletions

File tree

‎crates/buzz-cli/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ buzz messages get --channel <uuid> --limit 20
3636
buzz messages thread --channel <uuid> --event <event-id>
3737
buzz messages search --query "architecture"
3838
buzz messages search --author <pubkey|npub|name> --since <unix-ts>
39-
buzz messages edit --event <event-id> --content "Updated text"
39+
buzz messages edit --event <event-id> --content "Updated text" # attachments preserved
40+
buzz messages edit --event <event-id> --content "Updated text" --file pic.png # replace attachments
41+
buzz messages edit --event <event-id> --content "Updated text" --no-media # drop all attachments
4042
buzz messages delete --event <event-id>
4143

4244
# Diffs

‎crates/buzz-cli/TESTING.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,8 @@ buzz messages thread --channel "$CHANNEL_ID" --event "$EVENT_ID" | jq .
223223
buzz messages search --query "Hello" | jq .
224224
buzz messages search --query "CLI test" --limit 5 | jq .
225225

226-
# messages edit
226+
# messages edit (existing attachments are preserved by default;
227+
# --file replaces them, --no-media clears them)
227228
buzz messages edit --event "$EVENT_ID" --content "Edited by CLI test" | jq .
228229

229230
# messages delete

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

Lines changed: 128 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,15 @@ async fn resolve_thread_ref(
8686
/// Resolve the channel UUID for an event by querying for it via POST /query.
8787
/// Extracts the `h` tag value from the returned event's tags.
8888
async fn resolve_channel_id(client: &BuzzClient, event_id: &str) -> Result<Uuid, CliError> {
89+
let event = fetch_event_by_id(client, event_id).await?;
90+
channel_id_from_event(&event, event_id)
91+
}
92+
93+
/// Fetch a single event by its ID via POST /query.
94+
async fn fetch_event_by_id(
95+
client: &BuzzClient,
96+
event_id: &str,
97+
) -> Result<serde_json::Value, CliError> {
8998
let filter = serde_json::json!({
9099
"ids": [event_id]
91100
});
@@ -95,9 +104,13 @@ async fn resolve_channel_id(client: &BuzzClient, event_id: &str) -> Result<Uuid,
95104
let arr = events
96105
.as_array()
97106
.ok_or_else(|| CliError::Other("query response is not an array".into()))?;
98-
let event = arr
99-
.first()
100-
.ok_or_else(|| CliError::Other(format!("event {event_id} not found")))?;
107+
arr.first()
108+
.cloned()
109+
.ok_or_else(|| CliError::Other(format!("event {event_id} not found")))
110+
}
111+
112+
/// Extract the channel UUID from an event's h-tag.
113+
fn channel_id_from_event(event: &serde_json::Value, event_id: &str) -> Result<Uuid, CliError> {
101114
let tags = event
102115
.get("tags")
103116
.and_then(|t| t.as_array())
@@ -149,6 +162,27 @@ fn resolve_names_to_pubkeys(
149162
Ok(resolved)
150163
}
151164

165+
/// Extract raw `imeta` tag vectors from a fetched event's JSON tags.
166+
/// Only `imeta` tags are returned — no other tag kinds are carried.
167+
fn extract_imeta_tags(event: &serde_json::Value) -> Vec<Vec<String>> {
168+
event
169+
.get("tags")
170+
.and_then(|t| t.as_array())
171+
.map(|tags| {
172+
tags.iter()
173+
.filter_map(|t| t.as_array())
174+
.filter(|parts| parts.first().and_then(|v| v.as_str()) == Some("imeta"))
175+
.map(|parts| {
176+
parts
177+
.iter()
178+
.filter_map(|v| v.as_str().map(String::from))
179+
.collect()
180+
})
181+
.collect()
182+
})
183+
.unwrap_or_default()
184+
}
185+
152186
/// Resolve mention text against the channel membership snapshot.
153187
///
154188
/// Returns both the current member set and uniquely name-resolved pubkeys.
@@ -812,19 +846,61 @@ pub async fn cmd_delete_message(
812846
}
813847

814848
/// Edit a message you previously sent.
849+
///
850+
/// Attachment semantics:
851+
/// - No `--file` and no `--no-media`: preserves existing attachments (default carry-forward)
852+
/// - `--file` provided: replaces attachments with the uploaded file(s) and appends markdown
853+
/// - `--no-media`: removes all attachments from the message
815854
pub async fn cmd_edit_message(
816855
client: &BuzzClient,
817856
event_id: &str,
818857
content: &str,
858+
files: &[String],
859+
no_media: bool,
819860
) -> Result<(), CliError> {
820861
validate_hex64(event_id)?;
821862
validate_content_size(content)?;
822863

823-
// Resolve channel_id from the event's h-tag
824-
let channel_uuid = resolve_channel_id(client, event_id).await?;
864+
// Fetch the target event once; derive both the channel id and the
865+
// carry-forward attachment set from that single query.
866+
let target_event = fetch_event_by_id(client, event_id).await?;
867+
let channel_uuid = channel_id_from_event(&target_event, event_id)?;
825868
let target_eid = parse_event_id(event_id)?;
826869

827-
let builder = buzz_sdk::build_edit(channel_uuid, target_eid, content)
870+
// Decide media_tags and final_content based on flags
871+
let (media_tags, final_content) = if no_media {
872+
// --no-media: clear all attachments
873+
(Vec::new(), content.to_string())
874+
} else if !files.is_empty() {
875+
// --file provided: upload files and replace attachments
876+
let mut media_tags: Vec<Vec<String>> = Vec::new();
877+
let mut media_content = String::new();
878+
for file_path in files {
879+
let desc = client
880+
.upload_file(file_path)
881+
.await
882+
.map_err(|e| CliError::Other(format!("upload failed for {file_path}: {e}")))?;
883+
media_tags.push(crate::client::build_imeta_tag(&desc));
884+
if desc.mime_type.starts_with("video/") {
885+
media_content.push_str("\n![video](");
886+
} else {
887+
media_content.push_str("\n![image](");
888+
}
889+
media_content.push_str(&desc.url);
890+
media_content.push(')');
891+
}
892+
let final_content = if media_content.is_empty() {
893+
content.to_string()
894+
} else {
895+
format!("{}{media_content}", content)
896+
};
897+
(media_tags, final_content)
898+
} else {
899+
// Default: preserve existing attachments
900+
(extract_imeta_tags(&target_event), content.to_string())
901+
};
902+
903+
let builder = buzz_sdk::build_edit(channel_uuid, target_eid, &final_content, &media_tags)
828904
.map_err(|e| CliError::Other(format!("build_edit failed: {e}")))?;
829905

830906
let event = client.sign_event(builder)?;
@@ -928,7 +1004,12 @@ pub async fn dispatch(
9281004
)
9291005
.await
9301006
}
931-
MessagesCmd::Edit { event, content } => cmd_edit_message(client, &event, &content).await,
1007+
MessagesCmd::Edit {
1008+
event,
1009+
content,
1010+
files,
1011+
no_media,
1012+
} => cmd_edit_message(client, &event, &content, &files, no_media).await,
9321013
MessagesCmd::Delete {
9331014
event,
9341015
action_id,
@@ -993,8 +1074,8 @@ pub async fn dispatch(
9931074
#[cfg(test)]
9941075
mod tests {
9951076
use super::{
996-
event_mention_pubkeys, find_root_from_tags, match_profiles_by_name, merge_message_mentions,
997-
missing_members, normalize_explicit_mentions, parse_member_pubkeys,
1077+
event_mention_pubkeys, extract_imeta_tags, find_root_from_tags, match_profiles_by_name,
1078+
merge_message_mentions, missing_members, normalize_explicit_mentions, parse_member_pubkeys,
9981079
resolve_names_to_pubkeys,
9991080
};
10001081
use buzz_sdk::mentions::{
@@ -1372,4 +1453,42 @@ mod tests {
13721453
];
13731454
assert_eq!(match_profiles_by_name(&events, "Aaron").len(), 1);
13741455
}
1456+
1457+
#[test]
1458+
fn extract_imeta_tags_returns_only_imeta() {
1459+
let event = json!({
1460+
"tags": [
1461+
["h", "channel-uuid"],
1462+
["e", "event-id", "", "reply"],
1463+
["imeta", "url", "https://example.com/image.png", "m", "image/png"],
1464+
["emoji", "🎉"],
1465+
["imeta", "url", "https://example.com/video.mp4", "m", "video/mp4"],
1466+
]
1467+
});
1468+
let imeta_tags = extract_imeta_tags(&event);
1469+
assert_eq!(imeta_tags.len(), 2);
1470+
// Verify the full imeta vectors are preserved
1471+
assert_eq!(imeta_tags[0][0], "imeta");
1472+
assert_eq!(imeta_tags[0][1], "url");
1473+
assert_eq!(imeta_tags[1][0], "imeta");
1474+
}
1475+
1476+
#[test]
1477+
fn extract_imeta_tags_empty_when_none() {
1478+
let event = json!({
1479+
"tags": [
1480+
["h", "channel-uuid"],
1481+
["e", "event-id"],
1482+
]
1483+
});
1484+
let imeta_tags = extract_imeta_tags(&event);
1485+
assert!(imeta_tags.is_empty());
1486+
}
1487+
1488+
#[test]
1489+
fn extract_imeta_tags_handles_missing_tags() {
1490+
let event = json!({});
1491+
let imeta_tags = extract_imeta_tags(&event);
1492+
assert!(imeta_tags.is_empty());
1493+
}
13751494
}

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

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,12 @@ pub enum MessagesCmd {
424424
/// New message content
425425
#[arg(long)]
426426
content: String,
427+
/// Replace attachments: upload file(s) and include as imeta tags. Conflicts with --no-media.
428+
#[arg(long = "file", conflicts_with = "no_media")]
429+
files: Vec<String>,
430+
/// Remove all attachments from the message.
431+
#[arg(long, default_value_t = false)]
432+
no_media: bool,
427433
},
428434
/// Delete a message by event ID
429435
Delete {
@@ -2369,7 +2375,7 @@ mod tests {
23692375
);
23702376
}
23712377

2372-
// ── projects update mutation group ────────────────────────────────────────
2378+
// ── projects update mutation group ────────────────────────────────────────
23732379

23742380
/// Multiple independent fields must be accepted in the same invocation.
23752381
#[test]
@@ -2475,4 +2481,63 @@ mod tests {
24752481
"--visibility chartreuse on update must be rejected at parse time"
24762482
);
24772483
}
2484+
2485+
#[test]
2486+
fn messages_edit_file_conflicts_with_no_media() {
2487+
use clap::Parser;
2488+
2489+
// Should error: both --file and --no-media provided
2490+
let result = Cli::try_parse_from(vec![
2491+
"buzz",
2492+
"messages",
2493+
"edit",
2494+
"--event",
2495+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2496+
"--content",
2497+
"test",
2498+
"--file",
2499+
"a.png",
2500+
"--no-media",
2501+
]);
2502+
assert!(result.is_err());
2503+
2504+
// Should succeed: only --file
2505+
let result = Cli::try_parse_from(vec![
2506+
"buzz",
2507+
"messages",
2508+
"edit",
2509+
"--event",
2510+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2511+
"--content",
2512+
"test",
2513+
"--file",
2514+
"a.png",
2515+
]);
2516+
assert!(result.is_ok());
2517+
2518+
// Should succeed: only --no-media
2519+
let result = Cli::try_parse_from(vec![
2520+
"buzz",
2521+
"messages",
2522+
"edit",
2523+
"--event",
2524+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2525+
"--content",
2526+
"test",
2527+
"--no-media",
2528+
]);
2529+
assert!(result.is_ok());
2530+
2531+
// Should succeed: neither flag
2532+
let result = Cli::try_parse_from(vec![
2533+
"buzz",
2534+
"messages",
2535+
"edit",
2536+
"--event",
2537+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2538+
"--content",
2539+
"test",
2540+
]);
2541+
assert!(result.is_ok());
2542+
}
24782543
}

‎crates/buzz-sdk/src/builders.rs‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -380,16 +380,22 @@ pub fn build_diff_message(
380380
}
381381

382382
/// Build an edit event targeting an existing message (kind 40003).
383+
///
384+
/// - `media_tags`: raw imeta tag vectors — the FULL replacement attachment
385+
/// set for the edited message (clients treat an edit's imeta tags as
386+
/// authoritative; an edit with none clears attachments).
383387
pub fn build_edit(
384388
channel_id: Uuid,
385389
target_event_id: nostr::EventId,
386390
new_content: &str,
391+
media_tags: &[Vec<String>],
387392
) -> Result<EventBuilder, SdkError> {
388393
check_content(new_content, 64 * 1024)?;
389-
let tags = vec![
394+
let mut tags = vec![
390395
tag(&["h", &channel_id.to_string()])?,
391396
tag(&["e", &target_event_id.to_hex()])?,
392397
];
398+
imeta_tags(media_tags, &mut tags)?;
393399
Ok(EventBuilder::new(Kind::Custom(40003), new_content).tags(tags))
394400
}
395401

@@ -2542,7 +2548,7 @@ mod tests {
25422548
fn edit_happy_path() {
25432549
let cid = uuid();
25442550
let eid = event_id();
2545-
let ev = sign(build_edit(cid, eid, "new content").unwrap());
2551+
let ev = sign(build_edit(cid, eid, "new content", &[]).unwrap());
25462552
assert_eq!(ev.kind.as_u16(), 40003);
25472553
assert!(has_tag(&ev, "e", &eid.to_hex()));
25482554
}
@@ -2553,11 +2559,62 @@ mod tests {
25532559
let eid = event_id();
25542560
let big = "x".repeat(64 * 1024 + 1);
25552561
assert!(matches!(
2556-
build_edit(cid, eid, &big),
2562+
build_edit(cid, eid, &big, &[]),
25572563
Err(SdkError::ContentTooLarge { .. })
25582564
));
25592565
}
25602566

2567+
#[test]
2568+
fn edit_with_media() {
2569+
let cid = uuid();
2570+
let eid = event_id();
2571+
let media_tags = vec![vec![
2572+
"imeta".to_string(),
2573+
"url https://example.com/image.png".to_string(),
2574+
"m image/png".to_string(),
2575+
]];
2576+
let ev = sign(build_edit(cid, eid, "new content", &media_tags).unwrap());
2577+
assert_eq!(ev.kind.as_u16(), 40003);
2578+
assert!(has_tag(&ev, "e", &eid.to_hex()));
2579+
assert!(has_tag(&ev, "h", &cid.to_string()));
2580+
// Verify the imeta tag is present
2581+
let imeta_tags: Vec<_> = ev
2582+
.tags
2583+
.iter()
2584+
.filter(|t| {
2585+
let s = t.as_slice();
2586+
s.first().map(|v| v.as_str()) == Some("imeta")
2587+
})
2588+
.collect();
2589+
assert_eq!(imeta_tags.len(), 1);
2590+
}
2591+
2592+
#[test]
2593+
fn edit_without_media_has_no_imeta() {
2594+
let cid = uuid();
2595+
let eid = event_id();
2596+
let ev = sign(build_edit(cid, eid, "new content", &[]).unwrap());
2597+
assert_eq!(ev.kind.as_u16(), 40003);
2598+
let imeta_tags: Vec<_> = ev
2599+
.tags
2600+
.iter()
2601+
.filter(|t| {
2602+
let s = t.as_slice();
2603+
s.first().map(|v| v.as_str()) == Some("imeta")
2604+
})
2605+
.collect();
2606+
assert_eq!(imeta_tags.len(), 0);
2607+
}
2608+
2609+
#[test]
2610+
fn edit_rejects_malformed_media_tag() {
2611+
let cid = uuid();
2612+
let eid = event_id();
2613+
let malformed_tags = vec![vec![]];
2614+
let result = build_edit(cid, eid, "new content", &malformed_tags);
2615+
assert!(result.is_err());
2616+
}
2617+
25612618
#[test]
25622619
fn delete_message_happy_path() {
25632620
let cid = uuid();

0 commit comments

Comments
 (0)