Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: add dedicated permissions management UI and update permission request instructions in tools

Rishabh Bajpaic6a1b2346fb4
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 25cd613..2a219d1 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -35,6 +35,7 @@
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index ef34858..2652859 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -1,7 +1,9 @@
package com.gotcha
import android.app.admin.DevicePolicyManager
+import android.content.Context
import android.content.Intent
+import android.content.SharedPreferences
import android.net.Uri
import android.net.VpnService
import android.os.Build
@@ -55,26 +57,32 @@ class MainActivity : ComponentActivity() {
/** Set when launched from the assistive ball's "Open Chat" option. */
private var openChatRequested by mutableStateOf(false)
+ /** Used by the Settings screen to grant individual runtime permissions. */
private val permissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
- chatViewModel.onPermissionResult(granted)
Toast.makeText(
this,
- if (granted) "Permission granted — the assistant will retry the operation."
- else "Permission denied. The assistant cannot perform that action.",
+ if (granted) "Permission granted."
+ else "Permission denied.",
Toast.LENGTH_SHORT
).show()
}
+ /** Requests all runtime permissions at once on first launch. */
+ private val firstLaunchLauncher =
+ registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { _ ->
+ // No action needed; the Settings screen shows live permission state.
+ }
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleOwner = this
settingsRepository = SettingsRepository(this)
openChatRequested = intent?.getBooleanExtra(EXTRA_OPEN_CHAT, false) == true
- // Phase 7: tools report missing permissions; request them here on first use.
- // "special:*" markers map to per-access Settings deep-links; anything else is a
- // real runtime permission handled by the single RequestPermission launcher.
+ // Phase 7: tools report special-access markers; open Settings deep-links.
+ // Runtime permissions are no longer requested here — they are pre-configured
+ // in Settings → Permissions or auto-requested on first launch.
lifecycleScope.launch {
chatViewModel.permissionRequests.collect { permission ->
when (permission) {
@@ -120,18 +128,26 @@ class MainActivity : ComponentActivity() {
)
)
ToolResult.VPN_CONSENT -> VpnService.prepare(this@MainActivity)?.let {
- // Non-null means consent is still needed; launch the system dialog.
startActivity(it)
} ?: Toast.makeText(
this@MainActivity,
"VPN already authorized — ask the assistant again.",
Toast.LENGTH_SHORT
).show()
- else -> permissionLauncher.launch(permission)
+ // Runtime permissions are mapped in Settings → Permissions; skip here.
}
}
}
+ // Auto-request runtime permissions on first launch
+ lifecycleScope.launch {
+ val prefs = settingsRepository.prefs
+ if (!prefs.getBoolean(KEY_FIRST_LAUNCH_DONE, false)) {
+ requestAllRuntimePermissions()
+ prefs.edit().putBoolean(KEY_FIRST_LAUNCH_DONE, true).apply()
+ }
+ }
+
setContent {
GotchaTheme {
Surface(
@@ -259,7 +275,8 @@ class MainActivity : ComponentActivity() {
}
Pair(ttsModels, sttModels)
}
- }
+ },
+ packageName = packageName
)
}
Route.SESSIONS -> {
@@ -333,9 +350,35 @@ class MainActivity : ComponentActivity() {
/** Intent extra: when true, launch straight into the chat screen. */
const val EXTRA_OPEN_CHAT = "com.gotcha.OPEN_CHAT"
+ /** SharedPreferences key to track first-launch permission setup. */
+ const val KEY_FIRST_LAUNCH_DONE = "first_launch_setup_done"
+
/** Lifecycle owner for CameraX binding. Set in onCreate, valid while activity lives. */
@Volatile
var lifecycleOwner: androidx.lifecycle.LifecycleOwner? = null
private set
}
+
+ /** Request all runtime permissions the app needs on first launch. */
+ private fun requestAllRuntimePermissions() {
+ val perms = mutableListOf<String>().apply {
+ add(android.Manifest.permission.CAMERA)
+ add(android.Manifest.permission.RECORD_AUDIO)
+ add(android.Manifest.permission.ACCESS_FINE_LOCATION)
+ add(android.Manifest.permission.CALL_PHONE)
+ add(android.Manifest.permission.SEND_SMS)
+ add(android.Manifest.permission.READ_SMS)
+ add(android.Manifest.permission.READ_CALL_LOG)
+ add(android.Manifest.permission.READ_CONTACTS)
+ add(android.Manifest.permission.READ_CALENDAR)
+ if (Build.VERSION.SDK_INT <= 29) {
+ add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
+ add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ add(android.Manifest.permission.READ_MEDIA_IMAGES)
+ }
+ }
+ firstLaunchLauncher.launch(perms.toTypedArray())
+ }
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 0631876..6d0d06f 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -121,7 +121,6 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
private var nextId = 0L
private var confirmationGate: CompletableDeferred<Boolean>? = null
private var questionGate: CompletableDeferred<String>? = null
- private var permissionGate: CompletableDeferred<Boolean>? = null
private var agentJob: Job? = null
private val _uiState = MutableStateFlow(ChatUiState())
@@ -251,12 +250,6 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
questionGate = null
}
- /** Called from MainActivity after the user grants or denies a runtime permission. */
- fun onPermissionResult(granted: Boolean) {
- permissionGate?.complete(granted)
- permissionGate = null
- }
-
/** Called from the Activity's onStart/onStop so confirmations know if they'd be hidden. */
fun setForeground(foreground: Boolean) {
appInForeground = foreground
@@ -287,8 +280,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
getApplication(), perm
) == android.content.pm.PackageManager.PERMISSION_GRANTED
if (!granted) {
- _permissionRequests.tryEmit(perm)
- appendUi(MessageKind.ERROR, "Microphone permission needed for speech input.")
+ appendUi(MessageKind.ERROR, "Microphone permission not granted. Enable it in Settings → Permissions.")
return
}
val started = sttEngine.startAndroidListening()
@@ -555,25 +547,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
)
}
- // Permission gate: if the tool needs a runtime permission (not a special marker),
- // emit the request, suspend until the user responds, and retry if granted.
+ // Special-access markers: emit the marker and continue.
+ // Runtime permissions are pre-configured in Settings — the tool
+ // already returned an error message with guidance if one is missing.
val perm = result.needsPermission
- if (perm != null && !perm.startsWith("special:")) {
- Log.d(TAG, "Permission needed: $perm, waiting for user…")
+ if (perm != null && perm.startsWith("special:")) {
_permissionRequests.tryEmit(perm)
- val gate = CompletableDeferred<Boolean>()
- permissionGate = gate
- val granted = withTimeoutOrNull(120_000L) { gate.await() } ?: false
- permissionGate = null
- Log.d(TAG, "Permission $perm -> granted=$granted")
- if (granted) {
- result = executeCall(call)
- // If the granted permission was a storage permission,
- // ensure the per-chat working directory now exists.
- setupWorkingDir(activeSessionId!!)
- } else {
- result = ToolResult(false, "${result.message} Permission was not granted.")
- }
}
if (result.success && result.message.startsWith("IMAGE_DATA:")) {
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index d9a5632..7e36925 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -35,7 +35,7 @@ data class Settings(
/** Stores credentials in EncryptedSharedPreferences (PRD R6). Never logged. */
class SettingsRepository(context: Context) {
- private val prefs: SharedPreferences by lazy {
+ val prefs: SharedPreferences by lazy {
val masterKey = MasterKey.Builder(context.applicationContext)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
diff --git a/app/src/main/java/com/gotcha/tools/CalendarTool.kt b/app/src/main/java/com/gotcha/tools/CalendarTool.kt
index 5585c0e..65d6ebc 100644
--- a/app/src/main/java/com/gotcha/tools/CalendarTool.kt
+++ b/app/src/main/java/com/gotcha/tools/CalendarTool.kt
@@ -22,7 +22,7 @@ class CalendarTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.READ_CALENDAR,
- "Reading the calendar needs the Calendar permission. I have requested it — please grant it and ask again."
+ "The Calendar permission is not granted. Go to Settings → Permissions → Calendar and enable it, then ask again."
)
}
val days = daysAhead.coerceIn(1, 365)
diff --git a/app/src/main/java/com/gotcha/tools/ContactsTool.kt b/app/src/main/java/com/gotcha/tools/ContactsTool.kt
index 4f14f9b..f54a75d 100644
--- a/app/src/main/java/com/gotcha/tools/ContactsTool.kt
+++ b/app/src/main/java/com/gotcha/tools/ContactsTool.kt
@@ -18,7 +18,7 @@ class ContactsTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.READ_CONTACTS,
- "Looking up contacts needs the Contacts permission. I have requested it — please grant it and ask again."
+ "The Contacts permission is not granted. Go to Settings → Permissions → Contacts and enable it, then ask again."
)
}
return try {
@@ -64,7 +64,7 @@ class ContactsTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.WRITE_CONTACTS,
- "Adding a contact needs the Contacts permission. I have requested it — please grant it and ask again."
+ "The Contacts permission is not granted. Go to Settings → Permissions → Contacts and enable it, then ask again."
)
}
return try {
diff --git a/app/src/main/java/com/gotcha/tools/FileResolver.kt b/app/src/main/java/com/gotcha/tools/FileResolver.kt
index 543b5da..8459c3d 100644
--- a/app/src/main/java/com/gotcha/tools/FileResolver.kt
+++ b/app/src/main/java/com/gotcha/tools/FileResolver.kt
@@ -23,16 +23,16 @@ class FileResolver(private val context: Context) {
companion object {
private const val ALL_FILES_ACCESS_GUIDE =
- "Reading or writing outside the app sandbox needs \"All files access\". " +
- "I have opened that settings page — please enable it for Gotcha and try again."
+ "This operation needs \"All files access\" to read or write outside the app sandbox. " +
+ "Go to Settings → Permissions → All Files Access and enable it, then ask again."
private const val READ_STORAGE_GUIDE =
- "Reading from shared storage needs storage permission. I have requested it — " +
- "please grant it and ask again."
+ "This operation needs storage read permission. " +
+ "Go to Settings → Permissions → Storage Read and grant it, then ask again."
private const val WRITE_STORAGE_GUIDE =
- "Writing to shared storage needs storage permission. I have requested it — " +
- "please grant it and ask again."
+ "This operation needs storage write permission. " +
+ "Go to Settings → Permissions → Storage Write and grant it, then ask again."
var WORKING_DIR_BASE: String = "/storage/emulated/0/Gotcha"
diff --git a/app/src/main/java/com/gotcha/tools/LocationTool.kt b/app/src/main/java/com/gotcha/tools/LocationTool.kt
index eef791a..62470f8 100644
--- a/app/src/main/java/com/gotcha/tools/LocationTool.kt
+++ b/app/src/main/java/com/gotcha/tools/LocationTool.kt
@@ -18,7 +18,7 @@ class LocationTool(private val context: Context) {
if (fine != PackageManager.PERMISSION_GRANTED && coarse != PackageManager.PERMISSION_GRANTED) {
return ToolResult.permissionNeeded(
Manifest.permission.ACCESS_FINE_LOCATION,
- "Reading your location needs the Location permission. I have requested it — please grant it and ask again."
+ "The Location permission is not granted. Go to Settings → Permissions → Location and enable it, then ask again."
)
}
return try {
diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
index d24c7dc..8e62556 100644
--- a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt
@@ -37,8 +37,7 @@ class MediaCaptureTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.CAMERA,
- "Taking photos needs the Camera permission. I have requested it — " +
- "please grant it and ask again."
+ "The Camera permission is not granted. Go to Settings → Permissions → Camera and enable it, then ask again."
)
}
val lifecycleOwner = com.gotcha.MainActivity.lifecycleOwner
@@ -102,7 +101,7 @@ class MediaCaptureTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.RECORD_AUDIO,
- "Recording audio needs the Microphone permission. I have requested it — please grant it and ask again."
+ "The Microphone permission is not granted. Go to Settings → Permissions → Microphone and enable it, then ask again."
)
}
if (recorder != null) {
diff --git a/app/src/main/java/com/gotcha/tools/PhoneTool.kt b/app/src/main/java/com/gotcha/tools/PhoneTool.kt
index 14115a8..5c3a101 100644
--- a/app/src/main/java/com/gotcha/tools/PhoneTool.kt
+++ b/app/src/main/java/com/gotcha/tools/PhoneTool.kt
@@ -46,8 +46,7 @@ class PhoneTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.CALL_PHONE,
- "Placing a call directly needs the Phone permission. I have requested it — " +
- "please grant it and ask again."
+ "The Phone permission is not granted. Go to Settings → Permissions → Phone and enable it, then ask again."
)
}
return try {
@@ -59,7 +58,7 @@ class PhoneTool(private val context: Context) {
} catch (e: SecurityException) {
ToolResult.permissionNeeded(
Manifest.permission.CALL_PHONE,
- "Placing a call needs the Phone permission. I have requested it — please grant it and ask again."
+ "The Phone permission is not granted. Go to Settings → Permissions → Phone and enable it, then ask again."
)
} catch (e: Exception) {
ToolResult.error("Could not place the call: ${e.message}")
@@ -73,7 +72,7 @@ class PhoneTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.READ_CALL_LOG,
- "Reading the call log needs the Call log permission. I have requested it — please grant it and ask again."
+ "The Call Log permission is not granted. Go to Settings → Permissions → Call Log and enable it, then ask again."
)
}
val take = limit.coerceIn(1, 50)
diff --git a/app/src/main/java/com/gotcha/tools/SmsTool.kt b/app/src/main/java/com/gotcha/tools/SmsTool.kt
index 0f9ec52..d6108a8 100644
--- a/app/src/main/java/com/gotcha/tools/SmsTool.kt
+++ b/app/src/main/java/com/gotcha/tools/SmsTool.kt
@@ -24,7 +24,7 @@ class SmsTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.SEND_SMS,
- "Sending a text needs the SMS permission. I have requested it — please grant it and ask again."
+ "The SMS permission is not granted. Go to Settings → Permissions → SMS and enable it, then ask again."
)
}
return try {
@@ -44,7 +44,7 @@ class SmsTool(private val context: Context) {
} catch (e: SecurityException) {
ToolResult.permissionNeeded(
Manifest.permission.SEND_SMS,
- "Sending a text needs the SMS permission. I have requested it — please grant it and ask again."
+ "The SMS permission is not granted. Go to Settings → Permissions → SMS and enable it, then ask again."
)
} catch (e: Exception) {
ToolResult.error("Could not send the text: ${e.message}")
@@ -58,7 +58,7 @@ class SmsTool(private val context: Context) {
) {
return ToolResult.permissionNeeded(
Manifest.permission.READ_SMS,
- "Reading texts needs the SMS permission. I have requested it — please grant it and ask again."
+ "The Read SMS permission is not granted. Go to Settings → Permissions → Read SMS and enable it, then ask again."
)
}
val take = limit.coerceIn(1, 50)
diff --git a/app/src/main/java/com/gotcha/ui/PermissionItems.kt b/app/src/main/java/com/gotcha/ui/PermissionItems.kt
new file mode 100644
index 0000000..0f9a31e
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/PermissionItems.kt
@@ -0,0 +1,196 @@
+package com.gotcha.ui
+
+import android.content.Context
+import android.os.Build
+import android.os.Environment
+import android.provider.Settings
+import android.app.admin.DevicePolicyManager
+import android.app.AppOpsManager
+import android.content.ComponentName
+import android.content.ContextWrapper
+import androidx.core.content.ContextCompat
+import com.gotcha.service.GotchaDeviceAdminReceiver
+
+data class PermissionGroup(
+ val name: String,
+ val items: List<PermissionItem>
+)
+
+data class PermissionItem(
+ val name: String,
+ val description: String,
+ val androidPermission: String?,
+ val specialMarker: String?,
+ val isGranted: (Context) -> Boolean
+)
+
+fun allPermissionGroups(context: Context): List<PermissionGroup> = listOf(
+ PermissionGroup("Communications", listOf(
+ PermissionItem(
+ "Phone", "Place calls directly",
+ android.Manifest.permission.CALL_PHONE, null,
+ { c -> checkPerm(c, android.Manifest.permission.CALL_PHONE) }
+ ),
+ PermissionItem(
+ "SMS", "Send text messages",
+ android.Manifest.permission.SEND_SMS, null,
+ { c -> checkPerm(c, android.Manifest.permission.SEND_SMS) }
+ ),
+ PermissionItem(
+ "Read SMS", "Read inbox messages",
+ android.Manifest.permission.READ_SMS, null,
+ { c -> checkPerm(c, android.Manifest.permission.READ_SMS) }
+ ),
+ PermissionItem(
+ "Call Log", "Read recent call history",
+ android.Manifest.permission.READ_CALL_LOG, null,
+ { c -> checkPerm(c, android.Manifest.permission.READ_CALL_LOG) }
+ )
+ )),
+ PermissionGroup("Contacts", listOf(
+ PermissionItem(
+ "Contacts", "Read and create contacts",
+ android.Manifest.permission.READ_CONTACTS, null,
+ { c -> checkPerm(c, android.Manifest.permission.READ_CONTACTS) }
+ )
+ )),
+ PermissionGroup("Calendar", listOf(
+ PermissionItem(
+ "Calendar", "Read and create calendar events",
+ android.Manifest.permission.READ_CALENDAR, null,
+ { c -> checkPerm(c, android.Manifest.permission.READ_CALENDAR) }
+ )
+ )),
+ PermissionGroup("Media & Storage", listOf(
+ PermissionItem(
+ "Camera", "Take photos",
+ android.Manifest.permission.CAMERA, null,
+ { c -> checkPerm(c, android.Manifest.permission.CAMERA) }
+ ),
+ PermissionItem(
+ "Microphone", "Record audio",
+ android.Manifest.permission.RECORD_AUDIO, null,
+ { c -> checkPerm(c, android.Manifest.permission.RECORD_AUDIO) }
+ ),
+ PermissionItem(
+ "Storage Read", "Read files from shared storage",
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
+ android.Manifest.permission.READ_MEDIA_IMAGES
+ else android.Manifest.permission.READ_EXTERNAL_STORAGE, null,
+ { c ->
+ val perm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
+ android.Manifest.permission.READ_MEDIA_IMAGES
+ else android.Manifest.permission.READ_EXTERNAL_STORAGE
+ checkPerm(c, perm)
+ }
+ ),
+ PermissionItem(
+ "Storage Write", "Write files to shared storage",
+ android.Manifest.permission.WRITE_EXTERNAL_STORAGE, null,
+ { c ->
+ if (Build.VERSION.SDK_INT <= 29) checkPerm(c, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
+ else true // API 30+ uses MANAGE_EXTERNAL_STORAGE
+ }
+ ),
+ PermissionItem(
+ "All Files Access", "Full access to all files on device",
+ null, "special:all_files_access",
+ { c ->
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) Environment.isExternalStorageManager()
+ else checkPerm(c, android.Manifest.permission.READ_EXTERNAL_STORAGE)
+ }
+ )
+ )),
+ PermissionGroup("Location", listOf(
+ PermissionItem(
+ "Location", "Get device location",
+ android.Manifest.permission.ACCESS_FINE_LOCATION, null,
+ { c -> checkPerm(c, android.Manifest.permission.ACCESS_FINE_LOCATION) }
+ )
+ )),
+ PermissionGroup("Device Control", listOf(
+ PermissionItem(
+ "Write Settings", "Modify system settings (brightness)",
+ null, "special:write_settings",
+ { c -> Settings.System.canWrite(c) }
+ ),
+ PermissionItem(
+ "Do Not Disturb", "Silence/vibrate mode and DND",
+ null, "special:dnd_access",
+ { c ->
+ val nm = c.getSystemService(Context.NOTIFICATION_SERVICE) as? android.app.NotificationManager
+ nm?.isNotificationPolicyAccessGranted ?: false
+ }
+ ),
+ PermissionItem(
+ "Usage Access", "Read app usage and data stats",
+ null, "special:usage_access",
+ { c ->
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ val appOps = c.getSystemService(Context.APP_OPS_SERVICE) as? AppOpsManager
+ appOps?.checkOpNoThrow(
+ AppOpsManager.OPSTR_GET_USAGE_STATS,
+ android.os.Process.myUid(), c.packageName
+ ) == AppOpsManager.MODE_ALLOWED
+ } else true
+ }
+ ),
+ PermissionItem(
+ "Device Admin", "Lock screen, enforce password policy",
+ null, "special:device_admin",
+ { c ->
+ val dpm = c.getSystemService(Context.DEVICE_POLICY_SERVICE) as? DevicePolicyManager
+ dpm?.isAdminActive(ComponentName(c, GotchaDeviceAdminReceiver::class.java)) ?: false
+ }
+ )
+ )),
+ PermissionGroup("System Access", listOf(
+ PermissionItem(
+ "Accessibility", "Read screen, tap, swipe, type",
+ null, "special:accessibility_access",
+ { c ->
+ val expected = "${c.packageName}/com.gotcha.service.GotchaAccessibilityService"
+ val enabled = Settings.Secure.getString(
+ c.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
+ ) ?: ""
+ enabled.contains(expected, ignoreCase = true)
+ }
+ ),
+ PermissionItem(
+ "Notification Listener", "Read and dismiss notifications, media control",
+ null, "special:notification_listener_access",
+ { c ->
+ val expected = c.packageName
+ val enabled = Settings.Secure.getString(
+ c.contentResolver, "enabled_notification_listeners"
+ ) ?: ""
+ enabled.contains(expected, ignoreCase = true)
+ }
+ ),
+ PermissionItem(
+ "Display Over Apps", "Show floating overlays",
+ null, "special:overlay_access",
+ { c -> Settings.canDrawOverlays(c) }
+ ),
+ PermissionItem(
+ "VPN", "Block all network traffic (firewall kill-switch)",
+ null, "special:vpn_consent",
+ { c ->
+ try {
+ val cm = c.getSystemService(Context.CONNECTIVITY_SERVICE) as? android.net.ConnectivityManager
+ cm?.let { mgr ->
+ val network = mgr.activeNetwork
+ if (network != null) {
+ mgr.getNetworkCapabilities(network)
+ ?.hasTransport(android.net.NetworkCapabilities.TRANSPORT_VPN) ?: false
+ } else false
+ } ?: false
+ } catch (_: SecurityException) { false }
+ }
+ )
+ ))
+)
+
+private fun checkPerm(context: Context, permission: String): Boolean =
+ ContextCompat.checkSelfPermission(context, permission) ==
+ android.content.pm.PackageManager.PERMISSION_GRANTED
diff --git a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt
new file mode 100644
index 0000000..24ffded
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt
@@ -0,0 +1,176 @@
+package com.gotcha.ui
+
+import android.content.Intent
+import android.net.Uri
+import android.net.VpnService
+import android.os.Build
+import android.provider.Settings as AndroidSettings
+import android.app.admin.DevicePolicyManager
+import android.content.ComponentName
+import android.widget.Toast
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Switch
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import com.gotcha.service.GotchaDeviceAdminReceiver
+import com.gotcha.tools.ToolResult
+
+@Composable
+fun PermissionsSection(packageName: String) {
+ val context = LocalContext.current
+ val groups = remember { allPermissionGroups(context) }
+ var expandedGroups by remember { mutableStateOf(groups.associate { it.name to true }) }
+
+ val runtimeLauncher = rememberLauncherForActivityResult(
+ ActivityResultContracts.RequestPermission()
+ ) { /* permission state is checked live, no action needed */ }
+
+ Text("Permissions", style = MaterialTheme.typography.titleMedium)
+ Text(
+ "Configure permissions that the assistant needs. Runtime permissions show a system dialog " +
+ "when toggled on. Special-access permissions open a Settings screen for one-time setup.",
+ style = MaterialTheme.typography.bodySmall
+ )
+
+ for (group in groups) {
+ val expanded = expandedGroups[group.name] ?: true
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { expandedGroups = expandedGroups + (group.name to !expanded) }
+ .padding(vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = if (expanded) "▼ " else "▶ ",
+ style = MaterialTheme.typography.bodyMedium
+ )
+ Text(
+ text = group.name,
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = FontWeight.Medium
+ )
+ }
+
+ AnimatedVisibility(visible = expanded) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (item in group.items) {
+ val granted = remember { item.isGranted(context) }
+ PermissionRow(
+ item = item,
+ initiallyGranted = granted,
+ packageName = packageName,
+ onRequestRuntime = { perm ->
+ runtimeLauncher.launch(perm)
+ }
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun PermissionRow(
+ item: PermissionItem,
+ initiallyGranted: Boolean,
+ packageName: String,
+ onRequestRuntime: (String) -> Unit
+) {
+ val context = LocalContext.current
+ var granted by remember { mutableStateOf(initiallyGranted) }
+
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 4.dp, horizontal = 8.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(item.name, style = MaterialTheme.typography.bodyMedium)
+ Text(
+ item.description,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ Switch(
+ checked = granted,
+ onCheckedChange = { checked ->
+ if (checked) {
+ if (item.androidPermission != null) {
+ onRequestRuntime(item.androidPermission)
+ // Re-check after dialog (user may grant or deny)
+ granted = item.isGranted(context)
+ } else if (item.specialMarker != null) {
+ openSpecialAccess(context, item.specialMarker, packageName)
+ // Special-access: user leaves the app; re-check when they return
+ granted = item.isGranted(context)
+ }
+ } else {
+ // Cannot programmatically revoke, but navigate to system settings
+ Toast.makeText(
+ context,
+ "Revoke this permission in System Settings → Apps → Gotcha → Permissions",
+ Toast.LENGTH_LONG
+ ).show()
+ }
+ }
+ )
+ }
+}
+
+private fun openSpecialAccess(context: android.content.Context, marker: String, packageName: String) {
+ val intent: Intent? = when (marker) {
+ ToolResult.WRITE_SETTINGS -> Intent(
+ AndroidSettings.ACTION_MANAGE_WRITE_SETTINGS,
+ Uri.parse("package:$packageName")
+ )
+ ToolResult.USAGE_ACCESS -> Intent(AndroidSettings.ACTION_USAGE_ACCESS_SETTINGS)
+ ToolResult.DND_ACCESS -> Intent(AndroidSettings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)
+ ToolResult.ACCESSIBILITY_ACCESS -> Intent(AndroidSettings.ACTION_ACCESSIBILITY_SETTINGS)
+ ToolResult.NOTIFICATION_LISTENER_ACCESS -> Intent(AndroidSettings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
+ ToolResult.ALL_FILES_ACCESS -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
+ Intent(AndroidSettings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:$packageName"))
+ else Intent(AndroidSettings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))
+ ToolResult.OVERLAY_ACCESS -> Intent(AndroidSettings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName"))
+ ToolResult.DEVICE_ADMIN -> Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN).putExtra(
+ DevicePolicyManager.EXTRA_DEVICE_ADMIN,
+ ComponentName(context, GotchaDeviceAdminReceiver::class.java)
+ ).putExtra(
+ DevicePolicyManager.EXTRA_ADD_EXPLANATION,
+ "Gotcha uses device administration to lock the screen, enforce " +
+ "password policy, and disable the camera when you ask it to."
+ )
+ ToolResult.VPN_CONSENT -> VpnService.prepare(context)?.let {
+ Intent(Intent.ACTION_MAIN).apply {
+ `package` = it.`package`
+ }
+ }
+ else -> null
+ }
+ if (intent != null) {
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ context.startActivity(intent)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index 9076451..03cc610 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -1,5 +1,7 @@
package com.gotcha.ui
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
@@ -7,9 +9,9 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
-import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
@@ -31,8 +33,8 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
-import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
@@ -49,7 +51,8 @@ fun SettingsScreen(
onTestConnection: suspend (Settings) -> Result<String>,
onClearLlmCache: () -> Unit,
onBack: () -> Unit,
- onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) }
+ onRefreshAudioModels: suspend (Settings) -> Pair<List<AudioModel>, List<AudioModel>> = { Pair(emptyList(), emptyList()) },
+ packageName: String = ""
) {
var apiKey by remember { mutableStateOf(initial.apiKey) }
var baseUrl by remember { mutableStateOf(initial.baseUrl) }
@@ -73,6 +76,9 @@ fun SettingsScreen(
var status by remember { mutableStateOf<String?>(null) }
var testing by remember { mutableStateOf(false) }
var refreshingModels by remember { mutableStateOf(false) }
+ // Collapsible sections
+ var aiConfigExpanded by remember { mutableStateOf(false) }
+ var speechExpanded by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
// Dropdown expanded states
@@ -114,285 +120,292 @@ fun SettingsScreen(
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
- OutlinedTextField(
- value = apiKey,
- onValueChange = { apiKey = it },
- label = { Text("API key") },
- singleLine = true,
- visualTransformation = if (showKey) VisualTransformation.None
- else PasswordVisualTransformation(),
- trailingIcon = {
- TextButton(onClick = { showKey = !showKey }) {
- Text(if (showKey) "Hide" else "Show")
- }
- },
- modifier = Modifier.fillMaxWidth()
- )
- OutlinedTextField(
- value = baseUrl,
- onValueChange = { baseUrl = it },
- label = { Text("Base URL (OpenAI-compatible)") },
- singleLine = true,
- modifier = Modifier.fillMaxWidth()
- )
- OutlinedTextField(
- value = model,
- onValueChange = { model = it },
- label = { Text("Model name") },
- singleLine = true,
- modifier = Modifier.fillMaxWidth()
+ // ---- AI Configuration (collapsible, collapsed by default) ----
+ SectionHeader(
+ title = "AI Configuration",
+ expanded = aiConfigExpanded,
+ onToggle = { aiConfigExpanded = !aiConfigExpanded }
)
- OutlinedTextField(
- value = maxToolRounds,
- onValueChange = { maxToolRounds = it },
- label = { Text("Max tool rounds") },
- singleLine = true,
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
- modifier = Modifier.fillMaxWidth()
- )
- OutlinedTextField(
- value = maxContextTokens,
- onValueChange = { maxContextTokens = it },
- label = { Text("Max context tokens") },
- singleLine = true,
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
- modifier = Modifier.fillMaxWidth()
- )
- OutlinedTextField(
- value = apiTimeoutSeconds,
- onValueChange = { apiTimeoutSeconds = it },
- label = { Text("API Timeout (seconds, 0 for infinite)") },
- singleLine = true,
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
- modifier = Modifier.fillMaxWidth()
- )
-
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text("Confirm sensitive actions", style = MaterialTheme.typography.bodyLarge)
- Switch(checked = confirmSensitive, onCheckedChange = { confirmSensitive = it })
- }
-
- HorizontalDivider(thickness = 1.dp)
- Text("Speech (TTS / STT)", style = MaterialTheme.typography.titleMedium)
-
- // TTS provider dropdown
- ExposedDropdownMenuBox(
- expanded = ttsProviderExpanded,
- onExpandedChange = { ttsProviderExpanded = it }
- ) {
- OutlinedTextField(
- value = ttsProvider.name,
- onValueChange = {},
- readOnly = true,
- label = { Text("TTS Provider") },
- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = ttsProviderExpanded) },
- modifier = Modifier.fillMaxWidth().menuAnchor()
- )
- ExposedDropdownMenu(
- expanded = ttsProviderExpanded,
- onDismissRequest = { ttsProviderExpanded = false }
- ) {
- AudioProvider.entries.forEach { provider ->
- DropdownMenuItem(
- text = { Text(provider.name) },
- onClick = {
- ttsProvider = provider
- ttsProviderExpanded = false
+ AnimatedVisibility(visible = aiConfigExpanded) {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ OutlinedTextField(
+ value = apiKey,
+ onValueChange = { apiKey = it },
+ label = { Text("API key") },
+ singleLine = true,
+ visualTransformation = if (showKey) VisualTransformation.None
+ else PasswordVisualTransformation(),
+ trailingIcon = {
+ TextButton(onClick = { showKey = !showKey }) {
+ Text(if (showKey) "Hide" else "Show")
}
- )
+ },
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = baseUrl,
+ onValueChange = { baseUrl = it },
+ label = { Text("Base URL (OpenAI-compatible)") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = model,
+ onValueChange = { model = it },
+ label = { Text("Model name") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = maxToolRounds,
+ onValueChange = { maxToolRounds = it },
+ label = { Text("Max tool rounds") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = maxContextTokens,
+ onValueChange = { maxContextTokens = it },
+ label = { Text("Max context tokens") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
+ modifier = Modifier.fillMaxWidth()
+ )
+ OutlinedTextField(
+ value = apiTimeoutSeconds,
+ onValueChange = { apiTimeoutSeconds = it },
+ label = { Text("API Timeout (seconds, 0 for infinite)") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
+ modifier = Modifier.fillMaxWidth()
+ )
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text("Confirm sensitive actions", style = MaterialTheme.typography.bodyLarge)
+ Switch(checked = confirmSensitive, onCheckedChange = { confirmSensitive = it })
}
+ Button(
+ onClick = {
+ onSave(currentSettings())
+ status = "Saved."
+ },
+ enabled = apiKey.isNotBlank() && baseUrl.isNotBlank() && model.isNotBlank(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Save") }
+ OutlinedButton(
+ onClick = {
+ testing = true
+ status = "Testing connection…"
+ scope.launch {
+ val result = onTestConnection(currentSettings())
+ status = result.fold(
+ onSuccess = { "✓ Connected: $it" },
+ onFailure = { "✗ Connection failed: ${it.message}" }
+ )
+ testing = false
+ }
+ },
+ enabled = !testing && apiKey.isNotBlank() && baseUrl.isNotBlank(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Test connection") }
+ OutlinedButton(
+ onClick = {
+ onClearLlmCache()
+ status = "LLM response cache cleared."
+ },
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Clear LLM cache") }
}
}
- if (ttsProvider == AudioProvider.API) {
- OutlinedTextField(
- value = ttsApiBaseUrl,
- onValueChange = { ttsApiBaseUrl = it },
- label = { Text("TTS API Base URL") },
- singleLine = true,
- placeholder = { Text("http://10.0.2.2:8969/v1") },
- modifier = Modifier.fillMaxWidth()
- )
+ HorizontalDivider(thickness = 1.dp)
+
+ // ---- Permissions (collapsible, expanded by default) ----
+ PermissionsSection(packageName = packageName)
- // TTS model dropdown (populated after refresh)
- ExposedDropdownMenuBox(
- expanded = ttsModelExpanded,
- onExpandedChange = { ttsModelExpanded = it }
- ) {
- OutlinedTextField(
- value = ttsApiModel.ifEmpty { "(select model)" },
- onValueChange = {},
- readOnly = true,
- label = { Text("TTS Model") },
- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = ttsModelExpanded) },
- modifier = Modifier.fillMaxWidth().menuAnchor()
- )
- ExposedDropdownMenu(
- expanded = ttsModelExpanded,
- onDismissRequest = { ttsModelExpanded = false }
+ HorizontalDivider(thickness = 1.dp)
+
+ // ---- Speech (collapsible, collapsed by default) ----
+ SectionHeader(
+ title = "Speech (TTS / STT)",
+ expanded = speechExpanded,
+ onToggle = { speechExpanded = !speechExpanded }
+ )
+ AnimatedVisibility(visible = speechExpanded) {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ ExposedDropdownMenuBox(
+ expanded = ttsProviderExpanded,
+ onExpandedChange = { ttsProviderExpanded = it }
) {
- if (availableTtsModels.isEmpty()) {
- DropdownMenuItem(
- text = { Text("No models — refresh below") },
- onClick = { ttsModelExpanded = false }
- )
- } else {
- availableTtsModels.forEach { audioModel ->
+ OutlinedTextField(
+ value = ttsProvider.name,
+ onValueChange = {},
+ readOnly = true,
+ label = { Text("TTS Provider") },
+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = ttsProviderExpanded) },
+ modifier = Modifier.fillMaxWidth().menuAnchor()
+ )
+ ExposedDropdownMenu(
+ expanded = ttsProviderExpanded,
+ onDismissRequest = { ttsProviderExpanded = false }
+ ) {
+ AudioProvider.entries.forEach { provider ->
DropdownMenuItem(
- text = { Text(audioModel.id) },
+ text = { Text(provider.name) },
onClick = {
- ttsApiModel = audioModel.id
- ttsModelExpanded = false
+ ttsProvider = provider
+ ttsProviderExpanded = false
}
)
}
}
}
- }
- }
-
- // STT provider dropdown
- ExposedDropdownMenuBox(
- expanded = sttProviderExpanded,
- onExpandedChange = { sttProviderExpanded = it }
- ) {
- OutlinedTextField(
- value = sttProvider.name,
- onValueChange = {},
- readOnly = true,
- label = { Text("STT Provider") },
- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = sttProviderExpanded) },
- modifier = Modifier.fillMaxWidth().menuAnchor()
- )
- ExposedDropdownMenu(
- expanded = sttProviderExpanded,
- onDismissRequest = { sttProviderExpanded = false }
- ) {
- AudioProvider.entries.forEach { provider ->
- DropdownMenuItem(
- text = { Text(provider.name) },
- onClick = {
- sttProvider = provider
- sttProviderExpanded = false
- }
+ if (ttsProvider == AudioProvider.API) {
+ OutlinedTextField(
+ value = ttsApiBaseUrl,
+ onValueChange = { ttsApiBaseUrl = it },
+ label = { Text("TTS API Base URL") },
+ singleLine = true,
+ placeholder = { Text("http://10.0.2.2:8969/v1") },
+ modifier = Modifier.fillMaxWidth()
)
+ ExposedDropdownMenuBox(
+ expanded = ttsModelExpanded,
+ onExpandedChange = { ttsModelExpanded = it }
+ ) {
+ OutlinedTextField(
+ value = ttsApiModel.ifEmpty { "(select model)" },
+ onValueChange = {},
+ readOnly = true,
+ label = { Text("TTS Model") },
+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = ttsModelExpanded) },
+ modifier = Modifier.fillMaxWidth().menuAnchor()
+ )
+ ExposedDropdownMenu(
+ expanded = ttsModelExpanded,
+ onDismissRequest = { ttsModelExpanded = false }
+ ) {
+ if (availableTtsModels.isEmpty()) {
+ DropdownMenuItem(
+ text = { Text("No models — refresh below") },
+ onClick = { ttsModelExpanded = false }
+ )
+ } else {
+ availableTtsModels.forEach { audioModel ->
+ DropdownMenuItem(
+ text = { Text(audioModel.id) },
+ onClick = {
+ ttsApiModel = audioModel.id
+ ttsModelExpanded = false
+ }
+ )
+ }
+ }
+ }
+ }
}
- }
- }
-
- if (sttProvider == AudioProvider.API) {
- OutlinedTextField(
- value = sttApiBaseUrl,
- onValueChange = { sttApiBaseUrl = it },
- label = { Text("STT API Base URL") },
- singleLine = true,
- placeholder = { Text("http://10.0.2.2:8969/v1") },
- modifier = Modifier.fillMaxWidth()
- )
-
- // STT model dropdown
- ExposedDropdownMenuBox(
- expanded = sttModelExpanded,
- onExpandedChange = { sttModelExpanded = it }
- ) {
- OutlinedTextField(
- value = sttApiModel.ifEmpty { "(select model)" },
- onValueChange = {},
- readOnly = true,
- label = { Text("STT Model") },
- trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = sttModelExpanded) },
- modifier = Modifier.fillMaxWidth().menuAnchor()
- )
- ExposedDropdownMenu(
- expanded = sttModelExpanded,
- onDismissRequest = { sttModelExpanded = false }
+ ExposedDropdownMenuBox(
+ expanded = sttProviderExpanded,
+ onExpandedChange = { sttProviderExpanded = it }
) {
- if (availableSttModels.isEmpty()) {
- DropdownMenuItem(
- text = { Text("No models — refresh below") },
- onClick = { sttModelExpanded = false }
- )
- } else {
- availableSttModels.forEach { audioModel ->
+ OutlinedTextField(
+ value = sttProvider.name,
+ onValueChange = {},
+ readOnly = true,
+ label = { Text("STT Provider") },
+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = sttProviderExpanded) },
+ modifier = Modifier.fillMaxWidth().menuAnchor()
+ )
+ ExposedDropdownMenu(
+ expanded = sttProviderExpanded,
+ onDismissRequest = { sttProviderExpanded = false }
+ ) {
+ AudioProvider.entries.forEach { provider ->
DropdownMenuItem(
- text = { Text(audioModel.id) },
+ text = { Text(provider.name) },
onClick = {
- sttApiModel = audioModel.id
- sttModelExpanded = false
+ sttProvider = provider
+ sttProviderExpanded = false
}
)
}
}
}
- }
- }
-
- Row(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text("Auto-read replies aloud", style = MaterialTheme.typography.bodyLarge)
- Switch(checked = autoReadReplies, onCheckedChange = { autoReadReplies = it })
- }
-
- OutlinedButton(
- onClick = {
- refreshingModels = true
- status = "Refreshing audio models…"
- scope.launch {
- val (tts, stt) = onRefreshAudioModels(currentSettings())
- availableTtsModels = tts
- availableSttModels = stt
- status = "Found ${tts.size} TTS, ${stt.size} STT models"
- refreshingModels = false
- }
- },
- enabled = !refreshingModels && (ttsApiBaseUrl.isNotBlank() || sttApiBaseUrl.isNotBlank()),
- modifier = Modifier.fillMaxWidth()
- ) { Text(if (refreshingModels) "Refreshing…" else "Refresh audio models") }
-
- // Save / actions
- HorizontalDivider(thickness = 1.dp)
-
- Button(
- onClick = {
- onSave(currentSettings())
- status = "Saved."
- },
- enabled = apiKey.isNotBlank() && baseUrl.isNotBlank() && model.isNotBlank(),
- modifier = Modifier.fillMaxWidth()
- ) { Text("Save") }
-
- OutlinedButton(
- onClick = {
- testing = true
- status = "Testing connection…"
- scope.launch {
- val result = onTestConnection(currentSettings())
- status = result.fold(
- onSuccess = { "✓ Connected: $it" },
- onFailure = { "✗ Connection failed: ${it.message}" }
+ if (sttProvider == AudioProvider.API) {
+ OutlinedTextField(
+ value = sttApiBaseUrl,
+ onValueChange = { sttApiBaseUrl = it },
+ label = { Text("STT API Base URL") },
+ singleLine = true,
+ placeholder = { Text("http://10.0.2.2:8969/v1") },
+ modifier = Modifier.fillMaxWidth()
)
- testing = false
+ ExposedDropdownMenuBox(
+ expanded = sttModelExpanded,
+ onExpandedChange = { sttModelExpanded = it }
+ ) {
+ OutlinedTextField(
+ value = sttApiModel.ifEmpty { "(select model)" },
+ onValueChange = {},
+ readOnly = true,
+ label = { Text("STT Model") },
+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = sttModelExpanded) },
+ modifier = Modifier.fillMaxWidth().menuAnchor()
+ )
+ ExposedDropdownMenu(
+ expanded = sttModelExpanded,
+ onDismissRequest = { sttModelExpanded = false }
+ ) {
+ if (availableSttModels.isEmpty()) {
+ DropdownMenuItem(
+ text = { Text("No models — refresh below") },
+ onClick = { sttModelExpanded = false }
+ )
+ } else {
+ availableSttModels.forEach { audioModel ->
+ DropdownMenuItem(
+ text = { Text(audioModel.id) },
+ onClick = {
+ sttApiModel = audioModel.id
+ sttModelExpanded = false
+ }
+ )
+ }
+ }
+ }
+ }
}
- },
- enabled = !testing && apiKey.isNotBlank() && baseUrl.isNotBlank(),
- modifier = Modifier.fillMaxWidth()
- ) { Text("Test connection") }
-
- OutlinedButton(
- onClick = {
- onClearLlmCache()
- status = "LLM response cache cleared."
- },
- modifier = Modifier.fillMaxWidth()
- ) { Text("Clear LLM cache") }
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text("Auto-read replies aloud", style = MaterialTheme.typography.bodyLarge)
+ Switch(checked = autoReadReplies, onCheckedChange = { autoReadReplies = it })
+ }
+ OutlinedButton(
+ onClick = {
+ refreshingModels = true
+ status = "Refreshing audio models…"
+ scope.launch {
+ val (tts, stt) = onRefreshAudioModels(currentSettings())
+ availableTtsModels = tts
+ availableSttModels = stt
+ status = "Found ${tts.size} TTS, ${stt.size} STT models"
+ refreshingModels = false
+ }
+ },
+ enabled = !refreshingModels && (ttsApiBaseUrl.isNotBlank() || sttApiBaseUrl.isNotBlank()),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text(if (refreshingModels) "Refreshing…" else "Refresh audio models") }
+ }
+ }
+ // Status text
status?.let {
Text(it, style = MaterialTheme.typography.bodyMedium)
}
@@ -405,3 +418,28 @@ fun SettingsScreen(
}
}
}
+
+@Composable
+private fun SectionHeader(
+ title: String,
+ expanded: Boolean,
+ onToggle: () -> Unit
+) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = onToggle)
+ .padding(vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = if (expanded) "▼ " else "▶ ",
+ style = MaterialTheme.typography.bodyMedium
+ )
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.Medium
+ )
+ }
+}