diff --git a/.github/scripts/d1-migration-manifest.mjs b/.github/scripts/d1-migration-manifest.mjs index e47dd1e4..6fbe011f 100644 --- a/.github/scripts/d1-migration-manifest.mjs +++ b/.github/scripts/d1-migration-manifest.mjs @@ -124,4 +124,9 @@ export const D1_MIGRATIONS = [ file: "worker/migrations/2026-08-30-pinned-messages.sql", artifacts: ["table:channel_pins", "trigger:clear_pin_after_message_soft_delete"], }, + { + id: "2026-09-01-message-mentions", + file: "worker/migrations/2026-09-01-message-mentions.sql", + artifacts: ["column:messages.mention_user_ids"], + }, ]; diff --git a/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/2.json b/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/2.json new file mode 100644 index 00000000..108731f2 --- /dev/null +++ b/android/app/schemas/com.aozorae.edgechat.core.database.EdgeChatDatabase/2.json @@ -0,0 +1,438 @@ +{ + "formatVersion": 1, + "database": { + "version": 2, + "identityHash": "ccee9907a5e2fa49f8ff36095dfe03c5", + "entities": [ + { + "tableName": "users", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `username` TEXT NOT NULL, `displayName` TEXT NOT NULL, `avatarUrl` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "username", + "columnName": "username", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "conversations", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `id` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT NOT NULL, `avatarUrl` TEXT NOT NULL, `isGeneral` INTEGER NOT NULL, `isMember` INTEGER NOT NULL, `canManage` INTEGER NOT NULL, `myRole` TEXT NOT NULL, `memberCount` INTEGER NOT NULL, `otherUserId` INTEGER, `lastMessageAt` TEXT, `unreadCount` INTEGER NOT NULL, `mentionUnreadCount` INTEGER NOT NULL, PRIMARY KEY(`kind`, `id`))", + "fields": [ + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "title", + "columnName": "title", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subtitle", + "columnName": "subtitle", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isGeneral", + "columnName": "isGeneral", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isMember", + "columnName": "isMember", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canManage", + "columnName": "canManage", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "myRole", + "columnName": "myRole", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "memberCount", + "columnName": "memberCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "otherUserId", + "columnName": "otherUserId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "lastMessageAt", + "columnName": "lastMessageAt", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "unreadCount", + "columnName": "unreadCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mentionUnreadCount", + "columnName": "mentionUnreadCount", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "kind", + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `roomKind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `clientMessageId` TEXT, `content` TEXT NOT NULL, `createdAt` TEXT NOT NULL, `source` TEXT NOT NULL, `senderKind` TEXT NOT NULL, `senderId` TEXT NOT NULL, `senderUsername` TEXT NOT NULL, `senderDisplayName` TEXT NOT NULL, `senderAvatarUrl` TEXT NOT NULL, `attachmentKey` TEXT, `attachmentName` TEXT, `attachmentType` TEXT, `attachmentSize` INTEGER, `attachmentUrl` TEXT, `mentionUserIds` TEXT NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "roomKind", + "columnName": "roomKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "clientMessageId", + "columnName": "clientMessageId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderKind", + "columnName": "senderKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderId", + "columnName": "senderId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderUsername", + "columnName": "senderUsername", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderDisplayName", + "columnName": "senderDisplayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "senderAvatarUrl", + "columnName": "senderAvatarUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "attachmentKey", + "columnName": "attachmentKey", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentName", + "columnName": "attachmentName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentType", + "columnName": "attachmentType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentSize", + "columnName": "attachmentSize", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "attachmentUrl", + "columnName": "attachmentUrl", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "mentionUserIds", + "columnName": "mentionUserIds", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_messages_roomKind_roomId_id", + "unique": false, + "columnNames": [ + "roomKind", + "roomId", + "id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_roomKind_roomId_id` ON `${TABLE_NAME}` (`roomKind`, `roomId`, `id`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "room_sync", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `cursor` INTEGER NOT NULL, PRIMARY KEY(`kind`, `roomId`))", + "fields": [ + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cursor", + "columnName": "cursor", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "kind", + "roomId" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "outbox", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`clientMessageId` TEXT NOT NULL, `roomKind` TEXT NOT NULL, `roomId` INTEGER NOT NULL, `content` TEXT NOT NULL, `localAttachmentPath` TEXT, `attachmentName` TEXT, `attachmentType` TEXT, `attachmentSize` INTEGER, `clientUploadId` TEXT, `uploadedKey` TEXT, `uploadedUrl` TEXT, `mentionUserIds` TEXT NOT NULL, `state` TEXT NOT NULL, `failure` TEXT, `attempts` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`clientMessageId`))", + "fields": [ + { + "fieldPath": "clientMessageId", + "columnName": "clientMessageId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomKind", + "columnName": "roomKind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "roomId", + "columnName": "roomId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "content", + "columnName": "content", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "localAttachmentPath", + "columnName": "localAttachmentPath", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentName", + "columnName": "attachmentName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentType", + "columnName": "attachmentType", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attachmentSize", + "columnName": "attachmentSize", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "clientUploadId", + "columnName": "clientUploadId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "uploadedKey", + "columnName": "uploadedKey", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "uploadedUrl", + "columnName": "uploadedUrl", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "mentionUserIds", + "columnName": "mentionUserIds", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "failure", + "columnName": "failure", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "clientMessageId" + ] + }, + "indices": [ + { + "name": "index_outbox_createdAt", + "unique": false, + "columnNames": [ + "createdAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_outbox_createdAt` ON `${TABLE_NAME}` (`createdAt`)" + } + ], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ccee9907a5e2fa49f8ff36095dfe03c5')" + ] + } +} \ No newline at end of file diff --git a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/MessageComposerTest.kt b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/MessageComposerTest.kt index d98b814c..596a2db5 100644 --- a/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/MessageComposerTest.kt +++ b/android/app/src/androidTest/java/com/aozorae/edgechat/feature/chat/MessageComposerTest.kt @@ -26,9 +26,11 @@ class MessageComposerTest { roomTitle = "general", attachment = null, language = "en-US", + members = emptyList(), + currentUserId = 1, onChooseAttachment = {}, onClearAttachment = {}, - onSend = { sent = it }, + onSend = { content, _ -> sent = content }, ) } } @@ -54,9 +56,11 @@ class MessageComposerTest { roomTitle = "general", attachment = null, language = "en-US", + members = emptyList(), + currentUserId = 1, onChooseAttachment = {}, onClearAttachment = {}, - onSend = {}, + onSend = { _, _ -> }, ) } } diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/Daos.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/Daos.kt index 7373bc06..2503577c 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/database/Daos.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/Daos.kt @@ -22,7 +22,7 @@ interface UserDao { interface ConversationDao { @Query( """SELECT * FROM conversations - ORDER BY isGeneral DESC, unreadCount DESC, + ORDER BY isGeneral DESC, mentionUnreadCount DESC, unreadCount DESC, CASE WHEN lastMessageAt IS NULL THEN 1 ELSE 0 END, lastMessageAt DESC, title COLLATE NOCASE""" ) @@ -34,10 +34,14 @@ interface ConversationDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertAll(conversations: List) - @Query("UPDATE conversations SET unreadCount = :count, lastMessageAt = :createdAt WHERE kind = :kind AND id = :roomId") - suspend fun updateActivity(kind: String, roomId: Long, count: Int, createdAt: String?) + @Query( + "UPDATE conversations SET unreadCount = COALESCE(:count, unreadCount), " + + "mentionUnreadCount = COALESCE(:mentionCount, mentionUnreadCount), " + + "lastMessageAt = :createdAt WHERE kind = :kind AND id = :roomId" + ) + suspend fun updateActivity(kind: String, roomId: Long, count: Int?, mentionCount: Int?, createdAt: String?) - @Query("UPDATE conversations SET unreadCount = 0 WHERE kind = :kind AND id = :roomId") + @Query("UPDATE conversations SET unreadCount = 0, mentionUnreadCount = 0 WHERE kind = :kind AND id = :roomId") suspend fun clearUnread(kind: String, roomId: Long) @Query("DELETE FROM conversations") diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/DatabaseMigrations.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/DatabaseMigrations.kt new file mode 100644 index 00000000..207a2a9e --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/DatabaseMigrations.kt @@ -0,0 +1,14 @@ +package com.aozorae.edgechat.core.database + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +val MIGRATION_1_2 = object : Migration(1, 2) { + override fun migrate(database: SupportSQLiteDatabase) { + // 提及未读与普通未读语义不同,独立列能让会话列表稳定恢复多设备同步状态。 + database.execSQL("ALTER TABLE conversations ADD COLUMN mentionUnreadCount INTEGER NOT NULL DEFAULT 0") + // 离线消息和待发送队列都保留提及目标,避免重连或 WorkManager 重试时静默丢失通知。 + database.execSQL("ALTER TABLE messages ADD COLUMN mentionUserIds TEXT NOT NULL DEFAULT ''") + database.execSQL("ALTER TABLE outbox ADD COLUMN mentionUserIds TEXT NOT NULL DEFAULT ''") + } +} diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/EdgeChatDatabase.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/EdgeChatDatabase.kt index 21000a1f..3a72eac5 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/database/EdgeChatDatabase.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/EdgeChatDatabase.kt @@ -11,7 +11,7 @@ import androidx.room.RoomDatabase RoomSyncEntity::class, OutboxEntity::class, ], - version = 1, + version = 2, exportSchema = true, ) abstract class EdgeChatDatabase : RoomDatabase() { diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/Entities.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/Entities.kt index 021df368..511d1465 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/database/Entities.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/Entities.kt @@ -27,6 +27,7 @@ data class ConversationEntity( val otherUserId: Long?, val lastMessageAt: String?, val unreadCount: Int, + val mentionUnreadCount: Int = 0, ) @Entity( @@ -51,6 +52,7 @@ data class MessageEntity( val attachmentType: String?, val attachmentSize: Long?, val attachmentUrl: String?, + val mentionUserIds: String = "", ) @Entity(tableName = "room_sync", primaryKeys = ["kind", "roomId"]) @@ -69,6 +71,7 @@ data class OutboxEntity( val clientUploadId: String?, val uploadedKey: String?, val uploadedUrl: String?, + val mentionUserIds: String = "", val state: String, val failure: String?, val attempts: Int, diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/Mappers.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/Mappers.kt index 30024a8b..8f88f05d 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/database/Mappers.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/Mappers.kt @@ -21,6 +21,7 @@ fun ChannelDto.toEntity() = ConversationEntity( otherUserId = null, lastMessageAt = lastMessageAt, unreadCount = unreadCount, + mentionUnreadCount = mentionUnreadCount, ) fun DmDto.toEntity() = ConversationEntity( @@ -37,6 +38,7 @@ fun DmDto.toEntity() = ConversationEntity( otherUserId = otherUser.id, lastMessageAt = lastMessageAt, unreadCount = unreadCount, + mentionUnreadCount = 0, ) fun MessageDto.toEntity(kind: String, roomId: Long) = MessageEntity( @@ -57,4 +59,5 @@ fun MessageDto.toEntity(kind: String, roomId: Long) = MessageEntity( attachmentType = attachment?.type, attachmentSize = attachment?.size, attachmentUrl = attachment?.url, + mentionUserIds = encodeMentionUserIds(mentionUserIds), ) diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/database/MentionIds.kt b/android/app/src/main/java/com/aozorae/edgechat/core/database/MentionIds.kt new file mode 100644 index 00000000..427256be --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/core/database/MentionIds.kt @@ -0,0 +1,7 @@ +package com.aozorae.edgechat.core.database + +fun encodeMentionUserIds(userIds: List): String = + userIds.distinct().joinToString(",") + +fun decodeMentionUserIds(value: String): List = + value.split(',').mapNotNull(String::toLongOrNull) diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt b/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt index 6221a636..06918505 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/network/dto/ApiDtos.kt @@ -90,6 +90,7 @@ data class ChannelDto( val memberCount: Int = 0, val lastMessageAt: String? = null, val unreadCount: Int = 0, + val mentionUnreadCount: Int = 0, ) @Serializable @@ -129,6 +130,13 @@ data class AttachmentDto( val url: String, ) +@Serializable +data class MentionDto( + val userId: Long, + val username: String, + val displayName: String = "", +) + @Serializable data class MessageDto( val id: Long, @@ -138,6 +146,8 @@ data class MessageDto( val source: String = "edgechat", val sender: SenderDto, val attachment: AttachmentDto? = null, + val mentionUserIds: List = emptyList(), + val mentions: List = emptyList(), ) @Serializable @@ -171,6 +181,7 @@ data class SendMessageRequest( val clientMessageId: String, val content: String, val attachment: AttachmentDto? = null, + val mentionUserIds: List = emptyList(), ) @Serializable @@ -276,6 +287,10 @@ data class RealtimeEnvelope( val messageId: Long? = null, val createdAt: String? = null, val unreadCount: Int? = null, + val mentionUnreadCount: Int? = null, + val mentionsMe: Boolean = false, + val contentPreview: String? = null, + val sender: SenderDto? = null, val error: String? = null, ) diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/ChatRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/ChatRepository.kt index 6266b62f..150bc723 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/repository/ChatRepository.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/ChatRepository.kt @@ -117,7 +117,8 @@ class ChatRepository @Inject constructor( database.conversations().updateActivity( room.kind, room.id, - envelope.unreadCount ?: 0, + envelope.unreadCount, + envelope.mentionUnreadCount, envelope.createdAt, ) sync(room) diff --git a/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt b/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt index 61c56ae4..02528dc3 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/core/repository/OutboxRepository.kt @@ -9,6 +9,8 @@ import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import com.aozorae.edgechat.core.database.EdgeChatDatabase import com.aozorae.edgechat.core.database.OutboxEntity +import com.aozorae.edgechat.core.database.decodeMentionUserIds +import com.aozorae.edgechat.core.database.encodeMentionUserIds import com.aozorae.edgechat.core.database.toEntity import com.aozorae.edgechat.core.network.EdgeChatApi import com.aozorae.edgechat.core.network.bodyOrThrow @@ -48,7 +50,12 @@ class OutboxRepository @Inject constructor( fun observe(room: RoomIdentity): Flow> = database.outbox().observeRoom(room.kind, room.id) - suspend fun enqueue(room: RoomIdentity, content: String, attachment: PendingAttachment? = null) { + suspend fun enqueue( + room: RoomIdentity, + content: String, + attachment: PendingAttachment? = null, + mentionUserIds: List = emptyList(), + ) { val messageId = UUID.randomUUID().toString() database.outbox().upsert( OutboxEntity( @@ -63,6 +70,7 @@ class OutboxRepository @Inject constructor( clientUploadId = attachment?.let { UUID.randomUUID().toString() }, uploadedKey = null, uploadedUrl = null, + mentionUserIds = encodeMentionUserIds(mentionUserIds), state = "PENDING", failure = null, attempts = 0, @@ -91,7 +99,12 @@ class OutboxRepository @Inject constructor( val sent = api.sendMessage( item.roomKind, item.roomId, - SendMessageRequest(item.clientMessageId, item.content, attachment), + SendMessageRequest( + item.clientMessageId, + item.content, + attachment, + decodeMentionUserIds(item.mentionUserIds), + ), ).bodyOrThrow(json) database.messages().upsert(sent.message.toEntity(item.roomKind, item.roomId)) database.outbox().delete(item.clientMessageId) diff --git a/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt b/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt index a0e7ed49..1b4674a1 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/di/AppModule.kt @@ -7,6 +7,7 @@ import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.preferencesDataStoreFile import androidx.room.Room import com.aozorae.edgechat.core.database.EdgeChatDatabase +import com.aozorae.edgechat.core.database.MIGRATION_1_2 import com.aozorae.edgechat.core.network.AuthInterceptor import com.aozorae.edgechat.core.network.EdgeChatApi import com.aozorae.edgechat.core.network.ServerUrlInterceptor @@ -43,7 +44,9 @@ object AppModule { @Provides @Singleton fun database(@ApplicationContext context: Context): EdgeChatDatabase = - Room.databaseBuilder(context, EdgeChatDatabase::class.java, "edgechat.db").build() + Room.databaseBuilder(context, EdgeChatDatabase::class.java, "edgechat.db") + .addMigrations(MIGRATION_1_2) + .build() @Provides @Singleton diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatMessages.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatMessages.kt index bbd26df2..01b3f26f 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatMessages.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatMessages.kt @@ -49,11 +49,15 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.aozorae.edgechat.core.database.MessageEntity import com.aozorae.edgechat.core.database.OutboxEntity +import com.aozorae.edgechat.core.database.decodeMentionUserIds +import com.aozorae.edgechat.core.network.dto.MemberDto import com.aozorae.edgechat.core.network.dto.SessionDto import com.aozorae.edgechat.ui.components.EdgeAvatar import com.aozorae.edgechat.ui.components.resolveServerUrl @@ -76,6 +80,7 @@ fun ChatMessages( messages: List, outbox: List, currentUser: SessionDto, + members: List = emptyList(), serverBaseUrl: String, language: String, scrollState: LazyListState, @@ -138,6 +143,8 @@ fun ChatMessages( own = message.senderKind == "local" && message.senderId == currentUser.userId.toString(), groupPosition = messageGroupPosition(message, newer, older), showAuthor = startsMessageGroup(message, older), + currentUser = currentUser, + members = members, serverBaseUrl = serverBaseUrl, language = language, onDelete = onDeleteMessage, @@ -221,6 +228,8 @@ private fun MessageItem( own: Boolean, groupPosition: MessageGroupPosition, showAuthor: Boolean, + currentUser: SessionDto, + members: List, serverBaseUrl: String, language: String, onDelete: (Long) -> Unit, @@ -291,6 +300,8 @@ private fun MessageItem( message = message, own = own, groupPosition = groupPosition, + currentUser = currentUser, + members = members, serverBaseUrl = serverBaseUrl, language = language, onOpenAttachment = onOpenAttachment, @@ -306,6 +317,8 @@ private fun MessageBubble( message: MessageEntity, own: Boolean, groupPosition: MessageGroupPosition, + currentUser: SessionDto, + members: List, serverBaseUrl: String, language: String, onOpenAttachment: (String, String, String) -> Unit, @@ -321,7 +334,30 @@ private fun MessageBubble( ) { Column(Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) { if (message.content.isNotBlank()) { - Text(message.content, style = MaterialTheme.typography.bodyLarge) + val ranges = findMentionRanges( + message.content, + members, + decodeMentionUserIds(message.mentionUserIds), + ) + val annotatedContent = buildAnnotatedString { + append(message.content) + ranges.forEach { range -> + addStyle( + SpanStyle( + color = colors.accent, + background = if (range.userId == currentUser.userId) { + colors.accentSubtle + } else { + androidx.compose.ui.graphics.Color.Unspecified + }, + fontWeight = FontWeight.SemiBold, + ), + range.start, + range.end, + ) + } + } + Text(annotatedContent, style = MaterialTheme.typography.bodyLarge) } val attachmentUrl = message.attachmentUrl if (attachmentUrl != null) { diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt index c6d26aa1..cd4a23e1 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatPane.kt @@ -45,6 +45,7 @@ import com.aozorae.edgechat.core.database.ConversationEntity import com.aozorae.edgechat.core.database.MessageEntity import com.aozorae.edgechat.core.database.OutboxEntity import com.aozorae.edgechat.core.network.dto.SessionDto +import com.aozorae.edgechat.core.network.dto.MemberDto import com.aozorae.edgechat.core.repository.PendingAttachment import com.aozorae.edgechat.core.repository.RoomIdentity import com.aozorae.edgechat.ui.components.EdgeAvatar @@ -62,6 +63,7 @@ fun ChatPane( messages: List, outbox: List, attachment: PendingAttachment?, + members: List, currentUser: SessionDto, serverBaseUrl: String, busy: Boolean, @@ -69,7 +71,7 @@ fun ChatPane( openAttachmentEvents: SharedFlow>, onBack: (() -> Unit)?, onLoadOlder: () -> Unit, - onSend: (String) -> Unit, + onSend: (String, List) -> Unit, onChooseAttachment: (android.net.Uri) -> Unit, onClearAttachment: () -> Unit, onRetry: (String) -> Unit, @@ -189,6 +191,7 @@ fun ChatPane( messages = messages, outbox = outbox, currentUser = currentUser, + members = members, serverBaseUrl = serverBaseUrl, language = language, scrollState = scrollState, @@ -204,10 +207,12 @@ fun ChatPane( roomTitle = conversation.title, attachment = attachment, language = language, + members = members, + currentUserId = currentUser.userId, onChooseAttachment = { picker.launch("*/*") }, onClearAttachment = onClearAttachment, - onSend = { content -> - onSend(content) + onSend = { content, mentionUserIds -> + onSend(content, mentionUserIds) scope.launch { scrollState.animateScrollToItem(0) } }, ) diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt index 878fee0d..39e8aebe 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/ChatViewModel.kt @@ -55,6 +55,7 @@ class ChatViewModel @Inject constructor( private val members = MutableStateFlow>(emptyList()) private val busy = MutableStateFlow(false) private val error = MutableStateFlow(null) + private var memberLoadGeneration = 0 private val roomMessages = selectedRoom.flatMapLatest { room -> room?.let(chatRepository::messages) ?: flowOf(emptyList()) } @@ -90,13 +91,26 @@ class ChatViewModel @Inject constructor( fun refresh() = action { chatRepository.bootstrap() } fun select(room: RoomIdentity?) { + val generation = ++memberLoadGeneration selectedRoom.value = room members.value = emptyList() realtime.setRoom(room) - if (room != null) action { + if (room != null) { + if (room.kind != "dm") { + viewModelScope.launch { + runCatching { chatRepository.members(room.id).members } + .onSuccess { loadedMembers -> + if (generation == memberLoadGeneration && selectedRoom.value == room) { + members.value = loadedMembers + } + } + } + } + action { chatRepository.loadLatest(room) chatRepository.sync(room) chatRepository.markRead(room) + } } } @@ -104,12 +118,12 @@ class ChatViewModel @Inject constructor( selectedRoom.value?.let { room -> action { chatRepository.loadOlder(room) } } } - fun send(content: String) { + fun send(content: String, mentionUserIds: List) { val room = selectedRoom.value ?: return val pending = attachment.value if (content.isBlank() && pending == null) return action { - outboxRepository.enqueue(room, content, pending) + outboxRepository.enqueue(room, content, pending, mentionUserIds) attachment.value = null } } @@ -143,16 +157,16 @@ class ChatViewModel @Inject constructor( select(chatRepository.createGroup(name, description, kind, memberIds)) } - fun loadMembers(channelId: Long) = action { - members.value = chatRepository.members(channelId).members + fun loadMembers(channelId: Long) = updateMembers(channelId) { + chatRepository.members(channelId).members } - fun invite(channelId: Long, userIds: List) = action { - members.value = chatRepository.invite(channelId, userIds) + fun invite(channelId: Long, userIds: List) = updateMembers(channelId) { + chatRepository.invite(channelId, userIds) } - fun removeMember(channelId: Long, userId: Long) = action { - members.value = chatRepository.removeMember(channelId, userId) + fun removeMember(channelId: Long, userId: Long) = updateMembers(channelId) { + chatRepository.removeMember(channelId, userId) } fun renameGroup(channelId: Long, name: String) = action { @@ -168,6 +182,17 @@ class ChatViewModel @Inject constructor( error.value = null } + private fun updateMembers(channelId: Long, request: suspend () -> List) { + val generation = memberLoadGeneration + action { + val loadedMembers = request() + val room = selectedRoom.value + if (generation == memberLoadGeneration && room?.kind != "dm" && room?.id == channelId) { + members.value = loadedMembers + } + } + } + private fun action(block: suspend () -> Unit) { viewModelScope.launch { busy.value = true diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/Mentions.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/Mentions.kt new file mode 100644 index 00000000..e33a3b8c --- /dev/null +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/Mentions.kt @@ -0,0 +1,56 @@ +package com.aozorae.edgechat.feature.chat + +import com.aozorae.edgechat.core.network.dto.MemberDto + +data class ActiveMentionQuery(val start: Int, val end: Int, val query: String) + +data class MentionRange(val start: Int, val end: Int, val userId: Long) + +private fun isMentionBoundary(character: Char?): Boolean = + character == null || character.isWhitespace() || character in "()[]{}<>\"',。!?、:;,.!?" + +private fun mentionsUsername(content: String, username: String): Boolean { + val token = "@$username" + var offset = content.indexOf(token) + while (offset >= 0) { + val before = content.getOrNull(offset - 1) + val after = content.getOrNull(offset + token.length) + if (isMentionBoundary(before) && isMentionBoundary(after)) return true + offset = content.indexOf(token, offset + token.length) + } + return false +} + +fun resolveMentionUserIds(content: String, members: List, currentUserId: Long): List = + members.filter { it.id != currentUserId && mentionsUsername(content, it.username) }.map { it.id } + +fun findActiveMentionQuery(content: String, cursor: Int): ActiveMentionQuery? { + if (cursor !in 0..content.length) return null + val prefix = content.substring(0, cursor) + val at = prefix.lastIndexOf('@') + if (at < 0) return null + val before = prefix.getOrNull(at - 1) + if (!isMentionBoundary(before)) return null + val query = prefix.substring(at + 1) + if (query.any { it.isWhitespace() || it == '@' }) return null + return ActiveMentionQuery(at, cursor, query) +} + +fun findMentionRanges(content: String, members: List, mentionUserIds: List): List = + members + .filter { it.id in mentionUserIds } + .flatMap { member -> + val token = "@${member.username}" + buildList { + var offset = content.indexOf(token) + while (offset >= 0) { + val before = content.getOrNull(offset - 1) + val after = content.getOrNull(offset + token.length) + if (isMentionBoundary(before) && isMentionBoundary(after)) { + add(MentionRange(offset, offset + token.length, member.id)) + } + offset = content.indexOf(token, offset + token.length) + } + } + } + .sortedBy { it.start } diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageComposer.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageComposer.kt index 360fe829..83a633a1 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageComposer.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/chat/MessageComposer.kt @@ -1,6 +1,7 @@ package com.aozorae.edgechat.feature.chat import androidx.compose.foundation.border +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize @@ -38,9 +39,12 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.aozorae.edgechat.core.repository.PendingAttachment +import com.aozorae.edgechat.core.network.dto.MemberDto import com.aozorae.edgechat.ui.theme.LocalEdgeChatColors @Composable @@ -49,14 +53,30 @@ fun MessageComposer( roomTitle: String, attachment: PendingAttachment?, language: String, + members: List, + currentUserId: Long, onChooseAttachment: () -> Unit, onClearAttachment: () -> Unit, - onSend: (String) -> Unit, + onSend: (String, List) -> Unit, modifier: Modifier = Modifier, ) { - var content by rememberSaveable(roomKey) { mutableStateOf("") } - val canSend = content.isNotBlank() || attachment != null + var content by rememberSaveable(roomKey, stateSaver = TextFieldValue.Saver) { + mutableStateOf(TextFieldValue()) + } + val canSend = content.text.isNotBlank() || attachment != null val colors = LocalEdgeChatColors.current + val activeMention = findActiveMentionQuery(content.text, content.selection.start) + val mentionCandidates = activeMention?.let { active -> + members + .filter { member -> + member.id != currentUserId && ( + active.query.isBlank() || + member.username.contains(active.query, ignoreCase = true) || + member.displayName.contains(active.query, ignoreCase = true) + ) + } + .take(8) + }.orEmpty() Surface(modifier = modifier, color = colors.canvas) { Column { @@ -86,6 +106,38 @@ fun MessageComposer( } } } + if (mentionCandidates.isNotEmpty()) { + Surface( + modifier = Modifier.fillMaxWidth().padding(start = 64.dp, end = 60.dp, top = 6.dp), + color = colors.canvasLevel1, + shape = RoundedCornerShape(8.dp), + tonalElevation = 3.dp, + ) { + Column(Modifier.padding(vertical = 4.dp)) { + mentionCandidates.forEach { member -> + Row( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .clickable { + val active = activeMention ?: return@clickable + val replacement = "@${member.username} " + val nextText = content.text.replaceRange(active.start, active.end, replacement) + val nextCursor = active.start + replacement.length + content = TextFieldValue(nextText, TextRange(nextCursor)) + } + .padding(horizontal = 12.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column { + Text(member.displayName, style = MaterialTheme.typography.bodyMedium, color = colors.textPrimary) + Text("@${member.username}", style = MaterialTheme.typography.labelMedium, color = colors.textSecondary) + } + } + } + } + } + } Row( modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min).padding(horizontal = 8.dp, vertical = 8.dp), verticalAlignment = Alignment.Bottom, @@ -124,7 +176,7 @@ fun MessageComposer( maxLines = 5, decorationBox = { input -> Box(contentAlignment = Alignment.CenterStart) { - if (content.isBlank()) { + if (content.text.isBlank()) { Text( text = if (language == "zh-CN") "发送消息到 $roomTitle" else "Message $roomTitle", color = colors.textSecondary, @@ -140,7 +192,10 @@ fun MessageComposer( } Spacer(Modifier.width(4.dp)) IconButton( - onClick = { onSend(content); content = "" }, + onClick = { + onSend(content.text, resolveMentionUserIds(content.text, members, currentUserId)) + content = TextFieldValue() + }, enabled = canSend, modifier = Modifier.size(48.dp).testTag("send_message"), ) { diff --git a/android/app/src/main/java/com/aozorae/edgechat/feature/conversations/ConversationPane.kt b/android/app/src/main/java/com/aozorae/edgechat/feature/conversations/ConversationPane.kt index 7aa881eb..827cf7b9 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/feature/conversations/ConversationPane.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/feature/conversations/ConversationPane.kt @@ -289,6 +289,15 @@ private fun ConversationRow( style = MaterialTheme.typography.bodyMedium, color = colors.textSecondary, ) + if (item.mentionUnreadCount > 0) { + Spacer(Modifier.width(8.dp)) + Text( + text = if (language == "zh-CN") "有人@我" else "Mentioned you", + style = MaterialTheme.typography.labelSmall, + color = colors.critical, + fontWeight = FontWeight.Bold, + ) + } if (item.unreadCount > 0) { Spacer(Modifier.width(10.dp)) Badge(containerColor = colors.accent, contentColor = colors.onAccent) { diff --git a/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt b/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt index ebab70f7..039229e5 100644 --- a/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt +++ b/android/app/src/main/java/com/aozorae/edgechat/ui/EdgeChatApp.kt @@ -237,6 +237,7 @@ private fun ChatContent( messages = chatState.messages, outbox = chatState.outbox, attachment = chatState.attachment, + members = chatState.members, currentUser = session, serverBaseUrl = server.baseUrl, busy = chatState.busy, diff --git a/android/app/src/test/java/com/aozorae/edgechat/feature/chat/MentionsTest.kt b/android/app/src/test/java/com/aozorae/edgechat/feature/chat/MentionsTest.kt new file mode 100644 index 00000000..8a3fccf4 --- /dev/null +++ b/android/app/src/test/java/com/aozorae/edgechat/feature/chat/MentionsTest.kt @@ -0,0 +1,30 @@ +package com.aozorae.edgechat.feature.chat + +import com.aozorae.edgechat.core.network.dto.MemberDto +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class MentionsTest { + private val members = listOf( + MemberDto(1, "admin", "Admin", role = "owner"), + MemberDto(2, "alice", "Alice", role = "member"), + ) + + @Test + fun activeQueryAndMentionIdsFollowVisibleText() { + assertEquals(ActiveMentionQuery(6, 9, "al"), findActiveMentionQuery("hello @al", 9)) + assertEquals(ActiveMentionQuery(6, 9, "al"), findActiveMentionQuery("hello,@al", 9)) + assertNull(findActiveMentionQuery("mail@al", 7)) + assertEquals(listOf(2L), resolveMentionUserIds("@alice hello", members, 1)) + assertEquals(emptyList(), resolveMentionUserIds("@alice2", members, 1)) + } + + @Test + fun rangesOnlyIncludeServerConfirmedMentionIds() { + assertEquals( + listOf(MentionRange(3, 9, 2)), + findMentionRanges("Hi @alice and @admin", members, listOf(2)), + ) + } +} diff --git a/docs/api/edgechat-v1.openapi.yaml b/docs/api/edgechat-v1.openapi.yaml index 338b861b..10eae04d 100644 --- a/docs/api/edgechat-v1.openapi.yaml +++ b/docs/api/edgechat-v1.openapi.yaml @@ -286,6 +286,9 @@ paths: clientMessageId: { type: string, format: uuid } content: { type: string } attachment: { oneOf: [{ $ref: "#/components/schemas/Attachment" }, { type: "null" }] } + mentionUserIds: + type: array + items: { type: integer } responses: "200": { $ref: "#/components/responses/MessageSubmission" } "201": { $ref: "#/components/responses/MessageSubmission" } @@ -548,6 +551,7 @@ components: memberCount: { type: integer } lastMessageAt: { type: [string, "null"] } unreadCount: { type: integer } + mentionUnreadCount: { type: integer } Member: type: object required: [id, username, displayName, avatarUrl, role] @@ -577,6 +581,13 @@ components: displayName: { type: string } avatarUrl: { type: string } source: { type: string } + Mention: + type: object + required: [userId, username, displayName] + properties: + userId: { type: integer } + username: { type: string } + displayName: { type: string } Message: type: object required: [id, content, createdAt, source, sender, attachment] @@ -588,6 +599,8 @@ components: source: { type: string } sender: { $ref: "#/components/schemas/Sender" } attachment: { oneOf: [{ $ref: "#/components/schemas/Attachment" }, { type: "null" }] } + mentionUserIds: { type: array, items: { type: integer } } + mentions: { type: array, items: { $ref: "#/components/schemas/Mention" } } Bootstrap: type: object required: [users, channels, dms] diff --git a/docs/api/websocket-v1.md b/docs/api/websocket-v1.md index 10f41fbb..c90ff2ee 100644 --- a/docs/api/websocket-v1.md +++ b/docs/api/websocket-v1.md @@ -15,17 +15,17 @@ The ticket is bound to one device session and one scope. It is consumed once, in Every server frame is JSON and contains `protocolVersion: 1` plus `type`. - `ready`: the connection is authorized; room sockets include `room`. -- `message`: includes the canonical `message`. Room clients merge by `message.id` and `message.clientMessageId`. +- `message`: includes the canonical `message`, including `mentionUserIds` and resolved `mentions`. Room clients merge by `message.id` and `message.clientMessageId`. - `message_deleted`: includes `messageId`. - `message_pinned`: includes the canonical pinned `message` for the room. - `message_unpinned`: includes `messageId`; clients clear the pin only when it still matches that ID. -- `room_message`: inbox signal with `room`, `messageId`, `createdAt` and `unreadCount`; the client then runs room sync. +- `room_message`: inbox signal with `room`, `messageId`, `createdAt`, `unreadCount`, `mentionsMe`, `contentPreview` and `sender`; `mentionUnreadCount` is included for mentioned recipients and may be omitted otherwise so clients preserve their current value. The client then runs room sync. - `error`: includes a client-safe `error` message and never contains a stack trace. Example: ```json -{"protocolVersion":1,"type":"room_message","room":{"id":7,"kind":"private","name":"team"},"messageId":52,"createdAt":"2026-08-30 12:00:00","unreadCount":3} +{"protocolVersion":1,"type":"room_message","room":{"id":7,"kind":"private","name":"team"},"messageId":52,"createdAt":"2026-09-01 12:00:00","unreadCount":3,"mentionUnreadCount":1,"mentionsMe":true,"contentPreview":"@alice please review","sender":{"kind":"local","id":4,"username":"bob","displayName":"Bob","avatarUrl":"","source":"edgechat"}} ``` ## Lifecycle and recovery diff --git a/frontend/src/components/chat/ConversationList.vue b/frontend/src/components/chat/ConversationList.vue index 49d84da9..f6a039f8 100644 --- a/frontend/src/components/chat/ConversationList.vue +++ b/frontend/src/components/chat/ConversationList.vue @@ -1,5 +1,5 @@ + + + + diff --git a/frontend/src/components/chat/MessageComposer.vue b/frontend/src/components/chat/MessageComposer.vue index 521f37cb..a87c72d8 100644 --- a/frontend/src/components/chat/MessageComposer.vue +++ b/frontend/src/components/chat/MessageComposer.vue @@ -1,8 +1,9 @@ diff --git a/frontend/src/composables/useBrowserNotifications.js b/frontend/src/composables/useBrowserNotifications.js index 4dd838e4..de1d4bdd 100644 --- a/frontend/src/composables/useBrowserNotifications.js +++ b/frontend/src/composables/useBrowserNotifications.js @@ -119,14 +119,24 @@ export function useBrowserNotifications(options = {}) { return nextMutedRooms.has(key); } - function notifyRoom(room) { - syncPermission(); - if (!enabled.value || isRoomMuted(room)) { + function notifyRoom(event) { + const room = event?.room || event; + syncPermission(); + if (!enabled.value || (isRoomMuted(room) && !event?.mentionsMe)) { return false; } - const notification = new notificationApi(room.name || "EdgeChat", { - body: room.kind === "dm" ? t('notifications.directMessage') : t('notifications.groupMessage'), + const title = event?.mentionsMe + ? t("notifications.mentionedTitle", { room: room.name || "EdgeChat" }) + : room.name || "EdgeChat"; + const senderName = event?.sender?.displayName || event?.sender?.username || ""; + const mentionBody = [senderName, event?.contentPreview].filter(Boolean).join(": "); + const notification = new notificationApi(title, { + body: event?.mentionsMe + ? mentionBody || t("notifications.mentionedBody") + : room.kind === "dm" + ? t('notifications.directMessage') + : t('notifications.groupMessage'), tag: `edgechat:${browserNotificationRoomKey(room)}`, renotify: true, }); diff --git a/frontend/src/composables/useChatRoom.js b/frontend/src/composables/useChatRoom.js index 9b77df9d..844c9b2f 100644 --- a/frontend/src/composables/useChatRoom.js +++ b/frontend/src/composables/useChatRoom.js @@ -247,7 +247,7 @@ export function useChatRoom({ roomSession.disconnect(); } - async function sendMessage() { + async function sendMessage(mentionUserIds = []) { const key = activeRoom.value ? `${activeRoom.value.kind}:${activeRoom.value.id}` : ""; @@ -267,6 +267,7 @@ export function useChatRoom({ type: "send", content: composerText.value, attachment: pendingAttachment.value, + mentionUserIds, }), key, ); diff --git a/frontend/src/composables/useChatSidebar.js b/frontend/src/composables/useChatSidebar.js index 7c7c4531..d1969dab 100644 --- a/frontend/src/composables/useChatSidebar.js +++ b/frontend/src/composables/useChatSidebar.js @@ -22,6 +22,7 @@ function mapChannelItem(channel, subtitle) { lastMessageAt: channel.lastMessageAt || "", dateLabel: formatListTime(channel.lastMessageAt), unreadCount: Number(channel.unreadCount || 0), + mentionUnreadCount: Number(channel.mentionUnreadCount || 0), source: channel, }; } @@ -43,7 +44,8 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api fallback: dm.otherUser.displayName, lastMessageAt: dm.lastMessageAt || "", dateLabel: formatListTime(dm.lastMessageAt), - unreadCount: Number(dm.unreadCount || 0), + unreadCount: Number(dm.unreadCount || 0), + mentionUnreadCount: 0, source: dm, })); @@ -97,7 +99,8 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api function markConversationRead(kind, roomId) { const source = findConversationSource(kind, roomId); if (source) { - source.unreadCount = 0; + source.unreadCount = 0; + source.mentionUnreadCount = 0; } } @@ -105,8 +108,9 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api kind, roomId, lastMessageAt, - unreadCount, - }) { + unreadCount, + mentionUnreadCount, + }) { const source = findConversationSource(kind, roomId); if (!source) { return; @@ -122,9 +126,12 @@ export function useChatSidebar({ applyActiveChannel, selectDm, sidebarApi = api } } - if (unreadCount !== undefined) { - source.unreadCount = Math.max(0, Number(unreadCount || 0)); - } + if (unreadCount !== undefined) { + source.unreadCount = Math.max(0, Number(unreadCount || 0)); + } + if (mentionUnreadCount !== undefined) { + source.mentionUnreadCount = Math.max(0, Number(mentionUnreadCount || 0)); + } } async function refreshSidebar() { diff --git a/frontend/src/composables/useRoomManagement.js b/frontend/src/composables/useRoomManagement.js index 75737d20..f125312b 100644 --- a/frontend/src/composables/useRoomManagement.js +++ b/frontend/src/composables/useRoomManagement.js @@ -35,6 +35,7 @@ export function useRoomManagement({ avatarUrl: "", avatarKey: "", }); + let memberLoadGeneration = 0; const availableInviteUsers = computed(() => { const memberIds = new Set( @@ -92,14 +93,23 @@ export function useRoomManagement({ } async function loadMembers() { - if (!activeRoom.value || activeRoom.value.kind === "dm") { + const room = activeRoom.value; + if (!room || room.kind === "dm") { groupMembers.value = []; return; } + const generation = ++memberLoadGeneration; memberLoading.value = true; try { - const payload = await roomApi.getChannelMembers(activeRoom.value.id); + const payload = await roomApi.getChannelMembers(room.id); + if ( + generation !== memberLoadGeneration || + activeRoom.value?.kind !== room.kind || + Number(activeRoom.value?.id) !== Number(room.id) + ) { + return; + } groupMembers.value = payload.members; activeRoom.value.canManage = payload.room.canManage; activeRoom.value.myRole = payload.room.myRole; @@ -110,9 +120,13 @@ export function useRoomManagement({ activeRoom.value.avatarKey = payload.room.avatarKey || ""; syncGroupSettingsForm(); } catch (currentError) { - error.value = currentError.message; + if (generation === memberLoadGeneration) { + error.value = currentError.message; + } } finally { - memberLoading.value = false; + if (generation === memberLoadGeneration) { + memberLoading.value = false; + } } } @@ -272,11 +286,15 @@ export function useRoomManagement({ watch( () => activeRoom.value && `${activeRoom.value.kind}:${activeRoom.value.id}`, () => { + memberLoadGeneration += 1; groupMembers.value = []; inviteUserId.value = ""; showGroupEditor.value = false; showMemberPanel.value = false; syncGroupSettingsForm(); + if (activeRoom.value?.kind !== "dm") { + void loadMembers(); + } }, ); diff --git a/frontend/src/composables/useUnreadInbox.js b/frontend/src/composables/useUnreadInbox.js index edf1d1fe..c14c4e6a 100644 --- a/frontend/src/composables/useUnreadInbox.js +++ b/frontend/src/composables/useUnreadInbox.js @@ -42,9 +42,10 @@ export function useUnreadInbox({ kind: payload.room.kind, roomId: payload.room.id, lastMessageAt: payload.createdAt, - unreadCount: payload.unreadCount - }); - notifyRoom(payload.room); + unreadCount: payload.unreadCount, + mentionUnreadCount: payload.mentionUnreadCount + }); + notifyRoom(payload); }, }); diff --git a/frontend/src/demo/api.js b/frontend/src/demo/api.js index 99405411..056e3e40 100644 --- a/frontend/src/demo/api.js +++ b/frontend/src/demo/api.js @@ -346,7 +346,10 @@ export async function requestDemo(path, options = {}) { const room = body.kind === 'dm' ? demoState.dms.find((dm) => Number(dm.id) === Number(body.roomId)) : findDemoChannel(body.roomId); - if (room) room.unreadCount = 0; + if (room) { + room.unreadCount = 0; + room.mentionUnreadCount = 0; + } return { ok: true }; } if (method === 'POST' && pathname === '/dm/open') { diff --git a/frontend/src/demo/fixtures.js b/frontend/src/demo/fixtures.js index 54634846..9d4d8713 100644 --- a/frontend/src/demo/fixtures.js +++ b/frontend/src/demo/fixtures.js @@ -107,6 +107,7 @@ export function createDemoFixtures() { memberIds: [1, 2, 3], lastMessageAt: '2026-08-14T09:35:00.000Z', unreadCount: 2, + mentionUnreadCount: 1, createdAt: '2026-07-10T10:00:00.000Z' }, { @@ -208,9 +209,11 @@ export function createDemoFixtures() { }, { id: 112, - content: '收到,我会继续检查移动端消息列表。', + content: '@admin 收到,我会继续检查移动端消息列表。', createdAt: '2026-08-14T09:35:00.000Z', sender: internalSender(users[2]), + mentionUserIds: [1], + mentions: [{ userId: 1, username: 'admin', displayName: '演示管理员' }], attachment: null } ], diff --git a/frontend/src/demo/realtime.js b/frontend/src/demo/realtime.js index 8081e6da..963c1a83 100644 --- a/frontend/src/demo/realtime.js +++ b/frontend/src/demo/realtime.js @@ -19,6 +19,10 @@ function publishInbox(kind, roomId, message, { incrementUnread = false } = {}) { if (room && incrementUnread) { room.unreadCount = Number(room.unreadCount || 0) + 1; } + const mentionsMe = (message.mentionUserIds || []).includes(Number(demoState.session.userId)); + if (room && incrementUnread && mentionsMe) { + room.mentionUnreadCount = Number(room.mentionUnreadCount || 0) + 1; + } const payload = { type: 'room_message', room: { @@ -28,7 +32,11 @@ function publishInbox(kind, roomId, message, { incrementUnread = false } = {}) { }, messageId: message.id, createdAt: message.createdAt, - unreadCount: Number(room?.unreadCount || 0) + unreadCount: Number(room?.unreadCount || 0), + mentionUnreadCount: Number(room?.mentionUnreadCount || 0), + mentionsMe, + contentPreview: message.content, + sender: cloneDemo(message.sender) }; for (const socket of inboxSockets) emit(socket, payload); } @@ -69,7 +77,8 @@ function handleRoomFrame(socket, frame) { roomId: socket.roomId, content: payload.content, attachment: payload.attachment, - sender: currentSender() + sender: currentSender(), + mentionUserIds: payload.mentionUserIds || [] }); publishRoom(socket.kind, socket.roomId, { type: 'message', message: cloneDemo(message) }); @@ -78,9 +87,10 @@ function handleRoomFrame(socket, frame) { const reply = createDemoMessage({ kind: socket.kind, roomId: socket.roomId, - content: 'Telegram 已收到这条消息,并把群内回复同步回 EdgeChat。', + content: '@admin Telegram 已收到这条消息,并把群内回复同步回 EdgeChat。', attachment: null, - sender: telegramSender() + sender: telegramSender(), + mentionUserIds: [demoState.session.userId] }); publishRoom(socket.kind, socket.roomId, { type: 'message', message: cloneDemo(reply) }); publishInbox(socket.kind, socket.roomId, reply, { incrementUnread: true }); diff --git a/frontend/src/demo/state.js b/frontend/src/demo/state.js index 42d922b4..6ff5613b 100644 --- a/frontend/src/demo/state.js +++ b/frontend/src/demo/state.js @@ -63,7 +63,8 @@ export function projectDemoDm(dm) { kind: 'dm', otherUser: projectDemoUser(dm.otherUser), lastMessageAt: dm.lastMessageAt, - unreadCount: dm.unreadCount + unreadCount: dm.unreadCount, + mentionUnreadCount: 0 }; } @@ -78,13 +79,23 @@ export function getDemoMembers(channel) { })); } -export function createDemoMessage({ kind, roomId, content, attachment, sender }) { +export function createDemoMessage({ kind, roomId, content, attachment, sender, mentionUserIds = [] }) { + const normalizedMentionUserIds = [...new Set(mentionUserIds.map(Number))]; const message = { id: demoState.nextMessageId++, content: String(content || ''), createdAt: new Date().toISOString(), sender: cloneDemo(sender), - attachment: attachment ? cloneDemo(attachment) : null + attachment: attachment ? cloneDemo(attachment) : null, + mentionUserIds: normalizedMentionUserIds, + mentions: normalizedMentionUserIds + .map((userId) => findDemoUser(userId)) + .filter(Boolean) + .map((user) => ({ + userId: Number(user.id), + username: user.username, + displayName: user.displayName + })) }; const key = roomKey(kind, roomId); demoState.messages[key] ||= []; diff --git a/frontend/src/locales/en-US.js b/frontend/src/locales/en-US.js index e739bb98..4398a61e 100644 --- a/frontend/src/locales/en-US.js +++ b/frontend/src/locales/en-US.js @@ -113,6 +113,7 @@ export default { 'chat.addAttachment': 'Add attachment', 'chat.messagePlaceholder': 'Type a message...', 'chat.sendMessage': 'Send message', + 'chat.mentionedMe': 'Mentioned you', 'chat.send': 'Send', 'chat.realtimeNotReady': 'The realtime connection is not ready yet. Please try again.', 'chat.sessionInvalid': 'Your session is no longer valid. Please sign in again.', @@ -126,6 +127,8 @@ export default { 'notifications.enable': 'Enable notifications', 'notifications.directMessage': 'You received a new direct message', 'notifications.groupMessage': 'You received a new group message', + 'notifications.mentionedTitle': 'You were mentioned in {room}', + 'notifications.mentionedBody': 'You received a mention', 'conversation.chooseContact': 'Choose a contact you have not chatted with', 'conversation.chooseType': 'Choose a conversation type', 'conversation.startNew': 'Start a new conversation', diff --git a/frontend/src/locales/zh-CN.js b/frontend/src/locales/zh-CN.js index 1c338dc3..0a6ab7e3 100644 --- a/frontend/src/locales/zh-CN.js +++ b/frontend/src/locales/zh-CN.js @@ -113,6 +113,7 @@ export default { 'chat.addAttachment': '添加附件', 'chat.messagePlaceholder': '输入消息...', 'chat.sendMessage': '发送消息', + 'chat.mentionedMe': '有人@我', 'chat.send': '发送', 'chat.realtimeNotReady': '实时连接尚未就绪,请稍后重试', 'chat.sessionInvalid': '登录状态已失效,请重新登录。', @@ -126,6 +127,8 @@ export default { 'notifications.enable': '开启通知', 'notifications.directMessage': '收到一条新私信', 'notifications.groupMessage': '收到一条新群聊消息', + 'notifications.mentionedTitle': '有人在 {room} 提及你', + 'notifications.mentionedBody': '收到一条提及你的消息', 'conversation.chooseContact': '选择一位尚未聊天的联系人', 'conversation.chooseType': '选择要创建的会话类型', 'conversation.startNew': '发起新对话', diff --git a/frontend/src/mentions.js b/frontend/src/mentions.js new file mode 100644 index 00000000..351a9539 --- /dev/null +++ b/frontend/src/mentions.js @@ -0,0 +1,69 @@ +function isMentionBoundary(character) { + return !character || /[\s()[\]{}<>"',。!?、:;,.!?]/u.test(character); +} + +export function contentMentionsUsername(content, username) { + const token = `@${username}`; + let offset = content.indexOf(token); + while (offset !== -1) { + const before = offset > 0 ? content[offset - 1] : ""; + const after = content[offset + token.length] || ""; + if (isMentionBoundary(before) && isMentionBoundary(after)) { + return true; + } + offset = content.indexOf(token, offset + token.length); + } + return false; +} + +export function resolveMentionUserIds(content, users, currentUserId) { + return users + .filter( + (user) => + Number(user.id) !== Number(currentUserId) && + contentMentionsUsername(content, user.username), + ) + .map((user) => Number(user.id)); +} + +export function tokenizeMentionText(content, mentions) { + const sortedMentions = [...mentions] + .filter((mention) => mention.username) + .sort((left, right) => right.username.length - left.username.length); + const tokens = []; + let cursor = 0; + + while (cursor < content.length) { + let nextOffset = -1; + let nextMention = null; + for (const mention of sortedMentions) { + const token = `@${mention.username}`; + let offset = content.indexOf(token, cursor); + while (offset !== -1) { + const before = offset > 0 ? content[offset - 1] : ""; + const after = content[offset + token.length] || ""; + if (isMentionBoundary(before) && isMentionBoundary(after)) { + break; + } + offset = content.indexOf(token, offset + token.length); + } + if (offset !== -1 && (nextOffset === -1 || offset < nextOffset)) { + nextOffset = offset; + nextMention = mention; + } + } + + if (!nextMention || nextOffset === -1) { + tokens.push({ type: "text", text: content.slice(cursor) }); + break; + } + if (nextOffset > cursor) { + tokens.push({ type: "text", text: content.slice(cursor, nextOffset) }); + } + const text = `@${nextMention.username}`; + tokens.push({ type: "mention", text, userId: Number(nextMention.userId) }); + cursor = nextOffset + text.length; + } + + return tokens; +} diff --git a/frontend/src/mentions.ts b/frontend/src/mentions.ts new file mode 100644 index 00000000..87623c8d --- /dev/null +++ b/frontend/src/mentions.ts @@ -0,0 +1,21 @@ +export type MentionUser = { + id: number; + username: string; + displayName?: string; +}; + +export type MessageMention = { + userId: number; + username: string; + displayName?: string; +}; + +export type MentionTextToken = + | { type: "text"; text: string } + | { type: "mention"; text: string; userId: number }; + +export { + contentMentionsUsername, + resolveMentionUserIds, + tokenizeMentionText, +} from "./mentions.js"; diff --git a/frontend/src/pages/ChatPage.vue b/frontend/src/pages/ChatPage.vue index 2c215e43..553e7f5d 100644 --- a/frontend/src/pages/ChatPage.vue +++ b/frontend/src/pages/ChatPage.vue @@ -10,6 +10,7 @@ import GroupSettingsDialog from '../components/chat/GroupSettingsDialog.vue'; import MemberPanel from '../components/chat/MemberPanel.vue'; import MessageAttachment from '../components/chat/MessageAttachment.vue'; import MessageComposer from '../components/chat/MessageComposer.vue'; +import MentionText from '../components/chat/MentionText.vue'; import MessageContextMenu from '../components/chat/MessageContextMenu.vue'; import PinnedMessageBar from '../components/chat/PinnedMessageBar.vue'; import MobileNavigationDrawer from '../components/chat/MobileNavigationDrawer.vue'; @@ -28,6 +29,7 @@ import { useConversationCreation } from '../composables/useConversationCreation. import { useMessageContextMenu } from '../composables/useMessageContextMenu.ts'; import { useRoomManagement } from '../composables/useRoomManagement.js'; import { useUnreadInbox } from '../composables/useUnreadInbox.js'; +import { resolveMentionUserIds } from '../mentions.ts'; import store from '../store.js'; import { useI18n } from '../i18n.js'; @@ -89,8 +91,9 @@ function handleRoomActivity({ room, message }) { applyConversationActivity({ kind: room.kind, roomId: room.id, - lastMessageAt: message.createdAt, - unreadCount: 0 + lastMessageAt: message.createdAt, + unreadCount: 0, + mentionUnreadCount: 0 }); markConversationRead(room.kind, room.id); } @@ -192,6 +195,17 @@ const { invite: inviteMember, remove: removeMember } = memberManagement; +const mentionCandidates = computed(() => + activeRoom.value?.kind === 'dm' + ? [] + : groupMembers.value.filter((member) => Number(member.id) !== Number(session.value?.userId)) +); + +function sendComposerMessage() { + return sendMessage( + resolveMentionUserIds(composerText.value, mentionCandidates.value, session.value?.userId) + ); +} const { show: showGroupEditor, form: groupSettingsForm, @@ -563,7 +577,13 @@ onBeforeUnmount(() => { {{ msg.sender.displayName }} -

{{ msg.content }}

+

+ +

{{ formatBubbleTime(msg.createdAt) }} @@ -586,9 +606,10 @@ onBeforeUnmount(() => { v-model="composerText" :pending-attachment="pendingAttachment" :sending="sending" - :disabled="!activeRoom" - :error="error" - @send="sendMessage" + :disabled="!activeRoom" + :error="error" + :mention-candidates="mentionCandidates" + @send="sendComposerMessage" @upload="uploadAttachment" @clear-attachment="clearAttachment" /> diff --git a/test/api-v1-contract.test.js b/test/api-v1-contract.test.js index 5cd54eb8..3703159c 100644 --- a/test/api-v1-contract.test.js +++ b/test/api-v1-contract.test.js @@ -41,7 +41,9 @@ test("OpenAPI v1 keeps stable auth, idempotency, sync and error fields", () => { "clientUploadId", "syncCursor", "nextCursor", - "hasMore", + "hasMore", + "mentionUserIds", + "mentionUnreadCount", "required: [code, message]", ]) { const escaped = field.replaceAll("[", "\\[").replaceAll("]", "\\]"); @@ -64,4 +66,5 @@ test("WebSocket v1 documents all supported frames and recovery rules", () => { } assert.match(websocket, /1 second, 2 seconds and then 5 seconds/); assert.match(websocket, /HTTP room sync endpoint/); + assert.match(websocket, /mentionsMe/); }); diff --git a/test/browser-notifications.test.js b/test/browser-notifications.test.js index 99a0331d..2459c2f0 100644 --- a/test/browser-notifications.test.js +++ b/test/browser-notifications.test.js @@ -125,6 +125,19 @@ test("会话免打扰阻止通知,取消后通知可聚合并打开会话", as const groupRoom = { kind: "public", id: 3, name: "产品协作" }; assert.equal(notifications.notifyRoom(groupRoom), true); assert.equal(shown[1].options.body, "收到一条新群聊消息"); + + const mentionEvent = { + room: groupRoom, + mentionsMe: true, + contentPreview: "@admin 请看一下", + sender: { displayName: "Alice" }, + }; + assert.equal(notifications.notifyRoom(mentionEvent), true); + assert.equal(shown[2].title, "有人在 产品协作 提及你"); + assert.equal(shown[2].options.body, "Alice: @admin 请看一下"); + notifications.toggleRoomMuted(groupRoom); + assert.equal(notifications.notifyRoom(mentionEvent), true); + assert.equal(shown.length, 4); }); test("浏览器拒绝通知权限时开关保持禁用", async () => { diff --git a/test/chat-sidebar.test.js b/test/chat-sidebar.test.js index 2dc7d480..eae8dda6 100644 --- a/test/chat-sidebar.test.js +++ b/test/chat-sidebar.test.js @@ -62,6 +62,12 @@ test("general 在私信和其他群组之前永久置顶", () => { ["public:4"], ); assert.equal(sidebar.publicGroupItems.value[0].subtitle, "3 位成员"); + sidebar.channels.value[1].unreadCount = 4; + sidebar.channels.value[1].mentionUnreadCount = 2; + assert.equal(sidebar.conversationItems.value.find((item) => item.id === 2).mentionUnreadCount, 2); + sidebar.markConversationRead("private", 2); + assert.equal(sidebar.channels.value[1].unreadCount, 0); + assert.equal(sidebar.channels.value[1].mentionUnreadCount, 0); }); test("未加入公开群确认加入后才进入普通会话列表", async () => { diff --git a/test/data-projections.test.js b/test/data-projections.test.js index 6173f456..1341190b 100644 --- a/test/data-projections.test.js +++ b/test/data-projections.test.js @@ -33,7 +33,7 @@ function createQueryDb(results) { }; } -test("可见频道查询保持七个数值身份绑定与既有 projection", async () => { +test("可见频道查询保持十个数值身份绑定与提及 projection", async () => { const { db, capture } = createQueryDb([ { id: "9", @@ -48,13 +48,14 @@ test("可见频道查询保持七个数值身份绑定与既有 projection", asy can_manage: 0, member_count: "3", last_message_at: null, - unread_count: "2", + unread_count: "2", + mention_unread_count: "1", }, ]); const channels = await listVisibleChannels(db, "7"); - assert.deepEqual(capture.binds, [7, 7, 7, 7, 7, 7, 7]); + assert.deepEqual(capture.binds, [7, 7, 7, 7, 7, 7, 7, 7, 7, 7]); assert.deepEqual(channels[0], { id: 9, name: "General", @@ -70,6 +71,7 @@ test("可见频道查询保持七个数值身份绑定与既有 projection", asy memberCount: 3, lastMessageAt: null, unreadCount: 2, + mentionUnreadCount: 1, }); assert.match(capture.sql, /CASE WHEN c\.name = 'general' THEN 0 ELSE 1 END/); }); @@ -224,9 +226,10 @@ test("站点设置 projection 使用稳定默认值", async () => { test("消息 projection 保持附件和发送者字段", () => { assert.deepEqual( - mapMessage({ - id: "5", - content: "hello", + mapMessage({ + id: "5", + content: "hello", + mentions_json: "[]", created_at: "2026-07-23", sender_id: "2", sender_username: "alice", @@ -239,9 +242,11 @@ test("消息 projection 保持附件和发送者字段", () => { source_attachment_id: null, source_attachment_unique_id: null, }), - { - id: 5, - content: "hello", + { + id: 5, + content: "hello", + mentionUserIds: [], + mentions: [], createdAt: "2026-07-23", source: "edgechat", sender: { diff --git a/test/demo-runtime.test.js b/test/demo-runtime.test.js index 2102b4ce..9de767bd 100644 --- a/test/demo-runtime.test.js +++ b/test/demo-runtime.test.js @@ -139,15 +139,22 @@ test('demo room socket echoes sent messages through the real-time contract', asy }); }); - socket.send(JSON.stringify({ type: 'send', content: '浏览器本地消息', attachment: null })); + socket.send(JSON.stringify({ + type: 'send', + content: '@alice 浏览器本地消息', + attachment: null, + mentionUserIds: [2] + })); assert.equal(frames.length, 1); assert.equal(frames[0].type, 'message'); - assert.equal(frames[0].message.content, '浏览器本地消息'); - assert.equal(frames[0].message.sender.id, 1); + assert.equal(frames[0].message.content, '@alice 浏览器本地消息'); + assert.equal(frames[0].message.sender.id, 1); + assert.deepEqual(frames[0].message.mentionUserIds, [2]); const history = await requestDemo('/messages?kind=public&roomId=1'); - assert.equal(history.messages.at(-1).content, '浏览器本地消息'); + assert.equal(history.messages.at(-1).content, '@alice 浏览器本地消息'); + assert.equal(history.messages.at(-1).mentions[0].username, 'alice'); assert.deepEqual(inboxFrames, []); socket.close(); inboxSocket.close(); diff --git a/test/frontend-mentions.test.js b/test/frontend-mentions.test.js new file mode 100644 index 00000000..c8bb9b7c --- /dev/null +++ b/test/frontend-mentions.test.js @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + resolveMentionUserIds, + tokenizeMentionText, +} from "../frontend/src/mentions.js"; + +test("网页端发送只提交正文中仍存在的提及", () => { + const users = [ + { id: 2, username: "alice", displayName: "Alice" }, + { id: 3, username: "bob", displayName: "Bob" }, + ]; + assert.deepEqual(resolveMentionUserIds("@alice hi", users, 1), [2]); + assert.deepEqual(resolveMentionUserIds("mail@alice.test", users, 1), []); +}); + +test("消息正文按服务端 mention metadata 分段且保留原文", () => { + const tokens = tokenizeMentionText("Hi @alice and @bob.", [ + { userId: 2, username: "alice" }, + { userId: 3, username: "bob" }, + ]); + assert.equal(tokens.map((token) => token.text).join(""), "Hi @alice and @bob."); + assert.deepEqual( + tokens.filter((token) => token.type === "mention").map((token) => token.userId), + [2, 3], + ); +}); diff --git a/test/message-delivery.test.js b/test/message-delivery.test.js index 78957a5d..e9519609 100644 --- a/test/message-delivery.test.js +++ b/test/message-delivery.test.js @@ -25,7 +25,13 @@ test("消息提交 module 统一持久化参数与广播 packet", async () => { assert.deepEqual(calls, [{ env, - args: { channelId: 3, senderId: 7, content: "hello", attachment: { key: "a" } }, + args: { + channelId: 3, + senderId: 7, + content: "hello", + attachment: { key: "a" }, + mentionUserIds: [], + }, }]); assert.equal(result.message, message); assert.deepEqual(JSON.parse(result.packet), { protocolVersion: 1, type: "message", message }); @@ -63,6 +69,9 @@ test("未读投影排除发送者,并行投影所有收件人", async () => { countCalls.push(userId); return new Promise((resolve) => resolvers.set(userId, resolve)); }, + async countMentions(_db, { userId }) { + return userId === 2 ? 1 : 0; + }, async notifyInbox(_env, userId, payload) { notifications.push({ userId, payload }); }, @@ -72,7 +81,13 @@ test("未读投影排除发送者,并行投影所有收件人", async () => { { room: { id: "4", kind: "private", name: "Team" }, senderId: 1, - message: { id: "8", createdAt: "now" }, + message: { + id: "8", + createdAt: "now", + content: "@bob hello", + mentionUserIds: [2], + sender: { displayName: "Alice" }, + }, }, ); await Promise.resolve(); @@ -89,7 +104,11 @@ test("未读投影排除发送者,并行投影所有收件人", async () => { room: { id: 4, kind: "private", name: "Team" }, messageId: 8, createdAt: "now", - unreadCount: 5, + unreadCount: 5, + mentionUnreadCount: 1, + mentionsMe: true, + contentPreview: "@bob hello", + sender: { displayName: "Alice" }, }, }, { @@ -100,7 +119,10 @@ test("未读投影排除发送者,并行投影所有收件人", async () => { room: { id: 4, kind: "private", name: "Team" }, messageId: 8, createdAt: "now", - unreadCount: 6, + unreadCount: 6, + mentionsMe: false, + contentPreview: "@bob hello", + sender: { displayName: "Alice" }, }, }, ]); @@ -117,6 +139,9 @@ test("单个未读收件人失败被隔离,成员查询失败也不阻塞提 if (userId === 2) throw new Error("count failed"); return 1; }, + async countMentions() { + return 0; + }, async notifyInbox(_env, userId) { notifications.push(userId); }, diff --git a/test/message-mentions.test.js b/test/message-mentions.test.js new file mode 100644 index 00000000..25e2cd0e --- /dev/null +++ b/test/message-mentions.test.js @@ -0,0 +1,112 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import initSqlJs from "sql.js"; + +import { listVisibleChannels } from "../worker/src/data/channels.js"; +import { + insertMessage, + listMessages, +} from "../worker/src/data/messages.js"; +import { + contentMentionsUsername, + normalizeMentionUserIds, + resolveMessageMentionUserIds, +} from "../worker/src/data/mentions.js"; +import { countUnreadMentions, markRoomRead } from "../worker/src/data/unread.js"; +import { createD1Adapter } from "./support/d1.js"; + +const SQL = await initSqlJs(); + +function encodedKey() { + return Buffer.from(Uint8Array.from({ length: 32 }, (_, index) => index + 1)).toString("base64"); +} + +function createEnvironment() { + const database = new SQL.Database(); + database.exec(readFileSync(new URL("../worker/schema.sql", import.meta.url), "utf8")); + return { + database, + env: { + DB: createD1Adapter(database), + EDGECHAT_ENCRYPTION_KEYRING: JSON.stringify({ + activeKeyId: "test-v1", + keys: { "test-v1": encodedKey() }, + }), + }, + }; +} + +function insertUser(database, username, displayName = username) { + database.run( + "INSERT INTO users (username, display_name, password_hash, password_salt) VALUES (?, ?, 'hash', 'salt')", + [username, displayName], + ); + return Number(database.exec("SELECT last_insert_rowid()")[0].values[0][0]); +} + +test("提及文本使用完整用户名边界并去重候选 ID", () => { + assert.equal(contentMentionsUsername("hi @alice, please review", "alice"), true); + assert.equal(contentMentionsUsername("mail@example.com", "example.com"), false); + assert.equal(contentMentionsUsername("@alice2", "alice"), false); + assert.deepEqual(normalizeMentionUserIds([2, "2", 3, 0, -1, "bad"]), [2, 3]); +}); + +test("服务端只保留正文真实出现且仍属于当前群的提及", async () => { + const { database, env } = createEnvironment(); + const senderId = insertUser(database, "alice", "Alice"); + const bobId = insertUser(database, "bob", "Bob"); + const carolId = insertUser(database, "carol", "Carol"); + database.run("INSERT INTO channels (name, kind, created_by) VALUES ('mentions', 'private', ?)", [senderId]); + const channelId = Number(database.exec("SELECT last_insert_rowid()")[0].values[0][0]); + database.run( + "INSERT INTO channel_members (channel_id, user_id, role) VALUES (?, ?, 'owner'), (?, ?, 'member')", + [channelId, senderId, channelId, bobId], + ); + + const mentionUserIds = await resolveMessageMentionUserIds(env.DB, { + channelId, + roomKind: "public", + senderId, + content: "@bob 请看,carol 没有被真实提及", + candidateUserIds: [senderId, bobId, carolId, 999], + }); + assert.deepEqual(mentionUserIds, [bobId]); + assert.deepEqual( + await resolveMessageMentionUserIds(env.DB, { + channelId, + roomKind: "dm", + senderId, + content: "@bob", + candidateUserIds: [bobId], + }), + [], + ); +}); + +test("消息提及随历史消息返回,并基于已读游标清除会话标志", async () => { + const { database, env } = createEnvironment(); + const senderId = insertUser(database, "alice", "Alice"); + const bobId = insertUser(database, "bob", "Bob"); + const channelId = Number(database.exec("SELECT id FROM channels WHERE name = 'general'")[0].values[0][0]); + + const message = await insertMessage(env, { + channelId, + senderId, + content: "@bob hello", + mentionUserIds: [bobId], + }); + assert.deepEqual(message.mentionUserIds, [bobId]); + assert.equal(message.mentions[0].username, "bob"); + assert.equal((await listMessages(env, channelId)).at(-1).mentions[0].displayName, "Bob"); + assert.equal(await countUnreadMentions(env.DB, { channelId, userId: bobId }), 1); + const channel = (await listVisibleChannels(env.DB, bobId)).find((item) => item.id === channelId); + assert.equal(channel.mentionUnreadCount, 1); + + await markRoomRead(env.DB, { channelId, userId: bobId, messageId: message.id }); + assert.equal(await countUnreadMentions(env.DB, { channelId, userId: bobId }), 0); + assert.equal( + (await listVisibleChannels(env.DB, bobId)).find((item) => item.id === channelId).mentionUnreadCount, + 0, + ); +}); diff --git a/test/room-management.test.js b/test/room-management.test.js index 4087fb43..4d4f6f24 100644 --- a/test/room-management.test.js +++ b/test/room-management.test.js @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { computed, ref } from "vue"; +import { computed, nextTick, ref } from "vue"; import { useRoomManagement } from "../frontend/src/composables/useRoomManagement.js"; @@ -172,3 +172,32 @@ test("general 管理动作不会发出移除成员或删除群组请求", async assert.equal(calls.length, 0); assert.notEqual(activeRoom.value, null); }); + +test("快速切换群组时旧成员请求不会覆盖当前会话", async () => { + const resolvers = new Map(); + const { management, activeRoom } = createHarness({ + roomApi: { + getChannelMembers(id) { + return new Promise((resolve) => resolvers.set(Number(id), resolve)); + }, + }, + }); + const firstLoad = management.members.load(); + activeRoom.value = { id: 5, kind: "private", name: "Next" }; + await nextTick(); + + resolvers.get(4)({ + room: { name: "Old" }, + members: [{ id: 4, username: "old", displayName: "Old" }], + }); + await firstLoad; + assert.deepEqual(management.members.items.value, []); + assert.equal(activeRoom.value.name, "Next"); + + resolvers.get(5)({ + room: { name: "Next", canManage: false, myRole: "member" }, + members: [{ id: 5, username: "next", displayName: "Next" }], + }); + await nextTick(); + assert.equal(management.members.items.value[0].username, "next"); +}); diff --git a/test/telegram-bridge.test.js b/test/telegram-bridge.test.js index b42eb512..c6bbe52d 100644 --- a/test/telegram-bridge.test.js +++ b/test/telegram-bridge.test.js @@ -325,9 +325,10 @@ test("外部消息密文绑定来源和外部用户 ID", async () => { test("消息 projection 保留 Telegram 来源而不伪造 EdgeChat 账号", () => { assert.deepEqual( - mapMessage({ - id: 12, - content: "hello", + mapMessage({ + id: 12, + content: "hello", + mentions_json: "[]", created_at: "now", sender_kind: "external", external_sender_id: "42", @@ -335,9 +336,11 @@ test("消息 projection 保留 Telegram 来源而不伪造 EdgeChat 账号", () external_sender_avatar_url: null, source: "telegram", }), - { - id: 12, - content: "hello", + { + id: 12, + content: "hello", + mentionUserIds: [], + mentions: [], createdAt: "now", source: "telegram", sender: { diff --git a/test/unread-inbox.test.js b/test/unread-inbox.test.js index 29f2999b..4a568dc9 100644 --- a/test/unread-inbox.test.js +++ b/test/unread-inbox.test.js @@ -57,6 +57,8 @@ const messagePayload = { messageId: 18, createdAt: "2026-08-16T10:00:00.000Z", unreadCount: 3, + mentionUnreadCount: 1, + mentionsMe: true, }; test("正在查看且页面聚焦的会话直接标记已读,不弹通知", () => { @@ -81,7 +83,7 @@ test("页面失焦或消息来自其他会话时保留未读并触发通知", () }); hiddenActiveRoom.emit(messagePayload); assert.equal(hiddenActiveRoom.activity.length, 1); - assert.deepEqual(hiddenActiveRoom.notified, [messagePayload.room]); + assert.deepEqual(hiddenActiveRoom.notified, [messagePayload]); assert.deepEqual(hiddenActiveRoom.read, []); const otherRoom = createInboxHarness({ @@ -90,5 +92,6 @@ test("页面失焦或消息来自其他会话时保留未读并触发通知", () }); otherRoom.emit(messagePayload); assert.equal(otherRoom.activity[0].unreadCount, 3); - assert.deepEqual(otherRoom.notified, [messagePayload.room]); + assert.equal(otherRoom.activity[0].mentionUnreadCount, 1); + assert.deepEqual(otherRoom.notified, [messagePayload]); }); diff --git a/worker/migrations/2026-09-01-message-mentions.sql b/worker/migrations/2026-09-01-message-mentions.sql new file mode 100644 index 00000000..ffca7f9a --- /dev/null +++ b/worker/migrations/2026-09-01-message-mentions.sql @@ -0,0 +1 @@ +ALTER TABLE messages ADD COLUMN mention_user_ids TEXT NOT NULL DEFAULT '[]'; diff --git a/worker/schema.sql b/worker/schema.sql index de622633..9bd94e99 100644 --- a/worker/schema.sql +++ b/worker/schema.sql @@ -112,6 +112,7 @@ CREATE TABLE IF NOT EXISTS messages ( source_attachment_id TEXT, source_attachment_unique_id TEXT, client_message_id TEXT, + mention_user_ids TEXT NOT NULL DEFAULT '[]', created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, deleted_at TEXT, CHECK ( diff --git a/worker/src/api/v1.js b/worker/src/api/v1.js index bf80e88e..8deb30df 100644 --- a/worker/src/api/v1.js +++ b/worker/src/api/v1.js @@ -229,9 +229,10 @@ export function registerV1Routes(app) { action: { type: 'send', clientMessageId: payload.clientMessageId, - content: payload.content, - attachment: payload.attachment || null - } + content: payload.content, + attachment: payload.attachment || null, + mentionUserIds: payload.mentionUserIds || [] + } }); }); diff --git a/worker/src/data/channels.js b/worker/src/data/channels.js index 35ccd530..01b1341b 100644 --- a/worker/src/data/channels.js +++ b/worker/src/data/channels.js @@ -16,6 +16,7 @@ function mapVisibleChannel(row) { memberCount: Number(row.member_count || 0), lastMessageAt: row.last_message_at || null, unreadCount: Number(row.unread_count || 0), + mentionUnreadCount: Number(row.mention_unread_count || 0), }; } @@ -56,8 +57,17 @@ export async function listVisibleChannels(db, userId) { WHERE m.channel_id = c.id AND m.deleted_at IS NULL AND (m.sender_id IS NULL OR m.sender_id != ?) AND m.id > COALESCE((SELECT mr.last_read_message_id FROM message_reads mr WHERE mr.channel_id = c.id AND mr.user_id = ?), 0)) - ELSE 0 END AS unread_count - FROM channels c + ELSE 0 END AS unread_count, + CASE WHEN EXISTS (SELECT 1 FROM channel_members cm WHERE cm.channel_id = c.id AND cm.user_id = ?) + THEN (SELECT COUNT(*) FROM messages m + WHERE m.channel_id = c.id AND m.deleted_at IS NULL + AND m.id > COALESCE((SELECT mr.last_read_message_id FROM message_reads mr WHERE mr.channel_id = c.id AND mr.user_id = ?), 0) + AND EXISTS ( + SELECT 1 FROM json_each(COALESCE(m.mention_user_ids, '[]')) mention_ids + WHERE CAST(mention_ids.value AS INTEGER) = ? + )) + ELSE 0 END AS mention_unread_count + FROM channels c LEFT JOIN users owner ON owner.id = c.created_by WHERE c.kind IN ('public', 'private') AND c.deleted_at IS NULL @@ -68,10 +78,13 @@ export async function listVisibleChannels(db, userId) { c.name ASC`, ) .bind( - normalizedUserId, - normalizedUserId, - normalizedUserId, - normalizedUserId, + normalizedUserId, + normalizedUserId, + normalizedUserId, + normalizedUserId, + normalizedUserId, + normalizedUserId, + normalizedUserId, normalizedUserId, normalizedUserId, normalizedUserId, diff --git a/worker/src/data/mentions.js b/worker/src/data/mentions.js new file mode 100644 index 00000000..cb0ae93d --- /dev/null +++ b/worker/src/data/mentions.js @@ -0,0 +1,64 @@ +import { activeUserSql } from "../user-status.js"; + +export function normalizeMentionUserIds(values) { + if (!Array.isArray(values)) { + return []; + } + return [...new Set(values.map(Number).filter((value) => Number.isInteger(value) && value > 0))]; +} + +function isMentionBoundary(character) { + return !character || /[\s()[\]{}<>"',。!?、:;,.!?]/u.test(character); +} + +export function contentMentionsUsername(content, username) { + const text = String(content || ""); + const token = `@${String(username || "")}`; + if (token.length <= 1) { + return false; + } + + let offset = text.indexOf(token); + while (offset !== -1) { + const before = offset > 0 ? text[offset - 1] : ""; + const after = text[offset + token.length] || ""; + if (isMentionBoundary(before) && isMentionBoundary(after)) { + return true; + } + offset = text.indexOf(token, offset + token.length); + } + return false; +} + +export async function resolveMessageMentionUserIds(db, { + channelId, + roomKind, + senderId, + content, + candidateUserIds, +}) { + const candidates = normalizeMentionUserIds(candidateUserIds).filter( + (userId) => userId !== Number(senderId), + ); + if (roomKind === "dm" || candidates.length === 0) { + return []; + } + + const placeholders = candidates.map(() => "?").join(", "); + const { results } = await db + .prepare( + `SELECT cm.user_id, u.username + FROM channel_members cm + JOIN users u ON u.id = cm.user_id + WHERE cm.channel_id = ? + AND cm.user_id IN (${placeholders}) + AND u.deleted_at IS NULL + AND ${activeUserSql("u")}`, + ) + .bind(Number(channelId), ...candidates) + .all(); + + return results + .filter((row) => contentMentionsUsername(content, row.username)) + .map((row) => Number(row.user_id)); +} diff --git a/worker/src/data/messages.js b/worker/src/data/messages.js index 7343d9cc..96b17366 100644 --- a/worker/src/data/messages.js +++ b/worker/src/data/messages.js @@ -1,5 +1,6 @@ import { decryptMessageContent, encryptMessageContent } from "../encryption.js"; import { pickAttachment, publicFileUrl } from "../utils.js"; +import { normalizeMentionUserIds } from "./mentions.js"; import { fileBelongsToUser } from "./uploaded-files.js"; function toNullableNumber(value) { @@ -10,9 +11,16 @@ function toNullableNumber(value) { export function mapMessage(row, content = row.content) { const isExternal = row.sender_kind === "external"; const isTelegramExternal = isExternal && row.source === "telegram"; + const mentions = JSON.parse(row.mentions_json || "[]").map((mention) => ({ + userId: Number(mention.userId), + username: mention.username, + displayName: mention.displayName, + })); const message = { id: Number(row.id), content, + mentionUserIds: normalizeMentionUserIds(JSON.parse(row.mention_user_ids || "[]")), + mentions, createdAt: row.created_at, source: row.source || "edgechat", sender: { @@ -74,11 +82,21 @@ async function mapDecryptedMessage(env, row) { const MESSAGE_SELECT = `SELECT m.id, m.channel_id, m.content, m.attachment_key, m.attachment_name, m.attachment_type, m.attachment_size, m.sender_kind, m.external_sender_id, m.external_sender_name, - m.external_sender_avatar_url, m.source, m.source_message_id, - m.source_attachment_id, m.source_attachment_unique_id, m.client_message_id, m.created_at, - u.id AS sender_id, u.username AS sender_username, - u.display_name AS sender_display_name, u.avatar_key AS sender_avatar_key - FROM messages m LEFT JOIN users u ON u.id = m.sender_id`; + m.external_sender_avatar_url, m.source, m.source_message_id, + m.source_attachment_id, m.source_attachment_unique_id, m.client_message_id, + m.mention_user_ids, m.created_at, + u.id AS sender_id, u.username AS sender_username, + u.display_name AS sender_display_name, u.avatar_key AS sender_avatar_key, + COALESCE(( + SELECT json_group_array(json_object( + 'userId', mentioned.id, + 'username', mentioned.username, + 'displayName', mentioned.display_name + )) + FROM json_each(COALESCE(m.mention_user_ids, '[]')) mention_ids + JOIN users mentioned ON mentioned.id = CAST(mention_ids.value AS INTEGER) + ), '[]') AS mentions_json + FROM messages m LEFT JOIN users u ON u.id = m.sender_id`; export async function listMessages(env, roomId, before = null, limit = 30) { const filters = ["m.channel_id = ?", "m.deleted_at IS NULL"]; @@ -251,6 +269,7 @@ async function persistMessage(env, { sourceAttachmentId = null, sourceAttachmentUniqueId = null, clientMessageId = null, + mentionUserIds = [], }) { const isExternal = externalSender !== null; const normalizedSenderId = isExternal ? null : Number(senderId); @@ -288,15 +307,19 @@ async function persistMessage(env, { const normalizedClientMessageId = isExternal ? null : String(clientMessageId || "").trim() || null; + const storedMentionUserIds = JSON.stringify( + isExternal ? [] : normalizeMentionUserIds(mentionUserIds), + ); try { const result = await env.DB .prepare( `INSERT INTO messages ( channel_id, sender_id, content, attachment_key, attachment_name, attachment_type, attachment_size, sender_kind, external_sender_id, - external_sender_name, external_sender_avatar_url, source, source_message_id, - source_attachment_id, source_attachment_unique_id, client_message_id - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + external_sender_name, external_sender_avatar_url, source, source_message_id, + source_attachment_id, source_attachment_unique_id, client_message_id, + mention_user_ids + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .bind( Number(channelId), @@ -313,9 +336,10 @@ async function persistMessage(env, { String(source || "edgechat"), sourceMessageId ? String(sourceMessageId) : null, sourceAttachmentId ? String(sourceAttachmentId) : null, - sourceAttachmentUniqueId ? String(sourceAttachmentUniqueId) : null, - normalizedClientMessageId, - ) + sourceAttachmentUniqueId ? String(sourceAttachmentUniqueId) : null, + normalizedClientMessageId, + storedMentionUserIds, + ) .run(); return { message: await getMessageById(env, result.meta.last_row_id), created: true }; } catch (error) { @@ -356,6 +380,7 @@ export async function insertMessage(env, { content, attachment, clientMessageId = null, + mentionUserIds = [], }) { const result = await persistMessage(env, { channelId, @@ -363,6 +388,7 @@ export async function insertMessage(env, { content, attachment, clientMessageId, + mentionUserIds, }); return result.message; } diff --git a/worker/src/data/unread.js b/worker/src/data/unread.js index 796d3bb0..1ff0efd6 100644 --- a/worker/src/data/unread.js +++ b/worker/src/data/unread.js @@ -43,6 +43,27 @@ export async function countUnreadMessages(db, { channelId, userId }) { return Number(results[0]?.unread_count || 0); } +export async function countUnreadMentions(db, { channelId, userId }) { + const { results } = await db + .prepare( + `SELECT COUNT(*) AS unread_count + FROM messages m + WHERE m.channel_id = ? + AND m.deleted_at IS NULL + AND m.id > COALESCE((SELECT mr.last_read_message_id + FROM message_reads mr + WHERE mr.channel_id = ? AND mr.user_id = ?), 0) + AND EXISTS ( + SELECT 1 + FROM json_each(COALESCE(m.mention_user_ids, '[]')) mention_ids + WHERE CAST(mention_ids.value AS INTEGER) = ? + )`, + ) + .bind(Number(channelId), Number(channelId), Number(userId), Number(userId)) + .all(); + return Number(results[0]?.unread_count || 0); +} + export async function listRoomMemberIds(db, channelId) { const { results } = await db .prepare( diff --git a/worker/src/message-submission.js b/worker/src/message-submission.js index 64019fa1..6034fbfc 100644 --- a/worker/src/message-submission.js +++ b/worker/src/message-submission.js @@ -1,4 +1,5 @@ import { insertMessage, insertMessageIdempotent } from "./data/messages.js"; +import { resolveMessageMentionUserIds } from "./data/mentions.js"; export class MessageSubmissionError extends Error { constructor(message, code = "invalid_request", status = 400) { @@ -9,14 +10,25 @@ export class MessageSubmissionError extends Error { } } -export function createMessageSubmission({ persistMessage = insertMessage } = {}) { +export function createMessageSubmission({ + persistMessage = insertMessage, + resolveMentions = resolveMessageMentionUserIds, +} = {}) { return async function submitRoomMessage(env, meta, payload) { try { + const mentionUserIds = await resolveMentions(env.DB, { + channelId: meta.room.id, + roomKind: meta.room.kind, + senderId: meta.principal.userId, + content: payload.content, + candidateUserIds: payload.mentionUserIds, + }); const persistencePayload = { - channelId: meta.room.id, - senderId: meta.principal.userId, - content: payload.content, - attachment: payload.attachment, + channelId: meta.room.id, + senderId: meta.principal.userId, + content: payload.content, + attachment: payload.attachment, + mentionUserIds, }; if (payload.clientMessageId) { persistencePayload.clientMessageId = payload.clientMessageId; diff --git a/worker/src/unread-projection.js b/worker/src/unread-projection.js index 7bce25d3..2b3e3625 100644 --- a/worker/src/unread-projection.js +++ b/worker/src/unread-projection.js @@ -1,4 +1,8 @@ -import { countUnreadMessages, listRoomMemberIds } from "./data/unread.js"; +import { + countUnreadMentions, + countUnreadMessages, + listRoomMemberIds, +} from "./data/unread.js"; import { notifyUserInbox } from "./do-bridge.js"; function logProjectionFailure(message, data) { @@ -7,16 +11,20 @@ function logProjectionFailure(message, data) { export function createUnreadProjection({ countUnread = countUnreadMessages, + countMentions = countUnreadMentions, listMemberIds = listRoomMemberIds, notifyInbox = notifyUserInbox, logFailure = logProjectionFailure, } = {}) { async function notifyRecipient(env, room, message, userId) { try { - const unreadCount = await countUnread(env.DB, { - channelId: room.id, - userId, - }); + const mentionsMe = (message.mentionUserIds || []).includes(Number(userId)); + const [unreadCount, mentionUnreadCount] = await Promise.all([ + countUnread(env.DB, { channelId: room.id, userId }), + mentionsMe + ? countMentions(env.DB, { channelId: room.id, userId }) + : Promise.resolve(undefined), + ]); await notifyInbox(env, userId, { protocolVersion: 1, type: "room_message", @@ -25,10 +33,14 @@ export function createUnreadProjection({ kind: room.kind, name: room.name, }, - messageId: Number(message.id), - createdAt: message.createdAt, - unreadCount, - }); + messageId: Number(message.id), + createdAt: message.createdAt, + unreadCount, + ...(mentionUnreadCount === undefined ? {} : { mentionUnreadCount }), + mentionsMe, + contentPreview: String(message.content || "").slice(0, 160), + sender: message.sender, + }); } catch (error) { logFailure("unread recipient projection failed", { roomId: Number(room.id),