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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>` and `templates/<name>` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-<arch>.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 `<pluginId>-<hash>.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/<name>` and `templates/<name>` (`StageBundledAddons` in `app/build.gradle.kts`), and `createAssetsZip()` adds the same entries to the debug `assets-<arch>.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 `<pluginId>-<hash>.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-<arch>.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/<abi>/*.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).
Expand Down
28 changes: 28 additions & 0 deletions app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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()
Expand Down Expand Up @@ -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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
}
}

Expand Down
115 changes: 115 additions & 0 deletions app/src/main/java/com/itsaky/androidide/assets/addons/BundleSync.kt
Original file line number Diff line number Diff line change
@@ -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<BundledEntry>): 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<BundledEntry>,
): 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<File> =
pluginsDir
.listFiles { file ->
file.isFile &&
file.name != fileName &&
file.name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true) &&
runCatching { readPluginId(file) }.getOrNull() == pluginId
}.orEmpty()
.toList()
}
Loading
Loading