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(notification-inbox): serve the notifications inbox over GraphQL (#8716)
teod787e4a6070b
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex faeae9584a..26221a357a 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -4359,6 +4359,7 @@"crates/graphql_favorite","crates/graphql_initiative","crates/graphql_notification",+ "crates/graphql_notification_inbox","crates/graphql_permission","crates/graphql_properties","crates/graphql_scheduled_action",@@ -4418,6 +4419,7 @@"crates/models_team","crates/non_empty","crates/notification",+ "crates/notification_inbox","crates/notification_state","crates/pptx_engine","crates/predicate_index",@@ -5515,6 +5517,7 @@"crates/graphql_favorite","crates/graphql_initiative","crates/graphql_notification",+ "crates/graphql_notification_inbox","crates/graphql_permission","crates/graphql_properties","crates/graphql_scheduled_action",@@ -5596,6 +5599,7 @@"crates/name_search","crates/non_empty","crates/notification",+ "crates/notification_inbox","crates/notification_state","crates/opensearch_client","crates/opensearch_query_builder",@@ -8853,6 +8857,160 @@"crates/remote_env_var","crates/workspace-hack"],+ "graphql_notification_inbox": [+ "crates/activity",+ "crates/agent",+ "crates/agent_changes",+ "crates/agent_runtime_protocol",+ "crates/agent_session",+ "crates/ai_billing",+ "crates/ai_engine",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/analytics_client",+ "crates/attachment",+ "crates/attention_feed",+ "crates/authentication_service_client",+ "crates/bot_id",+ "crates/bot_token",+ "crates/bots",+ "crates/broadcast",+ "crates/calendar_events",+ "crates/call",+ "crates/channel_sender",+ "crates/channels",+ "crates/chat",+ "crates/comms_db_client",+ "crates/connection",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts",+ "crates/cowlike",+ "crates/crm",+ "crates/database_env_vars",+ "crates/database_sql",+ "crates/databases",+ "crates/document_sub_type",+ "crates/documents",+ "crates/docx_engine",+ "crates/dynamic_ui",+ "crates/dynamodb_client",+ "crates/email",+ "crates/email_api_client",+ "crates/email_db_client",+ "crates/email_utils",+ "crates/email_validator",+ "crates/embedding",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_access_management",+ "crates/entity_mutation",+ "crates/entity_registry/entity_registry",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry",+ "crates/favorites",+ "crates/fig_engine",+ "crates/filter_ast",+ "crates/folds/agent_fold",+ "crates/foreign_entity",+ "crates/frecency",+ "crates/genai_telemetry",+ "crates/generic_email_domains",+ "crates/git_patch",+ "crates/github_pull_requests",+ "crates/gmail_client",+ "crates/google_token",+ "crates/graphql_common",+ "crates/graphql_email",+ "crates/graphql_notification",+ "crates/graphql_notification_inbox",+ "crates/graphql_permission",+ "crates/graphql_soup",+ "crates/graphql_soup_filter_input",+ "crates/harness_id",+ "crates/harness_token",+ "crates/initiative",+ "crates/invite_email",+ "crates/ip_extractor",+ "crates/item_filter_index",+ "crates/item_filters",+ "crates/jev",+ "crates/kafka_util",+ "crates/last_online_tracker",+ "crates/lexical_client",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_aws_config",+ "crates/macro_db_client",+ "crates/macro_entrypoint",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_event_broker",+ "crates/macro_event_topics",+ "crates/macro_service_urls",+ "crates/macro_sha_count_client",+ "crates/macro_sync_service_jwt",+ "crates/macro_tower_layers",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/maybe_send",+ "crates/mention_utils",+ "crates/messages",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_owner",+ "crates/model_user",+ "crates/models_ai_projection",+ "crates/models_bulk_upload",+ "crates/models_databases",+ "crates/models_dcs",+ "crates/models_email",+ "crates/models_entity_access_management",+ "crates/models_grouping",+ "crates/models_opensearch",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/models_properties",+ "crates/models_sfs",+ "crates/models_soup",+ "crates/models_team",+ "crates/non_empty",+ "crates/notification",+ "crates/notification_inbox",+ "crates/notification_state",+ "crates/pptx_engine",+ "crates/predicate_index",+ "crates/projects",+ "crates/prompt",+ "crates/properties",+ "crates/psd_engine",+ "crates/rate_limit",+ "crates/readonly_pool",+ "crates/remote_env_var",+ "crates/roles_and_permissions",+ "crates/s3_key",+ "crates/secretsmanager_client",+ "crates/share_permission_db_utils",+ "crates/soup",+ "crates/soup_filter_projection",+ "crates/soup_realtime",+ "crates/sqs_client",+ "crates/sqs_worker",+ "crates/static_file_service_client",+ "crates/sync_service",+ "crates/sync_service_client",+ "crates/system_properties",+ "crates/system_skills",+ "crates/task_dedup",+ "crates/teams",+ "crates/trigger_context",+ "crates/unfurl",+ "crates/user_quota",+ "crates/workspace-hack"+ ],"graphql_permission": ["crates/agent","crates/ai_toolset",@@ -11485,6 +11643,150 @@"crates/remote_env_var","crates/workspace-hack"],+ "notification_inbox": [+ "crates/activity",+ "crates/agent",+ "crates/agent_changes",+ "crates/agent_runtime_protocol",+ "crates/agent_session",+ "crates/ai_billing",+ "crates/ai_engine",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/analytics_client",+ "crates/attachment",+ "crates/attention_feed",+ "crates/authentication_service_client",+ "crates/bot_id",+ "crates/bot_token",+ "crates/bots",+ "crates/broadcast",+ "crates/calendar_events",+ "crates/call",+ "crates/channel_sender",+ "crates/channels",+ "crates/chat",+ "crates/comms_db_client",+ "crates/connection",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts",+ "crates/cowlike",+ "crates/crm",+ "crates/database_env_vars",+ "crates/database_sql",+ "crates/databases",+ "crates/document_sub_type",+ "crates/documents",+ "crates/docx_engine",+ "crates/dynamic_ui",+ "crates/dynamodb_client",+ "crates/email",+ "crates/email_api_client",+ "crates/email_db_client",+ "crates/email_utils",+ "crates/email_validator",+ "crates/embedding",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_access_management",+ "crates/entity_mutation",+ "crates/entity_registry/entity_registry",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry",+ "crates/favorites",+ "crates/fig_engine",+ "crates/filter_ast",+ "crates/folds/agent_fold",+ "crates/foreign_entity",+ "crates/frecency",+ "crates/genai_telemetry",+ "crates/generic_email_domains",+ "crates/git_patch",+ "crates/github_pull_requests",+ "crates/gmail_client",+ "crates/google_token",+ "crates/harness_id",+ "crates/harness_token",+ "crates/initiative",+ "crates/invite_email",+ "crates/ip_extractor",+ "crates/item_filters",+ "crates/jev",+ "crates/kafka_util",+ "crates/last_online_tracker",+ "crates/lexical_client",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_aws_config",+ "crates/macro_db_client",+ "crates/macro_entrypoint",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_event_broker",+ "crates/macro_event_topics",+ "crates/macro_service_urls",+ "crates/macro_sha_count_client",+ "crates/macro_sync_service_jwt",+ "crates/macro_tower_layers",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/maybe_send",+ "crates/mention_utils",+ "crates/messages",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_owner",+ "crates/model_user",+ "crates/models_ai_projection",+ "crates/models_bulk_upload",+ "crates/models_databases",+ "crates/models_dcs",+ "crates/models_email",+ "crates/models_entity_access_management",+ "crates/models_grouping",+ "crates/models_opensearch",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/models_properties",+ "crates/models_sfs",+ "crates/models_soup",+ "crates/models_team",+ "crates/non_empty",+ "crates/notification",+ "crates/notification_inbox",+ "crates/notification_state",+ "crates/pptx_engine",+ "crates/projects",+ "crates/prompt",+ "crates/properties",+ "crates/psd_engine",+ "crates/rate_limit",+ "crates/readonly_pool",+ "crates/remote_env_var",+ "crates/roles_and_permissions",+ "crates/s3_key",+ "crates/secretsmanager_client",+ "crates/share_permission_db_utils",+ "crates/soup",+ "crates/soup_realtime",+ "crates/sqs_client",+ "crates/sqs_worker",+ "crates/static_file_service_client",+ "crates/sync_service",+ "crates/sync_service_client",+ "crates/system_properties",+ "crates/system_skills",+ "crates/task_dedup",+ "crates/teams",+ "crates/trigger_context",+ "crates/unfurl",+ "crates/user_quota",+ "crates/workspace-hack"+ ],"notification_retention_handler": ["crates/ai_toolset","crates/bot_id",diff --git a/Cargo.lock b/Cargo.lockindex 63d10d3d7a..072a7c04de 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4864,6 +4864,7 @@ dependencies = ["graphql_favorite","graphql_initiative","graphql_notification",+ "graphql_notification_inbox","graphql_permission","graphql_properties","graphql_scheduled_action",@@ -4881,6 +4882,7 @@ dependencies = ["models_properties","models_soup","notification",+ "notification_inbox","predicate-index","rootcause","saved_views",@@ -6718,6 +6720,7 @@ dependencies = ["models_properties","models_soup","notification",+ "notification_inbox","opensearch_client","opentelemetry","opentelemetry_sdk",@@ -9421,6 +9424,24 @@ dependencies = ["workspace-hack",]+[[package]]+name = "graphql_notification_inbox"+version = "0.1.0"+dependencies = [+ "async-graphql",+ "async-stream",+ "attention_feed",+ "futures",+ "graphql_common",+ "graphql_notification",+ "graphql_soup",+ "macro_user_id",+ "notification_inbox",+ "soup",+ "tracing",+ "workspace-hack",+]+[[package]]name = "graphql_permission"version = "0.1.0"@@ -13958,6 +13979,27 @@ dependencies = ["workspace-hack",]+[[package]]+name = "notification_inbox"+version = "0.1.0"+dependencies = [+ "attention_feed",+ "chrono",+ "filter_ast",+ "item_filters",+ "macro_user_id",+ "model-entity",+ "model_notifications",+ "notification",+ "rootcause",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "uuid",+ "workspace-hack",+]+[[package]]name = "notification_retention_handler"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex d9da61de40..9fe1b257dc 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -82,6 +82,7 @@ members = ["crates/graphql_crm","crates/graphql_initiative","crates/graphql_notification",+ "crates/graphql_notification_inbox","crates/graphql_permission","crates/graphql_properties","crates/graphql_scheduled_action",@@ -114,6 +115,7 @@ members = ["crates/model_owner","crates/mcp_select","crates/mcp_toolset",+ "crates/notification_inbox","crates/notification_state","crates/pipedream_mcp","crates/granola_sync",diff --git a/crates/attention_feed/AGENTS.md b/crates/attention_feed/AGENTS.mdindex 601d3851a5..c8905023ca 100644--- a/crates/attention_feed/AGENTS.md+++ b/crates/attention_feed/AGENTS.md@@ -3,7 +3,7 @@## What it isThe shared layer under Macro's attention feeds: Home's work feed-(`crates/work_feed`) and the notifications inbox. It pages authorized, hydrated+(`crates/work_feed`) and the notifications inbox (`crates/notification_inbox`). It pages authorized, hydratedcandidates with their notifications, completes, reads and restores them, andbatches realtime changes into recomputes. Each feed keeps its own model on top.@@ -28,7 +28,8 @@ whose `DoneReceipt` is the undo token. Subscriptions run `FeedTriggers` through- Owns: candidate paging and refill, notification loading per keying, done,seen and undo, inbox email archive on done, live trigger batching, viewerteam lookup.-- Not here: items, stacks and primary reasons → `crates/work_feed`;+- Not here: items, stacks and primary reasons → `crates/work_feed`; inbox+ rows → `crates/notification_inbox`;candidate SQL, access gates and hydration → `crates/soup` (`attention.rs`);notification storage → `crates/notification`.@@ -36,8 +37,8 @@ whose `DoneReceipt` is the undo token. Subscriptions run `FeedTriggers` through- Depends on: `notification`, `entity_access` (ports; `inbound` feature);`soup`, `email`, `activity`, `soup_realtime` (feature `outbound`).-- Used by: `work_feed`, `graphql_work_feed`, `document_storage_service`- (composition), `complete_graph` (tests).+- Used by: `work_feed`, `notification_inbox` and their GraphQL adapters,+ `document_storage_service` (composition), `complete_graph` (tests).## Recipesdiff --git a/crates/complete_graph/AGENTS.md b/crates/complete_graph/AGENTS.mdindex abb09ab6d9..c201dfd4ed 100644--- a/crates/complete_graph/AGENTS.md+++ b/crates/complete_graph/AGENTS.md@@ -4,8 +4,9 @@Part of the web client's shared infrastructure: this crate composes thedomain GraphQL adapter crates (`graphql_soup`, `graphql_properties`,-`graphql_notification`, `graphql_email`, `graphql_entity_mutation`, with-shared plumbing in `graphql_common`) into the complete GraphQL schema+`graphql_notification`, `graphql_email`, `graphql_entity_mutation`,+`graphql_work_feed`, `graphql_notification_inbox`, with shared plumbing in+`graphql_common`) into the complete GraphQL schemaconsumed by the client's **normalized cache** (`crates/client`, design doc:`apps/web/docs/graphql-normalized-cache-plan.md`). The conventions below areload-bearing for cache correctness and API consistency. The cache's builddiff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.tomlindex 6d6e4b237c..fdb571eb88 100644--- a/crates/complete_graph/Cargo.toml+++ b/crates/complete_graph/Cargo.toml@@ -35,6 +35,7 @@ graphql_favorite = { path = "../graphql_favorite" }graphql_initiative = { path = "../graphql_initiative" }graphql_databases = { path = "../graphql_databases" }graphql_notification = { path = "../graphql_notification" }+graphql_notification_inbox = { path = "../graphql_notification_inbox" }graphql_permission = { path = "../graphql_permission" }graphql_properties = { path = "../graphql_properties" }graphql_scheduled_action = { path = "../graphql_scheduled_action" }@@ -69,6 +70,7 @@ databases_sql = { path = "../databases_sql" }models_databases = { path = "../models_databases" }activity = { path = "../activity", default-features = false, features = ["realtime"] }attention_feed = { path = "../attention_feed", features = ["inbound"] }+notification_inbox = { path = "../notification_inbox" }work_feed = { path = "../work_feed" }agent_runtime_protocol = { path = "../agent_runtime_protocol" }apollo-compiler = { workspace = true }diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rsindex 2ecba462cb..274d57ce79 100644--- a/crates/complete_graph/src/lib.rs+++ b/crates/complete_graph/src/lib.rs@@ -1,6 +1,7 @@//! Composition of the domain GraphQL adapter crates (`graphql_soup`,//! `graphql_channel`, `graphql_properties`, `graphql_notification`, `graphql_email`,-//! `graphql_favorite`, `graphql_entity_mutation`, `graphql_work_feed`) into the+//! `graphql_favorite`, `graphql_entity_mutation`, `graphql_work_feed`,+//! `graphql_notification_inbox`) into the//! complete schema served by//! `document_storage_service` and exported as SDL.#![deny(missing_docs)]@@ -63,6 +64,9 @@ pub use graphql_notification::{NotificationMutationRoot, NotificationMutationService, SoupNotificationEdgeReader,UpdateNotificationsForEntityInput, UpdateNotificationsInput, entity_notifications_loader,};+pub use graphql_notification_inbox::{+ NotificationInboxGraphqlContext, NotificationInboxGraphqlService,+};pub use graphql_permission::{EntityPermissionEdgeReader, EntityPermissionLoader, GraphqlAccessLevelPermission,GraphqlChannelParticipantRole, GraphqlChannelRolePermission, GraphqlChannelViewOnlyPermission,diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rsindex 2d16a7c4ef..dce10e4dc0 100644--- a/crates/complete_graph/src/schema.rs+++ b/crates/complete_graph/src/schema.rs@@ -47,6 +47,10 @@ use graphql_notification::{NoOpNotificationMutationService, NoOpSoupNotificationEdgeReader, NotificationMutationRoot,NotificationMutationService, NotificationSubscriptionRoot, SoupNotificationEdgeReader,};+use graphql_notification_inbox::{+ GraphqlNotificationInboxPage, NotificationInboxInput, NotificationInboxMutationRoot,+ NotificationInboxSubscriptionRoot, resolve_notification_inbox,+};use graphql_permission::{EntityPermissionEdgeReader, NoOpEntityPermissionEdgeReader};use graphql_properties::{EntityPropertyReader, EntityPropertyWriter, GraphqlPropertyDefinition,@@ -107,6 +111,7 @@ pub struct CompleteMutationRoot<InitiativeMutationRoot<E>,CalendarMutationRoot,WorkFeedMutationRoot<E>,+ NotificationInboxMutationRoot<E>,SavedViewMutationRoot,);@@ -134,19 +139,21 @@ impl<InitiativeMutationRoot::<E>::default(),CalendarMutationRoot,WorkFeedMutationRoot::<E>::default(),+ NotificationInboxMutationRoot::<E>::default(),SavedViewMutationRoot,)}}/// Root subscription object combining realtime Soup, notification,-/// activity, and work feed adapters.+/// activity, work feed and notification inbox adapters.#[derive(MergedSubscription)]pub struct CompleteSubscriptionRoot<R, NS, AS, Auth, St, NR, PR, ER, FR, AR, AcR>(SoupSubscriptionRoot<R, Auth, St, NR, PR, ER, FR, AR, AcR>,NotificationSubscriptionRoot<NS>,ActivitySubscriptionRoot<AS>,WorkFeedSubscriptionRoot<SoupEdges<NR, PR, ER, FR, AR, AcR>>,+ NotificationInboxSubscriptionRoot<SoupEdges<NR, PR, ER, FR, AR, AcR>>,)whereR: SoupRealtimeSubscriptionService,@@ -461,6 +468,7 @@ whereNotificationSubscriptionRoot::new(notification_subscription_service),ActivitySubscriptionRoot::new(activity_subscription_service),WorkFeedSubscriptionRoot::default(),+ NotificationInboxSubscriptionRoot::default(),),).finish()@@ -883,6 +891,24 @@ where.await}+ /// A page of the authenticated user's notifications inbox, newest group+ /// first: their pending notifications grouped by the entity they are+ /// filed under and cut into rows, one per conversation thread, channel+ /// top level, email thread, task, request or agent session.+ async fn notification_inbox(+ &self,+ ctx: &Context<'_>,+ input: Option<NotificationInboxInput>,+ ) -> async_graphql::Result<GraphqlNotificationInboxPage<SoupEdges<NR, PR, ER, FR, AR, AcR>>>+ {+ resolve_notification_inbox::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(+ ctx,+ self.user_id.clone(),+ input.unwrap_or_default(),+ )+ .await+ }+/// Authenticated user email catalog fields supplied by `graphql_email`.#[graphql(flatten)]async fn email(&self, ctx: &Context<'_>) -> async_graphql::Result<GraphqlEmailQuery<E>> {diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex 1684816cac..e21f9ac099 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -53,6 +53,7 @@ mod database_view_rows;mod email_archive;mod form_activity;mod initiative;+mod notification_inbox;mod scheduled_actions;mod soup_patches;mod stale_client;diff --git a/crates/complete_graph/src/schema/test/notification_inbox.rs b/crates/complete_graph/src/schema/test/notification_inbox.rsnew file mode 100644index 0000000000..d10f0984cc--- /dev/null+++ b/crates/complete_graph/src/schema/test/notification_inbox.rs@@ -0,0 +1,506 @@+use std::sync::{Arc, Mutex};++use ::attention_feed::{+ domain::{+ models::{+ CandidateKeying, DoneReceipt, FeedError, FeedKey, FeedPosition, FeedRevision,+ FeedTrigger, FeedViewer,+ },+ ports::FeedTriggers,+ },+ inbound::viewers::FeedViewerResolver,+};+use ::notification_inbox::domain::models::{+ InboxActor, InboxChange, InboxDoneOutcome, InboxEntry, InboxPage, InboxQuery, InboxRow,+ InboxRowAction, InboxRowActionKind, InboxRowId, InboxRowTarget, InboxRowType, InboxScope,+};+use async_graphql::futures_util::{StreamExt as _, future::BoxFuture, pin_mut};+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};+use model_notifications::NotifEvent;+use notification::domain::models::{NotificationState, UserNotificationRow};+use soup::domain::models::SoupProjectionHydration;++use super::*;+use crate::{NotificationInboxGraphqlContext, NotificationInboxGraphqlService};++const DOC_ID: Uuid = Uuid::from_u128(0xD0C);++fn at(minute: u32) -> chrono::DateTime<chrono::Utc> {+ use chrono::TimeZone;+ chrono::Utc+ .with_ymd_and_hms(2024, 6, 1, 10, minute, 0)+ .unwrap()+}++fn doc_group() -> FeedKey {+ FeedKey::new(ModelEntityType::Document.with_entity_string(DOC_ID.to_string()))+}++fn thread_row_id() -> InboxRowId {+ InboxRowId {+ group: doc_group(),+ slot: "thread:a".to_string(),+ }+}++fn comment(id: u128, minute: u32) -> Arc<UserNotificationRow<NotifEvent>> {+ let metadata: NotifEvent = serde_json::from_value(serde_json::json!({+ "tag": "replied_to_document_comment_thread",+ "content": {+ "documentName": "Doc",+ "owner": VALID_USER_ID,+ "commentId": Uuid::from_u128(id),+ "threadId": Uuid::from_u128(0xA),+ "text": "looks good",+ },+ }))+ .unwrap();+ Arc::new(UserNotificationRow {+ owner_id: MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap(),+ notification_id: Uuid::from_u128(id),+ notification_event_type: "replied_to_document_comment_thread".to_string(),+ entity: doc_group().entity().clone(),+ sent: true,+ state: NotificationState::Unseen,+ created_at: at(minute),+ viewed_at: None,+ updated_at: at(minute),+ deleted_at: None,+ notification_metadata: metadata,+ sender_id: None,+ })+}++fn doc_entry() -> InboxEntry<SoupProjectionHydration> {+ InboxEntry {+ group: doc_group(),+ entity: SoupProjectionHydration {+ item: soup_document(DOC_ID),+ document_server_facts: None,+ sort_key: None,+ },+ sort_at: at(7),+ rows: vec![InboxRow {+ id: thread_row_id(),+ row_type: InboxRowType::DiscussionThread,+ thread_id: Some("a".to_string()),+ actor: Some(InboxActor::User(+ MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap(),+ )),+ actions: vec![InboxRowAction {+ kind: InboxRowActionKind::Open,+ target_id: None,+ url: None,+ }],+ notifications: vec![comment(2, 7), comment(1, 5)],+ hidden: vec![comment(3, 6)],+ unseen: true,+ }],+ }+}++#[derive(Default)]+struct RecordingInboxService {+ pages: Mutex<Vec<InboxQuery>>,+ recomputes: Mutex<Vec<(InboxScope, Vec<FeedKey>)>>,+ dones: Mutex<Vec<Vec<InboxRowTarget>>>,+ undos: Mutex<Vec<(InboxScope, DoneReceipt)>>,+ seens: Mutex<Vec<(InboxScope, Vec<InboxRowId>)>>,+}++/// Shares the recording service between the schema and the assertions.+struct Recording(Arc<RecordingInboxService>);++type Changes = Vec<InboxChange<SoupProjectionHydration>>;++impl NotificationInboxGraphqlService for Recording {+ fn page(+ &self,+ _viewer: FeedViewer,+ query: InboxQuery,+ ) -> BoxFuture<'_, Result<InboxPage<SoupProjectionHydration>, FeedError>> {+ self.0.pages.lock().unwrap().push(query);+ Box::pin(async {+ Ok(InboxPage {+ entries: vec![doc_entry()],+ next: Some(FeedPosition {+ sort_at: at(7),+ entity_id: DOC_ID.to_string(),+ }),+ })+ })+ }++ fn recompute(+ &self,+ _viewer: FeedViewer,+ scope: InboxScope,+ groups: Vec<FeedKey>,+ ) -> BoxFuture<'_, Result<Changes, FeedError>> {+ self.0+ .recomputes+ .lock()+ .unwrap()+ .push((scope, groups.clone()));+ Box::pin(async move {+ Ok(groups+ .into_iter()+ .map(|group| {+ if group == doc_group() {+ InboxChange::Upserted(doc_entry())+ } else {+ InboxChange::Removed(group)+ }+ })+ .collect())+ })+ }++ fn mark_done(+ &self,+ _viewer: FeedViewer,+ targets: Vec<InboxRowTarget>,+ ) -> BoxFuture<'_, Result<InboxDoneOutcome, FeedError>> {+ let rows: Vec<_> = targets.iter().map(|target| target.id.clone()).collect();+ self.0.dones.lock().unwrap().push(targets);+ Box::pin(async move {+ Ok(InboxDoneOutcome {+ receipt: DoneReceipt {+ keys: vec![doc_group().id()],+ notification_ids: vec![Uuid::from_u128(1)],+ ..Default::default()+ },+ rows,+ })+ })+ }++ fn undo_done(+ &self,+ _viewer: FeedViewer,+ scope: InboxScope,+ receipt: DoneReceipt,+ ) -> BoxFuture<'_, Result<Changes, FeedError>> {+ self.0.undos.lock().unwrap().push((scope, receipt));+ Box::pin(async { Ok(vec![InboxChange::Upserted(doc_entry())]) })+ }++ fn mark_seen(+ &self,+ _viewer: FeedViewer,+ scope: InboxScope,+ rows: Vec<InboxRowId>,+ ) -> BoxFuture<'_, Result<Changes, FeedError>> {+ self.0.seens.lock().unwrap().push((scope, rows));+ Box::pin(async { Ok(vec![InboxChange::Upserted(doc_entry())]) })+ }+}++/// Triggers a test drives by hand.+#[derive(Default, Clone)]+struct ManualTriggers {+ sender: Arc<Mutex<Option<tokio::sync::mpsc::Sender<FeedTrigger>>>>,+ subscribed: Arc<Mutex<Vec<(CandidateKeying, bool)>>>,+}++impl FeedTriggers for ManualTriggers {+ fn subscribe(+ &self,+ _user: MacroUserIdStr<'static>,+ keying: CandidateKeying,+ own_work: bool,+ ) -> tokio::sync::mpsc::Receiver<FeedTrigger> {+ let (sender, receiver) = tokio::sync::mpsc::channel(8);+ *self.sender.lock().unwrap() = Some(sender);+ self.subscribed.lock().unwrap().push((keying, own_work));+ receiver+ }+}++struct NoTeam;++impl FeedViewerResolver for NoTeam {+ fn team(+ &self,+ _user: MacroUserIdStr<'static>,+ ) -> BoxFuture<'_, Result<Option<EntityAccessReceipt<MemberTeamRole>>, rootcause::Report>> {+ Box::pin(async { Ok(None) })+ }+}++fn context(+ service: &Arc<RecordingInboxService>,+ triggers: &ManualTriggers,+) -> NotificationInboxGraphqlContext {+ NotificationInboxGraphqlContext::new(+ Recording(Arc::clone(service)),+ Arc::new(triggers.clone()),+ Arc::new(NoTeam),+ )+}++fn viewer_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap()+}++#[tokio::test]+async fn notification_inbox_pages_groups_with_their_rows() {+ let harness = harness();+ let service = Arc::new(RecordingInboxService::default());+ let response = harness+ .schema+ .execute(+ harness+ .request(+ r#"{ user { notificationInbox(input: {+ scope: { rowTypes: [DISCUSSION_THREAD, AGENT] },+ limit: 10+ }) {+ nextCursor+ nextPosition { sortAt entityId }+ entries {+ groupId sortAt+ entity { __typename id }+ rows {+ id rowType threadId latestAt unseen count revision+ actor { kind principalId name }+ actions { kind targetId url }+ notifications(limit: 1) { id eventType }+ }+ }+ } } }"#,+ authenticated_parts(),+ )+ .data(context(&service, &ManualTriggers::default())),+ )+ .await;+ assert!(response.errors.is_empty(), "{:?}", response.errors);+ let data = response.data.into_json().unwrap();+ let page = &data["user"]["notificationInbox"];+ let entry = &page["entries"][0];++ assert_eq!(entry["groupId"], format!("document:{DOC_ID}"));+ assert_eq!(entry["sortAt"], at(7).to_rfc3339());+ assert_eq!(entry["entity"]["__typename"], "GraphqlSoupDocument");+ let row = &entry["rows"][0];+ assert_eq!(row["id"], format!("document:{DOC_ID}#thread:a"));+ assert_eq!(row["rowType"], "DISCUSSION_THREAD");+ assert_eq!(row["threadId"], "a");+ assert_eq!(row["latestAt"], at(7).to_rfc3339());+ assert_eq!(row["unseen"], true);+ assert_eq!(row["count"], 2);+ assert_eq!(+ row["actor"],+ serde_json::json!({ "kind": "USER", "principalId": VALID_USER_ID, "name": null })+ );+ assert_eq!(+ row["actions"],+ serde_json::json!([{ "kind": "OPEN", "targetId": null, "url": null }])+ );+ // The revision covers hidden notifications too.+ let revision = FeedRevision::decode(row["revision"].as_str().unwrap()).unwrap();+ assert_eq!(revision.attention_through, Some(at(7)));+ assert_eq!(row["notifications"].as_array().unwrap().len(), 1);+ assert!(page["nextCursor"].is_string());+ assert_eq!(page["nextPosition"]["entityId"], DOC_ID.to_string());+ assert_eq!(page["nextPosition"]["sortAt"], at(7).to_rfc3339());++ let pages = service.pages.lock().unwrap();+ assert_eq!(+ pages[0].scope.row_types,+ vec![InboxRowType::DiscussionThread, InboxRowType::Agent]+ );+ assert_eq!(pages[0].limit, 10);+}++#[tokio::test]+async fn rows_are_marked_done_undone_and_seen() {+ let harness = harness();+ let service = Arc::new(RecordingInboxService::default());+ let triggers = ManualTriggers::default();+ let row_id = thread_row_id().id();+ let revision = FeedRevision {+ attention_through: Some(at(6)),+ }+ .encode();++ let done = harness+ .schema+ .execute(+ harness+ .request(+ &format!(+ r#"mutation {{ markNotificationInboxRowsDone(input: {{ rows: [+ {{ id: "{row_id}", revision: "{revision}" }}+ ] }}) {{ rowIds undoToken }} }}"#+ ),+ authenticated_parts(),+ )+ .data(viewer_id())+ .data(context(&service, &triggers)),+ )+ .await;+ assert!(done.errors.is_empty(), "{:?}", done.errors);+ let done = done.data.into_json().unwrap();+ assert_eq!(+ done["markNotificationInboxRowsDone"]["rowIds"],+ serde_json::json!([row_id])+ );+ let targets = service.dones.lock().unwrap()[0].clone();+ assert_eq!(targets[0].id, thread_row_id());+ assert_eq!(targets[0].revision.unwrap().attention_through, Some(at(6)));++ let undo_token = done["markNotificationInboxRowsDone"]["undoToken"]+ .as_str()+ .unwrap();+ let undo = harness+ .schema+ .execute(+ harness+ .request(+ &format!(+ r#"mutation {{ undoNotificationInboxRowsDone(input: {{+ undoToken: "{undo_token}", scope: {{ rowTypes: [DISCUSSION_THREAD] }}+ }}) {{ patches {{ __typename+ ... on NotificationInboxEntryUpserted {{ entry {{ groupId rows {{ id }} }} }}+ }} }} }}"#+ ),+ authenticated_parts(),+ )+ .data(viewer_id())+ .data(context(&service, &triggers)),+ )+ .await;+ assert!(undo.errors.is_empty(), "{:?}", undo.errors);+ let undo = undo.data.into_json().unwrap();+ assert_eq!(+ undo["undoNotificationInboxRowsDone"]["patches"][0]["entry"]["rows"][0]["id"],+ row_id+ );+ {+ let undos = service.undos.lock().unwrap();+ assert_eq!(undos[0].0.row_types, vec![InboxRowType::DiscussionThread]);+ assert_eq!(undos[0].1.notification_ids, vec![Uuid::from_u128(1)]);+ }++ let seen = harness+ .schema+ .execute(+ harness+ .request(+ &format!(+ r#"mutation {{ markNotificationInboxRowsSeen(input: {{ rowIds: ["{row_id}"] }}) {{+ patches {{ __typename }}+ }} }}"#+ ),+ authenticated_parts(),+ )+ .data(viewer_id())+ .data(context(&service, &triggers)),+ )+ .await;+ assert!(seen.errors.is_empty(), "{:?}", seen.errors);+ assert_eq!(service.seens.lock().unwrap()[0].1, vec![thread_row_id()]);+}++#[tokio::test]+async fn done_rejects_a_row_id_that_names_no_row() {+ let harness = harness();+ let service = Arc::new(RecordingInboxService::default());+ let response = harness+ .schema+ .execute(+ harness+ .request(+ r#"mutation { markNotificationInboxRowsDone(input: { rows: [{ id: "document:x" }] }) { rowIds } }"#,+ authenticated_parts(),+ )+ .data(viewer_id())+ .data(context(&service, &ManualTriggers::default())),+ )+ .await;+ assert_eq!(+ response.errors[0].message,+ "invalid notification inbox row id"+ );+ assert!(service.dones.lock().unwrap().is_empty());+}++#[tokio::test]+async fn notification_inbox_updates_batch_recomputed_patches() {+ let harness = harness();+ let service = Arc::new(RecordingInboxService::default());+ let triggers = ManualTriggers::default();+ let other =+ FeedKey::new(ModelEntityType::Chat.with_entity_string(Uuid::from_u128(0xC4A7).to_string()));++ let request = async_graphql::Request::new(+ r#"subscription { notificationInboxUpdates(scope: { rowTypes: [DISCUSSION_THREAD] }) {+ __typename+ ... on NotificationInboxEntryUpserted { entry { groupId rows { id } } }+ ... on NotificationInboxEntryRemoved { groupId }+ ... on NotificationInboxInvalidated { refresh }+ } }"#,+ )+ .data(viewer_id())+ .data(context(&service, &triggers));+ let responses = harness.schema.execute_stream(request);+ pin_mut!(responses);++ // The subscription opens its triggers lazily, on first poll.+ let first = tokio::spawn({+ let triggers = triggers.clone();+ let other = other.clone();+ async move {+ let sender = loop {+ if let Some(sender) = triggers.sender.lock().unwrap().clone() {+ break sender;+ }+ tokio::task::yield_now().await;+ };+ sender+ .send(FeedTrigger::Changed(vec![doc_group().into_entity()]))+ .await+ .unwrap();+ sender+ .send(FeedTrigger::Changed(vec![+ other.into_entity(),+ doc_group().into_entity(),+ ]))+ .await+ .unwrap();+ sender+ }+ });+ let response = responses.next().await.expect("patch batch");+ assert!(response.errors.is_empty(), "{:?}", response.errors);+ let data = response.data.into_json().unwrap();+ let patches = data["notificationInboxUpdates"].as_array().unwrap();+ assert_eq!(patches.len(), 2);+ assert_eq!(patches[0]["__typename"], "NotificationInboxEntryUpserted");+ assert_eq!(patches[1]["__typename"], "NotificationInboxEntryRemoved");+ assert_eq!(patches[1]["groupId"], other.id());+ {+ let recomputes = service.recomputes.lock().unwrap();+ assert_eq!(recomputes.len(), 1);+ assert_eq!(recomputes[0].1, vec![doc_group(), other.clone()]);+ }+ assert_eq!(+ triggers.subscribed.lock().unwrap().as_slice(),+ &[(CandidateKeying::FiledEntity, false)]+ );++ let sender = first.await.unwrap();+ sender.send(FeedTrigger::Invalidated).await.unwrap();+ let response = responses.next().await.expect("invalidation");+ let data = response.data.into_json().unwrap();+ assert_eq!(+ data["notificationInboxUpdates"][0]["__typename"],+ "NotificationInboxInvalidated"+ );++ drop(sender);+ *triggers.sender.lock().unwrap() = None;+ let response = responses.next().await.expect("closing error");+ assert!(!response.errors.is_empty());+}diff --git a/crates/graphql_common/AGENTS.md b/crates/graphql_common/AGENTS.mdindex a34649357e..b0587888f9 100644--- a/crates/graphql_common/AGENTS.md+++ b/crates/graphql_common/AGENTS.md@@ -30,7 +30,8 @@ schema types (entity type, owner type, property filters).`model-entity`, `model_owner`, `models_properties`.- Used by: every `graphql_*` domain adapter crate (favorite, initiative,calendar, email, notification, soup_filter_input, entity_mutation,- properties, crm, soup, channel, work_feed, activity) and `complete_graph`+ properties, crm, soup, channel, work_feed, notification_inbox, activity) and+ `complete_graph`(the schema that composes them all).## Recipesdiff --git a/crates/graphql_notification/AGENTS.md b/crates/graphql_notification/AGENTS.mdindex cdb25bb981..5b870d6591 100644--- a/crates/graphql_notification/AGENTS.md+++ b/crates/graphql_notification/AGENTS.md@@ -27,7 +27,8 @@ mutations, and the realtime subscription.- Depends on: `notification`, `notification_state` (graphql feature),`model_notifications`, `graphql_common`.-- Used by: `complete_graph` (schema composition), `graphql_work_feed`.+- Used by: `complete_graph` (schema composition), `graphql_work_feed`,+ `graphql_notification_inbox`.## Recipesdiff --git a/crates/graphql_notification_inbox/AGENTS.md b/crates/graphql_notification_inbox/AGENTS.mdnew file mode 100644index 0000000000..b627881e64--- /dev/null+++ b/crates/graphql_notification_inbox/AGENTS.md@@ -0,0 +1,44 @@+# graphql_notification_inbox++## What it is++Belongs to the unified notifications inbox. This crate is the GraphQL+inbound adapter exposing `user.notificationInbox`, the done, undo and seen+mutations, and the `notificationInboxUpdates` subscription. Its shapes mirror+`graphql_work_feed`'s so the web's shared live feed client serves both.++## Start here++- `src/objects.rs`: page, entry, row and patch objects.+- `src/inputs.rs`: scope, row type and mutation inputs with their limits.+- `src/subscriptions.rs`: realtime patches, batched by `attention_feed`'s+ `live::coalesce` with `FiledEntity` triggers.+- `src/context.rs`: `NotificationInboxGraphqlContext`.++## Scope++- Owns: GraphQL types, resolvers and subscription for the inbox.+- Not here: row rules and inbox membership → `crates/notification_inbox`;+ notification content → `crates/graphql_notification`.++## Boundaries++- Depends on: `notification_inbox`, `attention_feed` (inbound feature),+ `graphql_notification`, `graphql_soup`, `graphql_common`.+- Used by: `complete_graph` (schema composition).++## Checks++- `cargo test -p graphql_notification_inbox`+- After changing the schema: regenerate `static_assets/schema.graphql`+ (`cargo run -p complete_graph --bin graphql_schema -- static_assets/schema.graphql`)+ and the web's generated GraphQL types, then `cargo x graphql-schema-compat`.++## Gotchas++- `NotificationInboxEntry` has no `id` (it is per scope); `NotificationInboxRow.id`+ is the normalized key and must stay globally consistent.++## Related++- Rules: `.agents/rules/rust/architecture.md`diff --git a/crates/graphql_notification_inbox/CLAUDE.md b/crates/graphql_notification_inbox/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/crates/graphql_notification_inbox/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/crates/graphql_notification_inbox/Cargo.toml b/crates/graphql_notification_inbox/Cargo.tomlnew file mode 100644index 0000000000..6552937fcb--- /dev/null+++ b/crates/graphql_notification_inbox/Cargo.toml@@ -0,0 +1,19 @@+[package]+edition = "2024"+name = "graphql_notification_inbox"+publish = false+version = "0.1.0"++[dependencies]+async-graphql = { workspace = true }+async-stream = { workspace = true }+attention_feed = { path = "../attention_feed", features = ["inbound"] }+futures = { workspace = true }+graphql_common = { path = "../graphql_common" }+graphql_notification = { path = "../graphql_notification" }+graphql_soup = { path = "../graphql_soup" }+macro_user_id = { path = "../macro_user_id" }+notification_inbox = { path = "../notification_inbox" }+soup = { path = "../soup", default-features = false, features = ["ports"] }+tracing = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/graphql_notification_inbox/src/context.rs b/crates/graphql_notification_inbox/src/context.rsnew file mode 100644index 0000000000..4fc9e4a8a7--- /dev/null+++ b/crates/graphql_notification_inbox/src/context.rs@@ -0,0 +1,171 @@+use std::sync::Arc;++use attention_feed::{+ domain::{+ models::{DoneReceipt, FeedError, FeedKey, FeedViewer},+ ports::FeedTriggers,+ },+ inbound::viewers::{FeedViewerResolver, resolve_viewer},+};+use futures::future::BoxFuture;+use macro_user_id::user_id::MacroUserIdStr;+use notification_inbox::domain::{+ models::{+ InboxChange, InboxDoneOutcome, InboxPage, InboxQuery, InboxRowId, InboxRowTarget,+ InboxScope,+ },+ service::NotificationInboxService,+};+use soup::domain::models::SoupProjectionHydration;++/// Soup-hydrated inbox changes.+type Changes = Vec<InboxChange<SoupProjectionHydration>>;++/// The inbox use cases over Soup-hydrated groups, object-safe so request+/// data can carry them without a schema type parameter.+pub trait NotificationInboxGraphqlService: Send + Sync + 'static {+ /// See [`NotificationInboxService::page`].+ fn page(+ &self,+ viewer: FeedViewer,+ query: InboxQuery,+ ) -> BoxFuture<'_, Result<InboxPage<SoupProjectionHydration>, FeedError>>;++ /// See [`NotificationInboxService::recompute`].+ fn recompute(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ groups: Vec<FeedKey>,+ ) -> BoxFuture<'_, Result<Changes, FeedError>>;++ /// See [`NotificationInboxService::mark_done`].+ fn mark_done(+ &self,+ viewer: FeedViewer,+ targets: Vec<InboxRowTarget>,+ ) -> BoxFuture<'_, Result<InboxDoneOutcome, FeedError>>;++ /// See [`NotificationInboxService::undo_done`].+ fn undo_done(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ receipt: DoneReceipt,+ ) -> BoxFuture<'_, Result<Changes, FeedError>>;++ /// See [`NotificationInboxService::mark_seen`].+ fn mark_seen(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ rows: Vec<InboxRowId>,+ ) -> BoxFuture<'_, Result<Changes, FeedError>>;+}++impl<T> NotificationInboxGraphqlService for T+where+ T: NotificationInboxService<Entity = SoupProjectionHydration>,+{+ fn page(+ &self,+ viewer: FeedViewer,+ query: InboxQuery,+ ) -> BoxFuture<'_, Result<InboxPage<SoupProjectionHydration>, FeedError>> {+ Box::pin(NotificationInboxService::page(self, viewer, query))+ }++ fn recompute(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ groups: Vec<FeedKey>,+ ) -> BoxFuture<'_, Result<Changes, FeedError>> {+ Box::pin(NotificationInboxService::recompute(+ self, viewer, scope, groups,+ ))+ }++ fn mark_done(+ &self,+ viewer: FeedViewer,+ targets: Vec<InboxRowTarget>,+ ) -> BoxFuture<'_, Result<InboxDoneOutcome, FeedError>> {+ Box::pin(NotificationInboxService::mark_done(self, viewer, targets))+ }++ fn undo_done(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ receipt: DoneReceipt,+ ) -> BoxFuture<'_, Result<Changes, FeedError>> {+ Box::pin(NotificationInboxService::undo_done(+ self, viewer, scope, receipt,+ ))+ }++ fn mark_seen(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ rows: Vec<InboxRowId>,+ ) -> BoxFuture<'_, Result<Changes, FeedError>> {+ Box::pin(NotificationInboxService::mark_seen(+ self, viewer, scope, rows,+ ))+ }+}++/// Request data for the inbox fields, inserted by the composition root for+/// HTTP requests and subscription connections alike.+#[derive(Clone)]+pub struct NotificationInboxGraphqlContext {+ /// The inbox's use cases.+ pub(crate) service: Arc<dyn NotificationInboxGraphqlService>,+ /// Realtime changes that may affect a viewer's groups.+ pub(crate) triggers: Arc<dyn FeedTriggers>,+ /// Team access lookup for viewers.+ pub(crate) viewers: Arc<dyn FeedViewerResolver>,+}++impl NotificationInboxGraphqlContext {+ /// Bundle the inbox's capabilities for request data. The triggers and+ /// viewer lookup are shared with the other attention feeds.+ pub fn new(+ service: impl NotificationInboxGraphqlService,+ triggers: Arc<dyn FeedTriggers>,+ viewers: Arc<dyn FeedViewerResolver>,+ ) -> Self {+ Self {+ service: Arc::new(service),+ triggers,+ viewers,+ }+ }++ /// The viewer a request for `user` is evaluated as.+ pub(crate) async fn viewer(+ &self,+ user: MacroUserIdStr<'static>,+ ) -> async_graphql::Result<FeedViewer> {+ resolve_viewer(self.viewers.as_ref(), user)+ .await+ .map_err(|error| {+ tracing::error!(error = ?error, "notification inbox viewer lookup failed");+ async_graphql::Error::new("the notification inbox is unavailable")+ })+ }+}++/// Map a service error to a client-facing GraphQL error; dependency details+/// are logged, never exposed.+pub(crate) fn to_graphql_error(error: FeedError) -> async_graphql::Error {+ match error {+ FeedError::InvalidInput(message) => async_graphql::Error::new(message),+ FeedError::Unavailable(report) => {+ tracing::error!(error = ?report, "notification inbox request failed");+ async_graphql::Error::new("the notification inbox is unavailable")+ }+ }+}diff --git a/crates/graphql_notification_inbox/src/inputs.rs b/crates/graphql_notification_inbox/src/inputs.rsnew file mode 100644index 0000000000..f5623fabc8--- /dev/null+++ b/crates/graphql_notification_inbox/src/inputs.rs@@ -0,0 +1,228 @@+use async_graphql::{Enum, ID, InputObject};+use attention_feed::domain::models::{FeedPosition, FeedRevision};+use notification_inbox::domain::models::{+ InboxQuery, InboxRowId, InboxRowTarget, InboxRowType, InboxScope,+};++#[cfg(test)]+mod test;++/// Entries returned by one inbox page when no limit is given.+pub const DEFAULT_INBOX_LIMIT: i32 = 50;+/// Most entries one inbox page may return.+pub const MAX_INBOX_LIMIT: i32 = 100;+/// Most rows one done or seen mutation may name.+pub const MAX_INBOX_ROWS: usize = 200;++/// The kinds of notification inbox row. Values are added as the inbox+/// learns new sources; present a value you do not know as a generic row.+#[derive(Enum, Clone, Copy, Debug, PartialEq, Eq)]+#[graphql(name = "NotificationInboxRowType")]+pub enum GraphqlNotificationInboxRowType {+ /// An agent session's or AI chat's latest response or question.+ Agent,+ /// An email thread.+ Email,+ /// A top-level channel message that mentions the viewer, with its thread.+ ChannelMention,+ /// A channel's top-level messages, reactions to them and invites.+ ChannelMessages,+ /// A channel thread's replies, mentions and reactions.+ ChannelThread,+ /// A top-level discussion comment that mentions the viewer, with its+ /// thread.+ DiscussionMention,+ /// An entity's top-level discussion comments.+ DiscussionMessages,+ /// One discussion thread's replies.+ DiscussionThread,+ /// A task assigned to the viewer.+ Task,+ /// A GitHub pull request's activity.+ PullRequest,+ /// Reminders of an upcoming calendar event.+ CalendarEvent,+ /// A request to join a calendar event the viewer shared.+ CalendarJoinRequest,+ /// A request for access to something the viewer can share.+ AccessRequested,+ /// Access the viewer requested was granted.+ AccessGranted,+}++impl From<GraphqlNotificationInboxRowType> for InboxRowType {+ fn from(value: GraphqlNotificationInboxRowType) -> Self {+ use GraphqlNotificationInboxRowType as G;+ match value {+ G::Agent => Self::Agent,+ G::Email => Self::Email,+ G::ChannelMention => Self::ChannelMention,+ G::ChannelMessages => Self::ChannelMessages,+ G::ChannelThread => Self::ChannelThread,+ G::DiscussionMention => Self::DiscussionMention,+ G::DiscussionMessages => Self::DiscussionMessages,+ G::DiscussionThread => Self::DiscussionThread,+ G::Task => Self::Task,+ G::PullRequest => Self::PullRequest,+ G::CalendarEvent => Self::CalendarEvent,+ G::CalendarJoinRequest => Self::CalendarJoinRequest,+ G::AccessRequested => Self::AccessRequested,+ G::AccessGranted => Self::AccessGranted,+ }+ }+}++impl From<InboxRowType> for GraphqlNotificationInboxRowType {+ fn from(value: InboxRowType) -> Self {+ use InboxRowType as D;+ match value {+ D::Agent => Self::Agent,+ D::Email => Self::Email,+ D::ChannelMention => Self::ChannelMention,+ D::ChannelMessages => Self::ChannelMessages,+ D::ChannelThread => Self::ChannelThread,+ D::DiscussionMention => Self::DiscussionMention,+ D::DiscussionMessages => Self::DiscussionMessages,+ D::DiscussionThread => Self::DiscussionThread,+ D::Task => Self::Task,+ D::PullRequest => Self::PullRequest,+ D::CalendarEvent => Self::CalendarEvent,+ D::CalendarJoinRequest => Self::CalendarJoinRequest,+ D::AccessRequested => Self::AccessRequested,+ D::AccessGranted => Self::AccessGranted,+ }+ }+}++/// Which rows a notification inbox shows. Pages, subscriptions, seen and+/// undo for one inbox send the same scope.+#[derive(InputObject, Default, Clone)]+pub struct NotificationInboxScopeInput {+ /// Row kinds to include; omitted or empty means every kind.+ pub row_types: Option<Vec<GraphqlNotificationInboxRowType>>,+}++impl NotificationInboxScopeInput {+ /// Convert into the domain scope.+ pub(crate) fn into_scope(self) -> InboxScope {+ InboxScope {+ row_types: self+ .row_types+ .unwrap_or_default()+ .into_iter()+ .map(Into::into)+ .collect(),+ }+ }+}++/// Page request for the viewer's notification inbox.+#[derive(InputObject, Default)]+pub struct NotificationInboxInput {+ /// Which rows the inbox shows.+ pub scope: Option<NotificationInboxScopeInput>,+ /// Entries per page; defaults to 50, capped at 100.+ pub limit: Option<i32>,+ /// Opaque cursor from the previous page's `nextCursor`; absent for the+ /// first page. Send it with the same scope.+ pub cursor: Option<String>,+}++impl NotificationInboxInput {+ /// Validate and convert into the domain query.+ pub(crate) fn into_query(self) -> async_graphql::Result<InboxQuery> {+ let limit = graphql_common::parse_limit(self.limit, DEFAULT_INBOX_LIMIT, MAX_INBOX_LIMIT)?;+ let after = self+ .cursor+ .map(|cursor| FeedPosition::decode(&cursor))+ .transpose()+ .map_err(|_| async_graphql::Error::new("invalid notification inbox cursor"))?;+ Ok(InboxQuery {+ scope: self.scope.unwrap_or_default().into_scope(),+ limit: u16::try_from(limit).expect("limit is capped below u16::MAX"),+ after,+ })+ }+}++/// Parse a row id, rejecting ids that name no row.+fn parse_row_id(id: &ID) -> async_graphql::Result<InboxRowId> {+ InboxRowId::parse(id)+ .map_err(|_| async_graphql::Error::new("invalid notification inbox row id"))+}++/// Reject a mutation naming more than [`MAX_INBOX_ROWS`] rows.+fn check_row_count(count: usize) -> async_graphql::Result<()> {+ if count > MAX_INBOX_ROWS {+ return Err(async_graphql::Error::new(format!(+ "at most {MAX_INBOX_ROWS} rows can be changed at once"+ )));+ }+ Ok(())+}++/// One row to mark done.+#[derive(InputObject)]+pub struct NotificationInboxRowTargetInput {+ /// The row's id.+ pub id: ID,+ /// The row's `revision` the caller observed. Notifications newer than it+ /// stay active. Omit to acknowledge everything current.+ pub revision: Option<String>,+}++/// Input for marking inbox rows done.+#[derive(InputObject)]+pub struct MarkNotificationInboxRowsDoneInput {+ /// The rows to complete, at most 200.+ pub rows: Vec<NotificationInboxRowTargetInput>,+}++impl MarkNotificationInboxRowsDoneInput {+ /// Validate and convert into domain row targets.+ pub(crate) fn into_targets(self) -> async_graphql::Result<Vec<InboxRowTarget>> {+ check_row_count(self.rows.len())?;+ self.rows+ .into_iter()+ .map(|row| {+ let revision = row+ .revision+ .map(|revision| FeedRevision::decode(&revision))+ .transpose()+ .map_err(|_| {+ async_graphql::Error::new("invalid notification inbox revision")+ })?;+ Ok(InboxRowTarget {+ id: parse_row_id(&row.id)?,+ revision,+ })+ })+ .collect()+ }+}++/// Input for undoing one mark-done.+#[derive(InputObject)]+pub struct UndoNotificationInboxRowsDoneInput {+ /// The `undoToken` the mark-done returned.+ pub undo_token: String,+ /// The inbox the restored groups are placed in.+ pub scope: Option<NotificationInboxScopeInput>,+}++/// Input for marking inbox rows seen.+#[derive(InputObject)]+pub struct MarkNotificationInboxRowsSeenInput {+ /// The rows to mark seen, at most 200.+ pub row_ids: Vec<ID>,+ /// The inbox the updated groups are placed in.+ pub scope: Option<NotificationInboxScopeInput>,+}++impl MarkNotificationInboxRowsSeenInput {+ /// Validate and convert into domain row ids.+ pub(crate) fn into_rows(self) -> async_graphql::Result<Vec<InboxRowId>> {+ check_row_count(self.row_ids.len())?;+ self.row_ids.iter().map(parse_row_id).collect()+ }+}diff --git a/crates/graphql_notification_inbox/src/inputs/test.rs b/crates/graphql_notification_inbox/src/inputs/test.rsnew file mode 100644index 0000000000..db6fd04517--- /dev/null+++ b/crates/graphql_notification_inbox/src/inputs/test.rs@@ -0,0 +1,83 @@+use super::*;++#[test]+fn inbox_input_defaults_to_every_row_type() {+ let query = NotificationInboxInput::default().into_query().unwrap();+ assert!(query.scope.row_types.is_empty());+ assert_eq!(query.limit, 50);+ assert!(query.after.is_none());+}++#[test]+fn inbox_input_rejects_bad_limits_and_cursors() {+ let too_many = NotificationInboxInput {+ limit: Some(101),+ ..Default::default()+ };+ assert!(too_many.into_query().is_err());++ let bad_cursor = NotificationInboxInput {+ cursor: Some("not a cursor".to_string()),+ ..Default::default()+ };+ assert!(bad_cursor.into_query().is_err());+}++#[test]+fn scope_input_maps_row_types() {+ let scope = NotificationInboxScopeInput {+ row_types: Some(vec![+ GraphqlNotificationInboxRowType::Agent,+ GraphqlNotificationInboxRowType::ChannelThread,+ ]),+ }+ .into_scope();+ assert_eq!(+ scope.row_types,+ vec![InboxRowType::Agent, InboxRowType::ChannelThread]+ );+}++const ROW: &str = "channel:11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa#top_level";++#[test]+fn done_input_parses_row_ids_and_revisions() {+ let revision = FeedRevision::default().encode();+ let targets = MarkNotificationInboxRowsDoneInput {+ rows: vec![NotificationInboxRowTargetInput {+ id: ID(ROW.to_string()),+ revision: Some(revision),+ }],+ }+ .into_targets()+ .unwrap();+ assert_eq!(targets[0].id.slot, "top_level");+ assert_eq!(targets[0].revision, Some(FeedRevision::default()));++ let bad_id = MarkNotificationInboxRowsDoneInput {+ rows: vec![NotificationInboxRowTargetInput {+ id: ID("channel:x".to_string()),+ revision: None,+ }],+ };+ assert!(bad_id.into_targets().is_err());++ let too_many = MarkNotificationInboxRowsDoneInput {+ rows: (0..=MAX_INBOX_ROWS)+ .map(|_| NotificationInboxRowTargetInput {+ id: ID(ROW.to_string()),+ revision: None,+ })+ .collect(),+ };+ assert!(too_many.into_targets().is_err());+}++#[test]+fn seen_input_is_capped() {+ let too_many = MarkNotificationInboxRowsSeenInput {+ row_ids: (0..=MAX_INBOX_ROWS).map(|_| ID(ROW.to_string())).collect(),+ scope: None,+ };+ assert!(too_many.into_rows().is_err());+}diff --git a/crates/graphql_notification_inbox/src/lib.rs b/crates/graphql_notification_inbox/src/lib.rsnew file mode 100644index 0000000000..65e542bff2--- /dev/null+++ b/crates/graphql_notification_inbox/src/lib.rs@@ -0,0 +1,40 @@+//! GraphQL inbound adapter for the notifications inbox: the+//! `notificationInbox` page under the viewer, the done, undo and seen+//! mutations, and the `notificationInboxUpdates` subscription. The shapes+//! mirror the work feed's, so one live feed client serves both. The schema+//! itself is composed by `complete_graph`.+#![deny(missing_docs)]+#![deny(clippy::missing_docs_in_private_items)]++/// Request data carrying the inbox service and the shared triggers and+/// viewer lookup.+mod context;+/// Inbox, scope and mutation inputs.+mod inputs;+/// Done, undo and seen mutations.+mod mutations;+/// Page, entry, row, actor, action and patch objects.+mod objects;+/// The `notificationInbox` page resolver.+mod query;+/// The `notificationInboxUpdates` subscription.+mod subscriptions;++pub use context::{NotificationInboxGraphqlContext, NotificationInboxGraphqlService};+pub use inputs::{+ GraphqlNotificationInboxRowType, MarkNotificationInboxRowsDoneInput,+ MarkNotificationInboxRowsSeenInput, NotificationInboxInput, NotificationInboxRowTargetInput,+ NotificationInboxScopeInput, UndoNotificationInboxRowsDoneInput,+};+pub use mutations::{+ MarkNotificationInboxRowsDonePayload, MarkNotificationInboxRowsSeenPayload,+ NotificationInboxMutationRoot, UndoNotificationInboxRowsDonePayload,+};+pub use objects::{+ GraphqlNotificationInboxActor, GraphqlNotificationInboxActorKind,+ GraphqlNotificationInboxEntry, GraphqlNotificationInboxPage, GraphqlNotificationInboxPatch,+ GraphqlNotificationInboxRow, GraphqlNotificationInboxRowAction,+ GraphqlNotificationInboxRowActionKind,+};+pub use query::resolve_notification_inbox;+pub use subscriptions::NotificationInboxSubscriptionRoot;diff --git a/crates/graphql_notification_inbox/src/mutations.rs b/crates/graphql_notification_inbox/src/mutations.rsnew file mode 100644index 0000000000..57f91e0b1b--- /dev/null+++ b/crates/graphql_notification_inbox/src/mutations.rs@@ -0,0 +1,129 @@+use std::marker::PhantomData;++use async_graphql::{Context, ID, Object, SimpleObject};+use attention_feed::domain::models::DoneReceipt;+use graphql_common::require_authenticated_user;+use graphql_soup::SoupEntityEdges;++use crate::{+ context::{NotificationInboxGraphqlContext, to_graphql_error},+ inputs::{+ MarkNotificationInboxRowsDoneInput, MarkNotificationInboxRowsSeenInput,+ UndoNotificationInboxRowsDoneInput,+ },+ objects::GraphqlNotificationInboxPatch,+};++/// The result of marking inbox rows done.+#[derive(SimpleObject)]+pub struct MarkNotificationInboxRowsDonePayload {+ /// The completed rows; remove them from every inbox. Rows that were+ /// already gone are included.+ row_ids: Vec<ID>,+ /// Opaque token that reverses exactly this operation.+ undo_token: String,+}++/// The result of undoing a mark-done.+#[derive(SimpleObject)]+pub struct UndoNotificationInboxRowsDonePayload<E: SoupEntityEdges> {+ /// The restored groups' places in the requested inbox.+ patches: Vec<GraphqlNotificationInboxPatch<E>>,+}++/// The result of marking inbox rows seen.+#[derive(SimpleObject)]+pub struct MarkNotificationInboxRowsSeenPayload<E: SoupEntityEdges> {+ /// The updated groups' places in the requested inbox.+ patches: Vec<GraphqlNotificationInboxPatch<E>>,+}++/// Root GraphQL adapter for notification inbox mutations.+pub struct NotificationInboxMutationRoot<E>(PhantomData<fn() -> E>);++impl<E> Default for NotificationInboxMutationRoot<E> {+ fn default() -> Self {+ Self(PhantomData)+ }+}++#[Object]+impl<E: SoupEntityEdges> NotificationInboxMutationRoot<E> {+ /// Mark notification inbox rows done for the authenticated user:+ /// acknowledge the notifications each row shows and hides, and archive+ /// an email row's thread. Notifications newer than a row's `revision`+ /// stay active. Tasks, requests, reviews and pull requests themselves+ /// are not completed.+ async fn mark_notification_inbox_rows_done(+ &self,+ ctx: &Context<'_>,+ input: MarkNotificationInboxRowsDoneInput,+ ) -> async_graphql::Result<MarkNotificationInboxRowsDonePayload> {+ let user = require_authenticated_user(ctx)?;+ let context = ctx.data::<NotificationInboxGraphqlContext>()?;+ let targets = input.into_targets()?;+ let viewer = context.viewer(user).await?;+ let outcome = context+ .service+ .mark_done(viewer, targets)+ .await+ .map_err(to_graphql_error)?;+ Ok(MarkNotificationInboxRowsDonePayload {+ row_ids: outcome.rows.iter().map(|row| ID(row.id())).collect(),+ undo_token: outcome.receipt.encode(),+ })+ }++ /// Reverse one mark-done for the authenticated user without overwriting+ /// anything that happened since, and return the restored groups' places+ /// in the requested inbox.+ async fn undo_notification_inbox_rows_done(+ &self,+ ctx: &Context<'_>,+ input: UndoNotificationInboxRowsDoneInput,+ ) -> async_graphql::Result<UndoNotificationInboxRowsDonePayload<E>> {+ let user = require_authenticated_user(ctx)?;+ let context = ctx.data::<NotificationInboxGraphqlContext>()?;+ let receipt = DoneReceipt::decode(&input.undo_token)+ .map_err(|_| async_graphql::Error::new("invalid notification inbox undo token"))?;+ let scope = input.scope.unwrap_or_default().into_scope();+ let viewer = context.viewer(user).await?;+ let changes = context+ .service+ .undo_done(viewer, scope, receipt)+ .await+ .map_err(to_graphql_error)?;+ Ok(UndoNotificationInboxRowsDonePayload {+ patches: changes+ .into_iter()+ .map(GraphqlNotificationInboxPatch::from)+ .collect(),+ })+ }++ /// Mark notification inbox rows seen for the authenticated user: the+ /// notifications each row shows and hides become read. Returns the+ /// updated groups' places in the requested inbox.+ async fn mark_notification_inbox_rows_seen(+ &self,+ ctx: &Context<'_>,+ input: MarkNotificationInboxRowsSeenInput,+ ) -> async_graphql::Result<MarkNotificationInboxRowsSeenPayload<E>> {+ let user = require_authenticated_user(ctx)?;+ let context = ctx.data::<NotificationInboxGraphqlContext>()?;+ let scope = input.scope.clone().unwrap_or_default().into_scope();+ let rows = input.into_rows()?;+ let viewer = context.viewer(user).await?;+ let changes = context+ .service+ .mark_seen(viewer, scope, rows)+ .await+ .map_err(to_graphql_error)?;+ Ok(MarkNotificationInboxRowsSeenPayload {+ patches: changes+ .into_iter()+ .map(GraphqlNotificationInboxPatch::from)+ .collect(),+ })+ }+}diff --git a/crates/graphql_notification_inbox/src/objects.rs b/crates/graphql_notification_inbox/src/objects.rsnew file mode 100644index 0000000000..e085836502--- /dev/null+++ b/crates/graphql_notification_inbox/src/objects.rs@@ -0,0 +1,366 @@+use async_graphql::{Enum, ID, Object, SimpleObject, Union};+use graphql_notification::GraphqlNotification;+use graphql_soup::{GraphqlSoupEntity, SoupEntityEdges};+use notification_inbox::domain::models::{+ InboxActor, InboxChange, InboxEntry, InboxPage, InboxRow, InboxRowAction, InboxRowActionKind,+};+use soup::domain::models::SoupProjectionHydration;++use crate::inputs::GraphqlNotificationInboxRowType;++/// Notifications one row returns when no limit is given.+const DEFAULT_ROW_NOTIFICATION_LIMIT: i32 = 20;+/// Most notifications one row may return.+const MAX_ROW_NOTIFICATION_LIMIT: i32 = 100;++/// The kind of principal a row is from. Values may be added; present one+/// you do not know without an author.+#[derive(Enum, Clone, Copy, Debug, PartialEq, Eq)]+#[graphql(name = "NotificationInboxActorKind")]+pub enum GraphqlNotificationInboxActorKind {+ /// A Macro user.+ User,+ /// An agent.+ Agent,+ /// Macro itself.+ Macro,+}++/// Who a row is from: a person, an agent, or Macro itself.+#[derive(SimpleObject)]+#[graphql(name = "NotificationInboxActor")]+pub struct GraphqlNotificationInboxActor {+ /// The kind of principal.+ kind: GraphqlNotificationInboxActorKind,+ /// The user id for a user, the bot id for an agent; absent for Macro.+ /// Not `id`: the client cache reads an `id` field as entity identity.+ principal_id: Option<String>,+ /// The display name when the row carries it (an agent's bot name);+ /// users are looked up by id.+ name: Option<String>,+}++impl From<InboxActor> for GraphqlNotificationInboxActor {+ fn from(actor: InboxActor) -> Self {+ match actor {+ InboxActor::User(user) => Self {+ kind: GraphqlNotificationInboxActorKind::User,+ principal_id: Some(user.as_ref().to_string()),+ name: None,+ },+ InboxActor::Agent { bot_id, name } => Self {+ kind: GraphqlNotificationInboxActorKind::Agent,+ principal_id: Some(bot_id.to_string()),+ name: Some(name),+ },+ InboxActor::Macro => Self {+ kind: GraphqlNotificationInboxActorKind::Macro,+ principal_id: None,+ name: None,+ },+ }+ }+}++/// What the viewer can do from a row. Values are added with the row types+/// that offer them; skip one you do not know.+#[derive(Enum, Clone, Copy, Debug, PartialEq, Eq)]+#[graphql(name = "NotificationInboxRowActionKind")]+pub enum GraphqlNotificationInboxRowActionKind {+ /// Open what the row is about.+ Open,+ /// Answer the agent that is waiting for the viewer.+ Answer,+ /// Review the pull request at `url`.+ Review,+ /// Grant the access request `targetId`.+ Approve,+ /// Refuse the access request `targetId`.+ Deny,+ /// Accept the join request `targetId`.+ Accept,+ /// Decline the join request `targetId`.+ Decline,+}++impl From<InboxRowActionKind> for GraphqlNotificationInboxRowActionKind {+ fn from(kind: InboxRowActionKind) -> Self {+ match kind {+ InboxRowActionKind::Open => Self::Open,+ InboxRowActionKind::Answer => Self::Answer,+ InboxRowActionKind::Review => Self::Review,+ InboxRowActionKind::Approve => Self::Approve,+ InboxRowActionKind::Deny => Self::Deny,+ InboxRowActionKind::Accept => Self::Accept,+ InboxRowActionKind::Decline => Self::Decline,+ }+ }+}++/// One thing the viewer can do from a row, described as data. Perform it+/// through the API of the thing it acts on; the inbox only says it is+/// available.+#[derive(SimpleObject)]+#[graphql(name = "NotificationInboxRowAction")]+pub struct GraphqlNotificationInboxRowAction {+ /// What the action does.+ kind: GraphqlNotificationInboxRowActionKind,+ /// What the action acts on when it is not the row's group: an access or+ /// join request.+ target_id: Option<ID>,+ /// The page the action opens outside Macro, such as a pull request.+ url: Option<String>,+}++impl From<InboxRowAction> for GraphqlNotificationInboxRowAction {+ fn from(action: InboxRowAction) -> Self {+ Self {+ kind: action.kind.into(),+ target_id: action.target_id.map(ID),+ url: action.url,+ }+ }+}++/// One inbox row.+pub struct GraphqlNotificationInboxRow(InboxRow);++/// One inbox row: the notifications shown together for one thread, a+/// channel's top level, an email thread, a task, a request or a review. A+/// row's contents depend only on the viewer's notifications, so one id is+/// one row in every scope.+#[Object(name = "NotificationInboxRow")]+impl GraphqlNotificationInboxRow {+ /// Stable per-viewer row id: `<groupId>#<slot>`. Opaque.+ async fn id(&self) -> ID {+ ID(self.0.id.id())+ }++ /// The row's kind.+ async fn row_type(&self) -> GraphqlNotificationInboxRowType {+ self.0.row_type.into()+ }++ /// For a thread row, the channel root message or discussion root+ /// comment it is about.+ async fn thread_id(&self) -> Option<&str> {+ self.0.thread_id.as_deref()+ }++ /// When the row's newest shown notification was created, in RFC 3339.+ async fn latest_at(&self) -> String {+ self.0.latest().created_at.to_rfc3339()+ }++ /// Who the row is from, per its newest shown notification; absent when+ /// that is no one in Macro (outside email senders, GitHub users).+ async fn actor(&self) -> Option<GraphqlNotificationInboxActor> {+ self.0.actor.clone().map(Into::into)+ }++ /// What the viewer can do from the row, in presentation order; empty+ /// when the row only opens.+ async fn actions(&self) -> Vec<GraphqlNotificationInboxRowAction> {+ self.0.actions.iter().cloned().map(Into::into).collect()+ }++ /// Whether the row is unread.+ async fn unseen(&self) -> bool {+ self.0.unseen+ }++ /// How many notifications the row shows.+ async fn count(&self) -> i32 {+ i32::try_from(self.0.notifications.len()).unwrap_or(i32::MAX)+ }++ /// Opaque token of what the row stands for; send it with done so+ /// notifications that arrive later stay active.+ async fn revision(&self) -> String {+ self.0.revision().encode()+ }++ /// The row's shown notifications, newest first. Defaults to 20, capped+ /// at 100; `count` is the full size.+ async fn notifications(+ &self,+ limit: Option<i32>,+ ) -> async_graphql::Result<Vec<GraphqlNotification>> {+ let limit = graphql_common::parse_limit(+ limit,+ DEFAULT_ROW_NOTIFICATION_LIMIT,+ MAX_ROW_NOTIFICATION_LIMIT,+ )?;+ Ok(self+ .0+ .notifications+ .iter()+ .take(limit as usize)+ .cloned()+ .map(GraphqlNotification::from)+ .collect())+ }+}++/// One group of the inbox in one scope.+pub struct GraphqlNotificationInboxEntry<E: SoupEntityEdges> {+ /// The group's id.+ group_id: String,+ /// The entity the rows are filed under.+ entity: GraphqlSoupEntity<E>,+ /// The entry's sort time.+ sort_at: String,+ /// The matching rows.+ rows: Vec<GraphqlNotificationInboxRow>,+}++/// The matching rows of the notifications filed under one entity. Entries+/// belong to one inbox scope and have no id of their own; rows are shared.+#[Object(name = "NotificationInboxEntry")]+impl<E: SoupEntityEdges> GraphqlNotificationInboxEntry<E> {+ /// The group the rows are filed under: `<entity type>:<entity id>`.+ async fn group_id(&self) -> ID {+ ID(self.group_id.clone())+ }++ /// The entity the rows are filed under.+ async fn entity(&self) -> &GraphqlSoupEntity<E> {+ &self.entity+ }++ /// Where the entry sits, in RFC 3339: the group's newest pending+ /// notification.+ async fn sort_at(&self) -> &str {+ &self.sort_at+ }++ /// The matching rows, newest first; never empty.+ async fn rows(&self) -> &[GraphqlNotificationInboxRow] {+ &self.rows+ }+}++impl<E: SoupEntityEdges> GraphqlNotificationInboxEntry<E> {+ /// Build the GraphQL entry for a domain entry.+ pub fn new(entry: InboxEntry<SoupProjectionHydration>) -> Self {+ Self {+ group_id: entry.group.id(),+ entity: GraphqlSoupEntity::new_with_projection(entry.entity),+ sort_at: entry.sort_at.to_rfc3339(),+ rows: entry+ .rows+ .into_iter()+ .map(GraphqlNotificationInboxRow)+ .collect(),+ }+ }+}++/// A place in the inbox's order: newest `sortAt` first, then entity id+/// descending.+#[derive(SimpleObject)]+#[graphql(name = "NotificationInboxPosition")]+pub struct GraphqlNotificationInboxPosition {+ /// The sort time, RFC 3339.+ sort_at: String,+ /// The entity id that breaks ties at `sortAt`.+ entity_id: String,+}++/// One page of the viewer's notification inbox, newest group first.+#[derive(SimpleObject)]+#[graphql(name = "NotificationInboxPage")]+pub struct GraphqlNotificationInboxPage<E: SoupEntityEdges> {+ /// The page's entries.+ entries: Vec<GraphqlNotificationInboxEntry<E>>,+ /// Cursor for the next page; absent once the inbox is exhausted.+ next_cursor: Option<String>,+ /// Where this page's read stopped, the position `nextCursor` resumes+ /// after; absent once the inbox is exhausted. A filtered page can read+ /// past its last entry, so a live change placed after that entry but not+ /// after this position belongs to this page rather than a later one.+ next_position: Option<GraphqlNotificationInboxPosition>,+}++impl<E: SoupEntityEdges> GraphqlNotificationInboxPage<E> {+ /// Build the GraphQL page for a domain page.+ pub fn new(page: InboxPage<SoupProjectionHydration>) -> Self {+ Self {+ entries: page+ .entries+ .into_iter()+ .map(GraphqlNotificationInboxEntry::new)+ .collect(),+ next_cursor: page.next.as_ref().map(|next| next.encode()),+ next_position: page.next.map(|next| GraphqlNotificationInboxPosition {+ sort_at: next.sort_at.to_rfc3339(),+ entity_id: next.entity_id,+ }),+ }+ }+}++/// A group that belongs in the subscribed inbox, with its current rows and+/// placement. Insert it, or move it to its new `sortAt`.+#[derive(SimpleObject)]+#[graphql(name = "NotificationInboxEntryUpserted")]+pub struct GraphqlNotificationInboxEntryUpserted<E: SoupEntityEdges> {+ /// The entry.+ entry: GraphqlNotificationInboxEntry<E>,+}++/// A group with no matching row left in the subscribed inbox: done,+/// filtered out or inaccessible. The entity itself is not necessarily+/// deleted.+#[derive(SimpleObject)]+#[graphql(name = "NotificationInboxEntryRemoved")]+pub struct GraphqlNotificationInboxEntryRemoved {+ /// The removed group's id.+ group_id: ID,+}++/// Changes may have been missed: refetch the inbox.+#[derive(SimpleObject)]+#[graphql(name = "NotificationInboxInvalidated")]+pub struct GraphqlNotificationInboxInvalidated {+ /// Always true.+ refresh: bool,+}++/// One change to an inbox's membership, placement or rows.+#[expect(+ clippy::large_enum_variant,+ reason = "upserts dominate and carry hydrated entries"+)]+#[derive(Union)]+#[graphql(name = "NotificationInboxPatch")]+pub enum GraphqlNotificationInboxPatch<E: SoupEntityEdges> {+ /// A group belongs in the inbox with these rows and this placement.+ Upserted(GraphqlNotificationInboxEntryUpserted<E>),+ /// A group no longer belongs in the inbox.+ Removed(GraphqlNotificationInboxEntryRemoved),+ /// The inbox must be refetched.+ Invalidated(GraphqlNotificationInboxInvalidated),+}++impl<E: SoupEntityEdges> GraphqlNotificationInboxPatch<E> {+ /// The patch announcing that changes may have been missed.+ pub fn invalidated() -> Self {+ Self::Invalidated(GraphqlNotificationInboxInvalidated { refresh: true })+ }+}++impl<E: SoupEntityEdges> From<InboxChange<SoupProjectionHydration>>+ for GraphqlNotificationInboxPatch<E>+{+ fn from(change: InboxChange<SoupProjectionHydration>) -> Self {+ match change {+ InboxChange::Upserted(entry) => Self::Upserted(GraphqlNotificationInboxEntryUpserted {+ entry: GraphqlNotificationInboxEntry::new(entry),+ }),+ InboxChange::Removed(group) => Self::Removed(GraphqlNotificationInboxEntryRemoved {+ group_id: ID(group.id()),+ }),+ }+ }+}diff --git a/crates/graphql_notification_inbox/src/query.rs b/crates/graphql_notification_inbox/src/query.rsnew file mode 100644index 0000000000..edf2fc50a6--- /dev/null+++ b/crates/graphql_notification_inbox/src/query.rs@@ -0,0 +1,26 @@+use async_graphql::Context;+use graphql_soup::SoupEntityEdges;+use macro_user_id::user_id::MacroUserIdStr;++use crate::{+ context::{NotificationInboxGraphqlContext, to_graphql_error},+ inputs::NotificationInboxInput,+ objects::GraphqlNotificationInboxPage,+};++/// Resolve one page of `user`'s notification inbox.+pub async fn resolve_notification_inbox<E: SoupEntityEdges>(+ ctx: &Context<'_>,+ user: MacroUserIdStr<'static>,+ input: NotificationInboxInput,+) -> async_graphql::Result<GraphqlNotificationInboxPage<E>> {+ let context = ctx.data::<NotificationInboxGraphqlContext>()?;+ let query = input.into_query()?;+ let viewer = context.viewer(user).await?;+ let page = context+ .service+ .page(viewer, query)+ .await+ .map_err(to_graphql_error)?;+ Ok(GraphqlNotificationInboxPage::new(page))+}diff --git a/crates/graphql_notification_inbox/src/subscriptions.rs b/crates/graphql_notification_inbox/src/subscriptions.rsnew file mode 100644index 0000000000..749ee42747--- /dev/null+++ b/crates/graphql_notification_inbox/src/subscriptions.rs@@ -0,0 +1,74 @@+use std::marker::PhantomData;++use async_graphql::{Context, Subscription};+use attention_feed::domain::{+ live::{COALESCE_WINDOW, coalesce},+ models::CandidateKeying,+};+use futures::{Stream, StreamExt};+use graphql_common::require_authenticated_user;+use graphql_soup::SoupEntityEdges;++use crate::{+ context::NotificationInboxGraphqlContext, inputs::NotificationInboxScopeInput,+ objects::GraphqlNotificationInboxPatch,+};++/// Root GraphQL adapter for the notification inbox subscription.+pub struct NotificationInboxSubscriptionRoot<E>(PhantomData<fn() -> E>);++impl<E> Default for NotificationInboxSubscriptionRoot<E> {+ fn default() -> Self {+ Self(PhantomData)+ }+}++#[Subscription]+impl<E: SoupEntityEdges> NotificationInboxSubscriptionRoot<E> {+ /// Changes to the authenticated user's notification inbox in `scope`:+ /// groups to insert or move with their current rows, groups to remove,+ /// and an invalidation when changes may have been missed. Each payload+ /// is one batch to apply together. Start it before fetching the first+ /// page and refetch after an invalidation; the stream ends with an error+ /// when its sources end, after which the client resubscribes and+ /// refetches.+ async fn notification_inbox_updates(+ &self,+ ctx: &Context<'_>,+ scope: Option<NotificationInboxScopeInput>,+ ) -> async_graphql::Result<+ impl Stream<Item = async_graphql::Result<Vec<GraphqlNotificationInboxPatch<E>>>> + 'static,+ > {+ let user = require_authenticated_user(ctx)?;+ let context = ctx.data::<NotificationInboxGraphqlContext>()?.clone();+ let scope = scope.unwrap_or_default().into_scope();+ let viewer = context.viewer(user.clone()).await?;+ let triggers = context+ .triggers+ .subscribe(user, CandidateKeying::FiledEntity, false);++ Ok(async_stream::stream! {+ let batches = coalesce(triggers, COALESCE_WINDOW);+ futures::pin_mut!(batches);+ while let Some(batch) = batches.next().await {+ if batch.invalidated {+ yield Ok(vec![GraphqlNotificationInboxPatch::invalidated()]);+ continue;+ }+ match context.service.recompute(viewer.clone(), scope.clone(), batch.keys).await {+ Ok(changes) if changes.is_empty() => {}+ Ok(changes) => {+ yield Ok(changes.into_iter().map(GraphqlNotificationInboxPatch::from).collect());+ }+ Err(error) => {+ tracing::error!(error = ?error, "notification inbox recompute failed");+ yield Ok(vec![GraphqlNotificationInboxPatch::invalidated()]);+ }+ }+ }+ yield Err(async_graphql::Error::new(+ "notification inbox subscription ended; resubscribe and refetch the inbox",+ ));+ })+ }+}diff --git a/crates/model_notifications/AGENTS.md b/crates/model_notifications/AGENTS.mdindex a06e9eaa40..de95978111 100644--- a/crates/model_notifications/AGENTS.md+++ b/crates/model_notifications/AGENTS.md@@ -31,7 +31,8 @@ types.`calendar_events`, `channels`, `complete_graph`, `document_cognition_service`,`document_storage_service`, `email_formatting`, `email_service`, `github`,`graphql_notification`, `graphql_work_feed`, `messages`, `notification_db_client`,- `notification_service`, `properties`, `reminders`, `teams`, `work_feed`.+ `notification_inbox`, `notification_service`, `properties`, `reminders`, `teams`,+ `work_feed`.## Recipesdiff --git a/crates/notification_inbox/AGENTS.md b/crates/notification_inbox/AGENTS.mdnew file mode 100644index 0000000000..a649a7504b--- /dev/null+++ b/crates/notification_inbox/AGENTS.md@@ -0,0 +1,60 @@+# notification_inbox++## What it is++The unified notifications inbox: the viewer's pending notifications grouped+by the entity they are filed under and cut into rows (one per conversation+thread, channel top level, email thread, task, pull request, request or+agent session). Built on the shared feed layer, `crates/attention_feed`.++## Start here++- `src/domain/rows.rs`: the row rules — every notification's home row,+ one message one row, noise hidden in its natural row.+- `src/domain/service.rs`: page, recompute, done, seen and undo.+- `src/domain/policy.rs`: which groups the inbox lists.++## Scope++- Owns: row kinds, row ids (`<group id>#<slot>`), shown and hidden+ notifications, row state and revision, inbox membership.+- Not here: paging, refill, done/seen/undo plumbing, live batching and+ adapters → `crates/attention_feed`; GraphQL → `crates/graphql_notification_inbox`;+ candidate SQL and access gates → `crates/soup` (`attention.rs`).++## Boundaries++- Depends on: `attention_feed`, `item_filters`, `filter_ast`,+ `model_notifications`.+- Used by: `graphql_notification_inbox`, `document_storage_service`+ (composition).++## Recipes++- Give a new notification kind a row: `place_event` (or the channel and+ discussion rules) in `src/domain/rows.rs` → a row type in+ `src/domain/models.rs` → `graphql_notification_inbox` inputs → a test in+ `rows/test.rs`. The `place_event` match is exhaustive on purpose.+- Offer a button on a row: `actions` in `src/domain/rows.rs` →+ `InboxRowActionKind` → its GraphQL enum. The client performs the action+ through the API of what it acts on.++## Checks++- `cargo test -p notification_inbox`++## Gotchas++- Groups use `CandidateKeying::FiledEntity`: a channel's group holds its+ threads, so channel rows partition the whole channel's notifications.+- Row types, actor kinds and action kinds only grow: add values, never+ repurpose or remove them; clients skip values they do not know.+- Only rows have an `id` in GraphQL; the client cache reads any `id` field as+ entity identity and requires `ID!`, so other inbox types use other names+ (`groupId`, `principalId`, `targetId`).+- Row contents must not depend on the scope; scopes only filter rows, so the+ web cache can normalize rows by id across inboxes.++## Related++- Rules: `.agents/rules/rust/architecture.md` · Docs: `docs/guides/add-notification-kind.md`diff --git a/crates/notification_inbox/CLAUDE.md b/crates/notification_inbox/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/crates/notification_inbox/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/crates/notification_inbox/Cargo.toml b/crates/notification_inbox/Cargo.tomlnew file mode 100644index 0000000000..207de1d589--- /dev/null+++ b/crates/notification_inbox/Cargo.toml@@ -0,0 +1,25 @@+[package]+edition = "2024"+name = "notification_inbox"+publish = false+version = "0.1.0"++[dependencies]+attention_feed = { path = "../attention_feed" }+chrono = { workspace = true }+filter_ast = { path = "../filter_ast" }+item_filters = { path = "../item_filters" }+macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }+model_notifications = { path = "../model_notifications" }+rootcause = { workspace = true }+thiserror = { workspace = true }+tracing = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+attention_feed = { path = "../attention_feed", features = ["test-utils"] }+notification = { path = "../notification" }+serde_json = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/crates/notification_inbox/src/domain.rs b/crates/notification_inbox/src/domain.rsnew file mode 100644index 0000000000..db97e510cd--- /dev/null+++ b/crates/notification_inbox/src/domain.rs@@ -0,0 +1,6 @@+//! Notification inbox domain: models, policy, rows and the service.++pub mod models;+pub mod policy;+pub mod rows;+pub mod service;diff --git a/crates/notification_inbox/src/domain/models.rs b/crates/notification_inbox/src/domain/models.rsnew file mode 100644index 0000000000..0b6287e31b--- /dev/null+++ b/crates/notification_inbox/src/domain/models.rs@@ -0,0 +1,255 @@+//! Notification inbox domain models: rows, entries and scopes. Keys, tokens,+//! viewers and errors are the shared feed layer's (`attention_feed`).++use attention_feed::domain::models::{+ DoneReceipt, FeedKey, FeedNotification, FeedPosition, FeedRevision,+};+use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++#[cfg(test)]+mod test;++/// The kinds of inbox row, which callers can narrow the inbox to. Kinds are+/// added as the inbox learns new sources; callers present a kind they do not+/// know as a generic row.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum InboxRowType {+ /// An agent session's or AI chat's latest response or question.+ Agent,+ /// An email thread.+ Email,+ /// A top-level channel message that mentions the viewer, with its thread.+ ChannelMention,+ /// A channel's top-level messages, a lone reaction to one, and invites.+ ChannelMessages,+ /// A channel thread's replies, mentions and reactions, with its root+ /// message and the reactions to it.+ ChannelThread,+ /// An entity's discussion comments, when one of them mentions the viewer.+ DiscussionMention,+ /// An entity's discussion comments.+ DiscussionMessages,+ /// One discussion thread's replies. No longer listed, since an entity's+ /// comments share one row; kept because row kinds only grow.+ DiscussionThread,+ /// A task assigned to the viewer.+ Task,+ /// A GitHub pull request's activity.+ PullRequest,+ /// Reminders of an upcoming calendar event.+ CalendarEvent,+ /// A request to join a calendar event the viewer shared.+ CalendarJoinRequest,+ /// A request for access to something the viewer can share.+ AccessRequested,+ /// Access the viewer requested was granted.+ AccessGranted,+}++/// A row's identity: the group it belongs to and its slot in the group,+/// `<group id>#<slot>`. A row's contents depend only on the viewer's+/// notifications, so one id names one row in every scope; the row type is+/// left out so a thread row keeps its id between mention and reply.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct InboxRowId {+ /// The group the row belongs to.+ pub group: FeedKey,+ /// The row's slot within the group.+ pub slot: String,+}++/// A row id that does not name a row.+#[derive(Debug, thiserror::Error)]+#[error("invalid notification inbox row id")]+pub struct InvalidInboxRowId;++impl InboxRowId {+ /// The row's global id.+ pub fn id(&self) -> String {+ format!("{}#{}", self.group.id(), self.slot)+ }++ /// Parse an id produced by [`Self::id`].+ pub fn parse(id: &str) -> Result<Self, InvalidInboxRowId> {+ let (group, slot) = id.split_once('#').ok_or(InvalidInboxRowId)?;+ if slot.is_empty() {+ return Err(InvalidInboxRowId);+ }+ Ok(Self {+ group: FeedKey::parse(group).map_err(|_| InvalidInboxRowId)?,+ slot: slot.to_string(),+ })+ }+}++/// Who a row is from: a person, an agent, or Macro itself.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum InboxActor {+ /// A Macro user.+ User(MacroUserIdStr<'static>),+ /// An agent, by the bot it runs as.+ Agent {+ /// The bot.+ bot_id: Uuid,+ /// The bot's display name.+ name: String,+ },+ /// Macro itself: reminders and AI chat responses.+ Macro,+}++/// What the viewer can do from a row. Kinds are added with the row types+/// that offer them; callers skip a kind they do not know.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum InboxRowActionKind {+ /// Open what the row is about.+ Open,+ /// Answer the agent that is waiting for the viewer.+ Answer,+ /// Review the pull request.+ Review,+ /// Grant the access requested.+ Approve,+ /// Refuse the access requested.+ Deny,+ /// Accept the request to join the event.+ Accept,+ /// Decline the request to join the event.+ Decline,+}++/// One thing the viewer can do from a row, described as data. The caller+/// performs it through the API of the thing it acts on; the inbox only says+/// it is available.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct InboxRowAction {+ /// What the action does.+ pub kind: InboxRowActionKind,+ /// What the action acts on when it is not the row's group: an access or+ /// join request.+ pub target_id: Option<String>,+ /// The page the action opens outside Macro, such as a pull request.+ pub url: Option<String>,+}++/// One inbox row: the notifications shown together for one slot of a group.+#[derive(Debug, Clone)]+pub struct InboxRow {+ /// The row's identity.+ pub id: InboxRowId,+ /// The row's kind.+ pub row_type: InboxRowType,+ /// For a thread row, the channel root message or discussion root comment.+ pub thread_id: Option<String>,+ /// Who the row is from, per its newest shown notification; `None` when+ /// that is no one in Macro (outside email senders, GitHub users).+ pub actor: Option<InboxActor>,+ /// What the viewer can do from the row, in presentation order.+ pub actions: Vec<InboxRowAction>,+ /// The notifications the row shows, newest first; never empty.+ pub notifications: Vec<FeedNotification>,+ /// Notifications the row stands for without showing them: those another+ /// notification about the same message speaks for, and noise. Done and+ /// seen act on them with the row.+ pub hidden: Vec<FeedNotification>,+ /// Whether the row is unread.+ pub unseen: bool,+}++impl InboxRow {+ /// The newest notification the row shows.+ pub fn latest(&self) -> &FeedNotification {+ &self.notifications[0]+ }++ /// Every notification the row stands for, shown then hidden.+ pub fn all_notifications(&self) -> impl Iterator<Item = &FeedNotification> {+ self.notifications.iter().chain(&self.hidden)+ }++ /// What marking the row done acknowledges: everything it stands for up+ /// to its newest notification, shown or hidden.+ pub fn revision(&self) -> FeedRevision {+ FeedRevision::covering(self.all_notifications())+ }+}++/// One group of the inbox: the matching rows of the notifications filed+/// under one entity.+#[derive(Debug, Clone)]+pub struct InboxEntry<E> {+ /// The entity the rows are filed under.+ pub group: FeedKey,+ /// The hydrated entity.+ pub entity: E,+ /// Where the entry sits: the group's newest pending notification.+ pub sort_at: DateTime<Utc>,+ /// The matching rows, newest first; never empty.+ pub rows: Vec<InboxRow>,+}++/// Which rows one inbox shows.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct InboxScope {+ /// The row kinds to include; empty means every kind.+ pub row_types: Vec<InboxRowType>,+}++impl InboxScope {+ /// Whether the scope lists rows of `row_type`.+ pub fn admits(&self, row_type: InboxRowType) -> bool {+ self.row_types.is_empty() || self.row_types.contains(&row_type)+ }+}++/// A request for one page of the inbox.+#[derive(Debug, Clone)]+pub struct InboxQuery {+ /// Which rows the inbox shows.+ pub scope: InboxScope,+ /// Maximum entries on the page.+ pub limit: u16,+ /// Resume after this position; `None` for the first page.+ pub after: Option<FeedPosition>,+}++/// One page of the inbox, newest first.+#[derive(Debug)]+pub struct InboxPage<E> {+ /// The page's entries.+ pub entries: Vec<InboxEntry<E>>,+ /// Where the next page starts; `None` once the inbox is exhausted.+ pub next: Option<FeedPosition>,+}++/// How a known group changed for one inbox.+#[derive(Debug)]+pub enum InboxChange<E> {+ /// The group belongs in the inbox with these rows and this placement.+ Upserted(InboxEntry<E>),+ /// The group no longer has a matching row: done, filtered out or+ /// inaccessible. The entity itself may still exist.+ Removed(FeedKey),+}++/// A row the caller asked to mark done, with what they observed.+#[derive(Debug, Clone)]+pub struct InboxRowTarget {+ /// The row.+ pub id: InboxRowId,+ /// The row's revision the caller observed; `None` acknowledges+ /// everything current.+ pub revision: Option<FeedRevision>,+}++/// The outcome of marking rows done.+#[derive(Debug)]+pub struct InboxDoneOutcome {+ /// The rows now done; requested rows that were already gone are+ /// reported done as well, so callers can drop them.+ pub rows: Vec<InboxRowId>,+ /// What the operation changed, for undo.+ pub receipt: DoneReceipt,+}diff --git a/crates/notification_inbox/src/domain/models/test.rs b/crates/notification_inbox/src/domain/models/test.rsnew file mode 100644index 0000000000..54360a63a8--- /dev/null+++ b/crates/notification_inbox/src/domain/models/test.rs@@ -0,0 +1,38 @@+use attention_feed::test_support::uuid;+use model_entity::EntityType;++use super::*;++#[test]+fn row_ids_round_trip() {+ let id = InboxRowId {+ group: FeedKey::new(EntityType::Channel.with_entity_string(uuid(1).to_string())),+ slot: format!("thread:{}", uuid(2)),+ };+ let text = id.id();+ assert_eq!(text, format!("channel:{}#thread:{}", uuid(1), uuid(2)));+ assert_eq!(InboxRowId::parse(&text).unwrap(), id);+}++#[test]+fn malformed_row_ids_are_rejected() {+ for id in [+ "",+ "channel:x",+ "channel:x#",+ "#top_level",+ "not_a_type:x#top_level",+ ] {+ assert!(InboxRowId::parse(id).is_err(), "{id} parsed");+ }+}++#[test]+fn an_empty_scope_admits_every_row_type() {+ assert!(InboxScope::default().admits(InboxRowType::Email));+ let scope = InboxScope {+ row_types: vec![InboxRowType::Task],+ };+ assert!(scope.admits(InboxRowType::Task));+ assert!(!scope.admits(InboxRowType::Email));+}diff --git a/crates/notification_inbox/src/domain/policy.rs b/crates/notification_inbox/src/domain/policy.rsnew file mode 100644index 0000000000..d9a590e4e2--- /dev/null+++ b/crates/notification_inbox/src/domain/policy.rs@@ -0,0 +1,76 @@+//! Membership policy: which groups may appear in the inbox at all.+//!+//! Rows come from the viewer's pending notifications; this policy narrows+//! the entities they are filed under the way the inbox promises, and Soup's+//! access gates drop anything the viewer can no longer open.++use std::sync::Arc;++use filter_ast::Expr;+use item_filters::{+ SharedEmailFilter,+ ast::{+ EmailFilterAst, EntityFilterAst,+ agent_session::{AgentSessionLiteral, AgentSessionVisibility},+ email::EmailLiteral,+ foreign_entity::ForeignEntityLiteral,+ initiative::InitiativeLiteral,+ },+};+use model_entity::EntityType;++#[cfg(test)]+mod test;++/// The only foreign entities the inbox lists.+const GITHUB_PULL_REQUEST_SOURCE: &str = "github_pull_request";++/// The entities inbox groups are filed under. Channel threads are never+/// their own group: a channel's group holds its threads.+pub const CANDIDATE_TYPES: [EntityType; 11] = [+ EntityType::Document,+ EntityType::Chat,+ EntityType::Project,+ EntityType::EmailThread,+ EntityType::Channel,+ EntityType::CalendarEvent,+ EntityType::ForeignEntity,+ EntityType::AgentSession,+ EntityType::Initiative,+ EntityType::CrmCompany,+ EntityType::CrmContact,+];++/// The inbox membership filter.+///+/// - Email is Signal-classified and the viewer's own (not shared) mail.+/// - Pull requests include the viewer.+/// - Agent sessions are opted in (Soup excludes them by default), except+/// unlisted ones, whose runs live in their routine's history.+/// - Projects (initiatives) are opted in, so their discussions are listed.+/// - Snippets are documents like any other.+pub fn inbox_filter() -> EntityFilterAst {+ EntityFilterAst {+ email_filter: EmailFilterAst {+ tree: Some(Arc::new(Expr::and(+ Expr::val(EmailLiteral::Importance(true)),+ Expr::val(EmailLiteral::Shared(SharedEmailFilter::Exclude)),+ ))),+ crm_scope: None,+ },+ foreign_entity_filter: Some(Arc::new(Expr::and(+ Expr::val(ForeignEntityLiteral::ForeignEntitySource(+ GITHUB_PULL_REQUEST_SOURCE.to_string(),+ )),+ Expr::val(ForeignEntityLiteral::IncludesMe),+ ))),+ agent_session_filter: Some(Arc::new(Expr::and(+ Expr::val(AgentSessionLiteral::Include),+ Expr::is_not(Expr::val(AgentSessionLiteral::Visibility(+ AgentSessionVisibility::Unlisted,+ ))),+ ))),+ initiative_filter: Some(Arc::new(Expr::val(InitiativeLiteral::Include))),+ ..Default::default()+ }+}diff --git a/crates/notification_inbox/src/domain/policy/test.rs b/crates/notification_inbox/src/domain/policy/test.rsnew file mode 100644index 0000000000..8efb324482--- /dev/null+++ b/crates/notification_inbox/src/domain/policy/test.rs@@ -0,0 +1,20 @@+use super::*;++#[test]+fn the_inbox_lists_signal_mail_prs_listed_agents_and_projects() {+ let filter = inbox_filter();+ assert!(filter.document_filter.is_none(), "snippets are included");+ assert!(filter.email_filter.tree.is_some());+ assert!(filter.foreign_entity_filter.is_some());+ assert!(+ filter.agent_session_filter.is_some(),+ "agent sessions are opted in"+ );+ assert!(filter.initiative_filter.is_some(), "projects are opted in");+}++#[test]+fn channel_threads_are_never_groups() {+ assert!(!CANDIDATE_TYPES.contains(&EntityType::ChannelMessage));+ assert!(CANDIDATE_TYPES.contains(&EntityType::Channel));+}diff --git a/crates/notification_inbox/src/domain/rows.rs b/crates/notification_inbox/src/domain/rows.rsnew file mode 100644index 0000000000..838696451f--- /dev/null+++ b/crates/notification_inbox/src/domain/rows.rs@@ -0,0 +1,640 @@+//! Inbox rows: how one group's notifications are cut into rows.+//!+//! A group is the viewer's pending notifications filed under one entity. A+//! channel's group holds its top level and every thread, so each channel+//! notification has exactly one home: the channel's top-level row or one+//! thread row. Every other notification lives in its entity's slot (a+//! discussion thread, the email thread, the task, one access request, ...).+//! Within its home a notification is shown or hidden:+//!+//! - **One message, one row.** A channel message or discussion comment that+//! produced several notifications for the viewer is shown once, by the+//! highest of mention, reply, plain message or comment, then document+//! mention. The others are hidden in that row, so completing the row+//! acknowledges them too.+//! - **One top-level message, one stack.** Everything about a top-level+//! channel message stacks on its thread row once there is more than one+//! thing: replies, mentions in them, and reactions to the message itself.+//! - **One entity, one stack of comments.** All of an entity's comments stack+//! on one row, whichever thread they are in.+//! - **Noise is hidden in its natural row:** calls starting, successful+//! pull request checks, reminders for events that have ended, and document+//! mentions of documents the viewer does not own.+//!+//! A row is listed only while it shows something. Team invites, inbox+//! reconnection notices and external chat messages have no row at all. Each+//! row also says who it is from and what the viewer can do from it.++use std::collections::{HashMap, HashSet};++use attention_feed::domain::models::{+ FeedKey, FeedNotification, MailFacts, counts_as_unseen, sort_newest_first,+};+use chrono::{DateTime, Days, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use model_notifications::{+ AgentSessionNotificationRef, CalendarEventReminderMetadata, CrmDiscussionReason,+ GithubPrCheckRunState, InitiativeDiscussionReason, NotifEvent,+};+use uuid::Uuid;++use super::models::{+ InboxActor, InboxRow, InboxRowAction, InboxRowActionKind, InboxRowId, InboxRowType,+};++#[cfg(test)]+mod test;++/// A row slot within one group.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+enum Slot {+ /// A channel's or an entity's top-level discussion activity.+ TopLevel,+ /// One channel thread or discussion thread, by its root.+ Thread(String),+ Email,+ Agent,+ Task,+ PullRequest,+ CalendarEvent,+ CalendarJoinRequest(Uuid),+ AccessRequested(Uuid),+ AccessGranted(Uuid),+}++impl Slot {+ /// The slot's part of a row id.+ fn id(&self) -> String {+ match self {+ Self::TopLevel => "top_level".to_string(),+ Self::Thread(root) => format!("thread:{root}"),+ Self::Email => "email".to_string(),+ Self::Agent => "agent".to_string(),+ Self::Task => "task".to_string(),+ Self::PullRequest => "pull_request".to_string(),+ Self::CalendarEvent => "calendar_event".to_string(),+ Self::CalendarJoinRequest(id) => format!("calendar_join_request:{id}"),+ Self::AccessRequested(id) => format!("access_requested:{id}"),+ Self::AccessGranted(id) => format!("access_granted:{id}"),+ }+ }+}++/// A notification placed in its home slot.+#[derive(Debug, Clone)]+struct Placed {+ notification: FeedNotification,+ slot: Slot,+ shown: bool,+ /// A mention that makes its row a mention row: of a channel thread's+ /// root message, or anywhere in an entity's comments.+ mention: bool,+}++/// What a notification says about a channel message or discussion comment,+/// for one-message-one-row.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum MessageRole {+ Mention,+ Reply,+ Message,+ DocumentMention,+}++/// A channel notification, normalized.+struct ChannelView<'a> {+ notification: &'a FeedNotification,+ kind: ChannelKind<'a>,+}++enum ChannelKind<'a> {+ /// A message-shaped notification: a mention, reply, plain send or+ /// document mention of one message.+ Message {+ role: MessageRole,+ message_id: &'a str,+ thread_id: Option<&'a str>,+ /// For a document mention: the viewer owns the document.+ own_document: bool,+ },+ /// A reaction to one of the viewer's messages.+ Reaction {+ message_id: &'a str,+ thread_id: Option<&'a str>,+ },+ /// An invite to the channel.+ Invite,+ /// Anything else filed under the channel, such as a call starting.+ Quiet,+}++fn channel_view<'a>(+ notification: &'a FeedNotification,+ viewer: &MacroUserIdStr<'static>,+) -> ChannelView<'a> {+ let message = |role, message_id: &'a str, thread_id: Option<&'a str>| ChannelKind::Message {+ role,+ message_id,+ thread_id: thread_id.filter(|thread| !thread.is_empty()),+ own_document: false,+ };+ let kind = match ¬ification.notification_metadata {+ NotifEvent::ChannelMention(mention) => message(+ MessageRole::Mention,+ &mention.message_id,+ mention.thread_id.as_deref(),+ ),+ NotifEvent::ChannelMessageReply(reply) => message(+ MessageRole::Reply,+ &reply.message_id,+ Some(reply.thread_id.as_str()),+ ),+ NotifEvent::ChannelMessageSend(send) => {+ message(MessageRole::Message, &send.message_id, None)+ }+ NotifEvent::DocumentMention(mention) => ChannelKind::Message {+ role: MessageRole::DocumentMention,+ message_id: &mention.channel.message_id,+ thread_id: mention+ .channel+ .thread_id+ .as_deref()+ .filter(|thread| !thread.is_empty()),+ own_document: mention.owner == viewer.clone().into(),+ },+ NotifEvent::ChannelMessageReaction(reaction) => ChannelKind::Reaction {+ message_id: &reaction.message_id,+ thread_id: reaction+ .thread_id+ .as_deref()+ .filter(|thread| !thread.is_empty()),+ },+ NotifEvent::ChannelInvite(_) => ChannelKind::Invite,+ _ => ChannelKind::Quiet,+ };+ ChannelView { notification, kind }+}++/// The notification that speaks for one message.+#[derive(Debug, Clone, Copy)]+struct Speaker<'a> {+ role: MessageRole,+ notification_id: Uuid,+ thread_id: Option<&'a str>,+}++/// Place a channel's notifications on its top level and its threads.+fn place_channel(+ notifications: &[FeedNotification],+ viewer: &MacroUserIdStr<'static>,+) -> Vec<Placed> {+ let views: Vec<ChannelView<'_>> = notifications+ .iter()+ .map(|notification| channel_view(notification, viewer))+ .collect();++ // Threads with replies or mentions in their replies absorb their root.+ let mut active: HashSet<&str> = views+ .iter()+ .filter_map(|view| match view.kind {+ ChannelKind::Message {+ role: MessageRole::Reply | MessageRole::Mention,+ thread_id: Some(thread),+ ..+ } => Some(thread),+ _ => None,+ })+ .collect();++ // The notification that speaks for each message, with the thread it+ // names.+ let mut speakers: HashMap<&str, Speaker<'_>> = HashMap::new();+ for view in &views {+ if let ChannelKind::Message {+ role,+ message_id,+ thread_id,+ ..+ } = view.kind+ {+ let candidate = Speaker {+ role,+ notification_id: view.notification.notification_id,+ thread_id,+ };+ speakers+ .entry(message_id)+ .and_modify(|speaker| {+ if role < speaker.role {+ *speaker = candidate;+ }+ })+ .or_insert(candidate);+ }+ }++ // A top-level message with a reaction and anything else about it is a+ // stack of its own, so its reactions don't land on the channel's row.+ let mut reactions: HashMap<&str, usize> = HashMap::new();+ for view in &views {+ if let ChannelKind::Reaction {+ message_id,+ thread_id: None,+ } = view.kind+ {+ *reactions.entry(message_id).or_default() += 1;+ }+ }+ active.extend(+ reactions+ .iter()+ .filter(|(message, count)| **count > 1 || speakers.contains_key(*message))+ .map(|(message, _)| *message),+ );++ let thread = |root: &str| Slot::Thread(root.to_string());+ views+ .iter()+ .map(|view| {+ let (slot, shown, mention) = match view.kind {+ ChannelKind::Message {+ message_id,+ own_document,+ ..+ } => {+ let speaker = speakers[message_id];+ let slot = match (speaker.role, speaker.thread_id) {+ (_, Some(root)) => thread(root),+ (MessageRole::Mention, None) => thread(message_id),+ (_, None) if active.contains(message_id) => thread(message_id),+ (_, None) => Slot::TopLevel,+ };+ let speaks = speaker.notification_id == view.notification.notification_id;+ let shown =+ speaks && (speaker.role != MessageRole::DocumentMention || own_document);+ let mention = speaks+ && speaker.role == MessageRole::Mention+ && speaker.thread_id.is_none();+ (slot, shown, mention)+ }+ ChannelKind::Reaction {+ thread_id: Some(root),+ ..+ } => (thread(root), true, false),+ ChannelKind::Reaction {+ message_id,+ thread_id: None,+ } if active.contains(message_id) => (thread(message_id), true, false),+ ChannelKind::Reaction { .. } | ChannelKind::Invite => (Slot::TopLevel, true, false),+ ChannelKind::Quiet => (Slot::TopLevel, false, false),+ };+ Placed {+ notification: view.notification.clone(),+ slot,+ shown,+ mention,+ }+ })+ .collect()+}++/// A discussion notification, normalized: its comment and role.+struct DiscussionView<'a> {+ notification: &'a FeedNotification,+ role: MessageRole,+ comment_id: String,+}++fn discussion_view(notification: &FeedNotification) -> Option<DiscussionView<'_>> {+ let comment_role = |comment: &str, thread: &str| {+ if comment == thread {+ MessageRole::Message+ } else {+ MessageRole::Reply+ }+ };+ let (role, comment_id) = match ¬ification.notification_metadata {+ NotifEvent::CommentedOnDocument(comment) => {+ let (comment_id, thread_id) = (+ comment.comment_id.to_string(),+ comment.thread_id.to_string(),+ );+ (comment_role(&comment_id, &thread_id), comment_id)+ }+ NotifEvent::RepliedToDocumentCommentThread(reply) => {+ (MessageRole::Reply, reply.comment_id.to_string())+ }+ NotifEvent::MentionedInDocumentComment(mention) => {+ (MessageRole::Mention, mention.comment_id.to_string())+ }+ NotifEvent::InitiativeDiscussion(discussion) => {+ let (comment_id, thread_id) = (+ discussion.message_id.to_string(),+ discussion.thread_id.to_string(),+ );+ let role = match discussion.reason {+ InitiativeDiscussionReason::Mention => MessageRole::Mention,+ _ => comment_role(&comment_id, &thread_id),+ };+ (role, comment_id)+ }+ NotifEvent::CrmDiscussion(discussion) => {+ let (comment_id, thread_id) = (+ discussion.message_id.to_string(),+ discussion.thread_id.to_string(),+ );+ let role = match discussion.reason {+ CrmDiscussionReason::Mention => MessageRole::Mention,+ _ => comment_role(&comment_id, &thread_id),+ };+ (role, comment_id)+ }+ _ => return None,+ };+ Some(DiscussionView {+ notification,+ role,+ comment_id,+ })+}++/// Place an entity's discussion notifications on its one row of comments.+fn place_discussions(views: Vec<DiscussionView<'_>>) -> Vec<Placed> {+ let mut speakers: HashMap<&str, (MessageRole, Uuid)> = HashMap::new();+ for view in &views {+ let candidate = (view.role, view.notification.notification_id);+ speakers+ .entry(view.comment_id.as_str())+ .and_modify(|speaker| {+ if view.role < speaker.0 {+ *speaker = candidate;+ }+ })+ .or_insert(candidate);+ }+ views+ .iter()+ .map(|view| {+ let (role, speaker) = speakers[view.comment_id.as_str()];+ let speaks = speaker == view.notification.notification_id;+ Placed {+ notification: view.notification.clone(),+ slot: Slot::TopLevel,+ shown: speaks,+ mention: speaks && role == MessageRole::Mention,+ }+ })+ .collect()+}++/// Whether a calendar reminder's occurrence has ended by `now`. An all-day+/// occurrence counts as ended a day after its date, whatever the viewer's+/// zone.+fn occurrence_ended(reminder: &CalendarEventReminderMetadata, now: DateTime<Utc>) -> bool {+ match (reminder.ends_at, reminder.start_date) {+ (Some(ends_at), _) => ends_at < now,+ (None, Some(start_date)) => start_date+ .checked_add_days(Days::new(2))+ .is_some_and(|after| after <= now.date_naive()),+ (None, None) => false,+ }+}++/// The slot and visibility of a notification that is neither channel+/// activity nor discussion. `None` for kinds the inbox never shows.+fn place_event(notification: &FeedNotification, now: DateTime<Utc>) -> Option<(Slot, bool)> {+ Some(match ¬ification.notification_metadata {+ NotifEvent::EntityAccessRequested(request) => {+ (Slot::AccessRequested(request.request_id), true)+ }+ NotifEvent::EntityAccessGranted(grant) => (Slot::AccessGranted(grant.request_id), true),+ NotifEvent::NewEmail(_) | NotifEvent::Reminder(_) => (Slot::Email, true),+ NotifEvent::TaskAssigned(_) => (Slot::Task, true),+ NotifEvent::CalendarEventReminder(reminder) => {+ (Slot::CalendarEvent, !occurrence_ended(reminder, now))+ }+ NotifEvent::CalendarEventJoinRequest(request) => {+ (Slot::CalendarJoinRequest(request.request_id), true)+ }+ NotifEvent::AiResponse(_)+ | NotifEvent::AgentSessionSettled(_)+ | NotifEvent::AgentSessionWaitingForInput(_)+ | NotifEvent::AgentSessionMentioned(_) => (Slot::Agent, true),+ NotifEvent::GithubPrCheckRun(check) => (+ Slot::PullRequest,+ check.state != GithubPrCheckRunState::Completed,+ ),+ NotifEvent::GithubPrStatusChanged(_)+ | NotifEvent::GithubReviewRequested(_)+ | NotifEvent::GithubPrComment(_)+ | NotifEvent::GithubPrMention(_)+ | NotifEvent::GithubPrReview(_) => (Slot::PullRequest, true),+ NotifEvent::InboxReauthRequired(_)+ | NotifEvent::InviteToTeam(_)+ | NotifEvent::ExternalChatMessage(_)+ | NotifEvent::RoutineRunFinished(_) => return None,+ // Channel activity and discussions are placed by their own rules; on+ // any other entity they have no row.+ NotifEvent::ChannelMention(_)+ | NotifEvent::DocumentMention(_)+ | NotifEvent::ChannelMessageSend(_)+ | NotifEvent::ChannelMessageReply(_)+ | NotifEvent::ChannelMessageReaction(_)+ | NotifEvent::ChannelInvite(_)+ | NotifEvent::CallStarted(_)+ | NotifEvent::MentionedInDocumentComment(_)+ | NotifEvent::RepliedToDocumentCommentThread(_)+ | NotifEvent::CommentedOnDocument(_)+ | NotifEvent::InitiativeDiscussion(_)+ | NotifEvent::CrmDiscussion(_) => return None,+ })+}++fn row_type(slot: &Slot, channel: bool, mention: bool) -> InboxRowType {+ match (slot, channel, mention) {+ (Slot::TopLevel, true, _) => InboxRowType::ChannelMessages,+ (Slot::TopLevel, false, true) => InboxRowType::DiscussionMention,+ (Slot::TopLevel, false, false) => InboxRowType::DiscussionMessages,+ (Slot::Thread(_), true, true) => InboxRowType::ChannelMention,+ (Slot::Thread(_), true, false) => InboxRowType::ChannelThread,+ (Slot::Thread(_), false, true) => InboxRowType::DiscussionMention,+ (Slot::Thread(_), false, false) => InboxRowType::DiscussionThread,+ (Slot::Email, ..) => InboxRowType::Email,+ (Slot::Agent, ..) => InboxRowType::Agent,+ (Slot::Task, ..) => InboxRowType::Task,+ (Slot::PullRequest, ..) => InboxRowType::PullRequest,+ (Slot::CalendarEvent, ..) => InboxRowType::CalendarEvent,+ (Slot::CalendarJoinRequest(_), ..) => InboxRowType::CalendarJoinRequest,+ (Slot::AccessRequested(_), ..) => InboxRowType::AccessRequested,+ (Slot::AccessGranted(_), ..) => InboxRowType::AccessGranted,+ }+}++/// Who a notification is from: the agent for agent session events, Macro+/// for reminders and AI chat responses, otherwise the user who sent it.+fn actor(notification: &FeedNotification) -> Option<InboxActor> {+ let agent = |session: &AgentSessionNotificationRef| InboxActor::Agent {+ bot_id: session.bot_id,+ name: session.bot_name.clone(),+ };+ match ¬ification.notification_metadata {+ NotifEvent::AgentSessionSettled(settled) => Some(agent(&settled.session)),+ NotifEvent::AgentSessionWaitingForInput(waiting) => Some(agent(&waiting.session)),+ NotifEvent::AgentSessionMentioned(mentioned) => Some(+ mentioned+ .mentioned_by+ .clone()+ .map_or_else(|| agent(&mentioned.session), InboxActor::User),+ ),+ NotifEvent::AiResponse(_)+ | NotifEvent::Reminder(_)+ | NotifEvent::CalendarEventReminder(_) => Some(InboxActor::Macro),+ NotifEvent::TaskAssigned(task) => Some(InboxActor::User(task.assigned_by.clone())),+ _ => notification.sender_id.clone().map(InboxActor::User),+ }+}++/// What the viewer can do from a row in `slot` showing `shown`, newest+/// first.+fn actions(slot: &Slot, shown: &[FeedNotification]) -> Vec<InboxRowAction> {+ let action = |kind, target: Option<&Uuid>, url: Option<String>| InboxRowAction {+ kind,+ target_id: target.map(Uuid::to_string),+ url,+ };+ match slot {+ Slot::AccessRequested(request) => vec![+ action(InboxRowActionKind::Approve, Some(request), None),+ action(InboxRowActionKind::Deny, Some(request), None),+ ],+ Slot::CalendarJoinRequest(request) => vec![+ action(InboxRowActionKind::Accept, Some(request), None),+ action(InboxRowActionKind::Decline, Some(request), None),+ ],+ Slot::AccessGranted(_) => vec![action(InboxRowActionKind::Open, None, None)],+ Slot::Agent+ if matches!(+ shown[0].notification_metadata,+ NotifEvent::AgentSessionWaitingForInput(_)+ ) =>+ {+ vec![action(InboxRowActionKind::Answer, None, None)]+ }+ Slot::PullRequest => shown+ .iter()+ .find_map(|notification| match ¬ification.notification_metadata {+ NotifEvent::GithubReviewRequested(requested) => Some(action(+ InboxRowActionKind::Review,+ None,+ Some(requested.common.url.clone()),+ )),+ _ => None,+ })+ .into_iter()+ .collect(),+ _ => Vec::new(),+ }+}++/// The rows of the group filed under `group`, newest first.+///+/// `notifications` are the viewer's pending notifications filed under the+/// group's entity. `mail` is its mailbox state when it is an email thread,+/// whose row follows the mailbox's read state.+pub fn rows(+ group: &FeedKey,+ notifications: &[FeedNotification],+ mail: Option<MailFacts>,+ viewer: &MacroUserIdStr<'static>,+ now: DateTime<Utc>,+) -> Vec<InboxRow> {+ let channel = group.entity().entity_type == EntityType::Channel;+ let placed: Vec<Placed> = if channel {+ place_channel(notifications, viewer)+ } else {+ let mut placed =+ place_discussions(notifications.iter().filter_map(discussion_view).collect());+ placed.extend(notifications.iter().filter_map(|notification| {+ place_event(notification, now).map(|(slot, shown)| Placed {+ notification: notification.clone(),+ slot,+ shown,+ mention: false,+ })+ }));+ placed+ };++ let mut order: Vec<Slot> = Vec::new();+ let mut by_slot: HashMap<Slot, Vec<Placed>> = HashMap::new();+ for placed in placed {+ by_slot+ .entry(placed.slot.clone())+ .or_insert_with(|| {+ order.push(placed.slot.clone());+ Vec::new()+ })+ .push(placed);+ }++ let mut rows: Vec<InboxRow> = order+ .into_iter()+ .filter_map(|slot| {+ let group_slot = by_slot+ .remove(&slot)+ .expect("every ordered slot has a group");+ let mention = group_slot.iter().any(|placed| placed.mention);+ let (shown, hidden): (Vec<Placed>, Vec<Placed>) =+ group_slot.into_iter().partition(|placed| placed.shown);+ if shown.is_empty() {+ return None;+ }+ let mut notifications: Vec<FeedNotification> = shown+ .into_iter()+ .map(|placed| placed.notification)+ .collect();+ let mut hidden: Vec<FeedNotification> = hidden+ .into_iter()+ .map(|placed| placed.notification)+ .collect();+ sort_newest_first(&mut notifications);+ sort_newest_first(&mut hidden);+ let unseen = match (&slot, mail) {+ // Mail is unread while it has unread messages; a reminder+ // that has not been seen keeps it unread too.+ (Slot::Email, Some(mail)) => {+ !mail.is_read+ || notifications.iter().any(|n| {+ matches!(n.notification_metadata, NotifEvent::Reminder(_))+ && counts_as_unseen(n)+ })+ }+ _ => notifications.iter().any(|n| counts_as_unseen(n)),+ };+ Some(InboxRow {+ row_type: row_type(&slot, channel, mention),+ actor: actor(¬ifications[0]),+ actions: actions(&slot, ¬ifications),+ thread_id: match &slot {+ Slot::Thread(root) => Some(root.clone()),+ _ => None,+ },+ id: InboxRowId {+ group: group.clone(),+ slot: slot.id(),+ },+ notifications,+ hidden,+ unseen,+ })+ })+ .collect();+ rows.sort_by(|a, b| {+ let (a, b) = (a.latest(), b.latest());+ b.created_at+ .cmp(&a.created_at)+ .then_with(|| b.notification_id.cmp(&a.notification_id))+ });+ rows+}diff --git a/crates/notification_inbox/src/domain/rows/test.rs b/crates/notification_inbox/src/domain/rows/test.rsnew file mode 100644index 0000000000..e11ab911a3--- /dev/null+++ b/crates/notification_inbox/src/domain/rows/test.rs@@ -0,0 +1,670 @@+use attention_feed::test_support::*;+use notification::domain::models::NotificationState;+use serde_json::{Value, json};++use super::*;++const CHANNEL: u128 = 0xC0;+const ROOT: u128 = 0x7A;+const DOC: u128 = 0xD0;+const SESSION: u128 = 0x5E;++fn group(entity_type: EntityType, id: u128) -> FeedKey {+ FeedKey::new(entity(entity_type, id))+}++fn channel_rows(notifications: &[FeedNotification]) -> Vec<InboxRow> {+ rows(+ &group(EntityType::Channel, CHANNEL),+ notifications,+ None,+ &viewer_id(),+ at(59),+ )+}++fn rows_of(group: &FeedKey, notifications: &[FeedNotification]) -> Vec<InboxRow> {+ rows(group, notifications, None, &viewer_id(), at(59))+}++/// `(row type, shown ids, hidden ids)` per row.+fn shape(rows: &[InboxRow]) -> Vec<(InboxRowType, Vec<Uuid>, Vec<Uuid>)> {+ rows.iter()+ .map(|row| (row.row_type, ids(&row.notifications), ids(&row.hidden)))+ .collect()+}++fn document_mention(+ id: u128,+ message: u128,+ thread: Option<u128>,+ owner: &str,+ minute: u32,+) -> FeedNotification {+ let mut content = json!({+ "documentName": "Plan",+ "owner": owner,+ "messageId": uuid(message),+ "messageContent": "see doc",+ "channelType": "public",+ });+ if let Some(thread) = thread {+ content["threadId"] = json!(uuid(thread));+ }+ notification(+ id,+ entity(EntityType::Channel, CHANNEL),+ "document_mention",+ content,+ minute,+ NotificationState::Unseen,+ )+}++#[test]+fn a_top_level_message_that_mentions_you_is_one_mention_row() {+ // The mention and the document chip in the same message are one row on+ // the message's thread.+ let listed = channel_rows(&[+ channel_mention(1, CHANNEL, ROOT, None, 1),+ document_mention(2, ROOT, None, "macro|[email protected]", 1),+ ]);+ assert_eq!(+ shape(&listed),+ vec![(InboxRowType::ChannelMention, vec![uuid(1)], vec![uuid(2)])]+ );+ assert_eq!(listed[0].thread_id, Some(uuid(ROOT).to_string()));+}++#[test]+fn replies_join_the_mention_row_which_keeps_its_id() {+ let mention = channel_mention(1, CHANNEL, ROOT, None, 1);+ let reply = channel_reply(2, CHANNEL, ROOT, 0x101, 2);++ let alone = channel_rows(std::slice::from_ref(&mention));+ let with_reply = channel_rows(&[mention.clone(), reply]);+ assert_eq!(+ shape(&with_reply),+ vec![(InboxRowType::ChannelMention, vec![uuid(2), uuid(1)], vec![])]+ );+ assert_eq!(alone[0].id, with_reply[0].id);+ assert_eq!(+ alone[0].id.id(),+ format!("channel:{}#thread:{}", uuid(CHANNEL), uuid(ROOT))+ );++ // Once the mention is done the replies are a thread row with the same id.+ let reply_only = channel_rows(&[channel_reply(2, CHANNEL, ROOT, 0x101, 2)]);+ assert_eq!(reply_only[0].row_type, InboxRowType::ChannelThread);+ assert_eq!(reply_only[0].id, alone[0].id);+}++#[test]+fn a_channel_splits_into_its_top_level_row_and_thread_rows() {+ let listed = channel_rows(&[+ channel_send(1, CHANNEL, 0x100, 1),+ channel_reaction(2, CHANNEL, 0x101, None, 2),+ channel_invite(3, CHANNEL, 3),+ // A plain chip in a top-level message rides with that message.+ channel_send(4, CHANNEL, 0x102, 4),+ document_mention(5, 0x102, None, "macro|[email protected]", 4),+ // Reactions inside a thread belong to the thread.+ channel_reaction(6, CHANNEL, 0x103, Some(ROOT), 5),+ ]);+ assert_eq!(+ shape(&listed),+ vec![+ (InboxRowType::ChannelThread, vec![uuid(6)], vec![]),+ (+ InboxRowType::ChannelMessages,+ vec![uuid(4), uuid(3), uuid(2), uuid(1)],+ vec![uuid(5)]+ ),+ ]+ );+ assert_eq!(+ listed[1].id.id(),+ format!("channel:{}#top_level", uuid(CHANNEL))+ );+ assert_eq!(listed[1].thread_id, None);+}++#[test]+fn every_channel_notification_has_one_home() {+ let notifications = vec![+ channel_send(1, CHANNEL, ROOT, 1),+ channel_reply(2, CHANNEL, ROOT, 0x101, 2),+ channel_mention(3, CHANNEL, 0x102, Some(ROOT), 3),+ document_mention(4, 0x102, Some(ROOT), USER, 3),+ channel_reaction(5, CHANNEL, 0x103, None, 4),+ channel_mention(6, CHANNEL, 0x104, None, 5),+ channel_send(7, CHANNEL, 0x105, 6),+ ];+ let listed = channel_rows(¬ifications);+ let mut homed: Vec<Uuid> = listed+ .iter()+ .flat_map(|row| row.all_notifications().map(|n| n.notification_id))+ .collect();+ homed.sort();+ let mut all = ids(¬ifications);+ all.sort();+ assert_eq!(homed, all);+}++#[test]+fn a_root_message_moves_into_its_active_thread() {+ assert_eq!(+ shape(&channel_rows(&[+ channel_send(1, CHANNEL, ROOT, 1),+ channel_reply(2, CHANNEL, ROOT, 0x101, 2),+ ])),+ vec![(InboxRowType::ChannelThread, vec![uuid(2), uuid(1)], vec![])]+ );+}++#[test]+fn a_mention_in_a_reply_is_a_thread_row() {+ assert_eq!(+ shape(&channel_rows(&[+ channel_mention(1, CHANNEL, 0x101, Some(ROOT), 1),+ document_mention(2, 0x101, Some(ROOT), USER, 1),+ ])),+ vec![(InboxRowType::ChannelThread, vec![uuid(1)], vec![uuid(2)])]+ );+}++#[test]+fn document_mentions_show_only_your_documents() {+ assert_eq!(+ shape(&channel_rows(&[+ document_mention(1, 0x100, None, USER, 1),+ document_mention(2, 0x101, None, "macro|[email protected]", 2),+ ])),+ vec![(InboxRowType::ChannelMessages, vec![uuid(1)], vec![uuid(2)])]+ );+}++#[test]+fn calls_alone_list_nothing() {+ let call = notification(+ 1,+ entity(EntityType::Channel, CHANNEL),+ "call_started",+ json!({ "callId": uuid(0x99), "channelType": "public" }),+ 1,+ NotificationState::Unseen,+ );+ assert!(channel_rows(&[call]).is_empty());+}++#[test]+fn an_entitys_comments_stack_on_one_row() {+ let doc = group(EntityType::Document, DOC);+ let listed = rows_of(+ &doc,+ &[+ // Thread B: a reply to a thread you are in.+ doc_reply(3, DOC, 0xB1, 0xB0, 3),+ // Threads C and D: lone root comments.+ doc_comment(4, DOC, 0xC0, 0xC0, 4),+ doc_comment(5, DOC, 0xD0, 0xD0, 5),+ ],+ );+ assert_eq!(+ shape(&listed),+ vec![(+ InboxRowType::DiscussionMessages,+ vec![uuid(5), uuid(4), uuid(3)],+ vec![]+ )]+ );+ assert_eq!(+ listed[0].id.id(),+ format!("document:{}#top_level", uuid(DOC))+ );+ assert_eq!(listed[0].thread_id, None);+}++#[test]+fn a_mention_makes_an_entitys_comments_a_mention_row_with_the_same_id() {+ let doc = group(EntityType::Document, DOC);+ let comments = [+ doc_comment_mention(1, DOC, 0xA0, 0xA0, 1),+ doc_reply(2, DOC, 0xA1, 0xA0, 2),+ doc_comment(4, DOC, 0xC0, 0xC0, 4),+ // A mention in a reply shadows the same comment's plain notification.+ doc_comment(6, DOC, 0xB2, 0xB0, 6),+ doc_comment_mention(7, DOC, 0xB2, 0xB0, 6),+ ];+ let listed = rows_of(&doc, &comments);+ assert_eq!(+ shape(&listed),+ vec![(+ InboxRowType::DiscussionMention,+ vec![uuid(7), uuid(4), uuid(2), uuid(1)],+ vec![uuid(6)]+ )]+ );++ let without_mentions = rows_of(&doc, &[doc_comment(4, DOC, 0xC0, 0xC0, 4)]);+ assert_eq!(+ without_mentions[0].row_type,+ InboxRowType::DiscussionMessages+ );+ assert_eq!(without_mentions[0].id, listed[0].id);+}++#[test]+fn a_lone_reaction_stays_on_the_channels_row() {+ assert_eq!(+ shape(&channel_rows(&[+ channel_send(1, CHANNEL, 0x100, 1),+ channel_reaction(2, CHANNEL, ROOT, None, 2),+ ])),+ vec![(+ InboxRowType::ChannelMessages,+ vec![uuid(2), uuid(1)],+ vec![]+ )]+ );+}++#[test]+fn reactions_to_one_top_level_message_stack_on_it() {+ let listed = channel_rows(&[+ channel_send(1, CHANNEL, 0x100, 1),+ channel_reaction(2, CHANNEL, ROOT, None, 2),+ channel_reaction(3, CHANNEL, ROOT, None, 3),+ ]);+ assert_eq!(+ shape(&listed),+ vec![+ (InboxRowType::ChannelThread, vec![uuid(3), uuid(2)], vec![]),+ (InboxRowType::ChannelMessages, vec![uuid(1)], vec![]),+ ]+ );+ assert_eq!(listed[0].thread_id, Some(uuid(ROOT).to_string()));+}++#[test]+fn a_reaction_joins_its_messages_replies() {+ let listed = channel_rows(&[+ channel_send(1, CHANNEL, ROOT, 1),+ channel_reply(2, CHANNEL, ROOT, 0x101, 2),+ channel_reaction(3, CHANNEL, ROOT, None, 3),+ ]);+ assert_eq!(+ shape(&listed),+ vec![(+ InboxRowType::ChannelThread,+ vec![uuid(3), uuid(2), uuid(1)],+ vec![]+ )]+ );+}++#[test]+fn a_reaction_joins_the_mention_it_reacts_to() {+ let mention = channel_mention(1, CHANNEL, ROOT, None, 1);+ let alone = channel_rows(std::slice::from_ref(&mention));+ let listed = channel_rows(&[mention, channel_reaction(2, CHANNEL, ROOT, None, 2)]);+ assert_eq!(+ shape(&listed),+ vec![(InboxRowType::ChannelMention, vec![uuid(2), uuid(1)], vec![])]+ );+ assert_eq!(listed[0].id, alone[0].id);+}++fn project_discussion(+ id: u128,+ reason: &str,+ message: u128,+ thread: u128,+ minute: u32,+) -> FeedNotification {+ notification(+ id,+ entity(EntityType::Initiative, 0x1A),+ "initiative_discussion",+ json!({+ "projectName": "Launch",+ "owner": USER,+ "reason": reason,+ "messageId": uuid(message),+ "threadId": uuid(thread),+ "text": "hello",+ }),+ minute,+ NotificationState::Unseen,+ )+}++#[test]+fn project_discussions_stack_on_one_row() {+ let project = group(EntityType::Initiative, 0x1A);+ assert_eq!(+ shape(&rows_of(+ &project,+ &[+ project_discussion(1, "mention", 0xA0, 0xA0, 1),+ project_discussion(2, "owner", 0xB0, 0xB0, 2),+ project_discussion(3, "reply", 0xC1, 0xC0, 3),+ ],+ )),+ vec![(+ InboxRowType::DiscussionMention,+ vec![uuid(3), uuid(2), uuid(1)],+ vec![]+ )]+ );+ assert_eq!(+ shape(&rows_of(+ &project,+ &[+ project_discussion(2, "owner", 0xB0, 0xB0, 2),+ project_discussion(3, "reply", 0xC1, 0xC0, 3),+ ],+ )),+ vec![(+ InboxRowType::DiscussionMessages,+ vec![uuid(3), uuid(2)],+ vec![]+ )]+ );+}++fn access_requested(id: u128, request: u128, minute: u32) -> FeedNotification {+ notification(+ id,+ entity(EntityType::Document, DOC),+ "entity_access_requested",+ json!({+ "requestId": uuid(request),+ "revision": 1,+ "entityName": "Plan",+ "accessLevel": "edit",+ }),+ minute,+ NotificationState::Unseen,+ )+}++#[test]+fn each_access_request_and_task_is_its_own_row() {+ let task = notification(+ 3,+ entity(EntityType::Document, DOC),+ "task_assigned",+ json!({ "taskId": uuid(DOC), "taskName": "Ship", "assignedBy": "macro|[email protected]" }),+ 3,+ NotificationState::Seen,+ );+ let listed = rows_of(+ &group(EntityType::Document, DOC),+ &[+ access_requested(1, 0xE1, 1),+ access_requested(2, 0xE2, 2),+ task,+ ],+ );+ assert_eq!(+ listed.iter().map(|row| row.row_type).collect::<Vec<_>>(),+ vec![+ InboxRowType::Task,+ InboxRowType::AccessRequested,+ InboxRowType::AccessRequested,+ ]+ );+ assert!(!listed[0].unseen, "a seen assignment is read");+ assert_eq!(+ listed[1].id.id(),+ format!("document:{}#access_requested:{}", uuid(DOC), uuid(0xE2))+ );+}++fn calendar_reminder(id: u128, ends_minute: u32) -> FeedNotification {+ notification(+ id,+ entity(EntityType::CalendarEvent, 0xCA),+ "calendar_event_reminder",+ json!({+ "eventId": uuid(0xCA),+ "occurrenceKey": format!("o{id}"),+ "title": "Standup",+ "startsAt": at(ends_minute - 1),+ "endsAt": at(ends_minute),+ "minutesBefore": 10,+ }),+ 1,+ NotificationState::Unseen,+ )+}++#[test]+fn reminders_for_ended_events_are_hidden() {+ let event = group(EntityType::CalendarEvent, 0xCA);+ let upcoming = calendar_reminder(1, 30);+ let ended = calendar_reminder(2, 20);++ let listed = rows(+ &event,+ &[upcoming.clone(), ended.clone()],+ None,+ &viewer_id(),+ at(25),+ );+ assert_eq!(+ shape(&listed),+ vec![(InboxRowType::CalendarEvent, vec![uuid(1)], vec![uuid(2)])]+ );+ assert!(rows(&event, &[ended], None, &viewer_id(), at(25)).is_empty());+}++#[test]+fn email_rows_follow_the_mailbox_read_state() {+ let thread = group(EntityType::EmailThread, 0xE0);+ let email = new_email(1, 0xE0, 1, NotificationState::Unseen);+ let mailbox = |is_read| {+ Some(MailFacts {+ inbox_visible: true,+ is_read,+ })+ };+ let unread = rows(+ &thread,+ std::slice::from_ref(&email),+ mailbox(false),+ &viewer_id(),+ at(59),+ );+ let read = rows(&thread, &[email], mailbox(true), &viewer_id(), at(59));+ assert_eq!(unread[0].row_type, InboxRowType::Email);+ assert_eq!(+ unread[0].id.id(),+ format!("email_thread:{}#email", uuid(0xE0))+ );+ assert!(unread[0].unseen);+ assert!(+ !read[0].unseen,+ "an unseen new-email notification follows the read mailbox"+ );+}++fn session_ref() -> Value {+ json!({+ "sessionId": uuid(SESSION),+ "sessionName": "Inbox triage",+ "botId": uuid(0xB07),+ "botName": "Scout",+ })+}++fn agent_notification(id: u128, tag: &str, extra: Value, minute: u32) -> FeedNotification {+ let mut content = session_ref();+ for (key, value) in extra.as_object().unwrap() {+ content[key] = value.clone();+ }+ notification(+ id,+ entity(EntityType::AgentSession, SESSION),+ tag,+ content,+ minute,+ NotificationState::Unseen,+ )+}++fn settled(id: u128, minute: u32) -> FeedNotification {+ agent_notification(+ id,+ "agent_session_settled",+ json!({ "turn": id, "stopReason": "end_turn" }),+ minute,+ )+}++fn waiting(id: u128, minute: u32) -> FeedNotification {+ agent_notification(+ id,+ "agent_session_waiting_for_input",+ json!({ "turn": id, "question": "Which account?" }),+ minute,+ )+}++fn agent() -> Option<InboxActor> {+ Some(InboxActor::Agent {+ bot_id: uuid(0xB07),+ name: "Scout".to_string(),+ })+}++fn action(kind: InboxRowActionKind, target: Option<u128>, url: Option<&str>) -> InboxRowAction {+ InboxRowAction {+ kind,+ target_id: target.map(|target| uuid(target).to_string()),+ url: url.map(str::to_string),+ }+}++#[test]+fn an_agent_waiting_for_the_viewer_offers_an_answer() {+ let session = group(EntityType::AgentSession, SESSION);+ let listed = rows_of(&session, &[settled(1, 1), waiting(2, 2)]);+ assert_eq!(+ shape(&listed),+ vec![(InboxRowType::Agent, vec![uuid(2), uuid(1)], vec![])]+ );+ assert_eq!(+ listed[0].id.id(),+ format!("agent_session:{}#agent", uuid(SESSION))+ );+ assert_eq!(listed[0].actor, agent());+ assert_eq!(+ listed[0].actions,+ vec![action(InboxRowActionKind::Answer, None, None)]+ );++ // Once the agent finished again, there is nothing to answer.+ let finished = rows_of(&session, &[waiting(2, 2), settled(3, 3)]);+ assert_eq!(finished[0].actor, agent());+ assert!(finished[0].actions.is_empty());+}++#[test]+fn requests_offer_their_answers_on_the_request() {+ let listed = rows_of(+ &group(EntityType::Document, DOC),+ &[access_requested(1, 0xE1, 1)],+ );+ assert_eq!(+ listed[0].actions,+ vec![+ action(InboxRowActionKind::Approve, Some(0xE1), None),+ action(InboxRowActionKind::Deny, Some(0xE1), None),+ ]+ );++ let join = notification(+ 2,+ entity(EntityType::CalendarEvent, 0xCA),+ "calendar_event_join_request",+ json!({ "requestId": uuid(0xF2), "eventId": uuid(0xCA), "title": "Standup" }),+ 2,+ NotificationState::Unseen,+ );+ let listed = rows_of(&group(EntityType::CalendarEvent, 0xCA), &[join]);+ assert_eq!(listed[0].row_type, InboxRowType::CalendarJoinRequest);+ assert_eq!(+ listed[0].actions,+ vec![+ action(InboxRowActionKind::Accept, Some(0xF2), None),+ action(InboxRowActionKind::Decline, Some(0xF2), None),+ ]+ );+}++#[test]+fn rows_say_who_they_are_from() {+ let mut mention = channel_mention(1, CHANNEL, ROOT, None, 1);+ std::sync::Arc::make_mut(&mut mention).sender_id =+ Some(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());+ assert_eq!(+ channel_rows(&[mention])[0].actor,+ Some(InboxActor::User(+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+ ))+ );++ let event = group(EntityType::CalendarEvent, 0xCA);+ assert_eq!(+ rows(+ &event,+ &[calendar_reminder(1, 30)],+ None,+ &viewer_id(),+ at(25)+ )[0]+ .actor,+ Some(InboxActor::Macro)+ );++ // Mail from outside Macro has no actor.+ let thread = group(EntityType::EmailThread, 0xE0);+ assert_eq!(+ rows_of(&thread, &[new_email(1, 0xE0, 1, NotificationState::Unseen)])[0].actor,+ None+ );+}++#[test]+fn a_requested_review_offers_the_pull_request() {+ const URL: &str = "https://github.com/macro-inc/macro/pull/1";+ let requested = notification(+ 1,+ entity(EntityType::ForeignEntity, 0xF0),+ "github_review_requested",+ json!({+ "foreignEntityId": uuid(0xF0),+ "githubKey": "macro-inc/macro#1",+ "owner": "macro-inc",+ "repo": "macro",+ "number": 1,+ "url": URL,+ "displayName": "macro-inc/macro#1",+ "title": "Fix the inbox",+ }),+ 1,+ NotificationState::Unseen,+ );+ let listed = rows_of(&group(EntityType::ForeignEntity, 0xF0), &[requested]);+ assert_eq!(listed[0].row_type, InboxRowType::PullRequest);+ assert_eq!(+ listed[0].actions,+ vec![action(InboxRowActionKind::Review, None, Some(URL))]+ );+ assert_eq!(+ listed[0].actor, None,+ "GitHub users are not Macro principals"+ );+}diff --git a/crates/notification_inbox/src/domain/service.rs b/crates/notification_inbox/src/domain/service.rsnew file mode 100644index 0000000000..cb0bf13f88--- /dev/null+++ b/crates/notification_inbox/src/domain/service.rs@@ -0,0 +1,428 @@+//! The notification inbox use cases: list a page of groups with their rows,+//! recompute known groups, mark rows done or seen, and undo a done. Paging,+//! refill, notification loading and acknowledgment are the shared feed+//! layer's; this service cuts what it loads into rows.++use std::collections::{HashMap, HashSet};++use attention_feed::domain::{+ acknowledge::Acknowledger,+ models::{+ Acknowledgment, CandidateKeying, CandidateRequest, DoneReceipt, FeedError, FeedKey,+ FeedViewer, Loaded, MailFacts,+ },+ ports::{CandidateSource, FeedMail, FeedNotifications, FeedSignals},+ reader::FeedReader,+};+use chrono::{DateTime, Utc};+use model_entity::EntityType;+use rootcause::Report;+use uuid::Uuid;++use super::{+ models::{+ InboxChange, InboxDoneOutcome, InboxEntry, InboxPage, InboxQuery, InboxRow, InboxRowId,+ InboxRowTarget, InboxRowType, InboxScope,+ },+ policy, rows,+};++#[cfg(test)]+mod test;++/// The notification inbox's use cases.+pub trait NotificationInboxService: Send + Sync + 'static {+ /// The hydrated entity each group carries.+ type Entity: Send + Sync + 'static;++ /// One page of the viewer's inbox, newest group first.+ fn page(+ &self,+ viewer: FeedViewer,+ query: InboxQuery,+ ) -> impl Future<Output = Result<InboxPage<Self::Entity>, FeedError>> + Send;++ /// The current rows of known groups in one inbox: each key comes back+ /// upserted with its placement, or removed.+ fn recompute(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ groups: Vec<FeedKey>,+ ) -> impl Future<Output = Result<Vec<InboxChange<Self::Entity>>, FeedError>> + Send;++ /// Acknowledge what the caller observed on each row: the notifications+ /// it shows and hides, up to its revision, move to done, and an email+ /// row's thread is archived. Underlying tasks, requests and pull+ /// requests are not completed.+ fn mark_done(+ &self,+ viewer: FeedViewer,+ targets: Vec<InboxRowTarget>,+ ) -> impl Future<Output = Result<InboxDoneOutcome, FeedError>> + Send;++ /// Reverse exactly what one mark-done changed, then recompute its groups+ /// for the caller's inbox.+ fn undo_done(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ receipt: DoneReceipt,+ ) -> impl Future<Output = Result<Vec<InboxChange<Self::Entity>>, FeedError>> + Send;++ /// Mark the rows' shown and hidden notifications seen, then recompute+ /// their groups for the caller's inbox.+ fn mark_seen(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ rows: Vec<InboxRowId>,+ ) -> impl Future<Output = Result<Vec<InboxChange<Self::Entity>>, FeedError>> + Send;+}++/// The notification inbox service over the shared feed layer.+pub struct NotificationInboxServiceImpl<S, N, M, G> {+ reader: FeedReader<S, N>,+ acknowledger: Acknowledger<N, M, G>,+}++impl<S, N, M, G> NotificationInboxServiceImpl<S, N, M, G>+where+ S: CandidateSource,+ N: FeedNotifications + Clone,+ M: FeedMail,+ G: FeedSignals,+{+ /// Create the service from its ports; the reader and the acknowledger+ /// share the notification port.+ pub fn new(source: S, notifications: N, mail: M, signals: G) -> Self {+ Self {+ reader: FeedReader::new(source, notifications.clone()),+ acknowledger: Acknowledger::new(notifications, mail, signals),+ }+ }+}++/// The candidate request for the viewer's inbox. The reader sets the limit,+/// cursor and key restriction per read.+fn candidate_request(viewer: &FeedViewer) -> CandidateRequest {+ CandidateRequest {+ viewer: viewer.clone(),+ keying: CandidateKeying::FiledEntity,+ own_work: false,+ types: policy::CANDIDATE_TYPES.to_vec(),+ filter: policy::inbox_filter(),+ limit: 0,+ after: None,+ only: None,+ }+}++/// A group cut into every one of its rows.+struct Group<E> {+ key: FeedKey,+ entity: E,+ sort_at: DateTime<Utc>,+ mail: Option<MailFacts>,+ rows: Vec<InboxRow>,+}++impl<E> Group<E> {+ /// Cut a loaded candidate into rows. An email thread outside the inbox+ /// has none: archive is mail's own done.+ fn cut(loaded: Loaded<E>, viewer: &FeedViewer, now: DateTime<Utc>) -> Self {+ let Loaded {+ candidate,+ notifications,+ } = loaded;+ let key = FeedKey::new(candidate.key);+ let mail = candidate.facts.mail;+ let rows = if mail.is_some_and(|mail| !mail.inbox_visible) {+ Vec::new()+ } else {+ rows::rows(&key, ¬ifications, mail, &viewer.user, now)+ };+ Self {+ key,+ entity: candidate.entity,+ sort_at: candidate.sort_at,+ mail,+ rows,+ }+ }++ /// The group's entry in `scope`; `None` when no row matches.+ fn entry(self, scope: &InboxScope) -> Option<InboxEntry<E>> {+ let rows: Vec<InboxRow> = self+ .rows+ .into_iter()+ .filter(|row| scope.admits(row.row_type))+ .collect();+ (!rows.is_empty()).then_some(InboxEntry {+ group: self.key,+ entity: self.entity,+ sort_at: self.sort_at,+ rows,+ })+ }++ fn row(&self, id: &InboxRowId) -> Option<&InboxRow> {+ self.rows.iter().find(|row| row.id == *id)+ }+}++/// Values deduplicated in first-seen order.+fn unique<T: Clone + Eq + std::hash::Hash>(values: impl IntoIterator<Item = T>) -> Vec<T> {+ let mut seen = HashSet::new();+ values+ .into_iter()+ .filter(|value| seen.insert(value.clone()))+ .collect()+}++/// An email thread group's thread id.+fn email_thread_id(key: &FeedKey) -> Option<Uuid> {+ (key.entity().entity_type == EntityType::EmailThread)+ .then(|| Uuid::parse_str(key.entity().entity_id.as_ref()).ok())+ .flatten()+}++impl<S, N, M, G> NotificationInboxServiceImpl<S, N, M, G>+where+ S: CandidateSource,+ N: FeedNotifications,+ M: FeedMail,+ G: FeedSignals,+{+ /// Every row of each current group in `keys`, keyed by group.+ async fn current(+ &self,+ viewer: &FeedViewer,+ keys: &[FeedKey],+ ) -> Result<HashMap<FeedKey, Group<S::Entity>>, Report> {+ let now = Utc::now();+ Ok(self+ .reader+ .current(candidate_request(viewer), keys)+ .await?+ .into_iter()+ .map(|(key, loaded)| (key, Group::cut(loaded, viewer, now)))+ .collect())+ }++ async fn recompute_groups(+ &self,+ viewer: &FeedViewer,+ scope: &InboxScope,+ keys: Vec<FeedKey>,+ ) -> Result<Vec<InboxChange<S::Entity>>, Report> {+ let keys = unique(keys);+ if keys.is_empty() {+ return Ok(Vec::new());+ }+ let mut current = self.current(viewer, &keys).await?;+ Ok(keys+ .into_iter()+ .map(+ |key| match current.remove(&key).and_then(|group| group.entry(scope)) {+ Some(entry) => InboxChange::Upserted(entry),+ None => InboxChange::Removed(key),+ },+ )+ .collect())+ }+}++impl<S, N, M, G> NotificationInboxService for NotificationInboxServiceImpl<S, N, M, G>+where+ S: CandidateSource,+ N: FeedNotifications,+ M: FeedMail,+ G: FeedSignals,+{+ type Entity = S::Entity;++ #[tracing::instrument(+ name = "notification_inbox.page",+ skip_all,+ fields(+ user = %viewer.user,+ limit = query.limit,+ row_types = query.scope.row_types.len(),+ groups = tracing::field::Empty,+ rows = tracing::field::Empty,+ ),+ err+ )]+ async fn page(+ &self,+ viewer: FeedViewer,+ query: InboxQuery,+ ) -> Result<InboxPage<Self::Entity>, FeedError> {+ let request = CandidateRequest {+ limit: query.limit,+ after: query.after,+ ..candidate_request(&viewer)+ };+ let now = Utc::now();+ let page = self+ .reader+ .page(request, |loaded| {+ Group::cut(loaded, &viewer, now).entry(&query.scope)+ })+ .await?;+ let span = tracing::Span::current();+ span.record("groups", page.entries.len());+ span.record(+ "rows",+ page.entries+ .iter()+ .map(|entry| entry.rows.len())+ .sum::<usize>(),+ );+ Ok(InboxPage {+ entries: page.entries,+ next: page.next,+ })+ }++ #[tracing::instrument(+ name = "notification_inbox.recompute",+ skip_all,+ fields(user = %viewer.user, groups = groups.len()),+ err+ )]+ async fn recompute(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ groups: Vec<FeedKey>,+ ) -> Result<Vec<InboxChange<Self::Entity>>, FeedError> {+ Ok(self.recompute_groups(&viewer, &scope, groups).await?)+ }++ #[tracing::instrument(+ name = "notification_inbox.mark_done",+ skip_all,+ fields(+ user = %viewer.user,+ rows = targets.len(),+ row_types = tracing::field::Empty,+ notifications = tracing::field::Empty,+ ),+ err+ )]+ async fn mark_done(+ &self,+ viewer: FeedViewer,+ targets: Vec<InboxRowTarget>,+ ) -> Result<InboxDoneOutcome, FeedError> {+ let mut planned = HashSet::new();+ let targets: Vec<InboxRowTarget> = targets+ .into_iter()+ .filter(|target| planned.insert(target.id.clone()))+ .collect();+ if targets.is_empty() {+ return Ok(InboxDoneOutcome {+ rows: Vec::new(),+ receipt: DoneReceipt::default(),+ });+ }+ // Rows are found among every row of their group, whatever inbox the+ // caller was looking at, so done acknowledges what they observed.+ let groups = unique(targets.iter().map(|target| target.id.group.clone()));+ let current = self.current(&viewer, &groups).await?;++ let rows: Vec<InboxRowId> = targets.iter().map(|target| target.id.clone()).collect();+ let mut found = Vec::new();+ let mut acknowledgments = Vec::with_capacity(targets.len());+ for target in targets {+ // A row already gone, or outside the viewer's groups, has nothing+ // left to acknowledge but is still reported done.+ let current_row = current+ .get(&target.id.group)+ .and_then(|group| Some((group, group.row(&target.id)?)));+ let acknowledgment = match current_row {+ Some((group, row)) => {+ found.push(row.row_type);+ let observed = target.revision.unwrap_or_else(|| row.revision());+ let notification_ids = observed.acknowledged(row.all_notifications());+ // Archiving takes the whole thread out of the inbox, so a+ // done from before newer mail arrived leaves it there.+ let observed_all = notification_ids.len() == row.all_notifications().count();+ Acknowledgment {+ key: group.key.clone(),+ notification_ids,+ archive_thread: (observed_all+ && row.row_type == InboxRowType::Email+ && group.mail.is_some_and(|mail| mail.inbox_visible))+ .then(|| email_thread_id(&group.key))+ .flatten(),+ }+ }+ None => Acknowledgment {+ key: target.id.group,+ notification_ids: Vec::new(),+ archive_thread: None,+ },+ };+ acknowledgments.push(acknowledgment);+ }+ let span = tracing::Span::current();+ span.record("row_types", tracing::field::debug(unique(found)));++ let receipt = self+ .acknowledger+ .acknowledge(&viewer, acknowledgments)+ .await?;+ span.record("notifications", receipt.notification_ids.len());+ Ok(InboxDoneOutcome { rows, receipt })+ }++ #[tracing::instrument(+ name = "notification_inbox.undo",+ skip_all,+ fields(user = %viewer.user, groups = receipt.keys.len()),+ err+ )]+ async fn undo_done(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ receipt: DoneReceipt,+ ) -> Result<Vec<InboxChange<Self::Entity>>, FeedError> {+ let groups = self.acknowledger.undo(&viewer, &receipt).await?;+ Ok(self.recompute_groups(&viewer, &scope, groups).await?)+ }++ #[tracing::instrument(+ name = "notification_inbox.mark_seen",+ skip_all,+ fields(user = %viewer.user, rows = rows.len(), notifications = tracing::field::Empty),+ err+ )]+ async fn mark_seen(+ &self,+ viewer: FeedViewer,+ scope: InboxScope,+ rows: Vec<InboxRowId>,+ ) -> Result<Vec<InboxChange<Self::Entity>>, FeedError> {+ let rows = unique(rows);+ let groups = unique(rows.iter().map(|row| row.group.clone()));+ if groups.is_empty() {+ return Ok(Vec::new());+ }+ let current = self.current(&viewer, &groups).await?;+ let notification_ids: Vec<Uuid> = rows+ .iter()+ .filter_map(|id| current.get(&id.group)?.row(id))+ .flat_map(|row| row.all_notifications().map(|n| n.notification_id))+ .collect();+ let changed = self+ .acknowledger+ .mark_seen(&viewer, &groups, notification_ids)+ .await?;+ tracing::Span::current().record("notifications", changed.len());+ Ok(self.recompute_groups(&viewer, &scope, groups).await?)+ }+}diff --git a/crates/notification_inbox/src/domain/service/test.rs b/crates/notification_inbox/src/domain/service/test.rsnew file mode 100644index 0000000000..aa490ce28a--- /dev/null+++ b/crates/notification_inbox/src/domain/service/test.rs@@ -0,0 +1,418 @@+use attention_feed::{+ domain::{+ models::{Candidate, FeedNotification, FeedRevision},+ ports::NotificationTransition,+ },+ test_support::*,+};+use model_entity::Entity;+use notification::domain::models::NotificationState;+use serde_json::json;++use super::*;++const CHANNEL: u128 = 0xC0;+const ROOT: u128 = 0x7A;+const DOC: u128 = 0xD0;+const MAIL: u128 = 0xE0;+const ARCHIVED: u128 = 0xE1;++type Service = NotificationInboxServiceImpl<+ FakeSource<&'static str>,+ FakeNotifications,+ FakeMail,+ FakeSignals,+>;++/// The service with handles on its fakes.+struct Harness {+ service: Service,+ source: FakeSource<&'static str>,+ notifications: FakeNotifications,+ mail: FakeMail,+ signals: FakeSignals,+}++fn harness(items: Vec<Candidate<&'static str>>, notifications: Vec<FeedNotification>) -> Harness {+ let source = FakeSource::with(items);+ let notifications = FakeNotifications::with(notifications);+ let mail = FakeMail::default();+ let signals = FakeSignals::default();+ Harness {+ service: NotificationInboxServiceImpl::new(+ source.clone(),+ notifications.clone(),+ mail.clone(),+ signals.clone(),+ ),+ source,+ notifications,+ mail,+ signals,+ }+}++fn key(entity: Entity<'static>) -> FeedKey {+ FeedKey::new(entity)+}++fn channel() -> FeedKey {+ key(entity(EntityType::Channel, CHANNEL))+}++fn row(group: &FeedKey, slot: &str) -> InboxRowId {+ InboxRowId {+ group: group.clone(),+ slot: slot.to_string(),+ }+}++fn thread_slot() -> String {+ format!("thread:{}", uuid(ROOT))+}++fn query(row_types: Vec<InboxRowType>) -> InboxQuery {+ InboxQuery {+ scope: InboxScope { row_types },+ limit: 50,+ after: None,+ }+}++fn document_mention(id: u128, message: u128, minute: u32) -> FeedNotification {+ notification(+ id,+ entity(EntityType::Channel, CHANNEL),+ "document_mention",+ json!({+ "documentName": "Plan",+ "owner": "macro|[email protected]",+ "messageId": uuid(message),+ "messageContent": "see doc",+ "channelType": "public",+ }),+ minute,+ NotificationState::Unseen,+ )+}++/// A channel with a top-level message and a mention thread, an inbox email+/// thread, an archived one, and a document whose only notification is a+/// call (no row).+fn inbox() -> Harness {+ let inbox_mail = MailFacts {+ inbox_visible: true,+ is_read: false,+ };+ let archived_mail = MailFacts {+ inbox_visible: false,+ is_read: true,+ };+ harness(+ vec![+ candidate("channel", channel().into_entity(), Some(9), None),+ mail_candidate("mail", MAIL, Some(7), None, inbox_mail),+ mail_candidate("archived", ARCHIVED, Some(6), None, archived_mail),+ candidate("doc", entity(EntityType::Document, DOC), Some(5), None),+ ],+ vec![+ channel_send(1, CHANNEL, 0x100, 2),+ channel_mention(2, CHANNEL, ROOT, None, 8),+ document_mention(3, ROOT, 8),+ channel_reply(4, CHANNEL, ROOT, 0x101, 9),+ new_email(5, MAIL, 7, NotificationState::Unseen),+ new_email(6, ARCHIVED, 6, NotificationState::Unseen),+ notification(+ 7,+ entity(EntityType::Document, DOC),+ "call_started",+ json!({ "callId": uuid(0x99), "channelType": "public" }),+ 5,+ NotificationState::Unseen,+ ),+ ],+ )+}++#[tokio::test]+async fn a_page_lists_groups_with_their_rows_newest_first() {+ let harness = inbox();+ let page = harness+ .service+ .page(viewer(), query(Vec::new()))+ .await+ .unwrap();++ let groups: Vec<_> = page.entries.iter().map(|entry| entry.entity).collect();+ // The archived thread and the document with nothing to show list nothing.+ assert_eq!(groups, vec!["channel", "mail"]);+ let channel_entry = &page.entries[0];+ assert_eq!(channel_entry.group, channel());+ assert_eq!(channel_entry.sort_at, at(9));+ let rows: Vec<_> = channel_entry+ .rows+ .iter()+ .map(|row| (row.id.slot.clone(), row.row_type))+ .collect();+ assert_eq!(+ rows,+ vec![+ (thread_slot(), InboxRowType::ChannelMention),+ ("top_level".to_string(), InboxRowType::ChannelMessages),+ ]+ );+ assert_eq!(page.entries[1].rows[0].row_type, InboxRowType::Email);+ assert!(page.entries[1].rows[0].unseen);+}++#[tokio::test]+async fn a_page_reads_filed_entity_candidates_without_own_work() {+ let harness = inbox();+ harness+ .service+ .page(viewer(), query(Vec::new()))+ .await+ .unwrap();+ let requests = harness.source.requests.lock().unwrap();+ assert_eq!(requests[0].keying, CandidateKeying::FiledEntity);+ assert!(!requests[0].own_work);+ assert_eq!(requests[0].types, policy::CANDIDATE_TYPES.to_vec());+}++#[tokio::test]+async fn row_types_narrow_the_rows_and_drop_groups_without_any() {+ let harness = inbox();+ let page = harness+ .service+ .page(viewer(), query(vec![InboxRowType::ChannelMessages]))+ .await+ .unwrap();+ assert_eq!(page.entries.len(), 1);+ let rows = &page.entries[0].rows;+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].id, row(&channel(), "top_level"));+}++#[tokio::test]+async fn done_acknowledges_what_a_row_shows_and_hides_up_to_its_revision() {+ let harness = inbox();+ let thread = row(&channel(), &thread_slot());++ let outcome = harness+ .service+ .mark_done(+ viewer(),+ vec![InboxRowTarget {+ id: thread.clone(),+ // Observed before the reply arrived.+ revision: Some(FeedRevision {+ attention_through: Some(at(8)),+ }),+ }],+ )+ .await+ .unwrap();++ assert_eq!(outcome.rows, vec![thread]);+ // The mention and the document chip it speaks for; not the later reply,+ // and nothing from the channel's top-level row.+ assert_eq!(outcome.receipt.notification_ids, vec![uuid(2), uuid(3)]);+ assert_eq!(+ harness.notifications.state_of(uuid(4)),+ NotificationState::Unseen+ );+ assert_eq!(+ harness.notifications.state_of(uuid(1)),+ NotificationState::Unseen+ );+ assert!(harness.mail.calls.lock().unwrap().is_empty());+ assert_eq!(+ *harness.signals.calls.lock().unwrap(),+ vec![vec![channel().into_entity()]]+ );+}++#[tokio::test]+async fn done_on_an_email_row_archives_its_thread() {+ let harness = inbox();+ let thread = key(entity(EntityType::EmailThread, MAIL));+ let outcome = harness+ .service+ .mark_done(+ viewer(),+ vec![InboxRowTarget {+ id: row(&thread, "email"),+ revision: None,+ }],+ )+ .await+ .unwrap();+ assert_eq!(outcome.receipt.notification_ids, vec![uuid(5)]);+ assert_eq!(outcome.receipt.archived_threads, vec![uuid(MAIL)]);+ assert_eq!(+ *harness.mail.calls.lock().unwrap(),+ vec![(uuid(MAIL), true)]+ );+}++#[tokio::test]+async fn done_from_before_newer_mail_keeps_the_thread_in_the_inbox() {+ let harness = harness(+ vec![mail_candidate(+ "mail",+ MAIL,+ Some(8),+ None,+ MailFacts {+ inbox_visible: true,+ is_read: false,+ },+ )],+ vec![+ new_email(5, MAIL, 7, NotificationState::Unseen),+ new_email(6, MAIL, 8, NotificationState::Unseen),+ ],+ );+ let thread = key(entity(EntityType::EmailThread, MAIL));++ let outcome = harness+ .service+ .mark_done(+ viewer(),+ vec![InboxRowTarget {+ id: row(&thread, "email"),+ // Observed before the second email arrived.+ revision: Some(FeedRevision {+ attention_through: Some(at(7)),+ }),+ }],+ )+ .await+ .unwrap();++ assert_eq!(outcome.receipt.notification_ids, vec![uuid(5)]);+ assert!(outcome.receipt.archived_threads.is_empty());+ assert!(harness.mail.calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn done_on_rows_that_are_gone_acknowledges_nothing() {+ let harness = inbox();+ let gone = row(&channel(), "thread:nope");+ let foreign = row(&key(entity(EntityType::Document, 0xF0)), "top_level");+ let outcome = harness+ .service+ .mark_done(+ viewer(),+ vec![+ InboxRowTarget {+ id: gone.clone(),+ revision: None,+ },+ InboxRowTarget {+ id: foreign.clone(),+ revision: None,+ },+ InboxRowTarget {+ id: gone.clone(),+ revision: None,+ },+ ],+ )+ .await+ .unwrap();+ assert_eq!(outcome.rows, vec![gone, foreign]);+ assert!(outcome.receipt.notification_ids.is_empty());+ assert!(harness.notifications.transitions.lock().unwrap().is_empty());+}++#[tokio::test]+async fn undo_restores_a_done_and_recomputes_its_groups() {+ let harness = inbox();+ let outcome = harness+ .service+ .mark_done(+ viewer(),+ vec![InboxRowTarget {+ id: row(&channel(), "top_level"),+ revision: None,+ }],+ )+ .await+ .unwrap();+ assert_eq!(outcome.receipt.notification_ids, vec![uuid(1)]);++ let changes = harness+ .service+ .undo_done(+ viewer(),+ InboxScope::default(),+ DoneReceipt::decode(&outcome.receipt.encode()).unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(+ harness.notifications.state_of(uuid(1)),+ NotificationState::Seen+ );+ assert_eq!(changes.len(), 1);+ let InboxChange::Upserted(entry) = &changes[0] else {+ panic!("the channel comes back");+ };+ assert_eq!(entry.rows.len(), 2);+}++#[tokio::test]+async fn seen_reads_a_rows_shown_and_hidden_notifications() {+ let harness = inbox();+ let changes = harness+ .service+ .mark_seen(+ viewer(),+ InboxScope::default(),+ vec![row(&channel(), &thread_slot())],+ )+ .await+ .unwrap();++ let transitions = harness.notifications.transitions.lock().unwrap().clone();+ assert_eq!(transitions.len(), 1);+ let (mut seen, transition) = transitions[0].clone();+ seen.sort();+ assert_eq!(transition, NotificationTransition::Seen);+ assert_eq!(seen, vec![uuid(2), uuid(3), uuid(4)]);++ let InboxChange::Upserted(entry) = &changes[0] else {+ panic!("the channel stays listed");+ };+ let thread = entry+ .rows+ .iter()+ .find(|row| row.id.slot == thread_slot())+ .unwrap();+ assert!(!thread.unseen);+ let top_level = entry+ .rows+ .iter()+ .find(|row| row.id.slot == "top_level")+ .unwrap();+ assert!(top_level.unseen, "other rows keep their state");+}++#[tokio::test]+async fn recompute_removes_groups_with_no_matching_row() {+ let harness = inbox();+ let doc = key(entity(EntityType::Document, DOC));+ let changes = harness+ .service+ .recompute(+ viewer(),+ InboxScope::default(),+ vec![channel(), doc.clone(), channel()],+ )+ .await+ .unwrap();+ assert_eq!(changes.len(), 2);+ assert!(matches!(&changes[0], InboxChange::Upserted(entry) if entry.group == channel()));+ assert!(matches!(&changes[1], InboxChange::Removed(removed) if *removed == doc));+}diff --git a/crates/notification_inbox/src/lib.rs b/crates/notification_inbox/src/lib.rsnew file mode 100644index 0000000000..a6ad405857--- /dev/null+++ b/crates/notification_inbox/src/lib.rs@@ -0,0 +1,17 @@+#![deny(missing_docs)]+//! The notifications inbox: the viewer's pending notifications grouped by+//! the entity they are filed under and cut into rows, one per conversation+//! thread, channel top level, email thread, task, pull request, request or+//! agent session, served as one paginated, live-updating list. Each row also+//! says who it is from and what the viewer can do from it, as data.+//!+//! # Architecture+//!+//! - **domain**: rows, membership policy, and the page, recompute, done,+//! seen and undo use cases.+//!+//! Paging, notification loading, acknowledgment and the adapters over the+//! services that own the data are the shared feed layer's+//! (`crates/attention_feed`).++pub mod domain;diff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.mdindex 9c2498ca2c..7e139d2303 100644--- a/crates/soup/AGENTS.md+++ b/crates/soup/AGENTS.md@@ -49,7 +49,8 @@ rows, initiatives, ...) and get back a single unified, paginated result.collaborator is needed.- Add a filter/sort option: `item_filters`/`filter_ast` (the filter language) →`src/domain/models.rs` → the matching `src/outbound/pg_soup_repo/*` query.-- Change which candidates attention feeds (Home's work feed) page:+- Change which candidates attention feeds (Home's work feed, the+ notifications inbox) page:`src/domain/service/tests/attention.rs` → `src/outbound/pg_soup_repo/attention.rs`(`attention/query.sql`). Channel-thread keying applies only to`AttentionKeying::ThreadScoped`; keep it in step with `attention_feed`'sdiff --git a/docs/guides/add-notification-kind.md b/docs/guides/add-notification-kind.mdindex d439cd5479..9d31be052f 100644--- a/docs/guides/add-notification-kind.md+++ b/docs/guides/add-notification-kind.md@@ -232,6 +232,16 @@ kinds introduced by a newer backend.new kind defaults to a standalone stack (`_ => None`); add it to the thread-rootand `is_channel_event` / `is_comment_event` matches if it belongs to aconversation.+- **Notifications inbox:** `place_event` in+ `crates/notification_inbox/src/domain/rows.rs` matches every `NotifEvent`, so+ the compiler asks where a new kind's row goes: an existing slot, a new slot+ (one row per request id), or none. Hide noise there rather than dropping it,+ so done still acknowledges it. Give the row its actor in `actor` and any+ buttons in `actions` (as data; the client performs them). A new row type or+ action kind also needs `InboxRowType` or `InboxRowActionKind`, its GraphQL+ enum in `crates/graphql_notification_inbox`, and the regenerated+ `static_assets/schema.graphql`; adding enum values is compatible, removing+ them is not.- **Channel unread scoping:** channel thread SQL in`crates/notification/src/outbound/entity_notifications.rs` lists event types byname. Add a channel-scoped kind there, with tests beside it.diff --git a/services/document_storage_service/AGENTS.md b/services/document_storage_service/AGENTS.mdindex 6ed05d0de2..59506b6e5b 100644--- a/services/document_storage_service/AGENTS.md+++ b/services/document_storage_service/AGENTS.md@@ -23,6 +23,8 @@ threads, pins, recents, notifications, folders, activity.- `src/server.rs`: composition root, including access-request routes and thetracked delivery dispatcher; `src/outbound/access_requests.rs` composes thenotification/withdrawal/realtime ports. Policy lives in `crates/access_requests`.+ It also builds the attention feeds (Home's work feed and the notifications+ inbox) from one set of `attention_feed` adapters, triggers and viewer lookup.- `src/external_chat.rs`: composes `ExternalChatService<WhatsAppProvider>`,mounts `/external-chats` (`crates/external_chat`) and `/whatsapp`(`crates/whatsapp_linked`) and runs the notification/import worker (LISTENdiff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 34be76e0de..7feca241ba 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -217,6 +217,7 @@ models_permissions = { path = "../../crates/models_permissions" }models_properties = { path = "../../crates/models_properties" }models_soup = { path = "../../crates/models_soup", features = ["schema"] }notification = { path = "../../crates/notification" }+notification_inbox = { path = "../../crates/notification_inbox" }opensearch_client = { path = "../../crates/opensearch_client" }projects_hex = { path = "../../crates/projects", package = "projects" }properties = { path = "../../crates/properties" }diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 84458e8295..01f34a9738 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -941,6 +941,7 @@ pub(crate) struct ApiContext {pub graphql_calendar_context: graphql_calendar::CalendarGraphqlContext,pub graphql_calendar_mutation_context: graphql_calendar::CalendarGraphqlMutationContext,pub graphql_work_feed_context: complete_graph::WorkFeedGraphqlContext,+ pub graphql_notification_inbox_context: complete_graph::NotificationInboxGraphqlContext,pub graphql_initiative_entity_loader: graphql_initiative::InitiativeEntityLoader,pub graphql_agent_session_entity_loader: graphql_soup::AgentSessionEntityLoader,/// Focus reads for the GraphQL `emailFocus` list and thread `focus` field.diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rsindex 2db74780d2..af0c4c0953 100644--- a/services/document_storage_service/src/api/graphql_soup.rs+++ b/services/document_storage_service/src/api/graphql_soup.rs@@ -208,6 +208,7 @@ fn insert_graphql_context_data(data.insert(state.graphql_calendar_context.clone());data.insert(state.graphql_calendar_mutation_context.clone());data.insert(state.graphql_work_feed_context.clone());+ data.insert(state.graphql_notification_inbox_context.clone());data.insert(state.graphql_initiative_entity_loader.clone());data.insert(state.graphql_agent_session_entity_loader.clone());data.insert(state.graphql_primary_soup_item_loader.clone());diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rsindex 3178eda2ca..7e317d5f56 100644--- a/services/document_storage_service/src/server.rs+++ b/services/document_storage_service/src/server.rs@@ -2129,7 +2129,8 @@ pub async fn run() -> anyhow::Result<()> {entity_access_service.clone(),));- // Attention feeds (Home's work feed) share one feed layer: Soup+ // Attention feeds (Home's work feed and the notifications inbox) share+ // one feed layer and these adapters: Soup// candidates over the replica, notification acknowledgement on the// primary, and live updates recomputed from the viewer's notification,// activity and Soup streams. Done publishes a viewer-addressed Soup patch@@ -2159,6 +2160,23 @@ pub async fn run() -> anyhow::Result<()> {KafkaSoupRealtimePublisher::new(macro_event_broker.clone()),),),+ feed_triggers.clone(),+ feed_viewers.clone(),+ );+ let graphql_notification_inbox_context = complete_graph::NotificationInboxGraphqlContext::new(+ notification_inbox::domain::service::NotificationInboxServiceImpl::new(+ attention_feed::outbound::soup::SoupCandidateSource::new(+ soup_service.clone(),+ Arc::new(email_service.clone()),+ ),+ attention_feed::outbound::notifications::ReaderFeedNotifications::new(+ graphql_notification_reader.clone(),+ ),+ attention_feed::outbound::mail::EmailFeedMail::new(Arc::new(email_service.clone())),+ attention_feed::outbound::signals::SoupRealtimeFeedSignals::new(+ KafkaSoupRealtimePublisher::new(macro_event_broker.clone()),+ ),+ ),feed_triggers,feed_viewers,);@@ -2169,6 +2187,7 @@ pub async fn run() -> anyhow::Result<()> {sync_sessions,dictation_state,graphql_work_feed_context,+ graphql_notification_inbox_context,contacts_ingress: contacts_ingress.clone(),soup_router_state: SoupRouterState::from_arc(soup_service.clone(),diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex f615fcd392..6e1e9c0ec0 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -431,6 +431,26 @@ type CompleteMutationRoot {"""undoWorkFeedItemsDone(input: UndoWorkFeedItemsDoneInput!): UndoWorkFeedItemsDonePayload!"""+ Mark notification inbox rows done for the authenticated user:+ acknowledge the notifications each row shows and hides, and archive+ an email row's thread. Notifications newer than a row's `revision`+ stay active. Tasks, requests, reviews and pull requests themselves+ are not completed.+ """+ markNotificationInboxRowsDone(input: MarkNotificationInboxRowsDoneInput!): MarkNotificationInboxRowsDonePayload!+ """+ Reverse one mark-done for the authenticated user without overwriting+ anything that happened since, and return the restored groups' places+ in the requested inbox.+ """+ undoNotificationInboxRowsDone(input: UndoNotificationInboxRowsDoneInput!): UndoNotificationInboxRowsDonePayload!+ """+ Mark notification inbox rows seen for the authenticated user: the+ notifications each row shows and hides become read. Returns the+ updated groups' places in the requested inbox.+ """+ markNotificationInboxRowsSeen(input: MarkNotificationInboxRowsSeenInput!): MarkNotificationInboxRowsSeenPayload!+ """Create once; replaying the same owned ID returns its existing record."""createSavedView(input: CreateSavedViewInput!): GraphqlSavedView!@@ -446,7 +466,7 @@ type CompleteMutationRoot {"""Root subscription object combining realtime Soup, notification,-activity, and work feed adapters.+activity, work feed and notification inbox adapters."""type CompleteSubscriptionRoot {"""@@ -478,6 +498,16 @@ type CompleteSubscriptionRoot {client resubscribes and refetches."""workFeedUpdates(scope: WorkFeedScopeInput): [WorkFeedPatch!]!+ """+ Changes to the authenticated user's notification inbox in `scope`:+ groups to insert or move with their current rows, groups to remove,+ and an invalidation when changes may have been missed. Each payload+ is one batch to apply together. Start it before fetching the first+ page and refetch after an invalidation; the stream ends with an error+ when its sources end, after which the client resubscribes and+ refetches.+ """+ notificationInboxUpdates(scope: NotificationInboxScopeInput): [NotificationInboxPatch!]!}"""@@ -10279,6 +10309,13 @@ type GraphqlUser {"""workFeed(input: WorkFeedInput): WorkFeedPage!"""+ A page of the authenticated user's notifications inbox, newest group+ first: their pending notifications grouped by the entity they are+ filed under and cut into rows, one per conversation thread, channel+ top level, email thread, task, request or agent session.+ """+ notificationInbox(input: NotificationInboxInput): NotificationInboxPage!+ """Labels across every owned or delegated inbox accessible to the authenticated user."""emailLabels: [GraphqlSoupEmailLabel!]!@@ -10628,6 +10665,55 @@ input MarkEmailThreadUnreadInput {threadId: ID!}+"""+Input for marking inbox rows done.+"""+input MarkNotificationInboxRowsDoneInput {+ """+ The rows to complete, at most 200.+ """+ rows: [NotificationInboxRowTargetInput!]!+}++"""+The result of marking inbox rows done.+"""+type MarkNotificationInboxRowsDonePayload {+ """+ The completed rows; remove them from every inbox. Rows that were+ already gone are included.+ """+ rowIds: [ID!]!+ """+ Opaque token that reverses exactly this operation.+ """+ undoToken: String!+}++"""+Input for marking inbox rows seen.+"""+input MarkNotificationInboxRowsSeenInput {+ """+ The rows to mark seen, at most 200.+ """+ rowIds: [ID!]!+ """+ The inbox the updated groups are placed in.+ """+ scope: NotificationInboxScopeInput+}++"""+The result of marking inbox rows seen.+"""+type MarkNotificationInboxRowsSeenPayload {+ """+ The updated groups' places in the requested inbox.+ """+ patches: [NotificationInboxPatch!]!+}+"""Input for marking work feed items done."""@@ -10681,6 +10767,362 @@ input NotificationEntityInput {entityId: ID!}+"""+Who a row is from: a person, an agent, or Macro itself.+"""+type NotificationInboxActor {+ """+ The kind of principal.+ """+ kind: NotificationInboxActorKind!+ """+ The user id for a user, the bot id for an agent; absent for Macro.+ Not `id`: the client cache reads an `id` field as entity identity.+ """+ principalId: String+ """+ The display name when the row carries it (an agent's bot name);+ users are looked up by id.+ """+ name: String+}++"""+The kind of principal a row is from. Values may be added; present one+you do not know without an author.+"""+enum NotificationInboxActorKind {+ """+ A Macro user.+ """+ USER+ """+ An agent.+ """+ AGENT+ """+ Macro itself.+ """+ MACRO+}++"""+The matching rows of the notifications filed under one entity. Entries+belong to one inbox scope and have no id of their own; rows are shared.+"""+type NotificationInboxEntry {+ """+ The group the rows are filed under: `<entity type>:<entity id>`.+ """+ groupId: ID!+ """+ The entity the rows are filed under.+ """+ entity: GraphqlSoupEntity!+ """+ Where the entry sits, in RFC 3339: the group's newest pending+ notification.+ """+ sortAt: String!+ """+ The matching rows, newest first; never empty.+ """+ rows: [NotificationInboxRow!]!+}++"""+A group with no matching row left in the subscribed inbox: done,+filtered out or inaccessible. The entity itself is not necessarily+deleted.+"""+type NotificationInboxEntryRemoved {+ """+ The removed group's id.+ """+ groupId: ID!+}++"""+A group that belongs in the subscribed inbox, with its current rows and+placement. Insert it, or move it to its new `sortAt`.+"""+type NotificationInboxEntryUpserted {+ """+ The entry.+ """+ entry: NotificationInboxEntry!+}++"""+Page request for the viewer's notification inbox.+"""+input NotificationInboxInput {+ """+ Which rows the inbox shows.+ """+ scope: NotificationInboxScopeInput+ """+ Entries per page; defaults to 50, capped at 100.+ """+ limit: Int+ """+ Opaque cursor from the previous page's `nextCursor`; absent for the+ first page. Send it with the same scope.+ """+ cursor: String+}++"""+Changes may have been missed: refetch the inbox.+"""+type NotificationInboxInvalidated {+ """+ Always true.+ """+ refresh: Boolean!+}++"""+One page of the viewer's notification inbox, newest group first.+"""+type NotificationInboxPage {+ """+ The page's entries.+ """+ entries: [NotificationInboxEntry!]!+ """+ Cursor for the next page; absent once the inbox is exhausted.+ """+ nextCursor: String+ """+ Where this page's read stopped, the position `nextCursor` resumes+ after; absent once the inbox is exhausted. A filtered page can read+ past its last entry, so a live change placed after that entry but not+ after this position belongs to this page rather than a later one.+ """+ nextPosition: NotificationInboxPosition+}++"""+One change to an inbox's membership, placement or rows.+"""+union NotificationInboxPatch = NotificationInboxEntryUpserted | NotificationInboxEntryRemoved | NotificationInboxInvalidated++"""+A place in the inbox's order: newest `sortAt` first, then entity id+descending.+"""+type NotificationInboxPosition {+ """+ The sort time, RFC 3339.+ """+ sortAt: String!+ """+ The entity id that breaks ties at `sortAt`.+ """+ entityId: String!+}++"""+One inbox row: the notifications shown together for one thread, a+channel's top level, an email thread, a task, a request or a review. A+row's contents depend only on the viewer's notifications, so one id is+one row in every scope.+"""+type NotificationInboxRow {+ """+ Stable per-viewer row id: `<groupId>#<slot>`. Opaque.+ """+ id: ID!+ """+ The row's kind.+ """+ rowType: NotificationInboxRowType!+ """+ For a thread row, the channel root message or discussion root+ comment it is about.+ """+ threadId: String+ """+ When the row's newest shown notification was created, in RFC 3339.+ """+ latestAt: String!+ """+ Who the row is from, per its newest shown notification; absent when+ that is no one in Macro (outside email senders, GitHub users).+ """+ actor: NotificationInboxActor+ """+ What the viewer can do from the row, in presentation order; empty+ when the row only opens.+ """+ actions: [NotificationInboxRowAction!]!+ """+ Whether the row is unread.+ """+ unseen: Boolean!+ """+ How many notifications the row shows.+ """+ count: Int!+ """+ Opaque token of what the row stands for; send it with done so+ notifications that arrive later stay active.+ """+ revision: String!+ """+ The row's shown notifications, newest first. Defaults to 20, capped+ at 100; `count` is the full size.+ """+ notifications(limit: Int): [GraphqlNotification!]!+}++"""+One thing the viewer can do from a row, described as data. Perform it+through the API of the thing it acts on; the inbox only says it is+available.+"""+type NotificationInboxRowAction {+ """+ What the action does.+ """+ kind: NotificationInboxRowActionKind!+ """+ What the action acts on when it is not the row's group: an access or+ join request.+ """+ targetId: ID+ """+ The page the action opens outside Macro, such as a pull request.+ """+ url: String+}++"""+What the viewer can do from a row. Values are added with the row types+that offer them; skip one you do not know.+"""+enum NotificationInboxRowActionKind {+ """+ Open what the row is about.+ """+ OPEN+ """+ Answer the agent that is waiting for the viewer.+ """+ ANSWER+ """+ Review the pull request at `url`.+ """+ REVIEW+ """+ Grant the access request `targetId`.+ """+ APPROVE+ """+ Refuse the access request `targetId`.+ """+ DENY+ """+ Accept the join request `targetId`.+ """+ ACCEPT+ """+ Decline the join request `targetId`.+ """+ DECLINE+}++"""+One row to mark done.+"""+input NotificationInboxRowTargetInput {+ """+ The row's id.+ """+ id: ID!+ """+ The row's `revision` the caller observed. Notifications newer than it+ stay active. Omit to acknowledge everything current.+ """+ revision: String+}++"""+The kinds of notification inbox row. Values are added as the inbox+learns new sources; present a value you do not know as a generic row.+"""+enum NotificationInboxRowType {+ """+ An agent session's or AI chat's latest response or question.+ """+ AGENT+ """+ An email thread.+ """+ """+ A top-level channel message that mentions the viewer, with its thread.+ """+ CHANNEL_MENTION+ """+ A channel's top-level messages, reactions to them and invites.+ """+ CHANNEL_MESSAGES+ """+ A channel thread's replies, mentions and reactions.+ """+ CHANNEL_THREAD+ """+ A top-level discussion comment that mentions the viewer, with its+ thread.+ """+ DISCUSSION_MENTION+ """+ An entity's top-level discussion comments.+ """+ DISCUSSION_MESSAGES+ """+ One discussion thread's replies.+ """+ DISCUSSION_THREAD+ """+ A task assigned to the viewer.+ """+ TASK+ """+ A GitHub pull request's activity.+ """+ PULL_REQUEST+ """+ Reminders of an upcoming calendar event.+ """+ CALENDAR_EVENT+ """+ A request to join a calendar event the viewer shared.+ """+ CALENDAR_JOIN_REQUEST+ """+ A request for access to something the viewer can share.+ """+ ACCESS_REQUESTED+ """+ Access the viewer requested was granted.+ """+ ACCESS_GRANTED+}++"""+Which rows a notification inbox shows. Pages, subscriptions, seen and+undo for one inbox send the same scope.+"""+input NotificationInboxScopeInput {+ """+ Row kinds to include; omitted or empty means every kind.+ """+ rowTypes: [NotificationInboxRowType!]+}+"""The notification state as represented by GraphQL variables and responses."""@@ -11321,6 +11763,30 @@ input TimedEventTimeInput {timeZone: String}+"""+Input for undoing one mark-done.+"""+input UndoNotificationInboxRowsDoneInput {+ """+ The `undoToken` the mark-done returned.+ """+ undoToken: String!+ """+ The inbox the restored groups are placed in.+ """+ scope: NotificationInboxScopeInput+}++"""+The result of undoing a mark-done.+"""+type UndoNotificationInboxRowsDonePayload {+ """+ The restored groups' places in the requested inbox.+ """+ patches: [NotificationInboxPatch!]!+}+"""Input for undoing one mark-done."""