Repository navigation
Conversation
Add generic NeedsInput retry loop and update Claude model IDs
… heuristics, and support missing action parameter prompt loop
…on, and relative storage path resolution
… connection timeout
…PI and AICore, upgrade Kotlin to 2.0.21 and Hilt to 2.51.1
….1.10 and support Gemma 3n Multimodal on-device model
…th registry and dependency upgrades
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe release adds Gemma and LiteRT-LM on-device providers, hybrid fallback routing, persisted model downloads and status controls, streaming tool-call contracts, path normalization, notification loop prevention, lock-aware overlays, updated settings persistence, and Android build and release configuration changes. ChangesOn-device AI update
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant SettingsScreen
participant SettingsViewModel
participant ModelRepository
participant ModelDownloadWorker
participant HybridOnDeviceProvider
participant GemmaProvider
participant LiteRTLMProvider
SettingsScreen->>SettingsViewModel: select On-Device AI and model action
SettingsViewModel->>ModelRepository: start or control model lifecycle
ModelRepository->>ModelDownloadWorker: enqueue or resume download
ModelDownloadWorker-->>ModelRepository: persist progress or ready state
SettingsViewModel->>HybridOnDeviceProvider: use configured on-device model
HybridOnDeviceProvider->>GemmaProvider: check availability and generate
GemmaProvider-->>HybridOnDeviceProvider: return output or failure
HybridOnDeviceProvider->>LiteRTLMProvider: use fallback when needed
LiteRTLMProvider-->>HybridOnDeviceProvider: return fallback output
HybridOnDeviceProvider-->>SettingsScreen: expose backend and model status
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 14
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt (1)
191-205: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win"Ollama" is grouped under the "CLOUD AI" header.
cloudProvidersListexcludes only"On-Device AI", so"Ollama"(a local endpoint) is rendered beneath the disabled "CLOUD AI" header. Consider excluding/relocating it to avoid mislabeling a local provider as cloud.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt` around lines 191 - 205, Update the cloudProvidersList filtering in the provider dropdown to exclude both "On-Device AI" and "Ollama", keeping Ollama out of the "CLOUD AI" section and preserving the existing rendering for other cloud providers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/build.gradle`:
- Around line 133-138: Add the optional AICore uses-library declaration to the
AndroidManifest.xml application section, using the library name
com.google.android.aicore and required=false, so the GenAI Prompt API dependency
can be available without making AICore mandatory.
In
`@app/src/main/java/com/opendroid/ai/accessibility/OpenDroidAccessibilityService.kt`:
- Around line 130-135: In the service cleanup block, update the catch around
unregisterReceiver to catch only IllegalArgumentException, preserving the
existing behavior for an unregistered screenStateReceiver while allowing
unrelated exceptions to propagate. Leave serviceScope.cancel() unchanged.
In `@app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt`:
- Around line 51-68: Update resolvePath to canonicalize the resolved File and
reject paths containing traversal that resolve outside the approved
external-storage roots. Ensure /data paths and any other locations outside those
roots are rejected before file actions use the result, while preserving valid
external-storage path resolution.
In `@app/src/main/java/com/opendroid/ai/core/agent/IntentClassifier.kt`:
- Around line 88-107: Guard the fast-path in IntentClassifier’s
singleIntentPatterns check so it returns SIMPLE only when the query does not
contain compound-action indicators. Evaluate the existing compound detection
before or as part of this check, ensuring prefixes such as “set alarm and call
mom” and “open settings then turn on wifi” proceed to the compound
classification instead of matching startsWith immediately.
In `@app/src/main/java/com/opendroid/ai/core/llm/ModelFetcher.kt`:
- Around line 483-493: Extract the duplicated formatBaseUrl helper into one
shared internal utility, preserving its current trimming, scheme, and
trailing-slash behavior. Remove the private copies from ModelFetcher,
CopilotProvider, CustomOpenAIProvider, and OllamaProvider, then update their
call sites to use the shared function.
- Around line 308-321: Update the fetchModels provider selection to handle
"LiteRT-LM (On-device)" alongside "Gemma 4 (On-device)" and "On-Device AI",
reusing the existing OnDeviceModelRegistry.allModels mapping so direct LiteRT-LM
provider selection returns the available on-device models instead of an empty
list.
In
`@app/src/main/java/com/opendroid/ai/core/llm/providers/CustomOpenAIProvider.kt`:
- Around line 106-116: Extract the duplicated formatBaseUrl logic from
CustomOpenAIProvider, CopilotProvider, OllamaProvider, and ModelFetcher into one
shared utility function. Update each caller to use the shared function while
preserving its existing url and defaultUrl arguments, including ModelFetcher’s
empty-string default.
- Around line 106-116: Update formatBaseUrl so scheme-less endpoints default to
https:// instead of http://, preserving explicit http:// and https:// schemes
and the existing trimming and trailing-slash handling.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`:
- Around line 87-117: The downloadModel function currently writes a JSON
manifest to the model artifact path, causing isModelDownloaded and
checkModelReady to report readiness without a real .litertlm file. Store the
manifest or download marker at a separate path, and ensure those readiness
checks only recognize an existing valid .litertlm artifact before advertising
the model as available.
- Around line 305-330: Update the reflection flow in the LiteRT-LM provider to
target the SDK’s 0.14.0 Engine and EngineConfig classes and their corresponding
creation, generation, and cleanup methods instead of LlmInferenceOptions and
LlmInference. Preserve the existing modelPath, maxTokens, temperature, prompt,
and error-handling behavior while using the actual LiteRT-LM API surface;
alternatively, change the dependency only if the LlmInference API is
intentionally required.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/OllamaProvider.kt`:
- Around line 105-114: Extract the duplicated formatBaseUrl logic from
OllamaProvider into a shared top-level or extension utility, then update
OllamaProvider, CopilotProvider, CustomOpenAIProvider, and ModelFetcher to reuse
it. Preserve the existing trimming, default URL, scheme normalization, and
trailing-slash removal behavior.
In `@app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt`:
- Around line 641-691: Update the LiteRT model rows in the liteRTModels
rendering block so modelStatus is initialized from and refreshed using the
actual download state, such as LiteRTLMProvider.isModelDownloaded or the
established on-disk check, allowing the "Ready" state and color branch to
reflect reality. Wrap each spec row with key(spec.id) so remember state remains
associated with the correct model when the list changes.
- Line 176: Replace both `Divider` usages in `SettingsScreen` with
`HorizontalDivider`, preserving the existing `color` and `thickness` parameters
at each location. Update the corresponding Material 3 import if needed.
In `@RELEASE.md`:
- Line 12: Update the toolchain version entries in RELEASE.md, including the
entries around the “Toolchain Upgrades” note, to consistently match
build.gradle: Kotlin Gradle plugin 2.4.0, Hilt 2.58, and Room 2.8.4. Replace all
conflicting or stale Kotlin/Hilt/Room versions with this single accurate set.
---
Outside diff comments:
In `@app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt`:
- Around line 191-205: Update the cloudProvidersList filtering in the provider
dropdown to exclude both "On-Device AI" and "Ollama", keeping Ollama out of the
"CLOUD AI" section and preserving the existing rendering for other cloud
providers.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: d018a777-d627-4084-a7c2-e3b916eee983
⛔ Files ignored due to path filters (1)
.kotlin/errors/errors-1783797583544.logis excluded by!**/*.log
📒 Files selected for processing (23)
RELEASE.mdapp/build.gradleapp/src/main/java/com/opendroid/ai/accessibility/OpenDroidAccessibilityService.ktapp/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.ktapp/src/main/java/com/opendroid/ai/core/agent/AutoReplyEngine.ktapp/src/main/java/com/opendroid/ai/core/agent/IntentClassifier.ktapp/src/main/java/com/opendroid/ai/core/llm/LLMProvider.ktapp/src/main/java/com/opendroid/ai/core/llm/LLMProviderFactory.ktapp/src/main/java/com/opendroid/ai/core/llm/ModelFetcher.ktapp/src/main/java/com/opendroid/ai/core/llm/OnDeviceModelRegistry.ktapp/src/main/java/com/opendroid/ai/core/llm/providers/CopilotProvider.ktapp/src/main/java/com/opendroid/ai/core/llm/providers/CustomOpenAIProvider.ktapp/src/main/java/com/opendroid/ai/core/llm/providers/GemmaProvider.ktapp/src/main/java/com/opendroid/ai/core/llm/providers/HybridOnDeviceProvider.ktapp/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.ktapp/src/main/java/com/opendroid/ai/core/llm/providers/OllamaProvider.ktapp/src/main/java/com/opendroid/ai/core/service/OpenDroidNotificationListener.ktapp/src/main/java/com/opendroid/ai/core/service/OpenDroidService.ktapp/src/main/java/com/opendroid/ai/ui/screens/ChatScreen.ktapp/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.ktapp/src/main/java/com/opendroid/ai/ui/viewmodel/SettingsViewModel.ktbuild.gradlegradle/wrapper/gradle-wrapper.properties
💤 Files with no reviewable changes (1)
- app/src/main/java/com/opendroid/ai/core/service/OpenDroidService.kt
| // Google ML Kit GenAI Prompt API (Android AI Core) | ||
| implementation 'com.google.mlkit:genai-prompt:1.0.0-beta2' | ||
|
|
||
| // LiteRT-LM: On-device LLM inference fallback (no AI Core dependency) | ||
| implementation 'com.google.ai.edge.litertlm:litertlm-android:0.14.0' | ||
|
|
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -n 'com.google.android.aicore' app/src/main/AndroidManifest.xmlRepository: JMAN730/opendroid
Length of output: 155
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Manifest files:\n'
git ls-files '*AndroidManifest.xml' '*Manifest.xml' | sed 's#^`#-` #'
printf '\nAICore references anywhere in repo:\n'
rg -n 'com\.google\.android\.aicore|uses-library' -S . --glob '*AndroidManifest.xml' --glob '*Manifest.xml' || true
printf '\napp/src/main/AndroidManifest.xml excerpt:\n'
if [ -f app/src/main/AndroidManifest.xml ]; then
nl -ba app/src/main/AndroidManifest.xml | sed -n '1,220p'
fiRepository: JMAN730/opendroid
Length of output: 327
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'app/src/main/AndroidManifest.xml:\n'
if [ -f app/src/main/AndroidManifest.xml ]; then
cat -n app/src/main/AndroidManifest.xml | sed -n '1,240p'
fiRepository: JMAN730/opendroid
Length of output: 7376
Add the AICore uses-library entry to the manifest
com.google.mlkit:genai-prompt needs com.google.android.aicore declared in AndroidManifest.xml; without it, the GenAI path won’t be available. Add <uses-library android:name="com.google.android.aicore" android:required="false" /> under <application>.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/build.gradle` around lines 133 - 138, Add the optional AICore
uses-library declaration to the AndroidManifest.xml application section, using
the library name com.google.android.aicore and required=false, so the GenAI
Prompt API dependency can be available without making AICore mandatory.
| try { | ||
| unregisterReceiver(screenStateReceiver) | ||
| } catch (e: Exception) { | ||
| // Receiver may not have been registered | ||
| } | ||
| serviceScope.cancel() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Catch the specific exception instead of generic Exception.
unregisterReceiver only throws IllegalArgumentException when the receiver wasn't registered; catching and swallowing generic Exception hides unrelated failures.
🔧 Proposed fix
try {
unregisterReceiver(screenStateReceiver)
- } catch (e: Exception) {
+ } catch (e: IllegalArgumentException) {
// Receiver may not have been registered
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try { | |
| unregisterReceiver(screenStateReceiver) | |
| } catch (e: Exception) { | |
| // Receiver may not have been registered | |
| } | |
| serviceScope.cancel() | |
| try { | |
| unregisterReceiver(screenStateReceiver) | |
| } catch (e: IllegalArgumentException) { | |
| // Receiver may not have been registered | |
| } | |
| serviceScope.cancel() |
🧰 Tools
🪛 detekt (1.23.8)
[warning] 132-132: The caught exception is too generic. Prefer catching specific exceptions to the case that is currently handled.
(detekt.exceptions.TooGenericExceptionCaught)
[warning] 132-132: The caught exception is swallowed. The original exception could be lost.
(detekt.exceptions.SwallowedException)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@app/src/main/java/com/opendroid/ai/accessibility/OpenDroidAccessibilityService.kt`
around lines 130 - 135, In the service cleanup block, update the catch around
unregisterReceiver to catch only IllegalArgumentException, preserving the
existing behavior for an unregistered screenStateReceiver while allowing
unrelated exceptions to propagate. Leave serviceScope.cancel() unchanged.
Source: Linters/SAST tools
|
|
||
| private fun resolvePath(pathStr: String): File { | ||
| val trimmed = pathStr.trim() | ||
| if (trimmed.startsWith("/") || trimmed.startsWith("content://")) { | ||
| val externalStoragePath = Environment.getExternalStorageDirectory().absolutePath | ||
| if (trimmed.startsWith(externalStoragePath) || | ||
| trimmed.startsWith("/sdcard") || | ||
| trimmed.startsWith("/storage") || | ||
| trimmed.startsWith("/data") | ||
| ) { | ||
| return File(trimmed) | ||
| } | ||
| val relativePath = trimmed.removePrefix("/") | ||
| return File(Environment.getExternalStorageDirectory(), relativePath) | ||
| } else { | ||
| return File(Environment.getExternalStorageDirectory(), trimmed) | ||
| } | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Locate where LLM/tool-call output populates "path"/"filePath"/"sourcePath"/"destPath" params
rg -nP -C4 '"path"\s*(=|:)|"filePath"\s*(=|:)|"sourcePath"\s*(=|:)|"destPath"\s*(=|:)' --type=ktRepository: JMAN730/opendroid
Length of output: 182
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find the target file and nearby call sites
git ls-files | rg '^app/src/main/java/.+AdvancedControlActions\.kt$|^app/src/main/java/.+IntentClassifier\.kt$|^app/src/main/java/.+Notification.*\.kt$|^app/src/main/java/.+Action.*\.kt$'
echo '--- AdvancedControlActions.kt outline ---'
ast-grep outline app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt --view expanded || true
echo '--- Relevant lines ---'
sed -n '1,140p' app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt
echo '--- Search for path parameter population ---'
rg -n -C 3 --glob '*.kt' 'path|filePath|sourcePath|destPath' app/src/main/java
echo '--- Search for content:// handling ---'
rg -n -C 3 --glob '*.kt' 'content://' app/src/main/javaRepository: JMAN730/opendroid
Length of output: 41446
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the action implementation around resolvePath and its callers
sed -n '1,260p' app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt
echo '--- line numbers around resolvePath ---'
nl -ba app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt | sed -n '45,95p'
echo '--- usages of resolvePath ---'
rg -n -C 2 'resolvePath\(' app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt
echo '--- internal storage / permission related code ---'
rg -n -C 3 'MANAGE_EXTERNAL_STORAGE|READ_EXTERNAL_STORAGE|WRITE_EXTERNAL_STORAGE|Environment\.getExternalStorageDirectory|/data/data|shared_prefs|databases' app/src/main/java
echo '--- path-like parameters in prompt/tooling code ---'
rg -n -C 3 --glob '*.kt' 'path|filePath|sourcePath|destPath' app/src/main/javaRepository: JMAN730/opendroid
Length of output: 12457
Constrain resolvePath to approved storage roots. filePath/sourcePath/destPath can still resolve to /data/data/com.opendroid.ai/... or escape via .., so these file actions can read/write/delete the app’s private storage without any extra permission check. Reject anything whose canonical path leaves the allowed roots.
🧰 Tools
🪛 detekt (1.23.8)
[warning] 56-59: This condition is too complex (4). Defined complexity threshold for conditions is set to '4'
(detekt.complexity.ComplexCondition)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt` around
lines 51 - 68, Update resolvePath to canonicalize the resolved File and reject
paths containing traversal that resolve outside the approved external-storage
roots. Ensure /data paths and any other locations outside those roots are
rejected before file actions use the result, while preserving valid
external-storage path resolution.
| // ── Fast-path: known single-intent patterns that happen to contain | ||
| // multiple action keywords (e.g. "set" + "brightness"). | ||
| // These must be classified as SIMPLE so the AliasResolver handles them. | ||
| val singleIntentPatterns = listOf( | ||
| "set brightness", "set volume", "set alarm", "set timer", "set reminder", | ||
| "turn on flashlight", "turn off flashlight", "turn on wifi", "turn off wifi", | ||
| "turn on bluetooth", "turn off bluetooth", "turn on hotspot", "turn off hotspot", | ||
| "turn on dnd", "turn off dnd", "turn on torch", "turn off torch", | ||
| "take screenshot", "take a screenshot", "take ss", | ||
| "enable wifi", "disable wifi", "enable bluetooth", "disable bluetooth", | ||
| "enable hotspot", "disable hotspot", "enable dnd", "disable dnd", | ||
| "toggle flashlight", "toggle wifi", "toggle bluetooth", "toggle hotspot", "toggle dnd", | ||
| "open settings", "open camera", "lock screen", "lock phone", | ||
| "play music", "pause music", "resume music", "next song", "previous song", | ||
| "mute phone", "unmute phone", "set wallpaper" | ||
| ) | ||
| if (singleIntentPatterns.any { lowercaseQuery.startsWith(it) || lowercaseQuery == it }) { | ||
| return QueryComplexity.SIMPLE | ||
| } | ||
|
|
There was a problem hiding this comment.
🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win
Fast-path bypasses compound-query detection, misclassifying multi-step commands as SIMPLE.
The singleIntentPatterns check runs before the compound-indicator check at Line 108, and uses startsWith. Any compound query that happens to begin with one of these prefixes (e.g. "set alarm and call mom", "lock screen and open camera", "open settings and turn on wifi") will match startsWith(...) and return SIMPLE immediately — even though it clearly contains a second action joined by "and"/"then", which the very next block (Lines 108-129) is designed to catch.
This has real downstream consequences: AgentLoop.kt uses complexity != SIMPLE to decide whether to skip alias shortcuts and route to the planner; misclassifying as SIMPLE causes AliasResolver.resolve(query) to fire and execute only the first action via executeAliasDirect, then return@launch — silently dropping the second action. LLMProviderFactory.kt also maps SIMPLE to maxSteps = 1, further constraining any fallback planning to a single step.
🐛 Proposed fix — guard the fast-path with the compound check
fun classifyComplexity(query: String): QueryComplexity {
val lowercaseQuery = query.lowercase()
- // ── Fast-path: known single-intent patterns that happen to contain
- // multiple action keywords (e.g. "set" + "brightness").
- // These must be classified as SIMPLE so the AliasResolver handles them.
- val singleIntentPatterns = listOf(
- "set brightness", "set volume", "set alarm", "set timer", "set reminder",
- "turn on flashlight", "turn off flashlight", "turn on wifi", "turn off wifi",
- "turn on bluetooth", "turn off bluetooth", "turn on hotspot", "turn off hotspot",
- "turn on dnd", "turn off dnd", "turn on torch", "turn off torch",
- "take screenshot", "take a screenshot", "take ss",
- "enable wifi", "disable wifi", "enable bluetooth", "disable bluetooth",
- "enable hotspot", "disable hotspot", "enable dnd", "disable dnd",
- "toggle flashlight", "toggle wifi", "toggle bluetooth", "toggle hotspot", "toggle dnd",
- "open settings", "open camera", "lock screen", "lock phone",
- "play music", "pause music", "resume music", "next song", "previous song",
- "mute phone", "unmute phone", "set wallpaper"
- )
- if (singleIntentPatterns.any { lowercaseQuery.startsWith(it) || lowercaseQuery == it }) {
- return QueryComplexity.SIMPLE
- }
-
// Check for compound indicators FIRST — these always indicate multi-step tasks
val compoundIndicators = listOf(
" and then ", " then ", " after that ", " after ",
" also ", " plus ", "and send", "and message",
"and call", "and tell", "and notify", "and text",
"and book", "and set", "and create", "and open",
"then send", "then call", "then message",
"then open", "then set", "then play",
"and also ", "followed by", "afterwards"
)
val isCompound = compoundIndicators.any { lowercaseQuery.contains(it) }
// Additionally check for " and " with action verbs on both sides
val andWithActions = hasActionsAroundAnd(lowercaseQuery)
+ // Fast-path: known single-intent patterns that happen to contain multiple
+ // action keywords (e.g. "set" + "brightness"). Only applies when no
+ // compound indicator was found, so trailing "and <action>" clauses aren't dropped.
+ if (!isCompound && !andWithActions) {
+ val singleIntentPatterns = listOf(
+ "set brightness", "set volume", "set alarm", "set timer", "set reminder",
+ "turn on flashlight", "turn off flashlight", "turn on wifi", "turn off wifi",
+ "turn on bluetooth", "turn off bluetooth", "turn on hotspot", "turn off hotspot",
+ "turn on dnd", "turn off dnd", "turn on torch", "turn off torch",
+ "take screenshot", "take a screenshot", "take ss",
+ "enable wifi", "disable wifi", "enable bluetooth", "disable bluetooth",
+ "enable hotspot", "disable hotspot", "enable dnd", "disable dnd",
+ "toggle flashlight", "toggle wifi", "toggle bluetooth", "toggle hotspot", "toggle dnd",
+ "open settings", "open camera", "lock screen", "lock phone",
+ "play music", "pause music", "resume music", "next song", "previous song",
+ "mute phone", "unmute phone", "set wallpaper"
+ )
+ if (singleIntentPatterns.any { lowercaseQuery.startsWith(it) || lowercaseQuery == it }) {
+ return QueryComplexity.SIMPLE
+ }
+ }
+
if (isCompound || andWithActions) {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // ── Fast-path: known single-intent patterns that happen to contain | |
| // multiple action keywords (e.g. "set" + "brightness"). | |
| // These must be classified as SIMPLE so the AliasResolver handles them. | |
| val singleIntentPatterns = listOf( | |
| "set brightness", "set volume", "set alarm", "set timer", "set reminder", | |
| "turn on flashlight", "turn off flashlight", "turn on wifi", "turn off wifi", | |
| "turn on bluetooth", "turn off bluetooth", "turn on hotspot", "turn off hotspot", | |
| "turn on dnd", "turn off dnd", "turn on torch", "turn off torch", | |
| "take screenshot", "take a screenshot", "take ss", | |
| "enable wifi", "disable wifi", "enable bluetooth", "disable bluetooth", | |
| "enable hotspot", "disable hotspot", "enable dnd", "disable dnd", | |
| "toggle flashlight", "toggle wifi", "toggle bluetooth", "toggle hotspot", "toggle dnd", | |
| "open settings", "open camera", "lock screen", "lock phone", | |
| "play music", "pause music", "resume music", "next song", "previous song", | |
| "mute phone", "unmute phone", "set wallpaper" | |
| ) | |
| if (singleIntentPatterns.any { lowercaseQuery.startsWith(it) || lowercaseQuery == it }) { | |
| return QueryComplexity.SIMPLE | |
| } | |
| // Check for compound indicators FIRST — these always indicate multi-step tasks | |
| val compoundIndicators = listOf( | |
| " and then ", " then ", " after that ", " after ", | |
| " also ", " plus ", "and send", "and message", | |
| "and call", "and tell", "and notify", "and text", | |
| "and book", "and set", "and create", "and open", | |
| "then send", "then call", "then message", | |
| "then open", "then set", "then play", | |
| "and also ", "followed by", "afterwards" | |
| ) | |
| val isCompound = compoundIndicators.any { lowercaseQuery.contains(it) } | |
| // Additionally check for " and " with action verbs on both sides | |
| val andWithActions = hasActionsAroundAnd(lowercaseQuery) | |
| // Fast-path: known single-intent patterns that happen to contain multiple | |
| // action keywords (e.g. "set" + "brightness"). Only applies when no | |
| // compound indicator was found, so trailing "and <action>" clauses aren't dropped. | |
| if (!isCompound && !andWithActions) { | |
| val singleIntentPatterns = listOf( | |
| "set brightness", "set volume", "set alarm", "set timer", "set reminder", | |
| "turn on flashlight", "turn off flashlight", "turn on wifi", "turn off wifi", | |
| "turn on bluetooth", "turn off bluetooth", "turn on hotspot", "turn off hotspot", | |
| "turn on dnd", "turn off dnd", "turn on torch", "turn off torch", | |
| "take screenshot", "take a screenshot", "take ss", | |
| "enable wifi", "disable wifi", "enable bluetooth", "disable bluetooth", | |
| "enable hotspot", "disable hotspot", "enable dnd", "disable dnd", | |
| "toggle flashlight", "toggle wifi", "toggle bluetooth", "toggle hotspot", "toggle dnd", | |
| "open settings", "open camera", "lock screen", "lock phone", | |
| "play music", "pause music", "resume music", "next song", "previous song", | |
| "mute phone", "unmute phone", "set wallpaper" | |
| ) | |
| if (singleIntentPatterns.any { lowercaseQuery.startsWith(it) || lowercaseQuery == it }) { | |
| return QueryComplexity.SIMPLE | |
| } | |
| } | |
| if (isCompound || andWithActions) { |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/agent/IntentClassifier.kt` around
lines 88 - 107, Guard the fast-path in IntentClassifier’s singleIntentPatterns
check so it returns SIMPLE only when the query does not contain compound-action
indicators. Evaluate the existing compound detection before or as part of this
check, ensuring prefixes such as “set alarm and call mom” and “open settings
then turn on wifi” proceed to the compound classification instead of matching
startsWith immediately.
| "Gemma 4 (On-device)", | ||
| "On-Device AI" -> { | ||
| // Use the centralized registry — future models are | ||
| // added there and automatically appear here. | ||
| Result.success(OnDeviceModelRegistry.allModels.map { spec -> | ||
| AIModel( | ||
| id = spec.id, | ||
| displayName = spec.displayName, | ||
| provider = provider, | ||
| isFree = true, | ||
| isRecommended = spec.isRecommended | ||
| ) | ||
| }) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
fetchModels doesn't handle "LiteRT-LM (On-device)", unlike getProviderByName.
LLMProviderFactory.getProviderByName resolves "LiteRT-LM (On-device)" directly to liteRTLMProvider, but this switch only handles "Gemma 4 (On-device)"/"On-Device AI"; selecting the LiteRT-LM provider directly falls through to else -> Result.success(emptyList()), leaving the model list empty in Settings.
🐛 Suggested fix
"Gemma 4 (On-device)",
"On-Device AI" -> {
// Use the centralized registry — future models are
// added there and automatically appear here.
Result.success(OnDeviceModelRegistry.allModels.map { spec ->
AIModel(
id = spec.id,
displayName = spec.displayName,
provider = provider,
isFree = true,
isRecommended = spec.isRecommended
)
})
}
+ "LiteRT-LM (On-device)" -> {
+ Result.success(OnDeviceModelRegistry.liteRTOnly.map { spec ->
+ AIModel(
+ id = spec.id,
+ displayName = spec.displayName,
+ provider = provider,
+ isFree = true,
+ isRecommended = spec.isRecommended
+ )
+ })
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "Gemma 4 (On-device)", | |
| "On-Device AI" -> { | |
| // Use the centralized registry — future models are | |
| // added there and automatically appear here. | |
| Result.success(OnDeviceModelRegistry.allModels.map { spec -> | |
| AIModel( | |
| id = spec.id, | |
| displayName = spec.displayName, | |
| provider = provider, | |
| isFree = true, | |
| isRecommended = spec.isRecommended | |
| ) | |
| }) | |
| } | |
| "Gemma 4 (On-device)", | |
| "On-Device AI" -> { | |
| // Use the centralized registry — future models are | |
| // added there and automatically appear here. | |
| Result.success(OnDeviceModelRegistry.allModels.map { spec -> | |
| AIModel( | |
| id = spec.id, | |
| displayName = spec.displayName, | |
| provider = provider, | |
| isFree = true, | |
| isRecommended = spec.isRecommended | |
| ) | |
| }) | |
| } | |
| "LiteRT-LM (On-device)" -> { | |
| Result.success(OnDeviceModelRegistry.liteRTOnly.map { spec -> | |
| AIModel( | |
| id = spec.id, | |
| displayName = spec.displayName, | |
| provider = provider, | |
| isFree = true, | |
| isRecommended = spec.isRecommended | |
| ) | |
| }) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/ModelFetcher.kt` around lines 308
- 321, Update the fetchModels provider selection to handle "LiteRT-LM
(On-device)" alongside "Gemma 4 (On-device)" and "On-Device AI", reusing the
existing OnDeviceModelRegistry.allModels mapping so direct LiteRT-LM provider
selection returns the available on-device models instead of an empty list.
| private fun formatBaseUrl(url: String, defaultUrl: String): String { | ||
| val trimmed = url.trim() | ||
| val target = if (trimmed.isEmpty()) defaultUrl else trimmed | ||
| val withScheme = if (!target.startsWith("http://") && !target.startsWith("https://")) { | ||
| "http://$target" | ||
| } else { | ||
| target | ||
| } | ||
| return if (withScheme.endsWith("/")) withScheme.dropLast(1) else withScheme | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Extract the duplicated formatBaseUrl into a shared utility.
The exact same helper now appears in OllamaProvider, CopilotProvider, CustomOpenAIProvider, and ModelFetcher (per graph evidence). Four independent copies will drift over time. Consider hoisting it to a single top-level/extension function reused by all providers.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/OllamaProvider.kt`
around lines 105 - 114, Extract the duplicated formatBaseUrl logic from
OllamaProvider into a shared top-level or extension utility, then update
OllamaProvider, CopilotProvider, CustomOpenAIProvider, and ModelFetcher to reuse
it. Preserve the existing trimming, default URL, scheme normalization, and
trailing-slash removal behavior.
| } | ||
| ) | ||
|
|
||
| Divider(color = BorderColor, thickness = 1.dp) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Material3 Divider deprecated HorizontalDivider
💡 Result:
Yes, the Divider composable in Material3 has been deprecated [1][2]. It has been replaced by HorizontalDivider [1][2], which provides a more explicit naming convention alongside the introduction of VerticalDivider [3][4]. You should update your code to use HorizontalDivider instead of Divider [5]. The replacement is a direct swap, as both composables accept the same parameters (modifier, thickness, and color) [1][6]. Example replacement: - Old: Divider [1] - New: HorizontalDivider [6] This change was introduced to clarify the orientation of the divider component [3].
Citations:
- 1: https://developer.android.com/reference/kotlin/androidx/compose/material3/Divider.composable
- 2: https://kotlinlang.org/api/compose-multiplatform/material3/androidx.compose.material3/-divider.html
- 3: https://developer.android.com/develop/ui/compose/components/divider
- 4: https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary
- 5: Replace deprecated Divider with HorizontalDivider in Jetchat android/compose-samples#1664
- 6: https://developer.android.com/reference/kotlin/androidx/compose/material3/HorizontalDivider.composable
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file='app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt'
# Show file size and the relevant regions around the referenced lines.
wc -l "$file"
sed -n '1,120p' "$file"
printf '\n---\n'
sed -n '150,210p' "$file"
printf '\n---\n'
sed -n '590,650p' "$file"
# Show imports and any Divider/HorizontalDivider references.
printf '\n=== imports and divider refs ===\n'
grep -nE 'import .*material3|Divider|HorizontalDivider' "$file" || trueRepository: JMAN730/opendroid
Length of output: 12278
Replace Divider with HorizontalDivider
androidx.compose.material3.Divider is deprecated; both usages here (lines 176 and 621) can switch to HorizontalDivider with the same parameters.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt` at line 176,
Replace both `Divider` usages in `SettingsScreen` with `HorizontalDivider`,
preserving the existing `color` and `thickness` parameters at each location.
Update the corresponding Material 3 import if needed.
…cleanup for LiteRT-LM re-release v1.0.1
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
app/build.gradle (1)
7-17: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winSynchronize the release metadata with the new target SDK.
This change raises
targetSdkto 35, whileRELEASE.mdstill documents target SDK 34 for v1.0.1. Update the release notes before publishing.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/build.gradle` around lines 7 - 17, Update the v1.0.1 entry in RELEASE.md to document target SDK 35, keeping the release metadata synchronized with the targetSdk value in the Android defaultConfig.app/src/main/java/com/opendroid/ai/ui/viewmodel/SettingsViewModel.kt (1)
134-140: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winCancel pending model persistence before switching providers.
A queued
activeModelJobcan run after this provider update and overwrite the new provider’s default with the previous provider’s model ID.Proposed fix
fun updateActiveProvider(provider: String) { + activeModelJob?.cancel() + activeModelJob = null val defaultModel = when (provider) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/src/main/java/com/opendroid/ai/ui/viewmodel/SettingsViewModel.kt` around lines 134 - 140, Cancel the pending activeModelJob before updating the provider configuration in the provider-switching flow around normalizedProvider and settingsRepository.updateConfig. Ensure any queued model persistence cannot run after the new provider’s activeModel and defaultModel are applied, while preserving the existing provider and model update behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/src/main/java/com/opendroid/ai/core/llm/ModelDownloadWorker.kt`:
- Around line 329-343: Update formatSpeed and formatEta to pass an explicit
stable Locale to every String.format call, rather than relying on the device
default locale; preserve the existing units, rounding, and time formatting.
- Around line 148-280: The blocking download and file operations in
performDownload must run on Dispatchers.IO. Wrap the performDownload execution
path from CoroutineWorker.doWork in withContext(Dispatchers.IO), preserving its
existing resume handling, progress updates, verification, extraction, and result
behavior; do not broaden the requested refactor beyond moving this path to the
I/O dispatcher.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`:
- Around line 323-353: Update the cached engine reuse logic around cachedEngine,
cachedModelPath, and the LlmInference creation flow to include maxTokens and
temperature in the cache key. Store and compare both generation settings
alongside modelPath, closing and recreating the engine whenever any of the three
values changes; alternatively, move these options to the generation call if
supported by the SDK integration.
In `@app/src/main/java/com/opendroid/ai/data/repository/ModelRepository.kt`:
- Around line 114-135: The startDownload method must pass the model’s expected
SHA-256 checksum to ModelDownloadWorker. Add the checksum field to the
Data.Builder using the corresponding checksum value from entity, with the key
sha256, so doWork() receives a non-empty value and performDownload() can verify
downloads.
- Around line 110-112: Update ModelRepository.download and resumeDownload so
they pass simulate = false to startDownload, removing the unconditional true
behavior in the resumeDownload URL expression. Preserve the existing
startDownload flow so ModelDownloadWorker.performDownload handles real
downloads, including resume support and verification, through the public
ModelManager API.
- Around line 98-104: Update getModelSize in ModelRepository to obtain the
model’s actual byte size from OnDeviceModelSpec or OnDeviceModelRegistry using
modelId, and remove the modelId substring checks and hardcoded fallback sizes.
Preserve the existing Long return contract and handle unavailable registry/spec
data according to the repository’s established model lookup behavior.
- Around line 30-41: Replace the unsupervised CoroutineScope with a
SupervisorJob-backed scope so an initialization failure does not cancel future
launches, and add a synchronized/atomic one-time guard around initialization.
Implement initModelsInDatabaseOnce() to ensure concurrent or repeated calls from
init and allModelsFlow.onStart execute initModelsInDatabase only once, then
invoke that guarded method from both locations.
In `@app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt`:
- Around line 828-836: The production download action is forced into simulation.
In app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt:828-836,
remove the explicit simulated-download argument from the
SettingsViewModel.downloadModel call; in
app/src/main/java/com/opendroid/ai/ui/viewmodel/SettingsViewModel.kt:366-371,
default downloadModel’s simulate parameter to false or restrict simulation to
test/debug APIs, so the settings action performs a real download.
---
Outside diff comments:
In `@app/build.gradle`:
- Around line 7-17: Update the v1.0.1 entry in RELEASE.md to document target SDK
35, keeping the release metadata synchronized with the targetSdk value in the
Android defaultConfig.
In `@app/src/main/java/com/opendroid/ai/ui/viewmodel/SettingsViewModel.kt`:
- Around line 134-140: Cancel the pending activeModelJob before updating the
provider configuration in the provider-switching flow around normalizedProvider
and settingsRepository.updateConfig. Ensure any queued model persistence cannot
run after the new provider’s activeModel and defaultModel are applied, while
preserving the existing provider and model update behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 34167aa6-9e15-4b93-888c-6efe70583c7e
📒 Files selected for processing (13)
RELEASE.mdapp/build.gradleapp/src/main/java/com/opendroid/ai/core/llm/ModelDownloadWorker.ktapp/src/main/java/com/opendroid/ai/core/llm/ModelManager.ktapp/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.ktapp/src/main/java/com/opendroid/ai/data/db/Converters.ktapp/src/main/java/com/opendroid/ai/data/db/OpenDroidDatabase.ktapp/src/main/java/com/opendroid/ai/data/db/dao/ModelDao.ktapp/src/main/java/com/opendroid/ai/data/db/entities/ModelEntity.ktapp/src/main/java/com/opendroid/ai/data/repository/ModelRepository.ktapp/src/main/java/com/opendroid/ai/di/DatabaseModule.ktapp/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.ktapp/src/main/java/com/opendroid/ai/ui/viewmodel/SettingsViewModel.kt
| private suspend fun performDownload( | ||
| modelId: String, | ||
| downloadUrl: String, | ||
| targetPath: String, | ||
| expectedSize: Long, | ||
| expectedSha: String | ||
| ): Result { | ||
| val tempFile = File(applicationContext.cacheDir, "$modelId.tmp") | ||
| val isResume = tempFile.exists() && tempFile.length() > 0 | ||
| val startBytes = if (isResume) tempFile.length() else 0L | ||
|
|
||
| val requestBuilder = Request.Builder().url(downloadUrl) | ||
| if (isResume) { | ||
| requestBuilder.header("Range", "bytes=$startBytes-") | ||
| } | ||
| val request = requestBuilder.build() | ||
|
|
||
| modelDao.updateModelStatus(modelId, ModelStatus.DOWNLOADING) | ||
|
|
||
| val response = okHttpClient.newCall(request).execute() | ||
| if (!response.isSuccessful && response.code != 206) { | ||
| response.close() | ||
| modelDao.updateModelStatus(modelId, ModelStatus.FAILED) | ||
| return Result.failure() | ||
| } | ||
|
|
||
| val append = isResume && response.code == 206 | ||
| val responseBody = response.body ?: throw Exception("Response body is null") | ||
| val totalBytes = (if (append) startBytes else 0L) + responseBody.contentLength() | ||
|
|
||
| val outputStream = FileOutputStream(tempFile, append) | ||
| val inputStream: InputStream = responseBody.byteStream() | ||
| val buffer = ByteArray(64 * 1024) | ||
| var bytesRead: Int | ||
| var totalRead = if (append) startBytes else 0L | ||
| var lastUpdate = System.currentTimeMillis() | ||
| var bytesInLastSecond = 0L | ||
|
|
||
| try { | ||
| while (inputStream.read(buffer).also { bytesRead = it } != -1) { | ||
| if (isStopped) { | ||
| outputStream.close() | ||
| responseBody.close() | ||
| modelDao.updateModelStatus(modelId, ModelStatus.PAUSED) | ||
| return Result.retry() | ||
| } | ||
|
|
||
| outputStream.write(buffer, 0, bytesRead) | ||
| totalRead += bytesRead | ||
| bytesInLastSecond += bytesRead | ||
|
|
||
| val now = System.currentTimeMillis() | ||
| if (now - lastUpdate >= 1000) { | ||
| val progress = if (totalBytes > 0) ((totalRead * 100) / totalBytes).toInt() else 0 | ||
| val speedBytesPerSec = bytesInLastSecond * 1000 / (now - lastUpdate) | ||
| val speedString = formatSpeed(speedBytesPerSec) | ||
| val etaSeconds = if (speedBytesPerSec > 0) (totalBytes - totalRead) / speedBytesPerSec else 0L | ||
| val etaString = formatEta(etaSeconds) | ||
|
|
||
| modelDao.updateDownloadProgressDetails( | ||
| modelId, | ||
| progress, | ||
| totalRead, | ||
| speedString, | ||
| etaString, | ||
| ModelStatus.DOWNLOADING | ||
| ) | ||
|
|
||
| lastUpdate = now | ||
| bytesInLastSecond = 0 | ||
| } | ||
| } | ||
| outputStream.flush() | ||
| } finally { | ||
| outputStream.close() | ||
| responseBody.close() | ||
| } | ||
|
|
||
| if (expectedSha.isNotEmpty()) { | ||
| val actualSha = calculateSha256(tempFile) | ||
| if (actualSha.lowercase() != expectedSha.lowercase()) { | ||
| Log.e(tag, "SHA-256 verification failed for $modelId. Expected $expectedSha, got $actualSha") | ||
| tempFile.delete() | ||
| modelDao.updateModelStatus(modelId, ModelStatus.FAILED) | ||
| return Result.failure() | ||
| } | ||
| } | ||
|
|
||
| // Extract files | ||
| val targetDir = File(targetPath) | ||
| if (!targetDir.exists()) targetDir.mkdirs() | ||
|
|
||
| try { | ||
| if (downloadUrl.endsWith(".zip") || isZipFile(tempFile)) { | ||
| extractZip(tempFile, targetDir) | ||
| } else { | ||
| // If it's a single file (like model.task), copy it to targetDir/model.task | ||
| val modelTaskFile = File(targetDir, "model.task") | ||
| tempFile.copyTo(modelTaskFile, overwrite = true) | ||
|
|
||
| // Write a dummy manifest.json and config.json | ||
| val manifestFile = File(targetDir, "manifest.json") | ||
| val manifest = JSONObject().apply { | ||
| put("model_id", modelId) | ||
| put("status", "ready") | ||
| put("format", "litertlm") | ||
| } | ||
| manifestFile.writeText(manifest.toString()) | ||
| } | ||
| } catch (e: Exception) { | ||
| Log.e(tag, "Extraction failed", e) | ||
| modelDao.updateModelStatus(modelId, ModelStatus.FAILED) | ||
| return Result.failure() | ||
| } | ||
|
|
||
| // Create references for LiteRTLMProvider | ||
| val refFile = File(applicationContext.filesDir, "litert_models/${modelId}.litertlm") | ||
| refFile.parentFile?.mkdirs() | ||
| refFile.writeText(targetDir.absolutePath) | ||
|
|
||
| // Mark ready | ||
| modelDao.updateDownloadProgressDetails( | ||
| modelId, | ||
| 100, | ||
| totalBytes, | ||
| "", | ||
| "", | ||
| ModelStatus.READY | ||
| ) | ||
|
|
||
| tempFile.delete() | ||
| return Result.success() | ||
| } |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy lift
🧩 Analysis chain
🌐 Web query:
CoroutineWorker doWork default dispatcher Dispatchers.Default coroutineContext
💡 Result:
By default, the doWork suspending function in a CoroutineWorker runs on Dispatchers.Default [1][2][3]. Historically, the coroutineContext property was used to specify the dispatcher, but this property is now deprecated [2][4][5]. The recommended practice is to use withContext directly within your doWork function to switch to the appropriate dispatcher for your task, such as Dispatchers.IO for blocking I/O operations [2][5][6]. For example: override suspend fun doWork: Result = withContext(Dispatchers.IO) { // Perform blocking I/O work here Result.success } If you do not specify a different dispatcher using withContext, the worker will continue to execute on Dispatchers.Default [2][3][6].
Citations:
- 1: https://developer.android.com/develop/background-work/background-tasks/persistent/threading/coroutineworker
- 2: https://developer.android.com/reference/kotlin/androidx/work/CoroutineWorker
- 3: https://developer.android.com/reference/androidx/work/CoroutineWorker
- 4: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:work/work-runtime/src/main/java/androidx/work/CoroutineWorker.kt?authuser=3&q=file:androidx%2Fwork%2FCoroutineWorker.kt%20class:androidx.work.CoroutineWorker
- 5: https://stackoverflow.com/questions/58958618/android-workmanager-coroutineworker-overriding-coroutinecontext-is-deprecated
- 6: https://medium.com/androiddevelopers/workmanager-meets-kotlin-b9ad02f7405e
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Map the worker file and inspect the relevant methods only.
ast-grep outline app/src/main/java/com/opendroid/ai/core/llm/ModelDownloadWorker.kt --view expanded
printf '\n--- doWork / performDownload slice ---\n'
sed -n '1,380p' app/src/main/java/com/opendroid/ai/core/llm/ModelDownloadWorker.kt | cat -n | sed -n '1,380p'Repository: JMAN730/opendroid
Length of output: 16368
Move the download path onto Dispatchers.IO
performDownload() is doing blocking OkHttp/file I/O inside CoroutineWorker.doWork(), so wrap that path in withContext(Dispatchers.IO). It also mixes resume handling, progress updates, SHA checks, and extraction in one method; splitting those steps would make it easier to maintain and test.
🧰 Tools
🪛 ast-grep (0.44.1)
[warning] 154-154: A File / FileInputStream / FileReader / FileOutputStream / FileWriter is constructed from a path built with string concatenation ("baseDir" + input) or string interpolation ("$baseDir/$input"). If any segment is attacker-controlled, a value such as "../../etc/passwd" escapes the intended directory (path traversal). Validate and canonicalize the resolved path and confirm it stays under the intended base directory (e.g. compare File(baseDir, name).canonicalFile against baseDir.canonicalFile), or reject inputs containing path separators and "..".
Context: File(applicationContext.cacheDir, "$modelId.tmp")
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').
(path-traversal-file-concat-kotlin)
[warning] 263-263: A File / FileInputStream / FileReader / FileOutputStream / FileWriter is constructed from a path built with string concatenation ("baseDir" + input) or string interpolation ("$baseDir/$input"). If any segment is attacker-controlled, a value such as "../../etc/passwd" escapes the intended directory (path traversal). Validate and canonicalize the resolved path and confirm it stays under the intended base directory (e.g. compare File(baseDir, name).canonicalFile against baseDir.canonicalFile), or reject inputs containing path separators and "..".
Context: File(applicationContext.filesDir, "litert_models/${modelId}.litertlm")
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').
(path-traversal-file-concat-kotlin)
[error] 158-158: An outbound HTTP request is built from a non-literal URL: URL(...).openConnection(), OkHttp's Request.Builder().url(...), or a Spring RestTemplate call (getForObject/getForEntity/postForObject/postForEntity/exchange/execute). When the URL is derived from a variable, method call, concatenation, or interpolation, an attacker can point the request at internal services, cloud metadata endpoints (e.g. 169.254.169.254), or arbitrary hosts (Server-Side Request Forgery). Do not build request targets from untrusted input: validate the URL against a strict allowlist of permitted hosts/schemes, resolve and re-check the host after DNS resolution, and reject internal/link-local/loopback addresses before connecting.
Context: Request.Builder().url(downloadUrl)
Note: [CWE-918] Server-Side Request Forgery (SSRF).
(ssrf-outbound-request-tainted-url-kotlin)
🪛 detekt (1.23.8)
[warning] 148-148: The function performDownload appears to be too complex based on Cognitive Complexity (complexity: 32). Defined complexity threshold for methods is set to '25'
(detekt.complexity.CognitiveComplexMethod)
[warning] 257-257: The caught exception is too generic. Prefer catching specific exceptions to the case that is currently handled.
(detekt.exceptions.TooGenericExceptionCaught)
[warning] 175-175: Exception is a too generic Exception. Prefer throwing specific exceptions that indicate a specific error case.
(detekt.exceptions.TooGenericExceptionThrown)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/ModelDownloadWorker.kt` around
lines 148 - 280, The blocking download and file operations in performDownload
must run on Dispatchers.IO. Wrap the performDownload execution path from
CoroutineWorker.doWork in withContext(Dispatchers.IO), preserving its existing
resume handling, progress updates, verification, extraction, and result
behavior; do not broaden the requested refactor beyond moving this path to the
I/O dispatcher.
| private fun formatSpeed(bytesPerSec: Long): String { | ||
| return when { | ||
| bytesPerSec >= 1024 * 1024 -> String.format("%.1f MB/s", bytesPerSec.toDouble() / (1024 * 1024)) | ||
| bytesPerSec >= 1024 -> String.format("%.1f KB/s", bytesPerSec.toDouble() / 1024) | ||
| else -> "$bytesPerSec B/s" | ||
| } | ||
| } | ||
|
|
||
| private fun formatEta(seconds: Long): String { | ||
| return when { | ||
| seconds >= 3600 -> String.format("%dh %dm", seconds / 3600, (seconds % 3600) / 60) | ||
| seconds >= 60 -> String.format("%dm %ds", seconds / 60, seconds % 60) | ||
| else -> "${seconds}s" | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use explicit Locale in String.format.
formatSpeed/formatEta rely on the implicit default locale for numeric formatting shown to users; some locales use a comma decimal separator, which can look wrong in this UI context.
🌐 Proposed fix
- bytesPerSec >= 1024 * 1024 -> String.format("%.1f MB/s", bytesPerSec.toDouble() / (1024 * 1024))
- bytesPerSec >= 1024 -> String.format("%.1f KB/s", bytesPerSec.toDouble() / 1024)
+ bytesPerSec >= 1024 * 1024 -> String.format(java.util.Locale.US, "%.1f MB/s", bytesPerSec.toDouble() / (1024 * 1024))
+ bytesPerSec >= 1024 -> String.format(java.util.Locale.US, "%.1f KB/s", bytesPerSec.toDouble() / 1024)🧰 Tools
🪛 detekt (1.23.8)
[warning] 331-331: String.format("%.1f MB/s", bytesPerSec.toDouble() / (1024 * 1024)) uses implicitly default locale for string formatting.
(detekt.potential-bugs.ImplicitDefaultLocale)
[warning] 332-332: String.format("%.1f KB/s", bytesPerSec.toDouble() / 1024) uses implicitly default locale for string formatting.
(detekt.potential-bugs.ImplicitDefaultLocale)
[warning] 339-339: String.format("%dh %dm", seconds / 3600, (seconds % 3600) / 60) uses implicitly default locale for string formatting.
(detekt.potential-bugs.ImplicitDefaultLocale)
[warning] 340-340: String.format("%dm %ds", seconds / 60, seconds % 60) uses implicitly default locale for string formatting.
(detekt.potential-bugs.ImplicitDefaultLocale)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/ModelDownloadWorker.kt` around
lines 329 - 343, Update formatSpeed and formatEta to pass an explicit stable
Locale to every String.format call, rather than relying on the device default
locale; preserve the existing units, rounding, and time formatting.
Source: Linters/SAST tools
| if (cachedModelPath != modelPath) { | ||
| closeCachedEngine() | ||
| } | ||
|
|
||
| var engine = cachedEngine | ||
| val inferenceClass = Class.forName("com.google.ai.edge.litertlm.LlmInference") | ||
| if (engine == null) { | ||
| Log.i(TAG, "Creating new LlmInference instance for $modelPath") | ||
| val optionsBuilderClass = Class.forName("com.google.ai.edge.litertlm.LlmInferenceOptions\$Builder") | ||
| val builder = optionsBuilderClass.getDeclaredConstructor().newInstance() | ||
|
|
||
| val setModelPath = optionsBuilderClass.getMethod("setModelPath", String::class.java) | ||
| val setMaxTokens = optionsBuilderClass.getMethod("setMaxTokens", Int::class.javaPrimitiveType) | ||
| val setTemperature = optionsBuilderClass.getMethod("setTemperature", Float::class.javaPrimitiveType) | ||
| val buildMethod = optionsBuilderClass.getMethod("build") | ||
|
|
||
| setModelPath.invoke(builder, modelPath) | ||
| setMaxTokens.invoke(builder, maxTokens) | ||
| setTemperature.invoke(builder, temperature) | ||
| val options = buildMethod.invoke(builder) | ||
|
|
||
| val createMethod = inferenceClass.getMethod( | ||
| "createFromOptions", | ||
| Context::class.java, | ||
| options!!::class.java.interfaces.firstOrNull() ?: options::class.java | ||
| ) | ||
| engine = createMethod.invoke(null, context, options) | ||
| cachedEngine = engine | ||
| cachedModelPath = modelPath | ||
| } else { | ||
| Log.i(TAG, "Reusing cached LlmInference instance") |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Include generation options in the engine cache key.
The engine is configured with maxTokens and temperature, but reuse checks only modelPath. Every later request for that model silently uses the first request’s generation settings.
Cache all three values, or move per-request options to the generation call when correcting the SDK integration.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`
around lines 323 - 353, Update the cached engine reuse logic around
cachedEngine, cachedModelPath, and the LlmInference creation flow to include
maxTokens and temperature in the cache key. Store and compare both generation
settings alongside modelPath, closing and recreating the engine whenever any of
the three values changes; alternatively, move these options to the generation
call if supported by the SDK integration.
| private val tag = "ModelRepository" | ||
| private val scope = CoroutineScope(Dispatchers.IO) | ||
| private val workManager = WorkManager.getInstance(context) | ||
|
|
||
| init { | ||
| scope.launch { | ||
| initModelsInDatabase() | ||
| } | ||
| } | ||
|
|
||
| val allModelsFlow: Flow<List<ModelEntity>> = modelDao.getAllModels() | ||
| .onStart { initModelsInDatabase() } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Unsupervised scope + unsynchronized double-init race.
CoroutineScope(Dispatchers.IO) creates a real Job; an uncaught exception in any child (e.g. inside initModelsInDatabase()) cancels this Job and silently breaks all future scope.launch calls for the rest of the singleton's lifetime. Separately, initModelsInDatabase() runs both eagerly in init and again on every new allModelsFlow collector via .onStart{}, with no guard against concurrent execution — two non-transactional read-then-write passes over the same rows can interleave and stomp each other's downloadSpeed/etaString/status while a download is in progress.
🛡️ Proposed fix
- private val scope = CoroutineScope(Dispatchers.IO)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val initMutex = kotlinx.coroutines.sync.Mutex()
+
+ private suspend fun initModelsInDatabaseOnce() = initMutex.withLock { initModelsInDatabase() }Then call initModelsInDatabaseOnce() from both init and .onStart{}.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/data/repository/ModelRepository.kt` around
lines 30 - 41, Replace the unsupervised CoroutineScope with a
SupervisorJob-backed scope so an initialization failure does not cancel future
launches, and add a synchronized/atomic one-time guard around initialization.
Implement initModelsInDatabaseOnce() to ensure concurrent or repeated calls from
init and allModelsFlow.onStart execute initModelsInDatabase only once, then
invoke that guarded method from both locations.
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt (1)
296-426: 🎯 Functional Correctness | 🔴 Critical | 🏗️ Heavy liftReflection still targets the wrong LiteRT-LM API surface — inference will never actually run.
com.google.ai.edge.litertlm:litertlm-android:0.14.0(the declared dependency) exposesEngine/EngineConfig/Conversation, notLlmInference/LlmInferenceOptions/LlmInferenceOptions.Builder. The rewritten "[INIT FLOW]" reflection (Steps 1-6) still doesClass.forName("com.google.ai.edge.litertlm.LlmInference")and friends — these classes don't exist in that package for this SDK version, soClass.forNamewill always throwClassNotFoundExceptionin production, meaning real inference never executes despite the elaborate new logging/init steps. That surface (LlmInferenceOptions.builder(),LlmInference.createFromOptions(context, options),generateResponse) matches MediaPipe Tasks GenAI (com.google.mediapipe.tasks.genai.llminference), a different, maintenance-only library.This confirms the previously raised concern was never actually fixed for this file — the commit that supposedly addressed "reflection method lookup signature" rewrote the retry/logging flow around the same incorrect classes.
🔧 Correct reflection targets (or drop reflection and use the SDK directly)
val engineClass = Class.forName("com.google.ai.edge.litertlm.Engine") val engineConfigClass = Class.forName("com.google.ai.edge.litertlm.EngineConfig") // EngineConfig(modelPath = ..., backend = Backend.CPU()), Engine(config).initialize(), // engine.createConversation(), conversation.sendMessage(prompt)Given
litertlm-androidis already a Gradle dependency (per the AI summary), consider calling the SDK directly instead of via reflection, which would eliminate this entire class of bugs.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt` around lines 296 - 426, Replace the incorrect LlmInference/LlmInferenceOptions reflection flow in the initialization method with the litertlm-android 0.14.0 API: use com.google.ai.edge.litertlm.Engine and EngineConfig, initialize the engine, create a conversation, and send the prompt through that conversation. Prefer direct SDK calls since the dependency is available; otherwise update all class names, construction, initialization, and inference method lookups consistently while preserving caching and cleanup behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`:
- Around line 196-199: Prevent the catch blocks in the LiteRT-LM flow from
throwing while handling an original failure. Resolve and retain the model spec
before the try blocks, or otherwise guard resolveModelSpec and its
settingsRepository.llmConfig.first() recomputation in the catch handlers; ensure
failures in resolveModelSpec itself still emit the intended “Error (LiteRT-LM):
...” message instead of escaping the flow.
- Around line 296-303: Update cached-engine reuse in LiteRTLMProvider around
cachedModelPath, generate(), complete(), and streamComplete() so the cache key
includes maxTokens and temperature as well as modelPath. Track the active
generation options, invalidate and close the cached engine whenever any key
component changes, and ensure each request type passes its own options before
reuse or initialization.
- Around line 377-385: Update the UnsatisfiedLinkError rethrow in the exception
handler around LiteRT engine creation to preserve the original cause using
initCause before throwing. Keep the existing native-library error message and
logging unchanged, and only adjust this failure path so the cause stack trace
remains available.
---
Outside diff comments:
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`:
- Around line 296-426: Replace the incorrect LlmInference/LlmInferenceOptions
reflection flow in the initialization method with the litertlm-android 0.14.0
API: use com.google.ai.edge.litertlm.Engine and EngineConfig, initialize the
engine, create a conversation, and send the prompt through that conversation.
Prefer direct SDK calls since the dependency is available; otherwise update all
class names, construction, initialization, and inference method lookups
consistently while preserving caching and cleanup behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 6dda15fd-40ba-484b-bc38-78be55ea06e1
📒 Files selected for processing (1)
app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt
| try { | ||
| if (cachedModelPath != modelPath) { | ||
| Log.i(TAG, "[INIT FLOW] Active model path changed from '$cachedModelPath' to '$modelPath'. Resetting cached engine.") | ||
| closeCachedEngine() | ||
| } | ||
|
|
||
| var engine = cachedEngine | ||
|
|
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Cached engine reuse still ignores maxTokens/temperature changes.
cachedModelPath is the only cache key; a later request with different maxTokens/temperature silently reuses an engine configured with the first request's values. generate() (fixed 2000/0.7f) and complete()/streamComplete() (request-specific values) will interfere with each other's cached engine when they target the same model path.
🔧 Include generation options in the cache key
private var cachedEngine: Any? = null
private var cachedModelPath: String? = null
+private var cachedMaxTokens: Int? = null
+private var cachedTemperature: Float? = null
...
- if (cachedModelPath != modelPath) {
+ if (cachedModelPath != modelPath || cachedMaxTokens != maxTokens || cachedTemperature != temperature) {
closeCachedEngine()
}Also applies to: 364-376
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`
around lines 296 - 303, Update cached-engine reuse in LiteRTLMProvider around
cachedModelPath, generate(), complete(), and streamComplete() so the cache key
includes maxTokens and temperature as well as modelPath. Track the active
generation options, invalidate and close the cached engine whenever any key
component changes, and ensure each request type passes its own options before
reuse or initialization.
| } catch (e: Exception) { | ||
| val cause = e.cause | ||
| if (cause is UnsatisfiedLinkError) { | ||
| Log.e(TAG, "[INIT FLOW] [FAILURE] JNI native library failed to load (liblitertlm_jni.so)", cause) | ||
| throw UnsatisfiedLinkError("LiteRT JNI native library failed to load (liblitertlm_jni.so). Error: ${cause.localizedMessage}") | ||
| } | ||
| Log.e(TAG, "[INIT FLOW] [FAILURE] LlmInference engine creation failed", e) | ||
| throw IOException("LiteRT Engine creation failed (possibly corrupted model format or native crash): ${cause?.localizedMessage ?: e.localizedMessage}", cause ?: e) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
UnsatisfiedLinkError rethrow drops the original cause.
UnsatisfiedLinkError has no constructor accepting a cause, so throw UnsatisfiedLinkError("...") at line 381 discards cause's stack trace, matching the detekt SwallowedException hint. Use initCause to preserve it for diagnosing native-library failures in production.
🔧 Preserve the original cause
- throw UnsatisfiedLinkError("LiteRT JNI native library failed to load (liblitertlm_jni.so). Error: ${cause.localizedMessage}")
+ throw UnsatisfiedLinkError("LiteRT JNI native library failed to load (liblitertlm_jni.so). Error: ${cause.localizedMessage}").apply {
+ initCause(cause)
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| } catch (e: Exception) { | |
| val cause = e.cause | |
| if (cause is UnsatisfiedLinkError) { | |
| Log.e(TAG, "[INIT FLOW] [FAILURE] JNI native library failed to load (liblitertlm_jni.so)", cause) | |
| throw UnsatisfiedLinkError("LiteRT JNI native library failed to load (liblitertlm_jni.so). Error: ${cause.localizedMessage}") | |
| } | |
| Log.e(TAG, "[INIT FLOW] [FAILURE] LlmInference engine creation failed", e) | |
| throw IOException("LiteRT Engine creation failed (possibly corrupted model format or native crash): ${cause?.localizedMessage ?: e.localizedMessage}", cause ?: e) | |
| } | |
| } catch (e: Exception) { | |
| val cause = e.cause | |
| if (cause is UnsatisfiedLinkError) { | |
| Log.e(TAG, "[INIT FLOW] [FAILURE] JNI native library failed to load (liblitertlm_jni.so)", cause) | |
| throw UnsatisfiedLinkError("LiteRT JNI native library failed to load (liblitertlm_jni.so). Error: ${cause.localizedMessage}").apply { | |
| initCause(cause) | |
| } | |
| } | |
| Log.e(TAG, "[INIT FLOW] [FAILURE] LlmInference engine creation failed", e) | |
| throw IOException("LiteRT Engine creation failed (possibly corrupted model format or native crash): ${cause?.localizedMessage ?: e.localizedMessage}", cause ?: e) | |
| } |
🧰 Tools
🪛 detekt (1.23.8)
[warning] 377-377: The caught exception is too generic. Prefer catching specific exceptions to the case that is currently handled.
(detekt.exceptions.TooGenericExceptionCaught)
[warning] 377-377: The caught exception is swallowed. The original exception could be lost.
(detekt.exceptions.SwallowedException)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`
around lines 377 - 385, Update the UnsatisfiedLinkError rethrow in the exception
handler around LiteRT engine creation to preserve the original cause using
initCause before throwing. Keep the existing native-library error message and
logging unchanged, and only adjust this failure path so the cause stack trace
remains available.
Source: Linters/SAST tools
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`:
- Around line 411-415: Ensure both conversation lifecycles use Kotlin’s use
pattern: in
app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt lines
411-415, wrap engine.createConversation(conversationConfig) around sendMessage
and response extraction; in lines 213-224, wrap the streaming collect flow
similarly and combine it with the requested streaming-delta fix. Remove the
manual close calls so conversations close on success and exceptions.
- Line 204: Update the cold flows created by streamComplete and generate so
getOrInitializeEngine and engine.initialize execute on Dispatchers.IO, using
flowOn(Dispatchers.IO) or an equivalent withContext around initialization.
Preserve the existing streaming and generation behavior while ensuring model
startup does not run on the collector or main thread.
- Around line 215-223: Update the streaming logic in the
conversation.sendMessageAsync collector to treat each emitted message as an
incremental chunk rather than a cumulative snapshot. Remove the
lastLength/fullText substring-delta handling and emit the text content from each
stream item directly, preserving the existing Content.Text filtering and
concatenation within that item.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 795524a2-667a-4026-854e-b58c4cf087eb
📒 Files selected for processing (2)
app/build.gradleapp/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt
| ?: emptyList() | ||
| ) | ||
|
|
||
| val engine = getOrInitializeEngine(modelPath, request.maxTokens) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate the provider and inspect the relevant methods.
git ls-files | rg 'LiteRTLMProvider\.kt$|Engine|streamComplete|complete|generate'Repository: JMAN730/opendroid
Length of output: 608
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file='app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt'
# Show the structure first, then the relevant lines around complete/streamComplete/generate.
ast-grep outline "$file" --view expanded || true
echo '--- complete / streamComplete / generate ---'
rg -n -A80 -B30 'suspend fun complete|fun streamComplete|fun generate|getOrInitializeEngine|engine\.initialize|flowOn|withContext' "$file"Repository: JMAN730/opendroid
Length of output: 22481
Offload engine initialization from the flow context
streamComplete and generate both create cold flows without flowOn(Dispatchers.IO), so getOrInitializeEngine(...)/engine.initialize() still run on the collector thread. That can block the main thread during model startup. Move the flow work onto Dispatchers.IO (or wrap init in withContext) to keep streaming responsive.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt` at
line 204, Update the cold flows created by streamComplete and generate so
getOrInitializeEngine and engine.initialize execute on Dispatchers.IO, using
flowOn(Dispatchers.IO) or an equivalent withContext around initialization.
Preserve the existing streaming and generation behavior while ensuring model
startup does not run on the collector or main thread.
| var lastLength = 0 | ||
| conversation.sendMessageAsync(prompt).collect { msg -> | ||
| val fullText = msg.contents.contents.filterIsInstance<Content.Text>().joinToString("") { it.text } | ||
| if (fullText.length > lastLength) { | ||
| val delta = fullText.substring(lastLength) | ||
| emit(delta) | ||
| lastLength = fullText.length | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Locate the file and read the relevant section with line numbers.
sed -n '180,260p' app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt
# Search for sendMessageAsync usage and any comments/docs about streaming semantics.
rg -n "sendMessageAsync|LiteRT-LM|LiteRTLM|streaming Flow|incremental|cumulative|chunk" app src . -g '!**/build/**' -g '!**/.gradle/**' || trueRepository: JMAN730/opendroid
Length of output: 19052
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Read the relevant file section with line numbers.
cat -n app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt | sed -n '190,250p'
# Search for other references and comments about the streaming API.
rg -n "sendMessageAsync|LiteRTLMProvider|LiteRT-LM|LiteRT LM|streaming" . -g '!**/build/**' -g '!**/.gradle/**' || trueRepository: JMAN730/opendroid
Length of output: 11582
🏁 Script executed:
#!/bin/bash
set -euo pipefail
cat -n app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt | sed -n '190,250p'
rg -n "sendMessageAsync|LiteRTLMProvider|LiteRT-LM|LiteRT LM|streaming" . -g '!**/build/**' -g '!**/.gradle/**' || trueRepository: JMAN730/opendroid
Length of output: 11582
🌐 Web query:
LiteRT-LM sendMessageAsync streaming Flow incremental chunks cumulative snapshots documentation
💡 Result:
LiteRT-LM supports asynchronous, streaming message generation through methods such as sendMessageAsync (Kotlin/C++) and similar iterator-based or stream-based interfaces in other languages [1][2][3][4][5]. Streaming behavior in LiteRT-LM is characterized by the following: Incremental Chunks Asynchronous streaming methods return a stream of partial responses (chunks) as they are generated by the model [2][3][4][5]. In implementations like C++, these chunks are delivered via callbacks, where each callback invocation provides only the latest piece of the model's output rather than the full message history [4]. Similarly, in Python and JavaScript, the iterator or stream provides successive dictionaries or records containing text content fragments [2][6][5]. Cumulative Snapshots The API does not inherently provide "cumulative snapshots" (where every chunk contains the entire message history) within the stream itself. Instead, the streaming mechanism yields incremental updates [4]. If a full, updated history is required, the user is responsible for accumulating these incremental chunks manually [4]. Once the asynchronous call is complete, the full response is available as the final entry in the conversation history [4]. Kotlin Flow In the Kotlin API, sendMessageAsync can be used to return a Kotlin Flow [1]. This is implemented by bridging the internal callback-based mechanism into a Flow using callbackFlow [7]. This provides a idiomatic way to collect streaming responses within a coroutine scope [1]: conversation.sendMessageAsync("Hello!").catch { /* Handle error / }.collect { chunk -> / Process incremental chunk */ } Key Considerations - Streaming vs. Blocking: Synchronous methods (e.g., sendMessage) block until the entire response is generated, whereas asynchronous/streaming methods are non-blocking [1][2][4]. - Termination: Streams typically signal completion either through the exhaustion of the iterator/flow or a specific terminal callback/state [2][4][5]. - Cancellation: In environments like the Web API, exiting the consumption loop early (e.g., using break) will automatically cancel the ongoing generation [5]. Top Results: [1][2][4][5]
Citations:
- 1: https://github.com/google-ai-edge/LiteRT-LM/blob/main/docs/api/kotlin/getting_started.md
- 2: https://developers.google.com/edge/litert-lm/python
- 3: https://developers.google.com/edge/litert-lm/cpp
- 4: https://github.com/google-ai-edge/LiteRT-LM/blob/main/docs/api/cpp/conversation.md
- 5: https://ai.google.dev/edge/litert-lm/js
- 6: https://github.com/google-ai-edge/LiteRT-LM/blob/main/docs/api/python/getting_started.md
- 7: https://github.com/google-ai-edge/LiteRT-LM/blob/fe0fcbdc/kotlin/java/com/google/ai/edge/litertlm/Conversation.kt
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Show the exact method body and any imported types.
sed -n '1,280p' app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.ktRepository: JMAN730/opendroid
Length of output: 11350
Treat LiteRT-LM stream items as chunks, not snapshots — sendMessageAsync yields incremental updates, so lastLength will drop or mangle text. Emit each chunk directly, or accumulate it outside the collector if you need the full response.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`
around lines 215 - 223, Update the streaming logic in the
conversation.sendMessageAsync collector to treat each emitted message as an
incremental chunk rather than a cumulative snapshot. Remove the
lastLength/fullText substring-delta handling and emit the text content from each
stream item directly, preserving the existing Content.Text filtering and
concatenation within that item.
| val conversation = engine.createConversation(conversationConfig) | ||
|
|
||
| val message = conversation.sendMessage(prompt) | ||
| val responseText = message.contents.contents.filterIsInstance<Content.Text>().joinToString("") { it.text } | ||
| conversation.close() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Close Conversation on all paths (native resource leak). Both inference paths create a Conversation and call close() only after a successful send, so any exception mid-inference leaks the native conversation. The LiteRT-LM SDK samples wrap conversations in .use { }; adopt that (or try { … } finally { conversation.close() }) at each site.
app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt#L411-L415: wrap thecreateConversation/sendMessage/closeblock inengine.createConversation(conversationConfig).use { conversation -> … }so it closes even whensendMessagethrows.app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt#L213-L224: wrap thecreateConversation/collect/closeblock in.use { }so it closes whencollectthrows (combine with the streaming-delta fix in the L215-L223 comment).
📍 Affects 1 file
app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt#L411-L415(this comment)app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt#L213-L224
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt`
around lines 411 - 415, Ensure both conversation lifecycles use Kotlin’s use
pattern: in
app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt lines
411-415, wrap engine.createConversation(conversationConfig) around sendMessage
and response extraction; in lines 213-224, wrap the streaming collect flow
similarly and combine it with the requested streaming-delta fix. Remove the
manual close calls so conversations close on success and exceptions.
…h size and existence verification
…details, verify size > 100MB, and print full SDK exceptions
…t database status to NOT_DOWNLOADED
… fix download 404 errors
…ing, integrity checks, and local imports
…Android SDK 35, Java 21, Kotlin 2.4.0, Hilt 2.58, and Room 2.8.4
…gning Addresses static source review findings: - API keys: moved out of plaintext DataStore JSON into EncryptedSharedPreferences (Android Keystore). Persisted LLMConfig is stripped of secrets on every write; legacy embedded keys migrate to the encrypted store on first repository init. - Backups: allowBackup=false; backup_rules.xml and data_extraction_rules.xml now exclude sharedprefs, databases and DataStore instead of including them. - Prompt injection: auto-reply prompts wrap notification content in untrusted-content delimiters (with delimiter sanitization) and carry explicit security rules; notification summaries in LLM context are marked untrusted. Auto-reply is now opt-in (all channels default OFF). - Plan execution: autoConfirmPlans defaults to false — LLM-generated plans require user confirmation before executing device actions. - Screenshots: captured only when the query refers to the screen, no longer attached to every request while accessibility is active. - SecurePrefs: removed silent plaintext fallback; corrupt encrypted store is recreated, otherwise SecurityException is thrown. - Release signing: removed debug-key fallback; release builds fail loudly when signing credentials are missing.
fix: harden security posture across storage, auto-reply, and build si…
Add generic NeedsInput retry loop and update Claude model IDs
Description
Please include a summary of the changes and the related issue/bug that is resolved.
Fixes # (issue)
Type of Change
How Has This Been Tested?
Please describe the tests that you ran to verify your changes.
Checklist:
docs/folder (if applicable)Summary by CodeRabbit