Merge branch 'curated' into claude/quartz-1-15-2-compat-c8267f

Both sides had taken schema version 21: curated for the nullable
FrostSigningSession.signDeclinedAt (one refusal takes a member out of the n),
this branch for the Marmot current profile's three columns, with 22 and 23
behind it for the routing table and the publish obligations. Curated keeps 21.
This branch's three migrations move up one -- 21->22, 22->23, 23->24 -- and
the database is at 24; the comment on 22 says they moved and why.

The exported schemas for 22 and 23 could not be hand-edited, since each is a
snapshot of the whole entity set with an identity hash over it, and could
not be produced from the merged tree, which only exports its own version. So
each was regenerated the way the originals were: the tree of the commit that
introduced it (Phase 3 for 22, Phase 4 for 23), with curated's entity change
and its 21.json dropped in, the version bumped, and KSP run. The result is
what a device on curated's 21 migrates through: 22 adds the three columns
and nothing else, 23 adds MarmotRouting, 24 adds MarmotPublishObligation and
MarmotOutboundGate together with MarmotCommitResult.obligationId, and every
one of them carries signDeclinedAt. 24.json is the merged tree's own export.

Everything else merged itself: ChatMessage's kinds and line types, the
transcript's icons, the strings, the nav host. Full jvmTest 1220 green,
Android debug compile, M3 audit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5 committed 2026-09-14 08:09:54 +02:00
commit 984db0a180
36 files changed
+8053 -286

No files matched your search

@@ -65,6 +65,7 @@
<string name="creating_new_chat">Creating new chat.</string>
<string name="currently_no_contacts_please_search_and_chat">Currently no contacts. Please search and chat with a few people.</string>
<string name="currently_no_messages_have_been_shared">Currently no messages have been shared.\nBreak the ice.</string>
<string name="declined_to_sign">Declined to sign</string>
<string name="delete_group">Delete group</string>
<string name="details">Details</string>
<string name="dialect_name">Dialect name</string>
@@ -476,6 +477,18 @@
<string name="edit_schema">Edit schema</string>
<string name="propose_schema">Propose schema</string>
<string name="fields_colon">Fields: %1$s</string>
<!-- The template picker a new schema starts on: curare.to's "Start a list" page, with its four shapes. -->
<string name="start_a_list">Start a list</string>
<string name="a_list_is_a_schema_what_an_entry_may_contain">A list is a schema: what an entry may contain, who may suggest one, and where it lives. The group signs it with its shared key, and only that key can put an entry on the list.</string>
<string name="pick_a_shape_to_start_from">Pick a shape to start from. Everything in it can be changed before the group signs.</string>
<string name="template_links">Links &amp; text</string>
<string name="template_links_description">Reddit’s default: a title with a link or some text, a picture if you like, and a flair.</string>
<string name="template_discussion">Discussion</string>
<string name="template_discussion_description">Text posts only: a title and a body, with a flair.</string>
<string name="template_catalogue">Catalogue</string>
<string name="template_catalogue_description">bitcoin.mov’s shape: things with a year, a type, an external id and links — one entry per thing however often it is suggested.</string>
<string name="template_custom">Custom</string>
<string name="template_custom_description">Just the two fields every list has — an identifier and a title — and whatever you add.</string>
<string name="visibility_public">Public</string>
<string name="visibility_closed">Closed</string>
<string name="visibility_private">Private</string>
@@ -186,7 +186,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 23,
version = 24,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -330,28 +330,37 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// which is what they were, and any identity may drain them. The broadcast
// queue deliberately gets no owner: a signed event is anyone's to carry.
AutoMigration(from = 19, to = 20),
// v21 adds three nullable columns for the Marmot current profile (see
// v21 adds the nullable FrostSigningSession.signDeclinedAt, the other
// answer to the question signApprovedAt records: a member who refused to
// sign, on a session that runs on without them. Refusing used to end the
// session outright, so no row written before this can be one where the
// owner declined and the session is still open -- every such session is
// FAILED, and null reads as "not declined", which is true of all the
// rest. A nullable column is a shape Room migrates itself.
AutoMigration(from = 20, to = 21),
// v22 adds three nullable columns for the Marmot current profile (see
// docs/marmot-v2.md, Phase 3): MarmotKeyPackageBundle.profile and .dTag, and
// MarmotKeyPackage.profile. A bundle's profile decides which shape a rotation
// republishes into which slot, its dTag is the kind:30443 slot it reuses so a
// replacement supersedes rather than accumulates, and a peer package's profile
// is what a room picks by. Rows from before read back null, which every
// reader takes as legacy -- what they were.
AutoMigration(from = 20, to = 21),
// v22 adds MarmotRouting: the address a room's kind:445 traffic is carried
// reader takes as legacy -- what they were. (v22-v24 were v21-v23 on the
// branch that made them; they moved up one when the branch met v21 above.)
AutoMigration(from = 21, to = 22),
// v23 adds MarmotRouting: the address a room's kind:445 traffic is carried
// under, separate from the room's id (docs/marmot-v2.md, Phase 4). A
// current-profile room this app creates mints a random routing id -- the
// room's own id is a derived key, which v2's routing component says must
// never be the address -- and every reader keyed on the `h` tag resolves it
// through this table. No rows are backfilled: a room with none is addressed
// by its own id, which is what every room before the table was.
AutoMigration(from = 21, to = 22),
// v23 adds MarmotPublishObligation and MarmotOutboundGate: the commits this
AutoMigration(from = 22, to = 23),
// v24 adds MarmotPublishObligation and MarmotOutboundGate: the commits this
// device prepared and has not yet heard a relay accept, and the gates a room
// is under (docs/marmot-v2.md, Phase 6). Both have to outlive the process --
// an obligation forgotten at a crash is a replacement commit at the next
// start, which forks the group against whoever took the first one.
AutoMigration(from = 22, to = 23),
AutoMigration(from = 23, to = 24),
]
)
@ColumnTypeConverters(CurareConverters::class)
@@ -280,6 +280,17 @@ data class ChatMessage(
const val TYPE_FROST_COMPLETE = "frostComplete"
const val TYPE_FROST_FAILED = "frostFailed"
/**
* A member refused to sign, and the session went on without them.
*
* Its own type rather than a failure, because it is not one: a t-of-n key
* can do without `n - t` members, and this line is one of the refusals
* the key can absorb. The refusal that leaves too few to sign is written
* as [TYPE_FROST_FAILED] instead, saying both that the member declined
* and that it was the one that ended the session.
*/
const val TYPE_FROST_DECLINED = "frostDeclined"
/** Addressed to the reader rather than said by anyone -- see [DKG_REQUEST_TYPES]. */
const val TYPE_FROST_APPROVAL_NEEDED = "frostApprovalNeeded"
@@ -301,14 +312,18 @@ data class ChatMessage(
* The signing lines that end a session, whichever way it went.
*
* A request usually stops being one by being answered, but that is not
* the only way. A member who declines publishes nothing, and a quorum
* that signs without them asks them for nothing further -- from the
* transcript both look the same, nothing of the reader's own either
* side of the request, so the session's own ending is the only thing
* left to read it from.
* the only way. A quorum that signs without the reader asks them for
* nothing further, and a session that is abandoned asks nobody for
* anything -- in both there is nothing of the reader's own either side
* of the request, so the session's own ending is the only thing left to
* read it from.
*
* A ceremony has no equivalent because a ceremony step can only be
* taken or waited for. Signing is the one thing a member can refuse.
* taken or waited for. Signing is the one thing a member can refuse --
* and a refusal the session survives is the third way a request can be
* over, read by [settledRequests] from the reader's own
* [TYPE_FROST_DECLINED] line rather than from here: it settles only
* the refuser's request, where these settle everybody's.
*/
val FROST_SETTLEMENTS = setOf(TYPE_FROST_COMPLETE, TYPE_FROST_FAILED)
@@ -321,6 +336,7 @@ data class ChatMessage(
TYPE_FROST_SIGNATURE,
TYPE_FROST_COMPLETE,
TYPE_FROST_FAILED,
TYPE_FROST_DECLINED,
TYPE_FROST_APPROVAL_NEEDED,
)
@@ -337,6 +353,7 @@ data class ChatMessage(
TYPE_FROST_PARTIAL_SIGNATURE,
TYPE_FROST_SIGNATURE,
TYPE_FROST_FAILED,
TYPE_FROST_DECLINED,
)
val DKG_AUTHORED_TYPES = setOf(
@@ -677,17 +694,24 @@ data class ChatMessage(
* earned no tick and claiming otherwise would credit them with a
* signature they refused or were never needed for. What they have run
* out of is a decision to make -- see [FROST_SETTLEMENTS].
*
* The reader's own refusal settles their request too, and only theirs.
* The session is still open -- the others may yet sign it -- so it is
* not an ending, and another member's refusal leaves the reader with
* exactly the decision they had.
*/
fun settledRequests(messages: List<ChatMessage>): Set<Long> = messages
.filter { request ->
request.messageType in FROST_REQUEST_TYPES &&
messages.any {
it.messageType in FROST_SETTLEMENTS && it.isAbout(request)
}
messages.any { it.settles() && it.isAbout(request) }
}
.map { it.id }
.toSet()
private fun ChatMessage.settles(): Boolean =
messageType in FROST_SETTLEMENTS ||
(messageType == TYPE_FROST_DECLINED && isUserMessage)
/**
* Files one direct message, from whichever side of it this device is on.
*
@@ -13,8 +13,11 @@ import kotlin.time.Instant
* rather than accumulates — relays redeliver, and feeding the same nonce in
* twice would make the coordinator's signer set the wrong length.
*
* Covers the nonce and the partial signature; the coordinator's own broadcasts
* live on [FrostSigningSession] because there is only ever one of each.
* Covers the nonce, the partial signature and the refusal; the coordinator's
* own broadcasts live on [FrostSigningSession] because there is only ever one
* of each. A refusal is here rather than on the session for the same reason a
* nonce is: there is one per member, and how many there are is what decides
* whether the session goes on -- see `FrostSigningSession.declinesThatAbandon`.
*
* Keyed on `(sessionId, signerPublicKey, kind)`, which also means a member
* cannot replace their own nonce once the coordinator has aggregated it — a
@@ -45,7 +48,10 @@ data class FrostSignerMessage(
/** One of the `FrostSigningEvents` kinds. */
val kind: Kind,
/** Hex of the protocol bytes: a public nonce, or a partial signature. */
/**
* Hex of the protocol bytes: a public nonce, or a partial signature. For a
* refusal there are no bytes, and this is the reason the member gave.
*/
val payload: HexKey,
val createdAt: Instant = Clock.System.now(),
@@ -35,7 +35,7 @@ import to.curare.compose.managers.SharedKeyDerivation
* | ceremony, threshold, participant count | the unsigned event and its id |
* | [signerIds] and the signer set | nonce seed, and the nonce from it |
* | [derivationPath] and its tweak cache | aggregated nonce |
* | [signApprovedAt] -- one decision | the signature |
* | [signApprovedAt] or [signDeclinedAt] -- one decision | the signature |
*
* ### The nonce, and why one item means one message
*
@@ -136,6 +136,19 @@ data class FrostSigningSession(
*/
val signApprovedAt: Instant? = null,
/**
* When this device's owner refused instead. The other answer to the same
* question, and the same shape: a decision, recorded before anything is
* published on the strength of it, and never revisited. `advance` publishes
* the refusal the way it publishes a nonce for an approval -- whenever the
* row says so and no copy of the message is on file yet.
*
* Refusing does not end the session. A t-of-n key needs t willing members,
* so what one refusal does is take one member out of the n; the session is
* abandoned only once fewer than t are left -- see [declinesThatAbandon].
*/
val signDeclinedAt: Instant? = null,
/** Whether the chat line asking for that approval has been written. */
val approvalRequestedAt: Instant? = null,
@@ -154,6 +167,17 @@ data class FrostSigningSession(
/** Whether this device was picked to sign. A t-of-n key does not need everyone. */
fun isSigner(): Boolean = signerIdList()?.contains(signerId) ?: false
/**
* How many members have to refuse before the signature cannot be made.
*
* A t-of-n key can do without `n - t` members, so it is the refusal after
* that -- the one leaving fewer than t who could still sign -- that abandons
* the session. In a 2-of-3 group one member may decline and the other two
* still sign; the second refusal is the one that ends it. In an n-of-n group
* every member is needed and a single refusal is enough.
*/
fun declinesThatAbandon(): Int = participantCount - threshold + 1
/**
* [derivationPath] as indices, and an empty list when there is none.
*
@@ -7,6 +7,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import to.curare.compose.database.CurareDatabase
import to.curare.compose.database.model.FrostSignerMessage
import to.curare.compose.database.model.FrostSigningItem
@@ -14,6 +15,7 @@ import to.curare.compose.database.model.FrostSigningSession
import to.curare.compose.database.model.intermdiate.LocalChatRoom
import to.curare.compose.database.model.intermdiate.LocalFrostSigningSession
import to.curare.compose.managers.FrostSigningManager
import to.curare.compose.nostr.dkg.DkgRitualEvents
import to.curare.compose.repository.FrostSigningRepository
class DatabaseFrostSigningRepository(
@@ -31,6 +33,14 @@ class DatabaseFrostSigningRepository(
override fun observeMessages(sessionId: String): Flow<List<FrostSignerMessage>> =
database.frostSigningSessionDao().observeMessages(sessionId)
override fun observeShareHolders(dkgSessionId: String): Flow<Set<HexKey>> =
database.dkgSessionDao().observeMessages(dkgSessionId).map { messages ->
messages
.filter { it.kind == DkgRitualEvents.HOST_KEY }
.map { it.participantPublicKey }
.toSet()
}
override fun observeItems(sessionId: String): Flow<List<FrostSigningItem>> =
database.frostSigningSessionDao().observeItems(sessionId)
@@ -106,6 +106,12 @@ import to.curare.compose.nostr.frost.FrostSigningEvents
* threshold to be reachable, picks a signer set, and says who is in it. Members
* outside the set do nothing and are not stalling anything.
*
* The same arithmetic runs the other way. A member who refuses takes one of
* the n away rather than ending the session, and it is abandoned only once
* fewer than t are left who could still sign -- see [recordDecline]. In a
* 2-of-3 group one refusal is nothing the other two cannot sign around; the
* second is the one that ends it.
*
* ### Restart-safety is forced, not chosen
*
* `SecretNonce` cannot be serialised and refuses to be used twice. Storing the
@@ -634,6 +640,105 @@ object FrostSigningManager {
)
return false
}
FrostSigningEvents.DECLINE -> {
return recordDecline(
database = database,
session = session,
member = innerEvent.pubKey,
reason = innerEvent.content
)
}
}
return true
}
/**
* Files one member's refusal, and ends the session if it is the refusal
* that leaves too few members to sign. Returns false when it is, so the
* caller stops rather than trying to advance a dead one.
*
* The count is this device's own, made from the refusals it has received,
* and every device makes the same one: the threshold and the participant
* count came off the ceremony, and a refusal is a message like any other.
* Nobody announces the abandonment, because nobody has to -- each device
* reaches it on its own the way each writes its own transcript, and a
* FAILURE sent to say so would name one member as the culprit for what was
* the group's arithmetic.
*
* Only a ceremony participant's refusal counts, and only theirs is kept. A
* subgroup's ceremony runs in the parent's room over a subset of it, so a
* message here can come from a member who holds no share, and a refusal to
* sign from somebody who could not have signed takes nobody out of the n.
* A member who has already offered a nonce cannot refuse through the app --
* the screen offers one answer or the other -- so a refusal is never
* counted against a signer.
*
* The transcript line is written once, on the first delivery; the count is
* recomputed on every one, which costs nothing and is idempotent by
* [fail]'s own guard.
*/
private suspend fun recordDecline(
database: CurareDatabase,
session: FrostSigningSession,
member: HexKey,
reason: String
): Boolean {
val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return true
val participants = signerIds(database, key).keys
if (member !in participants) {
logger.w(
"Session ${session.id}: refusal from ${member.take(8)}, who holds no share of " +
"key ${key.id}; ignoring"
)
return true
}
val known = database.frostSigningSessionDao()
.getMessage(session.id, FrostSigningEvents.DECLINE, member) != null
database.frostSigningSessionDao().upsert(
FrostSignerMessage(
sessionId = session.id,
signerPublicKey = member,
kind = FrostSigningEvents.DECLINE,
payload = reason
)
)
val declined = database.frostSigningSessionDao()
.getMessagesByKind(session.id, FrostSigningEvents.DECLINE)
.map { it.signerPublicKey }
.filter { it in participants }
.toSet()
.size
val willing = session.participantCount - declined
if (declined >= session.declinesThatAbandon()) {
fail(
database = database,
session = session,
reason = "Abandoned: $declined of ${session.participantCount} members declined " +
"to sign, leaving fewer than the ${session.threshold} it takes.",
culprit = member,
content = "declined to sign. That leaves fewer than the ${session.threshold} of " +
"${session.participantCount} members it takes, so the signature is " +
"abandoned. Nothing was signed, and it is safe to ask again."
)
return false
}
if (!known) {
announce(
database = database,
session = session,
messageType = ChatMessage.TYPE_FROST_DECLINED,
content = "declined to sign. It takes ${session.threshold} of " +
"${session.participantCount} members, and $willing could still sign.",
actor = member
)
}
return true
@@ -690,8 +795,22 @@ object FrostSigningManager {
// Returns rather than throws: the session is not failing, it is waiting
// on a person, and everything received stays stored so it resumes the
// moment they approve.
//
// A refusal is the other way of having said so, and it returns from
// the same place: there is nothing more of this device's to publish,
// and the session goes on around it -- the signature arriving is what
// closes it, at the top of this pass. What a refusal does publish is
// itself, on the same terms as a nonce below: whenever the row says
// the owner refused and no copy of the message is on file, so that a
// device killed between deciding and sending says it on the next
// message rather than leaving the group to wait on a member who has
// already answered.
if (session.signApprovedAt == null) {
announceApprovalNeeded(database, session)
if (session.signDeclinedAt == null) {
announceApprovalNeeded(database, session)
} else if (ownMessage(database, session, FrostSigningEvents.DECLINE) == null) {
publishDecline(database, localChatRoom, session)
}
return
}
@@ -1550,17 +1669,32 @@ object FrostSigningManager {
if (settled || current.stage.ordinal >= stage.ordinal) current else current.copy(stage = stage)
}
/**
* Ends the session, and puts the line saying so in the group's chat with
* [culprit]'s name in front of it.
*
* [content] is that line's predicate. The default is the one a fault gets;
* a refusal that tips the count writes its own, because what happened there
* is that a member declined, and the abandonment is the arithmetic of it.
*/
private suspend fun fail(
database: CurareDatabase,
session: FrostSigningSession,
reason: String,
culprit: HexKey = session.userPublicKey
culprit: HexKey = session.userPublicKey,
content: String = "abandoned the signature. Nothing was signed, and it is safe to ask again."
) {
// Read before writing so the notice goes out once. A session can be failed
// from two directions -- a FAILURE message from a member, and a fault
// raised locally -- and the group does not need to be told twice.
//
// A signature the group has made is not abandoned by anything that
// arrives afterwards. A member who refused before their device had seen
// the signature has refused something that no longer needed them, and
// marking a signed session failed on their say-so would be reporting
// a signature that exists as one that does not.
val current = database.frostSigningSessionDao().getSessionById(session.id) ?: session
if (current.stage == FrostSigningStage.FAILED) return
if (current.stage == FrostSigningStage.FAILED || current.stage == FrostSigningStage.COMPLETE) return
update(database, current) {
it.copy(stage = FrostSigningStage.FAILED, failureReason = reason)
@@ -1569,7 +1703,7 @@ object FrostSigningManager {
database = database,
session = current,
messageType = ChatMessage.TYPE_FROST_FAILED,
content = "abandoned the signature. Nothing was signed, and it is safe to ask again.",
content = content,
actor = culprit
)
}
@@ -1599,10 +1733,13 @@ object FrostSigningManager {
// The group signed it without needing this member, and [advance] closes
// the session on its next pass without asking them anything. Offering the
// decision anyway would be offering two bad answers: a nonce nobody is
// waiting for, or a refusal that abandons a signature already made.
// waiting for, or a refusal nobody is counting.
if (items.isNotEmpty() && items.all { it.isSigned() }) return false
return session.signApprovedAt == null
// Either answer is an answer. A member who refused is not asked again,
// even though the session is still open around them: the question was
// theirs to answer once, and it has been.
return session.signApprovedAt == null && session.signDeclinedAt == null
}
/**
@@ -1639,6 +1776,17 @@ object FrostSigningManager {
* A t-of-n group can sign without this member, so declining is a normal
* outcome and not a failure of the session — but only if it is said out loud.
* Silence is indistinguishable from a phone in a pocket.
*
* It used to end the session on the spot, which made one member's no into
* everybody's. Now it is one refusal among however many the key can do
* without: [recordDecline] counts them, on this device as on every other,
* and the session is abandoned only once fewer than the threshold could
* still sign -- so in a 2-of-3 group the first refusal changes nothing the
* other two can do, and the second ends it.
*
* The same shape as [approve]: the decision is written to the row, and
* [advance] does the publishing, so that a device killed in between says
* it on the next message rather than never.
*/
suspend fun decline(
database: CurareDatabase,
@@ -1648,20 +1796,46 @@ object FrostSigningManager {
val session = database.frostSigningSessionDao().getSessionById(sessionId) ?: return
val items = database.frostSigningSessionDao().getItems(sessionId)
if (!isAwaitingApproval(session, items)) return
if (!isAwaitingApproval(session, items)) {
logger.i("Session $sessionId is not waiting on an approval; ignoring the refusal")
return
}
update(database, session) { it.copy(signDeclinedAt = Clock.System.now()) }
logger.i("Session $sessionId: signing declined")
advance(database, localChatRoom, sessionId)
}
/**
* Broadcasts this device's refusal AND files it, so it is counted here the
* way it will be everywhere else.
*
* Not [publishOwn], although it is the same two steps in the same order,
* because the local copy is not just a copy: filing it is what may end the
* session, and [recordDecline] is the one place that decides.
*/
private suspend fun publishDecline(
database: CurareDatabase,
localChatRoom: LocalChatRoom,
session: FrostSigningSession
) {
val reason = "Declined to sign"
fail(
database = database,
session = session,
reason = "Declined on this device",
culprit = session.userPublicKey
)
broadcast(
database = database,
localChatRoom = localChatRoom,
session = session,
kind = FrostSigningEvents.FAILURE,
content = "Declined to sign"
kind = FrostSigningEvents.DECLINE,
content = reason
)
recordDecline(
database = database,
session = session,
member = session.userPublicKey,
reason = reason
)
}
@@ -1746,8 +1920,8 @@ object FrostSigningManager {
"combined the parts into the group's " +
(if (batch) "$count signatures." else "signature.")
// PROPOSAL and FAILURE are announced by the code that acts on them --
// both say more than the message itself carries.
// PROPOSAL, FAILURE and DECLINE are announced by the code that acts on
// them -- each says more than the message itself carries.
else -> return
}
@@ -0,0 +1,262 @@
package to.curare.compose.nostr.curated
/**
* How a client works an entry's `d` out of the entry itself.
*
* The NIP marks the identifier field `derived` and leaves the derivation to the
* publishing client, which is fine for a site with one list and one rule --
* bitcoin.mov's -- and useless for a list started from a template, whose
* entries will be composed by clients that have never seen its code. So
* curare.to records the rule *in the schema*: a machine-readable mark,
* `[rule:<key>]`, at the end of a human sentence in the identifier field's
* hint. A client that knows the rule applies it and one that does not can at
* least read what it is; one that finds no mark falls back to [Title].
*
* This app composes no entries and applies none of these. It writes the mark
* so that a list the group starts here is one that site's form can post to
* with the right identifier -- the same link one post whoever submits it,
* say -- rather than with whatever its fallback happens to be.
*
* The keys, the wording and the shape of the hint are `lib/protocol/derive.ts`
* in the curare.to repository, byte for byte, so that a template started here
* and one started there produce the same schema.
*/
enum class CuratedDeriveRule(
/** The word in the mark. */
val key: String,
/** The rule as the hint says it, after "Derived by the client — ". */
private val phrase: String,
) {
/**
* A post with a link is identified by the link, so the same link is one
* post whoever submits it; a text post by its title and its author.
*/
LinkOrTitle("link-or-title", "the link, else the title and author"),
/** Two people's same-titled posts are two posts; one person's is an edit. */
TitleAuthor("title-author", "the title and author"),
/**
* A catalogue entry with an external id (`imdb:tt…`) is one entry however
* often it is suggested; otherwise the title and year.
*/
ExternalOrTitleYear("external-or-title-year", "the external id, else the title and year"),
/** The same title is the same post, whoever posts it. */
Title("title", "the title"),
;
/** The hint that records this rule on an identifier field. */
fun hint(): String = "Derived by the client — $phrase. [rule:$key]"
}
/**
* The shapes a list can start from: curare.to's templates, the ones its
* "Start a list" page offers, so that a list started in this app and one
* started on that site are the same kind of thing.
*
* Every template carries the two fields every list has -- the identifier,
* derived and with its [rule] recorded in its hint, and the title -- and
* declares no derived `t` field: the hashtag rule is bitcoin.mov's own, and a
* list is its own topic. Flair is the sub-topic.
*
* The field names, labels, placeholders and configs are signed into the
* schema and read by other clients, which is why they are plain strings here
* rather than resources: they are protocol data, not this app's copy. What
* the picker *calls* a template is UI text and lives in the catalogue.
*
* The fields are `lib/protocol/templates.ts` in the curare.to repository,
* field for field. A template added there belongs here too.
*/
enum class CuratedSchemaTemplate(
/** The stable key, the one curare.to's editor takes as `?template=`. */
val key: String,
val rule: CuratedDeriveRule,
val fields: List<CuratedField>,
val requireAny: List<List<String>> = emptyList(),
) {
/** Reddit's default: a title with a link or some text, a picture, and a flair. */
Links(
key = "links",
rule = CuratedDeriveRule.LinkOrTitle,
fields = listOf(
identifier(CuratedDeriveRule.LinkOrTitle),
title(placeholder = "What is it?"),
CuratedField(
name = "link",
type = CuratedFieldType.Url,
isRequired = false,
placeholder = "https://…",
label = "Link",
config = CuratedFieldConfig(tag = "r", marker = "link", max = 500),
),
CuratedField(
name = "body",
type = CuratedFieldType.LongText,
isRequired = false,
placeholder = "Say more, or nothing.",
label = "Text",
config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG, max = 10_000),
),
CuratedField(
name = "image",
type = CuratedFieldType.Image,
isRequired = false,
placeholder = "https://…/picture.jpg",
label = "Picture",
config = CuratedFieldConfig(max = 500, hint = "An https link to an image."),
),
flair("discussion", "news", "question"),
),
requireAny = listOf(listOf("link", "body")),
),
/** Text posts only: a title and a body, with a flair. */
Discussion(
key = "discussion",
rule = CuratedDeriveRule.TitleAuthor,
fields = listOf(
identifier(CuratedDeriveRule.TitleAuthor),
title(placeholder = "What do you want to talk about?"),
CuratedField(
name = "body",
type = CuratedFieldType.LongText,
isRequired = true,
label = "Text",
config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG, max = 10_000),
),
flair("question", "meta"),
),
),
/**
* bitcoin.mov's shape, generalised: things with a year, a type, an
* external id and links, one entry per thing however often it is suggested.
*/
Catalogue(
key = "catalogue",
rule = CuratedDeriveRule.ExternalOrTitleYear,
fields = listOf(
identifier(CuratedDeriveRule.ExternalOrTitleYear),
title(placeholder = "The thing’s name"),
CuratedField(
name = "year",
type = CuratedFieldType.Year,
isRequired = false,
placeholder = "2014",
label = "Year",
config = CuratedFieldConfig(min = 1900, max = 2100),
),
CuratedField(
name = "type",
type = CuratedFieldType.Enum,
isRequired = true,
label = "Type",
config = CuratedFieldConfig(
options = listOf("movie", "documentary", "short", "series", "book", "other"),
),
),
CuratedField(
name = "externalId",
type = CuratedFieldType.Token,
isRequired = false,
placeholder = "imdb:tt2821314",
label = "External id",
config = CuratedFieldConfig(
tag = "i",
max = 60,
hint = "Helps dedupe, e.g. imdb:tt2821314 or isbn:…",
),
),
CuratedField(
name = "watchUrl",
type = CuratedFieldType.Url,
isRequired = false,
placeholder = "https://…",
label = "Where to see it",
config = CuratedFieldConfig(tag = "r", marker = "watch", max = 500, repeat = true),
),
CuratedField(
name = "referenceUrl",
type = CuratedFieldType.Url,
isRequired = false,
placeholder = "https://…",
label = "Reference",
config = CuratedFieldConfig(tag = "r", marker = "reference", max = 500),
),
CuratedField(
name = "image",
type = CuratedFieldType.Image,
isRequired = false,
placeholder = "https://…/poster.jpg",
label = "Picture",
config = CuratedFieldConfig(max = 500),
),
CuratedField(
name = "lang",
type = CuratedFieldType.Token,
isRequired = false,
placeholder = "en",
label = "Language",
config = CuratedFieldConfig(max = 60, pattern = "[A-Za-z]{2,8}([-_][A-Za-z0-9]{2,8})*"),
),
CuratedField(
name = "description",
type = CuratedFieldType.LongText,
isRequired = false,
placeholder = "Why is it worth a look?",
label = "Description",
config = CuratedFieldConfig(tag = CuratedFieldConfig.CONTENT_TAG, max = 4000),
),
),
requireAny = listOf(listOf("watchUrl", "referenceUrl")),
),
/** Just the two fields every list has, and whatever the group adds. */
Custom(
key = "custom",
rule = CuratedDeriveRule.Title,
fields = listOf(identifier(CuratedDeriveRule.Title), title(placeholder = "")),
),
;
companion object {
/**
* The template with [key], or [Custom] for null and for a key this build
* does not know.
*
* Custom rather than the first, which is what curare.to falls back to,
* because Custom is the two fields every list has and nothing else: the
* one shape that cannot presume anything about a list it was not asked
* for. Null is what an edit carries, where the template is meaningless,
* and what a screen handed a loaded state without one gets.
*/
fun byKey(key: String?): CuratedSchemaTemplate = entries.firstOrNull { it.key == key } ?: Custom
}
}
// The fields the templates share, as functions of the file rather than of the
// companion: an enum's entries are built before its companion is, so they
// cannot call into it.
/**
* The identifier field every template starts with: [CuratedField.IDENTIFIER]
* with the rule recorded in its hint.
*/
private fun identifier(rule: CuratedDeriveRule): CuratedField =
CuratedField.IDENTIFIER.copy(
config = CuratedField.IDENTIFIER.config.copy(hint = rule.hint()),
)
/** The title field every template starts with: [CuratedField.TITLE] with an example. */
private fun title(placeholder: String): CuratedField =
CuratedField.TITLE.copy(placeholder = placeholder)
/** A sub-topic an entry may pick one of. */
private fun flair(vararg options: String): CuratedField = CuratedField(
name = "flair",
type = CuratedFieldType.Enum,
isRequired = false,
label = "Flair",
config = CuratedFieldConfig(options = options.toList()),
)
@@ -29,12 +29,23 @@ import to.curare.compose.nostr.frost.tags.FrostSignerIdsTag
* signer --[ 30323 partial ]-> everyone this device's partial signature
* proposer --[ 30324 signature ]-> everyone the finished 64-byte signature
* anyone --[ 30325 failure ]-> everyone abandon + blame
* signer --[ 30330 decline ]-> everyone this member will not sign
* ```
*
* [GroupKeyStateEvent] sits just past them on 30326. It is not part of a
* session -- it is the standing fact a session is opened against, saying which
* A decline is not a failure, which is why it is a kind of its own. A t-of-n
* key needs t willing members, not n, so one member saying no leaves the
* session open for the rest -- and every device counts the refusals it has
* seen against the same arithmetic, abandoning only once fewer than t members
* could still sign. See `FrostSigningManager.recordDecline`. A failure is the
* other thing: a fault that no quorum can work around, and it ends the session
* wherever it lands.
*
* [GroupKeyStateEvent] sits just past the first six on 30326. It is not part of
* a session -- it is the standing fact a session is opened against, saying which
* key the room signs with -- so it is deliberately outside [ALL], which is what
* the inbound path dispatches a session message on.
* the inbound path dispatches a session message on. 30327-30329 went to the
* chronicle and subgroup families before a session needed a seventh kind, which
* is why the decline sits at 30330 rather than in the run.
*
* ### Why 3032x
*
@@ -82,6 +93,18 @@ object FrostSigningEvents {
/** Session abandoned. Content is the reason, for showing to the group. */
val FAILURE: Kind = 30325
/**
* One member will not sign. Content is their reason, for showing to the
* group; the session goes on without them unless too few are left.
*
* A build predating this kind does not route it -- it is not in that build's
* [ALL] -- so an old device never learns of a refusal and simply keeps
* waiting, which is what it did for a member who said nothing. It still
* sends its own refusals as [FAILURE], and a new device honours those as
* the abandonment they always were.
*/
val DECLINE: Kind = 30330
/** Every kind above, for filtering inbound payloads in one check. */
val ALL: Set<Kind> = setOf(
PROPOSAL,
@@ -89,7 +112,8 @@ object FrostSigningEvents {
SIGNER_SET,
PARTIAL_SIGNATURE,
SIGNATURE,
FAILURE
FAILURE,
DECLINE
)
fun isFrostSigningKind(kind: Kind): Boolean = kind in ALL
@@ -32,6 +32,23 @@ interface FrostSigningRepository {
fun observeMessages(sessionId: String): Flow<List<FrostSignerMessage>>
/**
* Who holds a share of the key a ceremony made, and so can take part in a
* session signing with it.
*
* The members who put a host key into the ceremony -- the same rows
* `FrostSigningManager` places signer ids over, so this cannot disagree with
* whose nonces, partial signatures and refusals the session counts. A
* ceremony cannot complete without every participant's host key, so for a
* completed one this is the whole participant set.
*
* Not the room's roster. A room can hold members who were added after its
* ceremony and hold no share, and a subgroup's ceremony runs in the parent's
* room, which holds everybody the subgroup is not. A screen listing the room
* would show people the session is not waiting on and cannot be answered by.
*/
fun observeShareHolders(dkgSessionId: String): Flow<Set<HexKey>>
/**
* The events a session signs, in the order its proposal fixed.
*
@@ -139,6 +156,9 @@ interface FrostSigningRepository {
override fun observeMessages(sessionId: String): Flow<List<FrostSignerMessage>> =
flowOf(emptyList())
override fun observeShareHolders(dkgSessionId: String): Flow<Set<HexKey>> =
flowOf(emptySet())
override fun observeItems(sessionId: String): Flow<List<FrostSigningItem>> =
flowOf(emptyList())
@@ -92,6 +92,7 @@ import to.curare.compose.nostr.curated.CuratedField
import to.curare.compose.nostr.curated.CuratedFieldType
import to.curare.compose.nostr.curated.CuratedSchemaEvent
import to.curare.compose.nostr.curated.CuratedSchemaProblem
import to.curare.compose.nostr.curated.CuratedSchemaTemplate
import to.curare.compose.nostr.curated.CuratedVisibility
import to.curare.compose.repository.ChatRepository
import to.curare.compose.repository.FrostSigningRepository
@@ -250,6 +251,12 @@ import org.jetbrains.compose.resources.stringResource
* suggestion to the list replies to, so changing it would not edit the list but
* start a second one and orphan the first's queue. The field is read-only on an
* edit and says why; a new list is "Add schema" on the group's screen.
*
* **A new list starts from a template.** "Add schema" opens
* `SelectCuratedSchemaTemplateScreen` first, and the shape chosen there arrives
* as [template] -- the fields and rules the form is seeded with, in place of the
* bare two every list has. The form is the same either way: a template is a
* starting point, and everything in it can be changed before the group signs.
*/
@OptIn(
ExperimentalMaterial3ExpressiveApi::class,
@@ -262,6 +269,8 @@ fun EditGroupCuratedSchemaScreen(
chatRoomId: String,
relayHint: String?,
identifier: String?,
/** The key of the `CuratedSchemaTemplate` a new schema starts from. Ignored on an edit. */
template: String? = null,
initialEditGroupCuratedSchemaUIState: EditGroupCuratedSchemaUIState =
EditGroupCuratedSchemaUIState.Loading,
chatRepository: ChatRepository,
@@ -274,6 +283,7 @@ fun EditGroupCuratedSchemaScreen(
chatRoomId = chatRoomId,
relayHint = relayHint,
identifier = identifier,
template = template,
initialEditGroupCuratedSchemaUIState = initialEditGroupCuratedSchemaUIState,
activeUserPublicKey = activeUserPublicKey,
chatRepository = chatRepository,
@@ -1472,6 +1482,9 @@ private fun EditGroupCuratedSchemaScreenPreview() {
chatRoomId = "publicKey",
relayHint = null,
identifier = null,
// The shape a new list most often starts from, so the preview
// shows a templated form rather than the bare two fields.
template = CuratedSchemaTemplate.Links.key,
initialEditGroupCuratedSchemaUIState = EditGroupCuratedSchemaUIState.Loaded(
localChatRoom = LocalChatRoom(
chatRoom = ChatRoom(
@@ -1483,9 +1496,9 @@ private fun EditGroupCuratedSchemaScreenPreview() {
mlsGroupState = "state"
),
),
// A new schema, so the editor seeds the two fields every list
// has and the preview shows what a group actually starts from
// rather than an empty form.
// A new schema, so the editor seeds the template's fields and
// the preview shows what a group actually starts from rather
// than an empty form.
defaultRelays = listOf("wss://relay.example.com"),
// A group that can sign, so the form renders in the state a
// member actually meets it in rather than greyed out.
@@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Block
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Draw
import androidx.compose.material.icons.filled.ErrorOutline
@@ -57,6 +58,7 @@ import to.curare.compose.ui.theme.spacing
import to.curare.compose.ui.composable.widgets.Decorative
import curare.composeapp.generated.resources.Res
import org.jetbrains.compose.resources.stringResource
import curare.composeapp.generated.resources.declined_to_sign
import curare.composeapp.generated.resources.don_t_sign
import curare.composeapp.generated.resources.has_not_taken_part_yet
import curare.composeapp.generated.resources.members
@@ -170,7 +172,7 @@ fun FrostSigningScreen(
HorizontalDivider()
Text(
text = statusOf(session),
text = statusOf(session, declined = state.declined.size),
style = MaterialTheme.typography.bodyMedium
)
@@ -192,58 +194,72 @@ fun FrostSigningScreen(
// Named rather than counted, for the same reason the ceremony's
// ladder names people: "1 of 2" does not tell anyone whose door
// to knock on, and a session stalls until somebody knocks.
state.localChatRoom.localParticipants
.distinctBy { it.participant.participantPublicKey }
.forEach { localParticipant ->
val member = localParticipant.participant.participantPublicKey
//
// The share holders, not the room. A member added to the room
// after its key was made holds no share, and so can neither
// sign nor refuse -- listing them would name a door that cannot
// answer. See FrostSigningUIState.Loaded.members.
state.members.forEach { localParticipant ->
val member = localParticipant.participant.participantPublicKey
Card {
ListItem(
leadingContent = {
ProfileAvatar(
publicKey = member,
profile = localParticipant.profile
Card {
ListItem(
leadingContent = {
ProfileAvatar(
publicKey = member,
profile = localParticipant.profile
)
},
trailingContent = {
when {
member in state.signed -> Icon(
Icons.Default.CheckCircle,
contentDescription = "Signed",
tint = MaterialTheme.colorScheme.primary
)
},
trailingContent = {
when {
member in state.signed -> Icon(
Icons.Default.CheckCircle,
contentDescription = "Signed",
tint = MaterialTheme.colorScheme.primary
)
member in state.offeredNonce -> Icon(
Icons.Default.HourglassEmpty,
contentDescription = "Ready to sign"
)
else -> Icon(
Icons.Default.RadioButtonUnchecked,
contentDescription = "Not yet",
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
},
headlineContent = {
Text(
text = localParticipant.profile
?.humanReadableNameOrPubkey()
?: member
member in state.offeredNonce -> Icon(
Icons.Default.HourglassEmpty,
contentDescription = "Ready to sign"
)
},
supportingContent = {
Text(
text = when {
member in state.signed -> stringResource(Res.string.signed_their_part)
member in state.offeredNonce -> stringResource(Res.string.ready_to_sign)
else -> stringResource(Res.string.has_not_taken_part_yet)
}
// Quiet rather than red: a refusal the
// session survives is not an error, and
// the one it does not survive ends the
// session, which the status line says.
member in state.declined -> Icon(
Icons.Default.Block,
contentDescription = "Declined",
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
else -> Icon(
Icons.Default.RadioButtonUnchecked,
contentDescription = "Not yet",
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
)
}
},
headlineContent = {
Text(
text = localParticipant.profile
?.humanReadableNameOrPubkey()
?: member
)
},
supportingContent = {
Text(
text = when {
member in state.signed -> stringResource(Res.string.signed_their_part)
member in state.offeredNonce -> stringResource(Res.string.ready_to_sign)
member in state.declined -> stringResource(Res.string.declined_to_sign)
else -> stringResource(Res.string.has_not_taken_part_yet)
}
)
}
)
}
}
// Asked rather than re-derived: the manager owns when a session
// is still waiting on its owner, and a second copy of that rule
@@ -386,20 +402,40 @@ private fun OneThingBeingSigned(event: Event) {
}
}
private fun statusOf(session: FrostSigningSession): String = when (session.stage) {
FrostSigningStage.COLLECTING_NONCES ->
"Waiting for ${session.threshold} of ${session.participantCount} members to take part."
/**
* Where the session has got to, and -- once anybody has refused -- how many
* refusals it has left in it. A t-of-n session is abandoned only when fewer
* than t members could still sign, so "2 could still sign" beside "it takes 2"
* is the reader being told the next refusal ends it.
*/
private fun statusOf(session: FrostSigningSession, declined: Int): String {
val declinedHere = session.signDeclinedAt != null
val willing = session.participantCount - declined
FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES ->
if (session.isSigner()) {
"You are one of the signers. Waiting on the rest of them."
} else {
"Enough members took part without needing you. Waiting on them to sign."
return when (session.stage) {
FrostSigningStage.COLLECTING_NONCES -> when {
declinedHere ->
"You declined to sign. It takes ${session.threshold} of ${session.participantCount} " +
"members, and $willing could still sign."
declined > 0 ->
"Waiting for ${session.threshold} of ${session.participantCount} members to take " +
"part. $declined declined, and $willing could still sign."
else ->
"Waiting for ${session.threshold} of ${session.participantCount} members to take part."
}
FrostSigningStage.COMPLETE -> "Signed."
FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES -> when {
session.isSigner() -> "You are one of the signers. Waiting on the rest of them."
declinedHere -> "You declined to sign. Enough members took part without you. Waiting on them to sign."
else -> "Enough members took part without needing you. Waiting on them to sign."
}
FrostSigningStage.FAILED -> "Abandoned. Nothing was signed, and it is safe to ask again."
FrostSigningStage.COMPLETE -> "Signed."
FrostSigningStage.FAILED -> "Abandoned. Nothing was signed, and it is safe to ask again."
}
}
@ConformancePreviews
@@ -57,6 +57,7 @@ import to.curare.compose.ui.composable.navigation.routes.BroadcastGroupSignedEve
import to.curare.compose.ui.composable.navigation.routes.CuratedSuggestionListRoute
import to.curare.compose.ui.composable.navigation.routes.EditGroupCuratedSchemaRoute
import to.curare.compose.ui.composable.navigation.routes.Route
import to.curare.compose.ui.composable.navigation.routes.SelectCuratedSchemaTemplateRoute
import to.curare.compose.ui.composable.widgets.Decorative
import to.curare.compose.ui.composable.widgets.EmptyState
import to.curare.compose.ui.composable.widgets.ErrorState
@@ -80,7 +81,9 @@ import kotlin.time.Instant
* nothing more. This is where they are read: one card per list, most recently
* signed first, each with its queue and its broadcast under it, and -- for a
* member holding a share of the key -- the way into the editor, on the card
* for a revision and at the end for a new list.
* for a revision, and at the end the way to a new list, which starts with the
* template picker rather than with the editor: a new list has a shape to
* choose and a revision has one already.
*
* A schema exists to be read by people who were never in the room, so a member
* without a share reads it like anybody else, and reads its queue, which the
@@ -155,16 +158,28 @@ fun GroupCuratedSchemasScreen(
}
is GroupCuratedSchemasUIState.Loaded -> {
// The one way into the editor, for a revision and for a new
// list alike: the editor takes the identifier of the schema
// to revise, and null for one that does not exist yet.
val edit: (String?) -> Unit = { identifier ->
// A revision opens the editor on the schema to revise, which
// needs no template: it starts from the schema itself.
val edit: (String) -> Unit = { identifier ->
onNavigateToRoute.invoke(
EditGroupCuratedSchemaRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
relayHint = relayHint,
identifier = identifier
identifier = identifier,
template = null
)
)
}
// A new list opens the template picker, which opens the
// editor in turn on the shape chosen there.
val add: () -> Unit = {
onNavigateToRoute.invoke(
SelectCuratedSchemaTemplateRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
relayHint = relayHint
)
)
}
@@ -182,7 +197,7 @@ fun GroupCuratedSchemasScreen(
Res.string.this_group_has_not_published_a_curated_schema_yet
),
action = if (state.canSign) {
{ AddSchemaButton(onClick = { edit(null) }) }
{ AddSchemaButton(onClick = add) }
} else {
null
}
@@ -272,7 +287,7 @@ fun GroupCuratedSchemasScreen(
if (state.canSign) {
item {
AddSchemaButton(onClick = { edit(null) })
AddSchemaButton(onClick = add)
}
}
}
@@ -370,8 +385,9 @@ private fun GroupCuratedSchemaCard(
}
/**
* The way into `EditGroupCuratedSchemaScreen` for a list that does not exist
* yet. The icon is decorative because the label is beside it.
* The way to a list that does not exist yet: `SelectCuratedSchemaTemplateScreen`,
* and through it the editor. The icon is decorative because the label is
* beside it.
*/
@Composable
private fun AddSchemaButton(onClick: () -> Unit) {
@@ -377,8 +377,13 @@ private fun statusOf(proposal: ProposalListUIState.Proposal): String {
if (proposal.awaitsYou) return "Needs your review"
return when (session.stage) {
// Not awaiting the reader and still collecting means they answered, one
// way or the other. A refusal leaves the session open -- a t-of-n key
// can do without this member -- so it is still a session in progress,
// and the row has to say which answer was given.
FrostSigningStage.COLLECTING_NONCES ->
"You agreed. Waiting for ${session.threshold} of " +
(if (session.signDeclinedAt != null) "You declined. " else "You agreed. ") +
"Waiting for ${session.threshold} of " +
"${session.participantCount} members to take part."
FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES ->
@@ -0,0 +1,248 @@
package to.curare.compose.ui.composable
import androidx.compose.foundation.layout.Arrangement
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.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.automirrored.filled.Chat
import androidx.compose.material.icons.filled.Category
import androidx.compose.material.icons.filled.Link
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material3.Card
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.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import curare.composeapp.generated.resources.Res
import curare.composeapp.generated.resources.a_list_is_a_schema_what_an_entry_may_contain
import curare.composeapp.generated.resources.fields_colon
import curare.composeapp.generated.resources.pick_a_shape_to_start_from
import curare.composeapp.generated.resources.start_a_list
import curare.composeapp.generated.resources.template_catalogue
import curare.composeapp.generated.resources.template_catalogue_description
import curare.composeapp.generated.resources.template_custom
import curare.composeapp.generated.resources.template_custom_description
import curare.composeapp.generated.resources.template_discussion
import curare.composeapp.generated.resources.template_discussion_description
import curare.composeapp.generated.resources.template_links
import curare.composeapp.generated.resources.template_links_description
import org.jetbrains.compose.resources.StringResource
import org.jetbrains.compose.resources.stringResource
import to.curare.compose.nostr.curated.CuratedSchemaTemplate
import to.curare.compose.ui.composable.navigation.routes.EditGroupCuratedSchemaRoute
import to.curare.compose.ui.composable.navigation.routes.Route
import to.curare.compose.ui.composable.widgets.Decorative
import to.curare.compose.ui.composable.widgets.LocalSnackbarHostState
import to.curare.compose.ui.composable.widgets.NavigateBackButton
import to.curare.compose.ui.theme.ConformancePreviews
import to.curare.compose.ui.theme.CurareTheme
import to.curare.compose.ui.theme.readableContent
import to.curare.compose.ui.theme.spacing
/**
* The first step of adding a curated schema: which shape the list starts from.
*
* curare.to's "Start a list" page, which is what its `/new` shows before a
* template is chosen: a line on what a list is, and one card per template
* naming it, saying what it is for and listing what an entry in it asks for.
* Tapping a card opens the editor seeded from that template, so that a list
* started here and one started on that site are the same kind of thing --
* and a member who wants none of the shapes takes *Custom*, which is the two
* fields every list has and what "Add schema" used to open on directly.
*
* There is nothing to load and no state to keep: the templates are constants,
* and the choice leaves as an argument to `EditGroupCuratedSchemaRoute` rather
* than being remembered here. Back from the editor is this screen and another
* shape, the way the browser's back is on the site.
*
* Gated by the screen before it, not here. "Add schema" is offered only to a
* member holding a share of the key, and the editor says so again if a screen
* ever reaches it another way.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SelectCuratedSchemaTemplateScreen(
activeUserPublicKey: HexKey,
chatRoomId: String,
relayHint: String?,
onNavigateToRoute: (Route) -> Unit,
onNavigateBack: () -> Unit,
) {
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(Res.string.start_a_list),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = { NavigateBackButton(onNavigateBack) }
)
}
) { innerPadding ->
// A scrolling column rather than a lazy list: four cards, all of them
// wanted at once, and nothing under them to page in.
Column(
modifier = Modifier
.padding(innerPadding)
.readableContent()
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(
horizontal = MaterialTheme.spacing.screenMargin,
vertical = MaterialTheme.spacing.itemGap
),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
// At the leading edge like the cards under it, whose icons and
// headlines it lines up with; the editor after this one centres
// its lead because nothing on it has an edge to keep.
Text(
text = stringResource(Res.string.a_list_is_a_schema_what_an_entry_may_contain),
style = MaterialTheme.typography.bodyMedium
)
Text(
text = stringResource(Res.string.pick_a_shape_to_start_from),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
CuratedSchemaTemplate.entries.forEach { template ->
CuratedSchemaTemplateCard(
template = template,
onClick = {
onNavigateToRoute.invoke(
EditGroupCuratedSchemaRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
relayHint = relayHint,
identifier = null,
template = template.key
)
)
}
)
}
}
}
}
/**
* One shape a list can start from, as a card that opens the editor on it.
*
* The site's card is the name, the description and a count of fields. The
* count is the one thing changed: the fields are listed by label instead, the
* way the group's own schema cards list them, because what a member choosing
* a shape wants to know is what an entry in it will ask for, and "6 fields"
* answers a different question. The identifier is among them although a form
* never asks for it: the editor lists it as a row too, marked derived, and the
* card shows the rows the editor is about to.
*/
@Composable
private fun CuratedSchemaTemplateCard(
template: CuratedSchemaTemplate,
onClick: () -> Unit
) {
Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) {
ListItem(
leadingContent = {
// Decorative: the name beside it is the label, and the card is
// the target.
Icon(template.icon(), contentDescription = Decorative)
},
trailingContent = {
Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = Decorative)
},
headlineContent = {
Text(
text = stringResource(template.label()),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
supportingContent = {
Column(
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)
) {
Text(text = stringResource(template.description()))
// Unclipped, unlike the group's schema cards: a template's
// fields are this build's own and ten at most, and the list
// is what the choice is made on.
Text(
text = stringResource(
Res.string.fields_colon,
template.fields.joinToString { it.labelOrName() }
),
style = MaterialTheme.typography.bodySmall
)
}
}
)
}
}
/**
* What the picker calls a template.
*
* A `when` rather than a field on each entry, for the reason `CuratedVisibility`
* has one: the enum stays the protocol's four shapes with no copy behind it,
* and a fifth is a compile error here rather than a card with no name.
*/
private fun CuratedSchemaTemplate.label(): StringResource = when (this) {
CuratedSchemaTemplate.Links -> Res.string.template_links
CuratedSchemaTemplate.Discussion -> Res.string.template_discussion
CuratedSchemaTemplate.Catalogue -> Res.string.template_catalogue
CuratedSchemaTemplate.Custom -> Res.string.template_custom
}
/** What the template is for, in the site's words. */
private fun CuratedSchemaTemplate.description(): StringResource = when (this) {
CuratedSchemaTemplate.Links -> Res.string.template_links_description
CuratedSchemaTemplate.Discussion -> Res.string.template_discussion_description
CuratedSchemaTemplate.Catalogue -> Res.string.template_catalogue_description
CuratedSchemaTemplate.Custom -> Res.string.template_custom_description
}
/** The picture of the shape: what the entries mostly are, or the sliders for none in particular. */
private fun CuratedSchemaTemplate.icon(): ImageVector = when (this) {
CuratedSchemaTemplate.Links -> Icons.Default.Link
CuratedSchemaTemplate.Discussion -> Icons.AutoMirrored.Filled.Chat
CuratedSchemaTemplate.Catalogue -> Icons.Default.Category
CuratedSchemaTemplate.Custom -> Icons.Default.Tune
}
@ConformancePreviews
@Composable
private fun SelectCuratedSchemaTemplateScreenPreview() {
CurareTheme {
Surface(modifier = Modifier.fillMaxSize()) {
SelectCuratedSchemaTemplateScreen(
activeUserPublicKey = "a".repeat(64),
chatRoomId = "d".repeat(64),
relayHint = null,
onNavigateToRoute = {},
onNavigateBack = {},
)
}
}
}
@@ -45,6 +45,7 @@ import to.curare.compose.ui.composable.EditGroupNostrProfileScreen
import to.curare.compose.ui.composable.AddGroupPostScreen
import to.curare.compose.ui.composable.AcceptCuratedSuggestionScreen
import to.curare.compose.ui.composable.EditGroupCuratedSchemaScreen
import to.curare.compose.ui.composable.SelectCuratedSchemaTemplateScreen
import to.curare.compose.ui.composable.BroadcastGroupSignedEventScreen
import to.curare.compose.ui.composable.CuratedSuggestionListScreen
import to.curare.compose.ui.composable.ProposeGroupEventScreen
@@ -152,6 +153,7 @@ import to.curare.compose.ui.composable.navigation.routes.EditGroupNostrProfileRo
import to.curare.compose.ui.composable.navigation.routes.AddGroupPostRoute
import to.curare.compose.ui.composable.navigation.routes.AcceptCuratedSuggestionRoute
import to.curare.compose.ui.composable.navigation.routes.EditGroupCuratedSchemaRoute
import to.curare.compose.ui.composable.navigation.routes.SelectCuratedSchemaTemplateRoute
import to.curare.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute
import to.curare.compose.ui.composable.navigation.routes.CuratedSuggestionListRoute
import to.curare.compose.ui.composable.navigation.routes.ProposeGroupEventRoute
@@ -1330,6 +1332,23 @@ fun CurareNavHost(
}
)
}
composable<SelectCuratedSchemaTemplateRoute> { backStackEntry ->
val route = backStackEntry.toRoute<SelectCuratedSchemaTemplateRoute>()
SelectCuratedSchemaTemplateScreen(
activeUserPublicKey = route.activeUserPublicKey,
chatRoomId = route.chatRoomId,
relayHint = route.relayHint,
// Pushed rather than replaced, so back from the editor is
// this screen and another shape.
onNavigateToRoute = { editorRoute ->
navController.navigate(route = editorRoute)
},
onNavigateBack = {
navController.popBackStack()
}
)
}
composable<EditGroupCuratedSchemaRoute> { backStackEntry ->
val route = backStackEntry.toRoute<EditGroupCuratedSchemaRoute>()
@@ -1338,14 +1357,24 @@ fun CurareNavHost(
chatRoomId = route.chatRoomId,
relayHint = route.relayHint,
identifier = route.identifier,
template = route.template,
chatRepository = databaseChatRepository,
frostSigningRepository = databaseFrostSigningRepository,
onNavigateToRouteAndPopUpInclusive = { signingRoute ->
// Replace the editor so back returns to the group rather
// than to a schema whose proposal has already gone out.
// than to a schema whose proposal has already gone out --
// and, for a new list, the template picker under it, for
// the same reason: the shape has been chosen and signed
// for, and offering it again would offer a second list.
navController.navigate(route = signingRoute) {
popUpTo<EditGroupCuratedSchemaRoute> {
inclusive = true
if (route.identifier == null) {
popUpTo<SelectCuratedSchemaTemplateRoute> {
inclusive = true
}
} else {
popUpTo<EditGroupCuratedSchemaRoute> {
inclusive = true
}
}
}
},
@@ -10,11 +10,18 @@ import kotlinx.serialization.Serializable
* an edit replaces the event under the same `d`, and the editor's job is to
* propose that replacement, so the coordinate is what names the thing being
* edited and the event is only its current version.
*
* [template] is the key of the `CuratedSchemaTemplate` a new schema starts
* from -- what `SelectCuratedSchemaTemplateRoute` chose, and the same word
* curare.to's editor takes as `?template=`. It means nothing on an edit, which
* starts from the schema itself, and null on a new schema is the bare two
* fields every list has.
*/
@Serializable
data class EditGroupCuratedSchemaRoute(
val activeUserPublicKey: String,
val chatRoomId: String, // TODO: have this as a publicKey
val relayHint: String?,
val identifier: String?
val identifier: String?,
val template: String?
): Route()
@@ -0,0 +1,19 @@
package to.curare.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/**
* The first step of adding a curated schema: which shape the list starts from.
*
* Pushed from the group's schemas screen, and pushing the editor in turn with
* the chosen template's key -- so that back from the editor is this screen and
* a different shape, the way curare.to's `/new` page is under its editor.
* There is no template to carry: the choice is made here and leaves as an
* argument to `EditGroupCuratedSchemaRoute`.
*/
@Serializable
data class SelectCuratedSchemaTemplateRoute(
val activeUserPublicKey: String,
val chatRoomId: String, // TODO: have this as a publicKey
val relayHint: String?
): Route()
@@ -27,6 +27,7 @@ import curare.composeapp.generated.resources.the_key_ceremony_needs_you
import curare.composeapp.generated.resources.ceremonies_need_you
import to.curare.compose.database.model.types.DkgApprovalStep
import androidx.compose.material.icons.filled.AccessTime
import androidx.compose.material.icons.filled.Block
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.ChevronRight
@@ -821,6 +822,9 @@ private fun RitualNotice(
ChatMessage.TYPE_FROST_SIGNATURE -> Icons.Default.WorkspacePremium
ChatMessage.TYPE_FROST_COMPLETE -> Icons.Default.CheckCircle
ChatMessage.TYPE_FROST_FAILED -> Icons.Default.ErrorOutline
// A refusal the session survived. Quiet on purpose: it is not an error,
// and the one that ends a session is written as a failure instead.
ChatMessage.TYPE_FROST_DECLINED -> Icons.Default.Block
ChatMessage.TYPE_FROST_APPROVAL_NEEDED -> Icons.Default.Draw
ChatMessage.TYPE_CHRONICLE_REQUESTED -> Icons.Default.History
@@ -844,9 +848,9 @@ private fun RitualNotice(
// quiet; these are not.
// An answered request is history, not a summons: it keeps its stage's icon so
// the step is still recognisable, but drops the colour and the call to action.
// So is a settled one -- declined, or signed by a quorum that did not need this
// member. Nothing was answered there, so it gets no tick, but offering to
// review it would be offering a decision that has already gone by.
// So is a settled one -- declined, abandoned, or signed by a quorum that did
// not need this member. Nothing was answered there, so it gets no tick, but
// offering to review it would be offering a decision that has already gone by.
val isRequest = (
chatMessage.messageType in ChatMessage.DKG_REQUEST_TYPES ||
chatMessage.messageType in ChatMessage.FROST_REQUEST_TYPES
@@ -20,6 +20,7 @@ import to.curare.compose.nostr.curated.CuratedFieldType
import to.curare.compose.nostr.curated.CuratedSchema
import to.curare.compose.nostr.curated.CuratedSchemaEvent
import to.curare.compose.nostr.curated.CuratedSchemaProblem
import to.curare.compose.nostr.curated.CuratedSchemaTemplate
import to.curare.compose.nostr.curated.CuratedVisibility
import to.curare.compose.repository.ChatRepository
import to.curare.compose.repository.FrostSigningRepository
@@ -49,6 +50,16 @@ import kotlinx.coroutines.launch
* identifier is a new list, with a queue of its own, and the group's screen
* offers that as adding a schema rather than as editing this one.
*
* ### Starting from a template
*
* A new schema is seeded from a [CuratedSchemaTemplate] -- curare.to's four
* shapes, chosen on the screen before this one and named by [template] -- so
* that the form opens on a list's worth of fields rather than on the two every
* list has, and so that the identifier field records how a client derives an
* entry's `d`, which is what lets that site's form post to a list started here.
* The template decides only what the working copy starts as: it is not kept,
* and nothing about the schema remembers which one it came from.
*
* The comparison for "nothing changed" is against the schema as the group signed
* it, normalized on both sides, because re-signing an identical schema would put
* a second statement on the record with a newer timestamp: harmless, since the
@@ -61,6 +72,12 @@ class EditGroupCuratedSchemaViewModel(
val relayHint: String?,
/** The `d` of the schema being edited, or null for a new one. */
val identifier: String?,
/**
* The key of the [CuratedSchemaTemplate] a new schema starts from; see
* [CuratedSchemaTemplate.byKey] for what null and an unknown key get. Not
* read on an edit, which starts from the schema itself.
*/
val template: String? = null,
initialEditGroupCuratedSchemaUIState: EditGroupCuratedSchemaUIState,
val chatRepository: ChatRepository,
val frostSigningRepository: FrostSigningRepository,
@@ -204,10 +221,11 @@ class EditGroupCuratedSchemaViewModel(
/**
* Fills the working copy from the schema the group signed, once.
*
* An existing schema starts at itself. A new one starts at the two fields
* every list has -- the identifier and the title, which `CuratedSchema.normalized`
* would put back anyway, shown up front so that what the member sees is what
* the group will sign -- and at the group's own relays.
* An existing schema starts at itself. A new one starts at its [template]'s
* fields and rules -- every template carrying the identifier and the title,
* which `CuratedSchema.normalized` would put back anyway, shown up front so
* that what the member sees is what the group will sign -- and at the
* group's own relays.
*
* Called from the screen rather than from [initiateEditGroupCuratedSchema],
* because the loader is not the only way a loaded state arrives: a preview
@@ -226,8 +244,10 @@ class EditGroupCuratedSchemaViewModel(
suggesters.addAll(schema.suggesters)
relays.addAll(schema.relays)
} else {
val shape = CuratedSchemaTemplate.byKey(template)
visibility = CuratedVisibility.Public
fields.addAll(listOf(CuratedField.IDENTIFIER, CuratedField.TITLE))
fields.addAll(shape.fields)
requireAny.addAll(shape.requireAny)
relays.addAll(state.defaultRelays)
}
}
@@ -523,6 +543,7 @@ class EditGroupCuratedSchemaViewModel(
chatRoomId: String,
relayHint: String?,
identifier: String?,
template: String? = null,
initialEditGroupCuratedSchemaUIState: EditGroupCuratedSchemaUIState =
EditGroupCuratedSchemaUIState.Loading,
chatRepository: ChatRepository,
@@ -534,6 +555,7 @@ class EditGroupCuratedSchemaViewModel(
chatRoomId = chatRoomId,
relayHint = relayHint,
identifier = identifier,
template = template,
initialEditGroupCuratedSchemaUIState = initialEditGroupCuratedSchemaUIState,
chatRepository = chatRepository,
frostSigningRepository = frostSigningRepository
@@ -13,9 +13,13 @@ import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.IO
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
import to.curare.compose.database.model.FrostSignerMessage
import to.curare.compose.database.model.FrostSigningItem
import to.curare.compose.database.model.FrostSigningSession
import to.curare.compose.nostr.frost.FrostSigningEvents
@@ -44,7 +48,12 @@ class FrostSigningViewModel(
*
* A session moves on messages arriving from other members, so a screen that
* read it once would sit still while the rest of the group signed around it.
*
* Who can take part is read off the ceremony the session names, not off the
* room: the room can hold members who were added after its key was made and
* hold no share of it, and the screen is a list of whose door to knock on.
*/
@OptIn(ExperimentalCoroutinesApi::class)
fun initiate() {
viewModelScope.launch(Dispatchers.IO) {
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
@@ -55,16 +64,24 @@ class FrostSigningViewModel(
frostSigningUIState = FrostSigningUIState.Loaded(localChatRoom = localChatRoom)
val sessions = frostSigningRepository.observeSessionById(sessionId)
val shareHolders = sessions.flatMapLatest { session ->
session?.let { frostSigningRepository.observeShareHolders(it.dkgSessionId) }
?: flowOf(emptySet())
}
combine(
frostSigningRepository.observeSessionById(sessionId),
sessions,
frostSigningRepository.observeMessages(sessionId),
frostSigningRepository.observeItems(sessionId)
) { session, messages, items -> Triple(session, messages, items) }
.collect { (session, messages, items) ->
frostSigningRepository.observeItems(sessionId),
shareHolders
) { session, messages, items, holders -> Observed(session, messages, items, holders) }
.collect { (session, messages, items, holders) ->
frostSigningUIState = FrostSigningUIState.Loaded(
localChatRoom = localChatRoom,
session = session,
items = items,
shareHolders = holders,
offeredNonce = messages
.filter { it.kind == FrostSigningEvents.NONCE }
.map { it.signerPublicKey }
@@ -72,12 +89,24 @@ class FrostSigningViewModel(
signed = messages
.filter { it.kind == FrostSigningEvents.PARTIAL_SIGNATURE }
.map { it.signerPublicKey }
.toSet(),
declined = messages
.filter { it.kind == FrostSigningEvents.DECLINE }
.map { it.signerPublicKey }
.toSet()
)
}
}
}
/** One emission of everything the screen is drawn from -- the fourth flow outgrew `Triple`. */
private data class Observed(
val session: FrostSigningSession?,
val messages: List<FrostSignerMessage>,
val items: List<FrostSigningItem>,
val shareHolders: Set<HexKey>,
)
/** The events the group is being asked to sign, for showing them before they agree. */
fun proposedEvents(items: List<FrostSigningItem>): List<Event> =
items.mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) }
@@ -3,7 +3,9 @@ package to.curare.compose.ui.view.state
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import to.curare.compose.database.model.FrostSigningItem
import to.curare.compose.database.model.FrostSigningSession
import to.curare.compose.database.model.Participant
import to.curare.compose.database.model.intermdiate.LocalChatRoom
import to.curare.compose.database.model.intermdiate.LocalParticipant
sealed interface FrostSigningUIState {
data class Loaded(
@@ -23,7 +25,58 @@ sealed interface FrostSigningUIState {
/** Who has signed their part. */
val signed: Set<HexKey> = emptySet(),
): FrostSigningUIState
/**
* Who has refused. Named for the same reason the other two are: a
* t-of-n session survives some number of refusals and not one more, so
* which members those are is the difference between a session that is
* one refusal from ending and one that is nowhere near.
*/
val declined: Set<HexKey> = emptySet(),
/**
* Who holds a share of the key the session signs with -- the ceremony's
* participants, read off the ceremony rather than the room. Empty until
* the session has been collected, and so until [members] has anyone in it.
*/
val shareHolders: Set<HexKey> = emptySet(),
): FrostSigningUIState {
/**
* The members the session can be answered by, as rows to draw.
*
* The share holders and nobody else. The room's roster is the wrong
* list twice over: a room can hold members added after its key was
* made, who hold no share and cannot sign or refuse, and a subgroup's
* ceremony room is the parent, which holds everybody the subgroup is
* not. The list is whose door to knock on, and a door that cannot
* answer does not belong on it.
*
* Profiles still come off the room, since that is where the rows with
* names in them are, in the order the room keeps them. A share holder
* the room no longer holds -- one who left after the ceremony -- still
* has a share and a place in the count, so they get a placeholder row
* rather than being dropped.
*/
val members: List<LocalParticipant> get() {
val roomMembers = localChatRoom.localParticipants
.distinctBy { it.participant.participantPublicKey }
.associateBy { it.participant.participantPublicKey }
val inRoom = roomMembers.values.filter { it.participant.participantPublicKey in shareHolders }
val elsewhere = (shareHolders - roomMembers.keys).sorted().map { publicKey ->
LocalParticipant(
Participant(
participantPublicKey = publicKey,
chatRoomId = localChatRoom.chatRoom.id,
relayHint = null
),
null
)
}
return inRoom + elsewhere
}
}
data class Error(
val message: String