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
refactor(channels): extract progressive delivery into tinychannels crate
Steven Enamakel160827c983c4
diff --git a/crates/openhuman-core/src/channels/bus/delivery.rs b/crates/openhuman-core/src/channels/bus/delivery.rsindex a749ea7da6..05cfb6d0d2 100644--- a/crates/openhuman-core/src/channels/bus/delivery.rs+++ b/crates/openhuman-core/src/channels/bus/delivery.rs@@ -1,9 +1,19 @@-//! Building the backend REST client, sending/deleting channel messages, and-//! finalizing a turn's reply (replacing or deleting any draft in flight).+//! OpenHuman's [`ProgressiveSender`]: progressive channel replies over the+//! backend REST relay.+//!+//! The streaming choreography (draft, thinking and filler bubbles, failure+//! latches, finalize invariants) lives in `tinychannels::delivery::progressive`.+//! This adapter supplies the transport: it resolves the hosted session,+//! attaches idempotency keys, and maps [`BackendApiError`] onto+//! [`ProgressiveSendError`].-use super::progressive_ui::{channel_edits_unsupported, classify_edit_failure, EditFailure};-use super::streaming_state::StreamingState;+use crate::backend::{BackendApiError, BackendClient};+use crate::security::credentials::session_support::{+ get_session_token, is_local_session_token, BackendCredential,+};+use async_trait::async_trait;use serde_json::{json, Value};+use tinychannels::delivery::progressive::{ProgressiveSendError, ProgressiveSender};/// Attach a deterministic idempotency key to an outbound channel message/// body, derived from the channel and message content.@@ -12,184 +22,21 @@ pub(super) fn channel_message_body_with_idempotency(channel: &str, body: Value)tinychannels::legacy_message_value_from_outbound_intent(&intent)}-/// Delete a previously sent message from the channel. Used to clean-/// up ephemeral thinking messages once the final response is ready.-pub(super) async fn delete_channel_message(channel: &str, message_id: &str) {- let Some((client, jwt)) = build_channel_client().await else {- return;- };- match client.send_channel_delete(channel, message_id, &jwt).await {- Ok(_) => {- tracing::info!(- "[channel-inbound] deleted ephemeral msg channel='{}' msg_id={}",- channel,- message_id,- );- }- Err(err) => {- if let Some(crate::backend::BackendApiError::MessageNotFound { .. }) =- err.downcast_ref::<crate::backend::BackendApiError>()- {- tracing::info!(- "[channel-inbound] delete channel='{}' msg_id={} — message already gone provider-side (404), nothing to clean up",- channel,- message_id,- );- } else {- tracing::warn!(- "[channel-inbound] failed to delete ephemeral msg channel='{}' msg_id={} err={}",- channel,- message_id,- err,- );- }- }+/// Map a backend failure onto the recovery the progressive driver needs.+/// Typed, never by message text, so recoveries cannot drift with wording.+pub(super) fn map_backend_error(err: anyhow::Error) -> ProgressiveSendError {+ match err.downcast_ref::<BackendApiError>() {+ Some(BackendApiError::ChannelEditUnsupported { .. }) => {+ ProgressiveSendError::EditUnsupported+ }+ Some(BackendApiError::MessageNotFound { .. }) => ProgressiveSendError::MessageGone,+ _ => ProgressiveSendError::Other(err),}}-/// Deliver the final canonical reply.-///-/// **Invariant**: if a draft message has already been posted to the-/// channel (`state.draft_sent == true`), we MUST NOT post a second-/// message — that would duplicate the visible bubble on the user's-/// side. When we have an id we attempt one last edit; when the id was-/// lost we leave the draft in place silently. The only path that-/// creates a fresh outbound message is when no draft has been posted-/// at all.-pub(super) async fn finalize_channel_reply(- channel: &str,- state: &mut StreamingState,- final_text: &str,-) {- // Deliver the canonical reply FIRST, then clean up the ephemeral- // "💭 Thinking:" bubble. Deleting before the reply would leave the- // chat empty for a beat; this order keeps something visible at all- // times (#600).- 'send: {- if let Some(ref message_id) = state.message_id {- // Once this process knows the backend serves no edit route, the- // "one last edit" below is a guaranteed 404 — go straight to- // replacing the draft. Deleting it first matters: it is still on- // screen showing partial text, so leaving it would strand a stale- // "_working…_" bubble next to the real answer (#5230).- if channel_edits_unsupported(channel) {- tracing::info!(- "[channel-inbound] final edit skipped channel='{}' msg_id={} — no edit route on this backend, replacing the draft with a fresh atomic reply",- channel,- message_id,- );- let orphan = message_id.clone();- delete_channel_message(channel, &orphan).await;- send_channel_reply(channel, final_text).await;- break 'send;- }- // We committed to a draft earlier in the turn. Always attempt- // to edit it with the canonical reply, even when we'd- // previously latched `edit_disabled` during the streaming- // phase — the user is already looking at that message, so a- // late edit attempt is still the right call. If the edit- // fails, delete the orphan draft and send the final reply- // as a fresh atomic message so the user always sees it.- if let Some((client, jwt)) = build_channel_client().await {- let body = json!({ "text": final_text });- match client- .send_channel_edit(channel, message_id, &jwt, body)- .await- {- Ok(_) => {- tracing::info!(- "[channel-inbound] final edit ok channel='{}' msg_id={} chars={}",- channel,- message_id,- final_text.len(),- );- }- Err(err) => match classify_edit_failure(&err) {- EditFailure::MessageGone => {- tracing::info!(- "[channel-inbound] final edit channel='{}' msg_id={} — draft already gone provider-side (404), sending fresh atomic reply",- channel,- message_id,- );- send_channel_reply(channel, final_text).await;- }- // Route absent (or any other failure): the draft is- // still on screen showing partial text, so it has to be- // deleted before the canonical reply lands — otherwise- // the user keeps a stale "_working…_" bubble alongside- // the real answer (#5230).- EditFailure::RouteUnsupported => {- tracing::warn!(- "[channel-inbound] final edit channel='{}' msg_id={} — backend has no edit route, deleting the draft and sending a fresh atomic reply",- channel,- message_id,- );- super::progressive_ui::mark_channel_edits_unsupported(channel);- let orphan = message_id.clone();- delete_channel_message(channel, &orphan).await;- send_channel_reply(channel, final_text).await;- }- EditFailure::Transient => {- tracing::warn!(- "[channel-inbound] final edit failed channel='{}' msg_id={} err={} — deleting orphan draft and sending fresh atomic reply so user still sees the canonical response",- channel,- message_id,- err,- );- let orphan = message_id.clone();- delete_channel_message(channel, &orphan).await;- send_channel_reply(channel, final_text).await;- }- },- }- } else {- tracing::warn!(- "[channel-inbound] cannot finalize channel='{}' msg_id={} — backend client unavailable, draft left in place",- channel,- message_id,- );- }- break 'send;- }- if state.draft_sent {- // A draft was posted but the backend didn't return an id, so- // we have nothing to edit. Since the draft only contains a- // clean text prefix (or "_working…_" placeholder), sending the- // final response as a second bubble is acceptable — leaving- // the user without the canonical reply is worse (#600).- tracing::warn!(- "[channel-inbound] sending fresh reply on channel='{}' — id-less draft exists but user needs the final response",- channel,- );- send_channel_reply(channel, final_text).await;- break 'send;- }- // No draft exists — this is the first (and only) message for the- // turn. Safe to send atomically.- send_channel_reply(channel, final_text).await;- }-- // ── Clean up ephemeral filler + thinking messages ───────────- // Delete after the canonical reply is already on screen so the- // chat is never momentarily empty between the two operations.- // Fillers first (more of them, oldest-first), then the thinking- // bubble — purely cosmetic ordering.- let fillers = std::mem::take(&mut state.filler_message_ids);- for id in fillers {- delete_channel_message(channel, &id).await;- }- if let Some(thinking_id) = state.thinking_message_id.take() {- delete_channel_message(channel, &thinking_id).await;- }-}--/// Construct the REST client + backend credential (API key or session JWT)-/// shared by every outbound channel call on this turn. Returns `None` and logs if either is-/// unavailable so the caller can bail quietly.-pub(super) async fn build_channel_client() -> Option<(- crate::backend::BackendClient,- crate::security::credentials::session_support::BackendCredential,-)> {+/// Construct the REST client plus the hosted session credential. Returns+/// `None` (and logs why) when either is unavailable.+async fn build_channel_client() -> Option<(BackendClient, BackendCredential)> {let config = match crate::config::rpc::load_config_with_timeout().await {Ok(c) => c,Err(e) => {@@ -197,12 +44,8 @@ pub(super) async fn build_channel_client() -> Option<(return None;}};- let jwt = match crate::security::credentials::session_support::get_session_token(&config) {- Ok(Some(token))- if !crate::security::credentials::session_support::is_local_session_token(&token) =>- {- crate::security::credentials::session_support::BackendCredential::Session(token)- }+ let credential = match get_session_token(&config) {+ Ok(Some(token)) if !is_local_session_token(&token) => BackendCredential::Session(token),Ok(_) => {tracing::error!("[channel-inbound] no hosted user session — cannot send");return None;@@ -215,8 +58,8 @@ pub(super) async fn build_channel_client() -> Option<(return None;}};- match crate::backend::BackendClient::from_config(&config) {- Ok(c) => Some((c, jwt)),+ match BackendClient::from_config(&config) {+ Ok(client) => Some((client, credential)),Err(e) => {tracing::error!("[channel-inbound] failed to create API client: {}", e);None@@ -224,58 +67,55 @@ pub(super) async fn build_channel_client() -> Option<(}}-/// Send a text reply back to a channel via the backend REST API.-pub(super) async fn send_channel_reply(channel: &str, text: &str) {- let config = match crate::config::rpc::load_config_with_timeout().await {- Ok(c) => c,- Err(e) => {- tracing::error!("[channel-inbound] failed to load config: {}", e);- return;- }- };+async fn client() -> Result<(BackendClient, BackendCredential), ProgressiveSendError> {+ build_channel_client()+ .await+ .ok_or(ProgressiveSendError::Unavailable)+}- let jwt = match crate::security::credentials::session_support::get_session_token(&config) {- Ok(Some(token))- if !crate::security::credentials::session_support::is_local_session_token(&token) =>- {- crate::security::credentials::session_support::BackendCredential::Session(token)- }- Ok(_) => {- tracing::error!("[channel-inbound] no hosted user session — cannot send");- return;- }- Err(e) => {- tracing::error!(- "[channel-inbound] no backend credential — cannot reply: {}",- e- );- return;- }- };+/// Progressive replies through `BackendClient::send_channel_*`.+pub(super) struct BackendProgressiveSender;- let client = match crate::backend::BackendClient::from_config(&config) {- Ok(c) => c,- Err(e) => {- tracing::error!("[channel-inbound] failed to create API client: {}", e);- return;- }- };+#[async_trait]+impl ProgressiveSender for BackendProgressiveSender {+ async fn send(&self, channel: &str, text: &str) -> Result<Value, ProgressiveSendError> {+ let (client, credential) = client().await?;+ let body = channel_message_body_with_idempotency(channel, json!({ "text": text }));+ client+ .send_channel_message(channel, &credential, body)+ .await+ .map_err(map_backend_error)+ }- let body = channel_message_body_with_idempotency(channel, json!({ "text": text }));- match client.send_channel_message(channel, &jwt, body).await {- Ok(resp) => {- tracing::info!(- "[channel-inbound] reply sent to channel='{}' response={:?}",- channel,- resp- );- }- Err(e) => {- tracing::error!(- "[channel-inbound] failed to send reply to channel='{}': {}",- channel,- e- );- }+ async fn edit(+ &self,+ channel: &str,+ message_id: &str,+ text: &str,+ ) -> Result<(), ProgressiveSendError> {+ let (client, credential) = client().await?;+ client+ .send_channel_edit(channel, message_id, &credential, json!({ "text": text }))+ .await+ .map(drop)+ .map_err(map_backend_error)+ }++ async fn delete(&self, channel: &str, message_id: &str) -> Result<(), ProgressiveSendError> {+ let (client, credential) = client().await?;+ client+ .send_channel_delete(channel, message_id, &credential)+ .await+ .map(drop)+ .map_err(map_backend_error)+ }++ async fn typing(&self, channel: &str) -> Result<(), ProgressiveSendError> {+ let (client, credential) = client().await?;+ client+ .send_channel_typing(channel, &credential)+ .await+ .map(drop)+ .map_err(map_backend_error)}}diff --git a/crates/openhuman-core/src/channels/bus/draft.rs b/crates/openhuman-core/src/channels/bus/draft.rsdeleted file mode 100644index d33bfd48fb..0000000000--- a/crates/openhuman-core/src/channels/bus/draft.rs+++ /dev/null@@ -1,162 +0,0 @@-//! 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-}diff --git a/crates/openhuman-core/src/channels/bus/filler.rs b/crates/openhuman-core/src/channels/bus/filler.rsdeleted file mode 100644index 4b17b4915a..0000000000--- a/crates/openhuman-core/src/channels/bus/filler.rs+++ /dev/null@@ -1,69 +0,0 @@-//! Rotating "still working" filler messages posted during long turns.--use super::progressive_ui::{MAX_FILLER_FAILURES, STATIC_FILLERS};-use super::streaming_state::StreamingState;-use super::thinking::latest_thinking_snippet;-use serde_json::json;--/// Post a fresh filler message to the channel and record its id so-/// `finalize_channel_reply` can delete it once the real response is on-/// screen. Prefers a live snippet of the agent's latest reasoning-/// (`thinking_accumulator`); falls back to the rotating `STATIC_FILLERS`-/// pool when there's no new thinking to show.-pub(super) async fn send_filler_message(channel: &str, state: &mut StreamingState) {- let text = match latest_thinking_snippet(state) {- Some(snippet) if state.last_filler_snippet.as_deref() != Some(snippet.as_str()) => {- state.last_filler_snippet = Some(snippet.clone());- format!("💭 _{snippet}…_")- }- _ => {- let pool = STATIC_FILLERS;- let idx = state.filler_index % pool.len();- state.filler_index = state.filler_index.wrapping_add(1);- pool[idx].to_string()- }- };-- let Some((client, jwt)) = super::delivery::build_channel_client().await else {- return;- };- 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.filler_failures = 0;- if let Some(id) = super::draft::extract_message_id(&resp) {- tracing::debug!(- "[channel-inbound][filler] sent channel='{}' len={} msg_id={}",- channel,- text.len(),- id,- );- state.filler_message_ids.push(id);- } else {- tracing::warn!(- "[channel-inbound][filler] sent but response lacked id — cannot clean up on finalize channel='{}' resp={}",- channel,- resp,- );- }- }- Err(err) => {- state.filler_failures = state.filler_failures.saturating_add(1);- tracing::warn!(- "[channel-inbound][filler] send failed channel='{}' err={} (failures={}/{})",- channel,- err,- state.filler_failures,- MAX_FILLER_FAILURES,- );- if state.filler_failures >= MAX_FILLER_FAILURES {- tracing::info!(- "[channel-inbound][filler] disabling filler messages for channel='{}' — backend unsupported",- channel,- );- state.filler_disabled = true;- }- }- }-}diff --git a/crates/openhuman-core/src/channels/bus/progressive_ui.rs b/crates/openhuman-core/src/channels/bus/progressive_ui.rsdeleted file mode 100644index 694f73a960..0000000000--- a/crates/openhuman-core/src/channels/bus/progressive_ui.rs+++ /dev/null@@ -1,150 +0,0 @@-//! Progressive-UI capability gating: which channels support evolving-//! draft/thinking/filler bubbles, and the per-provider latch that remembers-//! when a backend has answered "no edit route" so we stop re-probing it.--/// Minimum interval between progressive edits of the outbound channel-/// message. Tuned to stay comfortably below Telegram's ~1 edit/sec cap-/// per chat. Slack has a similar soft limit.-pub(super) const EDIT_FLUSH_INTERVAL: tokio::time::Duration =- tokio::time::Duration::from_millis(1000);--/// Maximum consecutive edit failures tolerated before giving up on-/// progressive streaming and falling back to atomic-final delivery.-pub(super) const MAX_EDIT_FAILURES: u32 = 2;--/// How often to re-send the "typing…" indicator while a turn is in-/// flight. Telegram's `sendChatAction` keeps the UI alive for about-/// 5 seconds per call, so we refresh every 4 s to ensure continuity.-pub(super) const TYPING_REFRESH_INTERVAL: tokio::time::Duration =- tokio::time::Duration::from_secs(4);--/// Maximum consecutive typing-indicator failures before we stop-/// trying. One failure is usually "endpoint doesn't exist"; two is-/// enough to conclude the backend doesn't support it on this channel.-pub(super) const MAX_TYPING_FAILURES: u32 = 2;--/// How often to post a filler "still working" message to the channel-/// so the user keeps seeing activity during long agent turns. Deleted-/// on finalization alongside the ephemeral thinking bubble.-pub(super) const FILLER_INTERVAL: tokio::time::Duration = tokio::time::Duration::from_secs(13);--/// Maximum consecutive filler-send failures before we stop trying.-/// Same rationale as the thinking/typing latches.-pub(super) const MAX_FILLER_FAILURES: u32 = 2;--/// Maximum number of Unicode scalars to include in a dynamic filler-/// derived from the thinking accumulator. Keeps each bubble compact.-pub(super) const MAX_FILLER_CHARS: usize = 200;--/// Fallback rotating pool used when the thinking stream has produced-/// nothing new since the previous filler (or nothing at all). Index in-/// `StreamingState.filler_index` advances only when this branch is hit.-pub(super) const STATIC_FILLERS: &[&str] = &[- "💭 Still working on it…",- "💭 Just a moment…",- "💭 Almost there…",-];--/// Maximum length of the thinking snippet shown in the ephemeral-/// channel message. Longer reasoning is truncated with "…" to avoid-/// overwhelming the chat.-pub(super) const MAX_THINKING_DISPLAY_CHARS: usize = 500;--/// Whether a channel supports the progressive-UI placeholders — the-/// evolving draft bubble, the rotating "💭" fillers, and the ephemeral-/// "thinking" bubble. All three rely on the backend supporting **both**-/// message *edit* and *delete*: edit keeps a single bubble evolving in-/// place, delete removes it once the final reply lands. Telegram supports-/// both. Discord's adapter supports **neither** (edits 404, delete is a-/// hard `Delete not supported` stub), so every placeholder becomes a-/// permanent, un-editable, un-deletable message — the channel fills with-/// "💭 Still working on it…" bubbles.-///-/// This is an **allowlist**, not a denylist: only channels confirmed to-/// support edit+delete opt in. A new/unknown adapter therefore fails *safe*-/// (placeholders suppressed) rather than silently re-introducing the spam bug-/// this gate was added to fix.-pub(crate) fn channel_supports_progressive_ui(channel: &str) -> bool {- // Inbound channels arrive provider-prefixed from the socket layer- // (e.g. `discord:<guild>`, `tg:<chat>`), so compare the provider prefix,- // not the whole id — mirroring `channel_is_telegram`.- let provider = channel.split(':').next().unwrap_or(channel);- matches!(provider, "telegram" | "tg")-}--/// Why an edit of an already-posted channel message failed.-///-/// These three causes need three different recoveries, and conflating the-/// first two is what broke the live "💭 Thinking:" bubble (#5230).-#[derive(Debug, PartialEq, Eq)]-pub(super) enum EditFailure {- /// The backend serves no message-edit route at all, so the edit could- /// never have succeeded. The message itself is untouched and we still own- /// it: keep its id so it can still be deleted (or finally edited once the- /// backend ships the route) and just stop attempting edits.- RouteUnsupported,- /// The message really is gone on the provider side (user deleted it, or- /// the backend GC'd the relay row). The id is worthless — drop it.- MessageGone,- /// Anything else (transient 5xx, transport error, rate limit). Counts- /// against the per-turn failure budget and may be retried.- Transient,-}--/// Classify an edit failure by typed error rather than by message text, so the-/// recovery a call site picks cannot drift with `#[error(...)]` wording.-pub(super) fn classify_edit_failure(err: &anyhow::Error) -> EditFailure {- match err.downcast_ref::<crate::backend::BackendApiError>() {- Some(crate::backend::BackendApiError::ChannelEditUnsupported { .. }) => {- EditFailure::RouteUnsupported- }- Some(crate::backend::BackendApiError::MessageNotFound { .. }) => EditFailure::MessageGone,- _ => EditFailure::Transient,- }-}--/// Providers whose backend answered "no edit route" at least once this-/// process. Whether the route exists is a property of the deployed backend,-/// not of a turn, so re-probing it on every turn only buys a guaranteed-404-/// round-trip per turn forever. Latching it here keeps that to one attempt per-/// provider per process — and it self-heals on the next core start once the-/// backend ships the route (#5230).-static EDIT_UNSUPPORTED_PROVIDERS: std::sync::OnceLock<- std::sync::Mutex<std::collections::HashSet<String>>,-> = std::sync::OnceLock::new();--/// Provider key for the edit-capability latch. Inbound channels arrive-/// provider-prefixed (`telegram:<chat>`), and the route's existence is a-/// per-provider fact, so latch on the prefix — same reasoning as-/// [`channel_supports_progressive_ui`].-pub(super) fn edit_capability_key(channel: &str) -> String {- channel.split(':').next().unwrap_or(channel).to_string()-}--/// `true` once this process has learned the backend serves no edit route for-/// `channel`'s provider. Callers should skip the request entirely.-pub(super) fn channel_edits_unsupported(channel: &str) -> bool {- EDIT_UNSUPPORTED_PROVIDERS- .get_or_init(Default::default)- .lock()- .map(|set| set.contains(&edit_capability_key(channel)))- .unwrap_or(false)-}--/// Latch `channel`'s provider as having no message-edit route.-pub(super) fn mark_channel_edits_unsupported(channel: &str) {- let key = edit_capability_key(channel);- if let Ok(mut set) = EDIT_UNSUPPORTED_PROVIDERS- .get_or_init(Default::default)- .lock()- {- if set.insert(key.clone()) {- tracing::warn!(- "[channel-inbound][edit] backend serves no message-edit route for provider='{}' — \- progressive edits disabled for this process; placeholders will be posted once and \- cleaned up by delete instead (#5230)",- key,- );- }- }-}diff --git a/crates/openhuman-core/src/channels/bus/streaming_state.rs b/crates/openhuman-core/src/channels/bus/streaming_state.rsdeleted file mode 100644index 8f1dc4a74e..0000000000--- a/crates/openhuman-core/src/channels/bus/streaming_state.rs+++ /dev/null@@ -1,162 +0,0 @@-//! Per-turn state for progressive channel delivery: the evolving draft-//! bubble, the ephemeral "thinking" bubble, and the typing indicator.--use super::progressive_ui::MAX_TYPING_FAILURES;--/// Per-turn progressive-edit buffer. `dirty=true` means there's new-/// content to flush; `edit_disabled=true` means the backend doesn't-/// support editing for this channel and we should finalize atomically.-#[derive(Default)]-pub(super) struct StreamingState {- /// Accumulated visible assistant text from `text_delta` events.- pub(super) content: String,- /// Most recent tool status line (prepended to the message body).- pub(super) last_tool: Option<String>,- /// Backend-assigned message id returned from the initial- /// `send_channel_message`; subsequent edits target this id.- pub(super) message_id: Option<String>,- /// `true` once a draft message has been posted to the channel,- /// even when the backend response didn't include an id to target- /// for future edits. Decouples "a draft exists" from "we can edit- /// it" so `finalize_channel_reply` won't post a duplicate bubble- /// when the id was lost.- pub(super) draft_sent: bool,- /// New content has arrived since the last edit flush.- pub(super) dirty: bool,- /// Consecutive edit failures. Reset to zero on every success.- pub(super) edit_failures: u32,- /// Latched when the backend doesn't support edits for this channel- /// — we stop trying and rely on the final atomic send.- pub(super) edit_disabled: bool,- /// Accumulated LLM reasoning from `thinking_delta` events. Shown- /// to the user as an ephemeral "💭 Thinking…" message that is- /// **deleted** once the final response is ready (#600).- pub(super) thinking_accumulator: String,- /// Backend-assigned id of the ephemeral thinking message. Used to- /// delete it at finalization so the user sees only the clean reply.- pub(super) thinking_message_id: Option<String>,- /// `true` once a thinking message has been posted to the channel.- pub(super) thinking_sent: bool,- /// New thinking content has arrived since the last thinking flush.- pub(super) thinking_dirty: bool,- /// Latched when the first thinking POST succeeded with 200 but the- /// backend didn't return an id we can edit. Without this latch,- /// every subsequent `thinking_dirty` tick re-enters the "send new- /// message" branch and the user sees one italic bubble per- /// accumulated snippet instead of a single evolving one (#600).- pub(super) thinking_edit_disabled: bool,- /// Ids of ephemeral filler messages posted during long turns, in- /// send order. Deleted in `finalize_channel_reply` after the- /// canonical response is on screen.- pub(super) filler_message_ids: Vec<String>,- /// Next entry in `STATIC_FILLERS` to send when we fall back to the- /// rotating pool (no fresh thinking content to surface). Wraps- /// modulo pool size.- pub(super) filler_index: usize,- /// Consecutive filler-send failures. Reset to zero on success.- pub(super) filler_failures: u32,- /// Latched when the backend rejects filler sends — stops hitting- /// a broken endpoint every 13 s.- pub(super) filler_disabled: bool,- /// Last dynamic snippet we posted as a filler. Used to skip a- /// duplicate post when the thinking accumulator hasn't advanced- /// enough to produce a new tail slice — we fall through to the- /// static pool instead so the chat still sees movement.- pub(super) last_filler_snippet: Option<String>,-}--impl StreamingState {- /// The backend has no edit route: stop attempting edits but **keep**- /// `message_id`. The draft is still on the user's screen and we still own- /// it, so finalization needs the id to delete it before posting the- /// canonical reply. Dropping the id here is what orphaned the draft and- /// left a stale "_working…_" bubble (#5230).- pub(super) fn latch_draft_edits_unsupported(&mut self) {- self.edit_disabled = true;- }-- /// The draft really is gone provider-side: the id is worthless, so forget- /// it as well as disabling edits.- pub(super) fn forget_draft(&mut self) {- self.message_id = None;- self.edit_disabled = true;- }-- /// Thinking-bubble counterpart of [`Self::latch_draft_edits_unsupported`].- /// Keeping `thinking_message_id` is what lets finalization delete the- /// ephemeral "💭 Thinking:" bubble instead of leaving it in the chat (#5230).- pub(super) fn latch_thinking_edits_unsupported(&mut self) {- self.thinking_edit_disabled = true;- }-- /// Thinking-bubble counterpart of [`Self::forget_draft`].- pub(super) fn forget_thinking(&mut self) {- self.thinking_message_id = None;- self.thinking_edit_disabled = true;- }-- pub(super) fn compose_draft(&self) -> String {- let trimmed = self.content.trim_end();- if trimmed.is_empty() {- // No visible text yet — show a placeholder. Tool indicators- // (🔧 …) are intentionally omitted so the draft only ever- // contains content that is a clean prefix of the final- // response. If the draft persists after finalization the- // user sees benign placeholder text instead of stale tool- // status lines (#600).- "_working…_".to_string()- } else {- trimmed.to_string()- }- }-}--/// Typing-indicator bookkeeping. One per in-flight turn. Latches-/// `disabled` after repeated failures so channels without typing-/// support stop getting hit every 4 seconds.-#[derive(Default)]-pub(super) struct TypingState {- pub(super) failures: u32,- pub(super) disabled: bool,-}--/// Fire a single "typing…" indicator at the channel. Silently-/// latches `disabled` on repeated failure so callers can keep calling-/// this from a timer without accumulating warnings.-pub(super) async fn send_typing_indicator(channel: &str, state: &mut TypingState) {- if state.disabled {- return;- }- let Some((client, jwt)) = super::delivery::build_channel_client().await else {- return;- };- match client.send_channel_typing(channel, &jwt).await {- Ok(_) => {- if state.failures > 0 {- tracing::debug!(- "[channel-inbound][typing] recovered channel='{}' after {} failure(s)",- channel,- state.failures,- );- }- state.failures = 0;- }- Err(err) => {- state.failures += 1;- tracing::debug!(- "[channel-inbound][typing] indicator failed channel='{}' err={} (failures={}/{})",- channel,- err,- state.failures,- MAX_TYPING_FAILURES,- );- if state.failures >= MAX_TYPING_FAILURES {- tracing::info!(- "[channel-inbound][typing] disabling typing indicator for channel='{}' — backend unsupported",- channel,- );- state.disabled = true;- }- }- }-}diff --git a/crates/openhuman-core/src/channels/bus/subscriber.rs b/crates/openhuman-core/src/channels/bus/subscriber.rsindex 610723e242..f55d39a34a 100644--- a/crates/openhuman-core/src/channels/bus/subscriber.rs+++ b/crates/openhuman-core/src/channels/bus/subscriber.rs@@ -1,18 +1,20 @@//! The `ChannelInboundSubscriber` event handler: runs the agent loop for an//! inbound channel message and streams the reply back through the REST API.+//!+//! The web-chat event loop is host-owned; the progressive delivery it drives+//! (draft, thinking and filler bubbles, finalize) is+//! `tinychannels::delivery::progressive::ProgressiveReply` over+//! [`BackendProgressiveSender`].-use super::delivery::{finalize_channel_reply, send_channel_reply};-use super::draft::flush_streaming_edit;-use super::filler::send_filler_message;-use super::progressive_ui::{- channel_supports_progressive_ui, EDIT_FLUSH_INTERVAL, FILLER_INTERVAL, TYPING_REFRESH_INTERVAL,-};-use super::streaming_state::{send_typing_indicator, StreamingState, TypingState};-use super::thinking::flush_thinking_message;+use super::delivery::BackendProgressiveSender;use super::thread_id::{derive_inbound_client_id, derive_inbound_thread_id};use crate::core::events::DomainEvent;use async_trait::async_trait;+use std::sync::Arc;use tinybus::EventHandler;+use tinychannels::delivery::progressive::{+ ProgressiveReply, EDIT_FLUSH_INTERVAL, FILLER_INTERVAL, TYPING_REFRESH_INTERVAL,+};/// Subscribes to `ChannelInboundMessage` events and runs the agent loop,/// sending replies back to the originating channel via the backend REST API.@@ -89,6 +91,7 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {let client_id = derive_inbound_client_id(channel, sender.as_deref());let mut event_rx = crate::web_chat::subscribe_web_channel_events();+ let mut reply = ProgressiveReply::new(Arc::new(BackendProgressiveSender), channel.clone());let request_id = match crate::web_chat::start_chat(&client_id,@@ -117,11 +120,9 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {}Err(err) => {tracing::error!("[channel-inbound] start_chat failed: {}", err);- send_channel_reply(- channel,- &format!("Sorry, I couldn't process your message: {err}"),- )- .await;+ reply+ .send_reply(&format!("Sorry, I couldn't process your message: {err}"))+ .await;return;}};@@ -129,29 +130,24 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {let timeout = tokio::time::Duration::from_secs(180);let deadline = tokio::time::Instant::now() + timeout;- // ── Progressive-edit streaming state ──────────────────────────- // We buffer text/tool deltas and flush them as edits on a- // timer. If the first edit fails (e.g. the backend doesn't- // implement the PATCH endpoint for this channel) we latch into- // `edit_disabled` and fall back to atomic-final delivery.- let mut streaming_state = StreamingState::default();+ // ── Progressive-edit timer ────────────────────────────────────+ // Buffered text/thinking deltas flush as edits on this timer. The+ // driver latches into atomic-final delivery on channels or backends+ // that cannot edit.let mut edit_timer = tokio::time::interval(EDIT_FLUSH_INTERVAL);edit_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);// Don't fire immediately; wait for the first tick.edit_timer.tick().await;- // ── Typing indicator state ────────────────────────────────────+ // ── Typing indicator ──────────────────────────────────────────// Telegram's `sendChatAction` keeps the "typing…" UI alive for- // ~5s, so we re-send every 4s while the turn is in flight. The- // first call fires immediately; on repeated failures we latch- // `typing_disabled` to stop hitting a backend that doesn't- // support it.- let mut typing_state = TypingState::default();+ // ~5s, so re-send every 4s while the turn is in flight. The first+ // call fires immediately.let mut typing_timer = tokio::time::interval(TYPING_REFRESH_INTERVAL);typing_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);// Fire immediately on first tick so the indicator shows up as// soon as the inbound message is received.- send_typing_indicator(channel, &mut typing_state).await;+ reply.typing_tick().await;typing_timer.tick().await; // consume the immediate tick// ── Filler messages ──────────────────────────────────────────@@ -173,31 +169,22 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {match ev.event.as_str() {"text_delta" => {if let Some(delta) = ev.delta.as_ref() {- streaming_state.content.push_str(delta);- streaming_state.dirty = true;+ reply.on_text_delta(delta);}}"tool_call" => {if let Some(ref name) = ev.tool_name {- streaming_state.last_tool = Some(format!("🔧 {name}…"));- streaming_state.dirty = true;+ reply.on_tool_call(name);}}"tool_result" => {if let Some(ref name) = ev.tool_name {- let ok = ev.success.unwrap_or(true);- streaming_state.last_tool = Some(if ok {- format!("🔧 {name} ✓")- } else {- format!("🔧 {name} ✗")- });- streaming_state.dirty = true;+ reply.on_tool_result(name, ev.success.unwrap_or(true));}}"thinking_delta" => {if let Some(delta) = ev.delta.as_ref() {- streaming_state.thinking_accumulator.push_str(delta);- streaming_state.thinking_dirty = true;+ reply.on_thinking_delta(delta);}}"chat_done" | "chat:done" => {@@ -219,24 +206,19 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {"[channel-inbound] agent done, replying to channel='{}' len={} streamed_msg_id={:?}",channel,reply_text.len(),- streaming_state.message_id,+ reply.state().message_id,);// If we've been streaming progressive edits, replace// the outbound message with the final canonical text.// Otherwise send a fresh message atomically.- finalize_channel_reply(- channel,- &mut streaming_state,- reply_text,- )- .await;+ reply.finalize(reply_text).await;return;}"chat_error" | "chat:error" => {let err_msg = ev.message.unwrap_or_else(|| "unknown error".to_string());tracing::error!("[channel-inbound] agent error: {}", err_msg);- let reply = format!("Sorry, I encountered an error: {err_msg}");- finalize_channel_reply(channel, &mut streaming_state, &reply)+ reply+ .finalize(&format!("Sorry, I encountered an error: {err_msg}")).await;return;}@@ -256,12 +238,7 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {"[channel-inbound] turn cancelled reason={:?}",ev.cancel_reason);- finalize_channel_reply(- channel,- &mut streaming_state,- "Cancelled.",- )- .await;+ reply.finalize("Cancelled.").await;return;}_ => {}@@ -277,35 +254,15 @@ impl EventHandler<DomainEvent> for ChannelInboundSubscriber {}}}- _ = edit_timer.tick() => {- // Progressive draft/thinking bubbles require edit+delete- // support; skip them on channels that lack it (Discord) so- // they don't leave un-cleanable placeholder messages.- if channel_supports_progressive_ui(channel) {- if streaming_state.thinking_dirty && !streaming_state.thinking_edit_disabled {- flush_thinking_message(channel, &mut streaming_state).await;- }- if streaming_state.dirty && !streaming_state.edit_disabled {- flush_streaming_edit(channel, &mut streaming_state).await;- }- }- }- _ = typing_timer.tick() => {- if !typing_state.disabled {- send_typing_indicator(channel, &mut typing_state).await;- }- }- _ = filler_timer.tick() => {- // Fillers ("💭 Still working on it…") are ephemeral and- // deleted on finalize — only post them where cleanup works.- if channel_supports_progressive_ui(channel) && !streaming_state.filler_disabled {- send_filler_message(channel, &mut streaming_state).await;- }- }+ // Draft/thinking/filler bubbles need edit+delete support; the+ // driver skips them on channels without it (Discord) so they+ // never leave un-cleanable placeholder messages.+ _ = edit_timer.tick() => reply.edit_tick().await,+ _ = typing_timer.tick() => reply.typing_tick().await,+ _ = filler_timer.tick() => reply.filler_tick().await,_ = tokio::time::sleep_until(deadline) => {tracing::error!("[channel-inbound] agent timed out after {}s", timeout.as_secs());- let reply = "Sorry, the request timed out.";- finalize_channel_reply(channel, &mut streaming_state, reply).await;+ reply.finalize("Sorry, the request timed out.").await;return;}}diff --git a/crates/openhuman-core/src/channels/bus/thinking.rs b/crates/openhuman-core/src/channels/bus/thinking.rsdeleted file mode 100644index 04d84e1b2c..0000000000--- a/crates/openhuman-core/src/channels/bus/thinking.rs+++ /dev/null@@ -1,139 +0,0 @@-//! 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)- }-}