Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

test(raw_coverage): add telegram loopback and tokenjuice round-trip e2e coverage

Steven Enamakel4129c791694f
diff --git a/tests/raw_coverage/channels_telegram_loopback_e2e.rs b/tests/raw_coverage/channels_telegram_loopback_e2e.rs
new file mode 100644
index 0000000000..9b8edba49f
--- /dev/null
+++ b/tests/raw_coverage/channels_telegram_loopback_e2e.rs
@@ -0,0 +1,258 @@
+//! Round26 raw integration coverage for high-yield channel cold paths.
+//!
+//! Loopback Bot API endpoints only: no real channel
+//! network services are contacted.
+//!
+//! Yuanbao biz-codec cases live in `vendor/tinychannels` (`yuanbao/proto_biz.rs`).
+
+use crate::env_guard::EnvVarGuard;
+use axum::{
+ body::Bytes,
+ extract::State,
+ http::{HeaderMap, StatusCode},
+ routing::post,
+ Json, Router,
+};
+use tinychannels::providers::telegram::TelegramChannel;
+use tinychannels::{Channel, SendMessage};
+use serde_json::{json, Value};
+use std::sync::{Arc, Mutex};
+
+#[derive(Default)]
+struct TelegramMockState {
+ send_message_calls: Mutex<Vec<Value>>,
+ reaction_calls: Mutex<Vec<Value>>,
+ json_media_calls: Mutex<Vec<(String, Value)>>,
+ multipart_calls: Mutex<Vec<(String, String)>>,
+}
+
+async fn spawn_telegram_mock() -> (String, Arc<TelegramMockState>) {
+ let state = Arc::new(TelegramMockState::default());
+ let app = Router::new()
+ .route("/botround26/sendMessage", post(telegram_send_message))
+ .route(
+ "/botround26/setMessageReaction",
+ post(telegram_set_reaction),
+ )
+ .route("/botround26/sendDocument", post(telegram_media))
+ .route("/botround26/sendPhoto", post(telegram_media))
+ .route("/botround26/sendVideo", post(telegram_media))
+ .route("/botround26/sendAudio", post(telegram_media))
+ .route("/botround26/sendVoice", post(telegram_media))
+ .with_state(Arc::clone(&state));
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind telegram mock");
+ let addr = listener.local_addr().expect("telegram mock addr");
+ tokio::spawn(async move {
+ axum::serve(listener, app)
+ .await
+ .expect("serve telegram mock");
+ });
+ (format!("http://127.0.0.1:{}", addr.port()), state)
+}
+
+async fn telegram_send_message(
+ State(state): State<Arc<TelegramMockState>>,
+ Json(body): Json<Value>,
+) -> (StatusCode, Json<Value>) {
+ let mut calls = state.send_message_calls.lock().expect("sendMessage calls");
+ calls.push(body);
+ if calls.len() == 1 {
+ (
+ StatusCode::BAD_REQUEST,
+ Json(json!({"ok": false, "description": "markdown parse failed"})),
+ )
+ } else {
+ (
+ StatusCode::OK,
+ Json(json!({"ok": true, "result": {"message_id": 7}})),
+ )
+ }
+}
+
+async fn telegram_set_reaction(
+ State(state): State<Arc<TelegramMockState>>,
+ Json(body): Json<Value>,
+) -> (StatusCode, Json<Value>) {
+ let emoji = body
+ .pointer("/reaction/0/emoji")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string();
+ state
+ .reaction_calls
+ .lock()
+ .expect("reaction calls")
+ .push(body);
+ if emoji == "πŸ’₯" {
+ (
+ StatusCode::BAD_REQUEST,
+ Json(json!({"ok": false, "description": "reaction rejected"})),
+ )
+ } else {
+ (StatusCode::OK, Json(json!({"ok": true})))
+ }
+}
+
+async fn telegram_media(
+ State(state): State<Arc<TelegramMockState>>,
+ headers: HeaderMap,
+ uri: axum::http::Uri,
+ body: Bytes,
+) -> (StatusCode, Json<Value>) {
+ let method = uri
+ .path()
+ .rsplit('/')
+ .next()
+ .unwrap_or_default()
+ .to_string();
+ let content_type = headers
+ .get(axum::http::header::CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok())
+ .unwrap_or_default()
+ .to_string();
+
+ if content_type.starts_with("application/json") {
+ let value = serde_json::from_slice::<Value>(&body).expect("telegram media json");
+ state
+ .json_media_calls
+ .lock()
+ .expect("json media calls")
+ .push((method, value));
+ } else {
+ let text = String::from_utf8_lossy(&body).to_string();
+ state
+ .multipart_calls
+ .lock()
+ .expect("multipart calls")
+ .push((method, text));
+ }
+
+ (
+ StatusCode::OK,
+ Json(json!({"ok": true, "result": {"message_id": 9}})),
+ )
+}
+
+fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {
+ static LOCK: &std::sync::OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;
+ LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
+ .blocking_lock()
+}
+
+async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {
+ static LOCK: &std::sync::OnceLock<tokio::sync::Mutex<()>> = &crate::SHARED_ENV_LOCK;
+ LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
+ .lock().await
+}
+
+#[tokio::test]
+async fn telegram_loopback_covers_reaction_text_fallback_and_media_send_paths() {
+ let _env = env_lock_async().await;
+ let (base, state) = spawn_telegram_mock().await;
+ let _guard = EnvVarGuard::set("OPENHUMAN_TELEGRAM_BOT_API_BASE", base);
+ let _legacy_guard = EnvVarGuard::unset("OPENHUMAN_TELEGRAM_API_BASE");
+ let channel = TelegramChannel::new("round26".to_string(), vec!["alice".to_string()], false);
+
+ channel
+ .send(&SendMessage::new("[REACTION:πŸ‘|42]", "chat-1:topic-2"))
+ .await
+ .expect("reaction-only send");
+ channel
+ .send(&SendMessage::new("[REACTION:πŸ’₯|43]", "chat-1:topic-2"))
+ .await
+ .expect("failed reaction is non-fatal");
+ channel
+ .send(
+ &SendMessage::new("**markdown fallback**", "chat-1:topic-2")
+ .in_thread(Some("41".to_string())),
+ )
+ .await
+ .expect("send text falls back to plain");
+
+ channel
+ .send_document_by_url(
+ "chat-1",
+ Some("topic-2"),
+ "https://files.example/doc.pdf",
+ Some("doc"),
+ )
+ .await
+ .expect("document by url");
+ channel
+ .send_photo_by_url("chat-1", None, "https://files.example/photo.png", None)
+ .await
+ .expect("photo by url");
+ channel
+ .send_video_by_url(
+ "chat-1",
+ Some("topic-2"),
+ "https://files.example/video.mp4",
+ Some("video"),
+ )
+ .await
+ .expect("video by url");
+ channel
+ .send_audio_by_url("chat-1", None, "https://files.example/audio.mp3", None)
+ .await
+ .expect("audio by url");
+ channel
+ .send_voice_by_url(
+ "chat-1",
+ Some("topic-2"),
+ "https://files.example/voice.ogg",
+ Some("voice"),
+ )
+ .await
+ .expect("voice by url");
+ channel
+ .send_document_bytes(
+ "chat-1",
+ Some("topic-2"),
+ b"round26 document".to_vec(),
+ "round26.txt",
+ Some("bytes"),
+ )
+ .await
+ .expect("document bytes");
+ channel
+ .send_photo_bytes(
+ "chat-1",
+ None,
+ b"not really an image".to_vec(),
+ "round26.png",
+ Some("photo bytes"),
+ )
+ .await
+ .expect("photo bytes");
+
+ let reactions = state.reaction_calls.lock().expect("reaction calls");
+ assert_eq!(reactions.len(), 2);
+ assert_eq!(reactions[0]["message_id"], 42);
+ drop(reactions);
+
+ let messages = state.send_message_calls.lock().expect("sendMessage calls");
+ assert_eq!(messages.len(), 2);
+ assert_eq!(messages[0]["parse_mode"], "Markdown");
+ assert!(messages[1].get("parse_mode").is_none());
+ assert_eq!(messages[1]["message_thread_id"], "topic-2");
+ assert_eq!(messages[1]["reply_to_message_id"], 41);
+ drop(messages);
+
+ let json_media = state.json_media_calls.lock().expect("json media calls");
+ assert_eq!(json_media.len(), 5);
+ assert_eq!(json_media[0].0, "sendDocument");
+ assert_eq!(json_media[0].1["document"], "https://files.example/doc.pdf");
+ assert_eq!(json_media[2].0, "sendVideo");
+ assert_eq!(json_media[4].0, "sendVoice");
+ drop(json_media);
+
+ let multipart = state.multipart_calls.lock().expect("multipart calls");
+ assert_eq!(multipart.len(), 2);
+ assert_eq!(multipart[0].0, "sendDocument");
+ assert!(multipart[0].1.contains("round26.txt"));
+ assert_eq!(multipart[1].0, "sendPhoto");
+ assert!(multipart[1].1.contains("round26.png"));
+}
diff --git a/tests/raw_coverage/session_store_e2e.rs b/tests/raw_coverage/session_store_e2e.rs
index bb788e7037..76876c6706 100644
--- a/tests/raw_coverage/session_store_e2e.rs
+++ b/tests/raw_coverage/session_store_e2e.rs
@@ -406,6 +406,176 @@ async fn session_import_rejects_malformed_params() {
// ── tokenjuice ────────────────────────────────────────────────────────────
+/// `tokenjuice.detect` β†’ `.compress` β†’ `.retrieve`: the full CCR round trip,
+/// plus the invariants that must hold whichever branch the router takes.
+///
+/// A 400-row JSON array is the fixture because it is the one kind the existing
+/// `json_rpc_e2e` coverage already pins `detect` on, so the cross-controller
+/// assertion below rests on a classification asserted independently elsewhere.
+/// In practice it compresses ~19Γ— and takes the lossy path, so the `retrieve`
+/// leg runs for real and the original is compared byte for byte.
+///
+/// **The lossy branch is guarded rather than assumed, and that is deliberate.**
+/// Whether the router compresses is its own decision under a hint this RPC
+/// cannot fully steer: `handle_compress` builds `ContentHint` from `tool_name`
+/// alone (`inference/tokenjuice/schemas.rs:241-248`), leaving `explicit`,
+/// `mime`, `extension` and `query` unreachable. Asserting `lossy == true`
+/// unconditionally would pin a detector heuristic, not a contract β€” and the
+/// same controller passes a 16 KB uniform *log* straight through untouched, so
+/// the heuristic is not a stable thing to assert on. See
+/// `~/tinyhuman/bugs/e2e-wave-tokenjuice-compress-drops-most-of-the-content-hint.md`.
+///
+/// What is asserted unconditionally is what must hold on every branch:
+///
+/// 1. an applied `compress` and `detect` agree on the content kind β€” two
+/// controllers, one classifier, and nothing else checks they stay in step;
+/// 2. the reported byte counts describe the actual strings, not estimates;
+/// 3. **nothing is lost**: a lossy compaction is recoverable through the token
+/// byte-for-byte, and a pass-through returns the input unchanged.
+#[tokio::test]
+async fn tokenjuice_compress_agrees_with_detect_and_never_loses_content() {
+ let _lock = env_lock_async().await;
+ let harness = setup().await;
+
+ // A JSON array: the one kind the existing `json_rpc_e2e` coverage already
+ // pins `detect` on, so the cross-controller assertion below rests on a
+ // classification that is independently asserted elsewhere.
+ let rows: Vec<Value> = (0..400)
+ .map(|i| json!({ "id": i, "name": format!("row-{i}"), "status": "ok", "score": i * 3 }))
+ .collect();
+ let content = Value::Array(rows).to_string();
+ assert!(
+ content.len() > 8_000,
+ "the fixture must clear the 2048-byte compression floor with margin"
+ );
+
+ let detected = rpc(
+ &harness.rpc_base,
+ 32_001,
+ "openhuman.tokenjuice_detect",
+ json!({ "content": content }),
+ )
+ .await;
+ let detected_kind = payload(&detected, "tokenjuice_detect")
+ .get("kind")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("detect must report a kind: {detected}"))
+ .to_string();
+ assert_eq!(
+ detected_kind, "json",
+ "a JSON array must classify as json: {detected}"
+ );
+
+ let compressed = rpc(
+ &harness.rpc_base,
+ 32_002,
+ "openhuman.tokenjuice_compress",
+ json!({ "content": content, "tool_name": "session_store_e2e" }),
+ )
+ .await;
+ let compressed = payload(&compressed, "tokenjuice_compress");
+
+ // (2) The byte counts describe the actual strings.
+ let text = compressed
+ .get("text")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| panic!("compress must return the routed text: {compressed}"));
+ assert_eq!(
+ compressed.get("originalBytes").and_then(Value::as_u64),
+ Some(content.len() as u64),
+ "originalBytes must be the byte length handed in: {compressed}"
+ );
+ assert_eq!(
+ compressed.get("compactedBytes").and_then(Value::as_u64),
+ Some(text.len() as u64),
+ "compactedBytes is documented as the byte length of `text`: {compressed}"
+ );
+
+ // (3) Nothing is lost, on whichever branch the router took.
+ let applied = compressed
+ .get("applied")
+ .and_then(Value::as_bool)
+ .unwrap_or_else(|| {
+ panic!("compress must report whether it changed the content: {compressed}")
+ });
+ let lossy = compressed
+ .get("lossy")
+ .and_then(Value::as_bool)
+ .unwrap_or_else(|| panic!("compress must report whether it dropped data: {compressed}"));
+
+ if !applied {
+ assert!(!lossy, "a pass-through cannot be lossy: {compressed}");
+ let kind = compressed.get("kind").and_then(Value::as_str);
+ assert!(
+ kind == Some("plain_text") || kind == Some(detected_kind.as_str()),
+ "a pass-through uses either its plain-text wire kind or the detector's routed kind: {compressed}"
+ );
+ assert_eq!(
+ text, content,
+ "a pass-through must return the input unchanged β€” byte for byte"
+ );
+ assert_eq!(
+ compressed.get("compressor").and_then(Value::as_str),
+ Some("none"),
+ "a pass-through must name no compressor: {compressed}"
+ );
+ assert_eq!(
+ compressed.get("ccrToken"),
+ Some(&Value::Null),
+ "nothing was offloaded, so there is no token to hand back: {compressed}"
+ );
+ } else {
+ assert_eq!(
+ compressed.get("kind").and_then(Value::as_str),
+ Some(detected_kind.as_str()),
+ "an applied compression must route on the same kind detect reports: {compressed}"
+ );
+ assert!(
+ text.len() < content.len(),
+ "an applied compaction must shrink the payload: {compressed}"
+ );
+ assert_ne!(
+ compressed.get("compressor").and_then(Value::as_str),
+ Some("none"),
+ "an applied compaction must name the compressor that fired: {compressed}"
+ );
+ }
+
+ if lossy {
+ let token = compressed
+ .get("ccrToken")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| {
+ panic!(
+ "a lossy compaction over the CCR threshold must be recoverable: {compressed}"
+ )
+ })
+ .to_string();
+
+ let retrieved = rpc(
+ &harness.rpc_base,
+ 32_003,
+ "openhuman.tokenjuice_retrieve",
+ json!({ "token": token }),
+ )
+ .await;
+ let retrieved = payload(&retrieved, "tokenjuice_retrieve");
+ assert_eq!(
+ retrieved.get("found").and_then(Value::as_bool),
+ Some(true),
+ "the token minted by compress must resolve: {retrieved}"
+ );
+ assert_eq!(
+ retrieved.get("content").and_then(Value::as_str),
+ Some(content.as_str()),
+ "retrieve must return the original verbatim β€” a compaction that \
+ cannot be undone byte-for-byte has lost data"
+ );
+ }
+
+ harness.join.abort();
+}
+
/// Failure paths: `compress` needs content, and `retrieve` of a token that was
/// never minted is a clean `found: false` rather than an error.
#[tokio::test]
diff --git a/vendor/tinychannels b/vendor/tinychannels
index 8275a0d0e4..bd38abdd99 160000
--- a/vendor/tinychannels
+++ b/vendor/tinychannels
@@ -1 +1 @@
-Subproject commit 8275a0d0e406b78fbe3360b732e1778c1977b406
+Subproject commit bd38abdd999285f3ed2a72bf43d9aa184ab598f0
diff --git a/vendor/tinyflows b/vendor/tinyflows
index 1bb572a50e..cad43f9799 160000
--- a/vendor/tinyflows
+++ b/vendor/tinyflows
@@ -1 +1 @@
-Subproject commit 1bb572a50ed9ef9539d5758efddbe98d9933e184
+Subproject commit cad43f9799cf20f2815325a1a50b2116d6942642
diff --git a/vendor/tinyjuice b/vendor/tinyjuice
index 598b7d171f..7c43eedd7d 160000
--- a/vendor/tinyjuice
+++ b/vendor/tinyjuice
@@ -1 +1 @@
-Subproject commit 598b7d171f4abc721b2045fbcd454974dd2bc9d0
+Subproject commit 7c43eedd7d7917fa41ea1bd488649fe233d00531