Skip to content

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

fix(web-chat): send the reply-language directive with every turn

M3gA-Mind8ff7dadfcc85
diff --git a/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs b/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs
index 808118e3fe..126b11fb9e 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs
@@ -555,4 +555,25 @@ impl OpenHumanSessionHost {
.unwrap_or_else(|poisoned| poisoned.into_inner())
.pending_turn_overrides = overrides;
}
+
+ /// Set the reply-language instruction every following user message
+ /// carries (next to the `Current Date & Time` line), or clear it with
+ /// `None`. Sent per message rather than baked into the system prompt, so
+ /// the cached prompt prefix stays byte-stable and a changed interface
+ /// locale applies from the next turn.
+ pub fn set_reply_language_directive(&mut self, directive: Option<String>) {
+ self.runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .reply_language_directive = directive;
+ }
+
+ /// The reply-language instruction the next user message will carry.
+ pub fn reply_language_directive(&self) -> Option<String> {
+ self.runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .reply_language_directive
+ .clone()
+ }
}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
index 02ff2e98c8..e283c5cc0e 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
@@ -638,3 +638,80 @@ async fn artifact_store_stays_in_the_workspace_without_a_descriptor() {
crate::security::policy::tool_result_artifacts_dir(workspace.path())
);
}
+
+/// The reply-language instruction reaches the MODEL, on the user message next
+/// to the clock line, and clearing it removes it from the next turn. Before
+/// this, the web channel computed the directive, logged "injecting", and
+/// dropped it: no request ever carried it.
+#[test]
+fn reply_language_directive_rides_each_user_message_until_cleared() {
+ std::thread::Builder::new()
+ .stack_size(crate::core::runtime::AGENT_WORKER_STACK_BYTES)
+ .spawn(|| {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("test runtime")
+ .block_on(reply_language_directive_rides_each_user_message_until_cleared_body());
+ })
+ .expect("test thread")
+ .join()
+ .expect("test thread panicked");
+}
+
+async fn reply_language_directive_rides_each_user_message_until_cleared_body() {
+ const DIRECTIVE: &str = "User language: respond in Spanish (test directive).";
+ let root = tempfile::tempdir().expect("tempdir");
+ let model = Arc::new(tinyagents_harness::testkit::ScriptedModel::new(vec![
+ tinyinference_llm::model::ModelResponse::assistant("hola"),
+ tinyinference_llm::model::ModelResponse::assistant("hello"),
+ ]));
+ let mut host = crate::agent::SessionHostBuilder::new()
+ .chat_model(model.clone() as Arc<dyn tinyinference_llm::model::ChatModel<()>>)
+ .tools(Vec::new())
+ .workspace_dir(root.path().join("workspace"))
+ .action_dir(root.path().to_path_buf())
+ .tool_dispatcher(Box::new(tinytools_agent::dialect::XmlDialect))
+ .build()
+ .expect("session build");
+ host.set_thread_id(Some("thread-reply-language"));
+ let last_user_text = |request: &tinyinference_llm::model::ModelRequest| {
+ request
+ .messages
+ .iter()
+ .rev()
+ .find(|m| matches!(m, Message::User(_)))
+ .map(|m| m.text())
+ .expect("a user message reached the model")
+ };
+
+ host.set_reply_language_directive(Some(DIRECTIVE.to_string()));
+ assert_eq!(host.turn("¿qué tal?").await.unwrap(), "hola");
+ host.set_reply_language_directive(None);
+ assert_eq!(host.turn("and now?").await.unwrap(), "hello");
+
+ let requests = model.requests();
+ assert_eq!(requests.len(), 2, "one model call per turn");
+ let first = last_user_text(&requests[0]);
+ assert!(
+ first.contains("Current Date & Time:"),
+ "fixture: the clock line is there: {first}"
+ );
+ assert!(
+ first.contains(DIRECTIVE),
+ "the directive must reach the model: {first}"
+ );
+ assert!(
+ first.find(DIRECTIVE) < first.find("¿qué tal?"),
+ "the directive leads the user's own words: {first}"
+ );
+ let second = last_user_text(&requests[1]);
+ assert!(
+ second.contains("and now?"),
+ "fixture: the second turn's text: {second}"
+ );
+ assert!(
+ !second.contains(DIRECTIVE),
+ "a cleared directive is gone next turn: {second}"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index 53d95b4085..4c8575c3fe 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -54,6 +54,10 @@ pub(super) struct OpenHumanSessionState {
required_output: Option<tinyagents_harness::config::RequiredOutput>,
pub(crate) pending_turn_overrides: super::types::TurnOverrides,
pub(super) active_turn_overrides: super::types::TurnOverrides,
+ /// The reply-language instruction for the user's interface locale, sent
+ /// on every user message until the host changes it. Not part of the
+ /// cached system prompt, so a locale change takes effect on the next turn.
+ pub(super) reply_language_directive: Option<String>,
prelude: Option<OpenHumanTurnPrelude>,
}
@@ -530,6 +534,7 @@ impl OpenHumanTurnPrelude {
&self,
original_user_message: &str,
overrides: &super::types::TurnOverrides,
+ reply_language_directive: Option<&str>,
run_context: &mut OpenHumanRunContext,
) -> String {
let mut context = String::new();
@@ -633,10 +638,11 @@ impl OpenHumanTurnPrelude {
self.tool_dispatcher.tool_call_format(),
)
.harness_dispatcher();
- format!(
- "{}\n\n{enriched}",
- crate::agent::prompts::current_datetime_line()
- )
+ let now = crate::agent::prompts::current_datetime_line();
+ match reply_language_directive {
+ Some(directive) => format!("{now}\n{directive}\n\n{enriched}"),
+ None => format!("{now}\n\n{enriched}"),
+ }
}
fn parent_context(&self) -> crate::agent::harness::ParentExecutionContext {
@@ -1130,18 +1136,22 @@ impl OpenHumanSessionHost {
.context_window = context_window;
let original_user_message = user_text_with_markers(&request.input);
prelude.begin_user_effects(request);
- let overrides = std::mem::take(
- &mut state
+ let (overrides, reply_language_directive) = {
+ let mut state = state
.lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .active_turn_overrides,
- );
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ (
+ std::mem::take(&mut state.active_turn_overrides),
+ state.reply_language_directive.clone(),
+ )
+ };
let current_input =
view.history.last().filter(|last| **last == request.input);
let (enriched, memory_turn) = futures::join!(
prelude.enrich_request(
&original_user_message,
&overrides,
+ reply_language_directive.as_deref(),
&mut options.run_context.data,
),
// Boxed: the hook's future (config load, engine
diff --git a/crates/openhuman-core/src/web_chat/session.rs b/crates/openhuman-core/src/web_chat/session.rs
index f47f1bb969..be242edb8c 100644
--- a/crates/openhuman-core/src/web_chat/session.rs
+++ b/crates/openhuman-core/src/web_chat/session.rs
@@ -138,7 +138,6 @@ pub(super) fn build_session_agent(
target_agent_id: &str,
model_override: Option<String>,
temperature: Option<f64>,
- locale: Option<&str>,
) -> Result<OpenHumanSessionHost, String> {
let effective = effective_session_config(config, model_override.as_deref(), temperature);
let provider_role = provider_role_for_model_override(effective.default_model.as_deref());
@@ -151,17 +150,6 @@ pub(super) fn build_session_agent(
thread_id
);
- let locale_directive = locale.and_then(locale_reply_directive);
- if let Some(s) = locale_directive.as_deref() {
- log::info!(
- "[web-channel] injecting locale directive client={} thread={} locale={} directive={:?}",
- client_id,
- thread_id,
- locale.unwrap_or(""),
- s
- );
- }
-
let agent_result = OpenHumanSessionHost::from_config_for_agent(&effective, target_agent_id);
agent_result
@@ -442,7 +430,6 @@ pub(crate) async fn checkout_session_agent(
&target_agent_id,
model_override,
temperature,
- locale,
)?,
fingerprint,
)
@@ -455,12 +442,26 @@ pub(crate) async fn checkout_session_agent(
&target_agent_id,
model_override,
temperature,
- locale,
)?,
fingerprint,
),
};
+ // Every checkout re-arms the reply language from this turn's locale: a
+ // reused agent may have been built under a different one, and `None`
+ // (English, or no locale sent) must clear a stale instruction.
+ let mut agent = agent;
+ let directive = locale.and_then(locale_reply_directive);
+ if directive.is_some() {
+ log::info!(
+ "[web-channel] reply language directive armed client={} thread={} locale={}",
+ client_id,
+ thread_id,
+ locale.unwrap_or("")
+ );
+ }
+ agent.set_reply_language_directive(directive);
+
// Cold-boot resume needs no seeding here. `set_thread_id` binds the
// session's durable identity and the turn resumes by it, reading the one
// transcript this conversation has ever had — tool calls, tool results and
diff --git a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs b/crates/openhuman-core/src/web_chat/session_checkout_tests.rs
index e94618d434..7243a43064 100644
--- a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs
+++ b/crates/openhuman-core/src/web_chat/session_checkout_tests.rs
@@ -546,3 +546,63 @@ fn chat_agent_id_selects_the_web_chat_agent_and_defaults_to_the_orchestrator() {
"an unknown optional setting must not take web chat down"
);
}
+
+/// Every checkout arms the reply language from THIS turn's locale, on a fresh
+/// build and on a reused cached agent alike, and a locale with no directive
+/// (English) clears a stale one. Before the fix the directive was computed
+/// only on a fresh build, logged, and dropped.
+#[tokio::test]
+async fn each_checkout_arms_the_reply_language_from_its_own_locale() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = test_config(&tmp);
+ let thread_id = unique_thread("locale");
+ let checkout = |locale: Option<&'static str>| {
+ let config = config.clone();
+ let thread_id = thread_id.clone();
+ async move {
+ checkout_session_agent(
+ &config,
+ "client-1",
+ &thread_id,
+ None,
+ None,
+ locale,
+ CheckoutPolicy::Exact,
+ )
+ .await
+ .unwrap()
+ }
+ };
+
+ // Fresh build, Spanish UI.
+ let CheckedOutSession { agent, fingerprint } = checkout(Some("es")).await;
+ let directive = agent
+ .reply_language_directive()
+ .expect("es arms a directive");
+ assert!(directive.contains("Spanish"), "{directive}");
+ checkin_session_agent(&thread_id, agent, fingerprint).await;
+
+ // Reused cached agent, the user switched the UI to English: cleared.
+ assert!(
+ THREAD_SESSIONS
+ .lock()
+ .await
+ .contains_key(&key_for(&thread_id)),
+ "fixture: the next checkout must reuse the cached agent"
+ );
+ let CheckedOutSession { agent, fingerprint } = checkout(Some("en")).await;
+ assert_eq!(agent.reply_language_directive(), None);
+ checkin_session_agent(&thread_id, agent, fingerprint).await;
+
+ // Reused again, now Hindi: re-armed with the new language.
+ assert!(THREAD_SESSIONS
+ .lock()
+ .await
+ .contains_key(&key_for(&thread_id)));
+ let CheckedOutSession { agent, .. } = checkout(Some("hi")).await;
+ let directive = agent
+ .reply_language_directive()
+ .expect("hi arms a directive");
+ assert!(directive.contains("Hindi"), "{directive}");
+ evict(&thread_id).await;
+}