π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Split space notifications and messages
Anand Baburajan83e3816fe9e7
diff --git a/rust/bindings/wasm/ente-wasm/src/space.rs b/rust/bindings/wasm/ente-wasm/src/space.rsindex 1175f4fbc0..b109039ae2 100644--- a/rust/bindings/wasm/ente-wasm/src/space.rs+++ b/rust/bindings/wasm/ente-wasm/src/space.rs@@ -6,7 +6,7 @@ use ente_space::{DecryptedPost, DecryptedSpaceProfile, MessageConversationActivity, MessageConversationPost,MessageResponse, OpenAccountSpaceCtxInput, OpenSpaceLinkCtxInput, PostResponse,PrivateKeySource, ProfileAvatarResponse, ProfileCoverResponse, SpaceActorResponse,- SpaceError as CoreSpaceError, SpaceLinkCtx,+ SpaceError as CoreSpaceError, SpaceLinkCtx, SpaceNotificationResponse,crypto::{decode_b64, encode_b64},};use serde::{Deserialize, Serialize};@@ -231,10 +231,9 @@ struct MessagePageJs {#[serde(rename_all = "camelCase")]struct MessageConversationJs {friend: ActorJs,- latest_activity: MessageConversationActivityJs,+ latest_activity: Option<MessageConversationActivityJs>,unread: bool,unread_count: i64,- notification_unread: bool,}#[derive(Serialize)]@@ -287,6 +286,25 @@ struct MessageConversationPageJs {next_cursor: String,}+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct SpaceNotificationJs {+ id: String,+ #[serde(rename = "type")]+ notification_type: String,+ created_at: String,+ unread: bool,+ actor: ActorJs,+ post: Option<MessageConversationPostJs>,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct SpaceNotificationPageJs {+ items: Vec<SpaceNotificationJs>,+ next_cursor: String,+}+#[derive(Serialize)]#[serde(rename_all = "camelCase")]struct FriendJs {@@ -554,6 +572,23 @@ fn message_conversation_post_to_js(})}+async fn account_notification_to_js(+ ctx: &AccountSpaceCtx,+ notification: SpaceNotificationResponse,+) -> Result<SpaceNotificationJs, WasmSpaceError> {+ Ok(SpaceNotificationJs {+ id: notification.id,+ notification_type: notification.notification_type,+ created_at: notification.created_at,+ unread: notification.unread,+ actor: account_actor_to_js(ctx, notification.actor).await?,+ post: notification+ .post+ .map(message_conversation_post_to_js)+ .transpose()?,+ })+}+/// Open an authenticated space context for web.#[wasm_bindgen]pub async fn space_open_account_ctx(@@ -841,12 +876,43 @@ impl SpaceAccountCtxHandle {swb::to_value(&self.inner.unread_status().await?).map_err(Into::into)}- /// Mark notification activity for one friend as read.+ /// List post-like and friend notifications.+ pub async fn list_notifications(+ &self,+ cursor: Option<String>,+ limit: Option<i32>,+ ) -> Result<JsValue, WasmSpaceError> {+ let page = self.inner.list_notifications(cursor, limit).await?;+ let mut items = Vec::with_capacity(page.items.len());+ for notification in page.items {+ items.push(account_notification_to_js(&self.inner, notification).await?);+ }+ swb::to_value(&SpaceNotificationPageJs {+ items,+ next_cursor: page.next_cursor,+ })+ .map_err(Into::into)+ }++ /// Mark post-like and friend notifications as read.pub async fn mark_notifications_read(+ &self,+ read_at: Option<String>,+ ) -> Result<JsValue, WasmSpaceError> {+ swb::to_value(&self.inner.mark_notifications_read(read_at).await?).map_err(Into::into)+ }++ /// Mark message-like notifications as read.+ pub async fn mark_message_likes_read(&self) -> Result<JsValue, WasmSpaceError> {+ swb::to_value(&self.inner.mark_message_likes_read().await?).map_err(Into::into)+ }++ /// Mark one message conversation as read.+ pub async fn mark_message_thread_read(&self,friend_space_id: String,) -> Result<JsValue, WasmSpaceError> {- swb::to_value(&self.inner.mark_notifications_read(friend_space_id).await?)+ swb::to_value(&self.inner.mark_message_thread_read(friend_space_id).await?).map_err(Into::into)}@@ -1071,16 +1137,17 @@ impl SpaceAccountCtxHandle {let mut items = Vec::with_capacity(page.items.len());for conversation in page.items {let friend = account_actor_to_js(&self.inner, conversation.friend).await?;+ let latest_activity = match conversation.latest_activity {+ Some(activity) => {+ Some(message_conversation_activity_to_js(&self.inner, activity).await?)+ }+ None => None,+ };items.push(MessageConversationJs {friend,- latest_activity: message_conversation_activity_to_js(- &self.inner,- conversation.latest_activity,- )- .await?,+ latest_activity,unread: conversation.unread,unread_count: conversation.unread_count,- notification_unread: conversation.notification_unread,});}swb::to_value(&MessageConversationPageJs {diff --git a/rust/space/src/client.rs b/rust/space/src/client.rsindex ab7c3c9589..f58c2ef1ec 100644--- a/rust/space/src/client.rs+++ b/rust/space/src/client.rs@@ -20,14 +20,15 @@ use crate::transport::{CreatePostRequest, CreatePostResponse, CreateSpaceRequest, EntityKeyPayload, EntityKeyResponse,FriendRelationshipResponse, FriendShareResponse, FriendStatusResponse, FriendTargetPayload,LikeMessageRequest, LikeMessageResponse, LikePostRequest, LikePostResponse,- ListPostLikersResponse, MarkNotificationsReadRequest, MessageConversationPage, MessagePage,- MessageResponse, PostObjectPayload, PostPage, PostResponse, PresignUploadRequest,- PresignUploadResponse, ProfileAvatarPayload, ProfileCoverPayload, RefreshFriendSharesRequest,- RotateSpaceKeyRequest, ShareUpdatePayload, SpaceActorResponse, SpaceFriendResponse,- SpaceKeyResponse, SpaceKeyVersionResponse, SpaceLinkCreateRequest, SpaceLinkLoginRequest,- SpaceLinkLoginResponse, SpaceLinkStatusResponse, SpaceLookupResponse, SpaceProfileResponse,- SpaceUnreadStatusResponse, UpdatePostCaptionRequest, UpdateSpaceProfileRequest,- UpdateSpaceProfileResponse, UpdateSpaceSlugRequest,+ ListPostLikersResponse, MarkMessageThreadReadRequest, MarkNotificationsReadRequest,+ MessageConversationPage, MessagePage, MessageResponse, PostObjectPayload, PostPage,+ PostResponse, PresignUploadRequest, PresignUploadResponse, ProfileAvatarPayload,+ ProfileCoverPayload, RefreshFriendSharesRequest, RotateSpaceKeyRequest, ShareUpdatePayload,+ SpaceActorResponse, SpaceFriendResponse, SpaceKeyResponse, SpaceKeyVersionResponse,+ SpaceLinkCreateRequest, SpaceLinkLoginRequest, SpaceLinkLoginResponse, SpaceLinkStatusResponse,+ SpaceLookupResponse, SpaceNotificationPage, SpaceProfileResponse, SpaceUnreadStatusResponse,+ UpdatePostCaptionRequest, UpdateSpaceProfileRequest, UpdateSpaceProfileResponse,+ UpdateSpaceSlugRequest,};use ente_core::crypto::{sealed, secretbox};use ente_core::http::{Error as HttpError, HttpClient, HttpConfig};@@ -775,7 +776,45 @@ impl AccountSpaceCtx {.map_err(Into::into)}+ pub async fn list_notifications(+ &self,+ cursor: Option<String>,+ limit: Option<i32>,+ ) -> Result<SpaceNotificationPage> {+ let mut query = Vec::new();+ if let Some(value) = cursor.filter(|value| !value.trim().is_empty()) {+ query.push(("cursor", value));+ }+ if let Some(value) = limit {+ query.push(("limit", value.to_string()));+ }+ self.client+ .get_json("/space/notifications", &query)+ .await+ .map_err(Into::into)+ }+pub async fn mark_notifications_read(+ &self,+ read_at: Option<String>,+ ) -> Result<SpaceUnreadStatusResponse> {+ self.client+ .post_json(+ "/space/notifications/read",+ &MarkNotificationsReadRequest { read_at },+ )+ .await+ .map_err(Into::into)+ }++ pub async fn mark_message_likes_read(&self) -> Result<SpaceUnreadStatusResponse> {+ self.client+ .post_json("/space/messages/likes/read", &())+ .await+ .map_err(Into::into)+ }++ pub async fn mark_message_thread_read(&self,friend_space_id: impl Into<String>,) -> Result<SpaceUnreadStatusResponse> {@@ -788,7 +827,7 @@ impl AccountSpaceCtx {self.client.post_json("/space/messages/read",- &MarkNotificationsReadRequest { friend_space_id },+ &MarkMessageThreadReadRequest { friend_space_id },).await.map_err(Into::into)@@ -3400,17 +3439,62 @@ mod tests {.mock("GET", "/space/unread").match_header("x-auth-token", "token").with_status(200)- .with_body(json!({"notificationsUnread": false}).to_string())+ .with_body(+ json!({+ "notificationsUnread": false,+ "messagesUnread": false,+ "messageLikesUnread": false+ })+ .to_string(),+ ).create_async().await;let notifications_read = server+ .mock("POST", "/space/notifications/read")+ .match_header("x-auth-token", "token")+ .match_body(Matcher::JsonString(+ json!({"readAt": "2026-04-16T00:00:00Z"}).to_string(),+ ))+ .with_status(200)+ .with_body(+ json!({+ "notificationsUnread": false,+ "messagesUnread": false,+ "messageLikesUnread": false+ })+ .to_string(),+ )+ .create_async()+ .await;+ let message_likes_read = server+ .mock("POST", "/space/messages/likes/read")+ .match_header("x-auth-token", "token")+ .with_status(200)+ .with_body(+ json!({+ "notificationsUnread": false,+ "messagesUnread": false,+ "messageLikesUnread": false+ })+ .to_string(),+ )+ .create_async()+ .await;+ let thread_read = server.mock("POST", "/space/messages/read").match_header("x-auth-token", "token").match_body(Matcher::JsonString(json!({"friendSpaceId": "space_friend"}).to_string(),)).with_status(200)- .with_body(json!({"notificationsUnread": false}).to_string())+ .with_body(+ json!({+ "notificationsUnread": false,+ "messagesUnread": false,+ "messageLikesUnread": false+ })+ .to_string(),+ ).create_async().await;@@ -3419,15 +3503,31 @@ mod tests {.await.expect("unread status should load");assert!(!unread.notifications_unread);+ assert!(!unread.messages_unread);+ assert!(!unread.message_likes_unread);assert!(- !ctx.mark_notifications_read("space_friend")+ !ctx.mark_notifications_read(Some("2026-04-16T00:00:00Z".to_owned())).await.expect("notifications read").notifications_unread);+ assert!(+ !ctx.mark_message_likes_read()+ .await+ .expect("message likes read")+ .message_likes_unread+ );+ assert!(+ !ctx.mark_message_thread_read("space_friend")+ .await+ .expect("thread read")+ .messages_unread+ );status.assert_async().await;notifications_read.assert_async().await;+ message_likes_read.assert_async().await;+ thread_read.assert_async().await;}#[tokio::test]@@ -3645,6 +3745,58 @@ mod tests {likers.assert_async().await;}+ #[tokio::test]+ async fn list_notifications_uses_notifications_endpoint() {+ let mut server = Server::new_async().await;+ let ctx = test_account_ctx(&server.url());+ let notifications = server+ .mock("GET", "/space/notifications")+ .match_header("x-auth-token", "token")+ .match_query(Matcher::AllOf(vec![+ Matcher::UrlEncoded("cursor".into(), "3000:post_like:1".into()),+ Matcher::UrlEncoded("limit".into(), "10".into()),+ ]))+ .with_status(200)+ .with_body(+ json!({+ "items": [{+ "id": "post_like:42:space_liker",+ "type": "post_like",+ "createdAt": "2026-04-16T00:00:00Z",+ "unread": true,+ "actor": {+ "userId": 8,+ "spaceId": "space_liker",+ "spaceSlug": "liker"+ },+ "post": {+ "postId": 42,+ "spaceId": "space_owner",+ "spaceSlug": "owner",+ "ownerUserId": 7,+ "isDeleted": false+ }+ }],+ "nextCursor": "2000:friend_event:2"+ })+ .to_string(),+ )+ .create_async()+ .await;++ let response = ctx+ .list_notifications(Some("3000:post_like:1".to_owned()), Some(10))+ .await+ .expect("notifications should load");++ assert_eq!(response.items[0].notification_type, "post_like");+ assert_eq!(response.items[0].actor.space_id, "space_liker");+ assert!(response.items[0].unread);+ assert_eq!(response.items[0].post.as_ref().unwrap().post_id, 42);+ assert_eq!(response.next_cursor, "2000:friend_event:2");+ notifications.assert_async().await;+ }+#[tokio::test]async fn list_space_friends_uses_space_friends_endpoint() {let mut server = Server::new_async().await;diff --git a/rust/space/src/lib.rs b/rust/space/src/lib.rsindex c4b026a37c..57f91a18c3 100644--- a/rust/space/src/lib.rs+++ b/rust/space/src/lib.rs@@ -26,5 +26,6 @@ pub use transport::{PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse, ProfileCoverPayload,ProfileCoverResponse, SpaceActorResponse, SpaceFriendResponse, SpaceKeyResponse,SpaceKeyVersionResponse, SpaceLinkLoginResponse, SpaceLinkStatusResponse, SpaceLookupResponse,- SpaceProfileResponse, SpaceUnreadStatusResponse,+ SpaceNotificationPage, SpaceNotificationResponse, SpaceProfileResponse,+ SpaceUnreadStatusResponse,};diff --git a/rust/space/src/transport.rs b/rust/space/src/transport.rsindex 8304e3dd5c..24fd714954 100644--- a/rust/space/src/transport.rs+++ b/rust/space/src/transport.rs@@ -123,6 +123,13 @@ pub struct LikePostResponse {#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct MarkNotificationsReadRequest {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub read_at: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MarkMessageThreadReadRequest {pub friend_space_id: String,}@@ -130,6 +137,8 @@ pub struct MarkNotificationsReadRequest {#[serde(rename_all = "camelCase")]pub struct SpaceUnreadStatusResponse {pub notifications_unread: bool,+ pub messages_unread: bool,+ pub message_likes_unread: bool,}#[derive(Debug, Clone, Serialize)]@@ -192,13 +201,12 @@ pub struct MessagePage {#[serde(rename_all = "camelCase")]pub struct MessageConversationResponse {pub friend: SpaceActorResponse,- pub latest_activity: MessageConversationActivity,+ #[serde(default)]+ pub latest_activity: Option<MessageConversationActivity>,#[serde(default)]pub unread: bool,#[serde(default)]pub unread_count: i64,- #[serde(default)]- pub notification_unread: bool,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -238,6 +246,28 @@ pub struct MessageConversationPage {pub next_cursor: String,}+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SpaceNotificationResponse {+ pub id: String,+ #[serde(rename = "type")]+ pub notification_type: String,+ pub created_at: String,+ #[serde(default)]+ pub unread: bool,+ pub actor: SpaceActorResponse,+ #[serde(default)]+ pub post: Option<MessageConversationPost>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SpaceNotificationPage {+ pub items: Vec<SpaceNotificationResponse>,+ #[serde(default)]+ pub next_cursor: String,+}+#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct UpdatePostCaptionRequest {diff --git a/server/migrations/124_space.down.sql b/server/migrations/124_space.down.sqlindex 0fc04e9478..9c4f73ff8b 100644--- a/server/migrations/124_space.down.sql+++ b/server/migrations/124_space.down.sql@@ -24,8 +24,8 @@ DROP TABLE IF EXISTS space_posts;DROP TABLE IF EXISTS space_key_versions;-DROP TRIGGER IF EXISTS update_space_notification_read_markers_updated_at ON space_notification_read_markers;-DROP TABLE IF EXISTS space_notification_read_markers;+DROP TRIGGER IF EXISTS update_space_read_markers_updated_at ON space_read_markers;+DROP TABLE IF EXISTS space_read_markers;DROP TRIGGER IF EXISTS update_spaces_updated_at ON spaces;DROP TABLE IF EXISTS spaces;diff --git a/server/migrations/124_space.up.sql b/server/migrations/124_space.up.sqlindex 263fe38b56..01ca086576 100644--- a/server/migrations/124_space.up.sql+++ b/server/migrations/124_space.up.sql@@ -25,21 +25,28 @@ CREATE TRIGGER update_spaces_updated_atFOR EACH ROWEXECUTE PROCEDURE trigger_updated_at_microseconds_column();-CREATE TABLE IF NOT EXISTS space_notification_read_markers (- user_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,+CREATE TABLE IF NOT EXISTS space_read_markers (+ user_id BIGINT NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,viewer_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,- friend_space_id TEXT NOT NULL REFERENCES spaces (space_id) ON DELETE CASCADE,- read_at BIGINT NOT NULL DEFAULT 0,- created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),- updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),- PRIMARY KEY (viewer_space_id, friend_space_id)+ scope TEXT NOT NULL,+ friend_space_id TEXT NOT NULL DEFAULT '',+ read_at BIGINT NOT NULL DEFAULT 0,+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),+ PRIMARY KEY (viewer_space_id, scope, friend_space_id),+ CONSTRAINT chk_space_read_markers_scope CHECK (scope IN ('notifications', 'message_likes', 'message_thread')),+ CONSTRAINT chk_space_read_markers_friend_scope CHECK (+ (scope = 'message_thread' AND friend_space_id <> '')+ OR+ (scope <> 'message_thread' AND friend_space_id = '')+ ));-CREATE INDEX IF NOT EXISTS idx_space_notification_read_markers_user- ON space_notification_read_markers (user_id, read_at DESC);+CREATE INDEX IF NOT EXISTS idx_space_read_markers_user+ ON space_read_markers (user_id, scope, read_at DESC);-CREATE TRIGGER update_space_notification_read_markers_updated_at- BEFORE UPDATE ON space_notification_read_markers+CREATE TRIGGER update_space_read_markers_updated_at+ BEFORE UPDATE ON space_read_markersFOR EACH ROWEXECUTE PROCEDURE trigger_updated_at_microseconds_column();diff --git a/server/space/api/messages.go b/server/space/api/messages.goindex 9d85b64600..5602c3df6c 100644--- a/server/space/api/messages.go+++ b/server/space/api/messages.go@@ -51,6 +51,16 @@ func (h *Handlers) ListMessages(c *gin.Context) {respondJSON(c, resp, err)}+func (h *Handlers) ListNotifications(c *gin.Context) {+ var req models.ListNotificationsRequest+ if err := c.ShouldBindQuery(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ resp, err := h.Module.Messages.ListNotifications(c, req)+ respondJSON(c, resp, err)+}+func (h *Handlers) ListMessageThread(c *gin.Context) {var req models.ListMessageThreadRequestif err := c.ShouldBindQuery(&req); err != nil {diff --git a/server/space/api/read_markers.go b/server/space/api/read_markers.goindex 44c95ce2bf..8da95911d3 100644--- a/server/space/api/read_markers.go+++ b/server/space/api/read_markers.go@@ -1,6 +1,9 @@package apiimport (+ "errors"+ "io"+"github.com/ente-io/museum/ente""github.com/ente-io/museum/space/models""github.com/gin-gonic/gin"@@ -13,10 +16,25 @@ func (h *Handlers) GetUnreadStatus(c *gin.Context) {func (h *Handlers) MarkNotificationsRead(c *gin.Context) {var req models.MarkNotificationsReadRequest- if err := c.ShouldBindJSON(&req); err != nil {+ if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {respondJSON(c, nil, ente.ErrBadRequest)return}resp, err := h.Module.Read.MarkNotificationsRead(c, req)respondJSON(c, resp, err)}++func (h *Handlers) MarkMessageLikesRead(c *gin.Context) {+ resp, err := h.Module.Read.MarkMessageLikesRead(c)+ respondJSON(c, resp, err)+}++func (h *Handlers) MarkMessageThreadRead(c *gin.Context) {+ var req models.MarkMessageThreadReadRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ respondJSON(c, nil, ente.ErrBadRequest)+ return+ }+ resp, err := h.Module.Read.MarkMessageThreadRead(c, req)+ respondJSON(c, resp, err)+}diff --git a/server/space/api/register.go b/server/space/api/register.goindex cd06950a32..77c1c63a60 100644--- a/server/space/api/register.go+++ b/server/space/api/register.go@@ -17,8 +17,11 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {privateAPI.POST("/space/posts/:postID/like", handlers.TogglePostLike)privateAPI.POST("/space/posts/:postID/reply", handlers.ReplyToPost)privateAPI.DELETE("/space/posts/:postID", handlers.DeletePost)+ privateAPI.GET("/space/notifications", handlers.ListNotifications)+ privateAPI.POST("/space/notifications/read", handlers.MarkNotificationsRead)privateAPI.GET("/space/messages", handlers.ListMessages)- privateAPI.POST("/space/messages/read", handlers.MarkNotificationsRead)+ privateAPI.POST("/space/messages/likes/read", handlers.MarkMessageLikesRead)+ privateAPI.POST("/space/messages/read", handlers.MarkMessageThreadRead)privateAPI.GET("/space/messages/:spaceID", handlers.ListMessageThread)privateAPI.POST("/space/messages/:spaceID", handlers.CreateMessage)privateAPI.POST("/space/message/:messageID/like", handlers.ToggleMessageLike)diff --git a/server/space/controller/messages.go b/server/space/controller/messages.goindex de6a042292..8b913ad232 100644--- a/server/space/controller/messages.go+++ b/server/space/controller/messages.go@@ -140,17 +140,40 @@ func (c *MessagesController) List(ctx *gin.Context, req models.ListMessagesReque}items := make([]models.MessageConversationResponse, 0, len(conversations))for _, conversation := range conversations {- items = append(items, models.MessageConversationResponse{- Friend: toActorResponse(conversation.Friend, true),- LatestActivity: toMessageConversationActivityResponse(conversation.LatestActivity),- Unread: conversation.Unread,- UnreadCount: conversation.UnreadCount,- NotificationUnread: conversation.NotificationUnread,- })+ item := models.MessageConversationResponse{+ Friend: toActorResponse(conversation.Friend, true),+ Unread: conversation.Unread,+ UnreadCount: conversation.UnreadCount,+ }+ if strings.TrimSpace(conversation.LatestActivity.Type) != "" {+ latestActivity := toMessageConversationActivityResponse(conversation.LatestActivity)+ item.LatestActivity = &latestActivity+ }+ items = append(items, item)}return &models.MessageConversationPage{Items: items, NextCursor: nextCursor}, nil}+func (c *MessagesController) ListNotifications(ctx *gin.Context, req models.ListNotificationsRequest) (*models.SpaceNotificationPage, error) {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return nil, err+ }+ viewerSpace, err := c.auth.requireDefaultSpace(ctx.Request.Context(), userID)+ if err != nil {+ return nil, err+ }+ notifications, nextCursor, err := c.MessagesRepo.ListNotifications(ctx.Request.Context(), viewerSpace.SpaceID, req.Cursor, req.Limit)+ if err != nil {+ return nil, err+ }+ items := make([]models.SpaceNotificationResponse, 0, len(notifications))+ for _, notification := range notifications {+ items = append(items, toSpaceNotificationResponse(notification))+ }+ return &models.SpaceNotificationPage{Items: items, NextCursor: nextCursor}, nil+}+func (c *MessagesController) ListThread(ctx *gin.Context, targetSpaceID string, req models.ListMessageThreadRequest) (*models.MessagePage, error) {userID, err := c.auth.requireUser(ctx)if err != nil {@@ -350,23 +373,42 @@ func toMessageConversationActivityResponse(activity repo.SpaceMessageConversatioresp.Message = toMessageResponse(*activity.Message)}if activity.Post != nil {- resp.Post = &models.MessageConversationPostResponse{- PostID: activity.Post.PostID,- SpaceID: activity.Post.SpaceID,- SpaceSlug: activity.Post.SpaceSlug,- OwnerUserID: activity.Post.OwnerID,- IsDeleted: activity.Post.IsDeleted,- }- if activity.Post.ObjectKey.Valid {- resp.Post.Objects = []models.PostObjectPayload{- toPostObjectPayload(repo.SpacePostAssetRecord{- PostID: activity.Post.PostID,- ObjectKey: activity.Post.ObjectKey.String,- Size: activity.Post.ObjectSize,- Position: int(activity.Post.ObjectPosition.Int64),- MetadataCipher: activity.Post.ObjectMetadataCipher.String,- }),- }+ resp.Post = toMessageConversationPostResponse(*activity.Post)+ }+ return resp+}++func toSpaceNotificationResponse(notification repo.SpaceNotificationRecord) models.SpaceNotificationResponse {+ resp := models.SpaceNotificationResponse{+ ID: notification.ID,+ Type: notification.Type,+ CreatedAt: formatMicros(notification.CreatedAt),+ Unread: notification.Unread,+ Actor: toActorResponse(notification.Actor, true),+ }+ if notification.Post != nil {+ resp.Post = toMessageConversationPostResponse(*notification.Post)+ }+ return resp+}++func toMessageConversationPostResponse(post repo.SpaceMessageConversationPostRecord) *models.MessageConversationPostResponse {+ resp := &models.MessageConversationPostResponse{+ PostID: post.PostID,+ SpaceID: post.SpaceID,+ SpaceSlug: post.SpaceSlug,+ OwnerUserID: post.OwnerID,+ IsDeleted: post.IsDeleted,+ }+ if post.ObjectKey.Valid {+ resp.Objects = []models.PostObjectPayload{+ toPostObjectPayload(repo.SpacePostAssetRecord{+ PostID: post.PostID,+ ObjectKey: post.ObjectKey.String,+ Size: post.ObjectSize,+ Position: int(post.ObjectPosition.Int64),+ MetadataCipher: post.ObjectMetadataCipher.String,+ }),}}return respdiff --git a/server/space/controller/read_markers.go b/server/space/controller/read_markers.goindex 206f27fee8..ec99ce7219 100644--- a/server/space/controller/read_markers.go+++ b/server/space/controller/read_markers.go@@ -4,6 +4,7 @@ import ("database/sql""errors""strings"+ "time""github.com/ente-io/museum/ente""github.com/ente-io/museum/space/models"@@ -27,16 +28,88 @@ func (c *ReadMarkersController) GetUnreadStatus(ctx *gin.Context) (*models.Spaceif err != nil {return nil, err}- notificationsUnread, err := c.MessagesRepo.HasUnreadNotifications(ctx.Request.Context(), userID, viewerSpace.SpaceID)+ notificationsUnread, err := c.MessagesRepo.HasUnreadNotifications(ctx.Request.Context(), viewerSpace.SpaceID)+ if err != nil {+ return nil, err+ }+ messagesUnread, err := c.MessagesRepo.HasUnreadMessages(ctx.Request.Context(), viewerSpace.SpaceID)+ if err != nil {+ return nil, err+ }+ messageLikesUnread, err := c.MessagesRepo.HasUnreadMessageLikes(ctx.Request.Context(), viewerSpace.SpaceID)if err != nil {return nil, err}return &models.SpaceUnreadStatusResponse{NotificationsUnread: notificationsUnread,+ MessagesUnread: messagesUnread,+ MessageLikesUnread: messageLikesUnread,}, nil}func (c *ReadMarkersController) MarkNotificationsRead(ctx *gin.Context, req models.MarkNotificationsReadRequest) (*models.SpaceUnreadStatusResponse, error) {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return nil, err+ }+ viewerSpace, err := c.auth.requireDefaultSpace(ctx.Request.Context(), userID)+ if err != nil {+ return nil, err+ }+ readAt, hasReadAt, err := parseNotificationReadAt(req.ReadAt)+ if err != nil {+ return nil, err+ }+ if !hasReadAt {+ readAt, err = c.MessagesRepo.GetLatestNotificationActivityAt(ctx.Request.Context(), viewerSpace.SpaceID)+ if err != nil {+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {+ return c.GetUnreadStatus(ctx)+ }+ return nil, err+ }+ }+ if err := c.ReadMarkersRepo.UpsertNotificationsReadMarker(ctx.Request.Context(), userID, viewerSpace.SpaceID, readAt); err != nil {+ return nil, err+ }+ return c.GetUnreadStatus(ctx)+}++func parseNotificationReadAt(value string) (int64, bool, error) {+ value = strings.TrimSpace(value)+ if value == "" {+ return 0, false, nil+ }+ readAt, err := time.Parse(time.RFC3339Nano, value)+ if err != nil {+ return 0, true, ente.NewBadRequestWithMessage("invalid readAt")+ }+ return readAt.UnixMicro(), true, nil+}++func (c *ReadMarkersController) MarkMessageLikesRead(ctx *gin.Context) (*models.SpaceUnreadStatusResponse, error) {+ userID, err := c.auth.requireUser(ctx)+ if err != nil {+ return nil, err+ }+ viewerSpace, err := c.auth.requireDefaultSpace(ctx.Request.Context(), userID)+ if err != nil {+ return nil, err+ }+ readAt, err := c.MessagesRepo.GetLatestMessageLikeActivityAt(ctx.Request.Context(), viewerSpace.SpaceID)+ if err != nil {+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {+ return c.GetUnreadStatus(ctx)+ }+ return nil, err+ }+ if err := c.ReadMarkersRepo.UpsertMessageLikesReadMarker(ctx.Request.Context(), userID, viewerSpace.SpaceID, readAt); err != nil {+ return nil, err+ }+ return c.GetUnreadStatus(ctx)+}++func (c *ReadMarkersController) MarkMessageThreadRead(ctx *gin.Context, req models.MarkMessageThreadReadRequest) (*models.SpaceUnreadStatusResponse, error) {userID, err := c.auth.requireUser(ctx)if err != nil {return nil, err@@ -48,14 +121,14 @@ func (c *ReadMarkersController) MarkNotificationsRead(ctx *gin.Context, req modeif err != nil {return nil, err}- readAt, err := c.MessagesRepo.GetLatestConversationActivityAt(ctx.Request.Context(), userID, viewerSpace.SpaceID, req.FriendSpaceID)+ readAt, err := c.MessagesRepo.GetLatestMessageThreadActivityAt(ctx.Request.Context(), userID, viewerSpace.SpaceID, req.FriendSpaceID)if err != nil {if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {return nil, ente.ErrPermissionDenied}return nil, err}- if err := c.ReadMarkersRepo.UpsertNotificationReadMarker(ctx.Request.Context(), userID, viewerSpace.SpaceID, req.FriendSpaceID, readAt); err != nil {+ if err := c.ReadMarkersRepo.UpsertMessageThreadReadMarker(ctx.Request.Context(), userID, viewerSpace.SpaceID, req.FriendSpaceID, readAt); err != nil {return nil, err}return c.GetUnreadStatus(ctx)diff --git a/server/space/models/models.go b/server/space/models/models.goindex d47dfe2701..5ba27c27e1 100644--- a/server/space/models/models.go+++ b/server/space/models/models.go@@ -29,6 +29,11 @@ type ListMessagesRequest struct {Limit int `form:"limit"`}+type ListNotificationsRequest struct {+ Cursor string `form:"cursor"`+ Limit int `form:"limit"`+}+type ListMessageThreadRequest struct {Cursor string `form:"cursor"`Limit int `form:"limit"`@@ -311,11 +316,10 @@ type MessagePage struct {}type MessageConversationResponse struct {- Friend SpaceActorResponse `json:"friend"`- LatestActivity MessageConversationActivityResponse `json:"latestActivity"`- Unread bool `json:"unread"`- UnreadCount int64 `json:"unreadCount"`- NotificationUnread bool `json:"notificationUnread"`+ Friend SpaceActorResponse `json:"friend"`+ LatestActivity *MessageConversationActivityResponse `json:"latestActivity,omitempty"`+ Unread bool `json:"unread"`+ UnreadCount int64 `json:"unreadCount"`}type MessageConversationActivityResponse struct {@@ -341,6 +345,20 @@ type MessageConversationPage struct {NextCursor string `json:"nextCursor,omitempty"`}+type SpaceNotificationResponse struct {+ ID string `json:"id"`+ Type string `json:"type"`+ CreatedAt string `json:"createdAt"`+ Unread bool `json:"unread"`+ Actor SpaceActorResponse `json:"actor"`+ Post *MessageConversationPostResponse `json:"post,omitempty"`+}++type SpaceNotificationPage struct {+ Items []SpaceNotificationResponse `json:"items"`+ NextCursor string `json:"nextCursor,omitempty"`+}+type PostObjectPayload struct {ObjectKey string `json:"objectKey"`Size int64 `json:"size,omitempty"`@@ -365,9 +383,15 @@ type PostResponse struct {type SpaceUnreadStatusResponse struct {NotificationsUnread bool `json:"notificationsUnread"`+ MessagesUnread bool `json:"messagesUnread"`+ MessageLikesUnread bool `json:"messageLikesUnread"`}type MarkNotificationsReadRequest struct {+ ReadAt string `json:"readAt,omitempty"`+}++type MarkMessageThreadReadRequest struct {FriendSpaceID string `json:"friendSpaceId"`}diff --git a/server/space/repo/messages.go b/server/space/repo/messages.goindex 7af32db978..a3cea8d883 100644--- a/server/space/repo/messages.go+++ b/server/space/repo/messages.go@@ -208,8 +208,7 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intCASE WHEN m.sender_space_id = $2 THEN m.recipient_space_id ELSE m.sender_space_id END AS friend_space_id,m.message_id,NULL::bigint AS post_id,- CASE WHEN m.recipient_space_id = $2 THEN m.created_at ELSE NULL::bigint END AS notification_created_at,- FALSE AS is_outgoing+ m.sender_space_id = $2 AS is_outgoingFROM space_messages mWHERE (m.sender_space_id = $2 OR m.recipient_space_id = $2)AND (m.sender_id = $1 OR m.recipient_id = $1)@@ -225,7 +224,6 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intliker_space.space_id AS friend_space_id,m.message_id,NULL::bigint AS post_id,- ml.created_at AS notification_created_at,FALSE AS is_outgoingFROM space_message_likes mlJOIN space_messages m ON m.message_id = ml.message_id@@ -235,19 +233,6 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intAND ml.actor_space_id <> $2AND m.is_deleted = FALSE),- post_like_events AS (- SELECT- actor_space.space_id AS friend_space_id,- p.post_id,- MAX(pl.created_at) AS liked_at- FROM space_post_likes pl- JOIN space_posts p ON p.post_id = pl.post_id- JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id- WHERE p.space_id = $2- AND pl.actor_space_id <> $2- AND p.is_deleted = FALSE- GROUP BY actor_space.space_id, p.post_id- ),post_reply_events AS (SELECT DISTINCT ON (m.sender_space_id, m.reply_post_id)m.sender_space_id AS friend_space_id,@@ -264,18 +249,6 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intAND p.space_id = $2ORDER BY m.sender_space_id, m.reply_post_id, m.created_at DESC, m.message_id DESC),- post_like_candidates AS (- SELECT- 'post_like' AS activity_type,- 'post_like:' || l.post_id::text || ':' || l.friend_space_id AS activity_id,- l.liked_at AS activity_created_at,- l.friend_space_id,- NULL::text AS message_id,- l.post_id,- l.liked_at AS notification_created_at,- FALSE AS is_outgoing- FROM post_like_events l- ),post_reply_candidates AS (SELECT'post_reply' AS activity_type,@@ -284,35 +257,25 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intr.friend_space_id,r.message_id,r.post_id,- r.replied_at AS notification_created_at,FALSE AS is_outgoingFROM post_reply_events r),- friend_candidates AS (- SELECT- CASE fe.event_type- WHEN 'friend_remove' THEN 'friend_remove'- ELSE 'friend_add'- END AS activity_type,- 'friend_event:' || fe.event_id::text AS activity_id,- fe.created_at AS activity_created_at,- CASE WHEN fe.actor_space_id = $2 THEN fe.target_space_id ELSE fe.actor_space_id END AS friend_space_id,- NULL::text AS message_id,- NULL::bigint AS post_id,- CASE WHEN fe.target_space_id = $2 THEN fe.created_at ELSE NULL::bigint END AS notification_created_at,- fe.actor_space_id = $2 AS is_outgoing- FROM space_friend_events fe- WHERE (fe.target_space_id = $2 OR fe.actor_space_id = $2)- AND fe.actor_space_id <> fe.target_space_id- ),candidates AS (SELECT * FROM message_candidatesUNION ALL- SELECT * FROM post_like_candidates- UNION ALLSELECT * FROM post_reply_candidates- UNION ALL- SELECT * FROM friend_candidates+ ),+ current_friends AS (+ SELECT+ fs.friend_space_id,+ fs.created_at AS friendship_created_at+ FROM space_friend_shares fs+ WHERE fs.space_id = $2+ ),+ conversation_friends AS (+ SELECT friend_space_id FROM candidates+ UNION+ SELECT friend_space_id FROM current_friends),readable_activities AS (SELECT@@ -343,8 +306,9 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intra.friend_space_id,COUNT(*) AS unread_countFROM readable_activities ra- LEFT JOIN space_notification_read_markers nrm+ LEFT JOIN space_read_markers nrmON nrm.viewer_space_id = $2+ AND nrm.scope = 'message_thread'AND nrm.friend_space_id = ra.friend_space_idWHERE ra.readable_created_at > COALESCE(nrm.read_at, 0)GROUP BY ra.friend_space_id@@ -352,50 +316,42 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intlatest_activities AS (SELECT DISTINCT ON (friend_space_id)friend_space_id,- activity_created_at AS sort_created_at,- activity_id AS sort_id+ activity_type,+ activity_id,+ activity_created_at,+ message_id,+ post_id,+ is_outgoingFROM candidatesORDER BY friend_space_id, activity_created_at DESC, activity_id DESC),- candidates_with_read_state AS (+ conversations AS (SELECT- c.*,- COALESCE(nrm.read_at, 0) AS read_at,+ cf.friend_space_id,+ COALESCE(la.activity_type, '') AS activity_type,+ COALESCE(la.activity_id, '') AS activity_id,+ COALESCE(la.activity_created_at, 0) AS activity_created_at,+ la.message_id,+ la.post_id,+ COALESCE(la.is_outgoing, FALSE) AS is_outgoing,COALESCE(ruc.unread_count, 0) AS unread_count,- la.sort_created_at,- la.sort_id,- (- c.notification_created_at IS NOT NULL- AND c.notification_created_at > COALESCE(nrm.read_at, 0)- ) AS notification_unread- FROM candidates c- JOIN latest_activities la ON la.friend_space_id = c.friend_space_id- LEFT JOIN space_notification_read_markers nrm- ON nrm.viewer_space_id = $2- AND nrm.friend_space_id = c.friend_space_id+ COALESCE(la.activity_created_at, current_friends.friendship_created_at, 0) AS sort_created_at,+ COALESCE(la.activity_id, 'friend:' || cf.friend_space_id) AS sort_id+ FROM conversation_friends cf+ LEFT JOIN current_friends+ ON current_friends.friend_space_id = cf.friend_space_id+ LEFT JOIN latest_activities la+ ON la.friend_space_id = cf.friend_space_idLEFT JOIN readable_unread_counts ruc- ON ruc.friend_space_id = c.friend_space_id- ),- ranked AS (- SELECT- c.*,- (c.unread_count > 0) AS conversation_unread,- c.unread_count AS conversation_unread_count,- BOOL_OR(c.notification_unread) OVER (PARTITION BY c.friend_space_id) AS conversation_notification_unread,- ROW_NUMBER() OVER (- PARTITION BY c.friend_space_id- ORDER BY c.activity_created_at DESC, c.activity_id DESC- ) AS rn- FROM candidates_with_read_state c+ ON ruc.friend_space_id = cf.friend_space_id)SELECTc.activity_type,c.activity_id,c.activity_created_at,c.is_outgoing,- c.conversation_unread AS unread,- c.conversation_unread_count AS unread_count,- c.conversation_notification_unread AS notification_unread,+ (c.unread_count > 0) AS unread,+ c.unread_count AS unread_count,c.sort_created_at,c.sort_id,friend_space.owner_id,@@ -459,7 +415,7 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intasset.size AS post_object_size,asset.position AS post_object_position,asset.metadata_cipher AS post_object_metadata_cipher- FROM ranked c+ FROM conversations cJOIN spaces friend_space ON friend_space.space_id = c.friend_space_idJOIN key_attributes friend_ka ON friend_ka.user_id = friend_space.owner_idLEFT JOIN space_messages m ON m.message_id = c.message_id@@ -476,8 +432,7 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intORDER BY position ASC, asset_id ASCLIMIT 1) asset ON TRUE- WHERE c.rn = 1- AND ($3::bigint IS NULL OR (c.sort_created_at, c.sort_id) < ($3::bigint, $4::text))+ WHERE ($3::bigint IS NULL OR (c.sort_created_at, c.sort_id) < ($3::bigint, $4::text))ORDER BY c.sort_created_at DESC, c.sort_id DESCLIMIT $5`, viewerID, viewerSpaceID, cursorCreatedAt, cursorID, limit+1)@@ -504,7 +459,117 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intreturn out, nextCursor, nil}-func (r *MessagesRepository) GetLatestConversationActivityAt(ctx context.Context, viewerID int64, viewerSpaceID string, friendSpaceID string) (int64, error) {+func (r *MessagesRepository) ListNotifications(ctx context.Context, viewerSpaceID string, cursor string, limit int) ([]SpaceNotificationRecord, string, error) {+ limit = optionalInt(limit, 50)+ if limit > 100 {+ limit = 100+ }+ var cursorCreatedAt any+ var cursorID any+ if createdAt, id, ok := parseMessageCursor(cursor); ok {+ cursorCreatedAt = createdAt+ cursorID = id+ }+ rows, err := r.DB.QueryContext(ctx, `+ WITH notification_candidates AS (+ SELECT+ 'post_like' AS activity_type,+ 'post_like:' || pl.post_id::text || ':' || pl.actor_space_id AS activity_id,+ pl.created_at AS activity_created_at,+ pl.actor_space_id AS actor_space_id,+ pl.post_id+ FROM space_post_likes pl+ JOIN space_posts p ON p.post_id = pl.post_id+ WHERE p.space_id = $1+ AND pl.actor_space_id <> $1+ AND p.is_deleted = FALSE++ UNION ALL++ SELECT+ CASE fe.event_type+ WHEN 'friend_remove' THEN 'friend_remove'+ ELSE 'friend_add'+ END AS activity_type,+ 'friend_event:' || fe.event_id::text AS activity_id,+ fe.created_at AS activity_created_at,+ fe.actor_space_id AS actor_space_id,+ NULL::bigint AS post_id+ FROM space_friend_events fe+ WHERE fe.target_space_id = $1+ AND fe.actor_space_id <> fe.target_space_id+ )+ SELECT+ n.activity_type,+ n.activity_id,+ n.activity_created_at,+ n.activity_created_at > COALESCE(nrm.read_at, 0) AS unread,+ n.activity_created_at AS sort_created_at,+ n.activity_id AS sort_id,+ actor_space.owner_id,+ actor_space.space_id,+ actor_space.space_slug,+ actor_ka.public_key,+ actor_space.current_version,+ actor_space.encrypted_profile,+ actor_space.avatar_object_key,+ actor_space.avatar_size,+ actor_space.updated_at,+ (SELECT COUNT(*) FROM space_friend_shares fs WHERE fs.space_id = actor_space.space_id) AS actor_friends,+ (SELECT COUNT(*) FROM space_posts ap WHERE ap.space_id = actor_space.space_id AND ap.is_deleted = FALSE) AS actor_posts,+ p.post_id,+ COALESCE(p.space_id, '') AS post_space_id,+ COALESCE(post_space.space_slug, '') AS post_space_slug,+ COALESCE(p.owner_id, 0) AS post_owner_id,+ COALESCE(p.is_deleted, FALSE) AS post_is_deleted,+ asset.object_key AS post_object_key,+ asset.size AS post_object_size,+ asset.position AS post_object_position,+ asset.metadata_cipher AS post_object_metadata_cipher+ FROM notification_candidates n+ JOIN spaces actor_space ON actor_space.space_id = n.actor_space_id+ JOIN key_attributes actor_ka ON actor_ka.user_id = actor_space.owner_id+ LEFT JOIN space_read_markers nrm+ ON nrm.viewer_space_id = $1+ AND nrm.scope = 'notifications'+ AND nrm.friend_space_id = ''+ LEFT JOIN space_posts p ON p.post_id = n.post_id+ LEFT JOIN spaces post_space ON post_space.space_id = p.space_id+ LEFT JOIN LATERAL (+ SELECT object_key, size, position, metadata_cipher+ FROM space_post_assets+ WHERE post_id = p.post_id AND p.is_deleted = FALSE+ ORDER BY position ASC, asset_id ASC+ LIMIT 1+ ) asset ON TRUE+ WHERE ($2::bigint IS NULL OR (n.activity_created_at, n.activity_id) < ($2::bigint, $3::text))+ ORDER BY n.activity_created_at DESC, n.activity_id DESC+ LIMIT $4+ `, strings.TrimSpace(viewerSpaceID), cursorCreatedAt, cursorID, limit+1)+ if err != nil {+ return nil, "", stacktrace.Propagate(err, "")+ }+ defer rows.Close()+ out := make([]SpaceNotificationRecord, 0, limit+1)+ for rows.Next() {+ notification, err := scanSpaceNotificationRecord(rows)+ if err != nil {+ return nil, "", err+ }+ out = append(out, *notification)+ }+ if err := rows.Err(); err != nil {+ return nil, "", stacktrace.Propagate(err, "")+ }+ nextCursor := ""+ if len(out) > limit {+ nextCursor = formatSpaceNotificationCursor(out[limit-1])+ out = out[:limit]+ }+ return out, nextCursor, nil+}++func (r *MessagesRepository) GetLatestMessageThreadActivityAt(ctx context.Context, viewerID int64, viewerSpaceID string, friendSpaceID string) (int64, error) {var activityCreatedAt int64if err := r.DB.QueryRowContext(ctx, `WITH candidates AS (@@ -514,116 +579,148 @@ func (r *MessagesRepository) GetLatestConversationActivityAt(ctx context.ContextCASE WHEN m.sender_space_id = $1 THEN m.recipient_space_id ELSE m.sender_space_id END AS friend_space_idFROM space_messages mWHERE (m.sender_space_id = $1 OR m.recipient_space_id = $1)+ AND (m.sender_id = $3 OR m.recipient_id = $3)AND m.is_deleted = FALSE- AND NOT (m.kind = 'post_reply' AND m.recipient_space_id = $1)-- UNION ALL-- SELECT- ml.created_at AS activity_created_at,- 'message_like:' || ml.message_id || ':' || ml.actor_space_id AS activity_id,- liker_space.space_id AS friend_space_id- FROM space_message_likes ml- JOIN space_messages m ON m.message_id = ml.message_id- JOIN spaces liker_space ON liker_space.space_id = ml.actor_space_id- WHERE m.sender_space_id = $1- AND m.recipient_space_id = ml.actor_space_id- AND ml.actor_space_id <> $1- AND m.is_deleted = FALSE-- UNION ALL+ )+ SELECT c.activity_created_at+ FROM candidates c+ WHERE c.friend_space_id = $2+ ORDER BY c.activity_created_at DESC, c.activity_id DESC+ LIMIT 1+ `, strings.TrimSpace(viewerSpaceID), strings.TrimSpace(friendSpaceID), viewerID).Scan(&activityCreatedAt); err != nil {+ return 0, stacktrace.Propagate(err, "")+ }+ return activityCreatedAt, nil+}+func (r *MessagesRepository) GetLatestNotificationActivityAt(ctx context.Context, viewerSpaceID string) (int64, error) {+ var activityCreatedAt int64+ if err := r.DB.QueryRowContext(ctx, `+ WITH notification_candidates AS (SELECTpl.created_at AS activity_created_at,- 'post_like:' || pl.post_id::text || ':' || pl.actor_space_id AS activity_id,- actor_space.space_id AS friend_space_id+ 'post_like:' || pl.post_id::text || ':' || pl.actor_space_id AS activity_idFROM space_post_likes plJOIN space_posts p ON p.post_id = pl.post_id- JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_idWHERE p.space_id = $1AND pl.actor_space_id <> $1AND p.is_deleted = FALSEUNION ALL- SELECT- m.created_at AS activity_created_at,- 'post_reply:' || m.message_id AS activity_id,- m.sender_space_id AS friend_space_id- FROM space_messages m- JOIN space_posts p ON p.post_id = m.reply_post_id- WHERE m.recipient_space_id = $1- AND m.sender_space_id <> $1- AND m.kind = 'post_reply'- AND m.is_deleted = FALSE- AND m.reply_post_id IS NOT NULL- AND p.space_id = $1-- UNION ALL-SELECTfe.created_at AS activity_created_at,- 'friend_event:' || fe.event_id::text AS activity_id,- CASE WHEN fe.actor_space_id = $1 THEN fe.target_space_id ELSE fe.actor_space_id END AS friend_space_id+ 'friend_event:' || fe.event_id::text AS activity_idFROM space_friend_events fe- WHERE (fe.target_space_id = $1 OR fe.actor_space_id = $1)+ WHERE fe.target_space_id = $1AND fe.actor_space_id <> fe.target_space_id-)SELECT c.activity_created_at- FROM candidates c- WHERE c.friend_space_id = $2+ FROM notification_candidates cORDER BY c.activity_created_at DESC, c.activity_id DESCLIMIT 1- `, strings.TrimSpace(viewerSpaceID), strings.TrimSpace(friendSpaceID)).Scan(&activityCreatedAt); err != nil {+ `, strings.TrimSpace(viewerSpaceID)).Scan(&activityCreatedAt); err != nil {return 0, stacktrace.Propagate(err, "")}return activityCreatedAt, nil}-func (r *MessagesRepository) HasUnreadNotifications(ctx context.Context, viewerID int64, viewerSpaceID string) (bool, error) {+func (r *MessagesRepository) GetLatestMessageLikeActivityAt(ctx context.Context, viewerSpaceID string) (int64, error) {+ var activityCreatedAt int64+ if err := r.DB.QueryRowContext(ctx, `+ SELECT ml.created_at+ FROM space_message_likes ml+ JOIN space_messages m ON m.message_id = ml.message_id+ WHERE m.sender_space_id = $1+ AND m.recipient_space_id = ml.actor_space_id+ AND ml.actor_space_id <> $1+ AND m.is_deleted = FALSE+ ORDER BY ml.created_at DESC, ml.message_id DESC, ml.actor_space_id DESC+ LIMIT 1+ `, strings.TrimSpace(viewerSpaceID)).Scan(&activityCreatedAt); err != nil {+ return 0, stacktrace.Propagate(err, "")+ }+ return activityCreatedAt, nil+}++func (r *MessagesRepository) HasUnreadNotifications(ctx context.Context, viewerSpaceID string) (bool, error) {var exists boolif err := r.DB.QueryRowContext(ctx, `WITH notification_candidates AS (SELECT- m.sender_space_id AS friend_space_id,- m.created_at AS notification_created_at- FROM space_messages m- WHERE m.recipient_space_id = $1- AND m.sender_space_id <> $1- AND m.kind = 'regular'- AND m.is_deleted = FALSE+ pl.created_at AS notification_created_at+ FROM space_post_likes pl+ JOIN space_posts p ON p.post_id = pl.post_id+ WHERE p.space_id = $1+ AND pl.actor_space_id <> $1+ AND p.is_deleted = FALSEUNION ALLSELECT- liker_space.space_id AS friend_space_id,- ml.created_at AS notification_created_at+ fe.created_at AS notification_created_at+ FROM space_friend_events fe+ WHERE fe.target_space_id = $1+ AND fe.actor_space_id <> fe.target_space_id+ )+ SELECT EXISTS (+ SELECT 1+ FROM notification_candidates c+ LEFT JOIN space_read_markers nrm+ ON nrm.viewer_space_id = $1+ AND nrm.scope = 'notifications'+ AND nrm.friend_space_id = ''+ WHERE c.notification_created_at > COALESCE(nrm.read_at, 0)+ LIMIT 1+ )+ `, strings.TrimSpace(viewerSpaceID)).Scan(&exists); err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ return exists, nil+}++func (r *MessagesRepository) HasUnreadMessageLikes(ctx context.Context, viewerSpaceID string) (bool, error) {+ var exists bool+ if err := r.DB.QueryRowContext(ctx, `+ SELECT EXISTS (+ SELECT 1FROM space_message_likes mlJOIN space_messages m ON m.message_id = ml.message_id- JOIN spaces liker_space ON liker_space.space_id = ml.actor_space_id+ LEFT JOIN space_read_markers nrm+ ON nrm.viewer_space_id = $1+ AND nrm.scope = 'message_likes'+ AND nrm.friend_space_id = ''WHERE m.sender_space_id = $1AND m.recipient_space_id = ml.actor_space_idAND ml.actor_space_id <> $1AND m.is_deleted = FALSE+ AND ml.created_at > COALESCE(nrm.read_at, 0)+ LIMIT 1+ )+ `, strings.TrimSpace(viewerSpaceID)).Scan(&exists); err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ return exists, nil+}- UNION ALL-+func (r *MessagesRepository) HasUnreadMessages(ctx context.Context, viewerSpaceID string) (bool, error) {+ var exists bool+ if err := r.DB.QueryRowContext(ctx, `+ WITH readable_activities AS (SELECT- actor_space.space_id AS friend_space_id,- pl.created_at AS notification_created_at- FROM space_post_likes pl- JOIN space_posts p ON p.post_id = pl.post_id- JOIN spaces actor_space ON actor_space.space_id = pl.actor_space_id- WHERE p.space_id = $1- AND pl.actor_space_id <> $1- AND p.is_deleted = FALSE+ m.sender_space_id AS friend_space_id,+ m.created_at AS readable_created_at+ FROM space_messages m+ WHERE m.recipient_space_id = $1+ AND m.sender_space_id <> $1+ AND m.kind = 'regular'+ AND m.is_deleted = FALSEUNION ALLSELECTm.sender_space_id AS friend_space_id,- m.created_at AS notification_created_at+ m.created_at AS readable_created_atFROM space_messages mJOIN space_posts p ON p.post_id = m.reply_post_idWHERE m.recipient_space_id = $1@@ -632,23 +729,15 @@ func (r *MessagesRepository) HasUnreadNotifications(ctx context.Context, viewerIAND m.is_deleted = FALSEAND m.reply_post_id IS NOT NULLAND p.space_id = $1-- UNION ALL-- SELECT- fe.actor_space_id AS friend_space_id,- fe.created_at AS notification_created_at- FROM space_friend_events fe- WHERE fe.target_space_id = $1- AND fe.actor_space_id <> fe.target_space_id)SELECT EXISTS (SELECT 1- FROM notification_candidates c- LEFT JOIN space_notification_read_markers nrm+ FROM readable_activities ra+ LEFT JOIN space_read_markers nrmON nrm.viewer_space_id = $1- AND nrm.friend_space_id = c.friend_space_id- WHERE c.notification_created_at > COALESCE(nrm.read_at, 0)+ AND nrm.scope = 'message_thread'+ AND nrm.friend_space_id = ra.friend_space_id+ WHERE ra.readable_created_at > COALESCE(nrm.read_at, 0)LIMIT 1)`, strings.TrimSpace(viewerSpaceID)).Scan(&exists); err != nil {@@ -700,7 +789,6 @@ func scanMessageConversationRecord(scanner interface{ Scan(dest ...any) error })&rec.LatestActivity.Outgoing,&rec.Unread,&rec.UnreadCount,- &rec.NotificationUnread,&rec.SortCreatedAt,&rec.SortID,}@@ -748,6 +836,40 @@ func scanMessageConversationRecord(scanner interface{ Scan(dest ...any) error })return &rec, nil}+func scanSpaceNotificationRecord(scanner interface{ Scan(dest ...any) error }) (*SpaceNotificationRecord, error) {+ var rec SpaceNotificationRecord+ var postID sql.NullInt64+ var post SpaceMessageConversationPostRecord+ dest := []any{+ &rec.Type,+ &rec.ID,+ &rec.CreatedAt,+ &rec.Unread,+ &rec.SortCreatedAt,+ &rec.SortID,+ }+ dest = append(dest, spaceActorScanDest(&rec.Actor)...)+ dest = append(dest,+ &postID,+ &post.SpaceID,+ &post.SpaceSlug,+ &post.OwnerID,+ &post.IsDeleted,+ &post.ObjectKey,+ &post.ObjectSize,+ &post.ObjectPosition,+ &post.ObjectMetadataCipher,+ )+ if err := scanner.Scan(dest...); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ if postID.Valid {+ post.PostID = postID.Int64+ rec.Post = &post+ }+ return &rec, nil+}+func parseMessageCursor(cursor string) (int64, string, bool) {createdAtText, id, ok := strings.Cut(strings.TrimSpace(cursor), ":")if !ok || strings.TrimSpace(id) == "" {@@ -768,5 +890,15 @@ func formatMessageConversationCursor(conversation SpaceMessageConversationRecordif conversation.SortCreatedAt > 0 && strings.TrimSpace(conversation.SortID) != "" {return strconv.FormatInt(conversation.SortCreatedAt, 10) + ":" + conversation.SortID}+ if conversation.LatestActivity.CreatedAt <= 0 || strings.TrimSpace(conversation.LatestActivity.ID) == "" {+ return ""+ }return strconv.FormatInt(conversation.LatestActivity.CreatedAt, 10) + ":" + conversation.LatestActivity.ID}++func formatSpaceNotificationCursor(notification SpaceNotificationRecord) string {+ if notification.SortCreatedAt > 0 && strings.TrimSpace(notification.SortID) != "" {+ return strconv.FormatInt(notification.SortCreatedAt, 10) + ":" + notification.SortID+ }+ return strconv.FormatInt(notification.CreatedAt, 10) + ":" + notification.ID+}diff --git a/server/space/repo/module.go b/server/space/repo/module.goindex 7d42b32afe..4c675107d1 100644--- a/server/space/repo/module.go+++ b/server/space/repo/module.go@@ -140,13 +140,23 @@ type SpaceMessageRecord struct {}type SpaceMessageConversationRecord struct {- Friend SpaceActorRecord- LatestActivity SpaceMessageConversationActivityRecord- Unread bool- UnreadCount int64- NotificationUnread bool- SortCreatedAt int64- SortID string+ Friend SpaceActorRecord+ LatestActivity SpaceMessageConversationActivityRecord+ Unread bool+ UnreadCount int64+ SortCreatedAt int64+ SortID string+}++type SpaceNotificationRecord struct {+ ID string+ Type string+ CreatedAt int64+ Unread bool+ Actor SpaceActorRecord+ Post *SpaceMessageConversationPostRecord+ SortCreatedAt int64+ SortID string}type SpaceMessageConversationActivityRecord struct {diff --git a/server/space/repo/module_test.go b/server/space/repo/module_test.goindex d9c871da7b..7dec7538a5 100644--- a/server/space/repo/module_test.go+++ b/server/space/repo/module_test.go@@ -168,7 +168,7 @@ func TestSpaceMessagesThreadAndConversations(t *testing.T) {require.Error(t, err)}-func TestSpaceMessageConversationsUseLatestActivity(t *testing.T) {+func TestSpaceMessageConversationsAndNotificationsUseSplitActivity(t *testing.T) {ctx := context.Background()module := newSpaceTestModule(t)@@ -188,9 +188,17 @@ func TestSpaceMessageConversationsUseLatestActivity(t *testing.T) {require.Empty(t, nextCursor)require.Len(t, conversations, 1)require.Equal(t, bobSpace.SpaceID, conversations[0].Friend.SpaceID)- require.Equal(t, "friend_add", conversations[0].LatestActivity.Type)- require.Nil(t, conversations[0].LatestActivity.Message)- require.Nil(t, conversations[0].LatestActivity.Post)+ require.Empty(t, conversations[0].LatestActivity.Type)+ require.False(t, conversations[0].Unread)+ require.Equal(t, int64(0), conversations[0].UnreadCount)++ notifications, nextCursor, err := module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.Empty(t, nextCursor)+ require.Len(t, notifications, 1)+ require.Equal(t, bobSpace.SpaceID, notifications[0].Actor.SpaceID)+ require.Equal(t, "friend_add", notifications[0].Type)+ require.Nil(t, notifications[0].Post)bobMessage, err := module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{Kind: "regular",@@ -207,6 +215,7 @@ func TestSpaceMessageConversationsUseLatestActivity(t *testing.T) {conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)+ require.Len(t, conversations, 1)require.Equal(t, "message", conversations[0].LatestActivity.Type)require.Equal(t, bobMessage.MessageID, conversations[0].LatestActivity.Message.MessageID)@@ -244,10 +253,13 @@ func TestSpaceMessageConversationsUseLatestActivity(t *testing.T) {conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)- require.Equal(t, "post_like", conversations[0].LatestActivity.Type)- require.NotNil(t, conversations[0].LatestActivity.Post)- require.Equal(t, postID, conversations[0].LatestActivity.Post.PostID)- require.Equal(t, "activity-post-object", conversations[0].LatestActivity.Post.ObjectKey.String)+ require.Equal(t, "message_like", conversations[0].LatestActivity.Type)+ notifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "post_like", notifications[0].Type)+ require.NotNil(t, notifications[0].Post)+ require.Equal(t, postID, notifications[0].Post.PostID)+ require.Equal(t, "activity-post-object", notifications[0].Post.ObjectKey.String)postReply, err := module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{Kind: "post_reply",@@ -306,10 +318,13 @@ func TestSpaceMessageConversationsUseLatestActivity(t *testing.T) {require.Equal(t, replyOnlyPostID, conversations[0].LatestActivity.Post.PostID)require.True(t, conversations[0].LatestActivity.Post.IsDeleted)require.False(t, conversations[0].LatestActivity.Post.ObjectKey.Valid)- latestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)+ latestActivityAt, err := module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)require.NoError(t, err)require.Equal(t, int64(5500), latestActivityAt)- notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messagesUnread)+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.True(t, notificationsUnread)@@ -318,12 +333,14 @@ func TestSpaceMessageConversationsUseLatestActivity(t *testing.T) {conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)- require.Equal(t, "friend_remove", conversations[0].LatestActivity.Type)- require.Nil(t, conversations[0].LatestActivity.Message)- require.Nil(t, conversations[0].LatestActivity.Post)+ require.Equal(t, "post_reply", conversations[0].LatestActivity.Type)+ notifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "friend_remove", notifications[0].Type)+ require.Equal(t, bobSpace.SpaceID, notifications[0].Actor.SpaceID)}-func TestSpaceFriendEventsCreateConversationForBothSides(t *testing.T) {+func TestSpaceFriendEventsCreateNotificationsForTarget(t *testing.T) {ctx := context.Background()module := newSpaceTestModule(t)@@ -341,51 +358,63 @@ func TestSpaceFriendEventsCreateConversationForBothSides(t *testing.T) {require.NoError(t, err)require.Len(t, aliceConversations, 1)require.Equal(t, bobSpace.SpaceID, aliceConversations[0].Friend.SpaceID)- require.Equal(t, "friend_add", aliceConversations[0].LatestActivity.Type)- require.False(t, aliceConversations[0].LatestActivity.Outgoing)+ require.Empty(t, aliceConversations[0].LatestActivity.Type)require.False(t, aliceConversations[0].Unread)- require.True(t, aliceConversations[0].NotificationUnread)+ require.Equal(t, int64(0), aliceConversations[0].UnreadCount)bobConversations, _, err := module.Messages.ListConversations(ctx, bobID, bobSpace.SpaceID, "", 10)require.NoError(t, err)require.Len(t, bobConversations, 1)require.Equal(t, aliceSpace.SpaceID, bobConversations[0].Friend.SpaceID)- require.Equal(t, "friend_add", bobConversations[0].LatestActivity.Type)- require.True(t, bobConversations[0].LatestActivity.Outgoing)- require.False(t, bobConversations[0].Unread)- require.False(t, bobConversations[0].NotificationUnread)+ require.Empty(t, bobConversations[0].LatestActivity.Type)- aliceUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ aliceNotifications, _, err := module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.Len(t, aliceNotifications, 1)+ require.Equal(t, "friend_add", aliceNotifications[0].Type)+ require.Equal(t, bobSpace.SpaceID, aliceNotifications[0].Actor.SpaceID)+ require.True(t, aliceNotifications[0].Unread)+ bobNotifications, _, err := module.Messages.ListNotifications(ctx, bobSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.Empty(t, bobNotifications)++ aliceUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.True(t, aliceUnread)- bobUnread, err := module.Messages.HasUnreadNotifications(ctx, bobID, bobSpace.SpaceID)+ bobUnread, err := module.Messages.HasUnreadNotifications(ctx, bobSpace.SpaceID)require.NoError(t, err)require.False(t, bobUnread)- bobLatestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)+ aliceLatestActivityAt, err := module.Messages.GetLatestNotificationActivityAt(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.Equal(t, int64(1000), aliceLatestActivityAt)+ require.NoError(t, module.Read.UpsertNotificationsReadMarker(ctx, aliceID, aliceSpace.SpaceID, aliceLatestActivityAt))+ aliceUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)- require.Equal(t, int64(1000), bobLatestActivityAt)+ require.False(t, aliceUnread)+ aliceNotifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.Len(t, aliceNotifications, 1)+ require.False(t, aliceNotifications[0].Unread)require.NoError(t, module.Friends.DeleteFriendship(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID))setFriendEventCreatedAt(t, module, 2000, "friend_remove", bobID, aliceID)aliceConversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)- require.Len(t, aliceConversations, 1)- require.Equal(t, "friend_remove", aliceConversations[0].LatestActivity.Type)- require.False(t, aliceConversations[0].LatestActivity.Outgoing)- require.False(t, aliceConversations[0].Unread)- require.True(t, aliceConversations[0].NotificationUnread)+ require.Empty(t, aliceConversations)bobConversations, _, err = module.Messages.ListConversations(ctx, bobID, bobSpace.SpaceID, "", 10)require.NoError(t, err)- require.Len(t, bobConversations, 1)- require.Equal(t, "friend_remove", bobConversations[0].LatestActivity.Type)- require.True(t, bobConversations[0].LatestActivity.Outgoing)- require.False(t, bobConversations[0].Unread)- require.False(t, bobConversations[0].NotificationUnread)- bobLatestActivityAt, err = module.Messages.GetLatestConversationActivityAt(ctx, bobID, bobSpace.SpaceID, aliceSpace.SpaceID)+ require.Empty(t, bobConversations)+ aliceNotifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.Len(t, aliceNotifications, 2)+ require.Equal(t, "friend_remove", aliceNotifications[0].Type)+ require.True(t, aliceNotifications[0].Unread)+ require.False(t, aliceNotifications[1].Unread)+ aliceLatestActivityAt, err = module.Messages.GetLatestNotificationActivityAt(ctx, aliceSpace.SpaceID)require.NoError(t, err)- require.Equal(t, int64(2000), bobLatestActivityAt)+ require.Equal(t, int64(2000), aliceLatestActivityAt)}func TestSpaceMessageConversationPreviewUsesLatestActivityWithSeparateUnreadState(t *testing.T) {@@ -432,22 +461,37 @@ func TestSpaceMessageConversationPreviewUsesLatestActivityWithSeparateUnreadStatrequire.NoError(t, err)require.Len(t, conversations, 1)require.True(t, conversations[0].Unread)- require.True(t, conversations[0].NotificationUnread)require.Equal(t, "message_like", conversations[0].LatestActivity.Type)require.Equal(t, aliceOldMessage.MessageID, conversations[0].LatestActivity.Message.MessageID)require.Equal(t, int64(3000), conversations[0].SortCreatedAt)+ messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messagesUnread)+ messageLikesUnread, err := module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messageLikesUnread)- latestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)+ latestActivityAt, err := module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)require.NoError(t, err)- require.Equal(t, int64(3000), latestActivityAt)- require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))+ require.Equal(t, int64(2000), latestActivityAt)+ require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)require.False(t, conversations[0].Unread)- require.False(t, conversations[0].NotificationUnread)require.Equal(t, "message_like", conversations[0].LatestActivity.Type)require.Equal(t, aliceOldMessage.MessageID, conversations[0].LatestActivity.Message.MessageID)+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messagesUnread)+ messageLikesUnread, err = module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messageLikesUnread)++ require.NoError(t, module.Read.UpsertMessageLikesReadMarker(ctx, aliceID, aliceSpace.SpaceID, 3000))+ messageLikesUnread, err = module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messageLikesUnread)}func TestSpaceModuleLifecycle(t *testing.T) {@@ -1365,7 +1409,7 @@ func TestListFeedCursorUsesCreatedAtSortOrder(t *testing.T) {require.Empty(t, nextCursor)}-func TestSpaceReadMarkersDriveNotificationState(t *testing.T) {+func TestSpaceReadMarkersDriveSplitUnreadState(t *testing.T) {ctx := context.Background()module := newSpaceTestModule(t)@@ -1395,16 +1439,27 @@ func TestSpaceReadMarkersDriveNotificationState(t *testing.T) {require.Len(t, conversations, 1)require.True(t, conversations[0].Unread)require.Equal(t, int64(1), conversations[0].UnreadCount)- notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.True(t, notificationsUnread)+ messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messagesUnread)- require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, 2000))+ require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, 2000))conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)require.False(t, conversations[0].Unread)require.Equal(t, int64(0), conversations[0].UnreadCount)- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, notificationsUnread)+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messagesUnread)++ require.NoError(t, module.Read.UpsertNotificationsReadMarker(ctx, aliceID, aliceSpace.SpaceID, 500))+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.False(t, notificationsUnread)@@ -1425,12 +1480,15 @@ func TestSpaceReadMarkersDriveNotificationState(t *testing.T) {require.Equal(t, outgoing.MessageID, conversations[0].LatestActivity.Message.MessageID)require.False(t, conversations[0].Unread)require.Equal(t, int64(0), conversations[0].UnreadCount)- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.False(t, notificationsUnread)+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messagesUnread)}-func TestSpaceNotificationReadMarkersArePerFriend(t *testing.T) {+func TestSpaceReadMarkersUseThreadAndGlobalScopes(t *testing.T) {ctx := context.Background()module := newSpaceTestModule(t)@@ -1506,31 +1564,51 @@ func TestSpaceNotificationReadMarkersArePerFriend(t *testing.T) {charlieConversation := conversationBySpaceID(charlieSpace.SpaceID)require.True(t, charlieConversation.Unread)require.Equal(t, int64(1), charlieConversation.UnreadCount)- notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.True(t, notificationsUnread)+ messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messagesUnread)+ messageLikesUnread, err := module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messageLikesUnread)- bobLatestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)+ bobLatestActivityAt, err := module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)require.NoError(t, err)- require.Equal(t, int64(1002), bobLatestActivityAt)- require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, bobLatestActivityAt))+ require.Equal(t, int64(1001), bobLatestActivityAt)+ require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, bobLatestActivityAt))bobConversation = conversationBySpaceID(bobSpace.SpaceID)require.False(t, bobConversation.Unread)require.Equal(t, int64(0), bobConversation.UnreadCount)charlieConversation = conversationBySpaceID(charlieSpace.SpaceID)require.True(t, charlieConversation.Unread)require.Equal(t, int64(1), charlieConversation.UnreadCount)- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)require.NoError(t, err)- require.True(t, notificationsUnread)+ require.True(t, messagesUnread)+ messageLikesUnread, err = module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messageLikesUnread)- require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, charlieSpace.SpaceID, 2000))- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, charlieSpace.SpaceID, 2000))+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messagesUnread)+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, notificationsUnread)+ require.NoError(t, module.Read.UpsertNotificationsReadMarker(ctx, aliceID, aliceSpace.SpaceID, 200))+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.False(t, notificationsUnread)+ require.NoError(t, module.Read.UpsertMessageLikesReadMarker(ctx, aliceID, aliceSpace.SpaceID, 1002))+ messageLikesUnread, err = module.Messages.HasUnreadMessageLikes(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messageLikesUnread)}-func TestUnreadNotificationsTrackReadableActivityWithoutChangingLatestPreview(t *testing.T) {+func TestUnreadScopesTrackReadableActivityWithoutChangingLatestPreview(t *testing.T) {ctx := context.Background()module := newSpaceTestModule(t)@@ -1575,24 +1653,28 @@ func TestUnreadNotificationsTrackReadableActivityWithoutChangingLatestPreview(trequire.Equal(t, int64(2000), conversations[0].SortCreatedAt)require.True(t, conversations[0].Unread)require.Equal(t, int64(1), conversations[0].UnreadCount)- require.True(t, conversations[0].NotificationUnread)- notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notificationsUnread, err := module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.True(t, notificationsUnread)+ messagesUnread, err := module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messagesUnread)- latestActivityAt, err := module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)+ latestActivityAt, err := module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)require.NoError(t, err)require.Equal(t, int64(2000), latestActivityAt)- require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))+ require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)require.Equal(t, outgoing.MessageID, conversations[0].LatestActivity.Message.MessageID)require.False(t, conversations[0].Unread)require.Equal(t, int64(0), conversations[0].UnreadCount)- require.False(t, conversations[0].NotificationUnread)- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)- require.False(t, notificationsUnread)+ require.True(t, notificationsUnread)+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messagesUnread)alicePostID, err := module.Posts.CreatePost(ctx, aliceID, aliceSpace.SpaceID, "alice-post-key", nil, aliceSpace.CurrentVersion, nil)require.NoError(t, err)@@ -1621,10 +1703,12 @@ func TestUnreadNotificationsTrackReadableActivityWithoutChangingLatestPreview(trequire.Equal(t, int64(4000), conversations[0].SortCreatedAt)require.False(t, conversations[0].Unread)require.Equal(t, int64(0), conversations[0].UnreadCount)- require.True(t, conversations[0].NotificationUnread)- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.True(t, notificationsUnread)+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messagesUnread)incomingPostReply, err := module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{Kind: "post_reply",@@ -1660,37 +1744,53 @@ func TestUnreadNotificationsTrackReadableActivityWithoutChangingLatestPreview(trequire.Equal(t, int64(5001), conversations[0].SortCreatedAt)require.True(t, conversations[0].Unread)require.Equal(t, int64(2), conversations[0].UnreadCount)- require.True(t, conversations[0].NotificationUnread)- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.True(t, notificationsUnread)+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, messagesUnread)setPostLikeCreatedAt(t, module, 6000, alicePostID, bobSpace.SpaceID)conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)- require.Equal(t, "post_like", conversations[0].LatestActivity.Type)- require.Equal(t, alicePostID, conversations[0].LatestActivity.Post.PostID)- require.Equal(t, int64(6000), conversations[0].SortCreatedAt)+ require.Equal(t, "post_reply", conversations[0].LatestActivity.Type)+ require.Equal(t, secondIncomingPostReply.MessageID, conversations[0].LatestActivity.Message.MessageID)+ require.Equal(t, int64(5001), conversations[0].SortCreatedAt)require.True(t, conversations[0].Unread)require.Equal(t, int64(2), conversations[0].UnreadCount)- require.True(t, conversations[0].NotificationUnread)- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ notifications, _, err := module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "post_like", notifications[0].Type)+ require.Equal(t, alicePostID, notifications[0].Post.PostID)+ require.Equal(t, int64(6000), notifications[0].CreatedAt)+ require.True(t, notifications[0].Unread)+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.True(t, notificationsUnread)- latestActivityAt, err = module.Messages.GetLatestConversationActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)+ latestActivityAt, err = module.Messages.GetLatestMessageThreadActivityAt(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID)require.NoError(t, err)- require.Equal(t, int64(6000), latestActivityAt)- require.NoError(t, module.Read.UpsertNotificationReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))+ require.Equal(t, int64(5001), latestActivityAt)+ require.NoError(t, module.Read.UpsertMessageThreadReadMarker(ctx, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, latestActivityAt))conversations, _, err = module.Messages.ListConversations(ctx, aliceID, aliceSpace.SpaceID, "", 10)require.NoError(t, err)require.False(t, conversations[0].Unread)require.Equal(t, int64(0), conversations[0].UnreadCount)- require.False(t, conversations[0].NotificationUnread)- notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceID, aliceSpace.SpaceID)+ messagesUnread, err = module.Messages.HasUnreadMessages(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.False(t, messagesUnread)+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)+ require.NoError(t, err)+ require.True(t, notificationsUnread)+ require.NoError(t, module.Read.UpsertNotificationsReadMarker(ctx, aliceID, aliceSpace.SpaceID, 6000))+ notificationsUnread, err = module.Messages.HasUnreadNotifications(ctx, aliceSpace.SpaceID)require.NoError(t, err)require.False(t, notificationsUnread)+ notifications, _, err = module.Messages.ListNotifications(ctx, aliceSpace.SpaceID, "", 10)+ require.NoError(t, err)+ require.False(t, notifications[0].Unread)}func TestListPostLikersPaginates(t *testing.T) {diff --git a/server/space/repo/read_markers.go b/server/space/repo/read_markers.goindex dca356051b..368cf99f21 100644--- a/server/space/repo/read_markers.go+++ b/server/space/repo/read_markers.go@@ -7,20 +7,48 @@ import ("github.com/ente-io/stacktrace")-func (r *ReadMarkersRepository) UpsertNotificationReadMarker(ctx context.Context, userID int64, viewerSpaceID string, friendSpaceID string, readAt int64) error {+const (+ readScopeNotifications = "notifications"+ readScopeMessageLikes = "message_likes"+ readScopeMessageThread = "message_thread"+)++func (r *ReadMarkersRepository) UpsertNotificationsReadMarker(ctx context.Context, userID int64, viewerSpaceID string, readAt int64) error {+ return r.upsertReadMarker(ctx, userID, viewerSpaceID, "", readScopeNotifications, readAt)+}++func (r *ReadMarkersRepository) UpsertMessageLikesReadMarker(ctx context.Context, userID int64, viewerSpaceID string, readAt int64) error {+ return r.upsertReadMarker(ctx, userID, viewerSpaceID, "", readScopeMessageLikes, readAt)+}++func (r *ReadMarkersRepository) UpsertMessageThreadReadMarker(ctx context.Context, userID int64, viewerSpaceID string, friendSpaceID string, readAt int64) error {+ return r.upsertReadMarker(ctx, userID, viewerSpaceID, friendSpaceID, readScopeMessageThread, readAt)+}++func (r *ReadMarkersRepository) upsertReadMarker(ctx context.Context, userID int64, viewerSpaceID string, friendSpaceID string, scope string, readAt int64) error {viewerSpaceID = strings.TrimSpace(viewerSpaceID)friendSpaceID = strings.TrimSpace(friendSpaceID)- if userID <= 0 || viewerSpaceID == "" || friendSpaceID == "" || readAt <= 0 {+ scope = strings.TrimSpace(scope)+ if userID <= 0 || viewerSpaceID == "" || scope == "" || readAt <= 0 {+ return nil+ }+ if scope == readScopeMessageThread && friendSpaceID == "" {+ return nil+ }+ if scope != readScopeMessageThread {+ friendSpaceID = ""+ }+ if scope == readScopeMessageThread && friendSpaceID == viewerSpaceID {return nil}_, err := r.DB.ExecContext(ctx, `- INSERT INTO space_notification_read_markers (user_id, viewer_space_id, friend_space_id, read_at)- VALUES ($1, $2, $3, $4)- ON CONFLICT (viewer_space_id, friend_space_id) DO UPDATE+ INSERT INTO space_read_markers (user_id, viewer_space_id, scope, friend_space_id, read_at)+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (viewer_space_id, scope, friend_space_id) DO UPDATESET read_at = GREATEST(- space_notification_read_markers.read_at,+ space_read_markers.read_at,EXCLUDED.read_at)- `, userID, viewerSpaceID, friendSpaceID, readAt)+ `, userID, viewerSpaceID, scope, friendSpaceID, readAt)return stacktrace.Propagate(err, "")}diff --git a/web/apps/space/src/components/SpaceMessagesPage.tsx b/web/apps/space/src/components/SpaceMessagesPage.tsxindex 23d5b5722f..07da76b349 100644--- a/web/apps/space/src/components/SpaceMessagesPage.tsx+++ b/web/apps/space/src/components/SpaceMessagesPage.tsx@@ -10,6 +10,7 @@ import {loadCurrentMessageConversations,loadCurrentMessageThread,loadCurrentSpaceFriends,+ markCurrentMessageLikesRead,markCurrentMessagesRead,replyToCurrentMessage,sendCurrentMessage,@@ -107,9 +108,6 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({React.useState(true);const [isThreadLoading, setIsThreadLoading] = React.useState(false);const [messages, setMessages] = React.useState<SpaceMessage[]>([]);- const [newConversationIds, setNewConversationIds] = React.useState<- string[]- >([]);const selectedFriendSpaceIdRef = React.useRef<string | undefined>(undefined,);@@ -163,18 +161,10 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({Boolean(selectedFriend) && !isSelectedFriendCurrent;const markConversationRead = React.useCallback((spaceId: string) => {- setNewConversationIds((currentIds) =>- currentIds.filter((id) => id != spaceId),- );setConversations((currentConversations) => {return currentConversations.map((conversation) =>conversationId(conversation) == spaceId- ? {- ...conversation,- notificationUnread: false,- unread: false,- unreadCount: 0,- }+ ? { ...conversation, unread: false, unreadCount: 0 }: conversation,);});@@ -187,29 +177,7 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({setIsConversationsLoading(true);void loadCurrentMessageConversations().then((page) => {- const unreadConversationIds = page.items- .filter((conversation) => conversation.notificationUnread)- .map(conversationId);- const passiveUnreadConversationIds = page.items- .filter(- (conversation) =>- conversation.notificationUnread &&- !conversation.unread,- )- .map(conversationId);- setNewConversationIds(unreadConversationIds);setConversations(page.items);- if (passiveUnreadConversationIds.length == 0) return;- void Promise.all(- passiveUnreadConversationIds.map((spaceId) =>- markCurrentMessagesRead(spaceId),- ),- ).catch((error: unknown) =>- console.warn(- "Failed to mark passive message activity read",- error,- ),- );}).catch((error: unknown) =>console.error("Failed to load message conversations", error),@@ -290,6 +258,9 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({React.useEffect(() => {if (!profile) return;refreshConversations();+ void markCurrentMessageLikesRead().catch((error: unknown) =>+ console.warn("Failed to mark message likes read", error),+ );}, [profile, refreshConversations]);React.useEffect(() => {@@ -306,6 +277,12 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({React.useEffect(() => {if (!selectedSpaceId || !selectedConversation) return;+ if (+ !selectedConversation.unread &&+ selectedConversation.unreadCount <= 0+ ) {+ return;+ }if (markedReadSpaceIdRef.current == selectedSpaceId) return;markedReadSpaceIdRef.current = selectedSpaceId;@@ -386,7 +363,6 @@ export const SpaceMessagesPage: React.FC<SpaceMessagesPageProps> = ({isThreadLoading={isThreadLoading}isThreadReadOnly={isThreadReadOnly}messages={messages}- newConversationIds={newConversationIds}onBack={() => void router.push(spaceRoutes.home)}onCloseThread={closeConversation}onOpenSelectedFriendProfile={(friend) =>diff --git a/web/apps/space/src/components/SpaceNotificationsPage.tsx b/web/apps/space/src/components/SpaceNotificationsPage.tsxnew file mode 100644index 0000000000..e70838ebbb--- /dev/null+++ b/web/apps/space/src/components/SpaceNotificationsPage.tsx@@ -0,0 +1,94 @@+import { SpacePageMeta } from "components/SpacePageMeta";+import { SpaceRouteFallback } from "components/SpaceRouteFallback";+import { useRouter } from "next/router";+import React from "react";+import {+ NotificationsScreen,+ notificationsBackground,+} from "screens/NotificationsScreen";+import {+ createCurrentProfileLink,+ loadCurrentNotifications,+ markCurrentNotificationsRead,+ type SpaceNotification,+} from "services/space";+import { useSpaceAppState } from "state/spaceAppState";+import { spaceRoutes } from "utils/spaceRoutes";++export const SpaceNotificationsPage: React.FC = () => {+ const router = useRouter();+ const { profile, profileLoadError, profileLoadStatus } = useSpaceAppState();+ const [notifications, setNotifications] = React.useState<+ SpaceNotification[]+ >([]);+ const [isLoading, setIsLoading] = React.useState(true);++ React.useEffect(() => {+ if (profileLoadStatus == "ready" && !profile) {+ void router.replace(spaceRoutes.onboarding);+ }+ }, [profile, profileLoadStatus, router]);++ React.useEffect(() => {+ if (!profile) return;++ let cancelled = false;+ setIsLoading(true);+ void loadCurrentNotifications()+ .then((page) => {+ if (cancelled) return;+ setNotifications(page.items);+ const latestUnread = page.items.find(+ (notification) => notification.unread,+ );+ if (latestUnread) {+ void markCurrentNotificationsRead(+ latestUnread.createdAt,+ ).catch((error: unknown) =>+ console.warn(+ "Failed to mark space notifications read",+ error,+ ),+ );+ }+ })+ .catch((error: unknown) =>+ console.error("Failed to load space notifications", error),+ )+ .finally(() => {+ if (!cancelled) setIsLoading(false);+ });++ return () => {+ cancelled = true;+ };+ }, [profile]);++ if (profileLoadStatus != "ready" || !profile) {+ return (+ <SpaceRouteFallback+ background={notificationsBackground}+ message={profileLoadError}+ />+ );+ }++ return (+ <>+ <SpacePageMeta+ themeColor={notificationsBackground}+ title="Notifications | Ente Space"+ />+ <NotificationsScreen+ isLoading={isLoading}+ notifications={notifications}+ onBack={() => void router.push(spaceRoutes.home)}+ onShareProfileLink={async () => {+ if (!profile.spaceId) throw new Error("Missing space.");+ return (await createCurrentProfileLink(profile.spaceId))+ .url;+ }}+ />+ </>+ );+};diff --git a/web/apps/space/src/pages/app/index.tsx b/web/apps/space/src/pages/app/index.tsxindex 7ed37da0aa..fb3f50ce43 100644--- a/web/apps/space/src/pages/app/index.tsx+++ b/web/apps/space/src/pages/app/index.tsx@@ -44,6 +44,8 @@ const Page: React.FC = () => {const [feedItems, setFeedItems] = useState<SpacePost[]>([]);const [feedNextCursor, setFeedNextCursor] = useState<string>();const [hasUnreadMessages, setHasUnreadMessages] = useState<boolean>();+ const [hasUnreadNotifications, setHasUnreadNotifications] =+ useState<boolean>();const [isFeedLoading, setIsFeedLoading] = useState(true);const [isFeedLoadingMore, setIsFeedLoadingMore] = useState(false);const isInitialFeedLoading =@@ -84,6 +86,7 @@ const Page: React.FC = () => {setFeedItems([]);setFeedNextCursor(undefined);setHasUnreadMessages(false);+ setHasUnreadNotifications(false);setIsFeedLoading(false);setIsFeedLoadingMore(false);setSkipNextHomeFeedSkeleton(false);@@ -94,6 +97,7 @@ const Page: React.FC = () => {setFeedItems([]);setFeedNextCursor(undefined);setHasUnreadMessages(undefined);+ setHasUnreadNotifications(undefined);setIsFeedLoading(true);setIsFeedLoadingMore(false);void loadCurrentFeedPage()@@ -116,7 +120,11 @@ const Page: React.FC = () => {void loadCurrentUnreadStatus().then((unreadStatus) => {if (!cancelled) {- setHasUnreadMessages(unreadStatus.messagesUnread);+ setHasUnreadMessages(+ unreadStatus.messagesUnread ||+ unreadStatus.messageLikesUnread,+ );+ setHasUnreadNotifications(unreadStatus.notificationsUnread);}}).catch((error: unknown) =>@@ -200,6 +208,7 @@ const Page: React.FC = () => {friendsCount={friends.length}addedFriendToastName={addedFriendToastName}hasUnreadMessages={hasUnreadMessages}+ hasUnreadNotifications={hasUnreadNotifications}hasMoreFeedItems={Boolean(feedNextCursor)}isFeedLoading={isSkippingInitialFeedSkeleton ? false : isFeedLoading@@ -288,6 +297,9 @@ const Page: React.FC = () => {onLoadPostAvatar={loadCurrentSpacePostAvatarURL}onLoadPostImage={loadCurrentSpacePostAssetURL}onOpenMessages={() => void router.push(spaceRoutes.messages)}+ onOpenNotifications={() =>+ void router.push(spaceRoutes.notifications)+ }onOpenProfile={profile? () => void router.push(spaceRoutes.profile)diff --git a/web/apps/space/src/pages/app/notifications.tsx b/web/apps/space/src/pages/app/notifications.tsxnew file mode 100644index 0000000000..108a9dd0fe--- /dev/null+++ b/web/apps/space/src/pages/app/notifications.tsx@@ -0,0 +1,6 @@+import { SpaceNotificationsPage } from "components/SpaceNotificationsPage";+import React from "react";++const Page: React.FC = () => <SpaceNotificationsPage />;++export default Page;diff --git a/web/apps/space/src/screens/FriendsScreen.tsx b/web/apps/space/src/screens/FriendsScreen.tsxindex b11280f7ba..5e41fa5bff 100644--- a/web/apps/space/src/screens/FriendsScreen.tsx+++ b/web/apps/space/src/screens/FriendsScreen.tsx@@ -643,7 +643,7 @@ export const FriendsScreen: React.FC<FriendsScreenProps> = ({onClick={openInviteDialog}sx={{alignItems: "center",- bgcolor: "#E8E8E8",+ bgcolor: "#F2F2F2",border: 0,borderRadius: "18px",color: textBase,@@ -669,7 +669,7 @@ export const FriendsScreen: React.FC<FriendsScreenProps> = ({outlineOffset: 2,},"&:hover": onShareProfileLink- ? { bgcolor: "#DEDEDE" }+ ? { bgcolor: "#E8E8E8" }: undefined,}}>diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsxindex 34bd0d9a36..988aa43b5c 100644--- a/web/apps/space/src/screens/HomeScreen.tsx+++ b/web/apps/space/src/screens/HomeScreen.tsx@@ -1,7 +1,7 @@import {- BubbleChatIcon,FavouriteIcon,MultiplicationSignIcon,+ SentIcon,UserCheck01Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";@@ -56,12 +56,15 @@ const textSecondary = "#6B6B6B";const dangerColor = "#F63A3A";const headerActionSize = spaceTouchTargetSize;const headerAvatarSize = 27;+const headerAvatarBorderGap = 1;+const headerAvatarBorderColor = "#757575";+const headerIconStrokeWidth = 1.8;const feedAvatarSize = 38;const headerHeight = 64;const headerIconSize = 30;const headerHideStartY = 96;const headerScrollDelta = 4;-const headerSideWidth = 32;+const headerSideWidth = 76;const feedLikeActionSize = spaceTouchTargetSize;const feedActionIconSize = 20;const feedReplyIconSize = 17;@@ -108,6 +111,7 @@ interface HomeScreenProps {friendsCount: number;hasMoreFeedItems?: boolean;hasUnreadMessages?: boolean;+ hasUnreadNotifications?: boolean;isFeedLoading?: boolean;isFeedLoadingMore?: boolean;localFeedPosts?: LocalSpaceFeedPost[];@@ -122,6 +126,7 @@ interface HomeScreenProps {onLoadPostImage?: SpacePostAssetURLLoader;onOpenFriend?: (friendID: string) => void;onOpenMessages?: () => void;+ onOpenNotifications?: () => void;onOpenProfile?: () => void;onReplyToPost?: (postId: number, text: string) => Promise<void>;onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;@@ -1282,6 +1287,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({friendsCount,hasMoreFeedItems = false,hasUnreadMessages,+ hasUnreadNotifications,isFeedLoading = false,isFeedLoadingMore = false,localFeedPosts = [],@@ -1293,6 +1299,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({onLoadPostImage,onOpenFriend,onOpenMessages,+ onOpenNotifications,onOpenProfile,onReplyToPost,onSetPostLiked,@@ -1345,7 +1352,8 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({localFeedPosts.length > 0 || remoteFeedItems.length > 0;const isEmptyFeedLoading = !hasFeedItems && isFeedLoading;const showFeedCards = hasFeedItems;- const showUnreadIndicator = hasUnreadMessages === true;+ const showMessagesUnreadIndicator = hasUnreadMessages === true;+ const showNotificationsUnreadIndicator = hasUnreadNotifications === true;const emptyFeedMessage =friendsCount == 0? "When you add friends, their posts will appear here."@@ -1840,7 +1848,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({justifyContent: "center",lineHeight: 0,ml: "-6px",- overflow: "hidden",+ overflow: "visible",p: 0,placeSelf: "center start",width: headerActionSize,@@ -1856,10 +1864,11 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({alignItems: "center",bgcolor: feedSkeletonElementBackground,borderRadius: "50%",+ boxShadow: `0 0 0 ${headerAvatarBorderGap}px ${homeBackground}, 0 0 0 ${headerAvatarBorderGap + headerIconStrokeWidth}px ${headerAvatarBorderColor}`,display: "flex",height: headerAvatarSize,justifyContent: "center",- overflow: "hidden",+ overflow: "visible",width: headerAvatarSize,}}>@@ -1906,81 +1915,113 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({<EnteLogo height={18} /></Box><Box- component="button"- type="button"- aria-label={- showUnreadIndicator- ? "Open messages with unread activity"- : "Open messages"- }- onClick={onOpenMessages}sx={{- appearance: "none",- alignItems: "center",- bgcolor: "transparent",- border: 0,- boxSizing: "border-box",- color: textBase,- cursor: onOpenMessages ? "pointer" : "default",display: "flex",- fontSize: 0,- height: headerActionSize,- justifyContent: "center",+ gap: "2px",justifySelf: "end",- lineHeight: 0,mr: "-6px",- p: 0,- position: "relative",- width: headerActionSize,- "& svg": { display: "block" },- "&:focus-visible": {- borderRadius: "50%",- outline: `2px solid ${green}`,- outlineOffset: 2,- },}}>- <HugeiconsIcon- icon={BubbleChatIcon}- size={headerIconSize}- strokeWidth={1.5}- />- {showUnreadIndicator && (- <Box- aria-hidden- sx={{- "@keyframes spaceUnreadBadgePing": {- "75%, 100%": {- opacity: 0,- transform: "scale(2.5)",+ {[+ {+ ariaLabel: showNotificationsUnreadIndicator+ ? "Open notifications with unread activity"+ : "Open notifications",+ icon: FavouriteIcon,+ key: "notifications",+ onClick: onOpenNotifications,+ showUnread: showNotificationsUnreadIndicator,+ },+ {+ ariaLabel: showMessagesUnreadIndicator+ ? "Open messages with unread activity"+ : "Open messages",+ icon: SentIcon,+ key: "messages",+ onClick: onOpenMessages,+ showUnread: showMessagesUnreadIndicator,+ },+ ].map(+ ({ ariaLabel, icon, key, onClick, showUnread }) => (+ <Box+ key={key}+ component="button"+ type="button"+ aria-label={ariaLabel}+ onClick={onClick}+ sx={{+ appearance: "none",+ alignItems: "center",+ bgcolor: "transparent",+ border: 0,+ boxSizing: "border-box",+ color: textBase,+ cursor: onClick ? "pointer" : "default",+ display: "flex",+ fontSize: 0,+ height: headerActionSize,+ justifyContent: "center",+ lineHeight: 0,+ p: 0,+ position: "relative",+ width: headerActionSize,+ "& svg": { display: "block" },+ "&:focus-visible": {+ borderRadius: "50%",+ outline: `2px solid ${green}`,+ outlineOffset: 2,},- },- "@media (prefers-reduced-motion: reduce)": {- "&::after": { display: "none" },- },- bgcolor: dangerColor,- border: `2px solid ${homeBackground}`,- borderRadius: "50%",- height: 13,- position: "absolute",- right: 7,- top: 7,- width: 13,- zIndex: 0,- "&::after": {- animation:- "spaceUnreadBadgePing 1.25s cubic-bezier(0, 0, 0.2, 1) 1",- bgcolor: dangerColor,- borderRadius: "50%",- content: '""',- inset: 0,- opacity: 0.75,- pointerEvents: "none",- position: "absolute",- zIndex: -1,- },- }}- />+ }}+ >+ <HugeiconsIcon+ icon={icon}+ size={headerIconSize}+ strokeWidth={headerIconStrokeWidth}+ />+ {showUnread && (+ <Box+ aria-hidden+ sx={{+ "@keyframes spaceUnreadBadgePing":+ {+ "75%, 100%": {+ opacity: 0,+ transform:+ "scale(2.5)",+ },+ },+ "@media (prefers-reduced-motion: reduce)":+ {+ "&::after": {+ display: "none",+ },+ },+ bgcolor: dangerColor,+ border: `2px solid ${homeBackground}`,+ borderRadius: "50%",+ height: 13,+ position: "absolute",+ right: 5,+ top: 6,+ width: 13,+ zIndex: 0,+ "&::after": {+ animation:+ "spaceUnreadBadgePing 1.25s cubic-bezier(0, 0, 0.2, 1) 1",+ bgcolor: dangerColor,+ borderRadius: "50%",+ content: '""',+ inset: 0,+ opacity: 0.75,+ pointerEvents: "none",+ position: "absolute",+ zIndex: -1,+ },+ }}+ />+ )}+ </Box>+ ),)}</Box></Box>diff --git a/web/apps/space/src/screens/MessagesScreen.tsx b/web/apps/space/src/screens/MessagesScreen.tsxindex 20058c6268..c27512d6b1 100644--- a/web/apps/space/src/screens/MessagesScreen.tsx+++ b/web/apps/space/src/screens/MessagesScreen.tsx@@ -5,6 +5,7 @@ import {} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { Box, Menu, MenuItem, Skeleton, Tooltip } from "@mui/material";+import { SpaceInviteFriendsDialog } from "components/SpaceInviteFriendsDialog";import { SpaceLoadingSpinner } from "components/SpaceRouteFallback";import { formatTimeAgo } from "ente-base/date";import React from "react";@@ -66,7 +67,6 @@ interface MessagesScreenProps {onSendMessage: (spaceId: string, text: string) => Promise<void>;onSetMessageLiked: (messageId: string, liked: boolean) => Promise<void>;onShareProfileLink?: () => Promise<string>;- newConversationIds?: string[];profile: SetupProfile;selectedFriend?: SpaceMessageConversation["friend"];}@@ -205,15 +205,7 @@ const conversationPreview = (profile: SetupProfile,) => {const activity = conversation.latestActivity;- if (activity.type == "friend_add") {- return "You're now friends";- }- if (activity.type == "friend_remove") {- return activity.outgoing- ? "You're no longer friends"- : "Removed you as a friend";- }- if (activity.type == "post_like") return "Liked your post";+ if (!activity) return "No messages yet";if (activity.type == "post_reply") {return "Replied";}@@ -235,6 +227,7 @@ const conversationPreview = (const quotedConversationActivityPreview = (activity: SpaceMessageConversation["latestActivity"],) => {+ if (!activity) return undefined;const text = activity.message?.text.trim();if (!text) return undefined;const previewText = truncateMessageText(text);@@ -254,10 +247,12 @@ const ConversationPreviewLine: React.FC<{}> = ({ conversation, profile }) => {const activity = conversation.latestActivity;const quotedPreview = quotedConversationActivityPreview(activity);+ const isEmptyConversation = !activity;const previewLineSx = {color: textSecondary,fontFamily: '"Inter Variable", Inter, sans-serif',fontSize: 13,+ fontStyle: isEmptyConversation ? "italic" : "normal",fontWeight: 500,lineHeight: "18px",minWidth: 0,@@ -303,8 +298,6 @@ const conversationId = (conversation: SpaceMessageConversation) =>const conversationUnreadLabel = (count: number) =>count > 99 ? "99+" : String(count);-const dayMs = 24 * 60 * 60 * 1000;-const ConversationListItem: React.FC<{conversation: SpaceMessageConversation;onOpenThread: (conversation: SpaceMessageConversation) => void;@@ -312,10 +305,11 @@ const ConversationListItem: React.FC<{}> = ({ conversation, onOpenThread, profile }) => {const name =conversation.friend.fullName.trim() || conversation.friend.username;- const timestampLabel = formatTimeAgo(- microsForTimestamp(conversation.latestActivity.createdAtMs),- );- const postThumbnailUrl = conversation.latestActivity.post?.imageUrl;+ const latestActivity = conversation.latestActivity;+ const timestampLabel = latestActivity+ ? formatTimeAgo(microsForTimestamp(latestActivity.createdAtMs))+ : undefined;+ const postThumbnailUrl = latestActivity?.post?.imageUrl;const unreadCount = conversation.unreadCount;return (@@ -415,39 +409,43 @@ const ConversationListItem: React.FC<{>{firstNameFrom(name)}</Box>- <Box- aria-hidden- component="span"- sx={{- color: textSecondary,- flexShrink: 0,- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 12,- fontWeight: 600,- lineHeight: "16px",- }}- >- ·- </Box>- <Box- component="time"- dateTime={new Date(- conversation.latestActivity.createdAtMs,- ).toISOString()}- sx={{- color: textSecondary,- flexShrink: 0,- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 12,- fontWeight: 600,- lineHeight: "16px",- whiteSpace: "nowrap",- }}- >- {timestampLabel}- </Box>+ {timestampLabel && (+ <>+ <Box+ aria-hidden+ component="span"+ sx={{+ color: textSecondary,+ flexShrink: 0,+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 12,+ fontWeight: 600,+ lineHeight: "16px",+ }}+ >+ ·+ </Box>+ <Box+ component="time"+ dateTime={new Date(+ latestActivity!.createdAtMs,+ ).toISOString()}+ sx={{+ color: textSecondary,+ flexShrink: 0,+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 12,+ fontWeight: 600,+ lineHeight: "16px",+ whiteSpace: "nowrap",+ }}+ >+ {timestampLabel}+ </Box>+ </>+ )}</Box><ConversationPreviewLineconversation={conversation}@@ -474,50 +472,6 @@ const ConversationListItem: React.FC<{);};-interface ConversationSectionItem {- conversations: SpaceMessageConversation[];- title: string;-}--const ConversationSection: React.FC<{- conversations: SpaceMessageConversation[];- onOpenThread: (conversation: SpaceMessageConversation) => void;- profile: SetupProfile;- title: string;-}> = ({ conversations, onOpenThread, profile, title }) => {- if (conversations.length == 0) return null;-- return (- <Box component="section" sx={{ mb: "10px" }}>- <Box- component="h2"- sx={{- color: textSecondary,- fontFamily: '"Inter Variable", Inter, sans-serif',- fontSize: 13,- fontWeight: 700,- lineHeight: "18px",- m: 0,- pb: "4px",- pt: "12px",- }}- >- {title}- </Box>- <Box component="ul" sx={{ listStyle: "none", m: 0, p: 0 }}>- {conversations.map((conversation) => (- <ConversationListItem- key={conversationId(conversation)}- conversation={conversation}- onOpenThread={onOpenThread}- profile={profile}- />- ))}- </Box>- </Box>- );-};-const sameMessageSender = (first: SpaceMessage | undefined,second: SpaceMessage | undefined,@@ -1130,7 +1084,6 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({isThreadLoading = false,isThreadReadOnly = false,messages,- newConversationIds = [],onBack,onCloseThread,onDeleteMessage,@@ -1152,6 +1105,11 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({const [sendPhase, setSendPhase] = React.useState<"idle" | "sending">("idle",);+ const [isInviteDialogOpen, setIsInviteDialogOpen] = React.useState(false);+ const [isInviteSharing, setIsInviteSharing] = React.useState(false);+ const [inviteShareError, setInviteShareError] = React.useState<+ string | null+ >(null);const composerRef = React.useRef<HTMLTextAreaElement | null>(null);const threadScrollRef = React.useRef<HTMLDivElement | null>(null);const stickToThreadBottomRef = React.useRef(true);@@ -1176,57 +1134,6 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({() => new Map(messages.map((message) => [message.id, message])),[messages],);- const groupedConversations = React.useMemo(() => {- const newIds = new Set(newConversationIds);- const now = Date.now();- const today = new Date(now);- const startOfTodayMs = new Date(- today.getFullYear(),- today.getMonth(),- today.getDate(),- ).getTime();- const startOfYesterdayMs = new Date(- today.getFullYear(),- today.getMonth(),- today.getDate() - 1,- ).getTime();- const nextSections: ConversationSectionItem[] = [- { title: "New", conversations: [] },- { title: "Today", conversations: [] },- { title: "Yesterday", conversations: [] },- { title: "Last 7 days", conversations: [] },- { title: "Last 30 days", conversations: [] },- { title: "Older", conversations: [] },- ];- for (const conversation of conversations) {- if (newIds.has(conversationId(conversation))) {- nextSections[0]!.conversations.push(conversation);- continue;- }-- const activityCreatedAtMs = conversation.latestActivity.createdAtMs;- if (activityCreatedAtMs >= startOfTodayMs) {- nextSections[1]!.conversations.push(conversation);- continue;- }- if (activityCreatedAtMs >= startOfYesterdayMs) {- nextSections[2]!.conversations.push(conversation);- continue;- }-- const ageMs = Math.max(0, now - activityCreatedAtMs);- if (ageMs <= 7 * dayMs) {- nextSections[3]!.conversations.push(conversation);- continue;- }- if (ageMs <= 30 * dayMs) {- nextSections[4]!.conversations.push(conversation);- continue;- }- nextSections[5]!.conversations.push(conversation);- }- return nextSections;- }, [conversations, newConversationIds]);const isContextMessageLiked = Boolean(messageContextMenu?.message.viewerLiked,);@@ -1276,21 +1183,45 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({currentMenu?.open ? currentMenu : null,);- const shareProfileLink = async () => {- if (!onShareProfileLink) return;- const profileLink = await onShareProfileLink();+ const openInviteDialog = () => {+ setInviteShareError(null);+ setIsInviteDialogOpen(true);+ };- if (typeof navigator.share == "function") {- try {- await navigator.share({ url: profileLink });- return;- } catch (error) {- if (error instanceof DOMException && error.name == "AbortError")+ const closeInviteDialog = () => {+ if (isInviteSharing) return;+ setIsInviteDialogOpen(false);+ };++ const shareInviteLink = async () => {+ if (!onShareProfileLink || isInviteSharing) return;+ setIsInviteSharing(true);+ setInviteShareError(null);++ try {+ const profileLink = await onShareProfileLink();+ if (typeof navigator.share == "function") {+ try {+ await navigator.share({ url: profileLink });+ setIsInviteDialogOpen(false);return;+ } catch (error) {+ if (+ error instanceof DOMException &&+ error.name == "AbortError"+ )+ return;+ }}- }- await copyTextToClipboard(profileLink);+ await copyTextToClipboard(profileLink);+ setIsInviteDialogOpen(false);+ } catch (error) {+ console.error("Failed to share space invite", error);+ setInviteShareError("Couldn't share invite. Please try again.");+ } finally {+ setIsInviteSharing(false);+ }};const handleMessageAction = (@@ -2143,15 +2074,15 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({maxWidth: 260,}}>- {showInviteEmptyState- ? "No messages yet. Invite people to start conversations here."- : "No messages yet."}+ No messages yet. Once you add friends,+ you'll see their messages and replies+ to your posts here.</Box>{showInviteEmptyState && (<Boxcomponent="button"type="button"- onClick={() => void shareProfileLink()}+ onClick={openInviteDialog}sx={{alignItems: "center",bgcolor: "#F2F2F2",@@ -2179,7 +2110,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({}}><ShareIcon />- Invite people+ Invite friends</Box>)}</Box>@@ -2191,13 +2122,12 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({p: "6px 16px 28px",}}>- {groupedConversations.map((section) => (- <ConversationSection- key={section.title}- conversations={section.conversations}+ {conversations.map((conversation) => (+ <ConversationListItem+ key={conversationId(conversation)}+ conversation={conversation}onOpenThread={onOpenThread}profile={profile}- title={section.title}/>))}</Box>@@ -2205,6 +2135,13 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({</>)}</Box>+ <SpaceInviteFriendsDialog+ errorMessage={inviteShareError}+ open={isInviteDialogOpen}+ sharing={isInviteSharing}+ onClose={closeInviteDialog}+ onShare={() => void shareInviteLink()}+ /></Box>);};diff --git a/web/apps/space/src/screens/NotificationsScreen.tsx b/web/apps/space/src/screens/NotificationsScreen.tsxnew file mode 100644index 0000000000..bde5525106--- /dev/null+++ b/web/apps/space/src/screens/NotificationsScreen.tsx@@ -0,0 +1,506 @@+import { ArrowLeft02Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { Box } from "@mui/material";+import { SpaceInviteFriendsDialog } from "components/SpaceInviteFriendsDialog";+import { SpaceLoadingSpinner } from "components/SpaceRouteFallback";+import { formatTimeAgo } from "ente-base/date";+import React from "react";+import { ShareIcon } from "screens/ShareProfileLinkScreen";+import type { SpaceNotification } from "services/space";+import { spaceTouchTargetSize } from "styles/touchTargets";++export const notificationsBackground = "#FFFFFF";++const green = "#08C225";+const avatarSkeletonBackground = "#E6E6E6";+const textBase = "#000000";+const textSecondary = "#777777";+const rowHover = "#F6F6F6";+const dayMs = 24 * 60 * 60 * 1000;++interface NotificationsScreenProps {+ isLoading?: boolean;+ notifications: SpaceNotification[];+ onBack?: () => void;+ onShareProfileLink?: () => Promise<string>;+}++interface NotificationSection {+ items: SpaceNotification[];+ title: string;+}++interface NotificationGroup {+ actors: SpaceNotification["actor"][];+ createdAtMs: number;+ id: string;+ post?: SpaceNotification["post"];+ type: SpaceNotification["type"];+}++const fullName = (actor: SpaceNotification["actor"]) =>+ actor.fullName.trim() || actor.username.trim() || "Someone";++const actorSummary = (actors: SpaceNotification["actor"][]) => {+ if (actors.length == 0) return "Someone";+ const first = fullName(actors[0]!);+ if (actors.length == 1) return first;+ const second = fullName(actors[1]!);+ if (actors.length == 2) return `${first} and ${second}`;+ return `${first} and ${actors.length - 1} others`;+};++const notificationText = (group: NotificationGroup) => {+ const actors = actorSummary(group.actors);+ switch (group.type) {+ case "friend_add":+ return `${actors} became friends with you`;+ case "friend_remove":+ return `${actors} removed you as a friend`;+ case "post_like":+ return `${actors} liked your post`;+ }+};++const AvatarStack: React.FC<{ actors: SpaceNotification["actor"][] }> = ({+ actors,+}) => (+ <Box sx={{ flexShrink: 0, height: 42, position: "relative", width: 42 }}>+ {actors.slice(0, 3).map((actor, index) => (+ <Box+ key={`${actor.spaceId ?? actor.id}-${index}`}+ sx={{+ bgcolor: avatarSkeletonBackground,+ border: `2px solid ${notificationsBackground}`,+ borderRadius: "50%",+ height: actors.length == 1 ? 42 : 30,+ left: actors.length == 1 ? 0 : index * 6,+ overflow: "hidden",+ position: "absolute",+ top: actors.length == 1 ? 0 : index * 5,+ width: actors.length == 1 ? 42 : 30,+ zIndex: 3 - index,+ }}+ >+ {actor.avatarUrl && (+ <Box+ component="img"+ alt=""+ src={actor.avatarUrl}+ sx={{+ display: "block",+ height: "100%",+ objectFit: "cover",+ width: "100%",+ }}+ />+ )}+ </Box>+ ))}+ </Box>+);++const timeSections = (notifications: SpaceNotification[]) => {+ const now = Date.now();+ const today = new Date(now);+ const startOfTodayMs = new Date(+ today.getFullYear(),+ today.getMonth(),+ today.getDate(),+ ).getTime();+ const startOfYesterdayMs = new Date(+ today.getFullYear(),+ today.getMonth(),+ today.getDate() - 1,+ ).getTime();+ const sections: NotificationSection[] = [+ { title: "New", items: [] },+ { title: "Today", items: [] },+ { title: "Yesterday", items: [] },+ { title: "Last 7 days", items: [] },+ { title: "Last 30 days", items: [] },+ { title: "Older", items: [] },+ ];++ for (const notification of notifications) {+ if (notification.unread) {+ sections[0]!.items.push(notification);+ continue;+ }+ if (notification.createdAtMs >= startOfTodayMs) {+ sections[1]!.items.push(notification);+ continue;+ }+ if (notification.createdAtMs >= startOfYesterdayMs) {+ sections[2]!.items.push(notification);+ continue;+ }++ const ageMs = Math.max(0, now - notification.createdAtMs);+ if (ageMs <= 7 * dayMs) {+ sections[3]!.items.push(notification);+ continue;+ }+ if (ageMs <= 30 * dayMs) {+ sections[4]!.items.push(notification);+ continue;+ }+ sections[5]!.items.push(notification);+ }+ return sections;+};++const groupSectionNotifications = (items: SpaceNotification[]) => {+ const groups = new Map<string, NotificationGroup>();+ for (const item of items) {+ const key =+ item.type == "post_like"+ ? `post_like:${item.post?.postId ?? item.id}`+ : item.type;+ const existing = groups.get(key);+ if (existing) {+ existing.actors.push(item.actor);+ existing.createdAtMs = Math.max(+ existing.createdAtMs,+ item.createdAtMs,+ );+ continue;+ }+ groups.set(key, {+ actors: [item.actor],+ createdAtMs: item.createdAtMs,+ id: key,+ post: item.post,+ type: item.type,+ });+ }+ return [...groups.values()].sort((a, b) => b.createdAtMs - a.createdAtMs);+};++const NotificationRow: React.FC<{ group: NotificationGroup }> = ({ group }) => (+ <Box+ component="li"+ sx={{+ alignItems: "center",+ borderRadius: "8px",+ display: "grid",+ gap: "12px",+ gridTemplateColumns: "42px minmax(0, 1fr) auto",+ minHeight: 62,+ px: "6px",+ py: "7px",+ "&:hover": { bgcolor: rowHover },+ }}+ >+ <AvatarStack actors={group.actors} />+ <Box sx={{ minWidth: 0 }}>+ <Box+ component="p"+ sx={{+ color: textBase,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ fontWeight: 650,+ lineHeight: "19px",+ m: 0,+ }}+ >+ {notificationText(group)}+ </Box>+ <Box+ component="p"+ sx={{+ color: textSecondary,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 12,+ fontWeight: 500,+ lineHeight: "16px",+ m: 0,+ mt: "2px",+ }}+ >+ {formatTimeAgo(group.createdAtMs)}+ </Box>+ </Box>+ {group.post?.imageUrl && (+ <Box+ component="img"+ alt=""+ src={group.post.imageUrl}+ sx={{+ borderRadius: "6px",+ display: "block",+ height: 44,+ objectFit: "cover",+ width: 44,+ }}+ />+ )}+ </Box>+);++const NotificationSection: React.FC<{ section: NotificationSection }> = ({+ section,+}) => {+ const groups = groupSectionNotifications(section.items);+ if (groups.length == 0) return null;++ return (+ <Box component="section" sx={{ mb: "10px" }}>+ <Box+ component="h2"+ sx={{+ color: textSecondary,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 13,+ fontWeight: 700,+ lineHeight: "18px",+ m: 0,+ pb: "4px",+ pt: "12px",+ }}+ >+ {section.title}+ </Box>+ <Box component="ul" sx={{ listStyle: "none", m: 0, p: 0 }}>+ {groups.map((group) => (+ <NotificationRow key={group.id} group={group} />+ ))}+ </Box>+ </Box>+ );+};++export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({+ isLoading = false,+ notifications,+ onBack,+ onShareProfileLink,+}) => {+ const [isInviteDialogOpen, setIsInviteDialogOpen] = React.useState(false);+ const [isInviteSharing, setIsInviteSharing] = React.useState(false);+ const [inviteShareError, setInviteShareError] = React.useState<+ string | null+ >(null);+ const sections = React.useMemo(+ () => timeSections(notifications),+ [notifications],+ );+ const showInviteEmptyState = Boolean(onShareProfileLink);++ const openInviteDialog = () => {+ setInviteShareError(null);+ setIsInviteDialogOpen(true);+ };++ const closeInviteDialog = () => {+ if (isInviteSharing) return;+ setIsInviteDialogOpen(false);+ };++ const shareInviteLink = async () => {+ if (!onShareProfileLink || isInviteSharing) return;+ setIsInviteSharing(true);+ setInviteShareError(null);++ try {+ const profileLink = await onShareProfileLink();+ if (typeof navigator.share == "function") {+ try {+ await navigator.share({ url: profileLink });+ setIsInviteDialogOpen(false);+ return;+ } catch (error) {+ if (+ error instanceof DOMException &&+ error.name == "AbortError"+ )+ return;+ }+ }++ await navigator.clipboard.writeText(profileLink);+ setIsInviteDialogOpen(false);+ } catch (error) {+ console.error("Failed to share space invite", error);+ setInviteShareError("Couldn't share invite. Please try again.");+ } finally {+ setIsInviteSharing(false);+ }+ };++ return (+ <Box+ sx={{+ bgcolor: notificationsBackground,+ color: textBase,+ minHeight: "100svh",+ }}+ >+ <Box+ sx={{+ bgcolor: notificationsBackground,+ boxSizing: "border-box",+ minHeight: "100svh",+ mx: "auto",+ width: "100%",+ "@media (min-width: 600px)": { maxWidth: 390 },+ }}+ >+ <Box+ component="header"+ sx={{+ alignItems: "center",+ bgcolor: notificationsBackground,+ boxSizing: "border-box",+ display: "grid",+ gridTemplateColumns: "44px minmax(0, 1fr) 44px",+ height: 58,+ px: "10px",+ position: "sticky",+ top: 0,+ zIndex: 2,+ }}+ >+ <Box+ component="button"+ type="button"+ aria-label="Back"+ onClick={onBack}+ sx={{+ alignItems: "center",+ appearance: "none",+ bgcolor: "transparent",+ border: 0,+ color: textBase,+ cursor: onBack ? "pointer" : "default",+ display: "flex",+ height: spaceTouchTargetSize,+ justifyContent: "center",+ p: 0,+ width: spaceTouchTargetSize,+ "&:focus-visible": {+ borderRadius: "50%",+ outline: `2px solid ${green}`,+ outlineOffset: 2,+ },+ }}+ >+ <HugeiconsIcon+ icon={ArrowLeft02Icon}+ size={24}+ strokeWidth={1.8}+ />+ </Box>+ <Box+ component="h1"+ sx={{+ color: textBase,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 18,+ fontWeight: 750,+ lineHeight: "24px",+ m: 0,+ textAlign: "center",+ }}+ >+ Notifications+ </Box>+ </Box>+ <Box sx={{ boxSizing: "border-box", px: "16px", pb: "28px" }}>+ {isLoading ? (+ <Box+ sx={{+ alignItems: "center",+ display: "flex",+ height: "calc(100svh - 58px)",+ justifyContent: "center",+ }}+ >+ <SpaceLoadingSpinner ariaLabel="Loading notifications" />+ </Box>+ ) : notifications.length == 0 ? (+ <Box+ sx={{+ alignItems: "center",+ display: "flex",+ flexDirection: "column",+ gap: "22px",+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ height: "calc(100svh - 58px)",+ justifyContent: "center",+ px: 3,+ textAlign: "center",+ }}+ >+ <Box+ component="p"+ sx={{+ color: textSecondary,+ fontSize: 14,+ fontWeight: 500,+ lineHeight: "20px",+ m: 0,+ maxWidth: 292,+ }}+ >+ No notifications yet. Once you add friends,+ you'll see post likes and friend updates+ here.+ </Box>+ {showInviteEmptyState && (+ <Box+ component="button"+ type="button"+ onClick={openInviteDialog}+ sx={{+ alignItems: "center",+ bgcolor: "#F2F2F2",+ border: 0,+ borderRadius: "18px",+ color: textBase,+ cursor: "pointer",+ display: "inline-flex",+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 13,+ fontWeight: 600,+ gap: "6px",+ height: spaceTouchTargetSize,+ justifyContent: "center",+ lineHeight: "18px",+ px: "14px",+ whiteSpace: "nowrap",+ "&:focus-visible": {+ outline: `2px solid ${green}`,+ outlineOffset: 2,+ },+ "&:hover": { bgcolor: "#E8E8E8" },+ }}+ >+ <ShareIcon />+ Invite friends+ </Box>+ )}+ </Box>+ ) : (+ sections.map((section) => (+ <NotificationSection+ key={section.title}+ section={section}+ />+ ))+ )}+ </Box>+ </Box>+ <SpaceInviteFriendsDialog+ errorMessage={inviteShareError}+ open={isInviteDialogOpen}+ sharing={isInviteSharing}+ onClose={closeInviteDialog}+ onShare={() => void shareInviteLink()}+ />+ </Box>+ );+};diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.tsindex aefd07dd2a..88680d96a1 100644--- a/web/apps/space/src/services/space.ts+++ b/web/apps/space/src/services/space.ts@@ -76,13 +76,15 @@ interface SpacePostPageResponse {}type SpaceMessageConversationActivityType =- | "friend_add"- | "friend_remove"| "message"| "message_like"- | "post_like"| "post_reply";+export type SpaceNotificationType =+ | "friend_add"+ | "friend_remove"+ | "post_like";+interface SpaceMessageConversationPostResponse {isDeleted?: boolean;objects?: SpacePostObject[];@@ -144,8 +146,7 @@ interface SpaceMessagePageResponse {interface SpaceMessageConversationResponse {friend: SpaceActor;- latestActivity: SpaceMessageConversationActivity;- notificationUnread?: boolean;+ latestActivity?: SpaceMessageConversationActivity;unread?: boolean;unreadCount: number;}@@ -155,6 +156,20 @@ interface SpaceMessageConversationPageResponse {nextCursor?: string;}+interface SpaceNotificationResponse {+ actor: SpaceActor;+ createdAt: string;+ id: string;+ post?: SpaceMessageConversationPostResponse;+ type: SpaceNotificationType;+ unread?: boolean;+}++interface SpaceNotificationPageResponse {+ items?: SpaceNotificationResponse[];+ nextCursor?: string;+}+interface SpacePostBase {avatarObjectKey?: string;avatarSize?: number;@@ -283,8 +298,7 @@ export interface SpaceMessagePage {export interface SpaceMessageConversation {friend: FriendProfile;- latestActivity: SpaceMessageActivity;- notificationUnread: boolean;+ latestActivity?: SpaceMessageActivity;unread: boolean;unreadCount: number;}@@ -294,11 +308,30 @@ export interface SpaceMessageConversationPage {nextCursor?: string;}+export interface SpaceNotification {+ actor: FriendProfile;+ createdAt: string;+ createdAtMs: number;+ id: string;+ post?: SpaceMessageActivityPost;+ type: SpaceNotificationType;+ unread: boolean;+}++export interface SpaceNotificationPage {+ items: SpaceNotification[];+ nextCursor?: string;+}+export interface SpaceUnreadStatus {+ messageLikesUnread: boolean;messagesUnread: boolean;+ notificationsUnread: boolean;}interface SpaceUnreadStatusResponse {+ messageLikesUnread?: boolean;+ messagesUnread?: boolean;notificationsUnread: boolean;}@@ -820,8 +853,9 @@ const messageActivityPostFromSpacePost = async (const messageActivityFromSpaceActivity = async (ctx: SpaceAccountCtxHandle,- activity: SpaceMessageConversationActivity,-): Promise<SpaceMessageActivity> => {+ activity?: SpaceMessageConversationActivity,+): Promise<SpaceMessageActivity | undefined> => {+ if (!activity) return undefined;const [message, post] = await Promise.all([activity.message? messageFromSpaceMessage(ctx, activity.message, false)@@ -838,6 +872,31 @@ const messageActivityFromSpaceActivity = async (};};+const notificationFromSpaceNotification = async (+ ctx: SpaceAccountCtxHandle,+ notification: SpaceNotificationResponse,+): Promise<SpaceNotification> => {+ const actor = actorProfile(notification.actor);+ const [avatarUrl, post] = await Promise.all([+ accountAvatarURL(+ ctx,+ notification.actor.spaceId,+ notification.actor.avatar,+ ),+ messageActivityPostFromSpacePost(ctx, notification.post),+ ]);+ actor.avatarUrl = avatarUrl;+ return {+ actor,+ createdAt: notification.createdAt,+ createdAtMs: timestampMsFromSpaceDate(notification.createdAt),+ id: notification.id,+ post,+ type: notification.type,+ unread: Boolean(notification.unread),+ };+};+export const createCurrentProfileLink = async (spaceId: string,): Promise<SpaceLink> => {@@ -969,8 +1028,12 @@ export const loadCurrentUnreadStatus = async (): Promise<SpaceUnreadStatus> => {const ctx = await ensureCurrentSpaceContext();try {const status = (await ctx.unread_status()) as SpaceUnreadStatusResponse;+ const messagesUnread = Boolean(status.messagesUnread);+ const messageLikesUnread = Boolean(status.messageLikesUnread);return {- messagesUnread: status.notificationsUnread,+ messageLikesUnread,+ messagesUnread,+ notificationsUnread: Boolean(status.notificationsUnread),};} finally {releaseCurrentSpaceContext(ctx);@@ -1199,9 +1262,6 @@ export const loadCurrentMessageConversations =ctx,conversation.latestActivity,),- notificationUnread: Boolean(- conversation.notificationUnread,- ),unread: Boolean(conversation.unread),unreadCount: conversation.unreadCount,};@@ -1213,6 +1273,25 @@ export const loadCurrentMessageConversations =}};+export const loadCurrentNotifications =+ async (): Promise<SpaceNotificationPage> => {+ const ctx = await ensureCurrentSpaceContext();+ try {+ const page = (await ctx.list_notifications(+ null,+ 100,+ )) as SpaceNotificationPageResponse;+ const items = await Promise.all(+ (page.items ?? []).map((notification) =>+ notificationFromSpaceNotification(ctx, notification),+ ),+ );+ return { items, nextCursor: page.nextCursor || undefined };+ } finally {+ releaseCurrentSpaceContext(ctx);+ }+ };+export const loadCurrentMessageThread = async (spaceId: string,): Promise<SpaceMessagePage> => {@@ -1240,7 +1319,25 @@ export const markCurrentMessagesRead = async (friendSpaceId: string) => {if (!friendSpaceId.trim()) return;const ctx = await ensureCurrentSpaceContext();try {- await ctx.mark_notifications_read(friendSpaceId);+ await ctx.mark_message_thread_read(friendSpaceId);+ } finally {+ releaseCurrentSpaceContext(ctx);+ }+};++export const markCurrentNotificationsRead = async (readAt?: string) => {+ const ctx = await ensureCurrentSpaceContext();+ try {+ await ctx.mark_notifications_read(readAt ?? null);+ } finally {+ releaseCurrentSpaceContext(ctx);+ }+};++export const markCurrentMessageLikesRead = async () => {+ const ctx = await ensureCurrentSpaceContext();+ try {+ await ctx.mark_message_likes_read();} finally {releaseCurrentSpaceContext(ctx);}diff --git a/web/apps/space/src/utils/spaceRoutes.ts b/web/apps/space/src/utils/spaceRoutes.tsindex 86ee00ecd5..cfd78a0beb 100644--- a/web/apps/space/src/utils/spaceRoutes.ts+++ b/web/apps/space/src/utils/spaceRoutes.ts@@ -19,6 +19,7 @@ export const spaceRoutes = {message: (spaceId: string) =>`/app/messages/${encodeURIComponent(spaceId)}`,messages: "/app/messages",+ notifications: "/app/notifications",onboarding: "/",passkeysFinish: "/passkeys/finish",passkeysVerify: "/passkeys/verify",