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(feed): share paging, hydration and acknowledgment between feeds (#8715)
teoeba261728de9
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex e6fe2578cb..faeae9584a 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -2333,6 +2333,149 @@"crates/non_empty","crates/workspace-hack"],+ "attention_feed": [+ "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_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"+ ],"authentication_service": ["crates/activity","crates/agent",@@ -4149,6 +4292,7 @@"crates/ai_usage","crates/analytics_client","crates/attachment",+ "crates/attention_feed","crates/authentication_service_client","crates/bot_id","crates/bot_token",@@ -5289,6 +5433,7 @@"crates/analytics_client","crates/anthropic","crates/attachment",+ "crates/attention_feed","crates/authentication_service_client","crates/bot_id","crates/bot_token",@@ -9131,6 +9276,7 @@"crates/ai_usage","crates/analytics_client","crates/attachment",+ "crates/attention_feed","crates/authentication_service_client","crates/bot_id","crates/bot_token",@@ -15042,6 +15188,7 @@"crates/ai_usage","crates/analytics_client","crates/attachment",+ "crates/attention_feed","crates/authentication_service_client","crates/bot_id","crates/bot_token",diff --git a/Cargo.lock b/Cargo.lockindex 868544a2c0..63d10d3d7a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2153,6 +2153,36 @@ dependencies = ["workspace-hack",]+[[package]]+name = "attention_feed"+version = "0.1.0"+dependencies = [+ "activity",+ "async-stream",+ "base64 0.22.1",+ "chrono",+ "cowlike",+ "email",+ "entity_access",+ "futures",+ "item_filters",+ "macro_user_id",+ "model-entity",+ "model_notifications",+ "models_soup",+ "notification",+ "rootcause",+ "serde",+ "serde_json",+ "soup",+ "soup_realtime",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "uuid",+ "workspace-hack",+]+[[package]]name = "authentication_service"version = "0.1.0"@@ -4810,6 +4840,7 @@ dependencies = ["apollo-compiler","async-graphql","async-stream",+ "attention_feed","axum","bot_id","bots",@@ -6571,6 +6602,7 @@ dependencies = ["async-graphql","async-graphql-axum","async-trait",+ "attention_feed","authentication_service_client","aws-sdk-dynamodb","aws-sdk-s3",@@ -9511,22 +9543,14 @@ version = "0.1.0"dependencies = ["async-graphql","async-stream",- "chrono",- "entity_access",+ "attention_feed","futures","graphql_common","graphql_notification","graphql_soup","macro_user_id",- "model-entity",- "model_notifications",- "notification",- "rootcause",- "serde_json","soup",- "tokio","tracing",- "uuid","work_feed","workspace-hack",]@@ -22885,27 +22909,18 @@ dependencies = [name = "work_feed"version = "0.1.0"dependencies = [- "activity",- "base64 0.22.1",+ "attention_feed","chrono",- "cowlike","document_sub_type",- "email",- "entity_access","filter_ast",- "futures","item_filters","macro_user_id","model-entity","model_notifications",- "models_soup","notification","rootcause","serde","serde_json",- "soup",- "soup_realtime",- "thiserror 2.0.18","tokio","tracing","uuid",diff --git a/Cargo.toml b/Cargo.tomlindex 9168ad9908..d9da61de40 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -21,6 +21,7 @@ members = ["crates/ai_billing","crates/ai_projections","crates/ai_usage",+ "crates/attention_feed","crates/bot_id","crates/bot_token","crates/bots",diff --git a/crates/activity/AGENTS.md b/crates/activity/AGENTS.mdindex 4890c4f353..60d3a2756d 100644--- a/crates/activity/AGENTS.md+++ b/crates/activity/AGENTS.md@@ -39,7 +39,7 @@ distribution.`EntityAccessService::get_users_by_entity`; change both together.- Used by: most domain crates with activity surfaces (`documents`, `forms`,`databases`, `initiative`, `messages`, `channels`, `soup`, `call`, `chat`,- `work_feed`, `projects`, `github`, `email`, `properties`) and `ai_tools`.+ `attention_feed`, `projects`, `github`, `email`, `properties`) and `ai_tools`.## Recipesdiff --git a/crates/attention_feed/AGENTS.md b/crates/attention_feed/AGENTS.mdnew file mode 100644index 0000000000..601d3851a5--- /dev/null+++ b/crates/attention_feed/AGENTS.md@@ -0,0 +1,62 @@+# attention_feed++## What it is++The shared layer under Macro's attention feeds: Home's work feed+(`crates/work_feed`) and the notifications inbox. It pages authorized, hydrated+candidates with their notifications, completes, reads and restores them, and+batches realtime changes into recomputes. Each feed keeps its own model on top.++## How it works++A feed builds a `CandidateRequest` (viewer, keying, own work, types, membership+filter) and hands `FeedReader::page` a closure that turns each `Loaded`+candidate into its own entry or drops it; the reader refills from later+candidate pages. Done turns entries into `Acknowledgment`s for `Acknowledger`,+whose `DoneReceipt` is the undo token. Subscriptions run `FeedTriggers` through+`live::coalesce` and recompute with `FeedReader::current`.++## Start here++- `src/domain/models.rs`: keys, revisions, cursors, receipts, candidates.+- `src/domain/reader.rs`: paging with refill, recompute by key.+- `src/domain/keying.rs`: which candidate a notification belongs to.+- `src/outbound/soup.rs`: the candidate source over Soup's attention query.++## Scope++- Owns: candidate paging and refill, notification loading per keying, done,+ seen and undo, inbox email archive on done, live trigger batching, viewer+ team lookup.+- Not here: items, stacks and primary reasons → `crates/work_feed`;+ candidate SQL, access gates and hydration → `crates/soup` (`attention.rs`);+ notification storage → `crates/notification`.++## Boundaries++- 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).++## Recipes++- Change how notifications key to candidates: `src/domain/keying.rs` and the+ matching `thread_keyed` SQL in `crates/soup/src/outbound/pg_soup_repo/attention.rs`,+ with tests on both sides.++## Checks++- `cargo test -p attention_feed --all-features`+- Feeds' tests use `test_support` (feature `test-utils`) for fixtures and fakes.++## Gotchas++- Revision, cursor and undo token JSON is a wire format clients hold across+ deploys; `models/test.rs` pins it.+- Under `ThreadScoped`, a `channel_message` candidate reads its channel's+ notifications; the feed scopes them to the thread.++## Related++- Rules: `.agents/rules/rust/architecture.md` · Docs: `docs/guides/add-notification-kind.md`diff --git a/crates/attention_feed/CLAUDE.md b/crates/attention_feed/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/crates/attention_feed/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/crates/attention_feed/Cargo.toml b/crates/attention_feed/Cargo.tomlnew file mode 100644index 0000000000..2335915398--- /dev/null+++ b/crates/attention_feed/Cargo.toml@@ -0,0 +1,50 @@+[package]+edition = "2024"+name = "attention_feed"+publish = false+version = "0.1.0"++[features]+default = []+# Viewer resolution at the entity access boundary, for GraphQL adapters.+inbound = ["entity_access/inbound"]+# Adapters over the services that own the feeds' data.+outbound = [+ "dep:activity",+ "dep:cowlike",+ "dep:email",+ "dep:models_soup",+ "dep:soup",+ "dep:soup_realtime",+]+# Notification fixtures and port fakes for the feeds' tests.+test-utils = []++[dependencies]+activity = { path = "../activity", default-features = false, features = ["realtime"], optional = true }+async-stream = { workspace = true }+base64 = { workspace = true }+chrono = { workspace = true, features = ["serde"] }+cowlike = { path = "../cowlike", optional = true }+email = { path = "../email", default-features = false, features = ["ports"], optional = true }+entity_access = { path = "../entity_access", default-features = false, features = ["ports"] }+futures = { workspace = true }+item_filters = { path = "../item_filters" }+macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }+model_notifications = { path = "../model_notifications" }+models_soup = { path = "../models_soup", optional = true }+notification = { path = "../notification" }+rootcause = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+soup = { path = "../soup", default-features = false, features = ["ports"], optional = true }+soup_realtime = { path = "../soup_realtime", default-features = false, features = ["ports"], optional = true }+thiserror = { workspace = true }+tokio = { workspace = true, features = ["sync", "time", "macros", "rt"] }+tracing = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "test-util"] }diff --git a/crates/attention_feed/src/domain.rs b/crates/attention_feed/src/domain.rsnew file mode 100644index 0000000000..5445ade61d--- /dev/null+++ b/crates/attention_feed/src/domain.rs@@ -0,0 +1,9 @@+//! Shared feed domain: models, ports, candidate keying, the reader, the+//! acknowledger and live batching.++pub mod acknowledge;+pub mod keying;+pub mod live;+pub mod models;+pub mod ports;+pub mod reader;diff --git a/crates/attention_feed/src/domain/acknowledge.rs b/crates/attention_feed/src/domain/acknowledge.rsnew file mode 100644index 0000000000..602417d7c0--- /dev/null+++ b/crates/attention_feed/src/domain/acknowledge.rs@@ -0,0 +1,167 @@+//! Completing, reading and restoring a viewer's attention.+//!+//! A feed decides which notifications an entry (or a part of one) stands+//! for; the acknowledger moves them, archives inbox email (mail's done),+//! tells the viewer's other sessions, and returns a receipt that undo+//! reverses exactly.++use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use uuid::Uuid;++use super::{+ models::{Acknowledgment, DoneReceipt, FeedKey, FeedViewer},+ ports::{FeedMail, FeedNotifications, FeedSignals, NotificationTransition},+};++#[cfg(test)]+mod test;++/// Moves a viewer's notifications through done, seen and undo.+pub struct Acknowledger<N, M, G> {+ notifications: N,+ mail: M,+ signals: G,+}++/// Values deduplicated in first-seen order.+fn unique<T: PartialEq>(values: impl IntoIterator<Item = T>) -> Vec<T> {+ let mut unique = Vec::new();+ for value in values {+ if !unique.contains(&value) {+ unique.push(value);+ }+ }+ unique+}++impl<N, M, G> Acknowledger<N, M, G>+where+ N: FeedNotifications,+ M: FeedMail,+ G: FeedSignals,+{+ /// Create the acknowledger over its ports.+ pub fn new(notifications: N, mail: M, signals: G) -> Self {+ Self {+ notifications,+ mail,+ signals,+ }+ }++ async fn signal(&self, user: &MacroUserIdStr<'static>, keys: &[FeedKey]) {+ self.signals+ .changed(+ user.clone(),+ keys.iter().map(|key| key.entity().clone()).collect(),+ )+ .await;+ }++ /// Move every acknowledged notification to done and archive the named+ /// threads. Archiving is best effort: the thread's notifications are+ /// already done, which removes its attention on their own.+ #[tracing::instrument(+ name = "attention_feed.acknowledge",+ skip_all,+ fields(user = %viewer.user, keys = acknowledgments.len()),+ err+ )]+ pub async fn acknowledge(+ &self,+ viewer: &FeedViewer,+ acknowledgments: Vec<Acknowledgment>,+ ) -> Result<DoneReceipt, Report> {+ let keys = unique(acknowledgments.iter().map(|ack| ack.key.clone()));+ let notification_ids = unique(+ acknowledgments+ .iter()+ .flat_map(|ack| ack.notification_ids.iter().copied()),+ );+ let threads = unique(acknowledgments.iter().filter_map(|ack| ack.archive_thread));++ let user = viewer.user.clone();+ let changed = if notification_ids.is_empty() {+ Vec::new()+ } else {+ self.notifications+ .transition(user.clone(), notification_ids, NotificationTransition::Done)+ .await?+ };+ let mut archived = Vec::new();+ for thread_id in threads {+ match self.mail.set_archived(user.clone(), thread_id, true).await {+ Ok(()) => archived.push(thread_id),+ Err(error) => {+ tracing::warn!(error = ?error, %thread_id, "failed to archive feed email")+ }+ }+ }+ self.signal(&user, &keys).await;+ Ok(DoneReceipt {+ keys: keys.iter().map(FeedKey::id).collect(),+ notification_ids: changed,+ archived_threads: archived,+ })+ }++ /// Reverse exactly what one acknowledgment changed. Returns the keys it+ /// touched, for the feed to recompute.+ #[tracing::instrument(name = "attention_feed.undo", skip_all, fields(user = %viewer.user), err)]+ pub async fn undo(+ &self,+ viewer: &FeedViewer,+ receipt: &DoneReceipt,+ ) -> Result<Vec<FeedKey>, Report> {+ let user = viewer.user.clone();+ if !receipt.notification_ids.is_empty() {+ self.notifications+ .transition(+ user.clone(),+ receipt.notification_ids.clone(),+ NotificationTransition::Undone,+ )+ .await?;+ }+ for thread_id in &receipt.archived_threads {+ if let Err(error) = self+ .set_archived(user.clone(), *thread_id, false)+ .await+ {+ tracing::warn!(error = ?error, %thread_id, "failed to unarchive feed email");+ }+ }+ let keys = receipt.feed_keys();+ self.signal(&user, &keys).await;+ Ok(keys)+ }++ /// Mark notifications seen for the entries `keys` and tell the viewer's+ /// other sessions. Returns the ids whose state changed.+ #[tracing::instrument(+ name = "attention_feed.seen",+ skip_all,+ fields(user = %viewer.user, notifications = notification_ids.len()),+ err+ )]+ pub async fn mark_seen(+ &self,+ viewer: &FeedViewer,+ keys: &[FeedKey],+ notification_ids: Vec<Uuid>,+ ) -> Result<Vec<Uuid>, Report> {+ let notification_ids = unique(notification_ids);+ if notification_ids.is_empty() {+ return Ok(Vec::new());+ }+ let user = viewer.user.clone();+ let changed = self+ .notifications+ .transition(user.clone(), notification_ids, NotificationTransition::Seen)+ .await?;+ self.signal(&user, keys).await;+ Ok(changed)+ }+}diff --git a/crates/attention_feed/src/domain/acknowledge/test.rs b/crates/attention_feed/src/domain/acknowledge/test.rsnew file mode 100644index 0000000000..be30bb616c--- /dev/null+++ b/crates/attention_feed/src/domain/acknowledge/test.rs@@ -0,0 +1,188 @@+use model_entity::EntityType;+use notification::domain::models::NotificationState;++use super::*;+use crate::test_support::*;++const DOC: u128 = 0xD0;+const MAIL: u128 = 0xE0;++type Subject = Acknowledger<FakeNotifications, FakeMail, FakeSignals>;++fn acknowledger(notifications: &FakeNotifications) -> (Subject, FakeMail, FakeSignals) {+ let mail = FakeMail::default();+ let signals = FakeSignals::default();+ (+ Acknowledger::new(notifications.clone(), mail.clone(), signals.clone()),+ mail,+ signals,+ )+}++fn key(entity_type: EntityType, id: u128) -> FeedKey {+ FeedKey::new(entity(entity_type, id))+}++#[tokio::test]+async fn acknowledge_completes_each_notification_once_and_archives_mail() {+ let notifications = FakeNotifications::with(vec![+ doc_comment(1, DOC, 0xA0, 0xA0, 5),+ doc_comment(2, DOC, 0xB0, 0xB0, 6),+ new_email(3, MAIL, 4, NotificationState::Unseen),+ ]);+ let (acknowledger, mail, signals) = acknowledger(¬ifications);+ let doc = key(EntityType::Document, DOC);+ let thread = key(EntityType::EmailThread, MAIL);++ let receipt = acknowledger+ .acknowledge(+ &viewer(),+ vec![+ Acknowledgment {+ key: doc.clone(),+ notification_ids: vec![uuid(1), uuid(2)],+ archive_thread: None,+ },+ // A second part of the same entry, overlapping the first.+ Acknowledgment {+ key: doc.clone(),+ notification_ids: vec![uuid(2)],+ archive_thread: None,+ },+ Acknowledgment {+ key: thread.clone(),+ notification_ids: vec![uuid(3)],+ archive_thread: Some(uuid(MAIL)),+ },+ ],+ )+ .await+ .unwrap();++ assert_eq!(receipt.keys, vec![doc.id(), thread.id()]);+ assert_eq!(receipt.notification_ids, vec![uuid(1), uuid(2), uuid(3)]);+ assert_eq!(receipt.archived_threads, vec![uuid(MAIL)]);+ assert_eq!(+ *notifications.transitions.lock().unwrap(),+ vec![(+ vec![uuid(1), uuid(2), uuid(3)],+ NotificationTransition::Done+ )]+ );+ assert_eq!(*mail.calls.lock().unwrap(), vec![(uuid(MAIL), true)]);+ assert_eq!(+ *signals.calls.lock().unwrap(),+ vec![vec![doc.entity().clone(), thread.entity().clone()]]+ );+}++#[tokio::test]+async fn acknowledging_nothing_still_reports_the_keys() {+ let notifications = FakeNotifications::default();+ let (acknowledger, mail, _) = acknowledger(¬ifications);+ let gone = key(EntityType::Document, DOC);+ let receipt = acknowledger+ .acknowledge(+ &viewer(),+ vec![Acknowledgment {+ key: gone.clone(),+ notification_ids: Vec::new(),+ archive_thread: None,+ }],+ )+ .await+ .unwrap();+ assert_eq!(receipt.feed_keys(), vec![gone]);+ assert!(receipt.notification_ids.is_empty());+ assert!(notifications.transitions.lock().unwrap().is_empty());+ assert!(mail.calls.lock().unwrap().is_empty());+}++#[tokio::test]+async fn undo_reverses_exactly_one_receipt() {+ let notifications = FakeNotifications::with(vec![+ doc_comment(1, DOC, 0xA0, 0xA0, 5),+ new_email(2, MAIL, 4, NotificationState::Unseen),+ ]);+ let (acknowledger, mail, signals) = acknowledger(¬ifications);+ let receipt = acknowledger+ .acknowledge(+ &viewer(),+ vec![+ Acknowledgment {+ key: key(EntityType::Document, DOC),+ notification_ids: vec![uuid(1)],+ archive_thread: None,+ },+ Acknowledgment {+ key: key(EntityType::EmailThread, MAIL),+ notification_ids: vec![uuid(2)],+ archive_thread: Some(uuid(MAIL)),+ },+ ],+ )+ .await+ .unwrap();++ let keys = acknowledger+ .undo(&viewer(), &DoneReceipt::decode(&receipt.encode()).unwrap())+ .await+ .unwrap();++ assert_eq!(+ keys,+ vec![+ key(EntityType::Document, DOC),+ key(EntityType::EmailThread, MAIL)+ ]+ );+ // Undone notifications come back seen.+ assert_eq!(notifications.state_of(uuid(1)), NotificationState::Seen);+ assert_eq!(notifications.state_of(uuid(2)), NotificationState::Seen);+ assert_eq!(+ *mail.calls.lock().unwrap(),+ vec![(uuid(MAIL), true), (uuid(MAIL), false)]+ );+ assert_eq!(signals.calls.lock().unwrap().len(), 2);+}++#[tokio::test]+async fn seen_never_reopens_done_notifications() {+ let done = with_state(&doc_comment(1, DOC, 0xA0, 0xA0, 5), NotificationState::Done);+ let notifications = FakeNotifications::with(vec![done, doc_comment(2, DOC, 0xB0, 0xB0, 6)]);+ let (acknowledger, _, signals) = acknowledger(¬ifications);+ let doc = key(EntityType::Document, DOC);++ let changed = acknowledger+ .mark_seen(+ &viewer(),+ std::slice::from_ref(&doc),+ vec![uuid(1), uuid(2), uuid(2)],+ )+ .await+ .unwrap();++ assert_eq!(changed, vec![uuid(2)]);+ assert_eq!(notifications.state_of(uuid(1)), NotificationState::Done);+ assert_eq!(notifications.state_of(uuid(2)), NotificationState::Seen);+ assert_eq!(+ *notifications.transitions.lock().unwrap(),+ vec![(vec![uuid(1), uuid(2)], NotificationTransition::Seen)]+ );+ assert_eq!(+ *signals.calls.lock().unwrap(),+ vec![vec![doc.entity().clone()]]+ );+}++#[tokio::test]+async fn seeing_nothing_changes_nothing() {+ let notifications = FakeNotifications::default();+ let (acknowledger, _, signals) = acknowledger(¬ifications);+ let changed = acknowledger+ .mark_seen(&viewer(), &[], Vec::new())+ .await+ .unwrap();+ assert!(changed.is_empty());+ assert!(signals.calls.lock().unwrap().is_empty());+}diff --git a/crates/attention_feed/src/domain/keying.rs b/crates/attention_feed/src/domain/keying.rsnew file mode 100644index 0000000000..7c58dbdd5b--- /dev/null+++ b/crates/attention_feed/src/domain/keying.rs@@ -0,0 +1,72 @@+//! Which candidate a notification belongs to, per keying.+//!+//! The candidate query (Soup's `attention` repository) keys notifications the+//! same way: under [`CandidateKeying::ThreadScoped`] a channel notification+//! that names a thread root keys to a `channel_message` candidate on it;+//! under [`CandidateKeying::FiledEntity`] every notification keys to its own+//! entity.++use model_entity::{Entity, EntityType};+use model_notifications::NotifEvent;+use notification::domain::models::UserNotificationRow;++use super::models::CandidateKeying;++#[cfg(test)]+mod test;++/// The channel thread root a channel notification is attributed to, if any:+/// the thread for replies, and the named message's thread (or the message+/// itself, which becomes the root) for mentions, reactions and document+/// mentions. Plain sends and channel-level events have none.+pub fn channel_thread_root(notification: &UserNotificationRow<NotifEvent>) -> Option<&str> {+ if notification.entity.entity_type != EntityType::Channel {+ return None;+ }+ match ¬ification.notification_metadata {+ NotifEvent::ChannelMessageReply(reply) => Some(reply.thread_id.as_str()),+ NotifEvent::ChannelMention(mention) => {+ Some(mention.thread_id.as_deref().unwrap_or(&mention.message_id))+ }+ NotifEvent::ChannelMessageReaction(reaction) => Some(+ reaction+ .thread_id+ .as_deref()+ .unwrap_or(&reaction.message_id),+ ),+ NotifEvent::DocumentMention(mention) => Some(+ mention+ .channel+ .thread_id+ .as_deref()+ .unwrap_or(&mention.channel.message_id),+ ),+ _ => None,+ }+}++/// The candidates a notification about its entity may affect.+///+/// Under [`CandidateKeying::ThreadScoped`] a channel notification can move+/// between the channel candidate and a thread candidate, so both are+/// recomputed; a plain send names the thread it may root. Under+/// [`CandidateKeying::FiledEntity`] only the notification's own entity.+pub fn trigger_keys(+ notification: &UserNotificationRow<NotifEvent>,+ keying: CandidateKeying,+) -> Vec<Entity<'static>> {+ let mut keys = vec![notification.entity.clone()];+ if keying == CandidateKeying::FiledEntity+ || notification.entity.entity_type != EntityType::Channel+ {+ return keys;+ }+ let thread = channel_thread_root(notification).or(match ¬ification.notification_metadata {+ NotifEvent::ChannelMessageSend(send) => Some(send.message_id.as_str()),+ _ => None,+ });+ if let Some(root) = thread {+ keys.push(EntityType::ChannelMessage.with_entity_string(root.to_string()));+ }+ keys+}diff --git a/crates/attention_feed/src/domain/keying/test.rs b/crates/attention_feed/src/domain/keying/test.rsnew file mode 100644index 0000000000..732c6c08e4--- /dev/null+++ b/crates/attention_feed/src/domain/keying/test.rs@@ -0,0 +1,75 @@+use super::*;+use crate::{domain::models::FeedNotification, test_support::*};++const CHANNEL: u128 = 0xC0;++fn thread(id: u128) -> Entity<'static> {+ entity(EntityType::ChannelMessage, id)+}++#[test]+fn thread_scoped_channel_notifications_recompute_the_channel_and_its_thread() {+ let channel = entity(EntityType::Channel, CHANNEL);+ let keys = |row: FeedNotification| trigger_keys(&row, CandidateKeying::ThreadScoped);+ assert_eq!(+ keys(channel_reply(1, CHANNEL, 0x70, 0x71, 1)),+ vec![channel.clone(), thread(0x70)]+ );+ assert_eq!(+ keys(channel_mention(2, CHANNEL, 0x72, None, 1)),+ vec![channel.clone(), thread(0x72)]+ );+ // A plain send may root a thread that absorbs it.+ assert_eq!(+ keys(channel_send(3, CHANNEL, 0x73, 1)),+ vec![channel.clone(), thread(0x73)]+ );+ assert_eq!(keys(channel_invite(4, CHANNEL, 1)), vec![channel]);+}++#[test]+fn filed_entity_notifications_recompute_only_their_entity() {+ let channel = entity(EntityType::Channel, CHANNEL);+ for row in [+ channel_reply(1, CHANNEL, 0x70, 0x71, 1),+ channel_mention(2, CHANNEL, 0x72, Some(0x70), 1),+ channel_reaction(3, CHANNEL, 0x74, Some(0x70), 1),+ channel_send(4, CHANNEL, 0x73, 1),+ ] {+ assert_eq!(+ trigger_keys(&row, CandidateKeying::FiledEntity),+ vec![channel.clone()]+ );+ }+}++#[test]+fn other_notifications_recompute_their_entity() {+ let document = entity(EntityType::Document, 0xD0);+ for keying in [CandidateKeying::ThreadScoped, CandidateKeying::FiledEntity] {+ assert_eq!(+ trigger_keys(&doc_comment(1, 0xD0, 0xA0, 0xA0, 1), keying),+ vec![document.clone()]+ );+ }+}++#[test]+fn thread_roots_follow_the_named_message() {+ let root = |row: FeedNotification| channel_thread_root(&row).map(str::to_string);+ assert_eq!(+ root(channel_reply(1, CHANNEL, 0x70, 0x71, 1)),+ Some(uuid(0x70).to_string())+ );+ // A root mention or reaction names the thread its message would root.+ assert_eq!(+ root(channel_mention(2, CHANNEL, 0x72, None, 1)),+ Some(uuid(0x72).to_string())+ );+ assert_eq!(+ root(channel_reaction(3, CHANNEL, 0x74, Some(0x70), 1)),+ Some(uuid(0x70).to_string())+ );+ assert_eq!(root(channel_send(4, CHANNEL, 0x73, 1)), None);+ assert_eq!(root(doc_comment(5, 0xD0, 0xA0, 0xA0, 1)), None);+}diff --git a/crates/attention_feed/src/domain/live.rs b/crates/attention_feed/src/domain/live.rsnew file mode 100644index 0000000000..677701c412--- /dev/null+++ b/crates/attention_feed/src/domain/live.rs@@ -0,0 +1,58 @@+//! Batching realtime triggers into recomputes.++use std::{collections::HashSet, time::Duration};++use futures::Stream;+use tokio::sync::mpsc::Receiver;++use super::models::{FeedKey, FeedTrigger, LiveBatch};++#[cfg(test)]+mod test;++/// How long triggers are collected before one recompute, so a burst of+/// realtime events (a busy thread, a bulk done) costs one feed lookup.+pub const COALESCE_WINDOW: Duration = Duration::from_millis(300);++/// Add one trigger to `batch`, each key once.+fn absorb(batch: &mut LiveBatch, seen: &mut HashSet<FeedKey>, trigger: FeedTrigger) {+ match trigger {+ FeedTrigger::Changed(entities) => {+ for entity in entities {+ let key = FeedKey::new(entity);+ if seen.insert(key.clone()) {+ batch.keys.push(key);+ }+ }+ }+ FeedTrigger::Invalidated => batch.invalidated = true,+ }+}++/// One batch per burst of triggers: the first trigger opens a `window`,+/// everything arriving within it joins the batch. The stream ends when the+/// triggers end.+pub fn coalesce(+ mut triggers: Receiver<FeedTrigger>,+ window: Duration,+) -> impl Stream<Item = LiveBatch> {+ async_stream::stream! {+ while let Some(first) = triggers.recv().await {+ let mut batch = LiveBatch::default();+ let mut seen = HashSet::new();+ absorb(&mut batch, &mut seen, first);+ let deadline = tokio::time::sleep(window);+ tokio::pin!(deadline);+ loop {+ tokio::select! {+ () = &mut deadline => break,+ next = triggers.recv() => match next {+ Some(trigger) => absorb(&mut batch, &mut seen, trigger),+ None => break,+ },+ }+ }+ yield batch;+ }+ }+}diff --git a/crates/attention_feed/src/domain/live/test.rs b/crates/attention_feed/src/domain/live/test.rsnew file mode 100644index 0000000000..85b094f034--- /dev/null+++ b/crates/attention_feed/src/domain/live/test.rs@@ -0,0 +1,75 @@+use futures::StreamExt;+use model_entity::EntityType;+use tokio::sync::mpsc;++use super::*;++fn doc() -> model_entity::Entity<'static> {+ EntityType::Document.with_entity_string("d".to_string())+}++fn chat() -> model_entity::Entity<'static> {+ EntityType::Chat.with_entity_string("c".to_string())+}++#[test]+fn batches_deduplicate_keys_in_arrival_order() {+ let mut batch = LiveBatch::default();+ let mut seen = HashSet::new();+ absorb(+ &mut batch,+ &mut seen,+ FeedTrigger::Changed(vec![doc(), chat()]),+ );+ absorb(&mut batch, &mut seen, FeedTrigger::Changed(vec![doc()]));+ assert_eq!(batch.keys, vec![FeedKey::new(doc()), FeedKey::new(chat())]);+ assert!(!batch.invalidated);++ absorb(&mut batch, &mut seen, FeedTrigger::Invalidated);+ assert!(batch.invalidated);+}++#[tokio::test(start_paused = true)]+async fn a_burst_inside_one_window_is_one_batch() {+ let (sender, receiver) = mpsc::channel(8);+ let batches = coalesce(receiver, COALESCE_WINDOW);+ futures::pin_mut!(batches);++ sender+ .send(FeedTrigger::Changed(vec![doc()]))+ .await+ .unwrap();+ sender+ .send(FeedTrigger::Changed(vec![chat(), doc()]))+ .await+ .unwrap();+ let batch = batches.next().await.unwrap();+ assert_eq!(batch.keys, vec![FeedKey::new(doc()), FeedKey::new(chat())]);++ // After the window closes, the next trigger opens a new batch.+ sender.send(FeedTrigger::Invalidated).await.unwrap();+ let batch = batches.next().await.unwrap();+ assert!(batch.keys.is_empty());+ assert!(batch.invalidated);++ drop(sender);+ assert!(batches.next().await.is_none());+}++#[tokio::test(start_paused = true)]+async fn closing_the_triggers_flushes_the_open_batch() {+ let (sender, receiver) = mpsc::channel(8);+ let batches = coalesce(receiver, COALESCE_WINDOW);+ futures::pin_mut!(batches);++ sender+ .send(FeedTrigger::Changed(vec![doc()]))+ .await+ .unwrap();+ drop(sender);+ assert_eq!(+ batches.next().await.unwrap().keys,+ vec![FeedKey::new(doc())]+ );+ assert!(batches.next().await.is_none());+}diff --git a/crates/attention_feed/src/domain/models.rs b/crates/attention_feed/src/domain/models.rsnew file mode 100644index 0000000000..4ce654e11c--- /dev/null+++ b/crates/attention_feed/src/domain/models.rs@@ -0,0 +1,373 @@+//! Shared feed models: viewers, keys, tokens, candidates and acknowledgment.++use std::{str::FromStr, sync::Arc};++use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use chrono::{DateTime, Utc};+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};+use item_filters::ast::EntityFilterAst;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};+use model_notifications::NotifEvent;+use notification::domain::models::{NotificationState, UserNotificationRow};+use serde::{Deserialize, Serialize};+use uuid::Uuid;++#[cfg(test)]+mod test;++/// A notification row as feeds read it.+pub type FeedNotification = Arc<UserNotificationRow<NotifEvent>>;++/// The caller a feed request is evaluated for.+#[derive(Debug, Clone)]+pub struct FeedViewer {+ /// The authenticated user.+ pub user: MacroUserIdStr<'static>,+ /// The user's team membership, when they have one; foreign entities+ /// stored for the team and CRM records are visible through it.+ pub team: Option<EntityAccessReceipt<MemberTeamRole>>,+}++/// Stable per-viewer identity of a feed entry: the entity its candidate is+/// keyed on.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct FeedKey(Entity<'static>);++/// A feed key id that does not name an entity.+#[derive(Debug, thiserror::Error)]+#[error("invalid feed key")]+pub struct InvalidFeedKey;++impl FeedKey {+ /// The key for `entity`.+ pub fn new(entity: Entity<'static>) -> Self {+ Self(entity)+ }++ /// The entity the key names.+ pub fn entity(&self) -> &Entity<'static> {+ &self.0+ }++ /// Consume the key, returning its entity.+ pub fn into_entity(self) -> Entity<'static> {+ self.0+ }++ /// The key's global id: `<entity type>:<entity id>`.+ pub fn id(&self) -> String {+ format!("{}:{}", self.0.entity_type, self.0.entity_id)+ }++ /// Parse an id produced by [`Self::id`].+ pub fn parse(id: &str) -> Result<Self, InvalidFeedKey> {+ let (entity_type, entity_id) = id.split_once(':').ok_or(InvalidFeedKey)?;+ if entity_id.is_empty() {+ return Err(InvalidFeedKey);+ }+ let entity_type = EntityType::from_str(entity_type).map_err(|_| InvalidFeedKey)?;+ Ok(Self(entity_type.with_entity_string(entity_id.to_string())))+ }+}++/// How a feed keys the notifications that place its candidates.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum CandidateKeying {+ /// A notification about a channel thread (a reply, a mention, a+ /// reaction or a document mention, which name a thread root) keys to a+ /// `channel_message` candidate on that root; every other notification+ /// keys to the entity it is filed under. Home's work feed.+ ThreadScoped,+ /// Every notification keys to the entity it is filed under, so a+ /// channel's notifications, its threads' included, place one candidate.+ FiledEntity,+}++/// The attention one entry acknowledges. Done acknowledges only what was+/// observed, so a notification arriving later keeps the entry active.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]+pub struct FeedRevision {+ /// The newest notification observed.+ #[serde(rename = "a", default, skip_serializing_if = "Option::is_none")]+ pub attention_through: Option<DateTime<Utc>>,+}++/// A revision token that does not decode.+#[derive(Debug, thiserror::Error)]+#[error("invalid feed revision")]+pub struct InvalidFeedRevision;++impl FeedRevision {+ /// The revision covering `notifications`: their newest creation time.+ pub fn covering<'a>(notifications: impl IntoIterator<Item = &'a FeedNotification>) -> Self {+ Self {+ attention_through: notifications+ .into_iter()+ .map(|notification| notification.created_at)+ .max(),+ }+ }++ /// The ids of `notifications` this revision acknowledges, in order.+ pub fn acknowledged<'a>(+ &self,+ notifications: impl IntoIterator<Item = &'a FeedNotification>,+ ) -> Vec<Uuid> {+ let Some(through) = self.attention_through else {+ return Vec::new();+ };+ notifications+ .into_iter()+ .filter(|notification| notification.created_at <= through)+ .map(|notification| notification.notification_id)+ .collect()+ }++ /// The opaque token clients echo back.+ pub fn encode(&self) -> String {+ encode_token(self)+ }++ /// Decode a token produced by [`Self::encode`].+ pub fn decode(token: &str) -> Result<Self, InvalidFeedRevision> {+ decode_token(token).ok_or(InvalidFeedRevision)+ }+}++/// Where the next page of a feed starts.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct FeedPosition {+ /// The last walked candidate's sort time.+ #[serde(rename = "s")]+ pub sort_at: DateTime<Utc>,+ /// The last walked candidate's entity id.+ #[serde(rename = "i")]+ pub entity_id: String,+}++/// A cursor that does not decode.+#[derive(Debug, thiserror::Error)]+#[error("invalid feed cursor")]+pub struct InvalidFeedCursor;++impl FeedPosition {+ /// The opaque cursor clients send back for the next page.+ pub fn encode(&self) -> String {+ encode_token(self)+ }++ /// Decode a cursor produced by [`Self::encode`].+ pub fn decode(cursor: &str) -> Result<Self, InvalidFeedCursor> {+ decode_token(cursor).ok_or(InvalidFeedCursor)+ }+}++/// Facts about a candidate's entity that scoping and state depend on.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct EntityFacts {+ /// For a channel thread, the channel whose notifications it shares.+ pub thread_channel: Option<Uuid>,+ /// For an email thread, its mailbox state.+ pub mail: Option<MailFacts>,+}++/// An email thread's mailbox state.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct MailFacts {+ /// The thread is in the inbox (not archived).+ pub inbox_visible: bool,+ /// The thread has no unread mail.+ pub is_read: bool,+}++/// A request for one page of hydrated, authorized candidates.+#[derive(Debug, Clone)]+pub struct CandidateRequest {+ /// Who the feed is for.+ pub viewer: FeedViewer,+ /// How notifications key to candidates.+ pub keying: CandidateKeying,+ /// Whether the viewer's own work admits candidates besides attention.+ pub own_work: bool,+ /// Candidate entity types to include.+ pub types: Vec<EntityType>,+ /// The feed's membership filter, applied by the source's access gates+ /// and hydration.+ pub filter: EntityFilterAst,+ /// Maximum candidates to return.+ pub limit: u16,+ /// Resume after this position; `None` for the first page.+ pub after: Option<FeedPosition>,+ /// Restrict to these candidate keys, for recomputing known entries.+ pub only: Option<Vec<Entity<'static>>>,+}++/// One hydrated, authorized candidate.+#[derive(Debug, Clone)]+pub struct Candidate<E> {+ /// The candidate key.+ pub key: Entity<'static>,+ /// The hydrated entity.+ pub entity: E,+ /// Facts used for scoping and state.+ pub facts: EntityFacts,+ /// The candidate's live attention time, when it has any.+ pub attention_at: Option<DateTime<Utc>>,+ /// The viewer's own-work time, when it has any.+ pub touched_at: Option<DateTime<Utc>>,+ /// Where the candidate sits in the feed.+ pub sort_at: DateTime<Utc>,+}++/// One page of hydrated candidates.+#[derive(Debug)]+pub struct CandidatePage<E> {+ /// The page's candidates, newest first.+ pub items: Vec<Candidate<E>>,+ /// Where the next page starts; `None` once the feed is exhausted.+ pub next: Option<FeedPosition>,+}++/// A candidate with the viewer's active notifications its scope reads from:+/// its own entity's, or for a thread-scoped channel thread its channel's.+#[derive(Debug, Clone)]+pub struct Loaded<E> {+ /// The candidate.+ pub candidate: Candidate<E>,+ /// The active (unseen or seen) notifications, newest first.+ pub notifications: Vec<FeedNotification>,+}++/// One page of a feed's own entries.+#[derive(Debug)]+pub struct FeedPage<T> {+ /// The entries, in feed order.+ pub entries: Vec<T>,+ /// Where the next page starts; `None` once the feed is exhausted.+ pub next: Option<FeedPosition>,+}++/// What completing one entry, or part of one, changes.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Acknowledgment {+ /// The entry the notifications belong to.+ pub key: FeedKey,+ /// The viewer's notifications to move to done.+ pub notification_ids: Vec<Uuid>,+ /// An inbox email thread to archive, mail's own done.+ pub archive_thread: Option<Uuid>,+}++/// Everything one acknowledgment changed, so undo can reverse exactly those+/// effects and nothing that happened since.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct DoneReceipt {+ /// The ids of the keys the operation touched.+ #[serde(rename = "k")]+ pub keys: Vec<String>,+ /// Notifications this operation moved to done.+ #[serde(rename = "n", default)]+ pub notification_ids: Vec<Uuid>,+ /// Email threads this operation archived.+ #[serde(rename = "e", default)]+ pub archived_threads: Vec<Uuid>,+}++/// An undo token that does not decode.+#[derive(Debug, thiserror::Error)]+#[error("invalid undo token")]+pub struct InvalidUndoToken;++impl DoneReceipt {+ /// The opaque undo token returned to the caller.+ pub fn encode(&self) -> String {+ encode_token(self)+ }++ /// Decode a token produced by [`Self::encode`].+ pub fn decode(token: &str) -> Result<Self, InvalidUndoToken> {+ decode_token(token).ok_or(InvalidUndoToken)+ }++ /// The keys this receipt touched.+ pub fn feed_keys(&self) -> Vec<FeedKey> {+ self.keys+ .iter()+ .filter_map(|id| FeedKey::parse(id).ok())+ .collect()+ }+}++/// A change that may affect one viewer's entries, from any realtime source.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum FeedTrigger {+ /// These candidate keys may have changed.+ Changed(Vec<Entity<'static>>),+ /// Changes may have been missed; mounted feeds must refetch.+ Invalidated,+}++/// The triggers collected for one recompute.+#[derive(Debug, Default, PartialEq, Eq)]+pub struct LiveBatch {+ /// Keys to recompute, in arrival order, each once.+ pub keys: Vec<FeedKey>,+ /// Whether any trigger said changes may have been missed.+ pub invalidated: bool,+}++/// Errors returned by feed services.+#[derive(Debug, thiserror::Error)]+pub enum FeedError {+ /// The caller sent an invalid cursor, revision, id or undo token.+ #[error("{0}")]+ InvalidInput(&'static str),+ /// A dependency failed.+ #[error("the feed is unavailable: {0}")]+ Unavailable(rootcause::Report),+}++impl From<rootcause::Report> for FeedError {+ fn from(report: rootcause::Report) -> Self {+ Self::Unavailable(report)+ }+}++/// Whether a notification makes its entry unread. Channel events other than+/// messages, mentions and reactions (invites, calls) never do.+pub fn counts_as_unseen(notification: &UserNotificationRow<NotifEvent>) -> bool {+ if notification.state != NotificationState::Unseen {+ return false;+ }+ if notification.entity.entity_type != EntityType::Channel {+ return true;+ }+ matches!(+ notification.notification_metadata,+ NotifEvent::ChannelMention(_)+ | NotifEvent::ChannelMessageSend(_)+ | NotifEvent::ChannelMessageReaction(_)+ | NotifEvent::ChannelMessageReply(_)+ | NotifEvent::DocumentMention(_)+ )+}++/// Sort notifications newest first, breaking ties by id for a stable order.+pub fn sort_newest_first(notifications: &mut [FeedNotification]) {+ notifications.sort_by(|a, b| {+ b.created_at+ .cmp(&a.created_at)+ .then_with(|| b.notification_id.cmp(&a.notification_id))+ });+}++fn encode_token<T: Serialize>(value: &T) -> String {+ let json = serde_json::to_vec(value).expect("feed tokens serialize");+ URL_SAFE_NO_PAD.encode(json)+}++fn decode_token<T: for<'de> Deserialize<'de>>(token: &str) -> Option<T> {+ let json = URL_SAFE_NO_PAD.decode(token).ok()?;+ serde_json::from_slice(&json).ok()+}diff --git a/crates/attention_feed/src/domain/models/test.rs b/crates/attention_feed/src/domain/models/test.rsnew file mode 100644index 0000000000..bd82166ee1--- /dev/null+++ b/crates/attention_feed/src/domain/models/test.rs@@ -0,0 +1,95 @@+use super::*;+use crate::test_support::{at, doc_comment, uuid};++#[test]+fn key_ids_round_trip() {+ let key = FeedKey::new(EntityType::ChannelMessage.with_entity_string(uuid(7).to_string()));+ let id = key.id();+ assert_eq!(id, format!("channel_message:{}", uuid(7)));+ assert_eq!(FeedKey::parse(&id).unwrap(), key);+}++#[test]+fn malformed_key_ids_are_rejected() {+ for id in ["", "document", "document:", "not_a_type:abc"] {+ assert!(FeedKey::parse(id).is_err(), "{id} parsed");+ }+}++#[test]+fn tokens_round_trip() {+ let revision = FeedRevision {+ attention_through: Some(at(5)),+ };+ assert_eq!(FeedRevision::decode(&revision.encode()).unwrap(), revision);++ let position = FeedPosition {+ sort_at: at(9),+ entity_id: uuid(3).to_string(),+ };+ assert_eq!(FeedPosition::decode(&position.encode()).unwrap(), position);++ let receipt = DoneReceipt {+ keys: vec![format!("document:{}", uuid(1))],+ notification_ids: vec![uuid(2)],+ archived_threads: vec![uuid(3)],+ };+ assert_eq!(DoneReceipt::decode(&receipt.encode()).unwrap(), receipt);+ assert_eq!(+ receipt.feed_keys(),+ vec![FeedKey::new(+ EntityType::Document.with_entity_string(uuid(1).to_string())+ )]+ );+}++#[test]+fn tokens_keep_the_work_feed_wire_format() {+ // Clients hold revisions, cursors and undo tokens across deploys.+ assert_eq!(+ serde_json::to_value(FeedRevision {+ attention_through: Some(at(5)),+ })+ .unwrap(),+ serde_json::json!({ "a": "2024-06-01T10:05:00Z" })+ );+ assert_eq!(+ serde_json::to_value(DoneReceipt {+ keys: vec!["document:d".to_string()],+ notification_ids: Vec::new(),+ archived_threads: Vec::new(),+ })+ .unwrap(),+ serde_json::json!({ "k": ["document:d"], "n": [], "e": [] })+ );+}++#[test]+fn garbage_tokens_are_rejected() {+ assert!(FeedRevision::decode("not base64!").is_err());+ assert!(FeedPosition::decode("e30").is_err());+ assert!(DoneReceipt::decode("").is_err());+}++#[test]+fn a_revision_acknowledges_what_it_covers() {+ let older = doc_comment(1, 0xD0, 0xA0, 0xA0, 5);+ let newer = doc_comment(2, 0xD0, 0xB0, 0xB0, 8);+ let notifications = [newer.clone(), older.clone()];+ let revision = FeedRevision::covering(¬ifications);+ assert_eq!(revision.attention_through, Some(at(8)));+ assert_eq!(+ revision.acknowledged(¬ifications),+ vec![uuid(2), uuid(1)]+ );++ let observed = FeedRevision {+ attention_through: Some(at(6)),+ };+ assert_eq!(observed.acknowledged(¬ifications), vec![uuid(1)]);+ assert!(+ FeedRevision::default()+ .acknowledged(¬ifications)+ .is_empty()+ );+}diff --git a/crates/attention_feed/src/domain/ports.rs b/crates/attention_feed/src/domain/ports.rsnew file mode 100644index 0000000000..35bcefba66--- /dev/null+++ b/crates/attention_feed/src/domain/ports.rs@@ -0,0 +1,92 @@+//! Capabilities feeds need from the domains that own their data.++use std::collections::HashMap;++use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;+use rootcause::Report;+use uuid::Uuid;++use super::models::{+ CandidateKeying, CandidatePage, CandidateRequest, FeedNotification, FeedTrigger,+};++/// Lists hydrated, authorized candidates in feed order. A candidate the+/// viewer cannot open, or that the request's filter rejects, is never+/// returned.+pub trait CandidateSource: Send + Sync + 'static {+ /// The hydrated entity carried by each candidate.+ type Entity: Send + Sync + 'static;++ /// Fetch one page of candidates.+ fn page(+ &self,+ request: CandidateRequest,+ ) -> impl Future<Output = Result<CandidatePage<Self::Entity>, Report>> + Send;+}++/// The state a viewer's notifications move to.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum NotificationTransition {+ /// Read; never reopens a done notification.+ Seen,+ /// Completed.+ Done,+ /// Back from done to seen.+ Undone,+}++/// Reads and transitions the viewer's notifications.+pub trait FeedNotifications: Send + Sync + 'static {+ /// The viewer's active (unseen or seen) notifications about each entity.+ fn active(+ &self,+ user: MacroUserIdStr<'static>,+ entities: Vec<Entity<'static>>,+ ) -> impl Future<Output = Result<HashMap<Entity<'static>, Vec<FeedNotification>>, Report>> + Send;++ /// Move the viewer's notifications through `transition`. Returns the+ /// ids whose state changed.+ fn transition(+ &self,+ user: MacroUserIdStr<'static>,+ notification_ids: Vec<Uuid>,+ transition: NotificationTransition,+ ) -> impl Future<Output = Result<Vec<Uuid>, Report>> + Send;+}++/// Archives email threads; mail's notion of done.+pub trait FeedMail: Send + Sync + 'static {+ /// Archive or unarchive one of the viewer's threads.+ fn set_archived(+ &self,+ user: MacroUserIdStr<'static>,+ thread_id: Uuid,+ archived: bool,+ ) -> impl Future<Output = Result<(), Report>> + Send;+}++/// Tells the viewer's other sessions that entries changed in ways their+/// realtime streams do not report, such as notifications completed here.+pub trait FeedSignals: Send + Sync + 'static {+ /// Best effort: failures are logged, never returned.+ fn changed(+ &self,+ user: MacroUserIdStr<'static>,+ entities: Vec<Entity<'static>>,+ ) -> impl Future<Output = ()> + Send;+}++/// Realtime changes that may affect a viewer's entries.+pub trait FeedTriggers: Send + Sync + 'static {+ /// Subscribe to triggers for `user`, keyed the way `keying` keys+ /// candidates. With `own_work`, the viewer's own actions trigger too.+ /// The receiver closes when the underlying streams end; a subscriber that+ /// falls behind receives [`FeedTrigger::Invalidated`] first.+ fn subscribe(+ &self,+ user: MacroUserIdStr<'static>,+ keying: CandidateKeying,+ own_work: bool,+ ) -> tokio::sync::mpsc::Receiver<FeedTrigger>;+}diff --git a/crates/attention_feed/src/domain/reader.rs b/crates/attention_feed/src/domain/reader.rsnew file mode 100644index 0000000000..c84e83c42e--- /dev/null+++ b/crates/attention_feed/src/domain/reader.rs@@ -0,0 +1,211 @@+//! Paging and recomputing a feed's candidates with their notifications.+//!+//! A feed builds its own entries from loaded candidates and may drop some (an+//! item with no reason left, a group with only hidden notifications). The+//! reader refills a page from later candidate pages until it holds the+//! requested number of entries or the feed is exhausted, in a bounded number+//! of rounds, and the cursor always points just past the last candidate the+//! feed was shown, kept or dropped, so nothing repeats or is skipped.++use std::collections::{HashMap, HashSet};++use model_entity::{Entity, EntityType};+use rootcause::Report;++use super::{+ models::{+ Candidate, CandidateKeying, CandidateRequest, FeedKey, FeedPage, FeedPosition, FeedViewer,+ Loaded, sort_newest_first,+ },+ ports::{CandidateSource, FeedNotifications},+};++#[cfg(test)]+mod test;++/// Most candidate pages one feed page reads while refilling after drops.+pub const MAX_FILL_ROUNDS: usize = 4;++/// Most candidate keys recomputed per source request.+const RECOMPUTE_CHUNK: usize = 200;++/// Reads candidates and the notifications their scopes draw from.+pub struct FeedReader<S, N> {+ source: S,+ notifications: N,+}++/// The entity whose notifications a candidate reads: a thread-scoped channel+/// thread shares its channel's; every other candidate reads its own.+fn notification_source<E>(+ candidate: &Candidate<E>,+ keying: CandidateKeying,+) -> Option<Entity<'static>> {+ match (keying, candidate.key.entity_type) {+ (CandidateKeying::ThreadScoped, EntityType::ChannelMessage) => candidate+ .facts+ .thread_channel+ .map(|channel| EntityType::Channel.with_entity_string(channel.to_string())),+ _ => Some(candidate.key.clone()),+ }+}++fn position<E>(candidate: &Candidate<E>) -> FeedPosition {+ FeedPosition {+ sort_at: candidate.sort_at,+ entity_id: candidate.key.entity_id.to_string(),+ }+}++impl<S, N> FeedReader<S, N>+where+ S: CandidateSource,+ N: FeedNotifications,+{+ /// Create the reader over its ports.+ pub fn new(source: S, notifications: N) -> Self {+ Self {+ source,+ notifications,+ }+ }++ /// Load each candidate's notifications, in candidate order.+ async fn load(+ &self,+ viewer: &FeedViewer,+ keying: CandidateKeying,+ candidates: Vec<Candidate<S::Entity>>,+ ) -> Result<Vec<Loaded<S::Entity>>, Report> {+ let mut sources = Vec::new();+ let mut seen = HashSet::new();+ for source in candidates+ .iter()+ .filter_map(|candidate| notification_source(candidate, keying))+ {+ if seen.insert(source.clone()) {+ sources.push(source);+ }+ }+ let loaded = if sources.is_empty() {+ HashMap::new()+ } else {+ self.notifications+ .active(viewer.user.clone(), sources)+ .await?+ };+ Ok(candidates+ .into_iter()+ .map(|candidate| {+ let mut notifications = notification_source(&candidate, keying)+ .and_then(|source| loaded.get(&source).cloned())+ .unwrap_or_default();+ sort_newest_first(&mut notifications);+ Loaded {+ candidate,+ notifications,+ }+ })+ .collect())+ }++ /// One page of entries built by `build`, which drops a candidate by+ /// returning `None`. Reads further candidate pages until `request.limit`+ /// entries are kept, the feed ends, or [`MAX_FILL_ROUNDS`] pages were+ /// read.+ #[tracing::instrument(+ name = "attention_feed.page",+ skip_all,+ fields(+ user = %request.viewer.user,+ keying = ?request.keying,+ limit = request.limit,+ fill_rounds = tracing::field::Empty,+ entries = tracing::field::Empty,+ has_next = tracing::field::Empty,+ ),+ err+ )]+ pub async fn page<T>(+ &self,+ request: CandidateRequest,+ mut build: impl FnMut(Loaded<S::Entity>) -> Option<T>,+ ) -> Result<FeedPage<T>, Report> {+ let limit = usize::from(request.limit);+ let mut entries = Vec::with_capacity(limit);+ let mut after = request.after.clone();+ let mut rounds = 0;+ 'read: for _ in 0..MAX_FILL_ROUNDS {+ rounds += 1;+ let page = self+ .source+ .page(CandidateRequest {+ after: after.clone(),+ ..request.clone()+ })+ .await?;+ let loaded = self+ .load(&request.viewer, request.keying, page.items)+ .await?;+ let total = loaded.len();+ for (index, item) in loaded.into_iter().enumerate() {+ let walked = position(&item.candidate);+ if let Some(entry) = build(item) {+ entries.push(entry);+ }+ if entries.len() == limit && index + 1 < total {+ // Full before the page ran out: resume just past the+ // last candidate walked.+ after = Some(walked);+ break 'read;+ }+ }+ after = page.next;+ if entries.len() == limit || after.is_none() {+ break;+ }+ }+ let span = tracing::Span::current();+ span.record("fill_rounds", rounds);+ span.record("entries", entries.len());+ span.record("has_next", after.is_some());+ Ok(FeedPage {+ entries,+ next: after,+ })+ }++ /// The current candidates for `keys` in `request`'s feed, loaded, keyed+ /// by key. Keys the feed no longer admits are absent.+ #[tracing::instrument(+ name = "attention_feed.current",+ skip_all,+ fields(user = %request.viewer.user, keying = ?request.keying, keys = keys.len()),+ err+ )]+ pub async fn current(+ &self,+ request: CandidateRequest,+ keys: &[FeedKey],+ ) -> Result<HashMap<FeedKey, Loaded<S::Entity>>, Report> {+ let mut current = HashMap::with_capacity(keys.len());+ for chunk in keys.chunks(RECOMPUTE_CHUNK) {+ let page = self+ .source+ .page(CandidateRequest {+ limit: u16::try_from(chunk.len()).unwrap_or(u16::MAX),+ after: None,+ only: Some(chunk.iter().map(|key| key.entity().clone()).collect()),+ ..request.clone()+ })+ .await?;+ for loaded in self+ .load(&request.viewer, request.keying, page.items)+ .await?+ {+ current.insert(FeedKey::new(loaded.candidate.key.clone()), loaded);+ }+ }+ Ok(current)+ }+}diff --git a/crates/attention_feed/src/domain/reader/test.rs b/crates/attention_feed/src/domain/reader/test.rsnew file mode 100644index 0000000000..e3638d1a3a--- /dev/null+++ b/crates/attention_feed/src/domain/reader/test.rs@@ -0,0 +1,213 @@+use item_filters::ast::EntityFilterAst;++use super::*;+use crate::{domain::models::FeedNotification, test_support::*};++const CHANNEL: u128 = 0xC0;+const THREAD: u128 = 0x70;++type Reader = FeedReader<FakeSource<u32>, FakeNotifications>;++fn reader(candidates: Vec<Candidate<u32>>, notifications: Vec<FeedNotification>) -> Reader {+ FeedReader::new(+ FakeSource::with(candidates),+ FakeNotifications::with(notifications),+ )+}++fn request(keying: CandidateKeying, limit: u16) -> CandidateRequest {+ CandidateRequest {+ viewer: viewer(),+ keying,+ own_work: true,+ types: Vec::new(),+ filter: EntityFilterAst::default(),+ limit,+ after: None,+ only: None,+ }+}++/// Documents labelled by their id, newest first: document `n` sorts at+/// minute `n`.+fn documents(ids: impl IntoIterator<Item = u32>) -> Vec<Candidate<u32>> {+ ids.into_iter()+ .map(|n| {+ candidate(+ n,+ entity(EntityType::Document, u128::from(n)),+ Some(n),+ None,+ )+ })+ .collect()+}++#[tokio::test]+async fn a_page_refills_after_dropped_candidates() {+ let reader = reader(documents((1..=9).rev()), Vec::new());+ // Keep even documents only, two per page of candidates.+ let page = reader+ .page(request(CandidateKeying::FiledEntity, 2), |loaded| {+ (loaded.candidate.entity % 2 == 0).then_some(loaded.candidate.entity)+ })+ .await+ .unwrap();+ assert_eq!(page.entries, vec![8, 6]);+ // The cursor sits just past the last candidate walked, kept or dropped.+ let next = page.next.unwrap();+ assert_eq!(next.entity_id, uuid(6).to_string());++ let mut second = request(CandidateKeying::FiledEntity, 2);+ second.after = Some(next);+ let page = reader+ .page(second, |loaded| {+ (loaded.candidate.entity % 2 == 0).then_some(loaded.candidate.entity)+ })+ .await+ .unwrap();+ assert_eq!(page.entries, vec![4, 2]);+}++#[tokio::test]+async fn a_full_page_stops_mid_candidate_page() {+ let reader = reader(documents((1..=6).rev()), Vec::new());+ let page = reader+ .page(request(CandidateKeying::FiledEntity, 4), |loaded| {+ (loaded.candidate.entity != 5).then_some(loaded.candidate.entity)+ })+ .await+ .unwrap();+ assert_eq!(page.entries, vec![6, 4, 3, 2]);+ assert_eq!(page.next.unwrap().entity_id, uuid(2).to_string());+}++#[tokio::test]+async fn refilling_is_bounded() {+ let candidates = documents((1..=20).rev());+ let reader = reader(candidates, Vec::new());+ let page = reader+ .page(request(CandidateKeying::FiledEntity, 2), |_| None::<u32>)+ .await+ .unwrap();+ assert!(page.entries.is_empty());+ assert_eq!(+ reader.source.requests.lock().unwrap().len(),+ MAX_FILL_ROUNDS+ );+ // The next page resumes after everything walked.+ assert_eq!(page.next.unwrap().entity_id, uuid(13).to_string());+}++#[tokio::test]+async fn an_exhausted_feed_has_no_cursor() {+ let reader = reader(documents([3, 2, 1]), Vec::new());+ let page = reader+ .page(request(CandidateKeying::FiledEntity, 5), |loaded| {+ Some(loaded.candidate.entity)+ })+ .await+ .unwrap();+ assert_eq!(page.entries, vec![3, 2, 1]);+ assert!(page.next.is_none());+}++fn thread_candidate() -> Candidate<u32> {+ let mut thread = candidate(1, entity(EntityType::ChannelMessage, THREAD), Some(6), None);+ thread.facts.thread_channel = Some(uuid(CHANNEL));+ thread+}++#[tokio::test]+async fn thread_scoped_threads_read_their_channel_once() {+ let reader = reader(+ vec![+ thread_candidate(),+ candidate(2, entity(EntityType::Channel, CHANNEL), Some(5), None),+ ],+ vec![+ channel_reply(1, CHANNEL, THREAD, 0x71, 6),+ channel_send(2, CHANNEL, 0x72, 5),+ ],+ );+ let page = reader+ .page(request(CandidateKeying::ThreadScoped, 10), |loaded| {+ Some(ids(&loaded.notifications))+ })+ .await+ .unwrap();+ // Both read the channel's notifications, newest first; each feed scopes+ // them itself.+ assert_eq!(+ page.entries,+ vec![vec![uuid(1), uuid(2)], vec![uuid(1), uuid(2)]]+ );+ let loads = reader.notifications.loads.lock().unwrap();+ assert_eq!(+ *loads,+ vec![vec![entity(EntityType::Channel, CHANNEL)]],+ "one load, one source"+ );+}++#[tokio::test]+async fn filed_entity_candidates_read_their_own_notifications() {+ let reader = reader(+ vec![thread_candidate()],+ vec![channel_reply(1, CHANNEL, THREAD, 0x71, 6)],+ );+ let page = reader+ .page(request(CandidateKeying::FiledEntity, 10), |loaded| {+ Some(ids(&loaded.notifications))+ })+ .await+ .unwrap();+ assert_eq!(page.entries, vec![Vec::<uuid::Uuid>::new()]);+ assert_eq!(+ *reader.notifications.loads.lock().unwrap(),+ vec![vec![entity(EntityType::ChannelMessage, THREAD)]]+ );+}++#[tokio::test]+async fn current_returns_only_admitted_keys() {+ let reader = reader(documents([3, 2]), vec![doc_comment(1, 3, 0xA0, 0xA0, 3)]);+ let keys = [+ FeedKey::new(entity(EntityType::Document, 3)),+ FeedKey::new(entity(EntityType::Document, 9)),+ ];+ let current = reader+ .current(request(CandidateKeying::FiledEntity, 50), &keys)+ .await+ .unwrap();+ assert_eq!(current.len(), 1);+ assert_eq!(ids(¤t[&keys[0]].notifications), vec![uuid(1)]);+ let requests = reader.source.requests.lock().unwrap();+ assert_eq!(+ requests[0].only.as_deref(),+ Some(&[keys[0].entity().clone(), keys[1].entity().clone()][..])+ );+ assert_eq!(requests[0].limit, 2);+ assert!(requests[0].after.is_none());+}++#[tokio::test]+async fn current_reads_large_key_sets_in_chunks() {+ let reader = reader(Vec::new(), Vec::new());+ let keys: Vec<_> = (0..450u128)+ .map(|n| FeedKey::new(entity(EntityType::Document, n)))+ .collect();+ reader+ .current(request(CandidateKeying::FiledEntity, 50), &keys)+ .await+ .unwrap();+ let sizes: Vec<_> = reader+ .source+ .requests+ .lock()+ .unwrap()+ .iter()+ .map(|request| request.only.as_ref().unwrap().len())+ .collect();+ assert_eq!(sizes, vec![200, 200, 50]);+}diff --git a/crates/attention_feed/src/inbound.rs b/crates/attention_feed/src/inbound.rsnew file mode 100644index 0000000000..92c9f333e8--- /dev/null+++ b/crates/attention_feed/src/inbound.rs@@ -0,0 +1,3 @@+//! Inbound helpers shared by feed GraphQL adapters.++pub mod viewers;diff --git a/crates/attention_feed/src/inbound/viewers.rs b/crates/attention_feed/src/inbound/viewers.rsnew file mode 100644index 0000000000..72a801d1a5--- /dev/null+++ b/crates/attention_feed/src/inbound/viewers.rs@@ -0,0 +1,54 @@+//! The viewer a feed request is evaluated as.++use std::sync::Arc;++use entity_access::{+ domain::{+ models::{EntityAccessReceipt, MemberTeamRole},+ ports::EntityAccessService,+ },+ inbound::axum_extractors::user_team_receipt,+};+use futures::future::BoxFuture;+use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::models::FeedViewer;++/// Resolves the team access a feed request is evaluated with. Requests and+/// subscriptions alike only carry the authenticated user, so the team+/// receipt is minted from it at the entity access boundary.+pub trait FeedViewerResolver: Send + Sync + 'static {+ /// The user's qualifying team receipt, if any.+ fn team(+ &self,+ user: MacroUserIdStr<'static>,+ ) -> BoxFuture<'_, Result<Option<EntityAccessReceipt<MemberTeamRole>>, rootcause::Report>>;+}++/// Mints viewer team receipts through the entity access service.+pub struct EntityAccessFeedViewers<S>(pub Arc<S>);++impl<S> FeedViewerResolver for EntityAccessFeedViewers<S>+where+ S: EntityAccessService,+{+ fn team(+ &self,+ user: MacroUserIdStr<'static>,+ ) -> BoxFuture<'_, Result<Option<EntityAccessReceipt<MemberTeamRole>>, rootcause::Report>> {+ Box::pin(async move {+ user_team_receipt::<MemberTeamRole, S>(self.0.as_ref(), user)+ .await+ .map_err(|error| rootcause::report!("failed to resolve team access: {error}"))+ })+ }+}++/// The viewer `user` is evaluated as, with their team receipt.+pub async fn resolve_viewer(+ viewers: &dyn FeedViewerResolver,+ user: MacroUserIdStr<'static>,+) -> Result<FeedViewer, rootcause::Report> {+ let team = viewers.team(user.clone()).await?;+ Ok(FeedViewer { user, team })+}diff --git a/crates/attention_feed/src/lib.rs b/crates/attention_feed/src/lib.rsnew file mode 100644index 0000000000..444042a211--- /dev/null+++ b/crates/attention_feed/src/lib.rs@@ -0,0 +1,28 @@+#![deny(missing_docs)]+//! The layer every attention feed builds on: Home's work feed and the+//! notifications inbox each keep their own model, and share how candidates+//! are paged and refilled, how their notifications are loaded, completed,+//! read and restored, how inbox email is archived, and how realtime changes+//! are batched into recomputes.+//!+//! # Architecture+//!+//! - **domain**: viewers, keys, tokens, candidate keying, the reader, the+//! acknowledger, live batching, and the ports feeds depend on.+//! - **inbound** (feature `inbound`): resolving the viewer a request is+//! evaluated as, at the entity access boundary.+//! - **outbound** (feature `outbound`): adapters over the Soup,+//! notification, email, activity and realtime services.+//! - **test_support** (feature `test-utils`): notification fixtures and port+//! fakes for the feeds' tests.++pub mod domain;++#[cfg(feature = "inbound")]+pub mod inbound;++#[cfg(feature = "outbound")]+pub mod outbound;++#[cfg(any(test, feature = "test-utils"))]+pub mod test_support;diff --git a/crates/work_feed/src/outbound.rs b/crates/attention_feed/src/outbound.rssimilarity index 52%rename from crates/work_feed/src/outbound.rsrename to crates/attention_feed/src/outbound.rsindex f4173e02f7..33aaede619 100644--- a/crates/work_feed/src/outbound.rs+++ b/crates/attention_feed/src/outbound.rs@@ -1,7 +1,7 @@-//! Adapters implementing the work feed's ports.+//! Adapters implementing the shared feed ports.pub mod mail;pub mod notifications;pub mod signals;-pub mod source;+pub mod soup;pub mod triggers;diff --git a/crates/work_feed/src/outbound/mail.rs b/crates/attention_feed/src/outbound/mail.rssimilarity index 83%rename from crates/work_feed/src/outbound/mail.rsrename to crates/attention_feed/src/outbound/mail.rsindex d1b32c430a..6ac992c531 100644--- a/crates/work_feed/src/outbound/mail.rs+++ b/crates/attention_feed/src/outbound/mail.rs@@ -7,21 +7,21 @@ use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;use uuid::Uuid;-use crate::domain::ports::WorkFeedMail;+use crate::domain::ports::FeedMail;/// Archives threads through [`EmailService`].-pub struct EmailWorkFeedMail<E> {+pub struct EmailFeedMail<E> {email: Arc<E>,}-impl<E> EmailWorkFeedMail<E> {+impl<E> EmailFeedMail<E> {/// Create the adapter over the email service.pub fn new(email: Arc<E>) -> Self {Self { email }}}-impl<E> WorkFeedMail for EmailWorkFeedMail<E>+impl<E> FeedMail for EmailFeedMail<E>whereE: EmailService,{diff --git a/crates/work_feed/src/outbound/notifications.rs b/crates/attention_feed/src/outbound/notifications.rssimilarity index 70%rename from crates/work_feed/src/outbound/notifications.rsrename to crates/attention_feed/src/outbound/notifications.rsindex 25b8c2b4b3..37886101b4 100644--- a/crates/work_feed/src/outbound/notifications.rs+++ b/crates/attention_feed/src/outbound/notifications.rs@@ -15,21 +15,32 @@ use notification::domain::{use rootcause::Report;use uuid::Uuid;-use crate::domain::{models::FeedNotification, ports::WorkFeedNotifications};+use crate::domain::{+ models::FeedNotification,+ ports::{FeedNotifications, NotificationTransition},+};/// Reads and acknowledges notifications through [`NotificationReader`].-pub struct ReaderWorkFeedNotifications<R> {+pub struct ReaderFeedNotifications<R> {reader: Arc<R>,}-impl<R> ReaderWorkFeedNotifications<R> {+impl<R> ReaderFeedNotifications<R> {/// Create the adapter over a notification reader.pub fn new(reader: Arc<R>) -> Self {Self { reader }}}-impl<R> WorkFeedNotifications for ReaderWorkFeedNotifications<R>+impl<R> Clone for ReaderFeedNotifications<R> {+ fn clone(&self) -> Self {+ Self {+ reader: Arc::clone(&self.reader),+ }+ }+}++impl<R> FeedNotifications for ReaderFeedNotifications<R>whereR: NotificationReader,{@@ -52,18 +63,22 @@ where.collect())}- async fn set_done(+ async fn transition(&self,user: MacroUserIdStr<'static>,notification_ids: Vec<Uuid>,- done: bool,+ transition: NotificationTransition,) -> Result<Vec<Uuid>, Report> {Ok(self.reader.update_notifications_and_return::<serde_json::Value>(UpdateNotificationsRequest {user_id: user,notification_ids: ¬ification_ids,- status: NotificationStatus::Done(done),+ status: match transition {+ NotificationTransition::Seen => NotificationStatus::Seen,+ NotificationTransition::Done => NotificationStatus::Done(true),+ NotificationTransition::Undone => NotificationStatus::Done(false),+ },}).await?.into_iter()diff --git a/crates/work_feed/src/outbound/signals.rs b/crates/attention_feed/src/outbound/signals.rssimilarity index 68%rename from crates/work_feed/src/outbound/signals.rsrename to crates/attention_feed/src/outbound/signals.rsindex e97c1c159a..e1cdd2b0cf 100644--- a/crates/work_feed/src/outbound/signals.rs+++ b/crates/attention_feed/src/outbound/signals.rs@@ -7,30 +7,30 @@ use soup_realtime::domain::{ports::SoupRealtimePublisher,};-use crate::domain::ports::WorkFeedSignals;+use crate::domain::ports::FeedSignals;/// Publishes an entity patch addressed to the viewer alone, which every-/// one of their sessions' work feed subscriptions recomputes from.-pub struct SoupRealtimeWorkFeedSignals<P> {+/// one of their sessions' feed subscriptions recomputes from.+pub struct SoupRealtimeFeedSignals<P> {publisher: P,}-impl<P> SoupRealtimeWorkFeedSignals<P> {+impl<P> SoupRealtimeFeedSignals<P> {/// Create the adapter over a Soup realtime publisher.pub fn new(publisher: P) -> Self {Self { publisher }}}-impl<P> WorkFeedSignals for SoupRealtimeWorkFeedSignals<P>+impl<P> FeedSignals for SoupRealtimeFeedSignals<P>whereP: SoupRealtimePublisher,{- async fn items_changed(&self, user: MacroUserIdStr<'static>, entities: Vec<Entity<'static>>) {+ async fn changed(&self, user: MacroUserIdStr<'static>, entities: Vec<Entity<'static>>) {for entity in entities {let message = SoupRealtimeMessage::new(user.clone(), Patch::Updated(entity));if let Err(error) = self.publisher.publish(message).await {- tracing::warn!(error = ?error, "failed to publish work feed change");+ tracing::warn!(error = ?error, "failed to publish feed change");}}}diff --git a/crates/work_feed/src/outbound/source.rs b/crates/attention_feed/src/outbound/soup.rssimilarity index 68%rename from crates/work_feed/src/outbound/source.rsrename to crates/attention_feed/src/outbound/soup.rsindex badc71b009..de718b2c6d 100644--- a/crates/work_feed/src/outbound/source.rs+++ b/crates/attention_feed/src/outbound/soup.rs@@ -1,4 +1,4 @@-//! Feed candidates from the Soup service.+//! Candidates from the Soup service's attention query.use std::sync::Arc;@@ -8,23 +8,26 @@ use models_soup::item::SoupItem;use rootcause::Report;use soup::domain::{models::{- SoupProjectionHydration, WorkFeedPagePosition, WorkFeedSoupMode, WorkFeedSoupRequest,+ AttentionKeying, AttentionPagePosition, AttentionSoupRequest, SoupProjectionHydration,},ports::SoupService,};use crate::domain::{- models::{WorkFeedMode, WorkFeedPosition},- ports::{EntityFacts, MailFacts, SourceItem, SourcePage, SourceRequest, WorkFeedSource},+ models::{+ Candidate, CandidateKeying, CandidatePage, CandidateRequest, EntityFacts, FeedPosition,+ MailFacts,+ },+ ports::CandidateSource,};-/// Candidates from Soup's work feed query, hydrated as Soup items.-pub struct SoupWorkFeedSource<S, E> {+/// Candidates from Soup's attention query, hydrated as Soup items.+pub struct SoupCandidateSource<S, E> {soup: S,email: Arc<E>,}-impl<S, E> SoupWorkFeedSource<S, E> {+impl<S, E> SoupCandidateSource<S, E> {/// Create a source over the Soup service; the email service resolves the/// viewer's readable inboxes.pub fn new(soup: S, email: Arc<E>) -> Self {@@ -50,14 +53,14 @@ fn facts(item: &SoupItem<()>) -> EntityFacts {}}-impl<S, E> WorkFeedSource for SoupWorkFeedSource<S, E>+impl<S, E> CandidateSource for SoupCandidateSource<S, E>whereS: SoupService,E: EmailService,{type Entity = SoupProjectionHydration;- async fn page(&self, request: SourceRequest) -> Result<SourcePage<Self::Entity>, Report> {+ async fn page(&self, request: CandidateRequest) -> Result<CandidatePage<Self::Entity>, Report> {let link_ids = self.get_inboxes_for_macro_id(request.viewer.user.copied())@@ -68,18 +71,19 @@ where.collect();let page = self.soup- .get_work_feed_page(- WorkFeedSoupRequest {+ .get_attention_page(+ AttentionSoupRequest {user: request.viewer.user.clone(),link_ids,limit: request.limit,- mode: match request.mode {- WorkFeedMode::Work => WorkFeedSoupMode::Work,- WorkFeedMode::Attention => WorkFeedSoupMode::Attention,+ own_work: request.own_work,+ keying: match request.keying {+ CandidateKeying::ThreadScoped => AttentionKeying::ThreadScoped,+ CandidateKeying::FiledEntity => AttentionKeying::FiledEntity,},types: request.types,filter: request.filter,- after: request.after.map(|after| WorkFeedPagePosition {+ after: request.after.map(|after| AttentionPagePosition {sort_at: after.sort_at,entity_id: after.entity_id,}),@@ -88,13 +92,13 @@ whererequest.viewer.team,).await- .map_err(|error| rootcause::report!("failed to load work feed candidates: {error}"))?;+ .map_err(|error| rootcause::report!("failed to load feed candidates: {error}"))?;- Ok(SourcePage {+ Ok(CandidatePage {items: page.items.into_iter()- .map(|item| SourceItem {+ .map(|item| Candidate {key: item.hydration.item.entity(),facts: facts(&item.hydration.item),attention_at: item.attention_at,@@ -103,7 +107,7 @@ whereentity: item.hydration,}).collect(),- next: page.next.map(|next| WorkFeedPosition {+ next: page.next.map(|next| FeedPosition {sort_at: next.sort_at,entity_id: next.entity_id,}),diff --git a/crates/work_feed/src/outbound/triggers.rs b/crates/attention_feed/src/outbound/triggers.rssimilarity index 67%rename from crates/work_feed/src/outbound/triggers.rsrename to crates/attention_feed/src/outbound/triggers.rsindex c0a1b305f2..1e63fcfecf 100644--- a/crates/work_feed/src/outbound/triggers.rs+++ b/crates/attention_feed/src/outbound/triggers.rs@@ -1,5 +1,5 @@-//! Work feed triggers from the notification, activity and Soup realtime-//! streams a viewer already receives.+//! Feed triggers from the notification, activity and Soup realtime streams a+//! viewer already receives.use std::sync::Arc;@@ -13,20 +13,22 @@ use soup_realtime::domain::{models::Patch, ports::SoupRealtimeSubscriptionServicuse tokio::sync::mpsc;use crate::domain::{- models::WorkFeedTrigger, ports::WorkFeedTriggers, realtime::notification_trigger_keys,+ keying::trigger_keys,+ models::{CandidateKeying, FeedTrigger},+ ports::FeedTriggers,};/// Triggers buffered per subscriber before upstream reads wait.const TRIGGER_BUFFER: usize = 64;-/// Merges a viewer's realtime streams into work feed triggers.-pub struct RealtimeWorkFeedTriggers<NS, AS, R> {+/// Merges a viewer's realtime streams into feed triggers.+pub struct RealtimeFeedTriggers<NS, AS, R> {notifications: Arc<NS>,activity: Arc<AS>,soup: Arc<R>,}-impl<NS, AS, R> RealtimeWorkFeedTriggers<NS, AS, R> {+impl<NS, AS, R> RealtimeFeedTriggers<NS, AS, R> {/// Create the adapter over the three realtime subscription services.pub fn new(notifications: Arc<NS>, activity: Arc<AS>, soup: Arc<R>) -> Self {Self {@@ -42,60 +44,73 @@ impl<NS, AS, R> RealtimeWorkFeedTriggers<NS, AS, R> {fn activity_trigger(user: &MacroUserIdStr<'static>,update: ActivitySubscriptionUpdate,-) -> Option<WorkFeedTrigger> {+) -> Option<FeedTrigger> {match update {ActivitySubscriptionUpdate::Updated(record) => {let own = record.subject_id == user.as_ref();let viewed = matches!(record.action, RecordedAction::Known(Action::Opened));(own && !viewed).then(|| {- WorkFeedTrigger::Changed(vec![+ FeedTrigger::Changed(vec![record.entity_type.with_entity_string(record.entity_id.clone()),])})}- ActivitySubscriptionUpdate::Invalidated => Some(WorkFeedTrigger::Invalidated),+ ActivitySubscriptionUpdate::Invalidated => Some(FeedTrigger::Invalidated),}}-fn notification_trigger(update: NotificationSubscriptionUpdate<NotifEvent>) -> WorkFeedTrigger {+fn notification_trigger(+ update: NotificationSubscriptionUpdate<NotifEvent>,+ keying: CandidateKeying,+) -> FeedTrigger {match update {NotificationSubscriptionUpdate::New(row) | NotificationSubscriptionUpdate::Updated(row) => {- WorkFeedTrigger::Changed(notification_trigger_keys(&row))+ FeedTrigger::Changed(trigger_keys(&row, keying))}// A deleted row no longer names its entity; refetching is the only- // way to learn which item lost a reason.- NotificationSubscriptionUpdate::Deleted(_) => WorkFeedTrigger::Invalidated,+ // way to learn which entry lost a reason.+ NotificationSubscriptionUpdate::Deleted(_) => FeedTrigger::Invalidated,}}-impl<NS, AS, R> WorkFeedTriggers for RealtimeWorkFeedTriggers<NS, AS, R>+impl<NS, AS, R> FeedTriggers for RealtimeFeedTriggers<NS, AS, R>whereNS: WebSocketNotificationSubscriptionService<NotificationSubscriptionUpdate<NotifEvent>>,AS: ActivitySubscriptionService,R: SoupRealtimeSubscriptionService,{- fn subscribe(&self, user: MacroUserIdStr<'static>) -> mpsc::Receiver<WorkFeedTrigger> {+ fn subscribe(+ &self,+ user: MacroUserIdStr<'static>,+ keying: CandidateKeying,+ own_work: bool,+ ) -> mpsc::Receiver<FeedTrigger> {let (sender, receiver) = mpsc::channel(TRIGGER_BUFFER);let mut notifications = self.notifications.subscribe(user.clone());- let mut activity = self.activity.subscribe(user.clone());+ let mut activity = own_work.then(|| self.activity.subscribe(user.clone()));let mut soup = self.soup.subscribe(user.clone());tokio::spawn(async move {loop {let trigger = tokio::select! {() = sender.closed() => return,update = notifications.recv() => match update {- Some(update) => Some(notification_trigger(update)),+ Some(update) => Some(notification_trigger(update, keying)),None => break,},- update = activity.recv() => match update {+ update = async {+ match activity.as_mut() {+ Some(activity) => activity.recv().await,+ None => std::future::pending().await,+ }+ } => match update {Some(update) => activity_trigger(&user, update),None => break,},patch = soup.recv() => match patch {Some(Patch::Updated(entity) | Patch::Deleted(entity)) => {- Some(WorkFeedTrigger::Changed(vec![entity]))+ Some(FeedTrigger::Changed(vec![entity]))}None => break,},@@ -108,7 +123,7 @@ where}// An upstream stream ended, normally or after falling behind:// changes may have been missed, so subscribers must refetch.- let _ = sender.send(WorkFeedTrigger::Invalidated).await;+ let _ = sender.send(FeedTrigger::Invalidated).await;});receiver}diff --git a/crates/attention_feed/src/test_support.rs b/crates/attention_feed/src/test_support.rsnew file mode 100644index 0000000000..eb7b9acbe1--- /dev/null+++ b/crates/attention_feed/src/test_support.rs@@ -0,0 +1,536 @@+//! Notification fixtures and port fakes for tests of feeds built on this+//! layer. Fakes share their state through `Arc`s, so a test keeps a clone to+//! inspect after handing one to a service.++use std::{+ collections::HashMap,+ sync::{Arc, Mutex},+};++use chrono::{DateTime, TimeZone, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};+use model_notifications::NotifEvent;+use notification::domain::models::{NotificationState, UserNotificationRow};+use rootcause::Report;+use serde_json::{Value, json};+use uuid::Uuid;++use crate::domain::{+ models::{+ Candidate, CandidatePage, CandidateRequest, EntityFacts, FeedNotification, FeedPosition,+ FeedViewer, MailFacts,+ },+ ports::{CandidateSource, FeedMail, FeedNotifications, FeedSignals, NotificationTransition},+};++/// The viewer every fixture belongs to.+pub const USER: &str = "macro|[email protected]";++/// A minute past 10:00 on 2024-06-01, UTC.+pub fn at(minute: u32) -> DateTime<Utc> {+ Utc.with_ymd_and_hms(2024, 6, 1, 10, minute, 0).unwrap()+}++/// [`USER`]'s id.+pub fn viewer_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(USER).unwrap()+}++/// [`USER`] without a team.+pub fn viewer() -> FeedViewer {+ FeedViewer {+ user: viewer_id(),+ team: None,+ }+}++/// A deterministic id.+pub fn uuid(n: u128) -> Uuid {+ Uuid::from_u128(n)+}++/// An entity with a deterministic id.+pub fn entity(entity_type: EntityType, id: u128) -> Entity<'static> {+ entity_type.with_entity_string(uuid(id).to_string())+}++/// A notification with typed metadata decoded from `tag`/`content`, the way+/// stored rows are.+pub fn notification(+ id: u128,+ entity: Entity<'static>,+ tag: &str,+ content: Value,+ minute: u32,+ state: NotificationState,+) -> FeedNotification {+ let metadata: NotifEvent = serde_json::from_value(json!({ "tag": tag, "content": content }))+ .unwrap_or_else(|error| panic!("invalid {tag} fixture: {error}"));+ Arc::new(UserNotificationRow {+ owner_id: viewer_id(),+ notification_id: uuid(id),+ notification_event_type: tag.to_string(),+ entity,+ sent: true,+ state,+ created_at: at(minute),+ viewed_at: None,+ updated_at: at(minute),+ deleted_at: None,+ notification_metadata: metadata,+ sender_id: None,+ })+}++/// A new root message in a channel.+pub fn channel_send(id: u128, channel: u128, message: u128, minute: u32) -> FeedNotification {+ notification(+ id,+ entity(EntityType::Channel, channel),+ "channel_message_send",+ json!({ "messageId": uuid(message), "messageContent": "hi", "channelType": "public" }),+ minute,+ NotificationState::Unseen,+ )+}++/// A reply in a channel thread.+pub fn channel_reply(+ id: u128,+ channel: u128,+ thread: u128,+ message: u128,+ minute: u32,+) -> FeedNotification {+ notification(+ id,+ entity(EntityType::Channel, channel),+ "channel_message_reply",+ json!({+ "threadId": uuid(thread),+ "messageId": uuid(message),+ "messageContent": "re",+ "channelType": "public",+ }),+ minute,+ NotificationState::Unseen,+ )+}++/// A channel mention, in a thread when `thread` is given.+pub fn channel_mention(+ id: u128,+ channel: u128,+ message: u128,+ thread: Option<u128>,+ minute: u32,+) -> FeedNotification {+ let mut content = json!({+ "messageId": uuid(message),+ "messageContent": "@you",+ "channelType": "public",+ });+ if let Some(thread) = thread {+ content["threadId"] = json!(uuid(thread));+ }+ notification(+ id,+ entity(EntityType::Channel, channel),+ "channel_mention",+ content,+ minute,+ NotificationState::Unseen,+ )+}++/// A reaction to the viewer's channel message, in a thread when `thread` is+/// given.+pub fn channel_reaction(+ id: u128,+ channel: u128,+ message: u128,+ thread: Option<u128>,+ minute: u32,+) -> FeedNotification {+ let mut content = json!({+ "messageId": uuid(message),+ "messageContent": "nice",+ "emoji": "+1",+ "channelType": "public",+ });+ if let Some(thread) = thread {+ content["threadId"] = json!(uuid(thread));+ }+ notification(+ id,+ entity(EntityType::Channel, channel),+ "channel_message_reaction",+ content,+ minute,+ NotificationState::Unseen,+ )+}++/// An invitation to a channel.+pub fn channel_invite(id: u128, channel: u128, minute: u32) -> FeedNotification {+ notification(+ id,+ entity(EntityType::Channel, channel),+ "channel_invite",+ json!({ "invitedBy": USER, "channelType": "public" }),+ minute,+ NotificationState::Unseen,+ )+}++fn comment_content(comment: u128, thread: u128) -> Value {+ json!({+ "documentName": "Doc",+ "owner": USER,+ "commentId": uuid(comment),+ "threadId": uuid(thread),+ "text": "comment",+ })+}++/// A comment on a document; a root comment when `comment == thread`.+pub fn doc_comment(+ id: u128,+ document: u128,+ comment: u128,+ thread: u128,+ minute: u32,+) -> FeedNotification {+ notification(+ id,+ entity(EntityType::Document, document),+ "commented_on_document",+ comment_content(comment, thread),+ minute,+ NotificationState::Unseen,+ )+}++/// A reply in a document comment thread.+pub fn doc_reply(+ id: u128,+ document: u128,+ comment: u128,+ thread: u128,+ minute: u32,+) -> FeedNotification {+ notification(+ id,+ entity(EntityType::Document, document),+ "replied_to_document_comment_thread",+ comment_content(comment, thread),+ minute,+ NotificationState::Unseen,+ )+}++/// A mention in a document comment.+pub fn doc_comment_mention(+ id: u128,+ document: u128,+ comment: u128,+ thread: u128,+ minute: u32,+) -> FeedNotification {+ let mut content = comment_content(comment, thread);+ content["mentionId"] = json!("mention");+ notification(+ id,+ entity(EntityType::Document, document),+ "mentioned_in_document_comment",+ content,+ minute,+ NotificationState::Unseen,+ )+}++/// A reminder about `entity`.+pub fn reminder(id: u128, entity: Entity<'static>, minute: u32) -> FeedNotification {+ notification(+ id,+ entity,+ "reminder",+ json!({ "reminderId": uuid(id), "description": "follow up" }),+ minute,+ NotificationState::Unseen,+ )+}++/// New mail on an email thread.+pub fn new_email(+ id: u128,+ thread: u128,+ minute: u32,+ state: NotificationState,+) -> FeedNotification {+ notification(+ id,+ entity(EntityType::EmailThread, thread),+ "new_email",+ json!({+ "toEmail": "[email protected]",+ "threadId": uuid(thread),+ "subject": "Hello",+ "snippet": "...",+ }),+ minute,+ state,+ )+}++/// The same notification in another state.+pub fn with_state(notification: &FeedNotification, state: NotificationState) -> FeedNotification {+ let mut row = (**notification).clone();+ row.state = state;+ Arc::new(row)+}++/// The notifications' ids, in order.+pub fn ids(notifications: &[FeedNotification]) -> Vec<Uuid> {+ notifications.iter().map(|n| n.notification_id).collect()+}++/// A candidate carrying `entity`, sorted at the later of its times.+pub fn candidate<E>(+ entity: E,+ key: Entity<'static>,+ attention: Option<u32>,+ touched: Option<u32>,+) -> Candidate<E> {+ let attention_at = attention.map(at);+ let touched_at = touched.map(at);+ Candidate {+ key,+ entity,+ facts: EntityFacts::default(),+ attention_at,+ touched_at,+ sort_at: attention_at+ .max(touched_at)+ .expect("a candidate has a reason"),+ }+}++/// An email thread candidate in the given mailbox state.+pub fn mail_candidate<E>(+ entity: E,+ thread: u128,+ attention: Option<u32>,+ touched: Option<u32>,+ mail: MailFacts,+) -> Candidate<E> {+ let mut candidate = candidate(+ entity,+ self::entity(EntityType::EmailThread, thread),+ attention,+ touched,+ );+ candidate.facts.mail = Some(mail);+ candidate+}++/// Serves a fixed list of candidates in feed order, narrowed by each+/// request's `only` keys, cursor and limit, and records every request.+pub struct FakeSource<E> {+ /// The candidates, newest first.+ pub items: Arc<Mutex<Vec<Candidate<E>>>>,+ /// Every request received, in order.+ pub requests: Arc<Mutex<Vec<CandidateRequest>>>,+}++impl<E> Clone for FakeSource<E> {+ fn clone(&self) -> Self {+ Self {+ items: Arc::clone(&self.items),+ requests: Arc::clone(&self.requests),+ }+ }+}++impl<E> FakeSource<E> {+ /// A source serving `items`, newest first.+ pub fn with(items: Vec<Candidate<E>>) -> Self {+ Self {+ items: Arc::new(Mutex::new(items)),+ requests: Arc::default(),+ }+ }+}++impl<E> CandidateSource for FakeSource<E>+where+ E: Clone + Send + Sync + 'static,+{+ type Entity = E;++ async fn page(&self, request: CandidateRequest) -> Result<CandidatePage<E>, Report> {+ self.requests.lock().unwrap().push(request.clone());+ let items = self.items.lock().unwrap().clone();+ let mut page: Vec<_> = items+ .into_iter()+ .filter(|item| {+ request+ .only+ .as_ref()+ .is_none_or(|only| only.contains(&item.key))+ })+ .filter(|item| {+ request.after.as_ref().is_none_or(|after| {+ (item.sort_at, item.key.entity_id.to_string())+ < (after.sort_at, after.entity_id.clone())+ })+ })+ .collect();+ let full = page.len() > usize::from(request.limit);+ page.truncate(usize::from(request.limit));+ let next = full.then(|| {+ let last = page.last().expect("a full page has a last item");+ FeedPosition {+ sort_at: last.sort_at,+ entity_id: last.key.entity_id.to_string(),+ }+ });+ Ok(CandidatePage { items: page, next })+ }+}++/// One requested transition: the ids and the state they move to.+pub type RecordedTransition = (Vec<Uuid>, NotificationTransition);++/// Holds the viewer's notifications in memory, applies transitions to them,+/// and records loads and transitions.+#[derive(Clone, Default)]+pub struct FakeNotifications {+ /// Every notification, by the entity it is filed under.+ pub by_entity: Arc<Mutex<HashMap<Entity<'static>, Vec<FeedNotification>>>>,+ /// The entities each `active` call asked for.+ pub loads: Arc<Mutex<Vec<Vec<Entity<'static>>>>>,+ /// Every transition requested.+ pub transitions: Arc<Mutex<Vec<RecordedTransition>>>,+}++impl FakeNotifications {+ /// A store holding `notifications`.+ pub fn with(notifications: Vec<FeedNotification>) -> Self {+ let mut by_entity: HashMap<Entity<'static>, Vec<FeedNotification>> = HashMap::new();+ for notification in notifications {+ by_entity+ .entry(notification.entity.clone())+ .or_default()+ .push(notification);+ }+ Self {+ by_entity: Arc::new(Mutex::new(by_entity)),+ ..Default::default()+ }+ }++ /// The current state of notification `id`.+ pub fn state_of(&self, id: Uuid) -> NotificationState {+ self.by_entity+ .lock()+ .unwrap()+ .values()+ .flatten()+ .find(|n| n.notification_id == id)+ .map(|n| n.state)+ .expect("the notification exists")+ }+}++impl FeedNotifications for FakeNotifications {+ async fn active(+ &self,+ _user: MacroUserIdStr<'static>,+ entities: Vec<Entity<'static>>,+ ) -> Result<HashMap<Entity<'static>, Vec<FeedNotification>>, Report> {+ self.loads.lock().unwrap().push(entities.clone());+ let by_entity = self.by_entity.lock().unwrap();+ Ok(entities+ .into_iter()+ .map(|entity| {+ let active = by_entity+ .get(&entity)+ .into_iter()+ .flatten()+ .filter(|n| n.state != NotificationState::Done)+ .cloned()+ .collect();+ (entity, active)+ })+ .collect())+ }++ async fn transition(+ &self,+ _user: MacroUserIdStr<'static>,+ notification_ids: Vec<Uuid>,+ transition: NotificationTransition,+ ) -> Result<Vec<Uuid>, Report> {+ self.transitions+ .lock()+ .unwrap()+ .push((notification_ids.clone(), transition));+ let mut by_entity = self.by_entity.lock().unwrap();+ let mut changed = Vec::new();+ for id in notification_ids {+ let Some(notification) = by_entity+ .values_mut()+ .flatten()+ .find(|notification| notification.notification_id == id)+ else {+ continue;+ };+ let state = match (transition, notification.state) {+ // Seen never reopens a done notification.+ (NotificationTransition::Seen, NotificationState::Unseen) => {+ NotificationState::Seen+ }+ (NotificationTransition::Seen, _) => continue,+ (NotificationTransition::Done, _) => NotificationState::Done,+ (NotificationTransition::Undone, _) => NotificationState::Seen,+ };+ *notification = with_state(notification, state);+ changed.push(id);+ }+ Ok(changed)+ }+}++/// Records archive and unarchive calls.+#[derive(Clone, Default)]+pub struct FakeMail {+ /// Every `(thread, archived)` call, in order.+ pub calls: Arc<Mutex<Vec<(Uuid, bool)>>>,+}++impl FeedMail for FakeMail {+ async fn set_archived(+ &self,+ _user: MacroUserIdStr<'static>,+ thread_id: Uuid,+ archived: bool,+ ) -> Result<(), Report> {+ self.calls.lock().unwrap().push((thread_id, archived));+ Ok(())+ }+}++/// Records change signals.+#[derive(Clone, Default)]+pub struct FakeSignals {+ /// The entities of every signal, in order.+ pub calls: Arc<Mutex<Vec<Vec<Entity<'static>>>>>,+}++impl FeedSignals for FakeSignals {+ async fn changed(&self, _user: MacroUserIdStr<'static>, entities: Vec<Entity<'static>>) {+ self.calls.lock().unwrap().push(entities);+ }+}diff --git a/crates/channels/src/domain/side_effects/test.rs b/crates/channels/src/domain/side_effects/test.rsindex 370c9b3839..b57672353b 100644--- a/crates/channels/src/domain/side_effects/test.rs+++ b/crates/channels/src/domain/side_effects/test.rs@@ -962,6 +962,7 @@ async fn document_mentions_in_a_reply_notify_only_thread_participants() {thread_id: Some(thread_id),sender_id: Sender::new_from_user(sender.clone()),triggered_by: None,+ triggered_via: None,content: "see this".to_string(),created_at: now,updated_at: now,diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.tomlindex d28c8d5cf9..6d6e4b237c 100644--- a/crates/complete_graph/Cargo.toml+++ b/crates/complete_graph/Cargo.toml@@ -68,6 +68,7 @@ databases = { path = "../databases", default-features = false, features = ["portdatabases_sql = { path = "../databases_sql" }models_databases = { path = "../models_databases" }activity = { path = "../activity", default-features = false, features = ["realtime"] }+attention_feed = { path = "../attention_feed", features = ["inbound"] }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 90c523d3de..2ecba462cb 100644--- a/crates/complete_graph/src/lib.rs+++ b/crates/complete_graph/src/lib.rs@@ -74,10 +74,7 @@ pub use graphql_properties::{PropertiesEntityPropertyReader, PropertiesEntityPropertyWriter, PropertiesMutationRoot,entity_properties_loader,};-pub use graphql_work_feed::{- EntityAccessWorkFeedViewers, WorkFeedGraphqlContext, WorkFeedGraphqlService,- WorkFeedViewerResolver,-};+pub use graphql_work_feed::{WorkFeedGraphqlContext, WorkFeedGraphqlService};pub use mail_cache_profile::{MAIL_CACHE_PROFILE_HEADER, MailCacheProfile};pub use realtime::{AgentSessionLogSubscriptions, agent_session_log_subscriptions};pub use schema::{diff --git a/crates/complete_graph/src/schema/test/work_feed.rs b/crates/complete_graph/src/schema/test/work_feed.rsindex b1452649a1..cd927ed874 100644--- a/crates/complete_graph/src/schema/test/work_feed.rs+++ b/crates/complete_graph/src/schema/test/work_feed.rs@@ -1,14 +1,19 @@use std::sync::{Arc, Mutex};-use ::work_feed::domain::{- models::{- WorkFeedChange, WorkFeedDoneOutcome, WorkFeedDoneReceipt, WorkFeedDoneTarget,- WorkFeedEntry, WorkFeedError, WorkFeedItem, WorkFeedItemKey, WorkFeedItemState,- WorkFeedItemType, WorkFeedMode, WorkFeedPage, WorkFeedPosition, WorkFeedPrimaryReason,- WorkFeedQuery, WorkFeedRevision, WorkFeedScope, WorkFeedStack, WorkFeedStackKind,- WorkFeedTrigger, WorkFeedViewer,+use ::attention_feed::{+ domain::{+ models::{+ CandidateKeying, DoneReceipt, FeedError, FeedKey, FeedPosition, FeedRevision,+ FeedTrigger, FeedViewer,+ },+ ports::FeedTriggers,},- ports::WorkFeedTriggers,+ inbound::viewers::FeedViewerResolver,+};+use ::work_feed::domain::models::{+ WorkFeedChange, WorkFeedDoneOutcome, WorkFeedDoneTarget, WorkFeedEntry, WorkFeedItem,+ WorkFeedItemState, WorkFeedItemType, WorkFeedMode, WorkFeedPage, WorkFeedPrimaryReason,+ WorkFeedQuery, WorkFeedScope, WorkFeedStack, WorkFeedStackKind,};use async_graphql::futures_util::{StreamExt as _, future::BoxFuture, pin_mut};use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};@@ -17,7 +22,7 @@ use notification::domain::models::{NotificationState, UserNotificationRow};use soup::domain::models::SoupProjectionHydration;use super::*;-use crate::{WorkFeedGraphqlContext, WorkFeedGraphqlService, WorkFeedViewerResolver};+use crate::{WorkFeedGraphqlContext, WorkFeedGraphqlService};const DOC_ID: Uuid = Uuid::from_u128(0xD0C);@@ -28,8 +33,8 @@ fn at(minute: u32) -> chrono::DateTime<chrono::Utc> {.unwrap()}-fn doc_key() -> WorkFeedItemKey {- WorkFeedItemKey::new(ModelEntityType::Document.with_entity_string(DOC_ID.to_string()))+fn doc_key() -> FeedKey {+ FeedKey::new(ModelEntityType::Document.with_entity_string(DOC_ID.to_string()))}fn comment(id: u128, minute: u32) -> Arc<UserNotificationRow<NotifEvent>> {@@ -87,10 +92,10 @@ fn doc_entry() -> WorkFeedEntry<SoupProjectionHydration> {#[derive(Default)]struct RecordingWorkFeedService {- pages: Mutex<Vec<(WorkFeedViewer, WorkFeedQuery)>>,- recomputes: Mutex<Vec<(WorkFeedScope, Vec<WorkFeedItemKey>)>>,+ pages: Mutex<Vec<(FeedViewer, WorkFeedQuery)>>,+ recomputes: Mutex<Vec<(WorkFeedScope, Vec<FeedKey>)>>,dones: Mutex<Vec<Vec<WorkFeedDoneTarget>>>,- undos: Mutex<Vec<(WorkFeedScope, WorkFeedDoneReceipt)>>,+ undos: Mutex<Vec<(WorkFeedScope, DoneReceipt)>>,}/// Shares the recording service between the schema and the assertions.@@ -99,14 +104,14 @@ struct Recording(Arc<RecordingWorkFeedService>);impl WorkFeedGraphqlService for Recording {fn page(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,query: WorkFeedQuery,- ) -> BoxFuture<'_, Result<WorkFeedPage<SoupProjectionHydration>, WorkFeedError>> {+ ) -> BoxFuture<'_, Result<WorkFeedPage<SoupProjectionHydration>, FeedError>> {self.0.pages.lock().unwrap().push((viewer, query));Box::pin(async {Ok(WorkFeedPage {entries: vec![doc_entry()],- next: Some(WorkFeedPosition {+ next: Some(FeedPosition {sort_at: at(9),entity_id: DOC_ID.to_string(),}),@@ -116,10 +121,10 @@ impl WorkFeedGraphqlService for Recording {fn recompute(&self,- _viewer: WorkFeedViewer,+ _viewer: FeedViewer,scope: WorkFeedScope,- keys: Vec<WorkFeedItemKey>,- ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, WorkFeedError>> {+ keys: Vec<FeedKey>,+ ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, FeedError>> {self.0.recomputes.lock()@@ -141,9 +146,9 @@ impl WorkFeedGraphqlService for Recording {fn mark_done(&self,- _viewer: WorkFeedViewer,+ _viewer: FeedViewer,targets: Vec<WorkFeedDoneTarget>,- ) -> BoxFuture<'_, Result<WorkFeedDoneOutcome, WorkFeedError>> {+ ) -> BoxFuture<'_, Result<WorkFeedDoneOutcome, FeedError>> {let items = targets.iter().map(|target| target.key.clone())@@ -151,8 +156,8 @@ impl WorkFeedGraphqlService for Recording {self.0.dones.lock().unwrap().push(targets);Box::pin(async move {Ok(WorkFeedDoneOutcome {- receipt: WorkFeedDoneReceipt {- items: items.iter().map(WorkFeedItemKey::id).collect(),+ receipt: DoneReceipt {+ keys: items.iter().map(FeedKey::id).collect(),notification_ids: vec![Uuid::from_u128(1)],..Default::default()},@@ -163,10 +168,10 @@ impl WorkFeedGraphqlService for Recording {fn undo_done(&self,- _viewer: WorkFeedViewer,+ _viewer: FeedViewer,scope: WorkFeedScope,- receipt: WorkFeedDoneReceipt,- ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, WorkFeedError>> {+ receipt: DoneReceipt,+ ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, FeedError>> {self.0.undos.lock().unwrap().push((scope, receipt));Box::pin(async { Ok(vec![WorkFeedChange::Upserted(doc_entry())]) })}@@ -175,25 +180,30 @@ impl WorkFeedGraphqlService for Recording {/// Triggers a test drives by hand.#[derive(Default, Clone)]struct ManualTriggers {- sender: Arc<Mutex<Option<tokio::sync::mpsc::Sender<WorkFeedTrigger>>>>,- subscribed: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,+ sender: Arc<Mutex<Option<tokio::sync::mpsc::Sender<FeedTrigger>>>>,+ subscribed: Arc<Mutex<Vec<(MacroUserIdStr<'static>, CandidateKeying, bool)>>>,}-impl WorkFeedTriggers for ManualTriggers {+impl FeedTriggers for ManualTriggers {fn subscribe(&self,user: MacroUserIdStr<'static>,- ) -> tokio::sync::mpsc::Receiver<WorkFeedTrigger> {+ 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(user);+ self.subscribed+ .lock()+ .unwrap()+ .push((user, keying, own_work));receiver}}struct NoTeam;-impl WorkFeedViewerResolver for NoTeam {+impl FeedViewerResolver for NoTeam {fn team(&self,_user: MacroUserIdStr<'static>,@@ -206,7 +216,11 @@ fn context(service: &Arc<RecordingWorkFeedService>,triggers: &ManualTriggers,) -> WorkFeedGraphqlContext {- WorkFeedGraphqlContext::new(Recording(Arc::clone(service)), triggers.clone(), NoTeam)+ WorkFeedGraphqlContext::new(+ Recording(Arc::clone(service)),+ Arc::new(triggers.clone()),+ Arc::new(NoTeam),+ )}fn viewer_id() -> MacroUserIdStr<'static> {@@ -257,7 +271,7 @@ async fn work_feed_pages_hydrated_stacked_entries_for_the_viewer() {assert_eq!(entry["touchedAt"], at(9).to_rfc3339());assert_eq!(entry["primaryReason"], "OWN_WORK");assert!(entry["primaryStackIndex"].is_null());- let revision = WorkFeedRevision::decode(entry["revision"].as_str().unwrap()).unwrap();+ let revision = FeedRevision::decode(entry["revision"].as_str().unwrap()).unwrap();assert_eq!(revision.attention_through, Some(at(7)));let item = &entry["item"];@@ -277,7 +291,7 @@ async fn work_feed_pages_hydrated_stacked_entries_for_the_viewer() {Uuid::from_u128(2).to_string());- let position = WorkFeedPosition::decode(page["nextCursor"].as_str().unwrap()).unwrap();+ let position = FeedPosition::decode(page["nextCursor"].as_str().unwrap()).unwrap();assert_eq!(position.entity_id, DOC_ID.to_string());assert_eq!(page["nextPosition"]["entityId"], DOC_ID.to_string());assert_eq!(@@ -325,7 +339,7 @@ async fn mark_done_completes_the_observed_revision_and_undo_restores_it() {let harness = harness();let service = Arc::new(RecordingWorkFeedService::default());let triggers = ManualTriggers::default();- let revision = WorkFeedRevision {+ let revision = FeedRevision {attention_through: Some(at(7)),}.encode();@@ -409,9 +423,8 @@ async fn work_feed_updates_batch_recomputed_patches() {let harness = harness();let service = Arc::new(RecordingWorkFeedService::default());let triggers = ManualTriggers::default();- let other = WorkFeedItemKey::new(- ModelEntityType::Chat.with_entity_string(Uuid::from_u128(0xC4A7).to_string()),- );+ let other =+ FeedKey::new(ModelEntityType::Chat.with_entity_string(Uuid::from_u128(0xC4A7).to_string()));let request = async_graphql::Request::new(r#"subscription { workFeedUpdates(scope: { mode: WORK }) {@@ -439,11 +452,11 @@ async fn work_feed_updates_batch_recomputed_patches() {};// A burst inside one window becomes one recompute.sender- .send(WorkFeedTrigger::Changed(vec![doc_key().into_entity()]))+ .send(FeedTrigger::Changed(vec![doc_key().into_entity()])).await.unwrap();sender- .send(WorkFeedTrigger::Changed(vec![+ .send(FeedTrigger::Changed(vec![other.into_entity(),doc_key().into_entity(),]))@@ -472,7 +485,7 @@ async fn work_feed_updates_batch_recomputed_patches() {}let sender = first.await.unwrap();- sender.send(WorkFeedTrigger::Invalidated).await.unwrap();+ sender.send(FeedTrigger::Invalidated).await.unwrap();let response = responses.next().await.expect("invalidation");let data = response.data.into_json().unwrap();assert_eq!(@@ -487,6 +500,6 @@ async fn work_feed_updates_batch_recomputed_patches() {assert!(!response.errors.is_empty());assert_eq!(triggers.subscribed.lock().unwrap().as_slice(),- &[viewer_id()]+ &[(viewer_id(), CandidateKeying::ThreadScoped, true)]);}diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.mdindex 93dc8e9141..4c246870ce 100644--- a/crates/email/AGENTS.md+++ b/crates/email/AGENTS.md@@ -36,7 +36,7 @@ tools — hexagonal, heavily feature-gated.`crm`, `frecency`, `item_filters`, `lexical_client`, `macro_event_broker`,`calendar_events` (optional, feature `calendar_invitations`).- Used by: many crates and services, including `ai_tools`, `graphql_email`,- `teams`, `databases_sql`, `work_feed`, `calendar_service`, `email_service`,+ `teams`, `databases_sql`, `attention_feed`, `calendar_service`, `email_service`,`email_scheduled_handler`, `search_processing_service`.## Recipesdiff --git a/crates/graphql_work_feed/AGENTS.md b/crates/graphql_work_feed/AGENTS.mdindex 95c4672807..9694fcb205 100644--- a/crates/graphql_work_feed/AGENTS.md+++ b/crates/graphql_work_feed/AGENTS.md@@ -13,19 +13,22 @@ subscription.- `src/objects.rs`: `GraphqlWorkFeedPage`, `GraphqlWorkFeedEntry`,`GraphqlWorkFeedItem`, `GraphqlWorkFeedStack`, `GraphqlWorkFeedPatch`.- `src/mutations.rs`: mark-done / undo-done mutations.-- `src/subscriptions.rs`: `WorkFeedSubscriptionRoot` — realtime patches.-- `src/context.rs`: `WorkFeedGraphqlContext`, `WorkFeedViewerResolver`.+- `src/subscriptions.rs`: `WorkFeedSubscriptionRoot` — realtime patches,+ batched by `attention_feed`'s `live::coalesce`.+- `src/context.rs`: `WorkFeedGraphqlContext`, built with the shared+ `FeedTriggers` and `FeedViewerResolver`.## Scope- Owns: GraphQL types/resolvers/subscription for the work feed page.-- Not here: feed composition and item ranking → `crates/work_feed`;+- Not here: feed composition and item ranking → `crates/work_feed`; shared+ keys, tokens, triggers and viewer lookup → `crates/attention_feed`;notification content → `crates/graphql_notification`.## Boundaries-- Depends on: `work_feed`, `graphql_notification`, `graphql_soup`,- `entity_access` (inbound feature), `graphql_common`.+- Depends on: `work_feed`, `attention_feed` (inbound feature),+ `graphql_notification`, `graphql_soup`, `graphql_common`.- Used by: `complete_graph` (schema composition).## Recipesdiff --git a/crates/graphql_work_feed/Cargo.toml b/crates/graphql_work_feed/Cargo.tomlindex bee9cb2c99..abedce5af3 100644--- a/crates/graphql_work_feed/Cargo.toml+++ b/crates/graphql_work_feed/Cargo.toml@@ -7,24 +7,13 @@ version = "0.1.0"[dependencies]async-graphql = { workspace = true }async-stream = { workspace = true }-entity_access = { path = "../entity_access", default-features = false, features = ["inbound"] }+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" }-model_notifications = { path = "../model_notifications" }-rootcause = { workspace = true }soup = { path = "../soup", default-features = false, features = ["ports"] }-tokio = { workspace = true, features = ["sync", "time", "macros"] }tracing = { workspace = true }work_feed = { path = "../work_feed" }workspace-hack = { version = "0.1", path = "../workspace-hack" }--[dev-dependencies]-chrono = { workspace = true }-model-entity = { path = "../model-entity" }-notification = { path = "../notification" }-serde_json = { workspace = true }-tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }-uuid = { workspace = true }diff --git a/crates/graphql_work_feed/src/context.rs b/crates/graphql_work_feed/src/context.rsindex a73d960dff..3d95f9484a 100644--- a/crates/graphql_work_feed/src/context.rs+++ b/crates/graphql_work_feed/src/context.rs@@ -1,21 +1,20 @@use std::sync::Arc;-use entity_access::{+use attention_feed::{domain::{- models::{EntityAccessReceipt, MemberTeamRole},- ports::EntityAccessService,+ models::{DoneReceipt, FeedError, FeedKey, FeedViewer},+ ports::FeedTriggers,},- inbound::axum_extractors::user_team_receipt,+ inbound::viewers::{FeedViewerResolver, resolve_viewer},};use futures::future::BoxFuture;use macro_user_id::user_id::MacroUserIdStr;use soup::domain::models::SoupProjectionHydration;use work_feed::domain::{models::{- WorkFeedChange, WorkFeedDoneOutcome, WorkFeedDoneReceipt, WorkFeedDoneTarget,- WorkFeedError, WorkFeedItemKey, WorkFeedPage, WorkFeedQuery, WorkFeedScope, WorkFeedViewer,+ WorkFeedChange, WorkFeedDoneOutcome, WorkFeedDoneTarget, WorkFeedPage, WorkFeedQuery,+ WorkFeedScope,},- ports::WorkFeedTriggers,service::WorkFeedService,};@@ -25,32 +24,32 @@ pub trait WorkFeedGraphqlService: Send + Sync + 'static {/// See [`WorkFeedService::page`].fn page(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,query: WorkFeedQuery,- ) -> BoxFuture<'_, Result<WorkFeedPage<SoupProjectionHydration>, WorkFeedError>>;+ ) -> BoxFuture<'_, Result<WorkFeedPage<SoupProjectionHydration>, FeedError>>;/// See [`WorkFeedService::recompute`].fn recompute(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,scope: WorkFeedScope,- keys: Vec<WorkFeedItemKey>,- ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, WorkFeedError>>;+ keys: Vec<FeedKey>,+ ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, FeedError>>;/// See [`WorkFeedService::mark_done`].fn mark_done(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,targets: Vec<WorkFeedDoneTarget>,- ) -> BoxFuture<'_, Result<WorkFeedDoneOutcome, WorkFeedError>>;+ ) -> BoxFuture<'_, Result<WorkFeedDoneOutcome, FeedError>>;/// See [`WorkFeedService::undo_done`].fn undo_done(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,scope: WorkFeedScope,- receipt: WorkFeedDoneReceipt,- ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, WorkFeedError>>;+ receipt: DoneReceipt,+ ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, FeedError>>;}impl<T> WorkFeedGraphqlService for T@@ -59,69 +58,39 @@ where{fn page(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,query: WorkFeedQuery,- ) -> BoxFuture<'_, Result<WorkFeedPage<SoupProjectionHydration>, WorkFeedError>> {+ ) -> BoxFuture<'_, Result<WorkFeedPage<SoupProjectionHydration>, FeedError>> {Box::pin(WorkFeedService::page(self, viewer, query))}fn recompute(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,scope: WorkFeedScope,- keys: Vec<WorkFeedItemKey>,- ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, WorkFeedError>> {+ keys: Vec<FeedKey>,+ ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, FeedError>> {Box::pin(WorkFeedService::recompute(self, viewer, scope, keys))}fn mark_done(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,targets: Vec<WorkFeedDoneTarget>,- ) -> BoxFuture<'_, Result<WorkFeedDoneOutcome, WorkFeedError>> {+ ) -> BoxFuture<'_, Result<WorkFeedDoneOutcome, FeedError>> {Box::pin(WorkFeedService::mark_done(self, viewer, targets))}fn undo_done(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,scope: WorkFeedScope,- receipt: WorkFeedDoneReceipt,- ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, WorkFeedError>> {+ receipt: DoneReceipt,+ ) -> BoxFuture<'_, Result<Vec<WorkFeedChange<SoupProjectionHydration>>, FeedError>> {Box::pin(WorkFeedService::undo_done(self, viewer, scope, receipt))}}-/// Resolves the team access a work feed request is evaluated with. Requests-/// and subscriptions alike only carry the authenticated user, so the team-/// receipt is minted from it at the entity access boundary.-pub trait WorkFeedViewerResolver: Send + Sync + 'static {- /// The user's qualifying team receipt, if any.- fn team(- &self,- user: MacroUserIdStr<'static>,- ) -> BoxFuture<'_, Result<Option<EntityAccessReceipt<MemberTeamRole>>, rootcause::Report>>;-}--/// Mints viewer team receipts through the entity access service.-pub struct EntityAccessWorkFeedViewers<S>(pub Arc<S>);--impl<S> WorkFeedViewerResolver for EntityAccessWorkFeedViewers<S>-where- S: EntityAccessService,-{- fn team(- &self,- user: MacroUserIdStr<'static>,- ) -> BoxFuture<'_, Result<Option<EntityAccessReceipt<MemberTeamRole>>, rootcause::Report>> {- Box::pin(async move {- user_team_receipt::<MemberTeamRole, S>(self.0.as_ref(), user)- .await- .map_err(|error| rootcause::report!("failed to resolve team access: {error}"))- })- }-}-/// Request data for the work feed fields, inserted by the composition root/// for HTTP requests and subscription connections alike.#[derive(Clone)]@@ -129,22 +98,23 @@ pub struct WorkFeedGraphqlContext {/// The feed's use cases.pub(crate) service: Arc<dyn WorkFeedGraphqlService>,/// Realtime changes that may affect a viewer's items.- pub(crate) triggers: Arc<dyn WorkFeedTriggers>,+ pub(crate) triggers: Arc<dyn FeedTriggers>,/// Team access lookup for viewers.- pub(crate) viewers: Arc<dyn WorkFeedViewerResolver>,+ pub(crate) viewers: Arc<dyn FeedViewerResolver>,}impl WorkFeedGraphqlContext {- /// Bundle the work feed's capabilities for request data.+ /// Bundle the work feed's capabilities for request data. The triggers+ /// and viewer lookup are shared with the other attention feeds.pub fn new(service: impl WorkFeedGraphqlService,- triggers: impl WorkFeedTriggers,- viewers: impl WorkFeedViewerResolver,+ triggers: Arc<dyn FeedTriggers>,+ viewers: Arc<dyn FeedViewerResolver>,) -> Self {Self {service: Arc::new(service),- triggers: Arc::new(triggers),- viewers: Arc::new(viewers),+ triggers,+ viewers,}}@@ -152,21 +122,22 @@ impl WorkFeedGraphqlContext {pub(crate) async fn viewer(&self,user: MacroUserIdStr<'static>,- ) -> async_graphql::Result<WorkFeedViewer> {- let team = self.viewers.team(user.clone()).await.map_err(|error| {- tracing::error!(error = ?error, "work feed viewer lookup failed");- async_graphql::Error::new("the work feed is unavailable")- })?;- Ok(WorkFeedViewer { user, team })+ ) -> async_graphql::Result<FeedViewer> {+ resolve_viewer(self.viewers.as_ref(), user)+ .await+ .map_err(|error| {+ tracing::error!(error = ?error, "work feed viewer lookup failed");+ async_graphql::Error::new("the work feed 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: WorkFeedError) -> async_graphql::Error {+pub(crate) fn to_graphql_error(error: FeedError) -> async_graphql::Error {match error {- WorkFeedError::InvalidInput(message) => async_graphql::Error::new(message),- WorkFeedError::Unavailable(report) => {+ FeedError::InvalidInput(message) => async_graphql::Error::new(message),+ FeedError::Unavailable(report) => {tracing::error!(error = ?report, "work feed request failed");async_graphql::Error::new("the work feed is unavailable")}diff --git a/crates/graphql_work_feed/src/inputs.rs b/crates/graphql_work_feed/src/inputs.rsindex 349c311483..35b257b60f 100644--- a/crates/graphql_work_feed/src/inputs.rs+++ b/crates/graphql_work_feed/src/inputs.rs@@ -1,7 +1,8 @@use async_graphql::{Enum, ID, InputObject};+use attention_feed::domain::models::{FeedKey, FeedPosition, FeedRevision};use work_feed::domain::models::{- WorkFeedDoneTarget, WorkFeedItemKey, WorkFeedItemState, WorkFeedItemType, WorkFeedMode,- WorkFeedPosition, WorkFeedQuery, WorkFeedRevision, WorkFeedScope,+ WorkFeedDoneTarget, WorkFeedItemState, WorkFeedItemType, WorkFeedMode, WorkFeedQuery,+ WorkFeedScope,};use crate::objects::GraphqlWorkFeedItemState;@@ -133,7 +134,7 @@ impl WorkFeedInput {graphql_common::parse_limit(self.limit, DEFAULT_WORK_FEED_LIMIT, MAX_WORK_FEED_LIMIT)?;let after = self.cursor- .map(|cursor| WorkFeedPosition::decode(&cursor))+ .map(|cursor| FeedPosition::decode(&cursor)).transpose().map_err(|_| async_graphql::Error::new("invalid work feed cursor"))?;let state = match self.state {@@ -183,11 +184,11 @@ impl MarkWorkFeedItemsDoneInput {self.items.into_iter().map(|item| {- let key = WorkFeedItemKey::parse(&item.id)+ let key = FeedKey::parse(&item.id).map_err(|_| async_graphql::Error::new("invalid work feed item id"))?;let revision = item.revision- .map(|revision| WorkFeedRevision::decode(&revision))+ .map(|revision| FeedRevision::decode(&revision)).transpose().map_err(|_| async_graphql::Error::new("invalid work feed revision"))?;Ok(WorkFeedDoneTarget { key, revision })diff --git a/crates/graphql_work_feed/src/inputs/test.rs b/crates/graphql_work_feed/src/inputs/test.rsindex d6594d2b43..a3b195c338 100644--- a/crates/graphql_work_feed/src/inputs/test.rs+++ b/crates/graphql_work_feed/src/inputs/test.rs@@ -70,7 +70,7 @@ fn scope_input_maps_types_and_mode() {#[test]fn done_input_parses_ids_and_revisions() {- let revision = WorkFeedRevision::default().encode();+ let revision = FeedRevision::default().encode();let targets = MarkWorkFeedItemsDoneInput {items: vec![WorkFeedDoneItemInput {id: ID("document:11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa".to_string()),@@ -80,7 +80,7 @@ fn done_input_parses_ids_and_revisions() {.into_targets().unwrap();assert_eq!(targets.len(), 1);- assert_eq!(targets[0].revision, Some(WorkFeedRevision::default()));+ assert_eq!(targets[0].revision, Some(FeedRevision::default()));let bad_id = MarkWorkFeedItemsDoneInput {items: vec![WorkFeedDoneItemInput {diff --git a/crates/graphql_work_feed/src/lib.rs b/crates/graphql_work_feed/src/lib.rsindex d4b96282a4..fc789580b1 100644--- a/crates/graphql_work_feed/src/lib.rs+++ b/crates/graphql_work_feed/src/lib.rs@@ -4,7 +4,8 @@#![deny(missing_docs)]#![deny(clippy::missing_docs_in_private_items)]-/// Request data carrying the work feed service, triggers and viewer lookup.+/// Request data carrying the work feed service and the shared triggers and+/// viewer lookup.mod context;/// Feed, scope and mutation inputs.mod inputs;@@ -17,10 +18,7 @@ mod query;/// The `workFeedUpdates` subscription.mod subscriptions;-pub use context::{- EntityAccessWorkFeedViewers, WorkFeedGraphqlContext, WorkFeedGraphqlService,- WorkFeedViewerResolver,-};+pub use context::{WorkFeedGraphqlContext, WorkFeedGraphqlService};pub use inputs::{GraphqlWorkFeedItemType, GraphqlWorkFeedMode, MarkWorkFeedItemsDoneInput,UndoWorkFeedItemsDoneInput, WorkFeedDoneItemInput, WorkFeedInput, WorkFeedScopeInput,diff --git a/crates/graphql_work_feed/src/mutations.rs b/crates/graphql_work_feed/src/mutations.rsindex dbf2d4b72c..b259e92d5c 100644--- a/crates/graphql_work_feed/src/mutations.rs+++ b/crates/graphql_work_feed/src/mutations.rs@@ -1,9 +1,9 @@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 work_feed::domain::models::WorkFeedDoneReceipt;use crate::{context::{WorkFeedGraphqlContext, to_graphql_error},@@ -75,7 +75,7 @@ impl<E: SoupEntityEdges> WorkFeedMutationRoot<E> {) -> async_graphql::Result<UndoWorkFeedItemsDonePayload<E>> {let user = require_authenticated_user(ctx)?;let context = ctx.data::<WorkFeedGraphqlContext>()?;- let receipt = WorkFeedDoneReceipt::decode(&input.undo_token)+ let receipt = DoneReceipt::decode(&input.undo_token).map_err(|_| async_graphql::Error::new("invalid work feed undo token"))?;let scope = input.scope.unwrap_or_default().into_scope();let viewer = context.viewer(user).await?;diff --git a/crates/graphql_work_feed/src/objects.rs b/crates/graphql_work_feed/src/objects.rsindex d968cde6be..9e53a58ab8 100644--- a/crates/graphql_work_feed/src/objects.rs+++ b/crates/graphql_work_feed/src/objects.rs@@ -1,10 +1,11 @@use async_graphql::{Enum, ID, Object, SimpleObject, Union};+use attention_feed::domain::models::counts_as_unseen;use graphql_notification::GraphqlNotification;use graphql_soup::{GraphqlSoupEntity, SoupEntityEdges};use soup::domain::models::SoupProjectionHydration;use work_feed::domain::models::{WorkFeedChange, WorkFeedEntry, WorkFeedItemState, WorkFeedPage, WorkFeedPrimaryReason,- WorkFeedStack, WorkFeedStackKind, counts_as_unseen,+ WorkFeedStack, WorkFeedStackKind,};/// Most notifications one stack returns when no limit is given.diff --git a/crates/graphql_work_feed/src/subscriptions.rs b/crates/graphql_work_feed/src/subscriptions.rsindex 7bd197e3dc..d357abe5d6 100644--- a/crates/graphql_work_feed/src/subscriptions.rs+++ b/crates/graphql_work_feed/src/subscriptions.rs@@ -1,50 +1,18 @@-use std::{collections::HashSet, marker::PhantomData, time::Duration};+use std::marker::PhantomData;use async_graphql::{Context, Subscription};-use futures::Stream;+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 work_feed::domain::models::{WorkFeedItemKey, WorkFeedTrigger};use crate::{context::WorkFeedGraphqlContext, inputs::WorkFeedScopeInput, objects::GraphqlWorkFeedPatch,};-#[cfg(test)]-mod test;--/// How long triggers are collected before one recompute, so a burst of-/// realtime events (a busy thread, a bulk done) costs one feed lookup.-const COALESCE_WINDOW: Duration = Duration::from_millis(300);--/// The triggers collected for one recompute.-#[derive(Default)]-struct TriggerBatch {- /// Keys to recompute, in arrival order.- keys: Vec<WorkFeedItemKey>,- /// Keys already in `keys`.- seen: HashSet<WorkFeedItemKey>,- /// Whether any trigger said changes may have been missed.- invalidated: bool,-}--impl TriggerBatch {- /// Add one trigger to the batch.- fn absorb(&mut self, trigger: WorkFeedTrigger) {- match trigger {- WorkFeedTrigger::Changed(entities) => {- for entity in entities {- let key = WorkFeedItemKey::new(entity);- if self.seen.insert(key.clone()) {- self.keys.push(key);- }- }- }- WorkFeedTrigger::Invalidated => self.invalidated = true,- }- }-}-/// Root GraphQL adapter for the work feed subscription.pub struct WorkFeedSubscriptionRoot<E>(PhantomData<fn() -> E>);@@ -73,25 +41,15 @@ impl<E: SoupEntityEdges> WorkFeedSubscriptionRoot<E> {let context = ctx.data::<WorkFeedGraphqlContext>()?.clone();let scope = scope.unwrap_or_default().into_scope();let viewer = context.viewer(user.clone()).await?;- let mut triggers = context.triggers.subscribe(user);+ let triggers =+ context+ .triggers+ .subscribe(user, CandidateKeying::ThreadScoped, scope.mode.own_work());Ok(async_stream::stream! {- while let Some(first) = triggers.recv().await {- let mut batch = TriggerBatch::default();- batch.absorb(first);- let window = tokio::time::sleep(COALESCE_WINDOW);- tokio::pin!(window);- let mut open = true;- while open {- tokio::select! {- () = &mut window => break,- next = triggers.recv() => match next {- Some(trigger) => batch.absorb(trigger),- None => open = false,- },- }- }-+ let batches = coalesce(triggers, COALESCE_WINDOW);+ futures::pin_mut!(batches);+ while let Some(batch) = batches.next().await {if batch.invalidated {yield Ok(vec![GraphqlWorkFeedPatch::invalidated()]);continue;diff --git a/crates/graphql_work_feed/src/subscriptions/test.rs b/crates/graphql_work_feed/src/subscriptions/test.rsdeleted file mode 100644index 0086b93a2f..0000000000--- a/crates/graphql_work_feed/src/subscriptions/test.rs+++ /dev/null@@ -1,19 +0,0 @@-use super::*;-use model_entity::EntityType;--#[test]-fn batches_deduplicate_keys_in_arrival_order() {- let doc = EntityType::Document.with_entity_string("d".to_string());- let chat = EntityType::Chat.with_entity_string("c".to_string());- let mut batch = TriggerBatch::default();- batch.absorb(WorkFeedTrigger::Changed(vec![doc.clone(), chat.clone()]));- batch.absorb(WorkFeedTrigger::Changed(vec![doc.clone()]));- assert_eq!(- batch.keys,- vec![WorkFeedItemKey::new(doc), WorkFeedItemKey::new(chat)]- );- assert!(!batch.invalidated);-- batch.absorb(WorkFeedTrigger::Invalidated);- assert!(batch.invalidated);-}diff --git a/crates/model_notifications/AGENTS.md b/crates/model_notifications/AGENTS.mdindex bb8d8b2fd3..a06e9eaa40 100644--- a/crates/model_notifications/AGENTS.md+++ b/crates/model_notifications/AGENTS.md@@ -27,7 +27,7 @@ types.- Depends on: `macro_user_id`, `mention_utils`, `model-entity`, `model_owner`,`models_pagination`, `notification`, `invite_email`.-- Used by: `agent_harness`, `ai_tools`, `authentication_service`,+- Used by: `agent_harness`, `ai_tools`, `attention_feed`, `authentication_service`,`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`,diff --git a/crates/models_soup/AGENTS.md b/crates/models_soup/AGENTS.mdindex ba9d92266e..f55136a6f6 100644--- a/crates/models_soup/AGENTS.md+++ b/crates/models_soup/AGENTS.md@@ -30,7 +30,7 @@ model.`models_pagination`, `models_properties`.- Used by: `ai_tools`, `complete_graph`, `databases_sql`, `graphql_initiative`,`graphql_soup`, `models_search`, `search_service`, `skills`, `soup`,- `soup_filter_projection`, `work_feed`.+ `soup_filter_projection`, `attention_feed`.## Recipesdiff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.mdindex 42822ffad9..9c2498ca2c 100644--- a/crates/soup/AGENTS.md+++ b/crates/soup/AGENTS.md@@ -19,7 +19,7 @@ rows, initiatives, ...) and get back a single unified, paginated result.query logic layered onto the core service.- `src/outbound/pg_soup_repo.rs`: the Postgres repo, split by entity kind(`database_row.rs`, `calendar_event.rs`, `agent_session.rs`, `initiative.rs`,- `work_feed.rs`, `notified.rs`, `touched.rs`) and by shape+ `attention.rs`, `notified.rs`, `touched.rs`) and by shape(`expanded/` hydrated, `unexpanded/` id-only).- `src/inbound/axum_router.rs` + `src/inbound/toolset/list_entities.rs`: theHTTP route and the AI-tool surface over the same service.@@ -37,8 +37,8 @@ rows, initiatives, ...) and get back a single unified, paginated result.- Depends on: `entity_access`, `properties`, `crm`, `item_filters`,`filter_ast`, `favorites`, `frecency`, `channels`, `email`, `call`,`github_pull_requests`, `foreign_entity`, `activity`, `agent_changes`.-- Used by: `ai_tools`, `complete_graph`, `databases_sql`, `graphql_initiative`,- `graphql_soup`, `graphql_work_feed`, `memory`, `skills`, `work_feed`,+- Used by: `ai_tools`, `attention_feed`, `complete_graph`, `databases_sql`,+ `graphql_initiative`, `graphql_soup`, `graphql_work_feed`, `memory`, `skills`,`soup_filter_projection`.## Recipes@@ -49,8 +49,11 @@ 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 what the work feed/Signal surfaces: `src/domain/service/tests/work_feed.rs`- → `src/outbound/pg_soup_repo/work_feed.rs`.+- Change which candidates attention feeds (Home's work feed) 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`'s+ `keying.rs`.## Tool contractsdiff --git a/crates/soup/fixtures/attention_channel_keying.sql b/crates/soup/fixtures/attention_channel_keying.sqlnew file mode 100644index 0000000000..7cdf5934aa--- /dev/null+++ b/crates/soup/fixtures/attention_channel_keying.sql@@ -0,0 +1,38 @@+-- Channel-Y activity for the attention candidate query's keying.+-- Loads after `work_feed`, which creates user-1.+-- (T = minute past 10:00 on 2024-06-01, UTC)+--+-- T30 reaction to user-1's top-level message R1+-- T31 reaction to user-1's reply in thread R2+-- T32 document mention in top-level message R3+--+-- Thread-scoped keying places each at its message's thread, as Home shows+-- them; filed-entity keying places all three at channel-Y.++SET session_replication_role = 'replica';++INSERT INTO public.comms_channels ("id", "channel_type", "owner_id", "created_at", "updated_at")+VALUES ('33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'private', 'macro|[email protected]', '2023-01-07 10:00:00', '2023-01-07 10:00:00');++INSERT INTO public.comms_channel_participants ("channel_id", "role", "user_id", "joined_at", "left_at")+VALUES ('33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'member', 'macro|[email protected]', '2023-01-07 10:00:00', NULL);++INSERT INTO public.comms_messages ("id", "parent_entity_type", "parent_entity_id", "thread_id", "sender_id", "content", "created_at", "updated_at")+VALUES ('99999999-1111-1111-1111-111111111111', 'channel', '33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NULL, 'macro|[email protected]', 'r1', '2024-06-01 10:20:00+00', '2024-06-01 10:20:00+00'),+ ('99999999-2222-2222-2222-222222222222', 'channel', '33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NULL, 'macro|[email protected]', 'r2', '2024-06-01 10:21:00+00', '2024-06-01 10:21:00+00'),+ ('99999999-2222-2222-2222-aaaaaaaaaaaa', 'channel', '33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '99999999-2222-2222-2222-222222222222', 'macro|[email protected]', 'r2 reply', '2024-06-01 10:22:00+00', '2024-06-01 10:22:00+00'),+ ('99999999-3333-3333-3333-333333333333', 'channel', '33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NULL, 'macro|[email protected]', 'see doc', '2024-06-01 10:23:00+00', '2024-06-01 10:23:00+00');++INSERT INTO public.notification ("id", "notification_event_type", "event_item_id", "event_item_type", "service_sender", "created_at", "metadata", "sender_id", "secondary_event_item_id", "secondary_event_item_type")+VALUES+('0190b000-0000-7000-8000-000000000030', 'channel_message_reaction', '33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'channel', 'test', '2024-06-01 10:30:00', '{"messageId": "99999999-1111-1111-1111-111111111111", "emoji": "+1"}', 'macro|[email protected]', '99999999-1111-1111-1111-111111111111', 'channel_message'),+('0190b000-0000-7000-8000-000000000031', 'channel_message_reaction', '33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'channel', 'test', '2024-06-01 10:31:00', '{"messageId": "99999999-2222-2222-2222-aaaaaaaaaaaa", "threadId": "99999999-2222-2222-2222-222222222222", "emoji": "+1"}', 'macro|[email protected]', '99999999-2222-2222-2222-222222222222', 'channel_message'),+('0190b000-0000-7000-8000-000000000032', 'document_mention', '33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'channel', 'test', '2024-06-01 10:32:00', '{"messageId": "99999999-3333-3333-3333-333333333333", "documentName": "Doc A"}', 'macro|[email protected]', '99999999-3333-3333-3333-333333333333', 'channel_message');++INSERT INTO public.user_notification ("user_id", "notification_id", "created_at", "sent", "seen_at", "deleted_at", "state", "is_important_v0")+VALUES+('macro|[email protected]', '0190b000-0000-7000-8000-000000000030', '2024-06-01 10:30:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000031', '2024-06-01 10:31:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000032', '2024-06-01 10:32:00', TRUE, NULL, NULL, 'unseen', FALSE);++SET session_replication_role = 'origin';diff --git a/crates/soup/fixtures/attention_discussions.sql b/crates/soup/fixtures/attention_discussions.sqlnew file mode 100644index 0000000000..590449458f--- /dev/null+++ b/crates/soup/fixtures/attention_discussions.sql@@ -0,0 +1,67 @@+-- Project and CRM discussions for the attention candidate query.+-- Loads after `work_feed`, which creates user-1 and user-2.+-- (T = minute past 10:00 on 2024-06-01, UTC)+--+-- T40 discussion on company-1 (user-1's CRM team) -> listed+-- T41 discussion on company-2 (same team, hidden) -> not listed+-- T42 discussion on company-3 (another team) -> not listed+-- T43 discussion on contact-1 (company-1) -> listed+-- T44 discussion on contact-2 (company-1, hidden contact) -> not listed+-- T45 discussion on project-1 (shared with user-1) -> listed+-- T46 discussion on contact-3 (no company, same team) -> listed+-- T47 discussion on contact-4 (company-2, hidden company) -> not listed++SET session_replication_role = 'replica';++INSERT INTO public.team ("id", "name", "owner_id")+VALUES ('77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Team 1', 'macro|[email protected]'),+ ('77777777-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Team 2', 'macro|[email protected]');++INSERT INTO public.team_user ("user_id", "team_id", "team_role")+VALUES ('macro|[email protected]', '77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'member'),+ ('macro|[email protected]', '77777777-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'owner');++INSERT INTO public.team_crm_settings ("team_id", "crm_enabled")+VALUES ('77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', TRUE),+ ('77777777-bbbb-bbbb-bbbb-bbbbbbbbbbbb', TRUE);++INSERT INTO public.crm_companies ("id", "team_id", "hidden", "first_interaction", "last_interaction", "custom_name")+VALUES ('88888888-0000-0000-0000-000000000001', '77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', FALSE, '2024-06-01 09:00:00+00', '2024-06-01 09:00:00+00', 'Company 1'),+ ('88888888-0000-0000-0000-000000000002', '77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', TRUE, '2024-06-01 09:00:00+00', '2024-06-01 09:00:00+00', 'Company 2'),+ ('88888888-0000-0000-0000-000000000003', '77777777-bbbb-bbbb-bbbb-bbbbbbbbbbbb', FALSE, '2024-06-01 09:00:00+00', '2024-06-01 09:00:00+00', 'Company 3');++INSERT INTO public.crm_contacts ("id", "team_id", "company_id", "email", "hidden", "first_interaction", "last_interaction")+VALUES ('88888888-1111-0000-0000-000000000001', '77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '88888888-0000-0000-0000-000000000001', '[email protected]', FALSE, '2024-06-01 09:00:00+00', '2024-06-01 09:00:00+00'),+ ('88888888-1111-0000-0000-000000000002', '77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '88888888-0000-0000-0000-000000000001', '[email protected]', TRUE, '2024-06-01 09:00:00+00', '2024-06-01 09:00:00+00'),+ ('88888888-1111-0000-0000-000000000003', '77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, '[email protected]', FALSE, '2024-06-01 09:00:00+00', '2024-06-01 09:00:00+00'),+ ('88888888-1111-0000-0000-000000000004', '77777777-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '88888888-0000-0000-0000-000000000002', '[email protected]', FALSE, '2024-06-01 09:00:00+00', '2024-06-01 09:00:00+00');++INSERT INTO public.initiative ("id", "name", "owner_user_id", "share_permission_id")+VALUES ('66666666-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Project 1', 'macro|[email protected]', 'sp-project-1');++INSERT INTO public.entity_access ("entity_id", "entity_type", "source_id", "source_type", "access_level", "granted_from_project_id")+VALUES ('66666666-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'initiative', 'macro|[email protected]', 'user', 'edit', NULL);++INSERT INTO public.notification ("id", "notification_event_type", "event_item_id", "event_item_type", "service_sender", "created_at", "metadata", "sender_id", "secondary_event_item_id", "secondary_event_item_type")+VALUES+('0190b000-0000-7000-8000-000000000040', 'crm_discussion', '88888888-0000-0000-0000-000000000001', 'crm_company', 'test', '2024-06-01 10:40:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000041', 'crm_discussion', '88888888-0000-0000-0000-000000000002', 'crm_company', 'test', '2024-06-01 10:41:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000042', 'crm_discussion', '88888888-0000-0000-0000-000000000003', 'crm_company', 'test', '2024-06-01 10:42:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000043', 'crm_discussion', '88888888-1111-0000-0000-000000000001', 'crm_contact', 'test', '2024-06-01 10:43:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000044', 'crm_discussion', '88888888-1111-0000-0000-000000000002', 'crm_contact', 'test', '2024-06-01 10:44:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000045', 'initiative_discussion', '66666666-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'initiative', 'test', '2024-06-01 10:45:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000046', 'crm_discussion', '88888888-1111-0000-0000-000000000003', 'crm_contact', 'test', '2024-06-01 10:46:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000047', 'crm_discussion', '88888888-1111-0000-0000-000000000004', 'crm_contact', 'test', '2024-06-01 10:47:00', '{}', 'macro|[email protected]', NULL, NULL);++INSERT INTO public.user_notification ("user_id", "notification_id", "created_at", "sent", "seen_at", "deleted_at", "state", "is_important_v0")+VALUES+('macro|[email protected]', '0190b000-0000-7000-8000-000000000040', '2024-06-01 10:40:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000041', '2024-06-01 10:41:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000042', '2024-06-01 10:42:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000043', '2024-06-01 10:43:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000044', '2024-06-01 10:44:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000045', '2024-06-01 10:45:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000046', '2024-06-01 10:46:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000047', '2024-06-01 10:47:00', TRUE, NULL, NULL, 'unseen', FALSE);++SET session_replication_role = 'origin';diff --git a/crates/soup/fixtures/work_feed.sql b/crates/soup/fixtures/work_feed.sqlindex 4345bbcb63..0229b683c0 100644--- a/crates/soup/fixtures/work_feed.sql+++ b/crates/soup/fixtures/work_feed.sql@@ -29,12 +29,12 @@ VALUES (1, 'Test Organization', 'PILOT')ON CONFLICT DO NOTHING;INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id")-VALUES ('a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_id_1'),- ('a2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'stripe_id_2');+VALUES ('a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_id_1'),+ ('a2222222-2222-2222-2222-222222222222', '[email protected]', '[email protected]', 'stripe_id_2');INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")-VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_1', 1, 'a1111111-1111-1111-1111-111111111111'),- ('macro|[email protected]', '[email protected]', 'stripe_id_2', 1, 'a2222222-2222-2222-2222-222222222222')+VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_1', 1, 'a1111111-1111-1111-1111-111111111111'),+ ('macro|[email protected]', '[email protected]', 'stripe_id_2', 1, 'a2222222-2222-2222-2222-222222222222')ON CONFLICT DO NOTHING;---------------------------------------------------@@ -51,28 +51,28 @@ VALUES (1, '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa'),(8, '11111111-9999-9999-9999-999999999999');INSERT INTO public."Document" ("id", "name", "owner", "documentFamilyId", "fileType", "createdAt", "updatedAt", "deletedAt")-VALUES ('11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc A', 'macro|[email protected]', 1, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),- ('11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Doc B', 'macro|[email protected]', 2, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),- ('11111111-cccc-cccc-cccc-cccccccccccc', 'Doc C', 'macro|[email protected]', 3, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),- ('11111111-eeee-eeee-eeee-eeeeeeeeeeee', 'Doc E', 'macro|[email protected]', 5, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),- ('11111111-ffff-ffff-ffff-ffffffffffff', 'Doc F', 'macro|[email protected]', 6, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),- ('11111111-0000-0000-0000-000000000000', 'Doc G', 'macro|[email protected]', 7, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),- ('11111111-9999-9999-9999-999999999999', 'Doc H', 'macro|[email protected]', 8, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL);+VALUES ('11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Doc A', 'macro|[email protected]', 1, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),+ ('11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Doc B', 'macro|[email protected]', 2, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),+ ('11111111-cccc-cccc-cccc-cccccccccccc', 'Doc C', 'macro|[email protected]', 3, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),+ ('11111111-eeee-eeee-eeee-eeeeeeeeeeee', 'Doc E', 'macro|[email protected]', 5, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),+ ('11111111-ffff-ffff-ffff-ffffffffffff', 'Doc F', 'macro|[email protected]', 6, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),+ ('11111111-0000-0000-0000-000000000000', 'Doc G', 'macro|[email protected]', 7, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL),+ ('11111111-9999-9999-9999-999999999999', 'Doc H', 'macro|[email protected]', 8, 'md', '2023-01-05 10:00:00', '2023-01-05 10:00:00', NULL);INSERT INTO public."Chat" ("id", "name", "userId", "projectId", "createdAt", "updatedAt")-VALUES ('22222222-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Chat A', 'macro|[email protected]', NULL, '2023-01-06 10:00:00', '2023-01-06 10:00:00');+VALUES ('22222222-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Chat A', 'macro|[email protected]', NULL, '2023-01-06 10:00:00', '2023-01-06 10:00:00');INSERT INTO public.comms_channels ("id", "channel_type", "owner_id", "created_at", "updated_at")-VALUES ('33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'private', 'macro|[email protected]', '2023-01-07 10:00:00', '2023-01-07 10:00:00');+VALUES ('33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'private', 'macro|[email protected]', '2023-01-07 10:00:00', '2023-01-07 10:00:00');INSERT INTO public.comms_messages ("id", "parent_entity_type", "parent_entity_id", "thread_id", "sender_id", "content", "created_at", "updated_at")-VALUES ('99999999-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'channel', '33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'macro|[email protected]', 'hey @user-1', '2024-06-01 10:01:00+00', '2024-06-01 10:01:00+00');+VALUES ('99999999-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'channel', '33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'macro|[email protected]', 'hey @user-1', '2024-06-01 10:01:00+00', '2024-06-01 10:01:00+00');INSERT INTO public.comms_channel_participants ("channel_id", "role", "user_id", "joined_at", "left_at")-VALUES ('33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'member', 'macro|[email protected]', '2023-01-07 10:00:00', NULL);+VALUES ('33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'member', 'macro|[email protected]', '2023-01-07 10:00:00', NULL);INSERT INTO public.email_links ("id", "macro_id", "fusionauth_user_id", "email_address", "provider")-VALUES ('55555555-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'fa-user-1', '[email protected]', 'GMAIL');+VALUES ('55555555-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro|[email protected]', 'fa-user-1', '[email protected]', 'GMAIL');INSERT INTO public.email_threads ("id", "link_id", "inbox_visible", "is_signal", "latest_inbound_message_ts", "created_at", "updated_at")VALUES ('44444444-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '55555555-aaaa-aaaa-aaaa-aaaaaaaaaaaa', TRUE, TRUE, '2024-06-01 10:12:00+00', '2024-06-01 10:12:00+00', '2024-06-01 10:12:00+00'),@@ -82,14 +82,14 @@ VALUES ('44444444-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '55555555-aaaa-aaaa-aaaa-aaaaaaa('44444444-0000-0000-0000-000000000000', '55555555-aaaa-aaaa-aaaa-aaaaaaaaaaaa', FALSE, TRUE, '2024-06-01 10:14:00+00', '2024-06-01 10:14:00+00', '2024-06-01 10:14:00+00');INSERT INTO public.entity_access ("entity_id", "entity_type", "source_id", "source_type", "access_level", "granted_from_project_id")-VALUES ('11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document', 'macro|[email protected]', 'user', 'owner', NULL),- ('11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'document', 'macro|[email protected]', 'user', 'owner', NULL),- ('11111111-cccc-cccc-cccc-cccccccccccc', 'document', 'macro|[email protected]', 'user', 'owner', NULL),- ('11111111-eeee-eeee-eeee-eeeeeeeeeeee', 'document', 'macro|[email protected]', 'user', 'owner', NULL),- ('11111111-ffff-ffff-ffff-ffffffffffff', 'document', 'macro|[email protected]', 'user', 'owner', NULL),- ('11111111-0000-0000-0000-000000000000', 'document', 'macro|[email protected]', 'user', 'view', NULL),- ('11111111-9999-9999-9999-999999999999', 'document', 'macro|[email protected]', 'user', 'owner', NULL),- ('22222222-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'chat', 'macro|[email protected]', 'user', 'owner', NULL);+VALUES ('11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document', 'macro|[email protected]', 'user', 'owner', NULL),+ ('11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'document', 'macro|[email protected]', 'user', 'owner', NULL),+ ('11111111-cccc-cccc-cccc-cccccccccccc', 'document', 'macro|[email protected]', 'user', 'owner', NULL),+ ('11111111-eeee-eeee-eeee-eeeeeeeeeeee', 'document', 'macro|[email protected]', 'user', 'owner', NULL),+ ('11111111-ffff-ffff-ffff-ffffffffffff', 'document', 'macro|[email protected]', 'user', 'owner', NULL),+ ('11111111-0000-0000-0000-000000000000', 'document', 'macro|[email protected]', 'user', 'view', NULL),+ ('11111111-9999-9999-9999-999999999999', 'document', 'macro|[email protected]', 'user', 'owner', NULL),+ ('22222222-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'chat', 'macro|[email protected]', 'user', 'owner', NULL);----------------------------------------------------- NOTIFICATIONS@@ -97,31 +97,31 @@ VALUES ('11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document', 'macro|[email protected]INSERT INTO public.notification ("id", "notification_event_type", "event_item_id", "event_item_type", "service_sender", "created_at", "metadata", "sender_id", "secondary_event_item_id", "secondary_event_item_type")VALUES-('0190b000-0000-7000-8000-000000000005', 'document_mention', '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document', 'test', '2024-06-01 10:05:00', '{}', 'macro|[email protected]', NULL, NULL),-('0190b000-0000-7000-8000-000000000008', 'document_mention', '11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'document', 'test', '2024-06-01 10:08:00', '{}', 'macro|[email protected]', NULL, NULL),-('0190b000-0000-7000-8000-000000000108', 'document_mention', '11111111-0000-0000-0000-000000000000', 'document', 'test', '2024-06-01 10:08:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000005', 'document_mention', '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'document', 'test', '2024-06-01 10:05:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000008', 'document_mention', '11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'document', 'test', '2024-06-01 10:08:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000108', 'document_mention', '11111111-0000-0000-0000-000000000000', 'document', 'test', '2024-06-01 10:08:00', '{}', 'macro|[email protected]', NULL, NULL),('0190b000-0000-7000-8000-000000000004', 'ai_response', '22222222-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'chat', 'test', '2024-06-01 10:04:00', '{}', NULL, NULL, NULL),-('0190b000-0000-7000-8000-000000000010', 'document_mention', '11111111-eeee-eeee-eeee-eeeeeeeeeeee', 'document', 'test', '2024-06-01 10:10:00', '{}', 'macro|[email protected]', NULL, NULL),-('0190b000-0000-7000-8000-000000000006', 'document_mention', '11111111-9999-9999-9999-999999999999', 'document', 'test', '2024-06-01 10:06:00', '{}', 'macro|[email protected]', NULL, NULL),-('0190b000-0000-7000-8000-000000000015', 'document_mention', '11111111-9999-9999-9999-999999999999', 'document', 'test', '2024-06-01 10:15:00', '{}', 'macro|[email protected]', NULL, NULL),-('0190b000-0000-7000-8000-000000000001', 'channel_mention', '33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'channel', 'test', '2024-06-01 10:01:00', '{"messageId": "99999999-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}', 'macro|[email protected]', '99999999-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'channel_message'),+('0190b000-0000-7000-8000-000000000010', 'document_mention', '11111111-eeee-eeee-eeee-eeeeeeeeeeee', 'document', 'test', '2024-06-01 10:10:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000006', 'document_mention', '11111111-9999-9999-9999-999999999999', 'document', 'test', '2024-06-01 10:06:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000015', 'document_mention', '11111111-9999-9999-9999-999999999999', 'document', 'test', '2024-06-01 10:15:00', '{}', 'macro|[email protected]', NULL, NULL),+('0190b000-0000-7000-8000-000000000001', 'channel_mention', '33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'channel', 'test', '2024-06-01 10:01:00', '{"messageId": "99999999-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}', 'macro|[email protected]', '99999999-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'channel_message'),('0190b000-0000-7000-8000-000000000012', 'new_email', '44444444-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'email_thread', 'test', '2024-06-01 10:12:00', '{}', NULL, NULL, NULL),('0190b000-0000-7000-8000-000000000000', 'new_email', '44444444-5555-5555-5555-555555555555', 'email_thread', 'test', '2024-06-01 10:00:00', '{}', NULL, NULL, NULL),('0190b000-0000-7000-8000-000000000014', 'new_email', '44444444-0000-0000-0000-000000000000', 'email_thread', 'test', '2024-06-01 10:14:00', '{}', NULL, NULL, NULL);INSERT INTO public.user_notification ("user_id", "notification_id", "created_at", "sent", "seen_at", "deleted_at", "state", "is_important_v0")VALUES-('macro|[email protected]', '0190b000-0000-7000-8000-000000000005', '2024-06-01 10:05:00', TRUE, NULL, NULL, 'unseen', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000008', '2024-06-01 10:08:00', TRUE, NULL, NULL, 'seen', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000108', '2024-06-01 10:08:00', TRUE, NULL, NULL, 'unseen', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000004', '2024-06-01 10:04:00', TRUE, NULL, NULL, 'unseen', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000010', '2024-06-01 10:10:00', TRUE, NULL, NULL, 'done', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000006', '2024-06-01 10:06:00', TRUE, NULL, NULL, 'unseen', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000015', '2024-06-01 10:15:00', TRUE, NULL, NULL, 'done', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000001', '2024-06-01 10:01:00', TRUE, NULL, NULL, 'unseen', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000012', '2024-06-01 10:12:00', TRUE, NULL, NULL, 'unseen', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000000', '2024-06-01 10:00:00', TRUE, NULL, NULL, 'unseen', FALSE),-('macro|[email protected]', '0190b000-0000-7000-8000-000000000014', '2024-06-01 10:14:00', TRUE, NULL, NULL, 'unseen', FALSE);+('macro|[email protected]', '0190b000-0000-7000-8000-000000000005', '2024-06-01 10:05:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000008', '2024-06-01 10:08:00', TRUE, NULL, NULL, 'seen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000108', '2024-06-01 10:08:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000004', '2024-06-01 10:04:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000010', '2024-06-01 10:10:00', TRUE, NULL, NULL, 'done', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000006', '2024-06-01 10:06:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000015', '2024-06-01 10:15:00', TRUE, NULL, NULL, 'done', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000001', '2024-06-01 10:01:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000012', '2024-06-01 10:12:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000000', '2024-06-01 10:00:00', TRUE, NULL, NULL, 'unseen', FALSE),+('macro|[email protected]', '0190b000-0000-7000-8000-000000000014', '2024-06-01 10:14:00', TRUE, NULL, NULL, 'unseen', FALSE);----------------------------------------------------- OWN ACTIVITY@@ -129,22 +129,22 @@ VALUESINSERT INTO public.activity_events ("id", "actor_id", "subject_id", "action", "action_payload", "entity_type", "entity_id", "occurred_at")VALUES-('0190c000-0000-7000-8000-000000000009', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-06-01 10:09:00+00'),-('0190c000-0000-7000-8000-000000000003', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '2024-06-01 10:03:00+00'),-('0190c000-0000-7000-8000-000000000007', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-cccc-cccc-cccc-cccccccccccc', '2024-06-01 10:07:00+00'),-('0190c000-0000-7000-8000-000000000002', 'macro|[email protected]', 'macro|[email protected]', 'created', NULL, 'document', '11111111-eeee-eeee-eeee-eeeeeeeeeeee', '2024-06-01 10:02:00+00'),-('0190c000-0000-7000-8000-000000000015', 'macro|[email protected]', 'macro|[email protected]', 'opened', NULL, 'document', '11111111-ffff-ffff-ffff-ffffffffffff', '2024-06-01 10:15:00+00'),-('0190c000-0000-7000-8000-000000000011', 'macro|[email protected]', 'macro|[email protected]', 'messaged', NULL, 'channel', '33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-06-01 10:11:00+00'),-('0190c000-0000-7000-8000-000000000010', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-9999-9999-9999-999999999999', '2024-06-01 10:10:00+00'),-('0190c000-0000-7000-8000-000000000013', 'macro|[email protected]', 'macro|[email protected]', 'sent', NULL, 'email_thread', '44444444-5555-5555-5555-555555555555', '2024-06-01 10:13:00+00'),+('0190c000-0000-7000-8000-000000000009', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-06-01 10:09:00+00'),+('0190c000-0000-7000-8000-000000000003', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '2024-06-01 10:03:00+00'),+('0190c000-0000-7000-8000-000000000007', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-cccc-cccc-cccc-cccccccccccc', '2024-06-01 10:07:00+00'),+('0190c000-0000-7000-8000-000000000002', 'macro|[email protected]', 'macro|[email protected]', 'created', NULL, 'document', '11111111-eeee-eeee-eeee-eeeeeeeeeeee', '2024-06-01 10:02:00+00'),+('0190c000-0000-7000-8000-000000000015', 'macro|[email protected]', 'macro|[email protected]', 'opened', NULL, 'document', '11111111-ffff-ffff-ffff-ffffffffffff', '2024-06-01 10:15:00+00'),+('0190c000-0000-7000-8000-000000000011', 'macro|[email protected]', 'macro|[email protected]', 'messaged', NULL, 'channel', '33333333-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-06-01 10:11:00+00'),+('0190c000-0000-7000-8000-000000000010', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-9999-9999-9999-999999999999', '2024-06-01 10:10:00+00'),+('0190c000-0000-7000-8000-000000000013', 'macro|[email protected]', 'macro|[email protected]', 'sent', NULL, 'email_thread', '44444444-5555-5555-5555-555555555555', '2024-06-01 10:13:00+00'),-- Opening doc-A after editing it must not move it.-('0190c000-0000-7000-8000-000000000016', 'macro|[email protected]', 'macro|[email protected]', 'opened', NULL, 'document', '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-06-01 10:16:00+00'),+('0190c000-0000-7000-8000-000000000016', 'macro|[email protected]', 'macro|[email protected]', 'opened', NULL, 'document', '11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2024-06-01 10:16:00+00'),-- user-2's newer edit of doc-B is not user-1's own work.-('0190c000-0000-7000-8000-000000000020', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '2024-06-01 10:20:00+00'),+('0190c000-0000-7000-8000-000000000020', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'document', '11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '2024-06-01 10:20:00+00'),-- Archiving thread-A records an edit, which is triage, not own work.-('0190c000-0000-7000-8000-000000000017', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'email_thread', '44444444-0000-0000-0000-000000000000', '2024-06-01 10:17:00+00'),+('0190c000-0000-7000-8000-000000000017', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'email_thread', '44444444-0000-0000-0000-000000000000', '2024-06-01 10:17:00+00'),-- Archiving thread-S after sending must not move it from its send.-('0190c000-0000-7000-8000-000000000018', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'email_thread', '44444444-5555-5555-5555-555555555555', '2024-06-01 10:18:00+00');+('0190c000-0000-7000-8000-000000000018', 'macro|[email protected]', 'macro|[email protected]', 'edited', NULL, 'email_thread', '44444444-5555-5555-5555-555555555555', '2024-06-01 10:18:00+00');-- doc-B (attention) and doc-C (own work) are tasks.INSERT INTO document_sub_type (document_id, sub_type)diff --git a/crates/soup/src/domain/models.rs b/crates/soup/src/domain/models.rsindex 2911d5c77a..8079dc09d6 100644--- a/crates/soup/src/domain/models.rs+++ b/crates/soup/src/domain/models.rs@@ -968,21 +968,24 @@ pub struct NotifiedEntity {pub notified_at: chrono::DateTime<chrono::Utc>,}-/// Which reasons admit an entity to the work feed.+/// How the attention candidate query keys the notifications that place its+/// candidates.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-pub enum WorkFeedSoupMode {- /// Live notifications plus the viewer's own work.- Work,- /// Live notifications only.- Attention,+pub enum AttentionKeying {+ /// A channel notification naming a thread root (`secondary_event_item`+ /// of type `channel_message`) keys to a `channel_message` candidate on+ /// it, like the notified-at feed; others key to their own entity.+ ThreadScoped,+ /// Every notification keys to the entity it is filed under.+ FiledEntity,}-/// Keyset position for a work feed page: the sort time and entity id of the-/// last candidate the previous page walked.+/// Keyset position for an attention feed page: the sort time and entity id+/// of the last candidate the previous page walked.////// Like [`NotifiedPagePosition`], the id stays the raw stored string.#[derive(Debug, Clone, PartialEq, Eq)]-pub struct WorkFeedPagePosition {+pub struct AttentionPagePosition {/// The last candidate's sort time: the later of its attention and/// own-work timestamps.pub sort_at: chrono::DateTime<chrono::Utc>,@@ -990,17 +993,19 @@ pub struct WorkFeedPagePosition {pub entity_id: String,}-/// Parameters for one page of work feed candidates.+/// Parameters for one page of attention feed candidates.#[derive(Debug)]-pub struct WorkFeedCandidateRequest<'a> {+pub struct AttentionCandidateRequest<'a> {/// User whose feed is listed; also the access-check subject.pub user_id: MacroUserIdStr<'a>,/// Maximum candidates to return.pub limit: u16,- /// Whether own work admits candidates.- pub mode: WorkFeedSoupMode,+ /// Whether the viewer's own work admits candidates besides attention.+ pub own_work: bool,+ /// How notifications key to candidates.+ pub keying: AttentionKeying,/// Resume after this position; `None` for the first page.- pub after: Option<WorkFeedPagePosition>,+ pub after: Option<AttentionPagePosition>,/// Entity types the caller asked for. Narrowed further by the filter/// and by which hydration legs are active.pub types: &'a [EntityType],@@ -1013,17 +1018,20 @@ pub struct WorkFeedCandidateRequest<'a> {pub foreign_entity_sources: &'a [SourceId],/// Entity types whose candidates the domain can hydrate for this request.pub hydratable: NotifiedHydratableTypes,+ /// Whether CRM company and contact candidates can be hydrated: the viewer+ /// has a CRM team receipt.+ pub crm: bool,/// Restrict the feed to these candidate keys, for recomputing known items.pub only: Option<&'a [Entity<'static>]>,}-/// One work feed candidate and the timestamps of its two reasons.+/// One attention feed candidate and the timestamps of its two reasons.////// Each candidate carries the reason that places it in the feed: its/// `sort_at` is the later of the two timestamps, and exactly one of the/// candidate query's two streams emits it.#[derive(Debug, Clone, PartialEq, Eq)]-pub struct WorkFeedCandidate {+pub struct AttentionCandidate {/// The candidate's entity; channel-thread candidates are keyed on their/// thread root as a `channel_message`, like the notified-at feed.pub entity: Entity<'static>,@@ -1038,48 +1046,51 @@ pub struct WorkFeedCandidate {pub sort_at: chrono::DateTime<chrono::Utc>,}-/// Request for one page of the hydrated work feed.+/// Request for one page of a hydrated attention feed: Home's work feed or+/// the notifications inbox.#[derive(Debug, Clone)]-pub struct WorkFeedSoupRequest {+pub struct AttentionSoupRequest {/// User whose feed is listed.pub user: MacroUserIdStr<'static>,/// Every inbox the caller can read.pub link_ids: Vec<Uuid>,/// Maximum items to return.pub limit: u16,- /// Whether own work admits items.- pub mode: WorkFeedSoupMode,+ /// Whether the viewer's own work admits items besides attention.+ pub own_work: bool,+ /// How notifications key to candidates.+ pub keying: AttentionKeying,/// Entity types to include.pub types: Vec<EntityType>,/// Membership filters, folded into the candidate gates and applied in/// full by each domain's hydration leg.pub filter: EntityFilterAst,/// Resume after this position; `None` for the first page.- pub after: Option<WorkFeedPagePosition>,+ pub after: Option<AttentionPagePosition>,/// Restrict the feed to these candidate keys, for recomputing known items.pub only: Option<Vec<Entity<'static>>>,}-/// One hydrated work feed item and its reason timestamps.+/// One hydrated attention feed item and its reason timestamps.#[derive(Debug)]-pub struct WorkFeedSoupItem {+pub struct AttentionSoupItem {/// The authorized Soup item with its server facts.pub hydration: SoupProjectionHydration,- /// See [`WorkFeedCandidate::attention_at`].+ /// See [`AttentionCandidate::attention_at`].pub attention_at: Option<chrono::DateTime<chrono::Utc>>,- /// See [`WorkFeedCandidate::touched_at`].+ /// See [`AttentionCandidate::touched_at`].pub touched_at: Option<chrono::DateTime<chrono::Utc>>,- /// See [`WorkFeedCandidate::sort_at`].+ /// See [`AttentionCandidate::sort_at`].pub sort_at: chrono::DateTime<chrono::Utc>,}-/// One page of the hydrated work feed.+/// One page of a hydrated attention feed.#[derive(Debug)]-pub struct WorkFeedSoupPage {+pub struct AttentionSoupPage {/// The page's items, newest first.- pub items: Vec<WorkFeedSoupItem>,+ pub items: Vec<AttentionSoupItem>,/// Where the next page starts; `None` once the feed is exhausted.- pub next: Option<WorkFeedPagePosition>,+ pub next: Option<AttentionPagePosition>,}/// Whether the notified-at candidate query can fold this calendar filter.diff --git a/crates/soup/src/domain/ports.rs b/crates/soup/src/domain/ports.rsindex e06ea34e80..ad9cda458c 100644--- a/crates/soup/src/domain/ports.rs+++ b/crates/soup/src/domain/ports.rs@@ -2,10 +2,11 @@ use std::sync::Arc;use crate::domain::models::grouping::{GroupByField, GroupLabels};use crate::domain::models::{- AdvancedSortParams, CrmPropertyEdge, EnrichedSoupItem, GroupedSortRequest, IntoSoupReqAst,+ AdvancedSortParams, AttentionCandidate, AttentionCandidateRequest, AttentionSoupPage,+ AttentionSoupRequest, CrmPropertyEdge, EnrichedSoupItem, GroupedSortRequest, IntoSoupReqAst,NotifiedEntity, NotifiedSoupRequest, SimpleSortRequest, SoupErr, SoupProjectionHydration,- SoupPropertiesField, SoupRequest, TouchedEntity, TouchedSoupRequest, WorkFeedCandidate,- WorkFeedCandidateRequest, WorkFeedSoupPage, WorkFeedSoupRequest, grouping::ItemGroupingInfo,+ SoupPropertiesField, SoupRequest, TouchedEntity, TouchedSoupRequest,+ grouping::ItemGroupingInfo,};use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use macro_user_id::user_id::MacroUserIdStr;@@ -117,14 +118,14 @@ pub trait SoupRepo: Send + Sync + 'static {req: NotifiedSoupRequest<'a>,) -> impl Future<Output = Result<Vec<NotifiedEntity>, Self::Err>> + Send;- /// Fetch one page of work feed candidates: entities with live attention- /// or own work, newest `sort_at` first, already gated on existence,+ /// Fetch one page of attention feed candidates: entities with live+ /// attention or own work, newest `sort_at` first, already gated on existence,/// deletion and access, and on the request's entity filters where soup/// owns the fold.- fn work_feed_soup_page<'a>(+ fn attention_soup_page<'a>(&self,- req: WorkFeedCandidateRequest<'a>,- ) -> impl Future<Output = Result<Vec<WorkFeedCandidate>, Self::Err>> + Send;+ req: AttentionCandidateRequest<'a>,+ ) -> impl Future<Output = Result<Vec<AttentionCandidate>, Self::Err>> + Send;}/// The possible outputs of soup — one paginated page per query mode.@@ -360,21 +361,22 @@ pub trait SoupService: Send + Sync + 'static {user_id: MacroUserIdStr<'a>,) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, SoupErr>> + Send;- /// Fetch one hydrated page of the viewer's work feed: entities with live- /// attention or own work, newest `sort_at` first, each with its reason- /// timestamps and authoritative server facts.+ /// Fetch one hydrated page of one of the viewer's attention feeds (Home's+ /// work feed, the notifications inbox): entities with live attention or+ /// own work, newest `sort_at` first, each with its reason timestamps and+ /// authoritative server facts.///- /// Services without a work feed reject the request. The production+ /// Services without attention feeds reject the request. The production/// service overrides this method.- fn get_work_feed_page(+ fn get_attention_page(&self,- req: WorkFeedSoupRequest,+ req: AttentionSoupRequest,team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,- ) -> impl Future<Output = Result<WorkFeedSoupPage, SoupErr>> + Send {+ ) -> impl Future<Output = Result<AttentionSoupPage, SoupErr>> + Send {let _ = (req, team_receipt);async move {Err(SoupErr::SoupDbErr(anyhow::anyhow!(- "this soup service does not serve the work feed"+ "this soup service does not serve attention feeds")))}}@@ -489,12 +491,12 @@ where(**self).caller_tag_sets(user_id).await}- async fn get_work_feed_page(+ async fn get_attention_page(&self,- req: WorkFeedSoupRequest,+ req: AttentionSoupRequest,team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,- ) -> Result<WorkFeedSoupPage, SoupErr> {- (**self).get_work_feed_page(req, team_receipt).await+ ) -> Result<AttentionSoupPage, SoupErr> {+ (**self).get_attention_page(req, team_receipt).await}}diff --git a/crates/soup/src/domain/service.rs b/crates/soup/src/domain/service.rsindex b631a45e41..7856f77985 100644--- a/crates/soup/src/domain/service.rs+++ b/crates/soup/src/domain/service.rs@@ -1,14 +1,15 @@use crate::domain::models::grouping::{GroupByField, GroupLabels};use crate::domain::{models::{- AdvancedSortParams, EnrichedSoupItem, FrecencyQueryInner, GetCrmCompaniesRequest,- GroupedSortRequest, IntoSoupReqAst, NotifiedHydratableTypes, NotifiedPagePosition,- NotifiedQueryInner, NotifiedSoupRequest, SimpleQueryInner, SimpleSortQuery,- SimpleSortRequest, SoupDocumentServerFacts, SoupErr, SoupProjectionHydration,- SoupPropertiesField, SoupQuery, SoupRequest, SoupSortDirection, SoupType,- TouchedPagePosition, TouchedQueryInner, TouchedSoupRequest, WorkFeedCandidateRequest,- WorkFeedPagePosition, WorkFeedSoupItem, WorkFeedSoupPage, WorkFeedSoupRequest,- calendar_filter_supported_by_notified, grouping::ItemGroupingInfo,+ AdvancedSortParams, AttentionCandidateRequest, AttentionPagePosition, AttentionSoupItem,+ AttentionSoupPage, AttentionSoupRequest, EnrichedSoupItem, FrecencyQueryInner,+ GetCrmCompaniesRequest, GroupedSortRequest, IntoSoupReqAst, NotifiedHydratableTypes,+ NotifiedPagePosition, NotifiedQueryInner, NotifiedSoupRequest, SimpleQueryInner,+ SimpleSortQuery, SimpleSortRequest, SoupDocumentServerFacts, SoupErr,+ SoupProjectionHydration, SoupPropertiesField, SoupQuery, SoupRequest, SoupSortDirection,+ SoupType, TouchedPagePosition, TouchedQueryInner, TouchedSoupRequest,+ calendar_filter_supported_by_notified, contact_listing::GetCrmContactsRequest,+ grouping::ItemGroupingInfo,},ports::{SoupOutput, SoupRepo, SoupService},};@@ -18,7 +19,10 @@ use channels::domain::{ports::ChannelListService,};use cowlike::CowLike;-use crm::domain::service::CrmService;+use crm::domain::{+ auth::CrmTeamReceipt, companies_repo::CrmCompanyListSort, contact_listing::CrmContactListQuery,+ service::CrmService,+};use either::Either;use email::domain::{models::{GetEmailsRequest, PreviewView, PreviewViewStandardLabel},@@ -42,6 +46,7 @@ use github_pull_requests::domain::{use item_filters::ast::{EntityFilterAst, LiteralTree,channel::{ChannelLiteral, ChannelThreadLiteral},+ crm_contact::CrmContactLiteral,email::EmailLiteral,foreign_entity::ForeignEntityLiteral,github_pull_request::GithubPullRequestLiteral,@@ -65,6 +70,7 @@ use serde::Serialize;use std::cmp::Ordering;use std::collections::HashMap;use std::sync::Arc;+use tracing::Instrument;use uuid::Uuid;mod agent_metadata;@@ -127,6 +133,9 @@ struct NotifiedHydrationLegs {foreign_entities: Option<(Vec<SourceId>, ForeignEntityListQuery)>,/// Narrows the foreign entity leg to matching GitHub pull requests.github_pull_request_filter: LiteralTree<GithubPullRequestLiteral>,+ /// The viewer's team receipt when it is a valid CRM capability; only the+ /// attention feeds hydrate CRM candidates.+ crm: Option<EntityAccessReceipt<MemberTeamRole>>,}/// ANDs a leg's request-level filter tree onto the page's id tree, so the@@ -863,7 +872,7 @@ whereOk((page, next))}- /// Runs one page of the work feed: fetches merged attention and own-work+ /// Runs one page of an attention feed: fetches merged attention and own-work/// candidates, hydrates them through the notified-at feed's legs, and/// reassembles the page in feed order.///@@ -875,11 +884,11 @@ where/// the page refills from the next candidate page, bounded by/// [`MAX_NOTIFIED_FILL_ROUNDS`].#[tracing::instrument(err, skip(self, req, team_receipt), fields(user = %req.user))]- async fn handle_work_feed_request(+ async fn handle_attention_request(&self,- req: WorkFeedSoupRequest,+ req: AttentionSoupRequest,team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,- ) -> Result<WorkFeedSoupPage, SoupErr> {+ ) -> Result<AttentionSoupPage, SoupErr> {if !calendar_filter_supported_by_notified(req.filter.calendar_event_filter.as_deref()) {return Err(SoupErr::NotifiedUnsupportedFilter("calendar_event"));}@@ -903,6 +912,13 @@ wherelet foreign_entity_source_ids =legs_request.build_foreign_entity_source_ids(team_receipt.as_ref());let metadata_source_ids = foreign_entity_source_ids.clone();+ let crm = team_receipt.clone().filter(|receipt| {+ CrmTeamReceipt::from_team_receipt(receipt.clone())+ .inspect_err(|error| {+ tracing::warn!(error = ?error, "team receipt is not a CRM receipt; skipping CRM attention feed candidates");+ })+ .is_ok()+ });let legs = NotifiedHydrationLegs {link_ids: legs_request.link_ids.clone(),comms: legs_request.build_comms_request(),@@ -912,6 +928,7 @@ where.map(|query| (foreign_entity_source_ids, query)),github_pull_request_filter: legs_request.build_github_pull_request_filter(),email: legs_request.build_email_request(team_receipt),+ crm,};let foreign_entity_sources: Vec<SourceId> = legs.foreign_entities@@ -933,16 +950,18 @@ wherefor _ in 0..MAX_NOTIFIED_FILL_ROUNDS {let candidates = self.soup_storage- .work_feed_soup_page(WorkFeedCandidateRequest {+ .attention_soup_page(AttentionCandidateRequest {user_id: req.user.copied(),limit,- mode: req.mode,+ own_work: req.own_work,+ keying: req.keying,after: after.clone(),types: &req.types,filter: Some(&req.filter),link_ids: &legs.link_ids,foreign_entity_sources: &foreign_entity_sources,hydratable,+ crm: legs.crm.is_some(),only: req.only.as_deref(),}).await@@ -965,7 +984,7 @@ wherebreak;}consumed += 1;- walked = Some(WorkFeedPagePosition {+ walked = Some(AttentionPagePosition {sort_at: candidate.sort_at,entity_id: candidate.entity.entity_id.to_string(),});@@ -1003,11 +1022,11 @@ where).await?;- Ok(WorkFeedSoupPage {+ Ok(AttentionSoupPage {items: items.into_iter().zip(sort_ats)- .map(|(candidate, sort_at)| WorkFeedSoupItem {+ .map(|(candidate, sort_at)| AttentionSoupItem {attention_at: candidate.notified_at,touched_at: candidate.touched_at,sort_at,@@ -1038,6 +1057,8 @@ wherelet mut thread_ids = Vec::new();let mut email_ids = Vec::new();let mut foreign_entity_ids = Vec::new();+ let mut crm_company_ids = Vec::new();+ let mut crm_contact_ids = Vec::new();for entity in entities {match entity.entity_type {// Calendar events and agent sessions ride the main by-ids@@ -1063,6 +1084,12 @@ whereEntityType::ForeignEntity => {push_candidate_uuid(&mut foreign_entity_ids, entity, "foreign")}+ EntityType::CrmCompany => {+ push_candidate_uuid(&mut crm_company_ids, entity, "crm company")+ }+ EntityType::CrmContact => {+ push_candidate_uuid(&mut crm_contact_ids, entity, "crm contact")+ }// The candidate query only returns the types above._ => {}}@@ -1171,6 +1198,44 @@ where.map_err(anyhow::Error::from).map_err(SoupErr::from)};+ // An empty id list would list every record, so each CRM leg runs+ // only for the candidates it was given.+ let crm_access = || {+ legs.crm+ .clone()+ .and_then(|receipt| CrmTeamReceipt::from_team_receipt(receipt).ok())+ };+ let crm_company_request =+ crm_access()+ .filter(|_| !crm_company_ids.is_empty())+ .map(|access| GetCrmCompaniesRequest {+ access,+ user_id: user.clone(),+ limit: crm_company_ids.len() as i64,+ company_ids: crm_company_ids,+ hidden: None,+ sort: CrmCompanyListSort::UpdatedAt,+ cursor: None,+ });+ let crm_contact_request = crm_access().and_then(|access| {+ let ids = balanced_or_tree(+ crm_contact_ids+ .iter()+ .map(|id| Expr::val(CrmContactLiteral::Id(*id)))+ .collect(),+ )?;+ Some(GetCrmContactsRequest {+ user_id: user.clone(),+ access: Some(access),+ query: CrmContactListQuery {+ filter: Arc::unwrap_or_clone(ids),+ sort: CrmCompanyListSort::UpdatedAt,+ cursor: None,+ ascending: false,+ limit: u16::try_from(crm_contact_ids.len()).unwrap_or(u16::MAX),+ },+ })+ });let (main_items,project_items,@@ -1178,6 +1243,8 @@ wherethread_candidates,email_candidates,foreign_entity_candidates,+ crm_company_candidates,+ crm_contact_candidates,) = tokio::join!(main_items_fut,project_items_fut,@@ -1192,6 +1259,13 @@ wherelegs.github_pull_request_filter.clone(),SoupSortDirection::Desc,),+ self.handle_crm_company_request(crm_company_request),+ self.handle_crm_contact_request(crm_contact_request)+ .instrument(tracing::info_span!(+ "soup.crm_contact_candidates",+ contact_count = crm_contact_ids.len(),+ contact_ids = ?crm_contact_ids,+ )),);let mut candidates_by_entity = HashMap::new();@@ -1202,6 +1276,8 @@ where.chain(thread_candidates?).chain(email_candidates?).chain(foreign_entity_candidates?)+ .chain(crm_company_candidates?)+ .chain(crm_contact_candidates?){let key = {let entity = candidate.item.entity();@@ -1921,6 +1997,7 @@ whereforeign_entities: foreign_entity_query.map(|query| (foreign_entity_source_ids, query)),github_pull_request_filter,+ crm: None,};let (candidates, next) = self.handle_notified_request(@@ -2158,11 +2235,11 @@ where.map_err(anyhow::Error::from)?)}- async fn get_work_feed_page(+ async fn get_attention_page(&self,- req: WorkFeedSoupRequest,+ req: AttentionSoupRequest,team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,- ) -> Result<WorkFeedSoupPage, SoupErr> {- self.handle_work_feed_request(req, team_receipt).await+ ) -> Result<AttentionSoupPage, SoupErr> {+ self.handle_attention_request(req, team_receipt).await}}diff --git a/crates/soup/src/domain/service/tests.rs b/crates/soup/src/domain/service/tests.rsindex b5eb7b6d76..53788c0d9e 100644--- a/crates/soup/src/domain/service/tests.rs+++ b/crates/soup/src/domain/service/tests.rs@@ -45,10 +45,10 @@ use uuid::Uuid;use super::*;mod agent_metadata;+mod attention;mod crm_association;mod exclusions;mod favorites;-mod work_feed;struct NoopEmailPreviewService;diff --git a/crates/soup/src/domain/service/tests/work_feed.rs b/crates/soup/src/domain/service/tests/attention.rssimilarity index 88%rename from crates/soup/src/domain/service/tests/work_feed.rsrename to crates/soup/src/domain/service/tests/attention.rsindex 48b81634b3..83e3574df0 100644--- a/crates/soup/src/domain/service/tests/work_feed.rs+++ b/crates/soup/src/domain/service/tests/attention.rs@@ -1,14 +1,15 @@use super::*;use crate::domain::models::{- WorkFeedCandidate, WorkFeedPagePosition, WorkFeedSoupMode, WorkFeedSoupRequest,+ AttentionCandidate, AttentionKeying, AttentionPagePosition, AttentionSoupRequest,};-fn work_feed_request(limit: u16) -> WorkFeedSoupRequest {- WorkFeedSoupRequest {+fn work_feed_request(limit: u16) -> AttentionSoupRequest {+ AttentionSoupRequest {user: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),link_ids: vec![],limit,- mode: WorkFeedSoupMode::Work,+ own_work: true,+ keying: AttentionKeying::ThreadScoped,types: vec![EntityType::Document],filter: EntityFilterAst::default(),after: None,@@ -20,8 +21,8 @@ fn candidate(id: Uuid,attention: Option<DateTime<Utc>>,touched: Option<DateTime<Utc>>,-) -> WorkFeedCandidate {- WorkFeedCandidate {+) -> AttentionCandidate {+ AttentionCandidate {entity: EntityType::Document.with_entity_string(id.to_string()),attention_at: attention,touched_at: touched,@@ -52,7 +53,7 @@ fn service(}/// Hydration drops refill the page from the next candidate page, every item-/// keeps both reason timestamps, and the request's mode and types reach the+/// keeps both reason timestamps, and the request's own work, keying and types reach the/// candidate query.#[tokio::test]async fn work_feed_refills_after_drops_and_carries_reason_timestamps() {@@ -63,11 +64,12 @@ async fn work_feed_refills_after_drops_and_carries_reason_timestamps() {let mut soup_mock = MockSoupRepo::new();soup_mock- .expect_work_feed_soup_page()+ .expect_attention_soup_page().times(2).returning(move |req| {assert_eq!(req.limit, 2);- assert_eq!(req.mode, WorkFeedSoupMode::Work);+ assert!(req.own_work);+ assert_eq!(req.keying, AttentionKeying::ThreadScoped);assert_eq!(req.types, &[EntityType::Document]);assert!(req.only.is_none());let rows = match &req.after {@@ -78,7 +80,7 @@ async fn work_feed_refills_after_drops_and_carries_reason_timestamps() {Some(after) => {assert_eq!(*after,- WorkFeedPagePosition {+ AttentionPagePosition {sort_at: base + Days::new(4),entity_id: ghost.to_string(),}@@ -111,7 +113,7 @@ async fn work_feed_refills_after_drops_and_carries_reason_timestamps() {});let page = service(soup_mock)- .get_work_feed_page(work_feed_request(2), None)+ .get_attention_page(work_feed_request(2), None).await.unwrap();@@ -156,7 +158,7 @@ async fn work_feed_full_page_continues_from_the_last_candidate() {let mut soup_mock = MockSoupRepo::new();soup_mock- .expect_work_feed_soup_page()+ .expect_attention_soup_page().times(1).returning(move |_| {Box::pin(async move {@@ -186,14 +188,14 @@ async fn work_feed_full_page_continues_from_the_last_candidate() {});let page = service(soup_mock)- .get_work_feed_page(work_feed_request(2), None)+ .get_attention_page(work_feed_request(2), None).await.unwrap();assert_eq!(page.items.len(), 2);assert_eq!(page.next,- Some(WorkFeedPagePosition {+ Some(AttentionPagePosition {sort_at: base + Days::new(4),entity_id: second.to_string(),})@@ -203,14 +205,14 @@ async fn work_feed_full_page_continues_from_the_last_candidate() {#[tokio::test]async fn work_feed_rejects_calendar_filters_it_cannot_fold() {let mut soup_mock = MockSoupRepo::new();- soup_mock.expect_work_feed_soup_page().times(0);+ soup_mock.expect_attention_soup_page().times(0);let mut request = work_feed_request(2);request.filter.calendar_event_filter = Some(Arc::new(Expr::val(item_filters::ast::calendar_event::CalendarEventLiteral::Status("confirmed".into()),)));let error = service(soup_mock)- .get_work_feed_page(request, None)+ .get_attention_page(request, None).await.unwrap_err();assert_matches!(error, SoupErr::NotifiedUnsupportedFilter("calendar_event"));@@ -230,9 +232,9 @@ async fn work_feed_rejects_crm_associations() {for request in [scoped, literal] {let mut soup_mock = MockSoupRepo::new();- soup_mock.expect_work_feed_soup_page().times(0);+ soup_mock.expect_attention_soup_page().times(0);let error = service(soup_mock)- .get_work_feed_page(request, None)+ .get_attention_page(request, None).await.unwrap_err();assert_matches!(error, SoupErr::AstErr(_));diff --git a/crates/soup/src/outbound/pg_soup_repo.rs b/crates/soup/src/outbound/pg_soup_repo.rsindex a5fc0c3fac..83329dfd80 100644--- a/crates/soup/src/outbound/pg_soup_repo.rs+++ b/crates/soup/src/outbound/pg_soup_repo.rs@@ -1,10 +1,10 @@use crate::{domain::{models::{- AdvancedSortParams, CrmPropertyEdge, DynamicSort, GroupedSortRequest, NotifiedEntity,- NotifiedSoupRequest, SimpleSortQuery, SimpleSortRequest, SoupProjectionHydration,- SoupPropertiesField, TouchedEntity, TouchedSoupRequest, WorkFeedCandidate,- WorkFeedCandidateRequest, grouping::ItemGroupingInfo,+ AdvancedSortParams, AttentionCandidate, AttentionCandidateRequest, CrmPropertyEdge,+ DynamicSort, GroupedSortRequest, NotifiedEntity, NotifiedSoupRequest, SimpleSortQuery,+ SimpleSortRequest, SoupProjectionHydration, SoupPropertiesField, TouchedEntity,+ TouchedSoupRequest, grouping::ItemGroupingInfo,},ports::SoupRepo,},@@ -21,6 +21,7 @@ use readonly_pool::ReadOnlyPool;use system_properties::SystemPropertyKey;mod agent_session;+mod attention;mod calendar_event;mod candidate_gates;mod crm_association;@@ -31,7 +32,6 @@ mod initiative;mod notified;mod touched;mod unexpanded;-mod work_feed;/// PostgreSQL implementation of [`SoupRepo`].pub struct PgSoupRepo {@@ -354,11 +354,11 @@ impl SoupRepo for PgSoupRepo {notified::notified_soup_page(&self.pool.0, req).await}- async fn work_feed_soup_page<'a>(+ async fn attention_soup_page<'a>(&self,- req: WorkFeedCandidateRequest<'a>,- ) -> Result<Vec<WorkFeedCandidate>, Self::Err> {- work_feed::work_feed_soup_page(&self.pool.0, req).await+ req: AttentionCandidateRequest<'a>,+ ) -> Result<Vec<AttentionCandidate>, Self::Err> {+ attention::attention_soup_page(&self.pool.0, req).await}}diff --git a/crates/soup/src/outbound/pg_soup_repo/work_feed.rs b/crates/soup/src/outbound/pg_soup_repo/attention.rssimilarity index 63%rename from crates/soup/src/outbound/pg_soup_repo/work_feed.rsrename to crates/soup/src/outbound/pg_soup_repo/attention.rsindex 1142b7fad1..eb4baf2088 100644--- a/crates/soup/src/outbound/pg_soup_repo/work_feed.rs+++ b/crates/soup/src/outbound/pg_soup_repo/attention.rs@@ -1,6 +1,8 @@-//! The work feed candidate query: one keyset-paginated page merging the-//! viewer's attention (the newest pending, i.e. unseen or seen, notification)-//! with their own work (latest activity that counts as work), newest first.+//! The attention candidate query behind Home's work feed and the+//! notifications inbox: one keyset-paginated page merging the viewer's+//! attention (the newest pending, i.e. unseen or seen, notification) with,+//! when asked, their own work (latest activity that counts as work), newest+//! first.//!//! An item's place in the feed is `sort_at = max(attention_at, touched_at)`.//! The query runs two streams, each ordered by its own timestamp: the@@ -10,11 +12,13 @@//! `sort_at`, so merging the two ordered streams and taking the first `limit`//! rows is the page — no candidate repeats across pages and none is skipped.//!-//! Both streams share the notified-at feed's keying (thread-scoped channel-//! notifications become `channel_message` candidates on their thread root)-//! and its per-type gates. One condition is specific to the work feed: an-//! email thread's attention lasts only while the thread is in the inbox-//! (mail's own notion of done).+//! [`AttentionKeying`] decides which candidate a notification places.+//! `ThreadScoped` shares the notified-at feed's keying (thread-scoped channel+//! notifications become `channel_message` candidates on their thread root);+//! `FiledEntity` keys every notification to the entity it is filed under, so+//! a channel and all its threads are one candidate. Both share the per-type+//! gates and one attention condition: an email thread's attention lasts only+//! while the thread is in the inbox (mail's own notion of done).//!//! Done notifications never place an item, so the query reads only the//! viewer's pending ones, once, and both streams look attention up there.@@ -35,7 +39,7 @@ use sqlx::{PgPool, Row};use std::str::FromStr;use crate::domain::models::{- NotifiedSoupRequest, WorkFeedCandidate, WorkFeedCandidateRequest, WorkFeedSoupMode,+ AttentionCandidate, AttentionCandidateRequest, AttentionKeying, NotifiedSoupRequest,};use crate::outbound::pg_soup_repo::candidate_gates::{channel_gate, channel_thread_gate, chat_gate, document_gate, email_gate, initiative_gate,@@ -47,9 +51,9 @@ use crate::outbound::pg_soup_repo::notified::{use crate::outbound::pg_soup_repo::touched::view_tags_sql;use crate::outbound::pg_soup_repo::type_err;-/// Every type the work feed can surface, in the order the notified-at feed-/// decides them.-fn requested_types<'a>(req: &WorkFeedCandidateRequest<'a>) -> Vec<&'static str> {+/// Every type an attention feed can surface, in the order the notified-at+/// feed decides them, then the CRM records only attention feeds list.+fn requested_types<'a>(req: &AttentionCandidateRequest<'a>) -> Vec<&'static str> {let notified = NotifiedSoupRequest {user_id: req.user_id.copied(),limit: req.limit,@@ -60,12 +64,66 @@ fn requested_types<'a>(req: &WorkFeedCandidateRequest<'a>) -> Vec<&'static str>hydratable: req.hydratable,};let requested: Vec<&'static str> = req.types.iter().map(|t| (*t).into()).collect();+ let crm: &[&'static str] = if req.crm {+ &[EntityType::CrmCompany.into(), EntityType::CrmContact.into()]+ } else {+ &[]+ };included_types(¬ified).into_iter()+ .chain(crm.iter().copied()).filter(|entity_type| requested.contains(entity_type)).collect()}+/// The `crm_companies` row aliased `alias` is visible to the viewer: its+/// team has CRM enabled, the viewer belongs to that team, and the company is+/// not hidden (hidden records are listed only on explicit admin requests).+fn visible_crm_record(alias: &str) -> String {+ format!(+ r#"NOT {alias}.hidden+ AND EXISTS (+ SELECT 1 FROM team_user tu+ JOIN team_crm_settings tcs ON tcs.team_id = tu.team_id+ WHERE tu.team_id = {alias}.team_id+ AND tu.user_id = $1+ AND tcs.crm_enabled+ )"#+ )+}++fn crm_company_gate() -> String {+ uuid_guarded(+ ID_SQL,+ format!(+ r#"EXISTS (+ SELECT 1 FROM crm_companies c+ WHERE c.id = {ID_SQL}::uuid+ AND {visible}+ )"#,+ visible = visible_crm_record("c"),+ ),+ )+}++/// A contact belongs to its team directly, and its company is optional; a+/// hidden company still hides the contacts it has.+fn crm_contact_gate() -> String {+ uuid_guarded(+ ID_SQL,+ format!(+ r#"EXISTS (+ SELECT 1 FROM crm_contacts ct+ LEFT JOIN crm_companies c ON c.id = ct.company_id+ WHERE ct.id = {ID_SQL}::uuid+ AND NOT COALESCE(c.hidden, FALSE)+ AND {visible}+ )"#,+ visible = visible_crm_record("ct"),+ ),+ )+}+/// An email thread's attention lasts while the thread is in the inbox: mail/// done is archive, independent of the thread's notification states.fn email_inbox_gate() -> String {@@ -95,10 +153,22 @@ fn own_work(alias: &str) -> String {)}-fn build_query(req: &WorkFeedCandidateRequest<'_>) -> String {+/// Whether the `notification` row `n` places the `channel_message` candidate+/// named by its secondary item rather than the entity it is filed under.+fn thread_keyed(keying: AttentionKeying) -> &'static str {+ match keying {+ AttentionKeying::ThreadScoped => {+ "(n.event_item_type = 'channel' AND n.secondary_event_item_type = 'channel_message')"+ }+ AttentionKeying::FiledEntity => "FALSE",+ }+}++fn build_query(req: &AttentionCandidateRequest<'_>) -> String {let filter = req.filter;format!(- include_str!("work_feed/query.sql"),+ include_str!("attention/query.sql"),+ thread_keyed = thread_keyed(req.keying),own_work_ae = own_work("ae"),own_work_newer = own_work("newer"),email_inbox_gate = email_inbox_gate(),@@ -112,19 +182,21 @@ fn build_query(req: &WorkFeedCandidateRequest<'_>) -> String {calendar_event_gate = calendar_event_gate(filter),foreign_entity_gate = foreign_entity_gate(filter),agent_session_gate = agent_session_gate(filter),+ crm_company_gate = crm_company_gate(),+ crm_contact_gate = crm_contact_gate(),)}-/// Fetches one page of work feed candidates.+/// Fetches one page of attention feed candidates.////// `user_notification.created_at` is a naive `TIMESTAMP` written in UTC; the/// query converts it to `timestamptz` so attention and activity timestamps/// compare and paginate on one clock.#[tracing::instrument(err, skip(db, req))]-pub(super) async fn work_feed_soup_page(+pub(super) async fn attention_soup_page(db: &PgPool,- req: WorkFeedCandidateRequest<'_>,-) -> Result<Vec<WorkFeedCandidate>, sqlx::Error> {+ req: AttentionCandidateRequest<'_>,+) -> Result<Vec<AttentionCandidate>, sqlx::Error> {let types = requested_types(&req);if types.is_empty() {return Ok(Vec::new());@@ -162,7 +234,7 @@ pub(super) async fn work_feed_soup_page(.bind(req.limit as i64).bind(&source_ids).bind(&source_auth_entities)- .bind(req.mode == WorkFeedSoupMode::Work)+ .bind(req.own_work).bind(only_types).bind(only_ids)// Unnamed statement, same reasoning as the other candidate queries:@@ -172,7 +244,7 @@ pub(super) async fn work_feed_soup_page(let entity_type: String = row.try_get("entity_type")?;let entity_id: String = row.try_get("entity_id")?;let entity_type = EntityType::from_str(&entity_type).map_err(type_err)?;- Ok(WorkFeedCandidate {+ Ok(AttentionCandidate {entity: entity_type.with_entity_string(entity_id),attention_at: row.try_get("attention_at")?,touched_at: row.try_get("touched_at")?,diff --git a/crates/soup/src/outbound/pg_soup_repo/work_feed/query.sql b/crates/soup/src/outbound/pg_soup_repo/attention/query.sqlsimilarity index 96%rename from crates/soup/src/outbound/pg_soup_repo/work_feed/query.sqlrename to crates/soup/src/outbound/pg_soup_repo/attention/query.sqlindex e8e246a8fe..31b8b9c81a 100644--- a/crates/soup/src/outbound/pg_soup_repo/work_feed/query.sql+++ b/crates/soup/src/outbound/pg_soup_repo/attention/query.sql@@ -48,6 +48,8 @@ own_work AS NOT MATERIALIZED (WHEN 'calendar_event' THEN {calendar_event_gate}WHEN 'foreign_entity' THEN {foreign_entity_gate}WHEN 'agent_session' THEN {agent_session_gate}+ WHEN 'crm_company' THEN {crm_company_gate}+ WHEN 'crm_contact' THEN {crm_contact_gate}ELSE FALSEEND),@@ -77,12 +79,10 @@ pending AS MATERIALIZED (-- poor, and a hash join would scan every user's notifications instead.CROSS JOIN LATERAL (SELECT- CASE WHEN n.event_item_type = 'channel'- AND n.secondary_event_item_type = 'channel_message'+ CASE WHEN {thread_keyed}THEN 'channel_message' ELSE n.event_item_typeEND AS entity_type,- CASE WHEN n.event_item_type = 'channel'- AND n.secondary_event_item_type = 'channel_message'+ CASE WHEN {thread_keyed}THEN n.secondary_event_item_id ELSE n.event_item_idEND AS entity_idFROM notification n@@ -142,6 +142,8 @@ attention_page AS (WHEN 'calendar_event' THEN {calendar_event_gate}WHEN 'foreign_entity' THEN {foreign_entity_gate}WHEN 'agent_session' THEN {agent_session_gate}+ WHEN 'crm_company' THEN {crm_company_gate}+ WHEN 'crm_contact' THEN {crm_contact_gate}ELSE FALSEENDORDER BY nc.attention_at DESC, nc.entity_id DESCdiff --git a/crates/soup/src/outbound/pg_soup_repo/work_feed/test.rs b/crates/soup/src/outbound/pg_soup_repo/attention/test.rssimilarity index 60%rename from crates/soup/src/outbound/pg_soup_repo/work_feed/test.rsrename to crates/soup/src/outbound/pg_soup_repo/attention/test.rsindex 21f6a85ba4..459b65760c 100644--- a/crates/soup/src/outbound/pg_soup_repo/work_feed/test.rs+++ b/crates/soup/src/outbound/pg_soup_repo/attention/test.rs@@ -1,5 +1,5 @@use super::*;-use crate::domain::models::{NotifiedHydratableTypes, WorkFeedPagePosition};+use crate::domain::models::{AttentionKeying, AttentionPagePosition, NotifiedHydratableTypes};use chrono::Timelike;use document_sub_type::DocumentSubType;use filter_ast::Expr;@@ -12,7 +12,7 @@ use sqlx::{Pool, Postgres};use std::sync::Arc;use uuid::Uuid;-const USER_1: &str = "macro|[email protected]";+const USER_1: &str = "macro|[email protected]";const DOC_A: &str = "11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa";const DOC_B: &str = "11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb";const DOC_C: &str = "11111111-cccc-cccc-cccc-cccccccccccc";@@ -26,6 +26,20 @@ const THREAD_M: &str = "99999999-aaaa-aaaa-aaaa-aaaaaaaaaaaa";const THREAD_Z: &str = "44444444-aaaa-aaaa-aaaa-aaaaaaaaaaaa";const THREAD_S: &str = "44444444-5555-5555-5555-555555555555";const LINK_1: &str = "55555555-aaaa-aaaa-aaaa-aaaaaaaaaaaa";+const PROJECT_1: &str = "66666666-aaaa-aaaa-aaaa-aaaaaaaaaaaa";+const COMPANY_1: &str = "88888888-0000-0000-0000-000000000001";+const CONTACT_1: &str = "88888888-1111-0000-0000-000000000001";+const CONTACT_3: &str = "88888888-1111-0000-0000-000000000003";+const DISCUSSION_TYPES: &[EntityType] = &[+ EntityType::Initiative,+ EntityType::CrmCompany,+ EntityType::CrmContact,+];++/// Admit own work, as Home's work feed does.+const WORK: bool = true;+/// Attention only.+const ATTENTION: bool = false;const EVERYTHING: NotifiedHydratableTypes = NotifiedHydratableTypes {channels: true,@@ -47,32 +61,34 @@ const ALL_TYPES: &[EntityType] = &[];fn req<'a>(- mode: WorkFeedSoupMode,+ own_work: bool,link_ids: &'a [Uuid],sources: &'a [SourceId],-) -> WorkFeedCandidateRequest<'a> {- WorkFeedCandidateRequest {+) -> AttentionCandidateRequest<'a> {+ AttentionCandidateRequest {user_id: MacroUserIdStr::parse_from_str(USER_1).unwrap(),limit: 50,- mode,+ own_work,+ keying: AttentionKeying::ThreadScoped,after: None,types: ALL_TYPES,filter: None,link_ids,foreign_entity_sources: sources,hydratable: EVERYTHING,+ crm: false,only: None,}}-fn keys(page: &[WorkFeedCandidate]) -> Vec<(EntityType, String)> {+fn keys(page: &[AttentionCandidate]) -> Vec<(EntityType, String)> {page.iter().map(|c| (c.entity.entity_type, c.entity.entity_id.to_string())).collect()}/// `(sort, attention, touched)` minutes past 10:00 per candidate.-fn minutes(page: &[WorkFeedCandidate]) -> Vec<(u32, Option<u32>, Option<u32>)> {+fn minutes(page: &[AttentionCandidate]) -> Vec<(u32, Option<u32>, Option<u32>)> {page.iter().map(|c| {(@@ -112,7 +128,7 @@ fn work_feed_order() -> Vec<(EntityType, String)> {async fn work_mode_merges_attention_and_own_work(pool: Pool<Postgres>) -> anyhow::Result<()> {let link_ids = [Uuid::parse_str(LINK_1)?];let sources = sources();- let page = work_feed_soup_page(&pool, req(WorkFeedSoupMode::Work, &link_ids, &sources)).await?;+ let page = attention_soup_page(&pool, req(WORK, &link_ids, &sources)).await?;assert_eq!(keys(&page), work_feed_order());assert_eq!(@@ -152,8 +168,7 @@ async fn work_mode_merges_attention_and_own_work(pool: Pool<Postgres>) -> anyhowasync fn attention_mode_ignores_own_work(pool: Pool<Postgres>) -> anyhow::Result<()> {let link_ids = [Uuid::parse_str(LINK_1)?];let sources = sources();- let page =- work_feed_soup_page(&pool, req(WorkFeedSoupMode::Attention, &link_ids, &sources)).await?;+ let page = attention_soup_page(&pool, req(ATTENTION, &link_ids, &sources)).await?;assert_eq!(keys(&page),@@ -186,17 +201,17 @@ async fn keyset_paginates_across_both_streams(pool: Pool<Postgres>) -> anyhow::Rlet mut all = Vec::new();let mut after = None;loop {- let mut request = req(WorkFeedSoupMode::Work, &link_ids, &sources);+ let mut request = req(WORK, &link_ids, &sources);request.limit = 3;request.after = after;- let page = work_feed_soup_page(&pool, request).await?;+ let page = attention_soup_page(&pool, request).await?;let full = page.len() == 3;all.extend(page);if !full {break;}let last = all.last().unwrap();- after = Some(WorkFeedPagePosition {+ after = Some(AttentionPagePosition {sort_at: last.sort_at,entity_id: last.entity.entity_id.to_string(),});@@ -204,8 +219,7 @@ async fn keyset_paginates_across_both_streams(pool: Pool<Postgres>) -> anyhow::R// Pages of three — including a boundary inside the doc-B/doc-G tie —// yield the same feed as one page: nothing repeats and nothing is lost.- let one_page =- work_feed_soup_page(&pool, req(WorkFeedSoupMode::Work, &link_ids, &sources)).await?;+ let one_page = attention_soup_page(&pool, req(WORK, &link_ids, &sources)).await?;assert_eq!(keys(&all), keys(&one_page));assert_eq!(all.len(), 11);@@ -224,9 +238,9 @@ async fn every_page_size_matches_the_whole_feed(pool: Pool<Postgres>) -> anyhow:// A full page of own work bounds how far back attention is read; each// smaller page must still be the head of the whole feed.for limit in 1..=whole.len() {- let mut request = req(WorkFeedSoupMode::Work, &link_ids, &sources);+ let mut request = req(WORK, &link_ids, &sources);request.limit = u16::try_from(limit)?;- let page = work_feed_soup_page(&pool, request).await?;+ let page = attention_soup_page(&pool, request).await?;assert_eq!(keys(&page), whole[..limit], "limit {limit}");}@@ -246,9 +260,9 @@ async fn only_restricts_to_known_items(pool: Pool<Postgres>) -> anyhow::Result<(EntityType::Document.with_entity_string(DOC_F.to_string()),EntityType::ChannelMessage.with_entity_string(THREAD_M.to_string()),];- let mut request = req(WorkFeedSoupMode::Work, &link_ids, &sources);+ let mut request = req(WORK, &link_ids, &sources);request.only = Some(&only);- let page = work_feed_soup_page(&pool, request).await?;+ let page = attention_soup_page(&pool, request).await?;assert_eq!(keys(&page),@@ -268,9 +282,9 @@ async fn only_restricts_to_known_items(pool: Pool<Postgres>) -> anyhow::Result<(async fn types_narrow_both_streams(pool: Pool<Postgres>) -> anyhow::Result<()> {let link_ids = [Uuid::parse_str(LINK_1)?];let sources = sources();- let mut request = req(WorkFeedSoupMode::Work, &link_ids, &sources);+ let mut request = req(WORK, &link_ids, &sources);request.types = &[EntityType::EmailThread, EntityType::Chat];- let page = work_feed_soup_page(&pool, request).await?;+ let page = attention_soup_page(&pool, request).await?;assert_eq!(keys(&page),@@ -303,10 +317,10 @@ async fn task_subtype_narrows_documents_in_both_streams(..Default::default()};- let mut request = req(WorkFeedSoupMode::Work, &link_ids, &sources);+ let mut request = req(WORK, &link_ids, &sources);request.types = &[EntityType::Document];request.filter = Some(&tasks);- let page = work_feed_soup_page(&pool, request).await?;+ let page = attention_soup_page(&pool, request).await?;assert_eq!(keys(&page),vec![@@ -315,10 +329,10 @@ async fn task_subtype_narrows_documents_in_both_streams(]);- let mut request = req(WorkFeedSoupMode::Work, &link_ids, &sources);+ let mut request = req(WORK, &link_ids, &sources);request.types = &[EntityType::Document];request.filter = Some(&documents);- let page = work_feed_soup_page(&pool, request).await?;+ let page = attention_soup_page(&pool, request).await?;assert_eq!(keys(&page),vec![@@ -331,3 +345,135 @@ async fn task_subtype_narrows_documents_in_both_streams(Ok(())}++#[sqlx::test(+ fixtures(+ path = "../../../../fixtures",+ scripts("work_feed", "attention_discussions")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn discussions_on_visible_projects_and_crm_records_are_candidates(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_ids = [Uuid::parse_str(LINK_1)?];+ let sources = sources();+ let filter = EntityFilterAst {+ initiative_filter: Some(std::sync::Arc::new(filter_ast::Expr::val(+ item_filters::ast::initiative::InitiativeLiteral::Include,+ ))),+ ..Default::default()+ };+ let mut request = req(ATTENTION, &link_ids, &sources);+ request.types = DISCUSSION_TYPES;+ request.filter = Some(&filter);+ request.crm = true;+ let page = attention_soup_page(&pool, request).await?;++ // Hidden company-2 with its contact-4, hidden contact-2 and company-3 on+ // another team stay out; company-less contact-3 is in.+ assert_eq!(+ keys(&page),+ vec![+ (EntityType::CrmContact, CONTACT_3.to_string()),+ (EntityType::Initiative, PROJECT_1.to_string()),+ (EntityType::CrmContact, CONTACT_1.to_string()),+ (EntityType::CrmCompany, COMPANY_1.to_string()),+ ]+ );++ // Without a CRM receipt to hydrate them, CRM records are not candidates.+ let mut request = req(ATTENTION, &link_ids, &sources);+ request.types = DISCUSSION_TYPES;+ request.filter = Some(&filter);+ let page = attention_soup_page(&pool, request).await?;+ assert_eq!(+ keys(&page),+ vec![(EntityType::Initiative, PROJECT_1.to_string())]+ );++ Ok(())+}++const CHANNEL_Y: &str = "33333333-bbbb-bbbb-bbbb-bbbbbbbbbbbb";+const ROOT_R1: &str = "99999999-1111-1111-1111-111111111111";+const ROOT_R2: &str = "99999999-2222-2222-2222-222222222222";+const ROOT_R3: &str = "99999999-3333-3333-3333-333333333333";+const CHANNEL_TYPES: &[EntityType] = &[EntityType::Channel, EntityType::ChannelMessage];++#[sqlx::test(+ fixtures(+ path = "../../../../fixtures",+ scripts("work_feed", "attention_channel_keying")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn thread_scoped_keying_places_channel_notifications_on_their_threads(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_ids = [Uuid::parse_str(LINK_1)?];+ let sources = sources();+ let mut request = req(ATTENTION, &link_ids, &sources);+ request.types = CHANNEL_TYPES;+ let page = attention_soup_page(&pool, request).await?;++ assert_eq!(+ keys(&page),+ vec![+ (EntityType::ChannelMessage, ROOT_R3.to_string()),+ (EntityType::ChannelMessage, ROOT_R2.to_string()),+ (EntityType::ChannelMessage, ROOT_R1.to_string()),+ (EntityType::ChannelMessage, THREAD_M.to_string()),+ ]+ );++ Ok(())+}++#[sqlx::test(+ fixtures(+ path = "../../../../fixtures",+ scripts("work_feed", "attention_channel_keying")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn filed_entity_keying_places_a_channel_and_its_threads_together(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_ids = [Uuid::parse_str(LINK_1)?];+ let sources = sources();+ let mut request = req(ATTENTION, &link_ids, &sources);+ request.keying = AttentionKeying::FiledEntity;+ request.types = CHANNEL_TYPES;+ let page = attention_soup_page(&pool, request).await?;++ // Channel-Y's three notifications place it once, at the newest (T32);+ // channel-X carries the thread-M mention (T1).+ assert_eq!(+ keys(&page),+ vec![+ (EntityType::Channel, CHANNEL_Y.to_string()),+ (EntityType::Channel, CHANNEL_X.to_string()),+ ]+ );+ assert_eq!(+ minutes(&page),+ vec![(32, Some(32), None), (1, Some(1), None)]+ );++ // Recomputing a thread finds nothing: no notification keys to it.+ let only: Vec<Entity<'static>> = vec![+ EntityType::Channel.with_entity_string(CHANNEL_Y.to_string()),+ EntityType::ChannelMessage.with_entity_string(ROOT_R2.to_string()),+ ];+ let mut request = req(ATTENTION, &link_ids, &sources);+ request.keying = AttentionKeying::FiledEntity;+ request.only = Some(&only);+ let page = attention_soup_page(&pool, request).await?;+ assert_eq!(+ keys(&page),+ vec![(EntityType::Channel, CHANNEL_Y.to_string())]+ );++ Ok(())+}diff --git a/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs b/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rsindex 40ec3cdd04..8f9e831216 100644--- a/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs+++ b/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs@@ -1,24 +1,26 @@use super::*;-use crate::domain::models::{WorkFeedCandidateRequest, WorkFeedSoupMode};-use crate::outbound::pg_soup_repo::work_feed::work_feed_soup_page;+use crate::domain::models::{AttentionCandidateRequest, AttentionKeying};+use crate::outbound::pg_soup_repo::attention::attention_soup_page;use item_filters::ast::agent_session::AgentSessionVisibility;fn work_request<'a>(filter: &'a EntityFilterAst,sources: &'a [SourceId],- mode: WorkFeedSoupMode,+ own_work: bool,only: Option<&'a [model_entity::Entity<'static>]>,-) -> WorkFeedCandidateRequest<'a> {- WorkFeedCandidateRequest {+) -> AttentionCandidateRequest<'a> {+ AttentionCandidateRequest {user_id: MacroUserIdStr::parse_from_str(USER_1).unwrap(),limit: 50,- mode,+ own_work,+ keying: AttentionKeying::ThreadScoped,after: None,types: &[EntityType::AgentSession],filter: Some(filter),link_ids: &[],foreign_entity_sources: sources,hydratable: EVERYTHING,+ crm: false,only,}}@@ -40,11 +42,7 @@ async fn hidden_contexts_with_notifications_and_activity_stay_out_of_broad_feeds"INSERT INTO activity_events (id, actor_id, subject_id, action, entity_type, entity_id, occurred_at) VALUES ($1, $2, $2, 'edited', 'agent_session', $3, '2024-06-01 10:22:00+00')",Uuid::now_v7(), USER_1, mine.to_string(),).execute(&pool).await?;- let before = work_feed_soup_page(- &pool,- work_request(&include, &sources, WorkFeedSoupMode::Work, None),- )- .await?;+ let before = attention_soup_page(&pool, work_request(&include, &sources, true, None)).await?;assert_eq!(before.len(), 1);assert!(before[0].attention_at.is_some() && before[0].touched_at.is_some());sqlx::query!(@@ -56,21 +54,18 @@ async fn hidden_contexts_with_notifications_and_activity_stay_out_of_broad_feedslet notified =notified_soup_page(&pool, req(Some(&include), &[], &sources, EVERYTHING)).await?;assert!(!keys(¬ified).contains(&(EntityType::AgentSession, mine.to_string())));- for mode in [WorkFeedSoupMode::Work, WorkFeedSoupMode::Attention] {+ for mode in [true, false] {assert!(- work_feed_soup_page(&pool, work_request(&include, &sources, mode, None))+ attention_soup_page(&pool, work_request(&include, &sources, mode, None)).await?.is_empty());}let only = [EntityType::AgentSession.with_entity_string(mine.to_string())];assert!(- work_feed_soup_page(- &pool,- work_request(&include, &sources, WorkFeedSoupMode::Work, Some(&only))- )- .await?- .is_empty(),+ attention_soup_page(&pool, work_request(&include, &sources, true, Some(&only)))+ .await?+ .is_empty(),"internal by-ID recomputation does not reopen broad-list visibility");let named = EntityFilterAst {@@ -78,12 +73,9 @@ async fn hidden_contexts_with_notifications_and_activity_stay_out_of_broad_feeds..Default::default()};assert_eq!(- work_feed_soup_page(- &pool,- work_request(&named, &sources, WorkFeedSoupMode::Work, None)- )- .await?- .len(),+ attention_soup_page(&pool, work_request(&named, &sources, true, None))+ .await?+ .len(),1);let notified = notified_soup_page(&pool, req(Some(&named), &[], &sources, EVERYTHING)).await?;@@ -97,12 +89,9 @@ async fn hidden_contexts_with_notifications_and_activity_stay_out_of_broad_feeds..Default::default()};assert_eq!(- work_feed_soup_page(- &pool,- work_request(&favorite, &sources, WorkFeedSoupMode::Work, None)- )- .await?- .len(),+ attention_soup_page(&pool, work_request(&favorite, &sources, true, None))+ .await?+ .len(),1);let excluded = EntityFilterAst {@@ -115,12 +104,9 @@ async fn hidden_contexts_with_notifications_and_activity_stay_out_of_broad_feeds..Default::default()};assert!(- work_feed_soup_page(- &pool,- work_request(&excluded, &sources, WorkFeedSoupMode::Work, None)- )- .await?- .is_empty()+ attention_soup_page(&pool, work_request(&excluded, &sources, true, None))+ .await?+ .is_empty());Ok(())}@@ -156,17 +142,14 @@ async fn unlisted_runs_with_notifications_stay_out_of_feeds_that_exclude_them(..Default::default()};assert_eq!(- work_feed_soup_page(- &pool,- work_request(&include, &sources, WorkFeedSoupMode::Attention, None)- )- .await?- .len(),+ attention_soup_page(&pool, work_request(&include, &sources, false, None))+ .await?+ .len(),1);- for mode in [WorkFeedSoupMode::Work, WorkFeedSoupMode::Attention] {+ for mode in [true, false] {assert!(- work_feed_soup_page(&pool, work_request(&without_runs, &sources, mode, None))+ attention_soup_page(&pool, work_request(&without_runs, &sources, mode, None)).await?.is_empty());@@ -210,12 +193,9 @@ async fn followed_hidden_sessions_return_to_broad_feeds(notified_soup_page(&pool, req(Some(&include), &[], &sources, EVERYTHING)).await?;assert!(keys(¬ified).contains(&(EntityType::AgentSession, mine.to_string())));assert_eq!(- work_feed_soup_page(- &pool,- work_request(&include, &sources, WorkFeedSoupMode::Attention, None)- )- .await?- .len(),+ attention_soup_page(&pool, work_request(&include, &sources, false, None))+ .await?+ .len(),1);Ok(())diff --git a/crates/soup_realtime/AGENTS.md b/crates/soup_realtime/AGENTS.mdindex d320558bbd..8ea8c4f8e2 100644--- a/crates/soup_realtime/AGENTS.md+++ b/crates/soup_realtime/AGENTS.md@@ -35,7 +35,7 @@ tasks itself.`call`, `github_pull_requests`, `initiative`, `properties`, `projects`,`system_properties`, `rdkafka` (`consumer`), `agent_session`/`entity_access`(`outbound`).-- Used by: `complete_graph`, `graphql_soup`, `work_feed`.+- Used by: `complete_graph`, `graphql_soup`, `attention_feed`.## Recipesdiff --git a/crates/work_feed/AGENTS.md b/crates/work_feed/AGENTS.mdindex 462802f34f..de6ecc8314 100644--- a/crates/work_feed/AGENTS.md+++ b/crates/work_feed/AGENTS.md@@ -4,34 +4,33 @@Part of Home — the combined work feed: one paginated, stacked, live-updatinglist of things that need the viewer's attention plus work they recently did.+Built on the shared feed layer, `crates/attention_feed`.## Start here-- `src/domain/service.rs`: page, recompute, done/undo use cases.+- `src/domain/service.rs`: page, recompute, done/undo use cases; builds Home's+ items from the shared reader's loaded candidates.- `src/domain/policy.rs`: item membership policy — what belongs in the feed.- `src/domain/stacking.rs`: how related notifications collapse into one entry.-- `src/domain/realtime.rs`: live-update signals.-- `src/outbound/source.rs`: adapters over Soup, notifications, email, and- activity that supply the underlying items.## Scope-- Owns: feed membership, stacking, seen/done state, and pagination.-- Not here: the underlying item data itself (notifications, soup rows,- activity) → `crates/notification`, `crates/soup`, `crates/activity`.+- Owns: Home's items, membership policy, stacking, primary reason and state.+- Not here: paging, refill, notification loading, done/undo plumbing, live+ batching and the adapters → `crates/attention_feed`; candidate SQL →+ `crates/soup`.## Boundaries-- Depends on: `entity_access`, `filter_ast`, `item_filters`, `notification`,- `model_notifications`; optional `activity`, `email`, `soup`, `soup_realtime`,- `models_soup` (feature `outbound`).+- Depends on: `attention_feed`, `filter_ast`, `item_filters`,+ `model_notifications`.- Used by: `services/document_storage_service`, `crates/graphql_work_feed`,`crates/complete_graph`.## Recipes-- Add a new feed item source: implement a port in `src/domain/ports.rs` → new- adapter in `src/outbound/` → wire into `src/domain/policy.rs`.+- Change what Home lists: `src/domain/policy.rs` (filter and candidate types);+ a new candidate kind also needs Soup's `attention.rs` gates and hydration.## Checksdiff --git a/crates/work_feed/Cargo.toml b/crates/work_feed/Cargo.tomlindex 96ec3bcc6c..df942509bc 100644--- a/crates/work_feed/Cargo.toml+++ b/crates/work_feed/Cargo.toml@@ -4,43 +4,23 @@ name = "work_feed"publish = falseversion = "0.1.0"-[features]-default = []-# Adapters over the services that own the feed's data.-outbound = [- "dep:activity",- "dep:email",- "dep:soup",- "dep:soup_realtime",- "dep:models_soup",-]-[dependencies]-activity = { path = "../activity", default-features = false, features = ["realtime"], optional = true }-base64 = { workspace = true }+attention_feed = { path = "../attention_feed" }chrono = { workspace = true, features = ["serde"] }-cowlike = { path = "../cowlike" }document_sub_type = { path = "../document_sub_type" }-email = { path = "../email", default-features = false, features = ["ports"], optional = true }-entity_access = { path = "../entity_access", default-features = false, features = ["ports"] }filter_ast = { path = "../filter_ast" }-futures = { workspace = true }item_filters = { path = "../item_filters" }macro_user_id = { path = "../macro_user_id" }model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }-models_soup = { path = "../models_soup", optional = true }-notification = { path = "../notification" }rootcause = { workspace = true }serde = { workspace = true }-serde_json = { workspace = true }-soup = { path = "../soup", default-features = false, features = ["ports"], optional = true }-soup_realtime = { path = "../soup_realtime", default-features = false, features = ["ports"], optional = true }-thiserror = { workspace = true }-tokio = { workspace = true, features = ["sync", "time", "macros", "rt"] }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/work_feed/src/domain.rs b/crates/work_feed/src/domain.rsindex baba2fa569..e12e33cd03 100644--- a/crates/work_feed/src/domain.rs+++ b/crates/work_feed/src/domain.rs@@ -1,12 +1,6 @@-//! Work feed domain: models, ports, policy, stacking and the service.+//! Work feed domain: models, policy, stacking and the service.pub mod models;pub mod policy;-pub mod ports;-pub mod realtime;pub mod service;pub mod stacking;--/// Notification fixtures shared by the domain tests.-#[cfg(test)]-pub(crate) mod test_support;diff --git a/crates/work_feed/src/domain/models.rs b/crates/work_feed/src/domain/models.rsindex eea4c8e8f8..83389ed435 100644--- a/crates/work_feed/src/domain/models.rs+++ b/crates/work_feed/src/domain/models.rs@@ -1,33 +1,16 @@-//! Work feed domain models.+//! Work feed domain models: Home's items, stacks and scopes. Keys, tokens,+//! viewers and errors are the shared feed layer's (`attention_feed`).-use std::{str::FromStr, sync::Arc};--use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};+use attention_feed::domain::models::{+ DoneReceipt, FeedKey, FeedNotification, FeedPosition, FeedRevision, counts_as_unseen,+};use chrono::{DateTime, Utc};-use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::{Entity, EntityType};-use model_notifications::NotifEvent;-use notification::domain::models::UserNotificationRow;+use model_entity::EntityType;use serde::{Deserialize, Serialize};-use uuid::Uuid;#[cfg(test)]mod test;-/// A notification row as the work feed reads it.-pub type FeedNotification = Arc<UserNotificationRow<NotifEvent>>;--/// The caller a work feed request is evaluated for.-#[derive(Debug, Clone)]-pub struct WorkFeedViewer {- /// The authenticated user.- pub user: MacroUserIdStr<'static>,- /// The user's team membership, when they have one; foreign entities- /// stored for the team are visible through it.- pub team: Option<EntityAccessReceipt<MemberTeamRole>>,-}-/// Which reasons admit an item to the feed.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum WorkFeedMode {@@ -37,6 +20,13 @@ pub enum WorkFeedMode {Attention,}+impl WorkFeedMode {+ /// Whether the viewer's own work admits items.+ pub fn own_work(self) -> bool {+ self == Self::Work+ }+}+/// The kinds of item a caller can narrow the feed to.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum WorkFeedItemType {@@ -97,49 +87,6 @@ impl WorkFeedItemType {}}-/// Stable per-viewer identity of a work feed item: the entity its candidate-/// is keyed on. A channel thread is keyed on its root message, so it stays-/// one item as replies arrive and whether or not its channel is also listed.-#[derive(Debug, Clone, PartialEq, Eq, Hash)]-pub struct WorkFeedItemKey(Entity<'static>);--/// A work feed item id that does not name an item.-#[derive(Debug, thiserror::Error)]-#[error("invalid work feed item id")]-pub struct InvalidWorkFeedItemId;--impl WorkFeedItemKey {- /// The item keyed on `entity`.- pub fn new(entity: Entity<'static>) -> Self {- Self(entity)- }-- /// The entity the item is keyed on.- pub fn entity(&self) -> &Entity<'static> {- &self.0- }-- /// Consume the key, returning its entity.- pub fn into_entity(self) -> Entity<'static> {- self.0- }-- /// The item's global id: `<entity type>:<entity id>`.- pub fn id(&self) -> String {- format!("{}:{}", self.0.entity_type, self.0.entity_id)- }-- /// Parse an id produced by [`Self::id`].- pub fn parse(id: &str) -> Result<Self, InvalidWorkFeedItemId> {- let (entity_type, entity_id) = id.split_once(':').ok_or(InvalidWorkFeedItemId)?;- if entity_id.is_empty() {- return Err(InvalidWorkFeedItemId);- }- let entity_type = EntityType::from_str(entity_type).map_err(|_| InvalidWorkFeedItemId)?;- Ok(Self(entity_type.with_entity_string(entity_id.to_string())))- }-}-/// An item's state for its viewer, aggregated over its active reasons.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum WorkFeedItemState {@@ -202,26 +149,6 @@ impl WorkFeedStack {}}-/// Whether a notification makes its item unseen. Channel events other than-/// messages, mentions and reactions (invites, calls) never do.-pub fn counts_as_unseen(notification: &UserNotificationRow<NotifEvent>) -> bool {- use notification::domain::models::NotificationState;- if notification.state != NotificationState::Unseen {- return false;- }- if notification.entity.entity_type != EntityType::Channel {- return true;- }- matches!(- notification.notification_metadata,- NotifEvent::ChannelMention(_)- | NotifEvent::ChannelMessageSend(_)- | NotifEvent::ChannelMessageReaction(_)- | NotifEvent::ChannelMessageReply(_)- | NotifEvent::DocumentMention(_)- )-}-/// Why an item is presented the way it is, chosen with its click target.#[derive(Debug, Clone, PartialEq, Eq)]pub enum WorkFeedPrimaryReason {@@ -235,37 +162,13 @@ pub enum WorkFeedPrimaryReason {},}-/// The attention a viewer observed on an item. Done acknowledges only what-/// was observed, so a notification arriving later keeps the item active.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]-pub struct WorkFeedRevision {- /// The newest active notification observed.- #[serde(rename = "a", default, skip_serializing_if = "Option::is_none")]- pub attention_through: Option<DateTime<Utc>>,-}--/// A revision token that does not decode.-#[derive(Debug, thiserror::Error)]-#[error("invalid work feed revision")]-pub struct InvalidWorkFeedRevision;--impl WorkFeedRevision {- /// The opaque token clients echo back.- pub fn encode(&self) -> String {- encode_token(self)- }-- /// Decode a token produced by [`Self::encode`].- pub fn decode(token: &str) -> Result<Self, InvalidWorkFeedRevision> {- decode_token(token).ok_or(InvalidWorkFeedRevision)- }-}--/// One item of the feed for its viewer.+/// One item of the feed for its viewer. A channel thread is keyed on its+/// root message, so it stays one item as replies arrive and whether or not+/// its channel is also listed.#[derive(Debug, Clone)]pub struct WorkFeedItem<E> {/// The item's identity.- pub key: WorkFeedItemKey,+ pub key: FeedKey,/// The hydrated entity the item is about.pub entity: E,/// The item's aggregate state.@@ -285,8 +188,8 @@ pub struct WorkFeedItem<E> {impl<E> WorkFeedItem<E> {/// The attention this item currently carries.- pub fn revision(&self) -> WorkFeedRevision {- WorkFeedRevision {+ pub fn revision(&self) -> FeedRevision {+ FeedRevision {attention_through: self.attention_at,}}@@ -301,34 +204,6 @@ pub struct WorkFeedEntry<E> {pub sort_at: DateTime<Utc>,}-/// Where the next page of a feed starts.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-pub struct WorkFeedPosition {- /// The last walked candidate's sort time.- #[serde(rename = "s")]- pub sort_at: DateTime<Utc>,- /// The last walked candidate's entity id.- #[serde(rename = "i")]- pub entity_id: String,-}--/// A cursor that does not decode.-#[derive(Debug, thiserror::Error)]-#[error("invalid work feed cursor")]-pub struct InvalidWorkFeedCursor;--impl WorkFeedPosition {- /// The opaque cursor clients send back for the next page.- pub fn encode(&self) -> String {- encode_token(self)- }-- /// Decode a cursor produced by [`Self::encode`].- pub fn decode(cursor: &str) -> Result<Self, InvalidWorkFeedCursor> {- decode_token(cursor).ok_or(InvalidWorkFeedCursor)- }-}-/// Which items one feed shows.#[derive(Debug, Clone, PartialEq, Eq)]pub struct WorkFeedScope {@@ -363,7 +238,7 @@ pub struct WorkFeedQuery {/// Maximum items on the page.pub limit: u16,/// Resume after this position; `None` for the first page.- pub after: Option<WorkFeedPosition>,+ pub after: Option<FeedPosition>,}/// One page of the feed, newest first.@@ -372,7 +247,7 @@ pub struct WorkFeedPage<E> {/// The page's entries.pub entries: Vec<WorkFeedEntry<E>>,/// Where the next page starts; `None` once the feed is exhausted.- pub next: Option<WorkFeedPosition>,+ pub next: Option<FeedPosition>,}/// How a known item changed for one feed.@@ -382,56 +257,16 @@ pub enum WorkFeedChange<E> {Upserted(WorkFeedEntry<E>),/// The item no longer belongs in the feed. The entity itself may still/// exist: done, filtered out and inaccessible items all leave this way.- Removed(WorkFeedItemKey),+ Removed(FeedKey),}/// An item the caller asked to mark done, with the reasons they observed.#[derive(Debug, Clone)]pub struct WorkFeedDoneTarget {/// The item.- pub key: WorkFeedItemKey,+ pub key: FeedKey,/// What the caller observed; `None` acknowledges everything current.- pub revision: Option<WorkFeedRevision>,-}--/// Everything one mark-done operation changed, so undo can reverse exactly-/// those effects and nothing that happened since.-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]-pub struct WorkFeedDoneReceipt {- /// The items the operation completed.- #[serde(rename = "k")]- pub items: Vec<String>,- /// Notifications this operation moved to done.- #[serde(rename = "n", default)]- pub notification_ids: Vec<Uuid>,- /// Email threads this operation archived.- #[serde(rename = "e", default)]- pub archived_threads: Vec<Uuid>,-}--/// An undo token that does not decode.-#[derive(Debug, thiserror::Error)]-#[error("invalid work feed undo token")]-pub struct InvalidWorkFeedUndoToken;--impl WorkFeedDoneReceipt {- /// The opaque undo token returned to the caller.- pub fn encode(&self) -> String {- encode_token(self)- }-- /// Decode a token produced by [`Self::encode`].- pub fn decode(token: &str) -> Result<Self, InvalidWorkFeedUndoToken> {- decode_token(token).ok_or(InvalidWorkFeedUndoToken)- }-- /// The keys of the items this receipt completed.- pub fn item_keys(&self) -> Vec<WorkFeedItemKey> {- self.items- .iter()- .filter_map(|id| WorkFeedItemKey::parse(id).ok())- .collect()- }+ pub revision: Option<FeedRevision>,}/// The outcome of marking items done.@@ -439,67 +274,7 @@ impl WorkFeedDoneReceipt {pub struct WorkFeedDoneOutcome {/// The items now done; requested items that were already gone are/// reported done as well, so callers can drop them.- pub items: Vec<WorkFeedItemKey>,+ pub items: Vec<FeedKey>,/// What the operation changed, for undo.- pub receipt: WorkFeedDoneReceipt,-}--/// A change that may affect one viewer's items, from any realtime source.-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum WorkFeedTrigger {- /// These candidate keys may have changed.- Changed(Vec<Entity<'static>>),- /// Changes may have been missed; mounted feeds must refetch.- Invalidated,-}--/// Errors returned by the work feed service.-#[derive(Debug, thiserror::Error)]-pub enum WorkFeedError {- /// The caller sent an invalid cursor, revision, item id or undo token.- #[error("{0}")]- InvalidInput(&'static str),- /// A dependency failed.- #[error("the work feed is unavailable: {0}")]- Unavailable(rootcause::Report),-}--impl From<rootcause::Report> for WorkFeedError {- fn from(report: rootcause::Report) -> Self {- Self::Unavailable(report)- }-}--impl From<InvalidWorkFeedCursor> for WorkFeedError {- fn from(_: InvalidWorkFeedCursor) -> Self {- Self::InvalidInput("invalid work feed cursor")- }-}--impl From<InvalidWorkFeedRevision> for WorkFeedError {- fn from(_: InvalidWorkFeedRevision) -> Self {- Self::InvalidInput("invalid work feed revision")- }-}--impl From<InvalidWorkFeedItemId> for WorkFeedError {- fn from(_: InvalidWorkFeedItemId) -> Self {- Self::InvalidInput("invalid work feed item id")- }-}--impl From<InvalidWorkFeedUndoToken> for WorkFeedError {- fn from(_: InvalidWorkFeedUndoToken) -> Self {- Self::InvalidInput("invalid work feed undo token")- }-}--fn encode_token<T: Serialize>(value: &T) -> String {- let json = serde_json::to_vec(value).expect("work feed tokens serialize");- URL_SAFE_NO_PAD.encode(json)-}--fn decode_token<T: for<'de> Deserialize<'de>>(token: &str) -> Option<T> {- let json = URL_SAFE_NO_PAD.decode(token).ok()?;- serde_json::from_slice(&json).ok()+ pub receipt: DoneReceipt,}diff --git a/crates/work_feed/src/domain/models/test.rs b/crates/work_feed/src/domain/models/test.rsindex 98a6d8d55d..626fc6fea5 100644--- a/crates/work_feed/src/domain/models/test.rs+++ b/crates/work_feed/src/domain/models/test.rs@@ -1,55 +1,7 @@use super::*;-use crate::domain::test_support::{at, uuid};#[test]-fn item_ids_round_trip() {- let key =- WorkFeedItemKey::new(EntityType::ChannelMessage.with_entity_string(uuid(7).to_string()));- let id = key.id();- assert_eq!(id, format!("channel_message:{}", uuid(7)));- assert_eq!(WorkFeedItemKey::parse(&id).unwrap(), key);-}--#[test]-fn malformed_item_ids_are_rejected() {- for id in ["", "document", "document:", "not_a_type:abc"] {- assert!(WorkFeedItemKey::parse(id).is_err(), "{id} parsed");- }-}--#[test]-fn tokens_round_trip() {- let revision = WorkFeedRevision {- attention_through: Some(at(5)),- };- assert_eq!(- WorkFeedRevision::decode(&revision.encode()).unwrap(),- revision- );-- let position = WorkFeedPosition {- sort_at: at(9),- entity_id: uuid(3).to_string(),- };- assert_eq!(- WorkFeedPosition::decode(&position.encode()).unwrap(),- position- );-- let receipt = WorkFeedDoneReceipt {- items: vec![format!("document:{}", uuid(1))],- notification_ids: vec![uuid(2)],- archived_threads: vec![uuid(3)],- };- assert_eq!(- WorkFeedDoneReceipt::decode(&receipt.encode()).unwrap(),- receipt- );-}--#[test]-fn garbage_tokens_are_rejected() {- assert!(WorkFeedRevision::decode("not base64!").is_err());- assert!(WorkFeedPosition::decode("e30").is_err());- assert!(WorkFeedDoneReceipt::decode("").is_err());+fn work_mode_alone_admits_own_work() {+ assert!(WorkFeedMode::Work.own_work());+ assert!(!WorkFeedMode::Attention.own_work());}diff --git a/crates/work_feed/src/domain/policy/test.rs b/crates/work_feed/src/domain/policy/test.rsindex 581ef76e88..a3ae53ce41 100644--- a/crates/work_feed/src/domain/policy/test.rs+++ b/crates/work_feed/src/domain/policy/test.rs@@ -1,5 +1,7 @@+use attention_feed::test_support::viewer_id;+use super::*;-use crate::domain::{models::WorkFeedMode, test_support::viewer_id};+use crate::domain::models::WorkFeedMode;#[test]fn no_types_means_every_type() {diff --git a/crates/work_feed/src/domain/ports.rs b/crates/work_feed/src/domain/ports.rsdeleted file mode 100644index 22d93904e7..0000000000--- a/crates/work_feed/src/domain/ports.rs+++ /dev/null@@ -1,141 +0,0 @@-//! Capabilities the work feed needs from the domains that own its data.--use std::collections::HashMap;--use chrono::{DateTime, Utc};-use item_filters::ast::EntityFilterAst;-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::{Entity, EntityType};-use rootcause::Report;-use uuid::Uuid;--use super::models::{- FeedNotification, WorkFeedMode, WorkFeedPosition, WorkFeedTrigger, WorkFeedViewer,-};--/// Facts about a candidate's entity that scoping and state depend on.-#[derive(Debug, Clone, Default, PartialEq, Eq)]-pub struct EntityFacts {- /// For a channel thread, the channel whose notifications it shares.- pub thread_channel: Option<Uuid>,- /// For an email thread, its mailbox state.- pub mail: Option<MailFacts>,-}--/// An email thread's mailbox state.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub struct MailFacts {- /// The thread is in the inbox (not archived).- pub inbox_visible: bool,- /// The thread has no unread mail.- pub is_read: bool,-}--/// A request for one page of hydrated candidates.-#[derive(Debug, Clone)]-pub struct SourceRequest {- /// Who the feed is for.- pub viewer: WorkFeedViewer,- /// Which reasons admit candidates.- pub mode: WorkFeedMode,- /// Candidate entity types to include.- pub types: Vec<EntityType>,- /// The membership policy filter.- pub filter: EntityFilterAst,- /// Maximum candidates to return.- pub limit: u16,- /// Resume after this position; `None` for the first page.- pub after: Option<WorkFeedPosition>,- /// Restrict to these candidate keys, for recomputing known items.- pub only: Option<Vec<Entity<'static>>>,-}--/// One hydrated, authorized candidate.-#[derive(Debug, Clone)]-pub struct SourceItem<E> {- /// The candidate key.- pub key: Entity<'static>,- /// The hydrated entity.- pub entity: E,- /// Facts used for scoping and state.- pub facts: EntityFacts,- /// The candidate's live attention time, when it has any.- pub attention_at: Option<DateTime<Utc>>,- /// The viewer's own-work time, when it has any.- pub touched_at: Option<DateTime<Utc>>,- /// Where the candidate sits in the feed.- pub sort_at: DateTime<Utc>,-}--/// One page of hydrated candidates.-#[derive(Debug)]-pub struct SourcePage<E> {- /// The page's candidates, newest first.- pub items: Vec<SourceItem<E>>,- /// Where the next page starts; `None` once the feed is exhausted.- pub next: Option<WorkFeedPosition>,-}--/// Lists hydrated, authorized feed candidates in feed order.-pub trait WorkFeedSource: Send + Sync + 'static {- /// The hydrated entity carried by each candidate.- type Entity: Send + Sync + 'static;-- /// Fetch one page of candidates.- fn page(- &self,- request: SourceRequest,- ) -> impl Future<Output = Result<SourcePage<Self::Entity>, Report>> + Send;-}--/// Reads and acknowledges the viewer's notifications.-pub trait WorkFeedNotifications: Send + Sync + 'static {- /// The viewer's active (unseen or seen) notifications about each entity.- fn active(- &self,- user: MacroUserIdStr<'static>,- entities: Vec<Entity<'static>>,- ) -> impl Future<Output = Result<HashMap<Entity<'static>, Vec<FeedNotification>>, Report>> + Send;-- /// Move the viewer's notifications to done, or back from done to seen.- /// Returns the ids whose state changed.- fn set_done(- &self,- user: MacroUserIdStr<'static>,- notification_ids: Vec<Uuid>,- done: bool,- ) -> impl Future<Output = Result<Vec<Uuid>, Report>> + Send;-}--/// Archives email threads; mail's notion of done.-pub trait WorkFeedMail: Send + Sync + 'static {- /// Archive or unarchive one of the viewer's threads.- fn set_archived(- &self,- user: MacroUserIdStr<'static>,- thread_id: Uuid,- archived: bool,- ) -> impl Future<Output = Result<(), Report>> + Send;-}--/// Tells the viewer's other sessions that items changed in ways their-/// realtime streams do not report, such as notifications completed here.-pub trait WorkFeedSignals: Send + Sync + 'static {- /// Best effort: failures are logged, never returned.- fn items_changed(- &self,- user: MacroUserIdStr<'static>,- entities: Vec<Entity<'static>>,- ) -> impl Future<Output = ()> + Send;-}--/// Realtime changes that may affect a viewer's items.-pub trait WorkFeedTriggers: Send + Sync + 'static {- /// Subscribe to triggers for `user`. The receiver closes when the- /// underlying streams end; a subscriber that falls behind receives- /// [`WorkFeedTrigger::Invalidated`] first.- fn subscribe(- &self,- user: MacroUserIdStr<'static>,- ) -> tokio::sync::mpsc::Receiver<WorkFeedTrigger>;-}diff --git a/crates/work_feed/src/domain/realtime.rs b/crates/work_feed/src/domain/realtime.rsdeleted file mode 100644index 9b65ef901b..0000000000--- a/crates/work_feed/src/domain/realtime.rs+++ /dev/null@@ -1,34 +0,0 @@-//! Which items a realtime change may affect.-//!-//! Triggers only name candidate keys; the service recomputes those items-//! from storage, so a trigger that names an item outside the feed costs one-//! lookup and changes nothing.--use model_entity::{Entity, EntityType};-use model_notifications::NotifEvent;-use notification::domain::models::UserNotificationRow;--use super::stacking::channel_thread_root;--#[cfg(test)]-mod test;--/// The items a notification about its entity may affect. A channel-/// notification can move between the channel item and a thread item, so-/// both are recomputed; a plain send names the thread it may root.-pub fn notification_trigger_keys(- notification: &UserNotificationRow<NotifEvent>,-) -> Vec<Entity<'static>> {- let mut keys = vec![notification.entity.clone()];- if notification.entity.entity_type != EntityType::Channel {- return keys;- }- let thread = channel_thread_root(notification).or(match ¬ification.notification_metadata {- NotifEvent::ChannelMessageSend(send) => Some(send.message_id.as_str()),- _ => None,- });- if let Some(root) = thread {- keys.push(EntityType::ChannelMessage.with_entity_string(root.to_string()));- }- keys-}diff --git a/crates/work_feed/src/domain/realtime/test.rs b/crates/work_feed/src/domain/realtime/test.rsdeleted file mode 100644index 7356b8c560..0000000000--- a/crates/work_feed/src/domain/realtime/test.rs+++ /dev/null@@ -1,39 +0,0 @@-use super::*;-use crate::domain::test_support::*;--const CHANNEL: u128 = 0xC0;--fn thread(id: u128) -> Entity<'static> {- entity(EntityType::ChannelMessage, id)-}--#[test]-fn channel_notifications_recompute_the_channel_and_its_thread() {- let channel = entity(EntityType::Channel, CHANNEL);- assert_eq!(- notification_trigger_keys(&channel_reply(1, CHANNEL, 0x70, 0x71, 1)),- vec![channel.clone(), thread(0x70)]- );- assert_eq!(- notification_trigger_keys(&channel_mention(2, CHANNEL, 0x72, None, 1)),- vec![channel.clone(), thread(0x72)]- );- // A plain send may root a thread that absorbs it.- assert_eq!(- notification_trigger_keys(&channel_send(3, CHANNEL, 0x73, 1)),- vec![channel.clone(), thread(0x73)]- );- assert_eq!(- notification_trigger_keys(&channel_invite(4, CHANNEL, 1)),- vec![channel]- );-}--#[test]-fn other_notifications_recompute_their_entity() {- let document = entity(EntityType::Document, 0xD0);- assert_eq!(- notification_trigger_keys(&doc_comment(1, 0xD0, 0xA0, 0xA0, 1)),- vec![document]- );-}diff --git a/crates/work_feed/src/domain/service.rs b/crates/work_feed/src/domain/service.rsindex 98bbc6b282..05d43bb9d7 100644--- a/crates/work_feed/src/domain/service.rs+++ b/crates/work_feed/src/domain/service.rs@@ -1,38 +1,35 @@//! The work feed use cases: list a page, recompute known items, mark items-//! done, and undo a done.+//! done, and undo a done. Paging, refill, notification loading and+//! acknowledgment are the shared feed layer's; this service builds Home's+//! items from what it loads.use std::collections::{HashMap, HashSet};-use model_entity::{Entity, EntityType};+use attention_feed::domain::{+ acknowledge::Acknowledger,+ models::{+ Acknowledgment, CandidateKeying, CandidateRequest, DoneReceipt, EntityFacts, FeedError,+ FeedKey, FeedViewer, Loaded, counts_as_unseen,+ },+ ports::{CandidateSource, FeedMail, FeedNotifications, FeedSignals},+ reader::FeedReader,+};+use model_entity::EntityType;use model_notifications::NotifEvent;use rootcause::Report;use uuid::Uuid;use super::{models::{- FeedNotification, WorkFeedChange, WorkFeedDoneOutcome, WorkFeedDoneReceipt,- WorkFeedDoneTarget, WorkFeedEntry, WorkFeedError, WorkFeedItem, WorkFeedItemKey,- WorkFeedItemState, WorkFeedPage, WorkFeedPosition, WorkFeedPrimaryReason, WorkFeedQuery,- WorkFeedScope, WorkFeedViewer, counts_as_unseen,+ WorkFeedChange, WorkFeedDoneOutcome, WorkFeedDoneTarget, WorkFeedEntry, WorkFeedItem,+ WorkFeedItemState, WorkFeedPage, WorkFeedPrimaryReason, WorkFeedQuery, WorkFeedScope,},- policy,- ports::{- EntityFacts, SourceItem, SourceRequest, WorkFeedMail, WorkFeedNotifications,- WorkFeedSignals, WorkFeedSource,- },- stacking,+ policy, stacking,};#[cfg(test)]mod test;-/// Most candidate keys recomputed per source request.-const RECOMPUTE_CHUNK: usize = 200;--/// Most source pages one feed page reads while its state filter leaves it-/// short. A page that is still short carries a cursor; the caller asks again.-const MAX_PAGE_FILL_ROUNDS: usize = 4;-/// The work feed's use cases.pub trait WorkFeedService: Send + Sync + 'static {/// The hydrated entity each item carries.@@ -41,18 +38,18 @@ pub trait WorkFeedService: Send + Sync + 'static {/// One page of the viewer's feed, newest first.fn page(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,query: WorkFeedQuery,- ) -> impl Future<Output = Result<WorkFeedPage<Self::Entity>, WorkFeedError>> + Send;+ ) -> impl Future<Output = Result<WorkFeedPage<Self::Entity>, FeedError>> + Send;/// The current membership and content of known items in one feed: each/// key comes back upserted with its placement, or removed.fn recompute(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,scope: WorkFeedScope,- keys: Vec<WorkFeedItemKey>,- ) -> impl Future<Output = Result<Vec<WorkFeedChange<Self::Entity>>, WorkFeedError>> + Send;+ keys: Vec<FeedKey>,+ ) -> impl Future<Output = Result<Vec<WorkFeedChange<Self::Entity>>, FeedError>> + Send;/// Acknowledge the attention the caller observed on each item: its/// notifications move to done and its inbox email is archived. Own work@@ -61,36 +58,39 @@ pub trait WorkFeedService: Send + Sync + 'static {/// and pull requests are not completed.fn mark_done(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,targets: Vec<WorkFeedDoneTarget>,- ) -> impl Future<Output = Result<WorkFeedDoneOutcome, WorkFeedError>> + Send;+ ) -> impl Future<Output = Result<WorkFeedDoneOutcome, FeedError>> + Send;/// Reverse exactly what one mark-done changed, then recompute its items/// for the caller's feed.fn undo_done(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,scope: WorkFeedScope,- receipt: WorkFeedDoneReceipt,- ) -> impl Future<Output = Result<Vec<WorkFeedChange<Self::Entity>>, WorkFeedError>> + Send;+ receipt: DoneReceipt,+ ) -> impl Future<Output = Result<Vec<WorkFeedChange<Self::Entity>>, FeedError>> + Send;}-/// The work feed service over its ports.+/// The work feed service over the shared feed layer.pub struct WorkFeedServiceImpl<S, N, M, G> {- source: S,- notifications: N,- mail: M,- signals: G,+ reader: FeedReader<S, N>,+ acknowledger: Acknowledger<N, M, G>,}-impl<S, N, M, G> WorkFeedServiceImpl<S, N, M, G> {- /// Create the service from its ports.+impl<S, N, M, G> WorkFeedServiceImpl<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 {- source,- notifications,- mail,- signals,+ reader: FeedReader::new(source, notifications.clone()),+ acknowledger: Acknowledger::new(notifications, mail, signals),}}}@@ -101,43 +101,40 @@ struct Assembled<E> {facts: EntityFacts,}-/// The notifications an item's scope is drawn from: a thread shares its-/// channel's notifications, every other item reads its own entity's.-fn notification_source(item: &SourceItem<impl Sized>) -> Option<Entity<'static>> {- match item.key.entity_type {- EntityType::ChannelMessage => item- .facts- .thread_channel- .map(|channel| EntityType::Channel.with_entity_string(channel.to_string())),- _ => Some(item.key.clone()),+/// The candidate request for one feed scope. The reader sets the limit,+/// cursor and key restriction per read.+fn candidate_request(viewer: &FeedViewer, scope: &WorkFeedScope) -> CandidateRequest {+ CandidateRequest {+ viewer: viewer.clone(),+ keying: CandidateKeying::ThreadScoped,+ own_work: scope.mode.own_work(),+ types: policy::candidate_types(&scope.types),+ filter: policy::signal_filter(&viewer.user, scope),+ limit: 0,+ after: None,+ only: None,}}-/// Build one item from its candidate and its source's active notifications.-/// Returns `None` when, after scoping, the item has no reason left.-fn assemble_item<E>(- item: SourceItem<E>,- loaded: &HashMap<Entity<'static>, Vec<FeedNotification>>,-) -> Option<Assembled<E>> {- let source = notification_source(&item);- let available = source- .as_ref()- .and_then(|source| loaded.get(source))- .map(Vec::as_slice)- .unwrap_or_default();+/// Build one item from its loaded candidate. Returns `None` when, after+/// scoping, the item has no reason left.+fn assemble_item<E>(loaded: Loaded<E>) -> Option<Assembled<E>> {+ let Loaded {+ candidate: item,+ notifications: available,+ } = loaded;let mut scoped = match item.key.entity_type {- EntityType::Channel => stacking::scope_channel(available),+ EntityType::Channel => stacking::scope_channel(&available),EntityType::ChannelMessage => {- stacking::scope_channel_thread(available, item.key.entity_id.as_ref())+ stacking::scope_channel_thread(&available, item.key.entity_id.as_ref())}- _ => available.to_vec(),+ _ => available,};// An email's attention lasts while it is in the inbox: archive is mail's// own done, whatever its notifications' states.if item.facts.mail.is_some_and(|mail| !mail.inbox_visible) {scoped.clear();}- stacking::sort_newest_first(&mut scoped);if scoped.is_empty() && item.touched_at.is_none() {return None;}@@ -168,7 +165,7 @@ fn assemble_item<E>(entry: WorkFeedEntry {sort_at: item.sort_at,item: WorkFeedItem {- key: WorkFeedItemKey::new(item.key),+ key: FeedKey::new(item.key),entity: item.entity,state: if unseen {WorkFeedItemState::Unseen@@ -188,70 +185,30 @@ fn assemble_item<E>(impl<S, N, M, G> WorkFeedServiceImpl<S, N, M, G>where- S: WorkFeedSource,- N: WorkFeedNotifications,- M: WorkFeedMail,- G: WorkFeedSignals,+ S: CandidateSource,+ N: FeedNotifications,+ M: FeedMail,+ G: FeedSignals,{- /// Load the candidates' notifications and build their items, in order.- async fn assemble(- &self,- viewer: &WorkFeedViewer,- items: Vec<SourceItem<S::Entity>>,- ) -> Result<Vec<Assembled<S::Entity>>, Report> {- let mut sources = Vec::new();- let mut seen = HashSet::new();- for source in items.iter().filter_map(notification_source) {- if seen.insert(source.clone()) {- sources.push(source);- }- }- let loaded = if sources.is_empty() {- HashMap::new()- } else {- self.notifications- .active(viewer.user.clone(), sources)- .await?- };- Ok(items- .into_iter()- .filter_map(|item| assemble_item(item, &loaded))- .collect())- }-/// Current items for `keys` in `scope`, keyed by item.async fn current(&self,- viewer: &WorkFeedViewer,+ viewer: &FeedViewer,scope: &WorkFeedScope,- keys: &[WorkFeedItemKey],- ) -> Result<HashMap<WorkFeedItemKey, Assembled<S::Entity>>, Report> {- let filter = policy::signal_filter(&viewer.user, scope);- let types = policy::candidate_types(&scope.types);- let mut current = HashMap::with_capacity(keys.len());- for chunk in keys.chunks(RECOMPUTE_CHUNK) {- let page = self- .source- .page(SourceRequest {- viewer: viewer.clone(),- mode: scope.mode,- types: types.clone(),- filter: filter.clone(),- limit: u16::try_from(chunk.len()).unwrap_or(u16::MAX),- after: None,- only: Some(chunk.iter().map(|key| key.entity().clone()).collect()),- })- .await?;- for assembled in self.assemble(viewer, page.items).await? {- current.insert(assembled.entry.item.key.clone(), assembled);- }- }- Ok(current)+ keys: &[FeedKey],+ ) -> Result<HashMap<FeedKey, Assembled<S::Entity>>, Report> {+ Ok(self+ .reader+ .current(candidate_request(viewer, scope), keys)+ .await?+ .into_iter()+ .filter_map(|(key, loaded)| assemble_item(loaded).map(|assembled| (key, assembled)))+ .collect())}}/// Keys deduplicated in first-seen order.-fn unique_keys(keys: impl IntoIterator<Item = WorkFeedItemKey>) -> Vec<WorkFeedItemKey> {+fn unique_keys(keys: impl IntoIterator<Item = FeedKey>) -> Vec<FeedKey> {let mut seen = HashSet::new();keys.into_iter().filter(|key| seen.insert(key.clone()))@@ -259,7 +216,7 @@ fn unique_keys(keys: impl IntoIterator<Item = WorkFeedItemKey>) -> Vec<WorkFeedI}/// An email thread item's thread id.-fn email_thread_id(key: &WorkFeedItemKey) -> Option<Uuid> {+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()@@ -267,88 +224,48 @@ fn email_thread_id(key: &WorkFeedItemKey) -> Option<Uuid> {impl<S, N, M, G> WorkFeedService for WorkFeedServiceImpl<S, N, M, G>where- S: WorkFeedSource,- N: WorkFeedNotifications,- M: WorkFeedMail,- G: WorkFeedSignals,+ S: CandidateSource,+ N: FeedNotifications,+ M: FeedMail,+ G: FeedSignals,{type Entity = S::Entity;- #[tracing::instrument(- err,- skip(self, viewer),- fields(- user = %viewer.user,- fill_rounds = tracing::field::Empty,- entries = tracing::field::Empty,- has_next = tracing::field::Empty,- )- )]+ #[tracing::instrument(err, skip(self, viewer), fields(user = %viewer.user))]async fn page(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,query: WorkFeedQuery,- ) -> Result<WorkFeedPage<Self::Entity>, WorkFeedError> {- let types = policy::candidate_types(&query.scope.types);- let filter = policy::signal_filter(&viewer.user, &query.scope);- let limit = usize::from(query.limit);- let mut entries = Vec::with_capacity(limit);- let mut after = query.after;- let mut rounds = 0;- // Items with no reason left, and items in another state, are- // dropped, so the page reads on until it is full. A page that fills- // partway through a source page resumes after its last item.- for _ in 0..MAX_PAGE_FILL_ROUNDS {- rounds += 1;- let page = self- .source- .page(SourceRequest {- viewer: viewer.clone(),- mode: query.scope.mode,- types: types.clone(),- filter: filter.clone(),- limit: query.limit,- after: after.clone(),- only: None,- })- .await?;- let mut assembled = self.assemble(&viewer, page.items).await?.into_iter();- for Assembled { entry, .. } in assembled.by_ref() {- if query.state.is_none_or(|state| entry.item.state == state) {- entries.push(entry);- }- if entries.len() == limit {- break;- }- }- after = match (entries.last(), assembled.len()) {- (Some(last), 1..) if entries.len() == limit => Some(WorkFeedPosition {- sort_at: last.sort_at,- entity_id: last.item.key.entity().entity_id.to_string(),- }),- _ => page.next,- };- if entries.len() == limit || after.is_none() {- break;- }- }- let span = tracing::Span::current();- span.record("fill_rounds", rounds);- span.record("entries", entries.len());- span.record("has_next", after.is_some());+ ) -> Result<WorkFeedPage<Self::Entity>, FeedError> {+ let request = CandidateRequest {+ limit: query.limit,+ after: query.after,+ ..candidate_request(&viewer, &query.scope)+ };+ // Items with no reason left, and items in another state, are dropped,+ // so the reader reads on until the page is full.+ let state = query.state;+ let page = self+ .reader+ .page(request, |loaded| {+ assemble_item(loaded)+ .map(|assembled| assembled.entry)+ .filter(|entry| state.is_none_or(|state| entry.item.state == state))+ })+ .await?;Ok(WorkFeedPage {- entries,- next: after,+ entries: page.entries,+ next: page.next,})}#[tracing::instrument(err, skip(self, viewer, keys), fields(user = %viewer.user, keys = keys.len()))]async fn recompute(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,scope: WorkFeedScope,- keys: Vec<WorkFeedItemKey>,- ) -> Result<Vec<WorkFeedChange<Self::Entity>>, WorkFeedError> {+ keys: Vec<FeedKey>,+ ) -> Result<Vec<WorkFeedChange<Self::Entity>>, FeedError> {let keys = unique_keys(keys);if keys.is_empty() {return Ok(Vec::new());@@ -366,110 +283,72 @@ where#[tracing::instrument(err, skip(self, viewer, targets), fields(user = %viewer.user, targets = targets.len()))]async fn mark_done(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,targets: Vec<WorkFeedDoneTarget>,- ) -> Result<WorkFeedDoneOutcome, WorkFeedError> {+ ) -> Result<WorkFeedDoneOutcome, FeedError> {let keys = unique_keys(targets.iter().map(|target| target.key.clone()));if keys.is_empty() {return Ok(WorkFeedDoneOutcome {items: Vec::new(),- receipt: WorkFeedDoneReceipt::default(),+ receipt: DoneReceipt::default(),});}// Evaluate each item in every feed's scope, whatever feed the caller// was looking at, so done acknowledges what they observed.- let current = self+ let mut current = self.current(&viewer, &WorkFeedScope::everything(), &keys).await?;- let mut notification_ids = Vec::new();- let mut archive = Vec::new();+ let mut acknowledgments = Vec::with_capacity(keys.len());let mut planned = HashSet::new();- for target in &targets {+ for target in targets {if !planned.insert(target.key.clone()) {continue;}- let Some(assembled) = current.get(&target.key) else {- // Already gone from every feed: nothing left to acknowledge.- continue;- };- let item = &assembled.entry.item;- let observed = target.revision.unwrap_or_else(|| item.revision());- if let Some(through) = observed.attention_through {- notification_ids.extend(- item.notifications- .iter()- .filter(|notification| notification.created_at <= through)- .map(|notification| notification.notification_id),- );- }- if assembled.facts.mail.is_some_and(|mail| mail.inbox_visible)- && let Some(thread_id) = email_thread_id(&target.key)- {- archive.push(thread_id);- }- }-- let user = viewer.user.clone();- let changed_notifications = if notification_ids.is_empty() {- Vec::new()- } else {- self.notifications- .set_done(user.clone(), notification_ids, true)- .await?- };- // Archiving is best effort: the thread's notifications are already- // done, which removes its attention on their own.- let mut archived = Vec::new();- for thread_id in archive {- match self.mail.set_archived(user.clone(), thread_id, true).await {- Ok(()) => archived.push(thread_id),- Err(error) => {- tracing::warn!(error = ?error, %thread_id, "failed to archive work feed email")+ // An item already gone from every feed has nothing left to+ // acknowledge, but is still reported done.+ let acknowledgment = match current.remove(&target.key) {+ Some(assembled) => {+ let item = &assembled.entry.item;+ let observed = target.revision.unwrap_or_else(|| item.revision());+ Acknowledgment {+ notification_ids: observed.acknowledged(&item.notifications),+ archive_thread: assembled+ .facts+ .is_some_and(|mail| mail.inbox_visible)+ .then(|| email_thread_id(&target.key))+ .flatten(),+ key: target.key,+ }}- }+ None => Acknowledgment {+ key: target.key,+ notification_ids: Vec::new(),+ archive_thread: None,+ },+ };+ acknowledgments.push(acknowledgment);}- self.signals- .items_changed(user, keys.iter().map(|key| key.entity().clone()).collect())- .await;-+ let receipt = self+ .acknowledger+ .acknowledge(&viewer, acknowledgments)+ .await?;Ok(WorkFeedDoneOutcome {- receipt: WorkFeedDoneReceipt {- items: keys.iter().map(WorkFeedItemKey::id).collect(),- notification_ids: changed_notifications,- archived_threads: archived,- },items: keys,+ receipt,})}#[tracing::instrument(err, skip(self, viewer, receipt), fields(user = %viewer.user))]async fn undo_done(&self,- viewer: WorkFeedViewer,+ viewer: FeedViewer,scope: WorkFeedScope,- receipt: WorkFeedDoneReceipt,- ) -> Result<Vec<WorkFeedChange<Self::Entity>>, WorkFeedError> {- let user = viewer.user.clone();- if !receipt.notification_ids.is_empty() {- self.notifications- .set_done(user.clone(), receipt.notification_ids.clone(), false)- .await?;- }- for thread_id in &receipt.archived_threads {- if let Err(error) = self- .set_archived(user.clone(), *thread_id, false)- .await- {- tracing::warn!(error = ?error, %thread_id, "failed to unarchive work feed email");- }- }- let keys = receipt.item_keys();- self.signals- .items_changed(user, keys.iter().map(|key| key.entity().clone()).collect())- .await;+ receipt: DoneReceipt,+ ) -> Result<Vec<WorkFeedChange<Self::Entity>>, FeedError> {+ let keys = self.acknowledger.undo(&viewer, &receipt).await?;self.recompute(viewer, scope, keys).await}}diff --git a/crates/work_feed/src/domain/service/test.rs b/crates/work_feed/src/domain/service/test.rsindex fac382f57e..d08bfc82e8 100644--- a/crates/work_feed/src/domain/service/test.rs+++ b/crates/work_feed/src/domain/service/test.rs@@ -1,17 +1,15 @@-use std::sync::Mutex;--use macro_user_id::user_id::MacroUserIdStr;-use notification::domain::models::NotificationState;-use serde_json::json;--use super::*;-use crate::domain::{- models::{- WorkFeedItemType, WorkFeedMode, WorkFeedPosition, WorkFeedRevision, WorkFeedStackKind,+use attention_feed::{+ domain::{+ models::{Candidate, FeedNotification, FeedPosition, FeedRevision, MailFacts},+ ports::NotificationTransition,},- ports::{MailFacts, SourcePage},test_support::*,};+use model_entity::Entity;+use notification::domain::models::NotificationState;++use super::*;+use crate::domain::models::{WorkFeedItemType, WorkFeedMode, WorkFeedStackKind};const DOC: u128 = 0xD0;const OTHER_DOC: u128 = 0xD1;@@ -20,238 +18,37 @@ const THREAD: u128 = 0x70;const MAIL: u128 = 0xE0;const SENT_MAIL: u128 = 0xE1;-/// A source serving a fixed, ordered feed of labelled candidates.-#[derive(Default)]-struct FakeSource {- items: Mutex<Vec<SourceItem<&'static str>>>,- requests: Mutex<Vec<SourceRequest>>,-}--impl FakeSource {- fn with(items: Vec<SourceItem<&'static str>>) -> Self {- Self {- items: Mutex::new(items),- requests: Mutex::default(),- }- }-}--impl WorkFeedSource for FakeSource {- type Entity = &'static str;-- async fn page(&self, request: SourceRequest) -> Result<SourcePage<&'static str>, Report> {- self.requests.lock().unwrap().push(request.clone());- let items = self.items.lock().unwrap().clone();- let mut page: Vec<_> = items- .into_iter()- .filter(|item| {- request- .only- .as_ref()- .is_none_or(|only| only.contains(&item.key))- })- .filter(|item| {- request.after.as_ref().is_none_or(|after| {- (item.sort_at, item.key.entity_id.to_string())- < (after.sort_at, after.entity_id.clone())- })- })- .collect();- let full = page.len() > usize::from(request.limit);- page.truncate(usize::from(request.limit));- let next = full.then(|| {- let last = page.last().unwrap();- WorkFeedPosition {- sort_at: last.sort_at,- entity_id: last.key.entity_id.to_string(),- }- });- Ok(SourcePage { items: page, next })- }-}--#[derive(Default)]-struct FakeNotifications {- by_entity: Mutex<HashMap<Entity<'static>, Vec<FeedNotification>>>,- loads: Mutex<Vec<Vec<Entity<'static>>>>,- done_calls: Mutex<Vec<(Vec<Uuid>, bool)>>,-}--impl FakeNotifications {- fn with(notifications: Vec<FeedNotification>) -> Self {- let mut by_entity: HashMap<Entity<'static>, Vec<FeedNotification>> = HashMap::new();- for notification in notifications {- by_entity- .entry(notification.entity.clone())- .or_default()- .push(notification);- }- Self {- by_entity: Mutex::new(by_entity),- ..Default::default()- }- }-- fn state_of(&self, id: Uuid) -> NotificationState {- self.by_entity- .lock()- .unwrap()- .values()- .flatten()- .find(|n| n.notification_id == id)- .map(|n| n.state)- .unwrap()- }-}--impl WorkFeedNotifications for FakeNotifications {- async fn active(- &self,- _user: MacroUserIdStr<'static>,- entities: Vec<Entity<'static>>,- ) -> Result<HashMap<Entity<'static>, Vec<FeedNotification>>, Report> {- self.loads.lock().unwrap().push(entities.clone());- let by_entity = self.by_entity.lock().unwrap();- Ok(entities- .into_iter()- .map(|entity| {- let active = by_entity- .get(&entity)- .into_iter()- .flatten()- .filter(|n| n.state != NotificationState::Done)- .cloned()- .collect();- (entity, active)- })- .collect())- }-- async fn set_done(- &self,- _user: MacroUserIdStr<'static>,- notification_ids: Vec<Uuid>,- done: bool,- ) -> Result<Vec<Uuid>, Report> {- self.done_calls- .lock()- .unwrap()- .push((notification_ids.clone(), done));- let mut changed = Vec::new();- for notifications in self.by_entity.lock().unwrap().values_mut() {- for notification in notifications.iter_mut() {- if notification_ids.contains(¬ification.notification_id) {- let state = if done {- NotificationState::Done- } else {- NotificationState::Seen- };- *notification = with_state(notification, state);- changed.push(notification.notification_id);- }- }- }- Ok(changed)- }-}--#[derive(Default)]-struct FakeMail {- calls: Mutex<Vec<(Uuid, bool)>>,-}--impl WorkFeedMail for FakeMail {- async fn set_archived(- &self,- _user: MacroUserIdStr<'static>,- thread_id: Uuid,- archived: bool,- ) -> Result<(), Report> {- self.calls.lock().unwrap().push((thread_id, archived));- Ok(())- }-}--#[derive(Default)]-struct FakeSignals {- calls: Mutex<Vec<Vec<Entity<'static>>>>,-}--impl WorkFeedSignals for FakeSignals {- async fn items_changed(&self, _user: MacroUserIdStr<'static>, entities: Vec<Entity<'static>>) {- self.calls.lock().unwrap().push(entities);- }-}--type Service = WorkFeedServiceImpl<FakeSource, FakeNotifications, FakeMail, FakeSignals>;+type Service =+ WorkFeedServiceImpl<FakeSource<&'static str>, FakeNotifications, FakeMail, FakeSignals>;-fn service(items: Vec<SourceItem<&'static str>>, notifications: Vec<FeedNotification>) -> Service {- WorkFeedServiceImpl::new(- FakeSource::with(items),- FakeNotifications::with(notifications),- FakeMail::default(),- FakeSignals::default(),- )+/// The service with handles on its fakes.+struct Harness {+ service: Service,+ source: FakeSource<&'static str>,+ notifications: FakeNotifications,+ mail: FakeMail,+ signals: FakeSignals,}-fn viewer() -> WorkFeedViewer {- WorkFeedViewer {- user: viewer_id(),- team: None,+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: WorkFeedServiceImpl::new(+ source.clone(),+ notifications.clone(),+ mail.clone(),+ signals.clone(),+ ),+ source,+ notifications,+ mail,+ signals,}}-fn candidate(- label: &'static str,- key: Entity<'static>,- attention: Option<u32>,- touched: Option<u32>,-) -> SourceItem<&'static str> {- let attention_at = attention.map(at);- let touched_at = touched.map(at);- SourceItem {- key,- entity: label,- facts: EntityFacts::default(),- attention_at,- touched_at,- sort_at: attention_at.max(touched_at).unwrap(),- }-}--fn mail_candidate(- label: &'static str,- id: u128,- attention: Option<u32>,- touched: Option<u32>,- mail: MailFacts,-) -> SourceItem<&'static str> {- let mut item = candidate(- label,- entity(EntityType::EmailThread, id),- attention,- touched,- );- item.facts.mail = Some(mail);- item-}--fn new_email(id: u128, thread: u128, minute: u32, state: NotificationState) -> FeedNotification {- notification(- id,- entity(EntityType::EmailThread, thread),- "new_email",- json!({- "toEmail": "[email protected]",- "threadId": uuid(thread),- "subject": "Hello",- "snippet": "...",- }),- minute,- state,- )-}-fn query() -> WorkFeedQuery {WorkFeedQuery {scope: WorkFeedScope {@@ -265,8 +62,12 @@ fn query() -> WorkFeedQuery {}}-fn key(entity: Entity<'static>) -> WorkFeedItemKey {- WorkFeedItemKey::new(entity)+fn key(entity: Entity<'static>) -> FeedKey {+ FeedKey::new(entity)+}++fn done_calls(notifications: &FakeNotifications) -> Vec<(Vec<Uuid>, NotificationTransition)> {+ notifications.transitions.lock().unwrap().clone()}#[tokio::test]@@ -278,7 +79,7 @@ async fn page_assembles_stacked_items_in_feed_order() {None,);thread.facts.thread_channel = Some(uuid(CHANNEL));- let service = service(+ let harness = harness(vec![candidate("doc", entity(EntityType::Document, DOC), Some(5), Some(9)),thread,@@ -319,7 +120,7 @@ async fn page_assembles_stacked_items_in_feed_order() {],);- let page = service.page(viewer(), query()).await.unwrap();+ let page = harness.service.page(viewer(), query()).await.unwrap();let labels: Vec<_> = page.entries.iter().map(|e| e.item.entity).collect();assert_eq!(labels, vec!["doc", "thread", "mail", "sent"]);@@ -348,7 +149,7 @@ async fn page_assembles_stacked_items_in_feed_order() {assert_eq!(sent.primary, WorkFeedPrimaryReason::OwnWork);// The thread and its channel share one notification load.- let loads = service.notifications.loads.lock().unwrap();+ let loads = harness.notifications.loads.lock().unwrap();assert_eq!(loads.len(), 1);assert_eq!(loads[0]@@ -359,9 +160,41 @@ async fn page_assembles_stacked_items_in_feed_order() {);}+#[tokio::test]+async fn page_refills_after_items_with_no_reason_left() {+ let mut thread = candidate(+ "thread",+ entity(EntityType::ChannelMessage, THREAD),+ Some(6),+ None,+ );+ thread.facts.thread_channel = Some(uuid(CHANNEL));+ let harness = harness(+ vec![+ thread,+ // Its only notification belongs to the thread: no item.+ candidate(+ "channel",+ entity(EntityType::Channel, CHANNEL),+ Some(5),+ None,+ ),+ candidate("doc", entity(EntityType::Document, DOC), None, Some(4)),+ ],+ vec![channel_reply(1, CHANNEL, THREAD, 0x71, 6)],+ );+ let mut query = query();+ query.limit = 2;++ let page = harness.service.page(viewer(), query).await.unwrap();+ let labels: Vec<_> = page.entries.iter().map(|e| e.item.entity).collect();+ assert_eq!(labels, vec!["thread", "doc"]);+ assert_eq!(harness.source.requests.lock().unwrap().len(), 2);+}+#[tokio::test]async fn page_forwards_scope_and_cursor_to_the_source() {- let service = service(+ let harness = harness(vec![candidate("doc",entity(EntityType::Document, DOC),@@ -373,14 +206,15 @@ async fn page_forwards_scope_and_cursor_to_the_source() {let mut query = query();query.scope.mode = WorkFeedMode::Attention;query.scope.types = vec![WorkFeedItemType::Email, WorkFeedItemType::ChannelThread];- query.after = Some(WorkFeedPosition {+ query.after = Some(FeedPosition {sort_at: at(30),entity_id: "x".to_string(),});- service.page(viewer(), query).await.unwrap();+ harness.service.page(viewer(), query).await.unwrap();- let requests = service.source.requests.lock().unwrap();- assert_eq!(requests[0].mode, WorkFeedMode::Attention);+ let requests = harness.source.requests.lock().unwrap();+ assert!(!requests[0].own_work);+ assert_eq!(requests[0].keying, CandidateKeying::ThreadScoped);assert_eq!(requests[0].types,vec![EntityType::EmailThread, EntityType::ChannelMessage]@@ -396,7 +230,7 @@ async fn state_filter_reads_on_until_the_page_is_full() {const UNSEEN_3: u128 = 0xA3;const SEEN_1: u128 = 0xB1;const SEEN_2: u128 = 0xB2;- let service = service(+ let harness = harness(vec![candidate("unseen 1",@@ -447,18 +281,22 @@ async fn state_filter_reads_on_until_the_page_is_full() {// The first source page keeps one item; the second fills the page with// one of its two, so the next page starts right after it.- let first = service.page(viewer(), unseen.clone()).await.unwrap();+ let first = harness+ .service+ .page(viewer(), unseen.clone())+ .await+ .unwrap();assert_eq!(labels(&first), vec!["unseen 1", "unseen 2"]);assert_eq!(first.next.as_ref().unwrap().sort_at, at(7));unseen.after = first.next;- let second = service.page(viewer(), unseen).await.unwrap();+ let second = harness.service.page(viewer(), unseen).await.unwrap();assert_eq!(labels(&second), vec!["unseen 3"]);assert!(second.next.is_none());let mut seen = query();seen.state = Some(WorkFeedItemState::Seen);- let page = service.page(viewer(), seen).await.unwrap();+ let page = harness.service.page(viewer(), seen).await.unwrap();assert_eq!(labels(&page), vec!["seen 1", "seen 2"]);}@@ -474,21 +312,21 @@ async fn state_filter_stops_after_its_read_limit_with_a_cursor() {)}).collect();- let service = service(items, Vec::new());+ let harness = harness(items, Vec::new());let mut query = query();query.state = Some(WorkFeedItemState::Unseen);query.limit = 2;- let page = service.page(viewer(), query).await.unwrap();+ let page = harness.service.page(viewer(), query).await.unwrap();assert!(page.entries.is_empty());- assert_eq!(service.source.requests.lock().unwrap().len(), 4);+ assert_eq!(harness.source.requests.lock().unwrap().len(), 4);assert_eq!(page.next.unwrap().sort_at, at(43));}#[tokio::test]async fn recompute_upserts_present_items_and_removes_missing_ones() {- let service = service(+ let harness = harness(vec![candidate("doc",entity(EntityType::Document, DOC),@@ -497,7 +335,8 @@ async fn recompute_upserts_present_items_and_removes_missing_ones() {)],Vec::new(),);- let changes = service+ let changes = harness+ .service.recompute(viewer(),query().scope,@@ -519,7 +358,7 @@ async fn recompute_upserts_present_items_and_removes_missing_ones() {#[tokio::test]async fn done_acknowledges_only_what_was_observed() {- let service = service(+ let harness = harness(vec![candidate("doc",entity(EntityType::Document, DOC),@@ -534,12 +373,13 @@ async fn done_acknowledges_only_what_was_observed() {);let doc = key(entity(EntityType::Document, DOC));- let outcome = service+ let outcome = harness+ .service.mark_done(viewer(),vec![WorkFeedDoneTarget {key: doc.clone(),- revision: Some(WorkFeedRevision {+ revision: Some(FeedRevision {attention_through: Some(at(6)),}),}],@@ -550,17 +390,17 @@ async fn done_acknowledges_only_what_was_observed() {assert_eq!(outcome.items, vec![doc.clone()]);assert_eq!(outcome.receipt.notification_ids, vec![uuid(1)]);assert_eq!(- service.notifications.state_of(uuid(1)),+ harness.notifications.state_of(uuid(1)),NotificationState::Done);assert_eq!(- service.notifications.state_of(uuid(2)),+ harness.notifications.state_of(uuid(2)),NotificationState::Unseen);assert!(outcome.receipt.archived_threads.is_empty());// Every session of the viewer is told the item changed.assert_eq!(- *service.signals.calls.lock().unwrap(),+ *harness.signals.calls.lock().unwrap(),vec![vec![doc.entity().clone()]]);}@@ -575,7 +415,7 @@ async fn done_without_a_revision_completes_everything_current() {inbox_visible: false,is_read: true,};- let service = service(+ let harness = harness(vec![mail_candidate("mail", MAIL, Some(4), None, inbox),mail_candidate("sent", SENT_MAIL, None, Some(3), sent),@@ -583,7 +423,8 @@ async fn done_without_a_revision_completes_everything_current() {vec![new_email(1, MAIL, 4, NotificationState::Unseen)],);- let outcome = service+ let outcome = harness+ .service.mark_done(viewer(),vec![@@ -604,7 +445,7 @@ async fn done_without_a_revision_completes_everything_current() {// Only the inbox thread is archived; the sent thread is own work, which// done leaves alone.assert_eq!(- *service.mail.calls.lock().unwrap(),+ *harness.mail.calls.lock().unwrap(),vec![(uuid(MAIL), true)]);assert_eq!(outcome.receipt.archived_threads, vec![uuid(MAIL)]);@@ -612,7 +453,7 @@ async fn done_without_a_revision_completes_everything_current() {#[tokio::test]async fn done_leaves_own_work_alone() {- let service = service(+ let harness = harness(vec![candidate("doc",entity(EntityType::Document, DOC),@@ -622,7 +463,8 @@ async fn done_leaves_own_work_alone() {Vec::new(),);let doc = key(entity(EntityType::Document, DOC));- let outcome = service+ let outcome = harness+ .service.mark_done(viewer(),vec![WorkFeedDoneTarget {@@ -636,15 +478,16 @@ async fn done_leaves_own_work_alone() {// Nothing to acknowledge: the item keeps its own-work reason.assert_eq!(outcome.items, vec![doc]);assert!(outcome.receipt.notification_ids.is_empty());- assert!(service.notifications.done_calls.lock().unwrap().is_empty());- assert!(service.mail.calls.lock().unwrap().is_empty());+ assert!(done_calls(&harness.notifications).is_empty());+ assert!(harness.mail.calls.lock().unwrap().is_empty());}#[tokio::test]async fn done_on_an_item_already_gone_changes_nothing() {- let service = service(Vec::new(), Vec::new());+ let harness = harness(Vec::new(), Vec::new());let gone = key(entity(EntityType::Document, DOC));- let outcome = service+ let outcome = harness+ .service.mark_done(viewer(),vec![WorkFeedDoneTarget {@@ -656,7 +499,7 @@ async fn done_on_an_item_already_gone_changes_nothing() {.unwrap();assert_eq!(outcome.items, vec![gone]);assert_eq!(outcome.receipt.notification_ids, Vec::<Uuid>::new());- assert!(service.notifications.done_calls.lock().unwrap().is_empty());+ assert!(done_calls(&harness.notifications).is_empty());}#[tokio::test]@@ -665,7 +508,7 @@ async fn undo_reverses_exactly_one_done() {inbox_visible: true,is_read: true,};- let service = service(+ let harness = harness(vec![candidate("doc", entity(EntityType::Document, DOC), Some(5), Some(9)),mail_candidate("mail", MAIL, Some(4), None, inbox),@@ -677,7 +520,8 @@ async fn undo_reverses_exactly_one_done() {);let doc = key(entity(EntityType::Document, DOC));let mail = key(entity(EntityType::EmailThread, MAIL));- let outcome = service+ let outcome = harness+ .service.mark_done(viewer(),vec![@@ -694,23 +538,24 @@ async fn undo_reverses_exactly_one_done() {.await.unwrap();- let receipt = WorkFeedDoneReceipt::decode(&outcome.receipt.encode()).unwrap();- let changes = service+ let receipt = DoneReceipt::decode(&outcome.receipt.encode()).unwrap();+ let changes = harness+ .service.undo_done(viewer(), query().scope, receipt).await.unwrap();// Undone notifications come back seen.assert_eq!(- service.notifications.state_of(uuid(1)),+ harness.notifications.state_of(uuid(1)),NotificationState::Seen);assert_eq!(- service.notifications.state_of(uuid(2)),+ harness.notifications.state_of(uuid(2)),NotificationState::Seen);assert_eq!(- *service.mail.calls.lock().unwrap(),+ *harness.mail.calls.lock().unwrap(),vec![(uuid(MAIL), true), (uuid(MAIL), false)]);assert_eq!(changes.len(), 2);diff --git a/crates/work_feed/src/domain/stacking.rs b/crates/work_feed/src/domain/stacking.rsindex 9f370c6512..357570017f 100644--- a/crates/work_feed/src/domain/stacking.rs+++ b/crates/work_feed/src/domain/stacking.rs@@ -15,45 +15,17 @@use std::collections::{HashMap, HashSet};-use model_entity::EntityType;+use attention_feed::domain::{+ keying::channel_thread_root,+ models::{FeedNotification, sort_newest_first},+};use model_notifications::NotifEvent;-use notification::domain::models::UserNotificationRow;-use super::models::{FeedNotification, WorkFeedStack, WorkFeedStackKind};+use super::models::{WorkFeedStack, WorkFeedStackKind};#[cfg(test)]mod test;-/// The channel thread root a channel notification is attributed to, if any:-/// the thread for replies, and the named message's thread (or the message-/// itself, which becomes the root) for mentions, reactions and document-/// mentions. Plain sends and channel-level events have none.-pub fn channel_thread_root(notification: &UserNotificationRow<NotifEvent>) -> Option<&str> {- if notification.entity.entity_type != EntityType::Channel {- return None;- }- match ¬ification.notification_metadata {- NotifEvent::ChannelMessageReply(reply) => Some(reply.thread_id.as_str()),- NotifEvent::ChannelMention(mention) => {- Some(mention.thread_id.as_deref().unwrap_or(&mention.message_id))- }- NotifEvent::ChannelMessageReaction(reaction) => Some(- reaction- .thread_id- .as_deref()- .unwrap_or(&reaction.message_id),- ),- NotifEvent::DocumentMention(mention) => Some(- mention- .channel- .thread_id- .as_deref()- .unwrap_or(&mention.channel.message_id),- ),- _ => None,- }-}-/// Threads in a channel that have replies or thread mentions; their root/// messages belong to the thread rather than to the channel.fn active_threads(notifications: &[FeedNotification]) -> HashSet<&str> {@@ -103,15 +75,6 @@ pub fn scope_channel_thread(.collect()}-/// Sort notifications newest first, breaking ties by id for a stable order.-pub fn sort_newest_first(notifications: &mut [FeedNotification]) {- notifications.sort_by(|a, b| {- b.created_at- .cmp(&a.created_at)- .then_with(|| b.notification_id.cmp(&a.notification_id))- });-}-/// A message-shaped notification's role in its conversation.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum Role {diff --git a/crates/work_feed/src/domain/stacking/test.rs b/crates/work_feed/src/domain/stacking/test.rsindex d0f1b1ff4e..115bbb118b 100644--- a/crates/work_feed/src/domain/stacking/test.rs+++ b/crates/work_feed/src/domain/stacking/test.rs@@ -1,5 +1,6 @@use super::*;-use crate::domain::test_support::*;+use attention_feed::test_support::*;+use model_entity::EntityType;use notification::domain::models::NotificationState;const CHANNEL: u128 = 0xC0;diff --git a/crates/work_feed/src/domain/test_support.rs b/crates/work_feed/src/domain/test_support.rsdeleted file mode 100644index bbd0c91433..0000000000--- a/crates/work_feed/src/domain/test_support.rs+++ /dev/null@@ -1,248 +0,0 @@-//! Notification fixtures shared by the domain tests.--use std::sync::Arc;--use chrono::{DateTime, TimeZone, Utc};-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::{Entity, EntityType};-use model_notifications::NotifEvent;-use notification::domain::models::{NotificationState, UserNotificationRow};-use serde_json::{Value, json};-use uuid::Uuid;--use super::models::FeedNotification;--pub(crate) const USER: &str = "macro|[email protected]";--/// A minute past 10:00 on 2024-06-01, UTC.-pub(crate) fn at(minute: u32) -> DateTime<Utc> {- Utc.with_ymd_and_hms(2024, 6, 1, 10, minute, 0).unwrap()-}--pub(crate) fn viewer_id() -> MacroUserIdStr<'static> {- MacroUserIdStr::parse_from_str(USER).unwrap()-}--pub(crate) fn uuid(n: u128) -> Uuid {- Uuid::from_u128(n)-}--pub(crate) fn entity(entity_type: EntityType, id: u128) -> Entity<'static> {- entity_type.with_entity_string(uuid(id).to_string())-}--/// A notification with typed metadata decoded from `tag`/`content`, the way-/// stored rows are.-pub(crate) fn notification(- id: u128,- entity: Entity<'static>,- tag: &str,- content: Value,- minute: u32,- state: NotificationState,-) -> FeedNotification {- let metadata: NotifEvent = serde_json::from_value(json!({ "tag": tag, "content": content }))- .unwrap_or_else(|error| panic!("invalid {tag} fixture: {error}"));- Arc::new(UserNotificationRow {- owner_id: viewer_id(),- notification_id: uuid(id),- notification_event_type: tag.to_string(),- entity,- sent: true,- state,- created_at: at(minute),- viewed_at: None,- updated_at: at(minute),- deleted_at: None,- notification_metadata: metadata,- sender_id: None,- })-}--pub(crate) fn channel_send(- id: u128,- channel: u128,- message: u128,- minute: u32,-) -> FeedNotification {- notification(- id,- entity(EntityType::Channel, channel),- "channel_message_send",- json!({ "messageId": uuid(message), "messageContent": "hi", "channelType": "public" }),- minute,- NotificationState::Unseen,- )-}--pub(crate) fn channel_reply(- id: u128,- channel: u128,- thread: u128,- message: u128,- minute: u32,-) -> FeedNotification {- notification(- id,- entity(EntityType::Channel, channel),- "channel_message_reply",- json!({- "threadId": uuid(thread),- "messageId": uuid(message),- "messageContent": "re",- "channelType": "public",- }),- minute,- NotificationState::Unseen,- )-}--pub(crate) fn channel_mention(- id: u128,- channel: u128,- message: u128,- thread: Option<u128>,- minute: u32,-) -> FeedNotification {- let mut content = json!({- "messageId": uuid(message),- "messageContent": "@you",- "channelType": "public",- });- if let Some(thread) = thread {- content["threadId"] = json!(uuid(thread));- }- notification(- id,- entity(EntityType::Channel, channel),- "channel_mention",- content,- minute,- NotificationState::Unseen,- )-}--pub(crate) fn channel_reaction(- id: u128,- channel: u128,- message: u128,- thread: Option<u128>,- minute: u32,-) -> FeedNotification {- let mut content = json!({- "messageId": uuid(message),- "messageContent": "nice",- "emoji": "+1",- "channelType": "public",- });- if let Some(thread) = thread {- content["threadId"] = json!(uuid(thread));- }- notification(- id,- entity(EntityType::Channel, channel),- "channel_message_reaction",- content,- minute,- NotificationState::Unseen,- )-}--pub(crate) fn channel_invite(id: u128, channel: u128, minute: u32) -> FeedNotification {- notification(- id,- entity(EntityType::Channel, channel),- "channel_invite",- json!({ "invitedBy": USER, "channelType": "public" }),- minute,- NotificationState::Unseen,- )-}--fn comment_content(comment: u128, thread: u128) -> Value {- json!({- "documentName": "Doc",- "owner": USER,- "commentId": uuid(comment),- "threadId": uuid(thread),- "text": "comment",- })-}--pub(crate) fn doc_comment(- id: u128,- document: u128,- comment: u128,- thread: u128,- minute: u32,-) -> FeedNotification {- notification(- id,- entity(EntityType::Document, document),- "commented_on_document",- comment_content(comment, thread),- minute,- NotificationState::Unseen,- )-}--pub(crate) fn doc_reply(- id: u128,- document: u128,- comment: u128,- thread: u128,- minute: u32,-) -> FeedNotification {- notification(- id,- entity(EntityType::Document, document),- "replied_to_document_comment_thread",- comment_content(comment, thread),- minute,- NotificationState::Unseen,- )-}--pub(crate) fn doc_comment_mention(- id: u128,- document: u128,- comment: u128,- thread: u128,- minute: u32,-) -> FeedNotification {- let mut content = comment_content(comment, thread);- content["mentionId"] = json!("mention");- notification(- id,- entity(EntityType::Document, document),- "mentioned_in_document_comment",- content,- minute,- NotificationState::Unseen,- )-}--pub(crate) fn reminder(id: u128, entity: Entity<'static>, minute: u32) -> FeedNotification {- notification(- id,- entity,- "reminder",- json!({ "reminderId": uuid(id), "description": "follow up" }),- minute,- NotificationState::Unseen,- )-}--/// The same notification in another state.-pub(crate) fn with_state(- notification: &FeedNotification,- state: NotificationState,-) -> FeedNotification {- let mut row = (**notification).clone();- row.state = state;- Arc::new(row)-}--pub(crate) fn ids(notifications: &[FeedNotification]) -> Vec<Uuid> {- notifications.iter().map(|n| n.notification_id).collect()-}diff --git a/crates/work_feed/src/lib.rs b/crates/work_feed/src/lib.rsindex 9351b9945e..2a4ee48aed 100644--- a/crates/work_feed/src/lib.rs+++ b/crates/work_feed/src/lib.rs@@ -5,12 +5,11 @@//!//! # Architecture//!-//! - **domain**: item identity, membership policy, notification stacking,+//! - **domain**: Home's items, membership policy, notification stacking,//! seen/done state, and the page, recompute, done and undo use cases.-//! - **outbound**: adapters over the Soup, notification, email, activity and-//! realtime services that own the underlying data.+//!+//! 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;--#[cfg(feature = "outbound")]-pub mod outbound;diff --git a/docs/guides/add-entity.md b/docs/guides/add-entity.mdindex f9d5ab6504..1c25e0555c 100644--- a/docs/guides/add-entity.md+++ b/docs/guides/add-entity.md@@ -259,7 +259,7 @@ on the other.view with a bind-placeholder collision.- **Feeds** (if it belongs in Recent, inbox, or the Home work feed):`candidate_gates.rs`, `touched.rs` (Recent, which reads activity, so section 7- is a prerequisite), `notified.rs` with `notified/query.sql`, `work_feed/`, and+ is a prerequisite), `notified.rs` with `notified/query.sql`, `attention/`, andthe routing arms in `crates/soup/src/domain/service.rs` and`domain/service/favorites.rs`. Keep new gates index-only; these queries havebeen cancelled on the replica in production for scanning too much.diff --git a/docs/guides/add-notification-kind.md b/docs/guides/add-notification-kind.mdindex 62da9556d7..d439cd5479 100644--- a/docs/guides/add-notification-kind.md+++ b/docs/guides/add-notification-kind.md@@ -226,10 +226,12 @@ kinds introduced by a newer backend.## 7. Server-built feeds (when relevant)-- **Home work feed:** `crates/work_feed/src/domain/stacking.rs` attributes channel- notifications to thread roots and stacks comment events. A new kind defaults to- a standalone stack (`_ => None`); add it to the thread-root and- `is_channel_event` / `is_comment_event` matches if it belongs to a conversation.+- **Home work feed:** `crates/attention_feed/src/domain/keying.rs`+ (`channel_thread_root`) attributes channel notifications to thread roots, and+ `crates/work_feed/src/domain/stacking.rs` stacks channel and comment events. A+ new kind defaults to a standalone stack (`_ => None`); add it to the thread-root+ and `is_channel_event` / `is_comment_event` matches if it belongs to a+ conversation.- **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 5ecf54de80..6ed05d0de2 100644--- a/services/document_storage_service/AGENTS.md+++ b/services/document_storage_service/AGENTS.md@@ -78,7 +78,8 @@ threads, pins, recents, notifications, folders, activity.- `cargo test -p document_storage_service` (`SQLX_OFFLINE` unset; needsMacroDB + Redis — `just run_dbs` from repo root; DynamoDB local via- `just ensure::ensure_dynamodb`, see `justfile`).+ `just ensure::ensure_dynamodb` from `services/document_storage_service`,+ whose `justfile` declares the `ensure` module).- After query changes: `nix develop --command just prepare_db` from the repo root.## Gotchasdiff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 56d7dd84e3..34be76e0de 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -41,6 +41,7 @@ activity = { path = "../../crates/activity" }ai_tools = { path = "../../crates/ai_tools" }ai_usage = { path = "../../crates/ai_usage" }analytics_client = { path = "../../crates/analytics_client" }+attention_feed = { path = "../../crates/attention_feed", features = ["inbound", "outbound"] }anyhow = { workspace = true }async-graphql = { workspace = true }async-graphql-axum = "7.0.17"@@ -302,7 +303,7 @@ webhook = { path = "../../crates/webhook", features = ["outbound","worker",] }-work_feed = { path = "../../crates/work_feed", features = ["outbound"] }+work_feed = { path = "../../crates/work_feed" }workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }zip = { workspace = true }diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rsindex fdffa64185..3178eda2ca 100644--- a/services/document_storage_service/src/server.rs+++ b/services/document_storage_service/src/server.rs@@ -2129,31 +2129,38 @@ pub async fn run() -> anyhow::Result<()> {entity_access_service.clone(),));- // Home's work feed: 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 so the viewer's other sessions recompute- // too: GraphQL notification writes publish no realtime update.+ // Attention feeds (Home's work feed) share one feed layer: 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+ // so the viewer's other sessions recompute too: GraphQL notification+ // writes publish no realtime update.+ let feed_triggers: Arc<dyn attention_feed::domain::ports::FeedTriggers> = Arc::new(+ attention_feed::outbound::triggers::RealtimeFeedTriggers::new(+ websocket_notification_consumer_service.clone(),+ activity_realtime_service.clone(),+ soup_realtime_service.clone(),+ ),+ );+ let feed_viewers: Arc<dyn attention_feed::inbound::viewers::FeedViewerResolver> = Arc::new(+ attention_feed::inbound::viewers::EntityAccessFeedViewers(entity_access_service.clone()),+ );let graphql_work_feed_context = complete_graph::WorkFeedGraphqlContext::new(work_feed::domain::service::WorkFeedServiceImpl::new(- work_feed::outbound::source::SoupWorkFeedSource::new(+ attention_feed::outbound::soup::SoupCandidateSource::new(soup_service.clone(),Arc::new(email_service.clone()),),- work_feed::outbound::notifications::ReaderWorkFeedNotifications::new(+ attention_feed::outbound::notifications::ReaderFeedNotifications::new(graphql_notification_reader.clone(),),- work_feed::outbound::mail::EmailWorkFeedMail::new(Arc::new(email_service.clone())),- work_feed::outbound::signals::SoupRealtimeWorkFeedSignals::new(+ attention_feed::outbound::mail::EmailFeedMail::new(Arc::new(email_service.clone())),+ attention_feed::outbound::signals::SoupRealtimeFeedSignals::new(KafkaSoupRealtimePublisher::new(macro_event_broker.clone()),),),- work_feed::outbound::triggers::RealtimeWorkFeedTriggers::new(- websocket_notification_consumer_service.clone(),- activity_realtime_service.clone(),- soup_realtime_service.clone(),- ),- complete_graph::EntityAccessWorkFeedViewers(entity_access_service.clone()),+ feed_triggers,+ feed_viewers,);let sync_sessions =