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.

kill ChatMessage.isPartial (#323)

Eric Hayesea499ea8a322
diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
index 71328a12bb..c9fc83a77d 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs
@@ -1,10 +1,7 @@
mod ai_request;
mod toolset;
-use crate::api::ws::connection::{
- MESSAGE_ABORT_MAP, add_partial_message_part, clear_partial_message, register_partial_message,
- ws_send,
-};
+use crate::api::ws::connection::{MESSAGE_ABORT_MAP, ws_send};
use crate::core::model::FALLBACK_MODEL;
use crate::model::chats::ChatResponse;
use crate::model::ws::{StreamError, StreamWebSocketError};
@@ -12,7 +9,6 @@ use crate::{
api::{
context::ApiContext,
utils::{log, search},
- ws::connection::write_partial_message,
},
model::ws::{FromWebSocketMessage, SendChatMessagePayload},
service::{ai::name::maybe_rename_chat, get_chat::get_chat},
@@ -107,7 +103,6 @@ pub async fn stream_chat_response(
) -> Result<StreamChatResponse, ai::types::AiError> {
if MESSAGE_ABORT_MAP.contains_key(stream_id) {
MESSAGE_ABORT_MAP.remove(stream_id);
- // No database cleanup needed since we don't create partial messages until disconnect
return Ok(StreamChatResponse {
new_messages: Vec::new(), // Return empty for aborted streams
});
@@ -133,9 +128,6 @@ pub async fn stream_chat_response(
.send_message(request, request_context, user_id.to_owned())
.await?;
- // Register potential partial message with connection for disconnect-based saving
- register_partial_message(connection_id, message_id, chat_id, Some(model.to_string()));
-
// Process the stream completely
let mut usage_reqs = vec![];
let mut is_first_token = false;
@@ -149,8 +141,6 @@ pub async fn stream_chat_response(
// Abort streaming for a message if it has been stopped
if MESSAGE_ABORT_MAP.contains_key(stream_id) {
MESSAGE_ABORT_MAP.remove(stream_id);
- write_partial_message(connection_id, &context).await;
- // No database cleanup needed since we don't create partial messages until disconnect
return Ok(StreamChatResponse {
new_messages: Vec::new(), // Return empty for aborted streams
});
@@ -165,9 +155,6 @@ pub async fn stream_chat_response(
let message_part = AssistantMessagePart::Text { text: content };
- // Add part to partial message tracking for disconnect-based saving
- add_partial_message_part(connection_id, message_part.clone());
-
// Send to websocket
let response = FromWebSocketMessage::ChatMessageResponse {
stream_id: stream_id.to_string(),
@@ -184,9 +171,6 @@ pub async fn stream_chat_response(
id: call.id,
};
- // Add part to partial message tracking for disconnect-based saving
- add_partial_message_part(connection_id, message_part.clone());
-
let response = FromWebSocketMessage::ChatMessageResponse {
stream_id: stream_id.to_string(),
chat_id: chat_id.to_string(),
@@ -211,9 +195,6 @@ pub async fn stream_chat_response(
StreamPart::ToolResponse(ai::tool::types::ToolResponse::Json { id, json, name }) => {
let message_part = AssistantMessagePart::ToolCallResponseJson { name, json, id };
- // Add part to partial message tracking for disconnect-based saving
- add_partial_message_part(connection_id, message_part.clone());
-
ws_send(
sender,
FromWebSocketMessage::ChatMessageResponse {
@@ -235,9 +216,6 @@ pub async fn stream_chat_response(
id,
};
- // Add part to partial message tracking for disconnect-based saving
- add_partial_message_part(connection_id, message_part.clone());
-
ws_send(
sender,
FromWebSocketMessage::ChatMessageResponse {
@@ -255,9 +233,6 @@ pub async fn stream_chat_response(
// Explicitly drop the stream to release the mutable borrow
drop(stream);
- // Clear partial message tracking since stream completed successfully
- clear_partial_message(connection_id);
-
// Get new messages - no finalization needed since we only save on disconnect
let new_messages = chat.get_new_conversation_messages();
diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs
index c3e65d8358..d042a801bc 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs
@@ -1,5 +1,4 @@
-use ai::types::ChatMessageContent;
-use ai::types::{AssistantMessagePart, Role};
+use super::chat_permissions;
use anyhow::Result;
use axum::extract::State;
use axum::{
@@ -12,19 +11,9 @@ use axum::{
use dashmap::DashMap;
use macro_user_id::user_id::MacroUserId;
use model::{chat::AttachmentType, user::UserContext};
+use models_permissions::share_permission::access_level::AccessLevel;
use std::sync::Arc;
use std::sync::LazyLock;
-use tokio::sync::Mutex;
-
-#[derive(Debug, Clone)]
-pub struct PartialMessageInfo {
- pub chat_id: String,
- pub content: ChatMessageContent,
- pub model: Option<String>,
-}
-use super::chat_permissions;
-use macro_db_client::dcs::partial_message::create_partial_message;
-use models_permissions::share_permission::access_level::AccessLevel;
use tokio::sync::mpsc::{self, UnboundedSender, WeakUnboundedSender};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
@@ -54,105 +43,6 @@ pub static MESSAGE_ABORT_MAP: LazyLock<DashMap<String, bool>> =
pub static CONNECTION_MAP: LazyLock<DashMap<String, WeakUnboundedSender<FromWebSocketMessage>>> =
std::sync::LazyLock::new(DashMap::new);
-/// Maps a connection id to active partial message info
-pub static CONNECTION_PARTIAL_MESSAGES: LazyLock<DashMap<String, PartialMessageInfo>> =
- std::sync::LazyLock::new(DashMap::new);
-
-pub static CONNECTION_COUNT: LazyLock<Mutex<u32>> = std::sync::LazyLock::new(|| Mutex::new(0));
-
-pub async fn increment_connection_count() -> u32 {
- let mut connection_count = CONNECTION_COUNT.lock().await;
- *connection_count += 1;
- *connection_count
-}
-
-pub async fn decrement_connection_count() -> u32 {
- let mut connection_count = CONNECTION_COUNT.lock().await;
- *connection_count -= 1;
- *connection_count
-}
-
-pub fn register_partial_message(
- connection_id: &str,
- _message_id: &str,
- chat_id: &str,
- model: Option<String>,
-) {
- CONNECTION_PARTIAL_MESSAGES.insert(
- connection_id.to_string(),
- PartialMessageInfo {
- chat_id: chat_id.to_string(),
- content: ChatMessageContent::AssistantMessageParts(Vec::new()),
- model,
- },
- );
-}
-
-pub fn add_partial_message_part(connection_id: &str, part: AssistantMessagePart) {
- if let Some(mut entry) = CONNECTION_PARTIAL_MESSAGES.get_mut(connection_id)
- && let ChatMessageContent::AssistantMessageParts(ref mut parts) = entry.content
- {
- // Only add the part if serialization would succeed
- if serde_json::to_value(&part).is_ok() {
- match &part {
- AssistantMessagePart::Text { text } => {
- // If the last part is also text, accumulate it
- if let Some(AssistantMessagePart::Text { text: last_text }) = parts.last_mut() {
- last_text.push_str(text);
- } else {
- // Otherwise, add as new text part
- parts.push(part);
- }
- }
- _ => {
- // For non-text parts (tool calls, responses, etc.), add as separate parts
- parts.push(part);
- }
- }
- }
- }
-}
-
-/// Clears partial message tracking for a connection (used when stream completes successfully)
-pub fn clear_partial_message(connection_id: &str) {
- CONNECTION_PARTIAL_MESSAGES.remove(connection_id);
-}
-
-/// Handles disconnection from the websocket connection by removing the connection from the map
-/// and logging any partial message content
-pub async fn write_partial_message(connection_id: &str, ctx: &crate::api::context::ApiContext) {
- if let Some((_, partial_info)) = CONNECTION_PARTIAL_MESSAGES.remove(connection_id) {
- // Check if there are any message parts to save
- let has_content = match &partial_info.content {
- ChatMessageContent::AssistantMessageParts(parts) => !parts.is_empty(),
- ChatMessageContent::Text(text) => !text.is_empty(),
- };
-
- if has_content {
- // Create a partial message in database with the accumulated content
- if let Ok(mut transaction) = ctx.db.begin().await {
- if let Err(e) = create_partial_message(
- &mut transaction,
- &partial_info.chat_id,
- Role::Assistant,
- &partial_info.content,
- partial_info.model,
- )
- .await
- {
- tracing::warn!("Failed to save partial message on disconnect: {}", e);
- } else {
- let _ = transaction.commit().await;
- tracing::info!(
- chat_id=?partial_info.chat_id,
- "Saved partial message on disconnect",
- );
- }
- }
- }
- }
-}
-
#[utoipa::path(
get,
path = "/stream",
@@ -215,13 +105,7 @@ async fn handle_websocket_connection(
ctx: ApiContext,
user_context: UserContext,
) {
- let connection_count = increment_connection_count().await;
- tracing::debug!(
- user_id = ?user_context.user_id,
- connection_count,
- "accepted websocket connection"
- );
-
+ tracing::info!(abort_map_size=?MESSAGE_ABORT_MAP.len(), connection_map_size=?CONNECTION_MAP.len(), "new connection");
let connection_id = Uuid::new_v4().to_string();
// ws_sender handles sending messages over the websocket
@@ -240,7 +124,6 @@ async fn handle_websocket_connection(
// Ability to cancel the receiver task from any subtask
let receiver_cancel_token = CancellationToken::new();
let cancel_token = receiver_cancel_token.clone();
- let ctx_for_cleanup = ctx.clone();
let connection_id_clone = connection_id.clone();
// the sender task listens on messages to the message_receiver, and then
@@ -521,12 +404,7 @@ async fn handle_websocket_connection(
},
};
-
CONNECTION_MAP.remove(&connection_id);
- write_partial_message(&connection_id, &ctx_for_cleanup).await;
-
- let connection_count = decrement_connection_count().await;
- tracing::trace!(connection_count, "closed websocket connection");
}
pub fn ws_send(sender: &UnboundedSender<FromWebSocketMessage>, message: FromWebSocketMessage) {
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-35fc999ffe794606ccad33fe081a57a60284035692c75dda0ccc495f98fc85e1.json b/rust/cloud-storage/macro_db_client/.sqlx/query-35fc999ffe794606ccad33fe081a57a60284035692c75dda0ccc495f98fc85e1.json
deleted file mode 100644
index 6fff928a9c..0000000000
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-35fc999ffe794606ccad33fe081a57a60284035692c75dda0ccc495f98fc85e1.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE \"ChatMessage\"\n SET \"content\" = $1, \"updatedAt\" = NOW()\n WHERE id = $2 AND \"isPartial\" = true\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Jsonb",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "35fc999ffe794606ccad33fe081a57a60284035692c75dda0ccc495f98fc85e1"
-}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-3618c9015853457f4a119e1e6e240b6d6f015002dfd06d6b4a131fb075bd5a7c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-3618c9015853457f4a119e1e6e240b6d6f015002dfd06d6b4a131fb075bd5a7c.json
deleted file mode 100644
index d53ba82740..0000000000
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-3618c9015853457f4a119e1e6e240b6d6f015002dfd06d6b4a131fb075bd5a7c.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE \"ChatMessage\"\n SET \"content\" = $1, \"updatedAt\" = NOW(), \"isPartial\" = false\n WHERE id = $2\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Jsonb",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "3618c9015853457f4a119e1e6e240b6d6f015002dfd06d6b4a131fb075bd5a7c"
-}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-5734033c9efe4ba2019ffc42b20f0dfc31d6b64ceef358df575edca60717f705.json b/rust/cloud-storage/macro_db_client/.sqlx/query-5734033c9efe4ba2019ffc42b20f0dfc31d6b64ceef358df575edca60717f705.json
deleted file mode 100644
index 7d40d16c25..0000000000
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-5734033c9efe4ba2019ffc42b20f0dfc31d6b64ceef358df575edca60717f705.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO \"ChatMessage\" (\"chatId\", \"content\", \"role\", \"model\", \"isPartial\")\n VALUES ($1, $2, $3, $4, true)\n RETURNING id;\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Jsonb",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "5734033c9efe4ba2019ffc42b20f0dfc31d6b64ceef358df575edca60717f705"
-}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-5b3e3180b6378a70bea805344f89a963c2c2c22dadc9f2a21a88326ea8ccb6a0.json b/rust/cloud-storage/macro_db_client/.sqlx/query-5b3e3180b6378a70bea805344f89a963c2c2c22dadc9f2a21a88326ea8ccb6a0.json
deleted file mode 100644
index f5943ff2b7..0000000000
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-5b3e3180b6378a70bea805344f89a963c2c2c22dadc9f2a21a88326ea8ccb6a0.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT id, content, role\n FROM \"ChatMessage\"\n WHERE \"chatId\" = $1 AND \"isPartial\" = true\n ORDER BY \"createdAt\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "content",
- "type_info": "Jsonb"
- },
- {
- "ordinal": 2,
- "name": "role",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false
- ]
- },
- "hash": "5b3e3180b6378a70bea805344f89a963c2c2c22dadc9f2a21a88326ea8ccb6a0"
-}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-e338af000edc3f3bc0265a71172dbe5726c55200e2b73465757fd91fc0cfed42.json b/rust/cloud-storage/macro_db_client/.sqlx/query-e338af000edc3f3bc0265a71172dbe5726c55200e2b73465757fd91fc0cfed42.json
deleted file mode 100644
index d4be0c47a7..0000000000
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-e338af000edc3f3bc0265a71172dbe5726c55200e2b73465757fd91fc0cfed42.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM \"ChatMessage\"\n WHERE \"chatId\" = $1 AND \"isPartial\" = true\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "e338af000edc3f3bc0265a71172dbe5726c55200e2b73465757fd91fc0cfed42"
-}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20251124210006_drop_isPartial.sql b/rust/cloud-storage/macro_db_client/migrations/20251124210006_drop_isPartial.sql
new file mode 100644
index 0000000000..9ad13673c9
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20251124210006_drop_isPartial.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "ChatMessage"
+DROP COLUMN "isPartial";
diff --git a/rust/cloud-storage/macro_db_client/src/dcs/mod.rs b/rust/cloud-storage/macro_db_client/src/dcs/mod.rs
index 8fc23cb812..24383703eb 100644
--- a/rust/cloud-storage/macro_db_client/src/dcs/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/dcs/mod.rs
@@ -12,7 +12,6 @@ pub mod get_attachment;
pub mod get_attachments_for_message;
pub mod get_chats;
pub mod get_chats_for_attachment;
-pub mod partial_message;
pub mod patch_chat;
// Document queries
diff --git a/rust/cloud-storage/macro_db_client/src/dcs/partial_message.rs b/rust/cloud-storage/macro_db_client/src/dcs/partial_message.rs
deleted file mode 100644
index 8b4a707a0b..0000000000
--- a/rust/cloud-storage/macro_db_client/src/dcs/partial_message.rs
+++ /dev/null
@@ -1,121 +0,0 @@
-use ai::types::{ChatMessageContent, Role};
-use sqlx::{Postgres, Transaction};
-use std::str::FromStr;
-
-/// Creates a partial message record with specific content (used on disconnect/interrupt)
-#[tracing::instrument(skip(transaction, content), err)]
-pub async fn create_partial_message(
- transaction: &mut Transaction<'_, Postgres>,
- chat_id: &str,
- role: Role,
- content: &ChatMessageContent,
- model: Option<String>,
-) -> anyhow::Result<String> {
- // Create partial message with the provided content
- let message = sqlx::query!(
- r#"
- INSERT INTO "ChatMessage" ("chatId", "content", "role", "model", "isPartial")
- VALUES ($1, $2, $3, $4, true)
- RETURNING id;
- "#,
- chat_id,
- serde_json::to_value(content)?,
- role.as_ref(),
- model
- )
- .fetch_one(transaction.as_mut())
- .await?;
-
- Ok(message.id)
-}
-
-/// Updates a partial message with new content
-#[tracing::instrument(skip(transaction, content), err)]
-pub async fn update_partial_message(
- transaction: &mut Transaction<'_, Postgres>,
- message_id: &str,
- content: &ChatMessageContent,
-) -> anyhow::Result<()> {
- sqlx::query!(
- r#"
- UPDATE "ChatMessage"
- SET "content" = $1, "updatedAt" = NOW()
- WHERE id = $2 AND "isPartial" = true
- "#,
- serde_json::to_value(content)?,
- message_id
- )
- .execute(transaction.as_mut())
- .await?;
-
- Ok(())
-}
-
-/// Finalizes a partial message by setting isPartial to false
-#[tracing::instrument(skip(transaction), err)]
-pub async fn finalize_partial_message(
- transaction: &mut Transaction<'_, Postgres>,
- message_id: &str,
- final_content: &ChatMessageContent,
-) -> anyhow::Result<()> {
- sqlx::query!(
- r#"
- UPDATE "ChatMessage"
- SET "content" = $1, "updatedAt" = NOW(), "isPartial" = false
- WHERE id = $2
- "#,
- serde_json::to_value(final_content)?,
- message_id
- )
- .execute(transaction.as_mut())
- .await?;
-
- Ok(())
-}
-
-/// Removes partial messages for a chat (cleanup on abort/disconnect)
-#[tracing::instrument(skip(transaction), err)]
-pub async fn cleanup_partial_messages(
- transaction: &mut Transaction<'_, Postgres>,
- chat_id: &str,
-) -> anyhow::Result<()> {
- sqlx::query!(
- r#"
- DELETE FROM "ChatMessage"
- WHERE "chatId" = $1 AND "isPartial" = true
- "#,
- chat_id
- )
- .execute(transaction.as_mut())
- .await?;
-
- Ok(())
-}
-
-/// Gets all partial messages for a chat (for recovery on reconnection)
-#[tracing::instrument(skip(transaction), err)]
-pub async fn get_partial_messages(
- transaction: &mut Transaction<'_, Postgres>,
- chat_id: &str,
-) -> anyhow::Result<Vec<(String, ChatMessageContent, Role)>> {
- let messages = sqlx::query!(
- r#"
- SELECT id, content, role
- FROM "ChatMessage"
- WHERE "chatId" = $1 AND "isPartial" = true
- ORDER BY "createdAt"
- "#,
- chat_id
- )
- .fetch_all(transaction.as_mut())
- .await?;
-
- let mut result = Vec::new();
- for message in messages {
- let content: ChatMessageContent = serde_json::from_value(message.content)?;
- let role = Role::from_str(&message.role)?;
- result.push((message.id, content, role));
- }
-
- Ok(result)
-}