The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(chat): coalesce persisted assistant turn segments
Steven Enamakel8284e63dd79a
diff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.tsindex 3f318f356d..a8b891c8ed 100644--- a/app/src/providers/__tests__/assistantUiMessages.test.ts+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts@@ -137,9 +137,7 @@ describe('buildRuntimeMessages', () => {const projected = buildRuntimeMessages([msg({ id: 'answer', sender: 'agent' })], null, {isRunning: false,liveTimeline: [tool({ id: 'stale-tool', status: 'success' })],- liveTranscript: [- { kind: 'thinking', round: 1, seq: 0, text: 'already finished thinking' },- ],+ liveTranscript: [{ kind: 'thinking', round: 1, seq: 0, text: 'already finished thinking' }],});const ids = projected.map(message => message.id);@@ -213,15 +211,74 @@ describe('buildRuntimeMessages', () => {const finalText = 'hey! what is up?';const answer = msg({ id: 'answer', sender: 'agent', content: finalText });const content = buildRuntimeMessages([answer], null, {- turnTranscripts: {- request: [{ kind: 'narration', round: 1, seq: 0, text: finalText }],- },+ turnTranscripts: { request: [{ kind: 'narration', round: 1, seq: 0, text: finalText }] },turnTimelines: { request: [] },})[0]?.content;expect(content).toEqual([{ type: 'text', text: finalText }]);});+ it('coalesces legacy assistant segments into one bubble with one tool trail', () => {+ const requestId = 'legacy-segmented-request';+ const intro = "Here's the crypto picture today:";+ const finalText = `${intro}\n\nBitcoin is trading around $77,000.`;+ const messages = [+ msg({ id: 'user', content: 'What is happening with Bitcoin?' }),+ msg({+ id: 'tool-envelope',+ sender: 'agent',+ content: JSON.stringify({+ content: null,+ tool_calls: [+ { id: 'call-search', name: 'web_search_tool', arguments: '{"query":"bitcoin"}' },+ ],+ }),+ extraMetadata: { requestId },+ }),+ msg({ id: 'intro', sender: 'agent', content: intro, extraMetadata: { requestId } }),+ msg({ id: 'final', sender: 'agent', content: finalText, extraMetadata: { requestId } }),+ ];++ const projected = buildRuntimeMessages(messages, null, {+ turnTimelines: {+ [requestId]: [+ tool({ id: 'call-search', name: 'tool', status: 'success', result: 'market results' }),+ ],+ },+ turnTranscripts: {+ [requestId]: [{ kind: 'toolCall', round: 1, seq: 0, callId: 'call-search' }],+ },+ });++ expect(projected).toHaveLength(2);+ expect(projected[1]).toMatchObject({ id: 'final', role: 'assistant' });+ expect(projected[1]?.content).toEqual([+ expect.objectContaining({+ type: 'tool-call',+ toolCallId: 'call-search',+ toolName: 'web_search_tool',+ }),+ { type: 'text', text: finalText },+ ]);+ });++ it('does not coalesce adjacent assistant turns with different request ids', () => {+ const projected = buildRuntimeMessages(+ [+ msg({ id: 'first', sender: 'agent', content: 'first', extraMetadata: { requestId: 'r1' } }),+ msg({+ id: 'second',+ sender: 'agent',+ content: 'second',+ extraMetadata: { requestId: 'r2' },+ }),+ ],+ null+ );++ expect(projected.map(message => message.id)).toEqual(['first', 'second']);+ });+/*** The crash this guards: assistant-ui keys tool parts as `toolCallId-${id}`* and throws "Duplicate key … in useResources" on a repeat, taking the wholediff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.tsindex 117f1f46b0..31a0dd7551 100644--- a/app/src/providers/assistantUiMessages.ts+++ b/app/src/providers/assistantUiMessages.ts@@ -45,6 +45,8 @@ const conversionCache = new WeakMap<ThreadMessage, ConversionCacheEntry>();const EMPTY_TIMELINE: readonly ToolTimelineEntry[] = [];const EMPTY_TRANSCRIPT: readonly ProcessingTranscriptItem[] = [];+const RECOVERED_TOOL_NAMES_KEY = 'assistantUiToolNames';+/** Synthetic id for the live streaming tail. Stable so React reconciles it. */export const STREAMING_TAIL_ID = '__openhuman_streaming_tail__';@@ -168,6 +170,97 @@ function stringArray(value: unknown): string[] {: [];}+function requestIdOf(message: ThreadMessage): string | undefined {+ const requestId = message.extraMetadata?.requestId;+ return typeof requestId === 'string' && requestId.length > 0 ? requestId : undefined;+}++function isGenericToolName(name: string): boolean {+ return ['', 'tool', 'unknown', 'unknown_tool'].includes(name.trim().toLowerCase());+}++function recoverTimelineToolNames(+ timeline: readonly ToolTimelineEntry[],+ recoveredNames: readonly string[]+): readonly ToolTimelineEntry[] {+ if (recoveredNames.length === 0 || !timeline.some(entry => isGenericToolName(entry.name))) {+ return timeline;+ }+ let recoveredIndex = 0;+ return timeline.map(entry => {+ const recovered = recoveredNames[recoveredIndex];+ recoveredIndex += 1;+ return recovered && isGenericToolName(entry.name) ? { ...entry, name: recovered } : entry;+ });+}++function mergedAssistantText(messages: readonly ThreadMessage[]): string {+ const texts = messages+ .map(message => unwrapToolCallEnvelope(message.content ?? '').text)+ .filter(text => text.trim().length > 0)+ .filter((text, index, all) => all.indexOf(text) === index);+ if (texts.length < 2) return texts[0] ?? '';++ // Legacy web delivery persisted both paragraph-sized segments and the full+ // final response. Prefer the complete response when it contains every+ // segment; otherwise retain each distinct assistant emission in order.+ const longest = [...texts].sort((left, right) => right.length - left.length)[0] ?? '';+ if (texts.every(text => longest.includes(text.trim()))) return longest;+ return texts.join('\n\n');+}++function mergeAssistantRun(messages: readonly ThreadMessage[]): ThreadMessage {+ if (messages.length === 1) return messages[0];+ const first = messages[0];+ const last = messages[messages.length - 1];+ const extraMetadata = Object.assign({}, ...messages.map(message => message.extraMetadata));+ const requestId = messages.map(requestIdOf).find(Boolean);+ const toolNames = messages.flatMap(+ message => unwrapToolCallEnvelope(message.content ?? '').toolNames+ );+ if (requestId) extraMetadata.requestId = requestId;+ if (toolNames.length > 0) extraMetadata[RECOVERED_TOOL_NAMES_KEY] = toolNames;+ return {+ ...last,+ content: mergedAssistantText(messages),+ createdAt: first.createdAt,+ extraMetadata,+ };+}++/**+ * Collapse legacy paragraph/tool-envelope rows into one assistant turn.+ *+ * The old interactive-web delivery path persisted each segment as a separate+ * agent message. Consecutive assistant rows cannot cross a user turn; when+ * both rows carry request ids, a differing id is the explicit boundary.+ */+function coalesceAssistantSegments(messages: readonly ThreadMessage[]): ThreadMessage[] {+ const out: ThreadMessage[] = [];+ let run: ThreadMessage[] = [];+ let runRequestId: string | undefined;++ const flush = () => {+ if (run.length > 0) out.push(mergeAssistantRun(run));+ run = [];+ runRequestId = undefined;+ };++ for (const message of messages) {+ if (message.sender !== 'agent' || message.extraMetadata?.hidden) {+ flush();+ out.push(message);+ continue;+ }+ const requestId = requestIdOf(message);+ if (run.length > 0 && runRequestId && requestId && runRequestId !== requestId) flush();+ run.push(message);+ runRequestId ??= requestId;+ }+ flush();+ return out;+}+function mimeTypeFromDataUri(dataUri: string): string {return dataUri.match(/^data:([^;,]+)/i)?.[1] ?? 'application/octet-stream';}@@ -218,13 +311,19 @@ export function toThreadMessageLike(const cached = conversionCache.get(msg);if (cached?.timeline === timeline && cached.transcript === transcript) return cached.converted;- const text =- msg.sender === 'agent' ? unwrapToolCallEnvelope(msg.content ?? '').text : (msg.content ?? '');+ const unwrapped = unwrapToolCallEnvelope(msg.content ?? '');+ const text = msg.sender === 'agent' ? unwrapped.text : (msg.content ?? '');+ const recoveredToolNames = [+ ...unwrapped.toolNames,+ ...stringArray(msg.extraMetadata?.[RECOVERED_TOOL_NAMES_KEY]),+ ];+ const effectiveTimeline = recoverTimelineToolNames(timeline, recoveredToolNames);const converted: ThreadMessageLike = {id: msg.id,role: msg.sender === 'agent' ? 'assistant' : 'user',- content: msg.sender === 'agent' ? assistantParts(text, timeline, transcript) : userParts(msg),+ content:+ msg.sender === 'agent' ? assistantParts(text, effectiveTimeline, transcript) : userParts(msg),createdAt: new Date(msg.createdAt),...(msg.sender === 'agent' && msg.extraMetadata?.stopped === true? { status: { type: 'incomplete' as const, reason: 'cancelled' as const } }@@ -289,9 +388,10 @@ export function buildRuntimeMessages(streaming: StreamingAssistantState | null,projection: AssistantUiProjection = {}): ThreadMessageLike[] {+ const coalescedMessages = coalesceAssistantSegments(messages);const out: ThreadMessageLike[] = [];const claimedRequestIds = new Set(- messages.flatMap(message =>+ coalescedMessages.flatMap(message =>message.sender === 'agent' && typeof message.extraMetadata?.requestId === 'string'? [message.extraMetadata.requestId]: []@@ -304,10 +404,10 @@ export function buildRuntimeMessages(]),].filter(requestId => !claimedRequestIds.has(requestId));let orphanRequestCursor = 0;- const lastVisibleAgentId = [...messages]+ const lastVisibleAgentId = [...coalescedMessages].reverse().find(message => message.sender === 'agent' && !message.extraMetadata?.hidden)?.id;- for (const msg of messages) {+ for (const msg of coalescedMessages) {if (msg.extraMetadata?.hidden) continue;const requestId =msg.sender === 'agent' && typeof msg.extraMetadata?.requestId === 'string'diff --git a/app/test/playwright/specs/chat-tool-call-flow.spec.ts b/app/test/playwright/specs/chat-tool-call-flow.spec.tsindex 5642446b50..f5c1d96411 100644--- a/app/test/playwright/specs/chat-tool-call-flow.spec.ts+++ b/app/test/playwright/specs/chat-tool-call-flow.spec.ts@@ -11,6 +11,8 @@ const MOCK_ADMIN_BASE = `http://127.0.0.1:${process.env.E2E_MOCK_PORT || '18473'const USER_ID = 'pw-chat-tool-call';const PROMPT = 'Fetch the contents of https://example.com for me.';const CANARY_FINAL = 'canary-tool-call-fetched-a1b2c3';+const CANARY_SECOND_PARAGRAPH = 'The entire answer must stay in this same assistant bubble.';+const FINAL_RESPONSE = `Here is the fetched content: ${CANARY_FINAL}\n\n${CANARY_SECOND_PARAGRAPH}`;const FORCED_RESPONSES = [{content: '',@@ -22,7 +24,7 @@ const FORCED_RESPONSES = [},],},- { content: `Here is the fetched content: ${CANARY_FINAL}` },+ { content: FINAL_RESPONSE },];interface MockRequest {@@ -171,7 +173,10 @@ test.describe('Chat Tool Call Flow', () => {await sendMessage(page, PROMPT);await expect(agentMessageText(page, CANARY_FINAL)).toBeVisible({ timeout: 40_000 });- await expect(page.getByText(`Here is the fetched content: ${CANARY_FINAL}`, { exact: true })).toHaveCount(1);+ const finalBubble = page.getByTestId('agent-message').filter({ hasText: CANARY_FINAL });+ await expect(finalBubble).toHaveCount(1);+ await expect(finalBubble).toContainText(CANARY_SECOND_PARAGRAPH);+ await expect(page.getByText(CANARY_SECOND_PARAGRAPH, { exact: true })).toHaveCount(1);// Regression: completed tool/reasoning arrays remain in Redux briefly, but// they must not create a synthetic running tail after the final answer.@@ -181,8 +186,10 @@ test.describe('Chat Tool Call Flow', () => {// Tool activity belongs to assistant-ui and renders as a readable card,// never through the removed legacy Agentic task insights timeline.await expect(page.getByTestId('agent-task-insights')).toHaveCount(0);- const toolCard = page.getByTestId('assistant-ui-tool-call').last();+ await expect(page.getByTestId('assistant-ui-tool-call')).toHaveCount(1);+ const toolCard = page.getByTestId('assistant-ui-tool-call');await expect(toolCard).toBeVisible();+ await expect(toolCard).toContainText('Fetched from the web');await expect(toolCard).not.toContainText('running');const toolTrigger = toolCard.getByRole('button');if ((await toolTrigger.getAttribute('aria-expanded')) !== 'true') await toolTrigger.click();diff --git a/src/openhuman/threads/transcript_view/project.rs b/src/openhuman/threads/transcript_view/project.rsindex 411aa8e6a8..c1c7cc5a5a 100644--- a/src/openhuman/threads/transcript_view/project.rs+++ b/src/openhuman/threads/transcript_view/project.rs@@ -403,28 +403,37 @@ fn project_assistant(}}- let tool_calls = msg+ let persisted_tool_calls: Vec<(String, String, String)> = msg.turn_usage.as_ref()- .map(|tu| tu.tool_calls.as_slice())+ .map(|tu| {+ tu.tool_calls+ .iter()+ .map(|call| (call.id.clone(), call.name.clone(), call.arguments.clone()))+ .collect()+ }).unwrap_or_default();+ let native_envelope = parse_native_tool_envelope(&msg.message.content);+ // Some native/tinyagents histories predate top-level `turn_usage` lifting+ // and carry the invocation only inside the provider replay envelope. Use+ // that canonical call shape rather than degrading the paired result to an+ // orphan named "tool".+ let tool_calls = if persisted_tool_calls.is_empty() {+ native_envelope+ .as_ref()+ .map(|(_, calls)| calls.clone())+ .unwrap_or_default()+ } else {+ persisted_tool_calls+ };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 = serde_json::from_str::<serde_json::Value>(&msg.message.content)- .ok()- .and_then(|value| {- let object = value.as_object()?;- object.get("tool_calls")?.as_array()?;- match object.get("content") {- Some(serde_json::Value::String(content)) => Some(content.clone()),- Some(serde_json::Value::Null) | None => Some(String::new()),- _ => None,- }- })+ 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.@@ -438,20 +447,48 @@ fn project_assistant(});}- for call in tool_calls {- let args = parse_tool_args(&call.arguments);+ for (call_id, name, arguments) in tool_calls {+ let args = parse_tool_args(&arguments);items.push(DisplayItem::ToolCall {- call_id: call.id.clone(),- name: call.name.clone(),+ call_id: call_id.clone(),+ name,args,result: None,status: ToolCallStatus::Running,failure: None,});- pending.push_back((call.id.clone(), items.len() - 1));+ pending.push_back((call_id, items.len() - 1));}}+/// Decode the native provider replay envelope embedded in `ChatMessage.content`.+/// Returns visible assistant prose plus `(id, name, arguments)` calls.+fn parse_native_tool_envelope(raw: &str) -> Option<(String, Vec<(String, String, String)>)> {+ let value = serde_json::from_str::<serde_json::Value>(raw).ok()?;+ let object = value.as_object()?;+ let calls = object.get("tool_calls")?.as_array()?;+ let content = match object.get("content") {+ Some(serde_json::Value::String(content)) => content.clone(),+ Some(serde_json::Value::Null) | None => String::new(),+ _ => return None,+ };+ let calls = calls+ .iter()+ .filter_map(|call| {+ let call = call.as_object()?;+ let id = call.get("id")?.as_str()?.to_string();+ let name = call.get("name")?.as_str()?.to_string();+ let arguments = match call.get("arguments") {+ Some(serde_json::Value::String(arguments)) => arguments.clone(),+ Some(arguments) => arguments.to_string(),+ None => String::new(),+ };+ Some((id, name, arguments))+ })+ .collect();+ Some((content, calls))+}+fn project_tool_result(msg: &DisplayMessage,items: &mut Vec<DisplayItem>,diff --git a/src/openhuman/threads/transcript_view/transcript_view_tests.rs b/src/openhuman/threads/transcript_view/transcript_view_tests.rsindex bdbb8cb950..2532c95420 100644--- a/src/openhuman/threads/transcript_view/transcript_view_tests.rs+++ b/src/openhuman/threads/transcript_view/transcript_view_tests.rs@@ -123,6 +123,60 @@ fn projects_turn_with_tools_reasoning_and_sanitization() {}}+#[test]+fn recovers_tool_name_from_native_envelope_without_turn_usage() {+ let dir = TempDir::new().unwrap();+ let envelope = serde_json::json!({+ "content": null,+ "tool_calls": [{+ "id": "call-web-1",+ "name": "web_fetch",+ "arguments": { "url": "https://example.com" }+ }]+ })+ .to_string();+ let assistant = serde_json::json!({+ "role": "assistant",+ "content": envelope,+ "request_id": "req-native"+ })+ .to_string();+ let result =+ r#"{"role":"tool","content":"Example Domain","id":"call-web-1","request_id":"req-native"}"#;+ let path = write_raw(+ dir.path(),+ "101_orchestrator",+ "thr_native",+ &[assistant.as_str(), result],+ );+ let display = read_transcript_display(&path).unwrap();+ let items = project_records(&display.records);++ let tool = items+ .iter()+ .find_map(|item| match item {+ DisplayItem::ToolCall {+ name,+ args,+ result,+ status,+ ..+ } => Some((name, args, result, status)),+ _ => None,+ })+ .expect("native envelope tool call projected");+ assert_eq!(tool.0, "web_fetch");+ assert_eq!(+ tool.1+ .as_ref()+ .and_then(|args| args.get("url"))+ .and_then(serde_json::Value::as_str),+ Some("https://example.com")+ );+ assert_eq!(tool.2.as_deref(), Some("Example Domain"));+ assert_eq!(*tool.3, ToolCallStatus::Success);+}+#[test]fn projects_compaction_and_interrupted_partial() {let dir = TempDir::new().unwrap();