diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 840d5d3621..e35cd412fb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -107,7 +107,7 @@ These structural facts shape every module. Day-to-day build *commands* live in ` - **ABI product flavors.** Every Android module *except* `:plugin-api` and `:subprojects:sqlite-js` gets two flavors on the `abi` dimension — `v7` (`armeabi-v7a`) and `v8` (`arm64-v8a`) — defined centrally. There is no flavorless variant; tasks are `assembleV8Debug`, `assembleV7Release`, etc. - **SDK levels** (`build-logic/.../build/config/BuildConfig.kt`): `COMPILE_SDK=36`, `MIN_SDK=28`, `TARGET_SDK=28`. **`TARGET_SDK` is deliberately pinned at 28:** higher targets enforce W^X (write-xor-execute), which blocks executing code from app-writable files. That is fatal for an on-device IDE that compiles and runs code (Gradle, `javac`, Termux binaries), so it is a hard requirement, not tech debt. `MIN_SDK_FOR_APPS_BUILT_WITH_COGO=16` is the floor for the apps a *user* builds with CoGo — distinct from CoGo's own `MIN_SDK`. - **Native asset bundling.** The on-device LLM (`llama-impl`) ships as a per-flavor native AAR, wired through the root `build.gradle.kts` (`bundleLlamaV8Assets` / `assembleV8Assets`, …); prebuilt per-flavor assets live under `assets/release/v7/` and `assets/release/v8/`. -- **Bundled add-ons** (ADFA-7238). A build is *fat* when `assets/plugins/*.cgp` and `assets/templates/*.cgt` exist in the repo root: release builds put them in the APK assets as `plugins/` and `templates/` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-.zip`. Both also write the bundle index `bundled-addons.tsv` (one line per add-on: entry name, size, SHA-256; empty in a thin build), so the app lists and fingerprints the bundle without opening an add-on, which a release APK stores compressed, and a rebuilt add-on of the same size changes the fingerprint. A bundle without a valid index, such as an older debug zip, is listed from its folders by name and size. A missing or empty folder is the thin build. First-run setup (`AssetsInstallationHelper`) lists the bundle (`assets/addons/BundledAddons`), installs each file in the same parallel phase through `BundledAddonInstaller` (scratch file, then rename; a plugin lands in `filesDir/plugins` as `-.cgp`, a template in `Environment.TEMPLATES_DIR`; a copy whose SHA-256 differs from the index is rejected and reported like a plugin with no readable manifest), and writes `filesDir/bundled_addons.properties` last (`BundledAddonsRecord`: bundle fingerprint, bundled plugin IDs and template files, plugin load failures not yet reported to the user). `InstallationViewModel` then reloads the plugins once, and `MainActivity` shows one error bar for the recorded failures. +- **Bundled add-ons** (ADFA-7238). A build is *fat* when `assets/plugins/*.cgp` and `assets/templates/*.cgt` exist in the repo root: release builds put them in the APK assets as `plugins/` and `templates/` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-.zip`. Both also write the bundle index `bundled-addons.tsv` (one line per add-on: entry name, size, SHA-256; empty in a thin build), so the app lists and fingerprints the bundle without opening an add-on, which a release APK stores compressed, and a rebuilt add-on of the same size changes the fingerprint. A bundle without a valid index, such as an older debug zip, is listed from its folders by name and size. A missing or empty folder is the thin build. First-run setup (`AssetsInstallationHelper`) lists the bundle (`assets/addons/BundledAddons`), installs each file in the same parallel phase through `BundledAddonInstaller` (scratch file, then rename; a plugin lands in `filesDir/plugins` as `-.cgp`, a template in `Environment.TEMPLATES_DIR`; a copy whose SHA-256 differs from the index is rejected and reported like a plugin with no readable manifest), and writes `filesDir/bundled_addons.properties` last (`BundledAddonsRecord`: bundle fingerprint, bundled plugin IDs and template files, plugin load failures not yet reported to the user). `InstallationViewModel` then reloads the plugins once, and `MainActivity` shows one error bar for the recorded failures. At every later start (ADFA-7239), `CredentialProtectedApplicationLoader` runs `BundleSyncAtStart` before `loadPlugins()`: when the build's bundle fingerprint differs from the record, or there is no record (a first install cut short), `BundleSync` installs the whole bundle (replacing any other installed build of a bundled plugin ID, which clears that plugin's state, while an unchanged build keeps its state; and any template of a bundled name), removes recorded add-ons the new bundle lacks, leaves other user add-ons alone, and rewrites the record last. A debug build whose `assets-.zip` is gone skips the sync. A failed sync keeps the old record, so it runs again, and is reported in the error bar. `MainActivity` waits (up to 30 s) for the check to begin, shows a progress bar while a sync runs, then the error bar. - **sqlite-js for apps built with CoGo** (ADFA-7082). `subprojects:sqlite-js` builds the AAR that the JavaScript-in-SQLite project template depends on: the sqlite-js release vendored (see its README), for arm64-v8a and armeabi-v7a, minSdk 26, without core-library desugaring. Nothing in CoGo depends on it. Its default entry point runs no code stored in a database; loading stored functions is a separate entry point, only for databases the app made, since loading runs their code. `test-sqlite-js.yml` runs its host tests on pull requests. The manual `release-sqlite-js.yml` publishes it to the moving `sqlite-js-latest` release, from which dev-assets fetches it into the template, as it fetches `plugin-api-latest` for the plugin template. - **Native lib compression** (ADFA-2306, ADFA-4729). The app manifest hard-codes `android:extractNativeLibs="true"` (required: the installer must materialize libs in `nativeLibraryDir`, e.g. `libshizuku.so` is an executable the adb shell runs from there). That attribute overrides the `jniLibs.useLegacyPackaging` DSL, so AGP packages `lib//*.so` deflate-compressed in **every** APK — ~5.9 MB smaller (`libtree-sitter-kotlin.so` alone is 4.18 MB → 339 kB). The trap is the `recompressApk` post-step (release always, debug in CI only): its no-compress lists in `app/build.gradle.kts` must NOT contain `"so"`, or it silently re-stores the libs and undoes the saving — which is what ADFA-2306 fixed for release and ADFA-4729 for CI debug. Locally built debug APKs (including the e2e farm's) never run that step and were always fine. - **Quick Build shares the Gradle distribution's toolchain** (ADFA-4931). `:app`'s `quickBuildDaemonZip` leaves the Kotlin compiler and eight other jars out of the daemon zip, because the on-device Gradle distribution already carries them; `QuickBuildArtifactStager` links them in at provision time. That makes the daemon's Kotlin version the distribution's, so `:quickbuild:daemon` takes its Kotlin artifacts at `org.adfa.constants.GRADLE_DISTRIBUTION_KOTLIN_VERSION`, and `:app:quickBuildDistJarCheck` fails the build when the distribution it packages lacks a linked jar. See [ADR 0016](docs/adr/0016-quick-build-compiles-outside-gradle.md). diff --git a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt index 72ad9d62f4..f72ac8a03b 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -47,6 +47,7 @@ import com.itsaky.androidide.analytics.IAnalyticsManager import com.itsaky.androidide.analytics.depth import com.itsaky.androidide.analytics.selector import com.itsaky.androidide.app.EdgeToEdgeIDEActivity +import com.itsaky.androidide.assets.addons.BundleSyncAtStart import com.itsaky.androidide.assets.addons.BundledAddonsRecord import com.itsaky.androidide.assets.addons.reportFailures import com.itsaky.androidide.databinding.ActivityMainBinding @@ -83,6 +84,7 @@ import com.itsaky.androidide.utils.findValidProjects import com.itsaky.androidide.utils.flashError import com.itsaky.androidide.utils.flashErrorTracked import com.itsaky.androidide.utils.flashInfo +import com.itsaky.androidide.utils.flashProgress import com.itsaky.androidide.utils.hasVisibleDialog import com.itsaky.androidide.utils.recordProjectOpenedBookkeeping import com.itsaky.androidide.utils.resolveDeepLinkProject @@ -95,8 +97,11 @@ import com.itsaky.androidide.viewmodel.MainViewModel.Companion.SCREEN_TEMPLATE_D import com.itsaky.androidide.viewmodel.MainViewModel.Companion.SCREEN_TEMPLATE_LIST import com.itsaky.androidide.viewmodel.MainViewModel.Companion.TOOLTIPS_WEB_VIEW import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel import org.slf4j.LoggerFactory @@ -349,12 +354,16 @@ class MainActivity : EdgeToEdgeIDEActivity() { * away first, as a font scale change recreates it, shows them again next time. The report runs * until the dismissal, and [reportingBundledFailures] keeps a resume during the report from * starting a second one. + * + * Waits for the start-up bundle check first, showing a progress bar while it installs a new + * bundle (ADFA-7239), so the failures of that bundle are recorded before they are read. */ private fun reportBundledPluginFailures() { if (reportingBundledFailures) return reportingBundledFailures = true lifecycleScope.launch { try { + awaitBundleSync() val record = BundledAddonsRecord.inFilesDir(filesDir) record.reportFailures { failures -> flashErrorTracked( @@ -370,6 +379,22 @@ class MainActivity : EdgeToEdgeIDEActivity() { } } + private suspend fun awaitBundleSync() { + val syncState = BundleSyncAtStart.state + // The screen can resume before the plugin system starts. If it never does (a failed + // start-up that is retried later), stop waiting and report what is recorded. + withTimeoutOrNull(BUNDLE_SYNC_START_TIMEOUT_MS) { + syncState.first { it != BundleSyncAtStart.State.NOT_STARTED && it != BundleSyncAtStart.State.CHECKING } + } ?: return + if (syncState.value != BundleSyncAtStart.State.SYNCING) return + val bar = this@MainActivity.flashProgress { message(getString(string.msg_updating_bundled_addons)) } + try { + syncState.first { it == BundleSyncAtStart.State.IDLE } + } finally { + withContext(NonCancellable + Dispatchers.Main) { bar.dismiss() } + } + } + override fun onPause() { MainScreenActions.clear() super.onPause() @@ -842,5 +867,8 @@ class MainActivity : EdgeToEdgeIDEActivity() { companion object { private const val KEY_CONSUMED_DEEP_LINK_REQUESTS = "consumedDeepLinkRequests" private const val KEY_UNRESOLVED_DEEP_LINK_REQUESTS = "unresolvedDeepLinkRequests" + + /** How long the main screen waits for the plugin system to begin its bundle check. */ + private const val BUNDLE_SYNC_START_TIMEOUT_MS = 30_000L } } diff --git a/app/src/main/java/com/itsaky/androidide/activities/SetupState.kt b/app/src/main/java/com/itsaky/androidide/activities/SetupState.kt index ae26481dab..5e4ffef646 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/SetupState.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/SetupState.kt @@ -72,11 +72,18 @@ internal fun Context.isIdeSetupComplete(): Boolean = * the provider's job once it runs, and a directory that exists but holds nothing usable is a broken * install, not an unfinished setup. */ -private fun isJdkInstalled(): Boolean { +internal fun isJdkInstalled(): Boolean { val jvmDir = File(jdkInstallPrefix(), "lib/jvm") return jvmDir.isDirectory && (jvmDir.list()?.isNotEmpty() == true) } +/** + * Whether first-time setup has put a JDK and the Android SDK on disk: [isIdeSetupComplete] without + * the permissions. The bundle sync at start-up (ADFA-7239) asks it, from the loader coroutine, before + * the JDK provider has loaded. + */ +internal fun areIdeToolsInstalled(): Boolean = isJdkInstalled() && androidSdkHome().exists() + /** * [Environment.PREFIX], or the same path it will hold once `Environment.init()` has run. * diff --git a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt index 82f0d511ce..93829b449b 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -12,6 +12,9 @@ import com.itsaky.androidide.activities.CrashHandlerActivity import com.itsaky.androidide.activities.editor.IDELogcatReader import com.itsaky.androidide.api.BuildOutputProvider import com.itsaky.androidide.api.LogsProvider +import com.itsaky.androidide.assets.addons.BundleSyncAtStart +import com.itsaky.androidide.assets.addons.BundledAddonsRecord +import com.itsaky.androidide.assets.addons.BundledPluginStartup import com.itsaky.androidide.editor.schemes.IDEColorSchemeProvider import com.itsaky.androidide.eventbus.events.plugin.PluginCrashedEvent import com.itsaky.androidide.eventbus.events.preferences.PreferenceChangeEvent @@ -379,19 +382,39 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { setupPluginServices() setupPluginInflationErrorHandler() - // Load plugins asynchronously + // Load plugins asynchronously. The build's bundled add-ons are applied first, so the + // synced set loads once (ADFA-7239). + BundleSyncAtStart.begin() GlobalScope.launch { try { - pluginManager?.loadPlugins() + val manager = pluginManager + if (manager != null) { + // Under the load lock, as Add-ons Manager installs are: the sync replaces plugin files. + val synced = + manager.whileNotLoading { withContext(Dispatchers.IO) { BundleSyncAtStart.run(application, manager) } } + manager.loadPlugins() + if (synced) { + // Plugins are loaded already; this only records the bundled ones that failed. + BundledPluginStartup( + record = BundledAddonsRecord.inFilesDir(application.filesDir), + reloadPlugins = {}, + loadError = manager::getLoadError, + ).start() + } + } EditorDecorationBridge.init() logger.info("Plugin system initialized successfully") } catch (e: Exception) { logger.error("Failed to load plugins", e) + } finally { + BundleSyncAtStart.end() } } } catch (e: Exception) { Sentry.captureException(e) logger.error("Failed to initialize plugin system", e) + // No start-up coroutine will end the bundle check, so the main screen must not wait for it. + BundleSyncAtStart.end() } } diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt new file mode 100644 index 0000000000..da5bd0e175 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt @@ -0,0 +1,115 @@ +package com.itsaky.androidide.assets.addons + +import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION +import java.io.File +import java.io.IOException + +/** + * Applies the build's bundle to an installation that already has one (ADFA-7239): after an update + * to an APK with another bundle, or after a first installation that stopped before its record was + * written. + * + * The new bundle replaces the recorded one. Every bundled add-on is installed, overwriting a user's + * plugin with the same ID and a user's template with the same name, and bringing back one the user + * removed. A recorded add-on the new bundle lacks is removed, so a thin APK removes them all. Other + * user add-ons are left alone. + * + * A bundled plugin whose build is already the only one installed for its ID is copied over in + * place and keeps its state (enabled or not, crash count); only a real change of build goes + * through [uninstallPlugin], which clears that state, as an install from the Add-ons Manager does. + * + * The record is written last, so a sync cut short runs again at the next start. + * + * @param readPluginId the plugin ID in a plugin file's manifest, or null. + * @param uninstallPlugin removes every installed file of a plugin ID, with its state. + */ +class BundleSync( + private val record: BundledAddonsRecord, + private val pluginsDir: File, + private val templatesDir: File, + private val readPluginId: (File) -> String?, + private val uninstallPlugin: (pluginId: String) -> Unit, +) { + private val installer = BundledAddonInstaller(pluginsDir, templatesDir, readPluginId, ::replaceOtherBuilds) + + /** True when [entries] are not the recorded bundle, or no bundle is recorded. */ + fun isNeeded(entries: List): Boolean = record.read()?.fingerprint != BundledAddons.fingerprint(entries) + + /** + * Installs [entries] from [source] in place of the recorded bundle, and records them. An I/O + * error propagates and leaves the old record, so the sync runs again. + */ + fun sync( + source: BundleSource, + entries: List, + ): BundledAddonsState { + val old = record.read() + + val installed = + entries.map { entry -> + source.open(entry.kind.dir, entry.fileName).use { installer.install(entry.kind, entry.fileName, it, entry.sha256) } + } + + val pluginIds = installed.mapNotNull { it.pluginId }.toSet() + val templateFiles = installed.filter { it.kind == BundledAddonKind.TEMPLATE }.mapNotNull { it.file?.name }.toSet() + + // A rejected copy is not known by ID, so it may be a recorded add-on the new bundle still has: + // removing by the old record would then delete a working build. Keep the old ones instead. + if (installed.none { it.failure != null }) { + old + ?.pluginIds + .orEmpty() + .filterNot { it in pluginIds } + .forEach(uninstallPlugin) + old + ?.templateFiles + .orEmpty() + .filterNot { it in templateFiles } + .forEach { name -> File(templatesDir, name).takeIf { it.parentFile == templatesDir }?.delete() } + } + + val state = + BundledAddonsState( + fingerprint = BundledAddons.fingerprint(entries), + pluginIds = pluginIds.sorted(), + templateFiles = templateFiles.sorted(), + // The old bundle's failures went with it; these are the new one's rejected copies. + failures = + installed + .mapNotNull { addon -> addon.failure?.let { BundledPluginFailure(addon.sourceName ?: "?", it) } } + .sortedBy { it.pluginId }, + ) + record.write(state) + return state + } + + /** + * Before the bundled build [fileName] of [pluginId] lands: removes the other builds of that ID, + * a user's or an older bundled one. When none is left, the move overwrites the same build in + * place and nothing is uninstalled. Throws when a build stays, so the two never load together. + */ + private fun replaceOtherBuilds( + pluginId: String, + fileName: String, + ) { + if (otherBuilds(pluginId, fileName).isEmpty()) return + uninstallPlugin(pluginId) + val left = otherBuilds(pluginId, fileName) + if (left.isNotEmpty()) { + throw IOException("Could not remove the installed build of $pluginId: ${left.joinToString { it.name }}") + } + } + + private fun otherBuilds( + pluginId: String, + fileName: String, + ): List = + pluginsDir + .listFiles { file -> + file.isFile && + file.name != fileName && + file.name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true) && + runCatching { readPluginId(file) }.getOrNull() == pluginId + }.orEmpty() + .toList() +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSyncAtStart.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSyncAtStart.kt new file mode 100644 index 0000000000..5ba9808743 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSyncAtStart.kt @@ -0,0 +1,129 @@ +package com.itsaky.androidide.assets.addons + +import android.content.Context +import com.itsaky.androidide.activities.areIdeToolsInstalled +import com.itsaky.androidide.assets.AssetsInstaller +import com.itsaky.androidide.assets.BundledAssetsInstaller +import com.itsaky.androidide.plugins.manager.core.PluginManager +import com.itsaky.androidide.plugins.manager.loaders.PluginLoader +import com.itsaky.androidide.utils.Environment +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import org.slf4j.LoggerFactory +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean +import java.util.zip.ZipFile +import kotlin.coroutines.cancellation.CancellationException + +/** + * Runs [BundleSync] at most once per process, from the plugin system's start-up, before plugins + * load: the synced set then loads once. [state] tells the main screen when to show a progress bar + * and when the bundle's failures are recorded. + */ +object BundleSyncAtStart { + enum class State { + /** The plugin system has not started yet; the main screen waits, up to a limit. */ + NOT_STARTED, + + /** Comparing the build's bundle with the record. */ + CHECKING, + + /** Installing the build's bundle; ends once its plugins have loaded and failures are recorded. */ + SYNCING, + + /** Start-up is over, or the plugin system will not start. */ + IDLE, + } + + /** Failure key for a sync that did not finish; the error bar lists it like a plugin. */ + const val SYNC_FAILURE_KEY = "bundled add-ons" + + private val logger = LoggerFactory.getLogger(BundleSyncAtStart::class.java) + private val mutableState = MutableStateFlow(State.NOT_STARTED) + private val claimed = AtomicBoolean(false) + val state: StateFlow = mutableState.asStateFlow() + + /** Call before launching the start-up coroutine. */ + fun begin() { + mutableState.value = State.CHECKING + } + + /** Call when start-up is over, or when the plugin system fails to start, whatever happened. */ + fun end() { + mutableState.value = State.IDLE + } + + /** + * Syncs the build's bundle when it is not the recorded one. True when it synced. Never throws + * but for cancellation: on an error the old record stays, so the sync runs again next start, + * and the error is recorded for the error bar. Leaves [state] at [State.SYNCING] after a sync, + * for [end] to clear once failures are recorded. + */ + fun run( + context: Context, + manager: PluginManager, + ): Boolean { + // A retried start-up (the loader un-claims itself on a failure) must not sync a second time. + if (!claimed.compareAndSet(false, true)) return false + val record = BundledAddonsRecord.inFilesDir(context.filesDir) + return try { + // Before setup has finished, the asset phase installs the bundle (ADFA-7238). + if (!areIdeToolsInstalled()) { + false + } else { + val release = AssetsInstaller.CURRENT_INSTALLER is BundledAssetsInstaller + withBundleSource(release, Environment.SPLIT_ASSETS_ZIP, { AssetManagerBundleSource(context.assets) }) { source -> + syncIfNeeded(context, manager, record, source) + } ?: false + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.error("Could not apply the bundled add-ons", e) + // Only lands when a record exists; without one there is no installed bundle to fail. + runCatching { record.recordFailures(mapOf(SYNC_FAILURE_KEY to (e.message ?: e.toString()))) } + false + } finally { + if (mutableState.value == State.CHECKING) end() + } + } + + private fun syncIfNeeded( + context: Context, + manager: PluginManager, + record: BundledAddonsRecord, + source: BundleSource, + ): Boolean { + val sync = + BundleSync( + record = record, + pluginsDir = File(context.filesDir, "plugins"), + templatesDir = Environment.TEMPLATES_DIR, + readPluginId = { PluginLoader(context, it).getPluginMetadata()?.id }, + uninstallPlugin = { manager.uninstallPlugin(it) }, + ) + val entries = BundledAddons.list(source) + if (!sync.isNeeded(entries)) return false + mutableState.value = State.SYNCING + val state = sync.sync(source, entries) + logger.info("Applied the bundled add-ons: {} plugins, {} templates", state.pluginIds.size, state.templateFiles.size) + return true + } + + /** + * Runs [block] on the build's bundle: the APK assets in a release build, [splitZip] in a debug + * one. When the zip is gone, nothing is known about the bundle and [block] does not run: + * deleting the zip after setup must not remove the bundled add-ons. + */ + internal fun withBundleSource( + release: Boolean, + splitZip: File, + assets: () -> BundleSource, + block: (BundleSource) -> T, + ): T? { + if (release) return block(assets()) + if (!splitZip.isFile) return null + return ZipFile(splitZip).use { block(ZipBundleSource(it)) } + } +} diff --git a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt index 77a69bc353..d21f6db58e 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundledAddonInstaller.kt @@ -36,6 +36,12 @@ class BundledAddonInstaller( private val pluginsDir: File, private val templatesDir: File, private val readPluginId: (File) -> String?, + /** + * Called with a valid plugin ID and the file name its copy is about to take, just before the + * move. A sync removes the other installed builds of that ID here, so the new one does not sit + * beside them. + */ + private val beforePluginMove: (pluginId: String, fileName: String) -> Unit = { _, _ -> }, ) { /** * Copies [input] into place. With [sha256] (hex, from the bundle index), a copy whose content @@ -99,6 +105,7 @@ class BundledAddonInstaller( if (name.toByteArray(Charsets.UTF_8).size > MAX_FILE_NAME_BYTES) { throw RejectedAddonException("its plugin ID is too long") } + beforePluginMove(id, name) pluginId = id name }, diff --git a/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt b/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt new file mode 100644 index 0000000000..6e28ecb9c2 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt @@ -0,0 +1,342 @@ +package com.itsaky.androidide.assets.addons + +import com.google.common.truth.Truth.assertThat +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream +import java.io.File +import java.io.IOException +import java.io.InputStream + +class BundleSyncTest { + @get:Rule + val tempFolder = TemporaryFolder() + + private lateinit var pluginsDir: File + private lateinit var templatesDir: File + private lateinit var record: BundledAddonsRecord + private val uninstalled = mutableListOf() + + /** IDs whose files the fake uninstall cannot delete, like a failed delete on the device. */ + private val undeletable = mutableSetOf() + + @Before + fun setUp() { + pluginsDir = tempFolder.newFolder("plugins") + templatesDir = tempFolder.newFolder("templates") + record = BundledAddonsRecord(File(tempFolder.root, BundledAddonsRecord.FILE_NAME)) + } + + /** A fake plugin file's content: its ID, then a build marker. */ + private fun plugin( + id: String, + build: String = "1", + ) = "$id|$build" + + private fun idOf(file: File): String? = file.readText().substringBefore('|').takeIf { it.isNotEmpty() && '|' in file.readText() } + + /** Deletes every plugin file of [pluginId], as PluginManager.uninstallPlugin does. */ + private fun uninstall(pluginId: String) { + uninstalled += pluginId + if (pluginId in undeletable) return + pluginsDir.listFiles { f -> f.name.endsWith(".cgp") && idOf(f) == pluginId }?.forEach { it.delete() } + } + + private fun sync(): BundleSync = + BundleSync( + record = record, + pluginsDir = pluginsDir, + templatesDir = templatesDir, + readPluginId = ::idOf, + uninstallPlugin = ::uninstall, + ) + + private class FakeSource( + val plugins: Map = emptyMap(), + val templates: Map = emptyMap(), + val failOn: String? = null, + ) : BundleSource { + private fun files(dir: String) = if (dir == BundledAddonKind.PLUGIN.dir) plugins else templates + + override fun names(dir: String) = files(dir).keys.toList() + + override fun size( + dir: String, + name: String, + ) = files(dir).getValue(name).length.toLong() + + override fun open( + dir: String, + name: String, + ): InputStream { + if (name == failOn) throw IOException("disk full") + return ByteArrayInputStream(files(dir).getValue(name).toByteArray()) + } + } + + private fun run(source: FakeSource): BundledAddonsState = sync().sync(source, BundledAddons.list(source)) + + private fun installedPluginIds() = pluginsDir.listFiles { f -> f.name.endsWith(".cgp") }!!.mapNotNull(::idOf).sorted() + + private fun templateNames() = templatesDir.list()!!.sorted() + + /** A user's plugin, installed from the Add-ons Manager. */ + private fun userPlugin( + id: String, + build: String = "user", + ) = File(pluginsDir, "$id-user.cgp").apply { writeText(plugin(id, build)) } + + private fun userTemplate(name: String) = File(templatesDir, name).apply { writeText("user template") } + + private val bundleA = + FakeSource( + plugins = mapOf("p1.cgp" to plugin("com.p1"), "p2.cgp" to plugin("com.p2")), + templates = mapOf("t1.cgt" to "t1"), + ) + private val bundleB = + FakeSource( + plugins = mapOf("p2.cgp" to plugin("com.p2", "2"), "p3.cgp" to plugin("com.p3")), + templates = mapOf("t2.cgt" to "t2"), + ) + + @Test + fun `a missing record needs a sync and the sync installs the whole bundle`() { + assertThat(sync().isNeeded(BundledAddons.list(bundleA))).isTrue() + + val state = run(bundleA) + + assertThat(installedPluginIds()).containsExactly("com.p1", "com.p2") + assertThat(templateNames()).containsExactly("t1.cgt") + assertThat(state.pluginIds).containsExactly("com.p1", "com.p2").inOrder() + assertThat(record.read()).isEqualTo(state) + } + + @Test + fun `an unchanged bundle needs no sync`() { + run(bundleA) + + assertThat(sync().isNeeded(BundledAddons.list(bundleA))).isFalse() + assertThat(sync().isNeeded(BundledAddons.list(bundleB))).isTrue() + } + + @Test + fun `a new bundle replaces the old one and keeps user add-ons`() { + run(bundleA) + userPlugin("com.u1") + userTemplate("ut1.cgt") + + val state = run(bundleB) + + assertThat(installedPluginIds()).containsExactly("com.p2", "com.p3", "com.u1") + assertThat(templateNames()).containsExactly("t2.cgt", "ut1.cgt") + assertThat(state.pluginIds).containsExactly("com.p2", "com.p3") + assertThat(state.templateFiles).containsExactly("t2.cgt") + } + + @Test + fun `the new build of a bundled plugin replaces the old build`() { + run(bundleA) + + run(bundleB) + + val p2 = pluginsDir.listFiles { f -> idOf(f) == "com.p2" }!! + assertThat(p2).hasLength(1) + assertThat(p2.single().readText()).isEqualTo(plugin("com.p2", "2")) + } + + @Test + fun `a thin APK over a fat installation removes every bundled add-on`() { + run(bundleA) + userPlugin("com.u1") + userTemplate("ut1.cgt") + + val state = run(FakeSource()) + + assertThat(installedPluginIds()).containsExactly("com.u1") + assertThat(templateNames()).containsExactly("ut1.cgt") + assertThat(state.pluginIds).isEmpty() + assertThat(state.templateFiles).isEmpty() + } + + @Test + fun `a user plugin with a bundled ID is overwritten`() { + run(bundleA) + pluginsDir.listFiles { f -> idOf(f) == "com.p2" }!!.forEach { it.delete() } + userPlugin("com.p2", "mine") + + run(bundleB) + + val p2 = pluginsDir.listFiles { f -> idOf(f) == "com.p2" }!! + assertThat(p2.map { it.readText() }).containsExactly(plugin("com.p2", "2")) + } + + @Test + fun `a user template with a bundled name is overwritten`() { + userTemplate("t1.cgt") + + run(bundleA) + + assertThat(File(templatesDir, "t1.cgt").readText()).isEqualTo("t1") + } + + @Test + fun `a bundled add-on the user removed comes back with a new bundle`() { + run(bundleA) + uninstall("com.p2") + File(templatesDir, "t1.cgt").delete() + val bundleA2 = FakeSource(plugins = bundleA.plugins + ("p4.cgp" to plugin("com.p4")), templates = bundleA.templates) + + run(bundleA2) + + assertThat(installedPluginIds()).containsExactly("com.p1", "com.p2", "com.p4") + assertThat(templateNames()).containsExactly("t1.cgt") + } + + @Test + fun `a plugin with no readable ID is recorded as a failure and the rest install`() { + val source = FakeSource(plugins = mapOf("bad.cgp" to "no id here", "p1.cgp" to plugin("com.p1"))) + + val state = run(source) + + assertThat(installedPluginIds()).containsExactly("com.p1") + assertThat(state.failures.map { it.pluginId }).containsExactly("bad.cgp") + assertThat(state.failures.single().reported).isFalse() + } + + @Test + fun `a sync cut short keeps the old record so it runs again`() { + val before = run(bundleA) + val failing = FakeSource(plugins = bundleB.plugins, templates = bundleB.templates, failOn = "p3.cgp") + + assertThrows(IOException::class.java) { run(failing) } + + assertThat(record.read()).isEqualTo(before) + assertThat(sync().isNeeded(BundledAddons.list(bundleB))).isTrue() + } + + @Test + fun `a plugin whose build did not change is not uninstalled, so it keeps its state`() { + run(bundleA) + val p1Before = pluginsDir.listFiles { f -> idOf(f) == "com.p1" }!!.single() + uninstalled.clear() + + run(FakeSource(plugins = bundleA.plugins, templates = bundleA.templates + ("t9.cgt" to "t9"))) + + assertThat(uninstalled).isEmpty() + assertThat(pluginsDir.listFiles { f -> idOf(f) == "com.p1" }!!.map { it.name }).containsExactly(p1Before.name) + } + + @Test + fun `a changed build is installed through uninstall, which clears the old one's state`() { + run(bundleA) + uninstalled.clear() + + run(bundleB) + + // com.p2 changed build; com.p1 left the bundle. + assertThat(uninstalled).containsExactly("com.p2", "com.p1") + } + + @Test + fun `an older build that cannot be deleted fails the sync and keeps the old record`() { + val before = run(bundleA) + undeletable += "com.p2" + + assertThrows(IOException::class.java) { run(bundleB) } + + assertThat(record.read()).isEqualTo(before) + // The new build never landed beside the old one. + assertThat(pluginsDir.listFiles { f -> idOf(f) == "com.p2" }!!.map { it.readText() }).containsExactly(plugin("com.p2")) + } + + @Test + fun `a sync cut short converges at the next run`() { + run(bundleA) + assertThrows(IOException::class.java) { + run(FakeSource(plugins = bundleB.plugins, templates = bundleB.templates, failOn = "p3.cgp")) + } + + val state = run(bundleB) + + assertThat(installedPluginIds()).containsExactly("com.p2", "com.p3") + assertThat(templateNames()).containsExactly("t2.cgt") + assertThat(record.read()).isEqualTo(state) + } + + @Test + fun `a missing record over user add-ons removes nothing of theirs`() { + userPlugin("com.u1") + userTemplate("ut1.cgt") + + run(bundleA) + + assertThat(installedPluginIds()).containsExactly("com.p1", "com.p2", "com.u1") + assertThat(templateNames()).containsExactly("t1.cgt", "ut1.cgt") + assertThat(uninstalled).isEmpty() + } + + @Test + fun `a debug build whose assets zip is gone does not sync at all`() { + var ran = false + + val result = + BundleSyncAtStart.withBundleSource( + release = false, + splitZip = File(tempFolder.root, "assets-arm64-v8a.zip"), + assets = { error("a debug build reads no APK assets") }, + ) { ran = true } + + assertThat(result).isNull() + assertThat(ran).isFalse() + } + + @Test + fun `a release build reads the APK assets`() { + val source = FakeSource() + + val result = BundleSyncAtStart.withBundleSource(true, File(tempFolder.root, "absent.zip"), { source }) { it } + + assertThat(result).isSameInstanceAs(source) + } + + @Test + fun `a rejected copy keeps the old bundled add-ons instead of removing them`() { + run(bundleA) + val corrupted = FakeSource(plugins = mapOf("p1.cgp" to "no id here", "p2.cgp" to plugin("com.p2")), templates = mapOf()) + + val state = run(corrupted) + + assertThat(installedPluginIds()).containsExactly("com.p1", "com.p2") + assertThat(templateNames()).containsExactly("t1.cgt") + assertThat(state.failures.map { it.pluginId }).containsExactly("p1.cgp") + } + + @Test + fun `a copy that does not match the index is rejected and the installed build kept`() { + run(bundleA) + val source = + FakeSource( + plugins = mapOf("p1.cgp" to plugin("com.p1", "2"), "p2.cgp" to plugin("com.p2")), + templates = bundleA.templates, + ) + val entries = BundledAddons.list(source).map { if (it.fileName == "p1.cgp") it.copy(sha256 = "0".repeat(64)) else it } + + val state = sync().sync(source, entries) + + assertThat(pluginsDir.listFiles { f -> idOf(f) == "com.p1" }!!.map { it.readText() }).containsExactly(plugin("com.p1")) + assertThat(state.failures.map { it.pluginId }).containsExactly("p1.cgp") + assertThat(uninstalled).doesNotContain("com.p1") + } + + @Test + fun `old failures are dropped with the old bundle`() { + run(FakeSource(plugins = mapOf("bad.cgp" to "no id here"))) + + val state = run(bundleA) + + assertThat(state.failures).isEmpty() + } +} diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index c8584484b5..ff0000621e 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -111,6 +111,7 @@ Assets file \'%1$s\' not found. Copy it to %2$s, then restart %3$s. Some plugins or templates that came with the app could not be installed or started:\n%1$s + Updating the plugins and templates that came with the app… The picked file is not a directory. Please wait for a moment. Not enough storage available for installation. An additional %1$.1fGB is required on the internal storage partition. You currently have %2$.1fGB available.