From 6b783e224d6553b33897a3762663b813fb07da58 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 12:18:00 -0800 Subject: [PATCH 01/14] ADFA-3570: Let plugins hear project open/close and file saves Plugins had no supported way to react when the editor opens or closes a project or saves a file: the IDE's EventBus is not part of the plugin API contract. Add two listener types on the host services: - IdeProjectService.add/removeProjectLifecycleListener (onProjectOpened / onProjectClosed) - IdeEditorService.add/removeFileSaveListener (onFileSaved) Both need filesystem.read. PluginWorkspaceEvents fans the events out on one background thread, in order, isolating each listener's failures (Throwable, so a stale plugin's NoSuchMethodError cannot stop the rest). A re-sync is not a second open; switching projects reports the close first. PluginManager drops a plugin's listeners on disable and unload. The ABI change is additive: new interfaces and defaulted methods on host-implemented services. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- plugin-api/api/plugin-api.api | 17 + .../plugins/services/IdeServices.kt | 55 ++++ .../plugins/manager/core/PluginManager.kt | 5 + .../manager/services/IdeEditorServiceImpl.kt | 11 + .../manager/services/IdeProjectServiceImpl.kt | 13 + .../manager/services/PluginWorkspaceEvents.kt | 138 ++++++++ .../services/PluginWorkspaceEventsTest.kt | 301 ++++++++++++++++++ 7 files changed, 540 insertions(+) create mode 100644 plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt create mode 100644 plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt diff --git a/plugin-api/api/plugin-api.api b/plugin-api/api/plugin-api.api index df35e7d108..412049157e 100644 --- a/plugin-api/api/plugin-api.api +++ b/plugin-api/api/plugin-api.api @@ -1686,6 +1686,10 @@ public abstract interface class com/itsaky/androidide/plugins/services/FileChang public abstract fun onFileChanged (Ljava/io/File;)V } +public abstract interface class com/itsaky/androidide/plugins/services/FileSaveListener { + public abstract fun onFileSaved (Ljava/io/File;)V +} + public abstract interface class com/itsaky/androidide/plugins/services/GradleSyncCallback { public abstract fun onComplete (ZLjava/lang/String;)V } @@ -1806,6 +1810,7 @@ public final class com/itsaky/androidide/plugins/services/IdeCommandService$Defa public abstract interface class com/itsaky/androidide/plugins/services/IdeEditorService { public fun addContentChangeListener (Lcom/itsaky/androidide/plugins/services/EditorContentChangeListener;)V public abstract fun addFileChangeListener (Lcom/itsaky/androidide/plugins/services/FileChangeListener;)V + public fun addFileSaveListener (Lcom/itsaky/androidide/plugins/services/FileSaveListener;)V public abstract fun appendToLine (Ljava/io/File;ILjava/lang/String;)Z public fun clearPeerCursors (Ljava/io/File;)V public abstract fun deleteLine (Ljava/io/File;I)Z @@ -1834,6 +1839,7 @@ public abstract interface class com/itsaky/androidide/plugins/services/IdeEditor public abstract fun prependToLine (Ljava/io/File;ILjava/lang/String;)Z public fun removeContentChangeListener (Lcom/itsaky/androidide/plugins/services/EditorContentChangeListener;)V public abstract fun removeFileChangeListener (Lcom/itsaky/androidide/plugins/services/FileChangeListener;)V + public fun removeFileSaveListener (Lcom/itsaky/androidide/plugins/services/FileSaveListener;)V public abstract fun replaceLine (Ljava/io/File;ILjava/lang/String;)Z public abstract fun replaceRange (Ljava/io/File;Lcom/itsaky/androidide/plugins/services/SelectionRange;Ljava/lang/String;)Z public abstract fun replaceSelection (Ljava/lang/String;)Z @@ -1845,10 +1851,12 @@ public abstract interface class com/itsaky/androidide/plugins/services/IdeEditor public final class com/itsaky/androidide/plugins/services/IdeEditorService$DefaultImpls { public static fun addContentChangeListener (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Lcom/itsaky/androidide/plugins/services/EditorContentChangeListener;)V + public static fun addFileSaveListener (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Lcom/itsaky/androidide/plugins/services/FileSaveListener;)V public static fun clearPeerCursors (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/io/File;)V public static fun dismissInlineSuggestion (Lcom/itsaky/androidide/plugins/services/IdeEditorService;)V public static fun hidePeerCursor (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/io/File;Ljava/lang/String;)Z public static fun removeContentChangeListener (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Lcom/itsaky/androidide/plugins/services/EditorContentChangeListener;)V + public static fun removeFileSaveListener (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Lcom/itsaky/androidide/plugins/services/FileSaveListener;)V public static fun saveFile (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/io/File;Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public static fun showInlineSuggestion (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/lang/String;)V public static fun showPeerCursor (Lcom/itsaky/androidide/plugins/services/IdeEditorService;Ljava/io/File;IILjava/lang/String;Ljava/lang/String;I)Z @@ -1907,16 +1915,20 @@ public final class com/itsaky/androidide/plugins/services/IdeProjectManipulation } public abstract interface class com/itsaky/androidide/plugins/services/IdeProjectService { + public fun addProjectLifecycleListener (Lcom/itsaky/androidide/plugins/services/ProjectLifecycleListener;)V public abstract fun getAllProjects ()Ljava/util/List; public abstract fun getCurrentProject ()Lcom/itsaky/androidide/plugins/extensions/IProject; public fun getModuleContext (Ljava/lang/String;)Lcom/itsaky/androidide/plugins/services/ModuleContext; public abstract fun getProjectByPath (Ljava/io/File;)Lcom/itsaky/androidide/plugins/extensions/IProject; public fun openProject (Ljava/io/File;)Z + public fun removeProjectLifecycleListener (Lcom/itsaky/androidide/plugins/services/ProjectLifecycleListener;)V } public final class com/itsaky/androidide/plugins/services/IdeProjectService$DefaultImpls { + public static fun addProjectLifecycleListener (Lcom/itsaky/androidide/plugins/services/IdeProjectService;Lcom/itsaky/androidide/plugins/services/ProjectLifecycleListener;)V public static fun getModuleContext (Lcom/itsaky/androidide/plugins/services/IdeProjectService;Ljava/lang/String;)Lcom/itsaky/androidide/plugins/services/ModuleContext; public static fun openProject (Lcom/itsaky/androidide/plugins/services/IdeProjectService;Ljava/io/File;)Z + public static fun removeProjectLifecycleListener (Lcom/itsaky/androidide/plugins/services/IdeProjectService;Lcom/itsaky/androidide/plugins/services/ProjectLifecycleListener;)V } public abstract interface class com/itsaky/androidide/plugins/services/IdeSidebarService { @@ -2267,6 +2279,11 @@ public final class com/itsaky/androidide/plugins/services/ModuleContext { public fun toString ()Ljava/lang/String; } +public abstract interface class com/itsaky/androidide/plugins/services/ProjectLifecycleListener { + public abstract fun onProjectClosed (Ljava/io/File;)V + public abstract fun onProjectOpened (Ljava/io/File;)V +} + public abstract class com/itsaky/androidide/plugins/services/QuickBuildAvailability { } diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt index 6a49bd6631..b96d8ddb71 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt @@ -63,6 +63,47 @@ interface IdeProjectService { * @return The module context, or null if no module can be resolved */ fun getModuleContext(filePath: String): ModuleContext? = null + + /** + * Registers [listener] to hear when the editor opens and closes a project. A listener added + * while a project is open hears nothing about it until it closes; ask [getCurrentProject] for + * the project already open. Registering the same listener twice has no effect. The IDE drops + * the listener when the plugin is disabled or unloads, so register it from + * [com.itsaky.androidide.plugins.IPlugin.activate]. Available since 26.47. + * + * Requires the FILESYSTEM_READ permission. + * + * @throws SecurityException if the plugin lacks FILESYSTEM_READ. + */ + fun addProjectLifecycleListener(listener: ProjectLifecycleListener) {} + + /** Unregisters a listener added with [addProjectLifecycleListener]. Available since 26.47. */ + fun removeProjectLifecycleListener(listener: ProjectLifecycleListener) {} +} + +/** + * Hears the editor open and close a project. Calls arrive in order on one background thread + * shared by every plugin, so return quickly and hand slow work to your own thread. + * Available since 26.47. + */ +interface ProjectLifecycleListener { + /** + * The editor opened the project rooted at [projectDir] and is about to sync it. A sync or + * build of the same project later does not call this again. + */ + fun onProjectOpened(projectDir: File) + + /** The editor closed the project rooted at [projectDir]. */ + fun onProjectClosed(projectDir: File) +} + +/** + * Hears the editor write a file to disk: the user saving, the IDE saving before a build, or a + * plugin calling [IdeEditorService.saveFile]. Calls arrive in order on one background thread + * shared by every plugin, so return quickly. Available since 26.47. + */ +fun interface FileSaveListener { + fun onFileSaved(file: File) } /** @@ -287,6 +328,20 @@ interface IdeEditorService { */ fun removeContentChangeListener(listener: EditorContentChangeListener) {} + /** + * Registers [listener] to hear each file the editor saves. Registering the same listener twice + * has no effect. The IDE drops the listener when the plugin is disabled or unloads, so register + * it from [com.itsaky.androidide.plugins.IPlugin.activate]. Available since 26.47. + * + * Requires the FILESYSTEM_READ permission. + * + * @throws SecurityException if the plugin lacks FILESYSTEM_READ. + */ + fun addFileSaveListener(listener: FileSaveListener) {} + + /** Unregisters a listener added with [addFileSaveListener]. Available since 26.47. */ + fun removeFileSaveListener(listener: FileSaveListener) {} + /** * Shows an inline suggestion (ghost text) at the cursor position. * The suggestion is displayed semi-transparently and can be dismissed. diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 1fb0ebe0dd..33a2c5b654 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -60,6 +60,7 @@ import com.itsaky.androidide.plugins.manager.services.IdeThemeServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeTooltipServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeUIServiceImpl import com.itsaky.androidide.plugins.manager.services.PluginBuildService +import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents import com.itsaky.androidide.plugins.manager.snippets.PluginSnippetManager import com.itsaky.androidide.plugins.manager.ui.PluginEditorTabManager import com.itsaky.androidide.plugins.services.IdeArchiveService @@ -805,6 +806,8 @@ class PluginManager private constructor( snippetRefreshListener?.invoke(pluginId) PluginBuildActionManager.getInstance().cleanupPlugin(pluginId) + // Before deactivate(), so no workspace event reaches a plugin that is tearing down. + PluginWorkspaceEvents.getInstance().removeAll(pluginId) val commandService = loadedPlugin.context.services.get(IdeCommandService::class.java) if (commandService is IdeCommandServiceImpl) { commandService.cancelAllCommands() @@ -1198,6 +1201,8 @@ class PluginManager private constructor( }.onFailure { logger.error("Failed to clean snippets for: $pluginId", it) } runCatching { PluginBuildActionManager.getInstance().cleanupPlugin(pluginId) } .onFailure { logger.error("Failed to clean build actions for: $pluginId", it) } + // A disabled plugin must stop hearing workspace events; activate() registers again on enable. + PluginWorkspaceEvents.getInstance().removeAll(pluginId) runCatching { val commandService = loadedPlugin.context.services.get(IdeCommandService::class.java) if (commandService is IdeCommandServiceImpl) commandService.cancelAllCommands() diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt index 7de586be3e..caa7c35011 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt @@ -6,6 +6,7 @@ import com.itsaky.androidide.plugins.PluginPermission import com.itsaky.androidide.plugins.services.CursorPosition import com.itsaky.androidide.plugins.services.EditorContentChangeListener import com.itsaky.androidide.plugins.services.FileChangeListener +import com.itsaky.androidide.plugins.services.FileSaveListener import com.itsaky.androidide.plugins.services.IdeEditorService import com.itsaky.androidide.plugins.services.SelectionRange import com.itsaky.androidide.utils.Environment @@ -22,6 +23,7 @@ class IdeEditorServiceImpl( private val readPermissions: Set = setOf(PluginPermission.FILESYSTEM_READ), private val writePermissions: Set = setOf(PluginPermission.FILESYSTEM_WRITE), private val pathValidator: PathValidator? = null, + private val workspaceEvents: PluginWorkspaceEvents = PluginWorkspaceEvents.getInstance(), ) : IdeEditorService { interface PathValidator { fun isPathAllowed(file: File): Boolean @@ -450,6 +452,15 @@ class IdeEditorServiceImpl( contentChangeListeners.remove(listener) } + override fun addFileSaveListener(listener: FileSaveListener) { + requireRead() + workspaceEvents.addFileSaveListener(pluginId, listener) + } + + override fun removeFileSaveListener(listener: FileSaveListener) { + workspaceEvents.removeFileSaveListener(listener) + } + override fun showInlineSuggestion(text: String) { // Tag the suggestion with this plugin's id so concurrent plugins don't clobber or dismiss // each other's ghost text. The public IdeEditorService signature is unchanged. diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt index 0e804a00a6..67e1dd2454 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt @@ -7,6 +7,7 @@ import com.itsaky.androidide.plugins.extensions.IProject import com.itsaky.androidide.plugins.manager.core.PluginManager import com.itsaky.androidide.plugins.services.IdeProjectService import com.itsaky.androidide.plugins.services.ModuleContext +import com.itsaky.androidide.plugins.services.ProjectLifecycleListener import com.itsaky.androidide.preferences.internal.GeneralPreferences import com.itsaky.androidide.projects.ProjectManagerImpl import com.itsaky.androidide.utils.Environment @@ -24,6 +25,7 @@ class IdeProjectServiceImpl( private val requiredPermissions: Set = setOf(PluginPermission.FILESYSTEM_READ), private val pathValidator: PathValidator? = null, private val activityProvider: PluginManager.ActivityProvider? = null, + private val workspaceEvents: PluginWorkspaceEvents = PluginWorkspaceEvents.getInstance(), ) : IdeProjectService { /** * Interface for validating project path access @@ -164,6 +166,17 @@ class IdeProjectServiceImpl( } } + override fun addProjectLifecycleListener(listener: ProjectLifecycleListener) { + if (!hasRequiredPermissions()) { + throw SecurityException("Plugin $pluginId does not have required permissions: ${getRequiredPermissionsString()}") + } + workspaceEvents.addProjectLifecycleListener(pluginId, listener) + } + + override fun removeProjectLifecycleListener(listener: ProjectLifecycleListener) { + workspaceEvents.removeProjectLifecycleListener(listener) + } + private fun resolveProjectDirUnderProjectsDir(path: File): File? { val projectsDir = runCatching { Environment.PROJECTS_DIR }.getOrNull() ?: return null return runCatching { diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt new file mode 100644 index 0000000000..c8bad30439 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt @@ -0,0 +1,138 @@ +package com.itsaky.androidide.plugins.manager.services + +import com.itsaky.androidide.plugins.services.FileSaveListener +import com.itsaky.androidide.plugins.services.ProjectLifecycleListener +import org.slf4j.LoggerFactory +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.Executors + +/** + * Tells plugins when the editor opens or closes a project and when it saves a file. The app + * reports each moment here; [IdeProjectServiceImpl] and [IdeEditorServiceImpl] register a plugin's + * listeners, keyed by plugin id so [removeAll] drops them when the plugin unloads. + * + * Listeners run in order on [executor], one thread by default: the editor never waits on a plugin, + * and every plugin hears an open before the saves that follow it and the close after them. + */ +class PluginWorkspaceEvents internal constructor( + private val executor: Executor, +) { + private class Registration( + val pluginId: String, + val listener: L, + ) + + private val projectListeners = CopyOnWriteArrayList>() + private val saveListeners = CopyOnWriteArrayList>() + + private val lock = Any() + + // The project the listeners last heard open, so a re-sync of it is not reported as another open. + private var openProjectDir: File? = null + + /** The editor opened [projectDir]. Repeats for the project already open are ignored. */ + fun projectOpened(projectDir: File) { + val dir = normalize(projectDir) + val previous: File? + synchronized(lock) { + if (dir == openProjectDir) return + previous = openProjectDir + openProjectDir = dir + } + // Switching projects without a close report still tells listeners the old one went away. + previous?.let { closed -> dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(closed) } } + dispatch(projectListeners, "onProjectOpened") { it.onProjectOpened(dir) } + } + + /** The editor closed its project. Ignored when no open was reported. */ + fun projectClosed() { + val dir = + synchronized(lock) { + openProjectDir.also { openProjectDir = null } + } ?: return + dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(dir) } + } + + /** The editor wrote [file] to disk. */ + fun fileSaved(file: File) { + val saved = file.absoluteFile + dispatch(saveListeners, "onFileSaved") { it.onFileSaved(saved) } + } + + fun addProjectLifecycleListener( + pluginId: String, + listener: ProjectLifecycleListener, + ) = add(projectListeners, pluginId, listener) + + fun removeProjectLifecycleListener(listener: ProjectLifecycleListener) = remove(projectListeners, listener) + + fun addFileSaveListener( + pluginId: String, + listener: FileSaveListener, + ) = add(saveListeners, pluginId, listener) + + fun removeFileSaveListener(listener: FileSaveListener) = remove(saveListeners, listener) + + /** Drops every listener [pluginId] registered. */ + fun removeAll(pluginId: String) { + projectListeners.removeAll { it.pluginId == pluginId } + saveListeners.removeAll { it.pluginId == pluginId } + } + + private fun add( + registrations: CopyOnWriteArrayList>, + pluginId: String, + listener: L, + ) { + synchronized(registrations) { + if (registrations.none { it.listener === listener }) { + registrations.add(Registration(pluginId, listener)) + } + } + } + + private fun remove( + registrations: CopyOnWriteArrayList>, + listener: L, + ) { + registrations.removeAll { it.listener === listener } + } + + // The listener list is read when the event runs, not when it is reported, so a plugin that + // unloads in between is not called. + private fun dispatch( + registrations: CopyOnWriteArrayList>, + event: String, + call: (L) -> Unit, + ) { + executor.execute { + registrations.forEach { registration -> + try { + call(registration.listener) + } catch (e: Throwable) { + // A plugin's bug must not stop the others hearing the event, nor kill the thread. + log.warn("Plugin {} threw from {}", registration.pluginId, event, e) + } + } + } + } + + private fun normalize(dir: File): File = runCatching { dir.canonicalFile }.getOrDefault(dir.absoluteFile) + + companion object { + private val log = LoggerFactory.getLogger(PluginWorkspaceEvents::class.java) + + private val shared: PluginWorkspaceEvents by lazy { + PluginWorkspaceEvents( + Executors.newSingleThreadExecutor { runnable -> + Thread(runnable, "plugin-workspace-events").apply { isDaemon = true } + }, + ) + } + + @JvmStatic + fun getInstance(): PluginWorkspaceEvents = shared + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt new file mode 100644 index 0000000000..80ada15db0 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt @@ -0,0 +1,301 @@ +package com.itsaky.androidide.plugins.manager.services + +import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.extensions.IProject +import com.itsaky.androidide.plugins.services.FileSaveListener +import com.itsaky.androidide.plugins.services.ProjectLifecycleListener +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import java.io.File +import java.util.concurrent.Executor + +class PluginWorkspaceEventsTest { + private lateinit var root: File + private lateinit var projectA: File + private lateinit var projectB: File + private val queued = ArrayDeque() + + @Before + fun setUp() { + root = + File.createTempFile("workspace-events-", "").apply { + delete() + mkdirs() + } + projectA = File(root, "a").apply { mkdirs() }.canonicalFile + projectB = File(root, "b").apply { mkdirs() }.canonicalFile + } + + @After + fun tearDown() { + root.deleteRecursively() + } + + private fun direct() = PluginWorkspaceEvents(Executor { it.run() }) + + private fun deferred() = PluginWorkspaceEvents(Executor { queued.addLast(it) }) + + private class RecordingListener : ProjectLifecycleListener { + val calls = mutableListOf() + + override fun onProjectOpened(projectDir: File) { + calls += "opened ${projectDir.name}" + } + + override fun onProjectClosed(projectDir: File) { + calls += "closed ${projectDir.name}" + } + } + + @Test + fun anOpenedProjectIsReportedWithItsCanonicalDirectory() { + val events = direct() + val dirs = mutableListOf() + events.addProjectLifecycleListener( + "p", + object : ProjectLifecycleListener { + override fun onProjectOpened(projectDir: File) { + dirs += projectDir + } + + override fun onProjectClosed(projectDir: File) = Unit + }, + ) + + events.projectOpened(File(projectA, "../a")) + + assertEquals(listOf(projectA), dirs) + } + + @Test + fun aResyncOfTheOpenProjectIsNotReportedAsAnotherOpen() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.projectOpened(projectA) + + assertEquals(listOf("opened a"), listener.calls) + } + + @Test + fun openingAnotherProjectClosesThePreviousOneFirst() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.projectOpened(projectB) + + assertEquals(listOf("opened a", "closed a", "opened b"), listener.calls) + } + + @Test + fun aCloseIsReportedOnceAndOnlyAfterAnOpen() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectClosed() + events.projectOpened(projectA) + events.projectClosed() + events.projectClosed() + + assertEquals(listOf("opened a", "closed a"), listener.calls) + } + + @Test + fun reopeningAClosedProjectIsReportedAgain() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.projectClosed() + events.projectOpened(projectA) + + assertEquals(listOf("opened a", "closed a", "opened a"), listener.calls) + } + + @Test + fun aSavedFileIsReportedToSaveListeners() { + val events = direct() + val saved = mutableListOf() + events.addFileSaveListener("p") { saved += it } + + val file = File(projectA, "Main.kt") + events.fileSaved(file) + + assertEquals(listOf(file), saved) + } + + @Test + fun aListenerThatThrowsDoesNotStopTheOthers() { + val events = direct() + val heard = mutableListOf() + // An Error, not only an Exception: a plugin built against another API throws NoSuchMethodError. + events.addFileSaveListener("broken") { throw NoSuchMethodError("stale plugin") } + events.addFileSaveListener("crashy") { throw IllegalStateException("bug") } + events.addFileSaveListener("fine") { heard += it.name } + + events.fileSaved(File(projectA, "Main.kt")) + + assertEquals(listOf("Main.kt"), heard) + } + + @Test + fun theSameListenerAddedTwiceIsCalledOnce() { + val events = direct() + var calls = 0 + val listener = FileSaveListener { calls++ } + events.addFileSaveListener("p", listener) + events.addFileSaveListener("p", listener) + + events.fileSaved(File(projectA, "Main.kt")) + + assertEquals(1, calls) + } + + @Test + fun aRemovedListenerIsNotCalled() { + val events = direct() + val listener = RecordingListener() + var saves = 0 + val saveListener = FileSaveListener { saves++ } + events.addProjectLifecycleListener("p", listener) + events.addFileSaveListener("p", saveListener) + + events.removeProjectLifecycleListener(listener) + events.removeFileSaveListener(saveListener) + events.projectOpened(projectA) + events.fileSaved(File(projectA, "Main.kt")) + + assertEquals(emptyList(), listener.calls) + assertEquals(0, saves) + } + + @Test + fun removeAllDropsOnlyThatPluginsListeners() { + val events = direct() + val gone = RecordingListener().also { events.addProjectLifecycleListener("gone", it) } + val kept = RecordingListener().also { events.addProjectLifecycleListener("kept", it) } + var goneSaves = 0 + events.addFileSaveListener("gone") { goneSaves++ } + + events.removeAll("gone") + events.projectOpened(projectA) + events.fileSaved(File(projectA, "Main.kt")) + + assertEquals(emptyList(), gone.calls) + assertEquals(0, goneSaves) + assertEquals(listOf("opened a"), kept.calls) + } + + @Test + fun aPluginRemovedBeforeAQueuedEventRunsIsNotCalled() { + val events = deferred() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.removeAll("p") + while (queued.isNotEmpty()) queued.removeFirst().run() + + assertEquals(emptyList(), listener.calls) + } + + @Test + fun eventsRunInTheOrderTheyWereReported() { + val events = deferred() + val order = mutableListOf() + events.addProjectLifecycleListener( + "p", + object : ProjectLifecycleListener { + override fun onProjectOpened(projectDir: File) { + order += "opened" + } + + override fun onProjectClosed(projectDir: File) { + order += "closed" + } + }, + ) + events.addFileSaveListener("p") { order += "saved" } + + events.projectOpened(projectA) + events.fileSaved(File(projectA, "Main.kt")) + events.projectClosed() + while (queued.isNotEmpty()) queued.removeFirst().run() + + assertEquals(listOf("opened", "saved", "closed"), order) + } + + @Test(expected = SecurityException::class) + fun addingAProjectListenerWithoutReadPermissionThrows() { + projectService(permissions = emptySet()).addProjectLifecycleListener(RecordingListener()) + } + + @Test + fun aProjectListenerAddedThroughTheServiceHearsOpens() { + val events = direct() + val listener = RecordingListener() + projectService(setOf(PluginPermission.FILESYSTEM_READ), events).addProjectLifecycleListener(listener) + + events.projectOpened(projectA) + + assertEquals(listOf("opened a"), listener.calls) + } + + @Test(expected = SecurityException::class) + fun addingASaveListenerWithoutReadPermissionThrows() { + editorService(permissions = emptySet()).addFileSaveListener { } + } + + @Test + fun aSaveListenerAddedThroughTheServiceHearsSaves() { + val events = direct() + val saved = mutableListOf() + editorService(setOf(PluginPermission.FILESYSTEM_READ), events).addFileSaveListener { saved += it } + + val file = File(projectA, "Main.kt") + events.fileSaved(file) + + assertEquals(listOf(file), saved) + } + + private fun projectService( + permissions: Set, + events: PluginWorkspaceEvents = direct(), + ) = IdeProjectServiceImpl( + pluginId = "p", + permissions = permissions, + projectProvider = NoProjects, + workspaceEvents = events, + ) + + private fun editorService( + permissions: Set, + events: PluginWorkspaceEvents = direct(), + ) = IdeEditorServiceImpl( + pluginId = "p", + permissions = permissions, + editorProvider = NoEditors, + workspaceEvents = events, + ) + + private object NoProjects : IdeProjectServiceImpl.ProjectProvider { + override fun getCurrentProject(): IProject? = null + + override fun getAllProjects(): List = emptyList() + + override fun getProjectByPath(path: File): IProject? = null + } + + private object NoEditors : IdeEditorServiceImpl.EditorProvider { + override fun getCurrentFile(): File? = null + + override fun getOpenFiles(): List = emptyList() + + override fun isFileOpen(file: File): Boolean = false + + override fun getCurrentSelection(): String? = null + } +} From 197b98e1d9d1d6b5eb5f61de591f9f04a663a926 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 12:18:00 -0800 Subject: [PATCH 02/14] ADFA-3570: Report project open/close and saves to plugin listeners The editor reports a project as opened when it starts initializing it, before the sync, so a hook such as a git pull sees it at once, and as closed where it resets its project state. Saves come from the DocumentSaveEvent every save path already posts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../activities/editor/ProjectHandlerActivity.kt | 6 ++++++ .../app/CredentialProtectedApplicationLoader.kt | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 126b52f792..9dc9568dbc 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -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 @@ -1196,6 +1197,8 @@ abstract class ProjectHandlerActivity : } private fun closeProjectState() { + PluginWorkspaceEvents.getInstance().projectClosed() + // reset these values here // sometimes, when the IDE closed and reopened instantly, these values prevent initialization // of the project @@ -1591,6 +1594,9 @@ abstract class ProjectHandlerActivity : handleMissingProjectDirectory(projectDir) return@launch } + // Before the sync, so a hook such as a `git pull` sees the project as soon as it opens. + // A re-sync of the same project is not reported again. + PluginWorkspaceEvents.getInstance().projectOpened(projectDir) val needsSync = try { 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..30310de774 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -13,6 +13,7 @@ import com.itsaky.androidide.activities.editor.IDELogcatReader import com.itsaky.androidide.api.BuildOutputProvider import com.itsaky.androidide.api.LogsProvider import com.itsaky.androidide.editor.schemes.IDEColorSchemeProvider +import com.itsaky.androidide.eventbus.events.editor.DocumentSaveEvent import com.itsaky.androidide.eventbus.events.plugin.PluginCrashedEvent import com.itsaky.androidide.eventbus.events.preferences.PreferenceChangeEvent import com.itsaky.androidide.lookup.Lookup @@ -24,6 +25,7 @@ import com.itsaky.androidide.plugins.manager.core.PluginManager import com.itsaky.androidide.plugins.manager.services.IdeBuildServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeLogServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeTerminalServiceImpl +import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents import com.itsaky.androidide.preferences.internal.DevOpsPreferences import com.itsaky.androidide.preferences.internal.GeneralPreferences import com.itsaky.androidide.resources.localization.LocaleProvider @@ -567,6 +569,14 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { } } + // Plugins hear saves through IdeEditorService.addFileSaveListener. POSTING is enough: the call + // only queues the event for the plugins' own thread. + @Suppress("unused") + @Subscribe(threadMode = ThreadMode.POSTING) + fun onDocumentSaved(event: DocumentSaveEvent) { + PluginWorkspaceEvents.getInstance().fileSaved(event.savedFile.toFile()) + } + @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onPrefChanged(event: PreferenceChangeEvent) { From a303589ef7b7bd0059f00554a74491cff9d6c24f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 12:18:00 -0800 Subject: [PATCH 03/14] ADFA-3570: Document the project lifecycle and file save listeners Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- docs/PLUGIN_API_CHANGELOG.md | 12 ++++++++++++ docs/PLUGIN_AUTHORING.md | 6 ++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index d37c7f42c7..7f3fa0082a 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -35,6 +35,18 @@ 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 opens a project, before its sync, 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 nothing until it closes; + ask `getCurrentProject()`. 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 diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index eff39136fe..b1cb92dac7 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -385,6 +385,7 @@ Code on the Go cannot load Android Studio or IntelliJ plugins ([ADR 0018](adr/00 | Highlighting layered over a language (e.g. rainbow brackets) | `EditorDecorationProvider`, which adds foreground colours only | | `searchEverywhereContributor` | `ProjectSearchExtension`, which appends sections to Search Results | | `runConfigurationType`, external tools | `BuildActionExtension` returning `PluginBuildAction`s that run a `CommandSpec` | +| `projectListeners` for project open and close, `FileDocumentManagerListener` for saves | `IdeProjectService.addProjectLifecycleListener` and `IdeEditorService.addFileSaveListener`. A save is reported after the file is written, so there is no `beforeDocumentSaving` | | Project or module wizard | A `.cgt` template, built with `IdeTemplateService.createTemplateBuilder` and added with `registerTemplate` | | `applicationService` / `projectService` | Objects your plugin owns. Offer one to other plugins with `PluginContext.registerService`; reach IDE services with `PluginContext.services.get(...)` | @@ -392,7 +393,7 @@ No equivalent yet: - **Editor context-menu actions.** `UIExtension.getContextMenuItems()` exists, but the IDE does not call it. - **Quick fixes, intention actions and hover documentation.** The language-server bridge does not request code actions or hover. -- **Message-bus listeners** (`applicationListeners`, `projectListeners`). `PluginContext.eventBus` is the IDE's EventBus, typed `Any`; its events are not part of the [plugin API contract](plugin-api.md), so a subscriber can break on any release. +- **Other message-bus listeners** (`applicationListeners`, and `projectListeners` beyond project open, close and file save). `PluginContext.eventBus` is the IDE's EventBus, typed `Any`; its events are not part of the [plugin API contract](plugin-api.md), so a subscriber can break on any release. - **Anything that depends on the Android plugin** bundled with Android Studio (`org.jetbrains.android`). ## Porting a VS Code extension @@ -411,6 +412,7 @@ Code on the Go does not host VS Code's extension API ([ADR 0019](adr/0019-vscode | `window.createWebviewPanel` | A `Fragment` hosting an Android `WebView`, shown as an `EditorTabExtension` tab - `markdown-preview-plugin` does this | | `contributes.configuration` | `SettingsExtension`, storing values with `PluginContext.getPluginSharedPreferences` | | `contributes.taskDefinitions` | `BuildActionExtension` returning `PluginBuildAction`s that run a `CommandSpec` | +| `workspace.onDidSaveTextDocument` | `IdeEditorService.addFileSaveListener` | No equivalent yet: @@ -418,7 +420,7 @@ No equivalent yet: - **Debuggers** (`contributes.debuggers`). The IDE's debugger does not speak the Debug Adapter Protocol. - **Explorer and editor context menus** (`menus["explorer/context"]`, `menus["editor/context"]`). `UIExtension.getContextMenuItems()` exists, but the IDE does not call it. - **In-process language providers** (`languages.registerCompletionItemProvider` and the like). Put the logic in a language server instead. -- **Workspace events** (`workspace.onDidSaveTextDocument` and the like). As for Android Studio's message-bus listeners, `PluginContext.eventBus` is not part of the plugin API contract. +- **Other workspace events** (`workspace.onDidCreateFiles`, `onDidRenameFiles` and the like). As for Android Studio's message-bus listeners, `PluginContext.eventBus` is not part of the plugin API contract. ## Troubleshooting From 2ccf7a9cff61e7226f178ae34dd8f51d00e32243 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 13:11:15 -0800 Subject: [PATCH 04/14] ADFA-3570: Address code review of the workspace listeners - Report saves from CodeEditorView.save, the one path that writes an editor's file. DocumentSaveEvent is also posted on every Enter, with nothing written, so the save listener fired on each new line. - Replay the open project to a listener that registers late: plugins load in the background, often after the editor reopened the last project, so they missed its open. - Close only the project reported open, and only from the live editor's teardown; a doomed editor no longer closes its sibling's project. An editor already tearing down no longer reports a late open. - Queue each event under the lock, so the queue order is the order the state changed in; snapshot listeners when queuing, and skip one that was removed before its call runs. - Saved files are canonical, like project directories. - A plugin can remove only its own listeners. Unload drops them first, on its own, and a failed activate() drops them too. - Nothing is queued while no plugin listens. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../editor/ProjectHandlerActivity.kt | 15 ++- .../CredentialProtectedApplicationLoader.kt | 10 -- .../itsaky/androidide/ui/CodeEditorView.kt | 3 + docs/PLUGIN_API_CHANGELOG.md | 4 +- .../plugins/services/IdeServices.kt | 18 +-- .../plugins/manager/core/PluginManager.kt | 12 +- .../manager/services/IdeEditorServiceImpl.kt | 2 +- .../manager/services/IdeProjectServiceImpl.kt | 2 +- .../manager/services/PluginWorkspaceEvents.kt | 119 ++++++++++++------ .../services/PluginWorkspaceEventsTest.kt | 112 +++++++++++++++-- 10 files changed, 225 insertions(+), 72 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 9dc9568dbc..8fd96442b4 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -1192,13 +1192,17 @@ abstract class ProjectHandlerActivity : } private fun closeProjectSession() { + // Only the live editor's teardown reports the close; a doomed instance (onPause) does not. + ProjectManagerImpl + .getInstance() + .projectDirPath + .takeIf { it.isNotBlank() } + ?.let { PluginWorkspaceEvents.getInstance().projectClosed(File(it)) } stopLanguageServers() closeProjectState() } private fun closeProjectState() { - PluginWorkspaceEvents.getInstance().projectClosed() - // reset these values here // sometimes, when the IDE closed and reopened instantly, these values prevent initialization // of the project @@ -1595,8 +1599,11 @@ abstract class ProjectHandlerActivity : return@launch } // Before the sync, so a hook such as a `git pull` sees the project as soon as it opens. - // A re-sync of the same project is not reported again. - PluginWorkspaceEvents.getInstance().projectOpened(projectDir) + // 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. + if (!isDestroying && !isFinishing) { + PluginWorkspaceEvents.getInstance().projectOpened(projectDir) + } val needsSync = try { 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 30310de774..82f0d511ce 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -13,7 +13,6 @@ import com.itsaky.androidide.activities.editor.IDELogcatReader import com.itsaky.androidide.api.BuildOutputProvider import com.itsaky.androidide.api.LogsProvider import com.itsaky.androidide.editor.schemes.IDEColorSchemeProvider -import com.itsaky.androidide.eventbus.events.editor.DocumentSaveEvent import com.itsaky.androidide.eventbus.events.plugin.PluginCrashedEvent import com.itsaky.androidide.eventbus.events.preferences.PreferenceChangeEvent import com.itsaky.androidide.lookup.Lookup @@ -25,7 +24,6 @@ import com.itsaky.androidide.plugins.manager.core.PluginManager import com.itsaky.androidide.plugins.manager.services.IdeBuildServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeLogServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeTerminalServiceImpl -import com.itsaky.androidide.plugins.manager.services.PluginWorkspaceEvents import com.itsaky.androidide.preferences.internal.DevOpsPreferences import com.itsaky.androidide.preferences.internal.GeneralPreferences import com.itsaky.androidide.resources.localization.LocaleProvider @@ -569,14 +567,6 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { } } - // Plugins hear saves through IdeEditorService.addFileSaveListener. POSTING is enough: the call - // only queues the event for the plugins' own thread. - @Suppress("unused") - @Subscribe(threadMode = ThreadMode.POSTING) - fun onDocumentSaved(event: DocumentSaveEvent) { - PluginWorkspaceEvents.getInstance().fileSaved(event.savedFile.toFile()) - } - @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onPrefChanged(event: PreferenceChangeEvent) { diff --git a/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt b/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt index 895b49e983..b1824a2a4b 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt @@ -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 @@ -417,6 +418,8 @@ class CodeEditorView( markUnmodified() notifySaved() + // Here, not from DocumentSaveEvent: the editor also posts that on every Enter, with nothing written. + PluginWorkspaceEvents.getInstance().fileSaved(file) return true } diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 7f3fa0082a..0d7c1b664d 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -44,8 +44,8 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] `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 nothing until it closes; - ask `getCurrentProject()`. Floor `plugin.min_ide_version` at `26.47` to use them. + 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]** diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt index b96d8ddb71..0e0e649fa3 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt @@ -66,8 +66,9 @@ interface IdeProjectService { /** * Registers [listener] to hear when the editor opens and closes a project. A listener added - * while a project is open hears nothing about it until it closes; ask [getCurrentProject] for - * the project already open. Registering the same listener twice has no effect. The IDE drops + * while a project is open hears [ProjectLifecycleListener.onProjectOpened] for it first, since + * plugins often load after the editor reopened the last project. Registering the same listener + * twice has no effect. The IDE drops * the listener when the plugin is disabled or unloads, so register it from * [com.itsaky.androidide.plugins.IPlugin.activate]. Available since 26.47. * @@ -88,21 +89,24 @@ interface IdeProjectService { */ interface ProjectLifecycleListener { /** - * The editor opened the project rooted at [projectDir] and is about to sync it. A sync or - * build of the same project later does not call this again. + * The editor opened the project rooted at [projectDir] and is about to sync it, or the project + * was already open when this listener was added. A sync or build of the same project later + * does not call this again. [projectDir] is canonical. */ fun onProjectOpened(projectDir: File) - /** The editor closed the project rooted at [projectDir]. */ + /** The editor closed the project rooted at [projectDir], as given to [onProjectOpened]. */ fun onProjectClosed(projectDir: File) } /** * Hears the editor write a file to disk: the user saving, the IDE saving before a build, or a - * plugin calling [IdeEditorService.saveFile]. Calls arrive in order on one background thread - * shared by every plugin, so return quickly. Available since 26.47. + * plugin calling [IdeEditorService.saveFile]. Typing alone, without a save, is never reported. + * Calls arrive in order on one background thread shared by every plugin, so return quickly. + * Available since 26.47. */ fun interface FileSaveListener { + /** [file] is canonical, the same form as a project directory, so `file.startsWith(dir)` works. */ fun onFileSaved(file: File) } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 33a2c5b654..9fa809ebe3 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -735,6 +735,8 @@ class PluginManager private constructor( logger.error("Failed to activate plugin: ${manifest.id}", e) loadedPlugin.isEnabled = false savePluginState(manifest.id, false) + // activate() may have registered workspace listeners before it failed. + PluginWorkspaceEvents.getInstance().removeAll(manifest.id) } } @@ -773,6 +775,11 @@ class PluginManager private constructor( fun unloadPlugin(pluginId: String): Boolean { val loadedPlugin = loadedPlugins.remove(pluginId) ?: return false + // First and on its own: the plugin is already out of loadedPlugins, so if a later cleanup step + // throws, nothing could drop its listeners afterwards, and none may reach it while it tears down. + runCatching { PluginWorkspaceEvents.getInstance().removeAll(pluginId) } + .onFailure { logger.error("Failed to drop workspace listeners for: $pluginId", it) } + try { // Remove documentation if plugin implements DocumentationExtension if (loadedPlugin.plugin is DocumentationExtension) { @@ -806,8 +813,6 @@ class PluginManager private constructor( snippetRefreshListener?.invoke(pluginId) PluginBuildActionManager.getInstance().cleanupPlugin(pluginId) - // Before deactivate(), so no workspace event reaches a plugin that is tearing down. - PluginWorkspaceEvents.getInstance().removeAll(pluginId) val commandService = loadedPlugin.context.services.get(IdeCommandService::class.java) if (commandService is IdeCommandServiceImpl) { commandService.cancelAllCommands() @@ -1202,7 +1207,8 @@ class PluginManager private constructor( runCatching { PluginBuildActionManager.getInstance().cleanupPlugin(pluginId) } .onFailure { logger.error("Failed to clean build actions for: $pluginId", it) } // A disabled plugin must stop hearing workspace events; activate() registers again on enable. - PluginWorkspaceEvents.getInstance().removeAll(pluginId) + runCatching { PluginWorkspaceEvents.getInstance().removeAll(pluginId) } + .onFailure { logger.error("Failed to drop workspace listeners for: $pluginId", it) } runCatching { val commandService = loadedPlugin.context.services.get(IdeCommandService::class.java) if (commandService is IdeCommandServiceImpl) commandService.cancelAllCommands() diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt index caa7c35011..e5e61025df 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeEditorServiceImpl.kt @@ -458,7 +458,7 @@ class IdeEditorServiceImpl( } override fun removeFileSaveListener(listener: FileSaveListener) { - workspaceEvents.removeFileSaveListener(listener) + workspaceEvents.removeFileSaveListener(pluginId, listener) } override fun showInlineSuggestion(text: String) { diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt index 67e1dd2454..87ae212b02 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/IdeProjectServiceImpl.kt @@ -174,7 +174,7 @@ class IdeProjectServiceImpl( } override fun removeProjectLifecycleListener(listener: ProjectLifecycleListener) { - workspaceEvents.removeProjectLifecycleListener(listener) + workspaceEvents.removeProjectLifecycleListener(pluginId, listener) } private fun resolveProjectDirUnderProjectsDir(path: File): File? { diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt index c8bad30439..d5f8bee60d 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt @@ -14,7 +14,8 @@ import java.util.concurrent.Executors * listeners, keyed by plugin id so [removeAll] drops them when the plugin unloads. * * Listeners run in order on [executor], one thread by default: the editor never waits on a plugin, - * and every plugin hears an open before the saves that follow it and the close after them. + * and every plugin hears an open before the saves that follow it and the close after them. Each + * event is queued under [lock], so the queue order is the order the state changed in. */ class PluginWorkspaceEvents internal constructor( private val executor: Executor, @@ -35,45 +36,68 @@ class PluginWorkspaceEvents internal constructor( /** The editor opened [projectDir]. Repeats for the project already open are ignored. */ fun projectOpened(projectDir: File) { val dir = normalize(projectDir) - val previous: File? synchronized(lock) { if (dir == openProjectDir) return - previous = openProjectDir + // Switching projects without a close report still tells listeners the old one went away. + openProjectDir?.let { closed -> dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(closed) } } openProjectDir = dir + dispatch(projectListeners, "onProjectOpened") { it.onProjectOpened(dir) } } - // Switching projects without a close report still tells listeners the old one went away. - previous?.let { closed -> dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(closed) } } - dispatch(projectListeners, "onProjectOpened") { it.onProjectOpened(dir) } } - /** The editor closed its project. Ignored when no open was reported. */ - fun projectClosed() { - val dir = - synchronized(lock) { - openProjectDir.also { openProjectDir = null } - } ?: return - dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(dir) } + /** + * The editor closed [projectDir]. Ignored unless it is the project last reported open, so an + * editor tearing down a project that is no longer the open one cannot close the open one. + */ + fun projectClosed(projectDir: File) { + val dir = normalize(projectDir) + synchronized(lock) { + if (dir != openProjectDir) return + openProjectDir = null + dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(dir) } + } } /** The editor wrote [file] to disk. */ fun fileSaved(file: File) { - val saved = file.absoluteFile - dispatch(saveListeners, "onFileSaved") { it.onFileSaved(saved) } + // The same form as the project directory, so a listener can test saved.startsWith(projectDir). + val saved = normalize(file) + synchronized(lock) { + dispatch(saveListeners, "onFileSaved") { it.onFileSaved(saved) } + } } + /** + * Registers [listener] for [pluginId]. A listener added while a project is open hears that open + * first: plugins load in the background, often after the editor reopened the last project. + */ fun addProjectLifecycleListener( pluginId: String, listener: ProjectLifecycleListener, - ) = add(projectListeners, pluginId, listener) + ) { + synchronized(lock) { + val registration = add(projectListeners, pluginId, listener) ?: return + val open = openProjectDir ?: return + dispatchTo(projectListeners, registration, "onProjectOpened") { it.onProjectOpened(open) } + } + } - fun removeProjectLifecycleListener(listener: ProjectLifecycleListener) = remove(projectListeners, listener) + fun removeProjectLifecycleListener( + pluginId: String, + listener: ProjectLifecycleListener, + ) = remove(projectListeners, pluginId, listener) fun addFileSaveListener( pluginId: String, listener: FileSaveListener, - ) = add(saveListeners, pluginId, listener) + ) { + synchronized(lock) { add(saveListeners, pluginId, listener) } + } - fun removeFileSaveListener(listener: FileSaveListener) = remove(saveListeners, listener) + fun removeFileSaveListener( + pluginId: String, + listener: FileSaveListener, + ) = remove(saveListeners, pluginId, listener) /** Drops every listener [pluginId] registered. */ fun removeAll(pluginId: String) { @@ -81,45 +105,66 @@ class PluginWorkspaceEvents internal constructor( saveListeners.removeAll { it.pluginId == pluginId } } + /** The new registration, or null when [listener] was already registered. */ private fun add( registrations: CopyOnWriteArrayList>, pluginId: String, listener: L, - ) { - synchronized(registrations) { - if (registrations.none { it.listener === listener }) { - registrations.add(Registration(pluginId, listener)) - } - } + ): Registration? { + if (registrations.any { it.listener === listener }) return null + return Registration(pluginId, listener).also(registrations::add) } + // Scoped to the plugin, so one plugin cannot unregister another's listener. private fun remove( registrations: CopyOnWriteArrayList>, + pluginId: String, listener: L, ) { - registrations.removeAll { it.listener === listener } + registrations.removeAll { it.pluginId == pluginId && it.listener === listener } } - // The listener list is read when the event runs, not when it is reported, so a plugin that - // unloads in between is not called. private fun dispatch( registrations: CopyOnWriteArrayList>, event: String, call: (L) -> Unit, ) { + if (registrations.isEmpty()) return + // The listeners registered now: one added later hears the open project through its replay + // instead, so it never hears an open twice. + val targets = registrations.toList() executor.execute { - registrations.forEach { registration -> - try { - call(registration.listener) - } catch (e: Throwable) { - // A plugin's bug must not stop the others hearing the event, nor kill the thread. - log.warn("Plugin {} threw from {}", registration.pluginId, event, e) - } - } + targets.forEach { invoke(registrations, it, event, call) } + } + } + + private fun dispatchTo( + registrations: CopyOnWriteArrayList>, + registration: Registration, + event: String, + call: (L) -> Unit, + ) { + executor.execute { invoke(registrations, registration, event, call) } + } + + // Checked when the call runs: a plugin removed after the event was queued, or while an earlier + // listener of the same event was running, is not called. + private fun invoke( + registrations: CopyOnWriteArrayList>, + registration: Registration, + event: String, + call: (L) -> Unit, + ) { + if (registration !in registrations) return + try { + call(registration.listener) + } catch (e: Throwable) { + // A plugin's bug must not stop the others hearing the event, nor kill the thread. + log.warn("Plugin {} threw from {}", registration.pluginId, event, e) } } - private fun normalize(dir: File): File = runCatching { dir.canonicalFile }.getOrDefault(dir.absoluteFile) + private fun normalize(file: File): File = runCatching { file.canonicalFile }.getOrDefault(file.absoluteFile) companion object { private val log = LoggerFactory.getLogger(PluginWorkspaceEvents::class.java) diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt index 80ada15db0..85836dddee 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt @@ -9,6 +9,7 @@ import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import java.io.File +import java.nio.file.Files import java.util.concurrent.Executor class PluginWorkspaceEventsTest { @@ -96,10 +97,10 @@ class PluginWorkspaceEventsTest { val events = direct() val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } - events.projectClosed() + events.projectClosed(projectA) events.projectOpened(projectA) - events.projectClosed() - events.projectClosed() + events.projectClosed(projectA) + events.projectClosed(projectA) assertEquals(listOf("opened a", "closed a"), listener.calls) } @@ -110,7 +111,7 @@ class PluginWorkspaceEventsTest { val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } events.projectOpened(projectA) - events.projectClosed() + events.projectClosed(projectA) events.projectOpened(projectA) assertEquals(listOf("opened a", "closed a", "opened a"), listener.calls) @@ -164,8 +165,8 @@ class PluginWorkspaceEventsTest { events.addProjectLifecycleListener("p", listener) events.addFileSaveListener("p", saveListener) - events.removeProjectLifecycleListener(listener) - events.removeFileSaveListener(saveListener) + events.removeProjectLifecycleListener("p", listener) + events.removeFileSaveListener("p", saveListener) events.projectOpened(projectA) events.fileSaved(File(projectA, "Main.kt")) @@ -222,12 +223,109 @@ class PluginWorkspaceEventsTest { events.projectOpened(projectA) events.fileSaved(File(projectA, "Main.kt")) - events.projectClosed() + events.projectClosed(projectA) while (queued.isNotEmpty()) queued.removeFirst().run() assertEquals(listOf("opened", "saved", "closed"), order) } + @Test + fun aListenerAddedWhileAProjectIsOpenHearsThatOpen() { + val events = direct() + events.projectOpened(projectA) + + val late = RecordingListener().also { events.addProjectLifecycleListener("late", it) } + events.projectClosed(projectA) + + assertEquals(listOf("opened a", "closed a"), late.calls) + } + + @Test + fun aListenerAddedBeforeAQueuedOpenRunsHearsItOnce() { + val events = deferred() + // Another plugin is listening, so the open is really queued, not skipped as unheard. + events.addProjectLifecycleListener("early", RecordingListener()) + events.projectOpened(projectA) + val late = RecordingListener().also { events.addProjectLifecycleListener("late", it) } + while (queued.isNotEmpty()) queued.removeFirst().run() + + assertEquals(listOf("opened a"), late.calls) + } + + @Test + fun closingAProjectThatIsNotTheOpenOneIsIgnored() { + val events = direct() + val listener = RecordingListener().also { events.addProjectLifecycleListener("p", it) } + + events.projectOpened(projectA) + events.projectClosed(projectB) + + assertEquals(listOf("opened a"), listener.calls) + } + + @Test + fun aPluginRemovedWhileAnEventIsBeingDeliveredIsNotCalled() { + val events = direct() + var removedHeard = 0 + // The first listener unloads the other plugin while this save is being delivered. + events.addFileSaveListener("first") { events.removeAll("second") } + events.addFileSaveListener("second") { removedHeard++ } + + events.fileSaved(File(projectA, "Main.kt")) + + assertEquals(0, removedHeard) + } + + @Test + fun aSavedFileHasTheSameFormAsTheProjectDirectory() { + val events = direct() + val link = File(root, "link").toPath() + Files.createSymbolicLink(link, projectA.toPath()) + val opened = mutableListOf() + val saved = mutableListOf() + events.addProjectLifecycleListener( + "p", + object : ProjectLifecycleListener { + override fun onProjectOpened(projectDir: File) { + opened += projectDir + } + + override fun onProjectClosed(projectDir: File) = Unit + }, + ) + events.addFileSaveListener("p") { saved += it } + + events.projectOpened(link.toFile()) + events.fileSaved(File(link.toFile(), "Main.kt")) + + assertEquals(true, saved.single().startsWith(opened.single())) + } + + @Test + fun aPluginCannotRemoveAnotherPluginsListener() { + val events = direct() + var heard = 0 + val listener = FileSaveListener { heard++ } + events.addFileSaveListener("owner", listener) + + events.removeFileSaveListener("other", listener) + events.fileSaved(File(projectA, "Main.kt")) + + assertEquals(1, heard) + } + + @Test + fun nothingIsQueuedWhenNoPluginListens() { + var queuedTasks = 0 + val events = PluginWorkspaceEvents(Executor { queuedTasks++ }) + + events.fileSaved(File(projectA, "Main.kt")) + events.projectOpened(projectA) + events.projectClosed(projectA) + + assertEquals(0, queuedTasks) + } + @Test(expected = SecurityException::class) fun addingAProjectListenerWithoutReadPermissionThrows() { projectService(permissions = emptySet()).addProjectLifecycleListener(RecordingListener()) From b956d90df456edc79dbb4b6875c574608a346637 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 13:35:25 -0800 Subject: [PATCH 05/14] ADFA-3570: Close the project the editor opened, and say opens are async - Report a close for the project this editor reported open, kept in EditorViewModel so a recreated editor still closes it, rather than the global project path. If the app closed while a switch from A to B awaited confirmation, the path already named B: A's close was dropped and a later reopen of A was taken for a repeat. - onProjectOpened is queued; the sync does not wait for it. Drop the "before the sync" wording from the comment, KDoc and changelog. - Two plugins that register the same listener object each keep their own registration. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../activities/editor/ProjectHandlerActivity.kt | 10 ++++------ .../itsaky/androidide/viewmodel/EditorViewModel.kt | 8 ++++++++ docs/PLUGIN_API_CHANGELOG.md | 3 ++- .../androidide/plugins/services/IdeServices.kt | 7 ++++--- .../manager/services/PluginWorkspaceEvents.kt | 5 +++-- .../manager/services/PluginWorkspaceEventsTest.kt | 14 ++++++++++++++ 6 files changed, 35 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 8fd96442b4..a2e13a9f7d 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -1193,11 +1193,8 @@ abstract class ProjectHandlerActivity : private fun closeProjectSession() { // Only the live editor's teardown reports the close; a doomed instance (onPause) does not. - ProjectManagerImpl - .getInstance() - .projectDirPath - .takeIf { it.isNotBlank() } - ?.let { PluginWorkspaceEvents.getInstance().projectClosed(File(it)) } + editorViewModel.pluginOpenedProjectDir?.let { PluginWorkspaceEvents.getInstance().projectClosed(it) } + editorViewModel.pluginOpenedProjectDir = null stopLanguageServers() closeProjectState() } @@ -1598,11 +1595,12 @@ abstract class ProjectHandlerActivity : handleMissingProjectDirectory(projectDir) return@launch } - // Before the sync, so a hook such as a `git pull` sees the project as soon as it opens. + // 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. if (!isDestroying && !isFinishing) { PluginWorkspaceEvents.getInstance().projectOpened(projectDir) + editorViewModel.pluginOpenedProjectDir = projectDir } val needsSync = diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt index e8d602b5a4..3a71d52b98 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt @@ -272,6 +272,14 @@ class EditorViewModel : ViewModel() { _isInternalBuildInProgress.value = value } + /** + * The project directory this editor last reported open to plugins. 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) { diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 0d7c1b664d..ff2281e5bb 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -38,7 +38,8 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] ### 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 opens a project, before its sync, and + `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 diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt index 0e0e649fa3..f6e705ac01 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/services/IdeServices.kt @@ -89,9 +89,10 @@ interface IdeProjectService { */ interface ProjectLifecycleListener { /** - * The editor opened the project rooted at [projectDir] and is about to sync it, or the project - * was already open when this listener was added. A sync or build of the same project later - * does not call this again. [projectDir] is canonical. + * The editor started opening the project rooted at [projectDir], or the project was already open + * when this listener was added. The IDE does not wait for this call: the project's sync may + * already be running, so do not rely on finishing work before it starts. A later sync or build + * of the same project does not call this again. [projectDir] is canonical. */ fun onProjectOpened(projectDir: File) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt index d5f8bee60d..c3cc39f541 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt @@ -105,13 +105,14 @@ class PluginWorkspaceEvents internal constructor( saveListeners.removeAll { it.pluginId == pluginId } } - /** The new registration, or null when [listener] was already registered. */ + /** The new registration, or null when [pluginId] already registered [listener]. */ private fun add( registrations: CopyOnWriteArrayList>, pluginId: String, listener: L, ): Registration? { - if (registrations.any { it.listener === listener }) return null + // Per plugin: two plugins sharing one listener object each keep their own registration. + if (registrations.any { it.pluginId == pluginId && it.listener === listener }) return null return Registration(pluginId, listener).also(registrations::add) } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt index 85836dddee..6f35b93b33 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt @@ -314,6 +314,20 @@ class PluginWorkspaceEventsTest { assertEquals(1, heard) } + @Test + fun twoPluginsSharingOneListenerKeepSeparateRegistrations() { + val events = direct() + var heard = 0 + val shared = FileSaveListener { heard++ } + events.addFileSaveListener("a", shared) + events.addFileSaveListener("b", shared) + + events.removeAll("a") + events.fileSaved(File(projectA, "Main.kt")) + + assertEquals(1, heard) + } + @Test fun nothingIsQueuedWhenNoPluginListens() { var queuedTasks = 0 From 157ef098df0f538ee58e57ec4489b362c08063cc Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 11 Nov 2026 14:05:54 -0800 Subject: [PATCH 06/14] ADFA-3570: Pair the plugin open report and its close under one lock initializeProject runs on Dispatchers.Default and can race onPause's teardown. If the teardown ran between projectOpened and recording the opened directory, it read no project and sent no close, so plugins kept the project open. The open check, report and record, and the close read, report and clear, now take the same lock; projectOpened only queues, so the lock is held briefly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../editor/ProjectHandlerActivity.kt | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index a2e13a9f7d..589935a0d1 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -283,6 +283,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() @@ -1193,8 +1196,10 @@ abstract class ProjectHandlerActivity : private fun closeProjectSession() { // Only the live editor's teardown reports the close; a doomed instance (onPause) does not. - editorViewModel.pluginOpenedProjectDir?.let { PluginWorkspaceEvents.getInstance().projectClosed(it) } - editorViewModel.pluginOpenedProjectDir = null + synchronized(pluginProjectLock) { + editorViewModel.pluginOpenedProjectDir?.let { PluginWorkspaceEvents.getInstance().projectClosed(it) } + editorViewModel.pluginOpenedProjectDir = null + } stopLanguageServers() closeProjectState() } @@ -1598,9 +1603,13 @@ abstract class ProjectHandlerActivity : // 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. - if (!isDestroying && !isFinishing) { - PluginWorkspaceEvents.getInstance().projectOpened(projectDir) - editorViewModel.pluginOpenedProjectDir = projectDir + // 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) { + PluginWorkspaceEvents.getInstance().projectOpened(projectDir) + editorViewModel.pluginOpenedProjectDir = projectDir + } } val needsSync = From 829e44f0c4414b6e6bbc9c28f85ff296bd19abb9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 00:05:03 -0800 Subject: [PATCH 07/14] ADFA-3570: Keep a loaded plugin's instance when plugins load again loadPlugins() runs on every install and called loadPlugin() on every plugin file. Each plugin already loaded got a second instance, through initialize() and activate(), while the first stayed active with its listeners registered. Its build listeners, and now its project and save listeners, heard every event twice, so a Shell-Hooks hook would run twice after the user installed any other plugin. Found by reading the code while answering a review comment. - loadPlugin() returns the loaded instance for an ID already loaded. Install unloads its target first, so the new file still loads. - Install fails, instead of keeping the old version, if that unload did not happen. - A plugin that fails initialize(), fails later in loading, or loads disabled drops its workspace listeners. With no second instance of the same ID, dropping them by ID can't reach a live plugin. No unit test: loadPlugin() needs a real .cgp and dex class loading. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../repositories/PluginRepositoryImpl.kt | 4 ++++ .../plugins/manager/core/PluginManager.kt | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt index 8c3c29860e..ba7adbf6d8 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt @@ -141,6 +141,10 @@ class PluginRepositoryImpl( } 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. + check(manager.getPlugin(pluginId) == null) { + "Could not unload the installed version of \"$pluginId\"." + } val fileExtension = if (pluginFile.name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true)) ".$PLUGIN_ARCHIVE_EXTENSION" else ".apk" diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 9fa809ebe3..f8d59be716 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -541,6 +541,8 @@ class PluginManager private constructor( */ fun loadPlugin(file: File): Result { var reservedSlotsPluginId: String? = null + // Set once initialize() may have registered workspace listeners, so a later failure drops them. + var listenersPluginId: String? = null return try { logger.debug("Loading plugin from: ${file.absolutePath}") @@ -566,6 +568,14 @@ class PluginManager private constructor( logger.debug("Parsed manifest for plugin: ${manifest.name} (${manifest.id})") + // loadPlugins() runs on every install. Loading a plugin that is already loaded again would + // leave the old instance active, its listeners still registered, beside the new one. + // Installing over a plugin unloads it first, so its new file still loads. + loadedPlugins[manifest.id]?.let { loaded -> + logger.debug("Plugin already loaded, keeping its instance: ${manifest.id}") + return Result.success(loaded.plugin) + } + if (!securityManager.validatePlugin(file, manifest)) { return Result.failure(SecurityException("plugin failed security validation: ${manifest.id}")) } @@ -652,11 +662,13 @@ class PluginManager private constructor( val pluginContext = createPluginContextWithResources(manifest.id, manifest.name, classLoader, permissions, ctx) logger.debug("Initializing plugin: ${manifest.id}") + listenersPluginId = manifest.id val initResult = try { plugin.initialize(pluginContext) } catch (e: Exception) { logger.error("Plugin initialization threw exception for: ${manifest.id}", e) + PluginWorkspaceEvents.getInstance().removeAll(manifest.id) if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -665,6 +677,7 @@ class PluginManager private constructor( if (!initResult) { logger.warn(" plugin initialization returned false for: ${manifest.id}") + PluginWorkspaceEvents.getInstance().removeAll(manifest.id) if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -692,6 +705,8 @@ class PluginManager private constructor( loadedPlugins[manifest.id] = loadedPlugin if (!isEnabled) { + // A disabled plugin hears no workspace events, as after disablePlugin(). + PluginWorkspaceEvents.getInstance().removeAll(manifest.id) logger.info("Successfully loaded plugin (disabled): ${manifest.name} (${manifest.id})") return Result.success(plugin) } @@ -702,6 +717,9 @@ class PluginManager private constructor( reservedSlotsPluginId?.let { pluginId -> SidebarSlotManager.releasePluginSlots(pluginId) } + listenersPluginId?.let { pluginId -> + runCatching { PluginWorkspaceEvents.getInstance().removeAll(pluginId) } + } logger.error("Failed to load plugin from ${file.name}: ${e.javaClass.simpleName}: ${e.message}", e) val prefix = if (e is RuntimeException) "" else "[${e.javaClass.simpleName}] " Result.failure(RuntimeException("Error loading plugin: $prefix${e.message}", e)) From 57e19ffbd2c89c292ebd3f36cf594aa514a1688d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 15:13:44 -0800 Subject: [PATCH 08/14] ADFA-3570: Load plugins one at a time, and swap files between loads Startup and an install can both call loadPlugins(). Two loads that overlap could each find a plugin not loaded yet and load it twice, and if one failed, its cleanup by plugin ID could drop the other instance's listeners. A load already under way could also load a plugin that an install or uninstall had just unloaded, from the old file. Raised by CodeRabbit on the previous commit. - loadPlugins() holds a lock, so loads run one at a time. - Install unloads the old version and copies the new file under the same lock (whileNotLoading), and uninstall unloads and deletes under it. PluginManagerLoadLockTest checks that a load waits while a swap holds the lock. With the lock taken out of loadPlugins() it fails with "loadPlugins() ran while a file swap held the lock". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../repositories/PluginRepositoryImpl.kt | 43 +++++----- .../plugins/manager/core/PluginManager.kt | 15 +++- .../manager/core/PluginManagerLoadLockTest.kt | 83 +++++++++++++++++++ 3 files changed, 120 insertions(+), 21 deletions(-) create mode 100644 plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt diff --git a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt index ba7adbf6d8..bae302193b 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt @@ -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) } @@ -135,17 +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}") - } - // loadPlugins() keeps a plugin that is still loaded, so the new file would never load. - check(manager.getPlugin(pluginId) == null) { - "Could not unload the installed version of \"$pluginId\"." - } - val fileExtension = if (pluginFile.name.endsWith(".$PLUGIN_ARCHIVE_EXTENSION", ignoreCase = true)) ".$PLUGIN_ARCHIVE_EXTENSION" else ".apk" val finalFileName = "${pluginId}$fileExtension" @@ -156,13 +145,27 @@ 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. + check(manager.getPlugin(pluginId) == null) { + "Could not unload the installed version of \"$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() diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index f8d59be716..7a5dac2c9b 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -343,6 +343,10 @@ class PluginManager private constructor( private val statePersistScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val statePersistMutex = Mutex() + // One plugin load at a time. Startup and an install can both load plugins, and two loads that + // overlap could each find a plugin not loaded yet and load it twice. + private val loadMutex = Mutex() + fun setTemplateReloadListener(listener: (() -> Unit)?) { this.templateReloadListener = listener PluginProjectManager.getInstance().setTemplateReloadListener(listener) @@ -396,7 +400,16 @@ class PluginManager private constructor( } } - suspend fun loadPlugins() = + /** Loads every plugin file not loaded yet. Waits for a load already under way. */ + suspend fun loadPlugins() = loadMutex.withLock { loadAllPlugins() } + + /** + * Runs [block] while no plugin load is under way. Install swaps a plugin's file in it, so a load + * that started first can't load the old file after the old version was unloaded. + */ + suspend fun whileNotLoading(block: suspend () -> T): T = loadMutex.withLock { block() } + + private suspend fun loadAllPlugins() = withContext(Dispatchers.IO) { logger.info("Loading plugins from directory: ${pluginsDir.absolutePath}") diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt new file mode 100644 index 0000000000..631638d6b0 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt @@ -0,0 +1,83 @@ +package com.itsaky.androidide.plugins.manager.core + +import com.itsaky.androidide.plugins.PluginLogger +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.Assert.assertFalse +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +/** + * Plugin loads run one at a time, and install swaps a plugin's file between them: two overlapping + * loads could each load the same plugin, and a load under way could load a file install replaced. + */ +@RunWith(RobolectricTestRunner::class) +@Config(manifest = Config.NONE, sdk = [28]) +class PluginManagerLoadLockTest { + @Test + fun loadWaitsWhileInstallSwapsAFile() = + runBlocking { + val manager = PluginManager.getInstance(RuntimeEnvironment.getApplication(), Any(), SilentLogger) + val swapping = CompletableDeferred() + val swapDone = CompletableDeferred() + val swap = + launch(Dispatchers.Default) { + manager.whileNotLoading { + swapping.complete(Unit) + swapDone.await() + } + } + swapping.await() + + val load = async(Dispatchers.Default) { manager.loadPlugins() } + // With no plugin files, an unguarded load finishes in milliseconds. + delay(500) + assertFalse("loadPlugins() ran while a file swap held the lock", load.isCompleted) + + swapDone.complete(Unit) + withTimeout(10_000) { + swap.join() + load.await() + } + } + + private object SilentLogger : PluginLogger { + override val pluginId = "test" + + override fun debug(message: String) = Unit + + override fun debug( + message: String, + error: Throwable, + ) = Unit + + override fun info(message: String) = Unit + + override fun info( + message: String, + error: Throwable, + ) = Unit + + override fun warn(message: String) = Unit + + override fun warn( + message: String, + error: Throwable, + ) = Unit + + override fun error(message: String) = Unit + + override fun error( + message: String, + error: Throwable, + ) = Unit + } +} From 0d447a1537074602359dc0cea1a491dd82f12267 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 19:27:48 -0800 Subject: [PATCH 09/14] ADFA-3570: Use Truth in this PR's plugin-manager tests No behaviour change. assertEquals and assertFalse become Truth's assertThat and assertWithMessage, as ARCHITECTURE.md's Testing section asks. Raised by an architecture review of the PR. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../manager/core/PluginManagerLoadLockTest.kt | 4 +- .../services/PluginWorkspaceEventsTest.kt | 52 +++++++++---------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt index 631638d6b0..e0d9944372 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.plugins.manager.core +import com.google.common.truth.Truth.assertWithMessage import com.itsaky.androidide.plugins.PluginLogger import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers @@ -8,7 +9,6 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout -import org.junit.Assert.assertFalse import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -40,7 +40,7 @@ class PluginManagerLoadLockTest { val load = async(Dispatchers.Default) { manager.loadPlugins() } // With no plugin files, an unguarded load finishes in milliseconds. delay(500) - assertFalse("loadPlugins() ran while a file swap held the lock", load.isCompleted) + assertWithMessage("loadPlugins() ran while a file swap held the lock").that(load.isCompleted).isFalse() swapDone.complete(Unit) withTimeout(10_000) { diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt index 6f35b93b33..bc9c965968 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt @@ -1,11 +1,11 @@ package com.itsaky.androidide.plugins.manager.services +import com.google.common.truth.Truth.assertThat import com.itsaky.androidide.plugins.PluginPermission import com.itsaky.androidide.plugins.extensions.IProject import com.itsaky.androidide.plugins.services.FileSaveListener import com.itsaky.androidide.plugins.services.ProjectLifecycleListener import org.junit.After -import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import java.io.File @@ -67,7 +67,7 @@ class PluginWorkspaceEventsTest { events.projectOpened(File(projectA, "../a")) - assertEquals(listOf(projectA), dirs) + assertThat(dirs).containsExactly(projectA) } @Test @@ -78,7 +78,7 @@ class PluginWorkspaceEventsTest { events.projectOpened(projectA) events.projectOpened(projectA) - assertEquals(listOf("opened a"), listener.calls) + assertThat(listener.calls).containsExactly("opened a") } @Test @@ -89,7 +89,7 @@ class PluginWorkspaceEventsTest { events.projectOpened(projectA) events.projectOpened(projectB) - assertEquals(listOf("opened a", "closed a", "opened b"), listener.calls) + assertThat(listener.calls).containsExactly("opened a", "closed a", "opened b").inOrder() } @Test @@ -102,7 +102,7 @@ class PluginWorkspaceEventsTest { events.projectClosed(projectA) events.projectClosed(projectA) - assertEquals(listOf("opened a", "closed a"), listener.calls) + assertThat(listener.calls).containsExactly("opened a", "closed a").inOrder() } @Test @@ -114,7 +114,7 @@ class PluginWorkspaceEventsTest { events.projectClosed(projectA) events.projectOpened(projectA) - assertEquals(listOf("opened a", "closed a", "opened a"), listener.calls) + assertThat(listener.calls).containsExactly("opened a", "closed a", "opened a").inOrder() } @Test @@ -126,7 +126,7 @@ class PluginWorkspaceEventsTest { val file = File(projectA, "Main.kt") events.fileSaved(file) - assertEquals(listOf(file), saved) + assertThat(saved).containsExactly(file) } @Test @@ -140,7 +140,7 @@ class PluginWorkspaceEventsTest { events.fileSaved(File(projectA, "Main.kt")) - assertEquals(listOf("Main.kt"), heard) + assertThat(heard).containsExactly("Main.kt") } @Test @@ -153,7 +153,7 @@ class PluginWorkspaceEventsTest { events.fileSaved(File(projectA, "Main.kt")) - assertEquals(1, calls) + assertThat(calls).isEqualTo(1) } @Test @@ -170,8 +170,8 @@ class PluginWorkspaceEventsTest { events.projectOpened(projectA) events.fileSaved(File(projectA, "Main.kt")) - assertEquals(emptyList(), listener.calls) - assertEquals(0, saves) + assertThat(listener.calls).isEmpty() + assertThat(saves).isEqualTo(0) } @Test @@ -186,9 +186,9 @@ class PluginWorkspaceEventsTest { events.projectOpened(projectA) events.fileSaved(File(projectA, "Main.kt")) - assertEquals(emptyList(), gone.calls) - assertEquals(0, goneSaves) - assertEquals(listOf("opened a"), kept.calls) + assertThat(gone.calls).isEmpty() + assertThat(goneSaves).isEqualTo(0) + assertThat(kept.calls).containsExactly("opened a") } @Test @@ -200,7 +200,7 @@ class PluginWorkspaceEventsTest { events.removeAll("p") while (queued.isNotEmpty()) queued.removeFirst().run() - assertEquals(emptyList(), listener.calls) + assertThat(listener.calls).isEmpty() } @Test @@ -226,7 +226,7 @@ class PluginWorkspaceEventsTest { events.projectClosed(projectA) while (queued.isNotEmpty()) queued.removeFirst().run() - assertEquals(listOf("opened", "saved", "closed"), order) + assertThat(order).containsExactly("opened", "saved", "closed").inOrder() } @Test @@ -237,7 +237,7 @@ class PluginWorkspaceEventsTest { val late = RecordingListener().also { events.addProjectLifecycleListener("late", it) } events.projectClosed(projectA) - assertEquals(listOf("opened a", "closed a"), late.calls) + assertThat(late.calls).containsExactly("opened a", "closed a").inOrder() } @Test @@ -249,7 +249,7 @@ class PluginWorkspaceEventsTest { val late = RecordingListener().also { events.addProjectLifecycleListener("late", it) } while (queued.isNotEmpty()) queued.removeFirst().run() - assertEquals(listOf("opened a"), late.calls) + assertThat(late.calls).containsExactly("opened a") } @Test @@ -260,7 +260,7 @@ class PluginWorkspaceEventsTest { events.projectOpened(projectA) events.projectClosed(projectB) - assertEquals(listOf("opened a"), listener.calls) + assertThat(listener.calls).containsExactly("opened a") } @Test @@ -273,7 +273,7 @@ class PluginWorkspaceEventsTest { events.fileSaved(File(projectA, "Main.kt")) - assertEquals(0, removedHeard) + assertThat(removedHeard).isEqualTo(0) } @Test @@ -298,7 +298,7 @@ class PluginWorkspaceEventsTest { events.projectOpened(link.toFile()) events.fileSaved(File(link.toFile(), "Main.kt")) - assertEquals(true, saved.single().startsWith(opened.single())) + assertThat(saved.single().startsWith(opened.single())).isTrue() } @Test @@ -311,7 +311,7 @@ class PluginWorkspaceEventsTest { events.removeFileSaveListener("other", listener) events.fileSaved(File(projectA, "Main.kt")) - assertEquals(1, heard) + assertThat(heard).isEqualTo(1) } @Test @@ -325,7 +325,7 @@ class PluginWorkspaceEventsTest { events.removeAll("a") events.fileSaved(File(projectA, "Main.kt")) - assertEquals(1, heard) + assertThat(heard).isEqualTo(1) } @Test @@ -337,7 +337,7 @@ class PluginWorkspaceEventsTest { events.projectOpened(projectA) events.projectClosed(projectA) - assertEquals(0, queuedTasks) + assertThat(queuedTasks).isEqualTo(0) } @Test(expected = SecurityException::class) @@ -353,7 +353,7 @@ class PluginWorkspaceEventsTest { events.projectOpened(projectA) - assertEquals(listOf("opened a"), listener.calls) + assertThat(listener.calls).containsExactly("opened a") } @Test(expected = SecurityException::class) @@ -370,7 +370,7 @@ class PluginWorkspaceEventsTest { val file = File(projectA, "Main.kt") events.fileSaved(file) - assertEquals(listOf(file), saved) + assertThat(saved).containsExactly(file) } private fun projectService( From 835cbb25ae39a74fef71ce8215817eea8494bdf9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 19:27:49 -0800 Subject: [PATCH 10/14] ADFA-3570: Make the plugin listener registry safe across threads Removing a plugin's listeners ran outside the registry's lock, through Kotlin's removeAll {}, which edits a RandomAccess list index by index. A registration added at the same moment could be lost, one save could reach a listener twice, and reading the list mid-edit could throw. At startup a disabled plugin's load drops its listeners while another plugin activates, so that plugin could hear nothing all session. An independent review reproduced all three against the compiled class. - Add, remove and remove-all run under the lock and use removeIf, and an event's recipients are copied in one step. - They are internal: only plugin-manager calls them, and a plugin that reached the class could otherwise drop another plugin's listeners. - The app's three reports are wrapped in runCatching, so reporting to plugins can never fail a save or the editor's teardown. - A save is reported right after the write, before markUnmodified(), which throws when the tab was closed mid-save. - No canonical path is resolved on the main thread (ADR 0007): the close compares the directory projectOpened() returned, which EditorViewModel keeps, and a save's path is resolved on the listeners' thread. - ARCHITECTURE.md describes the close report and why it bypasses EventBus. registrationsChangedOnManyThreadsAreNeitherLostNorDoubled fails on the previous registry. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- ARCHITECTURE.md | 2 +- .../editor/ProjectHandlerActivity.kt | 12 +++-- .../itsaky/androidide/ui/CodeEditorView.kt | 7 ++- .../androidide/viewmodel/EditorViewModel.kt | 3 +- .../manager/services/PluginWorkspaceEvents.kt | 53 +++++++++++-------- .../services/PluginWorkspaceEventsTest.kt | 38 +++++++++++++ 6 files changed, 87 insertions(+), 28 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7c0b4a0857..c2672d0adb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -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 `/`, 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//` (`services/builder/BuildOutputLocation`), keyed like Quick Build's scratch (`ProjectStorageKey` in `:shared`): - `main/-/` per Gradle project (`` 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`). diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index 589935a0d1..ccfa81c730 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -1197,7 +1197,11 @@ 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 { PluginWorkspaceEvents.getInstance().projectClosed(it) } + 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() @@ -1607,8 +1611,10 @@ abstract class ProjectHandlerActivity : // teardown, which would otherwise read no open project between the report and the record. synchronized(pluginProjectLock) { if (!isDestroying && !isFinishing) { - PluginWorkspaceEvents.getInstance().projectOpened(projectDir) - editorViewModel.pluginOpenedProjectDir = projectDir + // 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) } } } diff --git a/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt b/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt index b1824a2a4b..815af2dda1 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt @@ -416,10 +416,13 @@ class CodeEditorView( _binding?.rwProgress?.isVisible = false } + // Here, not from DocumentSaveEvent: the editor also posts that on every Enter, with nothing + // written. Before markUnmodified(), which 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) } markUnmodified() notifySaved() - // Here, not from DocumentSaveEvent: the editor also posts that on every Enter, with nothing written. - PluginWorkspaceEvents.getInstance().fileSaved(file) return true } diff --git a/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt index 3a71d52b98..7cd5826ad9 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodel/EditorViewModel.kt @@ -273,7 +273,8 @@ class EditorViewModel : ViewModel() { } /** - * The project directory this editor last reported open to plugins. Held here rather than on the + * 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. */ diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt index c3cc39f541..ab203046aa 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt @@ -15,7 +15,8 @@ import java.util.concurrent.Executors * * Listeners run in order on [executor], one thread by default: the editor never waits on a plugin, * and every plugin hears an open before the saves that follow it and the close after them. Each - * event is queued under [lock], so the queue order is the order the state changed in. + * event is queued, and every registration added or removed, under [lock], so the queue order is the + * order the state changed in and an event's recipients are a consistent snapshot. */ class PluginWorkspaceEvents internal constructor( private val executor: Executor, @@ -33,37 +34,43 @@ class PluginWorkspaceEvents internal constructor( // The project the listeners last heard open, so a re-sync of it is not reported as another open. private var openProjectDir: File? = null - /** The editor opened [projectDir]. Repeats for the project already open are ignored. */ - fun projectOpened(projectDir: File) { + /** + * The editor opened [projectDir]. Repeats for the project already open are ignored. Returns the + * directory as listeners hear it, canonical; report the close with that. + */ + fun projectOpened(projectDir: File): File { val dir = normalize(projectDir) synchronized(lock) { - if (dir == openProjectDir) return + if (dir == openProjectDir) return dir // Switching projects without a close report still tells listeners the old one went away. openProjectDir?.let { closed -> dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(closed) } } openProjectDir = dir dispatch(projectListeners, "onProjectOpened") { it.onProjectOpened(dir) } } + return dir } /** - * The editor closed [projectDir]. Ignored unless it is the project last reported open, so an - * editor tearing down a project that is no longer the open one cannot close the open one. + * The editor closed [projectDir], the directory [projectOpened] returned. It is compared as given, + * without resolving it on disk, because the close is reported from the main thread. Ignored + * unless it is the project last reported open, so an editor tearing down a project that is no + * longer the open one cannot close the open one. */ fun projectClosed(projectDir: File) { - val dir = normalize(projectDir) synchronized(lock) { - if (dir != openProjectDir) return + if (projectDir != openProjectDir) return openProjectDir = null - dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(dir) } + dispatch(projectListeners, "onProjectClosed") { it.onProjectClosed(projectDir) } } } /** The editor wrote [file] to disk. */ fun fileSaved(file: File) { - // The same form as the project directory, so a listener can test saved.startsWith(projectDir). - val saved = normalize(file) + // Canonical like the project directory, so a listener can test saved.startsWith(projectDir). + // Resolved on the listeners' thread: the caller is often the main thread. + val saved = lazy { normalize(file) } synchronized(lock) { - dispatch(saveListeners, "onFileSaved") { it.onFileSaved(saved) } + dispatch(saveListeners, "onFileSaved") { it.onFileSaved(saved.value) } } } @@ -71,7 +78,7 @@ class PluginWorkspaceEvents internal constructor( * Registers [listener] for [pluginId]. A listener added while a project is open hears that open * first: plugins load in the background, often after the editor reopened the last project. */ - fun addProjectLifecycleListener( + internal fun addProjectLifecycleListener( pluginId: String, listener: ProjectLifecycleListener, ) { @@ -82,27 +89,31 @@ class PluginWorkspaceEvents internal constructor( } } - fun removeProjectLifecycleListener( + internal fun removeProjectLifecycleListener( pluginId: String, listener: ProjectLifecycleListener, ) = remove(projectListeners, pluginId, listener) - fun addFileSaveListener( + internal fun addFileSaveListener( pluginId: String, listener: FileSaveListener, ) { synchronized(lock) { add(saveListeners, pluginId, listener) } } - fun removeFileSaveListener( + internal fun removeFileSaveListener( pluginId: String, listener: FileSaveListener, ) = remove(saveListeners, pluginId, listener) /** Drops every listener [pluginId] registered. */ - fun removeAll(pluginId: String) { - projectListeners.removeAll { it.pluginId == pluginId } - saveListeners.removeAll { it.pluginId == pluginId } + internal fun removeAll(pluginId: String) { + synchronized(lock) { + // removeIf, not Kotlin's removeAll {}: on a RandomAccess list that edits the list index by + // index, and invoke() reads it without the lock while it is half done. + projectListeners.removeIf { it.pluginId == pluginId } + saveListeners.removeIf { it.pluginId == pluginId } + } } /** The new registration, or null when [pluginId] already registered [listener]. */ @@ -122,7 +133,7 @@ class PluginWorkspaceEvents internal constructor( pluginId: String, listener: L, ) { - registrations.removeAll { it.pluginId == pluginId && it.listener === listener } + synchronized(lock) { registrations.removeIf { it.pluginId == pluginId && it.listener === listener } } } private fun dispatch( @@ -133,7 +144,7 @@ class PluginWorkspaceEvents internal constructor( if (registrations.isEmpty()) return // The listeners registered now: one added later hears the open project through its replay // instead, so it never hears an open twice. - val targets = registrations.toList() + val targets = ArrayList(registrations) executor.execute { targets.forEach { invoke(registrations, it, event, call) } } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt index bc9c965968..41cd5f2abf 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt @@ -10,7 +10,10 @@ import org.junit.Before import org.junit.Test import java.io.File import java.nio.file.Files +import java.util.concurrent.CyclicBarrier import java.util.concurrent.Executor +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicInteger class PluginWorkspaceEventsTest { private lateinit var root: File @@ -410,4 +413,39 @@ class PluginWorkspaceEventsTest { override fun getCurrentSelection(): String? = null } + + @Test + fun registrationsChangedOnManyThreadsAreNeitherLostNorDoubled() { + // One plugin registers while another plugin's listeners are dropped, as at startup when a + // disabled plugin loads beside one that activates. The registration must survive, once. + val saved = File(projectA, "Main.kt") + val pool = Executors.newFixedThreadPool(2) + val start = CyclicBarrier(2) + var wrong = 0 + try { + repeat(20_000) { + val events = direct() + repeat(8) { i -> events.addFileSaveListener("other", FileSaveListener { _ -> i.hashCode() }) } + val heard = AtomicInteger() + val listener = FileSaveListener { heard.incrementAndGet() } + val drop = + pool.submit { + start.await() + events.removeAll("other") + } + val add = + pool.submit { + start.await() + events.addFileSaveListener("p", listener) + } + drop.get() + add.get() + events.fileSaved(saved) + if (heard.get() != 1) wrong++ + } + } finally { + pool.shutdownNow() + } + assertThat(wrong).isEqualTo(0) + } } From 7ae63f15a9941bd0cb7e95f174b721f585291c3b Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 19:27:49 -0800 Subject: [PATCH 11/14] ADFA-3570: Bound the plugin load lock's wait; catch LinkageError in initialize() The load lock is held while plugins' initialize() and activate() run. A plugin that never returned would block every later install and uninstall for good, including installing its fixed version, and if it hung in initialize() it could not even be disabled. - Loads, installs and uninstalls wait at most 30 s for the lock, then go on without it, as they did before the lock existed, and log it. - initialize() failing with a LinkageError (a plugin built against another API version) now takes the failure path, which drops the plugin's listeners. Before, the Error skipped that cleanup, and uninstall could not reach the listeners either. aLoadStuckHoldingTheLockDoesNotBlockTheNextForever times out with the bounded wait replaced by a plain withLock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../plugins/manager/core/PluginManager.kt | 38 ++++++++++++++++--- .../manager/core/PluginManagerLoadLockTest.kt | 27 +++++++++++++ 2 files changed, 60 insertions(+), 5 deletions(-) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 7a5dac2c9b..7639297f1b 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -91,6 +91,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION import java.io.File import java.util.concurrent.ConcurrentHashMap @@ -347,6 +348,9 @@ class PluginManager private constructor( // overlap could each find a plugin not loaded yet and load it twice. private val loadMutex = Mutex() + // How long a load, install or uninstall waits for the load lock. Internal so tests can shorten it. + internal var loadLockWaitMs = 30_000L + fun setTemplateReloadListener(listener: (() -> Unit)?) { this.templateReloadListener = listener PluginProjectManager.getInstance().setTemplateReloadListener(listener) @@ -400,14 +404,35 @@ class PluginManager private constructor( } } - /** Loads every plugin file not loaded yet. Waits for a load already under way. */ - suspend fun loadPlugins() = loadMutex.withLock { loadAllPlugins() } + /** Loads every plugin file not loaded yet. Waits for a load already under way: see [withLoadLock]. */ + suspend fun loadPlugins() = withLoadLock("load plugins") { loadAllPlugins() } /** * Runs [block] while no plugin load is under way. Install swaps a plugin's file in it, so a load - * that started first can't load the old file after the old version was unloaded. + * that started first can't load the old file after the old version was unloaded. See [withLoadLock]. */ - suspend fun whileNotLoading(block: suspend () -> T): T = loadMutex.withLock { block() } + suspend fun whileNotLoading(block: suspend () -> T): T = withLoadLock("change a plugin file", block) + + /** + * Runs [block] holding the load lock, waiting at most [loadLockWaitMs] for it, then without it. + * A load holds the lock while plugins' initialize() and activate() run, so a plugin that never + * returns would otherwise block every later install and uninstall for good, including installing + * its fixed version. Going on without the lock is how loads behaved before it existed. + */ + private suspend fun withLoadLock( + action: String, + block: suspend () -> T, + ): T { + val locked = withTimeoutOrNull(loadLockWaitMs) { loadMutex.lock() } != null + if (!locked) { + logger.warn("A plugin load has held the load lock for over ${loadLockWaitMs / 1000} s; going on to $action without it") + } + return try { + block() + } finally { + if (locked) loadMutex.unlock() + } + } private suspend fun loadAllPlugins() = withContext(Dispatchers.IO) { @@ -679,7 +704,10 @@ class PluginManager private constructor( val initResult = try { plugin.initialize(pluginContext) - } catch (e: Exception) { + } catch (e: Throwable) { + // LinkageError too: a plugin built against another API version fails with one, such as + // NoSuchMethodError, and its listeners must still go. Other Errors are not the plugin's. + if (e !is Exception && e !is LinkageError) throw e logger.error("Plugin initialization threw exception for: ${manifest.id}", e) PluginWorkspaceEvents.getInstance().removeAll(manifest.id) if (manifest.sidebarItems > 0) { diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt index e0d9944372..85c4c3fc6d 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt @@ -18,6 +18,7 @@ import org.robolectric.annotation.Config /** * Plugin loads run one at a time, and install swaps a plugin's file between them: two overlapping * loads could each load the same plugin, and a load under way could load a file install replaced. + * The wait is bounded, so a load stuck in a plugin's code can't block every later one. */ @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE, sdk = [28]) @@ -49,6 +50,32 @@ class PluginManagerLoadLockTest { } } + @Test + fun aLoadStuckHoldingTheLockDoesNotBlockTheNextForever() = + runBlocking { + val manager = PluginManager.getInstance(RuntimeEnvironment.getApplication(), Any(), SilentLogger) + manager.loadLockWaitMs = 300 + val stuck = CompletableDeferred() + val holding = CompletableDeferred() + // Stands in for a load whose plugin never returns from initialize() or activate(). + val holder = + launch(Dispatchers.Default) { + manager.whileNotLoading { + holding.complete(Unit) + stuck.await() + } + } + holding.await() + try { + // Waits out loadLockWaitMs, then loads without the lock instead of waiting for good. + withTimeout(10_000) { manager.loadPlugins() } + } finally { + stuck.complete(Unit) + holder.join() + manager.loadLockWaitMs = 30_000L + } + } + private object SilentLogger : PluginLogger { override val pluginId = "test" From 225553f48a0773a9a69007c233b7bfda77929d5e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 12 Nov 2026 19:27:49 -0800 Subject: [PATCH 12/14] ADFA-3570: Show the still-loaded install error from a string resource Install fails when the version it replaces is still loaded. Its message was hard-coded English. It is now PluginStillLoadedException, which the three places that report an install failure show as msg_plugin_install_still_loaded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../androidide/actions/file/InstallFileAction.kt | 9 ++++++++- .../activities/editor/ProjectHandlerActivity.kt | 13 +++++++++---- .../androidide/repositories/PluginRepositoryImpl.kt | 4 +--- .../repositories/PluginStillLoadedException.kt | 10 ++++++++++ .../androidide/viewmodels/PluginManagerViewModel.kt | 13 +++++++++---- resources/src/main/res/values/strings.xml | 1 + 6 files changed, 38 insertions(+), 12 deletions(-) create mode 100644 app/src/main/java/com/itsaky/androidide/repositories/PluginStillLoadedException.kt diff --git a/app/src/main/java/com/itsaky/androidide/actions/file/InstallFileAction.kt b/app/src/main/java/com/itsaky/androidide/actions/file/InstallFileAction.kt index 18cf2c188e..fa58d3effd 100644 --- a/app/src/main/java/com/itsaky/androidide/actions/file/InstallFileAction.kt +++ b/app/src/main/java/com/itsaky/androidide/actions/file/InstallFileAction.kt @@ -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 @@ -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) + }, + ) } } } diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt index ccfa81c730..9e6b1c30ea 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/ProjectHandlerActivity.kt @@ -95,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 @@ -1160,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("") diff --git a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt index bae302193b..0454c8af85 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/PluginRepositoryImpl.kt @@ -154,9 +154,7 @@ class PluginRepositoryImpl( Log.w(TAG, "Error uninstalling existing plugin: ${e.message}") } // loadPlugins() keeps a plugin that is still loaded, so the new file would never load. - check(manager.getPlugin(pluginId) == null) { - "Could not unload the installed version of \"$pluginId\"." - } + if (manager.getPlugin(pluginId) != null) throw PluginStillLoadedException(pluginId) try { pluginFile.copyTo(finalFile, overwrite = true) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/PluginStillLoadedException.kt b/app/src/main/java/com/itsaky/androidide/repositories/PluginStillLoadedException.kt new file mode 100644 index 0000000000..ce8e3867a0 --- /dev/null +++ b/app/src/main/java/com/itsaky/androidide/repositories/PluginStillLoadedException.kt @@ -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") diff --git a/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt b/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt index 625477ca56..587a06656b 100644 --- a/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt +++ b/app/src/main/java/com/itsaky/androidide/viewmodels/PluginManagerViewModel.kt @@ -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 @@ -406,10 +407,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 diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index 49f1ed7302..643591bfce 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -1316,6 +1316,7 @@ Plugin changes will take effect after restarting the app. Do you want to restart now? Restart now Failed to install plugin: %1$s + Failed to install plugin: the installed version of %1$s could not be unloaded. Restart Code on the Go and try again. \'%1$s\' was installed from a different build variant. Uninstall it before installing this version. Plugin error Plugin file not found From 969f5be66f2aeb6dc024b10d21efaa72e8c45aff Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 13 Nov 2026 03:18:45 -0800 Subject: [PATCH 13/14] ADFA-3570: Never leak the plugin load lock when its wait times out withTimeoutOrNull can time out just after the wrapped lock() returns, and then reports null for a lock the caller holds. withLoadLock read that as "not locked", so it never unlocked: the lock stayed held for the life of the process, and every later load, install and uninstall waited out the 30 s and ran without it. An independent review reproduced it: 1,153 leaks in 94,490 timeouts. - Mutex.lockWithin sets its flag inside the wait, after lock() returns, and withLoadLock uses it. - The KDoc names what running without the lock risks: a load stuck past the wait that later finishes can add a second instance of its plugin, or drop by id the listeners and sidebar slots of one installed meanwhile. - PluginManagerLoadLockTest restores the wait it saved, not a literal. LockWithinTest releases a held lock around a 1 ms wait 3,000 times. On the old code it counted 35 to 55 leaks per run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../plugins/manager/core/PluginManager.kt | 21 ++++++++- .../plugins/manager/core/LockWithinTest.kt | 47 +++++++++++++++++++ .../manager/core/PluginManagerLoadLockTest.kt | 3 +- 3 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/LockWithinTest.kt diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt index 759ef64e3c..8135dd9442 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManager.kt @@ -417,13 +417,16 @@ class PluginManager private constructor( * Runs [block] holding the load lock, waiting at most [loadLockWaitMs] for it, then without it. * A load holds the lock while plugins' initialize() and activate() run, so a plugin that never * returns would otherwise block every later install and uninstall for good, including installing - * its fixed version. Going on without the lock is how loads behaved before it existed. + * its fixed version. Going on without the lock is how loads behaved before it existed, with the + * same risks, now only behind a plugin stuck past the wait: if that stuck load later finishes, + * it can register a second instance of its plugin beside one loaded meanwhile, or, failing, + * drop by plugin id the listeners and sidebar slots of the instance installed meanwhile. */ private suspend fun withLoadLock( action: String, block: suspend () -> T, ): T { - val locked = withTimeoutOrNull(loadLockWaitMs) { loadMutex.lock() } != null + val locked = loadMutex.lockWithin(loadLockWaitMs) if (!locked) { logger.warn("A plugin load has held the load lock for over ${loadLockWaitMs / 1000} s; going on to $action without it") } @@ -2069,3 +2072,17 @@ internal fun initializePlugin( plugin: IPlugin, context: PluginContext, ): Result = runCatching { plugin.initialize(context) } + +/** + * Waits at most [timeoutMs] for this mutex. True when the caller now holds it, and must unlock it. + * The flag is set inside the wait, not taken from its result: the timeout can fire just after + * lock() returned, and withTimeoutOrNull then reports null for a lock the caller holds. + */ +internal suspend fun Mutex.lockWithin(timeoutMs: Long): Boolean { + var locked = false + withTimeoutOrNull(timeoutMs) { + lock() + locked = true + } + return locked +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/LockWithinTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/LockWithinTest.kt new file mode 100644 index 0000000000..ec16910a6a --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/LockWithinTest.kt @@ -0,0 +1,47 @@ +package com.itsaky.androidide.plugins.manager.core + +import com.google.common.truth.Truth.assertWithMessage +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.sync.Mutex +import org.junit.Test +import java.util.concurrent.locks.LockSupport + +/** + * [lockWithin] must never report "not locked" for a lock the caller got. The timeout can fire just + * after lock() returns; reading the result of withTimeoutOrNull then leaked the lock for good, and + * every later plugin load waited out the timeout and ran without it. + */ +class LockWithinTest { + @Test + fun aLockTakenAsTheWaitTimesOutIsReportedHeld() = + runBlocking { + var leaked = 0 + repeat(ROUNDS) { round -> + val mutex = Mutex() + mutex.lock() + val waiter = async(Dispatchers.IO) { mutex.lockWithin(1L) } + // Release around the 1 ms timeout, jittered, so some releases land as it fires. + val releaser = + launch(Dispatchers.Default) { + LockSupport.parkNanos(700_000L + (round % 600) * 1_000L) + mutex.unlock() + } + val locked = waiter.await() + releaser.join() + if (locked) { + mutex.unlock() + } else if (mutex.isLocked) { + leaked++ + } + } + assertWithMessage("rounds where the lock was taken but reported free").that(leaked).isEqualTo(0) + } + + private companion object { + // The old code leaked in about 1 in 100 timeouts, so 3,000 rounds (about 3 s) catch it. + const val ROUNDS = 3_000 + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt index 85c4c3fc6d..910aa78973 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerLoadLockTest.kt @@ -54,6 +54,7 @@ class PluginManagerLoadLockTest { fun aLoadStuckHoldingTheLockDoesNotBlockTheNextForever() = runBlocking { val manager = PluginManager.getInstance(RuntimeEnvironment.getApplication(), Any(), SilentLogger) + val wait = manager.loadLockWaitMs manager.loadLockWaitMs = 300 val stuck = CompletableDeferred() val holding = CompletableDeferred() @@ -72,7 +73,7 @@ class PluginManagerLoadLockTest { } finally { stuck.complete(Unit) holder.join() - manager.loadLockWaitMs = 30_000L + manager.loadLockWaitMs = wait } } From 29d07722e499782b4f7d8d9b7a956ad35ac47748 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 13 Nov 2026 03:18:45 -0800 Subject: [PATCH 14/14] ADFA-3570: Report saves after markUnmodified; say what the registry guarantees - CodeEditorView.save reports the save after markUnmodified() again, in a finally, so a listener that asks whether the file is modified hears no. The report still happens when markUnmodified() throws because the tab closed mid-save. - The registry comments were wrong or overstated. removeIf is used because it replaces the array in one step. A plugin removed just after invoke()'s unlocked check can still be called once while it tears down. - The threading test now drops 64 of another plugin's listeners per round. Against the old unlocked removal it failed 88 to 154 times per run, where it had failed 2 to 19 times out of 20,000. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAZWMkFWJh7CY7P4kCH --- .../com/itsaky/androidide/ui/CodeEditorView.kt | 18 +++++++++++------- .../manager/services/PluginWorkspaceEvents.kt | 9 +++++---- .../services/PluginWorkspaceEventsTest.kt | 11 +++++++++-- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt b/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt index 815af2dda1..a94bdfde54 100644 --- a/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt +++ b/app/src/main/java/com/itsaky/androidide/ui/CodeEditorView.kt @@ -416,13 +416,17 @@ class CodeEditorView( _binding?.rwProgress?.isVisible = false } - // Here, not from DocumentSaveEvent: the editor also posts that on every Enter, with nothing - // written. Before markUnmodified(), which 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) } - 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 } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt index ab203046aa..f5c2dfa463 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEvents.kt @@ -109,8 +109,8 @@ class PluginWorkspaceEvents internal constructor( /** Drops every listener [pluginId] registered. */ internal fun removeAll(pluginId: String) { synchronized(lock) { - // removeIf, not Kotlin's removeAll {}: on a RandomAccess list that edits the list index by - // index, and invoke() reads it without the lock while it is half done. + // removeIf replaces the array in one step, so invoke(), which reads without the lock, sees + // the list before or after the removal, never part-way through Kotlin's removeAll {}. projectListeners.removeIf { it.pluginId == pluginId } saveListeners.removeIf { it.pluginId == pluginId } } @@ -159,8 +159,9 @@ class PluginWorkspaceEvents internal constructor( executor.execute { invoke(registrations, registration, event, call) } } - // Checked when the call runs: a plugin removed after the event was queued, or while an earlier - // listener of the same event was running, is not called. + // Checked when the call runs, without the lock: a plugin removed after the event was queued, or + // while an earlier listener of the same event was running, is not called. One removed just after + // this check can still be called once, while it tears down; unload does not wait for plugin code. private fun invoke( registrations: CopyOnWriteArrayList>, registration: Registration, diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt index 41cd5f2abf..c32a7ad2af 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/PluginWorkspaceEventsTest.kt @@ -423,9 +423,9 @@ class PluginWorkspaceEventsTest { val start = CyclicBarrier(2) var wrong = 0 try { - repeat(20_000) { + repeat(ROUNDS) { val events = direct() - repeat(8) { i -> events.addFileSaveListener("other", FileSaveListener { _ -> i.hashCode() }) } + repeat(OTHERS) { i -> events.addFileSaveListener("other", FileSaveListener { _ -> i.hashCode() }) } val heard = AtomicInteger() val listener = FileSaveListener { heard.incrementAndGet() } val drop = @@ -448,4 +448,11 @@ class PluginWorkspaceEventsTest { } assertThat(wrong).isEqualTo(0) } + + private companion object { + // Enough rounds, with enough of another plugin's listeners to drop, that the old unlocked + // in-place removal loses a registration in almost every run. + const val ROUNDS = 20_000 + const val OTHERS = 64 + } }