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
feat(progress): add serialization support for progress tracing
Steven Enamakele557b4778440
diff --git a/crates/openhuman-core/src/agent/progress_tracing/serialize.rs b/crates/openhuman-core/src/agent/progress_tracing/serialize.rsnew file mode 100644index 0000000000..4f60b9fb41--- /dev/null+++ b/crates/openhuman-core/src/agent/progress_tracing/serialize.rs@@ -0,0 +1,106 @@+//! Content truncation caps, small JSON-value builders, and NDJSON+//! serialization for finished spans.++use crate::config::schema::AgentTracingBackend;++use super::types::TraceSpan;++/// Cap on tool arguments / tool output recorded onto spans when content+/// capture is on. Keeps a single runaway tool result from bloating the trace+/// batch while still giving Langfuse an actionable preview.+pub(super) const MAX_TOOL_CONTENT_CHARS: usize = 4_000;++/// Cap on captured error text (Langfuse observation `statusMessage`).+pub(super) const MAX_ERROR_MESSAGE_CHARS: usize = 500;++/// Cap on captured model request/completion content and subagent+/// prompt/output. Larger than the tool cap because a generation's input is the+/// full message array (system prompt included) — but still bounded so a+/// 100k-token context can't push the ingestion batch past Langfuse's event+/// size limits.+pub(super) const MAX_MODEL_CONTENT_CHARS: usize = 25_000;++/// Capture a model-payload JSON value for a span: kept structured when it+/// serializes within [`MAX_MODEL_CONTENT_CHARS`], else degraded to a truncated+/// string (readable in Langfuse, bounded in size).+pub(super) fn capture_model_content(value: &serde_json::Value) -> serde_json::Value {+ let serialized = value.to_string();+ if serialized.chars().count() <= MAX_MODEL_CONTENT_CHARS {+ value.clone()+ } else {+ serde_json::Value::String(truncate_chars(&serialized, MAX_MODEL_CONTENT_CHARS))+ }+}++/// Truncate `text` to `max` characters, appending an explicit truncation+/// marker (with the omitted char count) when content was dropped. Returns the+/// input unchanged when it already fits. Slices on char boundaries, so it+/// never panics on multi-byte content.+pub(super) fn truncate_chars(text: &str, max: usize) -> String {+ match text.char_indices().nth(max) {+ None => text.to_string(),+ Some((byte_end, _)) => {+ let omitted = text.chars().count() - max;+ format!("{}…[truncated {omitted} chars]", &text[..byte_end])+ }+ }+}++/// Truncate tool-content text to [`MAX_TOOL_CONTENT_CHARS`].+pub(super) fn truncate_capture_text(text: &str) -> String {+ truncate_chars(text, MAX_TOOL_CONTENT_CHARS)+}++pub(super) fn status_of(success: bool) -> super::types::SpanStatus {+ if success {+ super::types::SpanStatus::Ok+ } else {+ super::types::SpanStatus::Error+ }+}++pub(super) fn json_str(s: &str) -> serde_json::Value {+ serde_json::Value::String(s.to_string())+}++pub(super) fn json_u32(n: u32) -> serde_json::Value {+ serde_json::Value::Number(n.into())+}++pub(super) fn json_u64(n: u64) -> serde_json::Value {+ serde_json::Value::Number(n.into())+}++pub(super) fn json_usize(n: usize) -> serde_json::Value {+ serde_json::Value::Number((n as u64).into())+}++pub(super) fn json_f64(n: f64) -> serde_json::Value {+ serde_json::Number::from_f64(n)+ .map(serde_json::Value::Number)+ // NaN/inf can't be JSON numbers — degrade to null rather than panic.+ .unwrap_or(serde_json::Value::Null)+}++/// Serialize spans to NDJSON (one span object per line) in the requested+/// backend envelope. Both backends share the [`TraceSpan`] body; Langfuse+/// wraps each line with a `{"type":"span-create", ...}` observation envelope+/// so it can be POSTed to the Langfuse ingestion API, while OTel emits the+/// bare span. Returns an empty string for an empty slice.+pub(crate) fn spans_to_ndjson(backend: AgentTracingBackend, spans: &[TraceSpan]) -> String {+ let mut out = String::new();+ for span in spans {+ let line = match backend {+ AgentTracingBackend::Otel => serde_json::to_string(span),+ AgentTracingBackend::Langfuse => serde_json::to_string(&serde_json::json!({+ "type": "span-create",+ "body": span,+ })),+ };+ if let Ok(line) = line {+ out.push_str(&line);+ out.push('\n');+ }+ }+ out+}diff --git a/crates/openhuman-core/src/channels/bus/draft.rs b/crates/openhuman-core/src/channels/bus/draft.rsnew file mode 100644index 0000000000..15d39b95d5--- /dev/null+++ b/crates/openhuman-core/src/channels/bus/draft.rs@@ -0,0 +1,160 @@+//! Posting and progressively editing the evolving "draft" reply bubble.++use super::progressive_ui::{+ channel_edits_unsupported, classify_edit_failure, mark_channel_edits_unsupported,+ EditFailure, MAX_EDIT_FAILURES,+};+use super::streaming_state::StreamingState;+use serde_json::json;++/// Post or edit a draft message carrying the latest buffered text ++/// tool status. On the first call, sends a new message and records its+/// id; on subsequent calls, edits the existing message.+pub(super) async fn flush_streaming_edit(channel: &str, state: &mut StreamingState) {+ let draft = state.compose_draft();+ if draft.is_empty() {+ return;+ }+ state.dirty = false;++ let Some((client, jwt)) = super::delivery::build_channel_client().await else {+ return;+ };++ if let Some(ref message_id) = state.message_id {+ // Known-missing edit route: skip the guaranteed 404 and let+ // finalization replace the draft (delete + fresh atomic reply).+ if channel_edits_unsupported(channel) {+ tracing::debug!(+ "[channel-inbound][stream] skipping edit channel='{}' msg_id={} — no edit route on this backend, draft stays as-is until finalize",+ channel,+ message_id,+ );+ state.latch_draft_edits_unsupported();+ return;+ }+ let body = json!({ "text": draft });+ match client+ .send_channel_edit(channel, message_id, &jwt, body)+ .await+ {+ Ok(_) => {+ tracing::debug!(+ "[channel-inbound][stream] edit ok channel='{}' msg_id={} chars={}",+ channel,+ message_id,+ draft.len(),+ );+ state.edit_failures = 0;+ }+ Err(err) => {+ match classify_edit_failure(&err) {+ EditFailure::RouteUnsupported => {+ // Keep `message_id`: the draft is still on screen and+ // finalization must be able to delete it before posting+ // the canonical reply. Clearing it here (as the old+ // `MessageNotFound` branch did) orphaned the draft and+ // produced a stale "_working…_" bubble (#5230).+ tracing::info!(+ "[channel-inbound][stream] edit channel='{}' msg_id={} — backend has no edit route, keeping id for finalize cleanup and disabling progressive edits",+ channel,+ message_id,+ );+ mark_channel_edits_unsupported(channel);+ state.latch_draft_edits_unsupported();+ return;+ }+ EditFailure::MessageGone => {+ tracing::info!(+ "[channel-inbound][stream] edit channel='{}' msg_id={} — message gone provider-side (404), clearing stale id and disabling further edits",+ channel,+ message_id,+ );+ state.forget_draft();+ return;+ }+ EditFailure::Transient => {}+ }+ state.edit_failures += 1;+ tracing::warn!(+ "[channel-inbound][stream] edit failed channel='{}' msg_id={} err={} (failures={}/{})",+ channel,+ message_id,+ err,+ state.edit_failures,+ MAX_EDIT_FAILURES,+ );+ if state.edit_failures >= MAX_EDIT_FAILURES {+ tracing::info!(+ "[channel-inbound][stream] giving up on progressive edits for channel='{}', falling back to atomic delivery",+ channel,+ );+ state.edit_disabled = true;+ }+ }+ }+ } else {+ let body =+ super::delivery::channel_message_body_with_idempotency(channel, json!({ "text": draft }));+ match client.send_channel_message(channel, &jwt, body).await {+ Ok(resp) => {+ // A message was posted to the user — record that fact+ // *before* checking for an id. Even if we can't extract+ // one (and thus can't edit it further), we must never+ // later fall back to sending a second atomic message.+ state.draft_sent = true;+ let id = extract_message_id(&resp);+ if let Some(id) = id {+ tracing::debug!(+ "[channel-inbound][stream] initial draft sent channel='{}' msg_id={}",+ channel,+ id,+ );+ state.message_id = Some(id);+ } else {+ tracing::warn!(+ "[channel-inbound][stream] initial draft sent but response lacked id — disabling progressive edits (finalize will skip sending a duplicate) channel='{}' resp={}",+ channel,+ resp,+ );+ state.edit_disabled = true;+ }+ }+ Err(err) => {+ state.edit_failures += 1;+ tracing::warn!(+ "[channel-inbound][stream] initial send failed channel='{}' err={} (failures={})",+ channel,+ err,+ state.edit_failures,+ );+ if state.edit_failures >= MAX_EDIT_FAILURES {+ state.edit_disabled = true;+ }+ }+ }+ }+}++/// Extract a message id from a backend `send_channel_message` response.+/// The backend has used at least three shapes: `{"id":"..."}`,+/// `{"data":{"id":"..."}}`, and `{"messageId":1456,"success":true}` —+/// the last one returns the id as a JSON number, not a string, so+/// `as_str()` alone misses it (#600).+pub(super) fn extract_message_id(resp: &serde_json::Value) -> Option<String> {+ let candidate = resp+ .get("id")+ .or_else(|| resp.get("messageId"))+ .or_else(|| resp.get("data").and_then(|d| d.get("id")))+ .or_else(|| resp.get("data").and_then(|d| d.get("messageId")))?;+ if let Some(s) = candidate.as_str() {+ return Some(s.to_string());+ }+ if let Some(n) = candidate.as_i64() {+ return Some(n.to_string());+ }+ if let Some(n) = candidate.as_u64() {+ return Some(n.to_string());+ }+ None+}