From 051dd2d7aaae2cb6ce288cf55d571e9790fc38c2 Mon Sep 17 00:00:00 2001 From: Wes Date: Tue, 17 Nov 2026 14:19:27 -0700 Subject: [PATCH] fix(sdk): timestamp channel messages with millisecond offsets (#9548) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kind-9 messages sent through the SDK or `buzz messages send` omit the `ms` tag, so clients break same-second ties by event ID. Capture one clock reading in the shared message builder and use it for both `created_at` and the canonical 0–999 millisecond offset, including direct and nested replies. Validation: both new regressions failed before the fix; the full CLI suite (691 tests) and SDK suite (335 tests) pass. The SDK test checks that the timestamp is pinned before signing; the CLI test captures and verifies signed HTTP submissions for roots and both reply depths. The built CLI also sent direct and nested replies through a managed signer to a live relay; readback confirmed one canonical `ms` tag and correct thread tags on both. Client ordering and human testing remain pending; keep this PR draft. To test manually, run `cargo build -p buzz-cli`, then send several kind-9 messages with `target/debug/buzz messages send --channel --content ` and direct/nested replies using `--reply-to `. Inspect their raw events: each should carry exactly one canonical `ms` value, and a client that honors `ms` should display same-second sends in timestamp order. Related: #9541 updates mobile display ordering to consume these offsets. No duplicate producer fix found in the open PR/issue search. Repository-wide validation: `just ci` passed Rust/Tauri Clippy and formatting, then failed mobile analysis at `mobile/test/features/search/search_channels_journey_test.dart:933`: `_RenamingSession.subscribeWithStatus` omits the base method's `resumeSince` parameter. Mobile files are unchanged from the base commit. This unrelated failure remains outside this fix. The first push hook run failed the existing WebSocket throttle test `a_throttled_sign_in_reconnects_with_fresh_evidence` (connection reset during sign-in); a subsequent full CLI rerun and the complete normal push-hook retry passed without source changes. The test uses a kind-20001 event and does not call the changed builder. All required push hooks passed. Signed-off-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> --- crates/buzz-cli/src/commands/messages.rs | 45 ++++++++++++++++++++++++ crates/buzz-sdk/src/builders.rs | 42 ++++++++++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/crates/buzz-cli/src/commands/messages.rs b/crates/buzz-cli/src/commands/messages.rs index e2c661ea52..a8a8296250 100644 --- a/crates/buzz-cli/src/commands/messages.rs +++ b/crates/buzz-cli/src/commands/messages.rs @@ -1939,6 +1939,51 @@ mod tests { } } + #[tokio::test] + async fn cmd_send_message_submits_millisecond_timestamp_for_roots_and_replies() { + let root = "11".repeat(32); + let parent = "22".repeat(32); + for (reply_to, parent_tags) in [ + (None, serde_json::json!([])), + (Some(root.clone()), serde_json::json!([])), + (Some(parent), serde_json::json!([["e", root, "", "reply"]])), + ] { + let response = serde_json::json!([{ "tags": parent_tags }]).to_string(); + let (url, _, captured_event) = fake_send_relay(response).await; + let client = BuzzClient::new( + url, + crate::credentials::Credentials::from_keys(Keys::generate()), + ) + .unwrap(); + let mut params = send_params("timestamp"); + params.reply_to = reply_to; + let before = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap(); + cmd_send_message(&client, params).await.unwrap(); + let after = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap(); + let captured = captured_event.lock().unwrap(); + let event: nostr::Event = + serde_json::from_str(&captured.as_ref().unwrap().body).unwrap(); + event.verify().unwrap(); + let offsets: Vec<_> = event + .tags + .iter() + .filter(|tag| tag.as_slice()[0] == "ms") + .collect(); + assert_eq!(offsets.len(), 1); + let offset = &offsets[0].as_slice()[1]; + let milliseconds: u32 = offset.parse().unwrap(); + assert!(milliseconds < 1000); + assert_eq!(*offset, milliseconds.to_string()); + let timestamp = + u128::from(event.created_at.as_secs()) * 1000 + u128::from(milliseconds); + assert!((before.as_millis()..=after.as_millis()).contains(×tamp)); + } + } + #[tokio::test] async fn cmd_send_message_attaches_emoji_tags_for_known_shortcodes() { // Content contains `:wave:` which resolves in the palette. diff --git a/crates/buzz-sdk/src/builders.rs b/crates/buzz-sdk/src/builders.rs index 8a83c86f41..7f8e20489d 100644 --- a/crates/buzz-sdk/src/builders.rs +++ b/crates/buzz-sdk/src/builders.rs @@ -258,6 +258,8 @@ fn nip30_emoji_tags(emoji_tags: &[Vec], tags: &mut Vec) -> Result<( /// - `broadcast`: if true, adds `["broadcast", "1"]` tag /// - `media_tags`: raw imeta tag vectors /// - `emoji_tags`: NIP-30 `["emoji", shortcode, url]` tag vectors +/// +/// Pins `created_at` and the canonical `ms` offset from one clock reading. pub fn build_message( channel_id: Uuid, content: &str, @@ -278,8 +280,13 @@ pub fn build_message( } imeta_tags(media_tags, &mut tags)?; nip30_emoji_tags(emoji_tags, &mut tags)?; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + tags.push(tag(&["ms", &now.subsec_millis().to_string()])?); Ok(EventBuilder::new(Kind::Custom(9), content) .tags(tags) + .custom_created_at(nostr::Timestamp::from(now.as_secs())) .allow_self_tagging()) } @@ -2833,6 +2840,41 @@ mod tests { assert!(has_tag(&ev, "h", &cid.to_string())); } + #[test] + fn message_timestamp_includes_milliseconds_before_signing() { + let root = event_id(); + let direct = ThreadRef { + root_event_id: root, + parent_event_id: root, + }; + let nested = ThreadRef { + root_event_id: root, + parent_event_id: event_id(), + }; + for thread_ref in [None, Some(&direct), Some(&nested)] { + let before = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap(); + let builder = + build_message(uuid(), "timestamp", thread_ref, &[], false, &[], &[]).unwrap(); + let after = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap(); + let created_at = builder + .custom_created_at + .expect("timestamp pinned before signing"); + let event = sign(builder); + assert_eq!(event.created_at, created_at); + let offsets = tag_values(&event, "ms"); + assert_eq!(offsets.len(), 1); + let offset: u32 = offsets[0].parse().unwrap(); + assert!(offset < 1000); + assert_eq!(offsets[0], offset.to_string()); + let milliseconds = u128::from(created_at.as_secs()) * 1000 + u128::from(offset); + assert!((before.as_millis()..=after.as_millis()).contains(&milliseconds)); + } + } + #[test] fn message_preserves_self_mention_p_tag() { // nostr 0.44 strips p tags matching the signer by default.