Skip to content

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

refactor(web_chat): move WebChannelEvent and related types from core::socketio to web_chat

Steven Enamakel608d4de72297
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index 6124537aae..2e753468e7 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -391,7 +391,7 @@ async fn run_system_turn_on_thread(thread_id: String, prompt: String) -> Result<
"system", &thread_id, &run_id, response, None,
),
Err(error) => {
- crate::web_chat::publish_web_channel_event(crate::core::socketio::WebChannelEvent {
+ crate::web_chat::publish_web_channel_event(crate::web_chat::WebChannelEvent {
event: "chat_error".to_string(),
client_id: "system".to_string(),
thread_id: thread_id.clone(),
diff --git a/crates/openhuman-core/src/agent/progress.rs b/crates/openhuman-core/src/agent/progress.rs
index 054e363727..152607a5bf 100644
--- a/crates/openhuman-core/src/agent/progress.rs
+++ b/crates/openhuman-core/src/agent/progress.rs
@@ -126,7 +126,7 @@ pub enum AgentProgress {
/// every emit site is updated to pass it through; additive so
/// existing consumers reading only the other fields are
/// unaffected. Mirrors
- /// [`crate::core::socketio::SubagentProgressDetail::parent_call_id`].
+ /// [`crate::web_chat::SubagentProgressDetail::parent_call_id`].
parent_call_id: Option<String>,
},
diff --git a/crates/openhuman-core/src/channels/host/adapters.rs b/crates/openhuman-core/src/channels/host/adapters.rs
index d775881aa9..e4d5258700 100644
--- a/crates/openhuman-core/src/channels/host/adapters.rs
+++ b/crates/openhuman-core/src/channels/host/adapters.rs
@@ -342,7 +342,7 @@ impl EventSink for OpenHumanEventSink {
) -> anyhow::Result<()> {
match domain {
"web" => {
- let event: crate::core::socketio::WebChannelEvent = serde_json::from_value(payload)
+ let event: crate::web_chat::WebChannelEvent = serde_json::from_value(payload)
.map_err(|e| {
anyhow::anyhow!(
"{LOG_PREFIX} web event payload not a WebChannelEvent ({kind}): {e}"
diff --git a/crates/openhuman-core/src/channels/proactive.rs b/crates/openhuman-core/src/channels/proactive.rs
index 4a2ea30788..ce72436a9e 100644
--- a/crates/openhuman-core/src/channels/proactive.rs
+++ b/crates/openhuman-core/src/channels/proactive.rs
@@ -21,7 +21,7 @@
use crate::channels::{Channel, ChannelSendExt, SendMessage};
use crate::core::events::DomainEvent;
-use crate::core::socketio::WebChannelEvent;
+use crate::web_chat::WebChannelEvent;
use crate::web_chat::publish_web_channel_event;
use async_trait::async_trait;
use std::collections::HashMap;
diff --git a/crates/openhuman-core/src/cron/scheduler/retry.rs b/crates/openhuman-core/src/cron/scheduler/retry.rs
index 3788f4a4e9..2d9f180f88 100644
--- a/crates/openhuman-core/src/cron/scheduler/retry.rs
+++ b/crates/openhuman-core/src/cron/scheduler/retry.rs
@@ -259,7 +259,7 @@ pub(super) async fn execute_job_with_retry(
/// deep-link action even though no chat thread is active.
pub(super) fn publish_cron_user_error(kind: &str) {
log::debug!("[cron] action=surface_user_error kind={kind}");
- crate::web_chat::publish_web_channel_event(crate::core::socketio::WebChannelEvent {
+ crate::web_chat::publish_web_channel_event(crate::web_chat::WebChannelEvent {
event: "user_error".to_string(),
client_id: "system".to_string(),
error_type: Some(kind.to_string()),
diff --git a/crates/openhuman-core/src/cron/scheduler_tests.rs b/crates/openhuman-core/src/cron/scheduler_tests.rs
index 09be1458ae..e53ec159ee 100644
--- a/crates/openhuman-core/src/cron/scheduler_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_tests.rs
@@ -81,9 +81,9 @@ async fn cron_alerts(config: &Config) -> usize {
/// #4169); only a terminal `Empty`/`Closed` — the matching event genuinely was
/// not published — panics.
fn next_user_error(
- rx: &mut tokio::sync::broadcast::Receiver<crate::core::socketio::WebChannelEvent>,
+ rx: &mut tokio::sync::broadcast::Receiver<crate::web_chat::WebChannelEvent>,
kind: &str,
-) -> crate::core::socketio::WebChannelEvent {
+) -> crate::web_chat::WebChannelEvent {
use tokio::sync::broadcast::error::TryRecvError;
loop {
match rx.try_recv() {
diff --git a/crates/openhuman-core/src/flows/ops/streaming.rs b/crates/openhuman-core/src/flows/ops/streaming.rs
index a61648e8e4..97a4ffd8fb 100644
--- a/crates/openhuman-core/src/flows/ops/streaming.rs
+++ b/crates/openhuman-core/src/flows/ops/streaming.rs
@@ -122,7 +122,7 @@ pub(super) async fn finalize_flow_stream(
.await;
}
Err(err) => {
- crate::web_chat::publish_web_channel_event(crate::core::socketio::WebChannelEvent {
+ crate::web_chat::publish_web_channel_event(crate::web_chat::WebChannelEvent {
event: "chat_error".to_string(),
client_id: "system".to_string(),
thread_id: target.thread_id.clone(),
diff --git a/crates/openhuman-core/src/memory/tree/health/user_error.rs b/crates/openhuman-core/src/memory/tree/health/user_error.rs
index 27ba93e598..dda8b94c20 100644
--- a/crates/openhuman-core/src/memory/tree/health/user_error.rs
+++ b/crates/openhuman-core/src/memory/tree/health/user_error.rs
@@ -12,7 +12,7 @@ use tinymemory_api::host::{
LOCAL_MODEL_UNAVAILABLE_KIND, MEMORY_USER_ERROR_SOURCE, STORE_CORRUPT_KIND,
};
-use crate::core::socketio::WebChannelEvent;
+use crate::web_chat::WebChannelEvent;
/// The metadata-only `user_error` payload for an unusable local embedding
/// runtime. Built separately from the publish so the no-leak contract is
diff --git a/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs b/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs
index a48fb61e43..67a50dccc3 100644
--- a/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs
+++ b/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs
@@ -51,7 +51,7 @@ pub(super) fn deliver_voice_result_to_chat(
"[voice-harness] delivering deferred result to chat correlation={correlation_id} chars={} speak_back={allow_speak_back}",
spoken.chars().count()
);
- crate::web_chat::publish_web_channel_event(crate::core::socketio::WebChannelEvent {
+ crate::web_chat::publish_web_channel_event(crate::web_chat::WebChannelEvent {
event: "proactive_message".to_string(),
client_id: VOICE_CHAT_CLIENT_ID.to_string(),
thread_id: VOICE_CHAT_THREAD_ID.to_string(),
@@ -66,7 +66,7 @@ pub(super) fn deliver_voice_result_to_chat(
// session (a fast read-back turn). Skipped for read-back turns themselves to
// avoid a loop; harmless if the call already ended (nobody is subscribed).
if allow_speak_back {
- crate::web_chat::publish_web_channel_event(crate::core::socketio::WebChannelEvent {
+ crate::web_chat::publish_web_channel_event(crate::web_chat::WebChannelEvent {
event: "voice_speak".to_string(),
client_id: VOICE_CHAT_CLIENT_ID.to_string(),
full_response: Some(spoken.to_string()),
@@ -91,7 +91,7 @@ pub(super) fn deliver_voice_failure_to_chat(correlation_id: &str) {
info!(
"[voice-harness] delivering deferred failure notice to chat correlation={correlation_id}"
);
- crate::web_chat::publish_web_channel_event(crate::core::socketio::WebChannelEvent {
+ crate::web_chat::publish_web_channel_event(crate::web_chat::WebChannelEvent {
event: "proactive_message".to_string(),
client_id: VOICE_CHAT_CLIENT_ID.to_string(),
thread_id: VOICE_CHAT_THREAD_ID.to_string(),
diff --git a/crates/openhuman-core/src/web_chat/channel_event.rs b/crates/openhuman-core/src/web_chat/channel_event.rs
new file mode 100644
index 0000000000..964f275fab
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/channel_event.rs
@@ -0,0 +1,411 @@
+//! Payload types for events the web channel publishes to connected clients.
+//!
+//! Domains build these and hand them to
+//! [`publish_web_channel_event`](super::publish_web_channel_event); the
+//! Socket.IO transport in `openhuman-rpc` forwards them to the browser.
+
+use serde::{Deserialize, Serialize};
+
+/// Standard event payload for the web channel transport.
+///
+/// This structure defines the data sent to Socket.IO clients for various
+/// chat-related events, such as message delivery, tool execution, and errors.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct WebChannelEvent {
+ /// The event name (e.g., `chat_message`, `tool_call`).
+ pub event: String,
+ /// Unique identifier for the Socket.IO client.
+ pub client_id: String,
+ /// Identifier for the specific chat thread.
+ pub thread_id: String,
+ /// Unique identifier for the individual request/turn.
+ pub request_id: String,
+ /// The full text of the assistant's response (sent on completion).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub full_response: Option<String>,
+ /// A partial message segment or an error description.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub message: Option<String>,
+ /// Type of error, if the event represents a failure.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_type: Option<String>,
+ /// Structured rate-limit / error metadata produced by
+ /// `classify_inference_error` (issue #2606). All four fields are
+ /// additive — older FE clients that only read `message`/`error_type`
+ /// keep working; new clients can read these to render countdown,
+ /// retry-button, and fallback-CTA UI without regexing the message.
+ ///
+ /// Where the limit originated:
+ /// `"provider"` | `"openhuman_budget"` | `"agent_loop"`
+ /// | `"openhuman_billing"` | `"transport"` | `"config"`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_source: Option<String>,
+ /// Whether the same prompt can be retried in this same thread.
+ /// `false` for non-retryable business 429s, auth, model_unavailable,
+ /// context_overflow, and billing exhaustion.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_retryable: Option<bool>,
+ /// Milliseconds to wait before retrying, as supplied by the upstream
+ /// `Retry-After:` / `retry_after:` header. `None` when the upstream
+ /// didn't supply one or the error class has no retry-after concept.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_retry_after_ms: Option<u64>,
+ /// Provider name extracted from `"<provider> API error (...)"`
+ /// envelopes. `None` for non-provider errors (OpenHuman budget cap,
+ /// agent loop) and for transport failures without a provider prefix.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_provider: Option<String>,
+ /// `Some(false)` once the reliable-provider chain has exhausted
+ /// every configured `model_fallbacks` entry. `None` means "unknown
+ /// — FE should not promise a fallback".
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_fallback_available: Option<bool>,
+ /// Name of the tool being called.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tool_name: Option<String>,
+ /// ID of the skill owning the tool.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub skill_id: Option<String>,
+ /// Arguments passed to the tool.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub args: Option<serde_json::Value>,
+ /// The raw output from the tool execution.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub output: Option<String>,
+ /// Whether the tool execution or request was successful.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub success: Option<bool>,
+ /// The current iteration/round number in a tool-call loop.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub round: Option<u32>,
+ /// Emoji reaction the assistant wants to add to the user's message.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub reaction_emoji: Option<String>,
+ /// 0-based index when a response is delivered as multiple segments.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub segment_index: Option<u32>,
+ /// Total number of segments in a segmented delivery.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub segment_total: Option<u32>,
+ /// Fine-grained streaming payload for `text_delta`, `thinking_delta`,
+ /// and `tool_args_delta` events. Concatenating `delta`s in order
+ /// yields the full text/thinking/arguments string.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub delta: Option<String>,
+ /// Discriminator for the `delta` payload: `"text"`, `"thinking"`,
+ /// or `"tool_args"`. Only set on streaming delta events.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub delta_kind: Option<String>,
+ /// Provider-assigned tool call id that groups `tool_args_delta`
+ /// chunks together and ties them to the eventual `tool_call` /
+ /// `tool_result` events.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tool_call_id: Option<String>,
+ /// Structured, user-facing classification of a failed tool call (class,
+ /// category, plain-language cause + next action). Present on `tool_result`
+ /// events when the tool failed; the chat "View processing" timeline renders
+ /// the "why / what to do next" pair. `None` on success.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub failure: Option<serde_json::Value>,
+ /// Optional citations attached to `chat_done` payloads.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub citations: Option<serde_json::Value>,
+ /// Sub-agent specific progress detail. Populated on
+ /// `subagent_spawned`, `subagent_completed`, `subagent_iteration_start`,
+ /// `subagent_tool_call`, and `subagent_tool_result` events so the UI
+ /// can attribute child activity to the parent's live subagent row
+ /// without overloading the flat top-level fields. `None` for any
+ /// non-subagent event.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub subagent: Option<SubagentProgressDetail>,
+ /// Server-computed human label for a tool call (on `tool_call` /
+ /// `subagent_tool_call`), e.g. "Reading messages". The frontend renders
+ /// this verbatim for dynamic Composio/MCP/integration tools it can't
+ /// label itself, falling back to its own formatter when absent.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tool_display_label: Option<String>,
+ /// Server-computed contextual detail for a tool call (on `tool_call` /
+ /// `subagent_tool_call`), e.g. "[email protected]" — the bracketed target
+ /// shown after [`Self::tool_display_label`].
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tool_display_detail: Option<String>,
+ /// Milliseconds the tool call took to execute. Present on `tool_result` /
+ /// `subagent_tool_result`, mirroring `AgentProgress::ToolCallCompleted`'s
+ /// `elapsed_ms` / `SubagentToolCallCompleted`'s `elapsed_ms` — carried
+ /// as a plain top-level field (in addition to `subagent.elapsed_ms` for
+ /// the sub-agent case) so a frontend that only reads flat fields still
+ /// gets real timing instead of guessing from wall-clock deltas.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub elapsed_ms: Option<u64>,
+ /// Structured, tool-specific result payload copied from a tool's
+ /// `ToolResult::metadata` when it is a JSON object carrying a `"kind"`
+ /// discriminator, e.g.
+ /// `{"kind":"web_search","query":"...","provider":"...","results":[...]}`.
+ /// Present on `tool_result` / `subagent_tool_result` only for tools that
+ /// populate metadata of that shape (currently the web-search tools); the
+ /// model-facing `output` text is unaffected and stays byte-identical to
+ /// what the model itself saw.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub structured: Option<serde_json::Value>,
+ /// Holistic token/cost/context usage for a completed turn (parent +
+ /// sub-agents), carried on `chat_done`. Lets the UI footer show session
+ /// tokens, USD cost, and real context-window utilisation, with a
+ /// per-sub-agent hover breakdown. `None` for every non-`chat_done` event and
+ /// for synthetic done events that never ran a real turn.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub usage: Option<TurnUsagePayload>,
+ /// Additive per-request monotonic ordering key stamped by the web-channel
+ /// progress bridge on every event it emits (conversations-timeline-refactor,
+ /// Phase 4). Together with the always-present `request_id`, the frontend
+ /// dedups replayed vs live events by `(request_id, seq)` and orders them
+ /// identically to the persisted turn-state snapshot. `None` on events not
+ /// emitted through the stamping bridge and on older cores — older frontends
+ /// simply ignore it.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub seq: Option<u64>,
+ /// Epoch milliseconds this event was emitted at. Additive wall-clock
+ /// stamp so a frontend can order/annotate events without deriving time
+ /// from arrival order. `None` on emit sites not yet updated to stamp it.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ts: Option<u64>,
+ /// RFC3339 timestamp of when a pending approval / plan review expires,
+ /// mirrored from `PendingApproval::expires_at` (`security::approval::types`).
+ /// Present on `approval_request` / `plan_review_request` events.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub expires_at: Option<String>,
+ /// The turn/request id a lifecycle event (approval, plan review, queue
+ /// item, cancellation) correlates back to, when distinct from the
+ /// top-level `request_id` (e.g. a decision event fired outside the
+ /// original turn's request context).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub turn_request_id: Option<String>,
+ /// Time-to-first-visible timing summary, carried on `chat_done`. See
+ /// `web_chat::turn_timing`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub timing: Option<TurnTimingPayload>,
+ /// Follow-up prompt suggestions offered to the user after a turn.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub suggestions: Option<Vec<ChatSuggestion>>,
+ /// Guardrail verdict attached to a blocked/flagged turn.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub guardrail: Option<GuardrailPayload>,
+ /// Run-queue item this event reports on (queued/delivered/removed).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub queue_item: Option<QueueItemPayload>,
+ /// Session goal snapshot, carried on goal-lifecycle events. Left as a
+ /// raw `Value` because the goal shape is owned by `tinyagents-graph`,
+ /// not this crate.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub goal: Option<serde_json::Value>,
+ /// Session todo-list snapshot, carried on todo-lifecycle events. Raw
+ /// `Value` for the same reason as `goal`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub todos: Option<serde_json::Value>,
+ /// Human-readable reason a turn/queue item was cancelled.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cancel_reason: Option<String>,
+ /// Id of the turn/request that superseded this one (e.g. a steer
+ /// requeue), when applicable.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub superseded_by: Option<String>,
+}
+
+/// Time-to-first-visible timing summary for a completed turn. See
+/// `web_chat::turn_timing::TurnTiming`.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct TurnTimingPayload {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub first_token_ms: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub first_tool_ms: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub total_ms: Option<u64>,
+ /// `usage.output_tokens / (total_ms / 1000)`, computed at delivery time
+ /// when both a timing snapshot and the turn's output-token count are
+ /// available. `None` when either input is missing (e.g. a budget-
+ /// exhausted synthetic result, or a turn that produced no completion
+ /// tokens). Added by C4 — not in the original wire-contract prep pass;
+ /// see wire-contract.md "Added by C4".
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tokens_per_second: Option<f64>,
+}
+
+/// One follow-up prompt suggestion offered after a turn.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct ChatSuggestion {
+ pub prompt: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub label: Option<String>,
+}
+
+/// One guardrail rejection reason code + message.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct GuardrailReason {
+ pub code: String,
+ pub message: String,
+}
+
+/// Guardrail verdict attached to a blocked/flagged turn (`chat_error` with
+/// `error_type = "guardrail"`).
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct GuardrailPayload {
+ pub verdict: String,
+ pub score: f64,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub reasons: Vec<GuardrailReason>,
+}
+
+/// A run-queue item summary (`queue_item_queued` / `queue_item_delivered` /
+/// `queue_item_removed`).
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct QueueItemPayload {
+ pub id: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub lane: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub text_preview: Option<String>,
+}
+
+/// Token/cost/context totals for one completed turn, attached to `chat_done`.
+///
+/// Every numeric is a turn total (parent agent **plus** any sub-agents spawned
+/// during the turn); the `subagents` list breaks the same spend down per child
+/// for the UI hover. `context_window` is `0` when the core couldn't resolve the
+/// model's window (e.g. an unknown cloud model) — the UI falls back to a
+/// default in that case.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct TurnUsagePayload {
+ pub input_tokens: u64,
+ pub output_tokens: u64,
+ pub cached_input_tokens: u64,
+ pub cost_usd: f64,
+ pub context_window: u64,
+ /// Per-sub-agent spend, omitted from the wire when no sub-agents ran.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub subagents: Vec<SubagentUsagePayload>,
+}
+
+/// One sub-agent's token/cost contribution within a turn (hover breakdown).
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct SubagentUsagePayload {
+ pub task_id: String,
+ pub agent_id: String,
+ pub input_tokens: u64,
+ pub output_tokens: u64,
+ pub cost_usd: f64,
+}
+
+/// Per-event subagent progress detail attached to `WebChannelEvent`.
+///
+/// Carries the fields the parent thread's UI needs to render a live
+/// subagent block — child iteration counters, mode, child task/agent
+/// ids when distinct from the flat `tool_name` (which already carries
+/// the agent id on top-level subagent events but not on nested
+/// `subagent_tool_*` events where `tool_name` is the *child's* tool),
+/// and final-run statistics on `subagent_completed`.
+///
+/// Every field is optional and skipped from the JSON payload when
+/// absent — this keeps the wire format compact for non-subagent events
+/// (where the whole struct is `None`) and lets new fields land
+/// non-breakingly behind older clients.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct SubagentProgressDetail {
+ /// Resolved spawn mode — `"typed"` or `"fork"`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mode: Option<String>,
+ /// Whether the spawn requested a dedicated worker thread.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dedicated_thread: Option<bool>,
+ /// Character length of the delegation prompt (on `subagent_spawned`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub prompt_chars: Option<u64>,
+ /// Sub-agent's child iteration counter (on `subagent_iteration_start`,
+ /// `subagent_tool_call`, `subagent_tool_result`). 1-based.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub child_iteration: Option<u32>,
+ /// Sub-agent's configured iteration cap.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub child_max_iterations: Option<u32>,
+ /// Child agent id (on nested `subagent_tool_*` events where the flat
+ /// `tool_name` is the child's tool, not the agent).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub agent_id: Option<String>,
+ /// Spawn task id (on nested `subagent_tool_*` events).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub task_id: Option<String>,
+ /// Elapsed wall-clock for the call/run in milliseconds.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub elapsed_ms: Option<u64>,
+ /// This child's own token + cost spend (on `subagent_completed`), and
+ /// **only when it is not already inside the parent turn's totals**.
+ ///
+ /// The consumer adds these unconditionally, so an emit site that leaves
+ /// them absent contributes nothing — the safe direction. Populating them
+ /// for a child whose usage DID reach `parent_subagent_usage` silently
+ /// doubles the user's reported tokens and money, because
+ /// `holistic_last_turn_usage` already folded both into `chat_done`. See
+ /// `AgentProgress::SubagentCompleted::usage`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub input_tokens: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub output_tokens: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cached_input_tokens: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cost_usd: Option<f64>,
+ /// Total iterations the sub-agent used (on `subagent_completed`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub iterations: Option<u32>,
+ /// Character length of the sub-agent's final assistant text
+ /// (on `subagent_completed`) or the tool result
+ /// (on `subagent_tool_result`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub output_chars: Option<u64>,
+ /// Persistent worker sub-thread id backing the delegation (on
+ /// `subagent_spawned`). The frontend stores it on the subagent row and
+ /// uses it to reopen the full parent↔subagent conversation from memory.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub worker_thread_id: Option<String>,
+ /// Human-readable display name from the agent registry (e.g.
+ /// "Researcher", "Coding Agent"). The frontend uses this for
+ /// consistent agent labels across timeline, sub-mascots, and drawer.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub display_name: Option<String>,
+ /// Absolute path to the worker's isolated `git worktree` checkout
+ /// (on `subagent_completed`, when the worker ran with
+ /// `isolation = "worktree"`). Drives the inline worktree row's
+ /// open/diff/remove actions. `None` for non-isolated workers (#3376).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub worktree_path: Option<String>,
+ /// Files (relative to the worktree root) the worker changed, snapshot
+ /// after the run (on `subagent_completed`). Absent for non-isolated
+ /// workers and clean worktrees.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub changed_files: Option<Vec<String>>,
+ /// Whether the worker's worktree had uncommitted changes after the run
+ /// (on `subagent_completed`). A dirty worktree must not be auto-removed —
+ /// the UI requires an explicit user decision. `None` for non-isolated.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dirty_status: Option<bool>,
+ /// The parent turn's tool-call id that this sub-agent spawn is
+ /// attributed to (on `subagent_spawned`), mirroring
+ /// `AgentProgress::SubagentSpawned::parent_call_id`. Lets the UI
+ /// attach a spawn to the exact `spawn_subagent`/dispatch tool call
+ /// that created it instead of inferring it from arrival order.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub parent_call_id: Option<String>,
+ /// The sub-agent's final output text (on `subagent_completed`),
+ /// mirrored alongside the top-level `output` field so a consumer that
+ /// only reads `subagent.*` still gets the result text.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub output: Option<String>,
+}
diff --git a/crates/openhuman-core/src/web_chat/egress_surface.rs b/crates/openhuman-core/src/web_chat/egress_surface.rs
index b0e497a3cd..16a728f232 100644
--- a/crates/openhuman-core/src/web_chat/egress_surface.rs
+++ b/crates/openhuman-core/src/web_chat/egress_surface.rs
@@ -10,7 +10,7 @@ use async_trait::async_trait;
use tinybus::{EventHandler, SubscriptionHandle};
use crate::core::events::DomainEvent;
-use crate::core::socketio::WebChannelEvent;
+use crate::web_chat::WebChannelEvent;
use super::event_bus::publish_web_channel_event;
diff --git a/crates/openhuman-core/src/web_chat/event_bus.rs b/crates/openhuman-core/src/web_chat/event_bus.rs
index e17f020f6b..c2274786c2 100644
--- a/crates/openhuman-core/src/web_chat/event_bus.rs
+++ b/crates/openhuman-core/src/web_chat/event_bus.rs
@@ -8,7 +8,7 @@ use std::sync::{Arc, OnceLock};
use tokio::sync::broadcast;
use crate::core::events::DomainEvent;
-use crate::core::socketio::WebChannelEvent;
+use crate::web_chat::WebChannelEvent;
use tinybus::EventHandler;
use tinybus::SubscriptionHandle;
@@ -302,7 +302,7 @@ impl EventHandler<DomainEvent> for AgentSurfaceSubscriber {
event: "queue_item_queued".to_string(),
client_id: String::new(),
thread_id: thread_id.clone(),
- queue_item: Some(crate::core::socketio::QueueItemPayload {
+ queue_item: Some(crate::web_chat::QueueItemPayload {
id: item_id,
lane: None,
text_preview: text_preview.clone(),
@@ -328,7 +328,7 @@ impl EventHandler<DomainEvent> for AgentSurfaceSubscriber {
event: "queue_item_delivered".to_string(),
client_id: String::new(),
thread_id: thread_id.clone(),
- queue_item: Some(crate::core::socketio::QueueItemPayload {
+ queue_item: Some(crate::web_chat::QueueItemPayload {
id: item_id,
lane,
text_preview: text_preview.clone(),
@@ -359,7 +359,7 @@ impl EventHandler<DomainEvent> for AgentSurfaceSubscriber {
event: "queue_item_delivered".to_string(),
client_id: String::new(),
thread_id: thread_id.clone(),
- queue_item: Some(crate::core::socketio::QueueItemPayload {
+ queue_item: Some(crate::web_chat::QueueItemPayload {
id: item_id,
lane,
text_preview: text_preview.clone(),
diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rs
index 318a16ccf3..551b841045 100644
--- a/crates/openhuman-core/src/web_chat/mod.rs
+++ b/crates/openhuman-core/src/web_chat/mod.rs
@@ -25,6 +25,7 @@
//! `web_errors*.rs` (provider error classification), `schemas.rs` (RPC
//! contract), `types.rs` (shared param/state types).
+mod channel_event;
mod egress_surface;
mod event_bus;
mod journal_shadow;
@@ -52,6 +53,7 @@ pub(crate) use web_errors::{
};
// Public API — event bus
+pub use channel_event::{ChatSuggestion, GuardrailPayload, GuardrailReason, QueueItemPayload, SubagentProgressDetail, SubagentUsagePayload, TurnTimingPayload, TurnUsagePayload, WebChannelEvent};
pub use egress_surface::register_egress_surface_subscriber;
pub use event_bus::{
approval_request_event, plan_review_request_event, publish_web_channel_event,
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 1e0f95fed9..8a1865add3 100644
--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
@@ -4,7 +4,7 @@
use serde_json::{json, Value};
-use crate::core::socketio::WebChannelEvent;
+use crate::web_chat::WebChannelEvent;
use crate::core::Outcome;
use super::super::event_bus::publish_web_channel_event;
@@ -319,7 +319,7 @@ pub async fn channel_web_queue_remove(
event: "queue_item_removed".to_string(),
client_id: client_id.to_string(),
thread_id: thread_id.to_string(),
- queue_item: Some(crate::core::socketio::QueueItemPayload {
+ queue_item: Some(crate::web_chat::QueueItemPayload {
id: item_id.to_string(),
lane: None,
text_preview: None,
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 f3c91bba59..1c827201b1 100644
--- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
+++ b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
@@ -8,7 +8,7 @@ use std::time::Duration;
use tinyagents_harness::run_queue::RunQueue;
use tokio_util::sync::CancellationToken;
-use crate::core::socketio::WebChannelEvent;
+use crate::web_chat::WebChannelEvent;
use super::super::event_bus::publish_web_channel_event;
use super::super::run_task::run_chat_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 ac5c813a0c..eca608dea6 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -10,7 +10,7 @@ use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use crate::core::events::DomainEvent;
-use crate::core::socketio::WebChannelEvent;
+use crate::web_chat::WebChannelEvent;
use crate::security::prompt_injection::{
enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,
};
@@ -41,7 +41,7 @@ pub enum StartChatError {
Guardrail {
verdict: String,
score: f64,
- reasons: Vec<crate::core::socketio::GuardrailReason>,
+ reasons: Vec<crate::web_chat::GuardrailReason>,
},
Other(String),
}
@@ -104,7 +104,7 @@ impl From<StartChatError> for String {
score,
reasons,
} => {
- let payload = crate::core::socketio::GuardrailPayload {
+ let payload = crate::web_chat::GuardrailPayload {
verdict,
score,
reasons,
@@ -258,7 +258,7 @@ pub async fn start_chat(
reasons: prompt_decision
.reasons
.iter()
- .map(|r| crate::core::socketio::GuardrailReason {
+ .map(|r| crate::web_chat::GuardrailReason {
code: r.code.clone(),
message: r.message.clone(),
})
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat_tests.rs b/crates/openhuman-core/src/web_chat/ops/start_chat_tests.rs
index c657bb4e34..6798eef8cc 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat_tests.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat_tests.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::core::socketio::GuardrailReason;
+use crate::web_chat::GuardrailReason;
/// `is_guardrail_error_message` recognizes the `GUARDRAIL:` sentinel and
/// nothing else — mirrors `is_backend_unavailable_message`'s contract.
@@ -52,7 +52,7 @@ fn guardrail_variant_converts_to_sentinel_plus_json_payload() {
assert!(is_guardrail_error_message(&message));
let json_part = message.strip_prefix(GUARDRAIL_ERROR_PREFIX).unwrap();
- let payload: crate::core::socketio::GuardrailPayload =
+ let payload: crate::web_chat::GuardrailPayload =
serde_json::from_str(json_part).expect("payload must be valid JSON");
assert_eq!(payload.verdict, "block");
assert_eq!(payload.score, 0.87);
diff --git a/crates/openhuman-core/src/web_chat/presentation.rs b/crates/openhuman-core/src/web_chat/presentation.rs
index fb76e4e6a1..26568ed3b2 100644
--- a/crates/openhuman-core/src/web_chat/presentation.rs
+++ b/crates/openhuman-core/src/web_chat/presentation.rs
@@ -11,7 +11,7 @@
use crate::agent::tinyagents::host::LastTurnUsage;
use crate::config::rpc as config_rpc;
-use crate::core::socketio::{SubagentUsagePayload, TurnUsagePayload, WebChannelEvent};
+use crate::web_chat::{SubagentUsagePayload, TurnUsagePayload, WebChannelEvent};
use super::publish_web_channel_event;
@@ -306,7 +306,7 @@ fn publish_chat_done(
reaction_emoji: Option<String>,
citations: &[crate::memory::agent::memory_loader::MemoryCitation],
usage_payload: Option<TurnUsagePayload>,
- timing_payload: Option<crate::core::socketio::TurnTimingPayload>,
+ timing_payload: Option<crate::web_chat::TurnTimingPayload>,
) {
publish_web_channel_event(WebChannelEvent {
event: "chat_done".to_string(),
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rs
index 440206873b..d1fce51ef0 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs
@@ -5,7 +5,7 @@
use serde_json::json;
-use crate::core::socketio::{SubagentProgressDetail, WebChannelEvent};
+use crate::web_chat::{SubagentProgressDetail, WebChannelEvent};
use crate::threads::turn_state::{TurnStateMirror, TurnStateStore};
use super::event_bus::publish_web_channel_event;
@@ -1181,7 +1181,7 @@ pub(crate) fn spawn_progress_bridge(
thread_id: thread_id.clone(),
request_id: request_id.clone(),
round: Some(iteration),
- usage: Some(crate::core::socketio::TurnUsagePayload {
+ usage: Some(crate::web_chat::TurnUsagePayload {
input_tokens,
output_tokens,
cached_input_tokens,
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_subagent_events.rs b/crates/openhuman-core/src/web_chat/progress_bridge_subagent_events.rs
index a61e6520dd..54f694daa1 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge_subagent_events.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge_subagent_events.rs
@@ -14,7 +14,7 @@ use tinyagents_session::run_ledger::{
AgentRunKind, AgentRunStatus, AgentRunUpsert, RunEventAppend, RunTelemetryUpsert,
};
-use crate::core::socketio::{SubagentProgressDetail, WebChannelEvent};
+use crate::web_chat::{SubagentProgressDetail, WebChannelEvent};
use super::{
cap_wire_args, cap_wire_output, ledger_append_event, ledger_upsert_agent_run,
diff --git a/crates/openhuman-core/src/web_chat/suggestions.rs b/crates/openhuman-core/src/web_chat/suggestions.rs
index 764f23ca29..0545600536 100644
--- a/crates/openhuman-core/src/web_chat/suggestions.rs
+++ b/crates/openhuman-core/src/web_chat/suggestions.rs
@@ -35,7 +35,7 @@ use tinyinference_llm::message::Message;
use tinyinference_llm::model::ModelRequest;
use crate::config::rpc as config_rpc;
-use crate::core::socketio::{ChatSuggestion, WebChannelEvent};
+use crate::web_chat::{ChatSuggestion, WebChannelEvent};
use crate::inference::provider;
use super::publish_web_channel_event;
diff --git a/crates/openhuman-core/src/web_chat/turn_timing.rs b/crates/openhuman-core/src/web_chat/turn_timing.rs
index c3220f9944..69fff9c3b8 100644
--- a/crates/openhuman-core/src/web_chat/turn_timing.rs
+++ b/crates/openhuman-core/src/web_chat/turn_timing.rs
@@ -93,14 +93,14 @@ impl TurnTimingSnapshot {
pub(crate) fn into_payload(
self,
output_tokens: Option<u64>,
- ) -> crate::core::socketio::TurnTimingPayload {
+ ) -> crate::web_chat::TurnTimingPayload {
let tokens_per_second = match (output_tokens, self.total_ms) {
(Some(tokens), Some(total_ms)) if total_ms > 0 => {
Some(tokens as f64 / (total_ms as f64 / 1000.0))
}
_ => None,
};
- crate::core::socketio::TurnTimingPayload {
+ crate::web_chat::TurnTimingPayload {
first_token_ms: self.first_token_ms,
first_tool_ms: self.first_tool_ms,
total_ms: self.total_ms,
diff --git a/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
index a3f174455f..7ddac734db 100644
--- a/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
+++ b/crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs
@@ -241,7 +241,7 @@ async fn start_chat_chat_error_event_serializes_structured_fields_to_json_wire()
// Pin the additive contract: serializing a default (no error)
// event must NOT introduce any of the new keys.
- let empty = crate::core::socketio::WebChannelEvent {
+ let empty = crate::web_chat::WebChannelEvent {
event: "chat_done".to_string(),
..Default::default()
};
diff --git a/crates/openhuman-tui/src/app.rs b/crates/openhuman-tui/src/app.rs
index 45f9918aa1..ba8615f127 100644
--- a/crates/openhuman-tui/src/app.rs
+++ b/crates/openhuman-tui/src/app.rs
@@ -23,7 +23,7 @@ use serde_json::json;
use tokio::sync::broadcast;
use openhuman_core::core::runtime::CoreRuntime;
-use openhuman_core::core::socketio::WebChannelEvent;
+use openhuman_core::web_chat::WebChannelEvent;
use openhuman_core::web_chat;
use super::cockpit::{
diff --git a/crates/openhuman-tui/src/state.rs b/crates/openhuman-tui/src/state.rs
index 5688e1e7e8..57708d3670 100644
--- a/crates/openhuman-tui/src/state.rs
+++ b/crates/openhuman-tui/src/state.rs
@@ -10,7 +10,7 @@
//! into the transcript. Events for a different `client_id` are ignored, so a
//! process-wide broadcast bus can be drained safely.
-use openhuman_core::core::socketio::WebChannelEvent;
+use openhuman_core::web_chat::WebChannelEvent;
/// The kind of a transcript entry — drives colour / prefix in the renderer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/tests/raw_coverage/channels_large_round25_raw_coverage_e2e.rs b/tests/raw_coverage/channels_large_round25_raw_coverage_e2e.rs
index 0141aaa822..d77bda7995 100644
--- a/tests/raw_coverage/channels_large_round25_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/channels_large_round25_raw_coverage_e2e.rs
@@ -9,7 +9,7 @@ use axum::{
routing::{get, post},
Json, Router,
};
-use openhuman_core::core::socketio::WebChannelEvent;
+use openhuman_core::web_chat::WebChannelEvent;
use openhuman_core::channels::providers::email_channel::{
test_support as email_support, EmailChannel, EmailConfig,
};
diff --git a/tests/raw_coverage/tools_approval_channels_raw_coverage_e2e.rs b/tests/raw_coverage/tools_approval_channels_raw_coverage_e2e.rs
index ad11fe9e86..ee88568ffc 100644
--- a/tests/raw_coverage/tools_approval_channels_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/tools_approval_channels_raw_coverage_e2e.rs
@@ -23,7 +23,7 @@ use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};
use openhuman_core::core::events::DomainEvent;
use tinybus::EventHandler;
use openhuman_core::core::jsonrpc::build_core_http_router;
-use openhuman_core::core::socketio::WebChannelEvent;
+use openhuman_core::web_chat::WebChannelEvent;
use openhuman_core::agent::harness::definition::{
AgentDefinition, AgentDefinitionRegistry, AgentTier, DefinitionSource, ModelSpec, PromptSource,
SandboxMode, SkillsWildcard, SubagentEntry, ToolScope as AgentToolScope,
diff --git a/tests/raw_coverage/tools_network_channels_raw_coverage_e2e.rs b/tests/raw_coverage/tools_network_channels_raw_coverage_e2e.rs
index 53643e495b..a4d6ddc19f 100644
--- a/tests/raw_coverage/tools_network_channels_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/tools_network_channels_raw_coverage_e2e.rs
@@ -18,7 +18,7 @@ use serde_json::json;
use tempfile::{tempdir, TempDir};
use tokio::time::timeout;
-use openhuman_core::core::socketio::WebChannelEvent;
+use openhuman_core::web_chat::WebChannelEvent;
use openhuman_core::web_chat::{
all_web_channel_controller_schemas, all_web_channel_registered_controllers, cancel_chat,
channel_web_cancel, publish_web_channel_event, schemas as web_channel_schema, start_chat,