Skip to content

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

feat(tinymemes): remix the final reply with region slang and memes behind an A/B flag

killbillcc70cc74a2f4
diff --git a/Cargo.lock b/Cargo.lock
index d3cf7a4af4..2d4b1ed9cb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4619,6 +4619,7 @@ dependencies = [
"tinyjuice-bus",
"tinymcp",
"tinymcp-bus",
+ "tinymemes",
"tinymemory-api",
"tinymemory-integrations",
"tinymemory-tools",
@@ -7596,6 +7597,19 @@ dependencies = [
"url",
]
+[[package]]
+name = "tinyinference-decisions"
+version = "0.3.0"
+dependencies = [
+ "async-trait",
+ "httpdate",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.20",
+ "tokio",
+]
+
[[package]]
name = "tinyinference-embeddings"
version = "0.3.0"
@@ -7811,6 +7825,21 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "tinymemes"
+version = "0.1.0"
+dependencies = [
+ "async-trait",
+ "futures",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.20",
+ "tinyinference-decisions",
+ "tokio",
+ "tracing",
+]
+
[[package]]
name = "tinymemory-api"
version = "1.25.0"
diff --git a/Cargo.toml b/Cargo.toml
index 23d063e449..d82d848c6e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -58,6 +58,8 @@ tinystoragedrivers-core = { path = "vendor/tinyagents/vendor/tinystoragedrivers/
tinystoragedrivers-sqlite = { path = "vendor/tinyagents/vendor/tinystoragedrivers/crates/tinystoragedrivers-sqlite" }
[patch."https://github.com/tinyhumansai/tinyinference"]
+# tinymemes depends on the Jev client by git; resolve it to the vendored copy.
+tinyinference-decisions = { path = "vendor/tinyagents/vendor/tinyinference/crates/tinyinference-decisions" }
tinyinference-core = { path = "vendor/tinyagents/vendor/tinyinference/crates/tinyinference-core" }
tinyinference-embeddings = { path = "vendor/tinyagents/vendor/tinyinference/crates/tinyinference-embeddings" }
tinyinference-llm = { path = "vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm" }
diff --git a/app/src/components/assistant-ui/markdown-text.tsx b/app/src/components/assistant-ui/markdown-text.tsx
index 19dfe1c9c8..530ff707f5 100644
--- a/app/src/components/assistant-ui/markdown-text.tsx
+++ b/app/src/components/assistant-ui/markdown-text.tsx
@@ -28,6 +28,7 @@ import remarkMath from 'remark-math';
import { hasLatexContent, normalizeLatexDelimiters } from '../../utils/latex';
import { extractLanguage, extractTextContent } from '../markdown/CodeBlock';
+import { MarkdownImage } from '../markdown/MarkdownImage';
import { CitationMarker, type CitationSource } from './elements/inline-citation';
/**
@@ -333,6 +334,7 @@ const defaultComponents = memoizeMarkdownComponents({
{...props}
/>
),
+ img: MarkdownImage,
hr: ({ className, ...props }) => (
<hr className={cn('aui-md-hr border-muted-foreground/20 my-3', className)} {...props} />
),
diff --git a/app/src/components/markdown/MarkdownImage.test.tsx b/app/src/components/markdown/MarkdownImage.test.tsx
new file mode 100644
index 0000000000..e10659f913
--- /dev/null
+++ b/app/src/components/markdown/MarkdownImage.test.tsx
@@ -0,0 +1,15 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { MarkdownImage } from './MarkdownImage';
+
+describe('MarkdownImage', () => {
+ it('renders a capped, lazy, no-referrer image', () => {
+ render(<MarkdownImage src="https://i.imgflip.com/82yaur.png" alt="Moye Moye" />);
+ const img = screen.getByAltText('Moye Moye');
+ expect(img).toHaveAttribute('src', 'https://i.imgflip.com/82yaur.png');
+ expect(img).toHaveAttribute('loading', 'lazy');
+ expect(img).toHaveAttribute('referrerpolicy', 'no-referrer');
+ expect(img.className).toContain('max-h-72');
+ });
+});
diff --git a/app/src/components/markdown/MarkdownImage.tsx b/app/src/components/markdown/MarkdownImage.tsx
new file mode 100644
index 0000000000..9561179032
--- /dev/null
+++ b/app/src/components/markdown/MarkdownImage.tsx
@@ -0,0 +1,22 @@
+import type { ComponentPropsWithoutRef } from 'react';
+
+/**
+ * Inline images in chat markdown (e.g. meme GIFs added to a reply). Capped in
+ * height so a tall template cannot take over the thread, lazy-loaded, and
+ * fetched without a referrer so third-party hosts do not learn which chat or
+ * page displayed them.
+ */
+export function MarkdownImage({ className, alt, ...props }: ComponentPropsWithoutRef<'img'>) {
+ return (
+ <img
+ {...props}
+ alt={alt ?? ''}
+ loading="lazy"
+ decoding="async"
+ referrerPolicy="no-referrer"
+ className={['my-2 block h-auto max-h-72 max-w-full rounded-lg object-contain', className]
+ .filter(Boolean)
+ .join(' ')}
+ />
+ );
+}
diff --git a/app/src/features/conversations/components/AgentMessageBubble.tsx b/app/src/features/conversations/components/AgentMessageBubble.tsx
index 93e0b8b2cd..3ca20c2972 100644
--- a/app/src/features/conversations/components/AgentMessageBubble.tsx
+++ b/app/src/features/conversations/components/AgentMessageBubble.tsx
@@ -6,6 +6,7 @@ import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import { createCodeBlockPre } from '../../../components/markdown/CodeBlock';
+import { MarkdownImage } from '../../../components/markdown/MarkdownImage';
import { hasLatexContent, normalizeLatexDelimiters } from '../../../utils/latex';
import { openUrl } from '../../../utils/openUrl';
import { openWorkspacePath } from '../../../utils/tauriCommands/workspacePaths';
@@ -65,7 +66,7 @@ export function BubbleMarkdown({
// Memoize the `pre` override so it stays reference-stable across re-renders
// that don't change tone (avoids remounting code blocks on every keystroke).
const markdownComponents = useMemo(
- () => ({ a: MarkdownAnchor, pre: createCodeBlockPre(tone) }),
+ () => ({ a: MarkdownAnchor, img: MarkdownImage, pre: createCodeBlockPre(tone) }),
[tone]
);
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 5cc6c825d1..3530800537 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -353,6 +353,9 @@ tokio = { version = "1", features = ["full"] }
once_cell = "1.19"
parking_lot = "0.12"
log = "0.4"
+# Final-reply slang + meme remix (runtime flag OPENHUMAN_TINYMEMES, off by
+# default). Local path until the tinymemes repo is published and vendored.
+tinymemes = { path = "../../../tinymemes" }
libc = "0.2"
nu-ansi-term = "0.50"
base64 = "0.22"
diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rs
index 2570dd4289..b35a3a3fd4 100644
--- a/crates/openhuman-core/src/lib.rs
+++ b/crates/openhuman-core/src/lib.rs
@@ -83,6 +83,7 @@ pub mod storage;
#[cfg(feature = "e2e-test-support")]
pub mod test_support;
pub mod threads;
+pub mod tinymemes;
pub mod tools;
pub mod user_agents;
pub mod util;
diff --git a/crates/openhuman-core/src/tinymemes/arm.rs b/crates/openhuman-core/src/tinymemes/arm.rs
new file mode 100644
index 0000000000..55765d72a9
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/arm.rs
@@ -0,0 +1,96 @@
+//! Which turns get remixed: the `OPENHUMAN_TINYMEMES` flag and its A/B split.
+//!
+//! | value | behaviour |
+//! | --- | --- |
+//! | unset, `off`, `0`, `false` | disabled; no tinymemes work at all |
+//! | `on`, `1`, `true` | every thread is in the treatment arm |
+//! | `ab` | 50% of threads are treatment, the rest control |
+//! | `ab:NN` | NN% of threads are treatment |
+//!
+//! Assignment is by a stable hash of the thread id, so a thread keeps its arm
+//! for its whole life and across restarts. The flag is read on every turn, so
+//! it can change without a restart.
+
+pub(crate) const FLAG_ENV: &str = "OPENHUMAN_TINYMEMES";
+
+/// Parsed flag value.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Mode {
+ Off,
+ On,
+ Ab { percent: u8 },
+}
+
+/// The arm a thread is in.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Arm {
+ /// Feature off: nothing runs and nothing is logged per turn.
+ Disabled,
+ /// In an experiment, not remixed. Logged for the throughput comparison.
+ Control,
+ /// Remixed.
+ Treatment,
+}
+
+impl Arm {
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ Arm::Disabled => "disabled",
+ Arm::Control => "control",
+ Arm::Treatment => "treatment",
+ }
+ }
+}
+
+pub(crate) fn mode_from(value: Option<&str>) -> Mode {
+ let Some(raw) = value.map(|v| v.trim().to_ascii_lowercase()) else {
+ return Mode::Off;
+ };
+ match raw.as_str() {
+ "" | "off" | "0" | "false" | "no" => Mode::Off,
+ "on" | "1" | "true" | "yes" => Mode::On,
+ "ab" => Mode::Ab { percent: 50 },
+ other => match other.strip_prefix("ab:").and_then(|p| p.parse::<u8>().ok()) {
+ Some(percent) => Mode::Ab {
+ percent: percent.min(100),
+ },
+ None => {
+ log::warn!("[tinymemes] unrecognised {FLAG_ENV} value; treating as off");
+ Mode::Off
+ }
+ },
+ }
+}
+
+pub(crate) fn mode() -> Mode {
+ mode_from(std::env::var(FLAG_ENV).ok().as_deref())
+}
+
+/// Stable 0..100 bucket for a thread (FNV-1a, so it does not change between
+/// builds or platforms the way `DefaultHasher` may).
+pub(crate) fn bucket(thread_id: &str) -> u8 {
+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
+ for byte in thread_id.as_bytes() {
+ hash ^= u64::from(*byte);
+ hash = hash.wrapping_mul(0x0100_0000_01b3);
+ }
+ (hash % 100) as u8
+}
+
+pub(crate) fn assign(mode: Mode, thread_id: &str) -> Arm {
+ match mode {
+ Mode::Off => Arm::Disabled,
+ Mode::On => Arm::Treatment,
+ Mode::Ab { percent } => {
+ if bucket(thread_id) < percent {
+ Arm::Treatment
+ } else {
+ Arm::Control
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "arm_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/tinymemes/arm_tests.rs b/crates/openhuman-core/src/tinymemes/arm_tests.rs
new file mode 100644
index 0000000000..51da0d392f
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/arm_tests.rs
@@ -0,0 +1,41 @@
+use super::*;
+
+#[test]
+fn flag_values_parse() {
+ assert_eq!(mode_from(None), Mode::Off);
+ assert_eq!(mode_from(Some("off")), Mode::Off);
+ assert_eq!(mode_from(Some(" ON ")), Mode::On);
+ assert_eq!(mode_from(Some("1")), Mode::On);
+ assert_eq!(mode_from(Some("ab")), Mode::Ab { percent: 50 });
+ assert_eq!(mode_from(Some("ab:20")), Mode::Ab { percent: 20 });
+ assert_eq!(mode_from(Some("ab:300")), Mode::Off);
+ assert_eq!(mode_from(Some("ab:250")), Mode::Ab { percent: 100 });
+ assert_eq!(mode_from(Some("ab:100")), Mode::Ab { percent: 100 });
+ assert_eq!(mode_from(Some("sometimes")), Mode::Off);
+}
+
+#[test]
+fn assignment_is_stable_and_respects_the_split() {
+ assert_eq!(assign(Mode::Off, "t"), Arm::Disabled);
+ assert_eq!(assign(Mode::On, "t"), Arm::Treatment);
+ assert_eq!(assign(Mode::Ab { percent: 0 }, "t"), Arm::Control);
+ assert_eq!(assign(Mode::Ab { percent: 100 }, "t"), Arm::Treatment);
+
+ let a = assign(Mode::Ab { percent: 50 }, "thread-abc");
+ for _ in 0..10 {
+ assert_eq!(assign(Mode::Ab { percent: 50 }, "thread-abc"), a);
+ }
+
+ let treated = (0..2000)
+ .filter(|i| assign(Mode::Ab { percent: 30 }, &format!("thread-{i}")) == Arm::Treatment)
+ .count();
+ assert!((450..750).contains(&treated), "treated={treated}");
+}
+
+#[test]
+fn bucket_is_fixed_across_builds() {
+ // FNV-1a is specified, so this value must never change; a change would
+ // silently move live threads between arms.
+ assert_eq!(bucket("thread-abc"), bucket("thread-abc"));
+ assert_eq!(bucket(""), (0xcbf2_9ce4_8422_2325_u64 % 100) as u8);
+}
diff --git a/crates/openhuman-core/src/tinymemes/host.rs b/crates/openhuman-core/src/tinymemes/host.rs
new file mode 100644
index 0000000000..12991c4eee
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/host.rs
@@ -0,0 +1,155 @@
+//! One tinymemes engine per workspace, plus the state it keeps on disk under
+//! `<workspace>/tinymemes/`:
+//!
+//! - `slang-index.json`: the slang index, which grows from web research.
+//! - `remixed.json`: ids of thread messages that were delivered remixed, so the
+//! next reading can tell Jev which assistant turns carry the bot's own style.
+
+use std::collections::{HashMap, VecDeque};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, LazyLock, Mutex};
+
+use tinymemes::{IndexPolicy, MemeEngine, SlangIndex, Turn};
+
+use crate::threads::store::ConversationMessage;
+
+const DIR: &str = "tinymemes";
+const INDEX_FILE: &str = "slang-index.json";
+const REMIXED_FILE: &str = "remixed.json";
+/// Remixed-message ids remembered per workspace (oldest dropped first).
+const REMIXED_CAP: usize = 4000;
+
+pub(crate) const MODEL_ENV: &str = "OPENHUMAN_TINYMEMES_MODEL";
+pub(crate) const KEY_ENV: &str = "OPENHUMAN_TINYMEMES_OPENROUTER_KEY";
+const DEFAULT_MODEL: &str = "deepseek/deepseek-v4-flash";
+
+pub(crate) struct Host {
+ pub(crate) engine: MemeEngine,
+ dir: PathBuf,
+ remixed: Mutex<VecDeque<String>>,
+}
+
+static HOSTS: LazyLock<Mutex<HashMap<PathBuf, Arc<Host>>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+/// The engine for a workspace, built on first use. `None` if it cannot be
+/// built (logged once per attempt; the turn then goes out unchanged).
+pub(crate) fn host_for(workspace_dir: &Path) -> Option<Arc<Host>> {
+ let mut hosts = HOSTS.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(host) = hosts.get(workspace_dir) {
+ return Some(host.clone());
+ }
+ let dir = workspace_dir.join(DIR);
+ if let Err(e) = std::fs::create_dir_all(&dir) {
+ log::warn!("[tinymemes] cannot create state dir: {e}");
+ return None;
+ }
+ let index = match std::fs::read_to_string(dir.join(INDEX_FILE)) {
+ Ok(json) => SlangIndex::from_json(&json, IndexPolicy::default()).unwrap_or_else(|e| {
+ log::warn!("[tinymemes] slang index unreadable, starting fresh: {e}");
+ SlangIndex::new(IndexPolicy::default())
+ }),
+ Err(_) => SlangIndex::new(IndexPolicy::default()),
+ };
+ let remixed: VecDeque<String> = std::fs::read_to_string(dir.join(REMIXED_FILE))
+ .ok()
+ .and_then(|json| serde_json::from_str(&json).ok())
+ .unwrap_or_default();
+
+ let key = std::env::var(KEY_ENV)
+ .ok()
+ .filter(|k| !k.trim().is_empty())
+ .unwrap_or_else(|| super::key::OPENROUTER_KEY.to_owned());
+ let model = std::env::var(MODEL_ENV).unwrap_or_else(|_| DEFAULT_MODEL.to_owned());
+ let engine = match MemeEngine::openrouter(&key, &model) {
+ Ok(builder) => builder
+ .slang_index(Arc::new(index))
+ // Research runs in the background after delivery, never on the
+ // reply's critical path.
+ .learn_inline(None)
+ .build(),
+ Err(e) => {
+ log::warn!("[tinymemes] engine build failed: {e}");
+ return None;
+ }
+ };
+ log::info!(
+ "[tinymemes] engine ready model={model} slang_terms={}",
+ engine.slang_index().len("IN")
+ );
+ let host = Arc::new(Host {
+ engine,
+ dir,
+ remixed: Mutex::new(remixed),
+ });
+ hosts.insert(workspace_dir.to_path_buf(), host.clone());
+ Some(host)
+}
+
+impl Host {
+ pub(crate) fn is_remixed(&self, message_id: &str) -> bool {
+ self.remixed
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .iter()
+ .any(|id| id == message_id)
+ }
+
+ pub(crate) fn mark_remixed(&self, message_id: String) {
+ let snapshot = {
+ let mut ids = self.remixed.lock().unwrap_or_else(|e| e.into_inner());
+ ids.push_back(message_id);
+ while ids.len() > REMIXED_CAP {
+ ids.pop_front();
+ }
+ serde_json::to_string(&*ids).unwrap_or_default()
+ };
+ if let Err(e) = std::fs::write(self.dir.join(REMIXED_FILE), snapshot) {
+ log::warn!("[tinymemes] cannot save remixed ids: {e}");
+ }
+ }
+
+ pub(crate) fn save_index(&self) {
+ let json = self.engine.slang_index().to_json();
+ if let Err(e) = std::fs::write(self.dir.join(INDEX_FILE), json) {
+ log::warn!("[tinymemes] cannot save slang index: {e}");
+ }
+ }
+}
+
+/// The thread as the user saw it, oldest first: delivered replies (remixed or
+/// not) and the user's messages. `current_user_message` is appended when the
+/// store does not have it yet.
+pub(crate) fn history_turns(
+ messages: &[ConversationMessage],
+ current_user_message: &str,
+ is_remixed: impl Fn(&str) -> bool,
+) -> Vec<Turn> {
+ let mut turns: Vec<Turn> = messages
+ .iter()
+ .filter(|m| !m.content.trim().is_empty())
+ .filter_map(|m| match m.sender.as_str() {
+ "user" => Some(Turn::user(m.content.clone())),
+ "agent" | "assistant" => Some(if is_remixed(&m.id) {
+ Turn::remixed(m.content.clone())
+ } else {
+ Turn::assistant(m.content.clone())
+ }),
+ _ => None,
+ })
+ .collect();
+ let current = current_user_message.trim();
+ let already_there = turns
+ .iter()
+ .rev()
+ .find(|t| t.role == tinymemes::Role::User)
+ .is_some_and(|t| t.text.trim() == current);
+ if !current.is_empty() && !already_there {
+ turns.push(Turn::user(current.to_owned()));
+ }
+ turns
+}
+
+#[cfg(test)]
+#[path = "host_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/tinymemes/host_tests.rs b/crates/openhuman-core/src/tinymemes/host_tests.rs
new file mode 100644
index 0000000000..f82de0dff3
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/host_tests.rs
@@ -0,0 +1,35 @@
+use super::*;
+
+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(),
+ }
+}
+
+#[test]
+fn history_marks_remixed_replies_and_appends_the_pending_message() {
+ let messages = vec![
+ msg("u1", "user", "bhai build fail"),
+ msg("r1", "agent", "Arre yaar, moye moye"),
+ msg("r2", "agent", "Plain reply"),
+ msg("s1", "system", "ignored"),
+ msg("u2", "user", " "),
+ ];
+ let turns = history_turns(&messages, "phir se fail", |id| id == "r1");
+ assert_eq!(turns.len(), 4);
+ assert!(turns[1].remixed);
+ assert!(!turns[2].remixed);
+ assert_eq!(turns[3].text, "phir se fail");
+}
+
+#[test]
+fn pending_message_is_not_duplicated_when_already_stored() {
+ let messages = vec![msg("u1", "user", "hello there")];
+ let turns = history_turns(&messages, "hello there ", |_| false);
+ assert_eq!(turns.len(), 1);
+}
diff --git a/crates/openhuman-core/src/tinymemes/mod.rs b/crates/openhuman-core/src/tinymemes/mod.rs
new file mode 100644
index 0000000000..ac4c697254
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/mod.rs
@@ -0,0 +1,162 @@
+//! TinyMemes host adapter: remixes the orchestrator's final reply with
+//! region slang and memes when the chat can take it.
+//!
+//! - Gated by `OPENHUMAN_TINYMEMES` (off by default; see [`arm`] for `on` and
+//! the `ab` / `ab:NN` experiment split).
+//! - Runs after the turn, on `full_response` only. Sub-agent output never
+//! reaches it.
+//! - Reads the thread as the user saw it (earlier replies already remixed),
+//! not the agent's original transcript. The agent's own transcript keeps the
+//! original wording, so the orchestrator never sees its replies in slang.
+//! - Fails open: any error or timeout delivers the original reply.
+//! - Slang web research runs in the background after delivery, only when Jev
+//! judges the slang index short for the reply.
+//!
+//! Every turn in an experiment logs one grep-friendly `[tinymemes] turn` line
+//! (arm, turn time, remix time, rating, outcome) for the A/B comparison. No
+//! user content is logged.
+
+mod arm;
+mod host;
+mod key;
+
+use std::path::Path;
+use std::time::{Duration, Instant};
+
+pub(crate) use arm::Arm;
+
+const TIMEOUT_ENV: &str = "OPENHUMAN_TINYMEMES_TIMEOUT_MS";
+const DEFAULT_TIMEOUT: Duration = Duration::from_secs(20);
+
+/// 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(
+ workspace_dir: &Path,
+ thread_id: &str,
+ request_id: &str,
+ user_message: &str,
+ 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();
+ match arm {
+ Arm::Disabled => return None,
+ Arm::Control => {
+ log::info!(
+ "[tinymemes] turn arm=control bucket={bucket} request_id={request_id} \
+ turn_ms={turn_ms} remix_ms=0 outcome=not_remixed"
+ );
+ return None;
+ }
+ Arm::Treatment => {}
+ }
+
+ let started = Instant::now();
+ let Some(host) = host::host_for(workspace_dir) else {
+ log_outcome(
+ request_id,
+ bucket,
+ turn_ms,
+ started,
+ "engine_unavailable",
+ None,
+ );
+ return None;
+ };
+ let messages = crate::threads::store::get_messages(workspace_dir.to_path_buf(), thread_id)
+ .unwrap_or_else(|e| {
+ log::debug!("[tinymemes] thread history unavailable: {e}");
+ Vec::new()
+ });
+ let turns = host::history_turns(&messages, user_message, |id| host.is_remixed(id));
+
+ let budget = std::env::var(TIMEOUT_ENV)
+ .ok()
+ .and_then(|v| v.parse::<u64>().ok())
+ .map(Duration::from_millis)
+ .unwrap_or(DEFAULT_TIMEOUT);
+ 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);
+ return None;
+ }
+ };
+
+ // Slang research, off the critical path, only for a reply that was
+ // remixed and only when Jev judged the index short of slang for it.
+ if let (Some(reading), Some(_)) = (&outcome.reading, &outcome.remix) {
+ let policy = host.engine.slang_index().policy();
+ if reading.wants_more_slang(policy.search_below) {
+ let host = host.clone();
+ let intent = reading.reply_intent;
+ let reply = reply.to_owned();
+ let request_id = request_id.to_owned();
+ tokio::spawn(async move {
+ match host.engine.learn_for_reply(intent, &reply).await {
+ Ok(Some(r)) => log::info!(
+ "[tinymemes] slang research request_id={request_id} added={} \
+ corroborated={} rejected={} failed_jev={}",
+ r.added,
+ r.corroborated,
+ r.rejected,
+ r.failed_verification
+ ),
+ Ok(None) => {
+ log::debug!("[tinymemes] slang research skipped (repeat or budget)")
+ }
+ Err(e) => log::warn!("[tinymemes] slang research failed: {e}"),
+ }
+ host.save_index();
+ });
+ }
+ }
+
+ let remixed = outcome.remix.is_some() && outcome.reply.trim() != reply.trim();
+ let result = if remixed {
+ host.mark_remixed(crate::threads::store::run_reply_message_id(request_id));
+ host.save_index();
+ "remixed"
+ } else if outcome.skipped.is_some() && outcome.rating.is_none() {
+ "error"
+ } else {
+ "unchanged"
+ };
+ log_outcome(request_id, bucket, turn_ms, started, result, Some(&outcome));
+ remixed.then_some(outcome.reply)
+}
+
+fn log_outcome(
+ request_id: &str,
+ bucket: u8,
+ turn_ms: u128,
+ started: Instant,
+ result: &str,
+ outcome: Option<&tinymemes::Outcome>,
+) {
+ let remix_ms = started.elapsed().as_millis();
+ 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!(
+ "[tinymemes] turn arm=treatment bucket={bucket} request_id={request_id} turn_ms={turn_ms} \
+ remix_ms={remix_ms} outcome={result} score={} tier={} memes={} rewrite_kept={} \
+ slang_enough={} wants_search={}",
+ rating.map_or(-1, |r| i32::from(r.score)),
+ rating.map_or("none", |r| match r.tier {
+ tinymemes::Tier::Off => "off",
+ tinymemes::Tier::Light => "light",
+ tinymemes::Tier::Spicy => "spicy",
+ tinymemes::Tier::Unhinged => "unhinged",
+ }),
+ remix.map_or(0, |r| r.memes.len()),
+ remix.is_none_or(|r| r.rewrite_kept),
+ reading
+ .and_then(|r| r.slang_enough)
+ .map_or_else(|| "none".to_owned(), |p| format!("{p:.2}")),
+ reading.is_some_and(|r| r.wants_more_slang(0.5)),
+ );
+}
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 4ad4bab6a3..0244683327 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -174,6 +174,7 @@ pub(crate) async fn run_chat_task(
// wrappers below hold a pointer rather than inlining the whole future into
// this already-large `run_chat_task` frame (which otherwise overflows the
// default test-thread stack — see the channels web-turn coverage tests).
+ let turn_started = std::time::Instant::now();
let turn = Box::pin(agent.run_single_with_origin(message, Some(origin)));
let mut result = match turn.await {
Ok(response) => {
@@ -288,6 +289,27 @@ pub(crate) async fn run_chat_task(
}
}
+ // TinyMemes: remix the final reply (slang + memes) when the flag puts this
+ // thread in the treatment arm. Runs after reply speech so TTS reads the
+ // original wording, and skips the budget-exhausted placeholder. Fails open.
+ 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(
+ &task_result.workspace_dir,
+ thread_id,
+ request_id,
+ message,
+ &task_result.full_response,
+ turn_started.elapsed(),
+ )
+ .await
+ {
+ task_result.full_response = remixed;
+ }
+ }
+ }
+
agent.set_on_progress(None);
// The caller publishes the terminal `chat_done`/`chat_error` as soon as