Skip to content

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

refactor(agent): use TinyAgents run queue directly

Steven Enamakel9f051b4ea4b4
diff --git a/crates/openhuman-core/src/agent/harness/agent_graph.rs b/crates/openhuman-core/src/agent/harness/agent_graph.rs
index 45a5c63721..2a82a53e7e 100644
--- a/crates/openhuman-core/src/agent/harness/agent_graph.rs
+++ b/crates/openhuman-core/src/agent/harness/agent_graph.rs
@@ -25,11 +25,11 @@ use std::sync::Arc;
use tinytools::WorkspaceDescriptor;
use tokio::sync::mpsc::Sender;
-use crate::agent::harness::run_queue::RunQueue;
use crate::agent::harness::subagent_runner::SubagentRunError;
use crate::agent::messages::ChatMessage;
use crate::agent::progress::AgentProgress;
use crate::agent::tinyagents::TurnModelSource;
+use tinyagents_harness::run_queue::RunQueue;
use tinytools::{Tool, ToolSpec};
/// The assembled inputs for one sub-agent turn, handed to a custom
@@ -51,7 +51,7 @@ pub struct AgentTurnRequest {
pub specs: Vec<ToolSpec>,
pub allowed_names: HashSet<String>,
pub max_iterations: usize,
- pub run_queue: Option<Arc<RunQueue>>,
+ pub run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
pub on_progress: Option<Sender<AgentProgress>>,
pub agent_id: String,
pub task_id: String,
diff --git a/crates/openhuman-core/src/agent/harness/fork_context.rs b/crates/openhuman-core/src/agent/harness/fork_context.rs
index e10a759316..43696909d4 100644
--- a/crates/openhuman-core/src/agent/harness/fork_context.rs
+++ b/crates/openhuman-core/src/agent/harness/fork_context.rs
@@ -157,7 +157,8 @@ pub struct ParentExecutionContext {
/// Parent's active run queue. Tools that create background event sources
/// use this to inject concise collect-context at the same safe iteration
/// boundary as web-channel queue messages.
- pub run_queue: Option<Arc<crate::agent::harness::run_queue::RunQueue>>,
+ pub run_queue:
+ Option<Arc<tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
}
/// A context-preparation source that already ran for the current parent turn.
diff --git a/crates/openhuman-core/src/agent/harness/mod.rs b/crates/openhuman-core/src/agent/harness/mod.rs
index 2b3a8f5ba7..3cb6bad22e 100644
--- a/crates/openhuman-core/src/agent/harness/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/mod.rs
@@ -34,7 +34,6 @@ pub(crate) mod memory_context;
pub(crate) mod memory_context_safety;
pub(crate) mod memory_protocol;
pub(crate) mod required_output;
-pub mod run_queue;
pub mod sandbox_context;
pub mod session;
pub(crate) mod spawn_depth_context;
diff --git a/crates/openhuman-core/src/agent/harness/run_queue/mod.rs b/crates/openhuman-core/src/agent/harness/run_queue/mod.rs
deleted file mode 100644
index 9b03752a33..0000000000
--- a/crates/openhuman-core/src/agent/harness/run_queue/mod.rs
+++ /dev/null
@@ -1,84 +0,0 @@
-//! Active-run queue for mid-turn message steering.
-//!
-//! When an agent turn is in flight, incoming messages can be routed into
-//! one of three lanes instead of aborting the turn:
-//!
-//! - **steers** — injected at the next iteration boundary as a new user
-//! instruction the agent must address immediately.
-//! - **followups** — dispatched as a fresh turn after the current one completes.
-//! - **collects** — injected as additional context at the next iteration
-//! boundary without being a distinct instruction.
-//!
-//! The engine drains steers and collects at safe points (after tool results are
-//! committed to history), preserving the tool-call / tool-result pairing invariant.
-
-mod types;
-
-use std::sync::Arc;
-use tinyagents_harness::run_queue::{QueueLane, RunQueue as TinyAgentsRunQueue};
-
-pub use tinyagents_harness::run_queue::QueueStatus;
-pub use types::{QueueMode, QueuedMessage};
-
-/// Thread-safe run queue with three lanes. Wrapped in `Arc` for shared
-/// ownership between the web channel producer and the engine consumer.
-#[derive(Debug)]
-pub struct RunQueue {
- inner: TinyAgentsRunQueue<QueuedMessage>,
-}
-
-impl RunQueue {
- pub fn new() -> Arc<Self> {
- Arc::new(Self {
- inner: TinyAgentsRunQueue::new(),
- })
- }
-
- /// Push a message into the appropriate lane based on its mode.
- pub async fn push(&self, msg: QueuedMessage) {
- match msg.mode {
- QueueMode::Steer => self.inner.push(QueueLane::Steer, msg).await,
- QueueMode::Followup => self.inner.push(QueueLane::Followup, msg).await,
- QueueMode::Collect => self.inner.push(QueueLane::Collect, msg).await,
- QueueMode::Interrupt => {
- log::warn!(
- "[run_queue] interrupt-mode message pushed to queue — should have been handled by caller"
- );
- }
- QueueMode::Parallel => {
- log::warn!(
- "[run_queue] parallel-mode message pushed to queue — should have spawned a forked turn at the caller"
- );
- }
- }
- }
-
- /// Drain all pending steer messages (FIFO order).
- pub async fn drain_steers(&self) -> Vec<QueuedMessage> {
- self.inner.drain(QueueLane::Steer).await
- }
-
- /// Drain all pending collect messages (FIFO order).
- pub async fn drain_collects(&self) -> Vec<QueuedMessage> {
- self.inner.drain(QueueLane::Collect).await
- }
-
- /// Drain all pending followup messages (FIFO order).
- pub async fn drain_followups(&self) -> Vec<QueuedMessage> {
- self.inner.drain(QueueLane::Followup).await
- }
-
- /// Snapshot the current queue depth per lane.
- pub async fn status(&self) -> QueueStatus {
- self.inner.status().await
- }
-
- /// Clear all lanes and return the total number of messages dropped.
- pub async fn clear(&self) -> usize {
- self.inner.clear().await
- }
-}
-
-#[cfg(test)]
-#[path = "run_queue_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/harness/run_queue/run_queue_tests.rs b/crates/openhuman-core/src/agent/harness/run_queue/run_queue_tests.rs
deleted file mode 100644
index f4fac02104..0000000000
--- a/crates/openhuman-core/src/agent/harness/run_queue/run_queue_tests.rs
+++ /dev/null
@@ -1,142 +0,0 @@
-use super::*;
-
-fn msg(text: &str, mode: QueueMode) -> QueuedMessage {
- QueuedMessage {
- text: text.to_string(),
- mode,
- client_id: "c1".to_string(),
- thread_id: "t1".to_string(),
- queued_at_ms: 0,
- model_override: None,
- temperature: None,
- locale: None,
- }
-}
-
-#[tokio::test]
-async fn new_queue_is_empty() {
- let q = RunQueue::new();
- let s = q.status().await;
- assert_eq!(s.total, 0);
- assert_eq!(s.steers, 0);
- assert_eq!(s.followups, 0);
- assert_eq!(s.collects, 0);
-}
-
-#[tokio::test]
-async fn push_steer_routes_to_steer_lane() {
- let q = RunQueue::new();
- q.push(msg("fix it", QueueMode::Steer)).await;
- let s = q.status().await;
- assert_eq!(s.steers, 1);
- assert_eq!(s.followups, 0);
- assert_eq!(s.collects, 0);
- assert_eq!(s.total, 1);
-}
-
-#[tokio::test]
-async fn push_followup_routes_to_followup_lane() {
- let q = RunQueue::new();
- q.push(msg("then do this", QueueMode::Followup)).await;
- let s = q.status().await;
- assert_eq!(s.steers, 0);
- assert_eq!(s.followups, 1);
- assert_eq!(s.collects, 0);
-}
-
-#[tokio::test]
-async fn push_collect_routes_to_collect_lane() {
- let q = RunQueue::new();
- q.push(msg("btw", QueueMode::Collect)).await;
- let s = q.status().await;
- assert_eq!(s.steers, 0);
- assert_eq!(s.followups, 0);
- assert_eq!(s.collects, 1);
-}
-
-#[tokio::test]
-async fn drain_steers_returns_fifo_and_empties() {
- let q = RunQueue::new();
- q.push(msg("first", QueueMode::Steer)).await;
- q.push(msg("second", QueueMode::Steer)).await;
- let drained = q.drain_steers().await;
- assert_eq!(drained.len(), 2);
- assert_eq!(drained[0].text, "first");
- assert_eq!(drained[1].text, "second");
- assert_eq!(q.status().await.steers, 0);
-}
-
-#[tokio::test]
-async fn drain_collects_returns_fifo_and_empties() {
- let q = RunQueue::new();
- q.push(msg("a", QueueMode::Collect)).await;
- q.push(msg("b", QueueMode::Collect)).await;
- let drained = q.drain_collects().await;
- assert_eq!(drained.len(), 2);
- assert_eq!(drained[0].text, "a");
- assert_eq!(drained[1].text, "b");
- assert_eq!(q.status().await.collects, 0);
-}
-
-#[tokio::test]
-async fn drain_followups_returns_fifo_and_empties() {
- let q = RunQueue::new();
- q.push(msg("x", QueueMode::Followup)).await;
- let drained = q.drain_followups().await;
- assert_eq!(drained.len(), 1);
- assert_eq!(drained[0].text, "x");
- assert_eq!(q.status().await.followups, 0);
-}
-
-#[tokio::test]
-async fn clear_empties_all_lanes() {
- let q = RunQueue::new();
- q.push(msg("s", QueueMode::Steer)).await;
- q.push(msg("f", QueueMode::Followup)).await;
- q.push(msg("c", QueueMode::Collect)).await;
- let dropped = q.clear().await;
- assert_eq!(dropped, 3);
- assert_eq!(q.status().await.total, 0);
-}
-
-#[tokio::test]
-async fn drain_does_not_affect_other_lanes() {
- let q = RunQueue::new();
- q.push(msg("s", QueueMode::Steer)).await;
- q.push(msg("f", QueueMode::Followup)).await;
- q.push(msg("c", QueueMode::Collect)).await;
- let _ = q.drain_steers().await;
- let s = q.status().await;
- assert_eq!(s.steers, 0);
- assert_eq!(s.followups, 1);
- assert_eq!(s.collects, 1);
-}
-
-#[tokio::test]
-async fn multiple_pushes_accumulate() {
- let q = RunQueue::new();
- for i in 0..5 {
- q.push(msg(&format!("steer-{i}"), QueueMode::Steer)).await;
- }
- for i in 0..3 {
- q.push(msg(&format!("follow-{i}"), QueueMode::Followup))
- .await;
- }
- let s = q.status().await;
- assert_eq!(s.steers, 5);
- assert_eq!(s.followups, 3);
- assert_eq!(s.total, 8);
-}
-
-#[tokio::test]
-async fn queue_mode_display() {
- assert_eq!(QueueMode::Interrupt.to_string(), "interrupt");
- assert_eq!(QueueMode::Steer.to_string(), "steer");
- assert_eq!(QueueMode::Followup.to_string(), "followup");
- assert_eq!(QueueMode::Collect.to_string(), "collect");
-}
-
-#[tokio::test]
-async fn queue_mode_default_is_interrupt() {
- assert_eq!(QueueMode::default(), QueueMode::Interrupt);
-}
diff --git a/crates/openhuman-core/src/agent/harness/run_queue/types.rs b/crates/openhuman-core/src/agent/harness/run_queue/types.rs
deleted file mode 100644
index bab98d41af..0000000000
--- a/crates/openhuman-core/src/agent/harness/run_queue/types.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-//! Types for the active-run queue model.
-
-use std::fmt;
-
-/// How a message arriving during an active agent turn should be handled.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "snake_case")]
-#[derive(Default)]
-pub enum QueueMode {
- /// Abort the in-flight turn and start fresh (default, backward-compatible).
- #[default]
- Interrupt,
- /// Inject the message at the next safe iteration boundary so the agent
- /// sees it mid-turn without restarting.
- Steer,
- /// Queue the message as a follow-up turn that fires after the current
- /// turn completes.
- Followup,
- /// Silently collect the message as additional context; the agent sees it
- /// at the next iteration boundary but does not treat it as a new instruction.
- Collect,
- /// Run as an independent concurrent turn on the same thread. The new turn
- /// forks the thread's history-at-start (snapshot) and runs alongside any
- /// in-flight turn instead of interrupting or queueing — its result is
- /// appended to the conversation on completion (snapshot + append).
- Parallel,
-}
-
-impl fmt::Display for QueueMode {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- Self::Interrupt => write!(f, "interrupt"),
- Self::Steer => write!(f, "steer"),
- Self::Followup => write!(f, "followup"),
- Self::Collect => write!(f, "collect"),
- Self::Parallel => write!(f, "parallel"),
- }
- }
-}
-
-/// A message sitting in the run queue, tagged with its lane.
-#[derive(Debug, Clone)]
-pub struct QueuedMessage {
- pub text: String,
- pub mode: QueueMode,
- pub client_id: String,
- pub thread_id: String,
- pub queued_at_ms: u64,
- pub model_override: Option<String>,
- pub temperature: Option<f64>,
- pub locale: Option<String>,
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs b/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs
index 4bf08e8847..94f802f9fc 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs
+++ b/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs
@@ -381,7 +381,11 @@ impl Agent {
/// Attach an active-run queue for mid-turn steering.
pub fn set_run_queue(
&mut self,
- rq: Option<std::sync::Arc<crate::agent::harness::run_queue::RunQueue>>,
+ rq: Option<
+ std::sync::Arc<
+ tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>,
+ >,
+ >,
) {
self.run_queue = rq;
}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs b/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
index cf3cf2ae65..2a5f1cea4b 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/graph.rs
@@ -28,7 +28,6 @@ use std::sync::Arc;
use anyhow::Result;
use tokio::sync::mpsc::Sender;
-use crate::agent::harness::run_queue::RunQueue;
use crate::agent::harness::{with_current_sandbox_mode, SandboxMode};
use crate::agent::messages::ChatMessage;
use crate::agent::progress::AgentProgress;
@@ -36,6 +35,7 @@ use crate::agent::tinyagents::{
run_root_turn_via_hosted_agent, TinyagentsTurnOutcome, TurnContextMiddleware,
};
use crate::inference::provider::AGENT_TURN_MAX_OUTPUT_TOKENS;
+use tinyagents_harness::run_queue::RunQueue;
use tinytools::Tool;
/// Inputs for a single chat-turn graph dispatch. Grouped into a struct so the
@@ -73,7 +73,7 @@ pub(crate) struct ChatTurnGraph {
/// provider does not advertise a window.
pub context_window: Option<u64>,
/// Session run queue for mid-flight steering.
- pub run_queue: Option<Arc<RunQueue>>,
+ pub run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
/// openhuman context middlewares (cache-align, microcompact, tool-output
/// budget + payload summarizer) sourced from the session's `ContextManager`.
pub context_mw: TurnContextMiddleware,
diff --git a/crates/openhuman-core/src/agent/harness/session/types.rs b/crates/openhuman-core/src/agent/harness/session/types.rs
index e881639f7a..9510cf4b47 100644
--- a/crates/openhuman-core/src/agent/harness/session/types.rs
+++ b/crates/openhuman-core/src/agent/harness/session/types.rs
@@ -325,7 +325,8 @@ pub struct Agent {
pub(super) on_progress: Option<tokio::sync::mpsc::Sender<AgentProgress>>,
/// Optional active-run queue for mid-turn steering. When set, the
/// engine drains steers/collects at iteration boundaries.
- pub(super) run_queue: Option<Arc<crate::agent::harness::run_queue::RunQueue>>,
+ pub(super) run_queue:
+ Option<Arc<tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
/// Active Composio integrations the user has connected. Populated at
/// agent build time and threaded into each agent's `prompt.rs` so
/// the delegator / skill-executor voices can render their own
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
index 1456091a19..87cf96bde7 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
@@ -12,6 +12,7 @@ use crate::agent::messages::{ChatMessage, ConversationMessage};
use crate::agent::progress::AgentProgress;
use crate::agent::tinyagents::{run_turn_via_tinyagents_shared, SubagentScope};
use crate::inference::tokenjuice::AgentTokenjuiceCompression;
+use tinyagents_harness::run_queue::RunQueue;
use tinytools::WorkspaceDescriptor;
use tinytools::{Tool, ToolSpec};
@@ -126,7 +127,7 @@ pub(in super::super) async fn run_subagent_via_graph(
specs: Vec<ToolSpec>,
allowed_names: HashSet<String>,
max_iterations: usize,
- run_queue: Option<Arc<crate::agent::harness::run_queue::RunQueue>>,
+ run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
on_progress: Option<tokio::sync::mpsc::Sender<AgentProgress>>,
agent_id: &str,
task_id: &str,
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests.rs
index a03b3e8351..4d72d291f5 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests.rs
@@ -70,9 +70,9 @@ fn stub(name: &'static str) -> Box<dyn Tool> {
// ── End-to-end runner tests with mock provider ────────────────────────
use crate::agent::harness::fork_context::with_parent_context;
-use crate::agent::harness::run_queue::{QueueMode, QueuedMessage, RunQueue};
use parking_lot::Mutex;
use std::sync::Arc;
+use tinyagents_harness::run_queue::{QueueLane, RunQueue};
use tinyinference_llm::message::{AssistantMessage, ContentBlock, Message, MessageDelta};
use tinyinference_llm::model::{
ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_slug_filter_typed_mode_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_slug_filter_typed_mode_tests.rs
index 6c390784e9..009a9d7b41 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_slug_filter_typed_mode_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops_tests_slug_filter_typed_mode_tests.rs
@@ -283,18 +283,20 @@ async fn run_queue_steer_lands_in_subagent_history() {
let parent = make_parent(provider.clone(), vec![stub("file_read")]);
let def = make_def_named_tools(&[]);
- let run_queue = RunQueue::new();
+ let run_queue = Arc::new(RunQueue::new());
run_queue
- .push(QueuedMessage {
- text: "switch focus to memory safety".into(),
- mode: QueueMode::Steer,
- client_id: "steer_subagent".into(),
- thread_id: "t-steer".into(),
- queued_at_ms: 0,
- model_override: None,
- temperature: None,
- locale: None,
- })
+ .push(
+ QueueLane::Steer,
+ crate::agent::queued_turn::QueuedTurn {
+ text: "switch focus to memory safety".into(),
+ client_id: "steer_subagent".into(),
+ thread_id: "t-steer".into(),
+ queued_at_ms: 0,
+ model_override: None,
+ temperature: None,
+ locale: None,
+ },
+ )
.await;
let outcome = with_parent_context(parent, async {
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs
index e316ce849b..05967d38b4 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs
@@ -91,7 +91,11 @@ pub struct SubagentRunOptions {
/// iteration boundaries — exactly like the main agent loop — so the parent
/// can `steer_subagent` mid-flight. `None` keeps today's non-steerable
/// behaviour.
- pub run_queue: Option<std::sync::Arc<crate::agent::harness::run_queue::RunQueue>>,
+ pub run_queue: Option<
+ std::sync::Arc<
+ tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>,
+ >,
+ >,
}
/// Terminal status of a sub-agent run.
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index 37762e6268..0cc3748645 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -56,6 +56,8 @@ pub(crate) mod progress_tracing;
/// Prompt plumbing — types, section builders, and
/// [`SystemPromptBuilder`](prompts::SystemPromptBuilder).
pub mod prompts;
+/// Host-owned payload carried through TinyAgents run queues.
+pub mod queued_turn;
pub mod registry;
mod schemas;
pub mod session_db;
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs
index fba0dfaad4..76424b9f8c 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs
@@ -26,10 +26,10 @@ use std::sync::{Arc, OnceLock};
use tokio::sync::watch;
use tokio::task::AbortHandle;
-use crate::agent::harness::run_queue::RunQueue;
use crate::agent::tinyagents::host::steering::shared_steering_registry;
use tinyagents_graph::orchestration::DetachedTaskRegistry;
use tinyagents_harness::ids::TaskId;
+use tinyagents_harness::run_queue::RunQueue;
use tinyagents_harness::CancellationToken;
use super::task_ledger::record_spawned;
@@ -63,7 +63,7 @@ pub(crate) struct RunningSubagentMetadata {
/// `None` for a headless spawn with no originating thread. Used to abort the
/// sub-agent when its parent thread is deleted (see [`super::cancel::cancel_for_thread`]).
pub(crate) parent_thread_id: Option<String>,
- pub(crate) run_queue: Arc<RunQueue>,
+ pub(crate) run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -123,7 +123,7 @@ pub(crate) fn register(
subagent_session_id: Option<String>,
workspace_dir: PathBuf,
parent_thread_id: Option<String>,
- run_queue: Arc<RunQueue>,
+ run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
abort: AbortHandle,
status: watch::Receiver<SubagentStatus>,
) {
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs
index 79f055ef2a..b47c64d601 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs
@@ -2,9 +2,9 @@
//! sub-agent: the `RunQueue` compatibility lane, and the TinyAgents
//! `SteeringHandle` fast path for runs that have registered one.
-use crate::agent::harness::run_queue::{QueueMode, QueuedMessage};
use tinyagents_graph::orchestration::DetachedTaskRegistryError;
use tinyagents_harness::ids::TaskId;
+use tinyagents_harness::run_queue::QueueLane;
use tinyagents_harness::steering::{SteeringCommand, SteeringCommandKind};
use tinyinference_llm::message::Message as TaMessage;
@@ -20,6 +20,10 @@ pub enum SteerError {
NotOwned,
/// The sub-agent already reached a terminal status.
AlreadyDone,
+ /// Detached sub-agents can only receive an injected instruction or
+ /// collected context. Follow-up work is a web-turn concern and cannot be
+ /// meaningfully dispatched from this fallback queue.
+ UnsupportedLane,
}
pub(crate) fn steer_error_from_registry(error: DetachedTaskRegistryError) -> SteerError {
@@ -30,24 +34,32 @@ pub(crate) fn steer_error_from_registry(error: DetachedTaskRegistryError) -> Ste
}
}
-fn steering_command_for_mode(mode: QueueMode, text: String) -> Option<SteeringCommand> {
- match mode {
- QueueMode::Steer => Some(SteeringCommand::InjectMessage(TaMessage::user(format!(
+fn steering_command_for_lane(lane: QueueLane, text: String) -> Option<SteeringCommand> {
+ match lane {
+ QueueLane::Steer => Some(SteeringCommand::InjectMessage(TaMessage::user(format!(
"[User steering message]: {text}"
)))),
- QueueMode::Collect => Some(SteeringCommand::InjectMessage(TaMessage::user(format!(
+ QueueLane::Collect => Some(SteeringCommand::InjectMessage(TaMessage::user(format!(
"[Additional context from user]: {text}"
)))),
- QueueMode::Interrupt | QueueMode::Followup | QueueMode::Parallel => None,
+ QueueLane::Followup => None,
+ }
+}
+
+fn queue_lane_name(lane: QueueLane) -> &'static str {
+ match lane {
+ QueueLane::Steer => "steer",
+ QueueLane::Followup => "followup",
+ QueueLane::Collect => "collect",
}
}
fn send_registered_steering(
handle: &tinyagents_harness::steering::SteeringHandle,
text: String,
- mode: QueueMode,
+ lane: QueueLane,
) -> bool {
- let Some(command) = steering_command_for_mode(mode, text) else {
+ let Some(command) = steering_command_for_lane(lane, text) else {
return false;
};
handle.send(command);
@@ -172,8 +184,16 @@ pub async fn steer(
task_id: &str,
parent_session: &str,
text: String,
- mode: QueueMode,
+ lane: QueueLane,
) -> Result<(), SteerError> {
+ if !matches!(lane, QueueLane::Steer | QueueLane::Collect) {
+ log::warn!(
+ "[running_subagents] rejected unsupported queue lane task_id={} lane={}",
+ task_id,
+ queue_lane_name(lane)
+ );
+ return Err(SteerError::UnsupportedLane);
+ }
let task_id_key = TaskId::new(task_id);
let snapshot = registry()
.snapshot(&task_id_key, parent_session)
@@ -184,13 +204,13 @@ pub async fn steer(
let steered_via_registry = registry()
.steering_handle(&task_id_key, parent_session)
- .map(|handle| send_registered_steering(&handle, text.clone(), mode))
+ .map(|handle| send_registered_steering(&handle, text.clone(), lane))
.unwrap_or(false);
if steered_via_registry {
log::info!(
- "[running_subagents] steered task_id={} mode={} via=tinyagents_registry",
+ "[running_subagents] steered task_id={} lane={} via=tinyagents_registry",
task_id,
- mode
+ queue_lane_name(lane)
);
return Ok(());
}
@@ -198,21 +218,23 @@ pub async fn steer(
snapshot
.metadata
.run_queue
- .push(QueuedMessage {
- text,
- mode,
- client_id: "steer_subagent".to_string(),
- thread_id: task_id.to_string(),
- queued_at_ms: now_ms(),
- model_override: None,
- temperature: None,
- locale: None,
- })
+ .push(
+ lane,
+ crate::agent::queued_turn::QueuedTurn {
+ text,
+ client_id: "steer_subagent".to_string(),
+ thread_id: task_id.to_string(),
+ queued_at_ms: now_ms(),
+ model_override: None,
+ temperature: None,
+ locale: None,
+ },
+ )
.await;
log::info!(
- "[running_subagents] steered task_id={} mode={}",
+ "[running_subagents] steered task_id={} lane={}",
task_id,
- mode
+ queue_lane_name(lane)
);
Ok(())
}
@@ -226,8 +248,16 @@ pub async fn steer(
pub(crate) async fn steer_control(
task_id: &str,
text: String,
- mode: QueueMode,
+ lane: QueueLane,
) -> Result<(), SteerError> {
+ if !matches!(lane, QueueLane::Steer | QueueLane::Collect) {
+ log::warn!(
+ "[running_subagents] rejected unsupported control queue lane task_id={} lane={}",
+ task_id,
+ queue_lane_name(lane)
+ );
+ return Err(SteerError::UnsupportedLane);
+ }
let task_id_key = TaskId::new(task_id);
let snapshot = registry()
.snapshot_trusted(&task_id_key)
@@ -238,13 +268,13 @@ pub(crate) async fn steer_control(
let steered_via_registry = registry()
.steering_handle_trusted(&task_id_key)
- .map(|handle| send_registered_steering(&handle, text.clone(), mode))
+ .map(|handle| send_registered_steering(&handle, text.clone(), lane))
.unwrap_or(false);
if steered_via_registry {
log::info!(
- "[running_subagents] control_steered task_id={} mode={} via=tinyagents_registry",
+ "[running_subagents] control_steered task_id={} lane={} via=tinyagents_registry",
task_id,
- mode
+ queue_lane_name(lane)
);
return Ok(());
}
@@ -252,21 +282,23 @@ pub(crate) async fn steer_control(
snapshot
.metadata
.run_queue
- .push(QueuedMessage {
- text,
- mode,
- client_id: "subagent_control_rpc".to_string(),
- thread_id: task_id.to_string(),
- queued_at_ms: now_ms(),
- model_override: None,
- temperature: None,
- locale: None,
- })
+ .push(
+ lane,
+ crate::agent::queued_turn::QueuedTurn {
+ text,
+ client_id: "subagent_control_rpc".to_string(),
+ thread_id: task_id.to_string(),
+ queued_at_ms: now_ms(),
+ model_override: None,
+ temperature: None,
+ locale: None,
+ },
+ )
.await;
log::info!(
- "[running_subagents] control_steered task_id={} mode={}",
+ "[running_subagents] control_steered task_id={} lane={}",
task_id,
- mode
+ queue_lane_name(lane)
);
Ok(())
}
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_steering_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_steering_tests.rs
index 8af87820de..c459445193 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_steering_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents_steering_tests.rs
@@ -3,14 +3,14 @@ use super::*;
#[tokio::test]
async fn steer_pushes_into_the_subagent_queue() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let tx = register_test("task-steer", "session-A", rq.clone());
steer(
"task-steer",
"session-A",
"refocus on memory safety".into(),
- QueueMode::Steer,
+ QueueLane::Steer,
)
.await
.expect("steer should succeed");
@@ -23,7 +23,7 @@ async fn steer_pushes_into_the_subagent_queue() {
"task-steer",
"session-A",
"extra context".into(),
- QueueMode::Collect,
+ QueueLane::Collect,
)
.await
.unwrap();
@@ -39,7 +39,7 @@ async fn steer_pushes_into_the_subagent_queue() {
#[tokio::test]
async fn steer_prefers_registered_tinyagents_handle() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let tx = register_test("task-registered-steer", "session-A", rq.clone());
let handle = SteeringHandle::allow_all();
let task_id = TaskId::new("task-registered-steer");
@@ -49,7 +49,7 @@ async fn steer_prefers_registered_tinyagents_handle() {
"task-registered-steer",
"session-A",
"refocus".into(),
- QueueMode::Steer,
+ QueueLane::Steer,
)
.await
.expect("steer should succeed");
@@ -76,7 +76,7 @@ async fn steer_prefers_registered_tinyagents_handle() {
#[tokio::test]
async fn steer_directive_delivers_control_flow_via_background_policy() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let tx = register_test("task-directive", "session-A", rq.clone());
// A background sub-agent handle accepts Cancel/Redirect/Resume.
let handle = openhuman_steering_handle(SteeringRunClass::Background);
@@ -113,7 +113,7 @@ async fn steer_directive_delivers_control_flow_via_background_policy() {
#[tokio::test]
async fn steer_directive_refuses_kinds_the_policy_rejects() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let tx = register_test("task-tight", "session-A", rq);
// An interactive-class handle only allows InjectMessage/Pause, so a
// Cancel directive must be refused up front rather than enqueued (which
@@ -147,7 +147,7 @@ async fn steer_directive_refuses_kinds_the_policy_rejects() {
#[tokio::test]
async fn steer_directive_enforces_ownership_and_registration() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let tx = register_test("task-own", "session-owner", rq);
// Cross-parent is refused before any handle lookup.
@@ -176,7 +176,7 @@ async fn steer_directive_enforces_ownership_and_registration() {
#[tokio::test]
async fn steer_rejects_cross_parent_and_unknown() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let _tx = register_test("task-owned", "session-owner", rq);
assert_eq!(
@@ -184,7 +184,7 @@ async fn steer_rejects_cross_parent_and_unknown() {
"task-owned",
"session-intruder",
"x".into(),
- QueueMode::Steer
+ QueueLane::Steer
)
.await,
Err(SteerError::NotOwned)
@@ -194,7 +194,7 @@ async fn steer_rejects_cross_parent_and_unknown() {
"task-missing",
"session-owner",
"x".into(),
- QueueMode::Steer
+ QueueLane::Steer
)
.await,
Err(SteerError::Unknown)
@@ -205,15 +205,35 @@ async fn steer_rejects_cross_parent_and_unknown() {
#[tokio::test]
async fn steer_after_terminal_is_rejected() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let tx = register_test("task-term", "session-A", rq);
let _ = tx.send(SubagentStatus::Failed {
error: "boom".into(),
});
assert_eq!(
- steer("task-term", "session-A", "x".into(), QueueMode::Steer).await,
+ steer("task-term", "session-A", "x".into(), QueueLane::Steer).await,
Err(SteerError::AlreadyDone)
);
prune("task-term");
}
+
+#[tokio::test]
+async fn detached_subagent_rejects_followup_lane() {
+ let _guard = test_guard();
+ let rq = run_queue();
+ let _tx = register_test("task-no-followup", "session-A", rq.clone());
+
+ assert_eq!(
+ steer(
+ "task-no-followup",
+ "session-A",
+ "not a new turn".into(),
+ QueueLane::Followup,
+ )
+ .await,
+ Err(SteerError::UnsupportedLane)
+ );
+ assert_eq!(rq.status().await.total, 0);
+ prune("task-no-followup");
+}
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs
index 9165aa9ce6..f2e365f70c 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs
@@ -1,6 +1,4 @@
use super::*;
-use crate::agent::harness::run_queue::QueueMode;
-use crate::agent::harness::run_queue::RunQueue;
use crate::agent::orchestration::running_subagents::registry::DETACHED_LEDGER_TIMEOUT_MS;
use crate::agent::orchestration::running_subagents::resolve::resume_ref_for_task;
use crate::agent::orchestration::running_subagents::resolve::task_id_for_session;
@@ -9,6 +7,7 @@ use crate::agent::orchestration::running_subagents::steering::steer_directive;
use crate::agent::orchestration::running_subagents::steering::SteerDirectiveError;
use crate::agent::orchestration::running_subagents::steering::SteeringDirective;
use crate::agent::orchestration::running_subagents::wait::wait;
+use crate::agent::queued_turn::QueuedTurn;
use crate::agent::tinyagents::host::steering::{
openhuman_steering_handle, shared_steering_registry, SteeringRunClass,
};
@@ -18,6 +17,7 @@ use std::sync::MutexGuard;
use std::time::Duration;
use tinyagents_graph::orchestration::OrchestrationTaskStatus;
use tinyagents_harness::ids::TaskId;
+use tinyagents_harness::run_queue::{QueueLane, RunQueue};
use tinyagents_harness::steering::{
SteeringCommand, SteeringCommandKind, SteeringHandle, SteeringPolicy,
};
@@ -43,6 +43,10 @@ fn dummy_abort() -> AbortHandle {
tokio::spawn(async {}).abort_handle()
}
+fn run_queue() -> Arc<RunQueue<QueuedTurn>> {
+ Arc::new(RunQueue::new())
+}
+
/// Per-process-run unique workspace for the detached task store.
///
/// The task store is now a durable JSONL file under the given workspace
@@ -65,7 +69,7 @@ fn test_workspace() -> PathBuf {
fn register_test(
task_id: &str,
parent_session: &str,
- rq: Arc<RunQueue>,
+ rq: Arc<RunQueue<QueuedTurn>>,
) -> watch::Sender<SubagentStatus> {
register_test_with_thread(task_id, parent_session, None, rq)
}
@@ -76,7 +80,7 @@ fn register_test_with_thread(
task_id: &str,
parent_session: &str,
parent_thread_id: Option<&str>,
- rq: Arc<RunQueue>,
+ rq: Arc<RunQueue<QueuedTurn>>,
) -> watch::Sender<SubagentStatus> {
let (tx, rx) = status_channel();
register(
@@ -98,7 +102,7 @@ fn register_test_with_thread(
async fn task_store_records_spawn_complete_and_cancel() {
let _guard = test_guard();
// Spawn → the ledger sees a running SubAgent task scoped to the parent.
- let tx = register_test("task-ledger-1", "ledger-parent", RunQueue::new());
+ let tx = register_test("task-ledger-1", "ledger-parent", run_queue());
let running = task_records(Some("ledger-parent"));
assert!(
running
@@ -135,7 +139,7 @@ async fn task_store_records_spawn_complete_and_cancel() {
assert_eq!(rec.status, OrchestrationTaskStatus::Completed);
// A second sub-agent that gets cancelled is recorded Cancelled.
- let _tx2 = register_test("task-ledger-2", "ledger-parent", RunQueue::new());
+ let _tx2 = register_test("task-ledger-2", "ledger-parent", run_queue());
assert!(cancel_by_task("task-ledger-2").is_some());
let cancelled = task_records(None)
.into_iter()
@@ -149,7 +153,7 @@ async fn task_store_records_spawn_complete_and_cancel() {
#[tokio::test]
async fn task_id_for_session_enforces_parent_ownership() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let (tx, rx) = status_channel();
register(
"task-session".into(),
@@ -191,7 +195,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
Some("subsess-a".into()),
test_workspace(),
None,
- RunQueue::new(),
+ run_queue(),
dummy_abort(),
rx_a,
);
@@ -204,7 +208,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
Some("subsess-b".into()),
test_workspace(),
None,
- RunQueue::new(),
+ run_queue(),
dummy_abort(),
rx_b,
);
@@ -218,7 +222,7 @@ async fn snapshot_and_block_scope_to_parent_and_reflect_live_status() {
Some("subsess-other".into()),
test_workspace(),
None,
- RunQueue::new(),
+ run_queue(),
dummy_abort(),
rx_other,
);
@@ -325,7 +329,7 @@ async fn resume_ref_for_task_includes_resume_fields_and_enforces_ownership() {
Some("subsess-resume".into()),
test_workspace(),
Some("thread-1".into()),
- RunQueue::new(),
+ run_queue(),
dummy_abort(),
rx,
);
@@ -361,7 +365,7 @@ async fn task_id_for_session_prefers_live_task_over_terminal_task() {
Some("subsess-live".into()),
test_workspace(),
Some("thread-1".into()),
- RunQueue::new(),
+ run_queue(),
dummy_abort(),
old_rx,
);
@@ -378,7 +382,7 @@ async fn task_id_for_session_prefers_live_task_over_terminal_task() {
Some("subsess-live".into()),
test_workspace(),
Some("thread-1".into()),
- RunQueue::new(),
+ run_queue(),
dummy_abort(),
new_rx,
);
@@ -394,7 +398,7 @@ async fn task_id_for_session_prefers_live_task_over_terminal_task() {
#[tokio::test]
async fn wait_returns_completion_once_published() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let tx = register_test("task-wait", "session-A", rq);
tokio::spawn(async move {
@@ -427,7 +431,7 @@ async fn wait_returns_completion_once_published() {
#[tokio::test]
async fn wait_times_out_and_leaves_entry_intact() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let _tx = register_test("task-slow", "session-A", rq);
let outcome = wait("task-slow", "session-A", Duration::from_millis(20))
@@ -443,7 +447,7 @@ async fn wait_times_out_and_leaves_entry_intact() {
"task-slow",
"session-A",
"still here".into(),
- QueueMode::Steer
+ QueueLane::Steer
)
.await
.is_ok());
@@ -453,7 +457,7 @@ async fn wait_times_out_and_leaves_entry_intact() {
#[tokio::test]
async fn cancel_for_thread_aborts_only_matching_entries() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let _a = register_test_with_thread("task-tA-1", "session-A", Some("thread-X"), rq.clone());
let _b = register_test_with_thread("task-tA-2", "session-A", Some("thread-X"), rq.clone());
// Different thread — must survive.
@@ -466,20 +470,20 @@ async fn cancel_for_thread_aborts_only_matching_entries() {
// The two cancelled entries are gone (steer can't find them).
assert_eq!(
- steer("task-tA-1", "session-A", "x".into(), QueueMode::Steer).await,
+ steer("task-tA-1", "session-A", "x".into(), QueueLane::Steer).await,
Err(SteerError::Unknown)
);
assert_eq!(
- steer("task-tA-2", "session-A", "x".into(), QueueMode::Steer).await,
+ steer("task-tA-2", "session-A", "x".into(), QueueLane::Steer).await,
Err(SteerError::Unknown)
);
// Non-matching entries stay live and steerable.
- assert!(steer("task-tB", "session-A", "x".into(), QueueMode::Steer)
+ assert!(steer("task-tB", "session-A", "x".into(), QueueLane::Steer)
.await
.is_ok());
assert!(
- steer("task-headless", "session-A", "x".into(), QueueMode::Steer)
+ steer("task-headless", "session-A", "x".into(), QueueLane::Steer)
.await
.is_ok()
);
@@ -494,7 +498,7 @@ async fn cancel_for_thread_aborts_only_matching_entries() {
#[tokio::test]
async fn cancel_by_task_returns_metadata_and_removes_entry() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let _tx = register_test_with_thread("task-cbt", "session-Z", Some("thread-cbt"), rq.clone());
let task_id = TaskId::new("task-cbt");
shared_steering_registry().register(task_id.clone(), SteeringHandle::allow_all());
@@ -510,7 +514,7 @@ async fn cancel_by_task_returns_metadata_and_removes_entry() {
// Entry is gone — steer can no longer find it, and a second cancel is a no-op.
assert_eq!(
- steer("task-cbt", "session-Z", "x".into(), QueueMode::Steer).await,
+ steer("task-cbt", "session-Z", "x".into(), QueueLane::Steer).await,
Err(SteerError::Unknown)
);
assert!(cancel_by_task("task-cbt").is_none());
@@ -521,7 +525,7 @@ async fn cancel_by_task_returns_metadata_and_removes_entry() {
#[tokio::test]
async fn cancel_all_clears_everything() {
let _guard = test_guard();
- let rq = RunQueue::new();
+ let rq = run_queue();
let _a = register_test_with_thread("task-all-1", "session-A", Some("thread-1"), rq.clone());
// Headless (no parent thread) — aborted, but contributes no thread id.
let _b = register_test_with_thread("task-all-2", "session-B", None, rq);
@@ -537,11 +541,11 @@ async fn cancel_all_clears_everything() {
);
assert_eq!(
- steer("task-all-1", "session-A", "x".into(), QueueMode::Steer).await,
+ steer("task-all-1", "session-A", "x".into(), QueueLane::Steer).await,
Err(SteerError::Unknown)
);
assert_eq!(
- steer("task-all-2", "session-B", "x".into(), QueueMode::Steer).await,
+ steer("task-all-2", "session-B", "x".into(), QueueLane::Steer).await,
Err(SteerError::Unknown)
);
// Registry is empty now.
diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_control.rs b/crates/openhuman-core/src/agent/orchestration/subagent_control.rs
index a79e01d110..f76d2ffd68 100644
--- a/crates/openhuman-core/src/agent/orchestration/subagent_control.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_control.rs
@@ -16,12 +16,12 @@
use serde_json::{json, Map, Value};
-use crate::agent::harness::run_queue::QueueMode;
use crate::agent::orchestration::running_subagents::SteerError;
use crate::agent::orchestration::{background_completions, running_subagents, subagent_sessions};
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
use crate::rpc::RpcOutcome;
+use tinyagents_harness::run_queue::QueueLane;
/// Controller schemas exposed for detached sub-agent control.
pub fn all_controller_schemas() -> Vec<ControllerSchema> {
@@ -160,9 +160,9 @@ fn handle_subagent_steer(params: Map<String, Value>) -> ControllerFuture {
let cid = new_correlation_id();
let task_id = require_str(&params, "taskId")?;
let message = require_str(&params, "message")?;
- let mode = match opt_str(&params, "mode").as_deref() {
- Some("collect") => QueueMode::Collect,
- _ => QueueMode::Steer,
+ let (lane, mode) = match opt_str(&params, "mode").as_deref() {
+ Some("collect") => (QueueLane::Collect, "collect"),
+ _ => (QueueLane::Steer, "steer"),
};
log::debug!(
target: "subagent_control_rpc",
@@ -170,13 +170,13 @@ fn handle_subagent_steer(params: Map<String, Value>) -> ControllerFuture {
message.chars().count()
);
- match running_subagents::steer_control(&task_id, message, mode).await {
+ match running_subagents::steer_control(&task_id, message, lane).await {
Ok(()) => {
log::debug!(
target: "subagent_control_rpc",
"[subagent_control_rpc][{cid}] steer.done task_id={task_id} mode={mode} steered=true"
);
- to_json(json!({ "steered": true, "taskId": task_id, "mode": mode.to_string() }))
+ to_json(json!({ "steered": true, "taskId": task_id, "mode": mode }))
}
Err(err) => {
let reason = match err {
@@ -189,6 +189,7 @@ fn handle_subagent_steer(params: Map<String, Value>) -> ControllerFuture {
// ownership and returns `NotOwned`. Kept here for the Phase 4
// SteeringRegistry ownership consolidation.
SteerError::NotOwned => "not_owned",
+ SteerError::UnsupportedLane => "unsupported_lane",
};
log::debug!(
target: "subagent_control_rpc",
@@ -197,7 +198,7 @@ fn handle_subagent_steer(params: Map<String, Value>) -> ControllerFuture {
to_json(json!({
"steered": false,
"taskId": task_id,
- "mode": mode.to_string(),
+ "mode": mode,
"reason": reason,
}))
}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs
index f59b9c8338..e897ab8224 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs
@@ -5,7 +5,6 @@
//! events and, when possible, persisted in the child worker thread.
use crate::agent::harness::definition::AgentDefinitionRegistry;
-use crate::agent::harness::run_queue::RunQueue;
use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunOptions, SubagentRunStatus};
use crate::agent::messages::ChatMessage;
use crate::agent::orchestration::running_subagents::{self, SubagentStatus};
@@ -19,6 +18,7 @@ use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
use tinyagents_harness::context::RunContext;
+use tinyagents_harness::run_queue::RunQueue;
use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
use tinytools::ToolRunContext;
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs
index 0c7ebc881c..99e7aa3c36 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs
@@ -226,7 +226,7 @@ impl SpawnAsyncSubagentTool {
running_task_id,
&parent_session,
follow_up_prompt.clone(),
- crate::agent::harness::run_queue::QueueMode::Steer,
+ tinyagents_harness::run_queue::QueueLane::Steer,
)
.await
{
@@ -379,7 +379,7 @@ impl SpawnAsyncSubagentTool {
// this run mid-flight and `wait_subagent` for its result. The engine
// drains `steer_queue` at iteration boundaries; `status_tx` publishes
// the terminal state to any waiter.
- let steer_queue = RunQueue::new();
+ let steer_queue = Arc::new(RunQueue::new());
let task_queue = steer_queue.clone();
let (status_tx, status_rx) = running_subagents::status_channel();
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.rs
index a8cb91faae..287d699df9 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.rs
@@ -8,12 +8,12 @@
//! without waiting for it to finish or restarting it. Mirrors Codex `send_input`.
use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::harness::run_queue::QueueMode;
use crate::agent::orchestration::running_subagents::{self, SteerError};
use async_trait::async_trait;
use serde_json::json;
use std::sync::Arc;
use tinyagents_harness::context::RunContext;
+use tinyagents_harness::run_queue::QueueLane;
use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
@@ -131,9 +131,9 @@ impl SteerSubagentTool {
.unwrap_or("")
.trim()
.to_string();
- let mode = match args.get("mode").and_then(|v| v.as_str()).unwrap_or("steer") {
- "collect" => QueueMode::Collect,
- _ => QueueMode::Steer,
+ let (lane, mode) = match args.get("mode").and_then(|v| v.as_str()).unwrap_or("steer") {
+ "collect" => (QueueLane::Collect, "collect"),
+ _ => (QueueLane::Steer, "steer"),
};
if task_id.is_empty() && subagent_session_id.is_empty() {
@@ -189,7 +189,7 @@ impl SteerSubagentTool {
message.chars().count()
);
- match running_subagents::steer(&resolved_task_id, &parent_session, message, mode).await {
+ match running_subagents::steer(&resolved_task_id, &parent_session, message, lane).await {
Ok(()) => Ok(ToolResult::success(format!(
"Steered sub-agent `{resolved_task_id}` ({mode}). It will pick this up at its next step. \
Use wait_subagent with its subagent_session_id or task_id to collect its result."
@@ -204,6 +204,9 @@ impl SteerSubagentTool {
Err(SteerError::AlreadyDone) => Ok(ToolResult::error(format!(
"steer_subagent: sub-agent `{resolved_task_id}` has already finished. Use wait_subagent to collect its result."
))),
+ Err(SteerError::UnsupportedLane) => Ok(ToolResult::error(
+ "steer_subagent: only steer and collect messages can be delivered to a running sub-agent",
+ )),
}
}
}
diff --git a/crates/openhuman-core/src/agent/queued_turn.rs b/crates/openhuman-core/src/agent/queued_turn.rs
new file mode 100644
index 0000000000..d2128974b8
--- /dev/null
+++ b/crates/openhuman-core/src/agent/queued_turn.rs
@@ -0,0 +1,20 @@
+//! Host-owned payload for a message queued while an agent turn is active.
+//!
+//! TinyAgents owns the queue mechanics and its [`QueueLane`](tinyagents_harness::run_queue::QueueLane)
+//! selects how this payload is consumed. OpenHuman retains the web and
+//! orchestration metadata needed to dispatch a deferred follow-up turn.
+
+/// A queued OpenHuman turn input.
+///
+/// The payload deliberately does not carry a lane: lane selection is made at
+/// the host boundary when the item is pushed into TinyAgents' `RunQueue`.
+#[derive(Debug, Clone)]
+pub struct QueuedTurn {
+ pub text: String,
+ pub client_id: String,
+ pub thread_id: String,
+ pub queued_at_ms: u64,
+ pub model_override: Option<String>,
+ pub temperature: Option<f64>,
+ pub locale: Option<String>,
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs
index b85c430808..0ac3175938 100644
--- a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs
@@ -24,15 +24,15 @@
//! is held across the drive future, cleanup happens identically on normal
//! return, error, and drop-cancellation.
-use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use tinyagents_harness::ids::TaskId;
+use tinyagents_harness::run_queue::{QueueLane, RunQueue};
use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};
use tinyinference_llm::message::Message as TaMessage;
-use crate::agent::harness::run_queue::{QueueMode, QueuedMessage, RunQueue};
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
@@ -73,8 +73,12 @@ fn now_ms() -> u64 {
/// bridge behind the `steer_subagent` / mid-flight-steering feature. Emits a
/// [`DomainEvent::RunQueueMessageDelivered`] when at least one message is
/// delivered so the delivery is visible in the event stream (issue #4456).
-pub(super) async fn forward_steers(queue: &RunQueue, handle: &SteeringHandle, thread_label: &str) {
- let drained = queue.drain_steers().await;
+pub(super) async fn forward_steers(
+ queue: &RunQueue<crate::agent::queued_turn::QueuedTurn>,
+ handle: &SteeringHandle,
+ thread_label: &str,
+) {
+ let drained = queue.drain(QueueLane::Steer).await;
if drained.is_empty() {
return;
}
@@ -98,16 +102,16 @@ pub(super) async fn forward_steers(queue: &RunQueue, handle: &SteeringHandle, th
}
/// Forward any queued **collect** messages (orchestrator/monitor lines enqueued
-/// via `QueueMode::Collect`) into the run as injected user turns so they reach
+/// via the collect queue lane into the run as injected user turns so they reach
/// the next LLM call as additional context. Mirrors the legacy
/// `[Additional context from user]:` framing the model was taught to read. Emits
/// a [`DomainEvent::RunQueueMessageDelivered`] on delivery (issue #4456).
pub(super) async fn forward_collects(
- queue: &RunQueue,
+ queue: &RunQueue<crate::agent::queued_turn::QueuedTurn>,
handle: &SteeringHandle,
thread_label: &str,
) {
- let drained = queue.drain_collects().await;
+ let drained = queue.drain(QueueLane::Collect).await;
if drained.is_empty() {
return;
}
@@ -144,7 +148,7 @@ pub(super) struct SteeringForwarderGuard {
handle: SteeringHandle,
/// The session-owned run queue, used to requeue residual steers on drop.
/// `None` after the requeue so a double-drop is a no-op.
- run_queue: Option<Arc<RunQueue>>,
+ run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
/// The steering-registry key to deregister on drop (sub-agent runs only).
registry_task_id: Option<TaskId>,
/// Best-effort thread label for observability + requeued-message metadata.
@@ -163,7 +167,7 @@ impl SteeringForwarderGuard {
/// steering registry) and `None` for the interactive parent turn.
pub(super) fn new(
handle: SteeringHandle,
- run_queue: Option<Arc<RunQueue>>,
+ run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
registry_task_id: Option<TaskId>,
thread_label: String,
) -> Self {
@@ -225,7 +229,7 @@ impl Drop for SteeringForwarderGuard {
// Control-flow-only commands (Pause/Resume/Cancel/…) are meaningless
// once the run is gone and are intentionally dropped.
let residual = self.handle.drain();
- let requeue_texts: Vec<(String, QueueMode)> = residual
+ let requeue_texts: Vec<(String, QueueLane)> = residual
.into_iter()
.filter_map(|cmd| match cmd {
SteeringCommand::InjectMessage(msg) => {
@@ -236,11 +240,11 @@ impl Drop for SteeringForwarderGuard {
// re-labeled as user Steer. Default to Steer when neither
// prefix is present (a raw steer that was never framed).
if let Some(rest) = text.strip_prefix(STEER_PREFIX) {
- Some((rest.to_string(), QueueMode::Steer))
+ Some((rest.to_string(), QueueLane::Steer))
} else if let Some(rest) = text.strip_prefix(COLLECT_PREFIX) {
- Some((rest.to_string(), QueueMode::Collect))
+ Some((rest.to_string(), QueueLane::Collect))
} else {
- Some((text.to_string(), QueueMode::Steer))
+ Some((text.to_string(), QueueLane::Steer))
}
}
_ => None,
@@ -265,18 +269,20 @@ impl Drop for SteeringForwarderGuard {
Ok(rt) => {
let label = thread_label.clone();
rt.spawn(async move {
- for (text, mode) in requeue_texts {
+ for (text, lane) in requeue_texts {
queue
- .push(QueuedMessage {
- text,
- mode,
- client_id: String::new(),
- thread_id: label.clone(),
- queued_at_ms: now_ms(),
- model_override: None,
- temperature: None,
- locale: None,
- })
+ .push(
+ lane,
+ crate::agent::queued_turn::QueuedTurn {
+ text,
+ client_id: String::new(),
+ thread_id: label.clone(),
+ queued_at_ms: now_ms(),
+ model_override: None,
+ temperature: None,
+ locale: None,
+ },
+ )
.await;
}
});
@@ -305,3 +311,99 @@ impl Drop for SteeringForwarderGuard {
});
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tinyagents_harness::context::{RunConfig, RunContext};
+ use tinyagents_harness::runtime::AgentHarness;
+ use tinyagents_harness::testkit::ScriptedModel;
+
+ #[tokio::test]
+ async fn residual_collect_requeues_to_its_original_lane() {
+ let queue = Arc::new(RunQueue::new());
+ let handle = SteeringHandle::allow_all();
+ let guard = SteeringForwarderGuard::new(
+ handle.clone(),
+ Some(queue.clone()),
+ None,
+ "thread-test".to_string(),
+ );
+ handle.send(SteeringCommand::InjectMessage(TaMessage::user(format!(
+ "{COLLECT_PREFIX}recovered context"
+ ))));
+
+ drop(guard);
+ tokio::time::timeout(Duration::from_secs(1), async {
+ loop {
+ if queue.status().await.collects == 1 {
+ return;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("residual collect should be requeued before timeout");
+
+ assert!(queue.drain(QueueLane::Steer).await.is_empty());
+ let recovered = queue.drain(QueueLane::Collect).await;
+ assert_eq!(recovered.len(), 1);
+ assert_eq!(recovered[0].text, "recovered context");
+ }
+
+ #[tokio::test]
+ async fn collect_reaches_the_next_model_boundary_as_additional_context() {
+ let queue = Arc::new(RunQueue::new());
+ queue
+ .push(
+ QueueLane::Collect,
+ crate::agent::queued_turn::QueuedTurn {
+ text: "the deployment finished successfully".to_string(),
+ client_id: "client-test".to_string(),
+ thread_id: "thread-test".to_string(),
+ queued_at_ms: 1,
+ model_override: None,
+ temperature: None,
+ locale: None,
+ },
+ )
+ .await;
+ let handle = SteeringHandle::allow_all();
+
+ // This is the OpenHuman bridge at the safe boundary immediately before
+ // a harness model call. The assertion below observes the actual model
+ // request, not just queue status or the steering handle's contents.
+ forward_collects(&queue, &handle, "thread-test").await;
+
+ let model = Arc::new(ScriptedModel::replies(vec!["done"]));
+ let mut harness: AgentHarness<()> = AgentHarness::new();
+ harness
+ .register_model("scripted", model.clone())
+ .set_default_model("scripted");
+ harness
+ .invoke_in_context(
+ &(),
+ RunContext::new(RunConfig::new("collect-boundary"), ()).with_steering(handle),
+ vec![TaMessage::user("start")],
+ )
+ .await
+ .expect("collect-context run should complete");
+
+ let requests = model.requests();
+ assert_eq!(requests.len(), 1, "one model boundary should be crossed");
+ let collect = requests[0]
+ .messages
+ .iter()
+ .find(|message| message.text().contains("deployment finished successfully"))
+ .expect("the next model request should contain the collected context");
+ assert!(matches!(collect, TaMessage::User(_)));
+ assert_eq!(
+ collect.text(),
+ "[Additional context from user]: the deployment finished successfully"
+ );
+ assert!(
+ !collect.text().starts_with(STEER_PREFIX),
+ "collect must be context, not a steering instruction"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
index cc16309ff1..219d47a052 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
@@ -27,7 +27,7 @@ use tinyagents_harness::store::StoreRegistry;
use tinyagents_registry::DiagnosticSeverity;
use crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;
-use crate::agent::harness::{run_queue::RunQueue, MAX_SPAWN_DEPTH};
+use crate::agent::harness::MAX_SPAWN_DEPTH;
use crate::agent::messages::ChatMessage;
use crate::agent::tinyagents::harness_assembly::{assemble_turn_harness, AssembledTurnHarness};
use crate::agent::tinyagents::host::steering::shared_steering_registry;
@@ -41,6 +41,7 @@ use crate::agent::tinyagents::turn_run_error::map_turn_run_error;
use crate::agent::tinyagents::turn_run_finalize::finalize_turn_outcome;
use crate::agent::tinyagents::{journal, routes, steering_forwarder};
use tinyagents_harness::ids::TaskId;
+use tinyagents_harness::run_queue::RunQueue;
use super::ToolPolicyEnforcement;
@@ -252,7 +253,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(
max_iterations: usize,
subagent_scope: Option<SubagentScope>,
context_window: Option<u64>,
- run_queue: Option<Arc<RunQueue>>,
+ run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
early_exit_tools: &[&str],
pause_at_cap: bool,
max_output_tokens: Option<u32>,
@@ -312,7 +313,7 @@ pub(crate) async fn run_root_turn_via_hosted_agent(
allowed: Option<HashSet<String>>,
max_iterations: usize,
context_window: Option<u64>,
- run_queue: Option<Arc<RunQueue>>,
+ run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
early_exit_tools: &[&str],
pause_at_cap: bool,
max_output_tokens: Option<u32>,
@@ -356,7 +357,7 @@ async fn run_turn_via_tinyagents_inner(
max_iterations: usize,
subagent_scope: Option<SubagentScope>,
context_window: Option<u64>,
- run_queue: Option<Arc<RunQueue>>,
+ run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,
early_exit_tools: &[&str],
pause_at_cap: bool,
max_output_tokens: Option<u32>,
diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rs
index 49806ee97f..882eb52ccf 100644
--- a/crates/openhuman-core/src/web_chat/mod.rs
+++ b/crates/openhuman-core/src/web_chat/mod.rs
@@ -42,9 +42,10 @@ pub(crate) use web_errors::classify_inference_error;
#[cfg(any(test, debug_assertions))]
#[allow(unused_imports)]
pub(crate) use web_errors::{
- extract_provider_error_detail, extract_provider_name, generic_inference_error_user_message,
- is_action_budget_exhausted, is_fallback_chain_exhausted, is_non_retryable_rate_limit_text,
- parse_retry_after_secs_from_str, retry_after_hint, with_provider_detail, ClassifiedError,
+ ClassifiedError, extract_provider_error_detail, extract_provider_name,
+ generic_inference_error_user_message, is_action_budget_exhausted, is_fallback_chain_exhausted,
+ is_non_retryable_rate_limit_text, parse_retry_after_secs_from_str, retry_after_hint,
+ with_provider_detail,
};
// Public API — event bus
@@ -60,6 +61,8 @@ pub use event_bus::{
pub use event_bus::fresh_approval_surface_subscription;
// Public API — operations
+#[cfg(test)]
+pub use ops::drain_queued_turns_for_test;
#[cfg(any(test, debug_assertions))]
pub use ops::parallel_in_flight_entries_for_test;
pub use ops::{
@@ -105,11 +108,11 @@ pub(crate) use web_errors::{
// Test helpers (debug/test builds only)
#[cfg(any(test, debug_assertions))]
-pub use ops::set_test_forced_run_chat_task_error;
-#[cfg(any(test, debug_assertions))]
pub use ops::RUN_CHAT_TASK_TEST_LOCK;
#[cfg(any(test, debug_assertions))]
-pub use ops::{set_test_run_chat_task_block, TestRunChatTaskBlock};
+pub use ops::set_test_forced_run_chat_task_error;
+#[cfg(any(test, debug_assertions))]
+pub use ops::{TestRunChatTaskBlock, set_test_run_chat_task_block};
#[cfg(any(test, debug_assertions))]
#[path = "mod_test_support_tests.rs"]
diff --git a/crates/openhuman-core/src/web_chat/ops.rs b/crates/openhuman-core/src/web_chat/ops.rs
index 020f2f37f5..7bad3de183 100644
--- a/crates/openhuman-core/src/web_chat/ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops.rs
@@ -13,8 +13,8 @@ mod test_hooks;
mod turn_guards;
pub(super) use budget_correlation::{
- classify_budget_correlation, clear_budget_signal, has_fresh_budget_signal,
- record_budget_signal, BudgetCorrelation,
+ BudgetCorrelation, classify_budget_correlation, clear_budget_signal, has_fresh_budget_signal,
+ record_budget_signal,
};
pub use channel_ops::{
@@ -24,20 +24,22 @@ pub use channel_ops::{
pub use start_chat::start_chat;
+pub(super) use state::THREAD_SESSIONS;
+#[cfg(test)]
+pub use state::drain_queued_turns_for_test;
#[cfg(any(test, debug_assertions))]
pub use state::parallel_in_flight_entries_for_test;
-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};
-#[cfg(any(test, debug_assertions))]
-pub use test_hooks::set_test_forced_run_chat_task_error;
#[cfg(any(test, debug_assertions))]
pub use test_hooks::RUN_CHAT_TASK_TEST_LOCK;
#[cfg(any(test, debug_assertions))]
-pub use test_hooks::{set_test_run_chat_task_block, TestRunChatTaskBlock};
+pub use test_hooks::set_test_forced_run_chat_task_error;
#[cfg(any(test, debug_assertions))]
pub(super) use test_hooks::{TEST_FORCED_RUN_CHAT_TASK_ERROR, TEST_RUN_CHAT_TASK_BLOCK};
+#[cfg(any(test, debug_assertions))]
+pub use test_hooks::{TestRunChatTaskBlock, set_test_run_chat_task_block};
pub(crate) use turn_guards::sentry_suppression_reason;
#[cfg(test)]
diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
index 84b1482fe6..ede09ad06a 100644
--- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
+++ b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
@@ -2,8 +2,10 @@
//! already in flight on a thread, and the request- or thread-scoped
//! cancellation paths that tear them down.
+use std::sync::Arc;
use std::time::Duration;
+use tinyagents_harness::run_queue::RunQueue;
use tokio_util::sync::CancellationToken;
use crate::core::socketio::WebChannelEvent;
@@ -43,7 +45,7 @@ pub(crate) async fn spawn_parallel_turn(
let user_message = message.to_string();
// Forked turns don't participate in the steer/followup/collect queue, but
// `run_chat_task` requires a queue handle — give each its own.
- let run_queue = crate::agent::harness::run_queue::RunQueue::new();
+ let run_queue = Arc::new(RunQueue::new());
let handle = tokio::spawn(crate::core::runtime::context::CoreContext::propagate(
async move {
@@ -93,16 +95,16 @@ pub(crate) async fn spawn_parallel_turn(
}
Some(Err(err)) => {
log::warn!(
- "[web-channel] parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",
- client_id_task,
- thread_id_task,
- request_id_task,
- err
- );
+ "[web-channel] parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",
+ client_id_task,
+ thread_id_task,
+ request_id_task,
+ err
+ );
let detailed = format!(
- "parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",
- client_id_task, thread_id_task, request_id_task, err
- );
+ "parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",
+ client_id_task, thread_id_task, request_id_task, err
+ );
let classified = classify_inference_error(&err);
let classified_type = classified.error_type;
@@ -164,10 +166,10 @@ pub(crate) async fn spawn_parallel_turn(
}
None => {
log::info!(
- "[web-channel] parallel turn cancelled cooperatively thread_id={} request_id={}",
- thread_id_task,
- request_id_task
- );
+ "[web-channel] parallel turn cancelled cooperatively thread_id={} request_id={}",
+ thread_id_task,
+ request_id_task
+ );
}
}
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 8dd6b5e85d..5ce8f62437 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -4,21 +4,23 @@
//! classifies and reports a failure.
use serde_json::json;
+use std::sync::Arc;
+use tinyagents_harness::run_queue::{QueueLane, RunQueue};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use crate::core::events::DomainEvent;
use crate::core::socketio::WebChannelEvent;
use crate::security::prompt_injection::{
- enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,
+ PromptEnforcementAction, PromptEnforcementContext, enforce_prompt_input,
};
use super::super::event_bus::publish_web_channel_event;
use super::super::run_task::run_chat_task;
-use super::super::types::{ChatRequestMetadata, InFlightEntry};
+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::{IN_FLIGHT, cancel_in_flight_gracefully, key_for};
use super::turn_guards::{
run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,
};
@@ -223,20 +225,17 @@ pub async fn start_chat(
let map_key = key_for(&thread_id);
let parsed_mode = match queue_mode.as_deref() {
- Some("steer") => crate::agent::harness::run_queue::QueueMode::Steer,
- Some("followup") => crate::agent::harness::run_queue::QueueMode::Followup,
- Some("collect") => crate::agent::harness::run_queue::QueueMode::Collect,
- Some("parallel") => crate::agent::harness::run_queue::QueueMode::Parallel,
- _ => crate::agent::harness::run_queue::QueueMode::Interrupt,
+ Some("steer") => QueueMode::Steer,
+ Some("followup") => QueueMode::Followup,
+ Some("collect") => QueueMode::Collect,
+ Some("parallel") => QueueMode::Parallel,
+ _ => QueueMode::Interrupt,
};
// Parallel mode: spawn an independent forked turn that runs alongside any
// in-flight turn for this thread. It does not touch IN_FLIGHT (no
// interrupt/steer/queue) — it lives in its own request-keyed lane.
- if matches!(
- parsed_mode,
- crate::agent::harness::run_queue::QueueMode::Parallel
- ) {
+ if matches!(parsed_mode, QueueMode::Parallel) {
log::info!(
"[web-channel] starting PARALLEL forked turn thread_id={} request_id={}",
thread_id,
@@ -257,15 +256,11 @@ pub async fn start_chat(
}
// Non-interrupt modes: push into the running turn's queue and return.
- if !matches!(
- parsed_mode,
- crate::agent::harness::run_queue::QueueMode::Interrupt
- ) {
+ if !matches!(parsed_mode, QueueMode::Interrupt) {
let in_flight = IN_FLIGHT.lock().await;
if let Some(existing) = in_flight.get(&map_key) {
- let queued_msg = crate::agent::harness::run_queue::QueuedMessage {
+ let queued_msg = crate::agent::queued_turn::QueuedTurn {
text: message.clone(),
- mode: parsed_mode,
client_id: client_id.clone(),
thread_id: thread_id.clone(),
queued_at_ms: std::time::SystemTime::now()
@@ -276,7 +271,10 @@ pub async fn start_chat(
temperature,
locale: locale.clone(),
};
- existing.run_queue.push(queued_msg).await;
+ let lane = parsed_mode
+ .queue_lane()
+ .expect("only queueable modes reach an active run queue");
+ existing.run_queue.push(lane, queued_msg).await;
let status = existing.run_queue.status().await;
log::info!(
"[web-channel] queued {} message thread_id={} request_id={} queue_depth={}",
@@ -333,7 +331,7 @@ pub async fn start_chat(
}
}
- let turn_run_queue = crate::agent::harness::run_queue::RunQueue::new();
+ let turn_run_queue = Arc::new(RunQueue::new());
let turn_run_queue_task = turn_run_queue.clone();
let client_id_task = client_id.clone();
@@ -385,11 +383,11 @@ pub async fn start_chat(
Some(res) => res,
None => {
log::info!(
- "[web-channel] turn cancelled cooperatively client_id={} thread_id={} request_id={}",
- client_id_task,
- thread_id_task,
- request_id_task
- );
+ "[web-channel] turn cancelled cooperatively client_id={} thread_id={} request_id={}",
+ client_id_task,
+ thread_id_task,
+ request_id_task
+ );
// 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.
@@ -421,12 +419,12 @@ pub async fn start_chat(
}
Err(err) => {
log::warn!(
- "[web-channel] run_chat_task failed client_id={} thread_id={} request_id={} error={}",
- client_id_task,
- thread_id_task,
- request_id_task,
- err
- );
+ "[web-channel] run_chat_task failed client_id={} thread_id={} request_id={} error={}",
+ client_id_task,
+ thread_id_task,
+ request_id_task,
+ err
+ );
let detailed = format!(
"run_chat_task failed client_id={} thread_id={} request_id={} error={}",
client_id_task, thread_id_task, request_id_task, err
@@ -485,7 +483,7 @@ pub async fn start_chat(
let mut in_flight = IN_FLIGHT.lock().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_followups().await;
+ let fups = current.run_queue.drain(QueueLane::Followup).await;
in_flight.remove(&map_key_task);
fups
} else {
@@ -529,7 +527,7 @@ pub async fn start_chat(
Ok(request_id)
}
-fn dispatch_followups(followups: Vec<crate::agent::harness::run_queue::QueuedMessage>) {
+fn dispatch_followups(followups: Vec<crate::agent::queued_turn::QueuedTurn>) {
for fup in followups {
tokio::spawn(crate::core::runtime::context::CoreContext::propagate(
async move {
diff --git a/crates/openhuman-core/src/web_chat/ops/state.rs b/crates/openhuman-core/src/web_chat/ops/state.rs
index 277f27cd83..3f055a8e23 100644
--- a/crates/openhuman-core/src/web_chat/ops/state.rs
+++ b/crates/openhuman-core/src/web_chat/ops/state.rs
@@ -88,6 +88,22 @@ pub async fn in_flight_entries_for_test() -> Vec<(String, String)> {
.collect()
}
+/// Test-only host-routing seam: drain one lane from the active turn's real
+/// TinyAgents queue so acceptance tests can assert that web metadata survives
+/// queue admission. Production code only observes this queue through its
+/// status and terminal dispatch paths.
+#[cfg(test)]
+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;
+ match guard.get(&key_for(thread_id)) {
+ Some(entry) => entry.run_queue.drain(lane).await,
+ None => Vec::new(),
+ }
+}
+
/// 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)> {
diff --git a/crates/openhuman-core/src/web_chat/ops/test_hooks.rs b/crates/openhuman-core/src/web_chat/ops/test_hooks.rs
index d52f1857a0..f8dd305174 100644
--- a/crates/openhuman-core/src/web_chat/ops/test_hooks.rs
+++ b/crates/openhuman-core/src/web_chat/ops/test_hooks.rs
@@ -20,6 +20,9 @@ pub(crate) static TEST_FORCED_RUN_CHAT_TASK_ERROR: Lazy<Mutex<Option<String>>> =
pub struct TestRunChatTaskBlock {
pub started: std::sync::Arc<std::sync::atomic::AtomicBool>,
pub dropped: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ /// 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>,
}
#[cfg(any(test, debug_assertions))]
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index b169cf7843..9af1b360a2 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -5,11 +5,12 @@
//! (`ops/start_chat.rs`/`ops/parallel_turn.rs`) once the message has been validated.
use std::sync::Arc;
+use tinyagents_harness::run_queue::RunQueue;
use crate::config::rpc as config_rpc;
use crate::threads::turn_state::TurnStateStore;
-use super::ops::{key_for, BudgetCorrelation, THREAD_SESSIONS};
+use super::ops::{BudgetCorrelation, THREAD_SESSIONS, key_for};
use super::progress_bridge::spawn_progress_bridge;
use super::session::{
build_session_agent, build_session_fingerprint, normalize_model_override, pick_target_agent_id,
@@ -33,7 +34,7 @@ pub(crate) async fn run_chat_task(
model_override: Option<String>,
temperature: Option<f64>,
locale: Option<String>,
- run_queue: Arc<crate::agent::harness::run_queue::RunQueue>,
+ run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
metadata: ChatRequestMetadata,
// When true, run as an isolated fork: build a fresh agent seeded from the
// thread's history-at-start and never touch the shared `THREAD_SESSIONS`
@@ -84,8 +85,14 @@ pub(crate) async fn run_chat_task(
block
.started
.store(true, std::sync::atomic::Ordering::SeqCst);
- tokio::time::sleep(std::time::Duration::from_secs(30)).await;
- return Err("test block elapsed".to_string());
+ tokio::select! {
+ _ = block.release.notified() => {
+ return 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/types.rs b/crates/openhuman-core/src/web_chat/types.rs
index bca38bf481..fc9b4a5201 100644
--- a/crates/openhuman-core/src/web_chat/types.rs
+++ b/crates/openhuman-core/src/web_chat/types.rs
@@ -4,9 +4,48 @@
//! and the `channel.web_*` request param structs.
use serde::Deserialize;
+use tinyagents_harness::run_queue::QueueLane;
use crate::agent::Agent;
+/// How a web request arriving during an active turn is handled.
+///
+/// This is a web/orchestration disposition, not queue state. Only the three
+/// variants returned by [`Self::queue_lane`] are ever inserted into TinyAgents'
+/// run queue; interrupt and parallel are resolved by `start_chat` first.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(super) enum QueueMode {
+ #[default]
+ Interrupt,
+ Steer,
+ Followup,
+ Collect,
+ Parallel,
+}
+
+impl QueueMode {
+ pub(super) fn queue_lane(self) -> Option<QueueLane> {
+ match self {
+ Self::Steer => Some(QueueLane::Steer),
+ Self::Followup => Some(QueueLane::Followup),
+ Self::Collect => Some(QueueLane::Collect),
+ Self::Interrupt | Self::Parallel => None,
+ }
+ }
+}
+
+impl std::fmt::Display for QueueMode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(match self {
+ Self::Interrupt => "interrupt",
+ Self::Steer => "steer",
+ Self::Followup => "followup",
+ Self::Collect => "collect",
+ Self::Parallel => "parallel",
+ })
+ }
+}
+
/// All inputs that the cached `SessionEntry`'s `Agent` was built from,
/// captured at build time. The cache-hit predicate is a single
/// `entry.fingerprint == current_fingerprint` comparison — pulling the
@@ -41,7 +80,9 @@ pub(super) struct SessionEntry {
pub(super) struct InFlightEntry {
pub(super) request_id: String,
pub(super) handle: tokio::task::JoinHandle<()>,
- pub(super) run_queue: std::sync::Arc<crate::agent::harness::run_queue::RunQueue>,
+ pub(super) run_queue: std::sync::Arc<
+ tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>,
+ >,
/// Cooperative cancellation for this turn. Cancelling it makes the turn's
/// `tokio::select!` arm fire and drops the in-flight turn future (which
/// cancels the in-flight LLM request and releases locks at a safe await
diff --git a/crates/openhuman-core/src/web_chat/web_tests.rs b/crates/openhuman-core/src/web_chat/web_tests.rs
index cc8fabc1e9..7264560b95 100644
--- a/crates/openhuman-core/src/web_chat/web_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests.rs
@@ -1,19 +1,21 @@
use super::{
+ ChatRequestMetadata, ClassifiedError, TestRunChatTaskBlock, WebChatParams,
all_web_channel_controller_schemas, all_web_channel_registered_controllers, cancel_chat,
- classify_inference_error, compose_system_prompt_suffix, event_session_id_for,
- extract_provider_error_detail, generic_inference_error_user_message,
+ channel_web_cancel, channel_web_queue_clear, channel_web_queue_status,
+ classify_inference_error, compose_system_prompt_suffix, drain_queued_turns_for_test,
+ event_session_id_for, extract_provider_error_detail, generic_inference_error_user_message,
in_flight_entries_for_test, inference_budget_exceeded_user_message,
is_inference_budget_exceeded_error, json_output, key_for, locale_reply_directive,
normalize_model_override, optional_f64, optional_string, parallel_in_flight_entries_for_test,
provider_role_for_model_override, required_string, schemas, sentry_suppression_reason,
set_test_forced_run_chat_task_error, set_test_run_chat_task_block, start_chat,
- subscribe_web_channel_events, ChatRequestMetadata, ClassifiedError, TestRunChatTaskBlock,
- WebChatParams,
+ subscribe_web_channel_events,
};
use crate::core::TypeSchema;
-use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
-use tokio::time::{timeout, Duration};
+use std::sync::atomic::{AtomicBool, Ordering};
+use tinyagents_harness::run_queue::QueueLane;
+use tokio::time::{Duration, timeout};
// Serializes every test that drives `start_chat` with the process-global
// `run_chat_task` test hooks (forced error / forced block) or the
@@ -98,6 +100,7 @@ fn make_block() -> TestRunChatTaskBlock {
TestRunChatTaskBlock {
started: Arc::new(AtomicBool::new(false)),
dropped: Arc::new(AtomicBool::new(false)),
+ release: Arc::new(tokio::sync::Notify::new()),
}
}
@@ -118,6 +121,8 @@ async fn wait_for_parallel<F: Fn(&[(String, String)]) -> bool>(pred: F) -> Vec<(
#[path = "web_tests_error_code_classification_tests.rs"]
mod error_code_classification_tests;
+#[path = "web_tests_queue_acceptance_tests.rs"]
+mod queue_acceptance_tests;
#[path = "web_tests_rate_limit_classification_tests.rs"]
mod rate_limit_classification_tests;
#[path = "web_tests_session_and_concurrency_tests.rs"]
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.rs
new file mode 100644
index 0000000000..7255aa4224
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/web_tests_queue_acceptance_tests.rs
@@ -0,0 +1,319 @@
+use super::*;
+
+use serde_json::json;
+
+async fn start_parked_turn(thread_id: &str, block: &TestRunChatTaskBlock) -> String {
+ let request_id = start_chat(
+ "queue-test-client",
+ thread_id,
+ "primary turn",
+ None,
+ None,
+ None,
+ None,
+ ChatRequestMetadata::default(),
+ )
+ .await
+ .expect("primary turn should start");
+ wait_for_flag(&block.started, "primary turn started").await;
+ wait_for_in_flight(|entries| entries.iter().any(|(key, _)| key == thread_id)).await;
+ request_id
+}
+
+async fn queue_message(thread_id: &str, text: &str, mode: &str) -> serde_json::Value {
+ let response = start_chat(
+ "queue-test-client",
+ thread_id,
+ text,
+ Some("model-override".to_string()),
+ Some(0.7),
+ Some("ar".to_string()),
+ Some(mode.to_string()),
+ ChatRequestMetadata::default(),
+ )
+ .await
+ .expect("queued message should be accepted");
+ serde_json::from_str(&response).expect("queued result should be JSON")
+}
+
+async fn cancel_parked_turn(thread_id: &str, block: &TestRunChatTaskBlock) {
+ cancel_chat("queue-test-client", thread_id)
+ .await
+ .expect("parked turn should cancel");
+ wait_for_in_flight(|entries| !entries.iter().any(|(key, _)| key == thread_id)).await;
+ wait_for_flag(&block.dropped, "parked turn dropped during cleanup").await;
+ set_test_run_chat_task_block(None).await;
+}
+
+#[tokio::test]
+async fn web_queue_retains_typed_queued_turn_metadata() {
+ let _serial = FORCED_ERROR_TEST_LOCK.lock().await;
+ let block = make_block();
+ set_test_run_chat_task_block(Some(block.clone())).await;
+ let thread_id = "queue-typed-retention";
+ start_parked_turn(thread_id, &block).await;
+
+ let accepted = queue_message(thread_id, "defer this exact payload", "followup").await;
+ assert_eq!(accepted["queued"], true);
+ assert_eq!(accepted["queue_mode"], "followup");
+
+ // This drains the actual in-flight host queue, not a standalone
+ // RunQueue<String>, proving the concrete public DTO survives admission.
+ let queued = drain_queued_turns_for_test(thread_id, QueueLane::Followup).await;
+ assert_eq!(queued.len(), 1);
+ let queued = &queued[0];
+ assert_eq!(queued.text, "defer this exact payload");
+ assert_eq!(queued.client_id, "queue-test-client");
+ assert_eq!(queued.thread_id, thread_id);
+ assert!(queued.queued_at_ms > 0);
+ assert_eq!(queued.model_override.as_deref(), Some("model-override"));
+ assert_eq!(queued.temperature, Some(0.7));
+ assert_eq!(queued.locale.as_deref(), Some("ar"));
+
+ cancel_parked_turn(thread_id, &block).await;
+}
+
+#[tokio::test]
+async fn interrupt_and_parallel_bypass_the_active_turn_queue() {
+ let _serial = FORCED_ERROR_TEST_LOCK.lock().await;
+ let block = make_block();
+ set_test_run_chat_task_block(Some(block.clone())).await;
+ let thread_id = "queue-disposition-bypass";
+ let initial_request_id = start_parked_turn(thread_id, &block).await;
+
+ let replacement_request_id = start_chat(
+ "queue-test-client",
+ thread_id,
+ "replace the active turn",
+ None,
+ None,
+ None,
+ Some("interrupt".to_string()),
+ ChatRequestMetadata::default(),
+ )
+ .await
+ .expect("interrupt should start a replacement turn");
+ assert_ne!(replacement_request_id, initial_request_id);
+ wait_for_in_flight(|entries| {
+ entries
+ .iter()
+ .any(|(key, request_id)| key == thread_id && request_id == &replacement_request_id)
+ })
+ .await;
+
+ start_chat(
+ "queue-test-client",
+ thread_id,
+ "run alongside the replacement",
+ None,
+ None,
+ None,
+ Some("parallel".to_string()),
+ ChatRequestMetadata::default(),
+ )
+ .await
+ .expect("parallel should start a forked turn");
+ wait_for_parallel(|entries| entries.iter().any(|(_, key)| key == thread_id)).await;
+
+ let status = channel_web_queue_status(thread_id)
+ .await
+ .expect("queue status should be available");
+ assert_eq!(status.value["request_id"], replacement_request_id);
+ assert_eq!(status.value["total"], 0);
+ assert_eq!(status.value["steers"], 0);
+ assert_eq!(status.value["followups"], 0);
+ assert_eq!(status.value["collects"], 0);
+
+ cancel_parked_turn(thread_id, &block).await;
+ wait_for_parallel(|entries| !entries.iter().any(|(_, key)| key == thread_id)).await;
+}
+
+#[tokio::test]
+async fn terminal_turn_dispatches_followup_as_a_fresh_host_turn() {
+ let _serial = FORCED_ERROR_TEST_LOCK.lock().await;
+ let block = make_block();
+ set_test_run_chat_task_block(Some(block.clone())).await;
+ let thread_id = "queue-followup-terminal";
+ let primary_request_id = start_parked_turn(thread_id, &block).await;
+ let accepted = queue_message(thread_id, "start after terminal", "followup").await;
+ assert_eq!(accepted["queued"], true);
+
+ // End the primary normally from the host test seam. The queue's follow-up
+ // lane is drained only after terminal handling, then `dispatch_followups`
+ // must route it back through `start_chat` as a fresh in-flight turn.
+ block.release.notify_one();
+ let entries = wait_for_in_flight(|entries| {
+ entries
+ .iter()
+ .any(|(key, request_id)| key == thread_id && request_id != &primary_request_id)
+ })
+ .await;
+ assert!(
+ entries
+ .iter()
+ .any(|(key, request_id)| key == thread_id && request_id != &primary_request_id)
+ );
+
+ cancel_parked_turn(thread_id, &block).await;
+}
+
+#[tokio::test]
+async fn cancellation_discards_pending_lanes_before_a_replacement_turn() {
+ let _serial = FORCED_ERROR_TEST_LOCK.lock().await;
+ let cancelled_block = make_block();
+ set_test_run_chat_task_block(Some(cancelled_block.clone())).await;
+ let thread_id = "queue-cancelled-lanes";
+ let cancelled_request_id = start_parked_turn(thread_id, &cancelled_block).await;
+
+ // Queue every lane against the active turn. In particular, do not clear
+ // these lanes: this test verifies that the real cancellation cleanup owns
+ // their disposal.
+ for (text, mode) in [
+ ("followup must not survive", "followup"),
+ ("steer must not survive", "steer"),
+ ("collect must not survive", "collect"),
+ ] {
+ assert_eq!(queue_message(thread_id, text, mode).await["queued"], true);
+ }
+ assert_eq!(
+ channel_web_queue_status(thread_id)
+ .await
+ .expect("queued status should be available")
+ .value["total"],
+ 3
+ );
+
+ // Exercise the RPC-facing cancellation path used by the host, rather than
+ // reaching into the queue or clearing it first.
+ let cancelled = channel_web_cancel("queue-test-client", thread_id, Some(&cancelled_request_id))
+ .await
+ .expect("host cancellation should succeed");
+ assert_eq!(cancelled.value["cancelled"], true);
+ assert_eq!(cancelled.value["request_id"], cancelled_request_id);
+ wait_for_in_flight(|entries| !entries.iter().any(|(key, _)| key == thread_id)).await;
+ wait_for_flag(
+ &cancelled_block.dropped,
+ "cancelled turn should release its queue-owning task",
+ )
+ .await;
+
+ // A newly-started host turn owns a newly-created queue. No cancelled
+ // follow-up, steer, or collect payload may reappear in it or be delivered
+ // to it later.
+ set_test_run_chat_task_block(None).await;
+ let replacement_block = make_block();
+ set_test_run_chat_task_block(Some(replacement_block.clone())).await;
+ let replacement_request_id = start_parked_turn(thread_id, &replacement_block).await;
+ assert_ne!(replacement_request_id, cancelled_request_id);
+ let replacement = channel_web_queue_status(thread_id)
+ .await
+ .expect("replacement queue status should be available");
+ assert_eq!(replacement.value["total"], 0);
+ assert!(
+ drain_queued_turns_for_test(thread_id, QueueLane::Followup)
+ .await
+ .is_empty()
+ );
+ assert!(
+ drain_queued_turns_for_test(thread_id, QueueLane::Steer)
+ .await
+ .is_empty()
+ );
+ assert!(
+ drain_queued_turns_for_test(thread_id, QueueLane::Collect)
+ .await
+ .is_empty()
+ );
+
+ cancel_parked_turn(thread_id, &replacement_block).await;
+}
+
+#[tokio::test]
+async fn web_queue_status_wire_shape_and_clear_cleanup_remain_stable() {
+ let _serial = FORCED_ERROR_TEST_LOCK.lock().await;
+ let block = make_block();
+ set_test_run_chat_task_block(Some(block.clone())).await;
+ let thread_id = "queue-wire-and-clear";
+ let request_id = start_parked_turn(thread_id, &block).await;
+
+ for (text, mode) in [
+ ("steer payload", "steer"),
+ ("followup payload", "followup"),
+ ("collect payload", "collect"),
+ ] {
+ assert_eq!(queue_message(thread_id, text, mode).await["queued"], true);
+ }
+
+ let active = channel_web_queue_status(thread_id)
+ .await
+ .expect("active queue status should be available");
+ assert_eq!(
+ active
+ .into_cli_compatible_json()
+ .expect("queue status should serialize"),
+ json!({
+ "result": {
+ "thread_id": thread_id,
+ "active": true,
+ "request_id": request_id,
+ "steers": 1,
+ "followups": 1,
+ "collects": 1,
+ "total": 3,
+ },
+ "logs": ["queue status retrieved"],
+ })
+ );
+
+ let cleared = channel_web_queue_clear(thread_id)
+ .await
+ .expect("queue clear should be available");
+ assert_eq!(
+ cleared
+ .into_cli_compatible_json()
+ .expect("queue clear should serialize"),
+ json!({
+ "result": {"thread_id": thread_id, "cleared": true, "dropped": 3},
+ "logs": ["queue cleared"],
+ })
+ );
+ assert_eq!(
+ channel_web_queue_status(thread_id)
+ .await
+ .expect("empty queue status should be available")
+ .into_cli_compatible_json()
+ .expect("empty queue status should serialize"),
+ json!({
+ "result": {
+ "thread_id": thread_id,
+ "active": true,
+ "request_id": request_id,
+ "steers": 0,
+ "followups": 0,
+ "collects": 0,
+ "total": 0,
+ },
+ "logs": ["queue status retrieved"],
+ })
+ );
+
+ cancel_parked_turn(thread_id, &block).await;
+ assert_eq!(
+ channel_web_queue_status(thread_id)
+ .await
+ .expect("inactive queue status should be available")
+ .into_cli_compatible_json()
+ .expect("inactive queue status should serialize"),
+ json!({
+ "result": {
+ "thread_id": thread_id,
+ "active": false,
+ "steers": 0,
+ "followups": 0,
+ "collects": 0,
+ "total": 0,
+ },
+ "logs": ["no active turn for thread"],
+ })
+ );
+}