From ef33349e7f8d14dc07963be99774ebcae6f2664f Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:26:15 +0200 Subject: [PATCH] feat: the member row's menu, and leaving as an admin (member-admin-promotion, Phases 10 and 11, convenient rooms) Each member row says Admin and Holds a share as two labels, read off the group's state and the Shares roster; when they disagree a share is owed or still to be rotated away. An admin's row has an overflow menu whose items AdminGovernance.memberActions decides: make admin, remove as admin, step down on your own row, remove from group. Promotion and demotion ask first, and promotion says what it gives away. Leave group, pressed by an admin, opens a dialog instead of a refusal: step down and leave when another admin remains, or, for the only admin, pick who takes over (or disband instead). stepDownAndLeave chains the commits through MarmotEngine.afterConfirmed, which is now registered before the commit it waits on and taken back if publishing throws. Keyed rooms keep removal only; their admins wait on the group's signature. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 21 ++ .../compose/database/dao/MarmotOutboundDao.kt | 53 ++++- .../repository/DatabaseChatRepository.kt | 4 + .../giza/compose/managers/AdminGovernance.kt | 32 +++ .../giza/compose/managers/MarmotEngine.kt | 11 +- .../giza/compose/repository/ChatRepository.kt | 9 + .../ui/composable/ChatRoomDetailScreen.kt | 134 ++++++++++-- .../ui/composable/MemberAdminControls.kt | 190 ++++++++++++++++++ .../ui/view/model/ChatRoomDetailViewModel.kt | 64 +++++- .../ui/view/state/ChatRoomDetailUIState.kt | 17 ++ .../compose/ui/view/state/MemberAction.kt | 33 +++ .../compose/managers/AdminChangesJvmTest.kt | 61 ++++++ .../ui/composable/ChatRoomMemberRowJvmTest.kt | 41 +++- 13 files changed, 645 insertions(+), 25 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 258025f3..1fce5938 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -107,6 +107,27 @@ Learn more Leave group Couldn't leave the group + Member actions + Admin + Holds a share + Make admin + Make %1$s an admin? + They'll be able to add and remove members, including you, change who the admins are, and disband the group. + Remove as admin + Remove %1$s as admin? + They stay in the group as a member. + Step down as admin + Step down as admin? + You stay in the group as a member. Only an admin can make you one again. + Step down + Sent; it takes effect once a relay accepts it + Leave the group? + You're an admin, so you'll step down first, then leave once a relay accepts it. + Step down and leave + You're the only admin. Pick someone to make an admin before you leave. + Make admin and leave + Disband group instead + Stepping down; you'll leave once a relay accepts it Remove from group Disband group This group was disbanded. Nothing more can be sent into it, and nobody can rejoin. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt index da43e26a..6d70c8ed 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt @@ -876,8 +876,7 @@ abstract class MarmotOutboundDao( ?: throw IllegalArgumentException("$memberPublicKey is not in the group") if (memberPublicKey in group.currentAdminIdentities()) { - publishAdmins(localChatRoom) { admins -> admins - memberPublicKey } - engine.afterConfirmed(localChatRoom.routingId) { + thenAfterConfirmed(localChatRoom, publish = { publishAdmins(localChatRoom) { admins -> admins - memberPublicKey } }) { database.chatRoomDao().findChatRoomById(localChatRoom.chatRoom.id) ?.let { removeMember(it, memberPublicKey) } } @@ -933,6 +932,56 @@ abstract class MarmotOutboundDao( publishAdmins(localChatRoom) { admins -> admins - adminPublicKey } } + /** + * Leaves a convenient room this device administers, which an admin cannot do + * directly: the library refuses an admin's SelfRemove. Steps down first and + * leaves once that commit is accepted -- and, for the only admin, makes [heir] + * an admin before that, so the room is never left with nobody to govern it. + * + * The chain is held in memory ([MarmotEngine.afterConfirmed]). A restart part + * way through leaves this device a member that has not left, possibly no + * longer an admin, and **Leave group** finishes it. See + * docs/member-admin-promotion.md, Phase 10. + */ + @Transaction + open suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) { + val me = localChatRoom.chatRoom.userPublicKey + val roomId = localChatRoom.chatRoom.id + val group = database.marmotEngine.groupFor(localChatRoom.routingId) + ?: throw MarmotMissingChatGroupException("No live group for $roomId") + suspend fun fresh() = database.chatRoomDao().findChatRoomById(roomId) + val leaveOnceAccepted: suspend () -> Unit = { fresh()?.let { leave(it) } } + val admins = group.currentAdminIdentities() + + when { + // Nothing to step down from: leave as any member does. + me !in admins -> leave(localChatRoom) + + heir == null || heir in admins -> + thenAfterConfirmed(localChatRoom, publish = { demote(localChatRoom, me) }, step = leaveOnceAccepted) + + else -> thenAfterConfirmed(localChatRoom, publish = { promote(localChatRoom, heir) }) { + fresh()?.let { room -> thenAfterConfirmed(room, publish = { demote(room, me) }, step = leaveOnceAccepted) } + } + } + } + + /** + * Publishes a commit with [publish] and runs [step] once a relay accepts it. The + * step is registered first, so the acceptance cannot overtake it, and taken back + * if [publish] throws, so a refused change leaves nothing waiting. + */ + private suspend fun thenAfterConfirmed(localChatRoom: LocalChatRoom, publish: suspend () -> Unit, step: suspend () -> Unit) { + val engine = database.marmotEngine + engine.afterConfirmed(localChatRoom.routingId, step) + try { + publish() + } catch (e: Throwable) { + engine.cancelFollowUp(localChatRoom.routingId) + throw e + } + } + /** The room's live group, when this device may change who administers it. */ private suspend fun governedGroup(localChatRoom: LocalChatRoom): MlsGroup { require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room has admins to change" } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 86345ef1..b694e122 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -659,6 +659,10 @@ class DatabaseChatRepository( database.marmotOutboundDao().demote(localChatRoom, adminPublicKey) } + override suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) { + database.marmotOutboundDao().stepDownAndLeave(localChatRoom, heir) + } + override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) { database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt index 478133b6..66fa8c4a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminGovernance.kt @@ -4,6 +4,8 @@ import com.vitorpamplona.marmot.groups.MarmotGroupPermissions import com.vitorpamplona.marmot.groups.currentAdminIdentities import com.vitorpamplona.mls.group.MlsGroup import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.ui.view.state.AdminLeave +import mobi.giza.compose.ui.view.state.MemberAction /** * Who may change who governs a room, in one place, so the screen that offers an @@ -53,4 +55,34 @@ object AdminGovernance { fun canDemote(group: MlsGroup, actor: HexKey, target: HexKey): Boolean = !isKeyedRoom(group) && MarmotGroupPermissions.canDemote(group.currentAdminIdentities(), members(group), actor, target) + + /** + * What [me] may do to each member of [group], for the member rows' menus. Empty + * when [me] does not govern the room. Removal stays offered in a keyed room, + * where it always was; promotion and demotion are not, for [isKeyedRoom]'s + * reason. + */ + fun memberActions(group: MlsGroup, me: HexKey): Map> { + if (!MarmotGroupPermissions.canManage(group.currentAdminIdentities(), me)) return emptyMap() + return members(group).associateWith { member -> + buildSet { + if (member == me) { + if (canDemote(group, me, me)) add(MemberAction.STEP_DOWN) + } else { + if (canPromote(group, me, member)) add(MemberAction.MAKE_ADMIN) + if (canDemote(group, me, member)) add(MemberAction.REMOVE_AS_ADMIN) + if (MarmotGroupPermissions.canRemove(group.currentAdminIdentities(), me, member)) add(MemberAction.REMOVE_FROM_GROUP) + } + } + }.filterValues { it.isNotEmpty() } + } + + /** How **Leave group** goes for [me] in [group]: null when [me] is not an admin. */ + fun adminLeave(group: MlsGroup, me: HexKey): AdminLeave? = when { + me !in group.currentAdminIdentities() -> null + isKeyedRoom(group) -> AdminLeave.CANNOT + canDemote(group, me, me) -> AdminLeave.STEP_DOWN_FIRST + (members(group) - me).isEmpty() -> AdminLeave.CANNOT + else -> AdminLeave.PICK_HEIR + } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt index ace3766c..94892fa9 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotEngine.kt @@ -106,11 +106,20 @@ class MarmotEngine( private val followUps = mutableMapOf Unit>() private val followUpsMutex = Mutex() - /** Runs [step] once [routingId]'s commit now in flight is confirmed. */ + /** + * Runs [step] once [routingId]'s next commit is confirmed. Registered *before* + * that commit is published, so a relay's OK cannot arrive ahead of it; a caller + * whose publish then fails takes it back with [cancelFollowUp]. + */ suspend fun afterConfirmed(routingId: HexKey, step: suspend () -> Unit) { followUpsMutex.withLock { followUps[routingId] = step } } + /** Drops the step [afterConfirmed] registered for [routingId], if any. */ + suspend fun cancelFollowUp(routingId: HexKey) { + takeFollowUp(routingId) + } + private suspend fun takeFollowUp(routingId: HexKey): (suspend () -> Unit)? = followUpsMutex.withLock { followUps.remove(routingId) } private var restored = false diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index d11b84c2..27368c76 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -289,6 +289,13 @@ interface ChatRepository { */ suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) + /** + * Leaves a convenient room this device administers: steps down -- making + * [heir] an admin first, when this device is the only one -- and leaves once + * that is accepted. docs/member-admin-promotion.md, Phase 10. + */ + suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) + /** * Whether [memberPublicKey] holds a live share of the room's key, and so * whether a removal leaves them able to help sign until the shares are @@ -511,6 +518,8 @@ interface ChatRepository { override suspend fun demoteMember(localChatRoom: LocalChatRoom, adminPublicKey: HexKey) = Unit + override suspend fun stepDownAndLeave(localChatRoom: LocalChatRoom, heir: HexKey?) = Unit + override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = false 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 ee1573dd..2189e571 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 @@ -44,6 +44,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @@ -82,6 +83,12 @@ import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.ui.theme.spacing import mobi.giza.compose.resources.couldn_t_leave_the_group +import mobi.giza.compose.resources.admin_change_requested +import mobi.giza.compose.resources.stepping_down_to_leave +import mobi.giza.compose.resources.admin_badge +import mobi.giza.compose.resources.holds_a_share +import mobi.giza.compose.ui.view.state.AdminLeave +import mobi.giza.compose.ui.view.state.MemberAction import mobi.giza.compose.resources.run_by_members import mobi.giza.compose.resources.parent_group import mobi.giza.compose.resources.a_subgroup @@ -185,6 +192,10 @@ fun ChatRoomDetailScreen( val notify = rememberNotifier(rememberCoroutineScope()) val removalRequested = stringResource(Res.string.member_removal_requested) val couldNotLeave = stringResource(Res.string.couldn_t_leave_the_group) + val adminChangeRequested = stringResource(Res.string.admin_change_requested) + val steppingDownToLeave = stringResource(Res.string.stepping_down_to_leave) + val adminLabel = stringResource(Res.string.admin_badge) + val shareLabel = stringResource(Res.string.holds_a_share) val rotationRequested = stringResource(Res.string.share_rotation_requested) val sharesActionSent = stringResource(Res.string.shares_action_sent) @@ -225,6 +236,66 @@ fun ChatRoomDetailScreen( } } is ChatRoomDetailUIState.Loaded -> { + // The change a member row's menu asked for, while its dialog asks first. + var confirmingAdminChange by remember { mutableStateOf?>(null) } + var isLeavingAsAdmin by remember { mutableStateOf(false) } + val nameOf = { publicKey: HexKey -> + chatRoomDetailUIState.localChatRoom.localParticipants + .firstOrNull { it.participant.participantPublicKey == publicKey } + ?.profile?.humanReadableNameOrPubkey() + ?: publicKey.take(8) + } + + confirmingAdminChange?.let { (action, memberPublicKey) -> + ConfirmAdminChangeDialog( + action = action, + memberName = nameOf(memberPublicKey), + onDismiss = { confirmingAdminChange = null }, + onConfirm = { + confirmingAdminChange = null + val room = chatRoomDetailUIState.localChatRoom + val onDone = { failure: String? -> notify(failure ?: adminChangeRequested) } + when (action) { + MemberAction.MAKE_ADMIN -> chatRoomDetailViewModel.makeAdmin(room, memberPublicKey, onDone) + MemberAction.REMOVE_AS_ADMIN, MemberAction.STEP_DOWN -> + chatRoomDetailViewModel.removeAsAdmin(room, memberPublicKey, onDone) + MemberAction.REMOVE_FROM_GROUP -> Unit + } + }, + ) + } + + chatRoomDetailUIState.adminLeave?.takeIf { isLeavingAsAdmin }?.let { adminLeave -> + LeaveAsAdminDialog( + adminLeave = adminLeave, + candidates = chatRoomDetailUIState.localChatRoom.localParticipants + .map { it.participant.participantPublicKey } + .filter { it != chatRoomDetailUIState.localChatRoom.chatRoom.userPublicKey } + .map { it to nameOf(it) }, + onDismiss = { isLeavingAsAdmin = false }, + onDisband = { + isLeavingAsAdmin = false + chatRoomDetailViewModel.disbandGroup( + localChatRoom = chatRoomDetailUIState.localChatRoom, + onPopBackToRoute = onPopBackToRoute, + onFailed = { failure -> notify(failure ?: couldNotLeave) }, + ) + }, + onStepDownAndLeave = { heir -> + isLeavingAsAdmin = false + chatRoomDetailViewModel.stepDownAndLeave( + localChatRoom = chatRoomDetailUIState.localChatRoom, + heir = heir, + onPopBackToRoute = { route -> + notify(steppingDownToLeave) + onPopBackToRoute(route) + }, + onFailed = { failure -> notify(failure ?: couldNotLeave) }, + ) + }, + ) + } + Scaffold( snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, topBar = { @@ -699,24 +770,24 @@ fun ChatRoomDetailScreen( }, trailingContent = { val memberPublicKey = localParticipant.participant.participantPublicKey - if (chatRoomDetailUIState.canGovern && memberPublicKey != activeUserPublicKey) { - // An admin's removal of a member: a commit through the - // publish gate, applied when a relay accepts it, which is - // why the row stays until then. See docs/marmot-v2.md, Phase 7. - IconButton( - onClick = { + val actions = chatRoomDetailUIState.memberActions[memberPublicKey].orEmpty() + if (actions.isNotEmpty()) { + // What this device may do to this member, decided by the + // view model from the group's state. Every one is a commit + // through the publish gate, applied when a relay accepts + // it, which is why the row stays as it is until then. See + // docs/member-admin-promotion.md, Phase 11. + MemberActionsMenu(actions = actions) { action -> + if (action == MemberAction.REMOVE_FROM_GROUP) { chatRoomDetailViewModel.removeMember( localChatRoom = chatRoomDetailUIState.localChatRoom, memberPublicKey = memberPublicKey, ) { failure -> notify(failure ?: removalRequested) } + } else { + confirmingAdminChange = action to memberPublicKey } - ) { - Icon( - Icons.Default.PersonRemove, - contentDescription = stringResource(Res.string.remove_from_group) - ) } } else { Icon( @@ -731,10 +802,27 @@ fun ChatRoomDetailScreen( ) }, supportingContent = { - localParticipant.profile?.about?.let { - Text( - text = it - ) + // Two facts, shown apart: when they disagree, a share is + // still owed or still to be rotated away. + // docs/member-admin-promotion.md, D2. + val memberPublicKey = localParticipant.participant.participantPublicKey + val roles = listOfNotNull( + adminLabel.takeIf { memberPublicKey in chatRoomDetailUIState.adminPublicKeys }, + shareLabel.takeIf { memberPublicKey in chatRoomDetailUIState.shareHolders }, + ) + Column { + if (roles.isNotEmpty()) { + Text( + text = roles.joinToString(" ยท "), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + localParticipant.profile?.about?.let { + Text( + text = it + ) + } } } @@ -810,11 +898,17 @@ fun ChatRoomDetailScreen( // Disabled after we leave, and after the group ends. enabled = chatRoomDetailUIState.localChatRoom.chatRoom.leftGroupAt == null && !chatRoomDetailUIState.isDisbanded, onClick = { - chatRoomDetailViewModel.leaveGroup( - localChatRoom = chatRoomDetailUIState.localChatRoom, - onPopBackToRoute = onPopBackToRoute, - onFailed = { failure -> notify(failure ?: couldNotLeave) }, - ) + // An admin cannot simply leave; they step down first, and + // the only admin hands over. A keyed room's admin has no way + // to yet, and is told so by the refusal leaveGroup reports. + when (chatRoomDetailUIState.adminLeave) { + AdminLeave.STEP_DOWN_FIRST, AdminLeave.PICK_HEIR -> isLeavingAsAdmin = true + else -> chatRoomDetailViewModel.leaveGroup( + localChatRoom = chatRoomDetailUIState.localChatRoom, + onPopBackToRoute = onPopBackToRoute, + onFailed = { failure -> notify(failure ?: couldNotLeave) }, + ) + } } ) { Icon( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt new file mode 100644 index 00000000..64a6710a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberAdminControls.kt @@ -0,0 +1,190 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.minimumInteractiveComponentSize +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.cancel +import mobi.giza.compose.resources.disband_group_instead +import mobi.giza.compose.resources.make_admin +import mobi.giza.compose.resources.make_admin_and_leave +import mobi.giza.compose.resources.make_admin_body +import mobi.giza.compose.resources.make_admin_title +import mobi.giza.compose.resources.member_actions +import mobi.giza.compose.resources.pick_heir_body +import mobi.giza.compose.resources.leave_as_admin_title +import mobi.giza.compose.resources.remove_as_admin +import mobi.giza.compose.resources.remove_as_admin_body +import mobi.giza.compose.resources.remove_as_admin_title +import mobi.giza.compose.resources.remove_from_group +import mobi.giza.compose.resources.step_down +import mobi.giza.compose.resources.step_down_and_leave +import mobi.giza.compose.resources.step_down_and_leave_body +import mobi.giza.compose.resources.step_down_as_admin +import mobi.giza.compose.resources.step_down_body +import mobi.giza.compose.resources.step_down_title +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.state.AdminLeave +import mobi.giza.compose.ui.view.state.MemberAction +import org.jetbrains.compose.resources.stringResource + +/** + * The member row's overflow menu: the actions [actions] allows, and nothing else. + * The view model decides them; this only lays them out. A 48dp `IconButton`, as + * every target is. See docs/member-admin-promotion.md, Phase 11. + */ +@Composable +internal fun MemberActionsMenu( + actions: Set, + onAction: (MemberAction) -> Unit, +) { + var expanded by remember { mutableStateOf(false) } + Box { + IconButton(onClick = { expanded = true }) { + Icon(Icons.Default.MoreVert, contentDescription = stringResource(Res.string.member_actions)) + } + DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { + // In a fixed order, whatever order the set holds them in. + MemberAction.entries.filter { it in actions }.forEach { action -> + DropdownMenuItem( + text = { Text(stringResource(action.label())) }, + onClick = { + expanded = false + onAction(action) + }, + ) + } + } + } +} + +private fun MemberAction.label() = when (this) { + MemberAction.MAKE_ADMIN -> Res.string.make_admin + MemberAction.REMOVE_AS_ADMIN -> Res.string.remove_as_admin + MemberAction.STEP_DOWN -> Res.string.step_down_as_admin + MemberAction.REMOVE_FROM_GROUP -> Res.string.remove_from_group +} + +/** + * Asks before a change to who administers the room. Promotion says what it gives + * away -- the power to remove the person granting it, and to disband the group -- + * because that is the part nobody thinks of in the moment. [memberName] is the + * member's display name; it is unused for [MemberAction.STEP_DOWN]. + */ +@Composable +internal fun ConfirmAdminChangeDialog( + action: MemberAction, + memberName: String, + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + val (title, body, confirm) = when (action) { + MemberAction.MAKE_ADMIN -> Triple( + stringResource(Res.string.make_admin_title, memberName), + stringResource(Res.string.make_admin_body), + stringResource(Res.string.make_admin), + ) + MemberAction.REMOVE_AS_ADMIN -> Triple( + stringResource(Res.string.remove_as_admin_title, memberName), + stringResource(Res.string.remove_as_admin_body), + stringResource(Res.string.remove_as_admin), + ) + MemberAction.STEP_DOWN -> Triple( + stringResource(Res.string.step_down_title), + stringResource(Res.string.step_down_body), + stringResource(Res.string.step_down), + ) + // Removal keeps the immediate action it always had. + MemberAction.REMOVE_FROM_GROUP -> return + } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title) }, + text = { Text(body) }, + confirmButton = { TextButton(onClick = onConfirm) { Text(confirm) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } }, + ) +} + +/** + * **Leave group**, pressed by an admin, who cannot simply leave. Another admin + * remaining: step down, then leave. The only admin: pick who takes over, or + * disband instead -- the choice of who governs the group afterwards is the + * person's, not the device's. docs/member-admin-promotion.md, Phase 10. + * + * [candidates] are the other members, by public key and display name, for the + * [AdminLeave.PICK_HEIR] case. + */ +@Composable +internal fun LeaveAsAdminDialog( + adminLeave: AdminLeave, + candidates: List>, + onStepDownAndLeave: (heir: HexKey?) -> Unit, + onDisband: () -> Unit, + onDismiss: () -> Unit, +) { + var heir by remember { mutableStateOf(null) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(Res.string.leave_as_admin_title)) }, + text = { + when (adminLeave) { + AdminLeave.PICK_HEIR -> Column(modifier = Modifier.selectableGroup()) { + Text(stringResource(Res.string.pick_heir_body)) + candidates.forEach { (publicKey, name) -> + Row( + modifier = Modifier + .fillMaxWidth() + .selectable(selected = heir == publicKey, onClick = { heir = publicKey }, role = Role.RadioButton) + .minimumInteractiveComponentSize() + .padding(vertical = MaterialTheme.spacing.compactPadding), + verticalAlignment = Alignment.CenterVertically, + ) { + // The row is the target; the button only shows the state. + RadioButton(selected = heir == publicKey, onClick = null) + Text(name, modifier = Modifier.padding(start = MaterialTheme.spacing.relatedGap)) + } + } + TextButton(onClick = onDisband) { Text(stringResource(Res.string.disband_group_instead)) } + } + else -> Text(stringResource(Res.string.step_down_and_leave_body)) + } + }, + confirmButton = { + when (adminLeave) { + AdminLeave.PICK_HEIR -> TextButton(onClick = { onStepDownAndLeave(heir) }, enabled = heir != null) { + Text(stringResource(Res.string.make_admin_and_leave)) + } + else -> TextButton(onClick = { onStepDownAndLeave(null) }) { + Text(stringResource(Res.string.step_down_and_leave)) + } + } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.cancel)) } }, + ) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 0a1f26cc..6834ca4e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -10,6 +10,7 @@ import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import co.touchlab.kermit.Logger +import com.vitorpamplona.marmot.groups.currentAdminIdentities import com.vitorpamplona.marmot.groups.currentGroupState import com.vitorpamplona.marmot.groups.isLocalAdmin import com.vitorpamplona.quartz.nip01Core.core.Event @@ -20,6 +21,9 @@ import kotlinx.coroutines.IO import kotlinx.coroutines.launch import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.model.types.ShareStanding +import mobi.giza.compose.managers.AdminGovernance import mobi.giza.compose.managers.WalletRefusal import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.repository.ChatRepository @@ -102,6 +106,13 @@ class ChatRoomDetailViewModel( ?.let { Event.fromJsonOrNull(it) } ?.let(WalletRefusal::isGuarded) == true + val shares = chatRepository.sharesSummary(localChatRoom) + // Who governs, and what this device may do about it, from the group's + // state through the same rules the commits are made by. + // docs/member-admin-promotion.md, Phase 11. + val me = localChatRoom.chatRoom.userPublicKey + val roomIsOpen = !isDisbanded && localChatRoom.chatRoom.leftGroupAt == null + ChatRoomDetailUIState.Loaded( localChatRoom = localChatRoom, groupKeyState = groupKeyState, @@ -112,7 +123,15 @@ class ChatRoomDetailViewModel( subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, isDisbanded = isDisbanded, - shares = chatRepository.sharesSummary(localChatRoom), + shares = shares, + adminPublicKeys = group?.currentAdminIdentities().orEmpty(), + shareHolders = if (ExperimentalFeatures.shareRefresh) { + shares?.members.orEmpty().filter { it.standing == ShareStanding.LIVE }.map { it.publicKey }.toSet() + } else { + emptySet() + }, + memberActions = group?.takeIf { canGovern }?.let { AdminGovernance.memberActions(it, me) }.orEmpty(), + adminLeave = group?.takeIf { roomIsOpen }?.let { AdminGovernance.adminLeave(it, me) }, ) } } @@ -141,6 +160,49 @@ class ChatRoomDetailViewModel( } } + /** + * Runs one change to who administers the room, reloads the screen, and + * reports: null when the commit went out, or why it could not. The change + * itself lands when a relay accepts it, and the room says so then. + * docs/member-admin-promotion.md, Phase 11. + */ + private fun adminAction(onDone: (String?) -> Unit, action: suspend () -> Unit) { + viewModelScope.launch(Dispatchers.IO) { + val failure = runCatching { action() }.exceptionOrNull() + if (failure is CancellationException) throw failure + initiateChatRoomDetail() + viewModelScope.launch(Dispatchers.Main) { onDone(failure?.let { it.message ?: "Couldn't make that change" }) } + } + } + + fun makeAdmin(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (String?) -> Unit) = + adminAction(onDone) { chatRepository.promoteMember(localChatRoom, memberPublicKey) } + + /** Removes [adminPublicKey] as an admin; this device's own account is stepping down. */ + fun removeAsAdmin(localChatRoom: LocalChatRoom, adminPublicKey: HexKey, onDone: (String?) -> Unit) = + adminAction(onDone) { chatRepository.demoteMember(localChatRoom, adminPublicKey) } + + /** + * Leaves as an admin: steps down, after making [heir] an admin when this device + * is the only one, and leaves once that is accepted. Leaves the screen as soon + * as the first step is sent; a refusal stays on it and goes to [onFailed]. + */ + fun stepDownAndLeave( + localChatRoom: LocalChatRoom, + heir: HexKey?, + onPopBackToRoute: (Route) -> Unit, + onFailed: (String?) -> Unit, + ) { + viewModelScope.launch(Dispatchers.IO) { + val failure = runCatching { chatRepository.stepDownAndLeave(localChatRoom, heir) }.exceptionOrNull() + if (failure is CancellationException) throw failure + viewModelScope.launch(Dispatchers.Main) { + if (failure == null) onPopBackToRoute(HomeRoute(activeUserPublicKey = activeUserPublicKey)) + else onFailed(failure.message) + } + } + } + /** * Runs one Shares section action, reloads the screen, and reports: null for * done, or why not. Every one of them is a proposal or an answer the group diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 5b7b8511..0a73fcd9 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -84,6 +84,23 @@ sealed interface ChatRoomDetailUIState { * room has no key (docs/frost-share-refresh.md, Phase 11). */ val shares: SharesSummary? = null, + /** + * Who administers the room, read off the group's state rather than the + * participants' `adminAt` flags. Labels each member row **Admin**. + * docs/member-admin-promotion.md, D1 and Phase 11. + */ + val adminPublicKeys: Set = emptySet(), + /** + * Who holds a live share of the room's key, for the **Holds a share** + * label. Shown apart from [adminPublicKeys] on purpose: when the two + * disagree, an enrollment or a rotation is still owed. Empty while share + * rotation is behind its flag. + */ + val shareHolders: Set = emptySet(), + /** What this device may do to each member, by public key; absent means nothing. */ + val memberActions: Map> = emptyMap(), + /** How **Leave group** goes when this device is an admin; null when it is not. */ + val adminLeave: AdminLeave? = null, ): ChatRoomDetailUIState data class Error( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt new file mode 100644 index 00000000..2f6f4a7f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberAction.kt @@ -0,0 +1,33 @@ +package mobi.giza.compose.ui.view.state + +/** + * What this device may do to one member of a room, as the member row's menu offers + * it. Computed by the view model from the group's state and + * `mobi.giza.compose.managers.AdminGovernance`, so the screen never decides an + * action itself. See docs/member-admin-promotion.md, Phase 11. + */ +enum class MemberAction { + MAKE_ADMIN, + REMOVE_AS_ADMIN, + /** Removing yourself as an admin, on your own row. */ + STEP_DOWN, + REMOVE_FROM_GROUP, +} + +/** + * How **Leave group** goes for an admin, who cannot simply leave: the library + * refuses an admin's SelfRemove. docs/member-admin-promotion.md, Phase 10. + */ +enum class AdminLeave { + /** Another admin remains: step down, then leave once that is accepted. */ + STEP_DOWN_FIRST, + + /** The only admin: make someone else an admin first, or disband instead. */ + PICK_HEIR, + + /** + * Nothing this build can do: a keyed room, whose admins change only with the + * group's signature, or a room with nobody else in it to hand over to. + */ + CANNOT, +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt index ae809dbc..ec842d8c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/AdminChangesJvmTest.kt @@ -17,6 +17,7 @@ import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Instant import kotlinx.coroutines.CoroutineScope @@ -34,6 +35,8 @@ import mobi.giza.compose.exceptions.MarmotCommitPendingException import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.ui.view.state.AdminLeave +import mobi.giza.compose.ui.view.state.MemberAction /** * Promoting and demoting in a convenient room, which has no key to sign with and @@ -209,6 +212,62 @@ class AdminChangesJvmTest { assertEquals(setOf(user), appGroup().currentAdminIdentities(), "re-invited, and an admin again") } + @Test + fun `the member rows offer what the group would accept, and leaving says how it will go`() = runBlocking { + convenientRoomWithMember() + + assertEquals(mapOf(member.hex to setOf(MemberAction.MAKE_ADMIN, MemberAction.REMOVE_FROM_GROUP)), AdminGovernance.memberActions(appGroup(), user)) + assertEquals(AdminLeave.PICK_HEIR, AdminGovernance.adminLeave(appGroup(), user)) + assertEquals(emptyMap(), AdminGovernance.memberActions(member.manager.getGroup(routingId)!!, member.hex), "a member who is not an admin was offered something") + + chatRepository.promoteMember(room(), member.hex) + okTheLatestCommit() + + assertEquals( + mapOf(user to setOf(MemberAction.STEP_DOWN), member.hex to setOf(MemberAction.REMOVE_AS_ADMIN, MemberAction.REMOVE_FROM_GROUP)), + AdminGovernance.memberActions(appGroup(), user), + ) + assertEquals(AdminLeave.STEP_DOWN_FIRST, AdminGovernance.adminLeave(appGroup(), user)) + } + + @Test + fun `an admin with another admin beside them steps down, then leaves`() = runBlocking { + convenientRoomWithMember() + chatRepository.promoteMember(room(), member.hex) + okTheLatestCommit() + + chatRepository.stepDownAndLeave(room(), heir = null) + assertEquals(null, room().chatRoom.leftGroupAt, "left before the step-down was accepted") + okTheLatestCommit() // the step-down; its acceptance sends the leave + + assertNotNull(room().chatRoom.leftGroupAt, "the leave did not follow the step-down") + assertEquals(setOf(member.hex), member.manager.getGroup(routingId)!!.currentAdminIdentities()) + } + + @Test + fun `the only admin hands over to the member they pick, then leaves`() = runBlocking { + convenientRoomWithMember() + + chatRepository.stepDownAndLeave(room(), heir = member.hex) + okTheLatestCommit() // the promotion + assertNull(room().chatRoom.leftGroupAt) + okTheLatestCommit() // the step-down + + assertNotNull(room().chatRoom.leftGroupAt, "the leave did not follow the hand-over") + assertEquals(setOf(member.hex), member.manager.getGroup(routingId)!!.currentAdminIdentities()) + assertTrue(member.manager.getGroup(routingId)!!.isLocalAdmin()) + } + + @Test + fun `the only admin who names nobody is refused, and nothing waits`() = runBlocking { + convenientRoomWithMember() + + assertFailsWith { chatRepository.stepDownAndLeave(room(), heir = null) } + + assertNull(room().chatRoom.leftGroupAt) + assertTrue(db.marmotPublishObligationDao().getAll().isEmpty()) + } + @Test fun `a keyed room's admins are not changed by one admin's commit`() = runBlocking { seedProfile(user, "us") @@ -225,5 +284,7 @@ class AdminChangesJvmTest { val refusal = assertFailsWith { chatRepository.demoteMember(keyedRoom, user) } assertEquals(mobi.giza.compose.database.dao.MarmotOutboundDao.KEYED_ROOM_REFUSAL, refusal.message) assertTrue(db.marmotPublishObligationDao().getAll().isEmpty()) + val keyedGroup = db.marmotEngine.groupFor(keyedRoom.routingId)!! + assertEquals(AdminLeave.CANNOT, AdminGovernance.adminLeave(keyedGroup, user)) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt index b14af204..b0fe514a 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ChatRoomMemberRowJvmTest.kt @@ -5,6 +5,9 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.ui.Modifier import androidx.compose.ui.test.ComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithContentDescription +import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.runDesktopComposeUiTest @@ -20,6 +23,7 @@ import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState +import mobi.giza.compose.ui.view.state.MemberAction import kotlin.test.Test import kotlin.test.assertEquals @@ -66,6 +70,40 @@ class ChatRoomMemberRowJvmTest { assertEquals(ProfilePreviewRoute(activeUserPublicKey, stillLoading), opened) } + /** + * An admin's row menu offers what the view model decided, and promotion asks + * first, saying what it gives away. docs/member-admin-promotion.md, Phase 11. + */ + @Test + fun `an admin makes a member an admin from the row's menu, after being told what it gives`() { + render( + onNavigateToRoute = {}, + state = state().copy( + adminPublicKeys = setOf(activeUserPublicKey), + memberActions = mapOf(named to setOf(MemberAction.MAKE_ADMIN, MemberAction.REMOVE_FROM_GROUP)), + ), + ) { + onAllNodesWithContentDescription("Member actions").assertCountEquals(1) + onNodeWithContentDescription("Member actions").performClick() + onNodeWithText("Remove from group").assertExists() + onNodeWithText("Make admin").performClick() + + onNodeWithText("Make Nomvula an admin?").assertExists() + onNodeWithText("including you", substring = true).assertExists() + } + } + + @Test + fun `an admin's row says so, and a share holder's says that apart`() { + render( + onNavigateToRoute = {}, + state = state().copy(adminPublicKeys = setOf(named), shareHolders = setOf(stillLoading)), + ) { + onNodeWithText("Admin").assertExists() + onNodeWithText("Holds a share").assertExists() + } + } + private fun member(publicKey: String, profile: Profile?) = LocalParticipant( participant = Participant( participantPublicKey = publicKey, @@ -98,6 +136,7 @@ class ChatRoomMemberRowJvmTest { */ private fun render( onNavigateToRoute: (Route) -> Unit, + state: ChatRoomDetailUIState.Loaded = state(), assertions: ComposeUiTest.() -> Unit, ) = runDesktopComposeUiTest(width = 400, height = 4000) { setContent { @@ -108,7 +147,7 @@ class ChatRoomMemberRowJvmTest { activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, relayHint = null, - initialChatRoomDetailUIState = state(), + initialChatRoomDetailUIState = state, nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, onNavigateToRoute = onNavigateToRoute,