Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .agents/skills/verify-android/features/page-translation.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ language packs. The feature is off unless two remote flags are on, so the recipe
- `translate-settings-open` Settings > Translations (`TranslationsSettingsActivity`): title, description, the "Ask to Translate Pages" switch (`askToTranslateSetting`), the "Language Packs" header and a row per installed pack, or "No language packs downloaded yet".
- `translate-settings-ask` "Ask to Translate Pages" off: a Spanish page shows no banner but keeps the menu row.
- `translate-settings-delete` a pack row's options button ("Language pack options") offers Delete; the row goes, the snackbar "Language pack deleted" has Undo, and Undo brings the row back.
- `translate-pack-update` an installed pack whose saved version differs from the manifest's is replaced in the background after the next launch's manifest fetch, on an unmetered network and only while both flags are on; Translate then works on it with no download sheet.

## How to get to it (user POV)

Expand Down Expand Up @@ -54,6 +55,7 @@ Recipes, all inside `$V record start translate-<name>.mp4` / `$V record stop`:
- **Ask to Translate Pages off.** Turn the switch off, `$V key back` to the browser and open a fresh `$ES`: `$V assert not-visible id:translationBannerCard` for 7 s, while the menu still lists "Translate Page to English". Turn it back on, reload: the banner returns.
- **Delete a pack and Undo.** On the screen with a pack, `$V tap desc:Language pack options`, `$V tap id:deleteLanguagePack` (text "Delete"): the row is gone, "No language packs downloaded yet" shows, the snackbar reads "Language pack deleted" with an Undo action (`$V tap text:Undo`). Undo restores the row; `run-as ... ls files/page-translation/packs` still lists `es-en`. Without Undo the snackbar times out and the directory is gone.
- **Flag off.** Turn `translation` off in the inventory and `$V restart`: Settings has no "Translations" row, and a fresh `$ES` shows no banner or menu row. Turn it back on for the next recipe.
- **Pack update.** With the `es-en` pack installed, make it look outdated: rewrite the `version` in `files/page-translation/packs/es-en/manifest-entry.json` (`run-as ... cat` it, change the value, write it back with `adb exec-in run-as com.duckduckgo.mobile.android.debug sh -c 'cat > files/page-translation/packs/es-en/manifest-entry.json'`) and `touch` a marker file in `packs/es-en/`. `$V restart` starts a manifest fetch, which queues the update. Poll the entry's `version` (up to 3 min; it downloads the full pack again) until it is the manifest's again, the marker is gone (the directory was swapped), and `ls packs` lists only `es-en`. The update work is in WorkManager's database (`no_backup/androidx.work.workdb`, plus `-wal`; pull both with `run-as ... cat`): `workspec` rows with `worker_class_name` ending in `LanguagePackUpdateWorker`, `state` 2 = succeeded. With `pageTranslation` off (`translation` still on) the same restart still fetches the manifest but adds no update row and leaves the version and marker alone. Then translate `$ES` through the menu: no sheet, and the lead paragraph turns English.

## Gotchas

Expand All @@ -67,6 +69,11 @@ Recipes, all inside `$V record start translate-<name>.mp4` / `$V record stop`:
- The download runs in WorkManager and outlives the tab; a pack half-downloaded when the app is killed resumes later. Check `packs` before a "no pack" recipe rather than assuming it.
- Not driven: Download failed (cut the network mid-download) and "Not enough storage" (needs a filler file on the device) snackbars, "Retry", a failure while the tab is hidden, dark mode and landscape, the Translate prompt for a second language pair. `TranslationErrorPresenter` shows the first two; they are reliable only with a throttled network or a full disk, so they stay unverified.
- Driven on 2026-12-03 on a OnePlus 7T (OxygenOS, API 31) at commit `352d3e138c`: every sub-feature above except the ones under "Not driven". The selectors and strings in this file were seen in `android layout` or in screenshots on that run.
- `translate-pack-update` driven on 2026-12-03 on the emulator Pixel_8a_mh (`sdk_gphone64_arm64`, API 36) at commit `c57d10ad70`. Not driven there: the metered-network skip (the emulator's Wi-Fi is unmetered, and `cmd netpolicy set metered-network` didn't visibly change it) and a process death between the swap's two renames, which leaves the old pack in `packs/<pair>.replaced` for the next run of the update to restore.
- No offer appears for a page loaded in the same process that fetched the first manifest after the flags were turned on; `$V restart` once `files/page-translation/models.json` exists, then open the page.
- On the Pixel_8a_mh emulator the browser menu is the newer sheet: it has no `settingsMenuItem` id, and "Translate Page to English" can sit below the first screen. Open it with `id:browserMenuImageView`, wait for `text:Refresh`, and `$V scroll up` inside the sheet to find the row.
- In the Feature Flag Inventory, a switch tapped right after hiding the keyboard can miss; read it back with `$V rows primaryText trailingSwitch` and tap again before `$V restart`.
- WorkManager keeps finished work in its database across runs, so compare update rows before and after the action rather than expecting none, or start from `$V reset`.
- `android layout` takes about 4 s on a Wikipedia page on that phone and the banner lives 5 s, so `$V wait`, `$V text` and `$V tap` on the banner usually arrive too late. Detect the banner from one `android layout` read that carries all the text you need (title, languages, button), or from a raw `adb exec-out screencap` pixel (the button is rgb 16,116,204 at x 760..770, y 340..410), and tap the button with `adb shell input tap 880 373` at once. A tap placed after the banner has gone lands on the Wikipedia page (its search button sits under it).
- The progress bar `translationBannerProgress` is not in `android layout` or `$V ui` (not an accessibility element): the title, subtitle and the spinner in a screenshot are the evidence. The ring looked like the same spinner at every poll; this run did not prove it is determinate.
- "Downloading Spanish…" (subtitle "Language pack, 25 MB") lasts a few seconds on a fast network and was never caught by a poll; read it from the recording frames (the 25 MB pack was in place within 8 s of confirming).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ import dev.zacsweers.metro.SingleIn
import dev.zacsweers.metro.binding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import logcat.LogPriority.ERROR
import logcat.asLog
import logcat.logcat
Expand Down Expand Up @@ -78,6 +81,12 @@ interface TranslationEngine {

/** Translates [units] with [pair]'s installed language pack, replacing another pair's loaded translator. */
suspend fun translate(pair: LanguagePair, units: List<TranslationUnit>, isVisible: () -> Boolean): BatchTranslation

/**
* Waits until no translator of [pair] is loaded, then runs [replace] while none can be loaded, so a pack is never replaced
* under a translator that's using it. Returns what [replace] returns.
*/
suspend fun replacePack(pair: LanguagePair, replace: () -> Boolean): Boolean
}

@SingleIn(AppScope::class)
Expand All @@ -99,6 +108,11 @@ class RealTranslationEngine @Inject constructor(

// only touched on engineDispatcher
private var loadedTranslator: LoadedTranslator? = null
set(value) {
field = value
loadedPair.value = value?.pair
}
private val loadedPair = MutableStateFlow<LanguagePair?>(null)

// only touched on engineDispatcher; a pack that failed to load fails again until it's replaced, and each failure checks it again
private var failedPackVersion: PackVersion? = null
Expand Down Expand Up @@ -138,6 +152,14 @@ class RealTranslationEngine @Inject constructor(
BatchTranslation.Translated(translateUnits(translator, units))
}

override suspend fun replacePack(pair: LanguagePair, replace: () -> Boolean): Boolean {
while (true) {
loadedPair.first { it != pair }
// a call can load the pair's translator again before this runs on the engine's thread
withContext(engineDispatcher) { if (loadedTranslator?.pair == pair) null else replace() }?.let { return it }
}
}

private suspend fun <T> runCall(isVisible: () -> Boolean, block: () -> T): T = callQueue.run(isVisible) {
idleUnloadJob.cancel()
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,14 @@ interface LanguagePackDirectories {
/** Where [pair]'s pack waits after it was deleted, until it's restored or removed. */
fun getOldDirectory(pair: LanguagePair): File

/** Where [pair]'s pack waits while an update replaces it, so an interrupted update can restore it. */
fun getReplacedDirectory(pair: LanguagePair): File

fun getInstalledPairs(): Set<LanguagePair>

fun getPairsWithOldDirectory(): Set<LanguagePair>

fun getPairsWithReplacedDirectory(): Set<LanguagePair>
}

@ContributesBinding(AppScope::class)
Expand All @@ -49,6 +54,8 @@ class RealLanguagePackDirectories @Inject constructor(

override fun getOldDirectory(pair: LanguagePair): File = getPacksDirectory().resolve(pair.key + OLD_SUFFIX)

override fun getReplacedDirectory(pair: LanguagePair): File = getPacksDirectory().resolve(pair.key + REPLACED_SUFFIX)

override fun getInstalledPairs(): Set<LanguagePair> = getDirectoryNames().filter { '.' !in it }.mapNotNullTo(
mutableSetOf(),
LanguagePair::fromKey,
Expand All @@ -57,6 +64,13 @@ class RealLanguagePackDirectories @Inject constructor(
override fun getPairsWithOldDirectory(): Set<LanguagePair> =
getDirectoryNames().filter { it.endsWith(OLD_SUFFIX) }.mapNotNullTo(mutableSetOf()) { LanguagePair.fromKey(it.removeSuffix(OLD_SUFFIX)) }

override fun getPairsWithReplacedDirectory(): Set<LanguagePair> =
getDirectoryNames().filter {
it.endsWith(
REPLACED_SUFFIX,
)
}.mapNotNullTo(mutableSetOf()) { LanguagePair.fromKey(it.removeSuffix(REPLACED_SUFFIX)) }

private fun getDirectoryNames(): List<String> = getPacksDirectory().listFiles()?.filter { it.isDirectory }?.map { it.name }.orEmpty()

private fun getPacksDirectory(): File = context.filesDir.resolve(PACKS_DIRECTORY)
Expand All @@ -65,5 +79,6 @@ class RealLanguagePackDirectories @Inject constructor(
const val PACKS_DIRECTORY = "page-translation/packs"
const val STAGING_SUFFIX = ".tmp"
const val OLD_SUFFIX = ".old"
const val REPLACED_SUFFIX = ".replaced"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,12 @@ internal class LanguagePackDownloadWorker(
}
if (fetchResult != SUCCESS) return@async fetchResult

if (installer.value.install(pair, model, stagingDirectory, directories.getPackDirectory(pair))) SUCCESS else FAILURE
val isInstalled = installer.value.install(
pair,
model,
stagingDirectory,
) { stagingDirectory.renameTo(directories.getPackDirectory(pair)) }
if (isInstalled) SUCCESS else FAILURE
}
val stopWhenDisabled = launch {
feature.translation().enabled().firstOrNull { isEnabled -> !isEnabled } ?: return@launch
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ internal class LanguagePackFileWorker(
// the rename uninstalls the pack at once, so a crash while deleting never leaves a partly deleted pack installed
moveToOld(pair)
directories.getOldDirectory(pair).deleteRecursively()
directories.getReplacedDirectory(pair).deleteRecursively()
}

private fun moveToOld(pair: LanguagePair) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,14 @@ import javax.inject.Inject

interface LanguagePackInstaller {
/**
* Checks the files [LanguagePackFetcher] downloaded into [stagingDirectory] against [model], decompresses them and moves
* the pack to [packDirectory] if the manifest still lists [model]'s version for [pair]. Returns false, and deletes
* Checks the files [LanguagePackFetcher] downloaded into [stagingDirectory] against [model], decompresses them and calls
* [moveIntoPlace] to install the pack if the manifest still lists [model]'s version for [pair]. Returns false, and deletes
* [stagingDirectory], when the pack isn't installed.
*/
suspend fun install(pair: LanguagePair, model: TranslationModel, stagingDirectory: File, packDirectory: File): Boolean
suspend fun install(pair: LanguagePair, model: TranslationModel, stagingDirectory: File, moveIntoPlace: suspend () -> Boolean): Boolean

/** The version of the manifest entry [install] saved with the pack in [packDirectory], or null when it can't be read. */
suspend fun getInstalledVersion(packDirectory: File): String?

/** True when every file of the pack in [packDirectory] still matches the manifest entry [install] saved with it. */
suspend fun isIntact(packDirectory: File): Boolean
Expand All @@ -60,10 +63,10 @@ class RealLanguagePackInstaller @Inject constructor(
pair: LanguagePair,
model: TranslationModel,
stagingDirectory: File,
packDirectory: File,
moveIntoPlace: suspend () -> Boolean,
): Boolean = withContext(dispatchers.io()) {
val isInstalled = try {
translateKit.init() && installFiles(pair, model, stagingDirectory, packDirectory)
translateKit.init() && installFiles(pair, model, stagingDirectory, moveIntoPlace)
} catch (_: IOException) {
false
}
Expand All @@ -78,19 +81,30 @@ class RealLanguagePackInstaller @Inject constructor(
isInstalled
}

override suspend fun getInstalledVersion(packDirectory: File): String? = withContext(dispatchers.io()) {
readManifestEntry(packDirectory)?.version
}

override suspend fun isIntact(packDirectory: File): Boolean = withContext(dispatchers.io()) {
val model = try {
adapter.fromJson(packDirectory.resolve(MANIFEST_ENTRY_FILE_NAME).readText())
} catch (_: IOException) {
null
} catch (_: JsonDataException) {
null
} ?: return@withContext false
val model = readManifestEntry(packDirectory) ?: return@withContext false

model.files.all { (key, file) -> packDirectory.resolve(file.getInstalledFileName(key)).matches(file.decompressedSize, file.decompressedHash) }
}

private suspend fun installFiles(pair: LanguagePair, model: TranslationModel, stagingDirectory: File, packDirectory: File): Boolean {
private fun readManifestEntry(packDirectory: File): TranslationModel? = try {
adapter.fromJson(packDirectory.resolve(MANIFEST_ENTRY_FILE_NAME).readText())
} catch (_: IOException) {
null
} catch (_: JsonDataException) {
null
}

private suspend fun installFiles(
pair: LanguagePair,
model: TranslationModel,
stagingDirectory: File,
moveIntoPlace: suspend () -> Boolean,
): Boolean {
for ((key, file) in model.files) {
currentCoroutineContext().ensureActive()
val compressedFile = stagingDirectory.resolve(key + COMPRESSED_FILE_SUFFIX)
Expand All @@ -112,7 +126,7 @@ class RealLanguagePackInstaller @Inject constructor(
if (store.readManifest()?.getModel(pair)?.version != model.version) return false

currentCoroutineContext().ensureActive()
return stagingDirectory.renameTo(packDirectory)
return moveIntoPlace()
}

private fun File.matches(size: Long, sha256: String): Boolean = length() == size && this.sha256().equals(sha256, ignoreCase = true)
Expand Down
Loading
Loading