From 17253b46dc13edffdc5ba607b042943a44a260f4 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 26 Oct 2026 17:25:34 -0700 Subject: [PATCH 1/3] ADFA-6773: support a wildcard project name in deep links The project segment `<*>` (sent as %3C%2A%3E) now means "whichever project is open in the editor", so content such as the LLM Course plugin can link into a learner's project without knowing its name. - DeepLinkRequest: WILDCARD_PROJECT / isCurrentProject; the whole <...> namespace is reserved (parse rejects unknown selectors, buildUrl and isLinkableProjectName refuse such names, so Create link never emits one). - EditorHandlerActivity: wildcard is answered from the live project and never goes through switchToProject; same-project handling extracted into navigateWithinOpenProject. Bottom sheet collapses once the file opens. - MainActivity / resolveDeepLinkProject: no project open shows an error and records NO_PROJECT_OPEN. - Metrics: NO_PROJECT_OPEN outcome and a name/current selector. - Wildcard file-not-found message names the project searched. Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 2 + .../androidide/activities/DeepLinkActivity.kt | 10 +- .../androidide/activities/MainActivity.kt | 23 +- .../editor/EditorHandlerActivity.kt | 151 +++++++++---- .../androidide/analytics/DeepLinkMetric.kt | 23 ++ .../androidide/models/DeepLinkRequest.kt | 38 ++++ .../utils/DeepLinkProjectResolution.kt | 16 ++ .../androidide/utils/ProjectValidations.kt | 9 + .../actions/file/CreateLinkActionTest.kt | 18 ++ .../activities/DeepLinkSetupGateTest.kt | 16 ++ .../editor/WildcardDeepLinkEditorTest.kt | 213 ++++++++++++++++++ .../analytics/DeepLinkMetricTest.kt | 17 ++ .../androidide/models/DeepLinkBuildUrlTest.kt | 16 ++ .../androidide/models/DeepLinkRequestTest.kt | 68 ++++++ .../utils/ProjectValidationsTest.kt | 27 +++ resources/src/main/res/values/strings.xml | 2 + 16 files changed, 590 insertions(+), 59 deletions(-) create mode 100644 app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b858c4ac3d..b7f6f507d9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -55,6 +55,8 @@ Feature code layers as **UI → ViewModel → Repository → data source**, with `EditorHandlerActivity.onNewIntent` then branches on `projectDirPath` (set as soon as a project starts opening) rather than `workspace` so the mid-sync case still matches correctly: **same project already open** — no project-wise work, just navigate to the requested file (`applyDeepLinkFileRequest`); **a different project is open** — the existing, unmodified `confirmProjectClose()` dialog runs (it also guards against a second confirm-close request overlapping a manual close or an in-flight save, and a *third* overlapping request supersedes the second's pending callback rather than being dropped), and only once the user actually confirms does an `onDestroy()`-triggered hand-off (`PendingDeepLinkOpen`, Koin-provided) start the new project — deliberately deferred to `onDestroy()`, not fired synchronously after `finish()`, so the new `PROJECT_PATH` can't race a `singleTask` re-delivery to the dying instance; `projectDirPath` **is still blank** — this instance never actually finished initializing a project (e.g. recreated after process death with no `PROJECT_PATH` extra), so `confirmProjectClose()` would silently no-op (`contentOrNull` is null); this case reuses the same `onDestroy()`-deferred hand-off instead of showing a close dialog for a project that was never really open; **nothing was open** — `MainActivity.openProject`/`EditorHandlerActivity.postProjectInit` apply the pending file request once the cold-opened project's sync succeeds. +**A link can name "the open project" with a wildcard instead of a name (ADFA-6773).** The project segment `<*>` (`DeepLinkRequest.WILDCARD_PROJECT`, written `%3C%2A%3E` in a published link) means whichever project the editor has open, for content such as the LLM Course plugin's lessons that cannot know what the learner named their project. It is hand-authored only: `buildUrl` never emits one, and `isLinkableProjectName` refuses any `<...>` name, which is reserved for future selectors so one can never collide with a real project (`parse` returns null for an unknown one, so an older IDE reports it as an invalid link). A wildcard cannot be resolved by `lookupValidProjectByName(projectsRoot, ...)` because the open project can live outside the projects root, so `EditorHandlerActivity.onNewIntent` answers it from the live `IProjectManager.projectDirPath` (`openInCurrentProject`) and **never** through `switchToProject`: that method's `isFinishing` and blank-path branches arm a `PendingDeepLinkOpen` hand-off to a path a wildcard does not have, which would finish the editor or reopen a project the user just closed. The same-project half of `switchToProject` was extracted as `navigateWithinOpenProject` so both callers share the close-in-progress, ready and mid-sync handling. With no project open (a link reaching `MainActivity`, a finishing editor, a blank path) the user sees `msg_deeplink_no_project_open` and the metric records `NO_PROJECT_OPEN`; there is deliberately no fallback to Recents. `isDeepLinkTargetOfOpenProject` returns true for the wildcard whenever the open path is non-blank, which covers `isProjectSwitchIntent` and `BaseEditorActivity.onCreate`'s mismatch check without separate handling. `applyDeepLinkFileRequest` collapses the editor's bottom sheet once the file opens, and a wildcard file-not-found names the project searched (`PendingFileRequest.viaWildcard`, carried so the deferred mid-sync path can still say so). Security: a link no longer has to name its project, so any web page can open a named file in whatever project is open; it only displays it, on the device, and the path-traversal checks still apply. + `DeepLinkActivity`'s "is a live editor already on screen" check (`ActionContextProvider.getActivity()`) is itself a heuristic, not a guarantee: Android can still spin up a genuinely new `EditorActivityKt` instance instead of delivering to the live one via `onNewIntent`. `BaseEditorActivity.onCreate` is `EXTRA_KEY`'s only other reader on the editor side for exactly this case — it compares the deep link's requested project name against whatever project the new instance actually ends up holding (explicit `PROJECT_PATH` extra, restored `savedInstanceState`, or the process-wide `ProjectManagerImpl` singleton's last-loaded project) and, on a mismatch, bounces back to `MainActivity` with the deep link forwarded rather than silently continuing to build editor UI for the wrong project. The optional file path is attacker-controllable (a URL segment), so it's resolved through `PathTraversal.resolveWithinDirectory`'s traversal/symlink guard rather than a bare `File` join, both when opening a file in the already-open project and when matching the requested project name to a directory under `Environment.PROJECTS_DIR` (`findValidProjectByName`). diff --git a/app/src/main/java/com/itsaky/androidide/activities/DeepLinkActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/DeepLinkActivity.kt index b5ead707b0..1d2e22308b 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/DeepLinkActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/DeepLinkActivity.kt @@ -27,6 +27,7 @@ import com.itsaky.androidide.analytics.DeepLinkMetric import com.itsaky.androidide.analytics.DeepLinkOutcome import com.itsaky.androidide.analytics.IAnalyticsManager import com.itsaky.androidide.analytics.depth +import com.itsaky.androidide.analytics.selector import com.itsaky.androidide.api.ActionContextProvider import com.itsaky.androidide.models.DeepLinkRequest import com.itsaky.androidide.resources.R.string @@ -94,7 +95,14 @@ class DeepLinkActivity : Activity() { // The one place every accepted link passes through, whichever activity ends up handling it. // Paired with a terminal outcome logged wherever the request is finally resolved, so a link // that is accepted here and then quietly goes nowhere shows up as a gap between the two. - analyticsManager.trackDeepLink(DeepLinkMetric(request.depth(), DeepLinkOutcome.RECEIVED, request.projectName)) + analyticsManager.trackDeepLink( + DeepLinkMetric( + request.depth(), + DeepLinkOutcome.RECEIVED, + request.projectName.takeUnless { request.isCurrentProject }, + request.selector(), + ), + ) // ActionContextProvider tracks the live EditorHandlerActivity instance (set in its onCreate // and re-asserted in onResume, cleared in onDestroy) -- this reflects "is an editor instance diff --git a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt index 16463e09d4..c1a9c3a101 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -45,6 +45,7 @@ import com.itsaky.androidide.analytics.DeepLinkMetric import com.itsaky.androidide.analytics.DeepLinkOutcome import com.itsaky.androidide.analytics.IAnalyticsManager import com.itsaky.androidide.analytics.depth +import com.itsaky.androidide.analytics.selector import com.itsaky.androidide.app.EdgeToEdgeIDEActivity import com.itsaky.androidide.databinding.ActivityMainBinding import com.itsaky.androidide.deeplink.ConsumedRequests @@ -743,12 +744,14 @@ class MainActivity : EdgeToEdgeIDEActivity() { analyticsManager.trackDeepLink( DeepLinkMetric( request.depth(), - if (lookup is DeepLinkProjectLookup.NotFound) { - DeepLinkOutcome.PROJECT_NOT_FOUND - } else { - DeepLinkOutcome.PROJECT_UNVERIFIABLE + when (lookup) { + DeepLinkProjectLookup.NotFound -> DeepLinkOutcome.PROJECT_NOT_FOUND + DeepLinkProjectLookup.NoProjectOpen -> DeepLinkOutcome.NO_PROJECT_OPEN + else -> DeepLinkOutcome.PROJECT_UNVERIFIABLE }, - request.projectName, + // A wildcard resolves to nothing here, so there is no name to hash. + request.projectName.takeUnless { request.isCurrentProject }, + request.selector(), ), ) // Consumed even though nothing opened: the project does not exist, so retrying on @@ -756,11 +759,11 @@ class MainActivity : EdgeToEdgeIDEActivity() { // only when this request is still the current one, so a superseded slow resolve // cannot consume the newer request's slot. // - // NotFound only. An Unverifiable result -- an EACCES straight after a - // storage-permission change, an EIO on a flaky SD/FUSE mount -- says nothing about - // whether the project exists, and recording it made a momentary filesystem failure - // silence a valid link on every later delivery (ADFA-5067 review). - if (lookup is DeepLinkProjectLookup.NotFound && latestDeepLinkRequest === request) { + // NotFound and NoProjectOpen only, both definitive. An Unverifiable result -- an EACCES + // straight after a storage-permission change, an EIO on a flaky SD/FUSE mount -- says + // nothing about whether the project exists, and recording it made a momentary + // filesystem failure silence a valid link on every later delivery (ADFA-5067 review). + if (lookup !is DeepLinkProjectLookup.Unverifiable && latestDeepLinkRequest === request) { consumedDeepLinkRequests.add(request) // Tracked apart from the general consumed set so the re-forward gate in // onNewIntent can let this request through again -- see the field's docs. diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt index 90d5b3cf73..d8bc9e81ba 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt @@ -60,6 +60,7 @@ import com.itsaky.androidide.analytics.DeepLinkMetric import com.itsaky.androidide.analytics.DeepLinkOutcome import com.itsaky.androidide.analytics.IAnalyticsManager import com.itsaky.androidide.analytics.depth +import com.itsaky.androidide.analytics.selector import com.itsaky.androidide.api.ActionContextProvider import com.itsaky.androidide.app.BaseApplication import com.itsaky.androidide.app.EditorEvents @@ -2946,6 +2947,8 @@ open class EditorHandlerActivity : val isProjectSwitchIntent = ( deepLinkRequest != null && + // A wildcard is never a switch: it names the project already open, or nothing. + !deepLinkRequest.isCurrentProject && !isDeepLinkTargetOfOpenProject( IProjectManager.getInstance().projectDirPath, deepLinkRequest.projectName, @@ -3005,6 +3008,14 @@ open class EditorHandlerActivity : // out of order with this one -- mirrors MainActivity.latestDeepLinkRequest's identical race. latestDeepLinkRequest = request + // The wildcard is answered from the live project, never by a lookup under projectsRoot (the + // open project may live anywhere), and never through switchToProject, whose finishing and + // blank-path branches arm a hand-off to a project path that does not exist for a wildcard. + if (request.isCurrentProject) { + openInCurrentProject(request) + return + } + lifecycleScope.launch(Dispatchers.IO) { val lookup = resolveDeepLinkProject(projectsRoot(), request.projectName) if (lookup !is DeepLinkProjectLookup.Found) { @@ -3014,12 +3025,13 @@ open class EditorHandlerActivity : analyticsManager.trackDeepLink( DeepLinkMetric( request.depth(), - if (lookup is DeepLinkProjectLookup.NotFound) { - DeepLinkOutcome.PROJECT_NOT_FOUND - } else { - DeepLinkOutcome.PROJECT_UNVERIFIABLE + when (lookup) { + DeepLinkProjectLookup.NotFound -> DeepLinkOutcome.PROJECT_NOT_FOUND + DeepLinkProjectLookup.NoProjectOpen -> DeepLinkOutcome.NO_PROJECT_OPEN + else -> DeepLinkOutcome.PROJECT_UNVERIFIABLE }, - request.projectName, + request.projectName.takeUnless { request.isCurrentProject }, + request.selector(), ), ) // No such project, so the switch this intent announced is never going to happen. Without @@ -3064,6 +3076,28 @@ open class EditorHandlerActivity : } } + /** + * Handles a wildcard link ([DeepLinkRequest.WILDCARD_PROJECT]): shows [request]'s file in whatever + * project this editor has open. + * + * Runs on the main thread and reads the project path synchronously, so the answer is the project + * open at the moment the link arrived. If there is none -- this instance is finishing because a + * switch was confirmed, no project has loaded into it, or its views are gone -- the link has + * nothing to apply to and says so. It must not be handed to [switchToProject], which would arm a + * hand-off for it (see the call site). + */ + private fun openInCurrentProject(request: DeepLinkRequest) { + val projectPath = IProjectManager.getInstance().projectDirPath + if (isFinishing || projectPath.isBlank() || contentOrNull == null) { + analyticsManager.trackDeepLink( + DeepLinkMetric(request.depth(), DeepLinkOutcome.NO_PROJECT_OPEN, selector = request.selector()), + ) + if (!isDestroyed) flashError(getString(string.msg_deeplink_no_project_open)) + return + } + navigateWithinOpenProject(request.fileRequest) + } + override fun postProjectInit( isSuccessful: Boolean, failure: TaskExecutionResult.Failure?, @@ -3187,48 +3221,7 @@ open class EditorHandlerActivity : // "already in this project" case even mid-sync, instead of falling through to the // disruptive close-and-reopen confirmation below for a no-op. newProjectPath == currentProjectPath -> { - // Gates both applying now and draining the intent's own copy below: a request - // arriving while the project is still syncing (workspace == null) must stay armed for - // postProjectInit's deferred retry once that sync completes, or it's lost for good -- - // applyDeepLinkFileRequest resolves against files a still-in-progress sync may not - // have settled yet. - val projectReady = IProjectManager.getInstance().workspace != null - if (confirmCloseInProgress) { - // A close-confirmation dialog for a *different* project switch is already - // showing -- navigating underneath it now would just get silently discarded if - // the user goes on to confirm that close. - flashError(getString(string.msg_project_close_in_progress)) - // Drop only THIS request's own copy of the extra (the plain-switch path arms it - // on the intent before this runs). The extra can instead be an older, - // still-unapplied request for this staying project -- armed by the mid-sync - // branch below on an earlier call -- which has nothing to do with the in-flight - // close and which postProjectInit must still apply if the user cancels it; - // draining unconditionally here destroyed that older request along with this one. - val armedRequest = - IntentCompat.getParcelableExtra(intent, PendingFileRequest.EXTRA_KEY, PendingFileRequest::class.java) - if (fileRequest != null && fileRequest == armedRequest) { - drainPendingFileRequest() - } - } else if (projectReady) { - fileRequest?.let { - applyDeepLinkFileRequest(it) - // This request supersedes whatever onNewIntent's carry-forward guard just - // re-armed onto the intent from the PREVIOUS, still-unconsumed request -- - // leaving it in place would have postProjectInit silently jump back to that - // stale target once the current sync completes, discarding this newer - // navigation. - drainPendingFileRequest() - } - } else { - // Mid-sync: arm the request on the intent so postProjectInit's deferred retry - // finds it once the sync completes -- this branch is the "must stay armed" - // case the projectReady comment above describes, and without the put the - // request dies with this call while onNewIntent's carry-forward has already - // re-armed the PREVIOUS, still-unconsumed request, sending the editor to that - // stale target instead (ADFA-5067 review). The arm also supersedes that - // carried-forward value, so this branch needs no drain. - fileRequest?.let { armPendingFileRequest(intent, it) } - } + navigateWithinOpenProject(fileRequest) } else -> { @@ -3250,6 +3243,57 @@ open class EditorHandlerActivity : } } + /** + * Shows [fileRequest] in the project this editor already has open: the same-project half of + * [switchToProject], shared with wildcard links ([openInCurrentProject]), which never switch. + * Handles the three states that project can be in -- a close dialog already up, ready, or still + * syncing. + */ + private fun navigateWithinOpenProject(fileRequest: PendingFileRequest?) { + // Gates both applying now and draining the intent's own copy below: a request + // arriving while the project is still syncing (workspace == null) must stay armed for + // postProjectInit's deferred retry once that sync completes, or it's lost for good -- + // applyDeepLinkFileRequest resolves against files a still-in-progress sync may not + // have settled yet. + val projectReady = IProjectManager.getInstance().workspace != null + if (confirmCloseInProgress) { + // A close-confirmation dialog for a *different* project switch is already + // showing -- navigating underneath it now would just get silently discarded if + // the user goes on to confirm that close. + flashError(getString(string.msg_project_close_in_progress)) + // Drop only THIS request's own copy of the extra (the plain-switch path arms it + // on the intent before this runs). The extra can instead be an older, + // still-unapplied request for this staying project -- armed by the mid-sync + // branch below on an earlier call -- which has nothing to do with the in-flight + // close and which postProjectInit must still apply if the user cancels it; + // draining unconditionally here destroyed that older request along with this one. + val armedRequest = + IntentCompat.getParcelableExtra(intent, PendingFileRequest.EXTRA_KEY, PendingFileRequest::class.java) + if (fileRequest != null && fileRequest == armedRequest) { + drainPendingFileRequest() + } + } else if (projectReady) { + fileRequest?.let { + applyDeepLinkFileRequest(it) + // This request supersedes whatever onNewIntent's carry-forward guard just + // re-armed onto the intent from the PREVIOUS, still-unconsumed request -- + // leaving it in place would have postProjectInit silently jump back to that + // stale target once the current sync completes, discarding this newer + // navigation. + drainPendingFileRequest() + } + } else { + // Mid-sync: arm the request on the intent so postProjectInit's deferred retry + // finds it once the sync completes -- this branch is the "must stay armed" + // case the projectReady comment above describes, and without the put the + // request dies with this call while onNewIntent's carry-forward has already + // re-armed the PREVIOUS, still-unconsumed request, sending the editor to that + // stale target instead (ADFA-5067 review). The arm also supersedes that + // carried-forward value, so this branch needs no drain. + fileRequest?.let { armPendingFileRequest(intent, it) } + } + } + /** * Applies a deep-link file/line/column request to the *currently open* project. [request]'s * file path is attacker-controllable URL input, so it's resolved through @@ -3288,7 +3332,13 @@ open class EditorHandlerActivity : // window. Same race onNewIntent already guards against. if (isFinishing || isDestroyed) return@withContext if (file == null) { - flashError(getString(string.msg_deeplink_file_not_found, request.filePath)) + flashError( + if (request.viaWildcard) { + getString(string.msg_deeplink_file_not_found_in_project, request.filePath, projectDir.name) + } else { + getString(string.msg_deeplink_file_not_found, request.filePath) + }, + ) return@withContext } @@ -3310,6 +3360,11 @@ open class EditorHandlerActivity : // it hands back two distinct Positions -- passing one instance as both ends gives // EditorFeatures.validateRange a Range whose clamps move each other. openFileAndSelect(file, Range.pointRange(Position(line, column))) + + // The link is a request to look at this file, so get the bottom sheet out of the way. A + // course shown in that sheet used to do this itself, by reflection, even when this + // link was then rejected. + hideBottomSheet() } } } diff --git a/app/src/main/java/com/itsaky/androidide/analytics/DeepLinkMetric.kt b/app/src/main/java/com/itsaky/androidide/analytics/DeepLinkMetric.kt index 16c8bed7e0..bc987d6ce7 100644 --- a/app/src/main/java/com/itsaky/androidide/analytics/DeepLinkMetric.kt +++ b/app/src/main/java/com/itsaky/androidide/analytics/DeepLinkMetric.kt @@ -33,6 +33,15 @@ enum class DeepLinkDepth { COLUMN, } +/** How a link identified its project. */ +enum class DeepLinkSelector { + /** By name, the original form. */ + NAME, + + /** By the `<*>` wildcard: whichever project is open. */ + CURRENT, +} + /** What an incoming deep link ended up doing. */ enum class DeepLinkOutcome { /** Parsed and accepted, before anything was resolved. Pairs with a later terminal outcome. */ @@ -53,6 +62,9 @@ enum class DeepLinkOutcome { * here means storage trouble, not people mistyping project names. */ PROJECT_UNVERIFIABLE, + + /** A wildcard link arrived with no project open to resolve it against. */ + NO_PROJECT_OPEN, } /** @@ -64,7 +76,14 @@ enum class DeepLinkOutcome { class DeepLinkMetric( private val depth: DeepLinkDepth, private val outcome: DeepLinkOutcome, + /** + * The project's real name. For a wildcard link this is the name the wildcard resolved to, or + * `null` while it is unresolved -- never the wildcard token, which would hash to one value for + * every project and could not be joined with `project_opened`. + */ private val projectName: String? = null, + /** Whether the link named its project (`name`) or used the wildcard (`current`). */ + private val selector: DeepLinkSelector = DeepLinkSelector.NAME, ) : Metric { override val eventName: String = EVENT_NAME @@ -72,6 +91,7 @@ class DeepLinkMetric( Bundle().apply { putString("depth", depth.name.lowercase()) putString("outcome", outcome.name.lowercase()) + putString("selector", selector.name.lowercase()) // Hashed, never the raw name -- a project name is the user's content, and a link can // carry a file path too. Matches trackProjectOpened's project_hash, which also makes the // two joinable without either of them carrying the name off the device. @@ -84,6 +104,9 @@ class DeepLinkMetric( } } +/** See [DeepLinkSelector]. */ +fun DeepLinkRequest.selector(): DeepLinkSelector = if (isCurrentProject) DeepLinkSelector.CURRENT else DeepLinkSelector.NAME + /** How far down the optional segments this request actually reached. */ fun DeepLinkRequest.depth(): DeepLinkDepth { val file = fileRequest ?: return DeepLinkDepth.PROJECT diff --git a/app/src/main/java/com/itsaky/androidide/models/DeepLinkRequest.kt b/app/src/main/java/com/itsaky/androidide/models/DeepLinkRequest.kt index 53d312cf20..3f35191cd2 100644 --- a/app/src/main/java/com/itsaky/androidide/models/DeepLinkRequest.kt +++ b/app/src/main/java/com/itsaky/androidide/models/DeepLinkRequest.kt @@ -31,12 +31,18 @@ import java.nio.file.Paths * distinguish "segment absent from the URL" (`null`) from "segment present but not a valid positive * integer" (non-null, fails [String.toIntOrNull] or non-positive) -- the latter must be reported to the * user, the former must not. + * + * [viaWildcard] records that the link named its project with [DeepLinkRequest.WILDCARD_PROJECT]. The + * request is armed on an intent and applied later (after a sync), by which time the link itself is + * gone, and a failure to find the file in a project the author never named should say which project + * was searched. */ @Parcelize data class PendingFileRequest( val filePath: String, val lineRaw: String?, val columnRaw: String?, + val viaWildcard: Boolean = false, ) : Parcelable { companion object { const val EXTRA_KEY = "com.itsaky.androidide.PENDING_FILE_REQUEST" @@ -47,15 +53,35 @@ data class PendingFileRequest( * A parsed (but not yet resolved-to-a-path) request for * `https://appdevforall.org/device/open/project/{projectName}[/file/{filename}[/line/{n}[/column/{n}]]]` * (the `www` subdomain works identically -- see [HOSTS]). + * + * `{projectName}` may instead be the wildcard [WILDCARD_PROJECT] (`<*>`, written `%3C%2A%3E` in a + * link), meaning "whichever project is open in the editor right now". It is hand-authored only -- + * [buildUrl] never writes one -- and exists for content, such as a course shown inside the IDE, that + * cannot know the name the learner gave their project. Every other `<...>` name is reserved for + * future selectors: [parse] rejects it and [isLinkableProjectName] refuses it, so a selector added + * later can never collide with a real project's name. */ @Parcelize data class DeepLinkRequest( val projectName: String, val fileRequest: PendingFileRequest? = null, ) : Parcelable { + /** Whether this link names the open project via [WILDCARD_PROJECT] rather than by name. */ + val isCurrentProject: Boolean + get() = projectName == WILDCARD_PROJECT + companion object { const val EXTRA_KEY = "com.itsaky.androidide.DEEP_LINK_REQUEST" + /** + * The project segment meaning "the project open in the editor". The URL carries it encoded + * (`%3C%2A%3E`); [Uri.getPathSegments] hands it back decoded, which is the form compared here. + */ + const val WILDCARD_PROJECT = "<*>" + + /** The reserved `<...>` shape: see [DeepLinkRequest]'s docs. */ + private fun isSelectorShaped(name: String): Boolean = name.length >= 2 && name.startsWith('<') && name.endsWith('>') + private const val SCHEME = "https" /** @@ -192,6 +218,12 @@ data class DeepLinkRequest( } val projectName = segments[projectIdx + 1] + // Anything shaped like a selector that is not one this build knows is refused outright, so an + // older IDE reports a newer selector as an invalid link rather than as `No project named ""`. + if (isSelectorShaped(projectName) && projectName != WILDCARD_PROJECT) { + return null + } + val fileIdx = segments.indexOfFrom(projectIdx + 2, SEGMENT_FILE) val fileRequest = fileIdx.takeIf { it >= 0 }?.let { fIdx -> @@ -242,6 +274,7 @@ data class DeepLinkRequest( filePath = filePath, lineRaw = lineRaw, columnRaw = columnRaw, + viaWildcard = projectName == WILDCARD_PROJECT, ) } } @@ -264,9 +297,14 @@ data class DeepLinkRequest( * *offer* to make a link has to reach the same verdict, and cheaply. Its own copy of these * four conditions is exactly the drift that put an offer in front of the user for a project * this function refuses. + * + * A `<...>` name is refused too, [WILDCARD_PROJECT] included: those are reserved for + * selectors, so a link naming such a directory would be read back as a selector, not the + * project. */ fun isLinkableProjectName(projectName: String): Boolean = projectName.isNotEmpty() && + !isSelectorShaped(projectName) && !projectName.startsWith('.') && !projectName.contains('/') && !projectName.contains('\\') diff --git a/app/src/main/java/com/itsaky/androidide/utils/DeepLinkProjectResolution.kt b/app/src/main/java/com/itsaky/androidide/utils/DeepLinkProjectResolution.kt index c4cae1661f..a3eb88c07d 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/DeepLinkProjectResolution.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/DeepLinkProjectResolution.kt @@ -18,6 +18,7 @@ package com.itsaky.androidide.utils import android.app.Activity +import com.itsaky.androidide.models.DeepLinkRequest import com.itsaky.androidide.resources.R.string import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers @@ -41,6 +42,12 @@ sealed interface DeepLinkProjectLookup { /** No project of that name exists. Definitive, so callers may remember it. */ data object NotFound : DeepLinkProjectLookup + /** + * A wildcard link reached a path that looks projects up by name, with no open project to resolve + * it against. Definitive, like [NotFound]. + */ + data object NoProjectOpen : DeepLinkProjectLookup + /** The lookup failed for a reason unrelated to the project's existence. Remember nothing. */ data object Unverifiable : DeepLinkProjectLookup } @@ -58,6 +65,15 @@ suspend fun Activity.resolveDeepLinkProject( projectsRoot: File, projectName: String, ): DeepLinkProjectLookup { + // The wildcard has no directory under projectsRoot to find -- it means the OPEN project, which + // this lookup cannot see. A caller that gets here has no open project (a live editor resolves it + // itself), so say that, rather than reporting `No project named "<*>" was found.` + if (projectName == DeepLinkRequest.WILDCARD_PROJECT) { + log.error("Wildcard deep link reached a by-name lookup; no project is open") + flashOnMain(getString(string.msg_deeplink_no_project_open)) + return DeepLinkProjectLookup.NoProjectOpen + } + val lookup = try { lookupValidProjectByName(projectsRoot, projectName) diff --git a/app/src/main/java/com/itsaky/androidide/utils/ProjectValidations.kt b/app/src/main/java/com/itsaky/androidide/utils/ProjectValidations.kt index eebbae8644..7cbde2a6ce 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/ProjectValidations.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/ProjectValidations.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.utils +import com.itsaky.androidide.models.DeepLinkRequest import java.io.File import java.io.IOException import java.text.Normalizer @@ -139,6 +140,8 @@ internal fun projectNamesMatch( * OPEN one -- for two clones of a repo the path exists in both, so the wrong file opens silently. * So the parent has to match as well. * + * [DeepLinkRequest.WILDCARD_PROJECT] is the target of whichever project is open, as long as one is. + * * Canonicalised, since either side can reach the same directory through a symlink; a failure to * canonicalise (an unreadable parent) falls back to the absolute path rather than throwing. */ @@ -147,6 +150,12 @@ internal fun isDeepLinkTargetOfOpenProject( projectName: String, projectsRoot: File, ): Boolean { + // The wildcard names whatever is open, wherever it lives, so there is no parent to compare. + // Deliberately here and not in deepLinkTargetOfOpenProjectWithoutIo: its other caller, + // CreateLinkAction, passes a real project's name, and a directory literally called "<*>" must not + // be reported as linkable by it. + if (projectName == DeepLinkRequest.WILDCARD_PROJECT) return openProjectPath.isNotBlank() + deepLinkTargetOfOpenProjectWithoutIo(openProjectPath, projectName, projectsRoot)?.let { return it } // Deliberately NOT `deepLinkTargetOfOpenProjectOrNull(...) ?: false`, which was tried on the diff --git a/app/src/test/java/com/itsaky/androidide/actions/file/CreateLinkActionTest.kt b/app/src/test/java/com/itsaky/androidide/actions/file/CreateLinkActionTest.kt index 757819bf13..79378fc3a2 100644 --- a/app/src/test/java/com/itsaky/androidide/actions/file/CreateLinkActionTest.kt +++ b/app/src/test/java/com/itsaky/androidide/actions/file/CreateLinkActionTest.kt @@ -91,4 +91,22 @@ class CreateLinkActionTest { .endsWith("/file/Main.kt/line/1/column/1") assertThat(DeepLinkRequest.buildUrl("MyApp", "Main.kt", 0, 0)).isNull() } + + // Create link is for handing a link to another person, who has their own open project: a + // wildcard in it would open THEIR project's file, not the one the sender meant. Wildcards are + // hand-authored only. + @Test + fun `a project literally named like the wildcard gets no link`() { + val wildcardNamed = File("/storage/emulated/0/CodeOnTheGoProjects/<*>") + val relative = projectRelativePathOrNull(wildcardNamed, File(wildcardNamed, "Main.kt")) + assertThat(relative).isEqualTo("Main.kt") + assertThat(DeepLinkRequest.buildUrl(wildcardNamed.name, relative, 1, 1)).isNull() + } + + @Test + fun `a generated link never contains the wildcard`() { + val url = DeepLinkRequest.buildUrl("MyApp", "app/Main.kt", 3, 4)!! + assertThat(url).doesNotContain("%3C") + assertThat(url).doesNotContain("<") + } } diff --git a/app/src/test/java/com/itsaky/androidide/activities/DeepLinkSetupGateTest.kt b/app/src/test/java/com/itsaky/androidide/activities/DeepLinkSetupGateTest.kt index dbfedb2fa2..fa3c112f8f 100644 --- a/app/src/test/java/com/itsaky/androidide/activities/DeepLinkSetupGateTest.kt +++ b/app/src/test/java/com/itsaky/androidide/activities/DeepLinkSetupGateTest.kt @@ -64,6 +64,22 @@ class DeepLinkSetupGateTest { assertThat(activity.isFinishing).isTrue() } + // The gate runs before the link is even parsed, so a wildcard link -- which has no project name + // to look up -- must be held back by it exactly like a named one. + @Test + fun `a wildcard link arriving before setup is finished goes to the launcher chain too`() { + val intent = + Intent( + Intent.ACTION_VIEW, + Uri.parse("https://appdevforall.org/device/open/project/%3C%2A%3E/file/a.kt/line/1"), + ) + val activity = Robolectric.buildActivity(DeepLinkActivity::class.java, intent).create().get() + + val next = shadowOf(activity).nextStartedActivity + assertThat(next.component?.className).isEqualTo(SplashActivity::class.java.name) + assertThat(activity.isFinishing).isTrue() + } + @Test fun `the setup predicate is false when no toolchain is installed`() { val context = ApplicationProvider.getApplicationContext() diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt new file mode 100644 index 0000000000..e66408279b --- /dev/null +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt @@ -0,0 +1,213 @@ +/* + * This file is part of AndroidIDE. + * + * AndroidIDE is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * AndroidIDE is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with AndroidIDE. If not, see . + */ + +package com.itsaky.androidide.activities.editor + +import android.content.Intent +import androidx.core.content.IntentCompat +import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.analytics.DeepLinkMetric +import com.itsaky.androidide.analytics.IAnalyticsManager +import com.itsaky.androidide.app.BaseApplication +import com.itsaky.androidide.databinding.ActivityEditorBinding +import com.itsaky.androidide.databinding.ContentEditorBinding +import com.itsaky.androidide.deeplink.PendingDeepLinkOpen +import com.itsaky.androidide.models.DeepLinkRequest +import com.itsaky.androidide.models.PendingFileRequest +import com.itsaky.androidide.projects.IProjectManager +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkAll +import io.mockk.verify +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.koin.core.context.GlobalContext +import org.koin.core.context.GlobalContext.startKoin +import org.koin.core.context.GlobalContext.stopKoin +import org.koin.dsl.module +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * A wildcard deep link (`project/<*>`, ADFA-6773) is answered from the live project and must never + * go through `switchToProject`: its finishing and blank-path branches arm a hand-off to a project + * path that a wildcard does not have, which would finish the editor or reopen a project the user + * just closed. + * + * Same approach as [SameProjectDeepLinkMidSyncTest]: a built-but-not-created activity, with the + * project manager, binding and Koin collaborators provided directly. The ready-and-applying branch + * hits disk and the editor's views, so it is covered on a device instead. + */ +@RunWith(RobolectricTestRunner::class) +@Config(application = WildcardDeepLinkEditorTest.TestApp::class) +class WildcardDeepLinkEditorTest { + open class TestApp : BaseApplication() + + private val pending = mockk(relaxed = true) + private val analytics = mockk(relaxed = true) + private var startedKoin = false + + @Before + fun setUp() { + val binding = + module { + single { pending } + single { analytics } + } + val existing = GlobalContext.getOrNull() + if (existing == null) { + startedKoin = true + startKoin { modules(binding) } + } else { + existing.loadModules(listOf(binding), allowOverride = true) + } + } + + @After + fun tearDown() { + if (startedKoin) { + stopKoin() + startedKoin = false + } + unmockkAll() + } + + private fun projectManager( + path: String, + ready: Boolean, + ) { + mockkObject(IProjectManager.Companion) + val manager = mockk(relaxed = true) + every { manager.projectDirPath } returns path + every { manager.workspace } returns if (ready) mockk(relaxed = true) else null + every { IProjectManager.getInstance() } returns manager + } + + private fun activity(withViews: Boolean = true): EditorHandlerActivity { + val activity = Robolectric.buildActivity(EditorHandlerActivity::class.java, Intent()).get() + if (withViews) { + // `content` is a public Java field on the generated binding, which mockk cannot stub. + val activityBinding = mockk(relaxed = true) + ActivityEditorBinding::class.java + .getDeclaredField("content") + .apply { isAccessible = true } + .set(activityBinding, mockk(relaxed = true)) + activity._binding = activityBinding + } + return activity + } + + private fun EditorHandlerActivity.open(request: DeepLinkRequest) { + EditorHandlerActivity::class.java + .getDeclaredMethod("openInCurrentProject", DeepLinkRequest::class.java) + .apply { isAccessible = true } + .invoke(this, request) + } + + private val file = PendingFileRequest("lesson/A.kt", "10", "2", viaWildcard = true) + private val wildcard = DeepLinkRequest(DeepLinkRequest.WILDCARD_PROJECT, file) + + private fun assertNoProjectOpenReported() { + val metric = mutableListOf() + verify { analytics.trackDeepLink(capture(metric)) } + val bundle = metric.single().asBundle() + assertThat(bundle.getString("outcome")).isEqualTo("no_project_open") + assertThat(bundle.getString("selector")).isEqualTo("current") + } + + @Test + fun `mid-sync, the request is armed for the sync to apply`() { + projectManager("/anywhere/MyApp", ready = false) + val activity = activity() + activity.intent.putExtra(PendingFileRequest.EXTRA_KEY, PendingFileRequest("stale.kt", null, null)) + + activity.open(wildcard) + + val armed = IntentCompat.getParcelableExtra(activity.intent, PendingFileRequest.EXTRA_KEY, PendingFileRequest::class.java) + assertThat(armed).isEqualTo(file) + verify(exactly = 0) { pending.arm(any(), any()) } + assertThat(activity.isFinishing).isFalse() + } + + @Test + fun `a link with no file does nothing else to a project that is open`() { + projectManager("/anywhere/MyApp", ready = false) + val activity = activity() + + activity.open(DeepLinkRequest(DeepLinkRequest.WILDCARD_PROJECT)) + + assertThat(activity.intent.hasExtra(PendingFileRequest.EXTRA_KEY)).isFalse() + verify(exactly = 0) { pending.arm(any(), any()) } + verify(exactly = 0) { analytics.trackDeepLink(any()) } + assertThat(activity.isFinishing).isFalse() + } + + @Test + fun `a close dialog already showing refuses the request and arms nothing`() { + projectManager("/anywhere/MyApp", ready = true) + val activity = activity() + EditorHandlerActivity::class.java + .getDeclaredField("confirmCloseInProgress") + .apply { isAccessible = true } + .setBoolean(activity, true) + + activity.open(wildcard) + + assertThat(activity.intent.hasExtra(PendingFileRequest.EXTRA_KEY)).isFalse() + verify(exactly = 0) { pending.arm(any(), any()) } + assertThat(activity.isFinishing).isFalse() + } + + @Test + fun `an editor finishing because a switch was confirmed reports no project and never re-arms the hand-off`() { + projectManager("/anywhere/MyApp", ready = true) + val activity = activity() + activity.finish() + + activity.open(wildcard) + + verify(exactly = 0) { pending.arm(any(), any()) } + assertNoProjectOpenReported() + } + + @Test + fun `an editor with no project path reports no project, arms nothing and does not finish`() { + projectManager("", ready = false) + val activity = activity() + + activity.open(wildcard) + + verify(exactly = 0) { pending.arm(any(), any()) } + assertThat(activity.isFinishing).isFalse() + assertNoProjectOpenReported() + } + + @Test + fun `an editor whose views are gone reports no project`() { + projectManager("/anywhere/MyApp", ready = true) + val activity = activity(withViews = false) + + activity.open(wildcard) + + verify(exactly = 0) { pending.arm(any(), any()) } + assertNoProjectOpenReported() + } +} diff --git a/app/src/test/java/com/itsaky/androidide/analytics/DeepLinkMetricTest.kt b/app/src/test/java/com/itsaky/androidide/analytics/DeepLinkMetricTest.kt index 25bab1adcc..6cfe050fec 100644 --- a/app/src/test/java/com/itsaky/androidide/analytics/DeepLinkMetricTest.kt +++ b/app/src/test/java/com/itsaky/androidide/analytics/DeepLinkMetricTest.kt @@ -87,4 +87,21 @@ class DeepLinkMetricTest { assertThat(DeepLinkMetric(DeepLinkDepth.PROJECT, outcome).eventName).isEqualTo(DeepLinkMetric.EVENT_NAME) } } + + @Test + fun `selector defaults to name and records current for a wildcard link`() { + assertThat(DeepLinkMetric(DeepLinkDepth.PROJECT, DeepLinkOutcome.RECEIVED).asBundle().getString("selector")) + .isEqualTo("name") + + val wildcard = DeepLinkRequest(projectName = DeepLinkRequest.WILDCARD_PROJECT) + assertThat(wildcard.selector()).isEqualTo(DeepLinkSelector.CURRENT) + assertThat(request().selector()).isEqualTo(DeepLinkSelector.NAME) + + val bundle = + DeepLinkMetric(DeepLinkDepth.PROJECT, DeepLinkOutcome.NO_PROJECT_OPEN, selector = wildcard.selector()).asBundle() + assertThat(bundle.getString("selector")).isEqualTo("current") + assertThat(bundle.getString("outcome")).isEqualTo("no_project_open") + // Unresolved, so there is no project to hash -- and never the hash of the token itself. + assertThat(bundle.containsKey("project_hash")).isFalse() + } } diff --git a/app/src/test/java/com/itsaky/androidide/models/DeepLinkBuildUrlTest.kt b/app/src/test/java/com/itsaky/androidide/models/DeepLinkBuildUrlTest.kt index a08c8c197d..245fbff599 100644 --- a/app/src/test/java/com/itsaky/androidide/models/DeepLinkBuildUrlTest.kt +++ b/app/src/test/java/com/itsaky/androidide/models/DeepLinkBuildUrlTest.kt @@ -248,4 +248,20 @@ class DeepLinkBuildUrlTest { assertThat(DeepLinkRequest.buildUrl("P", "a".repeat(513 - prefixLength))).isNull() assertThat(DeepLinkRequest.buildUrl("P", "a".repeat(600))).isNull() } + + @Test + fun `a wildcard is never written, whatever the arguments`() { + assertThat(DeepLinkRequest.buildUrl(DeepLinkRequest.WILDCARD_PROJECT)).isNull() + assertThat(DeepLinkRequest.buildUrl(DeepLinkRequest.WILDCARD_PROJECT, "a.kt", 1, 1)).isNull() + } + + @Test + fun `the whole angle-bracket namespace is refused as a project name`() { + assertThat(DeepLinkRequest.buildUrl("")).isNull() + assertThat(DeepLinkRequest.isLinkableProjectName("")).isFalse() + assertThat(DeepLinkRequest.isLinkableProjectName("<*>")).isFalse() + // Only a name shaped like a selector is reserved. + assertThat(DeepLinkRequest.isLinkableProjectName("")).isTrue() + } } diff --git a/app/src/test/java/com/itsaky/androidide/models/DeepLinkRequestTest.kt b/app/src/test/java/com/itsaky/androidide/models/DeepLinkRequestTest.kt index af7ec4db8f..e55ea3d531 100644 --- a/app/src/test/java/com/itsaky/androidide/models/DeepLinkRequestTest.kt +++ b/app/src/test/java/com/itsaky/androidide/models/DeepLinkRequestTest.kt @@ -320,4 +320,72 @@ class DeepLinkRequestTest { ), ) } + + @Test + fun `the plugin's exact wildcard URL parses as the current project`() { + val request = + parse( + "https://appdevforall.org/device/open/project/%3C%2A%3E/file/" + + "src/main/kotlin/org/appdevforall/llmcourse/course/SourceLink.kt/line/11/column/5", + )!! + assertThat(request.isCurrentProject).isTrue() + assertThat(request.projectName).isEqualTo(DeepLinkRequest.WILDCARD_PROJECT) + assertThat(request.fileRequest) + .isEqualTo( + PendingFileRequest( + filePath = "src/main/kotlin/org/appdevforall/llmcourse/course/SourceLink.kt", + lineRaw = "11", + columnRaw = "5", + viaWildcard = true, + ), + ) + } + + @Test + fun `every spelling of the wildcard decodes to the same token`() { + for (segment in listOf("%3C%2A%3E", "%3C*%3E", "%3c%2a%3e", "<*>")) { + val request = parse("https://appdevforall.org/device/open/project/$segment") + assertThat(request).isEqualTo(DeepLinkRequest(projectName = DeepLinkRequest.WILDCARD_PROJECT)) + assertThat(request!!.isCurrentProject).isTrue() + } + } + + @Test + fun `a wildcard with no file is a plain project link`() { + val request = parse("https://appdevforall.org/device/open/project/%3C%2A%3E")!! + assertThat(request.isCurrentProject).isTrue() + assertThat(request.fileRequest).isNull() + } + + @Test + fun `a named project is not the current project and its file request is not wildcard`() { + val request = parse("https://appdevforall.org/device/open/project/MyApp/file/a.kt")!! + assertThat(request.isCurrentProject).isFalse() + assertThat(request.fileRequest!!.viaWildcard).isFalse() + } + + @Test + fun `an unknown selector is an invalid link`() { + for (segment in listOf("%3Cx%3E", "%3C.%2A%3E", "%3C%3E", "%3C%2A%2A%3E")) { + assertThat(parse("https://appdevforall.org/device/open/project/$segment/file/a.kt")).isNull() + } + } + + @Test + fun `a name that only starts or ends with an angle bracket is still a project name`() { + assertThat(parse("https://appdevforall.org/device/open/project/%3Cmy")!!.projectName).isEqualTo("") + } + + @Test + fun `a wildcard is not confused with a project or directory named line`() { + val request = parse("https://appdevforall.org/device/open/project/%3C%2A%3E/file/line/Notes.txt/line/3")!! + assertThat(request.isCurrentProject).isTrue() + assertThat(request.fileRequest!!.filePath).isEqualTo("line/Notes.txt") + assertThat(request.fileRequest!!.lineRaw).isEqualTo("3") + + val named = parse("https://appdevforall.org/device/open/project/line/file/a.kt/line/3")!! + assertThat(named.projectName).isEqualTo("line") + assertThat(named.isCurrentProject).isFalse() + } } diff --git a/app/src/test/java/com/itsaky/androidide/utils/ProjectValidationsTest.kt b/app/src/test/java/com/itsaky/androidide/utils/ProjectValidationsTest.kt index bd003a54cf..6638b56f5a 100644 --- a/app/src/test/java/com/itsaky/androidide/utils/ProjectValidationsTest.kt +++ b/app/src/test/java/com/itsaky/androidide/utils/ProjectValidationsTest.kt @@ -18,6 +18,7 @@ package com.itsaky.androidide.utils import com.google.common.truth.Truth.assertThat +import com.itsaky.androidide.models.DeepLinkRequest import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -237,4 +238,30 @@ class ProjectValidationsTest { // And the Boolean form collapses that to false for callers that only want a Boolean. assertThat(isDeepLinkTargetOfOpenProject(unresolvable, "MyApp", root)).isFalse() } + + @Test + fun `the wildcard targets the open project wherever it lives`() { + val root = tempFolder.newFolder("projects4") + val elsewhere = tempFolder.newFolder("elsewhere") + val wildcard = DeepLinkRequest.WILDCARD_PROJECT + + assertThat(isDeepLinkTargetOfOpenProject(File(root, "MyApp").path, wildcard, root)).isTrue() + assertThat(isDeepLinkTargetOfOpenProject(File(elsewhere, "Other").path, wildcard, root)).isTrue() + } + + @Test + fun `the wildcard targets nothing when no project is open`() { + val root = tempFolder.newFolder("projects5") + assertThat(isDeepLinkTargetOfOpenProject("", DeepLinkRequest.WILDCARD_PROJECT, root)).isFalse() + assertThat(isDeepLinkTargetOfOpenProject(" ", DeepLinkRequest.WILDCARD_PROJECT, root)).isFalse() + } + + // CreateLinkAction passes a real project's name, so a directory literally called "<*>" must not + // be reported as linkable by the disk-free check it uses. + @Test + fun `the disk-free check does not treat the wildcard as a project name`() { + val root = tempFolder.newFolder("projects6") + assertThat(deepLinkTargetOfOpenProjectWithoutIo(File(root, "<*>").path, "<*>", root)).isTrue() + assertThat(deepLinkTargetOfOpenProjectWithoutIo(File(root, "MyApp").path, "<*>", root)).isFalse() + } } diff --git a/resources/src/main/res/values/strings.xml b/resources/src/main/res/values/strings.xml index d33f9736d9..e237c531c3 100644 --- a/resources/src/main/res/values/strings.xml +++ b/resources/src/main/res/values/strings.xml @@ -148,6 +148,8 @@ Finish setting up Code on the Go, then open this link again. No project named \"%s\" was found. File \"%s\" was not found in the project. + File \"%1$s\" was not found in project \"%2$s\". + No project is open. Open a project, then try this link again. \"%s\" is not a valid line number. \"%s\" is not a valid column number. (no value given) From ab99763738d87768f7446055accd63ac8f395cfe Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 26 Oct 2026 17:42:19 -0700 Subject: [PATCH 2/3] ADFA-6773: address code-review findings - Collapse the bottom sheet only for wildcard links, not every deep link. - A wildcard arriving under an open close dialog no longer re-arms the pending switch's file request onto its own intent. - The resolver reports NoProjectOpen without flashing; MainActivity shows it. - Drop dead wildcard handling from the editor's by-name failure path. - Correct the DeepLinkMetric projectName doc. Co-Authored-By: Claude Sonnet 5.5 --- .../androidide/activities/MainActivity.kt | 3 ++ .../editor/EditorHandlerActivity.kt | 28 +++++++++++-------- .../androidide/analytics/DeepLinkMetric.kt | 7 +++-- .../utils/DeepLinkProjectResolution.kt | 10 ++++--- .../editor/WildcardDeepLinkEditorTest.kt | 23 +++++++++++++++ 5 files changed, 53 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt index c1a9c3a101..9c7067929e 100755 --- a/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/MainActivity.kt @@ -754,6 +754,9 @@ class MainActivity : EdgeToEdgeIDEActivity() { request.selector(), ), ) + if (lookup is DeepLinkProjectLookup.NoProjectOpen) { + flashError(getString(string.msg_deeplink_no_project_open)) + } // Consumed even though nothing opened: the project does not exist, so retrying on // every recreate only re-shows "No project named X was found" indefinitely. Recorded // only when this request is still the current one, so a superseded slow resolve diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt index d8bc9e81ba..f4184f5ea8 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt @@ -2960,7 +2960,13 @@ open class EditorHandlerActivity : // Preserve a not-yet-applied file-navigation request from the previous intent -- postProjectInit // reads it lazily once a sync completes, and setIntent() below would otherwise silently drop it // if this onNewIntent call is for something unrelated to that pending request. - if (!isProjectSwitchIntent && !intent.hasExtra(PendingFileRequest.EXTRA_KEY)) { + // + // Not for a wildcard arriving under an open close dialog: the intent being replaced is then the + // pending switch's, carrying the OTHER project's file request, and re-arming that onto this + // wildcard intent would apply it to the staying project if the user cancels the close. The + // staying project's own request is restored from pendingFileRequestBeforeSwitch on cancel. + val wildcardUnderCloseDialog = deepLinkRequest?.isCurrentProject == true && confirmCloseInProgress + if (!isProjectSwitchIntent && !wildcardUnderCloseDialog && !intent.hasExtra(PendingFileRequest.EXTRA_KEY)) { IntentCompat .getParcelableExtra(getIntent(), PendingFileRequest.EXTRA_KEY, PendingFileRequest::class.java) ?.let { armPendingFileRequest(intent, it) } @@ -3025,13 +3031,12 @@ open class EditorHandlerActivity : analyticsManager.trackDeepLink( DeepLinkMetric( request.depth(), - when (lookup) { - DeepLinkProjectLookup.NotFound -> DeepLinkOutcome.PROJECT_NOT_FOUND - DeepLinkProjectLookup.NoProjectOpen -> DeepLinkOutcome.NO_PROJECT_OPEN - else -> DeepLinkOutcome.PROJECT_UNVERIFIABLE + if (lookup is DeepLinkProjectLookup.NotFound) { + DeepLinkOutcome.PROJECT_NOT_FOUND + } else { + DeepLinkOutcome.PROJECT_UNVERIFIABLE }, - request.projectName.takeUnless { request.isCurrentProject }, - request.selector(), + request.projectName, ), ) // No such project, so the switch this intent announced is never going to happen. Without @@ -3361,10 +3366,11 @@ open class EditorHandlerActivity : // EditorFeatures.validateRange a Range whose clamps move each other. openFileAndSelect(file, Range.pointRange(Position(line, column))) - // The link is a request to look at this file, so get the bottom sheet out of the way. A - // course shown in that sheet used to do this itself, by reflection, even when this - // link was then rejected. - hideBottomSheet() + // A wildcard link comes from content shown IN the bottom sheet (the LLM Course plugin), which + // used to collapse the sheet itself, by reflection, even when this link was then rejected. + // Named links come from outside the editor and must leave a sheet someone is reading + // (build output, logs) alone. + if (request.viaWildcard) hideBottomSheet() } } } diff --git a/app/src/main/java/com/itsaky/androidide/analytics/DeepLinkMetric.kt b/app/src/main/java/com/itsaky/androidide/analytics/DeepLinkMetric.kt index bc987d6ce7..57e9be63fa 100644 --- a/app/src/main/java/com/itsaky/androidide/analytics/DeepLinkMetric.kt +++ b/app/src/main/java/com/itsaky/androidide/analytics/DeepLinkMetric.kt @@ -77,9 +77,10 @@ class DeepLinkMetric( private val depth: DeepLinkDepth, private val outcome: DeepLinkOutcome, /** - * The project's real name. For a wildcard link this is the name the wildcard resolved to, or - * `null` while it is unresolved -- never the wildcard token, which would hash to one value for - * every project and could not be joined with `project_opened`. + * The project's real name, or `null` when there is none to hash. Callers pass `null` for a + * wildcard link, whose name is never resolved on a path that reports a metric -- and never the + * wildcard token itself, which would hash to one value for every project and could not be joined + * with `project_opened`. */ private val projectName: String? = null, /** Whether the link named its project (`name`) or used the wildcard (`current`). */ diff --git a/app/src/main/java/com/itsaky/androidide/utils/DeepLinkProjectResolution.kt b/app/src/main/java/com/itsaky/androidide/utils/DeepLinkProjectResolution.kt index a3eb88c07d..35f4acce65 100644 --- a/app/src/main/java/com/itsaky/androidide/utils/DeepLinkProjectResolution.kt +++ b/app/src/main/java/com/itsaky/androidide/utils/DeepLinkProjectResolution.kt @@ -44,7 +44,8 @@ sealed interface DeepLinkProjectLookup { /** * A wildcard link reached a path that looks projects up by name, with no open project to resolve - * it against. Definitive, like [NotFound]. + * it against. Definitive, like [NotFound]. Unlike the other failures, nothing has been shown to + * the user: the caller reports it (`msg_deeplink_no_project_open`). */ data object NoProjectOpen : DeepLinkProjectLookup @@ -67,10 +68,11 @@ suspend fun Activity.resolveDeepLinkProject( ): DeepLinkProjectLookup { // The wildcard has no directory under projectsRoot to find -- it means the OPEN project, which // this lookup cannot see. A caller that gets here has no open project (a live editor resolves it - // itself), so say that, rather than reporting `No project named "<*>" was found.` + // itself), so say that, rather than reporting `No project named "<*>" was found.` Unlike every + // other failure here the message is left to the caller: this is an ordinary state, not a failure + // of the lookup, and the caller knows whether anything else is about to be shown. if (projectName == DeepLinkRequest.WILDCARD_PROJECT) { - log.error("Wildcard deep link reached a by-name lookup; no project is open") - flashOnMain(getString(string.msg_deeplink_no_project_open)) + log.warn("Wildcard deep link reached a by-name lookup; no project is open") return DeepLinkProjectLookup.NoProjectOpen } diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt index e66408279b..5384fa8db2 100644 --- a/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt @@ -210,4 +210,27 @@ class WildcardDeepLinkEditorTest { verify(exactly = 0) { pending.arm(any(), any()) } assertNoProjectOpenReported() } + + // A different project's switch is waiting on its close dialog, so the intent being replaced + // carries THAT project's file request. A wildcard must not re-arm it onto its own intent, or + // cancelling the close would apply the other project's file inside the staying one. + @Test + fun `a wildcard under an open close dialog does not inherit the pending switch's file request`() { + projectManager("/anywhere/MyApp", ready = true) + val activity = activity() + EditorHandlerActivity::class.java + .getDeclaredField("confirmCloseInProgress") + .apply { isAccessible = true } + .setBoolean(activity, true) + activity.intent.putExtra(PendingFileRequest.EXTRA_KEY, PendingFileRequest("other/B.kt", null, null)) + + val incoming = Intent().putExtra(DeepLinkRequest.EXTRA_KEY, wildcard) + EditorHandlerActivity::class.java + .getDeclaredMethod("onNewIntent", Intent::class.java) + .apply { isAccessible = true } + .invoke(activity, incoming) + + assertThat(activity.intent.hasExtra(PendingFileRequest.EXTRA_KEY)).isFalse() + verify(exactly = 0) { pending.arm(any(), any()) } + } } From ff3764df81a7548c7043c420b8c61b3bce58fdbc Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 26 Oct 2026 18:37:44 -0700 Subject: [PATCH 3/3] ADFA-6773: address CodeRabbit review findings - A wildcard superseding a still-resolving named switch now rolls back that switch's capture (unless a close dialog already owns it), so the next real switch takes its own capture. - applyDeepLinkFileRequest reads the project path once on the main thread and drops the result if another project took over while the file was resolved. Co-Authored-By: Claude Sonnet 5.5 --- .../editor/EditorHandlerActivity.kt | 15 +++- .../editor/WildcardDeepLinkEditorTest.kt | 71 +++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt index f4184f5ea8..cee4c67d4d 100644 --- a/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt +++ b/app/src/main/java/com/itsaky/androidide/activities/editor/EditorHandlerActivity.kt @@ -3018,6 +3018,12 @@ open class EditorHandlerActivity : // open project may live anywhere), and never through switchToProject, whose finishing and // blank-path branches arm a hand-off to a project path that does not exist for a wildcard. if (request.isCurrentProject) { + // A named switch still resolving has already captured the staying project's pending state + // (see the capture above), and this wildcard supersedes it: that lookup will now exit as + // "superseded" without restoring anything, so nothing else ever clears the capture and the + // next real switch would skip its own. Roll it back here. When a close dialog is already up + // for that switch it owns the capture, and its cancel or confirm path is what resolves it. + if (!confirmCloseInProgress) restoreIntentToStayingProject() openInCurrentProject(request) return } @@ -3310,8 +3316,12 @@ open class EditorHandlerActivity : * main thread the two call sites (`onNewIntent`, [postProjectInit]) invoke this from. */ private fun applyDeepLinkFileRequest(request: PendingFileRequest) { + // Read here, on the main thread, not inside the coroutine: callers have just decided what to + // do based on this project, and a switch landing before the IO thread gets going would + // otherwise resolve the file against a different one. + val projectDirPath = IProjectManager.getInstance().projectDirPath lifecycleScope.launch(Dispatchers.IO) { - val projectDir = File(IProjectManager.getInstance().projectDirPath) + val projectDir = File(projectDirPath) val file = try { resolveWithinDirectory(projectDir, request.filePath)?.takeIf { it.isFile } @@ -3336,6 +3346,9 @@ open class EditorHandlerActivity : // first flips true, so this continuation can otherwise still run and touch a dying // window. Same race onNewIntent already guards against. if (isFinishing || isDestroyed) return@withContext + // Another project took over while the file was being resolved: the file belongs to the + // old one, and opening it here would put it in the new project's editor. + if (IProjectManager.getInstance().projectDirPath != projectDirPath) return@withContext if (file == null) { flashError( if (request.viaWildcard) { diff --git a/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt b/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt index 5384fa8db2..df85b974d2 100644 --- a/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt +++ b/app/src/test/java/com/itsaky/androidide/activities/editor/WildcardDeepLinkEditorTest.kt @@ -233,4 +233,75 @@ class WildcardDeepLinkEditorTest { assertThat(activity.intent.hasExtra(PendingFileRequest.EXTRA_KEY)).isFalse() verify(exactly = 0) { pending.arm(any(), any()) } } + + private fun EditorHandlerActivity.field(name: String) = + EditorHandlerActivity::class.java.getDeclaredField(name).apply { isAccessible = true } + + private fun EditorHandlerActivity.captureForSwitch() { + field("capturedPendingFileRequestBeforeSwitch").setBoolean(this, true) + field("pendingFileRequestBeforeSwitch").set(this, PendingFileRequest("staying/A.kt", null, null)) + field("stayingProjectPathBeforeSwitch").set(this, "/anywhere/MyApp") + } + + private fun EditorHandlerActivity.deliver(request: DeepLinkRequest) { + EditorHandlerActivity::class.java + .getDeclaredMethod("onNewIntent", Intent::class.java) + .apply { isAccessible = true } + .invoke(this, Intent().putExtra(DeepLinkRequest.EXTRA_KEY, request)) + } + + // A named switch still resolving has captured the staying project's state. A wildcard supersedes + // it, so that lookup exits as "superseded" and restores nothing -- the wildcard has to roll the + // capture back, or the next real switch skips its own. + @Test + fun `a wildcard superseding a resolving switch clears that switch's capture`() { + projectManager("/anywhere/MyApp", ready = true) + val activity = activity() + activity.captureForSwitch() + + activity.deliver(wildcard) + + assertThat(activity.field("capturedPendingFileRequestBeforeSwitch").getBoolean(activity)).isFalse() + assertThat(activity.field("stayingProjectPathBeforeSwitch").get(activity)).isNull() + } + + @Test + fun `a wildcard leaves the capture alone while a close dialog owns it`() { + projectManager("/anywhere/MyApp", ready = true) + val activity = activity() + activity.captureForSwitch() + activity.field("confirmCloseInProgress").setBoolean(activity, true) + + activity.deliver(wildcard) + + assertThat(activity.field("capturedPendingFileRequestBeforeSwitch").getBoolean(activity)).isTrue() + assertThat(activity.field("stayingProjectPathBeforeSwitch").get(activity)).isEqualTo("/anywhere/MyApp") + } + + // The project path is read once, on the calling thread: a switch landing before the IO thread + // starts must not change which project the file is resolved against. + @Test + fun `the project path is read on the calling thread, not inside the IO coroutine`() { + val readers = java.util.concurrent.CopyOnWriteArrayList() + mockkObject(IProjectManager.Companion) + val manager = mockk(relaxed = true) + every { manager.projectDirPath } answers { + readers.add(Thread.currentThread()) + "/anywhere/MyApp" + } + every { manager.workspace } returns mockk(relaxed = true) + every { IProjectManager.getInstance() } returns manager + val activity = activity() + + EditorHandlerActivity::class.java + .getDeclaredMethod("applyDeepLinkFileRequest", PendingFileRequest::class.java) + .apply { isAccessible = true } + .invoke(activity, file) + Thread.sleep(500) + org.robolectric.shadows.ShadowLooper + .idleMainLooper() + + assertThat(readers).isNotEmpty() + assertThat(readers.toSet()).containsExactly(Thread.currentThread()) + } }