From 553f1bc84ec112bc949a11e4b29a3f8051c70ab7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 20:22:34 +0000 Subject: [PATCH 1/8] ADFA-7239: Apply a new APK's bundled add-ons at start-up When the build's bundle fingerprint differs from the record, or there is no record (a first install cut short), install the whole bundle before plugins load, remove recorded add-ons the new bundle lacks, keep other user add-ons, and rewrite the record last. - BundleSync: the sync. Each bundled plugin replaces every installed build of its ID (a user's or an older bundled one), through a new beforePluginMove hook on BundledAddonInstaller; a template replaces one of the same name; a removed bundled add-on comes back. An I/O error leaves the old record, so the sync runs again at the next start. - BundleSyncAtStart: runs it from CredentialProtectedApplicationLoader before loadPlugins(), only once setup has put a JDK and SDK on disk (areIdeToolsInstalled, from SetupState). A debug build whose assets zip is gone skips the sync rather than treat the bundle as empty. Bundled plugins that fail to load after a sync are recorded for the error bar. - MainActivity waits for the start-up check before reporting failures, and shows a progress bar only while a sync runs. - ARCHITECTURE.md describes the sync. Decisions (ADFA-7239 comment 41492): a missing debug zip is no change; a user's newer build of a bundled plugin stays bundled; the bar shows only while a sync runs. Not compiled or tested in this environment (no Android SDK); BundleSyncTest needs a run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- ARCHITECTURE.md | 2 +- .../androidide/activities/MainActivity.kt | 20 ++ .../androidide/activities/SetupState.kt | 9 +- .../CredentialProtectedApplicationLoader.kt | 21 +- .../androidide/assets/addons/BundleSync.kt | 70 ++++++ .../assets/addons/BundleSyncAtStart.kt | 121 ++++++++++ .../assets/addons/BundledAddonInstaller.kt | 6 + .../assets/addons/BundleSyncTest.kt | 223 ++++++++++++++++++ resources/src/main/res/values/strings.xml | 1 + 9 files changed, 469 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt create mode 100644 app/src/main/java/com/itsaky/androidide/assets/addons/BundleSyncAtStart.kt create mode 100644 app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c7d1269d4d..e777485cc8 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`. A missing or empty folder is the thin build, whose output is unchanged. 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`), 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`. A missing or empty folder is the thin build, whose output is unchanged. 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`), 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 installed build of a bundled plugin ID 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. `MainActivity` 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 4a01e38e31..7c4b08bc6d 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.databinding.ActivityMainBinding import com.itsaky.androidide.deeplink.ConsumedRequests @@ -82,6 +83,7 @@ import com.itsaky.androidide.utils.findValidProjects import com.itsaky.androidide.utils.flashError import com.itsaky.androidide.utils.flashErrorAwaitShown 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 @@ -94,6 +96,8 @@ 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 org.koin.android.ext.android.inject @@ -347,12 +351,16 @@ class MainActivity : EdgeToEdgeIDEActivity() { * marked reported only once the bar has finished appearing, so a screen that goes away first * reports them next time; [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) val failures = withContext(Dispatchers.IO) { @@ -373,6 +381,18 @@ class MainActivity : EdgeToEdgeIDEActivity() { } } + private suspend fun awaitBundleSync() { + val syncState = BundleSyncAtStart.state + syncState.first { it != BundleSyncAtStart.State.CHECKING } + 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() 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..56e7e3f65c 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,14 +382,28 @@ 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 + val synced = manager != null && withContext(Dispatchers.IO) { BundleSyncAtStart.run(application, manager) } + manager?.loadPlugins() + if (synced && manager != null) { + // 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) { 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..1dd9258f53 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt @@ -0,0 +1,70 @@ +package com.itsaky.androidide.assets.addons + +import java.io.File + +/** + * 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. + * + * The record is written last, so a sync cut short runs again at the next start; installing a + * bundle twice gives the same files. + * + * @param installer copies one bundled file; built with [uninstallPlugin] as its + * `beforePluginMove`, so an older build of the same ID is gone before the new one lands. + * @param uninstallPlugin removes every installed file of a plugin ID, with its state. + */ +class BundleSync( + private val record: BundledAddonsRecord, + private val installer: BundledAddonInstaller, + private val templatesDir: File, + private val uninstallPlugin: (pluginId: String) -> Unit, +) { + /** 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) } + } + + val pluginIds = installed.mapNotNull { it.pluginId }.toSet() + val templateFiles = installed.filter { it.kind == BundledAddonKind.TEMPLATE }.mapNotNull { it.file?.name }.toSet() + + 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 + } +} 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..35e270ebb7 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSyncAtStart.kt @@ -0,0 +1,121 @@ +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.zip.ZipFile +import kotlin.coroutines.cancellation.CancellationException + +/** + * Runs [BundleSync] 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 { + /** No check running; also the state before the plugin system starts. */ + IDLE, + + /** 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, + } + + private val logger = LoggerFactory.getLogger(BundleSyncAtStart::class.java) + private val mutableState = MutableStateFlow(State.IDLE) + val state: StateFlow = mutableState.asStateFlow() + + /** Call before launching the start-up coroutine, so a main screen that resumes first waits. */ + fun begin() { + mutableState.value = State.CHECKING + } + + /** Call when start-up is over, 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. + * Leaves [state] at [State.SYNCING] after a sync, for [end] to clear once failures are recorded. + */ + fun run( + context: Context, + manager: PluginManager, + ): Boolean = + try { + // Before setup has finished, the asset phase installs the bundle (ADFA-7238). + if (!areIdeToolsInstalled()) { + false + } else { + withBundleSource(context) { source -> syncIfNeeded(context, manager, source) } ?: false + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + logger.error("Could not apply the bundled add-ons", e) + false + } finally { + if (mutableState.value == State.CHECKING) end() + } + + private fun syncIfNeeded( + context: Context, + manager: PluginManager, + source: BundleSource, + ): Boolean { + val record = BundledAddonsRecord.inFilesDir(context.filesDir) + val uninstall = { pluginId: String -> + manager.uninstallPlugin(pluginId) + Unit + } + val sync = + BundleSync( + record = record, + installer = + BundledAddonInstaller( + pluginsDir = File(context.filesDir, "plugins"), + templatesDir = Environment.TEMPLATES_DIR, + readPluginId = { PluginLoader(context, it).getPluginMetadata()?.id }, + beforePluginMove = uninstall, + ), + templatesDir = Environment.TEMPLATES_DIR, + uninstallPlugin = uninstall, + ) + 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. A debug build reads the split assets zip; when that 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. + */ + private fun withBundleSource( + context: Context, + block: (BundleSource) -> T, + ): T? { + if (AssetsInstaller.CURRENT_INSTALLER is BundledAssetsInstaller) { + return block(AssetManagerBundleSource(context.assets)) + } + val zip = Environment.SPLIT_ASSETS_ZIP + if (!zip.isFile) return null + return ZipFile(zip).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 630421b3f6..02eb8ae8fe 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 @@ -33,6 +33,11 @@ class BundledAddonInstaller( private val pluginsDir: File, private val templatesDir: File, private val readPluginId: (File) -> String?, + /** + * Called with a valid plugin ID just before its copy is moved into place. A sync removes the + * installed builds of that ID here, so the new one does not sit beside them. + */ + private val beforePluginMove: (pluginId: String) -> Unit = {}, ) { fun install( kind: BundledAddonKind, @@ -73,6 +78,7 @@ class BundledAddonInstaller( if (name.toByteArray(Charsets.UTF_8).size > MAX_FILE_NAME_BYTES) { throw RejectedPluginException("its plugin ID is too long") } + beforePluginMove(id) 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..135361c460 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt @@ -0,0 +1,223 @@ +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() + + @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 + pluginsDir.listFiles { f -> f.name.endsWith(".cgp") && idOf(f) == pluginId }?.forEach { it.delete() } + } + + private fun sync(): BundleSync = + BundleSync( + record = record, + installer = BundledAddonInstaller(pluginsDir, templatesDir, ::idOf, beforePluginMove = ::uninstall), + templatesDir = templatesDir, + 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 `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 b29987ca32..ce38af31e6 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 that came with the app did not start:\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. From ae9e3c514851fb2f5f5bd02ee0dd3e918e549f9a Mon Sep 17 00:00:00 2001 From: ADFA Date: Sun, 22 Nov 2026 20:24:20 +0000 Subject: [PATCH 2/8] style: spotless reformat, no functional change --- .../java/com/itsaky/androidide/assets/addons/BundleSync.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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 index 1dd9258f53..d73158089a 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt @@ -46,7 +46,11 @@ class BundleSync( val pluginIds = installed.mapNotNull { it.pluginId }.toSet() val templateFiles = installed.filter { it.kind == BundledAddonKind.TEMPLATE }.mapNotNull { it.file?.name }.toSet() - old?.pluginIds.orEmpty().filterNot { it in pluginIds }.forEach(uninstallPlugin) + old + ?.pluginIds + .orEmpty() + .filterNot { it in pluginIds } + .forEach(uninstallPlugin) old ?.templateFiles .orEmpty() From 8a9569f5f9e174213c724f65b85f2fbbd48407a4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 20:38:31 +0000 Subject: [PATCH 3/8] ADFA-7239: Fix an always-true condition the -Werror build rejects `synced && manager != null`: synced is only true when manager is non-null, so the compiler flags the second test (CredentialProtectedApplicationLoader:393). Check the manager once around the sync, load and failure recording. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../CredentialProtectedApplicationLoader.kt | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) 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 56e7e3f65c..1d49132328 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -388,15 +388,17 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { GlobalScope.launch { try { val manager = pluginManager - val synced = manager != null && withContext(Dispatchers.IO) { BundleSyncAtStart.run(application, manager) } - manager?.loadPlugins() - if (synced && manager != null) { - // Plugins are loaded already; this only records the bundled ones that failed. - BundledPluginStartup( - record = BundledAddonsRecord.inFilesDir(application.filesDir), - reloadPlugins = {}, - loadError = manager::getLoadError, - ).start() + if (manager != null) { + val synced = 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") From e4f2a0ecba65837e26590eac22742f05b47dd159 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 20:58:44 +0000 Subject: [PATCH 4/8] ADFA-7239: Address the independent review - Keep an unchanged bundled plugin's state: a plugin whose bundled build is already the only one installed for its ID is copied over in place, and uninstallPlugin (which clears the enabled flag, crash count and caches) runs only for a real change of build. The hook now gets the target file name, and BundleSync builds the installer itself. - Fail the sync, keeping the old record, when an older build of a bundled ID cannot be deleted, so two builds never load together. - Close the start-up race: the state starts at NOT_STARTED, which the main screen waits through (up to 30 s) as well as CHECKING, so a screen that resumes before the plugin system starts still shows the bar and the report. A plugin system that fails to start ends the wait. - Sync at most once per process, even if a failed start-up is retried. - Record a failed sync for the error bar instead of only logging it. - Tests: an unchanged plugin is not uninstalled; a changed build goes through uninstall; an undeletable old build fails the sync and keeps the record; a sync cut short converges; a missing record removes no user add-on; a debug build without its zip does not sync; a release build reads the APK assets. - ARCHITECTURE.md updated. Not compiled or tested in this environment (no Android SDK). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- ARCHITECTURE.md | 2 +- .../androidide/activities/MainActivity.kt | 10 +- .../CredentialProtectedApplicationLoader.kt | 2 + .../androidide/assets/addons/BundleSync.kt | 47 +++++++++- .../assets/addons/BundleSyncAtStart.kt | 82 +++++++++-------- .../assets/addons/BundledAddonInstaller.kt | 9 +- .../assets/addons/BundleSyncTest.kt | 92 ++++++++++++++++++- 7 files changed, 195 insertions(+), 49 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index e777485cc8..6d16e3c87b 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`. A missing or empty folder is the thin build, whose output is unchanged. 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`), 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 installed build of a bundled plugin ID 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. `MainActivity` shows a progress bar while a sync runs, then the error bar. +- **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`. A missing or empty folder is the thin build, whose output is unchanged. 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`), 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 7c4b08bc6d..3ad06155ed 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -100,6 +100,7 @@ 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 @@ -383,7 +384,11 @@ class MainActivity : EdgeToEdgeIDEActivity() { private suspend fun awaitBundleSync() { val syncState = BundleSyncAtStart.state - syncState.first { it != BundleSyncAtStart.State.CHECKING } + // 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 { @@ -865,5 +870,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/app/CredentialProtectedApplicationLoader.kt b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt index 1d49132328..80f5ca7490 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -411,6 +411,8 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { } 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 index d73158089a..3ccebb2943 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt @@ -1,6 +1,8 @@ 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 @@ -12,19 +14,24 @@ import java.io.File * 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. * - * The record is written last, so a sync cut short runs again at the next start; installing a - * bundle twice gives the same files. + * 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. * - * @param installer copies one bundled file; built with [uninstallPlugin] as its - * `beforePluginMove`, so an older build of the same ID is gone before the new one lands. + * 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 installer: BundledAddonInstaller, + 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) @@ -71,4 +78,34 @@ class BundleSync( 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 index 35e270ebb7..5ba9808743 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSyncAtStart.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSyncAtStart.kt @@ -12,87 +12,96 @@ 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] 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. + * 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 { - /** No check running; also the state before the plugin system starts. */ - IDLE, + /** 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.IDLE) + private val mutableState = MutableStateFlow(State.NOT_STARTED) + private val claimed = AtomicBoolean(false) val state: StateFlow = mutableState.asStateFlow() - /** Call before launching the start-up coroutine, so a main screen that resumes first waits. */ + /** Call before launching the start-up coroutine. */ fun begin() { mutableState.value = State.CHECKING } - /** Call when start-up is over, whatever happened. */ + /** 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. - * Leaves [state] at [State.SYNCING] after a sync, for [end] to clear once failures are recorded. + * 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 = - try { + ): 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 { - withBundleSource(context) { source -> syncIfNeeded(context, manager, source) } ?: false + 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 record = BundledAddonsRecord.inFilesDir(context.filesDir) - val uninstall = { pluginId: String -> - manager.uninstallPlugin(pluginId) - Unit - } val sync = BundleSync( record = record, - installer = - BundledAddonInstaller( - pluginsDir = File(context.filesDir, "plugins"), - templatesDir = Environment.TEMPLATES_DIR, - readPluginId = { PluginLoader(context, it).getPluginMetadata()?.id }, - beforePluginMove = uninstall, - ), + pluginsDir = File(context.filesDir, "plugins"), templatesDir = Environment.TEMPLATES_DIR, - uninstallPlugin = uninstall, + readPluginId = { PluginLoader(context, it).getPluginMetadata()?.id }, + uninstallPlugin = { manager.uninstallPlugin(it) }, ) val entries = BundledAddons.list(source) if (!sync.isNeeded(entries)) return false @@ -103,19 +112,18 @@ object BundleSyncAtStart { } /** - * Runs [block] on the build's bundle. A debug build reads the split assets zip; when that 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. + * 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. */ - private fun withBundleSource( - context: Context, + internal fun withBundleSource( + release: Boolean, + splitZip: File, + assets: () -> BundleSource, block: (BundleSource) -> T, ): T? { - if (AssetsInstaller.CURRENT_INSTALLER is BundledAssetsInstaller) { - return block(AssetManagerBundleSource(context.assets)) - } - val zip = Environment.SPLIT_ASSETS_ZIP - if (!zip.isFile) return null - return ZipFile(zip).use { block(ZipBundleSource(it)) } + 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 02eb8ae8fe..7fdfa5803a 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 @@ -34,10 +34,11 @@ class BundledAddonInstaller( private val templatesDir: File, private val readPluginId: (File) -> String?, /** - * Called with a valid plugin ID just before its copy is moved into place. A sync removes the - * installed builds of that ID here, so the new one does not sit beside them. + * 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) -> Unit = {}, + private val beforePluginMove: (pluginId: String, fileName: String) -> Unit = { _, _ -> }, ) { fun install( kind: BundledAddonKind, @@ -78,7 +79,7 @@ class BundledAddonInstaller( if (name.toByteArray(Charsets.UTF_8).size > MAX_FILE_NAME_BYTES) { throw RejectedPluginException("its plugin ID is too long") } - beforePluginMove(id) + 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 index 135361c460..4745f79a43 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt @@ -20,6 +20,9 @@ class BundleSyncTest { 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") @@ -38,14 +41,16 @@ class BundleSyncTest { /** 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, - installer = BundledAddonInstaller(pluginsDir, templatesDir, ::idOf, beforePluginMove = ::uninstall), + pluginsDir = pluginsDir, templatesDir = templatesDir, + readPluginId = ::idOf, uninstallPlugin = ::uninstall, ) @@ -212,6 +217,91 @@ class BundleSyncTest { 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 `old failures are dropped with the old bundle`() { run(FakeSource(plugins = mapOf("bad.cgp" to "no id here"))) From 39f712ec835cf560011b9e7bce981e04c09df48d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 21:43:57 +0000 Subject: [PATCH 5/8] ADFA-7239: Keep the old bundled add-ons when a copy is rejected A copy rejected for its content or manifest is not known by plugin ID, so it may be a recorded add-on the new bundle still contains. Removing recorded IDs the new set lacks would then uninstall the user's working build of it. When any copy is rejected, skip the removals; the rejection is reported, and the next bundle change removes what is left over. Test: a rejected copy keeps the old bundled add-ons. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../androidide/assets/addons/BundleSync.kt | 24 +++++++++++-------- .../assets/addons/BundleSyncTest.kt | 12 ++++++++++ 2 files changed, 26 insertions(+), 10 deletions(-) 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 index 3152622658..da5bd0e175 100644 --- a/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt +++ b/app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt @@ -53,16 +53,20 @@ class BundleSync( val pluginIds = installed.mapNotNull { it.pluginId }.toSet() val templateFiles = installed.filter { it.kind == BundledAddonKind.TEMPLATE }.mapNotNull { it.file?.name }.toSet() - 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() } + // 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( 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 index 4745f79a43..a99a6cfc01 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt @@ -302,6 +302,18 @@ class BundleSyncTest { 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 `old failures are dropped with the old bundle`() { run(FakeSource(plugins = mapOf("bad.cgp" to "no id here"))) From 90731e8f1aff36192561882a082cba67798d607a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 22:18:40 +0000 Subject: [PATCH 6/8] ADFA-7239: Test that a copy not matching the bundle index keeps the old build A sync passes each entry's SHA-256 to the installer (0a5e4f0); this pins it: a copy whose content does not match is reported, the installed build stays, and nothing of that ID is uninstalled. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../androidide/assets/addons/BundleSyncTest.kt | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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 index a99a6cfc01..ace410855e 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt @@ -314,6 +314,19 @@ class BundleSyncTest { 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"))) From 78fc586f989dfc54fc97a449e3c7c4c76e10dc7e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 22:21:58 +0000 Subject: [PATCH 7/8] ADFA-7239: Wrap a test line over ktlint's 140-character limit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../com/itsaky/androidide/assets/addons/BundleSyncTest.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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 index ace410855e..6e28ecb9c2 100644 --- a/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt +++ b/app/src/test/java/com/itsaky/androidide/assets/addons/BundleSyncTest.kt @@ -317,7 +317,11 @@ class BundleSyncTest { @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 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) From 2b395c18f960aa4a4e1ae2fb72f6edb04d101a3f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:37:27 +0000 Subject: [PATCH 8/8] ADFA-7239: Run the start-up sync under the plugin load lock Stage (merged through feature/ADFA-7238) added PluginManager.whileNotLoading, which Add-ons Manager installs and uninstalls use so a load cannot run while a plugin file is swapped. Wrap the start-up sync in it too: it uninstalls and replaces plugin files. This closes the accepted limitation that the sync's uninstalls were not serialized with a loadPlugins() started elsewhere. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZ6QqzwTmigaKYLNVw --- .../androidide/app/CredentialProtectedApplicationLoader.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 80f5ca7490..93829b449b 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -389,7 +389,9 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { try { val manager = pluginManager if (manager != null) { - val synced = withContext(Dispatchers.IO) { BundleSyncAtStart.run(application, manager) } + // 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.