package com.cottondb.voice import android.content.Context import androidx.work.Constraints import androidx.work.CoroutineWorker import androidx.work.ExistingWorkPolicy import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import androidx.work.workDataOf import com.cottondb.shell.ShellApplication import com.cottondb.shell.Transfers import com.cottondb.shell.core.Lines import java.util.concurrent.CopyOnWriteArrayList import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import 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. */ object ModelFetch { /** 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() .setInputData(workDataOf("model" to model.id, "mobile_data" to mobileData)) .setConstraints(Constraints.Builder().setRequiredNetworkType(if (mobileData) NetworkType.CONNECTED else NetworkType.UNMETERED).build()) .build() WorkManager.getInstance(context).enqueueUniqueWork("voice-model-${model.id}", ExistingWorkPolicy.KEEP, request) } } class ModelFetchWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) { override suspend fun doWork(): Result { val id = inputData.getString("model") ?: return Result.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] ?: return Result.failure() val app = applicationContext as ShellApplication val debug = app.flavour.debug val 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? = 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_000 if (debug && step != said) { said = step; android.util.Log.i("CottonVoice", "fetch ${s.json()}") } } } core?.let { c -> runCatching { c.obj("voice.model", end.json()) } } return when { end.state == "ready" -> Result.success() end.why == "interrupted" || end.why == "offline" -> Result.retry() else -> Result.failure() } } }