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.

feat(ai): Notifications (#1670)

Eric Hayesfcb8878461d2
diff --git a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts
index 0f7ec9a26a..06b9d80140 100644
--- a/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts
+++ b/js/app/packages/entity/src/extractors-notification/notification-description-helpers.ts
@@ -1,6 +1,6 @@
+import type { NotificationType } from '@core/types';
import { match } from 'ts-pattern';
import type { Notification } from '../types/notification';
-import type { NotificationType } from '@core/types';
/**
* Gets unique sender IDs from a notification stack
@@ -27,6 +27,7 @@ export function getActionVerb(type: NotificationType): string {
.with('mentioned_in_document_comment', () => 'mentioned you')
.with('channel_message_reply', () => 'replied')
.with('channel_message_send', () => 'sent a message')
+ .with('ai_response', () => 'AI responded')
.with('new_email', () => 'sent an email')
.with('channel_invite', () => 'invited you')
.with('invite_to_team', () => 'invited you')
@@ -42,6 +43,7 @@ export function getTypeNoun(type: NotificationType, count: number): string {
return match(type)
.with('channel_message_reply', () => (count === 1 ? 'reply' : 'replies'))
.with('channel_message_send', () => (count === 1 ? 'message' : 'messages'))
+ .with('ai_response', () => (count === 1 ? 'response' : 'responses'))
.with('channel_mention', () => (count === 1 ? 'mention' : 'mentions'))
.with('document_mention', () => (count === 1 ? 'mention' : 'mentions'))
.with('mentioned_in_document_comment', () =>
diff --git a/js/app/packages/entity/src/extractors-notification/notification-description.tsx b/js/app/packages/entity/src/extractors-notification/notification-description.tsx
index 6424ba366f..66806c683d 100644
--- a/js/app/packages/entity/src/extractors-notification/notification-description.tsx
+++ b/js/app/packages/entity/src/extractors-notification/notification-description.tsx
@@ -92,7 +92,7 @@ export function NotificationDescription(props: NotificationDescriptionProps) {
// Single notification: "Peter mentioned you"
if (isSingleNotification()) {
- if (senderId) {
+ if (senderId && type !== 'ai_response') {
return `${primarySenderFirstName()} ${getActionVerb(type)}`;
}
return getActionVerb(type);
diff --git a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx
index d5ab676286..1b729a74e7 100644
--- a/js/app/packages/entity/src/extractors-notification/notification-icon.tsx
+++ b/js/app/packages/entity/src/extractors-notification/notification-icon.tsx
@@ -34,6 +34,7 @@ function getNotificationIcon(
.with('channel_invite', () => UserPlusIcon)
.with('invite_to_team', () => UserPlusIcon)
.with('task_assigned', () => CheckIcon)
+ .with('ai_response', () => ChatIcon)
.exhaustive();
}
diff --git a/js/app/packages/entity/src/utils/notification.ts b/js/app/packages/entity/src/utils/notification.ts
index d39513e905..a2f91a8560 100644
--- a/js/app/packages/entity/src/utils/notification.ts
+++ b/js/app/packages/entity/src/utils/notification.ts
@@ -60,6 +60,7 @@ export function getNotificationActionText(n: Notification): string {
.with('new_email', () => 'emailed')
.with('invite_to_team', () => 'invited')
.with('task_assigned', () => 'assigned')
+ .with('ai_response', () => 'responded')
.exhaustive();
}
@@ -81,6 +82,7 @@ export function extractMessageContent(notification: Notification): string {
.with({ tag: 'mentioned_in_document_comment' }, (m) => m.content.text || '')
.with({ tag: 'new_email' }, (m) => m.content.subject || '')
.with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? '')
+ .with({ tag: 'ai_response' }, (m) => m.content.summary || '')
.with({ tag: 'channel_invite' }, () => '')
.with({ tag: 'invite_to_team' }, () => '')
.exhaustive();
diff --git a/js/app/packages/notifications/notification-metadata.ts b/js/app/packages/notifications/notification-metadata.ts
index 5c20101124..dc7aa11223 100644
--- a/js/app/packages/notifications/notification-metadata.ts
+++ b/js/app/packages/notifications/notification-metadata.ts
@@ -9,6 +9,7 @@ export function getNotificationAction(n: UnifiedNotification): string {
.with('document_mention', () => 'sent a document')
.with('mentioned_in_document_comment', () => 'mentioned you in')
.with('channel_message_send', () => 'sent a message in')
+ .with('ai_response', () => 'AI responded')
.with('channel_message_reply', () => 'replied in')
.with('channel_invite', () => 'invited you to')
.with('new_email', () => 'sent a new email')
@@ -32,6 +33,7 @@ export function getNotificationTargetName(
.with({ tag: 'task_assigned' }, (m) => m.content.taskName ?? undefined)
.with({ tag: 'channel_mention' }, () => undefined)
.with({ tag: 'channel_message_send' }, () => undefined)
+ .with({ tag: 'ai_response' }, () => undefined)
.with({ tag: 'channel_message_reply' }, () => undefined)
.with({ tag: 'new_email' }, () => undefined)
.exhaustive();
@@ -44,6 +46,7 @@ export function getNotificationContent(
return match(m)
.with({ tag: 'channel_mention' }, (m) => m.content.messageContent)
.with({ tag: 'channel_message_send' }, (m) => m.content.messageContent)
+ .with({ tag: 'ai_response' }, (m) => m.content.summary)
.with({ tag: 'channel_message_reply' }, (m) => m.content.messageContent)
.with({ tag: 'document_mention' }, (m) => m.content.documentName)
.with({ tag: 'mentioned_in_document_comment' }, (m) => m.content.text)
@@ -69,6 +72,7 @@ export function shouldShowNotificationTarget(n: UnifiedNotification): boolean {
{ tag: 'channel_message_reply' },
(m) => m.content.channelType !== 'directMessage'
)
+ .with({ tag: 'ai_response' }, () => false)
.with({ tag: 'new_email' }, () => false)
.with({ tag: 'task_assigned' }, () => true)
.with({ tag: 'document_mention' }, () => true)
diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.ts
index eb6626e933..06ddce9206 100644
--- a/js/app/packages/notifications/notification-navigation.ts
+++ b/js/app/packages/notifications/notification-navigation.ts
@@ -101,6 +101,12 @@ function getSupportedHandler(
(lm: SplitManager, newSplit: boolean = false) =>
openChannelNotification(notification, lm, newSplit)
)
+ .with(
+ 'ai_response',
+ () =>
+ async (lm: SplitManager, newSplit: boolean = false) =>
+ openSplitIfNotOpen(lm, 'chat', notification.entity_id, newSplit)
+ )
.with('new_email', () => {
const meta = notification.notification_metadata;
if (meta.tag !== 'new_email') return null;
diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.ts
index 869a11205a..f488d16a3f 100644
--- a/js/app/packages/notifications/notification-preview.ts
+++ b/js/app/packages/notifications/notification-preview.ts
@@ -10,4 +10,5 @@ export const NOTIFICATION_LABEL_BY_TYPE: Record<NotificationType, string> = {
new_email: 'EMAIL',
invite_to_team: 'INVITE',
task_assigned: 'ASSIGNED',
+ ai_response: 'AI',
} as const;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/aiResponseMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/aiResponseMetadata.ts
new file mode 100644
index 0000000000..a0162ccdb8
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/aiResponseMetadata.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export interface AiResponseMetadata {
+ messageId: string;
+ summary: string;
+}
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
index e6a6ac2275..28c3bf20ed 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
+export * from './aiResponseMetadata';
export * from './apiUserNotification';
export * from './apiUserNotificationAllOf';
export * from './apiUserNotificationAllOfCreatedAt';
@@ -57,6 +58,8 @@ export * from './notifEventOneOfNine';
export * from './notifEventOneOfNineTag';
export * from './notifEventOneOfOnefive';
export * from './notifEventOneOfOnefiveTag';
+export * from './notifEventOneOfOnenine';
+export * from './notifEventOneOfOnenineTag';
export * from './notifEventOneOfOneone';
export * from './notifEventOneOfOneoneTag';
export * from './notifEventOneOfOneseven';
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts
index 6d99e56d06..9cab5ffd8c 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEvent.ts
@@ -8,6 +8,7 @@ import type { NotifEventOneOf } from './notifEventOneOf';
import type { NotifEventOneOfFive } from './notifEventOneOfFive';
import type { NotifEventOneOfNine } from './notifEventOneOfNine';
import type { NotifEventOneOfOnefive } from './notifEventOneOfOnefive';
+import type { NotifEventOneOfOnenine } from './notifEventOneOfOnenine';
import type { NotifEventOneOfOneone } from './notifEventOneOfOneone';
import type { NotifEventOneOfOneseven } from './notifEventOneOfOneseven';
import type { NotifEventOneOfOnethree } from './notifEventOneOfOnethree';
@@ -31,4 +32,5 @@ export type NotifEvent =
| NotifEventOneOfOneone
| NotifEventOneOfOnethree
| NotifEventOneOfOnefive
- | NotifEventOneOfOneseven;
+ | NotifEventOneOfOneseven
+ | NotifEventOneOfOnenine;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenine.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenine.ts
new file mode 100644
index 0000000000..fda6faf71e
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenine.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AiResponseMetadata } from './aiResponseMetadata';
+import type { NotifEventOneOfOnenineTag } from './notifEventOneOfOnenineTag';
+
+/**
+ * An AI assistant responded to a chat.
+ */
+export type NotifEventOneOfOnenine = {
+ /** An AI assistant responded to a chat. */
+ content: AiResponseMetadata;
+ tag: NotifEventOneOfOnenineTag;
+};
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenineTag.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenineTag.ts
new file mode 100644
index 0000000000..dfad5c8e07
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notifEventOneOfOnenineTag.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type NotifEventOneOfOnenineTag =
+ (typeof NotifEventOneOfOnenineTag)[keyof typeof NotifEventOneOfOnenineTag];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const NotifEventOneOfOnenineTag = {
+ ai_response: 'ai_response',
+} as const;
diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.json
index 7030437da2..27cb72642e 100644
--- a/js/app/packages/service-clients/service-notification/openapi.json
+++ b/js/app/packages/service-clients/service-notification/openapi.json
@@ -951,6 +951,18 @@
},
"components": {
"schemas": {
+ "AiResponseMetadata": {
+ "type": "object",
+ "required": ["summary", "messageId"],
+ "properties": {
+ "messageId": {
+ "type": "string"
+ },
+ "summary": {
+ "type": "string"
+ }
+ }
+ },
"ApiUserNotification": {
"allOf": [
{
@@ -1531,6 +1543,21 @@
"enum": ["task_assigned"]
}
}
+ },
+ {
+ "type": "object",
+ "description": "An AI assistant responded to a chat.",
+ "required": ["content", "tag"],
+ "properties": {
+ "content": {
+ "$ref": "#/components/schemas/AiResponseMetadata",
+ "description": "An AI assistant responded to a chat."
+ },
+ "tag": {
+ "type": "string",
+ "enum": ["ai_response"]
+ }
+ }
}
],
"description": "Mirrors [`model_notifications::NotificationEvent`] but uses `tag` / `content`\nas the serde adjacently-tagged field names so it can be deserialized from the\nshape produced by [`UserNotificationRow::into_tagged`] +\n[`UserNotificationRow::into_json`].\n\nOnly includes variants whose metadata types implement the `Notification` trait."
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 83030798ef..0faaf08071 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2689,6 +2689,7 @@ dependencies = [
"async-openai",
"async-stream",
"async-trait",
+ "aws-sdk-dynamodb",
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
"axum",
@@ -2707,6 +2708,7 @@ dependencies = [
"frecency",
"futures",
"http-body-util",
+ "last_online_tracker",
"lazy_static",
"lexical_client",
"log",
@@ -2725,9 +2727,11 @@ dependencies = [
"macro_uuid",
"model",
"model-entity",
+ "model_notifications",
"models_dcs",
"models_opensearch",
"models_permissions",
+ "notification",
"redis",
"regex",
"reqwest",
diff --git a/rust/cloud-storage/ai/src/chat_completion.rs b/rust/cloud-storage/ai/src/chat_completion.rs
index 3b5a14a46d..9afc26657a 100644
--- a/rust/cloud-storage/ai/src/chat_completion.rs
+++ b/rust/cloud-storage/ai/src/chat_completion.rs
@@ -1,36 +1,7 @@
-/* Non-streaming chat completion */
-use crate::types::OpenRouterClient;
-use crate::types::{ChatCompletionError, ChatCompletionRequest};
-use anyhow::Result;
+/* Non-streaming chat completion via Anthropic */
+use crate::types::{AnthropicClient, ChatCompletionError, ChatCompletionRequest, ExtendedClient};
use async_openai::types::CreateChatCompletionRequest;
-use async_openai::{Client, config::Config};
-use tracing::instrument;
-
-#[instrument(skip_all, err)]
-pub(crate) async fn get_openai_chat_completion<
- C: Config,
- T: std::ops::Deref<Target = Client<C>>,
->(
- client: T,
- request: CreateChatCompletionRequest,
-) -> Result<String, ChatCompletionError> {
- let response = client.chat().create(request).await?;
-
- let message = response
- .choices
- .into_iter()
- .next()
- .ok_or(ChatCompletionError::NoContent)?
- .message;
-
- if let Some(refusal) = message.refusal {
- Err(ChatCompletionError::Refusal(refusal))
- } else if let Some(content) = message.content {
- return Ok(content);
- } else {
- return Err(ChatCompletionError::NoContent);
- }
-}
+use futures::StreamExt;
#[tracing::instrument(skip(request), fields(model=?request.model, message_count=?request.messages.len()))]
pub async fn get_chat_completion(
@@ -38,19 +9,45 @@ pub async fn get_chat_completion(
) -> Result<String, ChatCompletionError> {
let openai_request: CreateChatCompletionRequest = request
.try_into()
- // TODO this causes a request error before the request is actually made. RequestError says
- // "/// The request was rejected by the provider" so this seems wrong.
.map_err(ChatCompletionError::RequestError)?;
- let client = OpenRouterClient::new();
- get_openai_chat_completion(client, openai_request).await
+ collect_anthropic_stream(openai_request).await
}
pub async fn get_chat_completion_openai_request(
request: CreateChatCompletionRequest,
) -> Result<String, ChatCompletionError> {
- // Streaming OpenAI models directly via OpenAI
- let client = OpenRouterClient::new();
- let request = client.preprocess_request(request);
- get_openai_chat_completion(client, request).await
+ collect_anthropic_stream(request).await
+}
+
+async fn collect_anthropic_stream(
+ request: CreateChatCompletionRequest,
+) -> Result<String, ChatCompletionError> {
+ let client = AnthropicClient::default();
+ let mut stream = client
+ .chat_stream(request)
+ .await
+ .map_err(|e| ChatCompletionError::RequestError(e.into()))?;
+
+ let mut content = String::new();
+
+ while let Some(item) = stream.next().await {
+ let item = item?;
+ if let crate::types::ExtendedOpenAIStreamItem::Response(response) = item {
+ for choice in response.choices {
+ if let Some(text) = choice.delta.content {
+ content.push_str(&text);
+ }
+ if let Some(refusal) = choice.delta.refusal {
+ return Err(ChatCompletionError::Refusal(refusal));
+ }
+ }
+ }
+ }
+
+ if content.is_empty() {
+ return Err(ChatCompletionError::NoContent);
+ }
+
+ Ok(content)
}
diff --git a/rust/cloud-storage/ai/src/types/message/message_builder.rs b/rust/cloud-storage/ai/src/types/message/message_builder.rs
index 657eb087a4..ff1eabbff9 100644
--- a/rust/cloud-storage/ai/src/types/message/message_builder.rs
+++ b/rust/cloud-storage/ai/src/types/message/message_builder.rs
@@ -88,6 +88,14 @@ impl<R> MessageBuilder<R, NoContent> {
role: self.role,
}
}
+
+ pub fn text<T: Into<String>>(self, content: T) -> MessageBuilder<R, ChatMessageContent> {
+ MessageBuilder {
+ content: ChatMessageContent::Text(content.into()),
+ image_urls: self.image_urls,
+ role: self.role,
+ }
+ }
}
impl<R, C> MessageBuilder<R, C> {
diff --git a/rust/cloud-storage/connection_gateway/src/service/connection.rs b/rust/cloud-storage/connection_gateway/src/service/connection.rs
index 1e54166733..57df7cb88d 100644
--- a/rust/cloud-storage/connection_gateway/src/service/connection.rs
+++ b/rust/cloud-storage/connection_gateway/src/service/connection.rs
@@ -14,7 +14,7 @@ use std::{
use tokio::{sync::mpsc::Sender, task::AbortHandle};
#[async_trait]
-pub trait ConnectionGatewayPersistence: Send + Sync {
+pub trait ConnectionRepo: Send + Sync {
/// Inserts a new [StoredConnectionEntity] into storage
async fn insert_connection_entry(
&self,
@@ -73,11 +73,11 @@ pub trait ConnectionGatewayPersistence: Send + Sync {
pub struct ConnectionManager {
pub connections: Arc<DashMap<String, Connection>>,
pub connection_count: Arc<AtomicUsize>,
- pub persistence: Arc<dyn ConnectionGatewayPersistence>,
+ pub persistence: Arc<dyn ConnectionRepo>,
}
impl ConnectionManager {
- pub fn new(persistence: impl ConnectionGatewayPersistence + 'static) -> Self {
+ pub fn new(persistence: impl ConnectionRepo + 'static) -> Self {
tracing::info!("creating new connection manager");
Self {
connections: Arc::new(DashMap::new()),
diff --git a/rust/cloud-storage/connection_gateway/src/service/dynamodb.rs b/rust/cloud-storage/connection_gateway/src/service/dynamodb.rs
index 340c1fd19e..668845a70b 100644
--- a/rust/cloud-storage/connection_gateway/src/service/dynamodb.rs
+++ b/rust/cloud-storage/connection_gateway/src/service/dynamodb.rs
@@ -1,6 +1,6 @@
use crate::model::connection::StoredConnectionEntity;
use crate::model::tracking::{EntityConnection, UserEntityConnection};
-use crate::service::connection::{ConnectionGatewayPersistence, ConnectionManager};
+use crate::service::connection::{ConnectionManager, ConnectionRepo};
use anyhow::{Context, Result};
use aws_sdk_dynamodb::error::ProvideErrorMetadata;
use aws_sdk_dynamodb::types::{AttributeValue, ReturnValue};
@@ -93,7 +93,7 @@ struct DynamoDbConnectionGatewayPersistence {
const CONNECTION_ID_GSI: &str = "ConnectionPkIndex";
#[async_trait]
-impl ConnectionGatewayPersistence for DynamoDbConnectionGatewayPersistence {
+impl ConnectionRepo for DynamoDbConnectionGatewayPersistence {
async fn insert_connection_entry(
&self,
connection: UserEntityConnection<'_>,
diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.toml
index 663753a750..a7a9a56314 100644
--- a/rust/cloud-storage/document_cognition_service/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml
@@ -38,6 +38,7 @@ anyhow = { workspace = true }
async-openai = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
macro_aws_config = { path = "../macro_aws_config" }
+aws-sdk-dynamodb = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true, features = ["tower-log", "ws"] }
base64 = { workspace = true }
@@ -55,6 +56,7 @@ email_service_client = { path = "../email_service_client" }
frecency = { path = "../frecency", features = ["outbound", "postgres"] }
futures = { workspace = true }
http-body-util = { workspace = true }
+last_online_tracker = { path = "../last_online_tracker" }
lazy_static = { workspace = true }
lexical_client = { path = "../lexical_client" }
log = { workspace = true }
@@ -65,6 +67,7 @@ macro_db_client = { path = "../macro_db_client" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
macro_env_var = { path = "../macro_env_var" }
+notification = { path = "../notification" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
"cloud_storage",
@@ -75,6 +78,7 @@ macro_share_permissions = { path = "../macro_share_permissions" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
+model_notifications = { path = "../model_notifications" }
models_dcs = { path = "../models_dcs" }
models_opensearch = { path = "../models_opensearch" }
models_permissions = { path = "../models_permissions" }
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context.rs b/rust/cloud-storage/document_cognition_service/src/api/context.rs
deleted file mode 100644
index e0bd4350f0..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/api/context.rs
+++ /dev/null
@@ -1,189 +0,0 @@
-use crate::config::Config;
-use ai_tools::ToolSoupService;
-use axum::extract::FromRef;
-use document_storage_service_client::DocumentStorageServiceClient;
-use macro_auth::middleware::decode_jwt::JwtValidationArgs;
-use macro_middleware::auth::internal_access::InternalApiSecretKey;
-use scribe::{
- ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,
- email::EmailClient, static_file::StaticFileClient,
-};
-use search_service_client::SearchServiceClient;
-use secretsmanager_client::LocalOrRemoteSecret;
-use sqlx::PgPool;
-use std::sync::{Arc, OnceLock};
-use stream::domain::StreamRepo;
-
-pub type DcsScribe =
- ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;
-
-#[derive(Clone, FromRef)]
-pub struct ApiContext {
- pub db: PgPool,
- pub sqs_client: Arc<sqs_client::SQS>,
- pub document_storage_client: Arc<DocumentStorageServiceClient>,
- pub comms_service_client: Arc<comms_service_client::CommsServiceClient>,
- pub search_service_client: Arc<SearchServiceClient>,
- pub scribe: Arc<DcsScribe>,
- pub email_service_client_external: Arc<email_service_client::EmailServiceClientExternal>,
- pub jwt_args: JwtValidationArgs,
- pub config: Arc<Config>,
- pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,
- pub soup_service: Arc<ToolSoupService>,
- pub stream_repo: Arc<dyn StreamRepo>,
-}
-
-pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();
-
-#[cfg(test)]
-mod mock_stream {
- use std::sync::Arc;
- use stream::domain::{ItemId, ItemStream, Result, StreamEvent, StreamId, StreamRepo};
- use tokio::sync::broadcast::{self, Receiver};
-
- /// Mock StreamRepo for testing - does nothing but satisfies the interface
- pub struct MockStreamRepo {
- tx: broadcast::Sender<StreamEvent>,
- }
-
- impl MockStreamRepo {
- pub fn new() -> Arc<dyn StreamRepo> {
- let (tx, _) = broadcast::channel(16);
- Arc::new(Self { tx })
- }
- }
-
- #[async_trait::async_trait]
- impl StreamRepo for MockStreamRepo {
- async fn append(&self, _id: &StreamId, _payload: serde_json::Value) -> Result<ItemId> {
- Ok("mock-item-id".to_string())
- }
-
- async fn stream_from_beginning(&self, _id: &StreamId) -> Result<ItemStream> {
- Ok(Box::pin(futures::stream::empty()))
- }
-
- async fn close(&self, _id: &StreamId) -> Result<()> {
- Ok(())
- }
-
- async fn active_streams(&self, _entity_id: &str) -> Result<Vec<StreamId>> {
- Ok(vec![])
- }
-
- async fn notify(&self) -> Receiver<StreamEvent> {
- self.tx.subscribe()
- }
- }
-}
-
-#[cfg(test)]
-pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arc<ApiContext> {
- use aws_sdk_sqs;
- use comms::domain::service::ChannelServiceImpl;
- use comms::outbound::http::user_repo::UserRepoImpl;
- use comms::outbound::postgres::comms_repo::PgCommsRepo;
- use comms_service_client::CommsServiceClient;
- use document_cognition_service_client::DocumentCognitionServiceClient;
- use document_storage_service_client::DocumentStorageServiceClient;
- use email::domain::service::EmailServiceImpl;
- use email::outbound::EmailPgRepo;
- use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
- use frecency::domain::services::FrecencyQueryServiceImpl;
- use frecency::outbound::postgres::FrecencyPgStorage;
- use lexical_client::LexicalClient;
- use scribe::ScribeClient;
- use search_service_client::SearchServiceClient;
- use soup::domain::service::SoupImpl;
- use soup::outbound::pg_soup_repo::PgSoupRepo;
- use sqs_client::SQS;
- use static_file_service_client::StaticFileServiceClient;
- use std::sync::Arc;
- use sync_service_client::SyncServiceClient;
-
- let sqs_config = aws_sdk_sqs::Config::builder()
- .behavior_version(aws_sdk_sqs::config::BehaviorVersion::latest())
- .build();
- let aws_sqs_client = aws_sdk_sqs::Client::from_conf(sqs_config);
- let sqs_client = SQS::new(aws_sqs_client);
-
- let document_storage_client = Arc::new(DocumentStorageServiceClient::new(
- "dummy_auth_key".into(),
- "http://localhost".into(),
- ));
- let comms_service_client = Arc::new(CommsServiceClient::new("http://localhost".into()));
- let search_service_client =
- SearchServiceClient::new("dummy_auth_key".into(), "http://localhost".into());
- let lexical_client = Arc::new(LexicalClient::new(
- "test".into(),
- "http://nofileshere".into(),
- ));
- let sync_service_client = Arc::new(SyncServiceClient::new(
- "dummy_auth_key".into(),
- "http://localhost".into(),
- ));
- let email_service_client = Arc::new(EmailServiceClient::new(
- "dummy_auth_key".into(),
- "http://localhost".into(),
- ));
- let document_cognition_service_client = Arc::new(DocumentCognitionServiceClient::new(
- "dummy_auth_key".into(),
- "http://localhost".into(),
- ));
- let static_file_service_client = Arc::new(StaticFileServiceClient::new(
- "dummy_auth_key".into(),
- "http://localhost".into(),
- ));
-
- let email_service_client_external = Arc::new(EmailServiceClientExternal::new(
- email_service_client.url().to_owned(),
- ));
-
- let content_client = ScribeClient::new()
- .with_document_client(
- DocumentClient::builder()
- .with_dss_client(document_storage_client.clone())
- .with_lexical_client(lexical_client)
- .with_sync_service_client(sync_service_client)
- .with_macro_db(pool.clone())
- .build(),
- )
- .with_channel_client_and_db(comms_service_client.clone(), pool.clone())
- .with_dcs_client(document_cognition_service_client)
- .with_email_client(email_service_client)
- .with_static_file_client(static_file_service_client.clone());
-
- // Build soup service dependencies
- let frecency_storage = FrecencyPgStorage::new(pool.clone());
- let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
- let email_service =
- EmailServiceImpl::new(EmailPgRepo::new(pool.clone()), frecency_service.clone());
- let user_repo = UserRepoImpl::new("dummy_auth_key".into(), "http://localhost".parse().unwrap());
- let channels_service = ChannelServiceImpl::new(
- PgCommsRepo { pool: pool.clone() },
- user_repo,
- frecency_storage,
- );
- let soup_service = Arc::new(SoupImpl::new(
- PgSoupRepo::new(pool.clone()),
- frecency_service,
- email_service,
- channels_service,
- ));
-
- let api_context = ApiContext {
- db: pool.clone(),
- sqs_client: Arc::new(sqs_client),
- document_storage_client,
- comms_service_client,
- search_service_client: Arc::new(search_service_client),
- scribe: Arc::new(content_client),
- email_service_client_external,
- jwt_args: JwtValidationArgs::new_testing(),
- config: Arc::new(Config::new_empty_for_test()),
- internal_auth_key: LocalOrRemoteSecret::Local(InternalApiSecretKey::Comptime("testing")),
- soup_service,
- stream_repo: mock_stream::MockStreamRepo::new(),
- };
- Arc::new(api_context)
-}
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.rs
new file mode 100644
index 0000000000..9ab2ea65b3
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs
@@ -0,0 +1,66 @@
+use crate::config::Config;
+use ai_tools::ToolSoupService;
+use axum::extract::FromRef;
+use connection_gateway_client::service::connection::ConnectionRepo;
+use document_storage_service_client::DocumentStorageServiceClient;
+use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use notification::domain::models::email_notification_digest::StateMachineDriverA;
+use notification::domain::service::NotificationIngressService;
+use notification::outbound::{
+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
+};
+use scribe::{
+ ScribeClient, channel::ChannelClient, dcs::DcsClient, document::DocumentClient,
+ email::EmailClient, static_file::StaticFileClient,
+};
+use search_service_client::SearchServiceClient;
+use secretsmanager_client::LocalOrRemoteSecret;
+use sqlx::PgPool;
+use std::sync::{Arc, OnceLock};
+use stream::domain::StreamRepo;
+
+#[cfg(test)]
+mod test;
+#[cfg(test)]
+pub use test::*;
+
+pub type DcsScribe =
+ ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;
+
+type StateMachine = StateMachineDriverA<
+ DbUserExistenceChecker,
+ PushNotificationCheckerImpl<DbNotificationRepository<PgPool>>,
+ LastOnlineCheckerImpl<
+ last_online_tracker::outbound::time::DefaultTime,
+ last_online_tracker::outbound::redis::RedisLastOnlineRepo,
+ >,
+ RedisDigestBatcher,
+>;
+pub(crate) type NotificationIngressType = NotificationIngressService<
+ DbNotificationRepository<PgPool>,
+ SqsNotificationQueue,
+ StateMachine,
+>;
+
+#[derive(Clone, FromRef)]
+pub struct ApiContext {
+ pub db: PgPool,
+ pub sqs_client: Arc<sqs_client::SQS>,
+ pub document_storage_client: Arc<DocumentStorageServiceClient>,
+ pub comms_service_client: Arc<comms_service_client::CommsServiceClient>,
+ pub search_service_client: Arc<SearchServiceClient>,
+ pub scribe: Arc<DcsScribe>,
+ pub email_service_client_external: Arc<email_service_client::EmailServiceClientExternal>,
+ pub jwt_args: JwtValidationArgs,
+ pub config: Arc<Config>,
+ pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,
+ pub notification_ingress_service: Arc<NotificationIngressType>,
+ pub connection_repo: Arc<dyn ConnectionRepo>,
+ pub soup_service: Arc<ToolSoupService>,
+ pub stream_repo: Arc<dyn StreamRepo>,
+}
+
+pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();
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.rs
new file mode 100644
index 0000000000..6bcfdc9c9f
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -0,0 +1,263 @@
+use super::*;
+use connection_gateway_client::model::connection::StoredConnectionEntity;
+use connection_gateway_client::model::tracking::{EntityConnection, UserEntityConnection};
+use connection_gateway_client::service::connection::ConnectionRepo;
+use std::sync::Arc;
+use stream::domain::{
+ ItemId, ItemStream, Result as StreamResult, StreamEvent, StreamId, StreamRepo,
+};
+use tokio::sync::broadcast::{self, Receiver};
+
+pub struct MockConnectionRepo;
+
+impl MockConnectionRepo {
+ pub fn new() -> Arc<dyn ConnectionRepo> {
+ Arc::new(Self)
+ }
+}
+
+#[async_trait::async_trait]
+impl ConnectionRepo for MockConnectionRepo {
+ async fn insert_connection_entry(
+ &self,
+ _connection: UserEntityConnection<'_>,
+ ) -> anyhow::Result<StoredConnectionEntity> {
+ unimplemented!()
+ }
+ async fn get_entries_by_entity(
+ &self,
+ _entity: &model_entity::Entity<'_>,
+ ) -> anyhow::Result<Vec<StoredConnectionEntity>> {
+ Ok(vec![])
+ }
+ async fn get_entries_by_connection_id(
+ &self,
+ _connection_id: &str,
+ ) -> anyhow::Result<Vec<StoredConnectionEntity>> {
+ Ok(vec![])
+ }
+ async fn get_connection(&self, _connection_id: &str) -> anyhow::Result<StoredConnectionEntity> {
+ unimplemented!()
+ }
+ async fn get_entry_for_connection_entity(
+ &self,
+ _entity: EntityConnection<'_>,
+ ) -> anyhow::Result<Option<StoredConnectionEntity>> {
+ Ok(None)
+ }
+ async fn remove_all_entries_for_by_connection_id(
+ &self,
+ _connection_id: &str,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+ async fn remove_entity(&self, _entity: &EntityConnection<'_>) -> anyhow::Result<()> {
+ Ok(())
+ }
+ async fn update_last_entity_ping(
+ &self,
+ _entity: &EntityConnection<'_>,
+ _timestamp: u64,
+ ) -> anyhow::Result<StoredConnectionEntity> {
+ unimplemented!()
+ }
+ async fn update_user_connection_last_ping(
+ &self,
+ _connection_id: &str,
+ _user: &str,
+ _timestamp: u64,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+/// Mock StreamRepo for testing - does nothing but satisfies the interface
+pub struct MockStreamRepo {
+ tx: broadcast::Sender<StreamEvent>,
+}
+
+impl MockStreamRepo {
+ pub fn new() -> Arc<dyn StreamRepo> {
+ let (tx, _) = broadcast::channel(16);
+ Arc::new(Self { tx })
+ }
+}
+
+#[async_trait::async_trait]
+impl StreamRepo for MockStreamRepo {
+ async fn append(&self, _id: &StreamId, _payload: serde_json::Value) -> StreamResult<ItemId> {
+ Ok("mock-item-id".to_string())
+ }
+
+ async fn stream_from_beginning(&self, _id: &StreamId) -> StreamResult<ItemStream> {
+ Ok(Box::pin(futures::stream::empty()))
+ }
+
+ async fn close(&self, _id: &StreamId) -> StreamResult<()> {
+ Ok(())
+ }
+
+ async fn active_streams(&self, _entity_id: &str) -> StreamResult<Vec<StreamId>> {
+ Ok(vec![])
+ }
+
+ async fn notify(&self) -> Receiver<StreamEvent> {
+ self.tx.subscribe()
+ }
+}
+
+pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arc<ApiContext> {
+ use aws_sdk_sqs;
+ use comms::domain::service::ChannelServiceImpl;
+ use comms::outbound::http::user_repo::UserRepoImpl;
+ use comms::outbound::postgres::comms_repo::PgCommsRepo;
+ use comms_service_client::CommsServiceClient;
+ use document_cognition_service_client::DocumentCognitionServiceClient;
+ use document_storage_service_client::DocumentStorageServiceClient;
+ use email::domain::service::EmailServiceImpl;
+ use email::outbound::EmailPgRepo;
+ use email_service_client::{EmailServiceClient, EmailServiceClientExternal};
+ use frecency::domain::services::FrecencyQueryServiceImpl;
+ use frecency::outbound::postgres::FrecencyPgStorage;
+ use lexical_client::LexicalClient;
+ use notification::domain::models::email_notification_digest::{
+ EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder, StateMachineDriverA,
+ };
+ use notification::domain::service::NotificationIngressService;
+ use notification::outbound::{
+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
+ };
+ use scribe::ScribeClient;
+ use search_service_client::SearchServiceClient;
+ use soup::domain::service::SoupImpl;
+ use soup::outbound::pg_soup_repo::PgSoupRepo;
+ use sqs_client::SQS;
+ use static_file_service_client::StaticFileServiceClient;
+ use sync_service_client::SyncServiceClient;
+
+ let sqs_config = aws_sdk_sqs::Config::builder()
+ .behavior_version(aws_sdk_sqs::config::BehaviorVersion::latest())
+ .build();
+ let aws_sqs_client = aws_sdk_sqs::Client::from_conf(sqs_config.clone());
+ let sqs_client = SQS::new(aws_sqs_client);
+
+ let document_storage_client = Arc::new(DocumentStorageServiceClient::new(
+ "dummy_auth_key".into(),
+ "http://localhost".into(),
+ ));
+ let comms_service_client = Arc::new(CommsServiceClient::new("http://localhost".into()));
+ let search_service_client =
+ SearchServiceClient::new("dummy_auth_key".into(), "http://localhost".into());
+ let lexical_client = Arc::new(LexicalClient::new(
+ "test".into(),
+ "http://nofileshere".into(),
+ ));
+ let sync_service_client = Arc::new(SyncServiceClient::new(
+ "dummy_auth_key".into(),
+ "http://localhost".into(),
+ ));
+ let email_service_client = Arc::new(EmailServiceClient::new(
+ "dummy_auth_key".into(),
+ "http://localhost".into(),
+ ));
+ let document_cognition_service_client = Arc::new(DocumentCognitionServiceClient::new(
+ "dummy_auth_key".into(),
+ "http://localhost".into(),
+ ));
+ let static_file_service_client = Arc::new(StaticFileServiceClient::new(
+ "dummy_auth_key".into(),
+ "http://localhost".into(),
+ ));
+
+ let email_service_client_external = Arc::new(EmailServiceClientExternal::new(
+ email_service_client.url().to_owned(),
+ ));
+
+ let content_client = ScribeClient::new()
+ .with_document_client(
+ DocumentClient::builder()
+ .with_dss_client(document_storage_client.clone())
+ .with_lexical_client(lexical_client)
+ .with_sync_service_client(sync_service_client)
+ .with_macro_db(pool.clone())
+ .build(),
+ )
+ .with_channel_client_and_db(comms_service_client.clone(), pool.clone())
+ .with_dcs_client(document_cognition_service_client)
+ .with_email_client(email_service_client)
+ .with_static_file_client(static_file_service_client.clone());
+
+ // Build soup service dependencies
+ let frecency_storage = FrecencyPgStorage::new(pool.clone());
+ let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage.clone());
+ let email_service =
+ EmailServiceImpl::new(EmailPgRepo::new(pool.clone()), frecency_service.clone());
+ let user_repo = UserRepoImpl::new("dummy_auth_key".into(), "http://localhost".parse().unwrap());
+ let channels_service = ChannelServiceImpl::new(
+ PgCommsRepo { pool: pool.clone() },
+ user_repo,
+ frecency_storage,
+ );
+ let soup_service = Arc::new(SoupImpl::new(
+ PgSoupRepo::new(pool.clone()),
+ frecency_service,
+ email_service,
+ channels_service,
+ ));
+
+ let redis_client = redis::Client::open("redis://localhost:6379").unwrap();
+ let redis_multiplexed_conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .unwrap();
+
+ let notification_ingress_service = Arc::new({
+ let notification_repository = DbNotificationRepository::new(pool.clone());
+ let notification_queue = SqsNotificationQueue::new(
+ aws_sdk_sqs::Client::from_conf(sqs_config),
+ "test-notification-queue".to_string(),
+ );
+ let state_machine = StateMachineDriverA {
+ user_checker: DbUserExistenceChecker::new(pool.clone()),
+ notification_checker: PushNotificationCheckerImpl::new(DbNotificationRepository::new(
+ pool.clone(),
+ )),
+ online_checker: LastOnlineCheckerImpl::new(
+ last_online_tracker::domain::services::LastOnlineService::new(
+ last_online_tracker::outbound::time::DefaultTime,
+ last_online_tracker::outbound::redis::RedisLastOnlineRepo::new(
+ redis_multiplexed_conn.clone(),
+ ),
+ ),
+ ),
+ digest_batcher: RedisDigestBatcher::new(redis_multiplexed_conn),
+ block_list: EmailBlockList::new::<model_notifications::NewEmailMetadata>(),
+ invite_list: ExplicitInviteAllowList::new::<model_notifications::InviteToTeamMetadata>(
+ )
+ .append::<model_notifications::ChannelInviteMetadata>(),
+ digest_window: std::time::Duration::from_secs(30 * 60),
+ online_duration_threshold: std::time::Duration::from_secs(60 * 60),
+ };
+ NotificationIngressService::new(notification_repository, notification_queue, state_machine)
+ });
+
+ let api_context = ApiContext {
+ db: pool.clone(),
+ sqs_client: Arc::new(sqs_client),
+ document_storage_client,
+ comms_service_client,
+ search_service_client: Arc::new(search_service_client),
+ scribe: Arc::new(content_client),
+ email_service_client_external,
+ jwt_args: JwtValidationArgs::new_testing(),
+ config: Arc::new(Config::new_empty_for_test()),
+ internal_auth_key: LocalOrRemoteSecret::Local(InternalApiSecretKey::Comptime("testing")),
+ notification_ingress_service,
+ connection_repo: MockConnectionRepo::new(),
+ soup_service,
+ stream_repo: MockStreamRepo::new(),
+ };
+ Arc::new(api_context)
+}
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.rs
index d0badf0255..36f944d2f8 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
@@ -10,6 +10,7 @@ use crate::core::model::FALLBACK_MODEL;
use crate::model::stream::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};
use crate::service::ai::name::maybe_rename_chat;
use crate::service::get_chat::get_chat;
+use crate::service::notification::notify;
use ai::tool::ToolLoop;
use ai::tool::types::StreamPart;
use ai::types::{AssistantMessagePart, Model};
@@ -488,19 +489,38 @@ fn stream_and_save_message(
// Save conversation messages
let new_messages = chat.get_new_conversation_messages();
+
+ // Extract assistant response text before moving new_messages into store
+ let assistant_text = new_messages
+ .iter()
+ .find(|m| m.role == ai::types::Role::Assistant)
+ .and_then(|m| m.content.assistant_message_text());
+
if let Err(err) = store_conversation_messages(
ctx.clone(),
user_id.0.as_ref(),
&chat_id,
new_messages,
model,
- Some(message_id),
+ Some(message_id.clone()),
)
.await
{
tracing::error!(error=?err, "failed to store conversation messages");
}
+ // Summarize and send notification in a background task
+ if let Some(text) = assistant_text {
+ notify(
+ ctx.connection_repo.clone(),
+ ctx.notification_ingress_service.clone(),
+ chat_id.clone(),
+ message_id.clone(),
+ text,
+ user_id.as_ref().clone(),
+ );
+ }
+
// Maybe rename chat if first message
if is_first_message
&& let Ok(new_name) =
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index fe2f4732de..abafa6afeb 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -15,6 +15,15 @@ use frecency::outbound::postgres::FrecencyPgStorage;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
+use notification::domain::models::email_notification_digest::{
+ EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder, StateMachineDriverA,
+};
+use notification::domain::service::NotificationIngressService;
+use notification::outbound::{
+ digest_batcher::RedisDigestBatcher, last_online_checker::LastOnlineCheckerImpl,
+ push_notification_checker::PushNotificationCheckerImpl, queue::SqsNotificationQueue,
+ repository::DbNotificationRepository, user_existence_checker::DbUserExistenceChecker,
+};
use scribe::{ScribeClient, document::DocumentClient};
use search_service_client::SearchServiceClient;
use secretsmanager_client::SecretManager;
@@ -63,6 +72,7 @@ async fn main() -> anyhow::Result<()> {
);
let aws_config = macro_aws_config::get_macro_aws_config().await;
+ let dynamodb_client = aws_sdk_dynamodb::Client::new(&aws_config);
let queue_aws_client = aws_sdk_sqs::Client::new(&aws_config);
let sqs_client = sqs_client::SQS::new(queue_aws_client)
@@ -191,6 +201,52 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized stream repo");
+ let connection_manager =
+ connection_gateway_client::service::dynamodb::create_dynamo_db_connection_manager(
+ dynamodb_client,
+ )
+ .await
+ .context("failed to create connection manager")?;
+
+ tracing::info!("initialized connection repo");
+
+ let redis_multiplexed_conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .context("failed to get multiplexed redis connection for notification state machine")?;
+
+ let notification_ingress_service = Arc::new({
+ let notification_repository = DbNotificationRepository::new(db.clone());
+ let notification_queue = SqsNotificationQueue::new(
+ aws_sdk_sqs::Client::new(&aws_config),
+ config.notification_queue.clone(),
+ );
+ let state_machine = StateMachineDriverA {
+ user_checker: DbUserExistenceChecker::new(db.clone()),
+ notification_checker: PushNotificationCheckerImpl::new(DbNotificationRepository::new(
+ db.clone(),
+ )),
+ online_checker: LastOnlineCheckerImpl::new(
+ last_online_tracker::domain::services::LastOnlineService::new(
+ last_online_tracker::outbound::time::DefaultTime,
+ last_online_tracker::outbound::redis::RedisLastOnlineRepo::new(
+ redis_multiplexed_conn.clone(),
+ ),
+ ),
+ ),
+ digest_batcher: RedisDigestBatcher::new(redis_multiplexed_conn.clone()),
+ block_list: EmailBlockList::new::<model_notifications::NewEmailMetadata>(),
+ invite_list: ExplicitInviteAllowList::new::<model_notifications::InviteToTeamMetadata>(
+ )
+ .append::<model_notifications::ChannelInviteMetadata>(),
+ digest_window: std::time::Duration::from_secs(30 * 60),
+ online_duration_threshold: std::time::Duration::from_secs(60 * 60),
+ };
+ NotificationIngressService::new(notification_repository, notification_queue, state_machine)
+ });
+
+ tracing::info!("initialized notification ingress service");
+
api::setup_and_serve(ApiContext {
db: db.clone(),
email_service_client_external: Arc::new(EmailServiceClientExternal::new(
@@ -218,6 +274,8 @@ async fn main() -> anyhow::Result<()> {
jwt_args,
config: Arc::new(config),
internal_auth_key,
+ notification_ingress_service,
+ connection_repo: connection_manager.persistence,
soup_service,
stream_repo,
})
diff --git a/rust/cloud-storage/document_cognition_service/src/service/ai/name.rs b/rust/cloud-storage/document_cognition_service/src/service/ai/name.rs
index 56101c6fc6..efce846fd8 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/ai/name.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/ai/name.rs
@@ -7,7 +7,8 @@ use crate::{
use ai::chat_completion::get_chat_completion_openai_request;
use async_openai::types::{
- ChatCompletionRequestSystemMessageArgs, CreateChatCompletionRequestArgs,
+ ChatCompletionRequestSystemMessageArgs, ChatCompletionRequestUserMessageArgs,
+ CreateChatCompletionRequestArgs,
};
use macro_db_client::dcs::patch_chat::patch_chat;
@@ -19,14 +20,14 @@ pub async fn get_recomended_chat_name(text: &str) -> anyhow::Result<String> {
.context("failed to build system message")?
.into();
- let user_message = ChatCompletionRequestSystemMessageArgs::default()
+ let user_message = ChatCompletionRequestUserMessageArgs::default()
.content(text)
.build()
.context("failed to build user message")?
.into();
let request = CreateChatCompletionRequestArgs::default()
- .model(ai::types::Model::Gemini20Flash.to_string())
+ .model(ai::types::Model::Claude45Haiku.to_string())
.max_tokens(DEFAULT_MAX_TOKENS)
.messages(vec![system_message, user_message])
.build()
diff --git a/rust/cloud-storage/document_cognition_service/src/service/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/mod.rs
index 3643711327..2b33b36c17 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/mod.rs
@@ -2,3 +2,4 @@ pub mod ai;
pub mod attachment;
pub mod get_chat;
pub mod id_mapping;
+pub mod notification;
diff --git a/rust/cloud-storage/document_cognition_service/src/service/notification.rs b/rust/cloud-storage/document_cognition_service/src/service/notification.rs
new file mode 100644
index 0000000000..d6149506ea
--- /dev/null
+++ b/rust/cloud-storage/document_cognition_service/src/service/notification.rs
@@ -0,0 +1,85 @@
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use connection_gateway_client::service::connection::ConnectionRepo;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
+use model_notifications::AiResponseMetadata;
+use notification::domain::models::SendNotificationRequestBuilder;
+use notification::domain::service::NotificationIngress;
+
+/// Summarize an AI response and send a notification to the chat owner in a background task.
+///
+/// Spawns a tokio task that summarizes the assistant response with Haiku and then
+/// sends a notification if the owner is not currently connected. Best-effort — errors
+/// are logged but never propagated.
+pub fn notify(
+ connection_repo: Arc<dyn ConnectionRepo>,
+ notification_ingress: Arc<impl NotificationIngress>,
+ chat_id: String,
+ message_id: String,
+ assistant_text: String,
+ user_id: MacroUserIdStr<'static>,
+) {
+ tokio::spawn(async move {
+ if let Err(err) = send_chat_notification(
+ connection_repo.as_ref(),
+ &*notification_ingress,
+ &chat_id,
+ &message_id,
+ &assistant_text,
+ user_id,
+ )
+ .await
+ {
+ tracing::error!(error=?err, "failed to send chat notification");
+ }
+ });
+}
+
+/// Send a chat notification to the chat owner if they are not currently connected.
+///
+/// Checks the connection gateway for active WebSocket connections to the chat entity.
+/// If the owner is already connected, no notification is sent.
+/// The sender is the system AI user, and the recipient is the chat owner.
+#[tracing::instrument(err, skip(connection_repo, notification_ingress))]
+async fn send_chat_notification(
+ connection_repo: &dyn ConnectionRepo,
+ notification_ingress: &impl NotificationIngress,
+ chat_id: &str,
+ message_id: &str,
+ summary: &str,
+ recipient_id: MacroUserIdStr<'static>,
+) -> anyhow::Result<()> {
+ let entity = EntityType::Chat.with_entity_str(chat_id);
+
+ let connections = connection_repo.get_entries_by_entity(&entity).await?;
+
+ let recipient_is_connected = connections
+ .iter()
+ .any(|c| c.user_id == recipient_id.as_ref());
+
+ if recipient_is_connected {
+ return Ok(());
+ }
+
+ let req = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Chat.with_entity_string(chat_id.to_string()),
+ notification: AiResponseMetadata {
+ summary: summary.to_string(),
+ message_id: message_id.to_string(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([recipient_id]),
+ }
+ .into_request()
+ .with_apns()
+ .with_conn_gateway();
+
+ notification_ingress
+ .send_notification(req)
+ .await
+ .map_err(|e| anyhow::anyhow!("{e}"))?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rs
index 6e95fe9da5..49ea67e86a 100644
--- a/rust/cloud-storage/model_notifications/src/lib.rs
+++ b/rust/cloud-storage/model_notifications/src/lib.rs
@@ -183,5 +183,8 @@ define_notif_event!(
/// A user was assigned to a task.
TaskAssigned(TaskAssignedMetadata),
+
+ /// An AI assistant responded to a chat.
+ AiResponse(AiResponseMetadata),
}
);
diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rs
index 935be6c413..1d5af50970 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -14,6 +14,13 @@ use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
+#[derive(Debug, Clone, ToSchema, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AiResponseMetadata {
+ pub summary: String,
+ pub message_id: String,
+}
+
#[derive(Debug, Clone, Copy, ToSchema, Doppleganger, Serialize, Deserialize)]
#[dg(backward = models_comms::channel::ChannelType)]
#[serde(rename_all = "camelCase")]
@@ -222,6 +229,16 @@ impl notification::domain::models::Notification for ChannelInviteMetadata {
}
}
+impl notification::domain::models::Notification for AiResponseMetadata {
+ const TYPE_NAME: &'static str = "ai_response";
+ fn rate_limit_config() -> Option<RateLimitConfig> {
+ None
+ }
+ fn rate_limit_key(&self) -> Option<RateLimitKey> {
+ None
+ }
+}
+
impl notification::domain::models::Notification for ChannelMessageSendMetadata {
const TYPE_NAME: &'static str = "channel_message_send";
@@ -398,6 +415,26 @@ impl NotificationExtIos for ChannelInviteMetadata {
}
}
+impl NotificationExtIos for AiResponseMetadata {
+ type NotifData = ::notification::domain::models::apple::PushNotificationData;
+ fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
+ NotifCollapseKey::new(&self.message_id)
+ }
+
+ fn into_apns<'a>(
+ self,
+ _sender_id: Option<MacroUserIdStr<'a>>,
+ _entity: &Entity<'_>,
+ notification_id: Uuid,
+ ) -> Option<APNSPushNotification<Self::NotifData>> {
+ Some(alert_apns(
+ "Ai Response".into(),
+ self.summary,
+ PushNotificationData { notification_id },
+ ))
+ }
+}
+
impl NotificationExtIos for ChannelMessageSendMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;