feat: running key ceremonies resume when the app starts (automatic ceremony, Phase 3)

A ritual moved on an arriving message or a member's tap. Without the
tap, a ceremony holding every message it needs -- one an older build
left waiting to be told to contribute, or one interrupted between
storing a message and acting on it -- would never move.

resumeRunning advances every ceremony this user has joined. Sync runs
it once per activation, after reopening the inbox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-19 22:51:09 +02:00
1 parent ca5cda81db
commit 9278ccd54e
7 files changed
+232

No files matched your search

@@ -156,6 +156,20 @@ interface DkgSessionDao {
@Query("SELECT * FROM DkgSession WHERE parentChatRoomId = :parentChatRoomId ORDER BY createdAt DESC")
suspend fun getByParentChatRoomId(parentChatRoomId: String): List<DkgSession>
/**
* Every ceremony [userPublicKey] has joined that has not finished either way,
* oldest first: what `ChillDkgRitualManager.resumeRunning` moves on.
*
* Joined, because a ceremony nobody here agreed to has nothing of this
* device's to send. Stage by name, which is how Room stores an enum.
*/
@Query(
"SELECT * FROM DkgSession WHERE userPublicKey = :userPublicKey AND " +
"hostKeyApprovedAt IS NOT NULL AND stage NOT IN ('COMPLETE', 'FAILED') " +
"ORDER BY createdAt ASC"
)
suspend fun getRunningSessionsFor(userPublicKey: HexKey): List<DkgSession>
@Upsert
suspend fun upsert(dkgSession: DkgSession)
@@ -58,6 +58,8 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mobi.giza.compose.managers.ChillDkgRitualManager
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import mobi.giza.compose.identity.Identity
/**
@@ -136,6 +138,20 @@ class DatabaseNostrRepository(
}
}
override suspend fun resumeRunningCeremonies(activeKeyPair: KeyPair): Int {
val privateKey = activeKeyPair.privKey ?: return 0
// Under the same lock as the inbound path that otherwise drives a ritual, so
// a message arriving mid-sweep is not acted on twice at once.
return storeNostrEventMutex.withLock {
ChillDkgRitualManager.resumeRunning(
database = database,
userPublicKey = activeKeyPair.pubKey.toHexKey(),
nostrPrivateKey = privateKey
)
}
}
override suspend fun createNewProfile(
publicKey: HexKey,
name: String?,
@@ -408,6 +408,48 @@ object ChillDkgRitualManager {
)
}
/**
* Moves every ceremony [userPublicKey] has joined as far as its stored messages
* allow. Returns how many it looked at.
*
* What a tap on "Contribute" used to do. [advance] runs when a message arrives,
* and until rounds 1 and 2 stopped being asked about, a member's approval was
* the other thing that ran it. Without one, a ceremony that already holds
* every message it needs and will be sent no more never moves -- which is
* exactly where an older build leaves a ceremony it was waiting to be told to
* contribute to, and where a crash between storing a message and acting on it
* leaves any ceremony.
*
* Safe to run as often as the caller likes: [advance] repeats no work, and a
* ceremony with nothing to do returns at its first missing input.
*/
suspend fun resumeRunning(
database: GizaDatabase,
userPublicKey: HexKey,
nostrPrivateKey: ByteArray
): Int {
val running = database.dkgSessionDao().getRunningSessionsFor(userPublicKey)
running.forEach { session ->
val localChatRoom = database.chatRoomDao().findChatRoomById(session.chatRoomId)
if (localChatRoom == null) {
logger.w("Ritual ${session.id} is in ${session.chatRoomId}, which is gone; not resuming it")
return@forEach
}
advance(
database = database,
localChatRoom = localChatRoom,
sessionId = session.id,
nostrPrivateKey = nostrPrivateKey
)
}
if (running.isNotEmpty()) logger.i("Resumed ${running.size} running ritual(s)")
return running.size
}
/**
* Records a proposal and answers it with this device's host key. Returns the
* session, whether it was just created or already known.
@@ -57,6 +57,14 @@ interface NostrRepository {
*/
suspend fun reopenInbox(activeKeyPair: KeyPair): Int
/**
* Moves every key ceremony [activeKeyPair] has joined as far as the messages
* already stored allow. Run once per activation, after [reopenInbox], since what
* that opens may be what a ceremony was waiting for. Returns how many it looked
* at. See docs/automatic-key-ceremony.md, Phase 3.
*/
suspend fun resumeRunningCeremonies(activeKeyPair: KeyPair): Int
suspend fun createNewProfile(
publicKey: HexKey,
name: String?,
@@ -265,6 +273,8 @@ interface NostrRepository {
override suspend fun reopenInbox(activeKeyPair: KeyPair): Int = 0
override suspend fun resumeRunningCeremonies(activeKeyPair: KeyPair): Int = 0
override suspend fun observePendingSynchronizeNostrEventRequests(ownerPublicKey: HexKey): Flow<SynchronizeNostrEventRequest?> {
TODO("Not yet implemented")
}
@@ -237,6 +237,15 @@ class SynchronizationViewModel(
runCatching { nostrRepository.reopenInbox(keyPair) }
.onSuccess { if (it > 0) logger.i { "Reopened $it gift wrap(s) that arrived while this profile was not open" } }
.onFailure { logger.e("Could not reopen the inbox", it) }
// A key ceremony moves when a message arrives, and nothing
// else moves it now that its members are not asked to.
// One that already holds what it needs -- an older build
// left it waiting on a tap, or the app died between storing
// a message and acting on it -- would sit still for good.
// After the reopen, since what that opened may be what it
// was waiting for. docs/automatic-key-ceremony.md, Phase 3.
runCatching { nostrRepository.resumeRunningCeremonies(keyPair) }
.onFailure { logger.e("Could not resume running key ceremonies", it) }
launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) }
// Runs until cancelled rather than draining a queue, but it
// belongs here for the same reason the pumps do: it needs the