package com.cottondb.voiceimport android.content.Contextimport androidx.work.Constraintsimport androidx.work.CoroutineWorkerimport androidx.work.ExistingWorkPolicyimport androidx.work.NetworkTypeimport androidx.work.OneTimeWorkRequestBuilderimport androidx.work.WorkManagerimport androidx.work.WorkerParametersimport androidx.work.workDataOfimport com.cottondb.shell.ShellApplicationimport com.cottondb.shell.Transfersimport com.cottondb.shell.core.Linesimport java.util.concurrent.CopyOnWriteArrayListimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport kotlinx.serialization.json.JsonPrimitive/** * Model downloads, run by WorkManager so they outlive the app that asked (a bound service's process is frozen as soon * as its caller unbinds: found on a Mac's emulator, 17 Nov 2026, the first file whole and the rest never begun). * One unique work per model; it waits for an unmetered network unless mobile data is allowed, stands in the * foreground while it runs, and when it is stopped it resumes from the file's `.part` on its next run. */objectModelFetch {/** Who hears each change: the binder's callers still bound, and this app's own screen. */val listeners = CopyOnWriteArrayList<(ModelState) -> Unit>()fun tell(state: ModelState) = listeners.forEach { runCatching { it(state) } }fun enqueue(context: Context, model: ModelEntry, mobileData: Boolean) {Runtime.remember(Runtime.of(context).first, model)val request = OneTimeWorkRequestBuilder<ModelFetchWorker>() .setInputData(workDataOf("model" to model.id, "mobile_data" to mobileData)) .setConstraints(Constraints.Builder().setRequiredNetworkType(if (mobileData) NetworkType.CONNECTED elseNetworkType.UNMETERED).build()) .build()WorkManager.getInstance(context).enqueueUniqueWork("voice-model-${model.id}", ExistingWorkPolicy.KEEP, request) }}classModelFetchWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {overridesuspendfun doWork(): Result {val id = inputData.getString("model") ?: returnResult.failure()val mobileData = inputData.getBoolean("mobile_data", false)val (store, _) = Runtime.of(applicationContext)val model = (Runtime.catalogue(applicationContext) + Runtime.known(store).associateBy { it.id })[id] ?: returnResult.failure()val app = applicationContext asShellApplicationval debug = app.flavour.debugval core = kotlinx.coroutines.withTimeoutOrNull(5_000) { app.connectedCore().getOrNull() }// In the foreground while it runs, as the shell's transfers are, so a large model is not stopped at ten minutes. core?.let { c -> runCatching {val name = (app.manifest["name"] as? JsonPrimitive)?.content.orEmpty() setForeground(Transfers.notice(applicationContext, Lines.of(c.obj("shell.lines"), name))) } }val end = withContext(Dispatchers.IO) {var said: Pair<String?, Long>? = null store.fetch(model, mobileData, stopped = { isStopped }) { s ->ModelFetch.tell(s)// A debug build logs each turn of a download and every 10 MB of it (the walk's proof of a resume).val step = s.why to s.bytesDone / 10_000_000if (debug && step != said) { said = step; android.util.Log.i("CottonVoice", "fetch ${s.json()}") } } } core?.let { c -> runCatching { c.obj("voice.model", end.json()) } }returnwhen { end.state == "ready" -> Result.success() end.why == "interrupted" || end.why == "offline" -> Result.retry()else -> Result.failure() } }}