Skip to content

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

refactor(observability): reorganize test modules

Steven Enamakel1a759c1504d0
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/cache_layout.rs b/crates/openhuman-core/src/agent/tinyagents/observability/cache_layout.rs
new file mode 100644
index 0000000000..04b60f4fb9
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/observability/cache_layout.rs
@@ -0,0 +1,27 @@
+//! Structured logging of prompt-cache layout drift reported by the crate guard.
+
+use tinyagents_harness::cache::CacheLayoutEvent;
+
+/// Surface the crate `PromptCacheGuardMiddleware`'s recorded
+/// [`CacheLayoutEvent`]s as structured `[cache]` warnings (issue #4249, 03.2).
+///
+/// The guard records a layout event whenever the cacheable prompt prefix changes
+/// between turns (volatile content — a timestamp, uuid, injected memory, etc. —
+/// silently busting the provider KV-cache prefix). This is the crate-native
+/// replacement for the deleted `CacheAlignMiddleware` free-text warn-log:
+/// instead of a token-pattern heuristic it reports the exact before/after
+/// cacheable segment ids. Drained by the turn loop after the run and logged
+/// here. The warn-only `CacheAlignMiddleware` shadow was deleted in C3; this
+/// guard is now the sole owner of KV-cache-prefix drift detection.
+pub(crate) fn surface_cache_layout_events(model: &str, events: &[CacheLayoutEvent]) {
+ for event in events {
+ tracing::warn!(
+ model,
+ changed_prefix = event.changed_prefix,
+ volatile_only = event.volatile_only,
+ segments_before = ?event.segment_ids_before,
+ segments_after = ?event.segment_ids_after,
+ "[cache] prompt-cache prefix changed across turns — KV-cache prefix may not hit; keep dynamic content out of the system prompt / stable tool set"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
index 71eda602ca..21a5a2e401 100644
--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
@@ -736,27 +736,3 @@ impl OpenhumanEventBridge {
})
}
}
-
-/// Surface the crate `PromptCacheGuardMiddleware`'s recorded
-/// [`CacheLayoutEvent`]s as structured `[cache]` warnings (issue #4249, 03.2).
-///
-/// The guard records a layout event whenever the cacheable prompt prefix changes
-/// between turns (volatile content — a timestamp, uuid, injected memory, etc. —
-/// silently busting the provider KV-cache prefix). This is the crate-native
-/// replacement for the deleted `CacheAlignMiddleware` free-text warn-log:
-/// instead of a token-pattern heuristic it reports the exact before/after
-/// cacheable segment ids. Drained by the turn loop after the run and logged
-/// here. The warn-only `CacheAlignMiddleware` shadow was deleted in C3; this
-/// guard is now the sole owner of KV-cache-prefix drift detection.
-pub(crate) fn surface_cache_layout_events(model: &str, events: &[CacheLayoutEvent]) {
- for event in events {
- tracing::warn!(
- model,
- changed_prefix = event.changed_prefix,
- volatile_only = event.volatile_only,
- segments_before = ?event.segment_ids_before,
- segments_after = ?event.segment_ids_after,
- "[cache] prompt-cache prefix changed across turns — KV-cache prefix may not hit; keep dynamic content out of the system prompt / stable tool set"
- );
- }
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability_projection_tests.rs b/crates/openhuman-core/src/agent/tinyagents/observability_projection_tests.rs
new file mode 100644
index 0000000000..3e20fde523
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/observability_projection_tests.rs
@@ -0,0 +1,215 @@
+use super::*;
+
+#[tokio::test]
+async fn duplicate_usage_for_same_model_call_is_recorded_once() {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
+ let bridge = OpenhumanEventBridge::new(Some(tx), "mock-model", 10);
+ let sink = EventSink::new();
+ sink.subscribe(bridge.clone());
+
+ // One model call → one `ModelStarted` (iteration cursor → 1).
+ sink.emit(AgentEvent::ModelStarted {
+ call_id: "c1".into(),
+ model: "mock-model".to_string(),
+ });
+ // Same call surfaces usage twice (runtime emit + BudgetMiddleware re-emit).
+ sink.emit(AgentEvent::UsageRecorded {
+ usage: Usage::new(100, 40),
+ });
+ sink.emit(AgentEvent::UsageRecorded {
+ usage: Usage::new(100, 40),
+ });
+
+ // Totals reflect a single record, not two.
+ let (input, output, _) = bridge.totals();
+ assert_eq!(
+ (input, output),
+ (100, 40),
+ "the duplicate UsageRecorded for the same iteration must be skipped"
+ );
+
+ // Exactly one `TurnCostUpdated` footer emit for the call.
+ let mut cost_updates = 0;
+ while let Ok(p) = rx.try_recv() {
+ if matches!(p, AgentProgress::TurnCostUpdated { .. }) {
+ cost_updates += 1;
+ }
+ }
+ assert_eq!(cost_updates, 1, "footer must update once per model call");
+
+ // A genuinely new model call (iteration cursor → 2) records again.
+ sink.emit(AgentEvent::ModelStarted {
+ call_id: "c2".into(),
+ model: "mock-model".to_string(),
+ });
+ sink.emit(AgentEvent::UsageRecorded {
+ usage: Usage::new(10, 5),
+ });
+ let (input, output, _) = bridge.totals();
+ assert_eq!(
+ (input, output),
+ (110, 45),
+ "a distinct model call (new iteration) must still record"
+ );
+}
+
+// NOTE: the former `sentinel_tool_started_is_not_forwarded` test was removed
+// here. The #4249 migration (commit 60097ba8d, "use sdk unknown tool
+// recovery") deleted `UNKNOWN_TOOL_SENTINEL` + `UnknownToolRewriteMiddleware`
+// in favour of the crate `UnknownToolPolicy::ReturnToolError` path, so a
+// `ToolStarted` now only ever fires for real, model-visible tools (see the
+// `ToolStarted` arm above — it no longer special-cases a sentinel). The test
+// referenced the deleted constant (a stale reference reintroduced by a merge)
+// and asserted behaviour that no longer exists.
+
+/// #6XXX (tool-call presentation): `ToolCallStarted`/`ToolCallCompleted` must
+/// carry the tool's OWN `display_label`/`display_detail` when the bridge was
+/// built with the turn's tool sets, not a name-derived guess — proven with a
+/// fake tool whose label is a fixed phrase and whose detail comes from a
+/// `"to"` argument only known once the call completes.
+#[tokio::test]
+async fn tool_call_events_use_the_tool_s_own_display_label_and_detail() {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
+ let bridge = OpenhumanEventBridge::with_scope(
+ Some(tx),
+ "mock-model",
+ "managed",
+ 10,
+ None,
+ Arc::default(),
+ Arc::default(),
+ Arc::default(),
+ Arc::default(),
+ fake_tool_sets(),
+ crate::core::runtime::DispatchCtx::ambient(),
+ );
+ let sink = EventSink::new();
+ sink.subscribe(bridge.clone());
+
+ sink.emit(AgentEvent::ModelStarted {
+ call_id: "c1".into(),
+ model: "mock-model".to_string(),
+ });
+ sink.emit(AgentEvent::ToolStarted {
+ parent_call_id: None,
+ call_id: "c1".into(),
+ tool_name: "fake_send_email".to_string(),
+ input: None,
+ });
+ sink.emit(AgentEvent::ToolCompleted {
+ parent_call_id: None,
+ call_id: "c1".into(),
+ tool_name: "fake_send_email".to_string(),
+ started_at_ms: None,
+ input: Some(serde_json::json!({"to": "[email protected]"})),
+ output: Some(serde_json::Value::String("sent".to_string())),
+ duration_ms: Some(5),
+ output_bytes: Some(4),
+ error: None,
+ metadata: None,
+ });
+
+ let mut started_label = None;
+ let mut completed = None;
+ while let Ok(p) = rx.try_recv() {
+ match p {
+ AgentProgress::ToolCallStarted {
+ display_label,
+ display_detail,
+ ..
+ } => started_label = Some((display_label, display_detail)),
+ AgentProgress::ToolCallCompleted {
+ display_label,
+ display_detail,
+ ..
+ } => completed = Some((display_label, display_detail)),
+ _ => {}
+ }
+ }
+
+ let (started_label, started_detail) = started_label.expect("ToolCallStarted projected");
+ assert_eq!(
+ started_label,
+ Some("Sending email".to_string()),
+ "the started label comes from the tool's own display_label, not a humanized name"
+ );
+ // No arguments exist yet at call-start, so the arg-derived detail is
+ // absent — this is recovered on the completed event below.
+ assert_eq!(started_detail, None);
+
+ let (completed_label, completed_detail) = completed.expect("ToolCallCompleted projected");
+ assert_eq!(completed_label, Some("Sending email".to_string()));
+ assert_eq!(
+ completed_detail,
+ Some("[email protected]".to_string()),
+ "the completed detail is recomputed from the real call arguments"
+ );
+}
+
+/// A running tool's progress report reaches the web channel as
+/// `ToolCallProgress` for the same call; an update with no message does not.
+#[tokio::test]
+async fn bridge_forwards_tool_progress_with_a_message() {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
+ let bridge = OpenhumanEventBridge::new(Some(tx), "mock-model", 10);
+ let sink = EventSink::new();
+ sink.subscribe(bridge.clone());
+
+ sink.emit(AgentEvent::ToolProgressDetail {
+ call_id: "c1".into(),
+ message: "running 4m 12s · 38.2 KB output".to_string(),
+ fraction: None,
+ partial: None,
+ });
+ sink.emit(AgentEvent::ToolProgressDetail {
+ call_id: "c1".into(),
+ message: String::new(),
+ fraction: Some(0.5),
+ partial: None,
+ });
+
+ let mut progress = Vec::new();
+ while let Ok(p) = rx.try_recv() {
+ if let AgentProgress::ToolCallProgress { call_id, message } = p {
+ progress.push((call_id, message));
+ }
+ }
+ assert_eq!(
+ progress,
+ vec![(
+ "c1".to_string(),
+ "running 4m 12s · 38.2 KB output".to_string()
+ )]
+ );
+}
+
+#[tokio::test]
+async fn only_a_top_level_turn_announces_its_compaction() {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(8);
+ OpenhumanEventBridge::new(Some(tx), "mock-model", 10).announce_compaction();
+ assert!(matches!(
+ rx.try_recv(),
+ Ok(AgentProgress::ContextCompacting)
+ ));
+
+ let (tx, mut rx) = tokio::sync::mpsc::channel(8);
+ OpenhumanEventBridge::with_scope(
+ Some(tx),
+ "mock-model",
+ "custom",
+ 10,
+ Some(SubagentScope {
+ agent_id: "researcher".into(),
+ task_id: "t1".into(),
+ extended_policy: false,
+ }),
+ Arc::default(),
+ Arc::default(),
+ Arc::default(),
+ Arc::default(),
+ Vec::new(),
+ crate::core::runtime::DispatchCtx::unbound(),
+ )
+ .announce_compaction();
+ assert!(rx.try_recv().is_err());
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs
index d113168b98..16d92df42c 100644
--- a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs
@@ -565,216 +565,6 @@ async fn unknown_tool_call_in_a_child_run_projects_one_subagent_row() {
/// its `after_model` folded, on top of the runtime's own emit) must be
/// recorded into the bridge accounting **exactly once**. Without the dedupe
/// guard the totals would double.
-#[tokio::test]
-async fn duplicate_usage_for_same_model_call_is_recorded_once() {
- let (tx, mut rx) = tokio::sync::mpsc::channel(64);
- let bridge = OpenhumanEventBridge::new(Some(tx), "mock-model", 10);
- let sink = EventSink::new();
- sink.subscribe(bridge.clone());
-
- // One model call → one `ModelStarted` (iteration cursor → 1).
- sink.emit(AgentEvent::ModelStarted {
- call_id: "c1".into(),
- model: "mock-model".to_string(),
- });
- // Same call surfaces usage twice (runtime emit + BudgetMiddleware re-emit).
- sink.emit(AgentEvent::UsageRecorded {
- usage: Usage::new(100, 40),
- });
- sink.emit(AgentEvent::UsageRecorded {
- usage: Usage::new(100, 40),
- });
-
- // Totals reflect a single record, not two.
- let (input, output, _) = bridge.totals();
- assert_eq!(
- (input, output),
- (100, 40),
- "the duplicate UsageRecorded for the same iteration must be skipped"
- );
-
- // Exactly one `TurnCostUpdated` footer emit for the call.
- let mut cost_updates = 0;
- while let Ok(p) = rx.try_recv() {
- if matches!(p, AgentProgress::TurnCostUpdated { .. }) {
- cost_updates += 1;
- }
- }
- assert_eq!(cost_updates, 1, "footer must update once per model call");
-
- // A genuinely new model call (iteration cursor → 2) records again.
- sink.emit(AgentEvent::ModelStarted {
- call_id: "c2".into(),
- model: "mock-model".to_string(),
- });
- sink.emit(AgentEvent::UsageRecorded {
- usage: Usage::new(10, 5),
- });
- let (input, output, _) = bridge.totals();
- assert_eq!(
- (input, output),
- (110, 45),
- "a distinct model call (new iteration) must still record"
- );
-}
-
-// NOTE: the former `sentinel_tool_started_is_not_forwarded` test was removed
-// here. The #4249 migration (commit 60097ba8d, "use sdk unknown tool
-// recovery") deleted `UNKNOWN_TOOL_SENTINEL` + `UnknownToolRewriteMiddleware`
-// in favour of the crate `UnknownToolPolicy::ReturnToolError` path, so a
-// `ToolStarted` now only ever fires for real, model-visible tools (see the
-// `ToolStarted` arm above — it no longer special-cases a sentinel). The test
-// referenced the deleted constant (a stale reference reintroduced by a merge)
-// and asserted behaviour that no longer exists.
-
-/// #6XXX (tool-call presentation): `ToolCallStarted`/`ToolCallCompleted` must
-/// carry the tool's OWN `display_label`/`display_detail` when the bridge was
-/// built with the turn's tool sets, not a name-derived guess — proven with a
-/// fake tool whose label is a fixed phrase and whose detail comes from a
-/// `"to"` argument only known once the call completes.
-#[tokio::test]
-async fn tool_call_events_use_the_tool_s_own_display_label_and_detail() {
- let (tx, mut rx) = tokio::sync::mpsc::channel(64);
- let bridge = OpenhumanEventBridge::with_scope(
- Some(tx),
- "mock-model",
- "managed",
- 10,
- None,
- Arc::default(),
- Arc::default(),
- Arc::default(),
- Arc::default(),
- fake_tool_sets(),
- crate::core::runtime::DispatchCtx::ambient(),
- );
- let sink = EventSink::new();
- sink.subscribe(bridge.clone());
-
- sink.emit(AgentEvent::ModelStarted {
- call_id: "c1".into(),
- model: "mock-model".to_string(),
- });
- sink.emit(AgentEvent::ToolStarted {
- parent_call_id: None,
- call_id: "c1".into(),
- tool_name: "fake_send_email".to_string(),
- input: None,
- });
- sink.emit(AgentEvent::ToolCompleted {
- parent_call_id: None,
- call_id: "c1".into(),
- tool_name: "fake_send_email".to_string(),
- started_at_ms: None,
- input: Some(serde_json::json!({"to": "[email protected]"})),
- output: Some(serde_json::Value::String("sent".to_string())),
- duration_ms: Some(5),
- output_bytes: Some(4),
- error: None,
- metadata: None,
- });
- let mut started_label = None;
- let mut completed = None;
- while let Ok(p) = rx.try_recv() {
- match p {
- AgentProgress::ToolCallStarted {
- display_label,
- display_detail,
- ..
- } => started_label = Some((display_label, display_detail)),
- AgentProgress::ToolCallCompleted {
- display_label,
- display_detail,
- ..
- } => completed = Some((display_label, display_detail)),
- _ => {}
- }
- }
-
- let (started_label, started_detail) = started_label.expect("ToolCallStarted projected");
- assert_eq!(
- started_label,
- Some("Sending email".to_string()),
- "the started label comes from the tool's own display_label, not a humanized name"
- );
- // No arguments exist yet at call-start, so the arg-derived detail is
- // absent — this is recovered on the completed event below.
- assert_eq!(started_detail, None);
-
- let (completed_label, completed_detail) = completed.expect("ToolCallCompleted projected");
- assert_eq!(completed_label, Some("Sending email".to_string()));
- assert_eq!(
- completed_detail,
- Some("[email protected]".to_string()),
- "the completed detail is recomputed from the real call arguments"
- );
-}
-
-/// A running tool's progress report reaches the web channel as
-/// `ToolCallProgress` for the same call; an update with no message does not.
-#[tokio::test]
-async fn bridge_forwards_tool_progress_with_a_message() {
- let (tx, mut rx) = tokio::sync::mpsc::channel(64);
- let bridge = OpenhumanEventBridge::new(Some(tx), "mock-model", 10);
- let sink = EventSink::new();
- sink.subscribe(bridge.clone());
-
- sink.emit(AgentEvent::ToolProgressDetail {
- call_id: "c1".into(),
- message: "running 4m 12s · 38.2 KB output".to_string(),
- fraction: None,
- partial: None,
- });
- sink.emit(AgentEvent::ToolProgressDetail {
- call_id: "c1".into(),
- message: String::new(),
- fraction: Some(0.5),
- partial: None,
- });
-
- let mut progress = Vec::new();
- while let Ok(p) = rx.try_recv() {
- if let AgentProgress::ToolCallProgress { call_id, message } = p {
- progress.push((call_id, message));
- }
- }
- assert_eq!(
- progress,
- vec![(
- "c1".to_string(),
- "running 4m 12s · 38.2 KB output".to_string()
- )]
- );
-}
-
-#[tokio::test]
-async fn only_a_top_level_turn_announces_its_compaction() {
- let (tx, mut rx) = tokio::sync::mpsc::channel(8);
- OpenhumanEventBridge::new(Some(tx), "mock-model", 10).announce_compaction();
- assert!(matches!(
- rx.try_recv(),
- Ok(AgentProgress::ContextCompacting)
- ));
-
- let (tx, mut rx) = tokio::sync::mpsc::channel(8);
- OpenhumanEventBridge::with_scope(
- Some(tx),
- "mock-model",
- "custom",
- 10,
- Some(SubagentScope {
- agent_id: "researcher".into(),
- task_id: "t1".into(),
- extended_policy: false,
- }),
- Arc::default(),
- Arc::default(),
- Arc::default(),
- Arc::default(),
- Vec::new(),
- crate::core::runtime::DispatchCtx::unbound(),
- )
- .announce_compaction();
- assert!(rx.try_recv().is_err());
-}
+#[path = "observability_projection_tests.rs"]
+mod projection_tests;
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror_observe_tests.rs b/crates/openhuman-core/src/threads/turn_state/mirror_observe_tests.rs
index de456e2b37..90f1b24dec 100644
--- a/crates/openhuman-core/src/threads/turn_state/mirror_observe_tests.rs
+++ b/crates/openhuman-core/src/threads/turn_state/mirror_observe_tests.rs
@@ -539,213 +539,5 @@ fn subagent_lifecycle_records_and_clears_active() {
assert!(s.active_subagent.is_none());
}
-#[test]
-fn thinking_blocks_record_start_and_end_timing() {
- // Regression: the "Thought for Ns" label reads these; a coalesced block
- // must keep its first-delta start and advance its end, and a new round's
- // block must open with its own start.
- let (_d, mut m) = fresh("t");
- m.observe(&AgentProgress::ThinkingDelta {
- delta: "First ".into(),
- iteration: 1,
- });
- let first_start = match &m.snapshot().transcript[0] {
- TranscriptItem::Thinking { started_at, .. } => started_at.expect("started_at stamped"),
- other => panic!("expected thinking, got {other:?}"),
- };
- std::thread::sleep(std::time::Duration::from_millis(5));
- m.observe(&AgentProgress::ThinkingDelta {
- delta: "round.".into(),
- iteration: 1,
- });
- m.observe(&AgentProgress::ThinkingDelta {
- delta: "Second round.".into(),
- iteration: 2,
- });
-
- let s = m.snapshot();
- assert_eq!(s.transcript.len(), 2, "one block per round");
- match &s.transcript[0] {
- TranscriptItem::Thinking {
- started_at,
- ended_at,
- text,
- ..
- } => {
- assert_eq!(text, "First round.");
- assert_eq!(*started_at, Some(first_start), "start is the first delta");
- let end = ended_at.expect("ended_at stamped");
- assert!(end > first_start, "end advances on coalesced deltas");
- }
- other => panic!("expected thinking, got {other:?}"),
- }
- match &s.transcript[1] {
- TranscriptItem::Thinking {
- started_at,
- ended_at,
- ..
- } => {
- let (start, end) = (started_at.unwrap(), ended_at.unwrap());
- assert!(start >= first_start && end >= start);
- }
- other => panic!("expected thinking, got {other:?}"),
- }
-}
-
-#[test]
-fn thinking_timing_wire_shape_is_camel_case_and_backward_compatible() {
- // The frontend reads `startedAt` / `endedAt`; rows persisted before timing
- // existed must still deserialize (as `None`) and must not grow the fields.
- let item = TranscriptItem::Thinking {
- round: 1,
- seq: 0,
- text: "t".into(),
- started_at: Some(1_000),
- ended_at: Some(13_000),
- };
- let json = serde_json::to_value(&item).unwrap();
- assert_eq!(json["kind"], "thinking");
- assert_eq!(json["startedAt"], 1_000);
- assert_eq!(json["endedAt"], 13_000);
-
- let legacy: TranscriptItem =
- serde_json::from_value(serde_json::json!({"kind":"thinking","round":1,"seq":0,"text":"t"}))
- .unwrap();
- match &legacy {
- TranscriptItem::Thinking {
- started_at,
- ended_at,
- ..
- } => assert!(started_at.is_none() && ended_at.is_none()),
- other => panic!("expected thinking, got {other:?}"),
- }
- let reserialized = serde_json::to_value(&legacy).unwrap();
- assert!(reserialized.get("startedAt").is_none());
- assert!(reserialized.get("endedAt").is_none());
-}
-
-// ── C1: parent_call_id / source_tool_name derivation ─────────────────────
-
-#[test]
-fn subagent_spawned_derives_source_tool_name_from_the_parent_row() {
- // Only `spawn_subagent` ever hardcoded a "spawn_subagent" source. Every
- // other delegation path (`spawn_parallel_agents`, `spawn_async_subagent`,
- // a synthesized `delegate_researcher`, …) must show its own real tool
- // name, derived from the parent call's row by `parent_call_id` — never
- // the historical hardcoded default.
- let (_d, mut m) = fresh("t");
- m.observe(&AgentProgress::ToolCallStarted {
- call_id: "call-parallel".into(),
- tool_name: "spawn_parallel_agents".into(),
- arguments: serde_json::json!({}),
- iteration: 1,
- display_label: None,
- display_detail: None,
- });
- m.observe(&AgentProgress::SubagentSpawned {
- agent_id: "researcher".into(),
- task_id: "sub-1".into(),
- mode: "typed".into(),
- dedicated_thread: false,
- prompt_chars: 4,
- prompt: "help".into(),
- worker_thread_id: None,
- display_name: None,
- parent_call_id: Some("call-parallel".into()),
- });
-
- let entry = m
- .snapshot()
- .tool_timeline
- .iter()
- .find(|e| e.id == "subagent:sub-1")
- .cloned()
- .expect("subagent row created");
- assert_eq!(
- entry.source_tool_name.as_deref(),
- Some("spawn_parallel_agents")
- );
- let activity = entry.subagent.expect("subagent activity present");
- assert_eq!(activity.parent_call_id.as_deref(), Some("call-parallel"));
-}
-
-#[test]
-fn subagent_spawned_falls_back_to_spawn_subagent_without_a_parent_call_id() {
- // No `parent_call_id` (e.g. the `orchestration::ops` spawn path, which
- // has no tool-call context to read one from) keeps the historical
- // default so existing snapshots/consumers don't regress.
- let (_d, mut m) = fresh("t");
- m.observe(&AgentProgress::SubagentSpawned {
- agent_id: "researcher".into(),
- task_id: "sub-2".into(),
- mode: "typed".into(),
- dedicated_thread: false,
- prompt_chars: 4,
- prompt: "help".into(),
- worker_thread_id: None,
- display_name: None,
- parent_call_id: None,
- });
-
- let entry = m
- .snapshot()
- .tool_timeline
- .iter()
- .find(|e| e.id == "subagent:sub-2")
- .cloned()
- .expect("subagent row created");
- assert_eq!(entry.source_tool_name.as_deref(), Some("spawn_subagent"));
- let activity = entry.subagent.expect("subagent activity present");
- assert_eq!(activity.parent_call_id, None);
-}
-
-#[test]
-fn subagent_completed_persists_capped_output_on_the_activity() {
- let (_d, mut m) = fresh("t");
- m.observe(&AgentProgress::SubagentSpawned {
- agent_id: "researcher".into(),
- task_id: "sub-3".into(),
- mode: "typed".into(),
- dedicated_thread: false,
- prompt_chars: 4,
- prompt: "help".into(),
- worker_thread_id: None,
- display_name: None,
- parent_call_id: Some("call-3".into()),
- });
- m.observe(&AgentProgress::SubagentCompleted {
- agent_id: "researcher".into(),
- task_id: "sub-3".into(),
- elapsed_ms: 5,
- iterations: 1,
- output_chars: 11,
- usage: None,
- output: "final answer".into(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- stop: None,
- });
-
- let entry = m
- .snapshot()
- .tool_timeline
- .iter()
- .find(|e| e.id == "subagent:sub-3")
- .cloned()
- .expect("subagent row created");
- let activity = entry.subagent.expect("subagent activity present");
- assert_eq!(activity.output.as_deref(), Some("final answer"));
- assert_eq!(activity.parent_call_id.as_deref(), Some("call-3"));
-}
-
-#[test]
-fn compacting_neither_flushes_nor_changes_the_phase() {
- let (_d, mut m) = fresh("t");
- m.observe(&AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 25,
- });
- assert!(!m.observe(&AgentProgress::ContextCompacting));
- assert_eq!(m.snapshot().phase, Some(TurnPhase::Thinking));
-}
+#[path = "mirror_observe_thinking_and_subagent_tests.rs"]
+mod thinking_and_subagent_tests;
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror_observe_thinking_and_subagent_tests.rs b/crates/openhuman-core/src/threads/turn_state/mirror_observe_thinking_and_subagent_tests.rs
new file mode 100644
index 0000000000..fb87fab9c1
--- /dev/null
+++ b/crates/openhuman-core/src/threads/turn_state/mirror_observe_thinking_and_subagent_tests.rs
@@ -0,0 +1,212 @@
+use super::*;
+
+#[test]
+fn thinking_blocks_record_start_and_end_timing() {
+ // Regression: the "Thought for Ns" label reads these; a coalesced block
+ // must keep its first-delta start and advance its end, and a new round's
+ // block must open with its own start.
+ let (_d, mut m) = fresh("t");
+ m.observe(&AgentProgress::ThinkingDelta {
+ delta: "First ".into(),
+ iteration: 1,
+ });
+ let first_start = match &m.snapshot().transcript[0] {
+ TranscriptItem::Thinking { started_at, .. } => started_at.expect("started_at stamped"),
+ other => panic!("expected thinking, got {other:?}"),
+ };
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ m.observe(&AgentProgress::ThinkingDelta {
+ delta: "round.".into(),
+ iteration: 1,
+ });
+ m.observe(&AgentProgress::ThinkingDelta {
+ delta: "Second round.".into(),
+ iteration: 2,
+ });
+
+ let s = m.snapshot();
+ assert_eq!(s.transcript.len(), 2, "one block per round");
+ match &s.transcript[0] {
+ TranscriptItem::Thinking {
+ started_at,
+ ended_at,
+ text,
+ ..
+ } => {
+ assert_eq!(text, "First round.");
+ assert_eq!(*started_at, Some(first_start), "start is the first delta");
+ let end = ended_at.expect("ended_at stamped");
+ assert!(end > first_start, "end advances on coalesced deltas");
+ }
+ other => panic!("expected thinking, got {other:?}"),
+ }
+ match &s.transcript[1] {
+ TranscriptItem::Thinking {
+ started_at,
+ ended_at,
+ ..
+ } => {
+ let (start, end) = (started_at.unwrap(), ended_at.unwrap());
+ assert!(start >= first_start && end >= start);
+ }
+ other => panic!("expected thinking, got {other:?}"),
+ }
+}
+
+#[test]
+fn thinking_timing_wire_shape_is_camel_case_and_backward_compatible() {
+ // The frontend reads `startedAt` / `endedAt`; rows persisted before timing
+ // existed must still deserialize (as `None`) and must not grow the fields.
+ let item = TranscriptItem::Thinking {
+ round: 1,
+ seq: 0,
+ text: "t".into(),
+ started_at: Some(1_000),
+ ended_at: Some(13_000),
+ };
+ let json = serde_json::to_value(&item).unwrap();
+ assert_eq!(json["kind"], "thinking");
+ assert_eq!(json["startedAt"], 1_000);
+ assert_eq!(json["endedAt"], 13_000);
+
+ let legacy: TranscriptItem =
+ serde_json::from_value(serde_json::json!({"kind":"thinking","round":1,"seq":0,"text":"t"}))
+ .unwrap();
+ match &legacy {
+ TranscriptItem::Thinking {
+ started_at,
+ ended_at,
+ ..
+ } => assert!(started_at.is_none() && ended_at.is_none()),
+ other => panic!("expected thinking, got {other:?}"),
+ }
+ let reserialized = serde_json::to_value(&legacy).unwrap();
+ assert!(reserialized.get("startedAt").is_none());
+ assert!(reserialized.get("endedAt").is_none());
+}
+
+// ── C1: parent_call_id / source_tool_name derivation ─────────────────────
+
+#[test]
+fn subagent_spawned_derives_source_tool_name_from_the_parent_row() {
+ // Only `spawn_subagent` ever hardcoded a "spawn_subagent" source. Every
+ // other delegation path (`spawn_parallel_agents`, `spawn_async_subagent`,
+ // a synthesized `delegate_researcher`, …) must show its own real tool
+ // name, derived from the parent call's row by `parent_call_id` — never
+ // the historical hardcoded default.
+ let (_d, mut m) = fresh("t");
+ m.observe(&AgentProgress::ToolCallStarted {
+ call_id: "call-parallel".into(),
+ tool_name: "spawn_parallel_agents".into(),
+ arguments: serde_json::json!({}),
+ iteration: 1,
+ display_label: None,
+ display_detail: None,
+ });
+ m.observe(&AgentProgress::SubagentSpawned {
+ agent_id: "researcher".into(),
+ task_id: "sub-1".into(),
+ mode: "typed".into(),
+ dedicated_thread: false,
+ prompt_chars: 4,
+ prompt: "help".into(),
+ worker_thread_id: None,
+ display_name: None,
+ parent_call_id: Some("call-parallel".into()),
+ });
+
+ let entry = m
+ .snapshot()
+ .tool_timeline
+ .iter()
+ .find(|e| e.id == "subagent:sub-1")
+ .cloned()
+ .expect("subagent row created");
+ assert_eq!(
+ entry.source_tool_name.as_deref(),
+ Some("spawn_parallel_agents")
+ );
+ let activity = entry.subagent.expect("subagent activity present");
+ assert_eq!(activity.parent_call_id.as_deref(), Some("call-parallel"));
+}
+
+#[test]
+fn subagent_spawned_falls_back_to_spawn_subagent_without_a_parent_call_id() {
+ // No `parent_call_id` (e.g. the `orchestration::ops` spawn path, which
+ // has no tool-call context to read one from) keeps the historical
+ // default so existing snapshots/consumers don't regress.
+ let (_d, mut m) = fresh("t");
+ m.observe(&AgentProgress::SubagentSpawned {
+ agent_id: "researcher".into(),
+ task_id: "sub-2".into(),
+ mode: "typed".into(),
+ dedicated_thread: false,
+ prompt_chars: 4,
+ prompt: "help".into(),
+ worker_thread_id: None,
+ display_name: None,
+ parent_call_id: None,
+ });
+
+ let entry = m
+ .snapshot()
+ .tool_timeline
+ .iter()
+ .find(|e| e.id == "subagent:sub-2")
+ .cloned()
+ .expect("subagent row created");
+ assert_eq!(entry.source_tool_name.as_deref(), Some("spawn_subagent"));
+ let activity = entry.subagent.expect("subagent activity present");
+ assert_eq!(activity.parent_call_id, None);
+}
+
+#[test]
+fn subagent_completed_persists_capped_output_on_the_activity() {
+ let (_d, mut m) = fresh("t");
+ m.observe(&AgentProgress::SubagentSpawned {
+ agent_id: "researcher".into(),
+ task_id: "sub-3".into(),
+ mode: "typed".into(),
+ dedicated_thread: false,
+ prompt_chars: 4,
+ prompt: "help".into(),
+ worker_thread_id: None,
+ display_name: None,
+ parent_call_id: Some("call-3".into()),
+ });
+ m.observe(&AgentProgress::SubagentCompleted {
+ agent_id: "researcher".into(),
+ task_id: "sub-3".into(),
+ elapsed_ms: 5,
+ iterations: 1,
+ output_chars: 11,
+ usage: None,
+ output: "final answer".into(),
+ worktree_path: None,
+ changed_files: Vec::new(),
+ dirty_status: None,
+ stop: None,
+ });
+
+ let entry = m
+ .snapshot()
+ .tool_timeline
+ .iter()
+ .find(|e| e.id == "subagent:sub-3")
+ .cloned()
+ .expect("subagent row created");
+ let activity = entry.subagent.expect("subagent activity present");
+ assert_eq!(activity.output.as_deref(), Some("final answer"));
+ assert_eq!(activity.parent_call_id.as_deref(), Some("call-3"));
+}
+
+#[test]
+fn compacting_neither_flushes_nor_changes_the_phase() {
+ let (_d, mut m) = fresh("t");
+ m.observe(&AgentProgress::IterationStarted {
+ iteration: 1,
+ max_iterations: 25,
+ });
+ assert!(!m.observe(&AgentProgress::ContextCompacting));
+ assert_eq!(m.snapshot().phase, Some(TurnPhase::Thinking));
+}