Skip to content

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

fix(web-chat): supersede an earlier reply language when switching to English

M3gA-Mindc16047fd90c8
diff --git a/crates/openhuman-core/src/web_chat/session.rs b/crates/openhuman-core/src/web_chat/session.rs
index 17d7103518..03f1f3c653 100644
--- a/crates/openhuman-core/src/web_chat/session.rs
+++ b/crates/openhuman-core/src/web_chat/session.rs
@@ -194,11 +194,16 @@ pub(crate) fn locale_reply_directive(locale: &str) -> Option<String> {
"zh-CN" | "zh" => "Simplified Chinese",
_ => return None,
};
- Some(format!(
+ Some(reply_directive_for(language))
+}
+
+/// The reply-language instruction for `language`.
+fn reply_directive_for(language: &str) -> String {
+ format!(
"User language: the user's interface is set to {language}. \
Respond in {language} unless the user explicitly asks for a different language. \
Keep proper nouns, code, and command names untranslated."
- ))
+ )
}
/// Byte offset of the first difference between two signature strings, or
@@ -456,7 +461,18 @@ pub(crate) async fn checkout_session_agent(
// 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);
+ let directive = match locale.and_then(locale_reply_directive) {
+ Some(directive) => Some(directive),
+ // Messages this session already sent carry another language's
+ // directive; an explicit English one supersedes them rather than
+ // leaving the last of them standing in the history.
+ None if locale.map(str::trim) == Some("en")
+ && agent.reply_language_directive().is_some() =>
+ {
+ Some(reply_directive_for("English"))
+ }
+ None => None,
+ };
if directive.is_some() {
log::info!(
"[web-channel] reply language directive armed client={} thread={} locale={}",
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 7243a43064..b3e7859ef1 100644
--- a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs
+++ b/crates/openhuman-core/src/web_chat/session_checkout_tests.rs
@@ -582,7 +582,8 @@ async fn each_checkout_arms_the_reply_language_from_its_own_locale() {
assert!(directive.contains("Spanish"), "{directive}");
checkin_session_agent(&thread_id, agent, fingerprint).await;
- // Reused cached agent, the user switched the UI to English: cleared.
+ // Reused cached agent, the user switched the UI to English: the Spanish
+ // directives already in the history are superseded explicitly.
assert!(
THREAD_SESSIONS
.lock()
@@ -591,7 +592,10 @@ async fn each_checkout_arms_the_reply_language_from_its_own_locale() {
"fixture: the next checkout must reuse the cached agent"
);
let CheckedOutSession { agent, fingerprint } = checkout(Some("en")).await;
- assert_eq!(agent.reply_language_directive(), None);
+ let directive = agent
+ .reply_language_directive()
+ .expect("switching to English supersedes the Spanish directive");
+ assert!(directive.contains("Respond in English"), "{directive}");
checkin_session_agent(&thread_id, agent, fingerprint).await;
// Reused again, now Hindi: re-armed with the new language.
@@ -606,3 +610,29 @@ async fn each_checkout_arms_the_reply_language_from_its_own_locale() {
assert!(directive.contains("Hindi"), "{directive}");
evict(&thread_id).await;
}
+
+/// A session that has only ever been English gets no directive: replies keep
+/// following the language the user writes in. A turn that sends no locale (a
+/// host-authored one) carries none either.
+#[tokio::test]
+async fn an_english_only_session_and_a_locale_less_turn_carry_no_directive() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = test_config(&tmp);
+ let thread_id = unique_thread("english");
+ for locale in [Some("en"), None] {
+ let CheckedOutSession { agent, fingerprint } = checkout_session_agent(
+ &config,
+ "client-1",
+ &thread_id,
+ None,
+ None,
+ locale,
+ CheckoutPolicy::Exact,
+ )
+ .await
+ .unwrap();
+ assert_eq!(agent.reply_language_directive(), None, "{locale:?}");
+ checkin_session_agent(&thread_id, agent, fingerprint).await;
+ }
+ evict(&thread_id).await;
+}
diff --git a/tests/in_process/agent_prompt_comprehension_e2e.rs b/tests/in_process/agent_prompt_comprehension_e2e.rs
index 09f14277b5..6c22306564 100644
--- a/tests/in_process/agent_prompt_comprehension_e2e.rs
+++ b/tests/in_process/agent_prompt_comprehension_e2e.rs
@@ -1059,3 +1059,70 @@ fn orchestrator_prompt_names_only_discoverable_delegates() {
);
});
}
+
+/// The last user message of an OpenAI-shaped chat request, as text.
+fn last_user_text(request: &Value) -> String {
+ request
+ .pointer("/body/messages")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .rev()
+ .find(|m| m["role"] == "user")
+ .map(|m| match &m["content"] {
+ Value::String(text) => text.clone(),
+ other => other.to_string(),
+ })
+ .unwrap_or_default()
+}
+
+/// The web chat's interface locale reaches the model: a Spanish turn's user
+/// message carries the Spanish reply instruction, and after the user switches
+/// the app to English the next turn carries an English one that supersedes it.
+/// Drives the real JSON-RPC chat path against a scripted upstream.
+#[test]
+fn the_interface_locale_reaches_the_model_on_every_turn() {
+ run_on_agent_stack("interface_locale_directive", || async {
+ let _lock = env_lock_async().await;
+ reset_script(vec![text_completion("Hola."), text_completion("Hello.")]);
+ let stack = boot_stack("").await;
+ let client_id = "locale-directive";
+ let (mut events, ready) =
+ spawn_sse_collector(format!("{}/events?client_id={client_id}", stack.rpc_base));
+ wait_for_sse_ready(ready).await;
+ for (id, (message, locale)) in [("hola", "es"), ("and now?", "en")].into_iter().enumerate() {
+ let resp = post_json_rpc(
+ &stack.rpc_base,
+ 20 + id as i64,
+ "openhuman.channel_web_chat",
+ json!({
+ "client_id": client_id,
+ "thread_id": "thread-locale",
+ "message": message,
+ "model_override": "e2e-mock-model",
+ "locale": locale,
+ }),
+ )
+ .await;
+ assert_no_jsonrpc_error(&resp, "channel_web_chat");
+ wait_for_terminal(&mut events).await;
+ }
+
+ let requests = captured().clone();
+ let turn = |words: &str| {
+ requests
+ .iter()
+ .map(last_user_text)
+ .find(|text| text.ends_with(words))
+ .unwrap_or_else(|| {
+ let seen: Vec<String> = requests.iter().map(last_user_text).collect();
+ panic!("no request whose user message is {words:?}: {seen:#?}")
+ })
+ };
+ let spanish = turn("hola");
+ assert!(spanish.contains("Respond in Spanish"), "{spanish}");
+ let english = turn("and now?");
+ assert!(english.contains("Respond in English"), "{english}");
+ assert!(!english.contains("Respond in Spanish"), "{english}");
+ });
+}