Skip to content

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

test(tinymemes): cover the remix hook, engine host, and Jev route

killbillb0d3f60dc63a
diff --git a/crates/openhuman-core/src/tinymemes/arm_tests.rs b/crates/openhuman-core/src/tinymemes/arm_tests.rs
index fabd5ba66d..ae630d1d45 100644
--- a/crates/openhuman-core/src/tinymemes/arm_tests.rs
+++ b/crates/openhuman-core/src/tinymemes/arm_tests.rs
@@ -54,3 +54,12 @@ fn runtime_flag_overrides_the_build_default() {
Mode::Ab { percent: 50 }
);
}
+
+#[test]
+fn arms_have_log_names() {
+ assert_eq!(Arm::Disabled.as_str(), "disabled");
+ assert_eq!(Arm::Control.as_str(), "control");
+ assert_eq!(Arm::Treatment.as_str(), "treatment");
+ // The live flag resolves without panicking whatever the environment holds.
+ let _ = mode();
+}
diff --git a/crates/openhuman-core/src/tinymemes/host.rs b/crates/openhuman-core/src/tinymemes/host.rs
index a13b8a2186..9c59188c06 100644
--- a/crates/openhuman-core/src/tinymemes/host.rs
+++ b/crates/openhuman-core/src/tinymemes/host.rs
@@ -199,12 +199,7 @@ pub(crate) fn host_for(config: &Config) -> Option<Arc<Host>> {
engine.slang_index().len("IN"),
engine.meme_index().len("IN")
);
- let host = Arc::new(Host {
- engine,
- dir,
- remixed: Mutex::new(remixed),
- fingerprint: fp,
- });
+ let host = Arc::new(Host::new(engine, dir, remixed, fp));
hosts.insert(workspace_dir.to_path_buf(), host.clone());
Some(host)
}
@@ -284,6 +279,21 @@ fn rating_policy() -> RatingPolicy {
}
impl Host {
+ /// A host over `engine`, keeping its state files in `dir`.
+ pub(crate) fn new(
+ engine: MemeEngine,
+ dir: PathBuf,
+ remixed: VecDeque<String>,
+ fingerprint: u64,
+ ) -> Self {
+ Self {
+ engine,
+ dir,
+ remixed: Mutex::new(remixed),
+ fingerprint,
+ }
+ }
+
pub(crate) fn is_remixed(&self, message_id: &str) -> bool {
self.remixed
.lock()
diff --git a/crates/openhuman-core/src/tinymemes/host_tests.rs b/crates/openhuman-core/src/tinymemes/host_tests.rs
index e1bb2e6175..075a26fce9 100644
--- a/crates/openhuman-core/src/tinymemes/host_tests.rs
+++ b/crates/openhuman-core/src/tinymemes/host_tests.rs
@@ -85,3 +85,106 @@ fn the_fingerprint_follows_the_provider_settings() {
changed.inference_url = Some("https://openrouter.ai/api/v1".into());
assert_ne!(fingerprint(&changed), base);
}
+
+fn config_in(dir: &std::path::Path) -> Config {
+ let mut config = Config::default();
+ config.config_path = dir.join("config.toml");
+ config.workspace_dir = dir.join("workspace");
+ config.secrets.encrypt = false;
+ config
+}
+
+#[test]
+fn remixed_ids_are_deduplicated_persisted_and_capped() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let host = host_for(&config_in(dir.path())).expect("engine");
+ host.mark_remixed("m1".into());
+ host.mark_remixed("m1".into());
+ host.mark_remixed("m2".into());
+ assert!(host.is_remixed("m1") && host.is_remixed("m2"));
+ assert!(!host.is_remixed("m3"));
+ let saved = load_remixed(&dir.path().join("workspace").join(DIR));
+ assert_eq!(saved, ["m1", "m2"]);
+
+ let mut ids: VecDeque<String> = (0..REMIXED_CAP + 3).map(|i| i.to_string()).collect();
+ cap_remixed(&mut ids);
+ assert_eq!(ids.len(), REMIXED_CAP);
+ assert_eq!(ids.front().map(String::as_str), Some("3"));
+}
+
+#[test]
+fn learned_state_survives_an_engine_rebuild() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let config = config_in(dir.path());
+ let first = host_for(&config).expect("engine");
+ assert!(Arc::ptr_eq(&first, &host_for(&config).unwrap()));
+ first.mark_remixed("kept".into());
+
+ // A settings change rebuilds the engine but keeps what it learned.
+ let mut changed = config.clone();
+ changed.inference_url = Some("https://openrouter.ai/api/v1".into());
+ let rebuilt = host_for(&changed).expect("engine");
+ assert!(!Arc::ptr_eq(&first, &rebuilt));
+ assert!(rebuilt.is_remixed("kept"));
+}
+
+#[test]
+fn indexes_round_trip_through_disk() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let config = config_in(dir.path());
+ let host = host_for(&config).expect("engine");
+ host.save_index();
+ host.save_memes();
+ let state = dir.path().join("workspace").join(DIR);
+ assert!(state.join(INDEX_FILE).exists());
+ assert!(state.join(MEME_INDEX_FILE).exists());
+ assert_eq!(
+ load_slang_index(&state).to_json(),
+ host.engine.slang_index().to_json()
+ );
+ assert_eq!(
+ load_meme_index(&state).to_json(),
+ host.engine.meme_index().to_json()
+ );
+}
+
+#[test]
+fn unreadable_state_files_start_fresh() {
+ let dir = tempfile::TempDir::new().unwrap();
+ for file in [INDEX_FILE, MEME_INDEX_FILE, REMIXED_FILE] {
+ std::fs::write(dir.path().join(file), "not json").unwrap();
+ }
+ assert_eq!(load_slang_index(dir.path()).len("IN"), 0);
+ assert_eq!(load_meme_index(dir.path()).len("IN"), 0);
+ assert!(load_remixed(dir.path()).is_empty());
+ // Missing files are a fresh start too.
+ let empty = tempfile::TempDir::new().unwrap();
+ assert_eq!(load_slang_index(empty.path()).len("IN"), 0);
+ assert_eq!(load_meme_index(empty.path()).len("IN"), 0);
+}
+
+#[test]
+fn the_meme_cooldown_follows_its_env_override() {
+ if std::env::var(MEME_COOLDOWN_ENV).is_err() {
+ assert_eq!(
+ rating_policy().meme_cooldown_turns,
+ RatingPolicy::default().meme_cooldown_turns
+ );
+ }
+}
+
+#[test]
+fn a_failed_write_leaves_no_temp_file() {
+ let dir = tempfile::TempDir::new().unwrap();
+ // Renaming over a directory fails; the temp file must be cleaned up.
+ let target = dir.path().join("taken");
+ std::fs::create_dir(&target).unwrap();
+ std::fs::write(target.join("child"), "x").unwrap();
+ assert!(write_atomic(&target, "{}").is_err());
+ let leftovers: Vec<_> = std::fs::read_dir(dir.path())
+ .unwrap()
+ .filter_map(|e| e.ok())
+ .filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
+ .collect();
+ assert!(leftovers.is_empty());
+}
diff --git a/crates/openhuman-core/src/tinymemes/inference_tests.rs b/crates/openhuman-core/src/tinymemes/inference_tests.rs
index 1424eb3875..ba2e2af360 100644
--- a/crates/openhuman-core/src/tinymemes/inference_tests.rs
+++ b/crates/openhuman-core/src/tinymemes/inference_tests.rs
@@ -15,3 +15,15 @@ fn openrouter_routes_are_detected() {
config.memory_provider = Some("ollama:llama3.1:8b".into());
assert!(!routes_to_openrouter(&config));
}
+
+#[test]
+fn the_model_label_never_fails() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.config_path = dir.path().join("config.toml");
+ config.workspace_dir = dir.path().join("workspace");
+ config.secrets.encrypt = false;
+ // Either the resolved model id or an `unavailable (...)` label.
+ assert!(!resolved_model(&config).trim().is_empty());
+ let _model = OpenHumanChatModel::new(config);
+}
diff --git a/crates/openhuman-core/src/tinymemes/jev.rs b/crates/openhuman-core/src/tinymemes/jev.rs
index c89fd82cb3..4e5c15d591 100644
--- a/crates/openhuman-core/src/tinymemes/jev.rs
+++ b/crates/openhuman-core/src/tinymemes/jev.rs
@@ -39,3 +39,7 @@ pub(crate) fn managed(config: &Config) -> Option<Arc<dyn tinymemes::Evaluator>>
}
}
}
+
+#[cfg(test)]
+#[path = "jev_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/tinymemes/jev_tests.rs b/crates/openhuman-core/src/tinymemes/jev_tests.rs
new file mode 100644
index 0000000000..87fbf708ac
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/jev_tests.rs
@@ -0,0 +1,23 @@
+use super::*;
+
+fn config_in(dir: &std::path::Path) -> Config {
+ let mut config = Config::default();
+ config.config_path = dir.join("config.toml");
+ config.workspace_dir = dir.join("workspace");
+ config.secrets.encrypt = false;
+ config
+}
+
+#[test]
+fn without_a_backend_credential_managed_jev_is_unavailable() {
+ let dir = tempfile::tempdir().unwrap();
+ assert!(managed(&config_in(dir.path())).is_none());
+}
+
+#[test]
+fn an_api_key_reaches_managed_jev() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = config_in(dir.path());
+ crate::security::credentials::api_key::store_api_key(&config, "th_live_test").unwrap();
+ assert!(managed(&config).is_some());
+}
diff --git a/crates/openhuman-core/src/tinymemes/mod.rs b/crates/openhuman-core/src/tinymemes/mod.rs
index 95f61769bb..25226bf902 100644
--- a/crates/openhuman-core/src/tinymemes/mod.rs
+++ b/crates/openhuman-core/src/tinymemes/mod.rs
@@ -38,10 +38,47 @@ pub(crate) fn holds_text_stream(thread_id: &str) -> bool {
arm::assign(arm::mode(), thread_id) == Arm::Treatment
}
+/// Remix a finished task's reply in place, when it is a real answer (not
+/// empty, not the `placeholder` sent when the inference budget ran out) and
+/// the thread is in the treatment arm. Fails open: the reply is left
+/// untouched on any error.
+pub(crate) async fn remix_task_reply(
+ config: &Config,
+ thread_id: &str,
+ request_id: &str,
+ user_message: &str,
+ full_response: &mut String,
+ placeholder: &str,
+ turn_elapsed: Duration,
+) {
+ if !should_remix(full_response, placeholder) {
+ return;
+ }
+ if let Some(remixed) = remix_final_reply(
+ arm::assign(arm::mode(), thread_id),
+ config,
+ thread_id,
+ request_id,
+ user_message,
+ full_response,
+ turn_elapsed,
+ )
+ .await
+ {
+ *full_response = remixed;
+ }
+}
+
+/// Whether a finished reply is worth remixing at all.
+fn should_remix(reply: &str, placeholder: &str) -> bool {
+ reply != placeholder && !reply.trim().is_empty()
+}
+
/// Remix a finished turn's reply. Returns the text to deliver instead, or
/// `None` to deliver the original. `turn_elapsed` is the agent turn's own
/// duration, logged for both arms so throughput can be compared.
-pub(crate) async fn remix_final_reply(
+async fn remix_final_reply(
+ arm: Arm,
config: &Config,
thread_id: &str,
request_id: &str,
@@ -49,74 +86,116 @@ pub(crate) async fn remix_final_reply(
reply: &str,
turn_elapsed: Duration,
) -> Option<String> {
- let arm = arm::assign(arm::mode(), thread_id);
- let bucket = arm::bucket(thread_id);
- let turn_ms = turn_elapsed.as_millis();
+ let turn = TurnInfo {
+ request_id,
+ bucket: arm::bucket(thread_id),
+ turn_ms: turn_elapsed.as_millis(),
+ };
+ if !gate(arm, &turn) {
+ return None;
+ }
+ let started = Instant::now();
+ let Some((host, messages)) = load(config, thread_id).await else {
+ log_outcome(&turn, started, "engine_unavailable", None);
+ return None;
+ };
+ // Fail open: without the thread, the reading would judge the reply out of
+ // context, so the original goes out instead.
+ let Some(messages) = messages else {
+ log_outcome(&turn, started, "history_unavailable", None);
+ return None;
+ };
+ remix_with(
+ &host,
+ &messages,
+ &turn,
+ started,
+ user_message,
+ reply,
+ budget(),
+ )
+ .await
+}
+
+/// Per-turn identifiers for the A/B log line.
+#[derive(Clone, Copy)]
+struct TurnInfo<'a> {
+ request_id: &'a str,
+ bucket: u8,
+ turn_ms: u128,
+}
+
+/// Whether the arm runs the remix. The control arm logs its turn for the
+/// throughput comparison; a disabled flag does nothing at all.
+fn gate(arm: Arm, turn: &TurnInfo<'_>) -> bool {
match arm {
- Arm::Disabled => return None,
+ Arm::Disabled => false,
Arm::Control => {
log::info!(
- "[tinymemes] turn arm=control bucket={bucket} request_id={request_id} \
- turn_ms={turn_ms} remix_ms=0 outcome=not_remixed"
+ "[tinymemes] turn arm={} bucket={} request_id={} turn_ms={} remix_ms=0 \
+ outcome=not_remixed",
+ arm.as_str(),
+ turn.bucket,
+ turn.request_id,
+ turn.turn_ms
);
- return None;
+ false
}
- Arm::Treatment => {}
+ Arm::Treatment => true,
}
+}
- let started = Instant::now();
- // Engine lookup (credentials, first-use state files) and the thread read
- // are blocking file work, so they run off the async runtime.
- let blocking_config = config.clone();
- let blocking_thread = thread_id.to_owned();
- let loaded = crate::core::runtime::spawn_blocking_scoped(move || {
- let host = host::host_for(&blocking_config)?;
- let messages = crate::threads::store::get_messages(
- blocking_config.workspace_dir.clone(),
- &blocking_thread,
- )
- .map_err(|e| log::warn!("[tinymemes] thread history unavailable: {e}"))
- .ok();
+/// The workspace's engine and the thread as stored. Engine lookup
+/// (credentials, first-use state files) and the thread read are blocking file
+/// work, so they run off the async runtime. `None` when no engine can be
+/// built; the inner `None` when the thread cannot be read.
+async fn load(
+ config: &Config,
+ thread_id: &str,
+) -> Option<(
+ std::sync::Arc<host::Host>,
+ Option<Vec<crate::threads::store::ConversationMessage>>,
+)> {
+ let config = config.clone();
+ let thread_id = thread_id.to_owned();
+ crate::core::runtime::spawn_blocking_scoped(move || {
+ let host = host::host_for(&config)?;
+ let messages =
+ crate::threads::store::get_messages(config.workspace_dir.clone(), &thread_id)
+ .map_err(|e| log::warn!("[tinymemes] thread history unavailable: {e}"))
+ .ok();
Some((host, messages))
})
.await
.ok()
- .flatten();
- let Some((host, messages)) = loaded else {
- log_outcome(
- request_id,
- bucket,
- turn_ms,
- started,
- "engine_unavailable",
- None,
- );
- return None;
- };
- // Fail open: without the thread, the reading would judge the reply out of
- // context, so the original goes out instead.
- let Some(messages) = messages else {
- log_outcome(
- request_id,
- bucket,
- turn_ms,
- started,
- "history_unavailable",
- None,
- );
- return None;
- };
- let turns = host::history_turns(&messages, user_message, |id| host.is_remixed(id));
+ .flatten()
+}
- let budget = std::env::var(TIMEOUT_ENV)
+/// The remix time budget: `OPENHUMAN_TINYMEMES_TIMEOUT_MS`, else 20 s.
+fn budget() -> Duration {
+ std::env::var(TIMEOUT_ENV)
.ok()
.and_then(|v| v.parse::<u64>().ok())
.map(Duration::from_millis)
- .unwrap_or(DEFAULT_TIMEOUT);
+ .unwrap_or(DEFAULT_TIMEOUT)
+}
+
+/// Read, rate, and remix `reply` against the thread, within `budget`.
+async fn remix_with(
+ host: &std::sync::Arc<host::Host>,
+ messages: &[crate::threads::store::ConversationMessage],
+ turn: &TurnInfo<'_>,
+ started: Instant,
+ user_message: &str,
+ reply: &str,
+ budget: Duration,
+) -> Option<String> {
+ let request_id = turn.request_id;
+ let turns = host::history_turns(messages, user_message, |id| host.is_remixed(id));
let outcome = match tokio::time::timeout(budget, host.engine.process(&turns, reply)).await {
Ok(outcome) => outcome,
Err(_) => {
- log_outcome(request_id, bucket, turn_ms, started, "timeout", None);
+ log_outcome(turn, started, "timeout", None);
return None;
}
};
@@ -196,23 +275,38 @@ pub(crate) async fn remix_final_reply(
} else {
"unchanged"
};
- log_outcome(request_id, bucket, turn_ms, started, result, Some(&outcome));
+ log_outcome(turn, started, result, Some(&outcome));
remixed.then_some(outcome.reply)
}
fn log_outcome(
- request_id: &str,
- bucket: u8,
- turn_ms: u128,
+ turn: &TurnInfo<'_>,
started: Instant,
result: &str,
outcome: Option<&tinymemes::Outcome>,
) {
- let remix_ms = started.elapsed().as_millis();
+ log::info!(
+ "{}",
+ turn_line(turn, started.elapsed().as_millis(), result, outcome)
+ );
+}
+
+/// The treatment arm's per-turn log line. No user content goes in it.
+fn turn_line(
+ turn: &TurnInfo<'_>,
+ remix_ms: u128,
+ result: &str,
+ outcome: Option<&tinymemes::Outcome>,
+) -> String {
+ let TurnInfo {
+ request_id,
+ bucket,
+ turn_ms,
+ } = *turn;
let rating = outcome.and_then(|o| o.rating);
let remix = outcome.and_then(|o| o.remix.as_ref());
let reading = outcome.and_then(|o| o.reading.as_ref());
- log::info!(
+ format!(
"[tinymemes] turn arm=treatment bucket={bucket} request_id={request_id} turn_ms={turn_ms} \
remix_ms={remix_ms} outcome={result} score={} tier={} mode={} memes={} rewrite_kept={} \
dupes={} slang_enough={} wants_search={} meme_pick={} meme_p={} matches={}",
@@ -251,5 +345,9 @@ fn log_outcome(
reading
.and_then(|r| r.reply_matches_user)
.map_or_else(|| "none".to_owned(), |p| format!("{p:.2}")),
- );
+ )
}
+
+#[cfg(test)]
+#[path = "mod_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/tinymemes/mod_tests.rs b/crates/openhuman-core/src/tinymemes/mod_tests.rs
new file mode 100644
index 0000000000..531c01f0b6
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/mod_tests.rs
@@ -0,0 +1,414 @@
+use super::*;
+
+use std::collections::{BTreeMap, VecDeque};
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use tinymemes::decisions::{
+ Answer, ChoiceAnswer, EvaluationRequest, EvaluationResponse, NoulAnswer, ScoreAnswer, Usage,
+};
+use tinymemes::{BoxError, ChatModel, Evaluator, MemeEngine, Region};
+
+use crate::threads::store::ConversationMessage;
+
+/// Answers every reading question the same way, whatever the chat.
+struct ScriptedJev {
+ frankness: f64,
+ playful: f64,
+ serious: f64,
+ slang_enough: f64,
+ meme: Option<&'static str>,
+}
+
+#[async_trait]
+impl Evaluator for ScriptedJev {
+ async fn evaluate(&self, request: &EvaluationRequest) -> Result<EvaluationResponse, BoxError> {
+ let choice = |c: &str| {
+ Answer::Choice(ChoiceAnswer {
+ choice: c.to_owned(),
+ probabilities: BTreeMap::new(),
+ confidence: 0.9,
+ })
+ };
+ let noul = |p: f64| Answer::Noul(NoulAnswer { noul: p });
+ let mut answers = BTreeMap::from([
+ ("chat_intent".to_owned(), choice("celebration")),
+ ("reply_intent".to_owned(), choice("celebration")),
+ (
+ "frankness".to_owned(),
+ Answer::Score(ScoreAnswer {
+ score: self.frankness * 4.0,
+ legend: BTreeMap::new(),
+ probabilities: BTreeMap::new(),
+ confidence: 0.8,
+ }),
+ ),
+ ("playful".to_owned(), noul(self.playful)),
+ ("serious".to_owned(), noul(self.serious)),
+ ]);
+ if request.questions.contains_key("slang_enough") {
+ answers.insert("slang_enough".to_owned(), noul(self.slang_enough));
+ answers.insert("slang_best".to_owned(), choice("yaar"));
+ }
+ if let (Some(meme), true) = (self.meme, request.questions.contains_key("meme_best")) {
+ answers.insert("meme_best".to_owned(), choice(meme));
+ }
+ Ok(EvaluationResponse {
+ model: "jev-latest".into(),
+ answers,
+ usage: Usage::default(),
+ })
+ }
+}
+
+struct FailingJev;
+
+#[async_trait]
+impl Evaluator for FailingJev {
+ async fn evaluate(&self, _: &EvaluationRequest) -> Result<EvaluationResponse, BoxError> {
+ Err("jev down".into())
+ }
+}
+
+/// Returns a fixed rewrite, after an optional delay.
+struct ScriptedModel {
+ rewrite: &'static str,
+ delay: Duration,
+}
+
+#[async_trait]
+impl ChatModel for ScriptedModel {
+ async fn complete(&self, _system: &str, _user: &str) -> Result<String, BoxError> {
+ tokio::time::sleep(self.delay).await;
+ Ok(self.rewrite.to_owned())
+ }
+}
+
+fn frank(slang_enough: f64) -> Arc<ScriptedJev> {
+ Arc::new(ScriptedJev {
+ frankness: 0.95,
+ playful: 0.95,
+ serious: 0.0,
+ slang_enough,
+ meme: None,
+ })
+}
+
+fn model(rewrite: &'static str) -> Arc<ScriptedModel> {
+ Arc::new(ScriptedModel {
+ rewrite,
+ delay: Duration::ZERO,
+ })
+}
+
+fn host(
+ dir: &tempfile::TempDir,
+ jev: Arc<dyn Evaluator>,
+ chat: Arc<dyn ChatModel>,
+ region: Option<Region>,
+) -> Arc<host::Host> {
+ let mut builder = MemeEngine::builder(jev, chat).learn_inline(None);
+ if let Some(region) = region {
+ builder = builder.region(region);
+ }
+ Arc::new(host::Host::new(
+ builder.build(),
+ dir.path().to_path_buf(),
+ VecDeque::new(),
+ 0,
+ ))
+}
+
+fn config_in(dir: &std::path::Path) -> Config {
+ let mut config = Config::default();
+ config.config_path = dir.join("config.toml");
+ config.workspace_dir = dir.join("workspace");
+ config.secrets.encrypt = false;
+ config
+}
+
+fn turn(request_id: &str) -> TurnInfo<'_> {
+ TurnInfo {
+ request_id,
+ bucket: 7,
+ turn_ms: 1200,
+ }
+}
+
+fn msg(id: &str, sender: &str, content: &str) -> ConversationMessage {
+ ConversationMessage {
+ id: id.to_owned(),
+ content: content.to_owned(),
+ message_type: "text".to_owned(),
+ extra_metadata: serde_json::Value::Null,
+ sender: sender.to_owned(),
+ created_at: "2026-10-09T00:00:00Z".to_owned(),
+ }
+}
+
+fn thread() -> Vec<ConversationMessage> {
+ vec![
+ msg("u1", "user", "yo the deploy finally went green lmaooo"),
+ msg("r1", "agent", "Nice. Want me to tag the release?"),
+ ]
+}
+
+const REPLY: &str = "Done. Tagged the release.";
+const REWRITE: &str = "Done bhai, release tagged, full send 🎉";
+
+/// Let spawned research tasks run to completion.
+async fn settle() {
+ for _ in 0..20 {
+ tokio::task::yield_now().await;
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+}
+
+#[test]
+fn only_real_answers_are_remixed() {
+ let placeholder = "You've hit your inference budget.";
+ assert!(should_remix("Here's the fix.", placeholder));
+ assert!(!should_remix("", placeholder));
+ assert!(!should_remix(" \n", placeholder));
+ assert!(!should_remix(placeholder, placeholder));
+}
+
+#[test]
+fn only_the_treatment_arm_passes_the_gate() {
+ let t = turn("req-gate");
+ assert!(!gate(Arm::Disabled, &t));
+ assert!(!gate(Arm::Control, &t));
+ assert!(gate(Arm::Treatment, &t));
+}
+
+#[test]
+fn the_budget_defaults_to_twenty_seconds() {
+ if std::env::var(TIMEOUT_ENV).is_err() {
+ assert_eq!(budget(), DEFAULT_TIMEOUT);
+ }
+}
+
+#[tokio::test]
+async fn a_disabled_flag_leaves_the_task_reply_alone() {
+ // The flag is unset in tests, so every thread is in the disabled arm.
+ if std::env::var(arm::FLAG_ENV).is_ok() {
+ return;
+ }
+ assert!(!holds_text_stream("thread-1"));
+ let dir = tempfile::TempDir::new().unwrap();
+ let config = config_in(dir.path());
+ let mut reply = REPLY.to_owned();
+ remix_task_reply(
+ &config,
+ "thread-1",
+ "req-1",
+ "tag it",
+ &mut reply,
+ "placeholder",
+ Duration::from_millis(5),
+ )
+ .await;
+ assert_eq!(reply, REPLY);
+
+ let mut empty = String::new();
+ remix_task_reply(
+ &config,
+ "thread-1",
+ "req-1",
+ "tag it",
+ &mut empty,
+ "placeholder",
+ Duration::ZERO,
+ )
+ .await;
+ assert!(empty.is_empty());
+}
+
+#[tokio::test]
+async fn load_builds_the_engine_once_per_workspace() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let config = config_in(dir.path());
+ let (first, _messages) = load(&config, "thread-missing").await.expect("engine");
+ let (second, _) = load(&config, "thread-missing").await.expect("engine");
+ assert!(Arc::ptr_eq(&first, &second), "the engine was rebuilt");
+ assert!(dir.path().join("workspace").join("tinymemes").is_dir());
+}
+
+#[tokio::test]
+async fn a_frank_chat_is_remixed_and_remembered() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let host = host(&dir, frank(0.9), model(REWRITE), Some(Region::global()));
+ let out = remix_with(
+ &host,
+ &thread(),
+ &turn("req-remix"),
+ Instant::now(),
+ "ya send it",
+ REPLY,
+ Duration::from_secs(5),
+ )
+ .await
+ .expect("remixed");
+ assert_ne!(out.trim(), REPLY);
+ // The delivered message is remembered as remixed, and state is saved.
+ let id = crate::threads::store::run_reply_message_id("req-remix");
+ assert!(host.is_remixed(&id));
+ let remixed: Vec<String> =
+ serde_json::from_str(&std::fs::read_to_string(dir.path().join("remixed.json")).unwrap())
+ .unwrap();
+ assert_eq!(remixed, [id]);
+ assert!(dir.path().join("slang-index.json").exists());
+ assert!(dir.path().join("meme-index.json").exists());
+}
+
+#[tokio::test]
+async fn a_short_slang_index_researches_after_delivery() {
+ let dir = tempfile::TempDir::new().unwrap();
+ // Jev judges the index short of slang; with no researcher configured the
+ // background task finds nothing to do and the reply still goes out.
+ let host = host(&dir, frank(0.05), model(REWRITE), Some(Region::global()));
+ let out = remix_with(
+ &host,
+ &thread(),
+ &turn("req-slang"),
+ Instant::now(),
+ "ya send it",
+ REPLY,
+ Duration::from_secs(5),
+ )
+ .await;
+ assert!(out.is_some());
+ settle().await;
+ assert!(dir.path().join("slang-index.json").exists());
+}
+
+#[tokio::test]
+async fn no_fitting_meme_starts_meme_research() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let jev = Arc::new(ScriptedJev {
+ meme: Some(tinymemes::reading::NONE_FIT),
+ ..*frank(0.9)
+ });
+ // The default (India) region offers catalog memes, so Jev is asked to
+ // pick one and answers that none fit.
+ let host = host(&dir, jev, model(REWRITE), None);
+ let _ = remix_with(
+ &host,
+ &thread(),
+ &turn("req-meme"),
+ Instant::now(),
+ "ya send it",
+ REPLY,
+ Duration::from_secs(5),
+ )
+ .await;
+ settle().await;
+ assert!(dir.path().join("meme-index.json").exists());
+}
+
+#[tokio::test]
+async fn an_off_rated_chat_is_left_unchanged() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let jev = Arc::new(ScriptedJev {
+ frankness: 0.0,
+ playful: 0.0,
+ serious: 0.9,
+ slang_enough: 0.9,
+ meme: None,
+ });
+ let host = host(&dir, jev, model(REWRITE), Some(Region::global()));
+ let out = remix_with(
+ &host,
+ &thread(),
+ &turn("req-off"),
+ Instant::now(),
+ "ya send it",
+ REPLY,
+ Duration::from_secs(5),
+ )
+ .await;
+ assert_eq!(out, None);
+ assert!(!dir.path().join("remixed.json").exists());
+}
+
+#[tokio::test]
+async fn a_jev_failure_sends_the_original() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let host = host(&dir, Arc::new(FailingJev), model(REWRITE), None);
+ let out = remix_with(
+ &host,
+ &thread(),
+ &turn("req-error"),
+ Instant::now(),
+ "ya send it",
+ REPLY,
+ Duration::from_secs(5),
+ )
+ .await;
+ assert_eq!(out, None);
+}
+
+#[tokio::test]
+async fn a_slow_remix_times_out_to_the_original() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let slow = Arc::new(ScriptedModel {
+ rewrite: REWRITE,
+ delay: Duration::from_secs(5),
+ });
+ let host = host(&dir, frank(0.9), slow, Some(Region::global()));
+ let out = remix_with(
+ &host,
+ &thread(),
+ &turn("req-timeout"),
+ Instant::now(),
+ "ya send it",
+ REPLY,
+ Duration::from_millis(50),
+ )
+ .await;
+ assert_eq!(out, None);
+}
+
+#[test]
+fn the_log_line_handles_a_missing_outcome() {
+ // Exercised for its formatting paths; it must not panic without a reading.
+ log_outcome(&turn("req-log"), Instant::now(), "engine_unavailable", None);
+}
+
+#[tokio::test]
+async fn the_turn_line_reports_the_outcome_without_user_content() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let host = host(&dir, frank(0.9), model(REWRITE), Some(Region::global()));
+ let turns = host::history_turns(&thread(), "ya send it", |_| false);
+ let outcome = host.engine.process(&turns, REPLY).await;
+ let line = turn_line(&turn("req-line"), 42, "remixed", Some(&outcome));
+ assert!(line.starts_with("[tinymemes] turn arm=treatment bucket=7 request_id=req-line"));
+ assert!(line.contains("turn_ms=1200 remix_ms=42 outcome=remixed"));
+ assert!(line.contains("tier=unhinged"), "{line}");
+ assert!(!line.contains("send it") && !line.contains("Tagged"));
+
+ let bare = turn_line(&turn("req-none"), 0, "timeout", None);
+ assert!(bare.contains("score=-1 tier=none mode=none memes=0 rewrite_kept=true dupes=0"));
+ assert!(bare.contains("meme_pick=none meme_p=none matches=none"));
+}
+
+#[tokio::test]
+async fn every_arm_fails_open_without_working_providers() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let config = config_in(dir.path());
+ for arm in [Arm::Disabled, Arm::Control, Arm::Treatment] {
+ // Treatment builds the real engine; with no provider configured every
+ // model call fails, so the original reply is delivered.
+ let out = remix_final_reply(
+ arm,
+ &config,
+ "thread-real",
+ "req-real",
+ "ya send it",
+ REPLY,
+ Duration::from_millis(5),
+ )
+ .await;
+ assert_eq!(out, None, "{arm:?}");
+ }
+}
diff --git a/crates/openhuman-core/src/tinymemes/search.rs b/crates/openhuman-core/src/tinymemes/search.rs
index 64be5244bd..c32c6bf676 100644
--- a/crates/openhuman-core/src/tinymemes/search.rs
+++ b/crates/openhuman-core/src/tinymemes/search.rs
@@ -60,3 +60,7 @@ impl tinymemes::WebSearch for OpenHumanSearch {
.collect())
}
}
+
+#[cfg(test)]
+#[path = "search_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/tinymemes/search_tests.rs b/crates/openhuman-core/src/tinymemes/search_tests.rs
new file mode 100644
index 0000000000..cabe0cb642
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/search_tests.rs
@@ -0,0 +1,19 @@
+use super::*;
+
+#[test]
+fn search_switched_off_in_settings_is_unavailable() {
+ let mut config = Config::default();
+ config.search.enabled = Some(false);
+ assert!(OpenHumanSearch::available(&config).is_none());
+}
+
+#[test]
+fn availability_follows_the_configured_providers() {
+ // Whatever the default providers resolve to, a backend is returned only
+ // when search is on; it never panics on a default config.
+ let mut config = Config::default();
+ config.search.enabled = Some(true);
+ if let Some(search) = OpenHumanSearch::available(&config) {
+ assert!(search.config.search.is_enabled());
+ }
+}
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 21e19315d2..e04fe3978c 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -301,21 +301,16 @@ pub(crate) async fn run_chat_task(
// original wording, and skips the budget-exhausted placeholder. Fails open.
#[cfg(feature = "tinymemes")]
if let Ok(ref mut task_result) = result {
- let is_placeholder = task_result.full_response == inference_budget_exceeded_user_message();
- if !is_placeholder && !task_result.full_response.trim().is_empty() {
- if let Some(remixed) = crate::tinymemes::remix_final_reply(
- &config,
- thread_id,
- request_id,
- message,
- &task_result.full_response,
- turn_started.elapsed(),
- )
- .await
- {
- task_result.full_response = remixed;
- }
- }
+ crate::tinymemes::remix_task_reply(
+ &config,
+ thread_id,
+ request_id,
+ message,
+ &mut task_result.full_response,
+ inference_budget_exceeded_user_message(),
+ turn_started.elapsed(),
+ )
+ .await;
}
agent.set_on_progress(None);