package com.cottondb.android import android.content.Context import com.cottondb.android.passwords.* import com.cottondb.android.platform.AndroidSensitiveClipboard import com.cottondb.android.platform.SensitiveClipboardIssue import com.cottondb.android.boot.BootModel import com.cottondb.android.boot.BootState import com.cottondb.android.boot.DeviceResetModel import com.cottondb.android.boot.DeviceResetPlatform import com.cottondb.android.boot.DeviceResetState import com.cottondb.android.platform.ScheduledNotifications import com.cottondb.android.platform.VaultKeyring import com.cottondb.android.boot.JoinModel import com.cottondb.android.boot.SyncModel import com.cottondb.android.core.CottonCore import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.home.HomeModel import com.cottondb.android.identity.DeviceIdentity import com.cottondb.android.identity.DeviceKeyResolution import com.cottondb.android.media.CoreMediaSource import com.cottondb.android.media.TrustedMediaRoots import java.io.File import com.cottondb.android.platform.DeviceKeyStore import com.cottondb.android.platform.SecureDeviceSeedRandom import com.cottondb.android.platform.AndroidVaultPublicKeyProvider import com.cottondb.android.platform.CoreVaultPublicKeyPublisher import com.cottondb.android.platform.VaultPublication import com.cottondb.android.platform.VaultPublicationState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.first import kotlinx.coroutines.withTimeout import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import java.util.TimeZone sealed interface RuntimeState { data object Opening : RuntimeState data class Ready( val boot: BootModel, val join: JoinModel, val home: HomeModel, val sync: SyncModel, val vault: VaultPublication, val vaultSession: VaultSession, val reset: DeviceResetModel, val features: FeatureModels, val notifications: ScheduledNotifications, ) : RuntimeState data class Error(val message: String) : RuntimeState } /** * The process-wide owner of the one native handle and its one subscription. * UI models receive copied [CottonEvent]s here; none may subscribe independently. */ class AppRuntime(private val context: Context) { // Models mutate UI state and their generations on this serial dispatcher; native calls // immediately leave it for CottonCore's own bounded worker pool. private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val _state = MutableStateFlow(RuntimeState.Opening) val state: StateFlow = _state.asStateFlow() private val _eventError = MutableStateFlow(null) val eventError: StateFlow = _eventError.asStateFlow() private val channelScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val keyboardChannel by lazy { com.cottondb.android.keyboard.AndroidKeyboardChannelStore.open(context, channelScope) } private var sessionScope: CoroutineScope? = null private var opening = false @Volatile private var wantsForeground = false private var core: CottonCore? = null private var joinPreflight: Job? = null private val clipboard = AndroidSensitiveClipboard(context, scope) private val searchRecents = com.cottondb.android.platform.AndroidSearchRecentsStore(context) private val importStager = com.cottondb.android.ui.traffic.messages.AndroidWhatsAppExportStager(context) private val documentStager = com.cottondb.android.ui.imports.AndroidSafFileStager(context, "documents-imports", "document") fun open() { if (opening || core != null) return opening = true _state.value = RuntimeState.Opening scope.launch { try { openSession() } catch (failure: CancellationException) { throw failure } catch (failure: Throwable) { _state.value = RuntimeState.Error(failure.message ?: "Cotton could not open on this phone.") } finally { opening = false } } } private suspend fun openSession() { // No native import survives process death. A reset closes the previous core (including // in-flight calls) before returning here, so no live import owns these old copies. importStager.cleanupOrphanedExports() documentStager.cleanupOrphans() com.cottondb.android.ui.work.meetings.meetingsImportStager(context).cleanupOrphans() val identity = withContext(Dispatchers.IO) { DeviceIdentity.loadOrCreate(DeviceKeyStore(context), SecureDeviceSeedRandom()) } val secret = when (identity) { is DeviceKeyResolution.Available -> identity.deviceSecret is DeviceKeyResolution.Refused -> throw IllegalStateException(identityMessage(identity)) } val opened = CottonCore.open(openConfig(secret)) val models = CoroutineScope(scope.coroutineContext + SupervisorJob(scope.coroutineContext[Job])) try { lateinit var boot: BootModel val keyboard = com.cottondb.android.keyboard.KeyboardModel(opened, keyboardChannel, models, java.time.Clock.systemUTC()) { java.util.UUID.randomUUID().toString() } val notifications = ScheduledNotifications(context, opened, models, ::reportPlatformError) val home = HomeModel(opened, models) val sync = SyncModel(opened, models, onStatusChanged = home::refresh) val vault = VaultPublication( AndroidVaultPublicKeyProvider(context), CoreVaultPublicKeyPublisher(opened), ) val vaultAccess = VaultAccess(opened) val vaultSession = VaultSession(vaultAccess, VaultOperations(vaultAccess, VaultKeyRepublisher { check(vault.publishIfAvailable()) { "The password key could not be shared." } }), models, ::reportPlatformError) val join = JoinModel(opened, models, onJoined = { boot.refresh() }) boot = BootModel( opened, models, onSyncFinished = sync::refresh, onReady = { notifications.request() (boot.state.value as? BootState.Ready)?.boot?.workspaceId?.let(keyboard::foreground) models.launch { vault.publishIfAvailable() } }, ) val mediaRoots = withContext(Dispatchers.IO) { TrustedMediaRoots(listOf( File(context.noBackupFilesDir, "client/media"), File(context.noBackupFilesDir, "cache/thumbs"), )) } val clock = java.time.Clock.systemDefaultZone() val passwords = PasswordModels(opened, models, clock, vaultSession) { clipboard.copy(it) } val features = FeatureModels(opened, clock, models, CoreMediaSource(opened, mediaRoots), importStager, passwords, searchRecents, documentStager, keyboard) val reset = DeviceResetModel(scope, object : DeviceResetPlatform { override suspend fun beforeLeaving() { // Retire reads, join polling and event consumers before removing this replica. // Android has no push registration yet; its cleanup belongs here when added. features.pauseCapture(); features.takes.retain(emptySet()) features.retireMeetings() keyboard.retire() vaultSession.retire().await() clipboard.clear() notifications.retire() models.cancel() } override suspend fun forgetDeviceKey() { // Retire the handle holding the old signing secret even // if a later platform deletion fails and leaves the reset on its retry screen. withContext(NonCancellable) { opened.close() } if (core === opened) core = null sessionScope = null withContext(Dispatchers.IO) { DeviceKeyStore(context).forget() searchRecents.save(emptyList()) } } override suspend fun forgetVaultKey() = withContext(Dispatchers.IO) { VaultKeyring(context).forget() } override suspend fun reopen() = reopenSession(opened) }, refreshBoot = { reopenSession(opened) }) core = opened sessionScope = models _eventError.value = null _state.value = RuntimeState.Ready(boot, join, home, sync, vault, vaultSession, reset, features, notifications) models.launch { opened.events.collect { event -> boot.handleEvent(event) join.handleEvent(event) sync.handleEvent(event) home.handleEvent(event) features.handleEvent(event) if (boot.state.value is BootState.Ready) notifications.request() } } models.launch { opened.eventErrors.collect(::noteEventError) } boot.start() sync.refresh() if (wantsForeground) { vaultSession.foreground(); boot.foregroundSync() } } catch (failure: Throwable) { models.cancel() if (core === opened) { core = null sessionScope = null } withContext(NonCancellable) { opened.close() } throw failure } } private suspend fun reopenSession(previous: CottonCore) { // A native handle holds its original signing secret. Close it before reading or minting // the platform identity again; leaving preserves the key, erasing deliberately replaces it. (state.value as? RuntimeState.Ready)?.let { ready -> ready.features.pauseCapture(); ready.features.takes.retain(emptySet()) ready.features.retireMeetings() ready.features.keyboard?.retire() ready.vaultSession.retire().await() } sessionScope?.cancel() sessionScope = null joinPreflight = null previous.close() core = null openSession() } private fun activeBoot(): BootModel? = (state.value as? RuntimeState.Ready)?.let { if (it.reset.state.value == DeviceResetState.Idle) it.boot else null } fun foreground() { wantsForeground = true (state.value as? RuntimeState.Ready)?.let { if (it.reset.state.value == DeviceResetState.Idle) it.vaultSession.foreground() } if (clipboard.issue.value == SensitiveClipboardIssue.ClearFailed) clipboard.clear() activeBoot()?.foregroundSync() retryVaultPublication() (state.value as? RuntimeState.Ready)?.let { ready -> if (ready.reset.state.value == DeviceResetState.Idle && ready.boot.state.value is BootState.Ready) { ready.notifications.request() (ready.boot.state.value as? BootState.Ready)?.boot?.workspaceId?.let { ready.features.keyboard?.foreground(it) } } } } /** A transient publication failure retries when the person returns or asks Passwords to retry. */ fun retryVaultPublication() { val ready = state.value as? RuntimeState.Ready ?: return if (ready.reset.state.value != DeviceResetState.Idle || ready.boot.state.value !is BootState.Ready) return if (ready.vault.state.value == VaultPublicationState.Published) return sessionScope?.launch { ready.vault.publishIfAvailable() } } fun background() { wantsForeground = false (state.value as? RuntimeState.Ready)?.let { ready -> if (ready.reset.state.value == DeviceResetState.Idle) { ready.vaultSession.background() ready.features.flushNotes() ready.features.flushGoals() ready.features.pauseCapture() ready.features.takes.onAppBackgrounded() } } activeBoot()?.backgroundSync() } /** Joins without a biometric prompt; any optional vault-key failure stays in VaultPublication.state. */ fun startJoin(server: String, name: String, appVersion: String) { if (joinPreflight?.isActive == true) return val ready = state.value as? RuntimeState.Ready ?: return val models = sessionScope ?: return joinPreflight = models.launch { val publicKey = ready.vault.keyForJoin() if ((state.value as? RuntimeState.Ready) === ready) { ready.join.start(server, name, appVersion, publicKey) } } } fun cancelJoin() { joinPreflight?.cancel() joinPreflight = null (state.value as? RuntimeState.Ready)?.join?.cancel() } /** Until a route is ported, its refusal is visible rather than a dead tap. */ fun unavailable(action: String) { _eventError.value = "$action is not available in this Android build yet." } fun close() { val opened = core core = null val closingFeatures = (state.value as? RuntimeState.Ready)?.features val retiring = (state.value as? RuntimeState.Ready)?.let { it.features.pauseCapture(); it.features.takes.retain(emptySet()) it.vaultSession.retire() } clipboard.clear() sessionScope?.cancel() sessionScope = null joinPreflight = null if (opened != null) scope.launch(NonCancellable) { try { closingFeatures?.retireMeetings(); retiring?.await() } finally { opened.close() } } scope.cancel() } fun reportPlatformError(message: String) { _eventError.value = message } /** A system job waits for the process-owned handle; it never opens a second core. */ suspend fun reconcileScheduledNotifications() = withTimeout(120_000L) { val current = state.first { it !is RuntimeState.Opening } if (current is RuntimeState.Error) error(current.message) val ready = current as RuntimeState.Ready check(ready.reset.state.value == DeviceResetState.Idle) { "This database is closing." } when (val boot = ready.boot.state.first { it is BootState.Ready || it is BootState.Start || it is BootState.Refused || it is BootState.Error }) { is BootState.Ready -> ready.notifications.reconcile() is BootState.Error -> error(boot.message) else -> ready.notifications.clearPlatform() } } private fun noteEventError(error: MalformedCoreEventException) { _eventError.value = error.message } private fun openConfig(deviceSecret: String) = buildJsonObject { // The replica belongs under Android's no-backup directory; media and database bytes // remain local to this device rather than entering the platform backup service. put("containerPath", context.noBackupFilesDir.absolutePath) put("appVersion", BuildConfig.VERSION_NAME) put("timeZone", TimeZone.getDefault().id) put("deviceSecret", deviceSecret) } private fun identityMessage(refusal: DeviceKeyResolution.Refused): String = when (refusal.reason) { com.cottondb.android.identity.DeviceKeyRefusal.SlotUnreadable -> "This phone's device identity cannot be opened." com.cottondb.android.identity.DeviceKeyRefusal.WrappingKeyWithoutSlot -> "This phone's device identity is incomplete and cannot be replaced safely." com.cottondb.android.identity.DeviceKeyRefusal.StorageFailure -> "This phone's device identity could not be stored." com.cottondb.android.identity.DeviceKeyRefusal.RandomUnavailable -> "This phone could not create a device identity." } }