Skip to content

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

refactor(cron): simplify channel bridge registration

Steven Enamakel9c0803223c3f
diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
index 3d59e01efa..0d085c7cab 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
@@ -250,13 +250,11 @@ async fn start_channels_inner(mut config: Config, session: CancellationToken) ->
context_slot
.set(Arc::downgrade(&runtime_ctx))
.map_err(|_| anyhow::anyhow!("channel callback context was already initialized"))?;
- // Let cron jobs created from a channel chat read that chat's history, send
- // into it and append their replies to it.
- crate::cron::channel_bridge::register_channel_bridge(
- Arc::clone(&runtime_ctx.conversation_histories),
- Arc::clone(&runtime_ctx.channels_by_name),
- crate::channels::context::MAX_CHANNEL_HISTORY,
- );
+ // Cron channel context and replies use the durable agent transcript; this
+ // bridge retains only the live channel transport adapters.
+ crate::cron::channel_bridge::register_channel_bridge(Arc::clone(
+ &runtime_ctx.channels_by_name,
+ ));
let startup = module_runtime
.as_mut()
diff --git a/crates/openhuman-core/src/cron/channel_bridge.rs b/crates/openhuman-core/src/cron/channel_bridge.rs
index 2248a68964..9b1828495e 100644
--- a/crates/openhuman-core/src/cron/channel_bridge.rs
+++ b/crates/openhuman-core/src/cron/channel_bridge.rs
@@ -1,29 +1,12 @@
-//! Cron's handle on the channel runtime, for jobs bound to a channel
-//! conversation.
-//!
-//! Cron runs outside the channel runtime, but a channel-origin job needs two
-//! things that live in it: the per-chat conversation history (read for the
-//! context tail, appended to after a reminder is delivered) and the live
-//! channel instances (to send through). The runtime registers both here when
-//! it starts; nothing registers in a core with no channels, and every accessor
-//! then answers "unavailable" instead of failing.
+//! Cron's handle on the live channel send adapters. Conversation context and
+//! delivered replies are stored in durable agent transcripts, not here.
use std::collections::HashMap;
-use std::sync::{Arc, Mutex, RwLock};
+use std::sync::{Arc, RwLock};
use tinychannels_bus::SendMessage;
-use tinychannels_runtime::context::ChatMessage;
use tinychannels_runtime::Channel;
-/// Same shape as `channels::context::ConversationHistoryMap`, spelled out so
-/// cron does not depend on the feature-gated `channels` module.
-pub type ChannelHistories = Arc<Mutex<HashMap<String, Vec<ChatMessage>>>>;
-
-/// How many messages a chat's history keeps; matches the channel processor's
-/// own trimming so a delivered reminder never grows it past that bound.
-pub const MAX_HISTORY_MESSAGES: usize = 40;
-
#[derive(Clone)]
struct Bridge {
- histories: ChannelHistories,
channels: Arc<HashMap<String, Arc<dyn Channel>>>,
}
@@ -36,65 +19,13 @@ fn current() -> Option<Bridge> {
slot().read().ok().and_then(|guard| guard.clone())
}
-/// Register the running channel runtime's histories and channels. The latest
+/// Register the running channel runtime's send adapters. The latest
/// registration wins (the runtime restarts on logout/login).
-pub fn register_channel_bridge(
- histories: ChannelHistories,
- channels: Arc<HashMap<String, Arc<dyn Channel>>>,
- max_history: usize,
-) {
- MAX_HISTORY.store(max_history.max(1), std::sync::atomic::Ordering::Relaxed);
+pub fn register_channel_bridge(channels: Arc<HashMap<String, Arc<dyn Channel>>>) {
if let Ok(mut guard) = slot().write() {
- *guard = Some(Bridge {
- histories,
- channels,
- });
- tracing::debug!(max_history, "[cron] channel bridge registered");
- }
-}
-
-static MAX_HISTORY: std::sync::atomic::AtomicUsize =
- std::sync::atomic::AtomicUsize::new(MAX_HISTORY_MESSAGES);
-
-/// The `(role, text)` messages of one chat's history, oldest first. Empty when
-/// no channel runtime is registered or the chat has no history.
-pub fn history_messages(history_key: &str) -> Vec<(String, String)> {
- let Some(bridge) = current() else {
- tracing::debug!("[cron] channel history requested but no channel bridge registered");
- return Vec::new();
- };
- let histories = bridge.histories.lock().unwrap_or_else(|e| e.into_inner());
- histories
- .get(history_key)
- .map(|turns| {
- turns
- .iter()
- .map(|m| (m.role.clone(), m.content.clone()))
- .collect()
- })
- .unwrap_or_default()
-}
-
-/// Append an assistant message to one chat's history and trim it the way the
-/// channel processor does, so the chat's next turn sees what was delivered.
-/// Returns `false` when no channel runtime is registered.
-pub fn append_assistant_message(history_key: &str, text: &str) -> bool {
- let Some(bridge) = current() else {
- tracing::debug!("[cron] channel history append skipped: no channel bridge registered");
- return false;
- };
- let max = MAX_HISTORY.load(std::sync::atomic::Ordering::Relaxed);
- let mut histories = bridge.histories.lock().unwrap_or_else(|e| e.into_inner());
- let turns = histories.entry(history_key.to_string()).or_default();
- turns.push(ChatMessage::assistant(text));
- while turns.len() > max {
- turns.remove(0);
+ *guard = Some(Bridge { channels });
+ tracing::debug!("[cron] channel delivery bridge registered");
}
- tracing::debug!(
- history_len = turns.len(),
- "[cron] appended delivered reply to channel history"
- );
- true
}
/// Send `text` to `reply_target` on the named channel through the registered
diff --git a/crates/openhuman-core/src/cron/channel_bridge_tests.rs b/crates/openhuman-core/src/cron/channel_bridge_tests.rs
index 541bdc3ce2..ecb498022f 100644
--- a/crates/openhuman-core/src/cron/channel_bridge_tests.rs
+++ b/crates/openhuman-core/src/cron/channel_bridge_tests.rs
@@ -30,12 +30,7 @@ impl Channel for MockChannel {
// One test: the bridge is process-global, so keep its steps sequential.
#[tokio::test]
-async fn bridge_reads_appends_trims_and_sends() {
- let histories: ChannelHistories = Arc::new(Mutex::new(HashMap::new()));
- histories.lock().unwrap().insert(
- "k".into(),
- vec![ChatMessage::user("remind me"), ChatMessage::assistant("ok")],
- );
+async fn bridge_sends_with_a_run_specific_idempotency_key() {
let sends = Arc::new(AtomicUsize::new(0));
let last_target = Arc::new(Mutex::new(String::new()));
let ch: Arc<dyn Channel> = Arc::new(MockChannel {
@@ -43,23 +38,7 @@ async fn bridge_reads_appends_trims_and_sends() {
last_target: Arc::clone(&last_target),
});
let channels = Arc::new(HashMap::from([("telegram".to_string(), ch)]));
- register_channel_bridge(Arc::clone(&histories), channels, 3);
-
- assert_eq!(
- history_messages("k"),
- vec![
- ("user".to_string(), "remind me".to_string()),
- ("assistant".to_string(), "ok".to_string())
- ]
- );
- assert!(history_messages("missing").is_empty());
-
- assert!(append_assistant_message("k", "drink water"));
- assert!(append_assistant_message("k", "again"));
- let got = history_messages("k");
- assert_eq!(got.len(), 3, "trimmed to the registered maximum");
- assert_eq!(got.last().unwrap().1, "again");
- assert_eq!(got[0].1, "ok");
+ register_channel_bridge(channels);
send_to_channel("Telegram", "42", None, "hi", "cron:j:r1")
.await