The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(cron): suppress NO_REPLY only for jobs whose prompt allows it
oxoxDevdc9e6e734dce
diff --git a/crates/openhuman-core/src/cron/scheduler/delivery.rs b/crates/openhuman-core/src/cron/scheduler/delivery.rsindex eb5b2923f8..6b131ac286 100644--- a/crates/openhuman-core/src/cron/scheduler/delivery.rs+++ b/crates/openhuman-core/src/cron/scheduler/delivery.rs@@ -3,7 +3,7 @@use super::agent_run::EMPTY_AGENT_OUTPUT;use super::failure_classification::AGENT_JOB_USER_FAILURE_MESSAGE;-use super::origin_delivery::{deliver_to_origin, is_suppressed_output};+use super::origin_delivery::{deliver_to_origin, deliverable_reply, is_no_reply, origin_kind};use crate::config::Config;use crate::core::bus::BUS;use crate::core::events::DomainEvent;@@ -151,17 +151,29 @@ pub(super) async fn deliver_run(mode.as_str(),delivery_mode::PROACTIVE | delivery_mode::ANNOUNCE | delivery_mode::ORIGIN);- // An origin-mode run that deliberately said nothing (`NO_REPLY` or blank)- // is not an event worth an alert.- let intentionally_silent =- success && mode == delivery_mode::ORIGIN && is_suppressed_output(output);+ let reply = if delivers {+ deliverable_reply(job, output)+ } else {+ None+ };+ if delivers && success && reply.is_some() && is_no_reply(output) {+ tracing::info!(+ job_id = %job.id,+ run_id = %run_id,+ mode = %mode,+ "[cron] run answered NO_REPLY but the job must deliver; sending the fallback reminder"+ );+ }+ // A delivering run that intentionally said nothing (blank, or `NO_REPLY`+ // from a job that allows it) is not an event worth an alert.+ let intentionally_silent = success && delivers && reply.is_none();let alert_to_notifications = cron_result_should_alert(success, output)&& (!success || delivers)&& !intentionally_silent;let alert_body = if is_empty {"Scheduled job failed without output."} else {- output+ reply.as_deref().unwrap_or(output)};let mut status = if delivers {@@ -182,8 +194,8 @@ pub(super) async fn deliver_run(// Proactive delivery — the channels module decides where to send.// Used by morning briefings, welcome messages, and other// user-facing proactive agents.- "proactive" => {- if deliver_to_chat {+ "proactive" => match reply.as_deref().filter(|_| deliver_to_chat) {+ Some(message) => {let source = format!("cron:{}", job.id);tracing::debug!(job_id = %job.id,@@ -192,58 +204,62 @@ pub(super) async fn deliver_run();BUS.publish(DomainEvent::ProactiveMessageRequested {source,- message: output.to_string(),+ message: message.to_string(),job_name: job.name.clone(),});status = DeliveryStatus::Delivered;}- }+ None if deliver_to_chat => log_suppressed(job, run_id),+ None => {}+ },// Announce delivery — the cron job specifies the exact channel// and target. Send synchronously so the recorded status reflects// whether the channel runtime accepted the message.- "announce" if deliver_to_chat => {- let channel = delivery- .channel- .as_deref()- .ok_or_else(|| anyhow::anyhow!("delivery.channel is required for announce mode"))?;- let target = delivery- .to- .as_deref()- .ok_or_else(|| anyhow::anyhow!("delivery.to is required for announce mode"))?;-- let idempotency_key = super::origin_delivery::origin_request_id(&job.id, run_id);- match crate::cron::channel_bridge::send_to_channel(- channel,- target,- None,- output,- &idempotency_key,- )- .await- {- Ok(()) => {- tracing::debug!(- job_id = %job.id,- run_id = %run_id,- channel = %channel,- "[cron] announce delivery sent"- );- status = DeliveryStatus::Delivered;- }- Err(error) => {- tracing::warn!(- job_id = %job.id,- run_id = %run_id,- channel = %channel,- target = %target,- error = %error,- "[cron] announce delivery failed"- );- status = DeliveryStatus::Failed;+ "announce" if deliver_to_chat => match reply.as_deref() {+ None => log_suppressed(job, run_id),+ Some(message) => {+ let channel = delivery.channel.as_deref().ok_or_else(|| {+ anyhow::anyhow!("delivery.channel is required for announce mode")+ })?;+ let target = delivery+ .to+ .as_deref()+ .ok_or_else(|| anyhow::anyhow!("delivery.to is required for announce mode"))?;++ let idempotency_key = super::origin_delivery::origin_request_id(&job.id, run_id);+ match crate::cron::channel_bridge::send_to_channel(+ channel,+ target,+ None,+ message,+ &idempotency_key,+ )+ .await+ {+ Ok(()) => {+ tracing::debug!(+ job_id = %job.id,+ run_id = %run_id,+ channel = %channel,+ "[cron] announce delivery sent"+ );+ status = DeliveryStatus::Delivered;+ }+ Err(error) => {+ tracing::warn!(+ job_id = %job.id,+ run_id = %run_id,+ channel = %channel,+ target = %target,+ error = %error,+ "[cron] announce delivery failed"+ );+ status = DeliveryStatus::Failed;+ }}}- }+ },// No delivery configured — output is stored in last_output only.// The failure still reaches the alerts tab via the hoisted@@ -264,6 +280,16 @@ pub(super) async fn deliver_run(Ok(status)}+fn log_suppressed(job: &CronJob, run_id: &str) {+ tracing::info!(+ job_id = %job.id,+ run_id = %run_id,+ mode = %job.delivery.mode,+ origin = origin_kind(job),+ "[cron] delivery suppressed: the run had nothing to send"+ );+}+/// Insert a notification into the alerts tab for a completed cron job.pub(super) fn push_cron_alert(config: &Config, job: &CronJob, output: &str) {use crate::desktop::notifications::store as notif_store;diff --git a/crates/openhuman-core/src/cron/scheduler/delivery_tests.rs b/crates/openhuman-core/src/cron/scheduler/delivery_tests.rsindex 0198d72dc7..30c34ee84f 100644--- a/crates/openhuman-core/src/cron/scheduler/delivery_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler/delivery_tests.rs@@ -13,3 +13,131 @@ pub(crate) async fn deliver_if_configured(.await.map(|_| ())}++fn proactive_job() -> CronJob {+ CronJob {+ claim_generation: 0,+ policy: Default::default(),+ id: format!("test-job-{}", uuid::Uuid::new_v4()),+ expression: "* * * * *".into(),+ schedule: tinyflows_bus::schedule::types::Schedule::Every { every_ms: 300_000 },+ command: String::new(),+ prompt: None,+ name: None,+ job_type: JobType::Agent,+ session_target: tinyflows_bus::schedule::types::SessionTarget::Isolated,+ model: None,+ agent_id: None,+ enabled: true,+ delivery: DeliveryConfig {+ mode: "proactive".into(),+ channel: None,+ to: None,+ best_effort: true,+ },+ delete_after_run: false,+ created_at: Utc::now(),+ next_run: Utc::now(),+ last_run: None,+ last_status: None,+ last_output: None,+ origin: None,+ }+}++async fn test_config(tmp: &tempfile::TempDir) -> Config {+ let workspace = tmp.path().join("workspace");+ std::fs::create_dir_all(&workspace).unwrap();+ Config {+ workspace_dir: workspace.clone(),+ action_dir: workspace,+ config_path: tmp.path().join("config.toml"),+ ..Config::default()+ }+}++async fn cron_alerts(config: &Config) -> usize {+ crate::desktop::notifications::store::list(config, 10, 0, Some("cron"), None)+ .unwrap()+ .len()+}++#[derive(Default)]+struct ProactiveCollector {+ source: String,+ messages: std::sync::Arc<std::sync::Mutex<Vec<String>>>,+}++#[async_trait::async_trait]+impl tinybus::EventHandler<crate::core::events::DomainEvent> for ProactiveCollector {+ fn name(&self) -> &str {+ "test::scheduler::proactive_no_reply::collector"+ }++ async fn handle(&self, event: &crate::core::events::DomainEvent) {+ if let crate::core::events::DomainEvent::ProactiveMessageRequested {+ source, message, ..+ } = event+ {+ if *source == self.source {+ self.messages.lock().unwrap().push(message.clone());+ }+ }+ }+}++async fn proactive_run(+ job: &CronJob,+ config: &Config,+ output: &str,+) -> (DeliveryStatus, Vec<String>) {+ crate::core::bus::init().await.expect("bus init");+ let messages = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let _handle = crate::core::bus::BUS+ .subscribe(std::sync::Arc::new(ProactiveCollector {+ source: format!("cron:{}", job.id),+ messages: std::sync::Arc::clone(&messages),+ }))+ .expect("bus subscriber installed");+ let status = deliver_run(+ &crate::core::runtime::DispatchCtx::ambient(),+ config,+ job,+ "run-1",+ output,+ true,+ )+ .await+ .unwrap();+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;+ let seen = messages.lock().unwrap().clone();+ (status, seen)+}++fn proactive_agent_job(prompt: &str) -> CronJob {+ let mut job = proactive_job();+ job.prompt = Some(prompt.into());+ job.name = Some("stretch".into());+ job+}++#[tokio::test]+async fn proactive_allowed_no_reply_publishes_nothing() {+ let tmp = tempfile::TempDir::new().unwrap();+ let config = test_config(&tmp).await;+ let job = proactive_agent_job("Summarise new mail, otherwise reply NO_REPLY");+ let (status, seen) = proactive_run(&job, &config, "NO_REPLY").await;+ assert_eq!(status, DeliveryStatus::Suppressed);+ assert!(seen.is_empty(), "{seen:?}");+ assert_eq!(cron_alerts(&config).await, 0);+}++#[tokio::test]+async fn proactive_disallowed_no_reply_publishes_the_fallback_not_the_token() {+ let tmp = tempfile::TempDir::new().unwrap();+ let config = test_config(&tmp).await;+ let job = proactive_agent_job("Remind the user to stretch");+ let (status, seen) = proactive_run(&job, &config, "`NO_REPLY`").await;+ assert_eq!(status, DeliveryStatus::Delivered);+ assert_eq!(seen, vec!["Reminder: stretch".to_string()]);+}diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rsindex 984efc4716..735aceb5fb 100644--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery.rs@@ -1,9 +1,12 @@//! `delivery.mode = "origin"`: commit a run's reply into the conversation that//! asked for it and send it there once.//!-//! - Empty output, or exactly [`NO_REPLY`], is an intentional "nothing to-//! say": recorded as [`DeliveryStatus::Suppressed`], nothing is sent and no-//! alert is raised.+//! - Empty output is recorded as [`DeliveryStatus::Suppressed`]; nothing is+//! sent and no alert is raised.+//! - A [`NO_REPLY`] answer (any spelling [`is_no_reply`] accepts) is suppressed+//! the same way only when the job opted into silence by naming the token in+//! its own prompt ([`job_allows_no_reply`]). Otherwise the token is never+//! sent: the host's [`fallback_reminder`] is delivered in its place.//! - Web origin: the reply is stored in the origin thread first, under the//! deterministic id of `run_reply_message_id("cron:<job>:<run>")`, then//! announced on the web channel as a `proactive_message` event addressed to@@ -20,16 +23,86 @@ use std::path::Path;use {crate::cron::channel_bridge, tinyflows_bus::schedule::types::CronJob,tinyflows_bus::schedule::types::DeliveryStatus, tinyflows_bus::schedule::types::JobOrigin,+ tinyflows_bus::schedule::types::JobType,};/// What a scheduled run replies when it has nothing worth sending.pub(crate) const NO_REPLY: &str = "NO_REPLY";-/// True when a run's output means "deliver nothing": blank, or exactly-/// [`NO_REPLY`] after trimming (case-sensitive).-pub(crate) fn is_suppressed_output(output: &str) -> bool {+/// True when `output` is the [`NO_REPLY`] token in any common spelling: any+/// case, `_`, `-` or a space between the words, wrapped in quotes, backticks+/// or emphasis, with trailing punctuation.+pub(crate) fn is_no_reply(output: &str) -> bool {+ let core = output.trim_matches(|c: char| {+ c.is_whitespace()+ || matches!(+ c,+ '"' | '\'' | '`' | '*' | '_' | '.' | '!' | '?' | ',' | ';' | ':'+ )+ });+ let folded: String = core+ .chars()+ .filter(|c| !matches!(c, '_' | '-' | ' '))+ .flat_map(char::to_lowercase)+ .collect();+ folded == "noreply"+}++/// True when the job may end a run with [`NO_REPLY`]: its prompt names the+/// token (a conditional check such as "otherwise reply NO_REPLY"). Shell and+/// flow output is not model-written, so those jobs always may.+pub(crate) fn job_allows_no_reply(job: &CronJob) -> bool {+ if !matches!(job.job_type, JobType::Agent) {+ return true;+ }+ job.prompt+ .as_deref()+ .is_some_and(|prompt| prompt.to_ascii_lowercase().contains("no_reply"))+}++/// The reminder the host sends when a run that must deliver produced no+/// message: the job's name, else its prompt.+pub(crate) fn fallback_reminder(job: &CronJob) -> String {+ let subject = job+ .name+ .as_deref()+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .map(str::to_string)+ .or_else(|| {+ job.prompt+ .as_deref()+ .map(str::trim)+ .filter(|prompt| !prompt.is_empty())+ .map(|prompt| crate::util::truncate_with_ellipsis(prompt, 200))+ });+ match subject {+ Some(subject) => format!("Reminder: {subject}"),+ None => "Reminder".to_string(),+ }+}++/// The text a run delivers, or `None` when it intentionally sends nothing+/// (blank output, or [`NO_REPLY`] from a job that allows it). A disallowed+/// `NO_REPLY` becomes the job's [`fallback_reminder`].+pub(crate) fn deliverable_reply(job: &CronJob, output: &str) -> Option<String> {let trimmed = output.trim();- trimmed.is_empty() || trimmed == NO_REPLY+ if trimmed.is_empty() {+ return None;+ }+ if is_no_reply(trimmed) {+ return (!job_allows_no_reply(job)).then(|| fallback_reminder(job));+ }+ Some(trimmed.to_string())+}++/// The kind of conversation a job delivers to, for logs.+pub(crate) fn origin_kind(job: &CronJob) -> &'static str {+ match job.origin {+ Some(JobOrigin::Web { .. }) => "web",+ Some(JobOrigin::Channel { .. }) => "channel",+ None => "none",+ }}/// The deterministic request id of one run's delivered reply.@@ -138,8 +211,9 @@ pub(crate) fn origin_transcripts(/// Deliver one run's output to the job's origin conversation.///-/// `Ok(Suppressed)` for an intentional empty/`NO_REPLY` output; `Ok(Delivered)`-/// when the reply was committed and sent; `Err` when it could not be.+/// `Ok(Suppressed)` when the run intentionally sends nothing (see+/// [`deliverable_reply`]); `Ok(Delivered)` when the reply was committed and+/// sent; `Err` when it could not be.pub(crate) async fn deliver_to_origin(ctx: &crate::core::runtime::DispatchCtx,config: &Config,@@ -147,20 +221,21 @@ pub(crate) async fn deliver_to_origin(run_id: &str,output: &str,) -> Result<DeliveryStatus> {- if is_suppressed_output(output) {- tracing::debug!(+ let Some(reply) = deliverable_reply(job, output) else {+ tracing::info!(job_id = %job.id,run_id = %run_id,- "[cron] origin delivery suppressed (empty or NO_REPLY)"+ origin = origin_kind(job),+ "[cron] origin delivery suppressed: the run had nothing to send");return Ok(DeliveryStatus::Suppressed);- }+ };let Some(origin) = job.origin.as_ref() else {return Err(anyhow!("delivery mode 'origin' requires the job to have an origin conversation"));};- let text = output.trim();+ let text = reply.as_str();// The job's tenant: a hosted profile's or an embedded agent's host routes// the reply itself; otherwise it keys the transcript store below.diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rsindex d24ab22cdd..6542419fdf 100644--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery_tests.rs@@ -74,38 +74,122 @@ fn seed_thread(config: &Config, id: &str) {.unwrap();}+fn conditional(origin: Option<JobOrigin>) -> CronJob {+ let mut j = job(origin);+ j.prompt = Some("Check the inbox; reply NO_REPLY if nothing changed".into());+ j+}++fn thread_messages(cfg: &Config, thread: &str) -> Vec<String> {+ conversations::get_messages(+ &crate::core::runtime::DispatchCtx::ambient(),+ cfg.workspace_dir.clone(),+ thread,+ )+ .unwrap()+ .into_iter()+ .map(|m| m.content)+ .collect()+}+#[test]-fn suppressed_output_is_blank_or_exactly_no_reply() {- for s in ["", " \n", "NO_REPLY", " NO_REPLY\n"] {- assert!(is_suppressed_output(s), "{s:?}");+fn no_reply_is_recognised_in_its_common_spellings() {+ for s in [+ "NO_REPLY",+ " no_reply ",+ "No_reply.",+ "`NO_REPLY`",+ "**NO_REPLY**",+ "NO REPLY",+ "no-reply!",+ "\"NO_REPLY\"",+ ] {+ assert!(is_no_reply(s), "{s:?}");}- for s in ["no_reply", "NO_REPLY please", "Drink water!"] {- assert!(!is_suppressed_output(s), "{s:?}");+ for s in [+ "",+ "Drink water!",+ "NO_REPLY please",+ "No reply needed, here's your newsletter: three stories today.",+ ] {+ assert!(!is_no_reply(s), "{s:?}");}}+#[test]+fn only_a_prompt_that_names_the_token_allows_no_reply() {+ assert!(!job_allows_no_reply(&job(None)));+ assert!(job_allows_no_reply(&conditional(None)));+ let mut lower = job(None);+ lower.prompt = Some("summarise new mail, otherwise reply no_reply".into());+ assert!(job_allows_no_reply(&lower));+ let mut shell = job(None);+ shell.job_type = JobType::Shell;+ shell.prompt = None;+ assert!(+ job_allows_no_reply(&shell),+ "shell output is not model-written"+ );+}++#[test]+fn fallback_reminder_names_the_job_or_its_prompt() {+ assert_eq!(fallback_reminder(&job(None)), "Reminder: water");+ let mut unnamed = job(None);+ unnamed.name = None;+ assert_eq!(fallback_reminder(&unnamed), "Reminder: drink water");+ unnamed.prompt = None;+ assert_eq!(fallback_reminder(&unnamed), "Reminder");+}++#[test]+fn deliverable_reply_suppresses_only_blank_or_an_allowed_no_reply() {+ assert_eq!(deliverable_reply(&job(None), " \n"), None);+ assert_eq!(deliverable_reply(&conditional(None), " NO_REPLY "), None);+ assert_eq!(+ deliverable_reply(&job(None), "No_reply."),+ Some("Reminder: water".into())+ );+ assert_eq!(+ deliverable_reply(&job(None), " Drink water! "),+ Some("Drink water!".into())+ );+}+#[tokio::test]-async fn no_reply_is_suppressed_without_writing_anything() {+async fn an_allowed_no_reply_is_suppressed_without_writing_anything() {let tmp = tempfile::TempDir::new().unwrap();let cfg = config(&tmp);seed_thread(&cfg, "t-1");let status = deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(),&cfg,- &job(Some(web("t-1"))),+ &conditional(Some(web("t-1"))),"run-1"," NO_REPLY ",).await.unwrap();assert_eq!(status, DeliveryStatus::Suppressed);- assert!(conversations::get_messages(+ assert!(thread_messages(&cfg, "t-1").is_empty());+}++#[tokio::test]+async fn a_disallowed_no_reply_delivers_the_fallback_never_the_token() {+ let tmp = tempfile::TempDir::new().unwrap();+ let cfg = config(&tmp);+ seed_thread(&cfg, "t-1");+ let status = deliver_to_origin(&crate::core::runtime::DispatchCtx::ambient(),- cfg.workspace_dir.clone(),- "t-1"+ &cfg,+ &job(Some(web("t-1"))),+ "run-1",+ "No_reply.",)- .unwrap()- .is_empty());+ .await+ .unwrap();+ assert_eq!(status, DeliveryStatus::Delivered);+ assert_eq!(thread_messages(&cfg, "t-1"), vec!["Reminder: water"]);}#[tokio::test]diff --git a/crates/openhuman-core/src/cron/scheduler_announce_delivery_tests.rs b/crates/openhuman-core/src/cron/scheduler_announce_delivery_tests.rsindex 1f84a1f856..cbdde65471 100644--- a/crates/openhuman-core/src/cron/scheduler_announce_delivery_tests.rs+++ b/crates/openhuman-core/src/cron/scheduler_announce_delivery_tests.rs@@ -142,3 +142,54 @@ async fn announce_success_is_reported_and_uses_a_run_idempotency_key() {vec![("target".into(), Some(format!("cron:{}:run-3", job.id)))]);}++fn agent_announce_job(channel: String, prompt: &str) -> CronJob {+ let mut job = test_job("");+ job.job_type = JobType::Agent;+ job.prompt = Some(prompt.into());+ job.delivery = DeliveryConfig {+ mode: "announce".into(),+ channel: Some(channel),+ to: Some("target".into()),+ best_effort: false,+ };+ job+}++#[tokio::test]+async fn announce_skips_an_allowed_no_reply_and_never_sends_the_token() {+ let _bridge_lock = crate::cron::channel_bridge::TEST_BRIDGE_LOCK.lock().await;+ let tmp = TempDir::new().unwrap();+ let config = test_config(&tmp).await;+ let channel = format!("quiet-{}", uuid::Uuid::new_v4());+ let sends = install_mock_channel(channel.clone(), false);++ let conditional = agent_announce_job(channel.clone(), "Report changes, otherwise NO_REPLY");+ let status = deliver_run(+ &crate::core::runtime::DispatchCtx::ambient(),+ &config,+ &conditional,+ "run-4",+ "NO_REPLY",+ true,+ )+ .await+ .unwrap();+ assert_eq!(status, DeliveryStatus::Suppressed);+ assert!(sends.lock().unwrap().is_empty());+ assert_eq!(cron_alerts(&config).await, 0);++ let reminder = agent_announce_job(channel, "Remind the user to stretch");+ let status = deliver_run(+ &crate::core::runtime::DispatchCtx::ambient(),+ &config,+ &reminder,+ "run-5",+ "No_reply.",+ true,+ )+ .await+ .unwrap();+ assert_eq!(status, DeliveryStatus::Delivered);+ assert_eq!(sends.lock().unwrap().len(), 1);+}