From 0e952f9905c2d469f8ade8bb5fb73290b20b43d4 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 11:48:39 +0200 Subject: [PATCH] feat: the group's messages, seen (group-threshold-ecdh, Phase 8) GroupDmListScreen: conversations with names, the last line and what is unread, and what is still being opened, naming the admins it waits on and how many are queued. GroupDmConversationScreen: messages in and out, outgoing ones with where they have got to. The group's Messages row opens the list; only a current admin sees anything of the group's mail. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 15 + .../repository/DatabaseGroupDmRepository.kt | 97 ++++++ .../giza/compose/managers/GroupDmReceiver.kt | 22 +- .../compose/repository/GroupDmRepository.kt | 17 ++ .../ui/composable/ChatRoomDetailScreen.kt | 15 +- .../compose/ui/composable/GroupDmScreens.kt | 279 ++++++++++++++++++ .../ui/composable/navigation/GizaNavHost.kt | 26 ++ .../navigation/routes/GroupDmRoutes.kt | 19 ++ .../model/GroupDmConversationViewModel.kt | 64 ++++ .../ui/view/model/GroupDmListViewModel.kt | 53 ++++ .../compose/ui/view/state/GroupDmUIState.kt | 65 ++++ .../compose/managers/GroupDmScreenJvmTest.kt | 97 ++++++ 12 files changed, 758 insertions(+), 11 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmRoutes.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmListViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmUIState.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmScreenJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7b557fd8..3a7bdb21 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -757,4 +757,19 @@ Ask the group to sign Couldn't ask the group to sign where it receives messages. Only a current admin holding a share can open the group's messages. + Nobody has written to the group yet + 1 message being opened + %1$d messages being opened + Waiting for 1 more admin to open this + Waiting for %1$d more admins to open this + Not yet answered by %1$s + %1$d more are queued: the group was sent more than its admins open in an hour + A message this screen can't show yet + The group + Signed, not yet sent + Sent + Signed but not sent + Declined by the group + Send again + Only the group's current admins see its messages. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt index 946d0ac4..496f8077 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupDmRepository.kt @@ -57,6 +57,103 @@ class DatabaseGroupDmRepository(private val database: GizaDatabase) : GroupDmRep override suspend fun receiveWrap(wrap: com.vitorpamplona.quartz.nip01Core.core.Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Boolean = mobi.giza.compose.managers.GroupDmReceiver.receive(database, wrap, userPublicKey, nostrPrivateKey) + override fun observeConversations(chatRoomId: HexKey): Flow> = + database.groupDmDao().observeMessages(chatRoomId).map { messages -> + messages.groupBy { it.conversationId }.map { (conversationId, inIt) -> + val newest = inIt.maxBy { it.createdAt } + val participants = participantsIn(chatRoomId, inIt) + mobi.giza.compose.ui.view.state.GroupDmConversationSummary( + conversationId = conversationId, + participants = participants, + names = participants.map { nameOf(it) }, + lastLine = lineOf(newest.rumorJson), + lastAt = newest.createdAt, + unread = inIt.count { !it.outgoing && it.readAt == null }, + ) + }.sortedByDescending { it.lastAt } + } + + override fun observePending(chatRoomId: HexKey): Flow = + kotlinx.coroutines.flow.combine( + database.groupDmDao().observePendingWraps(chatRoomId), + database.groupDmDao().observeOpenPartials(chatRoomId), + ) { wraps, _ -> wraps }.map { wraps -> + val waiting = wraps.filter { it.state == mobi.giza.compose.database.model.GroupDmWrapState.WAITING } + val newest = waiting.maxByOrNull { it.createdAt } + val (needed, notYet) = newest?.let { mobi.giza.compose.managers.GroupDmReceiver.waitingOn(database, chatRoomId, it) } + ?: (0 to emptyList()) + mobi.giza.compose.ui.view.state.GroupDmPending( + waiting = waiting.size, + queued = wraps.count { it.state == mobi.giza.compose.database.model.GroupDmWrapState.QUEUED }, + moreAdminsNeeded = needed, + notYetAnsweredBy = notYet.map { nameOf(it) }, + ) + }.distinctUntilChanged() + + override fun observeConversation(chatRoomId: HexKey, conversationId: HexKey): Flow> = + kotlinx.coroutines.flow.combine( + database.groupDmDao().observeConversation(chatRoomId, conversationId), + database.groupDmDao().observeOutbound(chatRoomId), + ) { messages, outbound -> messages to outbound }.map { (messages, outbound) -> + messages.map { message -> + val owed = message.signingSessionId?.let { id -> outbound.filter { it.signingSessionId == id } }.orEmpty() + mobi.giza.compose.ui.view.state.GroupDmLine( + id = message.rumorId, + text = lineOf(message.rumorJson), + outgoing = message.outgoing, + senderName = nameOf(message.senderPublicKey), + at = message.createdAt, + outgoingState = if (message.outgoing) outgoingStateOf(message.signingSessionId, owed) else null, + signingSessionId = message.signingSessionId, + ) + } + } + + /** + * Where a message the group sent has got to: its signing session, then its wraps. Sent once + * every recipient's wrap is on a relay; signed but not sent when the session completed and + * no wrap is owed here, which is how every device but the proposer's sees it (D10). + */ + private suspend fun outgoingStateOf( + signingSessionId: String?, + owed: List, + ): mobi.giza.compose.ui.view.state.GroupDmOutgoingState? { + val session = signingSessionId?.let { database.frostSigningSessionDao().getSessionById(it) } ?: return null + return when { + session.stage == mobi.giza.compose.database.model.types.FrostSigningStage.FAILED -> + mobi.giza.compose.ui.view.state.GroupDmOutgoingState.DECLINED + session.stage != mobi.giza.compose.database.model.types.FrostSigningStage.COMPLETE -> + mobi.giza.compose.ui.view.state.GroupDmOutgoingState.BEING_SIGNED + owed.isNotEmpty() && owed.all { it.publishedAt != null } -> mobi.giza.compose.ui.view.state.GroupDmOutgoingState.SENT + owed.isNotEmpty() && owed.any { it.attempts > 0 } -> mobi.giza.compose.ui.view.state.GroupDmOutgoingState.NOT_SENT + owed.isNotEmpty() -> mobi.giza.compose.ui.view.state.GroupDmOutgoingState.SIGNED + else -> mobi.giza.compose.ui.view.state.GroupDmOutgoingState.NOT_SENT + } + } + + override suspend fun participantsOf(chatRoomId: HexKey, conversationId: HexKey): List = + participantsIn(chatRoomId, database.groupDmDao().getMessages(chatRoomId).filter { it.conversationId == conversationId }) + + private fun participantsIn(chatRoomId: HexKey, messages: List): List = + messages.flatMap { message -> + runCatching { com.vitorpamplona.quartz.nip01Core.core.Event.fromJson(message.rumorJson) }.getOrNull() + ?.let { mobi.giza.compose.nostr.groupdm.GroupDmConversation.participantsOf(it, chatRoomId) } + .orEmpty() + }.distinct().sorted() + + /** A kind 14's words; null for anything else, which the screen says it cannot show yet. */ + private fun lineOf(rumorJson: String): String? = + runCatching { com.vitorpamplona.quartz.nip01Core.core.Event.fromJson(rumorJson) }.getOrNull() + ?.takeIf { it.kind == 14 }?.content + + override suspend fun markRead(chatRoomId: HexKey, conversationId: HexKey) = + database.groupDmDao().markRead(chatRoomId, conversationId, kotlin.time.Clock.System.now()) + + override suspend fun nameOf(publicKey: HexKey): String = + database.profileDao().getProfileByPublicKey(publicKey) + ?.let { profile -> profile.displayName?.takeIf { it.isNotBlank() && it != "LOADING..." } ?: profile.userName?.takeIf { it.isNotBlank() } } + ?: publicKey.take(8) + override suspend fun isCurrentAdmin(chatRoomId: HexKey, userPublicKey: HexKey): Boolean { val admins = RoomAdmins.of(database, chatRoomId)?.admins ?: return false if (userPublicKey !in admins) return false diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt index 739f16c7..36f6f018 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupDmReceiver.kt @@ -171,13 +171,21 @@ object GroupDmReceiver { if (inserted > 0) logger.i { "Filed a message of kind ${rumor.kind} to ${roomId.take(8)}" } } - /** Who a waiting wrap is waiting on: the current admins with no partial in its open round. */ - suspend fun waitingOn(database: GizaDatabase, context: GroupEcdhManager.RoomContext, ledger: GroupDmWrap): List { - val wrap = runCatching { Event.fromJson(ledger.wrapJson) }.getOrNull() ?: return emptyList() + /** + * What [ledger] waits on: how many more admins have to answer its open round, and which + * current admins have not. Read from public rows only, so a screen can show it. + */ + suspend fun waitingOn(database: GizaDatabase, roomId: HexKey, ledger: GroupDmWrap): Pair> { + val key = FrostSigningManager.completedKey(database, roomId) ?: return 0 to emptyList() + val shares = ShareGenerations.active(database, key) + val roomAdmins = RoomAdmins.of(database, roomId)?.admins.orEmpty() + val admins = shares.signerIds.filterKeys { it in roomAdmins } + val wrap = runCatching { Event.fromJson(ledger.wrapJson) }.getOrNull() ?: return 0 to emptyList() val point = ledger.sealJson?.let { runCatching { Event.fromJson(it).pubKey }.getOrNull() } ?: wrap.pubKey - val round = database.groupDmDao().getRound(GroupEcdhPayload.roundId(context.roomId, context.generation, point)) - ?.takeIf { it.state == GroupEcdhRoundState.OPEN } ?: return emptyList() - val answered = database.groupDmDao().getPartials(round.id).filter { it.verified }.map { it.participantId }.toSet() - return context.admins.filter { (_, entry) -> entry.first !in answered }.keys.sorted() + val round = database.groupDmDao().getRound(GroupEcdhPayload.roundId(roomId, shares.generation, point)) + ?.takeIf { it.state == GroupEcdhRoundState.OPEN } + val answered = round?.let { r -> database.groupDmDao().getPartials(r.id).filter { it.verified }.map { it.participantId }.toSet() }.orEmpty() + val needed = (key.threshold - answered.size).coerceAtLeast(0) + return needed to admins.filterValues { it !in answered }.keys.sorted() } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt index 2b913692..0863856c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupDmRepository.kt @@ -34,6 +34,23 @@ interface GroupDmRepository { /** A wrap a relay sent: into the group's own pipeline if it is one of its, else nothing. Whether it was. */ suspend fun receiveWrap(wrap: com.vitorpamplona.quartz.nip01Core.core.Event, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Boolean + /** The group's conversations, newest first (Phase 8). */ + fun observeConversations(chatRoomId: HexKey): Flow> + + /** What the group was sent and has not opened yet, and on whom it waits. */ + fun observePending(chatRoomId: HexKey): Flow + + /** One conversation's messages, oldest first, in and out. */ + fun observeConversation(chatRoomId: HexKey, conversationId: HexKey): Flow> + + /** The participants of [conversationId], from the messages this device holds. */ + suspend fun participantsOf(chatRoomId: HexKey, conversationId: HexKey): List + + suspend fun markRead(chatRoomId: HexKey, conversationId: HexKey) + + /** How a screen names a person: their profile's name, or the start of their key. */ + suspend fun nameOf(publicKey: HexKey): String + /** Asks the group to sign [relays] as where it receives messages (D8). */ suspend fun proposeRelays(localChatRoom: LocalChatRoom, userPublicKey: HexKey, relays: List): FrostSigningSession } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 4590cd5b..76180344 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -765,10 +765,17 @@ fun ChatRoomDetailScreen( row = row, onClick = { onNavigateToRoute.invoke( - GroupDmSetupRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - ) + if (row is GroupDmRow.Messages) { + mobi.giza.compose.ui.composable.navigation.routes.GroupDmListRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + ) + } else { + GroupDmSetupRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + ) + } ) } ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt new file mode 100644 index 00000000..54788074 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupDmScreens.kt @@ -0,0 +1,279 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ChevronRight +import androidx.compose.material.icons.filled.HourglassTop +import androidx.compose.material.icons.filled.Mail +import androidx.compose.material3.Badge +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupDmRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.a_message_this_screen_cant_show_yet +import mobi.giza.compose.resources.being_signed +import mobi.giza.compose.resources.declined_by_the_group +import mobi.giza.compose.resources.group_messages +import mobi.giza.compose.resources.n_messages_being_opened +import mobi.giza.compose.resources.n_more_are_queued +import mobi.giza.compose.resources.n_unread +import mobi.giza.compose.resources.nobody_has_written_to_the_group_yet +import mobi.giza.compose.resources.not_yet_answered_by +import mobi.giza.compose.resources.one_message_being_opened +import mobi.giza.compose.resources.only_current_admins_see_the_groups_messages +import mobi.giza.compose.resources.send_again +import mobi.giza.compose.resources.sent +import mobi.giza.compose.resources.signed_but_not_sent +import mobi.giza.compose.resources.signed_not_yet_sent +import mobi.giza.compose.resources.the_group +import mobi.giza.compose.resources.waiting_for_n_more_admins_to_open_this +import mobi.giza.compose.resources.waiting_for_one_more_admin_to_open_this +import mobi.giza.compose.ui.composable.navigation.routes.GroupDmConversationRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupDmConversationViewModel +import mobi.giza.compose.ui.view.model.GroupDmListViewModel +import mobi.giza.compose.ui.view.state.GroupDmConversationUIState +import mobi.giza.compose.ui.view.state.GroupDmLine +import mobi.giza.compose.ui.view.state.GroupDmListUIState +import mobi.giza.compose.ui.view.state.GroupDmOutgoingState +import mobi.giza.compose.ui.view.state.GroupDmPending +import org.jetbrains.compose.resources.stringResource + +/** + * A group's conversations (docs/group-threshold-ecdh.md, Phase 8): who has written, the last + * line, what is unread, and what is still being opened, naming the admins it waits on rather + * than a count. Nothing here says how the opening works; a person reads "waiting for 1 more + * admin", not a protocol. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupDmListScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + chatRepository: ChatRepository, + groupDmRepository: GroupDmRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, + composer: (@Composable () -> Unit)? = null, +) { + val viewModel: GroupDmListViewModel = viewModel( + factory = GroupDmListViewModel.factory(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository) + ) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.group_messages), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + floatingActionButton = { composer?.invoke() }, + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + GroupDmListUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + // The room came from a navigation argument; reading it again fails the same way. + is GroupDmListUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) + is GroupDmListUIState.Loaded -> LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + if (!state.isAdmin) { + item { EmptyState(message = stringResource(Res.string.only_current_admins_see_the_groups_messages), icon = Icons.Default.Mail) } + return@LazyColumn + } + if (state.pending.waiting > 0 || state.pending.queued > 0) { + item { PendingCard(state.pending) } + } + if (state.conversations.isEmpty()) { + item { EmptyState(message = stringResource(Res.string.nobody_has_written_to_the_group_yet), icon = Icons.Default.Mail) } + } + items(items = state.conversations, key = { it.conversationId }) { conversation -> + Card( + modifier = Modifier.fillMaxWidth(), + onClick = { + onNavigateToRoute(GroupDmConversationRoute(activeUserPublicKey, chatRoomId, conversation.conversationId)) + }, + ) { + ListItem( + leadingContent = { Icon(Icons.Default.Mail, contentDescription = Decorative) }, + trailingContent = { + if (conversation.unread > 0) { + Badge { Text(stringResource(Res.string.n_unread, conversation.unread)) } + } else { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + } + }, + headlineContent = { Text(conversation.names.joinToString(", "), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text( + conversation.lastLine ?: stringResource(Res.string.a_message_this_screen_cant_show_yet), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + }, + ) + } + } + } + } + } + } +} + +/** What is still being opened, and on whom it waits. */ +@Composable +internal fun PendingCard(pending: GroupDmPending) { + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(Icons.Default.HourglassTop, contentDescription = Decorative) }, + headlineContent = { + Text( + if (pending.waiting == 1) stringResource(Res.string.one_message_being_opened) + else stringResource(Res.string.n_messages_being_opened, pending.waiting) + ) + }, + supportingContent = { + Column { + when { + pending.moreAdminsNeeded == 1 -> Text(stringResource(Res.string.waiting_for_one_more_admin_to_open_this)) + pending.moreAdminsNeeded > 1 -> Text(stringResource(Res.string.waiting_for_n_more_admins_to_open_this, pending.moreAdminsNeeded)) + } + if (pending.notYetAnsweredBy.isNotEmpty()) { + Text(stringResource(Res.string.not_yet_answered_by, pending.notYetAnsweredBy.joinToString(", "))) + } + if (pending.queued > 0) Text(stringResource(Res.string.n_more_are_queued, pending.queued)) + } + }, + ) + } +} + +/** + * One of a group's conversations, in and out (Phase 8). A message the group sent shows where it + * has got to, and one signed but not on a relay offers Send again (Phase 9). + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupDmConversationScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + conversationId: HexKey?, + recipients: List, + chatRepository: ChatRepository, + groupDmRepository: GroupDmRepository, + onNavigateBack: () -> Unit, + onSendAgain: ((signingSessionId: String) -> Unit)? = null, + composer: (@Composable (participants: List, replyTo: GroupDmLine?) -> Unit)? = null, +) { + val viewModel: GroupDmConversationViewModel = viewModel( + key = "$chatRoomId/$conversationId/${recipients.joinToString(",")}", + factory = GroupDmConversationViewModel.factory(chatRoomId, activeUserPublicKey, conversationId, recipients, chatRepository, groupDmRepository) + ) + + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + GroupDmConversationUIState.Loading -> LoadingDataIndicator() + is GroupDmConversationUIState.Error -> ErrorState(message = state.message, onRetry = null) + is GroupDmConversationUIState.Loaded -> Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(state.names.joinToString(", "), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + bottomBar = { + if (state.isAdmin) composer?.invoke(state.participants, state.lines.lastOrNull { !it.outgoing }) + }, + ) { padding -> + LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + if (!state.isAdmin) { + item { EmptyState(message = stringResource(Res.string.only_current_admins_see_the_groups_messages), icon = Icons.Default.Mail) } + return@LazyColumn + } + items(items = state.lines, key = { it.id }) { line -> GroupDmBubble(line, onSendAgain) } + } + } + } + } +} + +@Composable +private fun GroupDmBubble(line: GroupDmLine, onSendAgain: ((String) -> Unit)?) { + Box(modifier = Modifier.fillMaxWidth(), contentAlignment = if (line.outgoing) Alignment.CenterEnd else Alignment.CenterStart) { + Card( + colors = if (line.outgoing) CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer) + else CardDefaults.cardColors(), + ) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.compactPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Text( + text = if (line.outgoing) stringResource(Res.string.the_group) else line.senderName, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text(text = line.text ?: stringResource(Res.string.a_message_this_screen_cant_show_yet), style = MaterialTheme.typography.bodyLarge) + line.outgoingState?.let { state -> + Text( + text = stringResource( + when (state) { + GroupDmOutgoingState.BEING_SIGNED -> Res.string.being_signed + GroupDmOutgoingState.SIGNED -> Res.string.signed_not_yet_sent + GroupDmOutgoingState.SENT -> Res.string.sent + GroupDmOutgoingState.NOT_SENT -> Res.string.signed_but_not_sent + GroupDmOutgoingState.DECLINED -> Res.string.declined_by_the_group + } + ), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + val sessionId = line.signingSessionId + if (state == GroupDmOutgoingState.NOT_SENT && sessionId != null && onSendAgain != null) { + TextButton(onClick = { onSendAgain(sessionId) }) { Text(stringResource(Res.string.send_again)) } + } + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 136ecc7f..b81fe02d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -1314,6 +1314,32 @@ fun GizaNavHost( onNavigateBack = { navController.popBackStack() } ) } + // A group's direct messages: docs/group-threshold-ecdh.md, Phase 8. + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + mobi.giza.compose.ui.composable.GroupDmListScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chatRepository = databaseChatRepository, + groupDmRepository = databaseGroupDmRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + mobi.giza.compose.ui.composable.GroupDmConversationScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + conversationId = route.conversationId, + recipients = route.recipients, + chatRepository = databaseChatRepository, + groupDmRepository = databaseGroupDmRepository, + onNavigateBack = { navController.popBackStack() } + ) + } // A group's confederations: docs/confederation.md. composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmRoutes.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmRoutes.kt new file mode 100644 index 00000000..12b6ff4a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupDmRoutes.kt @@ -0,0 +1,19 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** A group's conversations. docs/group-threshold-ecdh.md, Phase 8. */ +@Serializable +data class GroupDmListRoute( + val activeUserPublicKey: String, + val chatRoomId: String, +): Route() + +/** One of a group's conversations, or a new one when [conversationId] is null and [recipients] are given (Phase 9). */ +@Serializable +data class GroupDmConversationRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val conversationId: String?, + val recipients: List = emptyList(), +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt new file mode 100644 index 00000000..e2f2c987 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmConversationViewModel.kt @@ -0,0 +1,64 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupDmRepository +import mobi.giza.compose.ui.view.state.GroupDmConversationUIState + +/** + * One of a group's conversations, watched, and marked read while it is open + * (docs/group-threshold-ecdh.md, Phase 8). A new conversation is [recipients] with nothing in it. + */ +class GroupDmConversationViewModel( + val chatRoomId: String, + val activeUserPublicKey: HexKey, + val conversationId: HexKey?, + val recipients: List, + val chatRepository: ChatRepository, + val groupDmRepository: GroupDmRepository, +) : ViewModel() { + var uiState: GroupDmConversationUIState by mutableStateOf(GroupDmConversationUIState.Loading) + private set + + init { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (room == null) { + uiState = GroupDmConversationUIState.Error("Couldn't find the chat room") + return@launch + } + val isAdmin = groupDmRepository.isCurrentAdmin(chatRoomId, activeUserPublicKey) + val participants = conversationId?.let { groupDmRepository.participantsOf(chatRoomId, it) }?.takeIf { it.isNotEmpty() } ?: recipients + val names = participants.map { groupDmRepository.nameOf(it) } + val lines = if (isAdmin && conversationId != null) groupDmRepository.observeConversation(chatRoomId, conversationId) else flowOf(emptyList()) + lines.collect { current -> + if (isAdmin && conversationId != null) groupDmRepository.markRead(chatRoomId, conversationId) + uiState = GroupDmConversationUIState.Loaded(room, participants, names, current, isAdmin) + } + } + } + + companion object { + fun factory( + chatRoomId: String, + activeUserPublicKey: HexKey, + conversationId: HexKey?, + recipients: List, + chatRepository: ChatRepository, + groupDmRepository: GroupDmRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { GroupDmConversationViewModel(chatRoomId, activeUserPublicKey, conversationId, recipients, chatRepository, groupDmRepository) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmListViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmListViewModel.kt new file mode 100644 index 00000000..fcba88af --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupDmListViewModel.kt @@ -0,0 +1,53 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupDmRepository +import mobi.giza.compose.ui.view.state.GroupDmListUIState + +/** A group's conversations, watched (docs/group-threshold-ecdh.md, Phase 8). */ +class GroupDmListViewModel( + val chatRoomId: String, + val activeUserPublicKey: HexKey, + val chatRepository: ChatRepository, + val groupDmRepository: GroupDmRepository, +) : ViewModel() { + var uiState: GroupDmListUIState by mutableStateOf(GroupDmListUIState.Loading) + private set + + init { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (room == null) { + uiState = GroupDmListUIState.Error("Couldn't find the chat room") + return@launch + } + val isAdmin = groupDmRepository.isCurrentAdmin(chatRoomId, activeUserPublicKey) + combine(groupDmRepository.observeConversations(chatRoomId), groupDmRepository.observePending(chatRoomId)) { conversations, pending -> + // D12: only a current admin sees anything of the group's mail. + GroupDmListUIState.Loaded( + localChatRoom = room, + conversations = if (isAdmin) conversations else emptyList(), + pending = if (isAdmin) pending else mobi.giza.compose.ui.view.state.GroupDmPending(), + isAdmin = isAdmin, + ) + }.collect { uiState = it } + } + } + + companion object { + fun factory(chatRoomId: String, activeUserPublicKey: HexKey, chatRepository: ChatRepository, groupDmRepository: GroupDmRepository): ViewModelProvider.Factory = + viewModelFactory { initializer { GroupDmListViewModel(chatRoomId, activeUserPublicKey, chatRepository, groupDmRepository) } } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmUIState.kt new file mode 100644 index 00000000..299c29b4 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupDmUIState.kt @@ -0,0 +1,65 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +/** One of the group's conversations, for its list (docs/group-threshold-ecdh.md, Phase 8). */ +data class GroupDmConversationSummary( + val conversationId: HexKey, + val participants: List, + val names: List, + /** The newest message's words, or null for one the screen cannot show yet. */ + val lastLine: String?, + val lastAt: Instant, + val unread: Int, +) + +/** What the group was sent that its admins have not opened yet, and on whom it waits. */ +data class GroupDmPending( + val waiting: Int = 0, + val queued: Int = 0, + /** How many more admins have to answer the newest waiting message. */ + val moreAdminsNeeded: Int = 0, + /** The current admins who have not answered it, by name. */ + val notYetAnsweredBy: List = emptyList(), +) + +sealed interface GroupDmListUIState { + data object Loading : GroupDmListUIState + data class Error(val message: String) : GroupDmListUIState + data class Loaded( + val localChatRoom: LocalChatRoom, + val conversations: List, + val pending: GroupDmPending, + val isAdmin: Boolean, + ) : GroupDmListUIState +} + +/** Where a message the group sends has got to (Phase 9). */ +enum class GroupDmOutgoingState { BEING_SIGNED, SIGNED, SENT, NOT_SENT, DECLINED } + +/** One message in a conversation, in or out. */ +data class GroupDmLine( + val id: HexKey, + /** The words, or null for a kind this screen cannot show yet. */ + val text: String?, + val outgoing: Boolean, + val senderName: String, + val at: Instant, + val outgoingState: GroupDmOutgoingState? = null, + /** The signing session a message the group sent went out in, for Send again. */ + val signingSessionId: String? = null, +) + +sealed interface GroupDmConversationUIState { + data object Loading : GroupDmConversationUIState + data class Error(val message: String) : GroupDmConversationUIState + data class Loaded( + val localChatRoom: LocalChatRoom, + val participants: List, + val names: List, + val lines: List, + val isAdmin: Boolean, + ) : GroupDmConversationUIState +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmScreenJvmTest.kt new file mode 100644 index 00000000..ab7f0ffc --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupDmScreenJvmTest.kt @@ -0,0 +1,97 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.repository.DatabaseGroupDmRepository +import mobi.giza.compose.ui.view.state.GroupDmPending +import mobi.giza.compose.ui.view.state.GroupDmRow + +/** + * Phase 8 of docs/group-threshold-ecdh.md, read through the repositories the screens read: who + * sees which row on the group's screen, what the list says before anybody has written, and + * what a message still being opened waits on, by name. + */ +class GroupDmScreenJvmTest { + private val net = GroupDmNetwork(n = 4, t = 2) + private val a get() = net.devices[0] + private val b get() = net.devices[1] + private val d get() = net.devices[3] + + @BeforeTest + fun setUp() = runBlocking { + ExperimentalFeatures.groupDirectMessagesOverride = true + net.admins = net.members.take(3).toSet() + net.install() + net.all() + Unit + } + + @AfterTest + fun tearDown() { + net.close() + ExperimentalFeatures.groupDirectMessagesOverride = null + } + + private fun chat(device: GroupDmNetwork.Device) = DatabaseChatRepository(device.db, CoroutineScope(Dispatchers.IO)) + + @Test + fun `the rows by role, before and after the group opens its messages`(): Unit = runBlocking { + assertEquals(GroupDmRow.OpenMessages, chat(a).groupDmRow(net.roomId, a.publicKey), "an admin is offered to open them") + assertNull(chat(d).groupDmRow(net.roomId, d.publicKey), "a member who is not an admin sees nothing yet") + + net.openMessages() + assertEquals(GroupDmRow.Messages(unread = 0), chat(a).groupDmRow(net.roomId, a.publicKey)) + assertEquals(GroupDmRow.ReceivesMessages, chat(d).groupDmRow(net.roomId, d.publicKey), "the 10050 is public, and only that") + + ExperimentalFeatures.groupDirectMessagesOverride = false + assertNull(chat(a).groupDmRow(net.roomId, a.publicKey), "off, the feature shows nothing") + } + + @Test + fun `nobody has written yet, and then one message waits on one more admin, by name`(): Unit = runBlocking { + net.openMessages() + val repository = DatabaseGroupDmRepository(a.db) + assertEquals(emptyList(), repository.observeConversations(net.roomId).first()) + assertEquals(GroupDmPending(), repository.observePending(net.roomId).first()) + + // Only A's app is open: A answers, and the message waits on one more. + val wrap = net.wrapFrom(KeyPair(), "dumela") + net.receive(wrap, a) + val pending = repository.observePending(net.roomId).first() + assertEquals(1, pending.waiting) + assertEquals(1, pending.moreAdminsNeeded) + assertEquals(listOf(b.publicKey, net.devices[2].publicKey).sorted().map { it.take(8) }, pending.notYetAnsweredBy.sorted()) + + // B opens the app: the message opens, and is unread. + net.receive(wrap, b) + net.pump(between = listOf(a, b)) + assertEquals(GroupDmPending(), repository.observePending(net.roomId).first()) + val conversation = repository.observeConversations(net.roomId).first().single() + assertEquals("dumela", conversation.lastLine) + assertEquals(1, conversation.unread) + assertEquals(GroupDmRow.Messages(unread = 1), chat(a).groupDmRow(net.roomId, a.publicKey)) + + repository.markRead(net.roomId, conversation.conversationId) + assertEquals(0, repository.observeConversations(net.roomId).first().single().unread) + val lines = repository.observeConversation(net.roomId, conversation.conversationId).first() + assertEquals(listOf("dumela"), lines.map { it.text }) + } + + @Test + fun `a member who is not an admin reads no conversation`(): Unit = runBlocking { + net.openMessages() + assertEquals(false, DatabaseGroupDmRepository(d.db).isCurrentAdmin(net.roomId, d.publicKey)) + assertEquals(true, DatabaseGroupDmRepository(a.db).isCurrentAdmin(net.roomId, a.publicKey)) + } +}