Merge branch 'claude/confederation-shared-seats' into giza

This commit is contained in:
Kgothatso Ngako committed 2026-11-23 00:52:31 +02:00
commit 9db986c1e2
7 files changed
+286 -38

No files matched your search

@@ -768,6 +768,9 @@
<string name="you_declined_this">You declined this</string>
<string name="answer_yes">Approved</string>
<string name="answer_no">Declined</string>
<string name="answer_approved_for">Approved for %1$s</string>
<string name="answer_declined_for">Declined for %1$s</string>
<string name="answer_not_yet_endorsed_by">Not for %1$s, which had not endorsed it when signing began</string>
<string name="this_device_holds_no_such_request">This device holds no such request for the confederation to sign</string>
<string name="propose_the_charter">Propose the charter</string>
<string name="the_charter_names_the_groups">The charter is the confederation's public statement of the groups it is made of, signed with its own key. It is how members who are not admins hear of it.</string>
@@ -368,9 +368,12 @@ object ConfederationSigningManager {
}
/**
* Files one message. Per-person messages only from a person holding a role, with a value for
* exactly their roles; the session only from the proposer; a failure from anyone with a role.
* Returns false when it ended the attempt.
* Files one message. Per-person messages only from a person holding a role: an availability with
* a value for exactly their roles, and a nonce, confirmation or partial with a value for some of
* them -- only the roles the selection chose, which for somebody seated in several groups is
* seldom all of theirs; [perRole] reads one per selected role and waits while any is missing. The
* session only from the proposer; a failure from anyone with a role. Returns false when it ended
* the attempt.
*/
private suspend fun record(database: GizaDatabase, held: Held, attempt: ConfederationSigningAttempt, innerEvent: Event): Boolean {
val sender = innerEvent.pubKey
@@ -378,7 +381,12 @@ object ConfederationSigningManager {
when (innerEvent.kind) {
in ConfederationSigningEvents.PER_PERSON -> {
if (groups.isEmpty()) return true
if (ConfederationRitualEvents.decodeByGroup(innerEvent.content)?.keys != groups) return true
val keys = ConfederationRitualEvents.decodeByGroup(innerEvent.content)?.keys ?: return true
val wellFormed = if (innerEvent.kind == ConfederationSigningEvents.AVAILABILITY) keys == groups else keys.isNotEmpty() && groups.containsAll(keys)
if (!wellFormed) {
logger.w("Signing message kind ${innerEvent.kind} from ${sender.take(8)} does not fit the roles they hold; dropping")
return true
}
database.confederationCeremonyDao().insertSigningMessage(ConfederationSigningMessage(attempt.id, sender, innerEvent.kind, innerEvent.content))
}
ConfederationSigningEvents.SESSION -> {
@@ -29,11 +29,15 @@ import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent
import mobi.giza.compose.database.model.ConfederationSigningStage
import mobi.giza.compose.managers.ConfederationSigningManager
import mobi.giza.compose.repository.ConfederationRepository
import mobi.giza.compose.resources.Res
import mobi.giza.compose.resources.answer_approved_for
import mobi.giza.compose.resources.answer_declined_for
import mobi.giza.compose.resources.answer_no
import mobi.giza.compose.resources.answer_not_yet_endorsed_by
import mobi.giza.compose.resources.answer_waiting
import mobi.giza.compose.resources.answer_yes
import mobi.giza.compose.resources.approve_for_the_confederation
@@ -55,6 +59,7 @@ 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.ConfederationSigningViewModel
import mobi.giza.compose.ui.view.state.ConfederationSigningAnswer
import mobi.giza.compose.ui.view.state.ConfederationSigningUIState
import org.jetbrains.compose.resources.stringResource
@@ -136,34 +141,50 @@ fun ConfederationSigningScreen(
}
HorizontalDivider()
current.answers.forEach { (name, answer) ->
ListItem(
leadingContent = {
Icon(
imageVector = when (answer) {
true -> Icons.Default.CheckCircle
false -> Icons.Default.Block
null -> Icons.Default.HourglassEmpty
},
contentDescription = Decorative,
)
},
headlineContent = { Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = {
Text(
stringResource(
when (answer) {
true -> Res.string.answer_yes
false -> Res.string.answer_no
null -> Res.string.answer_waiting
}
)
)
},
)
}
val isProfile = current.event.kind == MetadataEvent.KIND
current.answers.forEach { answer -> AnswerItem(answer, isProfile) }
}
}
}
}
}
/**
* One role holder's answer. Somebody seated in several groups answers for each, so a yes for one
* group and a no for another is said group by group, not folded into either. On a profile the no
* is no one's refusal: the seat's group had not endorsed it when the signing began.
*/
@Composable
private fun AnswerItem(answer: ConfederationSigningAnswer, isProfile: Boolean) {
val approved = answer.approvedFor.isNotEmpty()
val declined = answer.declinedFor.isNotEmpty()
ListItem(
leadingContent = {
Icon(
imageVector = when {
!answer.hasSaid -> Icons.Default.HourglassEmpty
approved -> Icons.Default.CheckCircle
else -> Icons.Default.Block
},
contentDescription = Decorative,
)
},
headlineContent = { Text(answer.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
supportingContent = {
when {
!answer.hasSaid -> Text(stringResource(Res.string.answer_waiting))
!declined -> Text(stringResource(Res.string.answer_yes))
!approved && !isProfile -> Text(stringResource(Res.string.answer_no))
else -> Column {
if (approved) Text(stringResource(Res.string.answer_approved_for, answer.approvedFor.joinToString()))
Text(
stringResource(
if (isProfile) Res.string.answer_not_yet_endorsed_by else Res.string.answer_declined_for,
answer.declinedFor.joinToString(),
)
)
}
}
},
)
}
@@ -18,6 +18,7 @@ import kotlinx.coroutines.launch
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents
import mobi.giza.compose.repository.ConfederationRepository
import mobi.giza.compose.ui.view.state.ConfederationSigningAnswer
import mobi.giza.compose.ui.view.state.ConfederationSigningUIState
/** One attempt by a confederation to sign an event, watched as answers arrive (docs/confederation.md, Phase 15). */
@@ -42,10 +43,21 @@ class ConfederationSigningViewModel(
}
val plan = confederationRepository.confederationPlan(attempt.confederationId)
val event = Event.fromJsonOrNull(attempt.signedEventJson ?: attempt.eventJson) ?: return@collect
val said = messages.filter { it.kind == ConfederationSigningEvents.AVAILABILITY }.associate { message ->
message.senderPublicKey to (ConfederationRitualEvents.decodeByGroup(message.payload)?.values?.all { it == ConfederationSigningEvents.YES } == true)
// Per group, not per person: somebody seated in several groups can say yes for one and
// no for another, and is neither simply approving nor simply declining.
val said = messages.filter { it.kind == ConfederationSigningEvents.AVAILABILITY }.mapNotNull { message ->
ConfederationRitualEvents.decodeByGroup(message.payload)?.let { message.senderPublicKey to it }
}.toMap()
val groupNames = plan?.groups.orEmpty().associateWith { confederationRepository.nameOf(it) }
val answers = plan?.people.orEmpty().map { person ->
val byGroup = said[person].orEmpty()
val inRosterOrder = plan?.groups.orEmpty().filter { it in byGroup }
ConfederationSigningAnswer(
name = confederationRepository.nameOf(person),
approvedFor = inRosterOrder.filter { byGroup[it] == ConfederationSigningEvents.YES }.map(groupNames::getValue),
declinedFor = inRosterOrder.filter { byGroup[it] != ConfederationSigningEvents.YES }.map(groupNames::getValue),
)
}
val answers = plan?.people.orEmpty().map { person -> confederationRepository.nameOf(person) to said[person] }
val acting = (state.value as? ConfederationSigningUIState.Loaded)?.isActing == true
state.value = ConfederationSigningUIState.Loaded(
attempt = attempt,
@@ -8,8 +8,8 @@ sealed interface ConfederationSigningUIState {
data class Loaded(
val attempt: ConfederationSigningAttempt,
val event: Event,
/** Every role holder by name, with their answer: true, false, or null while they have not said. */
val answers: List<Pair<String, Boolean?>>,
/** Every role holder, with their answer for each group they hold a role in. */
val answers: List<ConfederationSigningAnswer>,
val roleCount: Int,
val groupCount: Int,
val isActing: Boolean = false,
@@ -19,3 +19,16 @@ sealed interface ConfederationSigningUIState {
data object Loading : ConfederationSigningUIState
}
/**
* One role holder's answer, by group: a person seated in several groups answers for each of them,
* and the answers can differ -- on a profile, each follows whether that group had endorsed it when
* the signing began. Both lists empty while they have not said.
*/
data class ConfederationSigningAnswer(
val name: String,
val approvedFor: List<String> = emptyList(),
val declinedFor: List<String> = emptyList(),
) {
val hasSaid: Boolean get() = approvedFor.isNotEmpty() || declinedFor.isNotEmpty()
}
@@ -0,0 +1,148 @@
package mobi.giza.compose.managers
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.Nip01Crypto
import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.time.Clock
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.Confederation
import mobi.giza.compose.database.model.ConfederationSigningStage
import mobi.giza.compose.database.model.MarmotInnerEvent
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.nostr.confederation.ConfederationProfileStatements
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationSigningEvents
/**
* A confederation whose people are seated in several of its groups, as admins of related groups
* usually are: 11 in all three, the rest in two each. The selection picks some of a person's seats
* and not others, so their nonce, confirmation and partial name only the chosen ones -- and have to
* be taken as they are, not dropped for not naming every seat the person holds.
*/
class ConfederationSharedSeatsSigningJvmTest {
private val adminsByGroup = listOf(listOf(11, 12, 13), listOf(11, 12, 14), listOf(11, 13, 14))
private val network = ConfederationPeople(adminsByGroup, tag = 0x72)
private val groups get() = network.groups
private fun npub(n: Int): HexKey = network.npub(n)
private inner class Device(val ceremonyDevice: ConfederationPeople.Device) {
val db get() = ceremonyDevice.db
val person get() = ceremonyDevice.person
val nsec get() = ceremonyDevice.secret.value.toByteArray()
lateinit var room: LocalChatRoom
val received = mutableSetOf<String>()
}
private val devices = linkedMapOf<HexKey, Device>()
private lateinit var confederation: Confederation
@BeforeTest
fun formed() = runBlocking {
network.setUp()
network.devices.values.forEach { devices[it.person] = Device(it) }
network.joinAll()
network.pump()
confederation = assertNotNull(devices.getValue(npub(11)).db.confederationCeremonyDao().getConfederationForProposal(network.proposalId))
devices.values.forEach { d ->
d.db.chatRoomDao().upsert(ChatRoom(id = confederation.id, userPublicKey = d.person, subject = "#Atlas", description = null, mlsGroupState = "00"))
d.room = d.db.chatRoomDao().findChatRoomById(confederation.id)!!
}
}
@AfterTest
fun close() {
ConfederationSigningManager.forgetSignersForTest()
network.close()
}
private fun pump() = runBlocking {
var moved = true
while (moved) {
moved = false
for (from in devices.values) for (to in devices.values) {
if (from === to) continue
from.db.marmotInnerEventDao().getByChatRoomAndKinds(confederation.id, ConfederationSigningEvents.ALL.toList())
.filter { it.publicKey == from.person }.sortedWith(compareBy({ it.createdAt }, { it.kind }))
.forEach { q: MarmotInnerEvent ->
if (!to.received.add(q.id)) return@forEach
moved = true
to.db.marmotInnerEventDao().upsert(q)
ConfederationSigningManager.process(to.db, to.room, Event(q.id, q.publicKey, q.createdAt.epochSeconds, q.kind, q.tags, q.content, ""), to.person, to.nsec)
}
}
}
}
private fun stages(attemptId: String) = runBlocking {
devices.values.associate { it.person to it.db.confederationCeremonyDao().getAttempt(attemptId) }
}
@Test
fun `a post is signed when the selection takes only some of a person's seats`() {
val proposer = devices.getValue(npub(11))
val attempt = runBlocking {
ConfederationSigningManager.propose(proposer.db, proposer.room, proposer.person, TextNoteEvent.KIND, emptyArray(), "Words from groups that share admins", proposer.nsec)
}
pump()
runBlocking { listOf(12, 13, 14).map { devices.getValue(npub(it)) }.forEach { ConfederationSigningManager.approve(it.db, attempt.id, it.nsec) } }
pump()
stages(attempt.id).forEach { (person, a) -> assertEquals(ConfederationSigningStage.COMPLETE, a?.stage, "${person.take(6)}: ${a?.failureReason}") }
val selection = runBlocking {
proposer.db.confederationCeremonyDao().getSigningMessage(attempt.id, proposer.person, ConfederationSigningEvents.SESSION)
?.let { ConfederationSigningEvents.Session.decode(it.payload) }
}
assertEquals(2, selection?.selection?.size, "two of the three groups sign, so 11 signs for fewer seats than it holds")
}
private val now get() = Clock.System.now().epochSeconds
@Test
fun `a profile two groups vouched for is signed, and the third group's admins answer for each of their groups`() {
val rumor = ConfederationProfileStatements.change(groups[0], groups.drop(1), confederation.id, 2, null, emptyArray(), """{"name":"Atlas"}""", now - 5, now + 1000)
val change = ConfederationProfileStatements.parseChange(rumor)!!
val endorsement = ConfederationProfileStatements.endorsement(groups[1], change, now - 4)
runBlocking {
devices.values.forEach { d ->
ConfederationProfileManager.recordStatement(d.db, rumor, ConfederationStatementFixture.seal(network.groupKeys[0], rumor), null)
ConfederationProfileManager.recordStatement(d.db, endorsement, ConfederationStatementFixture.seal(network.groupKeys[1], endorsement), null)
}
// Agora's and Polis's vouchers; Ekklesia's has not come by the time the signing starts.
listOf(0 to 12, 1 to 14).forEach { (group, poster) ->
val template = ConfederationProfileStatements.voucherTemplate(change, now - 3)
val id = EventHasher.hashId(groups[group], template.createdAt, template.kind, template.tags, template.content)
val voucher = Event(id, groups[group], template.createdAt, template.kind, template.tags, template.content,
Nip01Crypto.sign(id.hexToByteArray(), network.groupKeys[group].value.toByteArray()).toHex())
val device = devices.getValue(npub(poster))
ConfederationProfileManager.recordVoucher(device.db, voucher)
ConfederationSigningManager.postVoucher(device.db, device.person, voucher)
}
}
pump()
val started = runBlocking {
devices.values.sortedBy { it.person }.flatMap { ConfederationProfileFollowThrough.sweep(it.db, it.person, it.nsec) }
}
assertEquals(1, started.size)
pump()
val attemptId = started.single().id
stages(attemptId).forEach { (person, a) -> assertEquals(ConfederationSigningStage.COMPLETE, a?.stage, "${person.take(6)}: ${a?.failureReason}") }
runBlocking {
val said = devices.getValue(npub(11)).db.confederationCeremonyDao().getSigningMessage(attemptId, npub(11), ConfederationSigningEvents.AVAILABILITY)
val byGroup = assertNotNull(said?.let { ConfederationRitualEvents.decodeByGroup(it.payload) })
assertEquals(ConfederationSigningEvents.NO, byGroup[groups[2]], "Ekklesia had not vouched")
assertTrue(byGroup.filterKeys { it != groups[2] }.values.all { it == ConfederationSigningEvents.YES }, "yes for the groups that had")
}
}
}
@@ -24,6 +24,7 @@ import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost
import mobi.giza.compose.ui.theme.GizaTheme
import mobi.giza.compose.ui.view.state.ConfederationProposalUIState
import mobi.giza.compose.ui.view.state.ConfederationRitualUIState
import mobi.giza.compose.ui.view.state.ConfederationSigningAnswer
import mobi.giza.compose.ui.view.state.ConfederationSigningUIState
import mobi.giza.compose.database.model.ConfederationSigningAttempt
import mobi.giza.compose.database.model.ConfederationSigningStage
@@ -343,13 +344,26 @@ class ConfederationScreensJvmTest {
assertions()
}
private fun signing(stage: ConfederationSigningStage, approved: Boolean, failure: String? = null) = ConfederationSigningUIState.Loaded(
private fun signing(
stage: ConfederationSigningStage,
approved: Boolean,
failure: String? = null,
kind: Int = 1,
answers: List<ConfederationSigningAnswer> = listOf(
ConfederationSigningAnswer("Ana", approvedFor = listOf("Agora")),
ConfederationSigningAnswer("Bo"),
ConfederationSigningAnswer("Cy", declinedFor = listOf("Polis")),
),
) = ConfederationSigningUIState.Loaded(
attempt = ConfederationSigningAttempt(
id = "s".repeat(64), confederationId = roomId, proposerPublicKey = polis, userPublicKey = "a".repeat(64),
eventJson = "{}", stage = stage, approvedAt = if (approved) kotlin.time.Instant.fromEpochSeconds(1) else null, failureReason = failure,
),
event = com.vitorpamplona.quartz.nip01Core.core.Event("e".repeat(64), roomId, 1, 1, emptyArray(), "The first words of a group of groups", ""),
answers = listOf("Ana" to true, "Bo" to null, "Cy" to false),
event = com.vitorpamplona.quartz.nip01Core.core.Event(
"e".repeat(64), roomId, 1, kind, emptyArray(),
if (kind == 0) """{"name":"Atlas"}""" else "The first words of a group of groups", "",
),
answers = answers,
roleCount = 9,
groupCount = 3,
)
@@ -365,6 +379,35 @@ class ConfederationScreensJvmTest {
onNodeWithText("Approved").assertIsDisplayed()
}
@Test
fun `somebody seated in several groups is shown answering for each, not as declining`() =
renderSigning(
signing(
ConfederationSigningStage.NONCES, approved = true,
answers = listOf(ConfederationSigningAnswer("Ana", approvedFor = listOf("Agora", "Polis"), declinedFor = listOf("Ekklesia"))),
)
) {
onNodeWithText("Approved for Agora, Polis").assertIsDisplayed()
onNodeWithText("Declined for Ekklesia").assertIsDisplayed()
onAllNodesWithText("Declined").assertCountEquals(0)
}
@Test
fun `on a profile, a group that had not endorsed it yet is not a refusal`() =
renderSigning(
signing(
ConfederationSigningStage.NONCES, approved = true, kind = 0,
answers = listOf(
ConfederationSigningAnswer("Ana", approvedFor = listOf("Agora"), declinedFor = listOf("Ekklesia")),
ConfederationSigningAnswer("Cy", declinedFor = listOf("Ekklesia")),
),
)
) {
onNodeWithText("Approved for Agora").assertIsDisplayed()
onAllNodesWithText("Not for Ekklesia, which had not endorsed it when signing began").assertCountEquals(2)
onAllNodesWithText("Declined", substring = true).assertCountEquals(0)
}
@Test
fun `an attempt that did not finish says why, and asks nothing`() =
renderSigning(signing(ConfederationSigningStage.FAILED, approved = true, failure = "A device restarted while signing")) {