Skip to content

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

feat(web_chat): add channel ops and start chat handlers

Steven Enamakel1841eae220fd
diff --git a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
index 491e79e46f..9cf0990dff 100644
--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
@@ -1,6 +1,7 @@
//! Public RPC-facing operations for the web channel: sending a chat message,
//! cancelling in-flight turns (primary and parallel, scoped or unscoped), and
-//! inspecting/clearing a thread's run queue.
+//! inspecting/clearing a thread's run queue. The turns and their queues live
+//! in the context's turn runner; these are the thin entry points over it.
use serde_json::{json, Value};
@@ -9,10 +10,9 @@ use crate::core::Outcome;
use crate::web_chat::WebChannelEvent;
use super::super::event_bus::publish_web_channel_event_in;
+use super::super::runner::{runtime, scope_of, CancelNote};
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, in_flight, key_for};
/// Cancel the in-flight turn(s) for a thread.
///
@@ -89,52 +89,49 @@ async fn cancel_chat_inner(
return Err("thread_id is required".to_string());
}
- let map_key = key_for(ctx, thread_id);
- let mut removed_request_id: Option<String> = None;
- let mut removed_client_id: Option<String> = None;
-
+ let rt = runtime(ctx);
+ let scope = scope_of(ctx);
+ let live: Vec<_> = rt
+ .runner
+ .live_turns()
+ .await
+ .into_iter()
+ .filter(|turn| turn.scope == scope && turn.thread_id == thread_id)
+ .collect();
+ // The runner publishes each cancelled turn's terminal event; tell it why.
+ // A fence cancel names no real client, so each turn's events go to the
+ // client that started it; a user's cancel keeps the caller's id.
+ for turn in live
+ .iter()
+ .filter(|turn| request_id.is_none_or(|rid| turn.request_id == rid))
{
- let mut in_flight = in_flight(ctx).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.
- let should_cancel_primary = in_flight
- .get(&map_key)
- .map(|entry| cancel_should_target(request_id, &entry.request_id))
- .unwrap_or(false);
- if should_cancel_primary {
- if let Some(existing) = in_flight.remove(&map_key) {
- removed_client_id = Some(existing.client_id.clone());
- removed_request_id = Some(cancel_in_flight_gracefully(existing));
- }
- } else if let Some(rid) = request_id {
+ rt.shared.note_cancel(
+ &turn.request_id,
+ CancelNote {
+ user_stop: true,
+ client_id: (!fenced).then(|| client_id.to_string()),
+ superseded_by: None,
+ },
+ );
+ }
+ // #4760: a scoped cancel tears down only the turn it names. A stale cancel
+ // for an already-superseded request is a no-op, so the newer turn lives.
+ let cancelled = rt
+ .runner
+ .cancel_requests(&scope, thread_id, request_id)
+ .await;
+ if cancelled.is_empty() {
+ if let Some(rid) = request_id {
log::info!(
- "[web-channel] ignoring stale cancel request_id={} for thread_id={} — current in-flight is {:?}; newer turn preserved",
- rid,
- thread_id,
- in_flight.get(&map_key).map(|e| e.request_id.as_str())
+ "[web-channel] ignoring stale cancel request_id={rid} for thread_id={thread_id} — current in-flight is {:?}; newer turn preserved",
+ live.iter().find(|turn| !turn.parallel).map(|turn| turn.request_id.as_str())
);
}
}
- // Also tear down concurrent parallel (forked) turns. A scoped cancel targets
- // only the named parallel turn (if it is one); an unscoped cancel/stop
- // covers every parallel turn on the thread, not just the primary one.
- let cancelled_parallel = match request_id {
- Some(rid) => cancel_parallel_turn_by_request_id(ctx, thread_id, rid).await,
- None => cancel_parallel_turns_for_thread(ctx, thread_id).await,
- };
-
- // #4760: a scoped cancel that matched only a parallel (forked) turn — not the
- // primary — still genuinely tore a turn down and emitted its cancelled event.
- // Surface that id so `channel_web_cancel` reports `cancelled: true` with the
- // right request_id instead of misreporting a no-op just because the primary
- // turn wasn't the one cancelled.
- let cancelled_any = removed_request_id.clone().or_else(|| {
- cancelled_parallel
- .first()
- .map(|(request_id, _)| request_id.clone())
- });
+ // #4760: a scoped cancel that matched only a parallel (forked) turn still
+ // genuinely tore a turn down; the primary comes first when both did.
+ let cancelled_any = cancelled.first().cloned();
// An unscoped stop also halts the thread's detached work. Async sub-agents
// (`spawn_async_subagent`) run on their own tasks and deliberately drop the
@@ -149,7 +146,10 @@ async fn cancel_chat_inner(
//
// Only once nothing is left running on the thread: a scoped cancel can leave
// the primary or a parallel turn alive, and those still owe a terminal event.
- if cancelled_any.is_some() && !thread_has_live_turn(ctx, thread_id, &map_key).await {
+ let others_live = live
+ .iter()
+ .any(|turn| !cancelled.contains(&turn.request_id));
+ if cancelled_any.is_some() && !others_live {
crate::agent::orchestration::busy_guard::clear_busy_for_thread(ctx, thread_id);
// A drain that fired while the cancelled turn counted as busy returned
// without claiming anything; ask for another.
@@ -169,10 +169,9 @@ async fn cancel_chat_inner(
ctx, thread_id, &stopped,
);
log::info!(
- "[web-channel] stop thread_id={} turn={:?} parallel={} subagents_cancelled={} completions_discarded={}",
+ "[web-channel] stop thread_id={} turns={:?} subagents_cancelled={} completions_discarded={}",
thread_id,
- removed_request_id,
- cancelled_parallel.len(),
+ cancelled,
stopped.len(),
discarded
);
@@ -181,70 +180,12 @@ async fn cancel_chat_inner(
0
};
- // Emit a cancelled chat_error for each cancelled turn (primary + parallels)
- // so every interleaved branch's UI is resolved. `chat_cancelled` is the new,
- // purpose-built terminal event (structured `cancel_reason`, no
- // `error_type` string to parse); `chat_error{error_type:"cancelled"}` is
- // kept alongside it for one release so an older frontend build still
- // resolves the turn.
- // A fence cancel names no real client, so each turn's events go to the
- // client that started it; a user's cancel keeps the caller's id.
- let cancelled_turns = removed_request_id
- .into_iter()
- .map(|request_id| (request_id, removed_client_id.take()))
- .chain(cancelled_parallel.into_iter().map(|(r, c)| (r, Some(c))));
- for (request_id, started_by) in cancelled_turns {
- let client_id = match (fenced, started_by) {
- (true, Some(started_by)) => started_by,
- _ => client_id.to_string(),
- };
- publish_web_channel_event_in(
- ctx,
- WebChannelEvent {
- event: "chat_error".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.to_string(),
- request_id: request_id.clone(),
- message: Some("Cancelled".to_string()),
- error_type: Some("cancelled".to_string()),
- ..Default::default()
- },
- );
- publish_web_channel_event_in(
- ctx,
- WebChannelEvent {
- event: "chat_cancelled".to_string(),
- client_id,
- thread_id: thread_id.to_string(),
- request_id,
- cancel_reason: Some("user_stop".to_string()),
- ..Default::default()
- },
- );
- }
-
Ok(CancelOutcome {
request_id: cancelled_any,
subagents_cancelled,
})
}
-/// Is a primary or parallel turn still running on `thread_id`?
-async fn thread_has_live_turn(ctx: &DispatchCtx, thread_id: &str, map_key: &str) -> bool {
- if super::state::in_flight(ctx)
- .lock()
- .await
- .contains_key(map_key)
- {
- return true;
- }
- super::state::parallel_in_flight(ctx)
- .lock()
- .await
- .values()
- .any(|entry| entry.thread_id == thread_id)
-}
-
pub async fn channel_web_chat(
ctx: &crate::core::runtime::DispatchCtx,
client_id: &str,
@@ -312,7 +253,7 @@ fn queue_item_json(
item: &crate::agent::queued_turn::QueuedTurn,
) -> Value {
json!({
- "id": item.id,
+ "id": item.request_id,
"lane": lane.as_str(),
"text_preview": crate::agent::queued_turn::text_preview(&item.text),
})
@@ -322,32 +263,10 @@ pub async fn channel_web_queue_status(
ctx: &DispatchCtx,
thread_id: &str,
) -> Result<Outcome<Value>, String> {
- let map_key = key_for(ctx, thread_id);
- let in_flight = in_flight(ctx).lock_owned().await;
- if let Some(entry) = in_flight.get(&map_key) {
- let status = entry.run_queue.status().await;
- let items: Vec<Value> = entry
- .run_queue
- .snapshot()
- .await
- .iter()
- .map(|(lane, item)| queue_item_json(*lane, item))
- .collect();
- Ok(Outcome::single_log(
- json!({
- "thread_id": thread_id.trim(),
- "active": true,
- "request_id": entry.request_id,
- "steers": status.steers,
- "followups": status.followups,
- "collects": status.collects,
- "total": status.total,
- "items": items,
- }),
- "queue status retrieved",
- ))
- } else {
- Ok(Outcome::single_log(
+ let runner = &runtime(ctx).runner;
+ let scope = scope_of(ctx);
+ let Some(request_id) = runner.in_flight_request_id(&scope, thread_id).await else {
+ return Ok(Outcome::single_log(
json!({
"thread_id": thread_id.trim(),
"active": false,
@@ -358,8 +277,28 @@ pub async fn channel_web_queue_status(
"items": Vec::<Value>::new(),
}),
"no active turn for thread",
- ))
- }
+ ));
+ };
+ let status = runner.queue_status(&scope, thread_id).await;
+ let items: Vec<Value> = runner
+ .queue_snapshot(&scope, thread_id)
+ .await
+ .iter()
+ .map(|(lane, item)| queue_item_json(*lane, item))
+ .collect();
+ Ok(Outcome::single_log(
+ json!({
+ "thread_id": thread_id.trim(),
+ "active": true,
+ "request_id": request_id,
+ "steers": status.steers,
+ "followups": status.followups,
+ "collects": status.collects,
+ "total": status.total,
+ "items": items,
+ }),
+ "queue status retrieved",
+ ))
}
/// `channel.web_queue_remove` — retract one specific queued item (e.g. the
@@ -379,9 +318,9 @@ pub async fn channel_web_queue_remove(
if item_id.is_empty() {
return Err("item_id is required".to_string());
}
- let map_key = key_for(ctx, thread_id);
- let in_flight = in_flight(ctx).lock_owned().await;
- let Some(entry) = in_flight.get(&map_key) else {
+ let rt = runtime(ctx);
+ let scope = scope_of(ctx);
+ if rt.runner.in_flight_request_id(&scope, thread_id).await.is_none() {
return Ok(Outcome::single_log(
json!({
"thread_id": thread_id,
@@ -390,13 +329,10 @@ pub async fn channel_web_queue_remove(
}),
"no active turn for thread",
));
- };
- let removed = entry
- .run_queue
- .remove_where(|item| item.id == item_id)
- .await;
- drop(in_flight);
+ }
+ let removed = rt.runner.remove_queued(&scope, thread_id, item_id).await;
if removed > 0 {
+ rt.shared.forget_queued(item_id);
log::info!("[web-channel] removed queued item thread_id={thread_id} item_id={item_id}");
publish_web_channel_event_in(
ctx,
@@ -427,33 +363,31 @@ pub async fn channel_web_queue_clear(
ctx: &DispatchCtx,
thread_id: &str,
) -> Result<Outcome<Value>, String> {
- let map_key = key_for(ctx, thread_id);
- let in_flight = in_flight(ctx).lock_owned().await;
- if let Some(entry) = in_flight.get(&map_key) {
- let dropped = entry.run_queue.clear().await;
- log::info!(
- "[web-channel] cleared queue thread_id={} dropped={}",
- thread_id,
- dropped
- );
- Ok(Outcome::single_log(
- json!({
- "thread_id": thread_id.trim(),
- "cleared": true,
- "dropped": dropped,
- }),
- "queue cleared",
- ))
- } else {
- Ok(Outcome::single_log(
+ let rt = runtime(ctx);
+ let scope = scope_of(ctx);
+ if rt.runner.in_flight_request_id(&scope, thread_id).await.is_none() {
+ return Ok(Outcome::single_log(
json!({
"thread_id": thread_id.trim(),
"cleared": false,
"dropped": 0,
}),
"no active turn for thread",
- ))
+ ));
}
+ for (_, item) in rt.runner.queue_snapshot(&scope, thread_id).await {
+ rt.shared.forget_queued(&item.request_id);
+ }
+ let dropped = rt.runner.clear_queue(&scope, thread_id).await;
+ log::info!("[web-channel] cleared queue thread_id={thread_id} dropped={dropped}");
+ Ok(Outcome::single_log(
+ json!({
+ "thread_id": thread_id.trim(),
+ "cleared": true,
+ "dropped": dropped,
+ }),
+ "queue cleared",
+ ))
}
pub async fn channel_web_cancel(
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
index 22f35868ac..ecd5dfcae2 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -252,6 +252,7 @@ async fn start_chat_inner(
let mode = parse_mode(queue_mode.as_deref());
let request_id = Uuid::new_v4().to_string();
+ let preview = crate::agent::queued_turn::text_preview(&message);
let scope = scope_of(ctx);
let queued_at_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -329,7 +330,7 @@ async fn start_chat_inner(
mode: mode.to_string(),
queue_depth,
item_id: Some(request_id.clone()),
- text_preview: None,
+ text_preview: Some(preview),
});
Ok(json!({
"queued": true,