Modern Apps git

← Modern-Apps.git

translate: surface terminal translator load failure with retry (#842)

Commit
197deb2fe4c3be1c8dae86fe35c2291bcd97f009
Author
Vayun Mathur <[email protected]>
When
2026-11-05 18:59 UTC (1 month ago)
Parents
9ec7d53
After a fresh install the model download completes, but the translate
page spins on 'loading translator...' forever and camera claims the
model is not installed. The downloader and loader agree on every
path (nllb600/nllb600.maml + tokenizer.bin under getExternalFilesDir;
no zip step; single-source-of-truth names from NllbHandle; arm64 .so
ships), so the defect is load-side: on a device whose Vulkan driver
lacks shaderFloat16/storageBuffer16BitAccess (optional at the 1.1
floor) createNllb returns 0, NllbTranslator burns its two attempts at
ViewModel init, and translationAvailable stays false with reset()
never called — indistinguishable from still-loading.

Latch the terminal failure (NllbTranslator.loadFailed), expose it via
TranslateViewModel.translationLoadFailed, and show a 'couldn't load
the translator' error with a Retry action on the text, camera, and
image screens instead of the endless spinner. Retry clears the latch
via the previously-dead reset() path.

Shared note for openassistant #901: both apps' engines expose only a
boolean, so a native load failure is indistinguishable from files not
downloaded yet; kept changes translate-scoped per the brief.

Verified with :translate:compileDevKotlin and :translate:lint (both
green). Needs on-device testing on a non-fp16 device to confirm the
error state appears.

Diff

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 090983cf13..aa4bdcc813 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt@@ -37,11 +37,20 @@ class NllbTranslator(private val context: Context) : TranslationEngine {     private var model: NllbHandle? = null     private var attempts = 0     private var closed = false+    private var failed = false      override suspend fun isAvailable(): Boolean = withContext(Dispatchers.Default) {         lock.withLock { ensure() != null }     } +    /**+     * True once [ensure] has failed terminally (missing native library, no fp16+     * Vulkan device, corrupt weights). Distinct from "still loading": when the+     * engine is only warming up this is false, so the UI can show a spinner in+     * one case and a retryable error in the other instead of spinning forever.+     */+    suspend fun loadFailed(): Boolean = lock.withLock { failed && model == null }+     override suspend fun detectLanguage(text: String): String? = null      // Broad catch is deliberate: the native translator throws undocumented@@ -66,7 +75,10 @@ class NllbTranslator(private val context: Context) : TranslationEngine {         }      /** Call after a successful model download so the next use loads it. */-    suspend fun reset() = lock.withLock { attempts = 0 }+    suspend fun reset() = lock.withLock {+        attempts = 0+        failed = false+    }      /**      * Free the model. Terminal: nothing loads again afterwards, and it is idempotent.@@ -93,7 +105,13 @@ class NllbTranslator(private val context: Context) : TranslationEngine {      */     private fun ensure(): NllbHandle? {         model?.let { return it }-        if (closed || attempts >= MAX_ATTEMPTS) return null+        if (closed || attempts >= MAX_ATTEMPTS) {+            // Both attempts failed, or the translator was already attempted and+            // closed: this is a terminal load failure, not a download still in+            // flight. Latch it so the UI can say so instead of spinning forever.+            failed = attempts >= MAX_ATTEMPTS+            return null+        }         if (!NllbModel.isDownloaded(context)) return null         attempts++         val reclaimed = NllbModel.deleteRetired(context)@@ -103,6 +121,7 @@ class NllbTranslator(private val context: Context) : TranslationEngine {         val handle = NllbHandle.inDirectory(NllbModel.modelDir(context))         if (!handle.isAvailable) {             handle.close()+            if (attempts >= MAX_ATTEMPTS) failed = true             return null         }         model = handle
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 2bccbd8aaf..1c2f94fd59 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateUiContract.kt@@ -35,6 +35,8 @@ data class TextTranslateUiState(     val targetLang: String = "es",     /** False only while the NLLB engine is still loading; the model itself is pre-installed. */     val translationAvailable: Boolean = false,+    /** True once loading the engine has failed terminally; pairs with a Retry action. */+    val translationLoadFailed: Boolean = false,     val inputText: String = "",     val outputText: String = "",     val isTranslating: Boolean = false,@@ -59,6 +61,9 @@ interface TextTranslateActions {     /** The mic FAB: start listening, stop, or — while transcribing — nothing. */     fun toggleMic() {} +    /** Retry loading the translation engine after a terminal load failure. */+    fun retryTranslator() {}+     fun copyOutput() {}     fun speakOutput() {}     fun toggleFavorite() {}
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 dd76ebbcc8..8c2cb4b9b7 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt@@ -50,6 +50,15 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) {     private val _translationAvailable = MutableStateFlow(false)     val translationAvailable: StateFlow<Boolean> = _translationAvailable.asStateFlow() +    /**+     * True once loading the engine has failed terminally (missing native+     * library, no fp16 Vulkan device, corrupt weights) rather than merely not+     * yet finished. The text screen shows a retryable error in that case+     * instead of an endless "loading" spinner.+     */+    private val _translationLoadFailed = MutableStateFlow(false)+    val translationLoadFailed: StateFlow<Boolean> = _translationLoadFailed.asStateFlow()+     /** Saved translations, favorites first then newest — for the history screen. */     val history: StateFlow<List<TranslationRecord>> = historyRepo.history.stateIn(         viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList(),@@ -66,7 +75,26 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) {             _targetLang.value = settings.target()             _recentSourceLangs.value = settings.recentSources()             _recentTargetLangs.value = settings.recentTargets()-            _translationAvailable.value = translator.isAvailable()+            refreshTranslatorState()+        }+    }++    /** Re-read the engine state after init or a manual retry. */+    private suspend fun refreshTranslatorState() {+        _translationAvailable.value = translator.isAvailable()+        _translationLoadFailed.value =+            !_translationAvailable.value && (translator as? NllbTranslator)?.loadFailed() == true+    }++    /**+     * Retry loading the translation engine after a terminal load failure.+     * Clears the attempt latch so [refreshTranslatorState] gets a fresh answer.+     */+    fun retryTranslator() {+        viewModelScope.launch {+            (translator as? NllbTranslator)?.reset()+            _translationLoadFailed.value = false+            refreshTranslatorState()         }     } 
translate/src/main/java/com/vayunmathur/translate/ui/CameraOverlay.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/CameraOverlay.kt b/translate/src/main/java/com/vayunmathur/translate/ui/CameraOverlay.ktindex ad5d67f52f..20d6a1322b 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/CameraOverlay.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/CameraOverlay.kt@@ -52,6 +52,8 @@ internal fun CameraOverlay(     overlays: List<OverlayBox>,     translations: Map<String, String>,     translationAvailable: Boolean,+    translationLoadFailed: Boolean = false,+    onRetryTranslator: () -> Unit = {},     frameW: Int,     frameH: Int,     viewW: Int,@@ -81,15 +83,31 @@ internal fun CameraOverlay(     }      if (!translationAvailable) {-        Text(-            text = stringResource(R.string.translation_model_not_installed_showing),-            color = Color.White,-            modifier = Modifier-                .statusBarsPadding()-                .padding(top = 12.dp)-                .background(Color(0xB3000000), RoundedCornerShape(12.dp))-                .padding(horizontal = 12.dp, vertical = 6.dp),-        )+        // A terminal engine failure says so (rather than blaming the install+        // the download screen just finished); tap retries the load.+        if (translationLoadFailed) {+            TextButton(onClick = onRetryTranslator) {+                Text(+                    text = stringResource(R.string.translation_failed_to_load),+                    color = Color.White,+                    modifier = Modifier+                        .statusBarsPadding()+                        .padding(top = 12.dp)+                        .background(Color(0xB3000000), RoundedCornerShape(12.dp))+                        .padding(horizontal = 12.dp, vertical = 6.dp),+                )+            }+        } else {+            Text(+                text = stringResource(R.string.translation_model_not_installed_showing),+                color = Color.White,+                modifier = Modifier+                    .statusBarsPadding()+                    .padding(top = 12.dp)+                    .background(Color(0xB3000000), RoundedCornerShape(12.dp))+                    .padding(horizontal = 12.dp, vertical = 6.dp),+            )+        }     }      // The analysed frame *is* the visible region now, so placing a box is a
translate/src/main/java/com/vayunmathur/translate/ui/CameraPreviewLayer.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/CameraPreviewLayer.kt b/translate/src/main/java/com/vayunmathur/translate/ui/CameraPreviewLayer.ktindex 811db21f2e..7005d1a13b 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/CameraPreviewLayer.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/CameraPreviewLayer.kt@@ -45,6 +45,7 @@ internal fun CameraPreviewLayer(     val sourceLang by viewModel.sourceLang.collectAsState()     val targetLang by viewModel.targetLang.collectAsState()     val translationAvailable by viewModel.translationAvailable.collectAsState()+    val translationLoadFailed by viewModel.translationLoadFailed.collectAsState()      var camera by remember { mutableStateOf<androidx.camera.core.Camera?>(null) }     var provider by remember { mutableStateOf<androidx.camera.lifecycle.ProcessCameraProvider?>(null) }@@ -146,6 +147,8 @@ internal fun CameraPreviewLayer(             overlays = overlays.value,             translations = translations.value,             translationAvailable = translationAvailable,+            translationLoadFailed = translationLoadFailed,+            onRetryTranslator = viewModel::retryTranslator,             frameW = frameW.value,             frameH = frameH.value,             viewW = viewSize.width,
translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslateScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslateScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslateScreen.ktindex 3abdad2982..e8975619c4 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslateScreen.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/ImageTranslateScreen.kt@@ -80,6 +80,7 @@ fun ImageTranslateScreen(     val sourceLang by viewModel.sourceLang.collectAsState()     val targetLang by viewModel.targetLang.collectAsState()     val translationAvailable by viewModel.translationAvailable.collectAsState()+    val translationLoadFailed by viewModel.translationLoadFailed.collectAsState()      DisposableEffect(imageUri) {         onDispose {@@ -170,6 +171,8 @@ fun ImageTranslateScreen(                                 overlays = overlays.value,                                 translations = translations.value,                                 translationAvailable = translationAvailable,+                                translationLoadFailed = translationLoadFailed,+                                onRetryTranslator = viewModel::retryTranslator,                                 frameW = bmp.width,                                 frameH = bmp.height,                                 viewW = dispWpx,
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 c747f4537f..6d06db0747 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslatePage.kt@@ -62,6 +62,7 @@ fun TextTranslatePage(     val sourceLang by viewModel.sourceLang.collectAsState()     val targetLang by viewModel.targetLang.collectAsState()     val translationAvailable by viewModel.translationAvailable.collectAsState()+    val translationLoadFailed by viewModel.translationLoadFailed.collectAsState()     val history by viewModel.history.collectAsState()      var inputText by remember { mutableStateOf(initialText) }@@ -154,6 +155,7 @@ fun TextTranslatePage(             sourceLang = sourceLang,             targetLang = targetLang,             translationAvailable = translationAvailable,+            translationLoadFailed = translationLoadFailed,             inputText = inputText,             outputText = outputText,             isTranslating = isTranslating,@@ -188,6 +190,8 @@ fun TextTranslatePage(                 }             } +            override fun retryTranslator() = viewModel.retryTranslator()+             override fun copyOutput() = copyToClipboard(context, outputText)              // Star the current translation: if it is already saved, flip its flag;
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 b694728891..07fc71c1ce 100644--- a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt+++ b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt@@ -40,6 +40,7 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.isExpandedWidth+import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.translate.domain.Languages import com.vayunmathur.translate.platform.MicState import com.vayunmathur.translate.platform.TextTranslateActions@@ -130,6 +131,7 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio                     ) {                         OutputCard(                             translationAvailable = state.translationAvailable,+                            translationLoadFailed = state.translationLoadFailed,                             isTranslating = state.isTranslating,                             outputText = state.outputText,                             isFavorite = state.isFavorite,@@ -137,6 +139,7 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio                             onCopy = actions::copyOutput,                             onSpeak = actions::speakOutput,                             onToggleFavorite = actions::toggleFavorite,+                            onRetryTranslator = actions::retryTranslator,                         )                     }                 }@@ -150,6 +153,7 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio                  OutputCard(                     translationAvailable = state.translationAvailable,+                    translationLoadFailed = state.translationLoadFailed,                     isTranslating = state.isTranslating,                     outputText = state.outputText,                     isFavorite = state.isFavorite,@@ -157,6 +161,7 @@ fun TextTranslateScreen(state: TextTranslateUiState, actions: TextTranslateActio                     onCopy = actions::copyOutput,                     onSpeak = actions::speakOutput,                     onToggleFavorite = actions::toggleFavorite,+                    onRetryTranslator = actions::retryTranslator,                 )             }         }@@ -237,6 +242,7 @@ private fun LanguageBar( @Composable private fun OutputCard(     translationAvailable: Boolean,+    translationLoadFailed: Boolean,     isTranslating: Boolean,     outputText: String,     isFavorite: Boolean,@@ -244,6 +250,7 @@ private fun OutputCard(     onCopy: () -> Unit,     onSpeak: () -> Unit,     onToggleFavorite: () -> Unit,+    onRetryTranslator: () -> Unit, ) {     Card(modifier = Modifier.fillMaxWidth()) {         Column(@@ -253,14 +260,33 @@ 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) {-                    CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)-                    Spacer(Modifier.width(8.dp))-                    Text(stringResource(R.string.loading_translator), color = MaterialTheme.colorScheme.onSurfaceVariant)+                if (translationLoadFailed) {+                    // The engine failed to load (missing native library, no fp16+                    // Vulkan device, corrupt weights) even though the download+                    // screen finished. Say so with a retry instead of spinning+                    // forever — the old failure mode of issue #842.+                    Text(+                        stringResource(R.string.translation_failed_to_load),+                        fontWeight = FontWeight.Medium,+                        color = MaterialTheme.colorScheme.error,+                    )+                    Text(+                        stringResource(R.string.translation_failed_to_load_hint),+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                    TextButton(onClick = onRetryTranslator) {+                        Text(stringResource(UiR.string.retry))+                    }+                } else {+                    // The outer InitialModelDownloadChecker downloads the model+                    // before any Navigation is composed, and TranslateViewModel+                    // loads the engine on init. Show a spinner while the engine+                    // is still initializing.+                    Row(verticalAlignment = Alignment.CenterVertically) {+                        CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)+                        Spacer(Modifier.width(8.dp))+                        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 0e030b5448..cc81a50749 100644--- a/translate/src/main/res/values/strings.xml+++ b/translate/src/main/res/values/strings.xml@@ -3,6 +3,8 @@     <string name="app_name">Translate</string>     <string name="enter_text">Enter text</string>     <string name="loading_translator">Loading translator…</string>+    <string name="translation_failed_to_load">Couldn’t load the translator</string>+    <string name="translation_failed_to_load_hint">The model downloaded, but this device couldn’t start it. Try again, or reinstall the model from storage settings.</string>     <string name="copy">Copy</string>     <string name="speak">Speak</string>     <string name="translation">Translation</string>