translate: translator load can no longer latch into forever-loading (#842)
- Commit
6baf72bd6a5b4211fc9ba4b7c6018ccc07e22604- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 18:47 UTC (5 days ago)
- Parents
dfde2c7
The ViewModel was created before the model download gate finished and checked translator availability exactly once in init: on first run isDownloaded() was false, translationAvailable latched false forever, and the screen showed 'Loading translator...' permanently (restart fixed it — hence no-repro on devices with the model preinstalled). The same latch swallowed init failures (no Vulkan fp16, corrupt file): NllbTranslator's attempts were consumed and reset() had no production caller. New platform/TranslatorLoader: Loading only while an attempt runs, every attempt terminates in Ready or Failed, concurrent attempts coalesce, Ready is sticky. TranslateViewModel exposes the load state and loadTranslator() (init + page entry + camera/image entry), and retryTranslatorLoad() resets the native attempt latch first. TextTranslateScreen routes loading through AppScaffold isRefreshing per the scaffold contract and shows a friendly error with Retry on Failed instead of the endless label. NllbTranslator.ensure() catches Throwable so native/linkage failures read as unavailable rather than crashing. New TranslatorLoaderTest (already-downloaded, download-failure, init-failure-retry, coalescing) plus updated page tests — one existing test had encoded the stuck-loading behaviour. Verified: :translate:testDevUnitTest passes; lint errors are pre-existing RouteScreenshotCoverage findings in untouched Route.kt.
Diff
translate/AGENTS.md
diff --git a/translate/AGENTS.md b/translate/AGENTS.mdindex 7473813745..f69425e5de 100644--- a/translate/AGENTS.md+++ b/translate/AGENTS.md@@ -16,7 +16,7 @@ _Install: ./install translate (dev by default)._ - Text translation over the on-device NLLB engine (`NllbTranslator` + `NllbModel`); language catalog + recents in `domain/` - Camera mode: `CameraPreviewLayer` + `CameraOverlay` over `:library:ocr`; speech in via `SpeechRecognizerEngine`, spoken output via `TtsSpeaker` - History + persistent settings (`data/TranslateSettings`); translation available from the system selection menu-**Architecture / data-flow:** `ui/` text/camera/language pages → `platform/TranslateViewModel` (+ `TranslateUiContract`) → `domain/TranslationEngine` → `platform/NllbTranslator` on the `:library:ml` runtime; models fetched once via `:library:downloadservice` and hash-verified before first use.+**Architecture / data-flow:** `ui/` text/camera/language pages → `platform/TranslateViewModel` (+ `TranslateUiContract`) → `domain/TranslationEngine` → `platform/NllbTranslator` on the `:library:ml` runtime; models fetched once via `:library:downloadservice` and hash-verified before first use. Translator loading is a terminal state machine (`platform/TranslatorLoader` + `TranslatorLoadState`): the ViewModel is created before the download gate passes, so the text/camera/image pages re-attempt the load on entry, and every attempt ends in Ready or a Failed error with retry (Retry action / scaffold pull-to-refresh) — never an endless loading state. **Entry points + reading order:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/TextTranslateScreen.kt` → `platform/TranslateViewModel.kt` → `domain/TranslationEngine.kt` → `platform/NllbTranslator.kt`. **Gotchas:** - First run without downloaded models must degrade gracefully — never assume the NLLB weights exist@@ -35,6 +35,7 @@ _Install: ./install translate (dev by default)._ ### platform/ — ViewModel, NLLB, speech, TTS - com/vayunmathur/translate/platform/TranslateViewModel.kt - com/vayunmathur/translate/platform/TranslateUiContract.kt+- com/vayunmathur/translate/platform/TranslatorLoader.kt - com/vayunmathur/translate/platform/NllbTranslator.kt - com/vayunmathur/translate/platform/NllbModel.kt - com/vayunmathur/translate/platform/SpeechRecognizerEngine.kt
translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt b/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.ktindex 6b8c3e7607..8af65187ee 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt@@ -65,7 +65,12 @@ class NllbTranslator(private val context: Context) : TranslationEngine { } } - /** Call after a successful model download so the next use loads it. */+ /**+ * Call after a successful model download so the next use loads it. Also+ * the explicit-retry escape from the [MAX_ATTEMPTS] latch in [ensure]:+ * without a reset, two failed session creations would make every later+ * load attempt a no-op and a user retry could never succeed.+ */ suspend fun reset() = lock.withLock { attempts = 0 } /**@@ -100,7 +105,17 @@ class NllbTranslator(private val context: Context) : TranslationEngine { if (reclaimed > 0) { Log.status(TAG, "reclaimed $reclaimed bytes of retired SMaLL-100 weights") }- val handle = NllbHandle.inDirectory(NllbModel.modelDir(context))+ // inDirectory is documented never to throw, but a load failure must+ // read as "unavailable" here, not propagate and leave a caller in a+ // permanent loading state; TranslatorLoader also guards this.+ val handle = try {+ NllbHandle.inDirectory(NllbModel.modelDir(context))+ } catch (e: Throwable) {+ // Native/session failures can surface as linkage Errors, not+ // Exceptions; any of them means "unavailable", not a crash.+ Log.error(TAG, "cannot load the NLLB model", e)+ return null+ } if (!handle.isAvailable) { handle.close() return null
translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.ktindex 2af2837321..18b9cf7c5c 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt@@ -29,12 +29,23 @@ import com.vayunmathur.translate.domain.Languages */ enum class MicState { IDLE, LISTENING, TRANSCRIBING } +/**+ * Terminal-aware translator load state. Every load attempt ends in [Ready] or+ * [Failed]; [Loading] is only the in-flight state between an explicit attempt+ * (ViewModel init, text-page entry, or retry) and its outcome. There is no+ * path that stays in [Loading] without an attempt running.+ */+enum class TranslatorLoadState { Loading, Ready, Failed }+ /** Everything the text translation screen draws. */ data class TextTranslateUiState( val sourceLang: String = Languages.AUTO.code, val targetLang: String = "es",- /** False only while the NLLB engine is still loading; the model itself is pre-installed. */+ /** True only in [TranslatorLoadState.Ready]; kept for camera/image pages. */ val translationAvailable: Boolean = false,+ /** Load state behind [translationAvailable]; [Failed] shows an error with retry. */+ val translatorLoadState: TranslatorLoadState =+ if (translationAvailable) TranslatorLoadState.Ready else TranslatorLoadState.Loading, val inputText: String = "", val outputText: String = "", val isTranslating: Boolean = false,@@ -62,6 +73,9 @@ interface TextTranslateActions { fun copyOutput() {} fun speakOutput() {} fun toggleFavorite() {}++ /** Retry a failed translator load (also the scaffold pull-to-refresh action). */+ fun retryTranslatorLoad() {} fun openCamera() {} fun openImage() {} fun openHistory() {}
translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.ktindex 857f4651b3..f2d5d39892 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt@@ -34,11 +34,17 @@ sealed interface SharedImageArrival { /** * Holds the shared engines (translation, OCR, TTS) and the persisted language- * selection. The NLLB-200 model is now gated via+ * selection. The NLLB-200 model is gated via * [com.vayunmathur.library.downloadservice.InitialModelDownloadChecker] in * MainActivity — just like OpenAssistant — so it starts installing automatically- * as soon as the page is opened. By the time this screen is shown,- * [NllbModel] files are already present, and we just load the Vulkan engine.+ * as soon as the page is opened.+ *+ * This ViewModel is created before that gate finishes, so its init load+ * attempt can legitimately read "not downloaded yet" on a first run. That+ * attempt terminates in [TranslatorLoadState.Failed] (see [TranslatorLoader]),+ * and the text page re-attempts on entry — by then the gate has passed and+ * the files are present. No state waits forever for a download or a native+ * session that already failed. */ class TranslateViewModel(app: Application) : AndroidViewModel(app) { @@ -61,10 +67,40 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) { private val _recentTargetLangs = MutableStateFlow<List<String>>(emptyList()) val recentTargetLangs: StateFlow<List<String>> = _recentTargetLangs.asStateFlow() + private val translatorLoader = TranslatorLoader { translator.isAvailable() }++ /** Load state of the NLLB engine; every attempt ends Ready or Failed. */+ val translatorLoadState: StateFlow<TranslatorLoadState> = translatorLoader.state+ /** True once the NLLB engine is loaded (model already downloaded by the checker). */ private val _translationAvailable = MutableStateFlow(false) val translationAvailable: StateFlow<Boolean> = _translationAvailable.asStateFlow() + /**+ * Attempt (or re-attempt) loading the translator. Called from init, from+ * the text page on entry — the point where the download gate has passed —+ * and from retry. Concurrent calls join the attempt already in flight.+ */+ fun loadTranslator() {+ viewModelScope.launch { refreshTranslatorAvailability() }+ }++ /**+ * User retry after a failed load: clears the engine's failed-attempt+ * latch first, otherwise [NllbTranslator.ensure] would refuse to try+ * again and the retry could never reach Ready.+ */+ fun retryTranslatorLoad() {+ viewModelScope.launch {+ (translator as? NllbTranslator)?.reset()+ refreshTranslatorAvailability()+ }+ }++ private suspend fun refreshTranslatorAvailability() {+ _translationAvailable.value = translatorLoader.load()+ }+ /** Saved translations, favorites first then newest — for the history screen. */ val history: StateFlow<List<TranslationRecord>> = historyRepo.history.stateIn( viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList(),@@ -112,7 +148,7 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) { } _recentSourceLangs.value = settings.recentSources() _recentTargetLangs.value = settings.recentTargets()- _translationAvailable.value = translator.isAvailable()+ refreshTranslatorAvailability() } }
translate/src/main/java/com/vayunmathur/translate/platform/TranslatorLoader.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/TranslatorLoader.kt b/translate/src/main/java/com/vayunmathur/translate/platform/TranslatorLoader.ktnew file mode 100644index 0000000000..aaa75ca8cb--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/platform/TranslatorLoader.kt@@ -0,0 +1,83 @@+package com.vayunmathur.translate.platform++import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/**+ * The translator load state machine: [TranslatorLoadState.Loading] only while+ * an attempt is running, and every attempt terminates in+ * [TranslatorLoadState.Ready] or [TranslatorLoadState.Failed].+ *+ * This exists because the load used to be a single check in+ * `TranslateViewModel.init`: the ViewModel is created before the+ * `InitialModelDownloadChecker` gate in MainActivity finishes, so on a first+ * run (or any run where the model arrives after the ViewModel) that one check+ * read "not downloaded yet", latched `translationAvailable = false`, and+ * nothing ever checked again — the text screen then showed+ * "Loading translator…" forever, with no error and no retry. The same latch+ * wedged an engine whose native session failed to open: one failure, never+ * re-attempted.+ *+ * Callers drive attempts explicitly — ViewModel init, the text page entering+ * (i.e. the download gate having just passed), and the user's retry — so a+ * [Failed] result never auto-loops, and concurrent attempts coalesce into+ * the one already in flight instead of double-loading the model.+ */+class TranslatorLoader(private val loadAttempt: suspend () -> Boolean) {++ private val _state = MutableStateFlow(TranslatorLoadState.Loading)+ val state: StateFlow<TranslatorLoadState> = _state.asStateFlow()++ private val guard = Mutex()+ private var inFlight: CompletableDeferred<Boolean>? = null++ /**+ * Run one load attempt (or join the one already running) and return+ * whether the translator is ready. A `false` return — files still+ * missing, native session failed to open, or the attempt threw — lands+ * in [TranslatorLoadState.Failed], never back in Loading.+ */+ suspend fun load(): Boolean {+ val deferred: CompletableDeferred<Boolean>+ val owner: Boolean+ guard.withLock {+ if (_state.value == TranslatorLoadState.Ready) return true+ val existing = inFlight+ if (existing != null) {+ deferred = existing+ owner = false+ } else {+ deferred = CompletableDeferred()+ inFlight = deferred+ _state.value = TranslatorLoadState.Loading+ owner = true+ }+ }+ if (!owner) return deferred.await()++ val ready = try {+ loadAttempt()+ } catch (e: CancellationException) {+ guard.withLock { if (inFlight === deferred) inFlight = null }+ deferred.cancel()+ throw e+ } catch (e: Throwable) {+ // An engine load that throws (including native linkage Errors)+ // is an init failure, not a hang: surface it as the same+ // terminal Failed state as a false return.+ false+ }+ guard.withLock {+ _state.value =+ if (ready) TranslatorLoadState.Ready else TranslatorLoadState.Failed+ if (inFlight === deferred) inFlight = null+ }+ deferred.complete(ready)+ return ready+ }+}
translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.ktindex 489a8805b5..0b21b109c8 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt@@ -3,6 +3,7 @@ package com.vayunmathur.translate.ui import android.Manifest import androidx.camera.view.PreviewView import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource@@ -39,6 +40,7 @@ private fun CameraContent( onBack: () -> Unit, onOpenLanguagePicker: (Boolean) -> Unit, ) {+ LaunchedEffect(Unit) { viewModel.loadTranslator() } val context = LocalContext.current val previewView = remember { // The overlay maths below assumes a centre-crop preview; make that explicit
translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslatePage.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslatePage.kt b/translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslatePage.ktindex b285b439ae..942dc88d3c 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslatePage.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslatePage.kt@@ -1,6 +1,7 @@ package com.vayunmathur.translate.ui import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import com.vayunmathur.translate.platform.TranslateViewModel /**@@ -19,6 +20,8 @@ fun ImageTranslatePage( onBack: () -> Unit, onOpenLanguagePicker: (Boolean) -> Unit, ) {+ // A shared image can land here without the text page ever composing.+ LaunchedEffect(Unit) { viewModel.loadTranslator() } val pickImage = rememberImagePickerLauncher(onPicked = onReplaceImage) ImageTranslateScreen( viewModel = viewModel,
translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.ktindex cbaad5577b..5e8cf247f4 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt@@ -42,8 +42,11 @@ private const val TRANSLATE_DEBOUNCE_MS = 400L * * The NLLB-200 model is auto-installed on open via * [com.vayunmathur.library.downloadservice.InitialModelDownloadChecker] in MainActivity- * (like OpenAssistant), so this screen never needs to show a manual Download button. By the- * time we get here the files are on disk and [TranslateViewModel] has loaded the engine.+ * (like OpenAssistant), so this screen never needs to show a manual Download button.+ * The ViewModel predates that gate, so its init attempt may already have+ * failed on a first run; entering this page re-attempts the load (below),+ * which is what turns a finished download into a ready translator without+ * an app restart. */ @Composable fun TextTranslatePage(@@ -62,8 +65,15 @@ fun TextTranslatePage( val sourceLang by viewModel.sourceLang.collectAsState() val targetLang by viewModel.targetLang.collectAsState() val translationAvailable by viewModel.translationAvailable.collectAsState()+ val translatorLoadState by viewModel.translatorLoadState.collectAsState() val history by viewModel.history.collectAsState() + // Re-attempt on entry: this page only composes after the model-download+ // gate has passed, while the ViewModel's init attempt ran before it.+ // Keyed on Unit so a Failed result does not auto-loop; the retry action+ // and scaffold pull-to-refresh are the explicit re-attempts after that.+ LaunchedEffect(Unit) { viewModel.loadTranslator() }+ var inputText by remember { mutableStateOf(initialText) } var outputText by remember { mutableStateOf("") } var isTranslating by remember { mutableStateOf(false) }@@ -155,6 +165,7 @@ fun TextTranslatePage( sourceLang = sourceLang, targetLang = targetLang, translationAvailable = translationAvailable,+ translatorLoadState = translatorLoadState, inputText = inputText, outputText = outputText, isTranslating = isTranslating,@@ -179,6 +190,8 @@ fun TextTranslatePage( inputText = text } + override fun retryTranslatorLoad() = viewModel.retryTranslatorLoad()+ // Idle → start. Listening → end capture; the recognizer still delivers its last // result via onFinal, it does not cancel. Transcribing → busy finishing. override fun toggleMic() {
translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.ktindex d299a2a21f..0df3511687 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt@@ -42,6 +42,7 @@ import com.vayunmathur.translate.domain.Languages import com.vayunmathur.translate.platform.MicState import com.vayunmathur.translate.platform.TextTranslateActions import com.vayunmathur.translate.platform.TextTranslateUiState+import com.vayunmathur.translate.platform.TranslatorLoadState /** * The text translation screen, with no dependency on the ViewModel so it can be rendered@@ -52,6 +53,11 @@ import com.vayunmathur.translate.platform.TextTranslateUiState fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActions) { AppScaffold( title = stringResource(R.string.app_name),+ // Loading indication goes through the scaffold pull-to-refresh+ // contract, never a standalone spinner; pulling (or the Retry+ // action in the output card) re-attempts a failed load.+ isRefreshing = state.translatorLoadState == TranslatorLoadState.Loading,+ onRefresh = actions::retryTranslatorLoad, actions = { IconButton(onClick = actions::openHistory) { IconHistory()@@ -123,6 +129,8 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio verticalArrangement = Arrangement.spacedBy(12.dp), ) { OutputCard(+ translatorLoadState = state.translatorLoadState,+ onRetryTranslatorLoad = actions::retryTranslatorLoad, translationAvailable = state.translationAvailable, isTranslating = state.isTranslating, outputText = state.outputText,@@ -143,6 +151,8 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio ) OutputCard(+ translatorLoadState = state.translatorLoadState,+ onRetryTranslatorLoad = actions::retryTranslatorLoad, translationAvailable = state.translationAvailable, isTranslating = state.isTranslating, outputText = state.outputText,@@ -230,6 +240,8 @@ private fun LanguageBar( @Composable private fun OutputCard(+ translatorLoadState: TranslatorLoadState,+ onRetryTranslatorLoad: () -> Unit, translationAvailable: Boolean, isTranslating: Boolean, outputText: String,@@ -247,12 +259,23 @@ private fun OutputCard( verticalArrangement = Arrangement.spacedBy(12.dp), ) { if (!translationAvailable) {- // Should never happen — the outer InitialModelDownloadChecker- // downloads the model before any Navigation is composed, and- // TranslateViewModel loads the engine on init. Show a loading- // spinner if the engine is still initializing.- Row(verticalAlignment = Alignment.CenterVertically) {- Text(stringResource(R.string.loading_translator), color = MaterialTheme.colorScheme.onSurfaceVariant)+ // Loading is transient (an attempt is running; the scaffold+ // shows its pull-to-refresh indicator). Failed is terminal:+ // a visible error with retry, never an endless loading label.+ // This branch is reachable — the ViewModel is created before+ // the download gate passes, and a native session can fail.+ if (translatorLoadState == TranslatorLoadState.Failed) {+ Text(+ stringResource(R.string.translator_load_failed),+ color = MaterialTheme.colorScheme.error,+ )+ TextButton(onClick = onRetryTranslatorLoad) {+ Text(stringResource(R.string.retry_translator_load))+ }+ } else {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(stringResource(R.string.loading_translator), color = MaterialTheme.colorScheme.onSurfaceVariant)+ } } return@Column }
translate/src/main/res/values/strings.xml
diff --git a/translate/src/main/res/values/strings.xml b/translate/src/main/res/values/strings.xmlindex aa6024c220..81d9837176 100644--- a/translate/src/main/res/values/strings.xml+++ b/translate/src/main/res/values/strings.xml@@ -3,6 +3,9 @@ <string name="app_name">Translate</string> <string name="enter_text">Enter text</string> <string name="loading_translator">Loading translator…</string>+ <!-- Error in the translation output card when the on-device translator failed to load (model missing or native session failed); shown with a retry action. -->+ <string name="translator_load_failed">Couldn’t load the translator. The model may not be downloaded yet, or it failed to start on this device.</string>+ <string name="retry_translator_load">Retry</string> <string name="copy">Copy</string> <string name="speak">Speak</string> <string name="translation">Translation</string>
translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.kt b/translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.ktindex e6b1c2b651..2008f4b53e 100644--- a/translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.kt+++ b/translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.kt@@ -42,6 +42,32 @@ class PlatformEnginesTest { assertNull(translator.translate("hello", "en", "es")) } + @Test+ fun `nllb translator with present but invalid files fails terminally and reset re-attempts`() =+ runBlocking {+ // Model files present (already-downloaded path) but not a loadable+ // model: session init must fail closed, and an explicit reset —+ // what the retry action calls — must allow a fresh attempt rather+ // than leaving the attempt latch permanently closed (#842).+ val root = context.getExternalFilesDir(null)+ assertNotNull(root)+ for (item in NllbModel.FILES) {+ val f = File(root, item.fileName)+ f.parentFile?.mkdirs()+ if (!f.exists()) f.writeBytes(byteArrayOf(1))+ }+ assertTrue(NllbModel.isDownloaded(context))+ val translator = NllbTranslator(context)+ assertFalse(translator.isAvailable())+ assertFalse(translator.isAvailable())+ assertFalse(translator.isAvailable())+ translator.reset()+ assertFalse(translator.isAvailable())+ assertNull(translator.translate("hello", "en", "es"))+ translator.close()+ for (item in NllbModel.FILES) File(root, item.fileName).delete()+ }+ @Test fun `madlad translator without downloads is unavailable and fails closed`() = runBlocking { val translator = MadladTranslator(context)
translate/src/test/java/com/vayunmathur/translate/platform/TranslatorLoaderTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/platform/TranslatorLoaderTest.kt b/translate/src/test/java/com/vayunmathur/translate/platform/TranslatorLoaderTest.ktnew file mode 100644index 0000000000..f7bacb90de--- /dev/null+++ b/translate/src/test/java/com/vayunmathur/translate/platform/TranslatorLoaderTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.translate.platform++import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Regression tests for #842: every translator load path must terminate in+ * Ready or Failed, never sit in Loading forever.+ */+class TranslatorLoaderTest {++ @Test+ fun `already downloaded path - init attempt before download then page entry attempt reaches ready`() =+ runBlocking {+ // Init runs before the download gate: files absent, attempt fails.+ // By page entry the files are present, so the next attempt succeeds.+ var filesPresent = false+ var attempts = 0+ val loader = TranslatorLoader {+ attempts+++ filesPresent+ }+ assertFalse(loader.load())+ assertEquals(TranslatorLoadState.Failed, loader.state.value)++ filesPresent = true+ assertTrue(loader.load())+ assertEquals(TranslatorLoadState.Ready, loader.state.value)+ assertEquals(2, attempts)++ // Once ready, further attempts are no-ops.+ assertTrue(loader.load())+ assertEquals(2, attempts)+ }++ @Test+ fun `download failure path - missing model terminates in failed not loading`() = runBlocking {+ val loader = TranslatorLoader { false }+ assertFalse(loader.load())+ assertEquals(TranslatorLoadState.Failed, loader.state.value)+ // An explicit retry also terminates (still Failed while missing).+ assertFalse(loader.load())+ assertEquals(TranslatorLoadState.Failed, loader.state.value)+ }++ @Test+ fun `init failure path - throwing load terminates in failed and retry can reach ready`() =+ runBlocking {+ var shouldThrow = true+ val loader = TranslatorLoader {+ if (shouldThrow) throw IllegalStateException("native session failed")+ true+ }+ assertFalse(loader.load())+ assertEquals(TranslatorLoadState.Failed, loader.state.value)++ shouldThrow = false+ assertTrue(loader.load())+ assertEquals(TranslatorLoadState.Ready, loader.state.value)+ }++ @Test+ fun `concurrent loads coalesce into one attempt`() = runBlocking {+ var attempts = 0+ val loader = TranslatorLoader {+ attempts+++ delay(50)+ true+ }+ val results = listOf(async { loader.load() }, async { loader.load() }).awaitAll()+ assertTrue(results.all { it })+ assertEquals(1, attempts)+ assertEquals(TranslatorLoadState.Ready, loader.state.value)+ }+}
translate/src/test/java/com/vayunmathur/translate/platform/ViewModelAndPagesTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/platform/ViewModelAndPagesTest.kt b/translate/src/test/java/com/vayunmathur/translate/platform/ViewModelAndPagesTest.ktindex 111359db88..c4dd8a05aa 100644--- a/translate/src/test/java/com/vayunmathur/translate/platform/ViewModelAndPagesTest.kt+++ b/translate/src/test/java/com/vayunmathur/translate/platform/ViewModelAndPagesTest.kt@@ -146,6 +146,43 @@ class ViewModelAndPagesTest { assertFalse(viewModel.translationAvailable.value) } + @Test+ fun `viewmodel translator load terminates in failed without model and retry stays terminal`() {+ // #842: with no model downloaded the init attempt must land in Failed+ // (visible error + retry on screen), never linger in Loading.+ val viewModel = vm()+ waitForLoadTerminal(viewModel)+ assertEquals(+ com.vayunmathur.translate.platform.TranslatorLoadState.Failed,+ viewModel.translatorLoadState.value,+ )+ assertFalse(viewModel.translationAvailable.value)+ viewModel.retryTranslatorLoad()+ waitForLoadTerminal(viewModel)+ assertEquals(+ com.vayunmathur.translate.platform.TranslatorLoadState.Failed,+ viewModel.translatorLoadState.value,+ )+ viewModel.loadTranslator()+ waitForLoadTerminal(viewModel)+ assertEquals(+ com.vayunmathur.translate.platform.TranslatorLoadState.Failed,+ viewModel.translatorLoadState.value,+ )+ }++ private fun waitForLoadTerminal(viewModel: TranslateViewModel) {+ repeat(200) {+ if (viewModel.translatorLoadState.value !=+ com.vayunmathur.translate.platform.TranslatorLoadState.Loading+ ) {+ return+ }+ idle()+ Thread.sleep(10)+ }+ }+ @Test fun `viewmodel speak and stop delegate to tts safely`() { val viewModel = vm()
translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.kt b/translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.ktindex 3766250e76..b8e741bcdd 100644--- a/translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.kt+++ b/translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.kt@@ -105,8 +105,13 @@ class DbBackedPagesTest { ) } rule.onNodeWithText("good morning").assertIsDisplayed()- // No model files in this sandbox: the loading state is the honest output.- rule.onNodeWithText("Loading translator…").assertIsDisplayed()+ // No model files in this sandbox: the failed-load state with retry+ // is the terminal honest output (#842), not an endless loading label.+ rule.waitUntil(8_000) {+ rule.onAllNodesWithText("Couldn’t load the translator. The model may not be downloaded yet, or it failed to start on this device.")+ .fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Couldn’t load the translator. The model may not be downloaded yet, or it failed to start on this device.").assertIsDisplayed() rule.onNodeWithContentDescription("History").performClick() assertEquals(1, history) rule.onNodeWithContentDescription("Camera").performClick()@@ -141,7 +146,7 @@ class DbBackedPagesTest { rule.waitForIdle() assertTrue( rule.onAllNodesWithText("Translation will appear here").fetchSemanticsNodes().isNotEmpty() ||- rule.onAllNodesWithText("Loading translator…").fetchSemanticsNodes().isNotEmpty(),+ rule.onAllNodesWithText("Couldn’t load the translator. The model may not be downloaded yet, or it failed to start on this device.").fetchSemanticsNodes().isNotEmpty(), ) } @@ -184,10 +189,10 @@ class DbBackedPagesTest { assertEquals("en", viewModel.sourceLang.value) assertEquals("es", viewModel.targetLang.value) rule.onNodeWithText("reuse hello").assertIsDisplayed()- // Without the model the output card stays in its loading state; the- // star/copy wiring for a landed translation is covered on the+ // Without the model the output card reaches its failed-load state;+ // the star/copy wiring for a landed translation is covered on the // stateless screen (TranslateScreensTest) and needs a real model here.- rule.onNodeWithText("Loading translator…").assertIsDisplayed()+ rule.onNodeWithText("Couldn’t load the translator. The model may not be downloaded yet, or it failed to start on this device.").assertIsDisplayed() } @Test
translate/src/test/java/com/vayunmathur/translate/ui/TranslateScreensTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/ui/TranslateScreensTest.kt b/translate/src/test/java/com/vayunmathur/translate/ui/TranslateScreensTest.ktindex a43b15440c..95af8de385 100644--- a/translate/src/test/java/com/vayunmathur/translate/ui/TranslateScreensTest.kt+++ b/translate/src/test/java/com/vayunmathur/translate/ui/TranslateScreensTest.kt@@ -32,6 +32,8 @@ class TranslateScreensTest { private class RecText : TextTranslateActions { var sourcePicker = 0; var targetPicker = 0; var swap = 0; var mic = 0 var copy = 0; var speak = 0; var fav = 0; var camera = 0; var image = 0; var history = 0+ var retryLoad = 0+ override fun retryTranslatorLoad() { retryLoad++ } var typed: String? = null; var src: String? = null; var tgt: String? = null override fun setSource(code: String) { src = code } override fun setTarget(code: String) { tgt = code }@@ -62,6 +64,26 @@ class TranslateScreensTest { rule.onNodeWithText(Languages.displayName("es")).assertIsDisplayed() } + @Test+ fun `text screen failed load shows error with retry instead of loading`() {+ // #842 regression: a failed load is terminal and retryable, not a spinner.+ val actions = RecText()+ rule.setContent {+ TextTranslateScreen(+ TextTranslateUiState(+ translationAvailable = false,+ translatorLoadState = com.vayunmathur.translate.platform.TranslatorLoadState.Failed,+ sourceLang = "auto", targetLang = "es",+ ),+ actions,+ )+ }+ rule.onNodeWithText("Couldn’t load the translator. The model may not be downloaded yet, or it failed to start on this device.").assertIsDisplayed()+ rule.onNodeWithText("Retry").performClick()+ assertEquals(1, actions.retryLoad)+ assertTrue(rule.onAllNodesWithText("Loading translator…").fetchSemanticsNodes().isEmpty())+ }+ @Test fun `text screen with output enables copy speak and save`() { val actions = RecText()