Skip to content

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

chore: files changed crates/openhuman-core/src/channels/bus/subscriber.rs,crates/openhuman-core/src/

Steven Enamakelcf02baaa5ccd
diff --git a/crates/openhuman-core/src/channels/bus/subscriber.rs b/crates/openhuman-core/src/channels/bus/subscriber.rs
index 09ec02f8f4..8d29b7b5ed 100644
--- a/crates/openhuman-core/src/channels/bus/subscriber.rs
+++ b/crates/openhuman-core/src/channels/bus/subscriber.rs
@@ -139,155 +139,157 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {
}
};
- let timeout = tokio::time::Duration::from_secs(180);
- let wait = run_channel_reply_loop(async {
- let mut pending = Vec::with_capacity(32);
- let mut batch_timer = tokio::time::interval(tokio::time::Duration::from_millis(20));
- batch_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
- loop {
- tokio::select! {
- biased;
- _ = session.cancelled() => return,
- _ = batch_timer.tick(), if !pending.is_empty() => {
- if let Err(error) = flush_events(&reply, &mut pending).await {
- tracing::error!("[channel-inbound] delivery failed: {error}");
- return;
- }
+ run_channel_reply_loop(event_rx, request_id, channel.clone(), session, &reply).await;
+ }
+}
+
+#[async_trait::async_trait]
+trait ProgressiveReplySink: Send + Sync {
+ async fn feed(&self, events: Vec<ProgressiveEvent>) -> Result<(), String>;
+ async fn finalize(&self, text: &str) -> Result<(), String>;
+}
+
+#[async_trait::async_trait]
+impl ProgressiveReplySink for ModuleProgressiveReply {
+ async fn feed(&self, events: Vec<ProgressiveEvent>) -> Result<(), String> {
+ ModuleProgressiveReply::feed(self, events)
+ .await
+ .map_err(|error| error.to_string())
+ }
+
+ async fn finalize(&self, text: &str) -> Result<(), String> {
+ ModuleProgressiveReply::finalize(self, text)
+ .await
+ .map_err(|error| error.to_string())
+ }
+}
+
+/// Consume the backend socket path's events from the shared runner and project
+/// progress and terminal output onto its module-owned progressive reply.
+async fn run_channel_reply_loop(
+ mut event_rx: tokio::sync::broadcast::Receiver<crate::web_chat::ScopedWebEvent>,
+ request_id: String,
+ channel: String,
+ session: tokio_util::sync::CancellationToken,
+ reply: &dyn ProgressiveReplySink,
+) {
+ let timeout = tokio::time::Duration::from_secs(180);
+ let deadline = tokio::time::Instant::now() + timeout;
+ let mut pending = Vec::with_capacity(32);
+ let mut batch_timer = tokio::time::interval(tokio::time::Duration::from_millis(20));
+ batch_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ tokio::select! {
+ biased;
+ _ = session.cancelled() => return,
+ _ = batch_timer.tick(), if !pending.is_empty() => {
+ if let Err(error) = flush_events(reply, &mut pending).await {
+ tracing::error!("[channel-inbound] delivery failed: {error}");
+ return;
}
- event = event_rx.recv() => {
- match event {
- Ok(ev) if ev.context().request_id == request_id => {
- match ev.wire_event() {
- crate::web_chat::WebChannelEvent::TextDelta { delta, .. } => {
- if let Some(delta) = delta.as_ref() {
- pending.push(ProgressiveEvent::TextDelta(delta.clone()));
- }
+ }
+ _ = tokio::time::sleep_until(deadline) => {
+ tracing::error!("[channel-inbound] agent timed out after {}s", timeout.as_secs());
+ let _ = reply.finalize("Sorry, the request timed out.").await;
+ return;
+ }
+ event = event_rx.recv() => {
+ match event {
+ Ok(ev) if ev.context().request_id == request_id => {
+ match ev.wire_event() {
+ crate::web_chat::WebChannelEvent::TextDelta { delta, .. } => {
+ if let Some(delta) = delta.as_ref() {
+ pending.push(ProgressiveEvent::TextDelta(delta.clone()));
}
- crate::web_chat::WebChannelEvent::ToolCall {
- tool_name: Some(name), ..
- } => pending.push(ProgressiveEvent::ToolCall(name.clone())),
- crate::web_chat::WebChannelEvent::ToolCall { .. } => {}
- crate::web_chat::WebChannelEvent::ToolResult {
- tool_name: Some(name), success, ..
- } => pending.push(ProgressiveEvent::ToolResult {
- tool_name: name.clone(),
- success: success.unwrap_or(true),
- }),
- crate::web_chat::WebChannelEvent::ToolResult { .. } => {}
- crate::web_chat::WebChannelEvent::ThinkingDelta { delta, .. } => {
- if let Some(delta) = delta.as_ref() {
- pending.push(ProgressiveEvent::ThinkingDelta(delta.clone()));
- }
+ }
+ crate::web_chat::WebChannelEvent::ToolCall {
+ tool_name: Some(name), ..
+ } => pending.push(ProgressiveEvent::ToolCall(name.clone())),
+ crate::web_chat::WebChannelEvent::ToolCall { .. } => {}
+ crate::web_chat::WebChannelEvent::ToolResult {
+ tool_name: Some(name), success, ..
+ } => pending.push(ProgressiveEvent::ToolResult {
+ tool_name: name.clone(),
+ success: success.unwrap_or(true),
+ }),
+ crate::web_chat::WebChannelEvent::ToolResult { .. } => {}
+ crate::web_chat::WebChannelEvent::ThinkingDelta { delta, .. } => {
+ if let Some(delta) = delta.as_ref() {
+ pending.push(ProgressiveEvent::ThinkingDelta(delta.clone()));
}
- crate::web_chat::WebChannelEvent::ChatDone { full_response, .. } => {
- if let Err(error) = flush_events(&reply, &mut pending).await {
- tracing::error!("[channel-inbound] delivery failed: {error}");
- return;
- }
- let full_response = full_response.as_deref().unwrap_or_default();
- // Even when the agent produced no visible
- // text, we must close out any draft we
- // already posted — otherwise the user is
- // left staring at a stale "_working…_"
- // message indefinitely.
- let reply_text = if full_response.trim().is_empty() {
- tracing::warn!(
- "[channel-inbound] agent returned empty response — finalizing draft with fallback",
- );
- "(No response from agent.)"
- } else {
- full_response
- };
- tracing::info!(
- "[channel-inbound] agent done, replying to channel='{}' len={}",
- channel,
- reply_text.len(),
- );
- // If we've been streaming progressive edits, replace
- // the outbound message with the final canonical text.
- // Otherwise send a fresh message atomically.
- if let Err(error) = reply.finalize(reply_text).await { tracing::error!("[channel-inbound] final delivery failed: {error}"); }
+ }
+ crate::web_chat::WebChannelEvent::ChatDone { full_response, .. } => {
+ if let Err(error) = flush_events(reply, &mut pending).await {
+ tracing::error!("[channel-inbound] delivery failed: {error}");
return;
}
- crate::web_chat::WebChannelEvent::ChatError { message, .. } => {
- if let Err(error) = flush_events(&reply, &mut pending).await {
- tracing::error!("[channel-inbound] delivery failed: {error}");
- return;
- }
- let err_msg = message.as_deref().unwrap_or("unknown error");
- tracing::error!("[channel-inbound] agent error: {}", err_msg);
- let _ = reply.finalize(&format!("Sorry, I encountered an error: {err_msg}")).await;
+ let full_response = full_response.as_deref().unwrap_or_default();
+ let reply_text = if full_response.trim().is_empty() {
+ tracing::warn!(
+ "[channel-inbound] agent returned empty response — finalizing draft with fallback",
+ );
+ "(No response from agent.)"
+ } else {
+ full_response
+ };
+ tracing::info!(
+ "[channel-inbound] agent done, replying to channel='{}' len={}",
+ channel,
+ reply_text.len(),
+ );
+ if let Err(error) = reply.finalize(reply_text).await {
+ tracing::error!("[channel-inbound] final delivery failed: {error}");
+ }
+ return;
+ }
+ crate::web_chat::WebChannelEvent::ChatError { message, .. } => {
+ if let Err(error) = flush_events(reply, &mut pending).await {
+ tracing::error!("[channel-inbound] delivery failed: {error}");
return;
}
- // New terminal event (see web_chat::ops::channel_ops /
- // start_chat) — emitted alongside
- // `chat_error{error_type:"cancelled"}` for one
- // release. That legacy event already returns
- // above, ending this loop before `chat_cancelled`
- // for the same request_id would be observed, so
- // this arm only fires standalone (a cancel path
- // that stops emitting the legacy event, or one
- // that never did — e.g. the parallel-turn
- // cooperative-cancel path) and never double-ends
- // a turn already finalized by `chat_error`.
- crate::web_chat::WebChannelEvent::ChatCancelled { cancel_reason, .. } => {
- if let Err(error) = flush_events(&reply, &mut pending).await {
- tracing::error!("[channel-inbound] delivery failed: {error}");
- return;
- }
- tracing::info!(
- "[channel-inbound] turn cancelled reason={:?}",
- cancel_reason
- );
- let _ = reply.finalize("Cancelled.").await;
+ let err_msg = message.as_deref().unwrap_or("unknown error");
+ tracing::error!("[channel-inbound] agent error: {}", err_msg);
+ let _ = reply.finalize(&format!("Sorry, I encountered an error: {err_msg}")).await;
+ return;
+ }
+ // The runner may emit ChatCancelled on paths without
+ // the compatibility ChatError event; finalize once.
+ crate::web_chat::WebChannelEvent::ChatCancelled { cancel_reason, .. } => {
+ if let Err(error) = flush_events(reply, &mut pending).await {
+ tracing::error!("[channel-inbound] delivery failed: {error}");
return;
}
- _ => {}
+ tracing::info!("[channel-inbound] turn cancelled reason={:?}", cancel_reason);
+ let _ = reply.finalize("Cancelled.").await;
+ return;
}
- }
- Ok(_) => {}
- Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
- tracing::warn!("[channel-inbound] event bus lagged, skipped {} events", n);
- }
- Err(tokio::sync::broadcast::error::RecvError::Closed) => {
- tracing::error!("[channel-inbound] event bus closed unexpectedly");
- return;
+ _ => {}
}
}
- if pending.len() >= 32 {
- if let Err(error) = flush_events(&reply, &mut pending).await {
- tracing::error!("[channel-inbound] delivery failed: {error}");
- return;
- }
+ Ok(_) => {}
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
+ tracing::warn!("[channel-inbound] event bus lagged, skipped {} events", n);
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => {
+ tracing::error!("[channel-inbound] event bus closed unexpectedly");
+ return;
+ }
+ }
+ if pending.len() >= 32 {
+ if let Err(error) = flush_events(reply, &mut pending).await {
+ tracing::error!("[channel-inbound] delivery failed: {error}");
+ return;
}
}
-
}
}
- }).await;
- if wait.is_err() {
- tracing::error!(
- "[channel-inbound] agent timed out after {}s",
- timeout.as_secs()
- );
- let _ = reply.finalize("Sorry, the request timed out.").await;
- }
}
}
-/// The backend socket path's legacy fixed deadline around its shared-runner
-/// event stream. Kept separate so the same wait policy can be exercised with
-/// Tokio's virtual clock and later replaced by the runner's own lifecycle.
-async fn run_channel_reply_loop(
- event_loop: impl std::future::Future<Output = ()>,
-) -> Result<(), tokio::time::error::Elapsed> {
- tokio::time::timeout(tokio::time::Duration::from_secs(180), event_loop).await
-}
-
async fn flush_events(
- reply: &ModuleProgressiveReply,
+ reply: &dyn ProgressiveReplySink,
pending: &mut Vec<ProgressiveEvent>,
-) -> Result<(), tinybus::module::ModuleCallError> {
+) -> Result<(), String> {
if pending.is_empty() {
return Ok(());
}
diff --git a/crates/openhuman-core/src/channels/bus/subscriber_tests.rs b/crates/openhuman-core/src/channels/bus/subscriber_tests.rs
index 5daee6acbc..b6c6ddf969 100644
--- a/crates/openhuman-core/src/channels/bus/subscriber_tests.rs
+++ b/crates/openhuman-core/src/channels/bus/subscriber_tests.rs
@@ -1,42 +1,99 @@
use super::*;
+use crate::core::runtime::DispatchCtx;
+use std::sync::Mutex;
use std::time::Duration;
+use tinychannels_bus::web::{WebChannelEvent, WebEventContext};
-/// This uses the same fixed-deadline helper as the backend socket subscriber.
-/// Progress at 100 seconds is followed by a terminal event at 201 seconds,
-/// which the shared turn runner accepts but the subscriber legacy wrapper
-/// currently cuts off at 180 seconds.
+#[derive(Default)]
+struct RecordingReply {
+ progress: Mutex<Vec<ProgressiveEvent>>,
+ finalized: Mutex<Vec<String>>,
+}
+
+#[async_trait::async_trait]
+impl ProgressiveReplySink for RecordingReply {
+ async fn feed(&self, events: Vec<ProgressiveEvent>) -> Result<(), String> {
+ self.progress.lock().unwrap().extend(events);
+ Ok(())
+ }
+
+ async fn finalize(&self, text: &str) -> Result<(), String> {
+ self.finalized.lock().unwrap().push(text.to_owned());
+ Ok(())
+ }
+}
+
+/// The real backend-channel event consumer must keep the live shared-runner
+/// turn through its terminal event. Progress at 100 seconds is followed by a
+/// successful runner completion at 201 seconds; the old subscriber deadline
+/// finalizes its timeout copy at 180 seconds instead.
#[tokio::test(start_paused = true)]
async fn backend_channel_wait_does_not_cut_off_a_live_turn_after_180_seconds() {
- let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
- let event_loop = async move {
- let consumer = async move {
- let mut progress = 0;
- while let Some(event) = rx.recv().await {
- match event {
- "progress" => progress += 1,
- "terminal" => return progress,
- _ => {}
- }
- }
- progress
- };
- let producer = async move {
- tokio::time::sleep(Duration::from_secs(100)).await;
- tx.send("progress").expect("event consumer remains active");
- tokio::time::sleep(Duration::from_secs(101)).await;
- tx.send("terminal")
- .expect("terminal consumer remains active");
- };
- let (progress, ()) = tokio::join!(consumer, producer);
- progress
+ let _serial = crate::web_chat::RUN_CHAT_TASK_TEST_LOCK.lock().await;
+ let block = crate::web_chat::TestRunChatTaskBlock {
+ started: Default::default(),
+ dropped: Default::default(),
+ release: Default::default(),
+ succeed_in: Some(tempfile::tempdir().expect("temporary workspace").keep()),
};
+ crate::web_chat::set_test_run_chat_task_block(Some(block.clone())).await;
- let result = run_channel_reply_loop(async {
- let _progress_count = event_loop.await;
- })
- .await;
- assert!(
- result.is_ok(),
- "the live turn should reach its terminal event after 201 seconds"
+ let ctx = DispatchCtx::ambient();
+ let client_id = "channel-timeout-client";
+ let thread_id = "channel-timeout-thread";
+ let mut event_rx = crate::web_chat::subscribe_web_channel_events();
+ let request_id = crate::web_chat::start_chat(
+ &ctx,
+ client_id,
+ thread_id,
+ "keep working",
+ None,
+ None,
+ None,
+ None,
+ crate::web_chat::ChatRequestMetadata {
+ source: Some("channel_inbound".into()),
+ ..Default::default()
+ },
+ )
+ .await
+ .expect("the shared runner accepts the inbound channel turn");
+ while !block.started.load(std::sync::atomic::Ordering::SeqCst) {
+ tokio::task::yield_now().await;
+ }
+
+ let sink = RecordingReply::default();
+ let session = tokio_util::sync::CancellationToken::new();
+ let producer = async {
+ tokio::time::sleep(Duration::from_secs(100)).await;
+ crate::web_chat::publish_web_channel_event_in(
+ &ctx,
+ WebChannelEvent::TextDelta {
+ context: WebEventContext {
+ client_id: client_id.into(),
+ thread_id: thread_id.into(),
+ request_id: request_id.clone(),
+ ..Default::default()
+ },
+ delta: Some("still working".into()),
+ delta_kind: None,
+ round: Some(1),
+ },
+ );
+ tokio::time::sleep(Duration::from_secs(101)).await;
+ block.release.notify_one();
+ };
+ let consumer = run_channel_reply_loop(event_rx, request_id, "telegram".into(), session, &sink);
+ tokio::join!(producer, consumer);
+ crate::web_chat::set_test_run_chat_task_block(None).await;
+
+ assert_eq!(
+ *sink.progress.lock().unwrap(),
+ vec![ProgressiveEvent::TextDelta("still working".into())]
+ );
+ assert_eq!(
+ *sink.finalized.lock().unwrap(),
+ vec!["parked reply".to_string()],
+ "the subscriber should deliver the runner's terminal reply once, not its timeout copy"
);
}