The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(web_chat): keep turn tables in the agent context's slots (#7032)
oxoxDev8f40b5baaf5d
diff --git a/crates/openhuman-core/src/web_chat/ops.rs b/crates/openhuman-core/src/web_chat/ops.rsindex b6567f3c0a..14858ca1e9 100644--- a/crates/openhuman-core/src/web_chat/ops.rs+++ b/crates/openhuman-core/src/web_chat/ops.rs@@ -28,11 +28,11 @@ pub use system_turn::{run_system_turn_on_thread, SESSION_CHECKOUT_FAILURE, SYSTE#[cfg(test)]pub use state::drain_queued_turns_for_test;+#[cfg(test)]+pub(crate) use state::in_flight;#[cfg(any(test, debug_assertions))]pub use state::parallel_in_flight_entries_for_test;-#[cfg(test)]-pub(crate) use state::IN_FLIGHT;-pub(super) use state::THREAD_SESSIONS;+pub(super) use state::thread_sessions;pub use state::{cancel_should_target, in_flight_entries_for_test, invalidate_thread_sessions};pub(crate) use state::{event_session_id_for, key_for};diff --git a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs b/crates/openhuman-core/src/web_chat/ops/channel_ops.rsindex 461fc79cca..c2db763fd8 100644--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs@@ -11,7 +11,7 @@ use super::super::event_bus::publish_web_channel_event;use super::super::types::ChatRequestMetadata;use super::parallel_turn::{cancel_parallel_turn_by_request_id, cancel_parallel_turns_for_thread};use super::start_chat::start_chat;-use super::state::{cancel_in_flight_gracefully, cancel_should_target, key_for, IN_FLIGHT};+use super::state::{cancel_in_flight_gracefully, cancel_should_target, in_flight, key_for};/// Cancel whatever turn is currently running on a thread (unscoped stop).///@@ -68,7 +68,7 @@ async fn cancel_chat_inner(let mut removed_request_id: Option<String> = None;{- let mut in_flight = IN_FLIGHT.lock().await;+ let mut in_flight = in_flight().lock_owned().await;// #4760: only tear down the primary turn when the cancel is unscoped OR// targets exactly the request that is running. A stale cancel for an// already-superseded request must be a no-op so the newer turn lives.@@ -241,7 +241,7 @@ fn queue_item_json(pub async fn channel_web_queue_status(thread_id: &str) -> Result<Outcome<Value>, String> {let map_key = key_for(thread_id);- let in_flight = IN_FLIGHT.lock().await;+ let in_flight = in_flight().lock_owned().await;if let Some(entry) = in_flight.get(&map_key) {let status = entry.run_queue.status().await;let items: Vec<Value> = entry@@ -297,7 +297,7 @@ pub async fn channel_web_queue_remove(return Err("item_id is required".to_string());}let map_key = key_for(thread_id);- let in_flight = IN_FLIGHT.lock().await;+ let in_flight = in_flight().lock_owned().await;let Some(entry) = in_flight.get(&map_key) else {return Ok(Outcome::single_log(json!({@@ -339,7 +339,7 @@ pub async fn channel_web_queue_remove(pub async fn channel_web_queue_clear(thread_id: &str) -> Result<Outcome<Value>, String> {let map_key = key_for(thread_id);- let in_flight = IN_FLIGHT.lock().await;+ let in_flight = in_flight().lock_owned().await;if let Some(entry) = in_flight.get(&map_key) {let dropped = entry.run_queue.clear().await;log::info!(diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rsindex 7cf6f74c11..7e8f2aa65c 100644--- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs+++ b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs@@ -14,7 +14,7 @@ use super::super::event_bus::publish_web_channel_event;use super::super::run_task::run_chat_task;use super::super::types::{ChatRequestMetadata, ParallelEntry};use super::super::web_errors::classify_inference_error;-use super::state::PARALLEL_IN_FLIGHT;+use super::state::parallel_in_flight;use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,};@@ -193,11 +193,14 @@ pub(crate) async fn spawn_parallel_turn(}}- PARALLEL_IN_FLIGHT.lock().await.remove(&request_id_task);+ parallel_in_flight()+ .lock_owned()+ .await+ .remove(&request_id_task);},));- PARALLEL_IN_FLIGHT.lock().await.insert(+ parallel_in_flight().lock_owned().await.insert(request_id,ParallelEntry {thread_id: thread_id.to_string(),@@ -212,7 +215,7 @@ pub(crate) async fn spawn_parallel_turn(/// tears down any concurrent forked turns, not just the primary turn.pub(crate) async fn cancel_parallel_turns_for_thread(thread_id: &str) -> Vec<String> {let mut cancelled = Vec::new();- let mut parallel = PARALLEL_IN_FLIGHT.lock().await;+ let mut parallel = parallel_in_flight().lock_owned().await;let request_ids: Vec<String> = parallel.iter().filter(|(_, entry)| entry.thread_id == thread_id)@@ -244,7 +247,7 @@ pub(crate) async fn cancel_parallel_turn_by_request_id(thread_id: &str,request_id: &str,) -> Vec<String> {- let mut parallel = PARALLEL_IN_FLIGHT.lock().await;+ let mut parallel = parallel_in_flight().lock_owned().await;let matches = parallel.get(request_id).map(|entry| entry.thread_id == thread_id)diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rsindex f5ce3088a8..bf221dd111 100644--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs@@ -20,7 +20,7 @@ use super::super::run_task::run_chat_task;use super::super::types::{ChatRequestMetadata, InFlightEntry, QueueMode};use super::super::web_errors::classify_inference_error;use super::parallel_turn::spawn_parallel_turn;-use super::state::{cancel_in_flight_gracefully, key_for, IN_FLIGHT};+use super::state::{cancel_in_flight_gracefully, in_flight, key_for};use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,};@@ -371,7 +371,7 @@ async fn start_chat_inner(// Non-interrupt modes: push into the running turn's queue and return.if !matches!(parsed_mode, QueueMode::Interrupt) {- let in_flight = IN_FLIGHT.lock().await;+ let in_flight = in_flight().lock_owned().await;if let Some(existing) = in_flight.get(&map_key) {let item_id = uuid::Uuid::new_v4().to_string();let text_preview = crate::agent::queued_turn::text_preview(&message);@@ -425,7 +425,7 @@ async fn start_chat_inner(}{- let mut in_flight = IN_FLIGHT.lock().await;+ let mut in_flight = in_flight().lock_owned().await;if let Some(existing) = in_flight.remove(&map_key) {let cancelled_id = cancel_in_flight_gracefully(existing);@@ -526,7 +526,7 @@ async fn start_chat_inner(// Release any in-flight slot we still own and stop. The// `request_id` guard below prevents clobbering a newer turn that// replaced us on the interrupt path.- let mut in_flight = IN_FLIGHT.lock().await;+ let mut in_flight = in_flight().lock_owned().await;if let Some(current) = in_flight.get(&map_key_task) {if current.request_id == request_id_task {in_flight.remove(&map_key_task);@@ -622,7 +622,7 @@ async fn start_chat_inner(// Drain followup messages queued during this turn.let followups = {- let mut in_flight = IN_FLIGHT.lock().await;+ let mut in_flight = in_flight().lock_owned().await;let followups = if let Some(current) = in_flight.get(&map_key_task) {if current.request_id == request_id_task {let fups = current.run_queue.drain(QueueLane::Followup).await;@@ -683,7 +683,7 @@ async fn start_chat_inner());{- let mut in_flight = IN_FLIGHT.lock().await;+ let mut in_flight = in_flight().lock_owned().await;in_flight.insert(map_key,InFlightEntry {diff --git a/crates/openhuman-core/src/web_chat/ops/state.rs b/crates/openhuman-core/src/web_chat/ops/state.rsindex 3f055a8e23..417021499a 100644--- a/crates/openhuman-core/src/web_chat/ops/state.rs+++ b/crates/openhuman-core/src/web_chat/ops/state.rs@@ -3,26 +3,35 @@//! and mutate them.use std::collections::HashMap;+use std::sync::Arc;use std::time::Duration;-use once_cell::sync::Lazy;use serde_json::json;use tokio::sync::Mutex;use super::super::types::{InFlightEntry, ParallelEntry, SessionEntry};-pub(crate) static THREAD_SESSIONS: Lazy<Mutex<HashMap<String, SessionEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+type ThreadSessions = Mutex<HashMap<String, SessionEntry>>;+type InFlight = Mutex<HashMap<String, InFlightEntry>>;+type ParallelInFlight = Mutex<HashMap<String, ParallelEntry>>;-pub(crate) static IN_FLIGHT: Lazy<Mutex<HashMap<String, InFlightEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+/// The current agent context's per-thread session cache.+pub(crate) fn thread_sessions() -> Arc<ThreadSessions> {+ crate::core::runtime::current_slot::<ThreadSessions>()+}++/// The current agent context's primary in-flight turns, keyed by thread.+pub(crate) fn in_flight() -> Arc<InFlight> {+ crate::core::runtime::current_slot::<InFlight>()+}/// Parallel (forked) turns, keyed by `request_id`. A separate lane from-/// `IN_FLIGHT` (which holds one primary, interrupt-able turn per thread) so any-/// number of concurrent `QueueMode::Parallel` turns can run on the same thread-/// without touching interrupt/steer/queue semantics. See `QueueMode::Parallel`.-pub(crate) static PARALLEL_IN_FLIGHT: Lazy<Mutex<HashMap<String, ParallelEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));+/// [`in_flight`] (which holds one primary, interrupt-able turn per thread) so+/// any number of concurrent `QueueMode::Parallel` turns can run on the same+/// thread without touching interrupt/steer/queue semantics.+pub(crate) fn parallel_in_flight() -> Arc<ParallelInFlight> {+ crate::core::runtime::current_slot::<ParallelInFlight>()+}pub(crate) fn key_for(thread_id: &str) -> String {thread_id.to_string()@@ -62,7 +71,7 @@ pub(crate) fn cancel_in_flight_gracefully(entry: InFlightEntry) -> String {}pub async fn invalidate_thread_sessions(thread_id: &str) {- let mut sessions = THREAD_SESSIONS.lock().await;+ let mut sessions = thread_sessions().lock_owned().await;let keys_to_remove: Vec<String> = sessions.keys().filter(|k| k.as_str() == thread_id || k.ends_with(&format!("::{thread_id}")))@@ -81,7 +90,7 @@ pub async fn invalidate_thread_sessions(thread_id: &str) {}pub async fn in_flight_entries_for_test() -> Vec<(String, String)> {- let guard = IN_FLIGHT.lock().await;+ let guard = in_flight().lock_owned().await;guard.iter().map(|(k, v)| (k.clone(), v.request_id.clone()))@@ -97,7 +106,7 @@ pub async fn drain_queued_turns_for_test(thread_id: &str,lane: tinyagents_harness::run_queue::QueueLane,) -> Vec<crate::agent::queued_turn::QueuedTurn> {- let guard = IN_FLIGHT.lock().await;+ let guard = in_flight().lock_owned().await;match guard.get(&key_for(thread_id)) {Some(entry) => entry.run_queue.drain(lane).await,None => Vec::new(),@@ -107,7 +116,7 @@ pub async fn drain_queued_turns_for_test(/// Test accessor: `(request_id, thread_id)` for every in-flight parallel turn.#[cfg(any(test, debug_assertions))]pub async fn parallel_in_flight_entries_for_test() -> Vec<(String, String)> {- let guard = PARALLEL_IN_FLIGHT.lock().await;+ let guard = parallel_in_flight().lock_owned().await;guard.iter().map(|(request_id, entry)| (request_id.clone(), entry.thread_id.clone()))@@ -133,3 +142,4 @@ pub fn cancel_should_target(requested: Option<&str>, in_flight: &str) -> bool {None => true,}}+diff --git a/crates/openhuman-core/src/web_chat/session.rs b/crates/openhuman-core/src/web_chat/session.rsindex d6bbc41bf1..7e6ada82bb 100644--- a/crates/openhuman-core/src/web_chat/session.rs+++ b/crates/openhuman-core/src/web_chat/session.rs@@ -394,7 +394,7 @@ pub(crate) async fn checkout_session_agent(let prior = if policy == CheckoutPolicy::Fork {None} else {- let mut sessions = super::ops::THREAD_SESSIONS.lock().await;+ let mut sessions = super::ops::thread_sessions().lock_owned().await;sessions.remove(&map_key)};@@ -505,7 +505,7 @@ pub(crate) async fn checkin_session_agent(agent: OpenHumanSessionHost,fingerprint: SessionCacheFingerprint,) {- let mut sessions = super::ops::THREAD_SESSIONS.lock().await;+ let mut sessions = super::ops::thread_sessions().lock_owned().await;sessions.insert(super::ops::key_for(thread_id),SessionEntry { agent, fingerprint },@@ -522,7 +522,7 @@ pub(crate) async fn checkin_session_agent_if_vacant(agent: OpenHumanSessionHost,fingerprint: SessionCacheFingerprint,) -> bool {- let mut sessions = super::ops::THREAD_SESSIONS.lock().await;+ let mut sessions = super::ops::thread_sessions().lock_owned().await;match sessions.entry(super::ops::key_for(thread_id)) {std::collections::hash_map::Entry::Occupied(_) => {log::info!(diff --git a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs b/crates/openhuman-core/src/web_chat/session_checkout_tests.rsindex b3e7859ef1..9dd100e170 100644--- a/crates/openhuman-core/src/web_chat/session_checkout_tests.rs+++ b/crates/openhuman-core/src/web_chat/session_checkout_tests.rs@@ -16,7 +16,7 @@ use super::{};use crate::agent::OpenHumanSessionHost;use crate::config::Config;-use crate::web_chat::ops::{key_for, THREAD_SESSIONS};+use crate::web_chat::ops::{key_for, thread_sessions};use crate::web_chat::types::SessionCacheFingerprint;use tinyagents_session::transcript::TranscriptMessage;use tinytools_agent::dialect::TranscriptEntry;@@ -100,7 +100,10 @@ fn host_seeded_with(config: &Config, marker: &str) -> OpenHumanSessionHost {}async fn evict(thread_id: &str) {- THREAD_SESSIONS.lock().await.remove(&key_for(thread_id));+ thread_sessions()+ .lock_owned()+ .await+ .remove(&key_for(thread_id));}#[tokio::test]@@ -149,7 +152,7 @@ async fn checkout_cold_boots_from_the_thread_transcript_and_checkin_keeps_it_war);checkin_session_agent(&thread_id, agent, fingerprint).await;- assert!(THREAD_SESSIONS+ assert!(thread_sessions().lock().await.contains_key(&key_for(&thread_id)));@@ -173,7 +176,7 @@ async fn checkout_cold_boots_from_the_thread_transcript_and_checkin_keeps_it_war"warm checkout must carry the same history");// Checked out means removed: nobody else can drive this agent meanwhile.- assert!(!THREAD_SESSIONS+ assert!(!thread_sessions().lock().await.contains_key(&key_for(&thread_id)));@@ -259,7 +262,7 @@ async fn a_fork_never_takes_or_returns_the_cached_agent() {// Built fresh: no transcript on disk for this thread, so an empty history.assert!(prose(&agent.history()).is_empty());// The primary's cached agent was left in place.- assert!(THREAD_SESSIONS+ assert!(thread_sessions().lock().await.contains_key(&key_for(&thread_id)));@@ -585,7 +588,7 @@ async fn each_checkout_arms_the_reply_language_from_its_own_locale() {// Reused cached agent, the user switched the UI to English: the Spanish// directives already in the history are superseded explicitly.assert!(- THREAD_SESSIONS+ thread_sessions().lock().await.contains_key(&key_for(&thread_id)),@@ -599,7 +602,7 @@ async fn each_checkout_arms_the_reply_language_from_its_own_locale() {checkin_session_agent(&thread_id, agent, fingerprint).await;// Reused again, now Hindi: re-armed with the new language.- assert!(THREAD_SESSIONS+ assert!(thread_sessions().lock().await.contains_key(&key_for(&thread_id)));diff --git a/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rsindex 6c8a95250e..fe2d4f256a 100644--- a/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs+++ b/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs@@ -430,7 +430,7 @@ async fn chat_done_is_published_only_after_the_in_flight_slot_is_released() {event.event == "chat_done" && event.request_id == request_id};- let held = crate::web_chat::ops::IN_FLIGHT.lock().await;+ let held = crate::web_chat::ops::in_flight().lock_owned().await;block.release.notify_one();let early = timeout(Duration::from_millis(500), async {loop {