Skip to content

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

Merge remote-tracking branch 'upstream/main' into tool-call-presentation

Steven Enamakel7bd075f53418
diff --cc app/src/features/conversations/components/AssistantUiToolCall.test.tsx
index 6b736e30a6,0000000000..a65308061f
mode 100644,000000..100644
--- a/app/src/features/conversations/components/AssistantUiToolCall.test.tsx
+++ b/app/src/features/conversations/components/AssistantUiToolCall.test.tsx
@@@ -1,156 -1,0 +1,131 @@@
+import { render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { describe, expect, it } from 'vitest';
+
+import { AssistantUiToolCallCard, formatElapsed } from './AssistantUiToolCall';
- import { ChatToolGroup } from './ChatToolParts';
+
+const SEARCH_TEXT = [
+ 'Search results for: rust async traits (via Exa)',
+ '1. Async fn in traits',
+ ' https://blog.rust-lang.org/async-fn',
+ ' Stable in 1.75.',
+ '2. Bad link',
+ ' javascript:alert(1)',
+].join('\n');
+
+describe('AssistantUiToolCallCard', () => {
+ it('renders a web search through the web-search element, visible without expanding', () => {
+ render(
+ <AssistantUiToolCallCard
+ toolName="web_search_tool"
+ args={{ query: 'rust async traits' }}
+ result={SEARCH_TEXT}
+ status="success"
+ elapsedMs={1840}
+ />
+ );
+ const results = screen.getByTestId('web-search-results');
+ expect(results).toHaveTextContent('rust async traits');
+ expect(results).toHaveTextContent('Found 1 result · via Exa');
+ const hits = within(results).getAllByTestId('web-search-hit');
+ expect(hits).toHaveLength(1);
+ expect(hits[0]).toHaveAttribute('href', 'https://blog.rust-lang.org/async-fn');
+ // The javascript: hit never becomes a link or a row.
+ expect(results).not.toHaveTextContent('Bad link');
+ expect(screen.getByTestId('tool-call-elapsed')).toHaveTextContent('1.8s');
+ });
+
+ it('prefers the structured search payload the core attaches', () => {
+ render(
+ <AssistantUiToolCallCard
+ toolName="web_search_tool"
+ args={{ query: 'q' }}
+ result="unparseable"
+ structured={{
+ kind: 'web_search',
+ query: 'q',
+ provider: 'Parallel',
+ results: [{ title: 'From payload', url: 'https://a.dev/x' }],
+ }}
+ status="success"
+ />
+ );
+ expect(screen.getByTestId('web-search-results')).toHaveTextContent('From payload');
+ expect(screen.getByTestId('web-search-results')).toHaveTextContent('via Parallel');
+ });
+
+ it('swaps the label tense as the call settles', () => {
+ const { rerender } = render(
+ <AssistantUiToolCallCard toolName="file_read" args={{ path: 'a.ts' }} status="running" />
+ );
+ const card = screen.getByTestId('assistant-ui-tool-call');
+ expect(card).toHaveAttribute('data-outcome', 'running');
+ expect(within(card).getByRole('button', { name: /Reading file/ })).toBeInTheDocument();
+ rerender(
+ <AssistantUiToolCallCard
+ toolName="file_read"
+ args={{ path: 'a.ts' }}
+ status="success"
+ result="x"
+ />
+ );
+ expect(card).toHaveAttribute('data-outcome', 'success');
+ expect(within(card).getByRole('button', { name: /Read file/ })).toBeInTheDocument();
+ });
+
+ it('spells out states that need attention and keeps the rest for screen readers', () => {
+ render(
+ <>
+ <AssistantUiToolCallCard toolName="grep" status="error" result="bad regex" />
+ <AssistantUiToolCallCard toolName="shell" status="success" result="ok" />
+ </>
+ );
+ const [failed, done] = screen.getAllByTestId('tool-call-status');
+ expect(failed).toHaveTextContent('failed');
+ expect(failed).not.toHaveClass('sr-only');
+ expect(done).toHaveTextContent('done');
+ expect(done).toHaveClass('sr-only');
+ });
+
+ it('expands an edit into the code-diff element and a read into a code block', async () => {
+ render(
+ <>
+ <AssistantUiToolCallCard
+ toolName="edit"
+ args={{ path: 'a.ts', old_string: 'old', new_string: 'new' }}
+ status="success"
+ result="ok"
+ />
+ <AssistantUiToolCallCard
+ toolName="file_read"
+ args={{ path: 'src/b.rs' }}
+ status="success"
+ result="fn main() {}"
+ />
+ </>
+ );
+ const [edit, read] = screen.getAllByTestId('assistant-ui-tool-call');
+ await userEvent.click(within(edit).getByRole('button', { name: /Edited file/ }));
+ const diff = screen.getByTestId('tool-body-file-diff');
+ expect(diff).toHaveTextContent('+1');
+ expect(diff).toHaveTextContent('old');
+ await userEvent.click(within(read).getByRole('button', { name: /Read file/ }));
+ expect(screen.getByTestId('tool-body-file')).toHaveTextContent('fn main() {}');
+ });
+
+ it('names a connected-app action by its app, never the slug', () => {
+ render(<AssistantUiToolCallCard toolName="GMAIL_SEND_EMAIL" status="success" result="ok" />);
+ const card = screen.getByTestId('assistant-ui-tool-call');
+ expect(card).toHaveTextContent('Used Gmail');
+ expect(card).toHaveTextContent('Send email');
+ expect(card).not.toHaveTextContent('GMAIL_SEND_EMAIL');
+ });
+});
+
- describe('ChatToolGroup', () => {
- it('renders a lone call without a timeline header', () => {
- render(
- <ChatToolGroup group={{ type: 'group-tool', status: { type: 'complete' }, indices: [0] }}>
- <span>only step</span>
- </ChatToolGroup>
- );
- expect(screen.getByText('only step')).toBeVisible();
- expect(screen.queryByTestId('tool-timeline')).toBeNull();
- });
-
- it('wraps several calls in the assistant-ui tool timeline', () => {
- render(
- <ChatToolGroup group={{ type: 'group-tool', status: { type: 'running' }, indices: [0, 1] }}>
- <span>step one</span>
- <span>step two</span>
- </ChatToolGroup>
- );
- const timeline = screen.getByTestId('tool-timeline');
- expect(timeline).toHaveAttribute('data-slot', 'tool-timeline');
- expect(screen.getByText('step two')).toBeVisible();
- });
- });
-
+describe('formatElapsed', () => {
+ it('formats milliseconds, seconds and minutes', () => {
+ expect(formatElapsed(850)).toBe('850ms');
+ expect(formatElapsed(1840)).toBe('1.8s');
+ expect(formatElapsed(75_000)).toBe('1m 15s');
+ });
+});
diff --cc app/src/pages/__tests__/Conversations.render.test.tsx
index bee4eaec53,6f02d5dfae..a754245daa
--- a/app/src/pages/__tests__/Conversations.render.test.tsx
+++ b/app/src/pages/__tests__/Conversations.render.test.tsx
@@@ -630,8 -630,10 +630,10 @@@ describe('Conversations — smoke rende
});
});
- // The past turn's core transcript is projected into assistant-ui exactly once.
+ // The past turn's core transcript is projected into one settled activity
+ // group. Open it before checking the contained tool card.
+ fireEvent.click(await screen.findByRole('button', { name: '1 tool call' }));
- expect(await screen.findByTestId('assistant-ui-tool-call')).toHaveTextContent('Read File');
+ expect(await screen.findByTestId('assistant-ui-tool-call')).toHaveTextContent('Read file');
});
it('keeps assistant message copy available through assistant-ui', async () => {
diff --cc crates/openhuman-core/src/agent/learning/transcript_ingest/transcript_ingest_tests.rs
index f061e7793b,f061e7793b..cb485c16f9
--- a/crates/openhuman-core/src/agent/learning/transcript_ingest/transcript_ingest_tests.rs
+++ b/crates/openhuman-core/src/agent/learning/transcript_ingest/transcript_ingest_tests.rs
@@@ -203,6 -203,6 +203,7 @@@ async fn ingest_extracts_high_importanc
let mem = InMemory::new();
let transcript = SessionTranscript {
meta: fake_meta(Some("thr_alpha")),
++ tools: None,
messages: durable_messages([
ChatMessage::user("hi"),
ChatMessage::assistant("hello"),
@@@ -237,6 -237,6 +238,7 @@@ async fn re_ingest_is_idempotent()
let mem = InMemory::new();
let transcript = SessionTranscript {
meta: fake_meta(Some("thr_beta")),
++ tools: None,
messages: durable_messages([ChatMessage::user(
"I prefer Postgres for everything new — please default to it.",
)]),
@@@ -261,6 -261,6 +263,7 @@@ async fn ingest_captures_user_reflectio
let mem = InMemory::new();
let transcript = SessionTranscript {
meta: fake_meta(Some("thr_gamma")),
++ tools: None,
messages: durable_messages([
ChatMessage::user("I prefer terse responses with no preamble."),
ChatMessage::user("Going forward I want code-first answers."),
@@@ -297,6 -297,6 +300,7 @@@ async fn ingest_filters_low_signal_chat
let mem = InMemory::new();
let transcript = SessionTranscript {
meta: fake_meta(None),
++ tools: None,
messages: durable_messages([
ChatMessage::user("ok"),
ChatMessage::user("thanks!"),
@@@ -324,6 -324,6 +328,7 @@@ async fn ingest_persists_candidates_wit
// stores in flight at once — the bound assertion below would then fail.
let transcript = SessionTranscript {
meta: fake_meta(Some("thr_bound")),
++ tools: None,
messages: durable_messages([
ChatMessage::user("I prefer Postgres over MySQL for new metadata services."),
ChatMessage::user("I prefer tabs over spaces in our Go codebase."),
diff --cc crates/openhuman-core/src/agent/session_host/codec.rs
index ea36bb310e,bd553be830..0db8d0f8c4
--- a/crates/openhuman-core/src/agent/session_host/codec.rs
+++ b/crates/openhuman-core/src/agent/session_host/codec.rs
@@@ -178,12 -164,16 +178,18 @@@ impl TranscriptCodec<OpenHumanRunContex
},
ts: chrono::Utc::now().to_rfc3339(),
reasoning_content: None,
- // The writer attaches this record to the turn's *final* assistant
- // row. A call belongs to the row that issued it — the native
- // envelope, or `attach_text_dialect_rounds` for a text dialect —
- // so listing the turn's calls here filed every one of them under
- // the answer that followed their results, and the projection
- // reported them as never settled.
+ // Deliberately empty. `TurnUsage` lands on the turn's *final*
+ // assistant row, and the transcript writer falls back to
+ // `tool_calls` here for any assistant row whose own content is not
+ // a native tool-call envelope — i.e. the plain-text final answer.
+ // Filling it with every outcome of the turn wrote each tool call a
+ // second time onto that answer, so a reader projected the answer
+ // as an interim step followed by duplicate, never-settled tool
+ // rows (which also mis-paired later FIFO results). Each call is
+ // already recorded, once, in the envelope of the assistant row
+ // that issued it.
++ // A text dialect has no envelope; `attach_text_dialect_rounds` files
++ // each round's calls on its issuing row instead.
tool_calls: Vec::new(),
iteration: sidecar.model_calls.min(u32::MAX as usize) as u32,
}))
diff --cc crates/openhuman-core/src/agent/session_import/live_tests.rs
index 277a76acdf,277a76acdf..f3eb844608
--- a/crates/openhuman-core/src/agent/session_import/live_tests.rs
+++ b/crates/openhuman-core/src/agent/session_import/live_tests.rs
@@@ -318,6 -318,6 +318,7 @@@ async fn in_memory_store_reconstruction
attach_chat_turn_usage_metadata(&mut live_messages[last_assistant], &usage);
let reconstructed = SessionTranscript {
meta: meta.clone(),
++ tools: None,
messages: durable_messages(&live_messages),
};
write_live_turn(ws.path(), stem, &reconstructed)
@@@ -353,6 -353,6 +354,7 @@@ async fn shadow_read_unavailable_and_di
// transcript → Unavailable (no shadow), never a divergence.
let legacy = SessionTranscript {
meta: meta.clone(),
++ tools: None,
messages: durable_messages(&[ChatMessage::user("hi"), ChatMessage::assistant("done")]),
};
assert_eq!(
@@@ -368,6 -368,6 +370,7 @@@
.expect("live dual-write");
let diverging = SessionTranscript {
meta,
++ tools: None,
messages: durable_messages(&[
ChatMessage::user("hi"),
ChatMessage::assistant("done"),
diff --cc crates/openhuman-core/src/threads/transcript_view/mod.rs
index c9242a1df4,d94ae0ad7e..3ac807f937
--- a/crates/openhuman-core/src/threads/transcript_view/mod.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/mod.rs
@@@ -103,6 -105,7 +105,10 @@@ fn parse_cursor(cursor: Option<&str>) -
#[cfg(test)]
#[path = "transcript_view_tests.rs"]
mod tests;
+#[cfg(test)]
+#[path = "transcript_view_tool_round_tests.rs"]
+mod tool_round_tests;
+
+ #[cfg(test)]
+ #[path = "transcript_ordering_tests.rs"]
+ mod ordering_tests;
diff --cc crates/openhuman-core/src/threads/transcript_view/project.rs
index 681236cbab,3aa9924a3d..93e821c235
--- a/crates/openhuman-core/src/threads/transcript_view/project.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/project.rs
@@@ -10,10 -10,9 +10,12 @@@ use std::collections::{HashSet, VecDequ
use std::path::{Path, PathBuf};
use tinyagents_session::transcript::{self, CompactionMarker, DisplayMessage, DisplayRecord};
+use tinytools_agent::dialect::{parse_replayed_results, ToolResultEntry};
+
+use crate::agent::messages::TOOL_RESULT_FAILURES_METADATA_KEY;
+ use super::resolve;
+ use super::subagents;
use super::types::{DisplayItem, ProjectedTranscript, ToolCallFailure, ToolCallStatus};
const LOG_PREFIX: &str = "[threads][transcript]";
@@@ -328,88 -161,168 +164,191 @@@ pub fn project_records(records: &[Displ
}
}
}
- items
+ projector.items
}
- fn maybe_emit_turn_boundary(
- msg: &DisplayMessage,
- last_request_id: &mut Option<String>,
- items: &mut Vec<DisplayItem>,
- ) {
- let Some(rid) = msg.request_id.as_deref() else {
- return;
- };
- if last_request_id.as_deref() != Some(rid) {
- items.push(DisplayItem::TurnBoundary {
- request_id: rid.to_string(),
- });
- *last_request_id = Some(rid.to_string());
- }
+ #[derive(Default)]
+ struct Projector {
+ items: Vec<DisplayItem>,
+ /// Pending tool calls awaiting a result line: (call_id, index into `items`).
+ pending: VecDeque<(String, usize)>,
+ last_request_id: Option<String>,
+ /// Every tool-call id already projected, so a row repeating calls issued
+ /// earlier (the aggregate usage list) does not render them twice.
+ seen_call_ids: HashSet<String>,
+ /// The model-call ordinal of the last assistant row in the current turn —
+ /// the fallback `iteration` for rows written without one.
+ step: u32,
}
- fn project_message(
- msg: &DisplayMessage,
- items: &mut Vec<DisplayItem>,
- pending: &mut VecDeque<(String, usize)>,
- ) {
- // Interrupted partial: display-only, carries its own thinking.
- if msg.interrupted {
- items.push(DisplayItem::InterruptedPartial {
- text: msg.message.content.clone(),
- thinking: msg.reasoning_content.clone(),
- });
- return;
+ impl Projector {
+ fn turn_boundary(&mut self, msg: &DisplayMessage) {
+ let Some(rid) = msg.request_id.as_deref() else {
+ return;
+ };
+ if self.last_request_id.as_deref() != Some(rid) {
+ self.items.push(DisplayItem::TurnBoundary {
+ request_id: rid.to_string(),
+ });
+ self.last_request_id = Some(rid.to_string());
+ self.step = 0;
+ self.seen_call_ids.clear();
+ }
}
- match msg.message.role.as_str() {
- "system" => {
- // Scaffolding (tool-policy preamble, etc.) — never a display item.
- log::debug!("{LOG_PREFIX} sanitize: dropped system line from projection");
+ fn message(&mut self, msg: &DisplayMessage) {
+ // Interrupted partial: display-only, carries its own thinking.
+ if msg.interrupted {
+ self.items.push(DisplayItem::InterruptedPartial {
+ text: msg.message.content.clone(),
+ thinking: msg.reasoning_content.clone(),
+ });
+ return;
}
- "user" => {
- // A text dialect folds a round's results into one user turn; it is
- // tool output, never the user's words.
- if let Some(results) = parse_replayed_results(&msg.message.content) {
- project_text_tool_results(msg, results, items, pending);
- return;
+
+ match msg.message.role.as_str() {
+ "system" => {
+ // Scaffolding (tool-policy preamble, etc.) — never a display item.
+ log::debug!("{LOG_PREFIX} sanitize: dropped system line from projection");
}
- let raw = msg.message.content.clone();
- let sanitized = sanitize_user_content(&raw);
- if sanitized.is_some() {
- log::debug!("{LOG_PREFIX} sanitize: stripped injected prefix from user message");
+ "user" => {
++ // A text dialect folds a round's results into one user turn; it
++ // is tool output, never the user's words.
++ if let Some(results) = parse_replayed_results(&msg.message.content) {
++ self.text_tool_results(msg, results);
++ return;
++ }
+ // A legacy turn without request ids still restarts the step
+ // count at its prompt.
+ self.step = 0;
+ self.seen_call_ids.clear();
+ let raw = msg.message.content.clone();
+ let sanitized = sanitize_user_content(&raw);
+ if sanitized.is_some() {
+ log::debug!(
+ "{LOG_PREFIX} sanitize: stripped injected prefix from user message"
+ );
+ }
+ self.items.push(DisplayItem::UserMessage {
+ content: raw,
+ display_content: sanitized,
+ request_id: msg.request_id.clone(),
+ });
+ }
+ "assistant" => self.assistant(msg),
+ "tool" => self.tool_result(msg),
+ other => {
+ log::debug!("{LOG_PREFIX} projecting unknown role {other:?} as assistant message");
+ self.items.push(DisplayItem::AssistantMessage {
+ content: msg.message.content.clone(),
+ interim: false,
+ request_id: msg.request_id.clone(),
+ model: msg.turn_usage.as_ref().map(|tu| tu.model.clone()),
+ iteration: msg.iteration,
+ });
}
- items.push(DisplayItem::UserMessage {
- content: raw,
- display_content: sanitized,
- request_id: msg.request_id.clone(),
- });
}
- "assistant" => project_assistant(msg, items, pending),
- "tool" => project_tool_result(msg, items, pending),
- other => {
- log::debug!("{LOG_PREFIX} projecting unknown role {other:?} as assistant message");
- items.push(DisplayItem::AssistantMessage {
- content: msg.message.content.clone(),
- interim: false,
+ }
+
+ fn assistant(&mut self, msg: &DisplayMessage) {
+ // Rows the writer stamped keep their own number; earlier writers only
+ // stamped the final row, so unstamped rows count up within the turn.
+ let iteration = msg.iteration.unwrap_or(self.step + 1);
+ self.step = iteration;
+
+ // Reasoning precedes the message it belongs to.
+ if let Some(reasoning) = msg.reasoning_content.as_deref() {
+ if !reasoning.trim().is_empty() {
+ self.items.push(DisplayItem::Reasoning {
+ text: reasoning.to_string(),
+ iteration: Some(iteration),
+ });
+ }
+ }
+
+ let native_envelope = parse_native_tool_envelope(&msg.message.content);
+ let tool_calls: Vec<NativeToolCall> = match &native_envelope {
+ Some((_, calls)) => calls.clone(),
+ None => {
+ let recorded: Vec<NativeToolCall> = msg
+ .turn_usage
+ .as_ref()
+ .map(|tu| {
+ tu.tool_calls
+ .iter()
+ .map(|call| {
+ (call.id.clone(), call.name.clone(), call.arguments.clone())
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ let total = recorded.len();
+ let fresh: Vec<NativeToolCall> = recorded
+ .into_iter()
+ .filter(|(id, _, _)| id.is_empty() || !self.seen_call_ids.contains(id))
+ .collect();
+ if fresh.len() < total {
+ log::debug!(
+ "{LOG_PREFIX} dropped {} already-projected tool call(s) repeated on an assistant row iteration={iteration}",
+ total - fresh.len()
+ );
+ }
+ fresh
+ }
+ };
+ let interim = !tool_calls.is_empty();
+
+ // Native tool-call turns are persisted as their provider envelope so they
+ // can be replayed byte-faithfully. The display projection needs only the
+ // envelope's visible `content`; rendering/sanitizing the whole JSON object
+ // makes the narration disappear (and risks showing raw tool JSON).
+ let visible_content = native_envelope
+ .map(|(content, _)| content)
+ .unwrap_or_else(|| msg.message.content.clone());
+
+ // The assistant's prose (if any) shows before its tool calls.
+ if !visible_content.trim().is_empty() {
+ self.items.push(DisplayItem::AssistantMessage {
+ content: visible_content,
+ interim,
request_id: msg.request_id.clone(),
model: msg.turn_usage.as_ref().map(|tu| tu.model.clone()),
- iteration: msg.iteration,
+ iteration: Some(iteration),
});
}
- }
- }
- fn project_assistant(
- msg: &DisplayMessage,
- items: &mut Vec<DisplayItem>,
- pending: &mut VecDeque<(String, usize)>,
- ) {
- // Reasoning precedes the message it belongs to.
- if let Some(reasoning) = msg.reasoning_content.as_deref() {
- if !reasoning.trim().is_empty() {
- items.push(DisplayItem::Reasoning {
- text: reasoning.to_string(),
+ for (call_id, name, arguments) in tool_calls {
+ let args = parse_tool_args(&arguments);
+ if !call_id.is_empty() {
+ self.seen_call_ids.insert(call_id.clone());
+ }
++ // Transcripts written while the codec filed a turn's calls on its
++ // final row record a text-dialect call *after* its own result,
++ // which already projected as an orphan. Name that settled row
++ // rather than adding a second one that never settles.
++ if let Some(DisplayItem::ToolCall {
++ name: settled_name,
++ args: settled_args,
++ iteration: settled_iteration,
++ ..
++ }) = settled_orphan_mut(&mut self.items, &call_id)
++ {
++ log::debug!("{LOG_PREFIX} call {call_id} recorded after its result — merged");
++ *settled_name = name;
++ *settled_args = args;
++ *settled_iteration = Some(iteration);
++ continue;
++ }
+ self.items.push(DisplayItem::ToolCall {
+ call_id: call_id.clone(),
+ name,
+ iteration: Some(iteration),
+ args,
+ result: None,
+ status: ToolCallStatus::Running,
+ failure: None,
});
+ self.pending.push_back((call_id, self.items.len() - 1));
}
}
@@@ -514,137 -406,38 +432,122 @@@ pub(super) fn parse_native_tool_envelop
Some((content, calls))
}
- fn project_tool_result(
- msg: &DisplayMessage,
- items: &mut Vec<DisplayItem>,
- pending: &mut VecDeque<(String, usize)>,
- ) {
- let result = msg.message.content.clone();
- // A failed tool line (`ToolResult::is_error`, stamped at persistence) pairs
- // to an error row with a failure payload instead of a false success.
- let (status, failure) = if msg.failure {
- (
- ToolCallStatus::Error,
- Some(ToolCallFailure {
- detail: msg.failure_detail.clone(),
- }),
- )
- } else {
- (ToolCallStatus::Success, None)
+ /// Keys a native tool-result replay envelope may carry besides `content`.
+ const TOOL_RESULT_ENVELOPE_KEYS: &[&str] = &["content", "tool_call_id", "tool_name", "name"];
+
+ /// Unwrap a native tool-result replay envelope
+ /// (`{"tool_call_id":…,"content":…}`) to the tool's own output plus the call
+ /// id it names. Anything else — including a tool whose genuine output happens
+ /// to be JSON with other keys — is returned verbatim.
+ fn unwrap_tool_result(raw: &str) -> (String, Option<String>) {
+ let Ok(serde_json::Value::Object(object)) = serde_json::from_str::<serde_json::Value>(raw)
+ else {
+ return (raw.to_string(), None);
};
- // Pair by explicit call id first, else FIFO.
- let idx = msg
- .message
- .id
- .as_deref()
- .and_then(|id| take_pending_by_id(pending, id))
- .or_else(|| pending.pop_front().map(|(_, idx)| idx));
-
- if let Some(idx) = idx {
- if let Some(DisplayItem::ToolCall {
- result: slot,
- status: status_slot,
- failure: failure_slot,
- ..
- }) = items.get_mut(idx)
- {
- *slot = Some(result);
- *status_slot = status;
- *failure_slot = failure;
- return;
- }
+ let (Some(content), Some(call_id)) = (
+ object.get("content").and_then(serde_json::Value::as_str),
+ object
+ .get("tool_call_id")
+ .and_then(serde_json::Value::as_str),
+ ) else {
+ return (raw.to_string(), None);
+ };
+ if !object
+ .keys()
+ .all(|key| TOOL_RESULT_ENVELOPE_KEYS.contains(&key.as_str()))
+ {
+ return (raw.to_string(), None);
}
-
- // Orphan result (no matching assistant tool_call recorded) — surface it as
- // a best-effort completed tool row so the output is not lost.
- log::debug!("{LOG_PREFIX} tool result with no pending call — emitting orphan tool row");
- items.push(DisplayItem::ToolCall {
- call_id: msg.message.id.clone().unwrap_or_default(),
- name: "tool".to_string(),
- args: None,
- result: Some(result),
- status,
- failure,
- });
+ (
+ content.to_string(),
+ Some(call_id.to_string()).filter(|id| !id.is_empty()),
+ )
}
+/// Pair each result of a text-dialect `[Tool results]` row with its pending
+/// call. Failure status comes from the ids the session codec recorded on the
+/// row ([`TOOL_RESULT_FAILURES_METADATA_KEY`]); a result with no pending call
+/// surfaces as an orphan row, as for a native `tool` line.
++impl Projector {
++ fn text_tool_results(&mut self, msg: &DisplayMessage, results: Vec<ToolResultEntry>) {
++ project_text_tool_results(msg, results, &mut self.items, &mut self.pending);
++ }
++}
++
+fn project_text_tool_results(
+ msg: &DisplayMessage,
+ results: Vec<ToolResultEntry>,
+ items: &mut Vec<DisplayItem>,
+ pending: &mut VecDeque<(String, usize)>,
+) {
+ let failed: Vec<&str> = msg
+ .message
+ .extra_metadata
+ .as_ref()
+ .and_then(|meta| meta.get(TOOL_RESULT_FAILURES_METADATA_KEY))
+ .and_then(serde_json::Value::as_array)
+ .map(|ids| ids.iter().filter_map(serde_json::Value::as_str).collect())
+ .unwrap_or_default();
+ log::debug!(
+ "{LOG_PREFIX} text-dialect results row results={} failed={} pending={}",
+ results.len(),
+ failed.len(),
+ pending.len()
+ );
+ for result in results {
+ let (status, failure) = if failed.contains(&result.tool_call_id.as_str()) {
+ (
+ ToolCallStatus::Error,
+ Some(ToolCallFailure { detail: None }),
+ )
+ } else {
+ (ToolCallStatus::Success, None)
+ };
+ if let Some(idx) = take_pending_by_id(pending, &result.tool_call_id) {
+ if let Some(DisplayItem::ToolCall {
+ result: slot,
+ status: status_slot,
+ failure: failure_slot,
+ ..
+ }) = items.get_mut(idx)
+ {
+ *slot = Some(result.content);
+ *status_slot = status;
+ *failure_slot = failure;
+ continue;
+ }
+ }
+ items.push(DisplayItem::ToolCall {
+ call_id: result.tool_call_id,
+ name: "tool".to_string(),
++ iteration: None,
+ args: None,
+ result: Some(result.content),
+ status,
+ failure,
+ });
+ }
+}
+
+/// The already-settled orphan row for `call_id` in the current turn — a result
+/// that projected before any call named it.
+fn settled_orphan_mut<'a>(
+ items: &'a mut [DisplayItem],
+ call_id: &str,
+) -> Option<&'a mut DisplayItem> {
+ let turn_start = items
+ .iter()
+ .rposition(|item| matches!(item, DisplayItem::TurnBoundary { .. }))
+ .map_or(0, |idx| idx + 1);
+ items[turn_start..].iter_mut().find(|item| {
+ matches!(
+ item,
+ DisplayItem::ToolCall { call_id: id, name, result: Some(_), .. }
+ if id == call_id && name == "tool"
+ )
+ })
+}
+
/// Remove and return the pending entry whose call id matches `id`, if any.
fn take_pending_by_id(pending: &mut VecDeque<(String, usize)>, id: &str) -> Option<usize> {
let pos = pending.iter().position(|(cid, _)| cid == id)?;
diff --cc crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
index abf966b33a,252e6dc8cf..d66063b25a
--- a/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
@@@ -387,3 -386,142 +392,145 @@@ async fn stamps_monotonic_seq_on_emitte
drop(tx);
}
+
+ // ── Terminal-event ordering: the bridge drains before chat_done ─────────────
+
+ fn drain_test_config(tmp: &tempfile::TempDir) -> Config {
+ Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Default::default()
+ }
+ }
+
+ /// `wait_drained` returns only once the bridge has forwarded every event the
+ /// parent queued before `TurnCompleted` — the caller publishes `chat_done`
+ /// right after it, so a tool result must never still be in flight.
+ #[tokio::test]
+ async fn wait_drained_returns_after_queued_events_are_forwarded() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = TurnStateStore::new(tmp.path().join("turn_states"));
+ let (tx, rx) = tokio::sync::mpsc::channel(16);
+ let mut bus = super::super::event_bus::subscribe_web_channel_events();
+ let handle = spawn_progress_bridge(
+ rx,
+ "client-drain".into(),
+ "thread-drain".into(),
+ "req-drain".into(),
+ store,
+ ChatRequestMetadata::default(),
+ drain_test_config(&tmp),
+ );
+
+ tx.send(AgentProgress::ToolCallCompleted {
+ call_id: "call-last".into(),
+ tool_name: "web_search".into(),
+ success: true,
+ output_chars: 2,
+ output: "ok".into(),
+ arguments: None,
+ elapsed_ms: 1,
+ iteration: 1,
+ failure: None,
++ display_label: None,
++ display_detail: None,
++ structured: None,
+ })
+ .await
+ .unwrap();
+ tx.send(AgentProgress::TurnCompleted { iterations: 1 })
+ .await
+ .unwrap();
+
+ // The sender stays alive (as a detached sub-agent's clone would), so the
+ // drain must come from `TurnCompleted`, not from the channel closing.
+ assert!(handle.wait_drained(Duration::from_secs(5)).await);
+
+ let mut saw_result = false;
+ loop {
+ match bus.try_recv() {
+ Ok(ev) if ev.thread_id == "thread-drain" && ev.event == "tool_result" => {
+ saw_result = true;
+ }
+ Ok(_) | Err(TryRecvError::Lagged(_)) => continue,
+ Err(_) => break,
+ }
+ }
+ assert!(
+ saw_result,
+ "the queued tool_result was published before the drain released"
+ );
+ drop(tx);
+ }
+
+ /// Without `TurnCompleted` (a failed turn) and with a sender still held, the
+ /// wait is bounded and reports that it timed out.
+ #[tokio::test]
+ async fn wait_drained_is_bounded_when_the_turn_never_completes() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = TurnStateStore::new(tmp.path().join("turn_states"));
+ let (tx, rx) = tokio::sync::mpsc::channel::<AgentProgress>(16);
+ let handle = spawn_progress_bridge(
+ rx,
+ "client-drain-timeout".into(),
+ "thread-drain-timeout".into(),
+ "req-drain-timeout".into(),
+ store,
+ ChatRequestMetadata::default(),
+ drain_test_config(&tmp),
+ );
+ assert!(!handle.wait_drained(Duration::from_millis(50)).await);
+ // Closing the channel ends the bridge, which counts as drained.
+ drop(tx);
+ assert!(handle.wait_drained(Duration::from_secs(5)).await);
+ }
+
+ /// A short narration ("Let me check.") is flushed as `chat_interim` when the
+ /// round's first tool call starts, so the frontend resets its live preview
+ /// before the next round streams.
+ #[tokio::test]
+ async fn short_narration_is_flushed_on_the_rounds_first_tool_call() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let store = TurnStateStore::new(tmp.path().join("turn_states"));
+ let (tx, rx) = tokio::sync::mpsc::channel(16);
+ let mut bus = super::super::event_bus::subscribe_web_channel_events();
+ let _handle = spawn_progress_bridge(
+ rx,
+ "client-short".into(),
+ "thread-short-narration".into(),
+ "req-short".into(),
+ store,
+ ChatRequestMetadata::default(),
+ drain_test_config(&tmp),
+ );
+ tx.send(AgentProgress::TextDelta {
+ delta: "Let me check.".into(),
+ iteration: 1,
+ })
+ .await
+ .unwrap();
+ tx.send(AgentProgress::ToolCallStarted {
+ call_id: "call-1".into(),
+ tool_name: "web_search".into(),
+ arguments: serde_json::json!({}),
+ iteration: 1,
+ display_label: None,
+ display_detail: None,
+ })
+ .await
+ .unwrap();
+
+ let interim = tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ let ev = recv_for_thread(&mut bus, "thread-short-narration").await;
+ if ev.event == "chat_interim" {
+ return ev;
+ }
+ }
+ })
+ .await
+ .expect("chat_interim within timeout");
+ assert_eq!(interim.full_response.as_deref(), Some("Let me check."));
+ assert_eq!(interim.round, Some(1));
+ }
diff --cc vendor/tinyagents
index 635511fd10,c7d3508a17..2f9e2eb3e3
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@@ -1,1 -1,1 +1,1 @@@
- Subproject commit 635511fd105844a78756970931220a10ba39abd7
-Subproject commit c7d3508a17678c0a1cf2d0ef4f4d3c3509718d7c
++Subproject commit 2f9e2eb3e376044fe8061e62d9e76688838dcba9