Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
6b783e2
ADFA-3570: Let plugins hear project open/close and file saves
davidschachterADFA Nov 11, 2026
197b98e
ADFA-3570: Report project open/close and saves to plugin listeners
davidschachterADFA Nov 11, 2026
a303589
ADFA-3570: Document the project lifecycle and file save listeners
davidschachterADFA Nov 11, 2026
cdefb2f
Merge branch 'stage' into feature/ADFA-3570
davidschachterADFA Nov 11, 2026
2ccf7a9
ADFA-3570: Address code review of the workspace listeners
davidschachterADFA Nov 11, 2026
b956d90
ADFA-3570: Close the project the editor opened, and say opens are async
davidschachterADFA Nov 11, 2026
157ef09
ADFA-3570: Pair the plugin open report and its close under one lock
davidschachterADFA Nov 11, 2026
84fc629
Merge branch 'stage' into feature/ADFA-3570
davidschachterADFA Nov 12, 2026
829e44f
ADFA-3570: Keep a loaded plugin's instance when plugins load again
davidschachterADFA Nov 12, 2026
57e19ff
ADFA-3570: Load plugins one at a time, and swap files between loads
davidschachterADFA Nov 12, 2026
0d447a1
ADFA-3570: Use Truth in this PR's plugin-manager tests
davidschachterADFA Nov 13, 2026
835cbb2
ADFA-3570: Make the plugin listener registry safe across threads
davidschachterADFA Nov 13, 2026
7ae63f1
ADFA-3570: Bound the plugin load lock's wait; catch LinkageError in i…
davidschachterADFA Nov 13, 2026
225553f
ADFA-3570: Show the still-loaded install error from a string resource
davidschachterADFA Nov 13, 2026
4fa72b1
Merge branch 'stage' into feature/ADFA-3570
davidschachterADFA Nov 13, 2026
969f5be
ADFA-3570: Never leak the plugin load lock when its wait times out
davidschachterADFA Nov 13, 2026
29d0772
ADFA-3570: Report saves after markUnmodified; say what the registry g…
davidschachterADFA Nov 13, 2026
269162a
Merge branch 'stage' into feature/ADFA-3570
davidschachterADFA Nov 14, 2026
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 @@ -65,7 +65,7 @@ The optional file path is attacker-controllable (a URL segment), so it's resolve

Whether the open project *can* be named at all is `isDeepLinkTargetOfOpenProject` (`ProjectValidations.kt`): a link can only ever resolve to `<projectsRoot>/<name>`, but a project can be opened from anywhere. Its `deepLinkTargetOfOpenProjectWithoutIo` half exists so a caller on the main thread can settle the common case — equal path strings name the same directory — without the `canonicalPath` calls the full rule needs. `CreateLinkAction` sends its residue to `Dispatchers.IO` rather than to the StrictMode whitelist (ADR 0007); the two older callers (`EditorHandlerActivity.onNewIntent`, `BaseEditorActivity.onCreate`) still fall through to `canonicalPath` on the main thread and have not been migrated, so the shortcut narrows that exposure rather than removing it.

**Project session lifecycle: language servers stop before the project is destroyed, and only when the editor finishes.** Closing a project runs one teardown from `ProjectHandlerActivity.onPause` while the activity finishes (`ProjectSessionCloser`, with a `preDestroy` fallback for a `finish()` that arrives while already paused). Its order is the contract: (1) every language server's `shutdown()`, which must not block; (2) `ProjectManagerImpl.destroy()`, which ends the `IndexingServiceManager`'s session lifetime at once and closes its services and `IndexRegistry` in the background; (3) the Quick Build session restart. The next project's manager waits for that background close before it reopens the index databases, which are global files. Work the old session still has in flight may touch its closed indexes: reads return empty results, and `SQLiteIndex` logs that at DEBUG because the lifetime has ended (use after close in a live session stays ERROR, since it is a real bug). A closed registry refuses new indexes with `IndexRegistryClosedException`, which the Kotlin server's `CompilerSession` treats as the end of an update, not a failure. Each Kotlin project update binds one manager, under the same lock as its shutdown check, so a closing session never reads or writes the next session's indexes. A configuration change (rotation, font scale, dark mode) never runs the teardown: `isFinishing` is false, and servers and indexes survive the recreation. Other readers of the global `ProjectManagerImpl.indexingServiceManager` (the project setup, `GradleBuildService`, the Java and XML class lookups) are not bound to a session yet; a manager that sees a sync before any service registers retries setup on the next sync instead of staying empty.
**Project session lifecycle: language servers stop before the project is destroyed, and only when the editor finishes.** Closing a project runs one teardown from `ProjectHandlerActivity.onPause` while the activity finishes (`ProjectSessionCloser`, with a `preDestroy` fallback for a `finish()` that arrives while already paused). It first reports the close to plugins (`PluginWorkspaceEvents.projectClosed`, which only queues `onProjectClosed` on the plugins' own thread), but only for the directory this editor reported open, kept in `EditorViewModel`. This path, and the open and save reports beside it, call the plugin manager directly rather than through EventBus: no event marks a project open or close, and `DocumentSaveEvent` is also posted on every Enter, with nothing written. After that, its order is the contract: (1) every language server's `shutdown()`, which must not block; (2) `ProjectManagerImpl.destroy()`, which ends the `IndexingServiceManager`'s session lifetime at once and closes its services and `IndexRegistry` in the background; (3) the Quick Build session restart. The next project's manager waits for that background close before it reopens the index databases, which are global files. Work the old session still has in flight may touch its closed indexes: reads return empty results, and `SQLiteIndex` logs that at DEBUG because the lifetime has ended (use after close in a live session stays ERROR, since it is a real bug). A closed registry refuses new indexes with `IndexRegistryClosedException`, which the Kotlin server's `CompilerSession` treats as the end of an update, not a failure. Each Kotlin project update binds one manager, under the same lock as its shutdown check, so a closing session never reads or writes the next session's indexes. A configuration change (rotation, font scale, dark mode) never runs the teardown: `isFinishing` is false, and servers and indexes survive the recreation. Other readers of the global `ProjectManagerImpl.indexingServiceManager` (the project setup, `GradleBuildService`, the Java and XML class lookups) are not bound to a session yet; a manager that sees a sync before any service registers retries setup on the next sync instead of staying empty.

**Gradle build output lives in app storage, not the project folder (ADFA-4930).** Projects sit on shared storage (`/sdcard`), which Android serves through FUSE, so every file a build writes pays a user-space round trip. Each project's build output goes to `noBackupFilesDir/gradle-build/<projectKey>/` (`services/builder/BuildOutputLocation`), keyed like Quick Build's scratch (`ProjectStorageKey` in `:shared`):
- `main/<name>-<hash>/` per Gradle project (`<hash>` of its full path, so `:core:ui` is not inside `:core`'s output); nested builds get their own key. The init script plugin sets `layout.buildDirectory` from `-Pcotg.build.outputDir` (`gradle-plugin/.../BuildOutputRedirect`).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import com.itsaky.androidide.actions.markInvisible
import com.itsaky.androidide.activities.ExternalFileInstallActivity
import com.itsaky.androidide.activities.editor.EditorHandlerActivity
import com.itsaky.androidide.repositories.PluginRepository
import com.itsaky.androidide.repositories.PluginStillLoadedException
import com.itsaky.androidide.resources.R
import com.itsaky.androidide.utils.DialogUtils
import com.itsaky.androidide.utils.fileProviderUriFor
Expand Down Expand Up @@ -108,7 +109,13 @@ class InstallFileAction(
flashSuccess(getString(R.string.msg_plugin_installed_restart))
DialogUtils.showRestartPrompt(this@doAction)
}.onFailure { e ->
flashError(getString(R.string.msg_plugin_install_failed, e.message))
flashError(
if (e is PluginStillLoadedException) {
getString(R.string.msg_plugin_install_still_loaded, e.pluginId)
} else {
getString(R.string.msg_plugin_install_failed, e.message)
},
)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import com.itsaky.androidide.plugins.extensions.ProjectSearchExtension
import com.itsaky.androidide.plugins.extensions.ProjectSearchRequest
import com.itsaky.androidide.plugins.extensions.ProjectSearchResult
import com.itsaky.androidide.plugins.extensions.ProjectSearchSection
import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents
import com.itsaky.androidide.projects.IProjectManager
import com.itsaky.androidide.projects.ProjectManagerImpl
import com.itsaky.androidide.projects.builder.BuildService
Expand All @@ -94,6 +95,7 @@ import com.itsaky.androidide.quickbuild.QuickBuildWontStayUpRestart
import com.itsaky.androidide.quickbuild.quickBuildStatusBarUpdate
import com.itsaky.androidide.quickbuild.resolve
import com.itsaky.androidide.repositories.PluginRepository
import com.itsaky.androidide.repositories.PluginStillLoadedException
import com.itsaky.androidide.resources.R.string
import com.itsaky.androidide.search.replace.ReplaceCoordinator
import com.itsaky.androidide.search.replace.ReplaceHost
Expand Down Expand Up @@ -282,6 +284,9 @@ abstract class ProjectHandlerActivity :
const val STATE_KEY_SHOULD_INITIALIZE = "ide.editor.isInitializing"

private const val PLUGIN_SEARCH_TIMEOUT_SECONDS = 10L

// Pairs each editor's plugin open report with its close; see initializeProject.
private val pluginProjectLock = Any()
}

abstract fun doCloseAll()
Expand Down Expand Up @@ -1156,10 +1161,14 @@ abstract class ProjectHandlerActivity :
showRestartPrompt(this@ProjectHandlerActivity)
}.onFailure { error ->
flashError(
getString(
string.msg_plugin_install_failed,
error.message ?: "Unknown error",
),
if (error is PluginStillLoadedException) {
getString(string.msg_plugin_install_still_loaded, error.pluginId)
} else {
getString(
string.msg_plugin_install_failed,
error.message ?: "Unknown error",
)
},
)
}
setStatus("")
Expand Down Expand Up @@ -1191,6 +1200,15 @@ abstract class ProjectHandlerActivity :
}

private fun closeProjectSession() {
// Only the live editor's teardown reports the close; a doomed instance (onPause) does not.
synchronized(pluginProjectLock) {
editorViewModel.pluginOpenedProjectDir?.let { dir ->
// Reporting to plugins must never stop the editor's teardown.
runCatching { PluginWorkspaceEvents.getInstance().projectClosed(dir) }
.onFailure { logger.error("Failed to report a project close to plugins", it) }
}
editorViewModel.pluginOpenedProjectDir = null
}
stopLanguageServers()
closeProjectState()
}
Expand Down Expand Up @@ -1591,6 +1609,19 @@ abstract class ProjectHandlerActivity :
handleMissingProjectDirectory(projectDir)
return@launch
}
// As the editor starts opening the project; the sync below does not wait for listeners.
// A re-sync of the same project is not reported again. Not from an editor already tearing
// down: a late initialize after its close was reported would reopen a closed project.
// Under the lock the close takes: this runs on Dispatchers.Default and can race onPause's
// teardown, which would otherwise read no open project between the report and the record.
synchronized(pluginProjectLock) {
if (!isDestroying && !isFinishing) {
// The directory as plugins heard it, so the close compares it without touching the disk.
runCatching { PluginWorkspaceEvents.getInstance().projectOpened(projectDir) }
.onSuccess { editorViewModel.pluginOpenedProjectDir = it }
.onFailure { logger.error("Failed to report a project open to plugins", it) }
}
}

val needsSync =
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ class PluginRepositoryImpl(
?: throw IllegalStateException("Plugin system not available")

Log.d(TAG, "Uninstalling plugin: $pluginId")
val result = manager.uninstallPlugin(pluginId)
result
// A load already under way could otherwise load the plugin again after it was removed.
manager.whileNotLoading { manager.uninstallPlugin(pluginId) }
}.onFailure { exception ->
Log.e(TAG, "Failed to uninstall plugin: $pluginId", exception)
}
Expand Down Expand Up @@ -135,13 +135,6 @@ class PluginRepositoryImpl(
}
}

try {
manager.uninstallPlugin(pluginId)
Log.d(TAG, "Uninstalled existing version of plugin: $pluginId")
} catch (e: Exception) {
Log.w(TAG, "Error uninstalling existing plugin: ${e.message}")
}

val fileExtension =
if (pluginFile.name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true)) ".$PLUGIN_ARCHIVE_EXTENSION" else ".apk"
val finalFileName = "${pluginId}$fileExtension"
Expand All @@ -152,13 +145,25 @@ class PluginRepositoryImpl(

val finalFile = File(pluginsDir, finalFileName)

try {
pluginFile.copyTo(finalFile, overwrite = true)
Log.d(TAG, "Plugin file copied to: ${finalFile.absolutePath}")
pluginFile.delete()
} catch (e: Exception) {
Log.e(TAG, "Failed to copy plugin file to plugins directory", e)
throw e
// No load may run between the unload and the copy: it could load the old file again.
manager.whileNotLoading {
try {
manager.uninstallPlugin(pluginId)
Log.d(TAG, "Uninstalled existing version of plugin: $pluginId")
} catch (e: Exception) {
Log.w(TAG, "Error uninstalling existing plugin: ${e.message}")
}
// loadPlugins() keeps a plugin that is still loaded, so the new file would never load.
if (manager.getPlugin(pluginId) != null) throw PluginStillLoadedException(pluginId)

try {
pluginFile.copyTo(finalFile, overwrite = true)
Log.d(TAG, "Plugin file copied to: ${finalFile.absolutePath}")
pluginFile.delete()
} catch (e: Exception) {
Log.e(TAG, "Failed to copy plugin file to plugins directory", e)
throw e
}
}

manager.loadPlugins()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.itsaky.androidide.repositories

/**
* Installing [pluginId] found its installed version still loaded after uninstalling it, so the new
* file was not put in place: loading skips a plugin that is already loaded. Shown to the user as
* `msg_plugin_install_still_loaded`.
*/
class PluginStillLoadedException(
val pluginId: String,
) : IllegalStateException("The installed version of $pluginId could not be unloaded")
14 changes: 12 additions & 2 deletions app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import com.itsaky.androidide.lsp.java.JavaLanguageServer
import com.itsaky.androidide.lsp.kotlin.KotlinLanguageServer
import com.itsaky.androidide.lsp.xml.XMLLanguageServer
import com.itsaky.androidide.models.Range
import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents
import com.itsaky.androidide.preferences.internal.EditorPreferences
import com.itsaky.androidide.syntax.colorschemes.SchemeAndroidIDE
import com.itsaky.androidide.tasks.cancelIfActive
Expand Down Expand Up @@ -415,8 +416,17 @@ class CodeEditorView(
_binding?.rwProgress?.isVisible = false
}

markUnmodified()
notifySaved()
try {
markUnmodified()
notifySaved()
} finally {
// Here, not from DocumentSaveEvent: the editor also posts that on every Enter, with nothing
// written. After markUnmodified(), so a listener asking whether the file is modified hears
// no; in finally, because that throws once the tab is closed mid-save, though the file is
// written. A failure here must not fail the save.
runCatching { PluginWorkspaceEvents.getInstance().fileSaved(file) }
.onFailure { log.error("Failed to report a save to plugins", it) }
}

return true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,15 @@ class EditorViewModel : ViewModel() {
_isInternalBuildInProgress.value = value
}

/**
* The project directory this editor last reported open to plugins, as
* `PluginWorkspaceEvents.projectOpened` returned it (canonical). Held here rather than on the
* activity so a recreated editor closes the project its predecessor opened, and rather than read
* from the global project path, which a pending project switch may already have changed.
*/
@Volatile
var pluginOpenedProjectDir: File? = null

var isInitializing: Boolean
get() = _isInitializing.value ?: false
set(value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.itsaky.androidide.plugins.PluginInfo
import com.itsaky.androidide.repositories.PluginRepository
import com.itsaky.androidide.repositories.PluginStillLoadedException
import com.itsaky.androidide.resources.R
import com.itsaky.androidide.ui.models.PluginInstallSource
import com.itsaky.androidide.ui.models.PluginManagerUiEffect
Expand Down Expand Up @@ -421,10 +422,14 @@ class PluginManagerViewModel(
}.onFailure { exception ->
Log.e(TAG, "Failed to install plugin", exception)
_uiEffect.send(
PluginManagerUiEffect.ShowError(
R.string.msg_plugin_install_failed,
listOf(exception.message ?: ""),
),
if (exception is PluginStillLoadedException) {
PluginManagerUiEffect.ShowError(R.string.msg_plugin_install_still_loaded, listOf(exception.pluginId))
} else {
PluginManagerUiEffect.ShowError(
R.string.msg_plugin_install_failed,
listOf(exception.message ?: ""),
)
},
)
// A failed install deletes nothing but our own disposable temp copy - a
// user-picked PickedUri is preserved so they can retry, matching
Expand Down
13 changes: 13 additions & 0 deletions docs/PLUGIN_API_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ need a source change, a recompile, or both · `tooling` = API-stability
milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed]**
= diffed from `plugin-api/src` history (predates the dump; symbol-accurate).

### 26.47 — unreleased
- **added — Hear the editor open and close a project, and save a file** _(ADFA-3570)_ **[verified]**
`IdeProjectService.addProjectLifecycleListener(ProjectLifecycleListener)` calls
`onProjectOpened(projectDir)` when the editor starts opening a project (its sync does not wait
for listeners), and
`onProjectClosed(projectDir)` when it closes one; a re-sync is not another open, and switching
projects reports the close first. `IdeEditorService.addFileSaveListener(FileSaveListener)` calls
`onFileSaved(file)` after each file the editor writes, whoever asked for the save. Both need
`filesystem.read`. Calls arrive in order on one background thread shared by every plugin, so
return quickly. The IDE drops the listeners when the plugin is disabled or unloads, so register
them from `activate()`. A listener added while a project is open hears `onProjectOpened` for it
first. Paths are canonical. Floor `plugin.min_ide_version` at `26.47` to use them.

### 26.43 — unreleased
- **tooling — Interface bodies are Java default methods again** _(ADFA-6560)_ **[verified]**
Since ADFA-4058 (May 2026) pinned `languageVersion`, `plugin-api` compiled each Kotlin interface
Expand Down
Loading
Loading