Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix-message-order (#1565)
Eric Hayesa316f5ca51c5
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rsindex 9352c70783..f5024d0bf2 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs@@ -14,7 +14,7 @@ use crate::service::ai::name::maybe_rename_chat;use crate::service::get_chat::get_chat;use ai::tool::ToolLoop;use ai::tool::types::StreamPart;-use ai::types::{AssistantMessagePart, ChatMessage, Model};+use ai::types::{AssistantMessagePart, Model};use ai_tools::{AiToolSet, RequestContext, ToolServiceContext};use async_stream::stream;use axum::Json;@@ -33,8 +33,7 @@ use models_permissions::share_permission::access_level::AccessLevel;use serde::{Deserialize, Serialize};use std::fmt;use std::sync::Arc;-use stream::domain::{PayloadStream, StreamId, StreamRepoExt};-use tokio::sync::oneshot;+use stream::domain::{StreamId, StreamRepoExt};use utoipa::ToSchema;/// Raw Bearer token extracted from the Authorization header.@@ -254,11 +253,8 @@ pub async fn send_chat_message(stream_id: stream_id.clone(),};- // Create a channel to receive new_messages after streaming completes- let (messages_tx, messages_rx) = oneshot::channel::<Vec<ChatMessage>>();-- // Create the payload stream- let payload_stream = create_chat_payload_stream(+ // Stream the AI response, save messages when complete+ stream_and_save_message(ctx.clone(),ai_request,toolset.toolset,@@ -267,58 +263,15 @@ pub async fn send_chat_message(actual_chat_id.clone(),message_id.clone(),stream_id.clone(),- messages_tx,model,now,request.content.clone(),user_message_id,request.attachments.clone().unwrap_or_default(),+ durable_stream_id,+ is_first_message,);- // Use the extension trait to handle spawning and stream management- let stream_handle =- ctx.stream_repo- .clone()- .from_async_stream(durable_stream_id, payload_stream, None, None);-- // Spawn post-processing task- let ctx_clone = ctx.clone();- let user_id_clone = user_id.clone();- let chat_id = actual_chat_id.clone();- let message_id_for_store = message_id.clone();-- tokio::spawn(async move {- // Wait for the stream to complete- let _ = stream_handle.await;-- // Get the new messages from the channel- if let Ok(new_messages) = messages_rx.await {- // Store conversation messages, using the pre-generated message_id for the first assistant message- if let Err(err) = store_conversation_messages(- ctx_clone.clone(),- user_id_clone.0.as_ref(),- &chat_id,- new_messages,- model,- Some(message_id_for_store),- )- .await- {- tracing::error!(error=?err, "failed to store conversation messages");- }-- // Maybe rename chat if first message- if is_first_message- && let Ok(new_name) =- maybe_rename_chat(&chat_id, &ctx_clone, user_id_clone.0.as_ref())- .await- .inspect_err(|err| tracing::error!(error=?err, "failed to rename chat"))- {- tracing::info!(chat_id, new_name, "chat renamed after first message");- }- }- });-Ok(Json(SendChatMessageResponse {stream_id,message_id,@@ -368,10 +321,12 @@ async fn create_new_chat(Ok((chat, new_chat_id))}-/// Creates the AI stream and returns a PayloadStream that yields JSON values.-/// Returns Err if the stream should not be started (e.g., aborted).+/// Streams the AI response and saves conversation messages when complete.+///+/// Creates a payload stream, publishes it via `from_async_stream`, and stores+/// the conversation messages after the stream finishes.#[expect(clippy::too_many_arguments, reason = "matches WS handler signature")]-fn create_chat_payload_stream(+fn stream_and_save_message(ctx: Arc<ApiContext>,request: ai::types::ChatCompletionRequest,toolset: AiToolSet,@@ -380,18 +335,18 @@ fn create_chat_payload_stream(chat_id: String,message_id: String,stream_id: String,- messages_tx: oneshot::Sender<Vec<ChatMessage>>,model: Model,now: std::time::Instant,user_message_content: String,user_message_id: String,user_message_attachments: Vec<ChatAttachmentWithName>,-) -> PayloadStream {+ durable_stream_id: StreamId,+ is_first_message: bool,+) {// Check for abort before startingif MESSAGE_ABORT_MAP.contains_key(&stream_id) {MESSAGE_ABORT_MAP.remove(&stream_id);- let _ = messages_tx.send(vec![]);- return Box::pin(futures::stream::empty());+ return;}tracing::trace!(request=?request, "streaming chat request");@@ -408,6 +363,7 @@ fn create_chat_payload_stream(user_id: user_id.clone(),jwt: Arc::new(jwt_token),};+ let ctx_outer = ctx.clone();let payload_stream = stream! {// Yield the user message as the first item so other clients can display it@@ -449,7 +405,6 @@ fn create_chat_payload_stream(if let Ok(json) = serde_json::to_value(&error_msg) {yield json;}- let _ = messages_tx.send(vec![]);return;}};@@ -468,7 +423,6 @@ fn create_chat_payload_stream(// Check for abort during streamingif MESSAGE_ABORT_MAP.contains_key(&stream_id) {MESSAGE_ABORT_MAP.remove(&stream_id);- let _ = messages_tx.send(vec![]);return;}@@ -536,7 +490,6 @@ fn create_chat_payload_stream(if let Ok(json) = serde_json::to_value(&error_msg) {yield json;}- let _ = messages_tx.send(vec![]);return;}}@@ -553,10 +506,36 @@ fn create_chat_payload_stream(yield json;}- // Get new messages and send through channel+ // Save conversation messageslet new_messages = chat.get_new_conversation_messages();- let _ = messages_tx.send(new_messages);+ if let Err(err) = store_conversation_messages(+ ctx.clone(),+ user_id.0.as_ref(),+ &chat_id,+ new_messages,+ model,+ Some(message_id),+ )+ .await+ {+ tracing::error!(error=?err, "failed to store conversation messages");+ }++ // Maybe rename chat if first message+ if is_first_message+ && let Ok(new_name) =+ maybe_rename_chat(&chat_id, &ctx, user_id.0.as_ref())+ .await+ .inspect_err(|err| tracing::error!(error=?err, "failed to rename chat"))+ {+ tracing::info!(chat_id, new_name, "chat renamed after first message");+ }};- Box::pin(payload_stream)+ ctx_outer.stream_repo.clone().from_async_stream(+ durable_stream_id,+ Box::pin(payload_stream),+ None,+ None,+ );}diff --git a/rust/cloud-storage/stream/src/domain/ext.rs b/rust/cloud-storage/stream/src/domain/ext.rsindex e1d0a39dbb..f617568caf 100644--- a/rust/cloud-storage/stream/src/domain/ext.rs+++ b/rust/cloud-storage/stream/src/domain/ext.rs@@ -18,7 +18,7 @@ pub trait StreamRepoExt: StreamRepo {stream: PayloadStream,timeout: Option<Duration>,close_delay: Option<Duration>,- ) -> tokio::task::JoinHandle<()>;+ );}impl<S> StreamRepoExt for S@@ -34,7 +34,7 @@ wheremut stream: PayloadStream,timeout: Option<Duration>,close_delay: Option<Duration>,- ) -> tokio::task::JoinHandle<()> {+ ) {let writer = self.clone();let writer_id = id.clone();tokio::spawn(async move {@@ -59,6 +59,6 @@ where.close(&id).await.inspect_err(|e| tracing::error!(error=?e, "failed to mark stream as closed"));- })+ });}}