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(web_chat): remove custom segmentation logic in favor of tinychannels-bus
Steven Enamakel35a55b4881c8
diff --git a/crates/openhuman-core/src/web_chat/presentation.rs b/crates/openhuman-core/src/web_chat/presentation.rsindex 26568ed3b2..c71fe2ab34 100644--- a/crates/openhuman-core/src/web_chat/presentation.rs+++ b/crates/openhuman-core/src/web_chat/presentation.rs@@ -14,9 +14,9 @@ use crate::config::rpc as config_rpc;use crate::web_chat::{SubagentUsagePayload, TurnUsagePayload, WebChannelEvent};use super::publish_web_channel_event;--const MIN_SEGMENT_CHARS: usize = 40;-const MAX_SEGMENTS: usize = 5;+use tinychannels_bus::delivery::segment_delay;+#[cfg(test)]+use tinychannels_bus::delivery::segment_for_delivery;/// Convert a turn's [`LastTurnUsage`] into the wire payload carried on/// `chat_done`. Returns `None` for a turn that recorded no spend at all (e.g. a@@ -353,238 +353,6 @@ fn publish_chat_done(});}-// ── Segmentation ─────────────────────────────────────────────────────────────--/// Decide whether and how to split a response into multiple chat bubbles.-///-/// Rules (applied in order):-/// - Short messages (< 80 chars) are never split.-/// - Messages containing code fences (```) are never split.-/// - Messages that are predominantly structured (lists, tables, headers)-/// are never split — they read better as a single block.-/// - Otherwise, split on paragraph breaks (\n\n), merging segments that-/// are too short to stand alone.-/// - Fallback: split on sentence boundaries if paragraphs don't yield-/// multiple segments.-fn segment_for_delivery(text: &str) -> Vec<String> {- let trimmed = text.trim();-- // Don't split short messages.- if trimmed.len() < 80 {- return vec![trimmed.to_string()];- }-- // Never split messages containing code fences.- if trimmed.contains("```") {- tracing::debug!("[presentation:segment] skipping segmentation: contains code fences");- return vec![trimmed.to_string()];- }-- // Never split messages that are predominantly structured content.- if is_structured_content(trimmed) {- tracing::debug!("[presentation:segment] skipping segmentation: structured content");- return vec![trimmed.to_string()];- }-- // Strategy 1: paragraph splits.- let paragraphs: Vec<&str> = trimmed- .split("\n\n")- .map(|p| p.trim())- .filter(|p| !p.is_empty())- .collect();-- if paragraphs.len() >= 2 {- let merged = merge_short(¶graphs, "\n\n");- if merged.len() >= 2 {- tracing::debug!(- segments = merged.len(),- "[presentation:segment] split by paragraphs"- );- return cap_segments(merged, MAX_SEGMENTS, "\n\n");- }- }-- // Strategy 2: sentence splits.- let sentences = split_sentences(trimmed);- if sentences.len() >= 2 {- let grouped = group_sentences(&sentences);- if grouped.len() >= 2 {- tracing::debug!(- segments = grouped.len(),- "[presentation:segment] split by sentences"- );- return cap_segments(grouped, MAX_SEGMENTS, " ");- }- }-- // Fallback: single bubble.- vec![trimmed.to_string()]-}--/// Returns true if the text is predominantly structured content that-/// shouldn't be split across bubbles (markdown lists, tables, headers).-fn is_structured_content(text: &str) -> bool {- let lines: Vec<&str> = text.lines().collect();- if lines.is_empty() {- return false;- }-- let structured_count = lines- .iter()- .filter(|line| {- let trimmed = line.trim();- trimmed.starts_with("- ")- || trimmed.starts_with("* ")- || trimmed.starts_with("| ")- || trimmed.starts_with("# ")- || trimmed.starts_with("## ")- || trimmed.starts_with("### ")- || is_numbered_list_item(trimmed)- })- .count();-- // If more than 40% of non-empty lines are structured, don't split.- let non_empty = lines.iter().filter(|l| !l.trim().is_empty()).count();- non_empty > 0 && (structured_count * 100 / non_empty) > 40-}--/// Check if a line starts with a numbered list prefix like "1. " or "12. ".-/// Rejects dates ("2024. ") and decimals by requiring the digits+dot+space-/// to appear at the very start and be followed by text.-fn is_numbered_list_item(line: &str) -> bool {- let bytes = line.as_bytes();- let mut i = 0;- // Consume one or more leading ASCII digits.- while i < bytes.len() && bytes[i].is_ascii_digit() {- i += 1;- }- // Must have consumed at least one digit, followed by ". ".- i > 0 && i <= 3 && bytes.get(i) == Some(&b'.') && bytes.get(i + 1) == Some(&b' ')-}--/// Cap the number of delivered segments at `max` without losing content:-/// the first `max - 1` segments are kept as-is, and any overflow is-/// concatenated into a single trailing segment using `joiner`.-///-/// The earlier behavior (`.take(MAX_SEGMENTS)`) silently dropped every-/// segment past the cap, which truncated long agent replies in the UI-/// (issue #1041). Merging into the tail preserves all content while-/// still bounding the inter-bubble delay budget.-fn cap_segments(segments: Vec<String>, max: usize, joiner: &str) -> Vec<String> {- if max == 0 || segments.len() <= max {- return segments;- }- let original_len = segments.len();- let mut iter = segments.into_iter();- let mut result: Vec<String> = (&mut iter).take(max - 1).collect();- let tail: Vec<String> = iter.collect();- let tail_count = tail.len();- let merged = tail.join(joiner);- tracing::debug!(- target: "presentation",- max,- original_len,- tail_count,- tail_len = merged.len(),- joiner_len = joiner.len(),- "[presentation:segment] merging {} overflow segments into tail",- tail_count- );- result.push(merged);- result-}--/// Merge adjacent segments shorter than MIN_SEGMENT_CHARS.-fn merge_short(parts: &[&str], joiner: &str) -> Vec<String> {- let mut result: Vec<String> = Vec::new();- for part in parts {- if !result.is_empty() && part.len() < MIN_SEGMENT_CHARS {- let last = result.last_mut().unwrap();- last.push_str(joiner);- last.push_str(part);- } else {- result.push(part.to_string());- }- }- result-}--/// Split text on sentence-ending punctuation (. ! ?) followed by a space-/// and an uppercase letter.-fn split_sentences(text: &str) -> Vec<String> {- let mut parts: Vec<String> = Vec::new();- let mut current = String::new();- let chars: Vec<char> = text.chars().collect();-- let mut i = 0;- while i < chars.len() {- current.push(chars[i]);- let ch = chars[i];-- // Latin sentence terminators: split on ". " followed by uppercase.- if (ch == '.' || ch == '!' || ch == '?')- && i + 2 < chars.len()- && chars[i + 1] == ' '- && chars[i + 2].is_ascii_uppercase()- {- let trimmed = current.trim().to_string();- if !trimmed.is_empty() {- parts.push(trimmed);- }- current.clear();- i += 2; // skip the space- continue;- }-- // CJK sentence terminators: split after fullwidth period/exclamation/question.- if (ch == '\u{3002}' || ch == '\u{FF01}' || ch == '\u{FF1F}') && i + 1 < chars.len() {- let trimmed = current.trim().to_string();- if !trimmed.is_empty() {- parts.push(trimmed);- }- current.clear();- i += 1;- continue;- }-- i += 1;- }-- let remaining = current.trim().to_string();- if !remaining.is_empty() {- parts.push(remaining);- }- parts-}--/// Group sentences into 2-3 bubbles.-fn group_sentences(sentences: &[String]) -> Vec<String> {- let target_count = std::cmp::min(3, sentences.len().div_ceil(2));- let group_size = sentences.len().div_ceil(target_count);- let mut groups: Vec<String> = Vec::new();-- for chunk in sentences.chunks(group_size) {- let joined = chunk.join(" ");- if joined.len() >= MIN_SEGMENT_CHARS {- groups.push(joined);- } else if let Some(last) = groups.last_mut() {- last.push(' ');- last.push_str(&joined);- } else {- groups.push(joined);- }- }- groups-}--/// Compute a human-feeling inter-bubble delay in milliseconds.-/// Bounded: 500ms–1400ms, scaling with segment length.-fn segment_delay(segment: &str) -> u64 {- let base: u64 = 500;- let per_char: u64 = 2; // ~1.5-2ms per char for a natural reading pace- std::cmp::min(base + (segment.len() as u64) * per_char, 1400)-}-// ── Reactions ────────────────────────────────────────────────────────────────/// Ask the local model for an emoji reaction to the user's message.diff --git a/crates/openhuman-core/src/web_chat/presentation_test_support_tests.rs b/crates/openhuman-core/src/web_chat/presentation_test_support_tests.rsindex 982105f359..771f90c8a0 100644--- a/crates/openhuman-core/src/web_chat/presentation_test_support_tests.rs+++ b/crates/openhuman-core/src/web_chat/presentation_test_support_tests.rs@@ -1,17 +1,5 @@use crate::memory::agent::memory_loader::MemoryCitation;-pub fn segment_for_delivery_for_test(text: &str) -> Vec<String> {- super::segment_for_delivery(text)-}--pub fn segment_delay_for_test(segment: &str) -> u64 {- super::segment_delay(segment)-}--pub fn is_structured_content_for_test(text: &str) -> bool {- super::is_structured_content(text)-}-pub async fn deliver_response_for_test(client_id: &str,thread_id: &str,diff --git a/crates/openhuman-core/src/web_chat/presentation_tests.rs b/crates/openhuman-core/src/web_chat/presentation_tests.rsindex 362ccca0bb..89743bffa4 100644--- a/crates/openhuman-core/src/web_chat/presentation_tests.rs+++ b/crates/openhuman-core/src/web_chat/presentation_tests.rs@@ -1,276 +1,5 @@use super::*;-#[test]-fn short_messages_are_never_split() {- let result = segment_for_delivery("Hello there!");- assert_eq!(result, vec!["Hello there!"]);-}--#[test]-fn code_fences_prevent_splitting() {- let text = "Here is some code:\n\n```rust\nfn main() {}\n```\n\nAnd more text after.";- let result = segment_for_delivery(text);- assert_eq!(result.len(), 1);-}--#[test]-fn paragraph_splitting_works() {- let text = "This is the first paragraph with enough content to stand alone.\n\n\- This is the second paragraph that also has sufficient length.";- let result = segment_for_delivery(text);- assert_eq!(result.len(), 2);-}--#[test]-fn structured_content_not_split() {- let text = "Here are the steps:\n\n- First do this thing\n- Then do that thing\n- Finally wrap up\n\nThat should cover it.";- let result = segment_for_delivery(text);- assert_eq!(result.len(), 1);-}--#[test]-fn sentence_splitting_works() {- let text = "This is the first sentence and it has some length. This is the second sentence that continues the thought. And here is a third sentence to round things out.";- let result = segment_for_delivery(text);- assert!(- result.len() >= 2,- "expected >= 2 segments, got {}",- result.len()- );-}--#[test]-fn segment_delay_bounds() {- assert_eq!(segment_delay(""), 500);- assert_eq!(segment_delay(&"x".repeat(1000)), 1400);- assert!(segment_delay("Hello world") > 500);-}--#[test]-fn numbered_list_detection() {- assert!(is_numbered_list_item("1. First item"));- assert!(is_numbered_list_item("12. Twelfth item"));- assert!(!is_numbered_list_item("2024. Was a good year")); // too many digits- assert!(!is_numbered_list_item("hello 1. world")); // digits not at start- assert!(!is_numbered_list_item("1.5 seconds")); // no space after dot-}--#[test]-fn max_segments_respected_without_dropping_content() {- // Regression: the prior `.take(MAX_SEGMENTS)` silently dropped every- // paragraph past the cap (issue #1041). Verify the cap holds AND no- // input paragraph disappears from the delivered output.- let paras: Vec<String> = (0..10)- .map(|i| {- format!(- "Paragraph number {} has enough content to stand on its own.",- i- )- })- .collect();- let text = paras.join("\n\n");- let result = segment_for_delivery(&text);- assert!(result.len() <= MAX_SEGMENTS);- let joined = result.join("\n\n");- // Assert the full paragraph body survives, not just the prefix —- // a mid-text truncation would slip past a substring-only check.- for (i, original) in paras.iter().enumerate() {- assert!(- joined.contains(original),- "paragraph {} truncated or missing from delivered segments",- i- );- }-}--#[test]-fn cap_segments_passthrough_when_under_cap() {- let segs = vec!["one".to_string(), "two".to_string(), "three".to_string()];- assert_eq!(cap_segments(segs.clone(), 5, "\n\n"), segs);- assert_eq!(cap_segments(segs.clone(), 3, "\n\n"), segs);-}--#[test]-fn cap_segments_merges_overflow_into_tail() {- let segs = vec![- "one".to_string(),- "two".to_string(),- "three".to_string(),- "four".to_string(),- "five".to_string(),- "six".to_string(),- ];- let out = cap_segments(segs, 3, "\n\n");- assert_eq!(out.len(), 3);- assert_eq!(out[0], "one");- assert_eq!(out[1], "two");- assert_eq!(out[2], "three\n\nfour\n\nfive\n\nsix");-}--#[test]-fn cap_segments_handles_zero_max() {- let segs = vec!["one".to_string(), "two".to_string()];- // max=0 is a no-op: returns input unchanged rather than panicking.- assert_eq!(cap_segments(segs.clone(), 0, " "), segs);-}--#[test]-fn issue_1041_transcript_preserves_bullets_and_trailing_paragraphs() {- // The exact shape of the agent reply that triggered issue #1041:- // 11 paragraphs including a bullet list and 4 trailing paragraphs.- // Pre-fix `.take(MAX_SEGMENTS)` dropped paragraphs 6-11 entirely;- // post-fix they must survive (merged into the final segment).- let text = "here's the full message with a sharper CTA:\n\n\- ---\n\n\- hey [name], great meeting you at Startup Grind SF last week. really enjoyed our conversation about [insert 1 specific detail if you remember, otherwise remove this line].\n\n\- i'm reaching out to share what we're building at TinyHumans. we just launched OpenHuman, and the insight is simple: AI agents are incredibly powerful, but today they're locked behind developer workflows. setup, API keys, terminals. the 99% who can't code are completely left out.\n\n\- OpenHuman fixes that. it's AI agents that work out of the box. no setup, no API keys, no copy-paste. just plain English.\n\n\- we launched a week ago and the response has been strong:\n\n\- - 100+ paying users\n- 200+ GitHub stars, growing ~150% week over week\n- 50+ outside PRs merged\n\n\- attaching a screenshot of our growth curve since day one.\n\n\- we're second-time founders. previously scaled products to 100k DAUs, had a 1.5M exit, and built to 3M ARR. now we're going after the \"Apple moment\" for AI agents, making them actually usable for everyone.\n\n\- are you open to a 15-min demo next week? happy to work around your schedule.\n\n\- cheers,\n[your name]";-- let result = segment_for_delivery(text);- assert!(- result.len() <= MAX_SEGMENTS,- "segment count {} exceeds cap",- result.len()- );-- let joined = result.join("\n\n");- // Bullet list — the highest-priority symptom of #1041- assert!(joined.contains("100+ paying users"), "bullet 1 dropped");- assert!(joined.contains("200+ GitHub stars"), "bullet 2 dropped");- assert!(- joined.contains("50+ outside PRs merged"),- "bullet 3 dropped"- );- // Trailing paragraphs — also dropped pre-fix- assert!(- joined.contains("attaching a screenshot"),- "screenshot paragraph dropped"- );- assert!(- joined.contains("second-time founders"),- "founders paragraph dropped"- );- assert!(- joined.contains("15-min demo next week"),- "demo ask paragraph dropped"- );- assert!(joined.contains("[your name]"), "signature dropped");-}--#[test]-fn split_sentences_splits_on_sentence_terminators() {- let out = split_sentences("Hello world. How are you? I am fine!");- assert!(out.len() >= 3);-}--#[test]-fn split_sentences_handles_empty_string() {- assert!(split_sentences("").is_empty());-}--#[test]-fn split_sentences_single_sentence_without_terminator() {- let out = split_sentences("Just one thing");- assert_eq!(out.len(), 1);-}--#[test]-fn split_sentences_splits_on_cjk_terminators() {- let out = split_sentences("你好世界。今天天气很好!你觉得呢?");- assert_eq!(out.len(), 3);- assert_eq!(out[0], "你好世界。");- assert_eq!(out[1], "今天天气很好!");- assert_eq!(out[2], "你觉得呢?");-}--#[test]-fn group_sentences_single_entry_roundtrip() {- let v: Vec<String> = vec!["Hello world".into()];- let out = group_sentences(&v);- assert!(!out.is_empty());-}--#[test]-fn group_sentences_multi_entry_produces_output() {- let v: Vec<String> = vec![- "First sentence.".into(),- "Second sentence.".into(),- "Third sentence.".into(),- ];- let out = group_sentences(&v);- assert!(!out.is_empty());-}--#[test]-fn merge_short_joins_small_parts_with_separator() {- let out = merge_short(&["hi", "there"], " ");- assert!(!out.is_empty());-}--#[test]-fn merge_short_empty_input_returns_empty() {- let out: Vec<String> = merge_short(&[], " ");- assert!(out.is_empty());-}--#[test]-fn segment_delay_is_monotonic_in_length() {- let short = segment_delay("hi");- let longer = segment_delay(&"a".repeat(500));- assert!(longer >= short);-}--#[test]-fn segment_delay_is_finite_for_huge_text() {- let huge = "a".repeat(10_000);- assert!(segment_delay(&huge) < 1_000_000);-}--#[test]-fn segment_delay_works_on_empty_text() {- let _ = segment_delay("");-}--#[test]-fn is_structured_content_detects_markdown_headings() {- assert!(is_structured_content("# Heading\n\nbody"));-}--#[test]-fn is_structured_content_detects_bullet_list() {- assert!(is_structured_content("- item 1\n- item 2"));-}--#[test]-fn is_structured_content_detects_numbered_list() {- assert!(is_structured_content("1. First\n2. Second"));-}--#[test]-fn is_structured_content_false_for_plain_prose() {- assert!(!is_structured_content("Just a plain sentence."));-}--#[test]-fn segment_for_delivery_whitespace_only_is_empty_or_single() {- let r = segment_for_delivery(" ");- // Whitespace may return a single segment or empty depending on how- // the code treats leading/trailing whitespace. Either is acceptable.- assert!(r.len() <= 1);-}--#[test]-fn segment_for_delivery_single_short_returns_one() {- let r = segment_for_delivery("Quick.");- assert_eq!(r.len(), 1);-}-#[test]fn single_bubble_delivery_emits_one_unsegmented_chat_done_without_reaction() {let mut rx = crate::web_chat::subscribe_web_channel_events();