Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(channels): merge admitted channel message batches

oxoxDev99265491ad89
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/inbound_batch.rs b/crates/openhuman-core/src/channels/runtime/dispatch/inbound_batch.rs
new file mode 100644
index 0000000000..64ee0bbd7b
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/inbound_batch.rs
@@ -0,0 +1,65 @@
+//! Channel messages as [`crate::inbound_debounce`] items, and the merge that
+//! turns one debounced batch into the single message its turn runs on.
+
+use super::processor::AdmittedInbound;
+use crate::inbound_debounce::DebounceItem;
+
+const MEDIA_MARKERS: [&str; 5] = ["[IMAGE:", "[FILE:", "[VIDEO:", "[DOCUMENT:", "[Attachment:"];
+
+/// An admitted message with its receive order on the dispatch queue.
+#[derive(Debug, Clone)]
+pub(crate) struct QueuedInbound {
+ pub(crate) seq: u64,
+ pub(crate) inbound: AdmittedInbound,
+}
+
+impl DebounceItem for QueuedInbound {
+ fn chars(&self) -> usize {
+ self.inbound.msg.content.chars().count()
+ }
+
+ fn carries_media(&self) -> bool {
+ let content = &self.inbound.msg.content;
+ MEDIA_MARKERS.iter().any(|marker| content.contains(marker))
+ }
+
+ fn mergeable(&self) -> bool {
+ let trimmed = self.inbound.msg.content.trim_start();
+ !trimmed.is_empty() && !trimmed.starts_with('/')
+ }
+}
+
+/// Merge a batch into one message: ordered by (timestamp, receive order),
+/// addressed like the newest message, with the non-blank bodies joined by
+/// newlines.
+pub(crate) fn merge_channel_batch(mut batch: Vec<QueuedInbound>) -> Option<AdmittedInbound> {
+ batch.sort_by_key(|item| (item.inbound.msg.timestamp, item.seq));
+ if batch.len() <= 1 {
+ return batch.pop().map(|item| item.inbound);
+ }
+ let sender_name = batch
+ .iter()
+ .rev()
+ .find_map(|item| item.inbound.msg.sender_name.clone());
+ let content = batch
+ .iter()
+ .map(|item| item.inbound.msg.content.as_str())
+ .filter(|content| !content.trim().is_empty())
+ .collect::<Vec<_>>()
+ .join("\n");
+ let count = batch.len();
+ let mut merged = batch.pop()?.inbound;
+ merged.msg.content = content;
+ merged.msg.sender_name = sender_name;
+ tracing::debug!(
+ channel = %merged.msg.channel,
+ message_id = %merged.msg.id,
+ merged = count,
+ "[dispatch][debounce] merged inbound batch"
+ );
+ Some(merged)
+}
+
+#[cfg(test)]
+#[path = "inbound_batch_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/inbound_batch_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/inbound_batch_tests.rs
new file mode 100644
index 0000000000..8c371b8f64
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/inbound_batch_tests.rs
@@ -0,0 +1,85 @@
+use super::*;
+use tinychannels_bus::ChannelMessage;
+
+fn queued(seq: u64, id: &str, timestamp: u64, content: &str) -> QueuedInbound {
+ QueuedInbound {
+ seq,
+ inbound: AdmittedInbound {
+ msg: ChannelMessage {
+ id: id.to_string(),
+ sender: "alice".to_string(),
+ reply_target: format!("reply-{id}"),
+ content: content.to_string(),
+ channel: "telegram".to_string(),
+ timestamp,
+ thread_ts: Some(format!("thread-{id}")),
+ sender_name: None,
+ },
+ history_key: "telegram_alice_reply".to_string(),
+ },
+ }
+}
+
+#[test]
+fn single_message_passes_through_unchanged() {
+ let one = queued(1, "m1", 5, " hello ");
+ let merged = merge_channel_batch(vec![one.clone()]).unwrap();
+ assert_eq!(merged.msg.content, " hello ");
+ assert_eq!(merged.msg.id, "m1");
+ assert_eq!(merged.msg.thread_ts.as_deref(), Some("thread-m1"));
+ assert_eq!(merged.history_key, one.inbound.history_key);
+ assert!(merge_channel_batch(Vec::new()).is_none());
+}
+
+#[test]
+fn merge_orders_by_timestamp_then_receive_order_and_uses_newest_as_base() {
+ let batch = vec![
+ queued(3, "m3", 20, "third"),
+ queued(2, "m2", 10, "second"),
+ queued(1, "m1", 10, "first"),
+ ];
+ let merged = merge_channel_batch(batch).unwrap();
+ assert_eq!(merged.msg.content, "first\nsecond\nthird");
+ assert_eq!(merged.msg.id, "m3");
+ assert_eq!(merged.msg.reply_target, "reply-m3");
+ assert_eq!(merged.msg.thread_ts.as_deref(), Some("thread-m3"));
+ assert_eq!(merged.msg.timestamp, 20);
+}
+
+#[test]
+fn image_caption_then_text_keeps_marker_in_place_and_skips_blanks() {
+ let batch = vec![
+ queued(1, "m1", 1, "[IMAGE:/tmp/a.png]\nlook at this"),
+ queued(2, "m2", 2, " "),
+ queued(3, "m3", 3, "what is it?"),
+ ];
+ let merged = merge_channel_batch(batch).unwrap();
+ assert_eq!(
+ merged.msg.content,
+ "[IMAGE:/tmp/a.png]\nlook at this\nwhat is it?"
+ );
+}
+
+#[test]
+fn sender_name_is_the_last_one_present() {
+ let mut a = queued(1, "m1", 1, "a");
+ a.inbound.msg.sender_name = Some("Alice A".into());
+ let mut b = queued(2, "m2", 2, "b");
+ b.inbound.msg.sender_name = Some("Alice B".into());
+ let c = queued(3, "m3", 3, "c");
+ let merged = merge_channel_batch(vec![a, b, c]).unwrap();
+ assert_eq!(merged.msg.sender_name.as_deref(), Some("Alice B"));
+}
+
+#[test]
+fn item_traits_classify_media_commands_and_blanks() {
+ let image = queued(1, "m1", 1, "[IMAGE:x] caption");
+ assert!(image.carries_media());
+ assert!(image.mergeable());
+ assert_eq!(image.chars(), "[IMAGE:x] caption".chars().count());
+ assert!(queued(1, "m", 1, "[FILE:doc.pdf]").carries_media());
+ assert!(!queued(1, "m", 1, "plain ✓").carries_media());
+ assert_eq!(queued(1, "m", 1, "plain ✓").chars(), 7);
+ assert!(!queued(1, "m", 1, " /status").mergeable());
+ assert!(!queued(1, "m", 1, " \n ").mergeable());
+}
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs b/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
index 6fb02f67b5..801bcfd6eb 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/mod.rs
@@ -2,6 +2,8 @@
//!
//! Sub-modules:
//! * [`helpers`] — small stateless helpers (context block, ACK reaction, typing, workers).
+//! * [`inbound_batch`] — admitted messages as debounce items and the merge of
+//! one batch into the message its turn runs on.
//! * [`host_agent`] — channels bound to a host-registered agent
//! (`agent.channel_agents`): routing, the refusal for a missing agent, the
//! turn runner and the external-channel posture.
@@ -12,6 +14,7 @@
mod helpers;
pub(crate) mod host_agent;
+mod inbound_batch;
mod processor;
mod routing;
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
index a7e430bafb..58a988bc8d 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
@@ -74,6 +74,7 @@ impl From<ChannelMessage> for RuntimeChannelMessage {
}
}
+pub(crate) use admit::AdmittedInbound;
#[cfg(test)]
pub(crate) use approval::channel_has_approval_surface;
pub(crate) use turn::{process_channel_message, process_channel_runtime_message};