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
feat: auto rename chats after initial message (#3833)
Eric Hayes8f4003bda481
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsxindex 65ce3e0048..54ff0b3cf0 100644--- a/js/app/packages/app/component/Root.tsx+++ b/js/app/packages/app/component/Root.tsx@@ -48,6 +48,7 @@ import {prefetchUserInfo,useUserInfoQuery,} from '@queries/auth/user-info';+import { useChatRenameWebsocketSync } from '@queries/chat';import { prefetchHistory } from '@queries/history/history';import { invalidateUserNotifications } from '@queries/notification/user-notifications';import { QuerySyncProvider } from '@queries/sync/SyncProvider';@@ -361,6 +362,7 @@ const ROUTES: RouteDefinition[] = [function ConfiguredGlobalAppStateProvider(props: ParentProps) {// Initialize global notification helpersconst notifInterface = usePlatformNotificationState();+ useChatRenameWebsocketSync();const onNotification = (notification: UnifiedNotification) => {if (notifInterface === 'not-supported') return;diff --git a/js/app/packages/queries/chat.ts b/js/app/packages/queries/chat.tsindex 912e7163ca..e045a50f3b 100644--- a/js/app/packages/queries/chat.ts+++ b/js/app/packages/queries/chat.ts@@ -1,8 +1,20 @@import { throwOnErr } from '@core/util/result';import { cognitionApiServiceClient } from '@service-cognition/client';+import { createConnectionWebsocketEffect } from '@service-connection/websocket';import { useQuery } from '@tanstack/solid-query';+import { queryClient } from './client';+import { historyKeys } from './history/keys';+import { invalidatePreview } from './preview';+import { soupKeys } from './soup/keys';const CHAT_STALE_TIME = 30 * 1000;+const CHAT_RENAMED_MESSAGE_TYPE = 'chat_renamed';++type ChatRenamedMessage = {+ type: typeof CHAT_RENAMED_MESSAGE_TYPE;+ chat_id: string;+ name: string;+};export function useChatQuery(chatId: () => string | undefined) {return useQuery(() => {@@ -19,3 +31,27 @@ export function useChatQuery(chatId: () => string | undefined) {};});}++export function useChatRenameWebsocketSync() {+ createConnectionWebsocketEffect((message) => {+ if (message.type !== CHAT_RENAMED_MESSAGE_TYPE) return;++ let data: ChatRenamedMessage;+ try {+ data = JSON.parse(message.data);+ } catch {+ console.error('unparsable chat rename payload', message);+ return;+ }++ if (data.type !== CHAT_RENAMED_MESSAGE_TYPE || !data.chat_id) return;++ queryClient.invalidateQueries({ queryKey: ['chat', data.chat_id] });+ queryClient.invalidateQueries({ queryKey: ['entity'] });+ queryClient.invalidateQueries({ queryKey: historyKeys.list.queryKey });+ queryClient.invalidateQueries({ queryKey: soupKeys.items._def });+ queryClient.invalidateQueries({ queryKey: soupKeys.astItems._def });+ queryClient.invalidateQueries({ queryKey: soupKeys.search._def });+ invalidatePreview(data.chat_id);+ });+}diff --git a/js/bun.lock b/js/bun.lockindex 772e2c16ae..c1b5aff31b 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -830,7 +830,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],@@ -2550,7 +2550,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rsindex 3f0ff97c75..c1910d147a 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs@@ -21,6 +21,7 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_middleware::auth::internal_access::InternalApiSecretKey;use notification::domain::service::SqsNotificationIngress;use notification::outbound::queue::SqsQueue;+use notification::outbound::websocket::ConnectionGatewayClient;use search_service_client::SearchServiceClient;use secretsmanager_client::LocalOrRemoteSecret;use sqlx::PgPool;@@ -74,6 +75,7 @@ pub struct ApiContext {pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,pub notification_ingress_service: Arc<NotificationIngressType>,pub connection_repo: Arc<dyn ConnectionRepo>,+ pub connection_gateway_client: Arc<ConnectionGatewayClient>,pub soup_service: Arc<ToolSoupService>,pub email_service: Arc<ToolEmailService>,pub stream_repo: Arc<dyn StreamRepo>,diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex 564ce808b9..bfde55f425 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -352,6 +352,12 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arinternal_auth_key: LocalOrRemoteSecret::Local(InternalApiSecretKey::Comptime("testing")),notification_ingress_service,connection_repo: MockConnectionRepo::new(),+ connection_gateway_client: Arc::new(+ notification::outbound::websocket::ConnectionGatewayClient::new(+ "testing".to_string(),+ "http://localhost".to_string(),+ ),+ ),soup_service,email_service: email_service_for_tools.clone(),stream_repo: MockStreamRepo::new(),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.rsindex 727cd319bc..d109dfa2cf 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@@ -8,6 +8,7 @@ use crate::api::utils::log;use crate::core::constants::DEFAULT_CHAT_NAME;use crate::model::stream::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};use crate::service::ai_stream_registry::CancellationSubscription;+use crate::service::chat_renamer::spawn_initial_chat_rename;use crate::service::get_chat::get_chat;use crate::service::notification::notify;use agent::AgentModel;@@ -182,9 +183,10 @@ async fn send_chat_message_inner(let model = model_access.model();// Try to get the chat first - if it doesn't exist or no chat_id provided, create it- let (chat, actual_chat_id) = if requested_chat_id.is_empty() {+ let (chat, actual_chat_id, created_new_chat) = if requested_chat_id.is_empty() {// No chat_id provided - create a new chat- create_new_chat(&ctx, &user_id, model, &stream_id).await?+ let (chat, chat_id) = create_new_chat(&ctx, &user_id, model, &stream_id).await?;+ (chat, chat_id, true)} else {match get_chat(&ctx, &requested_chat_id, user_id.0.as_ref()).await {Ok(chat) => {@@ -215,7 +217,7 @@ async fn send_chat_message_inner(_ => (),},};- (chat, requested_chat_id)+ (chat, requested_chat_id, false)}Err(_) => {// Chat doesn't exist - create a new one@@ -223,10 +225,12 @@ async fn send_chat_message_inner(requested_chat_id = %requested_chat_id,"Chat not found, creating new chat");- create_new_chat(&ctx, &user_id, model, &stream_id).await?+ let (chat, chat_id) = create_new_chat(&ctx, &user_id, model, &stream_id).await?;+ (chat, chat_id, true)}}};+ let should_auto_rename_chat = created_new_chat || chat.messages.is_empty();// Convert HTTP request to internal payload for existing functionslet payload = SendChatMessagePayload {@@ -255,6 +259,16 @@ async fn send_chat_message_inner(})?;let user_message_id = resolved.message_id;+ if should_auto_rename_chat {+ spawn_initial_chat_rename(+ ctx.clone(),+ (*user_id).clone(),+ actual_chat_id.clone(),+ stream_id.clone(),+ request.content.clone(),+ );+ }+// Fetch all resolved attachment content for the chat (current + prior messages)let all_resolved_parts: Vec<FormattedParts> = ctx.message_servicediff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rsindex 114c975cea..2aba36183b 100644--- a/rust/cloud-storage/document_cognition_service/src/config.rs+++ b/rust/cloud-storage/document_cognition_service/src/config.rs@@ -1,8 +1,8 @@pub use macro_env::Environment;use macro_env_var::{env_var, maybe_env_var};use macro_service_urls::{- DocumentCognitionServiceUrl, DocumentStorageServiceUrl, EmailServiceUrl, LexicalServiceUrl,- StaticFileServiceUrl, SyncServiceUrl,+ ConnectionGatewayUrl, DocumentCognitionServiceUrl, DocumentStorageServiceUrl, EmailServiceUrl,+ LexicalServiceUrl, StaticFileServiceUrl, SyncServiceUrl,};use crate::core::constants::DEFAULT_DOCUMENT_BATCH_LIMIT;@@ -45,6 +45,8 @@ pub struct Config {pub document_cognition_service_url: String,/// static file service urlpub static_file_service_url: String,+ /// connection gateway url+ pub connection_gateway_url: String,/// authentication service url (for soup service)pub authentication_service_url: String,/// authentication service secret key (for soup service)@@ -112,6 +114,7 @@ impl Config {let email_service_url = EmailServiceUrl::new()?.to_string();let document_cognition_service_url = DocumentCognitionServiceUrl::new()?.to_string();let static_file_service_url = StaticFileServiceUrl::new()?.to_string();+ let connection_gateway_url = ConnectionGatewayUrl::new()?.to_string();let EnvVars {database_url,@@ -152,6 +155,7 @@ impl Config {email_service_url,document_cognition_service_url,static_file_service_url,+ connection_gateway_url,authentication_service_url: authentication_service_url.to_string(),authentication_service_secret_key: authentication_service_secret_key.to_string(),redis_host,@@ -187,6 +191,7 @@ impl Config {email_service_url: Default::default(),document_cognition_service_url: Default::default(),static_file_service_url: Default::default(),+ connection_gateway_url: Default::default(),authentication_service_url: Default::default(),authentication_service_secret_key: Default::default(),redis_host: RedisHost::Comptime("redis://localhost:6379"),diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 6eccc2f99d..b3911cff99 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -35,6 +35,7 @@ use notification::domain::service::{};use notification::outbound::queue::SqsQueue;use notification::outbound::repository::DbNotificationRepository;+use notification::outbound::websocket::ConnectionGatewayClient;use readonly_pool::ReadOnlyPool;use search_service_client::SearchServiceClient;use secretsmanager_client::SecretManager;@@ -165,6 +166,10 @@ async fn main() -> anyhow::Result<()> {.context("failed to create connection manager")?;tracing::info!("initialized connection repo");+ let connection_gateway_client = Arc::new(ConnectionGatewayClient::new(+ internal_auth_key.as_ref().to_string(),+ config.connection_gateway_url.clone(),+ ));let ingress_queue = SqsQueue::new(aws_sdk_sqs::Client::new(&aws_config),@@ -436,6 +441,7 @@ async fn main() -> anyhow::Result<()> {internal_auth_key,notification_ingress_service,connection_repo: connection_manager.persistence,+ connection_gateway_client,soup_service,email_service: email_service_for_tools,stream_repo,diff --git a/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs b/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rsnew file mode 100644index 0000000000..8fefa1f626--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/service/chat_renamer.rs@@ -0,0 +1,112 @@+use crate::api::context::ApiContext;+use agent::AgentModel;+use chat::domain::models::PatchChatArgs;+use chat::domain::ports::ChatRepo;+use chat::outbound::postgres::PgChatRepo;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use std::sync::Arc;++const CHAT_RENAMED_MESSAGE_TYPE: &str = "chat_renamed";+const MAX_CHAT_NAME_CHARS: usize = 100;++pub fn spawn_initial_chat_rename(+ ctx: Arc<ApiContext>,+ user_id: MacroUserIdStr<'static>,+ chat_id: String,+ stream_id: String,+ initial_question: String,+) {+ tokio::spawn(async move {+ if let Err(err) =+ rename_initial_chat(ctx, user_id, chat_id, stream_id, initial_question).await+ {+ tracing::warn!(error=?err, "failed to auto-rename initial chat");+ }+ });+}++#[tracing::instrument(skip(ctx, initial_question), err)]+async fn rename_initial_chat(+ ctx: Arc<ApiContext>,+ user_id: MacroUserIdStr<'static>,+ chat_id: String,+ stream_id: String,+ initial_question: String,+) -> anyhow::Result<()> {+ let name = generate_chat_name(&initial_question).await?;+ if name.is_empty() {+ anyhow::bail!("generated chat name was empty");+ }+ let user_id_string = user_id.as_ref().to_string();++ PgChatRepo::new(ctx.db.clone())+ .patch(+ user_id,+ &chat_id,+ PatchChatArgs {+ name: Some(name.clone()),+ project_id: None,+ share_permission: None,+ },+ )+ .await+ .map_err(anyhow::Error::from)?;++ ctx.connection_gateway_client+ .batch_send_to_entities(+ CHAT_RENAMED_MESSAGE_TYPE,+ &serde_json::json!({+ "type": CHAT_RENAMED_MESSAGE_TYPE,+ "stream_id": stream_id,+ "chat_id": chat_id,+ "name": name,+ }),+ vec![EntityType::User.with_entity_str(&user_id_string)],+ )+ .await+ .map_err(|err| anyhow::anyhow!("{err}"))?;++ Ok(())+}++async fn generate_chat_name(initial_question: &str) -> anyhow::Result<String> {+ let response = agent::complete(+ AgentModel::Fast,+ "You rename AI chats. Return only a concise title, no quotes, no punctuation-only text. Use 2-6 words.",+ initial_question,+ )+ .await?;++ Ok(clean_chat_name(&response))+}++fn clean_chat_name(raw: &str) -> String {+ let trimmed = raw+ .trim()+ .trim_matches('"')+ .trim_matches('\'')+ .trim()+ .replace(['\n', '\r', '\t'], " ");+ let collapsed = trimmed.split_whitespace().collect::<Vec<_>>().join(" ");+ collapsed.chars().take(MAX_CHAT_NAME_CHARS).collect()+}++#[cfg(test)]+mod tests {+ use super::clean_chat_name;++ #[test]+ fn clean_chat_name_trims_quotes_and_collapses_whitespace() {+ assert_eq!(+ clean_chat_name(" \"Plan Q3\nHiring\" "),+ "Plan Q3 Hiring"+ );+ }++ #[test]+ fn clean_chat_name_limits_length() {+ let raw = "a".repeat(120);+ assert_eq!(clean_chat_name(&raw).len(), 100);+ }+}diff --git a/rust/cloud-storage/document_cognition_service/src/service/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/mod.rsindex ae1221f7fd..758a9cac8c 100644--- a/rust/cloud-storage/document_cognition_service/src/service/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/mod.rs@@ -1,4 +1,5 @@pub mod ai_stream_registry;+pub mod chat_renamer;pub mod get_chat;pub mod id_mapping;pub mod notification;diff --git a/rust/cloud-storage/notification/src/outbound/websocket.rs b/rust/cloud-storage/notification/src/outbound/websocket.rsindex a9612e3ac5..0ad3cad933 100644--- a/rust/cloud-storage/notification/src/outbound/websocket.rs+++ b/rust/cloud-storage/notification/src/outbound/websocket.rs@@ -107,7 +107,8 @@ struct BatchSendUniqueMessagesBody<'a> {}impl ConnectionGatewayClient {- async fn batch_send_to_entities<T: Serialize + Send + Sync>(+ /// Send a payload to connection gateway entities with the provided message type.+ pub async fn batch_send_to_entities<T: Serialize + Send + Sync>(&self,message_type: &str,payload: &T,