Skip to content

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

test: expand channel, cron, and tui test coverage

Steven Enamakel5c5076060fdd
diff --git a/crates/openhuman-core/src/channels/bus/subscriber_loop_tests.rs b/crates/openhuman-core/src/channels/bus/subscriber_loop_tests.rs
index 463a6c3e99..0dab6925cf 100644
--- a/crates/openhuman-core/src/channels/bus/subscriber_loop_tests.rs
+++ b/crates/openhuman-core/src/channels/bus/subscriber_loop_tests.rs
@@ -54,15 +54,14 @@ fn event(request: &str, kind: &str, fields: serde_json::Value) -> ScopedWebEvent
let mut value = serde_json::json!({
"event": kind, "client_id": "c", "thread_id": "t", "request_id": request,
});
- value.as_object_mut().unwrap().extend(fields.as_object().unwrap().clone());
+ value
+ .as_object_mut()
+ .unwrap()
+ .extend(fields.as_object().unwrap().clone());
ScopedWebEvent::new(serde_json::from_value(value).expect("valid event"))
}
-async fn run(
- events: Vec<ScopedWebEvent>,
- sink: &Sink,
- close_bus: bool,
-) {
+async fn run(events: Vec<ScopedWebEvent>, sink: &Sink, close_bus: bool) {
let (tx, rx) = broadcast::channel(256);
for e in events {
tx.send(e).unwrap();
@@ -85,16 +84,40 @@ async fn progress_is_batched_and_the_final_reply_finalizes_once() {
let sink = Sink::default();
run(
vec![
- event("req-1", "thinking_delta", serde_json::json!({"delta": "hmm"})),
+ event(
+ "req-1",
+ "thinking_delta",
+ serde_json::json!({"delta": "hmm"}),
+ ),
event("req-1", "text_delta", serde_json::json!({"delta": "Hel"})),
- event("req-1", "tool_call", serde_json::json!({"tool_name": "search"})),
+ event(
+ "req-1",
+ "tool_call",
+ serde_json::json!({"tool_name": "search"}),
+ ),
event("req-1", "tool_call", serde_json::json!({})),
- event("req-1", "tool_result", serde_json::json!({"tool_name": "search", "success": false})),
- event("req-1", "tool_result", serde_json::json!({"tool_name": "fetch"})),
+ event(
+ "req-1",
+ "tool_result",
+ serde_json::json!({"tool_name": "search", "success": false}),
+ ),
+ event(
+ "req-1",
+ "tool_result",
+ serde_json::json!({"tool_name": "fetch"}),
+ ),
event("req-1", "tool_result", serde_json::json!({})),
- event("other-request", "text_delta", serde_json::json!({"delta": "NOT MINE"})),
+ event(
+ "other-request",
+ "text_delta",
+ serde_json::json!({"delta": "NOT MINE"}),
+ ),
event("req-1", "iteration_start", serde_json::json!({})),
- event("req-1", "chat_done", serde_json::json!({"full_response": "Hello!"})),
+ event(
+ "req-1",
+ "chat_done",
+ serde_json::json!({"full_response": "Hello!"}),
+ ),
],
&sink,
false,
@@ -117,10 +140,24 @@ async fn progress_is_batched_and_the_final_reply_finalizes_once() {
#[tokio::test]
async fn an_empty_final_response_gets_a_visible_fallback() {
let sink = Sink::default();
- run(vec![event("req-1", "chat_done", serde_json::json!({"full_response": " "}))], &sink, false).await;
+ run(
+ vec![event(
+ "req-1",
+ "chat_done",
+ serde_json::json!({"full_response": " "}),
+ )],
+ &sink,
+ false,
+ )
+ .await;
assert_eq!(sink.finals(), ["(No response from agent.)"]);
let sink = Sink::default();
- run(vec![event("req-1", "chat_done", serde_json::json!({}))], &sink, false).await;
+ run(
+ vec![event("req-1", "chat_done", serde_json::json!({}))],
+ &sink,
+ false,
+ )
+ .await;
assert_eq!(sink.finals(), ["(No response from agent.)"]);
}
@@ -129,25 +166,52 @@ async fn errors_and_cancellations_finalize_with_a_user_visible_message() {
let sink = Sink::default();
run(
vec![
- event("req-1", "text_delta", serde_json::json!({"delta": "partial"})),
- event("req-1", "chat_error", serde_json::json!({"message": "model exploded"})),
+ event(
+ "req-1",
+ "text_delta",
+ serde_json::json!({"delta": "partial"}),
+ ),
+ event(
+ "req-1",
+ "chat_error",
+ serde_json::json!({"message": "model exploded"}),
+ ),
],
&sink,
false,
)
.await;
- assert_eq!(sink.finals(), ["Sorry, I encountered an error: model exploded"]);
- assert_eq!(sink.events(), ["text:partial"], "pending progress flushes first");
+ assert_eq!(
+ sink.finals(),
+ ["Sorry, I encountered an error: model exploded"]
+ );
+ assert_eq!(
+ sink.events(),
+ ["text:partial"],
+ "pending progress flushes first"
+ );
let sink = Sink::default();
- run(vec![event("req-1", "chat_error", serde_json::json!({}))], &sink, false).await;
- assert_eq!(sink.finals(), ["Sorry, I encountered an error: unknown error"]);
+ run(
+ vec![event("req-1", "chat_error", serde_json::json!({}))],
+ &sink,
+ false,
+ )
+ .await;
+ assert_eq!(
+ sink.finals(),
+ ["Sorry, I encountered an error: unknown error"]
+ );
let sink = Sink::default();
run(
vec![
event("req-1", "text_delta", serde_json::json!({"delta": "x"})),
- event("req-1", "chat_cancelled", serde_json::json!({"cancel_reason": "user"})),
+ event(
+ "req-1",
+ "chat_cancelled",
+ serde_json::json!({"cancel_reason": "user"}),
+ ),
],
&sink,
false,
@@ -159,25 +223,41 @@ async fn errors_and_cancellations_finalize_with_a_user_visible_message() {
#[tokio::test]
async fn a_failed_progress_flush_ends_the_loop_without_a_final_message() {
- let sink = Sink { fail_feed: true, ..Default::default() };
+ let sink = Sink {
+ fail_feed: true,
+ ..Default::default()
+ };
run(
vec![
event("req-1", "text_delta", serde_json::json!({"delta": "a"})),
- event("req-1", "chat_done", serde_json::json!({"full_response": "done"})),
+ event(
+ "req-1",
+ "chat_done",
+ serde_json::json!({"full_response": "done"}),
+ ),
],
&sink,
false,
)
.await;
- assert!(sink.finals().is_empty(), "delivery failure stops the turn's projection");
+ assert!(
+ sink.finals().is_empty(),
+ "delivery failure stops the turn's projection"
+ );
for terminal in [
event("req-1", "chat_error", serde_json::json!({"message": "m"})),
event("req-1", "chat_cancelled", serde_json::json!({})),
] {
- let sink = Sink { fail_feed: true, ..Default::default() };
+ let sink = Sink {
+ fail_feed: true,
+ ..Default::default()
+ };
run(
- vec![event("req-1", "text_delta", serde_json::json!({"delta": "a"})), terminal],
+ vec![
+ event("req-1", "text_delta", serde_json::json!({"delta": "a"})),
+ terminal,
+ ],
&sink,
false,
)
@@ -190,12 +270,25 @@ async fn a_failed_progress_flush_ends_the_loop_without_a_final_message() {
async fn large_bursts_flush_in_bounded_batches() {
let sink = Sink::default();
let mut events: Vec<_> = (0..40)
- .map(|i| event("req-1", "text_delta", serde_json::json!({"delta": format!("{i}")})))
+ .map(|i| {
+ event(
+ "req-1",
+ "text_delta",
+ serde_json::json!({"delta": format!("{i}")}),
+ )
+ })
.collect();
- events.push(event("req-1", "chat_done", serde_json::json!({"full_response": "ok"})));
+ events.push(event(
+ "req-1",
+ "chat_done",
+ serde_json::json!({"full_response": "ok"}),
+ ));
run(events, &sink, false).await;
assert_eq!(sink.events().len(), 40);
- assert!(sink.batches.lock().unwrap().len() >= 2, "a batch is flushed at 32 events");
+ assert!(
+ sink.batches.lock().unwrap().len() >= 2,
+ "a batch is flushed at 32 events"
+ );
assert_eq!(sink.finals(), ["ok"]);
}
@@ -210,7 +303,16 @@ async fn the_loop_stops_when_the_session_is_cancelled_or_the_bus_closes() {
drop(tx);
let sink = Sink::default();
- run(vec![event("req-1", "text_delta", serde_json::json!({"delta": "x"}))], &sink, true).await;
+ run(
+ vec![event(
+ "req-1",
+ "text_delta",
+ serde_json::json!({"delta": "x"}),
+ )],
+ &sink,
+ true,
+ )
+ .await;
assert!(sink.finals().is_empty());
}
@@ -219,9 +321,19 @@ async fn a_lagging_receiver_skips_missed_events_and_still_finishes() {
let sink = Sink::default();
let (tx, rx) = broadcast::channel(2);
for i in 0..6 {
- tx.send(event("req-1", "text_delta", serde_json::json!({"delta": format!("{i}")}))).unwrap();
+ tx.send(event(
+ "req-1",
+ "text_delta",
+ serde_json::json!({"delta": format!("{i}")}),
+ ))
+ .unwrap();
}
- tx.send(event("req-1", "chat_done", serde_json::json!({"full_response": "after lag"}))).unwrap();
+ tx.send(event(
+ "req-1",
+ "chat_done",
+ serde_json::json!({"full_response": "after lag"}),
+ ))
+ .unwrap();
let session = tokio_util::sync::CancellationToken::new();
tokio::time::timeout(
std::time::Duration::from_secs(5),
diff --git a/crates/openhuman-core/src/channels/host/voice_tests.rs b/crates/openhuman-core/src/channels/host/voice_tests.rs
index 35c0db231a..23ed315c11 100644
--- a/crates/openhuman-core/src/channels/host/voice_tests.rs
+++ b/crates/openhuman-core/src/channels/host/voice_tests.rs
@@ -189,7 +189,9 @@ mod stt {
#[tokio::test]
async fn unscoped_transcription_runs_the_configured_provider_with_the_request_hints() {
- register_stt_provider("channel-voice-test-ok", |_, _| Ok(Box::new(EchoStt { fail: false })));
+ register_stt_provider("channel-voice-test-ok", |_, _| {
+ Ok(Box::new(EchoStt { fail: false }))
+ });
let result = host("channel-voice-test-ok")
.transcribe_host(HostTranscriptionRequest {
scope: None,
@@ -208,7 +210,9 @@ mod stt {
#[tokio::test]
async fn scoped_transcription_validates_the_scope_then_delegates() {
- register_stt_provider("channel-voice-test-scoped", |_, _| Ok(Box::new(EchoStt { fail: false })));
+ register_stt_provider("channel-voice-test-scoped", |_, _| {
+ Ok(Box::new(EchoStt { fail: false }))
+ });
let host = host("channel-voice-test-scoped");
let result = host
.transcribe_voice(HostVoiceTranscriptionRequest {
@@ -225,7 +229,9 @@ mod stt {
#[tokio::test]
async fn provider_failure_and_unknown_provider_surface_as_errors() {
- register_stt_provider("channel-voice-test-fail", |_, _| Ok(Box::new(EchoStt { fail: true })));
+ register_stt_provider("channel-voice-test-fail", |_, _| {
+ Ok(Box::new(EchoStt { fail: true }))
+ });
let err = host("channel-voice-test-fail")
.transcribe_host(HostTranscriptionRequest {
audio_base64: "QQ==".into(),
@@ -234,7 +240,10 @@ mod stt {
.await
.unwrap_err();
unregister_stt_provider("channel-voice-test-fail");
- assert!(err.to_string().contains("backend refused the audio"), "{err}");
+ assert!(
+ err.to_string().contains("backend refused the audio"),
+ "{err}"
+ );
let err = host("channel-voice-test-never-registered")
.transcribe_host(HostTranscriptionRequest::default())
@@ -265,12 +274,23 @@ async fn synthesis_fails_cleanly_when_the_voice_module_cannot_be_loaded() {
#[test]
fn reply_policy_reports_the_configured_mode_for_the_scoped_turn() {
let mut config = Config::default();
- config.channel_voice.threads.insert("chat-9".into(), VoiceReplyMode::SpeakReply);
+ config
+ .channel_voice
+ .threads
+ .insert("chat-9".into(), VoiceReplyMode::SpeakReply);
let host = ChannelVoiceHost {
config: Arc::new(config),
};
- let policy = host.reply_policy(&policy_request(scope("telegram", "chat-9", "t"), true, false));
+ let policy = host.reply_policy(&policy_request(
+ scope("telegram", "chat-9", "t"),
+ true,
+ false,
+ ));
assert_eq!(policy.mode, HostVoiceReplyMode::SpeakReply);
- let default = host.reply_policy(&policy_request(scope("telegram", "other", "t"), false, true));
+ let default = host.reply_policy(&policy_request(
+ scope("telegram", "other", "t"),
+ false,
+ true,
+ ));
assert_eq!(default.mode, HostVoiceReplyMode::Mirror);
}
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/native_media_flow_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/native_media_flow_tests.rs
index 259736a98e..9a001df5cf 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/native_media_flow_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/native_media_flow_tests.rs
@@ -11,9 +11,16 @@ use tinychannels_bus::{ChannelRef, ConversationKind, ConversationRef};
const THREAD: &str = "telegram:telegram:conversation-42";
/// A valid 1x1 PNG: the module checks image bytes against their declared type.
-const PNG: &[u8] = &[0x89, 0x50, 0x4e, 0x47, 0xd, 0xa, 0x1a, 0xa, 0x0, 0x0, 0x0, 0xd, 0x49, 0x48, 0x44, 0x52, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x8, 0x6, 0x0, 0x0, 0x0, 0x1f, 0x15, 0xc4, 0x89, 0x0, 0x0, 0x0, 0xb, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60, 0x0, 0x2, 0x0, 0x0, 0x5, 0x0, 0x1, 0x7a, 0x5e, 0xab, 0x3f, 0x0, 0x0, 0x0, 0x0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82];
-
-pub(in crate::channels::runtime::dispatch::processor) fn envelope(parts: Vec<ContentPart>) -> ChannelInboundEnvelope {
+const PNG: &[u8] = &[
+ 0x89, 0x50, 0x4e, 0x47, 0xd, 0xa, 0x1a, 0xa, 0x0, 0x0, 0x0, 0xd, 0x49, 0x48, 0x44, 0x52, 0x0,
+ 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x8, 0x6, 0x0, 0x0, 0x0, 0x1f, 0x15, 0xc4, 0x89, 0x0, 0x0,
+ 0x0, 0xb, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60, 0x0, 0x2, 0x0, 0x0, 0x5, 0x0, 0x1,
+ 0x7a, 0x5e, 0xab, 0x3f, 0x0, 0x0, 0x0, 0x0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
+];
+
+pub(in crate::channels::runtime::dispatch::processor) fn envelope(
+ parts: Vec<ContentPart>,
+) -> ChannelInboundEnvelope {
ChannelInboundEnvelope {
channel: ChannelRef {
id: "telegram".into(),
@@ -34,7 +41,9 @@ pub(in crate::channels::runtime::dispatch::processor) fn runtime_context(
objects: Arc<HashMap<String, ModuleObjectClient>>,
) -> ChannelRuntimeContext {
let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
- Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec!["ok"]));
+ Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec![
+ "ok",
+ ]));
ChannelRuntimeContext {
relay_thread: None,
channels_by_name: Arc::new(HashMap::new()),
@@ -75,7 +84,11 @@ async fn upload(
name: &str,
bytes: &[u8],
) -> MediaReference {
- let object = linked.module_objects().get("telegram").cloned().expect("telegram object");
+ let object = linked
+ .module_objects()
+ .get("telegram")
+ .cloned()
+ .expect("telegram object");
let scope = media_scope(envelope).unwrap();
let handle: tinychannels_bus::MediaUploadHandle = object
.call_confidential(
@@ -138,8 +151,24 @@ async fn typed_media_is_read_from_the_module_staged_and_converted_to_a_model_mes
let host = DispatchCtx::ambient();
let probe = envelope(Vec::new());
- let image = upload(&linked, &probe, MediaKind::Image, "image/png", "pic.png", PNG).await;
- let file = upload(&linked, &probe, MediaKind::Document, "text/plain", "notes.txt", b"file-payload").await;
+ let image = upload(
+ &linked,
+ &probe,
+ MediaKind::Image,
+ "image/png",
+ "pic.png",
+ PNG,
+ )
+ .await;
+ let file = upload(
+ &linked,
+ &probe,
+ MediaKind::Document,
+ "text/plain",
+ "notes.txt",
+ b"file-payload",
+ )
+ .await;
let voice = ContentPart::VoiceNote {
voice_note: tinychannels_bus::VoiceNote {
transcript: Some(tinychannels_bus::VoiceTranscript {
@@ -152,16 +181,20 @@ async fn typed_media_is_read_from_the_module_staged_and_converted_to_a_model_mes
},
};
let inbound = envelope(vec![
- ContentPart::Text { text: "look".into(), markdown_dialect: None },
+ ContentPart::Text {
+ text: "look".into(),
+ markdown_dialect: None,
+ },
voice,
image_part(image),
file_part(file),
]);
- let resolved = resolve_typed_message(&ctx, &host, &config, &inbound, THREAD, "[Channel context]")
- .await
- .expect("typed media resolves")
- .expect("media envelopes need preparation");
+ let resolved =
+ resolve_typed_message(&ctx, &host, &config, &inbound, THREAD, "[Channel context]")
+ .await
+ .expect("typed media resolves")
+ .expect("media envelopes need preparation");
assert_eq!(resolved.staged_parts.len(), 2);
for part in &resolved.staged_parts {
@@ -173,8 +206,14 @@ async fn typed_media_is_read_from_the_module_staged_and_converted_to_a_model_mes
};
use tinyinference_llm::message::{ContentBlock, MediaRef};
assert!(matches!(&user.content[0], ContentBlock::Text(t) if t == "[Channel context]"));
- assert!(user.content.iter().any(|b| matches!(b, ContentBlock::Text(t) if t == "spoken words")));
- assert!(user.content.iter().any(|b| matches!(b, ContentBlock::Image(i) if i.url.starts_with("openhuman-staged://"))));
+ assert!(user
+ .content
+ .iter()
+ .any(|b| matches!(b, ContentBlock::Text(t) if t == "spoken words")));
+ assert!(user
+ .content
+ .iter()
+ .any(|b| matches!(b, ContentBlock::Image(i) if i.url.starts_with("openhuman-staged://"))));
assert!(user.content.iter().any(|b| matches!(
b,
ContentBlock::Document(MediaRef::Path { path, .. }) if path.starts_with("openhuman-staged://")
@@ -187,7 +226,12 @@ async fn typed_media_is_read_from_the_module_staged_and_converted_to_a_model_mes
other => panic!("unexpected {other:?}"),
};
let read = crate::threads::attachments::read_authorized_native_attachment(
- &host, &config, THREAD, &id, std::slice::from_ref(staged_image), false,
+ &host,
+ &config,
+ THREAD,
+ &id,
+ std::slice::from_ref(staged_image),
+ false,
)
.await
.map_err(|e| e.to_string())
@@ -201,10 +245,20 @@ async fn typed_media_is_read_from_the_module_staged_and_converted_to_a_model_mes
async fn text_only_envelopes_need_no_media_preparation() {
let dir = tempfile::tempdir().unwrap();
let ctx = runtime_context(Arc::new(HashMap::new()));
- let inbound = envelope(vec![ContentPart::Text { text: "hi".into(), markdown_dialect: None }]);
- let out = resolve_typed_message(&ctx, &DispatchCtx::ambient(), &host_config(&dir), &inbound, THREAD, "c")
- .await
- .unwrap();
+ let inbound = envelope(vec![ContentPart::Text {
+ text: "hi".into(),
+ markdown_dialect: None,
+ }]);
+ let out = resolve_typed_message(
+ &ctx,
+ &DispatchCtx::ambient(),
+ &host_config(&dir),
+ &inbound,
+ THREAD,
+ "c",
+ )
+ .await
+ .unwrap();
assert!(out.is_none());
}
@@ -242,35 +296,53 @@ async fn typed_media_is_rejected_before_any_module_read_when_policy_fails() {
title: None,
transcript: None,
}]);
- assert!(reject(&ctx, &config, &audio).await.contains("not supported"));
+ assert!(reject(&ctx, &config, &audio)
+ .await
+ .contains("not supported"));
let mut no_account = envelope(vec![image_part(png_ref())]);
no_account.channel.account_id = None;
- assert!(reject(&ctx, &config, &no_account).await.contains("account scope"));
+ assert!(reject(&ctx, &config, &no_account)
+ .await
+ .contains("account scope"));
let mut bad_ref = png_ref();
bad_ref.path = Some("/etc/passwd".into());
- assert!(reject(&ctx, &config, &envelope(vec![image_part(bad_ref)])).await.contains("opaque"));
+ assert!(reject(&ctx, &config, &envelope(vec![image_part(bad_ref)]))
+ .await
+ .contains("opaque"));
let mut file_ref = png_ref();
file_ref.kind = MediaKind::Document;
file_ref.content_type = Some("text/plain".into());
let mut bad_file = file_ref.clone();
bad_file.url = Some("https://attacker.invalid/x".into());
- assert!(reject(&ctx, &config, &envelope(vec![file_part(bad_file)])).await.contains("opaque"));
+ assert!(reject(&ctx, &config, &envelope(vec![file_part(bad_file)]))
+ .await
+ .contains("opaque"));
let mut no_images = config.clone();
no_images.multimodal.max_images = 0;
- assert!(reject(&ctx, &no_images, &envelope(vec![image_part(png_ref())])).await.contains("image attachments"));
+ assert!(
+ reject(&ctx, &no_images, &envelope(vec![image_part(png_ref())]))
+ .await
+ .contains("image attachments")
+ );
let mut no_files = config.clone();
no_files.multimodal_files.max_files = 0;
- assert!(reject(&ctx, &no_files, &envelope(vec![file_part(file_ref)])).await.contains("file attachments"));
+ assert!(
+ reject(&ctx, &no_files, &envelope(vec![file_part(file_ref)]))
+ .await
+ .contains("file attachments")
+ );
// Valid parts but the configured module instance is not running.
- assert!(reject(&ctx, &config, &envelope(vec![image_part(png_ref())]))
- .await
- .contains("module is unavailable"));
+ assert!(
+ reject(&ctx, &config, &envelope(vec![image_part(png_ref())]))
+ .await
+ .contains("module is unavailable")
+ );
}
#[tokio::test]
@@ -284,20 +356,37 @@ async fn module_read_failures_and_metadata_mismatches_reject_the_turn() {
// The module has no such reference in this turn's scope.
let unknown = envelope(vec![image_part(png_ref())]);
let err = reject(&ctx, &config, &unknown).await;
- assert!(err.contains("could not be resolved") || err.contains("mismatch"), "{err}");
+ assert!(
+ err.contains("could not be resolved") || err.contains("mismatch"),
+ "{err}"
+ );
// The envelope's declared content type disagrees with what the module stored.
- let stored = upload(&linked, &probe, MediaKind::Image, "image/png", "pic.png", PNG).await;
+ let stored = upload(
+ &linked,
+ &probe,
+ MediaKind::Image,
+ "image/png",
+ "pic.png",
+ PNG,
+ )
+ .await;
let mut lying = stored.clone();
lying.content_type = Some("image/jpeg".into());
let err = reject(&ctx, &config, &envelope(vec![image_part(lying)])).await;
- assert!(err.contains("could not be resolved") || err.contains("does not match"), "{err}");
+ assert!(
+ err.contains("could not be resolved") || err.contains("does not match"),
+ "{err}"
+ );
// The declared size disagrees with the stored byte count.
let mut wrong_size = stored;
wrong_size.size_bytes = Some(3);
let err = reject(&ctx, &config, &envelope(vec![image_part(wrong_size)])).await;
- assert!(err.contains("could not be resolved") || err.contains("does not match"), "{err}");
+ assert!(
+ err.contains("could not be resolved") || err.contains("does not match"),
+ "{err}"
+ );
}
#[test]
@@ -309,7 +398,10 @@ fn rejection_logging_returns_the_error_text_unchanged() {
ModuleCallError::TransportFailed,
ModuleCallError::ModuleFault,
] {
- assert_eq!(log_module_call_rejection("method", error, "fallback text"), "fallback text");
+ assert_eq!(
+ log_module_call_rejection("method", error, "fallback text"),
+ "fallback text"
+ );
}
}
@@ -325,7 +417,8 @@ fn reference_validation_covers_kind_size_and_mime_rules() {
media.kind = MediaKind::Document;
assert!(validate_reference(&media, true, 1024, &[]).is_err());
media = png_ref();
- media.opaque_id = Some("x".repeat(tinychannels_bus::module_media::MEDIA_UPLOAD_BEGIN_MAX_BYTES + 1));
+ media.opaque_id =
+ Some("x".repeat(tinychannels_bus::module_media::MEDIA_UPLOAD_BEGIN_MAX_BYTES + 1));
assert!(validate_reference(&media, true, 1024, &[]).is_err());
let mut file = png_ref();
@@ -338,8 +431,10 @@ fn reference_validation_covers_kind_size_and_mime_rules() {
let mut incomplete = envelope(Vec::new());
incomplete.message_id.clear();
assert!(media_scope(&incomplete).is_err());
- assert!(!requires_typed_preparation(&envelope(vec![ContentPart::Text {
- text: "t".into(),
- markdown_dialect: None
- }])));
+ assert!(!requires_typed_preparation(&envelope(vec![
+ ContentPart::Text {
+ text: "t".into(),
+ markdown_dialect: None
+ }
+ ])));
}
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/progressive_flow_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/progressive_flow_tests.rs
index 477457fd52..d5fe432493 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/progressive_flow_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/progressive_flow_tests.rs
@@ -16,8 +16,13 @@ async fn native_target_resolves_only_a_configured_account_of_the_envelope_provid
let mut wrong_provider = envelope(Vec::new());
wrong_provider.channel.account_id = Some("slack:work".into());
- let err = native_target(&ctx, &wrong_provider).err().expect("provider mismatch");
- assert!(err.to_string().contains("no configured account identity"), "{err}");
+ let err = native_target(&ctx, &wrong_provider)
+ .err()
+ .expect("provider mismatch");
+ assert!(
+ err.to_string().contains("no configured account identity"),
+ "{err}"
+ );
let mut no_account = envelope(Vec::new());
no_account.channel.account_id = None;
@@ -25,7 +30,9 @@ async fn native_target_resolves_only_a_configured_account_of_the_envelope_provid
let mut unconfigured = envelope(Vec::new());
unconfigured.channel.account_id = Some("telegram:other".into());
- let err = native_target(&ctx, &unconfigured).err().expect("unknown account");
+ let err = native_target(&ctx, &unconfigured)
+ .err()
+ .expect("unknown account");
assert!(err.to_string().contains("not configured"), "{err}");
}
@@ -34,7 +41,12 @@ async fn progress_is_streamed_and_the_final_reply_is_delivered_to_the_provider()
let linked = linked_telegram_runtime().await;
let ctx = runtime_context(linked.module_objects());
let target = native_target(&ctx, &envelope(Vec::new())).unwrap().unwrap();
- let reply = Some(target.open("turn-progress-1").await.expect("module opens the turn"));
+ let reply = Some(
+ target
+ .open("turn-progress-1")
+ .await
+ .expect("module opens the turn"),
+ );
let (tx, rx) = mpsc::channel(8);
let worker = spawn_native_progress(rx, reply.clone().unwrap());
@@ -57,7 +69,9 @@ async fn progress_is_streamed_and_the_final_reply_is_delivered_to_the_provider()
assert!(finish_native_reply(&reply, "all done").await);
let paths = linked.provider_request_paths().await;
assert!(
- paths.iter().any(|p| p.ends_with("/sendMessage") || p.ends_with("/editMessageText")),
+ paths
+ .iter()
+ .any(|p| p.ends_with("/sendMessage") || p.ends_with("/editMessageText")),
"the provider received the output: {paths:?}"
);
}
@@ -107,24 +121,41 @@ fn delivery_counts_report_outcomes_and_unsupported_parts() {
ChannelSendError, ChannelSendOutcome, ContentPart, MessageReceipt, OutboundContentPart,
SendErrorKind,
};
- let ok = ChannelSendOutcome { receipt: MessageReceipt::default(), error: None };
+ let ok = ChannelSendOutcome {
+ receipt: MessageReceipt::default(),
+ error: None,
+ };
let failed = ChannelSendOutcome {
receipt: MessageReceipt::default(),
- error: Some(ChannelSendError { kind: SendErrorKind::Transient, ..Default::default() }),
+ error: Some(ChannelSendError {
+ kind: SendErrorKind::Transient,
+ ..Default::default()
+ }),
};
let unsupported = vec![OutboundContentPart::Content {
- part: ContentPart::Text { text: "x".into(), markdown_dialect: None },
+ part: ContentPart::Text {
+ text: "x".into(),
+ markdown_dialect: None,
+ },
}];
- let single = ProgressiveResult::DeliveryOutcome { outcome: Box::new(ok.clone()) };
+ let single = ProgressiveResult::DeliveryOutcome {
+ outcome: Box::new(ok.clone()),
+ };
assert_eq!(delivery_outcome_count(&single), 1);
assert_eq!(delivery_unsupported_count(&single), 0);
- let many = ProgressiveResult::DeliveryOutcomes { outcomes: vec![ok.clone(), failed.clone()] };
+ let many = ProgressiveResult::DeliveryOutcomes {
+ outcomes: vec![ok.clone(), failed.clone()],
+ };
assert_eq!(delivery_outcome_count(&many), 2);
assert!(!delivery_succeeded(&many));
- assert!(delivery_succeeded(&ProgressiveResult::DeliveryOutcomes { outcomes: vec![ok.clone()] }));
- assert!(!delivery_succeeded(&ProgressiveResult::DeliveryOutcome { outcome: Box::new(failed) }));
+ assert!(delivery_succeeded(&ProgressiveResult::DeliveryOutcomes {
+ outcomes: vec![ok.clone()]
+ }));
+ assert!(!delivery_succeeded(&ProgressiveResult::DeliveryOutcome {
+ outcome: Box::new(failed)
+ }));
let batch = ProgressiveResult::DeliveryBatch {
outcomes: vec![ok],
@@ -134,11 +165,16 @@ fn delivery_counts_report_outcomes_and_unsupported_parts() {
};
assert_eq!(delivery_outcome_count(&batch), 1);
assert_eq!(delivery_unsupported_count(&batch), 1);
- assert!(!delivery_succeeded(&batch), "unsupported parts are not a complete delivery");
+ assert!(
+ !delivery_succeeded(&batch),
+ "unsupported parts are not a complete delivery"
+ );
let unsupported_only = ProgressiveResult::DeliveryUnsupported { parts: unsupported };
assert_eq!(delivery_unsupported_count(&unsupported_only), 1);
assert_eq!(delivery_outcome_count(&unsupported_only), 0);
- assert!(delivery_succeeded(&ProgressiveResult::DeliveryUnsupported { parts: Vec::new() }));
+ assert!(delivery_succeeded(
+ &ProgressiveResult::DeliveryUnsupported { parts: Vec::new() }
+ ));
assert!(delivery_succeeded(&ProgressiveResult::Updated));
}
diff --git a/crates/openhuman-core/src/cron/channel_bridge_tests.rs b/crates/openhuman-core/src/cron/channel_bridge_tests.rs
index e0d87fa48a..c953c75fc4 100644
--- a/crates/openhuman-core/src/cron/channel_bridge_tests.rs
+++ b/crates/openhuman-core/src/cron/channel_bridge_tests.rs
@@ -33,7 +33,11 @@ fn conversation_ref_rejects_unknown_kind_claims() {
assert!(conversation_ref(&identity).is_err());
}
-fn session(provider: &str, account: Option<&str>, conversation: &str) -> tinyflows_bus::schedule::ChannelSessionIdentity {
+fn session(
+ provider: &str,
+ account: Option<&str>,
+ conversation: &str,
+) -> tinyflows_bus::schedule::ChannelSessionIdentity {
tinyflows_bus::schedule::ChannelSessionIdentity {
tenant_key: "t".into(),
agent_id: "orchestrator".into(),
@@ -56,11 +60,15 @@ async fn sends_and_announces_fail_closed_without_a_running_runtime() {
clear_channel_bridge();
let id = session("telegram", Some("telegram"), "42");
assert_eq!(
- send_to_channel("telegram", &id, "42", "hi", "k").await.unwrap_err(),
+ send_to_channel("telegram", &id, "42", "hi", "k")
+ .await
+ .unwrap_err(),
"channel runtime is not running"
);
assert_eq!(
- announce_to_channel("telegram", "42", None, "hi", "k").await.unwrap_err(),
+ announce_to_channel("telegram", "42", None, "hi", "k")
+ .await
+ .unwrap_err(),
"channel runtime is not running"
);
}
@@ -76,34 +84,87 @@ async fn send_rejects_identities_that_do_not_match_the_trusted_route() {
.clone();
register_channel_bridge(objects);
- let mismatch = send_to_channel("telegram", &session("slack", Some(&account), "42"), "42", "x", "k").await;
- assert_eq!(mismatch.unwrap_err(), "channel origin provider does not match the captured session");
+ let mismatch = send_to_channel(
+ "telegram",
+ &session("slack", Some(&account), "42"),
+ "42",
+ "x",
+ "k",
+ )
+ .await;
+ assert_eq!(
+ mismatch.unwrap_err(),
+ "channel origin provider does not match the captured session"
+ );
- let no_account = send_to_channel("telegram", &session("telegram", None, "42"), "42", "x", "k").await;
- assert_eq!(no_account.unwrap_err(), "channel origin has no configured account identity");
+ let no_account =
+ send_to_channel("telegram", &session("telegram", None, "42"), "42", "x", "k").await;
+ assert_eq!(
+ no_account.unwrap_err(),
+ "channel origin has no configured account identity"
+ );
- let foreign_account =
- send_to_channel("telegram", &session("telegram", Some("slack:team"), "42"), "42", "x", "k").await;
- assert_eq!(foreign_account.unwrap_err(), "channel origin has no configured account identity");
+ let foreign_account = send_to_channel(
+ "telegram",
+ &session("telegram", Some("slack:team"), "42"),
+ "42",
+ "x",
+ "k",
+ )
+ .await;
+ assert_eq!(
+ foreign_account.unwrap_err(),
+ "channel origin has no configured account identity"
+ );
- let other_room = send_to_channel("telegram", &session("telegram", Some(&account), "42"), "99", "x", "k").await;
+ let other_room = send_to_channel(
+ "telegram",
+ &session("telegram", Some(&account), "42"),
+ "99",
+ "x",
+ "k",
+ )
+ .await;
assert_eq!(
other_room.unwrap_err(),
"channel origin recipient does not match the captured conversation"
);
- let missing = send_to_channel("telegram", &session("telegram", Some("telegram:ghost"), "42"), "42", "x", "k").await;
- assert_eq!(missing.unwrap_err(), "configured channel module is unavailable");
+ let missing = send_to_channel(
+ "telegram",
+ &session("telegram", Some("telegram:ghost"), "42"),
+ "42",
+ "x",
+ "k",
+ )
+ .await;
+ assert_eq!(
+ missing.unwrap_err(),
+ "configured channel module is unavailable"
+ );
let mut bad_kind = session("telegram", Some(&account), "42");
bad_kind.conversation.kind = "invented".into();
let invalid = send_to_channel("telegram", &bad_kind, "42", "x", "k").await;
- assert_eq!(invalid.unwrap_err(), "channel origin conversation kind is invalid");
+ assert_eq!(
+ invalid.unwrap_err(),
+ "channel origin conversation kind is invalid"
+ );
let unconfigured = announce_to_channel("discord", "42", Some("thread"), "x", "k").await;
- assert_eq!(unconfigured.unwrap_err(), "channel discord is not configured");
+ assert_eq!(
+ unconfigured.unwrap_err(),
+ "channel discord is not configured"
+ );
- let ok = send_to_channel("telegram", &session("telegram", Some(&account), "42"), "42", "sent", "k-ok").await;
+ let ok = send_to_channel(
+ "telegram",
+ &session("telegram", Some(&account), "42"),
+ "42",
+ "sent",
+ "k-ok",
+ )
+ .await;
clear_channel_bridge();
ok.expect("a matching identity is delivered through the module");
assert!(linked
diff --git a/crates/openhuman-core/src/cron/scheduler/origin_delivery_channel_tests.rs b/crates/openhuman-core/src/cron/scheduler/origin_delivery_channel_tests.rs
index 475f0be02d..e9ec6d3a66 100644
--- a/crates/openhuman-core/src/cron/scheduler/origin_delivery_channel_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler/origin_delivery_channel_tests.rs
@@ -46,7 +46,9 @@ fn channel_origin(identity: Option<ChannelSessionIdentity>) -> JobOrigin {
}
}
-fn account_of(objects: &std::collections::HashMap<String, tinybus::module::ModuleObjectClient>) -> String {
+fn account_of(
+ objects: &std::collections::HashMap<String, tinybus::module::ModuleObjectClient>,
+) -> String {
objects
.keys()
.find(|key| tinychannels_bus::provider_id(key) == "telegram")
@@ -130,7 +132,10 @@ async fn channel_origin_reply_reaches_the_provider_and_the_durable_session() {
.await
.iter()
.any(|p| p.ends_with("/sendMessage")));
- assert_eq!(assistant_messages(&ctx, &cfg, &ident), ["Scheduled.", "Drink water!"]);
+ assert_eq!(
+ assistant_messages(&ctx, &cfg, &ident),
+ ["Scheduled.", "Drink water!"]
+ );
}
#[tokio::test]
@@ -139,8 +144,13 @@ async fn channel_origin_without_a_session_identity_is_rejected_before_sending()
let cfg = config(&tmp);
let ctx = ctx_for(&cfg);
let j = job(Some(channel_origin(None)));
- let err = deliver_to_origin(&ctx, &cfg, &j, "run-x", "hi").await.unwrap_err();
- assert!(err.to_string().contains("no durable session identity"), "{err}");
+ let err = deliver_to_origin(&ctx, &cfg, &j, "run-x", "hi")
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("no durable session identity"),
+ "{err}"
+ );
}
#[tokio::test]
@@ -151,17 +161,29 @@ async fn channel_origin_captured_under_another_tenant_or_agent_is_rejected() {
let mut foreign = identity(&ctx, &cfg, "telegram");
foreign.tenant_key = "another-tenant".into();
- let err = deliver_to_origin(&ctx, &cfg, &job(Some(channel_origin(Some(foreign)))), "r", "hi")
- .await
- .unwrap_err();
+ let err = deliver_to_origin(
+ &ctx,
+ &cfg,
+ &job(Some(channel_origin(Some(foreign)))),
+ "r",
+ "hi",
+ )
+ .await
+ .unwrap_err();
assert!(err.to_string().contains("invalid channel origin"), "{err}");
assert!(err.to_string().contains("different tenant"), "{err}");
let mut stale_agent = identity(&ctx, &cfg, "telegram");
stale_agent.agent_id = "no-such-agent".into();
- let err = deliver_to_origin(&ctx, &cfg, &job(Some(channel_origin(Some(stale_agent)))), "r", "hi")
- .await
- .unwrap_err();
+ let err = deliver_to_origin(
+ &ctx,
+ &cfg,
+ &job(Some(channel_origin(Some(stale_agent)))),
+ "r",
+ "hi",
+ )
+ .await
+ .unwrap_err();
assert!(err.to_string().contains("no longer matches"), "{err}");
}
@@ -172,10 +194,19 @@ async fn channel_origin_fails_when_the_channel_runtime_is_not_running() {
let cfg = config(&tmp);
let ctx = ctx_for(&cfg);
let ident = identity(&ctx, &cfg, "telegram");
- let err = deliver_to_origin(&ctx, &cfg, &job(Some(channel_origin(Some(ident.clone())))), "r", "hi")
- .await
- .unwrap_err();
- assert!(err.to_string().contains("channel runtime is not running"), "{err}");
+ let err = deliver_to_origin(
+ &ctx,
+ &cfg,
+ &job(Some(channel_origin(Some(ident.clone())))),
+ "r",
+ "hi",
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("channel runtime is not running"),
+ "{err}"
+ );
assert!(assistant_messages(&ctx, &cfg, &ident).is_empty());
}
@@ -222,6 +253,12 @@ async fn host_routed_channel_origin_reply_is_also_recorded_in_the_session_transc
let replies = sink.0.lock().unwrap().clone();
assert_eq!(replies.len(), 1);
assert_eq!(replies[0].text, "Host reply");
- assert_eq!(replies[0].profile_id.as_deref(), Some("cron-origin-profile"));
- assert_eq!(assistant_messages(&ctx, &cfg, &ident), ["Scheduled.", "Host reply"]);
+ assert_eq!(
+ replies[0].profile_id.as_deref(),
+ Some("cron-origin-profile")
+ );
+ assert_eq!(
+ assistant_messages(&ctx, &cfg, &ident),
+ ["Scheduled.", "Host reply"]
+ );
}
diff --git a/crates/openhuman-core/src/inference/failure_copy/localized_tests.rs b/crates/openhuman-core/src/inference/failure_copy/localized_tests.rs
index 48e316624a..e447cf6669 100644
--- a/crates/openhuman-core/src/inference/failure_copy/localized_tests.rs
+++ b/crates/openhuman-core/src/inference/failure_copy/localized_tests.rs
@@ -123,7 +123,13 @@ fn catalog_rejects_unknown_locale_or_key() {
#[test]
fn every_locale_renders_each_retry_hint_bucket() {
for locale in chat_error_catalog::SUPPORTED_LOCALES {
- for (secs, expect_n) in [(0u64, None), (1, None), (30, Some("30")), (60, None), (150, Some("3"))] {
+ for (secs, expect_n) in [
+ (0u64, None),
+ (1, None),
+ (30, Some("30")),
+ (60, None),
+ (150, Some("3")),
+ ] {
let out = render_channel_failure(
locale,
"fallback",
diff --git a/crates/openhuman-core/src/threads/attachments_native_tests.rs b/crates/openhuman-core/src/threads/attachments_native_tests.rs
index 180c74170a..c5a1745440 100644
--- a/crates/openhuman-core/src/threads/attachments_native_tests.rs
+++ b/crates/openhuman-core/src/threads/attachments_native_tests.rs
@@ -46,10 +46,18 @@ fn source(kind: MediaKind) -> ContentPart {
}
}
-async fn stage(f: &Fixture, input: &ContentPart, name: &str, mime: &str, bytes: &[u8]) -> ContentPart {
- stage_native_channel_part(&f.ctx, THREAD, &f.config, input, name, mime, bytes, &f.lease)
- .await
- .unwrap()
+async fn stage(
+ f: &Fixture,
+ input: &ContentPart,
+ name: &str,
+ mime: &str,
+ bytes: &[u8],
+) -> ContentPart {
+ stage_native_channel_part(
+ &f.ctx, THREAD, &f.config, input, name, mime, bytes, &f.lease,
+ )
+ .await
+ .unwrap()
}
async fn read(
@@ -70,24 +78,44 @@ fn opaque(part: &ContentPart) -> String {
#[tokio::test]
async fn staged_native_image_is_readable_only_with_a_current_grant() {
let f = fixture();
- let part = stage(&f, &source(MediaKind::Image), "pic.png", "image/png", b"png-bytes").await;
+ let part = stage(
+ &f,
+ &source(MediaKind::Image),
+ "pic.png",
+ "image/png",
+ b"png-bytes",
+ )
+ .await;
let id = opaque(&part);
- let (bytes, mime, path) = read(&f, &id, std::slice::from_ref(&part), false).await.unwrap();
+ let (bytes, mime, path) = read(&f, &id, std::slice::from_ref(&part), false)
+ .await
+ .unwrap();
assert_eq!(bytes, b"png-bytes");
assert_eq!(mime, "image/png");
assert!(!path.is_empty());
let no_grant = read(&f, &id, &[], false).await.unwrap_err();
- assert!(no_grant.contains("lacks a current or committed host grant"), "{no_grant}");
+ assert!(
+ no_grant.contains("lacks a current or committed host grant"),
+ "{no_grant}"
+ );
let other_thread = read_authorized_native_attachment(
- &f.ctx, &f.config, "other-thread", &id, std::slice::from_ref(&part), false,
+ &f.ctx,
+ &f.config,
+ "other-thread",
+ &id,
+ std::slice::from_ref(&part),
+ false,
)
.await
.map(|_| ())
.unwrap_err();
- assert!(other_thread.contains("outside the active session scope"), "{other_thread}");
+ assert!(
+ other_thread.contains("outside the active session scope"),
+ "{other_thread}"
+ );
let unknown = uuid::Uuid::new_v4().simple().to_string();
let missing = read(&f, &unknown, &[], false).await.unwrap_err();
@@ -98,7 +126,14 @@ async fn staged_native_image_is_readable_only_with_a_current_grant() {
#[tokio::test]
async fn committed_native_attachment_stays_readable_for_history_only_when_allowed() {
let f = fixture();
- let part = stage(&f, &source(MediaKind::Image), "pic.png", "image/png", b"history-bytes").await;
+ let part = stage(
+ &f,
+ &source(MediaKind::Image),
+ "pic.png",
+ "image/png",
+ b"history-bytes",
+ )
+ .await;
let id = opaque(&part);
let repo = staged_repo(&f.ctx, &f.config.workspace_dir).unwrap();
let tenant = tenant_for(&f.ctx).unwrap();
@@ -109,11 +144,22 @@ async fn committed_native_attachment_stays_readable_for_history_only_when_allowe
part: part.clone(),
canceled: false,
};
- claim_staged_record(&repo, &tenant, THREAD, &staged_doc_id(&id).unwrap(), &part, &claim).unwrap();
+ claim_staged_record(
+ &repo,
+ &tenant,
+ THREAD,
+ &staged_doc_id(&id).unwrap(),
+ &part,
+ &claim,
+ )
+ .unwrap();
f.lease.mark_committed();
let denied = read(&f, &id, &[], false).await.unwrap_err();
- assert!(denied.contains("lacks a current or committed host grant"), "{denied}");
+ assert!(
+ denied.contains("lacks a current or committed host grant"),
+ "{denied}"
+ );
let (bytes, _, _) = read(&f, &id, &[], true).await.unwrap();
assert_eq!(bytes, b"history-bytes");
}
@@ -121,20 +167,39 @@ async fn committed_native_attachment_stays_readable_for_history_only_when_allowe
#[tokio::test]
async fn canceled_native_attachment_cannot_be_read_even_with_a_grant() {
let f = fixture();
- let part = stage(&f, &source(MediaKind::Image), "pic.png", "image/png", b"cancel-me").await;
+ let part = stage(
+ &f,
+ &source(MediaKind::Image),
+ "pic.png",
+ "image/png",
+ b"cancel-me",
+ )
+ .await;
let id = opaque(&part);
f.lease.discard().await.unwrap();
// A second discard is a no-op.
f.lease.discard().await.unwrap();
- let err = read(&f, &id, std::slice::from_ref(&part), true).await.unwrap_err();
+ let err = read(&f, &id, std::slice::from_ref(&part), true)
+ .await
+ .unwrap_err();
assert!(err.contains("canceled"), "{err}");
- assert!(f.lease.track(part).is_err(), "a discarded lease accepts no new parts");
+ assert!(
+ f.lease.track(part).is_err(),
+ "a discarded lease accepts no new parts"
+ );
}
#[tokio::test]
async fn native_attachment_policy_is_rechecked_when_it_is_read() {
let mut f = fixture();
- let part = stage(&f, &source(MediaKind::Document), "notes.txt", "text/plain", b"hello file").await;
+ let part = stage(
+ &f,
+ &source(MediaKind::Document),
+ "notes.txt",
+ "text/plain",
+ b"hello file",
+ )
+ .await;
let id = opaque(&part);
let current = std::slice::from_ref(&part);
@@ -145,20 +210,37 @@ async fn native_attachment_policy_is_rechecked_when_it_is_read() {
// ...and rejected once the operator removes it.
f.config.multimodal_files.allowed_mime_types.clear();
let err = read(&f, &id, current, false).await.unwrap_err();
- assert!(err.contains("MIME is no longer allowed") || err.contains("limit"), "{err}");
+ assert!(
+ err.contains("MIME is no longer allowed") || err.contains("limit"),
+ "{err}"
+ );
}
#[tokio::test]
async fn staging_rejects_empty_input_and_unstageable_kinds_without_leaving_files() {
let f = fixture();
let empty = stage_native_channel_part(
- &f.ctx, THREAD, &f.config, &source(MediaKind::Image), "x.png", "image/png", b"", &f.lease,
+ &f.ctx,
+ THREAD,
+ &f.config,
+ &source(MediaKind::Image),
+ "x.png",
+ "image/png",
+ b"",
+ &f.lease,
)
.await
.unwrap_err();
assert!(empty.contains("non-empty"), "{empty}");
let no_thread = stage_native_channel_part(
- &f.ctx, " ", &f.config, &source(MediaKind::Image), "x.png", "image/png", b"x", &f.lease,
+ &f.ctx,
+ " ",
+ &f.config,
+ &source(MediaKind::Image),
+ "x.png",
+ "image/png",
+ b"x",
+ &f.lease,
)
.await
.unwrap_err();
@@ -169,21 +251,43 @@ async fn staging_rejects_empty_input_and_unstageable_kinds_without_leaving_files
markdown_dialect: None,
};
let err = stage_native_channel_part(
- &f.ctx, THREAD, &f.config, &text, "x.png", "image/png", b"bytes", &f.lease,
+ &f.ctx,
+ THREAD,
+ &f.config,
+ &text,
+ "x.png",
+ "image/png",
+ b"bytes",
+ &f.lease,
)
.await
.unwrap_err();
assert!(err.contains("cannot be staged"), "{err}");
- let workspace = crate::attachments::thread_action_dir(&f.ctx, &f.config, &f.config.workspace_dir, Some(THREAD))
- .await
- .unwrap();
+ let workspace = crate::attachments::thread_action_dir(
+ &f.ctx,
+ &f.config,
+ &f.config.workspace_dir,
+ Some(THREAD),
+ )
+ .await
+ .unwrap();
let leftovers = walk_files(&workspace);
- assert!(leftovers.is_empty(), "failed staging removed its file: {leftovers:?}");
+ assert!(
+ leftovers.is_empty(),
+ "failed staging removed its file: {leftovers:?}"
+ );
// A lease that is no longer active refuses the staged part and cleans up.
f.lease.discard().await.unwrap();
let inactive = stage_native_channel_part(
- &f.ctx, THREAD, &f.config, &source(MediaKind::Image), "y.png", "image/png", b"bytes", &f.lease,
+ &f.ctx,
+ THREAD,
+ &f.config,
+ &source(MediaKind::Image),
+ "y.png",
+ "image/png",
+ b"bytes",
+ &f.lease,
)
.await
.unwrap_err();
@@ -212,7 +316,10 @@ async fn bounded_staged_reads_reject_oversize_and_missing_files() {
let root = std::fs::canonicalize(dir.path()).unwrap();
let file = root.join("blob.bin");
std::fs::write(&file, b"0123456789").unwrap();
- assert_eq!(read_staged_file_bounded(&file, &root, 10).await.unwrap(), b"0123456789");
+ assert_eq!(
+ read_staged_file_bounded(&file, &root, 10).await.unwrap(),
+ b"0123456789"
+ );
let too_big = read_staged_file_bounded(&file, &root, 9).await.unwrap_err();
assert!(too_big.contains("byte limit"), "{too_big}");
let missing = read_staged_file_bounded(&root.join("missing.bin"), &root, 10)
@@ -224,12 +331,26 @@ async fn bounded_staged_reads_reject_oversize_and_missing_files() {
#[tokio::test]
async fn discarding_staged_native_parts_removes_files_and_empty_input_is_a_no_op() {
let f = fixture();
- commit_native_channel_parts(&f.ctx, THREAD, &[], "message-0").await.unwrap();
-
- let part = stage(&f, &source(MediaKind::Image), "gone.png", "image/png", b"discard").await;
- let workspace = crate::attachments::thread_action_dir(&f.ctx, &f.config, &f.config.workspace_dir, Some(THREAD))
+ commit_native_channel_parts(&f.ctx, THREAD, &[], "message-0")
.await
.unwrap();
+
+ let part = stage(
+ &f,
+ &source(MediaKind::Image),
+ "gone.png",
+ "image/png",
+ b"discard",
+ )
+ .await;
+ let workspace = crate::attachments::thread_action_dir(
+ &f.ctx,
+ &f.config,
+ &f.config.workspace_dir,
+ Some(THREAD),
+ )
+ .await
+ .unwrap();
assert_eq!(walk_files(&workspace).len(), 1);
drop(part);
f.lease.discard().await.unwrap();
@@ -285,7 +406,10 @@ fn committed_message_selects_only_the_staged_parts_it_references() {
assert!(matches!(&message, Message::User(user)
if user.content.iter().any(|b| matches!(b, ContentBlock::Image(_)))
&& user.content.iter().any(|b| matches!(b, ContentBlock::Document(MediaRef::Path { .. })))));
- assert_eq!(native_parts_in_committed_message(&all, &message), vec![image, file]);
+ assert_eq!(
+ native_parts_in_committed_message(&all, &message),
+ vec![image, file]
+ );
assert!(native_parts_in_committed_message(&all, &Message::assistant("text")).is_empty());
}
@@ -309,8 +433,15 @@ fn typed_parts_pair_with_staged_files_and_drop_provider_locations() {
..Default::default()
};
let parts = vec![
- ContentPart::Text { text: "hello".into(), markdown_dialect: None },
- ContentPart::Image { media: located(MediaKind::Image), caption: Some("c".into()), alt_text: Some("a".into()) },
+ ContentPart::Text {
+ text: "hello".into(),
+ markdown_dialect: None,
+ },
+ ContentPart::Image {
+ media: located(MediaKind::Image),
+ caption: Some("c".into()),
+ alt_text: Some("a".into()),
+ },
ContentPart::Audio {
media: located(MediaKind::Audio),
codec: Some("opus".into()),
@@ -324,7 +455,11 @@ fn typed_parts_pair_with_staged_files_and_drop_provider_locations() {
duration_ms: Some(900),
thumbnail: Some(located(MediaKind::Image)),
},
- ContentPart::File { media: located(MediaKind::Document), file_name: Some("report.pdf".into()), caption: None },
+ ContentPart::File {
+ media: located(MediaKind::Document),
+ file_name: Some("report.pdf".into()),
+ caption: None,
+ },
];
let files = vec![
stored_file("a.png", "image/png", 11),
@@ -335,8 +470,16 @@ fn typed_parts_pair_with_staged_files_and_drop_provider_locations() {
let entries = from_staged_parts(&parts, &files).unwrap();
assert_eq!(entries.len(), 4);
assert_eq!(
- entries.iter().map(|(_, path)| path.as_str()).collect::<Vec<_>>(),
- ["uploads/a.png", "uploads/b.opus", "uploads/c.mp4", "uploads/d.pdf"]
+ entries
+ .iter()
+ .map(|(_, path)| path.as_str())
+ .collect::<Vec<_>>(),
+ [
+ "uploads/a.png",
+ "uploads/b.opus",
+ "uploads/c.mp4",
+ "uploads/d.pdf"
+ ]
);
for ((part, _), (mime, size)) in entries.iter().zip([
("image/png", 11u64),
@@ -345,22 +488,38 @@ fn typed_parts_pair_with_staged_files_and_drop_provider_locations() {
("application/pdf", 44),
]) {
let media = opaque_media(part).unwrap();
- assert_ne!(media.opaque_id.as_deref(), Some("provider-id"), "fresh opaque id");
+ assert_ne!(
+ media.opaque_id.as_deref(),
+ Some("provider-id"),
+ "fresh opaque id"
+ );
assert!(media.path.is_none() && media.url.is_none() && media.local_cache_path.is_none());
assert_eq!(media.content_type.as_deref(), Some(mime));
assert_eq!(media.size_bytes, Some(size));
}
- assert!(matches!(&entries[0].0, ContentPart::Image { caption: Some(c), alt_text: Some(a), .. } if c == "c" && a == "a"));
- assert!(matches!(&entries[1].0, ContentPart::Audio { codec: Some(c), duration_ms: Some(1200), .. } if c == "opus"));
+ assert!(
+ matches!(&entries[0].0, ContentPart::Image { caption: Some(c), alt_text: Some(a), .. } if c == "c" && a == "a")
+ );
+ assert!(
+ matches!(&entries[1].0, ContentPart::Audio { codec: Some(c), duration_ms: Some(1200), .. } if c == "opus")
+ );
match &entries[2].0 {
- ContentPart::Video { thumbnail: Some(thumb), duration_ms: Some(900), .. } => {
+ ContentPart::Video {
+ thumbnail: Some(thumb),
+ duration_ms: Some(900),
+ ..
+ } => {
assert!(thumb.path.is_none() && thumb.url.is_none());
assert!(thumb.local_cache_path.is_none() && thumb.opaque_id.is_none());
}
other => panic!("video expected: {other:?}"),
}
match &entries[3].0 {
- ContentPart::File { media, file_name: Some(name), .. } => {
+ ContentPart::File {
+ media,
+ file_name: Some(name),
+ ..
+ } => {
assert_eq!(name, "report.pdf");
assert_eq!(media.file_name.as_deref(), Some("report.pdf"));
}
@@ -383,6 +542,8 @@ fn typed_part_pairing_rejects_count_mismatches_and_unsupported_kinds() {
let err = from_staged_parts(&[image.clone()], &[]).unwrap_err();
assert!(err.contains("media ordering"), "{err}");
// Voice notes carry no staged file and are skipped.
- let voice = ContentPart::VoiceNote { voice_note: Default::default() };
+ let voice = ContentPart::VoiceNote {
+ voice_note: Default::default(),
+ };
assert!(from_staged_parts(&[voice], &[]).unwrap().is_empty());
}
diff --git a/crates/openhuman-tui/src/demo_tests.rs b/crates/openhuman-tui/src/demo_tests.rs
index d08fd842a0..d5a2fb0568 100644
--- a/crates/openhuman-tui/src/demo_tests.rs
+++ b/crates/openhuman-tui/src/demo_tests.rs
@@ -16,16 +16,21 @@ fn sample_transcript_has_user_turn_tools_subagent_and_final_answer() {
.unwrap()
.contains("offline preview; no model or account calls"));
assert!(!state.is_streaming());
- assert!(state.entries().iter().any(|e| e.activity.as_ref().is_some_and(|a| a.child)));
- assert!(state.entries().iter().any(|e| e.activity.as_ref().is_some_and(|a| !a.child)));
+ assert!(state
+ .entries()
+ .iter()
+ .any(|e| e.activity.as_ref().is_some_and(|a| a.child)));
+ assert!(state
+ .entries()
+ .iter()
+ .any(|e| e.activity.as_ref().is_some_and(|a| !a.child)));
}
#[test]
fn sample_renders_on_the_production_renderer() {
let state = sample();
let mut ui = ui();
- let mut terminal =
- ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
+ let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
terminal
.draw(|f| crate::render::draw(f, &state, &mut ui))
.unwrap();
@@ -48,7 +53,12 @@ fn sending_in_preview_explains_it_is_offline_and_clears_the_composer() {
ui.composer.insert_str("hello there");
assert!(!act(Action::Send, &mut state, &mut ui));
assert_eq!(state.entries().len(), before + 1);
- assert!(state.entries().last().unwrap().text.contains("Offline preview"));
+ assert!(state
+ .entries()
+ .last()
+ .unwrap()
+ .text
+ .contains("Offline preview"));
assert_eq!(ui.composer.text(), "");
assert_eq!(ui.scroll_from_bottom, 0);
// An empty composer sends nothing.
@@ -118,7 +128,12 @@ fn commands_open_overlays_tabs_and_reset_the_conversation() {
let before = state.entries().len();
command("compact", &mut state, &mut ui);
assert_eq!(state.entries().len(), before + 1);
- assert!(state.entries().last().unwrap().text.contains("needs live mode"));
+ assert!(state
+ .entries()
+ .last()
+ .unwrap()
+ .text
+ .contains("needs live mode"));
command("new", &mut state, &mut ui);
assert!(state.entries().is_empty());
}
diff --git a/crates/openhuman-tui/src/event_view_tests.rs b/crates/openhuman-tui/src/event_view_tests.rs
index 01121af9ff..0032ab4a56 100644
--- a/crates/openhuman-tui/src/event_view_tests.rs
+++ b/crates/openhuman-tui/src/event_view_tests.rs
@@ -28,7 +28,11 @@ fn context_fields_and_event_name_are_projected() {
let v = view(json!({"event": "text_delta", "delta": "hi"}));
assert_eq!(v.event, "text_delta");
assert_eq!(
- (v.client_id.as_str(), v.thread_id.as_str(), v.request_id.as_str()),
+ (
+ v.client_id.as_str(),
+ v.thread_id.as_str(),
+ v.request_id.as_str()
+ ),
("c1", "t1", "r1")
);
assert_eq!(v.seq, Some(7));
@@ -37,13 +41,25 @@ fn context_fields_and_event_name_are_projected() {
#[test]
fn final_response_variants_expose_full_response() {
- for name in ["chat_done", "chat_interim", "chat_message", "chat_segment", "proactive_message", "voice_speak", "channel_outbound"] {
+ for name in [
+ "chat_done",
+ "chat_interim",
+ "chat_message",
+ "chat_segment",
+ "proactive_message",
+ "voice_speak",
+ "channel_outbound",
+ ] {
let parsed = serde_json::from_value::<WebChannelEvent>(json!({
"event": name, "client_id": "c", "thread_id": "t", "request_id": "r",
"full_response": "answer"
}));
let event = parsed.unwrap_or_else(|e| panic!("{name}: {e}"));
- assert_eq!(WebEventView::from_event(&event).full_response.as_deref(), Some("answer"), "{name}");
+ assert_eq!(
+ WebEventView::from_event(&event).full_response.as_deref(),
+ Some("answer"),
+ "{name}"
+ );
}
let v = view(json!({"event": "chat_done", "full_response": "answer"}));
assert_eq!(v.full_response.as_deref(), Some("answer"));
@@ -51,8 +67,10 @@ fn final_response_variants_expose_full_response() {
#[test]
fn chat_error_and_cancel_expose_retry_metadata() {
- let v = view(json!({"event": "chat_error", "message": "boom", "error_type": "network",
- "error_retryable": true, "error_retry_after_ms": 1500}));
+ let v = view(
+ json!({"event": "chat_error", "message": "boom", "error_type": "network",
+ "error_retryable": true, "error_retry_after_ms": 1500}),
+ );
assert_eq!(v.message.as_deref(), Some("boom"));
assert_eq!(v.error_type.as_deref(), Some("network"));
assert_eq!(v.error_retryable, Some(true));
@@ -67,16 +85,31 @@ fn chat_error_and_cancel_expose_retry_metadata() {
#[test]
fn deltas_and_iteration_messages_are_projected() {
- assert_eq!(view(json!({"event": "thinking_delta", "delta": "hm"})).delta.as_deref(), Some("hm"));
- assert_eq!(view(json!({"event": "iteration_start", "message": "round 2"})).message.as_deref(), Some("round 2"));
- let v = view(json!({"event": "tool_args_delta", "delta": "{\"a\"", "tool_name": "t",
- "skill_id": "s", "tool_call_id": "tc"}));
+ assert_eq!(
+ view(json!({"event": "thinking_delta", "delta": "hm"}))
+ .delta
+ .as_deref(),
+ Some("hm")
+ );
+ assert_eq!(
+ view(json!({"event": "iteration_start", "message": "round 2"}))
+ .message
+ .as_deref(),
+ Some("round 2")
+ );
+ let v = view(
+ json!({"event": "tool_args_delta", "delta": "{\"a\"", "tool_name": "t",
+ "skill_id": "s", "tool_call_id": "tc"}),
+ );
assert_eq!(v.delta.as_deref(), Some("{\"a\""));
assert_eq!(v.tool_name.as_deref(), Some("t"));
assert_eq!(v.skill_id.as_deref(), Some("s"));
assert_eq!(v.tool_call_id.as_deref(), Some("tc"));
let v = view(json!({"event": "tool_progress", "tool_call_id": "tc", "message": "50%"}));
- assert_eq!((v.tool_call_id.as_deref(), v.message.as_deref()), (Some("tc"), Some("50%")));
+ assert_eq!(
+ (v.tool_call_id.as_deref(), v.message.as_deref()),
+ (Some("tc"), Some("50%"))
+ );
}
#[test]
@@ -91,14 +124,18 @@ fn subagent_deltas_carry_subagent_detail() {
#[test]
fn tool_call_and_result_variants_project_all_fields() {
- let v = view(json!({"event": "tool_call", "tool_name": "read", "skill_id": "s",
- "args": {"p": 1}, "tool_call_id": "tc", "tool_display_label": "Reading"}));
+ let v = view(
+ json!({"event": "tool_call", "tool_name": "read", "skill_id": "s",
+ "args": {"p": 1}, "tool_call_id": "tc", "tool_display_label": "Reading"}),
+ );
assert_eq!(v.tool_name.as_deref(), Some("read"));
assert_eq!(v.args, Some(json!({"p": 1})));
assert_eq!(v.tool_display_label.as_deref(), Some("Reading"));
- let v = view(json!({"event": "subagent_tool_call", "tool_name": "read", "skill_id": "s",
- "args": {"p": 1}, "tool_call_id": "tc", "tool_display_label": "Reading", "subagent": sub()}));
+ let v = view(
+ json!({"event": "subagent_tool_call", "tool_name": "read", "skill_id": "s",
+ "args": {"p": 1}, "tool_call_id": "tc", "tool_display_label": "Reading", "subagent": sub()}),
+ );
assert_eq!(v.tool_call_id.as_deref(), Some("tc"));
assert_sub(&v);
@@ -126,14 +163,18 @@ fn tool_call_and_result_variants_project_all_fields() {
#[test]
fn approval_and_plan_review_variants_project_prompt_fields() {
for name in ["approval_request", "plan_review_request"] {
- let v = view(json!({"event": name, "tool_name": "shell", "args": {"cmd": "ls"},
- "tool_call_id": "tc", "message": "allow?"}));
+ let v = view(
+ json!({"event": name, "tool_name": "shell", "args": {"cmd": "ls"},
+ "tool_call_id": "tc", "message": "allow?"}),
+ );
assert_eq!(v.tool_name.as_deref(), Some("shell"), "{name}");
assert_eq!(v.message.as_deref(), Some("allow?"), "{name}");
assert_eq!(v.args, Some(json!({"cmd": "ls"})), "{name}");
}
for name in ["approval_decided", "plan_review_decided"] {
- let v = view(json!({"event": name, "tool_name": "shell", "message": "approved", "tool_call_id": "tc"}));
+ let v = view(
+ json!({"event": name, "tool_name": "shell", "message": "approved", "tool_call_id": "tc"}),
+ );
assert_eq!(v.message.as_deref(), Some("approved"), "{name}");
assert_eq!(v.tool_call_id.as_deref(), Some("tc"), "{name}");
}
@@ -142,14 +183,22 @@ fn approval_and_plan_review_variants_project_prompt_fields() {
#[test]
fn subagent_lifecycle_events_project_status() {
for name in ["subagent_spawned", "subagent_iteration_start"] {
- let v = view(json!({"event": name, "tool_name": "Explore", "skill_id": "s",
- "message": "go", "subagent": sub()}));
+ let v = view(
+ json!({"event": name, "tool_name": "Explore", "skill_id": "s",
+ "message": "go", "subagent": sub()}),
+ );
assert_eq!(v.message.as_deref(), Some("go"), "{name}");
assert_sub(&v);
}
- for name in ["subagent_completed", "subagent_failed", "subagent_awaiting_user"] {
- let v = view(json!({"event": name, "tool_name": "Explore", "skill_id": "s",
- "message": "m", "success": true, "subagent": sub()}));
+ for name in [
+ "subagent_completed",
+ "subagent_failed",
+ "subagent_awaiting_user",
+ ] {
+ let v = view(
+ json!({"event": name, "tool_name": "Explore", "skill_id": "s",
+ "message": "m", "success": true, "subagent": sub()}),
+ );
assert_eq!(v.success, Some(true), "{name}");
assert_eq!(v.tool_name.as_deref(), Some("Explore"), "{name}");
assert_sub(&v);