From c72508a1ab19d88bec0ee586a9e7f9e1bd33bef7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:34:22 -0800 Subject: [PATCH 01/35] ADFA-7139 Add DebuggerEndpointService and the debugger.endpoints permission Plugins such as AI-Agent-MCP need to reach the SQLite debugger of the app the user just built, without the user typing a port or token. DebuggerEndpointService.getEndpoints() returns the open project's endpoints as DebuggerEndpoint values (application ID, port, token, updated at), behind the new permission debugger.endpoints. Contract: SecurityException without the permission; IllegalStateException on a read failure or when called on the main thread; an empty list when no project is open or no app has reported. The API dump and docs/PLUGIN_API_CHANGELOG.md (26.43) are updated, and the plugin docs list the permission. A plugin that declares it needs plugin.min_ide_version 26.43: an older Code on the Go rejects the unknown permission at validation. Tests: the DebuggerEndpoint value class. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 11 +++ docs/PLUGIN_AUTHORING.md | 1 + docs/plugin-api.md | 2 +- plugin-api/api/plugin-api.api | 17 ++++ .../plugins/services/DebuggerEndpoint.java | 98 +++++++++++++++++++ .../services/DebuggerEndpointService.java | 36 +++++++ .../com/itsaky/androidide/plugins/IPlugin.kt | 1 + .../services/DebuggerEndpointTest.java | 56 +++++++++++ 8 files changed, 221 insertions(+), 1 deletion(-) create mode 100644 plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java create mode 100644 plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java create mode 100644 plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index d37c7f42c7..b74e6290c3 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -36,6 +36,17 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] = diffed from `plugin-api/src` history (predates the dump; symbol-accurate). ### 26.43 — unreleased +- **added — Find the SQLite debugger of the open project's apps** _(ADFA-7139)_ **[verified]** + `DebuggerEndpointService.getEndpoints()` returns a `List`, one per app of the open + project that has reported to the IDE: `applicationId`, `port` (on `127.0.0.1`), `token` (the bearer + token the server requires) and `updatedAtMillis`. The list is empty, never null, when no project is + open or no app has reported. Port and token change every time the app starts, so call again after a + refused connection or a 401/403. The call reads the IDE's database: use a background thread. It needs + the new `debugger.endpoints` permission (`PluginPermission.DEBUGGER_ENDPOINTS`) and throws + `SecurityException` without it, and `IllegalStateException` on the main thread or when the database + cannot be read (an unreadable database is not reported as an empty list). Floor `plugin.min_ide_version` + at `26.43`: an IDE of 26.42 or older rejects the unknown `debugger.endpoints` permission when it + validates the manifest, so it refuses to install a plugin that declares it. - **tooling — Interface bodies are Java default methods again** _(ADFA-6560)_ **[verified]** Since ADFA-4058 (May 2026) pinned `languageVersion`, `plugin-api` compiled each Kotlin interface body as an abstract method plus a `DefaultImpls` static. Plugins built against an earlier diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index eff39136fe..72d536332e 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -343,6 +343,7 @@ Defined by `PluginPermission` in `plugin-api/src/main/kotlin/com/itsaky/androidi | `project.structure` | Modify project structure | | `native.code` | Execute native machine code | | `ide.environment.write` | Write to IDE-managed directories (Android SDK, NDK, cache) | +| `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers | ## Contributing a language diff --git a/docs/plugin-api.md b/docs/plugin-api.md index 3eb7d85b76..7eeec75834 100644 --- a/docs/plugin-api.md +++ b/docs/plugin-api.md @@ -22,7 +22,7 @@ The surface a plugin binds to is broader than one module. All of the following a - **Wire/format contracts outside the module:** - Manifest `` keys — `plugin.id`, `plugin.name`, `plugin.version`, `plugin.description`, `plugin.author`, `plugin.main_class`, `plugin.min_ide_version`, `plugin.max_ide_version`, `plugin.permissions`, `plugin.sidebar_items`, `plugin.icon_day`, `plugin.icon_night`, `plugin.vcs_revision`, `plugin.build_timestamp`. Matched **by string** — a rename silently breaks every plugin. - Plugin language assets: `lib//libtree-sitter-.so` exporting `tree_sitter_`, the query file names under `TreeSitterGrammar.queriesAssetPath`, and the standard capture names mapped by each colour scheme's `generic.json`. - - Permission **key strings** (`filesystem.read`, `filesystem.write`, `network.access`, `system.commands`, `ide.settings`, `project.structure`, `native.code`, `ide.environment.write`) — also matched by string. + - Permission **key strings** (`filesystem.read`, `filesystem.write`, `network.access`, `system.commands`, `ide.settings`, `project.structure`, `native.code`, `ide.environment.write`, `debugger.endpoints`) — also matched by string. - The path allowlist and per-plugin data directories enforced by `IdeFileService` / `IdeArchiveService`. - File/format contracts: the `.cgp` package format (including `assets/cgp-build.properties`, the provenance record the builder writes into every artifact — see [PLUGIN_AUTHORING.md](PLUGIN_AUTHORING.md#provenance)), the `.cgt` template format, the `plugin_documentation.db` schema, `.codeonthego/scripts.json`, the TextMate snippet syntax, and the `http://localhost:6174/` help-server URL scheme with the `plugin//` namespace. diff --git a/plugin-api/api/plugin-api.api b/plugin-api/api/plugin-api.api index df35e7d108..85403778ad 100644 --- a/plugin-api/api/plugin-api.api +++ b/plugin-api/api/plugin-api.api @@ -107,6 +107,7 @@ public final class com/itsaky/androidide/plugins/PluginMetadata : android/os/Par } public final class com/itsaky/androidide/plugins/PluginPermission : java/lang/Enum { + public static final field DEBUGGER_ENDPOINTS Lcom/itsaky/androidide/plugins/PluginPermission; public static final field FILESYSTEM_READ Lcom/itsaky/androidide/plugins/PluginPermission; public static final field FILESYSTEM_WRITE Lcom/itsaky/androidide/plugins/PluginPermission; public static final field IDE_ENVIRONMENT_WRITE Lcom/itsaky/androidide/plugins/PluginPermission; @@ -1651,6 +1652,22 @@ public final class com/itsaky/androidide/plugins/services/CursorPosition { public fun toString ()Ljava/lang/String; } +public final class com/itsaky/androidide/plugins/services/DebuggerEndpoint { + public fun (Ljava/lang/String;ILjava/lang/String;J)V + public fun equals (Ljava/lang/Object;)Z + public fun getApplicationId ()Ljava/lang/String; + public fun getPort ()I + public fun getToken ()Ljava/lang/String; + public fun getUpdatedAtMillis ()J + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + +public abstract interface class com/itsaky/androidide/plugins/services/DebuggerEndpointService { + public static final field CONTRACT_VERSION I + public abstract fun getEndpoints ()Ljava/util/List; +} + public abstract interface class com/itsaky/androidide/plugins/services/EditorContentChangeListener { public abstract fun onContentChanged (Ljava/lang/String;IILjava/lang/String;)V } diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java new file mode 100644 index 0000000000..b54412d8e8 --- /dev/null +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java @@ -0,0 +1,98 @@ +package com.itsaky.androidide.plugins.services; + +import androidx.annotation.NonNull; +import java.util.Objects; + +/** + * Where one app's SQLite debugger server is listening, as the app last reported it to the IDE. Immutable. + * + *

+ * The port and the token are chosen by the app on every start, so a value read here goes stale when the app dies or is relaunched; a client that is refused (or answered 401/403) asks {@link DebuggerEndpointService#getEndpoints} again instead of retrying the same values. The token is a credential for the debugger server: do not log it or persist it. {@link #toString} leaves it out. + */ +public final class DebuggerEndpoint { + + private final String applicationId; + private final int port; + private final String token; + private final long updatedAtMillis; + + /** + * Creates an endpoint. + * + * @param applicationId + * the app's package name (must not be null) + * @param port + * the TCP port the debugger server listens on, on the loopback interface + * @param token + * the bearer token the server requires (must not be null) + * @param updatedAtMillis + * when the app reported these values, in milliseconds since the Unix epoch + */ + public DebuggerEndpoint(@NonNull String applicationId, int port, @NonNull String token, long updatedAtMillis) { + this.applicationId = Objects.requireNonNull(applicationId, "applicationId"); + this.port = port; + this.token = Objects.requireNonNull(token, "token"); + this.updatedAtMillis = updatedAtMillis; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof DebuggerEndpoint)) { + return false; + } + final DebuggerEndpoint that = (DebuggerEndpoint) other; + return port == that.port && updatedAtMillis == that.updatedAtMillis && applicationId.equals(that.applicationId) && token.equals(that.token); + } + + /** + * Gets the app's package name, which identifies the app within the project. + * + * @return the application ID (never null) + */ + @NonNull + public String getApplicationId() { + return applicationId; + } + + /** + * Gets the port the debugger server listens on, on {@code 127.0.0.1}. + * + * @return the port + */ + public int getPort() { + return port; + } + + /** + * Gets the bearer token the server requires on every request. + * + * @return the token (never null) + */ + @NonNull + public String getToken() { + return token; + } + + /** + * Gets when the app reported {@link #getPort} and {@link #getToken}. + * + * @return milliseconds since the Unix epoch + */ + public long getUpdatedAtMillis() { + return updatedAtMillis; + } + + @Override + public int hashCode() { + return Objects.hash(applicationId, port, token, updatedAtMillis); + } + + @NonNull + @Override + public String toString() { + return "DebuggerEndpoint{applicationId=" + applicationId + ", port=" + port + ", updatedAtMillis=" + updatedAtMillis + "}"; + } +} diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java new file mode 100644 index 0000000000..67c4a2a80d --- /dev/null +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -0,0 +1,36 @@ +package com.itsaky.androidide.plugins.services; + +import androidx.annotation.NonNull; +import java.util.List; + +/** + * Tells a plugin where the SQLite debugger servers of the open project's apps are listening, so a plugin such as an MCP client can connect without the user typing a port or token. + * + *

+ * The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it, like the other permission-gated services. + * + *

+ * Calls are synchronous, as in {@link IdeLogService} and {@link IdeProjectService}, rather than returning a {@link java.util.concurrent.CompletableFuture} as the services that start long work do: the answer is a small read of the IDE's own database, not an operation with a lifecycle. That read is disk I/O, so call from a background thread: on the main thread the call throws {@link IllegalStateException}. + */ +public interface DebuggerEndpointService { + + /** + * Contract revision, bumped whenever a member is added here. It marks the revision and does not negotiate one; see {@link ToolSourceRegistry#CONTRACT_VERSION}. + */ + int CONTRACT_VERSION = 1; + + /** + * Gets the debugger endpoints of the open project, one per app that has reported. Read fresh on every call, so call it again after a connection fails: a relaunched app has a new port and token. + * + *

+ * An app the IDE installed or launched but that has not yet reported is not listed. + * + * @return the endpoints (never null; empty when no project is open or no app has reported) + * @throws SecurityException + * if the plugin lacks the {@code debugger.endpoints} permission + * @throws IllegalStateException + * if called on the main thread, or if the IDE's database could not be read. A failed read is not the same as no apps: keep what you had and try again later + */ + @NonNull + List getEndpoints(); +} diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt index c54581cc1f..c0db691a08 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt @@ -54,6 +54,7 @@ enum class PluginPermission( PROJECT_STRUCTURE("project.structure", "Modify project structure"), NATIVE_CODE("native.code", "Execute native machine code"), IDE_ENVIRONMENT_WRITE("ide.environment.write", "Write to IDE-managed directories such as the Android SDK, NDK, and cache"), + DEBUGGER_ENDPOINTS("debugger.endpoints", "Read the port and token of the open project's SQLite debugger servers"), } data class PluginInfo( diff --git a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java new file mode 100644 index 0000000000..db35c1407d --- /dev/null +++ b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java @@ -0,0 +1,56 @@ +package com.itsaky.androidide.plugins.services; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.itsaky.androidide.plugins.PluginPermission; +import org.junit.Test; + +public class DebuggerEndpointTest { + + @Test + public void equalityCoversEveryField() { + final DebuggerEndpoint base = new DebuggerEndpoint("a", 1, "t", 2L); + assertEquals(base, new DebuggerEndpoint("a", 1, "t", 2L)); + assertEquals(base.hashCode(), new DebuggerEndpoint("a", 1, "t", 2L).hashCode()); + assertNotEquals(base, new DebuggerEndpoint("b", 1, "t", 2L)); + assertNotEquals(base, new DebuggerEndpoint("a", 9, "t", 2L)); + assertNotEquals(base, new DebuggerEndpoint("a", 1, "u", 2L)); + assertNotEquals(base, new DebuggerEndpoint("a", 1, "t", 3L)); + } + + @Test + public void exposesWhatItWasBuiltWith() { + final DebuggerEndpoint endpoint = new DebuggerEndpoint("com.example.app", 43210, "secret", 1234L); + assertEquals("com.example.app", endpoint.getApplicationId()); + assertEquals(43210, endpoint.getPort()); + assertEquals("secret", endpoint.getToken()); + assertEquals(1234L, endpoint.getUpdatedAtMillis()); + } + + @Test + public void nullApplicationIdOrTokenIsRejected() { + try { + new DebuggerEndpoint(null, 1, "t", 0L); + fail(); + } catch (NullPointerException expected) {} + try { + new DebuggerEndpoint("a", 1, null, 0L); + fail(); + } catch (NullPointerException expected) {} + } + + @Test + public void permissionKeyIsStable() { + assertEquals("debugger.endpoints", PluginPermission.DEBUGGER_ENDPOINTS.getKey()); + assertTrue(DebuggerEndpointService.CONTRACT_VERSION >= 1); + } + + @Test + public void toStringDoesNotLeakTheToken() { + assertFalse(new DebuggerEndpoint("a", 1, "hunter2", 2L).toString().contains("hunter2")); + } +} From a84d59b3574d3898733e3caf4c742f820fc3f793 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:34:22 -0800 Subject: [PATCH 02/35] ADFA-7139 Implement DebuggerEndpointService in plugin-manager PluginManager hands each plugin a DebuggerEndpointServiceImpl, which checks the debugger.endpoints permission, refuses the main thread, and maps a read failure to IllegalStateException so a plugin cannot mistake a failure for "no app has reported". Tests: permission refused, no project, endpoints of another project not returned, read failure, main thread refused. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/manager/core/PluginManager.kt | 28 +++++++ .../services/DebuggerEndpointServiceImpl.kt | 59 +++++++++++++ .../DebuggerEndpointServiceImplTest.kt | 82 +++++++++++++++++++ 3 files changed, 169 insertions(+) create mode 100644 plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt create mode 100644 plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.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 03e42340e7..d6d1b57665 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 @@ -42,6 +42,7 @@ import com.itsaky.androidide.plugins.manager.loaders.toPluginMetadata import com.itsaky.androidide.plugins.manager.project.PluginProjectManager import com.itsaky.androidide.plugins.manager.security.PluginSecurityManager import com.itsaky.androidide.plugins.manager.services.CogoProjectProvider +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeArchiveServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeCommandServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeEditorServiceImpl @@ -62,6 +63,7 @@ import com.itsaky.androidide.plugins.manager.services.IdeUIServiceImpl import com.itsaky.androidide.plugins.manager.services.PluginBuildService import com.itsaky.androidide.plugins.manager.snippets.PluginSnippetManager import com.itsaky.androidide.plugins.manager.ui.PluginEditorTabManager +import com.itsaky.androidide.plugins.services.DebuggerEndpointService import com.itsaky.androidide.plugins.services.IdeArchiveService import com.itsaky.androidide.plugins.services.IdeBuildService import com.itsaky.androidide.plugins.services.IdeCommandService @@ -1577,6 +1579,19 @@ class PluginManager private constructor( IdeFeatureFlagServiceImpl() } + registerServiceWithErrorHandling( + pluginServiceRegistry, + DebuggerEndpointService::class.java, + pluginId, + "debugger_endpoint", + ) { + DebuggerEndpointServiceImpl( + pluginId = pluginId, + permissions = permissions, + projectRootProvider = { projectProvider.getCurrentProject()?.rootDir }, + ) + } + registerServiceWithErrorHandling( pluginServiceRegistry, IdeTemplateService::class.java, @@ -1846,6 +1861,19 @@ class PluginManager private constructor( IdeFeatureFlagServiceImpl() } + registerServiceWithErrorHandling( + pluginServiceRegistry, + DebuggerEndpointService::class.java, + pluginId, + "debugger_endpoint", + ) { + DebuggerEndpointServiceImpl( + pluginId = pluginId, + permissions = permissions, + projectRootProvider = { projectProvider.getCurrentProject()?.rootDir }, + ) + } + registerServiceWithErrorHandling( pluginServiceRegistry, IdeTemplateService::class.java, diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt new file mode 100644 index 0000000000..b5062368c3 --- /dev/null +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -0,0 +1,59 @@ +package com.itsaky.androidide.plugins.manager.services + +import android.os.Looper +import com.itsaky.androidide.plugins.PluginPermission +import com.itsaky.androidide.plugins.services.DebuggerEndpoint +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import org.slf4j.LoggerFactory +import java.io.File + +/** + * Where the host keeps what apps reported: the app module's `debugger_endpoint_table`. The app + * installs an implementation with [DebuggerEndpointSources.install]; this module cannot reach the + * table itself. + */ +fun interface DebuggerEndpointSource { + /** Returns the endpoints stored for the project at [projectLocation], as it appears in `recent_project_table.location`. */ + fun endpointsFor(projectLocation: String): List +} + +object DebuggerEndpointSources { + @Volatile + var current: DebuggerEndpointSource = DebuggerEndpointSource { emptyList() } + private set + + /** Installs the app's source, or restores the empty default when [source] is null. */ + fun install(source: DebuggerEndpointSource?) { + current = source ?: DebuggerEndpointSource { emptyList() } + } +} + +class DebuggerEndpointServiceImpl( + private val pluginId: String, + private val permissions: Set, + private val projectRootProvider: () -> File?, + private val sourceProvider: () -> DebuggerEndpointSource = { DebuggerEndpointSources.current }, + private val isMainThread: () -> Boolean = { Looper.myLooper() == Looper.getMainLooper() }, +) : DebuggerEndpointService { + override fun getEndpoints(): List { + if (PluginPermission.DEBUGGER_ENDPOINTS !in permissions) { + throw SecurityException( + "Plugin $pluginId does not have required permissions: ${PluginPermission.DEBUGGER_ENDPOINTS.name}", + ) + } + + check(!isMainThread()) { "DebuggerEndpointService.getEndpoints() reads a database; call it off the main thread" } + + val root = projectRootProvider() ?: return emptyList() + return try { + sourceProvider().endpointsFor(root.absolutePath) + } catch (e: Exception) { + log.warn("getEndpoints failed for plugin {}", pluginId, e) + throw IllegalStateException("Could not read the debugger endpoints: ${e.message}", e) + } + } + + private companion object { + private val log = LoggerFactory.getLogger(DebuggerEndpointServiceImpl::class.java) + } +} diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt new file mode 100644 index 0000000000..3d92e238c6 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -0,0 +1,82 @@ +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.services.DebuggerEndpoint +import org.junit.Assert.assertThrows +import org.junit.Test +import java.io.File + +class DebuggerEndpointServiceImplTest { + private val project = File("/data/projects/demo") + private val endpoint = DebuggerEndpoint("com.example.demo", 4321, "tok", 99L) + private val seen = mutableListOf() + private val source = + DebuggerEndpointSource { location -> + seen += location + if (location == project.absolutePath) listOf(endpoint) else emptyList() + } + + private fun service( + permissions: Set = setOf(PluginPermission.DEBUGGER_ENDPOINTS), + root: File? = project, + source: DebuggerEndpointSource = this.source, + mainThread: Boolean = false, + ) = DebuggerEndpointServiceImpl("p", permissions, { root }, { source }, { mainThread }) + + @Test + fun `returns the endpoints stored for the open project`() { + assertThat(service().getEndpoints()).containsExactly(endpoint) + assertThat(seen).containsExactly(project.absolutePath) + } + + @Test + fun `is empty and never asks the source when no project is open`() { + assertThat(service(root = null).getEndpoints()).isEmpty() + assertThat(seen).isEmpty() + } + + @Test + fun `is empty when the project has no endpoint`() { + assertThat(service(root = File("/data/projects/other")).getEndpoints()).isEmpty() + } + + @Test + fun `refuses a plugin without the permission`() { + val denied = service(permissions = setOf(PluginPermission.FILESYSTEM_READ, PluginPermission.NETWORK_ACCESS)) + + assertThrows(SecurityException::class.java) { denied.getEndpoints() } + assertThat(seen).isEmpty() + } + + @Test + fun `a failing source is reported, not mistaken for no apps`() { + val cause = IllegalStateException("db closed") + val failing = service(source = { throw cause }) + + val thrown = assertThrows(IllegalStateException::class.java) { failing.getEndpoints() } + assertThat(thrown).hasCauseThat().isSameInstanceAs(cause) + } + + @Test + fun `refuses to read on the main thread`() { + val onMain = service(mainThread = true) + + assertThrows(IllegalStateException::class.java) { onMain.getEndpoints() } + assertThat(seen).isEmpty() + } + + @Test + fun `the default source is empty until the app installs one`() { + DebuggerEndpointSources.install(null) + val defaulted = DebuggerEndpointServiceImpl("p", setOf(PluginPermission.DEBUGGER_ENDPOINTS), { project }, isMainThread = { false }) + assertThat(defaulted.getEndpoints()).isEmpty() + + DebuggerEndpointSources.install(source) + try { + assertThat(defaulted.getEndpoints()).containsExactly(endpoint) + } finally { + DebuggerEndpointSources.install(null) + } + } +} From 030c678fc5c501866b0a7d10e6e57f2fa01ecc31 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:34:22 -0800 Subject: [PATCH 03/35] ADFA-7139 Serve the stored debugger endpoints to plugins The app registers the service when it loads plugins, backed by debugger_endpoint_table (ADFA-7137). The repository looks endpoints up by the canonical project path, so a project opened through a symlink or a non-normalised path still finds the rows stored under its real location. Tests: repository lookup through a non-canonical path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../CredentialProtectedApplicationLoader.kt | 8 ++++++ .../DebuggerEndpointRepository.kt | 14 +++++++++++ .../DebuggerEndpointRepositoryTest.kt | 25 +++++++++++++++++++ 3 files changed, 47 insertions(+) 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..663ca06994 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -21,11 +21,13 @@ import com.itsaky.androidide.managers.ToolsManager import com.itsaky.androidide.plugins.PluginLogger import com.itsaky.androidide.plugins.base.PluginFragmentHelper import com.itsaky.androidide.plugins.manager.core.PluginManager +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSources 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.preferences.internal.DevOpsPreferences import com.itsaky.androidide.preferences.internal.GeneralPreferences +import com.itsaky.androidide.repositories.DebuggerEndpointRepository import com.itsaky.androidide.resources.localization.LocaleProvider import com.itsaky.androidide.services.builder.BuildOutputLocation import com.itsaky.androidide.tooling.api.messages.result.TaskExecutionResult @@ -41,10 +43,12 @@ import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode +import org.koin.core.context.GlobalContext import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.atomic.AtomicBoolean @@ -404,6 +408,10 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { setupBuildServiceProviders() setupProjectManipulationProviders() IdeLogServiceImpl.getInstance().setLogReader(LogsProvider::read) + // Plugins call it on a background thread (DebuggerEndpointService), so blocking on Room is fine. + DebuggerEndpointSources.install { location -> + runBlocking { GlobalContext.get().get().reportedEndpoints(File(location)) } + } IdeTerminalServiceImpl.setSessionLauncher(PluginTerminalLauncher { application.foregroundActivity }) logger.info("Plugin services configured successfully") } diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index ea7ff37729..f1e102bec2 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -11,6 +11,7 @@ import kotlinx.coroutines.withContext import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.ConcurrentHashMap +import com.itsaky.androidide.plugins.services.DebuggerEndpoint as PluginDebuggerEndpoint /** * Which app each project builds, and the SQLite debugger endpoint the app last reported (ADFA-7137). @@ -132,6 +133,19 @@ class DebuggerEndpointRepository( false } + /** + * The endpoints the apps of [projectDir] have reported, for the plugin API (ADFA-7139). Looked + * up by the canonical path, as the pairing stores it; apps that have not reported yet are left + * out. Unlike the writes, a read failure is thrown: the plugin API reports it rather than + * answering "no apps". + */ + suspend fun reportedEndpoints(projectDir: File): List = + dao.getByProjectLocation(projectDir.canonicalProjectLocation()).mapNotNull { row -> + val token = row.token ?: return@mapNotNull null + val port = row.port ?: return@mapNotNull null + PluginDebuggerEndpoint(row.applicationId, port, token, row.updatedAt ?: 0L) + } + private companion object { private const val PENDING_INSTALL_MAX_AGE_MILLIS = 5 * 60 * 1000L private val log = LoggerFactory.getLogger(DebuggerEndpointRepository::class.java) diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index b0e6d0c6fb..caa6f09a3a 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -337,4 +337,29 @@ class DebuggerEndpointRepositoryTest { assertThat(result.exceptionOrNull()).isInstanceOf(kotlinx.coroutines.CancellationException::class.java) } + + @Test + fun `reported endpoints are found through a non-canonical path and unreported apps are left out`() = + runBlocking { + val dir = + java.nio.file.Files + .createTempDirectory("proj") + .toFile() + try { + addProject(dir.canonicalPath) + assertThat(repository.recordInstalled("com.example.reported", dir.canonicalPath)).isTrue() + assertThat(repository.recordInstalled("com.example.silent", dir.canonicalPath)).isTrue() + assertThat(repository.storeEndpoint("com.example.reported", endpoint)).isTrue() + + val endpoints = repository.reportedEndpoints(File(dir, "../" + dir.name)) + + assertThat(endpoints.map { it.applicationId }).containsExactly("com.example.reported") + val e = endpoints.single() + assertThat(e.port).isEqualTo(5555) + assertThat(e.token).isEqualTo("tok-en_1") + assertThat(e.updatedAtMillis).isEqualTo(1234L) + } finally { + dir.delete() + } + } } From 4181e7ced4deca8231443671fbee25acb2fcb9e7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:34:22 -0800 Subject: [PATCH 04/35] ADFA-7139 Docs: describe DebuggerEndpointService in the sqlite-debugger README Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- subprojects/sqlite-debugger/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index aae2d42883..8a5a961e70 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -24,6 +24,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. - On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. The row is deleted with its project (foreign key, ON DELETE CASCADE). +- Plugins get the stored endpoints through `DebuggerEndpointService` (plugin API), which needs the `debugger.endpoints` permission. `getEndpoints()` returns one entry per app of the open project that has reported (application ID, port, token, last update), read fresh on every call and not on the main thread, so a plugin asks again after a refused connection. The AI-Agent-MCP plugin (addons repository) is the first client. ### The event record @@ -51,5 +52,4 @@ No workflow in `.github/workflows` runs either yet. ## Not done yet - Gradle plugin wiring and the build-time rewrite that adds the library to debug builds (ADFA-7138). -- The AI-Agent-MCP side that connects to the server (ADFA-7139). - Verification on a device. The C tests run on the host and the Kotlin tests on the JVM; nothing has run in an app on a device or emulator. From 6a9981445dec146af587ad556e146831d3571366 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 23:19:39 -0800 Subject: [PATCH 05/35] ADFA-7139 Leave uninstalled apps out of the endpoints and rethrow interrupts reportedEndpoints no longer returns the stored port and token of an app that is no longer installed (injected check, PackageManager in the app). No is needed: Code on the Go targets SDK 28, below the package visibility filter of SDK 30. The Javadoc says an endpoint can still be stale after the process dies and that updatedAtMillis is when it last reported. DebuggerEndpointServiceImpl rethrows InterruptedException (restoring the flag) and CancellationException unchanged instead of wrapping them. Tests: an uninstalled app is left out, installed ones are returned, the interrupt and the cancellation pass through; all three fail with the fix removed. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../com/itsaky/androidide/di/AppModule.kt | 7 +++- .../DebuggerEndpointRepository.kt | 24 +++++++++++- .../DebuggerEndpointRepositoryTest.kt | 39 +++++++++++++++++++ .../plugins/services/DebuggerEndpoint.java | 3 ++ .../services/DebuggerEndpointService.java | 2 +- .../services/DebuggerEndpointServiceImpl.kt | 6 +++ .../DebuggerEndpointServiceImplTest.kt | 21 ++++++++++ subprojects/sqlite-debugger/README.md | 2 +- 8 files changed, 99 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt b/app/src/main/java/com/itsaky/androidide/di/AppModule.kt index eb3bc46704..97501b3851 100644 --- a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/AppModule.kt @@ -63,7 +63,12 @@ val coreModule = } single { - DebuggerEndpointRepository(get(), get(named(APPLICATION_SCOPE))) + val packageManager = androidContext().packageManager + DebuggerEndpointRepository( + get(), + get(named(APPLICATION_SCOPE)), + isInstalled = { DebuggerEndpointRepository.isPackageInstalled(packageManager, it) }, + ) } single { diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index f1e102bec2..bf74041864 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.repositories +import android.content.pm.PackageManager import com.itsaky.androidide.roomData.recentproject.DebuggerEndpointDao import com.itsaky.androidide.sqlitedebugger.DebuggerEndpointValidation import com.itsaky.androidide.utils.canonicalProjectLocation @@ -23,6 +24,7 @@ class DebuggerEndpointRepository( private val dao: DebuggerEndpointDao, private val scope: CoroutineScope, private val clock: () -> Long = System::currentTimeMillis, + private val isInstalled: (String) -> Boolean = { true }, ) { private class PendingInstall( val location: String, @@ -136,17 +138,35 @@ class DebuggerEndpointRepository( /** * The endpoints the apps of [projectDir] have reported, for the plugin API (ADFA-7139). Looked * up by the canonical path, as the pairing stores it; apps that have not reported yet are left - * out. Unlike the writes, a read failure is thrown: the plugin API reports it rather than + * out, and so are apps that are no longer installed: their stored port and token would otherwise + * come back as live. An endpoint can still be stale when the app's process has died. Unlike the writes, a read failure is thrown: the plugin API reports it rather than * answering "no apps". */ suspend fun reportedEndpoints(projectDir: File): List = dao.getByProjectLocation(projectDir.canonicalProjectLocation()).mapNotNull { row -> + if (!isInstalled(row.applicationId)) return@mapNotNull null val token = row.token ?: return@mapNotNull null val port = row.port ?: return@mapNotNull null PluginDebuggerEndpoint(row.applicationId, port, token, row.updatedAt ?: 0L) } - private companion object { + companion object { + /** + * Whether [applicationId] is installed. Every package is visible because Code on the Go targets SDK 28; at a + * target of 30 or later, package visibility filtering would make every endpoint look uninstalled unless the + * manifest declares a matching ``. + */ + fun isPackageInstalled( + packageManager: PackageManager, + applicationId: String, + ): Boolean = + try { + packageManager.getPackageInfo(applicationId, 0) + true + } catch (e: PackageManager.NameNotFoundException) { + false + } + private const val PENDING_INSTALL_MAX_AGE_MILLIS = 5 * 60 * 1000L private val log = LoggerFactory.getLogger(DebuggerEndpointRepository::class.java) } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index caa6f09a3a..71f8af57d5 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -362,4 +362,43 @@ class DebuggerEndpointRepositoryTest { dir.delete() } } + + @Test + fun `an app that is no longer installed is left out and installed ones are returned`() = + runBlocking { + val dir = + java.nio.file.Files + .createTempDirectory("proj") + .toFile() + try { + addProject(dir.canonicalPath) + val installed = setOf("com.example.alive") + val pruning = + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { 1234L }, + isInstalled = { it in installed }, + ) + for (id in listOf("com.example.alive", "com.example.gone")) { + assertThat(pruning.recordInstalled(id, dir.canonicalPath)).isTrue() + assertThat(pruning.storeEndpoint(id, endpoint)).isTrue() + } + + val endpoints = pruning.reportedEndpoints(dir) + + assertThat(endpoints.map { it.applicationId }).containsExactly("com.example.alive") + } finally { + dir.delete() + } + } + + @Test + fun `the package manager check tells installed from missing apps`() { + val app = ApplicationProvider.getApplicationContext() + val packageManager = app.packageManager + + assertThat(DebuggerEndpointRepository.isPackageInstalled(packageManager, app.packageName)).isTrue() + assertThat(DebuggerEndpointRepository.isPackageInstalled(packageManager, "com.example.not.installed")).isFalse() + } } diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java index b54412d8e8..943fd5a236 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpoint.java @@ -8,6 +8,9 @@ * *

* The port and the token are chosen by the app on every start, so a value read here goes stale when the app dies or is relaunched; a client that is refused (or answered 401/403) asks {@link DebuggerEndpointService#getEndpoints} again instead of retrying the same values. The token is a credential for the debugger server: do not log it or persist it. {@link #toString} leaves it out. + * + *

+ * An endpoint whose app has been uninstalled is not returned, but one whose process has died is: nothing removes it until the app reports again. {@link #getUpdatedAtMillis} is when the app last reported, not a sign that it is still running. */ public final class DebuggerEndpoint { diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index 67c4a2a80d..afc28d2aa8 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -23,7 +23,7 @@ public interface DebuggerEndpointService { * Gets the debugger endpoints of the open project, one per app that has reported. Read fresh on every call, so call it again after a connection fails: a relaunched app has a new port and token. * *

- * An app the IDE installed or launched but that has not yet reported is not listed. + * An app the IDE installed or launched but that has not yet reported is not listed, and neither is an app that has since been uninstalled. An endpoint can still be stale: when the app's process has died, its last reported port and token stay here until the app reports again, so treat {@link DebuggerEndpoint#getUpdatedAtMillis} (when it last reported) as a hint, and when a connection is refused, call this again and reconnect. * * @return the endpoints (never null; empty when no project is open or no app has reported) * @throws SecurityException diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index b5062368c3..9b8d180845 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -6,6 +6,7 @@ import com.itsaky.androidide.plugins.services.DebuggerEndpoint import com.itsaky.androidide.plugins.services.DebuggerEndpointService import org.slf4j.LoggerFactory import java.io.File +import java.util.concurrent.CancellationException /** * Where the host keeps what apps reported: the app module's `debugger_endpoint_table`. The app @@ -47,6 +48,11 @@ class DebuggerEndpointServiceImpl( val root = projectRootProvider() ?: return emptyList() return try { sourceProvider().endpointsFor(root.absolutePath) + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + throw e + } catch (e: CancellationException) { + throw e } catch (e: Exception) { log.warn("getEndpoints failed for plugin {}", pluginId, e) throw IllegalStateException("Could not read the debugger endpoints: ${e.message}", e) diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt index 3d92e238c6..4d6d1d4e11 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -58,6 +58,27 @@ class DebuggerEndpointServiceImplTest { assertThat(thrown).hasCauseThat().isSameInstanceAs(cause) } + @Test + fun `an interrupt from the source is rethrown unchanged and keeps the flag`() { + val interrupted = service(source = { throw InterruptedException("stop") }) + + try { + val thrown = assertThrows(InterruptedException::class.java) { interrupted.getEndpoints() } + assertThat(thrown).hasMessageThat().isEqualTo("stop") + assertThat(Thread.currentThread().isInterrupted).isTrue() + } finally { + Thread.interrupted() + } + } + + @Test + fun `a cancellation from the source is rethrown unchanged`() { + val cancelled = service(source = { throw java.util.concurrent.CancellationException("cancelled") }) + + val thrown = assertThrows(java.util.concurrent.CancellationException::class.java) { cancelled.getEndpoints() } + assertThat(thrown).hasMessageThat().isEqualTo("cancelled") + } + @Test fun `refuses to read on the main thread`() { val onMain = service(mainThread = true) diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 8a5a961e70..82bde03dca 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -24,7 +24,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. - On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. The row is deleted with its project (foreign key, ON DELETE CASCADE). -- Plugins get the stored endpoints through `DebuggerEndpointService` (plugin API), which needs the `debugger.endpoints` permission. `getEndpoints()` returns one entry per app of the open project that has reported (application ID, port, token, last update), read fresh on every call and not on the main thread, so a plugin asks again after a refused connection. The AI-Agent-MCP plugin (addons repository) is the first client. +- Plugins get the stored endpoints through `DebuggerEndpointService` (plugin API), which needs the `debugger.endpoints` permission. `getEndpoints()` returns one entry per app of the open project that has reported (application ID, port, token, last update), read fresh on every call and not on the main thread, so a plugin asks again after a refused connection. Apps that are no longer installed are left out; an app whose process died is still listed until it reports again. The AI-Agent-MCP plugin (addons repository) is the first client. ### The event record From cbe541ac542a72658e0767a9199ca91df7b45472 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 23:19:39 -0800 Subject: [PATCH 06/35] ADFA-7139 Docs: DebuggerEndpointService ships in 26.47, not 26.43 26.43 to 26.46 are released without it. The changelog entry moves to a new 26.47 section and the floor plugin.min_ide_version is 26.47. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index b74e6290c3..536419803c 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -35,18 +35,21 @@ 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.43 — unreleased +### 26.47 — unreleased - **added — Find the SQLite debugger of the open project's apps** _(ADFA-7139)_ **[verified]** `DebuggerEndpointService.getEndpoints()` returns a `List`, one per app of the open project that has reported to the IDE: `applicationId`, `port` (on `127.0.0.1`), `token` (the bearer token the server requires) and `updatedAtMillis`. The list is empty, never null, when no project is open or no app has reported. Port and token change every time the app starts, so call again after a - refused connection or a 401/403. The call reads the IDE's database: use a background thread. It needs + refused connection or a 401/403. An app that was uninstalled is left out, but one whose process died stays + listed until it reports again (`updatedAtMillis` is when it last reported). The call reads the IDE's database: use a background thread. It needs the new `debugger.endpoints` permission (`PluginPermission.DEBUGGER_ENDPOINTS`) and throws `SecurityException` without it, and `IllegalStateException` on the main thread or when the database cannot be read (an unreadable database is not reported as an empty list). Floor `plugin.min_ide_version` - at `26.43`: an IDE of 26.42 or older rejects the unknown `debugger.endpoints` permission when it + at `26.47`: an IDE of 26.46 or older rejects the unknown `debugger.endpoints` permission when it validates the manifest, so it refuses to install a plugin that declares it. + +### 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 body as an abstract method plus a `DefaultImpls` static. Plugins built against an earlier From 238edfbc6d6bb910f4765cf44ee37a62b89d52a0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:03:21 -0800 Subject: [PATCH 07/35] ADFA-7139 Inject the SQLite debugger endpoint source through Koin The plugin services setup resolved DebuggerEndpointRepository with GlobalContext.get() inside the source lambda, against ADR 0006 and out of reach of a test. coreModule now binds the DebuggerEndpointSource, built on the repository by constructor, and CredentialProtectedApplicationLoader resolves it as a KoinComponent, the pattern DeviceProtectedApplicationLoader already uses. DebuggerEndpointBindingsTest resolves the binding from coreModule over an in-memory database. Review R8 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../CredentialProtectedApplicationLoader.kt | 15 ++-- .../com/itsaky/androidide/di/AppModule.kt | 9 +++ .../di/DebuggerEndpointBindingsTest.kt | 80 +++++++++++++++++++ 3 files changed, 96 insertions(+), 8 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/di/DebuggerEndpointBindingsTest.kt 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 663ca06994..552a14959f 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -21,13 +21,13 @@ import com.itsaky.androidide.managers.ToolsManager import com.itsaky.androidide.plugins.PluginLogger import com.itsaky.androidide.plugins.base.PluginFragmentHelper import com.itsaky.androidide.plugins.manager.core.PluginManager +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSource import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSources 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.preferences.internal.DevOpsPreferences import com.itsaky.androidide.preferences.internal.GeneralPreferences -import com.itsaky.androidide.repositories.DebuggerEndpointRepository import com.itsaky.androidide.resources.localization.LocaleProvider import com.itsaky.androidide.services.builder.BuildOutputLocation import com.itsaky.androidide.tooling.api.messages.result.TaskExecutionResult @@ -43,12 +43,12 @@ import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode -import org.koin.core.context.GlobalContext +import org.koin.core.component.KoinComponent +import org.koin.core.component.get import org.slf4j.LoggerFactory import java.io.File import java.util.concurrent.atomic.AtomicBoolean @@ -63,7 +63,9 @@ import kotlin.system.exitProcess * * @author Akash Yadav */ -internal object CredentialProtectedApplicationLoader : ApplicationLoader { +internal object CredentialProtectedApplicationLoader : + ApplicationLoader, + KoinComponent { private val logger = LoggerFactory.getLogger(CredentialProtectedApplicationLoader::class.java) private val _isLoaded = AtomicBoolean(false) @@ -408,10 +410,7 @@ internal object CredentialProtectedApplicationLoader : ApplicationLoader { setupBuildServiceProviders() setupProjectManipulationProviders() IdeLogServiceImpl.getInstance().setLogReader(LogsProvider::read) - // Plugins call it on a background thread (DebuggerEndpointService), so blocking on Room is fine. - DebuggerEndpointSources.install { location -> - runBlocking { GlobalContext.get().get().reportedEndpoints(File(location)) } - } + DebuggerEndpointSources.install(get()) IdeTerminalServiceImpl.setSessionLauncher(PluginTerminalLauncher { application.foregroundActivity }) logger.info("Plugin services configured successfully") } diff --git a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt b/app/src/main/java/com/itsaky/androidide/di/AppModule.kt index 97501b3851..e063d9dec1 100644 --- a/app/src/main/java/com/itsaky/androidide/di/AppModule.kt +++ b/app/src/main/java/com/itsaky/androidide/di/AppModule.kt @@ -7,6 +7,7 @@ import com.itsaky.androidide.deeplink.PendingDeepLinkOpen import com.itsaky.androidide.editor.language.outline.OutlineProvider import com.itsaky.androidide.editor.language.outline.TreeSitterOutlineProvider import com.itsaky.androidide.git.core.GitCredentialsManager +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSource import com.itsaky.androidide.repositories.DebuggerEndpointRepository import com.itsaky.androidide.repositories.RecentProjectRepository import com.itsaky.androidide.repositories.RecentProjectRepositoryImpl @@ -18,11 +19,13 @@ import com.itsaky.androidide.viewmodel.OutlineViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.runBlocking import org.koin.android.ext.koin.androidApplication import org.koin.android.ext.koin.androidContext import org.koin.core.module.dsl.viewModel import org.koin.core.qualifier.named import org.koin.dsl.module +import java.io.File /** Qualifier for the process-lifetime [CoroutineScope]; see the binding for why it is named. */ const val APPLICATION_SCOPE = "applicationScope" @@ -71,6 +74,12 @@ val coreModule = ) } + // What DebuggerEndpointService reads. Plugins call it off the main thread, so blocking on Room is fine. + single { + val repository = get() + DebuggerEndpointSource { location -> runBlocking { repository.reportedEndpoints(File(location)) } } + } + single { RecentProjectRepositoryImpl(get()) } diff --git a/app/src/test/java/com/itsaky/androidide/di/DebuggerEndpointBindingsTest.kt b/app/src/test/java/com/itsaky/androidide/di/DebuggerEndpointBindingsTest.kt new file mode 100644 index 0000000000..fc3eda5847 --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/di/DebuggerEndpointBindingsTest.kt @@ -0,0 +1,80 @@ +package com.itsaky.androidide.di + +import android.app.Application +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSource +import com.itsaky.androidide.repositories.DebuggerEndpointRepository +import com.itsaky.androidide.roomData.recentproject.RecentProject +import com.itsaky.androidide.roomData.recentproject.RecentProjectRoomDatabase +import com.itsaky.androidide.sqlitedebugger.DebuggerEndpointValidation +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.koin.android.ext.koin.androidContext +import org.koin.core.Koin +import org.koin.dsl.koinApplication +import org.koin.dsl.module +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File +import java.nio.file.Files + +/** The SQLite debugger bindings of [coreModule], resolved as the app resolves them, over an in-memory database. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], application = Application::class) +class DebuggerEndpointBindingsTest { + private val app: Application get() = ApplicationProvider.getApplicationContext() + private lateinit var room: RecentProjectRoomDatabase + private lateinit var koin: Koin + private lateinit var project: File + + @Before + fun setUp() { + room = + Room + .inMemoryDatabaseBuilder(app, RecentProjectRoomDatabase::class.java) + .allowMainThreadQueries() + .build() + koin = + koinApplication { + androidContext(app) + allowOverride(true) + modules(coreModule, module { single { room } }) + }.koin + project = Files.createTempDirectory("proj").toFile() + runBlocking { + room.recentProjectDao().insert(RecentProject(name = "p", createdAt = "1", location = project.canonicalPath)) + } + } + + @After + fun tearDown() { + koin.close() + room.close() + project.deleteRecursively() + } + + private suspend fun report( + applicationId: String, + token: String, + ) { + val repository = koin.get() + assertThat(repository.recordInstalled(applicationId, project.canonicalPath)).isTrue() + assertThat(repository.storeEndpoint(applicationId, DebuggerEndpointValidation.Endpoint(token, 5555))).isTrue() + } + + @Test + fun `the source plugins read returns what the bound repository stored`() = + runBlocking { + report(app.packageName, "tok-en_1") + + val endpoints = koin.get().endpointsFor(project.path) + + assertThat(endpoints.map { it.applicationId }).containsExactly(app.packageName) + assertThat(endpoints.single().token).isEqualTo("tok-en_1") + } +} From 89b5c7e120118ee6e3a535ad44d615209ae80f2d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:03:54 -0800 Subject: [PATCH 08/35] ADFA-7139 Require the installed-app check of DebuggerEndpointRepository isInstalled defaulted to { true }, so a binding that dropped the argument would serve an uninstalled app's stored port and token as live, and no test would fail. The parameter has no default now; the tests pass it explicitly. DebuggerEndpointBindingsTest resolves the repository from coreModule and checks an app the package manager does not know is left out. Review R5 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../repositories/DebuggerEndpointRepository.kt | 3 ++- .../androidide/di/DebuggerEndpointBindingsTest.kt | 11 +++++++++++ .../repositories/DebuggerEndpointRepositoryTest.kt | 8 +++++--- .../sqlitedebugger/DebuggerEndpointReceiverTest.kt | 2 +- 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index bf74041864..a48e43e423 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -24,7 +24,8 @@ class DebuggerEndpointRepository( private val dao: DebuggerEndpointDao, private val scope: CoroutineScope, private val clock: () -> Long = System::currentTimeMillis, - private val isInstalled: (String) -> Boolean = { true }, + /** Required, with no default: one that answered true would serve an uninstalled app's port and token as live. */ + private val isInstalled: (String) -> Boolean, ) { private class PendingInstall( val location: String, diff --git a/app/src/test/java/com/itsaky/androidide/di/DebuggerEndpointBindingsTest.kt b/app/src/test/java/com/itsaky/androidide/di/DebuggerEndpointBindingsTest.kt index fc3eda5847..4e8bc0406c 100644 --- a/app/src/test/java/com/itsaky/androidide/di/DebuggerEndpointBindingsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/di/DebuggerEndpointBindingsTest.kt @@ -77,4 +77,15 @@ class DebuggerEndpointBindingsTest { assertThat(endpoints.map { it.applicationId }).containsExactly(app.packageName) assertThat(endpoints.single().token).isEqualTo("tok-en_1") } + + @Test + fun `the bound repository asks the package manager, so an app that is not installed is left out`() = + runBlocking { + report(app.packageName, "tok-en_1") + report("com.example.not.installed", "tok-en_2") + + val endpoints = koin.get().reportedEndpoints(project) + + assertThat(endpoints.map { it.applicationId }).containsExactly(app.packageName) + } } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index 71f8af57d5..ee436cb776 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -32,7 +32,8 @@ class DebuggerEndpointRepositoryTest { .inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), RecentProjectRoomDatabase::class.java) .allowMainThreadQueries() .build() - repository = DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { 1234L }) + repository = + DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { 1234L }, isInstalled = { true }) } @After @@ -178,7 +179,7 @@ class DebuggerEndpointRepositoryTest { } private fun clockedRepository(now: AtomicLong) = - DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { now.get() }) + DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { now.get() }, isInstalled = { true }) @Test fun `a failed install does not pair a later install of the same app`() = @@ -317,7 +318,7 @@ class DebuggerEndpointRepositoryTest { { IllegalStateException("closed") }, { android.database.SQLException("generic") }, )) { - val failing = DebuggerEndpointRepository(ThrowingDao(error), CoroutineScope(Dispatchers.IO)) + val failing = DebuggerEndpointRepository(ThrowingDao(error), CoroutineScope(Dispatchers.IO), isInstalled = { true }) assertThat(failing.recordInstalled("com.example", "/p/a")).isFalse() assertThat(failing.recordLaunched("com.example", "/p/a")).isFalse() @@ -331,6 +332,7 @@ class DebuggerEndpointRepositoryTest { DebuggerEndpointRepository( ThrowingDao { kotlinx.coroutines.CancellationException("cancelled") }, CoroutineScope(Dispatchers.IO), + isInstalled = { true }, ) val result = runCatching { runBlocking { failing.storeEndpoint("com.example", endpoint) } } diff --git a/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt index 8a251767e9..056a447a6b 100644 --- a/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt +++ b/app/src/test/java/com/itsaky/androidide/sqlitedebugger/DebuggerEndpointReceiverTest.kt @@ -42,7 +42,7 @@ class DebuggerEndpointReceiverTest { .allowMainThreadQueries() .build() val scope = CoroutineScope(Dispatchers.IO) - val repository = DebuggerEndpointRepository(room.debuggerEndpointDao(), scope, clock = { 99L }) + val repository = DebuggerEndpointRepository(room.debuggerEndpointDao(), scope, clock = { 99L }, isInstalled = { true }) if (GlobalContext.getOrNull() != null) stopKoin() startKoin { modules( From ce08883de4020d34bab06c029aea575201970e8a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:04:12 -0800 Subject: [PATCH 09/35] ADFA-7139 Test two projects and a symlinked path against the real DAO Cross-project isolation was tested only against a fake source that filters by path, so a DAO query that returned every row would have passed. This promotes the review's scratch test: two projects each get only their own app, a symlinked project path finds the canonical row, and an app moved to the other project drops out of the first. Review R9 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../DebuggerEndpointRepositoryTest.kt | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index ee436cb776..6dc59e8352 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -395,6 +395,36 @@ class DebuggerEndpointRepositoryTest { } } + @Test + fun `each project gets only its own apps, also through a symlinked path, and an app moved away leaves the old one`() = + runBlocking { + val a = java.nio.file.Files.createTempDirectory("projA").toFile() + val b = java.nio.file.Files.createTempDirectory("projB").toFile() + val link = File(a.parentFile, a.name + "-link") + java.nio.file.Files.createSymbolicLink(link.toPath(), a.toPath()) + try { + addProject(a.canonicalPath) + addProject(b.canonicalPath) + assertThat(repository.recordInstalled("com.example.a", a.canonicalPath)).isTrue() + assertThat(repository.recordInstalled("com.example.b", b.canonicalPath)).isTrue() + assertThat(repository.storeEndpoint("com.example.a", DebuggerEndpointValidation.Endpoint("tok-a", 1111))).isTrue() + assertThat(repository.storeEndpoint("com.example.b", DebuggerEndpointValidation.Endpoint("tok-b", 2222))).isTrue() + + assertThat(repository.reportedEndpoints(a).map { it.applicationId }).containsExactly("com.example.a") + assertThat(repository.reportedEndpoints(b).map { it.applicationId }).containsExactly("com.example.b") + assertThat(repository.reportedEndpoints(link).map { it.token }).containsExactly("tok-a") + + // The app is now built by project b: a no longer lists it, and its token was cleared. + assertThat(repository.recordInstalled("com.example.a", b.canonicalPath)).isTrue() + assertThat(repository.reportedEndpoints(a)).isEmpty() + assertThat(repository.reportedEndpoints(b).map { it.applicationId }).containsExactly("com.example.b") + } finally { + link.delete() + a.delete() + b.delete() + } + } + @Test fun `the package manager check tells installed from missing apps`() { val app = ApplicationProvider.getApplicationContext() From f7a7497d101e59f03a3c591f78b25d4fab3fe0a9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:06:52 -0800 Subject: [PATCH 10/35] ADFA-7139 Return no SQLite debugger endpoints when no project is open DebuggerEndpointService took its project from CogoProjectProvider, which reads GeneralPreferences.lastOpenedProject. Nothing clears that on close, so on the home screen a plugin still got the closed project's ports and tokens, and "empty when no project is open" was false. The service now takes the root from the editor: IProjectManager's project path, but only while the editor activity has its provider registered, which it does from onCreate to preDestroy. The project path alone is not enough: ProjectManagerImpl.destroy() leaves it set too. CogoProjectProvider is unchanged; the other services still use it. PluginManagerDebuggerEndpointTest loads a plugin through PluginManager and checks the open project's endpoints come back and a closed one's do not. Review R1 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 2 +- .../services/DebuggerEndpointService.java | 4 +- .../plugins/manager/core/PluginManager.kt | 20 +- .../core/PluginManagerDebuggerEndpointTest.kt | 200 ++++++++++++++++++ subprojects/sqlite-debugger/README.md | 2 +- 5 files changed, 222 insertions(+), 6 deletions(-) create mode 100644 plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 536419803c..eacd875333 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -40,7 +40,7 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] `DebuggerEndpointService.getEndpoints()` returns a `List`, one per app of the open project that has reported to the IDE: `applicationId`, `port` (on `127.0.0.1`), `token` (the bearer token the server requires) and `updatedAtMillis`. The list is empty, never null, when no project is - open or no app has reported. Port and token change every time the app starts, so call again after a + open in the editor (the home screen, even right after a project was closed) or no app has reported. Port and token change every time the app starts, so call again after a refused connection or a 401/403. An app that was uninstalled is left out, but one whose process died stays listed until it reports again (`updatedAtMillis` is when it last reported). The call reads the IDE's database: use a background thread. It needs the new `debugger.endpoints` permission (`PluginPermission.DEBUGGER_ENDPOINTS`) and throws diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index afc28d2aa8..7ad91279c7 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -20,12 +20,12 @@ public interface DebuggerEndpointService { int CONTRACT_VERSION = 1; /** - * Gets the debugger endpoints of the open project, one per app that has reported. Read fresh on every call, so call it again after a connection fails: a relaunched app has a new port and token. + * Gets the SQLite debugger endpoints of the project open in the editor, one per app that has reported. Read fresh on every call, so call it again after a connection fails: a relaunched app has a new port and token. * *

* An app the IDE installed or launched but that has not yet reported is not listed, and neither is an app that has since been uninstalled. An endpoint can still be stale: when the app's process has died, its last reported port and token stay here until the app reports again, so treat {@link DebuggerEndpoint#getUpdatedAtMillis} (when it last reported) as a hint, and when a connection is refused, call this again and reconnect. * - * @return the endpoints (never null; empty when no project is open or no app has reported) + * @return the endpoints (never null; empty when no project is open in the editor, as on the home screen, or no app has reported) * @throws SecurityException * if the plugin lacks the {@code debugger.endpoints} permission * @throws IllegalStateException 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 d6d1b57665..306f2c166f 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 @@ -82,6 +82,7 @@ import com.itsaky.androidide.plugins.services.IdeTerminalService import com.itsaky.androidide.plugins.services.IdeThemeService import com.itsaky.androidide.plugins.services.IdeTooltipService import com.itsaky.androidide.plugins.services.IdeUIService +import com.itsaky.androidide.projects.IProjectManager import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -391,6 +392,21 @@ class PluginManager private constructor( // IDE service providers private val projectProvider = CogoProjectProvider() + /** + * The root of the project open in the editor, or null on the home screen. Not [projectProvider]: + * `GeneralPreferences.lastOpenedProject` still names a project after it is closed, and so does + * [IProjectManager.projectDirPath]. The editor activity registers [editorProvider] while it shows + * a project and clears it when it ends, so that is what says a project is open. + */ + private fun openProjectRoot(): File? { + if (editorProvider == null) return null + return IProjectManager + .getInstance() + .projectDirPath + .takeIf { it.isNotEmpty() } + ?.let(::File) + } + init { if (!pluginsDir.exists()) { pluginsDir.mkdirs() @@ -1588,7 +1604,7 @@ class PluginManager private constructor( DebuggerEndpointServiceImpl( pluginId = pluginId, permissions = permissions, - projectRootProvider = { projectProvider.getCurrentProject()?.rootDir }, + projectRootProvider = ::openProjectRoot, ) } @@ -1870,7 +1886,7 @@ class PluginManager private constructor( DebuggerEndpointServiceImpl( pluginId = pluginId, permissions = permissions, - projectRootProvider = { projectProvider.getCurrentProject()?.rootDir }, + projectRootProvider = ::openProjectRoot, ) } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt new file mode 100644 index 0000000000..9c67defda9 --- /dev/null +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -0,0 +1,200 @@ +package com.itsaky.androidide.plugins.manager.core + +import android.content.pm.ApplicationInfo +import android.content.pm.PackageInfo +import android.os.Bundle +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.app.BaseApplication +import com.itsaky.androidide.plugins.IPlugin +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.PluginLogger +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSources +import com.itsaky.androidide.plugins.manager.services.IdeEditorServiceImpl +import com.itsaky.androidide.plugins.services.DebuggerEndpoint +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import com.itsaky.androidide.preferences.internal.GeneralPreferences +import com.itsaky.androidide.projects.ProjectManagerImpl +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.io.File +import java.nio.file.Files +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicReference +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import kotlin.concurrent.thread + +/** + * The [DebuggerEndpointService] a plugin gets when [PluginManager] loads it, through the registration + * the app runs (createPluginContextWithResources). BaseApplication backs GeneralPreferences, which + * remembers the last opened project. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = BaseApplication::class) +class PluginManagerDebuggerEndpointTest { + private lateinit var project: File + private val endpoint = DebuggerEndpoint("com.example.demo", 4321, "tok", 99L) + private val asked = CopyOnWriteArrayList() + + @Before + fun setUp() { + project = Files.createTempDirectory("proj").toFile() + DebuggerEndpointSources.install { location -> + asked += location + if (location == project.absolutePath) listOf(endpoint) else emptyList() + } + } + + @After + fun tearDown() { + DebuggerEndpointSources.install(null) + forgetPluginManager() + ProjectManagerImpl.getInstance().projectPath = "" + GeneralPreferences.lastOpenedProject = GeneralPreferences.NO_OPENED_PROJECT + project.deleteRecursively() + } + + @Test + fun `the endpoints of the project open in the editor are returned`() { + val service = load("reader", "debugger.endpoints") + openInEditor(project) + + assertThat(offMainThread { service.getEndpoints() }).containsExactly(endpoint) + } + + @Test + fun `a closed project's endpoints are not returned, though it is still the last opened project`() { + val service = load("reader", "debugger.endpoints") + openInEditor(project) + pluginManager().setEditorProvider(null) + + assertThat(offMainThread { service.getEndpoints() }).isEmpty() + assertThat(asked).isEmpty() + } + + /** What opening [dir] leaves behind: the project path and the last opened project, and an editor showing it. */ + private fun openInEditor(dir: File) { + ProjectManagerImpl.getInstance().projectPath = dir.absolutePath + GeneralPreferences.lastOpenedProject = dir.absolutePath + pluginManager().setEditorProvider(OpenEditor) + } + + private fun load( + id: String, + permissions: String, + ): DebuggerEndpointService { + val file = fakePlugin(File(RuntimeEnvironment.getApplication().filesDir, "plugins/$id.cgp"), id, permissions) + val result = pluginManager().loadPlugin(file) + assertWithMessage("plugin $id did not load: ${result.exceptionOrNull()}").that(result.isSuccess).isTrue() + val plugin = pluginManager().getPlugin(id) as ContextKeepingPlugin + return checkNotNull(plugin.context.services.get(DebuggerEndpointService::class.java)) { "no DebuggerEndpointService for $id" } + } + + /** Runs [block] on a worker thread: on the main thread, where Robolectric runs the test, getEndpoints throws. */ + private fun offMainThread(block: () -> T): T { + val result = AtomicReference>() + thread { result.set(runCatching(block)) }.join() + return result.get().getOrThrow() + } + + private fun pluginManager() = PluginManager.getInstance(RuntimeEnvironment.getApplication(), Any(), NoLogger) + + /** Forgets the singleton plugin manager: each test has an application of its own. */ + private fun forgetPluginManager() { + PluginManager::class.java + .getDeclaredField("INSTANCE") + .apply { isAccessible = true } + .set(null, null) + } + + /** Writes [file] as a plugin whose manifest states [id] and [permissions]: Robolectric can't read one from an APK. */ + private fun fakePlugin( + file: File, + id: String, + permissions: String, + ): File { + file.parentFile?.mkdirs() + ZipOutputStream(file.outputStream()).use { it.putNextEntry(ZipEntry("classes.dex")) } + val info = + PackageInfo().apply { + packageName = "org.example.$id" + applicationInfo = + ApplicationInfo().apply { + metaData = + Bundle().apply { + putString("plugin.id", id) + putString("plugin.main_class", ContextKeepingPlugin::class.java.name) + putString("plugin.permissions", permissions) + } + } + } + shadowOf(RuntimeEnvironment.getApplication().packageManager).setPackageArchiveInfo(file.absolutePath, info) + return file + } + + /** A plugin that keeps its context. Its class loader finds it through its parent, the test's. */ + class ContextKeepingPlugin : IPlugin { + lateinit var context: PluginContext + + override fun initialize(context: PluginContext): Boolean { + this.context = context + return true + } + + override fun activate() = true + + override fun deactivate() = true + + override fun dispose() = Unit + } + + /** The editor activity's provider, as registered while it shows a project. */ + private object OpenEditor : IdeEditorServiceImpl.EditorProvider { + override fun getCurrentFile(): File? = null + + override fun getOpenFiles(): List = emptyList() + + override fun isFileOpen(file: File): Boolean = false + + override fun getCurrentSelection(): String? = null + } + + private object NoLogger : 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 + } +} diff --git a/subprojects/sqlite-debugger/README.md b/subprojects/sqlite-debugger/README.md index 0077fa097e..9fe4fc7eb7 100644 --- a/subprojects/sqlite-debugger/README.md +++ b/subprojects/sqlite-debugger/README.md @@ -24,7 +24,7 @@ MCP client --HTTP, 127.0.0.1--> McpHttp -> McpProtocol -> DatabaseTools -> Debug - `DebuggerStartup` is a `ContentProvider` with the highest `initOrder`, declared in the AAR's manifest. It runs before the app's own providers and `Application.onCreate`, so the extension is registered before the app opens a database. It installs the extension synchronously in `onCreate` (so an app that opens its database in `Application.onCreate` is still seen) and starts the server on a background thread. Everything after the debuggable check is wrapped in `catch (Throwable)`: a missing requery library (`UnsatisfiedLinkError`) means the debugger is disabled and logged, never a crash of the host app. - `EndpointBroadcast` runs once the server listens, on every process start (the port changes). It sends an explicit broadcast, action `com.itsaky.androidide.SQLITE_DEBUGGER_ENDPOINT`, to `com.itsaky.androidide` with `FLAG_INCLUDE_STOPPED_PACKAGES`, carrying the token, the port and a `PendingIntent` that identifies the app. The `PendingIntent` is immutable (on API 23 and later; the flag does not exist before) and wraps an intent that is never sent: Code on the Go reads its `creatorPackage`, which the framework sets and another app cannot forge, as the app's package name. The library manifest declares `` for Code on the Go. A failure to send is logged and never thrown. - On the Code on the Go side, `DebuggerEndpointReceiver` (exported) validates the token and port and resolves the sender, then `DebuggerEndpointRepository` stores them in `debugger_endpoint_table` of the Recent Projects database, keyed by application ID. A row exists only for an app Code on the Go installed or launched (`LaunchAppAction` and `ProjectHandlerActivity` record the pairing); a broadcast from any other app stores nothing. The row is deleted with its project (foreign key, ON DELETE CASCADE). -- Plugins get the stored endpoints through `DebuggerEndpointService` (plugin API), which needs the `debugger.endpoints` permission. `getEndpoints()` returns one entry per app of the open project that has reported (application ID, port, token, last update), read fresh on every call and not on the main thread, so a plugin asks again after a refused connection. Apps that are no longer installed are left out; an app whose process died is still listed until it reports again. The AI-Agent-MCP plugin (addons repository) is the first client. +- Plugins get the stored endpoints through `DebuggerEndpointService` (plugin API), which needs the `debugger.endpoints` permission. `getEndpoints()` returns one entry per app of the project open in the editor that has reported (application ID, port, token, last update), and none on the home screen, read fresh on every call and not on the main thread, so a plugin asks again after a refused connection. Apps that are no longer installed are left out; an app whose process died is still listed until it reports again. The AI-Agent-MCP plugin (addons repository) is the first client. ### The event record From e6880dd0d89b041d7cddb6c9e7a8b6d46e38f273 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:09:00 -0800 Subject: [PATCH 11/35] ADFA-7139 Keep the SQLite debugger endpoint source out of plugins' reach The debugger.endpoints permission was checked only in getEndpoints(), while DebuggerEndpointSources was a public object with a public current and install. Plugin classes load through a child of the host class loader, so a plugin without the permission could read any project's tokens through current, or replace or blank the source for every plugin with install. The permission set the service held was the mutable LinkedHashSet PluginManager built, so a plugin could also add the permission to it by reflection. - The public holder is gone. PluginManager keeps the source in a private field, and installDebuggerEndpointSource() installs it once: the app does so before plugins load, and a later call fails. - DebuggerEndpointServiceImpl is internal and keeps its own unmodifiable copy of the permissions. - The Javadoc, the permission's description, the changelog and PLUGIN_AUTHORING.md say plugins run in Code on the Go's process, so the permission declares intent and cannot stop reflection. The review's scratch bypass tests, inverted: a second install fails and the app's source stays (PluginManagerDebuggerEndpointTest), no public member returns the source, and neither changing the set the service was built from nor adding to the service's own set grants the permission (DebuggerEndpointServiceImplTest). Review R2 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../CredentialProtectedApplicationLoader.kt | 3 +- docs/PLUGIN_API_CHANGELOG.md | 4 +- docs/PLUGIN_AUTHORING.md | 4 ++ .../services/DebuggerEndpointService.java | 2 +- .../com/itsaky/androidide/plugins/IPlugin.kt | 6 ++- .../plugins/manager/core/PluginManager.kt | 19 +++++++++ .../services/DebuggerEndpointServiceImpl.kt | 39 ++++++++++-------- .../core/PluginManagerDebuggerEndpointTest.kt | 26 ++++++++++-- .../DebuggerEndpointServiceImplTest.kt | 41 ++++++++++++++----- 9 files changed, 109 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt index 552a14959f..a498cf2cae 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -22,7 +22,6 @@ import com.itsaky.androidide.plugins.PluginLogger import com.itsaky.androidide.plugins.base.PluginFragmentHelper import com.itsaky.androidide.plugins.manager.core.PluginManager import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSource -import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSources import com.itsaky.androidide.plugins.manager.services.IdeBuildServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeLogServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeTerminalServiceImpl @@ -410,7 +409,7 @@ internal object CredentialProtectedApplicationLoader : setupBuildServiceProviders() setupProjectManipulationProviders() IdeLogServiceImpl.getInstance().setLogReader(LogsProvider::read) - DebuggerEndpointSources.install(get()) + manager.installDebuggerEndpointSource(get()) IdeTerminalServiceImpl.setSessionLauncher(PluginTerminalLauncher { application.foregroundActivity }) logger.info("Plugin services configured successfully") } diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index eacd875333..34b2f13785 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -45,7 +45,9 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] listed until it reports again (`updatedAtMillis` is when it last reported). The call reads the IDE's database: use a background thread. It needs the new `debugger.endpoints` permission (`PluginPermission.DEBUGGER_ENDPOINTS`) and throws `SecurityException` without it, and `IllegalStateException` on the main thread or when the database - cannot be read (an unreadable database is not reported as an empty list). Floor `plugin.min_ide_version` + cannot be read (an unreadable database is not reported as an empty list). Plugins run in Code on the + Go's process, so the permission declares intent and cannot stop reflection, as with `IdeLogService` + below. Floor `plugin.min_ide_version` at `26.47`: an IDE of 26.46 or older rejects the unknown `debugger.endpoints` permission when it validates the manifest, so it refuses to install a plugin that declares it. diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index 72d536332e..6f1a98c186 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -345,6 +345,10 @@ Defined by `PluginPermission` in `plugin-api/src/main/kotlin/com/itsaky/androidi | `ide.environment.write` | Write to IDE-managed directories (Android SDK, NDK, cache) | | `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers | +Plugins run in Code on the Go's process. A permission declares what a plugin means to do, and the +services check it on every call, but it cannot stop a plugin that reaches into the host by +reflection. + ## Contributing a language Implement `LanguageExtension` to give a file type syntax highlighting, a language server, or both: diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index 7ad91279c7..09626a00ed 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -7,7 +7,7 @@ * Tells a plugin where the SQLite debugger servers of the open project's apps are listening, so a plugin such as an MCP client can connect without the user typing a port or token. * *

- * The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it, like the other permission-gated services. + * The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it, like the other permission-gated services. Plugins run in Code on the Go's process, so the permission declares what a plugin means to do: it cannot stop a plugin that reaches into the host by reflection. * *

* Calls are synchronous, as in {@link IdeLogService} and {@link IdeProjectService}, rather than returning a {@link java.util.concurrent.CompletableFuture} as the services that start long work do: the answer is a small read of the IDE's own database, not an operation with a lifecycle. That read is disk I/O, so call from a background thread: on the main thread the call throws {@link IllegalStateException}. diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt index c0db691a08..e1be903e9f 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt @@ -54,7 +54,11 @@ enum class PluginPermission( PROJECT_STRUCTURE("project.structure", "Modify project structure"), NATIVE_CODE("native.code", "Execute native machine code"), IDE_ENVIRONMENT_WRITE("ide.environment.write", "Write to IDE-managed directories such as the Android SDK, NDK, and cache"), - DEBUGGER_ENDPOINTS("debugger.endpoints", "Read the port and token of the open project's SQLite debugger servers"), + DEBUGGER_ENDPOINTS( + "debugger.endpoints", + "Read the port and token of the open project's SQLite debugger servers. Plugins run in Code on the Go's process, " + + "so this declares intent and cannot stop reflection", + ), } data class PluginInfo( 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 306f2c166f..c7e08ccb3a 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 @@ -43,6 +43,7 @@ import com.itsaky.androidide.plugins.manager.project.PluginProjectManager import com.itsaky.androidide.plugins.manager.security.PluginSecurityManager import com.itsaky.androidide.plugins.manager.services.CogoProjectProvider import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointServiceImpl +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSource import com.itsaky.androidide.plugins.manager.services.IdeArchiveServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeCommandServiceImpl import com.itsaky.androidide.plugins.manager.services.IdeEditorServiceImpl @@ -96,6 +97,7 @@ import kotlinx.coroutines.withContext import org.adfa.constants.PLUGIN_ARCHIVE_EXTENSION import java.io.File import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicReference class PluginManager private constructor( private val context: Context, @@ -407,6 +409,21 @@ class PluginManager private constructor( ?.let(::File) } + /** Where [DebuggerEndpointService] reads. Private: short of reflection, a plugin cannot read tokens around the service. */ + private val debuggerEndpointSource = AtomicReference() + + /** + * Installs where every plugin's [DebuggerEndpointService] reads the SQLite debugger endpoints apps + * reported. The app installs it once, before plugins load. Plugins share this class loader, so a + * later call, which can only be a plugin's, fails rather than replacing or blanking the source for + * every plugin. + * + * @throws IllegalStateException if a source is already installed + */ + fun installDebuggerEndpointSource(source: DebuggerEndpointSource) { + check(debuggerEndpointSource.compareAndSet(null, source)) { "The SQLite debugger endpoint source is already installed" } + } + init { if (!pluginsDir.exists()) { pluginsDir.mkdirs() @@ -1605,6 +1622,7 @@ class PluginManager private constructor( pluginId = pluginId, permissions = permissions, projectRootProvider = ::openProjectRoot, + sourceProvider = debuggerEndpointSource::get, ) } @@ -1887,6 +1905,7 @@ class PluginManager private constructor( pluginId = pluginId, permissions = permissions, projectRootProvider = ::openProjectRoot, + sourceProvider = debuggerEndpointSource::get, ) } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index 9b8d180845..98a5569789 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -6,36 +6,40 @@ import com.itsaky.androidide.plugins.services.DebuggerEndpoint import com.itsaky.androidide.plugins.services.DebuggerEndpointService import org.slf4j.LoggerFactory import java.io.File +import java.util.Collections +import java.util.EnumSet import java.util.concurrent.CancellationException /** * Where the host keeps what apps reported: the app module's `debugger_endpoint_table`. The app - * installs an implementation with [DebuggerEndpointSources.install]; this module cannot reach the - * table itself. + * installs one with [com.itsaky.androidide.plugins.manager.core.PluginManager.installDebuggerEndpointSource]; + * this module cannot reach the table itself. */ fun interface DebuggerEndpointSource { /** Returns the endpoints stored for the project at [projectLocation], as it appears in `recent_project_table.location`. */ fun endpointsFor(projectLocation: String): List } -object DebuggerEndpointSources { - @Volatile - var current: DebuggerEndpointSource = DebuggerEndpointSource { emptyList() } - private set - - /** Installs the app's source, or restores the empty default when [source] is null. */ - fun install(source: DebuggerEndpointSource?) { - current = source ?: DebuggerEndpointSource { emptyList() } - } -} - -class DebuggerEndpointServiceImpl( +/** + * The [DebuggerEndpointService] the plugin manager registers for each plugin, with that plugin's permissions. + * + * Plugins run in Code on the Go's process, and their class loader's parent is the host's, so the + * permission check declares intent: it cannot stop a plugin that reaches host objects by reflection. + * What it does close is every path short of that. The source is held privately by the plugin manager, + * which installs it once, and this service keeps its own unmodifiable copy of the permissions, so + * changing the set it was built from grants nothing. + */ +internal class DebuggerEndpointServiceImpl( private val pluginId: String, - private val permissions: Set, + permissions: Set, private val projectRootProvider: () -> File?, - private val sourceProvider: () -> DebuggerEndpointSource = { DebuggerEndpointSources.current }, + /** Null until the app installs one. */ + private val sourceProvider: () -> DebuggerEndpointSource?, private val isMainThread: () -> Boolean = { Looper.myLooper() == Looper.getMainLooper() }, ) : DebuggerEndpointService { + private val permissions: Set = + Collections.unmodifiableSet(EnumSet.noneOf(PluginPermission::class.java).apply { addAll(permissions) }) + override fun getEndpoints(): List { if (PluginPermission.DEBUGGER_ENDPOINTS !in permissions) { throw SecurityException( @@ -46,8 +50,9 @@ class DebuggerEndpointServiceImpl( check(!isMainThread()) { "DebuggerEndpointService.getEndpoints() reads a database; call it off the main thread" } val root = projectRootProvider() ?: return emptyList() + val source = sourceProvider() ?: return emptyList() return try { - sourceProvider().endpointsFor(root.absolutePath) + source.endpointsFor(root.absolutePath) } catch (e: InterruptedException) { Thread.currentThread().interrupt() throw e diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index 9c67defda9..9ce2339c45 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -9,13 +9,14 @@ import com.itsaky.androidide.app.BaseApplication import com.itsaky.androidide.plugins.IPlugin import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.PluginLogger -import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSources +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSource import com.itsaky.androidide.plugins.manager.services.IdeEditorServiceImpl import com.itsaky.androidide.plugins.services.DebuggerEndpoint import com.itsaky.androidide.plugins.services.DebuggerEndpointService import com.itsaky.androidide.preferences.internal.GeneralPreferences import com.itsaky.androidide.projects.ProjectManagerImpl import org.junit.After +import org.junit.Assert.assertThrows import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -46,7 +47,7 @@ class PluginManagerDebuggerEndpointTest { @Before fun setUp() { project = Files.createTempDirectory("proj").toFile() - DebuggerEndpointSources.install { location -> + pluginManager().installDebuggerEndpointSource { location -> asked += location if (location == project.absolutePath) listOf(endpoint) else emptyList() } @@ -54,7 +55,6 @@ class PluginManagerDebuggerEndpointTest { @After fun tearDown() { - DebuggerEndpointSources.install(null) forgetPluginManager() ProjectManagerImpl.getInstance().projectPath = "" GeneralPreferences.lastOpenedProject = GeneralPreferences.NO_OPENED_PROJECT @@ -79,6 +79,26 @@ class PluginManagerDebuggerEndpointTest { assertThat(asked).isEmpty() } + @Test + fun `a second install, as a plugin would try, fails and leaves the app's source in place`() { + val service = load("reader", "debugger.endpoints") + openInEditor(project) + + assertThrows(IllegalStateException::class.java) { pluginManager().installDebuggerEndpointSource { emptyList() } } + + assertThat(offMainThread { service.getEndpoints() }).containsExactly(endpoint) + } + + @Test + fun `no public member hands out the source, and the public holder plugins could read is gone`() { + val types = PluginManager::class.java.methods.map { it.returnType } + PluginManager::class.java.fields.map { it.type } + + assertThat(types.filter { DebuggerEndpointSource::class.java.isAssignableFrom(it) }).isEmpty() + assertThrows(ClassNotFoundException::class.java) { + Class.forName("com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSources") + } + } + /** What opening [dir] leaves behind: the project path and the last opened project, and an editor showing it. */ private fun openInEditor(dir: File) { ProjectManagerImpl.getInstance().projectPath = dir.absolutePath diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt index 4d6d1d4e11..94c49ce01f 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -88,16 +88,37 @@ class DebuggerEndpointServiceImplTest { } @Test - fun `the default source is empty until the app installs one`() { - DebuggerEndpointSources.install(null) - val defaulted = DebuggerEndpointServiceImpl("p", setOf(PluginPermission.DEBUGGER_ENDPOINTS), { project }, isMainThread = { false }) - assertThat(defaulted.getEndpoints()).isEmpty() + fun `is empty until the app installs a source`() { + var installed: DebuggerEndpointSource? = null + val service = DebuggerEndpointServiceImpl("p", setOf(PluginPermission.DEBUGGER_ENDPOINTS), { project }, { installed }, { false }) + assertThat(service.getEndpoints()).isEmpty() - DebuggerEndpointSources.install(source) - try { - assertThat(defaulted.getEndpoints()).containsExactly(endpoint) - } finally { - DebuggerEndpointSources.install(null) - } + installed = source + + assertThat(service.getEndpoints()).containsExactly(endpoint) + } + + @Test + fun `adding the permission to the set the service was built from grants nothing`() { + val granted = linkedSetOf(PluginPermission.FILESYSTEM_READ, PluginPermission.NETWORK_ACCESS) + val denied = service(permissions = granted) + + granted += PluginPermission.DEBUGGER_ENDPOINTS + + assertThrows(SecurityException::class.java) { denied.getEndpoints() } + assertThat(seen).isEmpty() + } + + @Test + fun `the service's own permission set cannot be added to, as a plugin would by reflection`() { + val denied = service(permissions = linkedSetOf(PluginPermission.FILESYSTEM_READ, PluginPermission.NETWORK_ACCESS)) + val field = DebuggerEndpointServiceImpl::class.java.getDeclaredField("permissions").apply { isAccessible = true } + + @Suppress("UNCHECKED_CAST") + val held = field.get(denied) as MutableSet + assertThrows(UnsupportedOperationException::class.java) { held.add(PluginPermission.DEBUGGER_ENDPOINTS) } + + assertThrows(SecurityException::class.java) { denied.getEndpoints() } + assertThat(seen).isEmpty() } } From a754c2b55c0ba075ad4b723d08c164283f96a8d6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:10:20 -0800 Subject: [PATCH 12/35] ADFA-7139 Test the DebuggerEndpointService each loaded plugin gets Nothing checked that PluginManager registers the service, nor with which permissions: deleting the registration left every plugin-manager test green, and a block lost in a merge would leave plugins with null. The new test loads two plugins through PluginManager.loadPlugin, so the registration in createPluginContextWithResources runs, and asks each plugin's own registry for the service. The one with debugger.endpoints gets the open project's endpoints and, after a switch, the new project's; the one without it gets SecurityException. createPluginContext has no caller (ADFA-7191 removes it) and is not tested. Review R4 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../core/PluginManagerDebuggerEndpointTest.kt | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index 9ce2339c45..e96c0e68ca 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -79,6 +79,26 @@ class PluginManagerDebuggerEndpointTest { assertThat(asked).isEmpty() } + @Test + fun `each loaded plugin gets a service bound to its own permissions and the project now open`() { + val reader = load("reader", "debugger.endpoints") + val other = load("other", "filesystem.read,network.access") + val elsewhere = Files.createTempDirectory("other").toFile() + try { + openInEditor(project) + + assertThat(offMainThread { reader.getEndpoints() }).containsExactly(endpoint) + assertThrows(SecurityException::class.java) { offMainThread { other.getEndpoints() } } + + openInEditor(elsewhere) + + assertThat(offMainThread { reader.getEndpoints() }).isEmpty() + assertThat(asked).containsExactly(project.absolutePath, elsewhere.absolutePath).inOrder() + } finally { + elsewhere.deleteRecursively() + } + } + @Test fun `a second install, as a plugin would try, fails and leaves the app's source in place`() { val service = load("reader", "debugger.endpoints") From b4d682b7bec0abad0bb402c51b2ae310459319b9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:11:33 -0800 Subject: [PATCH 13/35] ADFA-7139 Refuse SQLite debugger endpoints to a disabled plugin A plugin's services outlive a disable, and only the terminal service was closed then, so a thread a disabled plugin left running kept getting ports and tokens. The endpoint service now follows the terminal service: the plugin manager closes it on disable, force-disable (after crashes) and unload, and reopens it on enable, and a closed service throws CancellationException. It is also closed when a plugin loads disabled or fails to activate, since initialize() has already run then. A call already reading checks again after the read, so it gets no tokens either. The Javadoc and the changelog say so. PluginManagerDebuggerEndpointTest disables, force-disables, unloads and reloads a disabled plugin through PluginManager; DebuggerEndpointServiceImplTest covers close, reopen and a close during a read. Review R6 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 4 +- .../services/DebuggerEndpointService.java | 2 + .../plugins/manager/core/PluginManager.kt | 14 ++++- .../services/DebuggerEndpointServiceImpl.kt | 48 ++++++++++++---- .../core/PluginManagerDebuggerEndpointTest.kt | 56 +++++++++++++++++++ .../DebuggerEndpointServiceImplTest.kt | 25 +++++++++ 6 files changed, 136 insertions(+), 13 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 34b2f13785..e5edebd267 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -45,7 +45,9 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] listed until it reports again (`updatedAtMillis` is when it last reported). The call reads the IDE's database: use a background thread. It needs the new `debugger.endpoints` permission (`PluginPermission.DEBUGGER_ENDPOINTS`) and throws `SecurityException` without it, and `IllegalStateException` on the main thread or when the database - cannot be read (an unreadable database is not reported as an empty list). Plugins run in Code on the + cannot be read (an unreadable database is not reported as an empty list). Once the plugin is disabled + or unloaded, a call throws `java.util.concurrent.CancellationException` until it is enabled again, as + `IdeTerminalService` calls do. Plugins run in Code on the Go's process, so the permission declares intent and cannot stop reflection, as with `IdeLogService` below. Floor `plugin.min_ide_version` at `26.47`: an IDE of 26.46 or older rejects the unknown `debugger.endpoints` permission when it diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index 09626a00ed..d975c922c3 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -30,6 +30,8 @@ public interface DebuggerEndpointService { * if the plugin lacks the {@code debugger.endpoints} permission * @throws IllegalStateException * if called on the main thread, or if the IDE's database could not be read. A failed read is not the same as no apps: keep what you had and try again later + * @throws java.util.concurrent.CancellationException + * if the plugin has been disabled or unloaded, until it is enabled again; also when a call already reading sees it disabled */ @NonNull List getEndpoints(); 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 c7e08ccb3a..1d660e2f40 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 @@ -724,6 +724,8 @@ class PluginManager private constructor( loadedPlugins[manifest.id] = loadedPlugin if (!isEnabled) { + // initialize() ran, so the plugin may already have threads of its own. + loadedPlugin.debuggerEndpointService()?.close() logger.info("Successfully loaded plugin (disabled): ${manifest.name} (${manifest.id})") return Result.success(plugin) } @@ -766,6 +768,7 @@ class PluginManager private constructor( }.onFailure { e -> logger.error("Failed to activate plugin: ${manifest.id}", e) loadedPlugin.isEnabled = false + loadedPlugin.debuggerEndpointService()?.close() savePluginState(manifest.id, false) } } @@ -806,6 +809,9 @@ class PluginManager private constructor( val loadedPlugin = loadedPlugins.remove(pluginId) ?: return false try { + // First: a later step can throw and end the unload. + loadedPlugin.debuggerEndpointService()?.close() + // Remove documentation if plugin implements DocumentationExtension if (loadedPlugin.plugin is DocumentationExtension) { CoroutineScope(Dispatchers.IO).launch { @@ -1165,8 +1171,9 @@ class PluginManager private constructor( return true } - // The services outlive a disable, which closed the terminal service. + // The services outlive a disable, which closed the terminal and SQLite debugger endpoint services. (loadedPlugin.context.services.get(IdeTerminalService::class.java) as? IdeTerminalServiceImpl)?.reopen() + loadedPlugin.debuggerEndpointService()?.reopen() loadedPlugin.isEnabled = true activateLoadedPlugin(loadedPlugin) return if (loadedPlugin.isEnabled) { @@ -1223,6 +1230,7 @@ class PluginManager private constructor( private fun cleanupPluginContributions(loadedPlugin: LoadedPlugin) { val pluginId = loadedPlugin.manifest.id + loadedPlugin.debuggerEndpointService()?.close() runCatching { PluginProjectManager.getInstance().cleanupPluginTemplates(pluginId) } .onFailure { logger.error("Failed to clean project templates for: $pluginId", it) } runCatching { @@ -1245,6 +1253,10 @@ class PluginManager private constructor( }.onFailure { logger.error("Failed to cleanup templates for: $pluginId", it) } } + /** The plugin's [DebuggerEndpointServiceImpl]. Its services outlive a disable, so it is closed instead. */ + private fun LoadedPlugin.debuggerEndpointService(): DebuggerEndpointServiceImpl? = + context.services.get(DebuggerEndpointService::class.java) as? DebuggerEndpointServiceImpl + sealed class CrashResult { abstract val pluginId: String abstract val pluginName: String diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index 98a5569789..016ac14d81 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -40,28 +40,54 @@ internal class DebuggerEndpointServiceImpl( private val permissions: Set = Collections.unmodifiableSet(EnumSet.noneOf(PluginPermission::class.java).apply { addAll(permissions) }) + // Set by close, cleared by reopen. A disabled plugin keeps its services, and any thread it left running. + @Volatile + private var closed = false + override fun getEndpoints(): List { if (PluginPermission.DEBUGGER_ENDPOINTS !in permissions) { throw SecurityException( "Plugin $pluginId does not have required permissions: ${PluginPermission.DEBUGGER_ENDPOINTS.name}", ) } + requireOpen() check(!isMainThread()) { "DebuggerEndpointService.getEndpoints() reads a database; call it off the main thread" } val root = projectRootProvider() ?: return emptyList() val source = sourceProvider() ?: return emptyList() - return try { - source.endpointsFor(root.absolutePath) - } catch (e: InterruptedException) { - Thread.currentThread().interrupt() - throw e - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - log.warn("getEndpoints failed for plugin {}", pluginId, e) - throw IllegalStateException("Could not read the debugger endpoints: ${e.message}", e) - } + val endpoints = + try { + source.endpointsFor(root.absolutePath) + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + throw e + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + log.warn("getEndpoints failed for plugin {}", pluginId, e) + throw IllegalStateException("Could not read the debugger endpoints: ${e.message}", e) + } + // Again after the read: a plugin disabled while it ran gets no tokens either. + requireOpen() + return endpoints + } + + /** + * Refuses every later call, and one still reading, with [CancellationException] until [reopen], + * as [IdeTerminalServiceImpl.cancelAll] does. Called when the plugin is disabled or unloaded. + */ + fun close() { + closed = true + } + + /** Lets calls through again after [close]. Called when the plugin is enabled. */ + fun reopen() { + closed = false + } + + private fun requireOpen() { + if (closed) throw CancellationException("Plugin $pluginId is disabled or unloaded") } private companion object { diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index e96c0e68ca..35d94627c8 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -15,6 +15,7 @@ import com.itsaky.androidide.plugins.services.DebuggerEndpoint import com.itsaky.androidide.plugins.services.DebuggerEndpointService import com.itsaky.androidide.preferences.internal.GeneralPreferences import com.itsaky.androidide.projects.ProjectManagerImpl +import com.itsaky.androidide.utils.Environment import org.junit.After import org.junit.Assert.assertThrows import org.junit.Before @@ -26,6 +27,7 @@ import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import java.io.File import java.nio.file.Files +import java.util.concurrent.CancellationException import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicReference import java.util.zip.ZipEntry @@ -44,9 +46,13 @@ class PluginManagerDebuggerEndpointTest { private val endpoint = DebuggerEndpoint("com.example.demo", 4321, "tok", 99L) private val asked = CopyOnWriteArrayList() + private val templatesDir = Environment.TEMPLATES_DIR + @Before fun setUp() { project = Files.createTempDirectory("proj").toFile() + // Disabling and unloading clean up the plugin's templates there. + Environment.TEMPLATES_DIR = File(RuntimeEnvironment.getApplication().filesDir, "templates").apply { mkdirs() } pluginManager().installDebuggerEndpointSource { location -> asked += location if (location == project.absolutePath) listOf(endpoint) else emptyList() @@ -56,6 +62,7 @@ class PluginManagerDebuggerEndpointTest { @After fun tearDown() { forgetPluginManager() + Environment.TEMPLATES_DIR = templatesDir ProjectManagerImpl.getInstance().projectPath = "" GeneralPreferences.lastOpenedProject = GeneralPreferences.NO_OPENED_PROJECT project.deleteRecursively() @@ -99,6 +106,55 @@ class PluginManagerDebuggerEndpointTest { } } + @Test + fun `a disabled plugin's service refuses until the plugin is enabled again`() { + val service = load("reader", "debugger.endpoints") + openInEditor(project) + + assertThat(pluginManager().disablePlugin("reader")).isTrue() + + assertThrows(CancellationException::class.java) { offMainThread { service.getEndpoints() } } + + assertThat(pluginManager().enablePlugin("reader")).isTrue() + + assertThat(offMainThread { service.getEndpoints() }).containsExactly(endpoint) + } + + @Test + fun `a plugin disabled after crashing gets nothing`() { + val service = load("reader", "debugger.endpoints") + openInEditor(project) + + pluginManager().forceDisablePlugin("reader") + + assertThrows(CancellationException::class.java) { offMainThread { service.getEndpoints() } } + assertThat(asked).isEmpty() + } + + @Test + fun `an unloaded plugin's service refuses`() { + val service = load("reader", "debugger.endpoints") + openInEditor(project) + + assertThat(pluginManager().unloadPlugin("reader")).isTrue() + + assertThrows(CancellationException::class.java) { offMainThread { service.getEndpoints() } } + assertThat(asked).isEmpty() + } + + @Test + fun `a plugin loaded while disabled gets a service that refuses`() { + load("reader", "debugger.endpoints") + assertThat(pluginManager().disablePlugin("reader")).isTrue() + assertThat(pluginManager().unloadPlugin("reader")).isTrue() + openInEditor(project) + + val reloaded = load("reader", "debugger.endpoints") + + assertThat(pluginManager().getLoadedPlugin("reader")).isNull() + assertThrows(CancellationException::class.java) { offMainThread { reloaded.getEndpoints() } } + } + @Test fun `a second install, as a plugin would try, fails and leaves the app's source in place`() { val service = load("reader", "debugger.endpoints") diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt index 94c49ce01f..d700f3e87a 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -87,6 +87,31 @@ class DebuggerEndpointServiceImplTest { assertThat(seen).isEmpty() } + @Test + fun `a closed service refuses until reopened`() { + val service = service() + service.close() + + assertThrows(java.util.concurrent.CancellationException::class.java) { service.getEndpoints() } + assertThat(seen).isEmpty() + + service.reopen() + + assertThat(service.getEndpoints()).containsExactly(endpoint) + } + + @Test + fun `a plugin disabled during a read gets no tokens from it`() { + lateinit var disabledMidRead: DebuggerEndpointServiceImpl + disabledMidRead = + service(source = { + disabledMidRead.close() + listOf(endpoint) + }) + + assertThrows(java.util.concurrent.CancellationException::class.java) { disabledMidRead.getEndpoints() } + } + @Test fun `is empty until the app installs a source`() { var installed: DebuggerEndpointSource? = null From e651f95384fdf731b44977397b328c23bc3579f9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:11:50 -0800 Subject: [PATCH 14/35] ADFA-7139 Docs: list DebuggerEndpointService in the plugin API surface plugin-api.md's list of service interfaces plugins call left out DebuggerEndpointService, and named no DebuggerEndpoint value type; only the permission key had been added. Docs only. Review R7 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/plugin-api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plugin-api.md b/docs/plugin-api.md index 7eeec75834..40e729aebf 100644 --- a/docs/plugin-api.md +++ b/docs/plugin-api.md @@ -11,7 +11,7 @@ The surface a plugin binds to is broader than one module. All of the following a - **The `:plugin-api` module** — package `com.itsaky.androidide.plugins.*`: - Core: `IPlugin` (lifecycle), `PluginContext`, `PluginLogger`, `ServiceRegistry`, `ResourceManager`. - Extension interfaces plugins **implement**: `UIExtension`, `EditorExtension`, `EditorTabExtension`, `DocumentationExtension`, `BuildActionExtension`, `SnippetExtension`, `ProjectExtension`, `FileOpenExtension`, `SettingsExtension`, `LanguageExtension`. - - IDE service interfaces plugins **call** (via `ServiceRegistry.get(X::class.java)`): `IdeProjectService`, `IdeEditorService`, `IdeFileService`, `IdeEnvironmentService`, `IdeArchiveService`, `IdeBuildService`, `IdeLogService`, `IdeUIService`, `IdeEditorTabService`, `IdeTooltipService`, `IdeThemeService`, `IdeFeatureFlagService` (the overall experiments switch only - see [EXPERIMENTS.md](../EXPERIMENTS.md#plugins)), `IdeCommandService`, `IdeTerminalService`, `IdeTemplateService`, `IdeSnippetService`, `IdeSidebarService`. + - IDE service interfaces plugins **call** (via `ServiceRegistry.get(X::class.java)`): `IdeProjectService`, `IdeEditorService`, `IdeFileService`, `IdeEnvironmentService`, `IdeArchiveService`, `IdeBuildService`, `IdeLogService`, `IdeUIService`, `IdeEditorTabService`, `IdeTooltipService`, `IdeThemeService`, `IdeFeatureFlagService` (the overall experiments switch only - see [EXPERIMENTS.md](../EXPERIMENTS.md#plugins)), `IdeCommandService`, `IdeTerminalService`, `IdeTemplateService`, `IdeSnippetService`, `IdeSidebarService`, `DebuggerEndpointService` (with `DebuggerEndpoint`, the value type it returns: one app's SQLite debugger port and token). - Cross-plugin service interfaces, where **one plugin implements what another calls** (via `SharedServices`): `LlmInferenceService` — implemented by ai-core, called by every AI plugin — together with the types nested in it that a *backend* plugin implements (`LlmBackend`, `HistoryCapableBackend`, `ToolCallingBackend`, `CancellableBackend`, `ConfigurableBackend`, `EmbeddingBackend`) and the value types either side constructs (`ChatMessage`, `LlmConfig`, `LlmResponse`, `SystemPromptRequest`, `ToolDefinition`, `ToolCallRequest`). Also `ToolSourceRegistry` — implemented by ai-core, called by any plugin contributing tools to the agent — with `ToolSource` and `ToolSpec`, which a *contributing* plugin implements, `ToolInvocation`, which ai-core constructs and passes to `ToolSource.invoke`, and `ToolOutcome`, which the source returns. - Utility classes plugins **instantiate**: `KeystoreSecretStore` (AES/GCM over the Android Keystore, alias supplied by the caller); the AI prompt config engine in `ai.prompt` (`PromptTemplateEngine`, `PromptConfigLoader`, `PromptConfigStore`, `PromptConfigDocument`, `PromptConfigObject`, `AssetPromptConfigSource`), generic over a plugin's own config type through `PromptConfigParser` and `PromptConfigProvider`, which a plugin implements; and the settings-pane helpers in `ai.ui` (`SecretRevealController` with `RevealToggle`, `applyPaneStyling` with `PaneStyle`, `ButtonColors` and `FieldColors`). Host-side implementations rather than interfaces, so plugins share one copy in the process instead of compiling their own. - Data classes plugins **construct** (e.g. `MenuItem`, `TabItem`, `EditorTabItem`, `NavigationItem`, `ToolbarAction`, `FabAction`, `PluginBuildAction`, `SnippetContribution`, `PluginTooltipEntry`, `PluginSettingsEntry`, `LanguageDefinition`, `TreeSitterGrammar`, `LanguageServerDefinition`). From d7a9b08a94a61e16afd521ccc8c797c94037728b Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:13:03 -0800 Subject: [PATCH 15/35] ADFA-7139 Return the SQLite debugger endpoints in an unmodifiable list getEndpoints() handed back whatever list the source built, which for the app's source is a mutable ArrayList, and the Javadoc did not say either way. The service now returns an unmodifiable copy, and the Javadoc and the changelog say the list cannot be modified. DebuggerEndpointServiceImplTest checks that adding to it throws, also when the source built a mutable list. Review Q4 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 2 +- .../plugins/services/DebuggerEndpointService.java | 2 +- .../manager/services/DebuggerEndpointServiceImpl.kt | 3 ++- .../manager/services/DebuggerEndpointServiceImplTest.kt | 9 +++++++++ 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index e5edebd267..2c9a07725e 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -37,7 +37,7 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] ### 26.47 — unreleased - **added — Find the SQLite debugger of the open project's apps** _(ADFA-7139)_ **[verified]** - `DebuggerEndpointService.getEndpoints()` returns a `List`, one per app of the open + `DebuggerEndpointService.getEndpoints()` returns an unmodifiable `List`, one per app of the open project that has reported to the IDE: `applicationId`, `port` (on `127.0.0.1`), `token` (the bearer token the server requires) and `updatedAtMillis`. The list is empty, never null, when no project is open in the editor (the home screen, even right after a project was closed) or no app has reported. Port and token change every time the app starts, so call again after a diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index d975c922c3..3c18b7aaba 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -25,7 +25,7 @@ public interface DebuggerEndpointService { *

* An app the IDE installed or launched but that has not yet reported is not listed, and neither is an app that has since been uninstalled. An endpoint can still be stale: when the app's process has died, its last reported port and token stay here until the app reports again, so treat {@link DebuggerEndpoint#getUpdatedAtMillis} (when it last reported) as a hint, and when a connection is refused, call this again and reconnect. * - * @return the endpoints (never null; empty when no project is open in the editor, as on the home screen, or no app has reported) + * @return the endpoints, in a list the caller cannot modify (never null; empty when no project is open in the editor, as on the home screen, or no app has reported) * @throws SecurityException * if the plugin lacks the {@code debugger.endpoints} permission * @throws IllegalStateException diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index 016ac14d81..57caff6626 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -70,7 +70,8 @@ internal class DebuggerEndpointServiceImpl( } // Again after the read: a plugin disabled while it ran gets no tokens either. requireOpen() - return endpoints + // The contract promises an unmodifiable list, whatever list the source built. + return Collections.unmodifiableList(ArrayList(endpoints)) } /** diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt index d700f3e87a..5b0dd86135 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -36,6 +36,15 @@ class DebuggerEndpointServiceImplTest { assertThat(seen).isEmpty() } + @Test + fun `the list returned cannot be modified, whatever list the source built`() { + val endpoints = service(source = { arrayListOf(endpoint) }).getEndpoints() + val none = service(root = null).getEndpoints() + + assertThrows(UnsupportedOperationException::class.java) { (endpoints as MutableList).add(endpoint) } + assertThrows(UnsupportedOperationException::class.java) { (none as MutableList).add(endpoint) } + } + @Test fun `is empty when the project has no endpoint`() { assertThat(service(root = File("/data/projects/other")).getEndpoints()).isEmpty() From 4f1230a3e161d998b5d859c5629d9916a063232c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:14:20 -0800 Subject: [PATCH 16/35] ADFA-7139 Declare the InterruptedException getEndpoints() can throw The implementation rethrows an interrupt as InterruptedException, but the Java method declared no throws clause, so a Java plugin could not catch it (javac: "exception is never thrown in body of try"), and one that caught only the documented exceptions lost its worker to an undeclared one. getEndpoints() now declares InterruptedException, and the Javadoc says the interrupt status stays set, and that CancellationException also comes from a cancelled read. The class Javadoc also says refusing the main thread is deliberate, stricter than IdeLogService and IdeProjectService, because the call reads a database (review Q3). The changelog says so too. The API dump has no throws clauses, so apiDump is unchanged. The endpoint API is unreleased (26.47), so the new checked exception breaks no shipped caller. DebuggerEndpointTest has a Java caller catch the InterruptedException; it does not compile without the declaration. The read-failure message now says "SQLite debugger". Review R3 and Q3 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 3 ++- .../plugins/services/DebuggerEndpointService.java | 8 +++++--- .../plugins/services/DebuggerEndpointTest.java | 13 +++++++++++++ .../manager/services/DebuggerEndpointServiceImpl.kt | 3 ++- 4 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 2c9a07725e..3b45974b29 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -47,7 +47,8 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] `SecurityException` without it, and `IllegalStateException` on the main thread or when the database cannot be read (an unreadable database is not reported as an empty list). Once the plugin is disabled or unloaded, a call throws `java.util.concurrent.CancellationException` until it is enabled again, as - `IdeTerminalService` calls do. Plugins run in Code on the + `IdeTerminalService` calls do. The method declares `InterruptedException`, thrown with the thread's + interrupt status set again when the caller is interrupted during the read. Plugins run in Code on the Go's process, so the permission declares intent and cannot stop reflection, as with `IdeLogService` below. Floor `plugin.min_ide_version` at `26.47`: an IDE of 26.46 or older rejects the unknown `debugger.endpoints` permission when it diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index 3c18b7aaba..994f0a1af6 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -10,7 +10,7 @@ * The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it, like the other permission-gated services. Plugins run in Code on the Go's process, so the permission declares what a plugin means to do: it cannot stop a plugin that reaches into the host by reflection. * *

- * Calls are synchronous, as in {@link IdeLogService} and {@link IdeProjectService}, rather than returning a {@link java.util.concurrent.CompletableFuture} as the services that start long work do: the answer is a small read of the IDE's own database, not an operation with a lifecycle. That read is disk I/O, so call from a background thread: on the main thread the call throws {@link IllegalStateException}. + * Calls are synchronous, as in {@link IdeLogService} and {@link IdeProjectService}, rather than returning a {@link java.util.concurrent.CompletableFuture} as the services that start long work do: the answer is a small read of the IDE's own database, not an operation with a lifecycle. That read is disk I/O, so call from a background thread: on the main thread the call throws {@link IllegalStateException}. This is stricter than those two services on purpose: they answer on any thread, but a database read on the main thread can stall the UI. */ public interface DebuggerEndpointService { @@ -31,8 +31,10 @@ public interface DebuggerEndpointService { * @throws IllegalStateException * if called on the main thread, or if the IDE's database could not be read. A failed read is not the same as no apps: keep what you had and try again later * @throws java.util.concurrent.CancellationException - * if the plugin has been disabled or unloaded, until it is enabled again; also when a call already reading sees it disabled + * if the plugin has been disabled or unloaded, until it is enabled again; also when a call already reading sees it disabled, or when the read itself is cancelled + * @throws InterruptedException + * if the calling thread is interrupted while it waits for the read. The thread's interrupt status is set again before this is thrown, so code further up still sees it */ @NonNull - List getEndpoints(); + List getEndpoints() throws InterruptedException; } diff --git a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java index db35c1407d..91d96875b8 100644 --- a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java +++ b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java @@ -11,6 +11,19 @@ public class DebuggerEndpointTest { + @Test + public void aJavaCallerCanCatchTheInterrupt() { + final DebuggerEndpointService interrupted = () -> { + throw new InterruptedException("stop"); + }; + try { + interrupted.getEndpoints(); + fail(); + } catch (InterruptedException expected) { + assertEquals("stop", expected.getMessage()); + } + } + @Test public void equalityCoversEveryField() { final DebuggerEndpoint base = new DebuggerEndpoint("a", 1, "t", 2L); diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index 57caff6626..ec2230fba1 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -44,6 +44,7 @@ internal class DebuggerEndpointServiceImpl( @Volatile private var closed = false + @Throws(InterruptedException::class) override fun getEndpoints(): List { if (PluginPermission.DEBUGGER_ENDPOINTS !in permissions) { throw SecurityException( @@ -66,7 +67,7 @@ internal class DebuggerEndpointServiceImpl( throw e } catch (e: Exception) { log.warn("getEndpoints failed for plugin {}", pluginId, e) - throw IllegalStateException("Could not read the debugger endpoints: ${e.message}", e) + throw IllegalStateException("Could not read the SQLite debugger endpoints: ${e.message}", e) } // Again after the read: a plugin disabled while it ran gets no tokens either. requireOpen() From 46bc104e747569fca6275f5ab33fe1a94f004723 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:14:42 -0800 Subject: [PATCH 17/35] ADFA-7139 Docs: say what the debugger.endpoints permission gives a plugin The sqlite-debugger README says whoever holds the token can run SQL, but nothing a plugin author reads said so. The permission's description, the DebuggerEndpointService Javadoc, the changelog and PLUGIN_AUTHORING.md now state it: the token is the server's only credential, so a plugin with the permission can query the databases of the open project's apps, read-only in this version, writes possibly later. Text only. Review Q2 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 4 +++- docs/PLUGIN_AUTHORING.md | 2 +- .../androidide/plugins/services/DebuggerEndpointService.java | 3 +++ .../src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt | 5 +++-- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 3b45974b29..07af4c4b24 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -44,7 +44,9 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] refused connection or a 401/403. An app that was uninstalled is left out, but one whose process died stays listed until it reports again (`updatedAtMillis` is when it last reported). The call reads the IDE's database: use a background thread. It needs the new `debugger.endpoints` permission (`PluginPermission.DEBUGGER_ENDPOINTS`) and throws - `SecurityException` without it, and `IllegalStateException` on the main thread or when the database + `SecurityException` without it. The token is the server's only credential, so a plugin holding the + permission can query the databases of the open project's apps (read-only in this version; a later + version may allow writes). The call throws `IllegalStateException` on the main thread or when the database cannot be read (an unreadable database is not reported as an empty list). Once the plugin is disabled or unloaded, a call throws `java.util.concurrent.CancellationException` until it is enabled again, as `IdeTerminalService` calls do. The method declares `InterruptedException`, thrown with the thread's diff --git a/docs/PLUGIN_AUTHORING.md b/docs/PLUGIN_AUTHORING.md index 6f1a98c186..5463593a6c 100644 --- a/docs/PLUGIN_AUTHORING.md +++ b/docs/PLUGIN_AUTHORING.md @@ -343,7 +343,7 @@ Defined by `PluginPermission` in `plugin-api/src/main/kotlin/com/itsaky/androidi | `project.structure` | Modify project structure | | `native.code` | Execute native machine code | | `ide.environment.write` | Write to IDE-managed directories (Android SDK, NDK, cache) | -| `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers | +| `debugger.endpoints` | Read the port and token of the open project's SQLite debugger servers, and so query the apps' databases (read-only for now) | Plugins run in Code on the Go's process. A permission declares what a plugin means to do, and the services check it on every call, but it cannot stop a plugin that reaches into the host by diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index 994f0a1af6..8419b3d49e 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -7,6 +7,9 @@ * Tells a plugin where the SQLite debugger servers of the open project's apps are listening, so a plugin such as an MCP client can connect without the user typing a port or token. * *

+ * What a plugin gets: the token is the only credential a SQLite debugger server checks, so a plugin with this service's permission can query the databases of the open project's apps through it. The server opens them read-only in this version; a later version may allow writes. Declare the permission only if the plugin needs that access. + * + *

* The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it, like the other permission-gated services. Plugins run in Code on the Go's process, so the permission declares what a plugin means to do: it cannot stop a plugin that reaches into the host by reflection. * *

diff --git a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt index e1be903e9f..246836d1c8 100644 --- a/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt +++ b/plugin-api/src/main/kotlin/com/itsaky/androidide/plugins/IPlugin.kt @@ -56,8 +56,9 @@ enum class PluginPermission( IDE_ENVIRONMENT_WRITE("ide.environment.write", "Write to IDE-managed directories such as the Android SDK, NDK, and cache"), DEBUGGER_ENDPOINTS( "debugger.endpoints", - "Read the port and token of the open project's SQLite debugger servers. Plugins run in Code on the Go's process, " + - "so this declares intent and cannot stop reflection", + "Read the port and token of the open project's SQLite debugger servers. The token lets the plugin query the " + + "databases of the project's apps: read-only for now, and later versions may allow writes. Plugins run in " + + "Code on the Go's process, so this declares intent and cannot stop reflection", ), } From 0bd8ab166662d9c6e59478f1bb713b99d9dfa8f3 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:14:51 -0800 Subject: [PATCH 18/35] ADFA-7139 Pin DebuggerEndpointService.CONTRACT_VERSION at 1 CONTRACT_VERSION >= 1 held for any value, so it pinned nothing. The test now asserts it is 1, so a bump has to change the test too and cannot happen by accident. Review Q5 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../androidide/plugins/services/DebuggerEndpointTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java index 91d96875b8..e0073e71c8 100644 --- a/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java +++ b/plugin-api/src/test/java/com/itsaky/androidide/plugins/services/DebuggerEndpointTest.java @@ -3,7 +3,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.itsaky.androidide.plugins.PluginPermission; @@ -59,7 +58,7 @@ public void nullApplicationIdOrTokenIsRejected() { @Test public void permissionKeyIsStable() { assertEquals("debugger.endpoints", PluginPermission.DEBUGGER_ENDPOINTS.getKey()); - assertTrue(DebuggerEndpointService.CONTRACT_VERSION >= 1); + assertEquals(1, DebuggerEndpointService.CONTRACT_VERSION); } @Test From ad91c840732ebb0879dfaf90e449ee44c43a44de Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:23:21 -0800 Subject: [PATCH 19/35] ADFA-7139 Drop the empty-list case from the unmodifiable-list test The test added in d7a9b08a9 also cast the empty result to MutableList. That result is Kotlin's emptyList(), a read-only Kotlin type, so the cast itself threw ClassCastException before add() could throw. A Java caller's add() on it throws UnsupportedOperationException, so the empty result keeps the contract; the test now checks only the case the fix changed, a list the source built as an ArrayList. Review Q4 on #2261. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/manager/services/DebuggerEndpointServiceImplTest.kt | 2 -- 1 file changed, 2 deletions(-) diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt index 5b0dd86135..b5f6e9528c 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -39,10 +39,8 @@ class DebuggerEndpointServiceImplTest { @Test fun `the list returned cannot be modified, whatever list the source built`() { val endpoints = service(source = { arrayListOf(endpoint) }).getEndpoints() - val none = service(root = null).getEndpoints() assertThrows(UnsupportedOperationException::class.java) { (endpoints as MutableList).add(endpoint) } - assertThrows(UnsupportedOperationException::class.java) { (none as MutableList).add(endpoint) } } @Test From 6ed99d77d3d8650d6a4449ea6fce4f237b3435d5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 09:24:40 -0800 Subject: [PATCH 20/35] ADFA-7139 style: spotless reformat of DebuggerEndpointRepositoryTest, no functional change The explicit isInstalled argument (89b5c7e12) took two constructor calls past ktlint's 140 columns, and the promoted two-project test (ce08883de) chained java.nio.file.Files calls on one line. spotlessApply output, nothing else. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../DebuggerEndpointRepositoryTest.kt | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index 6dc59e8352..925d3e3319 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -33,7 +33,12 @@ class DebuggerEndpointRepositoryTest { .allowMainThreadQueries() .build() repository = - DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { 1234L }, isInstalled = { true }) + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { 1234L }, + isInstalled = { true }, + ) } @After @@ -179,7 +184,12 @@ class DebuggerEndpointRepositoryTest { } private fun clockedRepository(now: AtomicLong) = - DebuggerEndpointRepository(room.debuggerEndpointDao(), CoroutineScope(Dispatchers.IO), clock = { now.get() }, isInstalled = { true }) + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { now.get() }, + isInstalled = { true }, + ) @Test fun `a failed install does not pair a later install of the same app`() = @@ -398,10 +408,17 @@ class DebuggerEndpointRepositoryTest { @Test fun `each project gets only its own apps, also through a symlinked path, and an app moved away leaves the old one`() = runBlocking { - val a = java.nio.file.Files.createTempDirectory("projA").toFile() - val b = java.nio.file.Files.createTempDirectory("projB").toFile() + val a = + java.nio.file.Files + .createTempDirectory("projA") + .toFile() + val b = + java.nio.file.Files + .createTempDirectory("projB") + .toFile() val link = File(a.parentFile, a.name + "-link") - java.nio.file.Files.createSymbolicLink(link.toPath(), a.toPath()) + java.nio.file.Files + .createSymbolicLink(link.toPath(), a.toPath()) try { addProject(a.canonicalPath) addProject(b.canonicalPath) From a32d2886bbe30779c5cebf1b6045f83cacdcc255 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:22:07 -0800 Subject: [PATCH 21/35] ADFA-7139 Say which public paths still reach another plugin's DebuggerEndpointService The KDoc, the Javadoc and the changelog claimed every path short of reflection was closed. A plugin without the permission can still take another plugin's service from PluginManager.getInstance().getLoadedPlugin(id).context.services and from PluginFragmentHelper.getServiceRegistry. Name both, and point at ADFA-7194, which tracks them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 4 +++- .../plugins/services/DebuggerEndpointService.java | 2 +- .../manager/services/DebuggerEndpointServiceImpl.kt | 8 +++++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 07af4c4b24..0e11d4ff48 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -52,7 +52,9 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] `IdeTerminalService` calls do. The method declares `InterruptedException`, thrown with the thread's interrupt status set again when the caller is interrupted during the read. Plugins run in Code on the Go's process, so the permission declares intent and cannot stop reflection, as with `IdeLogService` - below. Floor `plugin.min_ide_version` + below, and does not stop a plugin from taking another plugin's service from + `PluginManager.getInstance().getLoadedPlugin(id).context.services` or `PluginFragmentHelper.getServiceRegistry` + (tracked in ADFA-7194). Floor `plugin.min_ide_version` at `26.47`: an IDE of 26.46 or older rejects the unknown `debugger.endpoints` permission when it validates the manifest, so it refuses to install a plugin that declares it. diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index 8419b3d49e..30fc641c23 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -10,7 +10,7 @@ * What a plugin gets: the token is the only credential a SQLite debugger server checks, so a plugin with this service's permission can query the databases of the open project's apps through it. The server opens them read-only in this version; a later version may allow writes. Declare the permission only if the plugin needs that access. * *

- * The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it, like the other permission-gated services. Plugins run in Code on the Go's process, so the permission declares what a plugin means to do: it cannot stop a plugin that reaches into the host by reflection. + * The host registers this service for every plugin; a call needs the {@link com.itsaky.androidide.plugins.PluginPermission#DEBUGGER_ENDPOINTS} permission and throws {@link SecurityException} without it, like the other permission-gated services. Plugins run in Code on the Go's process, so the permission declares what a plugin means to do: it cannot stop a plugin that reaches into the host by reflection, nor one that takes another plugin's service from the public {@code PluginManager.getInstance().getLoadedPlugin(id).context.services} or {@code PluginFragmentHelper.getServiceRegistry} (tracked in ADFA-7194). * *

* Calls are synchronous, as in {@link IdeLogService} and {@link IdeProjectService}, rather than returning a {@link java.util.concurrent.CompletableFuture} as the services that start long work do: the answer is a small read of the IDE's own database, not an operation with a lifecycle. That read is disk I/O, so call from a background thread: on the main thread the call throws {@link IllegalStateException}. This is stricter than those two services on purpose: they answer on any thread, but a database read on the main thread can stall the UI. diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index ec2230fba1..002eb0036d 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -25,9 +25,11 @@ fun interface DebuggerEndpointSource { * * Plugins run in Code on the Go's process, and their class loader's parent is the host's, so the * permission check declares intent: it cannot stop a plugin that reaches host objects by reflection. - * What it does close is every path short of that. The source is held privately by the plugin manager, - * which installs it once, and this service keeps its own unmodifiable copy of the permissions, so - * changing the set it was built from grants nothing. + * It does not stop a plugin without the permission from reaching another plugin's service either: + * two public entry points hand it out, `PluginManager.getInstance().getLoadedPlugin(id).context.services` + * and `PluginFragmentHelper.getServiceRegistry`. Both are tracked in ADFA-7194. What this class does + * keep: the source is held privately by the plugin manager, which installs it once, and this service + * keeps its own unmodifiable copy of the permissions, so changing the set it was built from grants nothing. */ internal class DebuggerEndpointServiceImpl( private val pluginId: String, From 24453ed0090c2a38d25c16d25fd7f3147d6d512d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:27:09 -0800 Subject: [PATCH 22/35] ADFA-7139 Keep the DebuggerEndpointService closed for a plugin saved as disabled and after a failed initialize The service started open, so a plugin saved as disabled could read tokens from its own initialize(), and one whose initialize() threw or returned false kept an open service for any thread it started. Create it closed when the saved state is disabled (enablePlugin reopens it) and close it when initialize() fails. The activation-failure close, which a failed activate() already relies on, keeps working. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/manager/core/PluginManager.kt | 11 ++- .../services/DebuggerEndpointServiceImpl.kt | 4 +- .../core/PluginManagerDebuggerEndpointTest.kt | 84 ++++++++++++++++++- 3 files changed, 94 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 1d660e2f40..60d424a4e0 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 @@ -409,7 +409,7 @@ class PluginManager private constructor( ?.let(::File) } - /** Where [DebuggerEndpointService] reads. Private: short of reflection, a plugin cannot read tokens around the service. */ + /** Where [DebuggerEndpointService] reads. Private, so no member of this class hands it out. This does not seal every path: see [DebuggerEndpointServiceImpl]. */ private val debuggerEndpointSource = AtomicReference() /** @@ -689,6 +689,8 @@ class PluginManager private constructor( val initResult = initializePlugin(plugin, pluginContext).getOrElse { e -> logger.error("Plugin initialization threw exception for: ${manifest.id}", e) + // The plugin may have started threads of its own in initialize(). + pluginContext.closeDebuggerEndpointService() if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -697,6 +699,7 @@ class PluginManager private constructor( if (!initResult) { logger.warn(" plugin initialization returned false for: ${manifest.id}") + pluginContext.closeDebuggerEndpointService() if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -1253,6 +1256,10 @@ class PluginManager private constructor( }.onFailure { logger.error("Failed to cleanup templates for: $pluginId", it) } } + private fun PluginContext.closeDebuggerEndpointService() { + (services.get(DebuggerEndpointService::class.java) as? DebuggerEndpointServiceImpl)?.close() + } + /** The plugin's [DebuggerEndpointServiceImpl]. Its services outlive a disable, so it is closed instead. */ private fun LoadedPlugin.debuggerEndpointService(): DebuggerEndpointServiceImpl? = context.services.get(DebuggerEndpointService::class.java) as? DebuggerEndpointServiceImpl @@ -1635,6 +1642,8 @@ class PluginManager private constructor( permissions = permissions, projectRootProvider = ::openProjectRoot, sourceProvider = debuggerEndpointSource::get, + // A plugin saved as disabled gets no tokens from its own initialize(); enablePlugin reopens it. + startOpen = getPluginState(pluginId), ) } diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index 002eb0036d..acaa5dd481 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -38,13 +38,15 @@ internal class DebuggerEndpointServiceImpl( /** Null until the app installs one. */ private val sourceProvider: () -> DebuggerEndpointSource?, private val isMainThread: () -> Boolean = { Looper.myLooper() == Looper.getMainLooper() }, + /** False for a plugin saved as disabled: it stays closed through its own initialize() until [reopen]. */ + startOpen: Boolean = true, ) : DebuggerEndpointService { private val permissions: Set = Collections.unmodifiableSet(EnumSet.noneOf(PluginPermission::class.java).apply { addAll(permissions) }) // Set by close, cleared by reopen. A disabled plugin keeps its services, and any thread it left running. @Volatile - private var closed = false + private var closed = !startOpen @Throws(InterruptedException::class) override fun getEndpoints(): List { diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index 35d94627c8..8af9177ac4 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -155,6 +155,46 @@ class PluginManagerDebuggerEndpointTest { assertThrows(CancellationException::class.java) { offMainThread { reloaded.getEndpoints() } } } + @Test + fun `a plugin saved as disabled cannot read endpoints from its own initialize`() { + load("reader", "debugger.endpoints") + assertThat(pluginManager().disablePlugin("reader")).isTrue() + assertThat(pluginManager().unloadPlugin("reader")).isTrue() + openInEditor(project) + ReadingInInitializePlugin.outcome = null + + load("reader", "debugger.endpoints", ReadingInInitializePlugin::class.java) + + assertThat(ReadingInInitializePlugin.outcome!!.exceptionOrNull()).isInstanceOf(CancellationException::class.java) + assertThat(asked).isEmpty() + } + + @Test + fun `an enabled plugin can read endpoints from its own initialize`() { + openInEditor(project) + ReadingInInitializePlugin.outcome = null + + load("reader", "debugger.endpoints", ReadingInInitializePlugin::class.java) + + assertThat(ReadingInInitializePlugin.outcome!!.getOrThrow()).containsExactly(endpoint) + } + + @Test + fun `a plugin whose initialize returns false or throws is left with a service that refuses`() { + openInEditor(project) + for (mode in listOf(FailingInitializePlugin.Mode.RETURN_FALSE, FailingInitializePlugin.Mode.THROW)) { + FailingInitializePlugin.mode = mode + FailingInitializePlugin.service = null + val file = fakePlugin(File(RuntimeEnvironment.getApplication().filesDir, "plugins/failing.cgp"), "failing", "debugger.endpoints", FailingInitializePlugin::class.java) + + assertThat(pluginManager().loadPlugin(file).isFailure).isTrue() + + val service = checkNotNull(FailingInitializePlugin.service) + assertThrows(CancellationException::class.java) { offMainThread { service.getEndpoints() } } + } + assertThat(asked).isEmpty() + } + @Test fun `a second install, as a plugin would try, fails and leaves the app's source in place`() { val service = load("reader", "debugger.endpoints") @@ -185,8 +225,9 @@ class PluginManagerDebuggerEndpointTest { private fun load( id: String, permissions: String, + mainClass: Class = ContextKeepingPlugin::class.java, ): DebuggerEndpointService { - val file = fakePlugin(File(RuntimeEnvironment.getApplication().filesDir, "plugins/$id.cgp"), id, permissions) + val file = fakePlugin(File(RuntimeEnvironment.getApplication().filesDir, "plugins/$id.cgp"), id, permissions, mainClass) val result = pluginManager().loadPlugin(file) assertWithMessage("plugin $id did not load: ${result.exceptionOrNull()}").that(result.isSuccess).isTrue() val plugin = pluginManager().getPlugin(id) as ContextKeepingPlugin @@ -215,6 +256,7 @@ class PluginManagerDebuggerEndpointTest { file: File, id: String, permissions: String, + mainClass: Class = ContextKeepingPlugin::class.java, ): File { file.parentFile?.mkdirs() ZipOutputStream(file.outputStream()).use { it.putNextEntry(ZipEntry("classes.dex")) } @@ -226,7 +268,7 @@ class PluginManagerDebuggerEndpointTest { metaData = Bundle().apply { putString("plugin.id", id) - putString("plugin.main_class", ContextKeepingPlugin::class.java.name) + putString("plugin.main_class", mainClass.name) putString("plugin.permissions", permissions) } } @@ -236,7 +278,7 @@ class PluginManagerDebuggerEndpointTest { } /** A plugin that keeps its context. Its class loader finds it through its parent, the test's. */ - class ContextKeepingPlugin : IPlugin { + open class ContextKeepingPlugin : IPlugin { lateinit var context: PluginContext override fun initialize(context: PluginContext): Boolean { @@ -251,6 +293,42 @@ class PluginManagerDebuggerEndpointTest { override fun dispose() = Unit } + /** Reads endpoints from initialize(), on a thread of its own as a real plugin would. */ + class ReadingInInitializePlugin : ContextKeepingPlugin() { + override fun initialize(context: PluginContext): Boolean { + super.initialize(context) + val service = checkNotNull(context.services.get(DebuggerEndpointService::class.java)) + val result = AtomicReference>>() + thread { result.set(runCatching { service.getEndpoints() }) }.join() + outcome = result.get() + return true + } + + companion object { + @Volatile + var outcome: Result>? = null + } + } + + /** Keeps its service, then fails initialize() as [mode] says. */ + class FailingInitializePlugin : ContextKeepingPlugin() { + enum class Mode { RETURN_FALSE, THROW } + + override fun initialize(context: PluginContext): Boolean { + service = context.services.get(DebuggerEndpointService::class.java) + if (mode == Mode.THROW) error("initialize failed") + return false + } + + companion object { + @Volatile + var mode = Mode.RETURN_FALSE + + @Volatile + var service: DebuggerEndpointService? = null + } + } + /** The editor activity's provider, as registered while it shows a project. */ private object OpenEditor : IdeEditorServiceImpl.EditorProvider { override fun getCurrentFile(): File? = null From 14067c08bd4c55be1c664d32d10d8b19107fe1d6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:27:09 -0800 Subject: [PATCH 23/35] ADFA-7139 Test that a failed activation closes the DebuggerEndpointService Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../core/PluginManagerDebuggerEndpointTest.kt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index 8af9177ac4..d8d87ef747 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -195,6 +195,17 @@ class PluginManagerDebuggerEndpointTest { assertThat(asked).isEmpty() } + @Test + fun `a plugin whose activation fails is left disabled and its service refuses`() { + openInEditor(project) + + val service = load("reader", "debugger.endpoints", FailingActivationPlugin::class.java) + + assertThat(pluginManager().getLoadedPlugin("reader")).isNull() + assertThrows(CancellationException::class.java) { offMainThread { service.getEndpoints() } } + assertThat(asked).isEmpty() + } + @Test fun `a second install, as a plugin would try, fails and leaves the app's source in place`() { val service = load("reader", "debugger.endpoints") @@ -329,6 +340,11 @@ class PluginManagerDebuggerEndpointTest { } } + /** initialize() succeeds, activate() throws. */ + class FailingActivationPlugin : ContextKeepingPlugin() { + override fun activate(): Boolean = error("activate failed") + } + /** The editor activity's provider, as registered while it shows a project. */ private object OpenEditor : IdeEditorServiceImpl.EditorProvider { override fun getCurrentFile(): File? = null From cff9d24adf53d64e18532446c3cdbc807d723fbd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 10:31:32 -0800 Subject: [PATCH 24/35] ADFA-7139 style: spotless format of PluginManagerDebuggerEndpointTest, no functional change Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../manager/core/PluginManagerDebuggerEndpointTest.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index d8d87ef747..d0c6ed075a 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -185,7 +185,13 @@ class PluginManagerDebuggerEndpointTest { for (mode in listOf(FailingInitializePlugin.Mode.RETURN_FALSE, FailingInitializePlugin.Mode.THROW)) { FailingInitializePlugin.mode = mode FailingInitializePlugin.service = null - val file = fakePlugin(File(RuntimeEnvironment.getApplication().filesDir, "plugins/failing.cgp"), "failing", "debugger.endpoints", FailingInitializePlugin::class.java) + val file = + fakePlugin( + File(RuntimeEnvironment.getApplication().filesDir, "plugins/failing.cgp"), + "failing", + "debugger.endpoints", + FailingInitializePlugin::class.java, + ) assertThat(pluginManager().loadPlugin(file).isFailure).isTrue() From 9149b5825cc38b04592019e4bdbaa526cb7a9a1d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 18:39:40 -0800 Subject: [PATCH 25/35] ADFA-7139 Let a retried plugin start install the same endpoint source CredentialProtectedApplicationLoader.load clears _isLoaded when a step after initializePluginSystem fails, and the retry after the user unlocks runs initializePluginSystem again on the same PluginManager singleton with the same Koin DebuggerEndpointSource. installDebuggerEndpointSource then threw IllegalStateException; initializePluginSystem caught it, sent it to Sentry, and skipped the rest of plugin setup, plugin loading included. Installing the same source again is now a no-op. A different source, which can only be a plugin's, still throws and leaves the app's source in place. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/manager/core/PluginManager.kt | 14 +++++++---- .../core/PluginManagerDebuggerEndpointTest.kt | 23 +++++++++++++++---- 2 files changed, 28 insertions(+), 9 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 91b04856e6..6507c88412 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 @@ -420,14 +420,18 @@ class PluginManager private constructor( /** * Installs where every plugin's [DebuggerEndpointService] reads the SQLite debugger endpoints apps - * reported. The app installs it once, before plugins load. Plugins share this class loader, so a - * later call, which can only be a plugin's, fails rather than replacing or blanking the source for - * every plugin. + * reported. The app installs it before plugins load. Installing the same source again does nothing: + * the app's start runs again when a later step of it failed (CredentialProtectedApplicationLoader.load + * retries after the user unlocks). Plugins share this class loader, so a different source, which can + * only be a plugin's, fails rather than replacing or blanking the source for every plugin. * - * @throws IllegalStateException if a source is already installed + * @throws IllegalStateException if a different source is already installed */ fun installDebuggerEndpointSource(source: DebuggerEndpointSource) { - check(debuggerEndpointSource.compareAndSet(null, source)) { "The SQLite debugger endpoint source is already installed" } + // Never cleared, so once compareAndSet fails, get() is the installed source. + check(debuggerEndpointSource.compareAndSet(null, source) || debuggerEndpointSource.get() === source) { + "A different SQLite debugger endpoint source is already installed" + } } init { diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index d0c6ed075a..c8535c0011 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -46,6 +46,13 @@ class PluginManagerDebuggerEndpointTest { private val endpoint = DebuggerEndpoint("com.example.demo", 4321, "tok", 99L) private val asked = CopyOnWriteArrayList() + /** The app's source, which setUp installs. */ + private val source = + DebuggerEndpointSource { location -> + asked += location + if (location == project.absolutePath) listOf(endpoint) else emptyList() + } + private val templatesDir = Environment.TEMPLATES_DIR @Before @@ -53,10 +60,7 @@ class PluginManagerDebuggerEndpointTest { project = Files.createTempDirectory("proj").toFile() // Disabling and unloading clean up the plugin's templates there. Environment.TEMPLATES_DIR = File(RuntimeEnvironment.getApplication().filesDir, "templates").apply { mkdirs() } - pluginManager().installDebuggerEndpointSource { location -> - asked += location - if (location == project.absolutePath) listOf(endpoint) else emptyList() - } + pluginManager().installDebuggerEndpointSource(source) } @After @@ -222,6 +226,17 @@ class PluginManagerDebuggerEndpointTest { assertThat(offMainThread { service.getEndpoints() }).containsExactly(endpoint) } + @Test + fun `installing the same source again, as a retried app start does, is allowed and a different one still fails`() { + val service = load("reader", "debugger.endpoints") + openInEditor(project) + + pluginManager().installDebuggerEndpointSource(source) + assertThrows(IllegalStateException::class.java) { pluginManager().installDebuggerEndpointSource { emptyList() } } + + assertThat(offMainThread { service.getEndpoints() }).containsExactly(endpoint) + } + @Test fun `no public member hands out the source, and the public holder plugins could read is gone`() { val types = PluginManager::class.java.methods.map { it.returnType } + PluginManager::class.java.fields.map { it.type } From d51c88faf7dcd0221d91ed3a3932c7e336af42a8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 18:39:57 -0800 Subject: [PATCH 26/35] ADFA-7139 Delete the unused createPluginContext overload The private createPluginContext(pluginId, classLoader, permissions) had no caller (plugins load through createPluginContextWithResources), and its DebuggerEndpointService registration took startOpen's default of true, so a plugin saved as disabled would have started with an open service had anything ever called it. Every symbol it used is still used elsewhere. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/manager/core/PluginManager.kt | 220 ------------------ 1 file changed, 220 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 6507c88412..f8e4608bad 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 @@ -1742,226 +1742,6 @@ class PluginManager private constructor( ) } - private fun createPluginContext( - pluginId: String, - classLoader: ClassLoader, - permissions: Set, - ): PluginContext { - val pluginServiceRegistry = ServiceRegistryImpl() - - logger.debug("Creating IDE services for plugin: $pluginId") - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeProjectService::class.java, - pluginId, - "project", - ) { - IdeProjectServiceImpl( - pluginId = pluginId, - permissions = permissions, - projectProvider = projectProvider, - requiredPermissions = projectServicePermissions, - pathValidator = - pathValidator?.let { validator -> - object : IdeProjectServiceImpl.PathValidator { - override fun isPathAllowed(path: File): Boolean = validator.isPathAllowed(path) - - override fun getAllowedPaths(): List = validator.getAllowedPaths() - } - }, - activityProvider = delegatingActivityProvider, - ) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeUIService::class.java, - pluginId, - "UI", - ) { - IdeUIServiceImpl(delegatingActivityProvider) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeBuildService::class.java, - pluginId, - "build", - ) { - PluginBuildService(pluginId, permissions) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeLogService::class.java, - pluginId, - "log", - ) { - IdeLogServiceImpl.getInstance() - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeProjectManipulationService::class.java, - pluginId, - "project_manipulation", - ) { - IdeProjectManipulationServiceImpl.getInstance() - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeTooltipService::class.java, - pluginId, - "tooltip", - ) { - IdeTooltipServiceImpl(context, pluginId, delegatingActivityProvider) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeEditorTabService::class.java, - pluginId, - "editor_tab", - ) { - IdeEditorTabServiceImpl(delegatingActivityProvider) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeFileService::class.java, - pluginId, - "file", - ) { - IdeFileServiceImpl( - pluginId = pluginId, - permissions = permissions, - pathValidator = - pathValidator?.let { validator -> - object : IdeFileServiceImpl.PathValidator { - override fun isPathAllowed(path: File): Boolean = validator.isPathAllowed(path) - - override fun getAllowedPaths(): List = validator.getAllowedPaths() - } - }, - ) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeEnvironmentService::class.java, - pluginId, - "environment", - ) { - IdeEnvironmentServiceImpl(pluginId) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeArchiveService::class.java, - pluginId, - "archive", - ) { - IdeArchiveServiceImpl( - pluginId = pluginId, - permissions = permissions, - pathValidator = - pathValidator?.let { validator -> - object : IdeFileServiceImpl.PathValidator { - override fun isPathAllowed(path: File): Boolean = validator.isPathAllowed(path) - - override fun getAllowedPaths(): List = validator.getAllowedPaths() - } - }, - ) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeSidebarService::class.java, - pluginId, - "sidebar", - ) { - IdeSidebarServiceImpl(pluginId) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeThemeService::class.java, - pluginId, - "theme", - ) { - IdeThemeServiceImpl(context) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeFeatureFlagService::class.java, - pluginId, - "feature_flag", - ) { - IdeFeatureFlagServiceImpl() - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - DebuggerEndpointService::class.java, - pluginId, - "debugger_endpoint", - ) { - DebuggerEndpointServiceImpl( - pluginId = pluginId, - permissions = permissions, - projectRootProvider = ::openProjectRoot, - sourceProvider = debuggerEndpointSource::get, - ) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeTemplateService::class.java, - pluginId, - "template", - ) { - IdeTemplateServiceImpl( - pluginId = pluginId, - permissions = permissions, - onTemplatesChanged = { templateReloadListener?.invoke() }, - loadedPluginIds = { loadedPlugins.keys }, - ) - } - - registerServiceWithErrorHandling( - pluginServiceRegistry, - IdeSnippetService::class.java, - pluginId, - "snippet", - ) { - IdeSnippetServiceImpl().apply { - setRefreshCallback { pid -> - snippetRefreshListener?.invoke(pid) - } - } - } - - return PluginContextImpl( - androidContext = context, - services = pluginServiceRegistry, - eventBus = eventBus, - logger = PluginLoggerImpl(pluginId, logger), - resources = ResourceManagerImpl(pluginId, pluginsDir, classLoader), - pluginId = pluginId, - sharedServices = serviceRegistry, - lifecycleDispatcher = lifecycleDispatcher, - pluginInfoProvider = { id -> - loadedPlugins[id]?.let { - PluginInfo(it.toPluginMetadata(), it.isEnabled, isLoaded = true) - } - }, - ) - } - /** * Clean up ALL plugin files and cache directories */ From dc4c095d2d261bb1477b836d669d46872a41e517 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 21:59:33 -0800 Subject: [PATCH 27/35] ADFA-7139 Docs: DebuggerEndpointService ships in 26.48, not 26.47 Code on the Go 26.47 was released on 2026-11-17 without this stack, so the plugin API changelog entry moves to the next unreleased version, 26.48, and plugins floor plugin.min_ide_version at 26.48 (an IDE of 26.47 or older rejects the debugger.endpoints permission). Recheck against the real release number if the stack misses 26.48. No KDoc or Javadoc in #2259 to #2262 names a release version for this stack. Documentation only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- docs/PLUGIN_API_CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index b50125605d..1962698a22 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -35,7 +35,7 @@ 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 +### 26.48 — unreleased - **added — Find the SQLite debugger of the open project's apps** _(ADFA-7139)_ **[verified]** `DebuggerEndpointService.getEndpoints()` returns an unmodifiable `List`, one per app of the open project that has reported to the IDE: `applicationId`, `port` (on `127.0.0.1`), `token` (the bearer @@ -55,7 +55,7 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] below, and does not stop a plugin from taking another plugin's service from `PluginManager.getInstance().getLoadedPlugin(id).context.services` or `PluginFragmentHelper.getServiceRegistry` (tracked in ADFA-7194). Floor `plugin.min_ide_version` - at `26.47`: an IDE of 26.46 or older rejects the unknown `debugger.endpoints` permission when it + at `26.48`: an IDE of 26.47 or older rejects the unknown `debugger.endpoints` permission when it validates the manifest, so it refuses to install a plugin that declares it. ### 26.43 — unreleased From 300bf93e1a507651c44c0497b98bb00f4931bfbb Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 22:47:27 -0800 Subject: [PATCH 28/35] ADFA-7139 One endpoint-service helper; drop the close startOpen already does Review cleanups, no behaviour change (hal-eisen-adfa, PR #2261): - PluginContext.closeDebuggerEndpointService() and LoadedPlugin.debuggerEndpointService() did the same lookup. One PluginContext.debuggerEndpointService() now serves both; callers with a LoadedPlugin go through its context. - loadPlugin closed the service of a plugin loaded as disabled, but the service was created closed from the same saved state (startOpen = getPluginState), which isEnabled was just read from. Two mechanisms enforced one rule. startOpen stays, because it also covers the plugin's own initialize(); the comment there now says it is the only close such a plugin needs. "a plugin loaded while disabled gets a service that refuses" still passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/manager/core/PluginManager.kt | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 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 f8e4608bad..4cb3683cad 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 @@ -709,7 +709,7 @@ class PluginManager private constructor( initializePlugin(plugin, pluginContext).getOrElse { e -> logger.error("Plugin initialization threw exception for: ${manifest.id}", e) // The plugin may have started threads of its own in initialize(). - pluginContext.closeDebuggerEndpointService() + pluginContext.debuggerEndpointService()?.close() if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -718,7 +718,7 @@ class PluginManager private constructor( if (!initResult) { logger.warn(" plugin initialization returned false for: ${manifest.id}") - pluginContext.closeDebuggerEndpointService() + pluginContext.debuggerEndpointService()?.close() if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -747,8 +747,6 @@ class PluginManager private constructor( loadedPlugins[manifest.id] = loadedPlugin if (!isEnabled) { - // initialize() ran, so the plugin may already have threads of its own. - loadedPlugin.debuggerEndpointService()?.close() logger.info("Successfully loaded plugin (disabled): ${manifest.name} (${manifest.id})") return Result.success(plugin) } @@ -791,7 +789,7 @@ class PluginManager private constructor( }.onFailure { e -> logger.error("Failed to activate plugin: ${manifest.id}", e) loadedPlugin.isEnabled = false - loadedPlugin.debuggerEndpointService()?.close() + loadedPlugin.context.debuggerEndpointService()?.close() savePluginState(manifest.id, false) } } @@ -833,7 +831,7 @@ class PluginManager private constructor( try { // First: a later step can throw and end the unload. - loadedPlugin.debuggerEndpointService()?.close() + loadedPlugin.context.debuggerEndpointService()?.close() // Remove documentation if plugin implements DocumentationExtension if (loadedPlugin.plugin is DocumentationExtension) { @@ -1163,7 +1161,7 @@ class PluginManager private constructor( // The services outlive a disable, which closed the terminal and SQLite debugger endpoint services. (loadedPlugin.context.services.get(IdeTerminalService::class.java) as? IdeTerminalServiceImpl)?.reopen() - loadedPlugin.debuggerEndpointService()?.reopen() + loadedPlugin.context.debuggerEndpointService()?.reopen() loadedPlugin.isEnabled = true activateLoadedPlugin(loadedPlugin) return if (loadedPlugin.isEnabled) { @@ -1220,7 +1218,7 @@ class PluginManager private constructor( private fun cleanupPluginContributions(loadedPlugin: LoadedPlugin) { val pluginId = loadedPlugin.manifest.id - loadedPlugin.debuggerEndpointService()?.close() + loadedPlugin.context.debuggerEndpointService()?.close() runCatching { PluginProjectManager.getInstance().cleanupPluginTemplates(pluginId, loadedPlugins.keys - pluginId) } .onFailure { logger.error("Failed to clean project templates for: $pluginId", it) } runCatching { @@ -1243,13 +1241,9 @@ class PluginManager private constructor( }.onFailure { logger.error("Failed to cleanup templates for: $pluginId", it) } } - private fun PluginContext.closeDebuggerEndpointService() { - (services.get(DebuggerEndpointService::class.java) as? DebuggerEndpointServiceImpl)?.close() - } - /** The plugin's [DebuggerEndpointServiceImpl]. Its services outlive a disable, so it is closed instead. */ - private fun LoadedPlugin.debuggerEndpointService(): DebuggerEndpointServiceImpl? = - context.services.get(DebuggerEndpointService::class.java) as? DebuggerEndpointServiceImpl + private fun PluginContext.debuggerEndpointService(): DebuggerEndpointServiceImpl? = + services.get(DebuggerEndpointService::class.java) as? DebuggerEndpointServiceImpl sealed class CrashResult { abstract val pluginId: String @@ -1629,7 +1623,8 @@ class PluginManager private constructor( permissions = permissions, projectRootProvider = ::openProjectRoot, sourceProvider = debuggerEndpointSource::get, - // A plugin saved as disabled gets no tokens from its own initialize(); enablePlugin reopens it. + // The only close a plugin loaded as disabled needs: it stays closed through its own + // initialize() and after, until enablePlugin reopens it. startOpen = getPluginState(pluginId), ) } From d1626c99dfdd32fd8c848f064299a580e88cb280 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 22:52:10 -0800 Subject: [PATCH 29/35] ADFA-7139 Close the endpoint service only once a disable has happened disablePlugin closed the SQLite debugger endpoint service in cleanupPluginContributions, before deactivate(). When deactivate() threw, the disable failed and the plugin stayed enabled, but its service stayed closed. Enable then returned early ("already enabled") and never reopened it, so the plugin could not get endpoints until it was unloaded or the process restarted (hal-eisen-adfa, PR #2261). markDisabled now closes the service and clears isEnabled in one step, and disablePlugin calls it only after deactivate() returns. forceDisablePlugin and a failed activation, which always disable, call it too, so the service is closed exactly when a plugin stops being enabled, and the close no longer sits in cleanupPluginContributions. IdeTerminalServiceImpl has the same gap on this path (its cancelAll runs in cleanupPluginContributions before deactivate()). That code comes from stage, not this PR, and is left as is here. Test: "a disable whose deactivate throws leaves the plugin enabled and its service open" fails without this change with CancellationException: Plugin reader is disabled or unloaded. "a plugin force-disabled after crashing gets nothing, even when its deactivate throws" pins the force-disable side. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/manager/core/PluginManager.kt | 19 +++++++++---- .../core/PluginManagerDebuggerEndpointTest.kt | 27 +++++++++++++++++++ 2 files changed, 41 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 4cb3683cad..0c9917c512 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 @@ -788,8 +788,7 @@ class PluginManager private constructor( notifyLanguageContributionsChanged(plugin) }.onFailure { e -> logger.error("Failed to activate plugin: ${manifest.id}", e) - loadedPlugin.isEnabled = false - loadedPlugin.context.debuggerEndpointService()?.close() + markDisabled(loadedPlugin) savePluginState(manifest.id, false) } } @@ -1186,7 +1185,7 @@ class PluginManager private constructor( return try { cleanupPluginContributions(loadedPlugin) loadedPlugin.plugin.deactivate() - loadedPlugin.isEnabled = false + markDisabled(loadedPlugin) savePluginState(pluginId, false) lifecycleDispatcher.notifyDeactivated(pluginId) notifyLanguageContributionsChanged(loadedPlugin.plugin) @@ -1209,7 +1208,7 @@ class PluginManager private constructor( runCatching { loadedPlugin.plugin.deactivate() }.onFailure { e -> logger.error("Plugin deactivate threw during force-disable: $pluginId", e) } - loadedPlugin.isEnabled = false + markDisabled(loadedPlugin) savePluginState(pluginId, false) lifecycleDispatcher.notifyDeactivated(pluginId) notifyLanguageContributionsChanged(loadedPlugin.plugin) @@ -1218,7 +1217,6 @@ class PluginManager private constructor( private fun cleanupPluginContributions(loadedPlugin: LoadedPlugin) { val pluginId = loadedPlugin.manifest.id - loadedPlugin.context.debuggerEndpointService()?.close() runCatching { PluginProjectManager.getInstance().cleanupPluginTemplates(pluginId, loadedPlugins.keys - pluginId) } .onFailure { logger.error("Failed to clean project templates for: $pluginId", it) } runCatching { @@ -1241,6 +1239,17 @@ class PluginManager private constructor( }.onFailure { logger.error("Failed to cleanup templates for: $pluginId", it) } } + /** + * Marks [loadedPlugin] disabled and closes its SQLite debugger endpoint service in one step, so the + * service is closed exactly when the plugin stops being enabled. A disable that fails before this + * point, as when deactivate() throws, leaves the plugin enabled and its service open: enablePlugin + * returns early for an enabled plugin, so it could never reopen the service. + */ + private fun markDisabled(loadedPlugin: LoadedPlugin) { + loadedPlugin.context.debuggerEndpointService()?.close() + loadedPlugin.isEnabled = false + } + /** The plugin's [DebuggerEndpointServiceImpl]. Its services outlive a disable, so it is closed instead. */ private fun PluginContext.debuggerEndpointService(): DebuggerEndpointServiceImpl? = services.get(DebuggerEndpointService::class.java) as? DebuggerEndpointServiceImpl diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index c8535c0011..ff8da6337b 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -124,6 +124,28 @@ class PluginManagerDebuggerEndpointTest { assertThat(offMainThread { service.getEndpoints() }).containsExactly(endpoint) } + @Test + fun `a disable whose deactivate throws leaves the plugin enabled and its service open`() { + val service = load("reader", "debugger.endpoints", FailingDeactivatePlugin::class.java) + openInEditor(project) + + assertThat(pluginManager().disablePlugin("reader")).isFalse() + + assertThat(pluginManager().getLoadedPlugin("reader")).isNotNull() + assertThat(offMainThread { service.getEndpoints() }).containsExactly(endpoint) + } + + @Test + fun `a plugin force-disabled after crashing gets nothing, even when its deactivate throws`() { + val service = load("reader", "debugger.endpoints", FailingDeactivatePlugin::class.java) + openInEditor(project) + + pluginManager().forceDisablePlugin("reader") + + assertThrows(CancellationException::class.java) { offMainThread { service.getEndpoints() } } + assertThat(asked).isEmpty() + } + @Test fun `a plugin disabled after crashing gets nothing`() { val service = load("reader", "debugger.endpoints") @@ -366,6 +388,11 @@ class PluginManagerDebuggerEndpointTest { override fun activate(): Boolean = error("activate failed") } + /** Loads and activates, then deactivate() throws. */ + class FailingDeactivatePlugin : ContextKeepingPlugin() { + override fun deactivate(): Boolean = error("deactivate failed") + } + /** The editor activity's provider, as registered while it shows a project. */ private object OpenEditor : IdeEditorServiceImpl.EditorProvider { override fun getCurrentFile(): File? = null From 6793181cf502258ce0882ef7d79b296f7b5f15bd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 22:58:34 -0800 Subject: [PATCH 30/35] ADFA-7139 Close the endpoint service on every way a load fails loadPlugin closed the SQLite debugger endpoint service on its two initialize() failure paths, but not in the outer catch. When initialize() succeeded and a later step threw (registering the resource context or the service registry, building the LoadedPlugin), the service stayed open, and threads the plugin started in initialize() kept getting live tokens for a plugin the IDE reported as failed to load (hal-eisen-adfa, PR #2261). One finally now closes the service of a plugin whose context exists but which never reached loadedPlugins, whichever way loadPlugin leaves. It replaces the two closes on the initialize() paths, and covers any early return added later. Once loadedPlugins holds the plugin, disabling and unloading close the service instead; closing it there for a plugin left enabled would recreate the stuck state of the previous commit. Test: "a plugin that fails to load after its initialize succeeded is left with a service that refuses" makes the step right after initialize() throw, through the test's logger. Without this change it fails with "expected java.util.concurrent.CancellationException to be thrown, but nothing was thrown". "a plugin whose initialize returns false or throws is left with a service that refuses" still passes through the finally. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/manager/core/PluginManager.kt | 11 +++-- .../core/PluginManagerDebuggerEndpointTest.kt | 48 +++++++++++++++++-- 2 files changed, 53 insertions(+), 6 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 0c9917c512..9d5de6780c 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 @@ -593,6 +593,10 @@ class PluginManager private constructor( */ fun loadPlugin(file: File): Result { var reservedSlotsPluginId: String? = null + // The new plugin's context until loadedPlugins holds the plugin. Every way out before that, a + // failure path or a throw, leaves a plugin whose initialize() may have started threads, so the + // finally below closes its endpoint service. Once loaded, disabling or unloading closes it. + var notLoadedContext: PluginContext? = null return try { logger.debug("Loading plugin from: ${file.absolutePath}") @@ -703,13 +707,12 @@ class PluginManager private constructor( } val pluginContext = createPluginContextWithResources(manifest.id, manifest.name, classLoader, permissions, ctx) + notLoadedContext = pluginContext logger.debug("Initializing plugin: ${manifest.id}") val initResult = initializePlugin(plugin, pluginContext).getOrElse { e -> logger.error("Plugin initialization threw exception for: ${manifest.id}", e) - // The plugin may have started threads of its own in initialize(). - pluginContext.debuggerEndpointService()?.close() if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -718,7 +721,6 @@ class PluginManager private constructor( if (!initResult) { logger.warn(" plugin initialization returned false for: ${manifest.id}") - pluginContext.debuggerEndpointService()?.close() if (manifest.sidebarItems > 0) { SidebarSlotManager.releasePluginSlots(manifest.id) } @@ -745,6 +747,7 @@ class PluginManager private constructor( nativeLibraryDir = nativeLibPath?.let(::File), ) loadedPlugins[manifest.id] = loadedPlugin + notLoadedContext = null if (!isEnabled) { logger.info("Successfully loaded plugin (disabled): ${manifest.name} (${manifest.id})") @@ -760,6 +763,8 @@ class PluginManager private constructor( 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)) + } finally { + notLoadedContext?.debuggerEndpointService()?.close() } } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index ff8da6337b..e3b2d62f8a 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -65,6 +65,7 @@ class PluginManagerDebuggerEndpointTest { @After fun tearDown() { + QuietLogger.failOn = null forgetPluginManager() Environment.TEMPLATES_DIR = templatesDir ProjectManagerImpl.getInstance().projectPath = "" @@ -227,6 +228,27 @@ class PluginManagerDebuggerEndpointTest { assertThat(asked).isEmpty() } + @Test + fun `a plugin that fails to load after its initialize succeeded is left with a service that refuses`() { + openInEditor(project) + ServiceKeepingPlugin.service = null + // Logged by the step right after initialize(), which registers the plugin's resource context. + QuietLogger.failOn = "Registered resource context for plugin: keeper" + val file = + fakePlugin( + File(RuntimeEnvironment.getApplication().filesDir, "plugins/keeper.cgp"), + "keeper", + "debugger.endpoints", + ServiceKeepingPlugin::class.java, + ) + + assertThat(pluginManager().loadPlugin(file).isFailure).isTrue() + + val service = checkNotNull(ServiceKeepingPlugin.service) + assertThrows(CancellationException::class.java) { offMainThread { service.getEndpoints() } } + assertThat(asked).isEmpty() + } + @Test fun `a plugin whose activation fails is left disabled and its service refuses`() { openInEditor(project) @@ -295,7 +317,7 @@ class PluginManagerDebuggerEndpointTest { return result.get().getOrThrow() } - private fun pluginManager() = PluginManager.getInstance(RuntimeEnvironment.getApplication(), Any(), NoLogger) + private fun pluginManager() = PluginManager.getInstance(RuntimeEnvironment.getApplication(), Any(), QuietLogger) /** Forgets the singleton plugin manager: each test has an application of its own. */ private fun forgetPluginManager() { @@ -383,6 +405,19 @@ class PluginManagerDebuggerEndpointTest { } } + /** Keeps its service where the test can reach it when the load fails, then succeeds in initialize(). */ + class ServiceKeepingPlugin : ContextKeepingPlugin() { + override fun initialize(context: PluginContext): Boolean { + service = context.services.get(DebuggerEndpointService::class.java) + return super.initialize(context) + } + + companion object { + @Volatile + var service: DebuggerEndpointService? = null + } + } + /** initialize() succeeds, activate() throws. */ class FailingActivationPlugin : ContextKeepingPlugin() { override fun activate(): Boolean = error("activate failed") @@ -404,10 +439,17 @@ class PluginManagerDebuggerEndpointTest { override fun getCurrentSelection(): String? = null } - private object NoLogger : PluginLogger { + /** Logs nothing. A debug message starting with [failOn] throws, standing in for a load step that fails. */ + private object QuietLogger : PluginLogger { override val pluginId = "test" - override fun debug(message: String) = Unit + @Volatile + var failOn: String? = null + + override fun debug(message: String) { + // Not error(): in here that is this logger's own error(String). + if (failOn?.let(message::startsWith) == true) throw IllegalStateException("simulated failure at: $message") + } override fun debug( message: String, From 4c98e4e133b63394e0cb9bc3e44f5237f3758885 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 23:02:24 -0800 Subject: [PATCH 31/35] ADFA-7139 Ask the endpoint source by the canonical project path DebuggerEndpointSource.endpointsFor documents projectLocation as it appears in recent_project_table.location, which is the canonical path, but DebuggerEndpointServiceImpl passed root.absolutePath. It worked only because the app's source canonicalizes again. A source written from the KDoc, such as a test double or a direct DAO lookup, missed a project opened through a symlink, and getEndpoints() returned an empty list (hal-eisen-adfa, PR #2261). The service now passes the canonical path, falling back to the absolute path when canonicalPath throws, as the app's canonicalProjectLocation does when it stores the pairing. The KDoc says "its canonical path". The two test doubles that matched on absolutePath now match on canonicalPath. Test: "asks the source by the canonical path, as recent_project_table stores it, for a root opened through a symlink" fails without this change: expected [DebuggerEndpoint{applicationId=com.example.demo, ...}] but was []. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../services/DebuggerEndpointServiceImpl.kt | 7 +++-- .../core/PluginManagerDebuggerEndpointTest.kt | 4 +-- .../DebuggerEndpointServiceImplTest.kt | 28 +++++++++++++++++-- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index acaa5dd481..cedd14cca6 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -16,7 +16,7 @@ import java.util.concurrent.CancellationException * this module cannot reach the table itself. */ fun interface DebuggerEndpointSource { - /** Returns the endpoints stored for the project at [projectLocation], as it appears in `recent_project_table.location`. */ + /** Returns the endpoints stored for the project at [projectLocation], as it appears in `recent_project_table.location`: its canonical path. */ fun endpointsFor(projectLocation: String): List } @@ -61,9 +61,12 @@ internal class DebuggerEndpointServiceImpl( val root = projectRootProvider() ?: return emptyList() val source = sourceProvider() ?: return emptyList() + // The canonical path, as recent_project_table.location holds it, falling back to the absolute + // path as the app's pairing does, so a project opened through a symlink still finds its apps. + val location = runCatching { root.canonicalPath }.getOrElse { root.absolutePath } val endpoints = try { - source.endpointsFor(root.absolutePath) + source.endpointsFor(location) } catch (e: InterruptedException) { Thread.currentThread().interrupt() throw e diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt index e3b2d62f8a..effcc5796a 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/core/PluginManagerDebuggerEndpointTest.kt @@ -50,7 +50,7 @@ class PluginManagerDebuggerEndpointTest { private val source = DebuggerEndpointSource { location -> asked += location - if (location == project.absolutePath) listOf(endpoint) else emptyList() + if (location == project.canonicalPath) listOf(endpoint) else emptyList() } private val templatesDir = Environment.TEMPLATES_DIR @@ -105,7 +105,7 @@ class PluginManagerDebuggerEndpointTest { openInEditor(elsewhere) assertThat(offMainThread { reader.getEndpoints() }).isEmpty() - assertThat(asked).containsExactly(project.absolutePath, elsewhere.absolutePath).inOrder() + assertThat(asked).containsExactly(project.canonicalPath, elsewhere.canonicalPath).inOrder() } finally { elsewhere.deleteRecursively() } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt index b5f6e9528c..b541e6cb21 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -6,6 +6,7 @@ import com.itsaky.androidide.plugins.services.DebuggerEndpoint import org.junit.Assert.assertThrows import org.junit.Test import java.io.File +import java.nio.file.Files class DebuggerEndpointServiceImplTest { private val project = File("/data/projects/demo") @@ -14,7 +15,7 @@ class DebuggerEndpointServiceImplTest { private val source = DebuggerEndpointSource { location -> seen += location - if (location == project.absolutePath) listOf(endpoint) else emptyList() + if (location == project.canonicalPath) listOf(endpoint) else emptyList() } private fun service( @@ -27,7 +28,30 @@ class DebuggerEndpointServiceImplTest { @Test fun `returns the endpoints stored for the open project`() { assertThat(service().getEndpoints()).containsExactly(endpoint) - assertThat(seen).containsExactly(project.absolutePath) + assertThat(seen).containsExactly(project.canonicalPath) + } + + @Test + fun `asks the source by the canonical path, as recent_project_table stores it, for a root opened through a symlink`() { + val dir = Files.createTempDirectory("proj").toFile() + val links = Files.createTempDirectory("links").toFile() + val link = File(links, "proj") + try { + Files.createSymbolicLink(link.toPath(), dir.toPath()) + val stored = + DebuggerEndpointSource { location -> + seen += location + if (location == dir.canonicalPath) listOf(endpoint) else emptyList() + } + + assertThat(service(root = link, source = stored).getEndpoints()).containsExactly(endpoint) + assertThat(seen).containsExactly(dir.canonicalPath) + } finally { + // The link first, by itself: walking it would reach into the directory it points at. + link.delete() + links.delete() + dir.delete() + } } @Test From 7f717efb60ed687e7ac34367ec06ee794ea21643 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 23:25:46 -0800 Subject: [PATCH 32/35] ADFA-7139 Start the plugin system when the endpoint source can't be set up setupPluginServices resolved and installed the DebuggerEndpointSource unguarded, before setSessionLauncher, setupPluginInflationErrorHandler and loadPlugins. When resolving it threw (a binding missing in some variant, the repository or DAO failing to build) or installDebuggerEndpointSource's check() failed (a different source already installed), initializePluginSystem's catch swallowed it and no plugin loaded at all. An optional SQLite debugger source must not take down the plugin system (hal-eisen-adfa, PR #2261). - The install now runs in its own runCatching, which reports the failure to the log and Sentry, and the rest of the start carries on. - A plugin that then asks for endpoints gets IllegalStateException ("The SQLite debugger endpoints are unavailable: ...") instead of an empty list, which would read as "no apps". The service checks the source before the open project, so the failure shows on the home screen too. - initializePluginSystem takes the context and the source resolver as parameters, defaulting to the application and Koin, so a test can run the real start without IDEApplication. - DebuggerEndpointService's @throws, the changelog entry and the KDoc of installDebuggerEndpointSource and the service's sourceProvider say so. Tests: - PluginSystemStartTest runs initializePluginSystem with a source that cannot be built, and with a different source already installed. Both check that the terminal launcher and the inflation error handler are set and that a plugin loads; the first also checks that the plugin's getEndpoints() fails with the message above. Without the guard both fail at the first check: "terminal session launcher, expected not to be: null". - DebuggerEndpointServiceImplTest "without a source, as when the app could not set one up, a call fails clearly instead of reporting no apps" replaces "is empty until the app installs a source". Without the service change it fails with "expected java.lang.IllegalStateException to be thrown, but nothing was thrown". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../CredentialProtectedApplicationLoader.kt | 34 +++- .../androidide/app/PluginSystemStartTest.kt | 173 ++++++++++++++++++ docs/PLUGIN_API_CHANGELOG.md | 5 +- .../services/DebuggerEndpointService.java | 2 +- .../plugins/manager/core/PluginManager.kt | 3 +- .../services/DebuggerEndpointServiceImpl.kt | 8 +- .../DebuggerEndpointServiceImplTest.kt | 13 +- 7 files changed, 220 insertions(+), 18 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/app/PluginSystemStartTest.kt 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 a498cf2cae..bafbd3165b 100644 --- a/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt +++ b/app/src/main/java/com/itsaky/androidide/app/CredentialProtectedApplicationLoader.kt @@ -1,9 +1,11 @@ package com.itsaky.androidide.app +import android.content.Context import android.content.Intent import android.os.Handler import android.os.Looper import android.os.UserManager +import androidx.annotation.VisibleForTesting import androidx.appcompat.app.AppCompatDelegate import androidx.core.os.LocaleListCompat import androidx.work.WorkManager @@ -332,8 +334,13 @@ internal object CredentialProtectedApplicationLoader : ideLogcatReader = null } + /** [context] and [endpointSource] are parameters only so a test can start the plugin system without the app. */ + @VisibleForTesting @OptIn(DelicateCoroutinesApi::class) - private fun initializePluginSystem() { + internal fun initializePluginSystem( + context: Context = application, + endpointSource: () -> DebuggerEndpointSource = { get() }, + ) { try { logger.info("Initializing plugin system...") @@ -373,7 +380,7 @@ internal object CredentialProtectedApplicationLoader : pluginManager = PluginManager.getInstance( - context = application, + context = context, eventBus = EventBus.getDefault(), logger = pluginLogger, ) @@ -381,7 +388,7 @@ internal object CredentialProtectedApplicationLoader : pluginManager?.setLanguageContributionsListener(PluginLanguageSupport::refresh) // Set up plugin service providers - setupPluginServices() + setupPluginServices(endpointSource) setupPluginInflationErrorHandler() // Load plugins asynchronously @@ -403,18 +410,35 @@ internal object CredentialProtectedApplicationLoader : /** * Sets up the plugin service providers to integrate with AndroidIDE's actual systems. */ - private fun setupPluginServices() { + private fun setupPluginServices(endpointSource: () -> DebuggerEndpointSource) { pluginManager?.let { manager -> manager.setActivityProvider { application.foregroundActivity } setupBuildServiceProviders() setupProjectManipulationProviders() IdeLogServiceImpl.getInstance().setLogReader(LogsProvider::read) - manager.installDebuggerEndpointSource(get()) + installDebuggerEndpointSource(manager, endpointSource) IdeTerminalServiceImpl.setSessionLauncher(PluginTerminalLauncher { application.foregroundActivity }) logger.info("Plugin services configured successfully") } } + /** + * Installs where every plugin's DebuggerEndpointService reads the SQLite debugger endpoints. The + * SQLite debugger is optional, so a failure here, such as a binding that cannot be built or a + * different source already installed, is reported and the plugin system starts anyway: plugins load, + * and getEndpoints() throws IllegalStateException saying the endpoints are unavailable. + */ + private fun installDebuggerEndpointSource( + manager: PluginManager, + endpointSource: () -> DebuggerEndpointSource, + ) { + runCatching { manager.installDebuggerEndpointSource(endpointSource()) } + .onFailure { e -> + Sentry.captureException(e) + logger.error("Could not set up the SQLite debugger endpoints for plugins; plugins load without them", e) + } + } + @OptIn(DelicateCoroutinesApi::class) private fun setupBuildServiceProviders() { val buildServiceImpl = IdeBuildServiceImpl.getInstance() diff --git a/app/src/test/java/com/itsaky/androidide/app/PluginSystemStartTest.kt b/app/src/test/java/com/itsaky/androidide/app/PluginSystemStartTest.kt new file mode 100644 index 0000000000..d18b5afafc --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/app/PluginSystemStartTest.kt @@ -0,0 +1,173 @@ +package com.itsaky.androidide.app + +import android.content.pm.ApplicationInfo +import android.content.pm.PackageInfo +import android.os.Bundle +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import com.itsaky.androidide.plugins.IPlugin +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.PluginLogger +import com.itsaky.androidide.plugins.base.PluginFragmentHelper +import com.itsaky.androidide.plugins.manager.core.LoadedPlugin +import com.itsaky.androidide.plugins.manager.core.PluginManager +import com.itsaky.androidide.plugins.manager.services.DebuggerEndpointSource +import com.itsaky.androidide.plugins.manager.services.IdeTerminalServiceImpl +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import org.junit.After +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.io.File +import java.util.concurrent.atomic.AtomicReference +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream +import kotlin.concurrent.thread + +/** + * CredentialProtectedApplicationLoader's plugin start when the SQLite debugger endpoint source cannot + * be installed: the steps after it still run and plugins still load. BaseApplication backs the + * preferences the plugin manager reads; IDEApplication would start the whole app. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = BaseApplication::class) +class PluginSystemStartTest { + private val app get() = RuntimeEnvironment.getApplication() + + @Before + fun setUp() { + reset() + probePlugin(File(app.filesDir, "plugins/probe.cgp")) + } + + @After + fun tearDown() = reset() + + @Test + fun `a source that cannot be built leaves the later setup steps and plugin loading in place`() { + CredentialProtectedApplicationLoader.initializePluginSystem(app) { error("database unavailable") } + + assertLaterStepsRan() + val service = checkNotNull(awaitProbe().context.services.get(DebuggerEndpointService::class.java)) + val thrown = offMainThread { assertThrows(IllegalStateException::class.java) { service.getEndpoints() } } + assertThat(thrown).hasMessageThat().startsWith("The SQLite debugger endpoints are unavailable") + } + + @Test + fun `a different source already installed leaves the later setup steps and plugin loading in place`() { + PluginManager.getInstance(app, Any(), QuietLogger).installDebuggerEndpointSource { emptyList() } + + CredentialProtectedApplicationLoader.initializePluginSystem(app) { DebuggerEndpointSource { emptyList() } } + + assertLaterStepsRan() + awaitProbe() + } + + /** The steps that come after the endpoint source: the terminal launcher and the inflation error handler. */ + private fun assertLaterStepsRan() { + assertWithMessage("terminal session launcher").that(sessionLauncherField().get(null)).isNotNull() + assertWithMessage("plugin inflation error handler").that(PluginFragmentHelper.onPluginInflationError).isNotNull() + } + + /** Waits for the plugin loading that initializePluginSystem starts on a background coroutine. */ + private fun awaitProbe(): LoadedPlugin { + val deadline = System.currentTimeMillis() + 20_000 + while (System.currentTimeMillis() < deadline) { + PluginManager.getInstance()?.getLoadedPlugin("probe")?.let { return it } + Thread.sleep(50) + } + val error = PluginManager.getInstance()?.getLoadError("probe") + throw AssertionError("plugin probe was not loaded within 20 s (load error: $error)") + } + + /** getEndpoints refuses the main thread, where Robolectric runs the test. */ + private fun offMainThread(block: () -> T): T { + val result = AtomicReference>() + thread { result.set(runCatching(block)) }.join() + return result.get().getOrThrow() + } + + /** Forgets what a start leaves in process-wide state, so each test starts from none. */ + private fun reset() { + PluginManager::class.java + .getDeclaredField("INSTANCE") + .apply { isAccessible = true } + .set(null, null) + CredentialProtectedApplicationLoader::class.java + .getDeclaredField("pluginManager") + .apply { isAccessible = true } + .set(null, null) + sessionLauncherField().set(null, null) + PluginFragmentHelper.onPluginInflationError = null + } + + private fun sessionLauncherField() = IdeTerminalServiceImpl::class.java.getDeclaredField("sessionLauncher").apply { isAccessible = true } + + /** Writes [file] as a plugin with the debugger.endpoints permission: Robolectric can't read a manifest from an APK. */ + private fun probePlugin(file: File) { + file.parentFile?.mkdirs() + ZipOutputStream(file.outputStream()).use { it.putNextEntry(ZipEntry("classes.dex")) } + val info = + PackageInfo().apply { + packageName = "org.example.probe" + applicationInfo = + ApplicationInfo().apply { + metaData = + Bundle().apply { + putString("plugin.id", "probe") + putString("plugin.main_class", ProbePlugin::class.java.name) + putString("plugin.permissions", "debugger.endpoints") + } + } + } + shadowOf(app.packageManager).setPackageArchiveInfo(file.absolutePath, info) + } + + /** A plugin that loads and activates. Its class loader finds it through its parent, the test's. */ + class ProbePlugin : IPlugin { + override fun initialize(context: PluginContext) = true + + override fun activate() = true + + override fun deactivate() = true + + override fun dispose() = Unit + } + + private object QuietLogger : 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 + } +} diff --git a/docs/PLUGIN_API_CHANGELOG.md b/docs/PLUGIN_API_CHANGELOG.md index 1962698a22..92a949f21b 100644 --- a/docs/PLUGIN_API_CHANGELOG.md +++ b/docs/PLUGIN_API_CHANGELOG.md @@ -46,8 +46,9 @@ milestone. **[verified]** = read from the checked-in ABI dump. **[reconstructed] the new `debugger.endpoints` permission (`PluginPermission.DEBUGGER_ENDPOINTS`) and throws `SecurityException` without it. The token is the server's only credential, so a plugin holding the permission can query the databases of the open project's apps (read-only in this version; a later - version may allow writes). The call throws `IllegalStateException` on the main thread or when the database - cannot be read (an unreadable database is not reported as an empty list). Once the plugin is disabled + version may allow writes). The call throws `IllegalStateException` on the main thread, when the database + cannot be read, or when the IDE could not set up access to the endpoints at startup (neither failure is + reported as an empty list). Once the plugin is disabled or unloaded, a call throws `java.util.concurrent.CancellationException` until it is enabled again, as `IdeTerminalService` calls do. The method declares `InterruptedException`, thrown with the thread's interrupt status set again when the caller is interrupted during the read. Plugins run in Code on the diff --git a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java index 30fc641c23..69b8ab4e20 100644 --- a/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java +++ b/plugin-api/src/main/java/com/itsaky/androidide/plugins/services/DebuggerEndpointService.java @@ -32,7 +32,7 @@ public interface DebuggerEndpointService { * @throws SecurityException * if the plugin lacks the {@code debugger.endpoints} permission * @throws IllegalStateException - * if called on the main thread, or if the IDE's database could not be read. A failed read is not the same as no apps: keep what you had and try again later + * if called on the main thread, if the IDE's database could not be read, or if the IDE could not set up access to the endpoints when it started (its log says why). A failed read is not the same as no apps: keep what you had and try again later * @throws java.util.concurrent.CancellationException * if the plugin has been disabled or unloaded, until it is enabled again; also when a call already reading sees it disabled, or when the read itself is cancelled * @throws InterruptedException 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 9d5de6780c..673e1278d2 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 @@ -420,7 +420,8 @@ class PluginManager private constructor( /** * Installs where every plugin's [DebuggerEndpointService] reads the SQLite debugger endpoints apps - * reported. The app installs it before plugins load. Installing the same source again does nothing: + * reported. The app installs it before plugins load; when it cannot, plugins load anyway and their + * getEndpoints() throws IllegalStateException. Installing the same source again does nothing: * the app's start runs again when a later step of it failed (CredentialProtectedApplicationLoader.load * retries after the user unlocks). Plugins share this class loader, so a different source, which can * only be a plugin's, fails rather than replacing or blanking the source for every plugin. diff --git a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt index cedd14cca6..1175f2007a 100644 --- a/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt +++ b/plugin-manager/src/main/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImpl.kt @@ -35,7 +35,7 @@ internal class DebuggerEndpointServiceImpl( private val pluginId: String, permissions: Set, private val projectRootProvider: () -> File?, - /** Null until the app installs one. */ + /** Null when the app could not install one; [getEndpoints] then fails rather than report no apps. */ private val sourceProvider: () -> DebuggerEndpointSource?, private val isMainThread: () -> Boolean = { Looper.myLooper() == Looper.getMainLooper() }, /** False for a plugin saved as disabled: it stays closed through its own initialize() until [reopen]. */ @@ -59,8 +59,12 @@ internal class DebuggerEndpointServiceImpl( check(!isMainThread()) { "DebuggerEndpointService.getEndpoints() reads a database; call it off the main thread" } + val source = + sourceProvider() + ?: throw IllegalStateException( + "The SQLite debugger endpoints are unavailable: Code on the Go could not set up access to them when it started", + ) val root = projectRootProvider() ?: return emptyList() - val source = sourceProvider() ?: return emptyList() // The canonical path, as recent_project_table.location holds it, falling back to the absolute // path as the app's pairing does, so a project opened through a symlink still finds its apps. val location = runCatching { root.canonicalPath }.getOrElse { root.absolutePath } diff --git a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt index b541e6cb21..a384315eff 100644 --- a/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt +++ b/plugin-manager/src/test/kotlin/com/itsaky/androidide/plugins/manager/services/DebuggerEndpointServiceImplTest.kt @@ -144,14 +144,13 @@ class DebuggerEndpointServiceImplTest { } @Test - fun `is empty until the app installs a source`() { - var installed: DebuggerEndpointSource? = null - val service = DebuggerEndpointServiceImpl("p", setOf(PluginPermission.DEBUGGER_ENDPOINTS), { project }, { installed }, { false }) - assertThat(service.getEndpoints()).isEmpty() + fun `without a source, as when the app could not set one up, a call fails clearly instead of reporting no apps`() { + for (root in listOf(project, null)) { + val service = DebuggerEndpointServiceImpl("p", setOf(PluginPermission.DEBUGGER_ENDPOINTS), { root }, { null }, { false }) - installed = source - - assertThat(service.getEndpoints()).containsExactly(endpoint) + val thrown = assertThrows(IllegalStateException::class.java) { service.getEndpoints() } + assertThat(thrown).hasMessageThat().startsWith("The SQLite debugger endpoints are unavailable") + } } @Test From 33cdf50266bd70515b41fa1a5323507039bb7cd8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 23:26:04 -0800 Subject: [PATCH 33/35] ADFA-7139 Docs: name reportedEndpoints as the repository read that throws The class KDoc of DebuggerEndpointRepository still said nothing in it throws except CancellationException, but reportedEndpoints, added for the plugin API, throws on a read failure, as its own KDoc says. A caller who trusted the class contract and called it on the application scope, which has no handler, would crash the process on a database or IO failure (hal-eisen-adfa, PR #2261). The class KDoc now limits the no-throw rule to the writes, and names reportedEndpoints as the exception, to be called where a failure is handled. The method KDoc's overlong line is reflowed. KDoc only, no code change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../repositories/DebuggerEndpointRepository.kt | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index 9b585afd29..957cf64627 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -17,9 +17,11 @@ import com.itsaky.androidide.plugins.services.DebuggerEndpoint as PluginDebugger /** * Which app each project builds, and the SQLite debugger endpoint the app last reported (ADFA-7137). - * Nothing here throws except [CancellationException]: any other failure is logged and reported as - * false, because none of the callers can do anything about it, and they run on the application scope, - * which has no CoroutineExceptionHandler (an escaping exception would crash the process). + * The writes throw nothing but [CancellationException]: any other failure is logged and reported as + * false, because none of their callers can do anything about it, and they run on the application + * scope, which has no CoroutineExceptionHandler (an escaping exception would crash the process). + * [reportedEndpoints], the read behind the plugin API, is the exception: it throws on a read failure, + * so call it where a failure is handled, not on the application scope. */ class DebuggerEndpointRepository( private val dao: DebuggerEndpointDao, @@ -160,8 +162,8 @@ class DebuggerEndpointRepository( * The endpoints the apps of [projectDir] have reported, for the plugin API (ADFA-7139). Looked * up by the canonical path, as the pairing stores it; apps that have not reported yet are left * out, and so are apps that are no longer installed: their stored port and token would otherwise - * come back as live. An endpoint can still be stale when the app's process has died. Unlike the writes, a read failure is thrown: the plugin API reports it rather than - * answering "no apps". + * come back as live. An endpoint can still be stale when the app's process has died. Unlike the + * writes, a read failure is thrown: the plugin API reports it rather than answering "no apps". */ suspend fun reportedEndpoints(projectDir: File): List = dao.getByProjectLocation(projectDir.canonicalProjectLocation()).mapNotNull { row -> From da6a0e39feca61c5be786645f450c47f070f4b30 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 23:40:56 -0800 Subject: [PATCH 34/35] ADFA-7139 Check token and port before asking whether an app is installed reportedEndpoints asked isInstalled, a PackageManager.getPackageInfo binder call, before the token and port null checks. Every getEndpoints() call then cost one binder call per paired app, including apps that never reported and were dropped on the next line anyway, on a call a plugin may make repeatedly (hal-eisen-adfa, PR #2261). The null checks now come first; the result is the same. Test: "an app that has not reported is dropped without asking whether it is installed, a binder call" fails without this change: isInstalled is asked about com.example.silent as well ("unexpected (1): com.example.silent"). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../DebuggerEndpointRepository.kt | 3 +- .../DebuggerEndpointRepositoryTest.kt | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt index 957cf64627..5f5d638e98 100644 --- a/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt +++ b/app/src/main/java/com/itsaky/androidide/repositories/DebuggerEndpointRepository.kt @@ -167,9 +167,10 @@ class DebuggerEndpointRepository( */ suspend fun reportedEndpoints(projectDir: File): List = dao.getByProjectLocation(projectDir.canonicalProjectLocation()).mapNotNull { row -> - if (!isInstalled(row.applicationId)) return@mapNotNull null val token = row.token ?: return@mapNotNull null val port = row.port ?: return@mapNotNull null + // Last: a binder call per app, which an app that has not reported need not cost. + if (!isInstalled(row.applicationId)) return@mapNotNull null PluginDebuggerEndpoint(row.applicationId, port, token, row.updatedAt ?: 0L) } diff --git a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt index 4dd7ad1a7f..34104196f1 100644 --- a/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt +++ b/app/src/test/java/com/itsaky/androidide/repositories/DebuggerEndpointRepositoryTest.kt @@ -430,6 +430,38 @@ class DebuggerEndpointRepositoryTest { } } + @Test + fun `an app that has not reported is dropped without asking whether it is installed, a binder call`() = + runBlocking { + val dir = + java.nio.file.Files + .createTempDirectory("proj") + .toFile() + try { + addProject(dir.canonicalPath) + val asked = CopyOnWriteArrayList() + val counting = + DebuggerEndpointRepository( + room.debuggerEndpointDao(), + CoroutineScope(Dispatchers.IO), + clock = { 1234L }, + isInstalled = { + asked += it + true + }, + announce = {}, + ) + assertThat(counting.recordInstalled("com.example.reported", dir.canonicalPath)).isTrue() + assertThat(counting.recordInstalled("com.example.silent", dir.canonicalPath)).isTrue() + assertThat(counting.storeEndpoint("com.example.reported", endpoint)).isTrue() + + assertThat(counting.reportedEndpoints(dir).map { it.applicationId }).containsExactly("com.example.reported") + assertThat(asked).containsExactly("com.example.reported") + } finally { + dir.delete() + } + } + @Test fun `an app that is no longer installed is left out and installed ones are returned`() = runBlocking { From 3406a95f8b4622dc4ff85f99d1ad0d8ad59f10f4 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 00:12:22 -0800 Subject: [PATCH 35/35] ADFA-7139 Style: wrap an overlong line in PluginSystemStartTest ktlint max-line-length (140) flagged the sessionLauncherField line added with the plugin-start test. Formatting only, no change to the test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../java/com/itsaky/androidide/app/PluginSystemStartTest.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/com/itsaky/androidide/app/PluginSystemStartTest.kt b/app/src/test/java/com/itsaky/androidide/app/PluginSystemStartTest.kt index d18b5afafc..a93f9cea68 100644 --- a/app/src/test/java/com/itsaky/androidide/app/PluginSystemStartTest.kt +++ b/app/src/test/java/com/itsaky/androidide/app/PluginSystemStartTest.kt @@ -106,7 +106,10 @@ class PluginSystemStartTest { PluginFragmentHelper.onPluginInflationError = null } - private fun sessionLauncherField() = IdeTerminalServiceImpl::class.java.getDeclaredField("sessionLauncher").apply { isAccessible = true } + private fun sessionLauncherField() = + IdeTerminalServiceImpl::class.java + .getDeclaredField("sessionLauncher") + .apply { isAccessible = true } /** Writes [file] as a plugin with the debugger.endpoints permission: Robolectric can't read a manifest from an APK. */ private fun probePlugin(file: File) {