Skip to content

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

refactor(progress_bridge): extract subagent event handling into dedicated module

Steven Enamakelb305d70340b2
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rs
index 7d00bfb149..0fabecc73b 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs
@@ -780,83 +780,25 @@ pub(crate) fn spawn_progress_bridge(
parent_call_id,
..
} => {
- subagent_parent_call_ids.insert(task_id.clone(), parent_call_id.clone());
- let label = display_name.as_deref().unwrap_or(&agent_id);
- let kind = if worker_thread_id.is_some() {
- AgentRunKind::WorkerThread
- } else {
- AgentRunKind::Subagent
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
};
- ledger_upsert_agent_run(
- &config,
- AgentRunUpsert {
- id: task_id.clone(),
- kind,
- parent_run_id: Some(request_id.clone()),
- parent_thread_id: Some(thread_id.clone()),
- agent_id: Some(agent_id.clone()),
- status: AgentRunStatus::Running,
- prompt_ref: worker_thread_id
- .as_ref()
- .map(|id| format!("thread:{id}:message:seed")),
- worker_thread_id: worker_thread_id.clone(),
- checkpoint_path: None,
- checkpoint: None,
- summary: None,
- error: None,
- metadata: json!({
- "mode": mode,
- "dedicatedThread": dedicated_thread,
- "promptChars": prompt_chars,
- "displayName": display_name,
- "parentCallId": parent_call_id,
- "source": "agent_progress",
- "schemaVersion": 1
- }),
- started_at: None,
- completed_at: None,
- },
- );
- ledger_append_event(
- &config,
- RunEventAppend {
- run_id: task_id.clone(),
- event_type: "subagent_spawned".to_string(),
- payload: json!({
- "agentId": agent_id,
- "parentRunId": request_id,
- "threadId": thread_id,
- "workerThreadId": worker_thread_id,
- "mode": mode,
- "dedicatedThread": dedicated_thread,
- "promptChars": prompt_chars,
- "displayName": display_name,
- "parentCallId": parent_call_id
- }),
- },
- );
- publish_seq_stamped(
+ subagent_events::on_subagent_spawned(
+ &ctx,
&mut emit_seq,
- WebChannelEvent {
- event: "subagent_spawned".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- message: Some(format!("Sub-agent '{label}' spawned")),
- tool_name: Some(agent_id),
- skill_id: Some(task_id),
- round: Some(round),
- subagent: Some(SubagentProgressDetail {
- mode: Some(mode),
- dedicated_thread: Some(dedicated_thread),
- prompt_chars: Some(prompt_chars as u64),
- worker_thread_id,
- display_name,
- parent_call_id,
- ..Default::default()
- }),
- ..Default::default()
- },
+ &mut subagent_parent_call_ids,
+ round,
+ agent_id,
+ task_id,
+ mode,
+ dedicated_thread,
+ prompt_chars,
+ worker_thread_id,
+ display_name,
+ parent_call_id,
);
}
AgentProgress::SubagentCompleted {
@@ -872,98 +814,28 @@ pub(crate) fn spawn_progress_bridge(
dirty_status,
..
} => {
- let parent_call_id = subagent_parent_call_ids.remove(&task_id).flatten();
- let capped_output = cap_wire_output(output);
- let completed_at = chrono::Utc::now();
- ledger_upsert_agent_run(
- &config,
- AgentRunUpsert {
- id: task_id.clone(),
- kind: AgentRunKind::Subagent,
- parent_run_id: Some(request_id.clone()),
- parent_thread_id: Some(thread_id.clone()),
- agent_id: Some(agent_id.clone()),
- status: AgentRunStatus::Completed,
- prompt_ref: None,
- worker_thread_id: None,
- checkpoint_path: None,
- checkpoint: None,
- summary: Some(format!(
- "Completed in {iterations} iteration(s), {output_chars} output chars"
- )),
- error: None,
- metadata: json!({}),
- started_at: None,
- completed_at: Some(completed_at),
- },
- );
- ledger_upsert_telemetry(
- &config,
- RunTelemetryUpsert {
- run_id: task_id.clone(),
- elapsed_ms: Some(elapsed_ms),
- tool_count: child_tool_counts.get(&task_id).copied(),
- ..Default::default()
- },
- );
- ledger_append_event(
- &config,
- RunEventAppend {
- run_id: task_id.clone(),
- event_type: "subagent_completed".to_string(),
- payload: json!({
- "agentId": agent_id,
- "elapsedMs": elapsed_ms,
- "iterations": iterations,
- "outputChars": output_chars,
- "worktreePath": worktree_path,
- "changedFiles": changed_files,
- "dirtyStatus": dirty_status,
- "parentCallId": parent_call_id
- }),
- },
- );
- publish_seq_stamped(
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
+ };
+ subagent_events::on_subagent_completed(
+ &ctx,
&mut emit_seq,
- WebChannelEvent {
- event: "subagent_completed".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- message: Some(format!(
- "Sub-agent '{agent_id}' completed in {elapsed_ms}ms"
- )),
- tool_name: Some(agent_id),
- skill_id: Some(task_id),
- success: Some(true),
- round: Some(round),
- subagent: Some(SubagentProgressDetail {
- elapsed_ms: Some(elapsed_ms),
- iterations: Some(iterations),
- output_chars: Some(output_chars as u64),
- output: Some(capped_output),
- parent_call_id,
- // Present only when this child's spend is NOT
- // already in the parent turn's totals — the
- // emitting site decides, because only it can
- // see whether the usage reached
- // `parent_subagent_usage`. Absent is the safe
- // default and means "add nothing".
- input_tokens: usage.as_ref().map(|u| u.input_tokens),
- output_tokens: usage.as_ref().map(|u| u.output_tokens),
- cached_input_tokens: usage.as_ref().map(|u| u.cached_input_tokens),
- cost_usd: usage.as_ref().map(|u| u.charged_amount_usd),
- // Worktree isolation metadata (#3376) — drives the
- // inline subagent worktree row's open/diff/remove
- // actions. All `None`/absent for non-isolated workers.
- ..subagent_worktree_detail(
- worktree_path,
- changed_files,
- dirty_status,
- )
- }),
- ..Default::default()
- },
+ &mut subagent_parent_call_ids,
+ &child_tool_counts,
+ round,
+ agent_id,
+ task_id,
+ elapsed_ms,
+ iterations,
+ output_chars,
+ output,
+ usage,
+ worktree_path,
+ changed_files,
+ dirty_status,
);
}
AgentProgress::SubagentFailed {
@@ -971,67 +843,21 @@ pub(crate) fn spawn_progress_bridge(
task_id,
error,
} => {
- let parent_call_id = subagent_parent_call_ids.remove(&task_id).flatten();
- let completed_at = chrono::Utc::now();
- ledger_upsert_agent_run(
- &config,
- AgentRunUpsert {
- id: task_id.clone(),
- kind: AgentRunKind::Subagent,
- parent_run_id: Some(request_id.clone()),
- parent_thread_id: Some(thread_id.clone()),
- agent_id: Some(agent_id.clone()),
- status: AgentRunStatus::Failed,
- prompt_ref: None,
- worker_thread_id: None,
- checkpoint_path: None,
- checkpoint: None,
- summary: None,
- error: Some(error.clone()),
- metadata: json!({}),
- started_at: None,
- completed_at: Some(completed_at),
- },
- );
- ledger_upsert_telemetry(
- &config,
- RunTelemetryUpsert {
- run_id: task_id.clone(),
- tool_count: child_tool_counts.get(&task_id).copied(),
- error: Some(error.clone()),
- ..Default::default()
- },
- );
- ledger_append_event(
- &config,
- RunEventAppend {
- run_id: task_id.clone(),
- event_type: "subagent_failed".to_string(),
- payload: json!({
- "agentId": agent_id,
- "error": error,
- "parentCallId": parent_call_id
- }),
- },
- );
- publish_seq_stamped(
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
+ };
+ subagent_events::on_subagent_failed(
+ &ctx,
&mut emit_seq,
- WebChannelEvent {
- event: "subagent_failed".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- message: Some(error),
- tool_name: Some(agent_id),
- skill_id: Some(task_id),
- success: Some(false),
- subagent: Some(SubagentProgressDetail {
- parent_call_id,
- ..Default::default()
- }),
- round: Some(round),
- ..Default::default()
- },
+ &mut subagent_parent_call_ids,
+ &child_tool_counts,
+ round,
+ agent_id,
+ task_id,
+ error,
);
}
AgentProgress::SubagentAwaitingUser {
@@ -1041,81 +867,22 @@ pub(crate) fn spawn_progress_bridge(
worker_thread_id,
checkpoint_path,
} => {
- let parent_call_id = subagent_parent_call_ids.get(&task_id).cloned().flatten();
- log::debug!(
- "[web_channel][bridge] subagent_awaiting_user agent_id={} task_id={} client_id={} thread_id={} request_id={}",
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
+ };
+ subagent_events::on_subagent_awaiting_user(
+ &ctx,
+ &mut emit_seq,
+ &subagent_parent_call_ids,
+ round,
agent_id,
task_id,
- client_id,
- thread_id,
- request_id,
- );
- ledger_upsert_agent_run(
- &config,
- AgentRunUpsert {
- id: task_id.clone(),
- kind: if worker_thread_id.is_some() {
- AgentRunKind::WorkerThread
- } else {
- AgentRunKind::Subagent
- },
- parent_run_id: Some(request_id.clone()),
- parent_thread_id: Some(thread_id.clone()),
- agent_id: Some(agent_id.clone()),
- status: AgentRunStatus::AwaitingUser,
- prompt_ref: None,
- worker_thread_id: worker_thread_id.clone(),
- // What the runner actually wrote; the old rebuild
- // from `workspace_dir` asserted a checkpoint that
- // may never have been written (#5928).
- checkpoint_path: checkpoint_path.clone(),
- checkpoint: Some(json!({
- "resumeTool": "continue_subagent",
- "taskId": task_id,
- "agentId": agent_id,
- "question": question,
- "workerThreadId": worker_thread_id,
- "checkpointPersisted": checkpoint_path.is_some()
- })),
- summary: Some(question.clone()),
- error: None,
- metadata: json!({}),
- started_at: None,
- completed_at: None,
- },
- );
- ledger_append_event(
- &config,
- RunEventAppend {
- run_id: task_id.clone(),
- event_type: "subagent_awaiting_user".to_string(),
- payload: json!({
- "agentId": agent_id,
- "question": question,
- "workerThreadId": worker_thread_id,
- "parentCallId": parent_call_id
- }),
- },
- );
- publish_seq_stamped(
- &mut emit_seq,
- WebChannelEvent {
- event: "subagent_awaiting_user".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- message: Some(question),
- tool_name: Some(agent_id),
- skill_id: Some(task_id),
- success: Some(true),
- round: Some(round),
- subagent: Some(SubagentProgressDetail {
- worker_thread_id,
- parent_call_id,
- ..Default::default()
- }),
- ..Default::default()
- },
+ question,
+ worker_thread_id,
+ checkpoint_path,
);
}
AgentProgress::SubagentIterationStarted {
@@ -1125,34 +892,21 @@ pub(crate) fn spawn_progress_bridge(
max_iterations,
extended_policy,
} => {
- publish_seq_stamped(
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
+ };
+ subagent_events::on_subagent_iteration_started(
+ &ctx,
&mut emit_seq,
- WebChannelEvent {
- event: "subagent_iteration_start".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- message: Some(if extended_policy {
- format!("Sub-agent '{agent_id}' step {iteration}")
- } else {
- format!(
- "Sub-agent '{agent_id}' iteration {iteration}/{max_iterations}"
- )
- }),
- tool_name: Some(agent_id),
- skill_id: Some(task_id),
- round: Some(round),
- subagent: Some(SubagentProgressDetail {
- child_iteration: Some(iteration),
- child_max_iterations: if extended_policy {
- None
- } else {
- Some(max_iterations)
- },
- ..Default::default()
- }),
- ..Default::default()
- },
+ round,
+ agent_id,
+ task_id,
+ iteration,
+ max_iterations,
+ extended_policy,
);
}
AgentProgress::SubagentToolCallStarted {
@@ -1165,58 +919,25 @@ pub(crate) fn spawn_progress_bridge(
display_label,
display_detail,
} => {
- let count = child_tool_counts.entry(task_id.clone()).or_insert(0);
- *count += 1;
- ledger_upsert_telemetry(
- &config,
- RunTelemetryUpsert {
- run_id: task_id.clone(),
- tool_count: Some(*count),
- ..Default::default()
- },
- );
- ledger_append_event(
- &config,
- RunEventAppend {
- run_id: task_id.clone(),
- event_type: "subagent_tool_call_started".to_string(),
- payload: json!({
- "agentId": agent_id,
- "callId": call_id,
- "toolName": tool_name,
- "iteration": iteration
- }),
- },
- );
- publish_seq_stamped(
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
+ };
+ subagent_events::on_subagent_tool_call_started(
+ &ctx,
&mut emit_seq,
- WebChannelEvent {
- event: "subagent_tool_call".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- tool_name: Some(tool_name),
- skill_id: Some(task_id.clone()),
- // The child's tool arguments, so the UI can show what
- // the sub-agent actually did (issue: subagent drawer
- // detail). Skipped from the wire when `null`.
- args: if arguments.is_null() {
- None
- } else {
- Some(arguments)
- },
- round: Some(round),
- tool_call_id: Some(call_id),
- tool_display_label: display_label,
- tool_display_detail: display_detail,
- subagent: Some(SubagentProgressDetail {
- child_iteration: Some(iteration),
- agent_id: Some(agent_id),
- task_id: Some(task_id),
- ..Default::default()
- }),
- ..Default::default()
- },
+ &mut child_tool_counts,
+ round,
+ agent_id,
+ task_id,
+ call_id,
+ tool_name,
+ arguments,
+ iteration,
+ display_label,
+ display_detail,
);
}
AgentProgress::SubagentToolCallCompleted {
@@ -1235,60 +956,30 @@ pub(crate) fn spawn_progress_bridge(
display_detail,
structured,
} => {
- // Serialize the classified failure (if any) so a failed
- // sub-agent tool row carries its "why + next" copy on the
- // wire + ledger, matching the main-agent path (#4459).
- let failure_json = failure.as_ref().and_then(|f| serde_json::to_value(f).ok());
- ledger_append_event(
- &config,
- RunEventAppend {
- run_id: task_id.clone(),
- event_type: "subagent_tool_call_completed".to_string(),
- payload: json!({
- "agentId": agent_id,
- "callId": call_id,
- "toolName": tool_name,
- "success": success,
- "outputChars": output_chars,
- "elapsedMs": elapsed_ms,
- "iteration": iteration,
- "failure": failure_json,
- }),
- },
- );
- publish_seq_stamped(
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
+ };
+ subagent_events::on_subagent_tool_call_completed(
+ &ctx,
&mut emit_seq,
- WebChannelEvent {
- event: "subagent_tool_result".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- tool_name: Some(tool_name),
- skill_id: Some(task_id.clone()),
- success: Some(success),
- round: Some(round),
- tool_call_id: Some(call_id),
- // The child's actual tool output, so the drawer can show
- // *what came back* (not just a char count). Capped to a
- // bounded size for the wire (#4007); `output_chars` +
- // `elapsed_ms` still ride along in `subagent` below.
- output: Some(cap_wire_output(output)),
- args: cap_wire_args(arguments),
- elapsed_ms: Some(elapsed_ms),
- structured,
- tool_display_label: display_label,
- tool_display_detail: display_detail,
- failure: failure_json,
- subagent: Some(SubagentProgressDetail {
- child_iteration: Some(iteration),
- agent_id: Some(agent_id),
- task_id: Some(task_id),
- elapsed_ms: Some(elapsed_ms),
- output_chars: Some(output_chars as u64),
- ..Default::default()
- }),
- ..Default::default()
- },
+ round,
+ agent_id,
+ task_id,
+ call_id,
+ tool_name,
+ success,
+ output_chars,
+ output,
+ arguments,
+ elapsed_ms,
+ iteration,
+ failure,
+ display_label,
+ display_detail,
+ structured,
);
}
AgentProgress::SubagentTextDelta {
@@ -1297,25 +988,20 @@ pub(crate) fn spawn_progress_bridge(
delta,
iteration,
} => {
- publish_seq_stamped(
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
+ };
+ subagent_events::on_subagent_text_delta(
+ &ctx,
&mut emit_seq,
- WebChannelEvent {
- event: "subagent_text_delta".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- round: Some(round),
- delta: Some(delta),
- delta_kind: Some("text".to_string()),
- skill_id: Some(task_id.clone()),
- subagent: Some(SubagentProgressDetail {
- child_iteration: Some(iteration),
- agent_id: Some(agent_id),
- task_id: Some(task_id),
- ..Default::default()
- }),
- ..Default::default()
- },
+ round,
+ agent_id,
+ task_id,
+ delta,
+ iteration,
);
}
AgentProgress::SubagentThinkingDelta {
@@ -1324,25 +1010,20 @@ pub(crate) fn spawn_progress_bridge(
delta,
iteration,
} => {
- publish_seq_stamped(
+ let ctx = BridgeCtx {
+ client_id: &client_id,
+ thread_id: &thread_id,
+ request_id: &request_id,
+ config: &config,
+ };
+ subagent_events::on_subagent_thinking_delta(
+ &ctx,
&mut emit_seq,
- WebChannelEvent {
- event: "subagent_thinking_delta".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- round: Some(round),
- delta: Some(delta),
- delta_kind: Some("thinking".to_string()),
- skill_id: Some(task_id.clone()),
- subagent: Some(SubagentProgressDetail {
- child_iteration: Some(iteration),
- agent_id: Some(agent_id),
- task_id: Some(task_id),
- ..Default::default()
- }),
- ..Default::default()
- },
+ round,
+ agent_id,
+ task_id,
+ delta,
+ iteration,
);
}
AgentProgress::TextDelta { delta, iteration } => {