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/thinking.rs,crates/openhuman-core/src/cr

Steven Enamakele534c9a114b2
diff --git a/crates/openhuman-core/src/channels/bus/thinking.rs b/crates/openhuman-core/src/channels/bus/thinking.rs
new file mode 100644
index 0000000000..6ba49a87d9
--- /dev/null
+++ b/crates/openhuman-core/src/channels/bus/thinking.rs
@@ -0,0 +1,137 @@
+//! Posting and progressively editing the ephemeral "💭 Thinking:" bubble.
+
+use super::progressive_ui::{
+ channel_edits_unsupported, classify_edit_failure, mark_channel_edits_unsupported,
+ EditFailure, MAX_FILLER_CHARS, MAX_THINKING_DISPLAY_CHARS,
+};
+use super::streaming_state::StreamingState;
+use serde_json::json;
+
+/// Send or edit the ephemeral "💭 Thinking…" message on the channel.
+/// This message is deleted when the final response is ready.
+pub(super) async fn flush_thinking_message(channel: &str, state: &mut StreamingState) {
+ state.thinking_dirty = false;
+
+ if state.thinking_accumulator.trim().is_empty() {
+ return;
+ }
+
+ let mut snippet = state.thinking_accumulator.trim().to_string();
+ if snippet.len() > MAX_THINKING_DISPLAY_CHARS {
+ snippet.truncate(MAX_THINKING_DISPLAY_CHARS);
+ snippet.push('…');
+ }
+ let text = format!("💭 Thinking:\n_{snippet}_");
+
+ let Some((client, jwt)) = super::delivery::build_channel_client().await else {
+ return;
+ };
+
+ if let Some(msg_id) = state.thinking_message_id.clone() {
+ // Known-missing edit route: the bubble stays as first posted and is
+ // deleted at finalization. Skip the guaranteed 404.
+ if channel_edits_unsupported(channel) {
+ tracing::debug!(
+ "[channel-inbound][thinking] skipping edit channel='{}' msg_id={} — no edit route on this backend, bubble stays until finalize deletes it",
+ channel,
+ msg_id,
+ );
+ state.latch_thinking_edits_unsupported();
+ return;
+ }
+ // Edit existing thinking message with updated content.
+ let body = json!({ "text": text });
+ if let Err(err) = client.send_channel_edit(channel, &msg_id, &jwt, body).await {
+ match classify_edit_failure(&err) {
+ EditFailure::RouteUnsupported => {
+ // Keep `thinking_message_id`. Clearing it (as the old
+ // `MessageNotFound` branch did) meant finalization had
+ // nothing to delete, so the ephemeral "💭 Thinking:"
+ // bubble stayed in the chat forever (#5230).
+ tracing::info!(
+ "[channel-inbound][thinking] edit channel='{}' msg_id={} — backend has no edit route, keeping id so finalize still deletes the bubble",
+ channel,
+ msg_id,
+ );
+ mark_channel_edits_unsupported(channel);
+ state.latch_thinking_edits_unsupported();
+ }
+ EditFailure::MessageGone => {
+ tracing::info!(
+ "[channel-inbound][thinking] edit channel='{}' msg_id={} — thinking msg gone provider-side (404), clearing id and disabling further thinking edits",
+ channel,
+ msg_id,
+ );
+ state.forget_thinking();
+ }
+ EditFailure::Transient => {
+ tracing::debug!(
+ "[channel-inbound][thinking] edit failed channel='{}' msg_id={} err={}",
+ channel,
+ msg_id,
+ err,
+ );
+ }
+ }
+ }
+ } else {
+ // Send initial thinking message.
+ let body =
+ super::delivery::channel_message_body_with_idempotency(channel, json!({ "text": text }));
+ match client.send_channel_message(channel, &jwt, body).await {
+ Ok(resp) => {
+ state.thinking_sent = true;
+ let id = super::draft::extract_message_id(&resp);
+ if let Some(id) = id {
+ tracing::debug!(
+ "[channel-inbound][thinking] thinking msg sent channel='{}' msg_id={}",
+ channel,
+ id,
+ );
+ state.thinking_message_id = Some(id);
+ } else {
+ tracing::warn!(
+ "[channel-inbound][thinking] thinking msg sent but response lacked id — disabling further thinking flushes (message won't be deletable) channel='{}' resp={}",
+ channel,
+ resp,
+ );
+ state.thinking_edit_disabled = true;
+ }
+ }
+ Err(err) => {
+ tracing::warn!(
+ "[channel-inbound][thinking] failed to send thinking msg channel='{}' err={} — disabling further thinking flushes",
+ channel,
+ err,
+ );
+ state.thinking_edit_disabled = true;
+ }
+ }
+ }
+}
+
+/// Pull the most recent `MAX_FILLER_CHARS` Unicode scalars out of the
+/// thinking accumulator so we can surface a live snapshot of the agent's
+/// reasoning as a filler. Returns `None` when there's nothing to show
+/// yet. Trims any partial leading word so the snippet reads cleanly.
+pub(super) fn latest_thinking_snippet(state: &StreamingState) -> Option<String> {
+ let acc = state.thinking_accumulator.trim();
+ if acc.is_empty() {
+ return None;
+ }
+ let total = acc.chars().count();
+ let snippet: String = if total <= MAX_FILLER_CHARS {
+ acc.to_string()
+ } else {
+ acc.chars().skip(total - MAX_FILLER_CHARS).collect()
+ };
+ let trimmed = snippet
+ .trim_start_matches(|c: char| !c.is_whitespace())
+ .trim_start()
+ .to_string();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed)
+ }
+}
diff --git a/crates/openhuman-core/src/cron/store/runs.rs b/crates/openhuman-core/src/cron/store/runs.rs
new file mode 100644
index 0000000000..05ce45f46e
--- /dev/null
+++ b/crates/openhuman-core/src/cron/store/runs.rs
@@ -0,0 +1,176 @@
+//! Cron run-history persistence: recording job outcomes with bounded output,
+//! pruning old history, and reading it back.
+
+use super::schema::{parse_rfc3339, sql_conversion_error, with_connection};
+use crate::config::Config;
+use crate::cron::{next_run_for_schedule, CronJob, CronRun};
+use anyhow::{Context, Result};
+use chrono::{DateTime, Utc};
+use rusqlite::params;
+
+const MAX_CRON_OUTPUT_BYTES: usize = 16 * 1024;
+const TRUNCATED_OUTPUT_MARKER: &str = "\n...[truncated]";
+
+pub fn record_last_run(
+ config: &Config,
+ job_id: &str,
+ finished_at: DateTime<Utc>,
+ success: bool,
+ output: &str,
+) -> Result<()> {
+ let status = if success { "ok" } else { "error" };
+ let bounded_output = truncate_cron_output(output);
+ with_connection(config, |conn| {
+ conn.execute(
+ "UPDATE cron_jobs
+ SET last_run = ?1, last_status = ?2, last_output = ?3
+ WHERE id = ?4",
+ params![finished_at.to_rfc3339(), status, bounded_output, job_id],
+ )
+ .context("Failed to update cron last run fields")?;
+ Ok(())
+ })
+}
+
+pub fn reschedule_after_run(
+ config: &Config,
+ job: &CronJob,
+ success: bool,
+ output: &str,
+) -> Result<()> {
+ let now = Utc::now();
+ let next_run = next_run_for_schedule(&job.schedule, now)?;
+ let status = if success { "ok" } else { "error" };
+ let bounded_output = truncate_cron_output(output);
+
+ with_connection(config, |conn| {
+ conn.execute(
+ "UPDATE cron_jobs
+ SET next_run = ?1, last_run = ?2, last_status = ?3, last_output = ?4
+ WHERE id = ?5",
+ params![
+ next_run.to_rfc3339(),
+ now.to_rfc3339(),
+ status,
+ bounded_output,
+ job.id
+ ],
+ )
+ .context("Failed to update cron job run state")?;
+ Ok(())
+ })
+}
+
+pub fn record_run(
+ config: &Config,
+ job_id: &str,
+ started_at: DateTime<Utc>,
+ finished_at: DateTime<Utc>,
+ status: &str,
+ output: Option<&str>,
+ duration_ms: i64,
+) -> Result<()> {
+ let bounded_output = output.map(truncate_cron_output);
+ with_connection(config, |conn| {
+ // Wrap INSERT + pruning DELETE in an explicit transaction so that
+ // if the DELETE fails, the INSERT is rolled back and the run table
+ // cannot grow unboundedly.
+ let tx = conn.unchecked_transaction()?;
+
+ tx.execute(
+ "INSERT INTO cron_runs (job_id, started_at, finished_at, status, output, duration_ms)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
+ params![
+ job_id,
+ started_at.to_rfc3339(),
+ finished_at.to_rfc3339(),
+ status,
+ bounded_output.as_deref(),
+ duration_ms,
+ ],
+ )
+ .context("Failed to insert cron run")?;
+
+ let keep = config.cron.max_run_history.max(1) as i64;
+ tx.execute(
+ "DELETE FROM cron_runs
+ WHERE job_id = ?1
+ AND id NOT IN (
+ SELECT id FROM cron_runs
+ WHERE job_id = ?1
+ ORDER BY started_at DESC, id DESC
+ LIMIT ?2
+ )",
+ params![job_id, keep],
+ )
+ .context("Failed to prune cron run history")?;
+
+ tx.commit()
+ .context("Failed to commit cron run transaction")?;
+ Ok(())
+ })
+}
+
+/// Remove all "queued" placeholder records for a given job so that only the
+/// real (ok/error) result row remains in the run history.
+pub fn delete_queued_runs(config: &Config, job_id: &str) -> Result<usize> {
+ with_connection(config, |conn| {
+ let deleted = conn.execute(
+ "DELETE FROM cron_runs WHERE job_id = ?1 AND status = 'queued'",
+ params![job_id],
+ )?;
+ Ok(deleted)
+ })
+}
+
+fn truncate_cron_output(output: &str) -> String {
+ if output.len() <= MAX_CRON_OUTPUT_BYTES {
+ return output.to_string();
+ }
+
+ if MAX_CRON_OUTPUT_BYTES <= TRUNCATED_OUTPUT_MARKER.len() {
+ return TRUNCATED_OUTPUT_MARKER.to_string();
+ }
+
+ let mut cutoff = MAX_CRON_OUTPUT_BYTES - TRUNCATED_OUTPUT_MARKER.len();
+ while cutoff > 0 && !output.is_char_boundary(cutoff) {
+ cutoff -= 1;
+ }
+
+ let mut truncated = output[..cutoff].to_string();
+ truncated.push_str(TRUNCATED_OUTPUT_MARKER);
+ truncated
+}
+
+pub fn list_runs(config: &Config, job_id: &str, limit: usize) -> Result<Vec<CronRun>> {
+ with_connection(config, |conn| {
+ let lim = i64::try_from(limit.max(1)).context("Run history limit overflow")?;
+ let mut stmt = conn.prepare(
+ "SELECT id, job_id, started_at, finished_at, status, output, duration_ms
+ FROM cron_runs
+ WHERE job_id = ?1
+ ORDER BY started_at DESC, id DESC
+ LIMIT ?2",
+ )?;
+
+ let rows = stmt.query_map(params![job_id, lim], |row| {
+ Ok(CronRun {
+ id: row.get(0)?,
+ job_id: row.get(1)?,
+ started_at: parse_rfc3339(&row.get::<_, String>(2)?)
+ .map_err(sql_conversion_error)?,
+ finished_at: parse_rfc3339(&row.get::<_, String>(3)?)
+ .map_err(sql_conversion_error)?,
+ status: row.get(4)?,
+ output: row.get(5)?,
+ duration_ms: row.get(6)?,
+ })
+ })?;
+
+ let mut runs = Vec::new();
+ for row in rows {
+ runs.push(row?);
+ }
+ Ok(runs)
+ })
+}