Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix (ai): scheduled agent goofy rendering (#3672)

Eric Hayes51e7698b5a3d
diff --git a/rust/cloud-storage/agent/src/accumulator.rs b/rust/cloud-storage/agent/src/accumulator.rs
new file mode 100644
index 0000000000..467c8257a1
--- /dev/null
+++ b/rust/cloud-storage/agent/src/accumulator.rs
@@ -0,0 +1,103 @@
+#[cfg(test)]
+mod test;
+
+/// Accumulation of streamed agent parts into a persistable message.
+use crate::convert::merge_consecutive_parts;
+use crate::stream::{StreamPart, ToolResponse};
+use crate::types::AssistantMessagePart;
+
+/// Accumulates [`StreamPart`]s emitted by an agent stream into an ordered
+/// sequence of [`AssistantMessagePart`]s.
+///
+/// Parts are stored in arrival order exactly as they stream in. Consecutive
+/// text and thinking deltas are only collapsed when the accumulated parts are
+/// accessed via [`StreamAccumulator::into_parts`] or
+/// [`StreamAccumulator::parts`]. This lets a consumer forward each individual
+/// delta as it arrives while the persisted message still ends up with merged
+/// text and thinking blocks.
+#[derive(Debug, Default, Clone)]
+pub struct StreamAccumulator {
+ parts: Vec<AssistantMessagePart>,
+}
+
+impl StreamAccumulator {
+ /// Create an empty accumulator.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Convert a [`StreamPart`] into the [`AssistantMessagePart`] it persists
+ /// as, accumulate it, and return a reference to the stored part.
+ ///
+ /// Returns `None` (accumulating nothing) for parts that carry no
+ /// persistable content: token [`Usage`](StreamPart::Usage) events and empty
+ /// text or thinking deltas. The returned reference is the unmerged part, so
+ /// a consumer can forward it as an individual streamed chunk.
+ pub fn push(&mut self, part: StreamPart) -> Option<&AssistantMessagePart> {
+ let part = stream_part_to_message_part(part)?;
+ self.parts.push(part);
+ self.parts.last()
+ }
+
+ /// Consume the accumulator, returning the parts with consecutive text and
+ /// thinking deltas merged.
+ pub fn into_parts(self) -> Vec<AssistantMessagePart> {
+ merge_consecutive_parts(self.parts)
+ }
+
+ /// Return the merged parts without consuming the accumulator.
+ pub fn parts(&self) -> Vec<AssistantMessagePart> {
+ merge_consecutive_parts(self.parts.clone())
+ }
+
+ /// Whether nothing has been accumulated yet.
+ ///
+ /// Reflects the raw accumulated parts; since merging never drops parts this
+ /// also indicates whether [`parts`](Self::parts) would be empty.
+ pub fn is_empty(&self) -> bool {
+ self.parts.is_empty()
+ }
+}
+
+/// Convert a single [`StreamPart`] into the [`AssistantMessagePart`] that should
+/// be persisted for it, if any.
+///
+/// MCP tool calls are mapped to [`AssistantMessagePart::McpToolCall`] so the
+/// originating service is preserved. Usage events and empty text/thinking
+/// deltas return `None`.
+fn stream_part_to_message_part(part: StreamPart) -> Option<AssistantMessagePart> {
+ match part {
+ StreamPart::Content(text) if !text.is_empty() => Some(AssistantMessagePart::Text { text }),
+ StreamPart::Thinking(thinking) if !thinking.is_empty() => {
+ Some(AssistantMessagePart::Thinking { thinking })
+ }
+ StreamPart::ToolCall(call) => Some(match call.mcp {
+ Some(mcp) => AssistantMessagePart::McpToolCall {
+ name: mcp.tool_name,
+ service: mcp.service,
+ display_name: mcp.display_name,
+ json: call.json,
+ id: call.id,
+ },
+ None => AssistantMessagePart::ToolCall {
+ name: call.name,
+ json: call.json,
+ id: call.id,
+ },
+ }),
+ StreamPart::ToolResponse(ToolResponse::Json { id, json, name }) => {
+ Some(AssistantMessagePart::ToolCallResponseJson { name, json, id })
+ }
+ StreamPart::ToolResponse(ToolResponse::Err {
+ id,
+ name,
+ description,
+ }) => Some(AssistantMessagePart::ToolCallErr {
+ name,
+ description,
+ id,
+ }),
+ // Empty text/thinking deltas and usage events carry nothing to persist.
+ StreamPart::Content(_) | StreamPart::Thinking(_) | StreamPart::Usage(_) => None,
+ }
+}
diff --git a/rust/cloud-storage/agent/src/accumulator/test.rs b/rust/cloud-storage/agent/src/accumulator/test.rs
new file mode 100644
index 0000000000..1e33d8a36a
--- /dev/null
+++ b/rust/cloud-storage/agent/src/accumulator/test.rs
@@ -0,0 +1,219 @@
+use super::*;
+use crate::stream::{McpInfo, ToolCall, Usage};
+use serde_json::json;
+
+fn content(s: &str) -> StreamPart {
+ StreamPart::Content(s.to_owned())
+}
+
+fn thinking(s: &str) -> StreamPart {
+ StreamPart::Thinking(s.to_owned())
+}
+
+fn tool_call(id: &str, name: &str) -> StreamPart {
+ StreamPart::ToolCall(ToolCall {
+ id: id.to_owned(),
+ name: name.to_owned(),
+ json: json!({"q": "x"}),
+ mcp: None,
+ })
+}
+
+#[test]
+fn consecutive_text_is_merged_on_access() {
+ let mut acc = StreamAccumulator::new();
+ acc.push(content("Hello"));
+ acc.push(content(", "));
+ acc.push(content("world"));
+
+ assert_eq!(
+ acc.into_parts(),
+ vec![AssistantMessagePart::Text {
+ text: "Hello, world".to_owned()
+ }]
+ );
+}
+
+#[test]
+fn consecutive_thinking_is_merged_on_access() {
+ let mut acc = StreamAccumulator::new();
+ acc.push(thinking("Let me "));
+ acc.push(thinking("think."));
+
+ assert_eq!(
+ acc.into_parts(),
+ vec![AssistantMessagePart::Thinking {
+ thinking: "Let me think.".to_owned()
+ }]
+ );
+}
+
+#[test]
+fn text_separated_by_a_tool_call_is_not_merged() {
+ let mut acc = StreamAccumulator::new();
+ acc.push(content("before"));
+ acc.push(tool_call("c1", "search"));
+ acc.push(content("after"));
+
+ assert_eq!(
+ acc.into_parts(),
+ vec![
+ AssistantMessagePart::Text {
+ text: "before".to_owned()
+ },
+ AssistantMessagePart::ToolCall {
+ name: "search".to_owned(),
+ json: json!({"q": "x"}),
+ id: "c1".to_owned(),
+ },
+ AssistantMessagePart::Text {
+ text: "after".to_owned()
+ },
+ ]
+ );
+}
+
+#[test]
+fn text_and_thinking_are_not_merged_together() {
+ let mut acc = StreamAccumulator::new();
+ acc.push(thinking("reasoning"));
+ acc.push(content("answer"));
+
+ assert_eq!(
+ acc.into_parts(),
+ vec![
+ AssistantMessagePart::Thinking {
+ thinking: "reasoning".to_owned()
+ },
+ AssistantMessagePart::Text {
+ text: "answer".to_owned()
+ },
+ ]
+ );
+}
+
+#[test]
+fn push_returns_the_unmerged_part_for_forwarding() {
+ let mut acc = StreamAccumulator::new();
+
+ let first = acc.push(content("Hel")).cloned();
+ assert_eq!(
+ first,
+ Some(AssistantMessagePart::Text {
+ text: "Hel".to_owned()
+ })
+ );
+
+ let second = acc.push(content("lo")).cloned();
+ assert_eq!(
+ second,
+ Some(AssistantMessagePart::Text {
+ text: "lo".to_owned()
+ }),
+ "individual deltas are returned unmerged so consumers can stream them"
+ );
+
+ // ...but accessing the accumulated parts merges them.
+ assert_eq!(
+ acc.into_parts(),
+ vec![AssistantMessagePart::Text {
+ text: "Hello".to_owned()
+ }]
+ );
+}
+
+#[test]
+fn empty_text_and_thinking_are_skipped() {
+ let mut acc = StreamAccumulator::new();
+ assert!(acc.push(content("")).is_none());
+ assert!(acc.push(thinking("")).is_none());
+ assert!(acc.is_empty());
+ assert!(acc.into_parts().is_empty());
+}
+
+#[test]
+fn usage_events_are_ignored() {
+ let mut acc = StreamAccumulator::new();
+ assert!(
+ acc.push(StreamPart::Usage(Usage {
+ input_tokens: 10,
+ output_tokens: 20,
+ }))
+ .is_none()
+ );
+ assert!(acc.is_empty());
+}
+
+#[test]
+fn mcp_tool_calls_preserve_service_info() {
+ let mut acc = StreamAccumulator::new();
+ acc.push(StreamPart::ToolCall(ToolCall {
+ id: "call_mcp".to_owned(),
+ name: "slack__slack_search".to_owned(),
+ json: json!({"query": "standup"}),
+ mcp: Some(McpInfo {
+ service: "slack".to_owned(),
+ tool_name: "slack_search".to_owned(),
+ display_name: Some("Search Slack".to_owned()),
+ }),
+ }));
+
+ assert_eq!(
+ acc.into_parts(),
+ vec![AssistantMessagePart::McpToolCall {
+ name: "slack_search".to_owned(),
+ service: "slack".to_owned(),
+ display_name: Some("Search Slack".to_owned()),
+ json: json!({"query": "standup"}),
+ id: "call_mcp".to_owned(),
+ }]
+ );
+}
+
+#[test]
+fn tool_responses_convert_to_parts() {
+ let mut acc = StreamAccumulator::new();
+ acc.push(StreamPart::ToolResponse(ToolResponse::Json {
+ id: "c1".to_owned(),
+ name: "search".to_owned(),
+ json: json!({"results": []}),
+ }));
+ acc.push(StreamPart::ToolResponse(ToolResponse::Err {
+ id: "c2".to_owned(),
+ name: "delete".to_owned(),
+ description: "permission denied".to_owned(),
+ }));
+
+ assert_eq!(
+ acc.into_parts(),
+ vec![
+ AssistantMessagePart::ToolCallResponseJson {
+ name: "search".to_owned(),
+ json: json!({"results": []}),
+ id: "c1".to_owned(),
+ },
+ AssistantMessagePart::ToolCallErr {
+ name: "delete".to_owned(),
+ description: "permission denied".to_owned(),
+ id: "c2".to_owned(),
+ },
+ ]
+ );
+}
+
+#[test]
+fn parts_does_not_consume_and_matches_into_parts() {
+ let mut acc = StreamAccumulator::new();
+ acc.push(content("a"));
+ acc.push(content("b"));
+
+ let borrowed = acc.parts();
+ let owned = acc.into_parts();
+ assert_eq!(borrowed, owned);
+ assert_eq!(
+ owned,
+ vec![AssistantMessagePart::Text {
+ text: "ab".to_owned()
+ }]
+ );
+}
diff --git a/rust/cloud-storage/agent/src/lib.rs b/rust/cloud-storage/agent/src/lib.rs
index 8425db2cbe..e0438d55b1 100644
--- a/rust/cloud-storage/agent/src/lib.rs
+++ b/rust/cloud-storage/agent/src/lib.rs
@@ -2,6 +2,7 @@
//! Agent crate — agentic loop
+mod accumulator;
mod agent_loop;
mod anthropic_model;
mod completion;
@@ -15,6 +16,7 @@ pub mod structured_output;
mod tool_adapter;
pub mod types;
+pub use accumulator::StreamAccumulator;
pub use agent_loop::{AgentLoop, Session};
pub use completion::{complete, complete_with_history};
pub use convert::{merge_consecutive_parts, to_rig_messages};
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
index 937b14b937..727cd319bc 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message/mod.rs
@@ -12,7 +12,7 @@ use crate::service::get_chat::get_chat;
use crate::service::notification::notify;
use agent::AgentModel;
use agent::types::{AssistantMessagePart, ChatMessage, ChatMessageContent};
-use agent::{AgentLoop, StreamPart};
+use agent::{AgentLoop, StreamAccumulator};
use async_stream::stream;
use attachment::FormattedParts;
use axum::Json;
@@ -514,7 +514,7 @@ fn stream_and_save_message(
let mut is_first_token = false;
let idle_timeout = std::time::Duration::from_secs(3 * 60);
let mut was_cancelled = false;
- let mut yielded_parts: Vec<AssistantMessagePart> = Vec::new();
+ let mut accumulator = StreamAccumulator::new();
loop {
let next_item = tokio::select! {
@@ -551,55 +551,14 @@ fn stream_and_save_message(
match response {
Ok(response_chunk) => {
- let message_part = match response_chunk {
- StreamPart::Content(content) => {
- if content.is_empty() {
- continue;
- }
- AssistantMessagePart::Text { text: content }
- }
- StreamPart::Thinking(thinking) => {
- if thinking.is_empty() {
- continue;
- }
- AssistantMessagePart::Thinking { thinking }
- }
- StreamPart::ToolCall(call) => match call.mcp {
- Some(mcp) => AssistantMessagePart::McpToolCall {
- name: mcp.tool_name,
- service: mcp.service,
- display_name: mcp.display_name,
- json: call.json,
- id: call.id,
- },
- None => AssistantMessagePart::ToolCall {
- name: call.name,
- json: call.json,
- id: call.id,
- },
- },
- StreamPart::Usage(usage) => {
- tracing::debug!(?usage, "usage");
- continue;
- }
- StreamPart::ToolResponse(agent::ToolResponse::Json {
- id,
- json,
- name,
- }) => AssistantMessagePart::ToolCallResponseJson { name, json, id },
- StreamPart::ToolResponse(agent::ToolResponse::Err {
- id,
- name,
- description,
- }) => AssistantMessagePart::ToolCallErr {
- name,
- description,
- id,
- },
+ // Accumulate the part for persistence; the accumulator merges
+ // consecutive text/thinking when accessed below. Parts with no
+ // persistable content (usage, empty deltas) are skipped here and
+ // are not forwarded to the client.
+ let Some(message_part) = accumulator.push(response_chunk).cloned() else {
+ continue;
};
- yielded_parts.push(message_part.clone());
-
let response = ChatStream::ChatMessageResponse {
stream_id: stream_id.clone(),
chat_id: chat_id.clone(),
@@ -636,9 +595,7 @@ fn stream_and_save_message(
// Build the set of messages to persist from the parts we yielded.
// This matches exactly what the user saw in the streamed chunks.
let new_messages = {
- let resolved_parts = resolve_pending_tool_calls(
- agent::merge_consecutive_parts(yielded_parts),
- );
+ let resolved_parts = resolve_pending_tool_calls(accumulator.into_parts());
if resolved_parts.is_empty() {
vec![]
} else {
diff --git a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
index 2ffa6de0c8..801ca168f3 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/structured_completion.rs
@@ -1,8 +1,8 @@
use crate::api::context::ApiContext;
use crate::model::stream::ToolSet;
use agent::structured_output::DynamicSchema;
-use agent::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, Role};
-use agent::{AgentLoop, AgentModel, StreamPart};
+use agent::types::{ChatMessage, ChatMessageContent, Role};
+use agent::{AgentLoop, AgentModel, StreamAccumulator};
use axum::Json;
use axum::extract::{Extension, State};
use axum::http::StatusCode;
@@ -124,47 +124,12 @@ pub async fn structured_completion(
status: StatusCode::INTERNAL_SERVER_ERROR,
})?;
- let mut yielded_parts: Vec<AssistantMessagePart> = Vec::new();
+ let mut accumulator = StreamAccumulator::new();
while let Some(item) = ai_stream.next().await {
match item {
- Ok(part) => match part {
- StreamPart::Content(content) if !content.is_empty() => {
- yielded_parts.push(AssistantMessagePart::Text { text: content });
- }
- StreamPart::ToolCall(call) => match call.mcp {
- Some(mcp) => yielded_parts.push(AssistantMessagePart::McpToolCall {
- name: mcp.tool_name,
- service: mcp.service,
- display_name: mcp.display_name,
- json: call.json,
- id: call.id,
- }),
- None => yielded_parts.push(AssistantMessagePart::ToolCall {
- name: call.name,
- json: call.json,
- id: call.id,
- }),
- },
- StreamPart::ToolResponse(agent::ToolResponse::Json { id, json, name }) => {
- yielded_parts.push(AssistantMessagePart::ToolCallResponseJson {
- name,
- json,
- id,
- });
- }
- StreamPart::ToolResponse(agent::ToolResponse::Err {
- id,
- name,
- description,
- }) => {
- yielded_parts.push(AssistantMessagePart::ToolCallErr {
- name,
- description,
- id,
- });
- }
- _ => {}
- },
+ Ok(part) => {
+ accumulator.push(part);
+ }
Err(e) => {
return Err(StructuredCompletionError {
error: format!("Agent loop error: {e}"),
@@ -174,6 +139,7 @@ pub async fn structured_completion(
}
}
drop(ai_stream);
+ let yielded_parts = accumulator.into_parts();
// Phase 2: Structured completion with the gathered context
let conversation: Vec<ChatMessage> = vec![
diff --git a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
index abf94171d4..5e0a9730ef 100644
--- a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
+++ b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
@@ -2,7 +2,7 @@ use super::notify::notify_completion;
use std::sync::Arc;
use agent::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, Role};
-use agent::{AgentLoop, StreamPart};
+use agent::{AgentLoop, StreamAccumulator};
use ai_tools::{ToolServiceContext, ToolSetWithPrompt, all_tools};
use ai_toolset::ToolSet as AiToolSet;
use anyhow::{Context, Result};
@@ -151,41 +151,13 @@ async fn run_tool_loop(
.context("failed to start agent stream")?;
let idle_timeout = std::time::Duration::from_secs(3 * 60);
- let mut yielded_parts: Vec<AssistantMessagePart> = Vec::new();
+ let mut accumulator = StreamAccumulator::new();
loop {
match tokio::time::timeout(idle_timeout, stream.next()).await {
- Ok(Some(Ok(part))) => match part {
- StreamPart::Content(text) if !text.is_empty() => {
- yielded_parts.push(AssistantMessagePart::Text { text });
- }
- StreamPart::ToolCall(call) => {
- yielded_parts.push(AssistantMessagePart::ToolCall {
- name: call.name,
- json: call.json,
- id: call.id,
- });
- }
- StreamPart::ToolResponse(agent::ToolResponse::Json { id, json, name }) => {
- yielded_parts.push(AssistantMessagePart::ToolCallResponseJson {
- name,
- json,
- id,
- });
- }
- StreamPart::ToolResponse(agent::ToolResponse::Err {
- id,
- name,
- description,
- }) => {
- yielded_parts.push(AssistantMessagePart::ToolCallErr {
- name,
- description,
- id,
- });
- }
- _ => {}
- },
+ Ok(Some(Ok(part))) => {
+ accumulator.push(part);
+ }
Ok(Some(Err(e))) => {
tracing::error!(error=?e, "agent stream error");
break;
@@ -198,7 +170,7 @@ async fn run_tool_loop(
}
}
- Ok(yielded_parts)
+ Ok(accumulator.into_parts())
}
async fn store_conversation(