Skip to content

Merge pull request #3 from JMAN730/JMAN730/fork-pr-to-main - #3

Merged
JMAN730 merged 27 commits into
mainfrom
main
Jul 20, 2026
Merged

JMAN730 merged 27 commits into
mainfrom
main

Conversation

@yashab-cyber

@yashab-cyber yashab-cyber commented Jul 2, 2026 •

Copy link
Copy Markdown

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

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes.

  • Test Configuration: Android version / Emulated or physical device.
  • Manual Verification steps:

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new build errors or warnings
  • I have updated the documentation in the docs/ folder (if applicable)

Summary by CodeRabbit

  • New Features
    • On-device AI for Gemma and LiteRT-LM with model discovery, dual-model status/download UI, and lifecycle controls (download, pause/resume, cancel, delete) plus storage cleanup.
    • Added streaming responses with structured tool calls.
  • Bug Fixes
    • Reduced auto-reply bounceback loops; improved self-message/echo detection.
    • Floating accessibility overlay now also respects device lock state.
    • Improved provider URL normalization and several settings/intent edge cases (including missing-parameter prompting loops).
  • Documentation
    • Re-released the v1.0.1 changelog and added the debug APK asset.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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.

Changes

On-device AI update

Layer / File(s) Summary
Build and release configuration
RELEASE.md, build.gradle, app/build.gradle, gradle/wrapper/...
Updates release notes and assets, Android SDK levels, Gradle tooling, Compose, Room, Hilt, DataStore, serialization, and on-device AI dependencies.
Filesystem path handling
app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt
Normalizes filesystem inputs, validates file and directory operations, and reports resolved paths and exception details.
LLM contracts and provider routing
app/src/main/java/com/opendroid/ai/core/llm/LLMProvider.kt, LLMProviderFactory.kt, ModelFetcher.kt, OnDeviceModelRegistry.kt, providers/*
Adds streaming and tool-call types, registers on-device providers and models, handles local model discovery, and centralizes provider URL normalization.
On-device inference providers
app/src/main/java/com/opendroid/ai/core/llm/providers/GemmaProvider.kt, LiteRTLMProvider.kt
Adds Gemma and LiteRT-LM inference, readiness checks, local model handling, streaming, tool-call parsing, engine caching, and error mapping.
Hybrid backend fallback
app/src/main/java/com/opendroid/ai/core/llm/providers/HybridOnDeviceProvider.kt
Selects the configured backend and retries with the alternate backend when availability or inference fails.
Model persistence and download lifecycle
app/src/main/java/com/opendroid/ai/data/db/*, app/src/main/java/com/opendroid/ai/data/repository/ModelRepository.kt, app/src/main/java/com/opendroid/ai/core/llm/ModelDownloadWorker.kt
Adds Room model state, migrations, WorkManager downloads, resume and pause handling, integrity checks, extraction, storage reporting, and cleanup.
Provider settings and model status
app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt, SettingsViewModel.kt, ChatScreen.kt
Adds On-Device AI selection and status controls, normalizes legacy provider names, adjusts persistence debounce timing, and formats model badges.
Runtime interaction safeguards
app/src/main/java/com/opendroid/ai/accessibility/..., app/src/main/java/com/opendroid/ai/core/agent/..., app/src/main/java/com/opendroid/ai/core/service/...
Adds lock-aware overlay visibility, auto-reply bounceback suppression, simple-intent fast paths, self-message filtering, and removes the record-action greeting.

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
Loading
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is a generic merge message and does not describe the actual changes in the pull request. Replace it with a concise, specific title that summarizes the main change, such as on-device model management or LiteRT-LM updates.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

cloudProvidersList excludes 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

📥 Commits

Reviewing files that changed from the base of the PR and between fae42d2 and fda5d6d.

⛔ Files ignored due to path filters (1)
  • .kotlin/errors/errors-1783797583544.log is excluded by !**/*.log
📒 Files selected for processing (23)
  • RELEASE.md
  • app/build.gradle
  • app/src/main/java/com/opendroid/ai/accessibility/OpenDroidAccessibilityService.kt
  • app/src/main/java/com/opendroid/ai/actions/AdvancedControlActions.kt
  • app/src/main/java/com/opendroid/ai/core/agent/AutoReplyEngine.kt
  • app/src/main/java/com/opendroid/ai/core/agent/IntentClassifier.kt
  • app/src/main/java/com/opendroid/ai/core/llm/LLMProvider.kt
  • app/src/main/java/com/opendroid/ai/core/llm/LLMProviderFactory.kt
  • app/src/main/java/com/opendroid/ai/core/llm/ModelFetcher.kt
  • app/src/main/java/com/opendroid/ai/core/llm/OnDeviceModelRegistry.kt
  • app/src/main/java/com/opendroid/ai/core/llm/providers/CopilotProvider.kt
  • app/src/main/java/com/opendroid/ai/core/llm/providers/CustomOpenAIProvider.kt
  • app/src/main/java/com/opendroid/ai/core/llm/providers/GemmaProvider.kt
  • app/src/main/java/com/opendroid/ai/core/llm/providers/HybridOnDeviceProvider.kt
  • app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt
  • app/src/main/java/com/opendroid/ai/core/llm/providers/OllamaProvider.kt
  • app/src/main/java/com/opendroid/ai/core/service/OpenDroidNotificationListener.kt
  • app/src/main/java/com/opendroid/ai/core/service/OpenDroidService.kt
  • app/src/main/java/com/opendroid/ai/ui/screens/ChatScreen.kt
  • app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt
  • app/src/main/java/com/opendroid/ai/ui/viewmodel/SettingsViewModel.kt
  • build.gradle
  • gradle/wrapper/gradle-wrapper.properties
💤 Files with no reviewable changes (1)
  • app/src/main/java/com/opendroid/ai/core/service/OpenDroidService.kt

Comment thread app/build.gradle
Comment on lines +133 to +138
// 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'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -n 'com.google.android.aicore' app/src/main/AndroidManifest.xml

Repository: 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'
fi

Repository: 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'
fi

Repository: 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.

Comment on lines +130 to 135
try {
unregisterReceiver(screenStateReceiver)
} catch (e: Exception) {
// Receiver may not have been registered
}
serviceScope.cancel()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
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

Comment on lines +51 to +68

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)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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=kt

Repository: 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/java

Repository: 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/java

Repository: 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.

Comment on lines +88 to +107
// ── 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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
// ── 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.

Comment on lines +308 to +321
"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
)
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
"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.

Comment on lines +105 to +114
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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:


🏁 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" || true

Repository: 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.

Comment thread RELEASE.md Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Synchronize the release metadata with the new target SDK.

This change raises targetSdk to 35, while RELEASE.md still 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 win

Cancel pending model persistence before switching providers.

A queued activeModelJob can 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2fd0a0f and c7c4852.

📒 Files selected for processing (13)
  • RELEASE.md
  • app/build.gradle
  • app/src/main/java/com/opendroid/ai/core/llm/ModelDownloadWorker.kt
  • app/src/main/java/com/opendroid/ai/core/llm/ModelManager.kt
  • app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt
  • app/src/main/java/com/opendroid/ai/data/db/Converters.kt
  • app/src/main/java/com/opendroid/ai/data/db/OpenDroidDatabase.kt
  • app/src/main/java/com/opendroid/ai/data/db/dao/ModelDao.kt
  • app/src/main/java/com/opendroid/ai/data/db/entities/ModelEntity.kt
  • app/src/main/java/com/opendroid/ai/data/repository/ModelRepository.kt
  • app/src/main/java/com/opendroid/ai/di/DatabaseModule.kt
  • app/src/main/java/com/opendroid/ai/ui/screens/SettingsScreen.kt
  • app/src/main/java/com/opendroid/ai/ui/viewmodel/SettingsViewModel.kt

Comment on lines +148 to +280
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()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 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:


🏁 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.

Comment on lines +329 to +343
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"
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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

Comment on lines +323 to +353
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")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +30 to +41
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() }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 lift

Reflection 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) exposes Engine/EngineConfig/Conversation, not LlmInference/LlmInferenceOptions/LlmInferenceOptions.Builder. The rewritten "[INIT FLOW]" reflection (Steps 1-6) still does Class.forName("com.google.ai.edge.litertlm.LlmInference") and friends — these classes don't exist in that package for this SDK version, so Class.forName will always throw ClassNotFoundException in 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-android is 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

📥 Commits

Reviewing files that changed from the base of the PR and between c7c4852 and ad5df9b.

📒 Files selected for processing (1)
  • app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt

Comment on lines +296 to +303
try {
if (cachedModelPath != modelPath) {
Log.i(TAG, "[INIT FLOW] Active model path changed from '$cachedModelPath' to '$modelPath'. Resetting cached engine.")
closeCachedEngine()
}

var engine = cachedEngine

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Comment on lines +377 to +385
} 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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
} 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between ad5df9b and ef1bcad.

📒 Files selected for processing (2)
  • app/build.gradle
  • app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt

?: emptyList()
)

val engine = getOrInitializeEngine(modelPath, request.maxTokens)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Comment on lines +215 to +223
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
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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/**' || true

Repository: 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/**' || true

Repository: 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/**' || true

Repository: 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:


🏁 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.kt

Repository: 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.

Comment on lines +411 to +415
val conversation = engine.createConversation(conversationConfig)

val message = conversation.sendMessage(prompt)
val responseText = message.contents.contents.filterIsInstance<Content.Text>().joinToString("") { it.text }
conversation.close()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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 the createConversation/sendMessage/close block in engine.createConversation(conversationConfig).use { conversation -> … } so it closes even when sendMessage throws.
  • app/src/main/java/com/opendroid/ai/core/llm/providers/LiteRTLMProvider.kt#L213-L224: wrap the createConversation/collect/close block in .use { } so it closes when collect throws (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.

yashab-cyber and others added 12 commits July 13, 2026 20:40
…details, verify size > 100MB, and print full SDK exceptions
…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.
JMAN730 and others added 2 commits July 16, 2026 20:49
@JMAN730
JMAN730 merged commit c09cb55 into JMAN730:main Jul 20, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants