Modern Apps git

← Modern-Apps.git

openassistant: added better conversation list using adaptive nav3

Commit
5a6a59374494793b871bd44c5fae8ac7ae9e629f
Author
Vayun Mathur <[email protected]>
When
2026-03-17 03:49 UTC (8 months ago)
Parents
5d14a51

Diff

gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 1abe4ff17e..60c33d2759 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -8,6 +8,7 @@ ksp = "2.3.4" coreKtx = "1.17.0" lifecycleRuntimeKtx = "2.10.0" lifecycleViewmodel = "2.10.0"+litertlmAndroid = "0.8.0" workRuntimeKtx = "2.11.1" datastorePreferences = "1.2.0" @@ -47,6 +48,7 @@ kotlinCsvJvm = "1.10.0" junit = "4.13.2" junitVersion = "1.3.0" espressoCore = "3.7.0"+material3AdaptiveNavigationSuite = "1.4.0"  [libraries] # AndroidX Core & Lifecycle@@ -82,6 +84,7 @@ androidx-media3-datasource-okhttp = { group = "androidx.media3", name = "media3- coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" } coil-video = { module = "io.coil-kt:coil-video", version.ref = "coilCompose" } compose-markdown = { group = "com.github.jeziellago", name = "compose-markdown", version.ref = "composeMarkdown" }+litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" } reorderable = { module = "sh.calvin.reorderable:reorderable", version.ref = "reorderable" }  # PDF Support@@ -130,6 +133,7 @@ androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-toolin androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" } androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" } androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }+androidx-compose-material3-adaptive-navigation-suite = { group = "androidx.compose.material3", name = "material3-adaptive-navigation-suite", version.ref = "material3AdaptiveNavigationSuite" }  [plugins] android-application = { id = "com.android.application", version.ref = "agp" }
library/src/main/java/com/vayunmathur/library/util/Navigation.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt b/library/src/main/java/com/vayunmathur/library/util/Navigation.ktindex 34a3eae897..eb3e480336 100644--- a/library/src/main/java/com/vayunmathur/library/util/Navigation.kt+++ b/library/src/main/java/com/vayunmathur/library/util/Navigation.kt@@ -100,7 +100,6 @@ fun <T: NavKey> MainNavigation(backStack: NavBackStack<T>, entryProvider:  Entry         }     } }- @Composable fun <T: NavKey> rememberNavBackStack(vararg elements: T): NavBackStack<T> {     return rememberSerializable(
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex e39777ed9e..426d9b041e 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -20,9 +20,10 @@ dependencies {     implementation(libs.androidx.room.ktx)     implementation(libs.androidx.navigation3.runtime)     implementation(libs.androidx.work.runtime.ktx)+    implementation(libs.androidx.compose.material3.adaptive.navigation.suite)     ksp(libs.androidx.room.compiler)     implementation(libs.coil.compose)-    implementation("com.google.ai.edge.litertlm:litertlm-android:latest.release")+    implementation(libs.litertlm.android)       // markdown
openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.ktindex 862b6ffc37..9e22530068 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/LiteRTChatUi.kt@@ -34,16 +34,24 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CenterAlignedTopAppBar+import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.ModalDrawerSheet+import androidx.compose.material3.ModalNavigationDrawer+import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TopAppBarDefaults+import androidx.compose.material3.adaptive.currentWindowAdaptiveInfo+import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteScaffold+import androidx.compose.material3.adaptive.navigationsuite.NavigationSuiteType+import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -65,11 +73,13 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.content.ContextCompat import androidx.navigation3.runtime.NavBackStack+import androidx.window.core.layout.WindowSizeClass.Companion.WIDTH_DP_EXPANDED_LOWER_BOUND import coil.compose.AsyncImage import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconMenu import com.vayunmathur.library.util.DatabaseViewModel-import com.vayunmathur.library.util.setLast+import com.vayunmathur.library.util.reset import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch@@ -136,175 +146,274 @@ fun LiteRTChatUi(backStack: NavBackStack<Route>, conversationId: Long, viewModel         }     } -    Scaffold(-        topBar = {-            CenterAlignedTopAppBar(-                title = { Text(activeConversation?.title ?: "New Conversation", fontWeight = FontWeight.Bold) },-                colors = TopAppBarDefaults.centerAlignedTopAppBarColors(-                    containerColor = MaterialTheme.colorScheme.surface-                )-            )-        },-        bottomBar = {-            Column(-                modifier = Modifier-                    .fillMaxWidth()-                    .padding(horizontal = 16.dp, vertical = 8.dp)-            ) {-                if (selectedImageUris.isNotEmpty() || isRecording) {-                    Row(-                        modifier = Modifier.padding(bottom = 8.dp),-                        verticalAlignment = Alignment.Bottom+    val adaptiveInfo = currentWindowAdaptiveInfo()+    val customNavSuiteType = with(adaptiveInfo) {+        if (windowSizeClass.isWidthAtLeastBreakpoint(WIDTH_DP_EXPANDED_LOWER_BOUND)) {+            NavigationSuiteType.WideNavigationRailExpanded+        } else {+            NavigationSuiteType.None+        }+    }+    val allConversations by viewModel.data<Conversation>().collectAsState(initial = emptyList())++    val coroutineScope = rememberCoroutineScope()++    NavigationSuiteScaffold(layoutType = customNavSuiteType, navigationSuiteItems = {+        allConversations.forEach {+            item(it.id == conversationId, {+                backStack.reset(Route.ConversationPage(it.id))+            }, {}, label = {Text(it.title)})+        }+    }) {+        val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)+        ModalNavigationDrawer({+            ModalDrawerSheet {+                allConversations.forEach {+                    NavigationDrawerItem(+                        { Text(it.title) },+                        selected = it.id == conversationId,+                        onClick = {+                            backStack.reset(Route.ConversationPage(it.id))+                        })+                }+            }+        }, drawerState = drawerState) {+            Scaffold(+                topBar = {+                    CenterAlignedTopAppBar(+                        title = {+                            Text(+                                activeConversation?.title ?: "New Conversation",+                                fontWeight = FontWeight.Bold+                            )+                        },+                        colors = TopAppBarDefaults.topAppBarColors(+                            containerColor = MaterialTheme.colorScheme.surface+                        ),+                        actions = {+                            IconButton({backStack.reset(Route.ConversationPage(0))}) {+                                IconAdd()+                            }+                        },+                        navigationIcon = {+                            if(customNavSuiteType == NavigationSuiteType.None) {+                                IconButton({ coroutineScope.launch {+                                    drawerState.open()+                                }}) {+                                    IconMenu()+                                }+                            }+                        }+                    )+                },+                bottomBar = {+                    Column(+                        modifier = Modifier+                            .fillMaxWidth()+                            .padding(horizontal = 16.dp, vertical = 8.dp)                     ) {-                        if (selectedImageUris.isNotEmpty()) {-                            LazyRow(-                                horizontalArrangement = Arrangement.spacedBy(12.dp),-                                modifier = Modifier.weight(1f, fill = false)+                        if (selectedImageUris.isNotEmpty() || isRecording) {+                            Row(+                                modifier = Modifier.padding(bottom = 8.dp),+                                verticalAlignment = Alignment.Bottom                             ) {-                                items(selectedImageUris) { uri ->-                                    Box(modifier = Modifier.size(80.dp)) {-                                        AsyncImage(-                                            model = uri,-                                            contentDescription = null,-                                            modifier = Modifier-                                                .fillMaxSize()-                                                .clip(RoundedCornerShape(12.dp))-                                                .background(MaterialTheme.colorScheme.surfaceVariant),-                                            contentScale = ContentScale.Crop-                                        )-                                        IconButton(-                                            onClick = {-                                                val index = selectedImageUris.indexOf(uri)-                                                if (index != -1) {-                                                    selectedImageUris.removeAt(index)-                                                    if (index < selectedImageFiles.size) selectedImageFiles.removeAt(index)+                                if (selectedImageUris.isNotEmpty()) {+                                    LazyRow(+                                        horizontalArrangement = Arrangement.spacedBy(12.dp),+                                        modifier = Modifier.weight(1f, fill = false)+                                    ) {+                                        items(selectedImageUris) { uri ->+                                            Box(modifier = Modifier.size(80.dp)) {+                                                AsyncImage(+                                                    model = uri,+                                                    contentDescription = null,+                                                    modifier = Modifier+                                                        .fillMaxSize()+                                                        .clip(RoundedCornerShape(12.dp))+                                                        .background(MaterialTheme.colorScheme.surfaceVariant),+                                                    contentScale = ContentScale.Crop+                                                )+                                                IconButton(+                                                    onClick = {+                                                        val index = selectedImageUris.indexOf(uri)+                                                        if (index != -1) {+                                                            selectedImageUris.removeAt(index)+                                                            if (index < selectedImageFiles.size) selectedImageFiles.removeAt(+                                                                index+                                                            )+                                                        }+                                                    }+                                                ) {+                                                    IconClose()                                                 }                                             }+                                        }+                                    }+                                }+                                if (isRecording) {+                                    Spacer(Modifier.width(8.dp))+                                    Card(+                                        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),+                                        shape = RoundedCornerShape(12.dp)+                                    ) {+                                        Row(+                                            Modifier.padding(horizontal = 12.dp, vertical = 8.dp),+                                            verticalAlignment = Alignment.CenterVertically                                         ) {-                                            IconClose()+                                            Text(+                                                "Recording...",+                                                style = MaterialTheme.typography.bodySmall,+                                                color = MaterialTheme.colorScheme.error+                                            )+                                            IconButton(+                                                onClick = {+                                                    audioRecorder?.stop()+                                                    audioRecorder = null+                                                    isRecording = false+                                                    recordedAudioFile = null+                                                }+                                            ) {+                                                IconClose()+                                            }                                         }                                     }                                 }                             }                         }-                        if (isRecording) {-                            Spacer(Modifier.width(8.dp))-                            Card(-                                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),-                                shape = RoundedCornerShape(12.dp)++                        Surface(+                            tonalElevation = 3.dp,+                            shape = RoundedCornerShape(28.dp),+                            color = MaterialTheme.colorScheme.surfaceVariant+                        ) {+                            Row(+                                verticalAlignment = Alignment.CenterVertically,+                                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)                             ) {-                                Row(Modifier.padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {-                                    Text("Recording...", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)-                                    IconButton(-                                        onClick = {+                                IconButton(onClick = { imagePickerLauncher.launch("image/*") }) { IconAdd() }+                                IconButton(+                                    onClick = {+                                        if (ContextCompat.checkSelfPermission(+                                                context,+                                                Manifest.permission.RECORD_AUDIO+                                            ) == PackageManager.PERMISSION_GRANTED+                                        ) {+                                            val file = File(+                                                context.cacheDir,+                                                "recording_${+                                                    Clock.System.now().toEpochMilliseconds()+                                                }.wav"+                                            )+                                            recordedAudioFile = file+                                            try {+                                                val recorder = WavRecorder(context, file, scope)+                                                recorder.start()+                                                audioRecorder = recorder+                                                isRecording = true+                                            } catch (e: Exception) {+                                            }+                                        } else recordAudioPermission.launch(Manifest.permission.RECORD_AUDIO)+                                    }+                                ) {+                                    Icon(+                                        painterResource(android.R.drawable.ic_btn_speak_now),+                                        contentDescription = "Voice"+                                    )+                                }++                                TextField(+                                    value = inputText,+                                    onValueChange = { inputText = it },+                                    modifier = Modifier.weight(1f),+                                    placeholder = { Text("Message...") },+                                    colors = TextFieldDefaults.colors(+                                        focusedContainerColor = Color.Transparent,+                                        unfocusedContainerColor = Color.Transparent,+                                        disabledContainerColor = Color.Transparent,+                                        focusedIndicatorColor = Color.Transparent,+                                        unfocusedIndicatorColor = Color.Transparent+                                    )+                                )++                                val canSend =+                                    (inputText.isNotBlank() || selectedImageFiles.isNotEmpty() || recordedAudioFile != null)+                                IconButton(+                                    enabled = canSend,+                                    onClick = {+                                        if (isRecording) {                                             audioRecorder?.stop()                                             audioRecorder = null                                             isRecording = false-                                            recordedAudioFile = null                                         }-                                    ) {-                                        IconClose()-                                    }-                                }-                            }-                        }-                    }-                } -                Surface(-                    tonalElevation = 3.dp,-                    shape = RoundedCornerShape(28.dp),-                    color = MaterialTheme.colorScheme.surfaceVariant-                ) {-                    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)) {-                        IconButton(onClick = { imagePickerLauncher.launch("image/*") }) { IconAdd() }-                        IconButton(-                            onClick = {-                                if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {-                                    val file = File(context.cacheDir, "recording_${Clock.System.now().toEpochMilliseconds()}.wav")-                                    recordedAudioFile = file-                                    try {-                                        val recorder = WavRecorder(context, file, scope)-                                        recorder.start()-                                        audioRecorder = recorder-                                        isRecording = true-                                    } catch (e: Exception) { }-                                } else recordAudioPermission.launch(Manifest.permission.RECORD_AUDIO)-                            }-                        ) {-                            Icon(painterResource(android.R.drawable.ic_btn_speak_now), contentDescription = "Voice")-                        }+                                        scope.launch {+                                            var currentId = conversationId+                                            if (currentId == 0L) {+                                                val newConv = Conversation(title = "New Conversation")+                                                currentId =+                                                    viewModel.getDaoInterface<Conversation>().dao.upsert(+                                                        newConv+                                                    )+                                                backStack.reset(Route.ConversationPage(currentId))+                                            } -                        TextField(-                            value = inputText,-                            onValueChange = { inputText = it },-                            modifier = Modifier.weight(1f),-                            placeholder = { Text("Message...") },-                            colors = TextFieldDefaults.colors(-                                focusedContainerColor = Color.Transparent,-                                unfocusedContainerColor = Color.Transparent,-                                disabledContainerColor = Color.Transparent,-                                focusedIndicatorColor = Color.Transparent,-                                unfocusedIndicatorColor = Color.Transparent-                            )-                        )+                                            // 1. Save User Message to Database+                                            val userMsg = Message(+                                                conversationId = currentId,+                                                text = inputText,+                                                role = "user",+                                                imagePaths = selectedImageFiles.map { it.absolutePath },+                                                hasAudio = recordedAudioFile != null,+                                                timestamp = Clock.System.now().toEpochMilliseconds()+                                            )+                                            viewModel.getDaoInterface<Message>().dao.upsert(userMsg) -                        val canSend = (inputText.isNotBlank() || selectedImageFiles.isNotEmpty() || recordedAudioFile != null)-                        IconButton(-                            enabled = canSend,-                            onClick = {-                                if (isRecording) {-                                    audioRecorder?.stop()-                                    audioRecorder = null-                                    isRecording = false-                                }+                                            // 2. Start Service with the message payload+                                            val intent =+                                                Intent(context, InferenceService::class.java).apply {+                                                    putExtra("conversation_id", currentId)+                                                    putExtra("user_text", inputText)+                                                    putExtra(+                                                        "image_paths",+                                                        selectedImageFiles.map { it.absolutePath }+                                                            .toTypedArray()+                                                    )+                                                    putExtra(+                                                        "audio_path",+                                                        recordedAudioFile?.absolutePath+                                                    )+                                                }+                                            context.startService(intent) -                                scope.launch {-                                    var currentId = conversationId-                                    if (currentId == 0L) {-                                        val newConv = Conversation(title = "New Conversation")-                                        currentId = viewModel.getDaoInterface<Conversation>().dao.upsert(newConv)-                                        backStack.setLast(Route.ConversationPage(currentId))+                                            // 3. Clear UI State+                                            inputText = ""+                                            selectedImageFiles.clear()+                                            selectedImageUris.clear()+                                            recordedAudioFile = null+                                        }                                     }--                                    // 1. Save User Message to Database-                                    val userMsg = Message(-                                        conversationId = currentId,-                                        text = inputText,-                                        role = "user",-                                        imagePaths = selectedImageFiles.map { it.absolutePath },-                                        hasAudio = recordedAudioFile != null,-                                        timestamp = Clock.System.now().toEpochMilliseconds()+                                ) {+                                    Icon(+                                        painterResource(android.R.drawable.ic_menu_send),+                                        contentDescription = "Send",+                                        tint = if (canSend) MaterialTheme.colorScheme.primary else Color.Gray                                     )-                                    viewModel.getDaoInterface<Message>().dao.upsert(userMsg)--                                    // 2. Start Service with the message payload-                                    val intent = Intent(context, InferenceService::class.java).apply {-                                        putExtra("conversation_id", currentId)-                                        putExtra("user_text", inputText)-                                        putExtra("image_paths", selectedImageFiles.map { it.absolutePath }.toTypedArray())-                                        putExtra("audio_path", recordedAudioFile?.absolutePath)-                                    }-                                    context.startService(intent)--                                    // 3. Clear UI State-                                    inputText = ""-                                    selectedImageFiles.clear()-                                    selectedImageUris.clear()-                                    recordedAudioFile = null                                 }                             }-                        ) {-                            Icon(painterResource(android.R.drawable.ic_menu_send), contentDescription = "Send", tint = if (canSend) MaterialTheme.colorScheme.primary else Color.Gray)                         }                     }                 }-            }-        }-    ) { padding ->-        Box(modifier = Modifier.padding(padding).fillMaxSize()) {-            LazyColumn(state = listState, modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {-                items(filteredMessages, key = { it.id }) { msg -> ChatBubble(msg) }+            ) { padding ->+                Box(modifier = Modifier.padding(padding).fillMaxSize()) {+                    LazyColumn(+                        state = listState,+                        modifier = Modifier.fillMaxSize(),+                        contentPadding = PaddingValues(16.dp),+                        verticalArrangement = Arrangement.spacedBy(16.dp)+                    ) {+                        items(filteredMessages, key = { it.id }) { msg -> ChatBubble(msg) }+                    }+                }             }         }     }
openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.ktindex bf5be21abf..e2fa5bbc37 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/MainActivity.kt@@ -4,20 +4,16 @@ import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge-import androidx.compose.material3.Text import androidx.compose.runtime.Composable-import androidx.navigation3.runtime.NavBackStack import androidx.navigation3.runtime.NavKey import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.InitialDownloadChecker-import com.vayunmathur.library.ui.ListPage import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.DatabaseViewModel import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.rememberNavBackStack import kotlinx.serialization.Serializable-import java.io.File  class MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {@@ -43,32 +39,16 @@ class MainActivity : ComponentActivity() {  @Serializable sealed interface Route: NavKey {-    @Serializable-    data object ListPage: Route     @Serializable     data class ConversationPage(val id: Long): Route }  @Composable fun Navigation(viewModel: DatabaseViewModel) {-    val backStack = rememberNavBackStack<Route>(Route.ListPage)+    val backStack = rememberNavBackStack<Route>(Route.ConversationPage(0))     MainNavigation(backStack) {-        entry<Route.ListPage>() {-            ConversationListPage(backStack, viewModel)-        }         entry<Route.ConversationPage>() {             LiteRTChatUi(backStack, it.id, viewModel)         }     }-}--@Composable-fun ConversationListPage(backStack: NavBackStack<Route>, viewModel: DatabaseViewModel) {-    ListPage<Conversation, Route, Route.ConversationPage>(backStack, viewModel, "Open Assistant", {-        Text(it.title)-    }, {}, {-        Route.ConversationPage(it)-    }, {-        Route.ConversationPage(0)-    }) }\ No newline at end of file