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
fix(web-chat): publish chat_done only after the turn releases its slot
M3gA-Mind6ddb7c77e674
diff --git a/crates/openhuman-core/src/web_chat/ops.rs b/crates/openhuman-core/src/web_chat/ops.rsindex 08aeb01a3b..b6567f3c0a 100644--- a/crates/openhuman-core/src/web_chat/ops.rs+++ b/crates/openhuman-core/src/web_chat/ops.rs@@ -30,6 +30,8 @@ pub use system_turn::{run_system_turn_on_thread, SESSION_CHECKOUT_FAILURE, SYSTEpub use state::drain_queued_turns_for_test;#[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 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/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rsindex 64b72552fd..f5ce3088a8 100644--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs@@ -537,29 +537,24 @@ async fn start_chat_inner(};// A terminal socket event is also the UI's permission to submit a- // replacement turn. Defer `chat_error` until after the in-flight- // slot below has been removed: publishing it while the failed slot- // is still present lets an immediate retry interrupt the dead run- // and inherit its failed model state.+ // replacement turn. Defer both terminals until after the in-flight+ // slot below has been removed: publishing either while the slot is+ // still present lets the next message interrupt this finished run,+ // which then gets a spurious "cancelled" chat_error (and, after a+ // failure, lets an immediate retry inherit its failed model state).+ // The reply is stored now, before the slot is released (#6034).+ let mut deferred_done = None;let deferred_error = match result {Ok(chat_result) => {- crate::web_chat::presentation::deliver_response(- &client_id_task,+ crate::web_chat::presentation::persist_reply(&thread_id_task,&request_id_task,&chat_result.full_response,- &user_message,&chat_result.citations,- chat_result.usage.as_ref(),- // The workspace the turn ran in, so the reply is stored- // there before it is announced (#6034).Some(chat_result.workspace_dir.as_path()),- chat_result.timing,- // The main single-user turn is the only surface with- // a human waiting on a next-message suggestion (C5).- true,).await;+ deferred_done = Some(chat_result);None}Err(err) => {@@ -645,6 +640,21 @@ async fn start_chat_inner(// Socket subscribers then observe the old terminal event before// any inference_start from the follow-up, even if it starts at// once on another task.+ if let Some(chat_result) = deferred_done {+ crate::web_chat::presentation::announce_reply(+ &client_id_task,+ &thread_id_task,+ &request_id_task,+ &chat_result.full_response,+ &user_message,+ &chat_result.citations,+ chat_result.usage.as_ref(),+ chat_result.timing,+ // The main single-user turn is the only surface with a+ // human waiting on a next-message suggestion (C5).+ true,+ );+ }if let Some(event) = deferred_error {publish_web_channel_event(event);}diff --git a/crates/openhuman-core/src/web_chat/ops/test_hooks.rs b/crates/openhuman-core/src/web_chat/ops/test_hooks.rsindex f8dd305174..cd2f71bd33 100644--- a/crates/openhuman-core/src/web_chat/ops/test_hooks.rs+++ b/crates/openhuman-core/src/web_chat/ops/test_hooks.rs@@ -23,6 +23,9 @@ pub struct TestRunChatTaskBlock {/// Lets a test end a parked turn without using cancellation, so it can/// exercise terminal queue handling such as follow-up dispatch.pub release: std::sync::Arc<tokio::sync::Notify>,+ /// When set, a released turn succeeds with a fixed reply stored under+ /// this workspace instead of failing, so success delivery is observable.+ pub succeed_in: Option<std::path::PathBuf>,}#[cfg(any(test, debug_assertions))]diff --git a/crates/openhuman-core/src/web_chat/presentation.rs b/crates/openhuman-core/src/web_chat/presentation.rsindex b3423f3d28..e372603183 100644--- a/crates/openhuman-core/src/web_chat/presentation.rs+++ b/crates/openhuman-core/src/web_chat/presentation.rs@@ -60,10 +60,6 @@ pub(crate) async fn deliver_response(timing: Option<super::turn_timing::TurnTimingSnapshot>,suggest_follow_ups: bool,) {- let usage_payload = usage_payload(usage);- let timing_payload =- timing.map(|snapshot| snapshot.into_payload(usage.map(|u| u.output_tokens)));-// Keep the response byte-for-byte in one assistant message. The legacy// segmentation helpers remain available to channel-specific callers/tests,// but the interactive web surface must not cut or reformat model output.@@ -76,69 +72,32 @@ pub(crate) async fn deliver_response(// not the reply (#6034). Only this single-bubble branch persists — the// segmented branch below hands the client one row per segment to write,// and a full-text row beside those would read as a duplicate answer.- if let Some(dir) = workspace_dir {- // The store appends under a process-wide lock and fsyncs, and its- // existence check folds the whole threads log (#5156) — blocking- // work that has no business holding a runtime worker while a turn- // is settling. Hand it to the blocking pool and await the handle,- // which keeps the ordering this whole change rests on.- let (dir, thread, request, reply, cites) = (- dir.to_path_buf(),- thread_id.to_string(),- request_id.to_string(),- full_response.to_string(),- citations.to_vec(),- );- let persisted = tokio::task::spawn_blocking(move || {- super::reply_persistence::persist_delivered_reply(- &dir, &thread, &request, &reply, &cites,- )- })- .await;- match persisted {- Ok(Ok(stored)) => {- if stored {- log::debug!(- "[web-channel] persisted reply before announcing it thread_id={thread_id} request_id={request_id}"- );- }- }- // Deliberately non-fatal: announce anyway. The client's own- // append still persists the reply in the common case, and a- // storage failure must not also cost the user the delivery.- Ok(Err(err)) => log::warn!(- "[web-channel] could not persist reply before announcing it \- thread_id={thread_id} request_id={request_id} error={err}"- ),- Err(err) => log::warn!(- "[web-channel] reply persistence task did not run \- thread_id={thread_id} request_id={request_id} error={err}"- ),- }- }-- // Single bubble — emit chat_done directly.- publish_chat_done(+ persist_reply(+ thread_id,+ request_id,+ full_response,+ citations,+ workspace_dir,+ )+ .await;+ announce_reply(client_id,thread_id,request_id,full_response,+ user_message,citations,- usage_payload,- timing_payload,+ usage,+ timing,+ suggest_follow_ups,);- if suggest_follow_ups {- super::suggestions::spawn_follow_up_suggestions(- client_id.to_string(),- thread_id.to_string(),- request_id.to_string(),- user_message.to_string(),- full_response.to_string(),- );- }return;}+ let usage_payload = usage_payload(usage);+ let timing_payload =+ timing.map(|snapshot| snapshot.into_payload(usage.map(|u| u.output_tokens)));+let total = segments.len() as u32;// Emit each segment as a separate bubble with a human-feeling delay.@@ -249,6 +208,96 @@ pub(crate) async fn deliver_response(}}+/// Stores a single-bubble reply in the thread log before it is announced+/// (#6034): once the row is on disk, a `chat_done` that is never delivered or+/// painted costs the user a repaint, not the reply. A storage failure is+/// logged and never blocks the announcement. `None` stores nothing.+pub(crate) async fn persist_reply(+ thread_id: &str,+ request_id: &str,+ full_response: &str,+ citations: &[crate::memory::types::TurnCitation],+ workspace_dir: Option<&std::path::Path>,+) {+ if let Some(dir) = workspace_dir {+ // The store appends under a process-wide lock and fsyncs, and its+ // existence check folds the whole threads log (#5156) — blocking+ // work that has no business holding a runtime worker while a turn+ // is settling. Hand it to the blocking pool and await the handle,+ // which keeps the ordering this whole change rests on.+ let (dir, thread, request, reply, cites) = (+ dir.to_path_buf(),+ thread_id.to_string(),+ request_id.to_string(),+ full_response.to_string(),+ citations.to_vec(),+ );+ let persisted = tokio::task::spawn_blocking(move || {+ super::reply_persistence::persist_delivered_reply(+ &dir, &thread, &request, &reply, &cites,+ )+ })+ .await;+ match persisted {+ Ok(Ok(stored)) => {+ if stored {+ log::debug!(+ "[web-channel] persisted reply before announcing it thread_id={thread_id} request_id={request_id}"+ );+ }+ }+ // Deliberately non-fatal: announce anyway. The client's own+ // append still persists the reply in the common case, and a+ // storage failure must not also cost the user the delivery.+ Ok(Err(err)) => log::warn!(+ "[web-channel] could not persist reply before announcing it \+ thread_id={thread_id} request_id={request_id} error={err}"+ ),+ Err(err) => log::warn!(+ "[web-channel] reply persistence task did not run \+ thread_id={thread_id} request_id={request_id} error={err}"+ ),+ }+ }+}++/// Announces a reply already stored by [`persist_reply`]: the terminal+/// `chat_done`, then (for the main chat turn) the follow-up suggestions.+#[allow(clippy::too_many_arguments)]+pub(crate) fn announce_reply(+ client_id: &str,+ thread_id: &str,+ request_id: &str,+ full_response: &str,+ user_message: &str,+ citations: &[crate::memory::types::TurnCitation],+ usage: Option<&LastTurnUsage>,+ timing: Option<super::turn_timing::TurnTimingSnapshot>,+ suggest_follow_ups: bool,+) {+ let usage_payload = usage_payload(usage);+ let timing_payload =+ timing.map(|snapshot| snapshot.into_payload(usage.map(|u| u.output_tokens)));+ publish_chat_done(+ client_id,+ thread_id,+ request_id,+ full_response,+ citations,+ usage_payload,+ timing_payload,+ );+ if suggest_follow_ups {+ super::suggestions::spawn_follow_up_suggestions(+ client_id.to_string(),+ thread_id.to_string(),+ request_id.to_string(),+ user_message.to_string(),+ full_response.to_string(),+ );+ }+}+/// Deliver an agent response as exactly one `chat_done` bubble — no/// segmentation — for turns the core runs on its own behalf/// (background sub-agent result delivery).diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rsindex 56487aae19..4ad4bab6a3 100644--- a/crates/openhuman-core/src/web_chat/run_task.rs+++ b/crates/openhuman-core/src/web_chat/run_task.rs@@ -88,7 +88,16 @@ pub(crate) async fn run_chat_task(.store(true, std::sync::atomic::Ordering::SeqCst);tokio::select! {_ = block.release.notified() => {- return Err("test block released".to_string());+ return match block.succeed_in.clone() {+ Some(workspace_dir) => Ok(WebChatTaskResult {+ full_response: "parked reply".to_string(),+ citations: Vec::new(),+ usage: None,+ workspace_dir,+ timing: None,+ }),+ None => Err("test block released".to_string()),+ };}_ = tokio::time::sleep(std::time::Duration::from_secs(30)) => {return Err("test block elapsed".to_string());diff --git a/crates/openhuman-core/src/web_chat/web_tests.rs b/crates/openhuman-core/src/web_chat/web_tests.rsindex 1619823249..08f53a86f7 100644--- a/crates/openhuman-core/src/web_chat/web_tests.rs+++ b/crates/openhuman-core/src/web_chat/web_tests.rs@@ -101,6 +101,7 @@ fn make_block() -> TestRunChatTaskBlock {started: Arc::new(AtomicBool::new(false)),dropped: Arc::new(AtomicBool::new(false)),release: Arc::new(tokio::sync::Notify::new()),+ succeed_in: None,}}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 ae7e040f67..6c8a95250e 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@@ -407,3 +407,64 @@ async fn web_queue_remove_retracts_one_item_and_emits_event() {cancel_parked_turn(thread_id, &block).await;}++/// `chat_done` is the client's go-ahead for its next message, so it must not+/// go out while the finished turn still holds the thread's in-flight slot: a+/// message sent on it would interrupt the finished request and publish a+/// "cancelled" `chat_error` for it. The test holds the slot map's lock while+/// the turn completes; `chat_done` may only arrive after the lock is dropped,+/// and by then the slot is gone.+#[tokio::test]+async fn chat_done_is_published_only_after_the_in_flight_slot_is_released() {+ let _serial = FORCED_ERROR_TEST_LOCK.lock().await;+ let workspace = tempfile::tempdir().expect("workspace");+ let block = TestRunChatTaskBlock {+ succeed_in: Some(workspace.path().to_path_buf()),+ ..make_block()+ };+ set_test_run_chat_task_block(Some(block.clone())).await;+ let thread_id = "chat-done-after-slot-release";+ let request_id = start_parked_turn(thread_id, &block).await;+ let mut events = crate::web_chat::subscribe_web_channel_events();+ let is_done = |event: &crate::web_chat::WebChannelEvent| {+ event.event == "chat_done" && event.request_id == request_id+ };++ let held = crate::web_chat::ops::IN_FLIGHT.lock().await;+ block.release.notify_one();+ let early = timeout(Duration::from_millis(500), async {+ loop {+ if let Ok(event) = events.recv().await {+ if is_done(&event) {+ return event;+ }+ }+ }+ })+ .await;+ assert!(+ early.is_err(),+ "chat_done went out while the turn still held its in-flight slot"+ );+ drop(held);++ timeout(Duration::from_secs(5), async {+ loop {+ if let Ok(event) = events.recv().await {+ if is_done(&event) {+ return;+ }+ }+ }+ })+ .await+ .expect("chat_done after the slot is released");+ assert!(+ !in_flight_entries_for_test()+ .await+ .iter()+ .any(|(key, _)| key == thread_id),+ "the slot is released by the time chat_done is seen"+ );+ set_test_run_chat_task_block(None).await;+}