feat: a member's admin flag is true from the room's first moment (member-admin-promotion, Phase 1)

Participant.adminAt was written only when a commit arrived, so on the
device that created a convenient room or a direct message nobody was an
admin until somebody else committed. MarmotInboundManager.reconcileAdmins
brings the flags into line with the group's admin set without a caption.
It runs where every Marmot room is made -- replacing stampAdmins, which
only the keyed rooms had -- and when a room's detail screen opens, which
catches up rooms made before this build.

processGroupMembershipChanges shares the same flag rule, adminFlagChanges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-20 01:09:56 +02:00
1 parent 2ed83c55ab
commit 53acae68a4
9 files changed
+197 -71

No files matched your search

@@ -59,6 +59,7 @@ import mobi.giza.compose.extensions.shortened
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.managers.ChronicleManager
import mobi.giza.compose.managers.MarmotGroupFactory
import mobi.giza.compose.managers.MarmotInboundManager
import mobi.giza.compose.managers.MarmotInboundManager.EPOCH_RETENTION_WINDOW
import mobi.giza.compose.nostr.MarmotDelivery
import mobi.giza.compose.nostr.MarmotDirectMessage
@@ -137,6 +138,9 @@ abstract class MarmotOutboundDao(
)
)
)
// The creator administers the room from epoch 0, and this device learns that
// nowhere else. docs/member-admin-promotion.md, Phase 1.
MarmotInboundManager.reconcileAdmins(database, chatRoom.id, mlsGroup)
// Invite peer. On the current profile the manager owns the group from the row
// just written, and the invite moves that instance rather than the one the
@@ -5,9 +5,11 @@ import kotlinx.serialization.Serializable
/**
* How a chat room is governed.
*
* The choice is stamped into the epoch-0 `MarmotGroupData.admin_pubkeys` list,
* which is what `MarmotInboundManager.processGroupMembershipChanges` reads to
* flag participants as admins on every side of the group.
* The choice decides the room's founding admins, written into its epoch-0 admin
* list. That list is the group's state from then on, and a promotion or demotion
* changes it; `MarmotInboundManager.reconcileAdmins` and
* `processGroupMembershipChanges` keep each participant's `adminAt` in line with
* whatever it says now. See docs/member-admin-promotion.md.
*/
@Serializable
enum class ChatRoomType {
@@ -7,6 +7,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import mobi.giza.compose.managers.MarmotInboundManager
import mobi.giza.compose.managers.CeremonyFollowThrough
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
@@ -643,6 +644,13 @@ class DatabaseChatRepository(
onCompletion.invoke()
}
override suspend fun reconcileAdmins(chatRoomId: String): Boolean {
val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return false
// A row whose state this build cannot read has no admin set to agree with.
val group = runCatching { room.chatRoom.toMlsGroup() }.getOrNull() ?: return false
return MarmotInboundManager.reconcileAdmins(database, chatRoomId, group)
}
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) {
database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey)
}
@@ -187,7 +187,13 @@ object MarmotGroupCreation {
logger.w("$groupId created without ${notAdded.size} member(s): $notAdded")
}
stampAdmins(database, groupId, adminPublicKeys)
// The creating device learns who administers the room from nowhere else:
// `adminAt` is otherwise written only when a commit arrives. Read off the
// group, which names the creator whether or not [adminPublicKeys] did.
// Swallowed on failure, like `adopt` above: what a missing flag costs is a
// label, and the room is made and usable.
runCatching { MarmotInboundManager.reconcileAdmins(database, groupId, group) }
.onFailure { logger.e("Created $groupId but could not flag its admins", it) }
return Outcome.Created(
room = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom,
@@ -195,54 +201,6 @@ object MarmotGroupCreation {
)
}
/**
* Writes `adminAt` on the rows of the members this room was created with as
* admins.
*
* The creating device never learns this any other way, which is a bug older
* than subgroups and easy to miss. `Participant.adminAt` is written in exactly
* one place -- `MarmotInboundManager.processGroupMembershipChanges`, on an
* arriving commit -- while the rows a creator makes come from
* `getOrCreateChatRoom` and `addMembers`, neither of which sets it. So on the
* device that made the room, every participant reads as a non-admin until some
* *other* member sends a commit it processes: a room whose epoch-0 context
* names three admins had none of them flagged, on the one device certain to be
* one.
*
* This is the same list already baked into `MarmotGroupData` a few lines
* above, so nothing new is being asserted -- the row is being caught up with
* the group context it was created from. `processGroupMembershipChanges`
* reconciles it against the MLS tree from then on and will agree.
*
* Only flags are written. That function also *removes* participants missing
* from the tree, and running the whole reconciliation here would soft-delete
* the rows of anyone `addMembers` could not reach -- turning a partial invite
* into a partial membership. Widening a flag is safe; narrowing membership on
* a best-effort step is not.
*
* Swallowed on failure, like `adopt` above it: the room is made and usable,
* and what a missing flag costs is a button not being offered rather than
* anything being wrong.
*/
private suspend fun stampAdmins(
database: GizaDatabase,
groupId: String,
adminPublicKeys: Set<HexKey>
) {
runCatching {
val room = database.chatRoomDao().findChatRoomById(groupId) ?: return
val stamped = room.localParticipants
.map { it.participant }
.filter { it.participantPublicKey in adminPublicKeys && it.adminAt == null }
.map { it.copy(adminAt = Clock.System.now()) }
if (stamped.isNotEmpty()) database.participantDao().upsert(stamped)
}.onFailure {
logger.e("Created $groupId but could not flag its admins", it)
}
}
/**
* Every peer's published key package, or null where there is none.
*
@@ -165,23 +165,8 @@ object MarmotInboundManager {
)
}
logger.d("newParticipants: $newParticipants")
val removedAdmins = localChatRoom.localParticipants.filter { localParticipant ->
localParticipant.participant.adminAt != null && !adminPublicKeys.contains(localParticipant.participant.participantPublicKey)
}.map { localParticipant ->
localParticipant.participant.copy(
adminAt = null
)
}
logger.d("removedAdmins: $removedAdmins")
val graduatedAdmins = localChatRoom.localParticipants.filter { localParticipant ->
localParticipant.participant.adminAt == null && adminPublicKeys.contains(localParticipant.participant.participantPublicKey)
}.map { localParticipant ->
localParticipant.participant.copy(
adminAt = Clock.System.now()
)
}
logger.d("graduatedAdmins: $graduatedAdmins")
val adminFlags = adminFlagChanges(localChatRoom.localParticipants.map { it.participant }, adminPublicKeys)
logger.d("adminFlags: $adminFlags")
// Placeholder profiles for new participants...
newParticipants.forEach { newParticipant ->
@@ -246,10 +231,9 @@ object MarmotInboundManager {
)
}
// Handle membership changes...
database.participantDao().upsert(removedAdmins)
database.participantDao().upsert(adminFlags)
database.participantDao().delete(excludedParticipants)
database.participantDao().upsert(newParticipants)
database.participantDao().upsert(graduatedAdmins)
val userPublicKey = localChatRoom.chatRoom.userPublicKey
val disbanded = mlsGroup.currentGroupState().isDisbanded
@@ -279,6 +263,45 @@ object MarmotInboundManager {
}
}
/**
* The participant rows whose `adminAt` disagrees with [adminPublicKeys], each
* corrected: flagged now if the group names them, cleared if it does not. Rows
* that already agree are left out, so a flag keeps the moment it was first set.
*/
internal fun adminFlagChanges(participants: List<Participant>, adminPublicKeys: Set<HexKey>): List<Participant> {
val now = Clock.System.now()
return participants.mapNotNull { participant ->
val named = participant.participantPublicKey in adminPublicKeys
when {
named && participant.adminAt == null -> participant.copy(adminAt = now)
!named && participant.adminAt != null -> participant.copy(adminAt = null)
else -> null
}
}
}
/**
* Brings the room's `adminAt` flags into line with [mlsGroup]'s admin set, and
* says nothing about it.
*
* The flag is a cache of the group's state, and until this existed it was written
* only when a commit arrived -- so on the device that created a convenient room or
* a direct message, nobody was an admin until somebody else committed. Run where
* rooms are made and when a room is opened, it makes the cache true before
* anything reads it as news. Only flags move: membership is
* [processGroupMembershipChanges]'s, which also captions what it changes. Returns
* whether any row changed. See docs/member-admin-promotion.md, Phase 1.
*/
suspend fun reconcileAdmins(database: GizaDatabase, chatRoomId: String, mlsGroup: MlsGroup): Boolean {
val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return false
val changes = adminFlagChanges(
participants = room.localParticipants.map { it.participant },
adminPublicKeys = mlsGroup.currentAdminIdentities(),
)
if (changes.isNotEmpty()) database.participantDao().upsert(changes)
return changes.isNotEmpty()
}
private suspend fun memberName(database: GizaDatabase, publicKey: HexKey): String =
database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey()
?: publicKey.take(8)
@@ -261,6 +261,12 @@ interface ChatRepository {
onCompletion: () -> Unit
)
/**
* Brings the room's admin flags into line with its group's admin set, without a
* caption. Returns whether any changed. See docs/member-admin-promotion.md, Phase 1.
*/
suspend fun reconcileAdmins(chatRoomId: String): Boolean
/**
* Removes [memberPublicKey] from a current-profile room this device administers:
* a commit through the publish gate, applied when a relay accepts it. See
@@ -484,6 +490,8 @@ interface ChatRepository {
TODO("Not yet implemented")
}
override suspend fun reconcileAdmins(chatRoomId: String): Boolean = false
override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit
override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = false
@@ -71,6 +71,11 @@ class ChatRoomDetailViewModel(
logger.d("compressed (most likely chat room): $chatRoomId")
// Get ChatRoomById
viewModelScope.launch(Dispatchers.IO) {
// A room made before its creator's flag was written at creation reads as
// having no admins until a commit arrives; caught up here, silently, before
// anything reads it. docs/member-admin-promotion.md, Phase 1.
runCatching { chatRepository.reconcileAdmins(chatRoomId) }
.onFailure { if (it is CancellationException) throw it else logger.w(throwable = it) { "Couldn't reconcile $chatRoomId's admins" } }
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
logger.d("localChatRoom: $localChatRoom")
@@ -257,6 +257,9 @@ class SelectChatRoomTypeViewModel(
)
if (localChatRoom != null) {
chatRepository.recordMarmotRouting(chatRoomId = gid, routingId = created.routingId)
// The creator administers the room from epoch 0, and this device learns
// that nowhere else. docs/member-admin-promotion.md, Phase 1.
chatRepository.reconcileAdmins(gid)
}
if (localChatRoom == null) {
@@ -0,0 +1,115 @@
package mobi.giza.compose.managers
import androidx.room3.Room
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Instant
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.MarmotKeyPackage
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Participant
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.repository.DatabaseChatRepository
import mobi.giza.compose.nostr.MarmotProfile
/**
* `Participant.adminAt` made true where rooms are made and when a room is opened,
* so that nothing reads a stale flag as news. docs/member-admin-promotion.md,
* Phase 1.
*
* Before, the flag was written only when a commit arrived, so on the device that
* created a convenient room or a direct message nobody was an admin until somebody
* else committed. With admin captions derived from changes, that would have put
* "You are now an admin" on the creator's screen at their first invite.
*/
class AdminFlagsJvmTest {
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
private val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default))
@AfterTest
fun closeDb() = db.close()
private val keyPair = KeyPair()
private val user = keyPair.pubKey.toHexKey()
private val member = MarmotStandIn()
private suspend fun seedProfile(publicKey: String) {
val eventId = publicKey.take(32).padEnd(64, 'f')
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = publicKey, userName = publicKey.take(8), nostrEventId = eventId))
}
private suspend fun directMessage(): String {
seedProfile(user)
seedProfile(member.hex)
member.makeBundle()
return db.marmotOutboundDao().createMlsDirectMessageChatRoom(
creator = keyPair,
peerPublicKey = member.hex,
peerKeyPackage = MarmotKeyPackage(
id = member.hex, publicKey = member.hex,
tlsEncodedMarmotKeyPackage = member.bundle.keyPackage.toTlsBytes(),
profile = MarmotProfile.CURRENT.wireName,
),
profile = MarmotProfile.CURRENT,
)
}
private suspend fun flags(roomId: String): Map<String, Instant?> =
db.chatRoomDao().findChatRoomById(roomId)!!.localParticipants
.associate { it.participant.participantPublicKey to it.participant.adminAt }
@Test
fun `the creator of a direct message is its admin from the start, and the peer is not`() = runBlocking {
val roomId = directMessage()
val flags = flags(roomId)
assertNotNull(flags[user], "the creator was not flagged before any commit arrived")
assertNull(flags[member.hex])
}
@Test
fun `opening a room whose flags went stale catches them up and says nothing`() = runBlocking {
val roomId = directMessage()
// A room made before this build: the creator's row never flagged.
val creatorRow = db.chatRoomDao().findChatRoomById(roomId)!!.localParticipants
.single { it.participant.participantPublicKey == user }.participant
db.participantDao().upsert(listOf(creatorRow.copy(adminAt = null)))
val linesBefore = db.chatMessageDao().getChatMessagesByChatRoomId(roomId).size
assertTrue(chatRepository.reconcileAdmins(roomId))
assertNotNull(flags(roomId)[user])
assertEquals(linesBefore, db.chatMessageDao().getChatMessagesByChatRoomId(roomId).size, "a reconcile wrote a line")
assertFalse(chatRepository.reconcileAdmins(roomId), "a second reconcile found something to change")
}
@Test
fun `a flag the group no longer backs is cleared, and one that agrees keeps its moment`() {
val since = Instant.fromEpochSeconds(1_700_000_000)
val rows = listOf(
Participant(participantPublicKey = "a", chatRoomId = "r", relayHint = null, adminAt = since),
Participant(participantPublicKey = "b", chatRoomId = "r", relayHint = null, adminAt = since),
Participant(participantPublicKey = "c", chatRoomId = "r", relayHint = null),
)
val changes = MarmotInboundManager.adminFlagChanges(rows, adminPublicKeys = setOf("a", "c"))
.associateBy { it.participantPublicKey }
assertEquals(setOf("b", "c"), changes.keys, "a row that already agreed was rewritten")
assertNull(changes.getValue("b").adminAt)
assertNotNull(changes.getValue("c").adminAt)
}
}