π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
refactor
Prateek Sunal454c1afefcc3
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeDialogs.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeDialogs.ktnew file mode 100644index 0000000000..64d4fec163--- /dev/null+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeDialogs.kt@@ -0,0 +1,141 @@+package io.ente.ensu++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.weight+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuCornerRadius+import io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.designsystem.EnsuTypography+import io.ente.ensu.domain.model.AttachmentDownloadItem+import io.ente.ensu.domain.model.AttachmentDownloadStatus+import io.ente.ensu.domain.util.formattedFileSize++@Composable+internal fun ComingSoonDialog(+ title: String,+ message: String,+ onDismiss: () -> Unit+) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = {+ Text(text = title, style = EnsuTypography.h3Bold)+ },+ text = {+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .height(140.dp)+ .background(+ EnsuColor.fillFaint(),+ RoundedCornerShape(EnsuCornerRadius.card.dp)+ ),+ contentAlignment = Alignment.Center+ ) {+ Text(text = "Illustration", style = EnsuTypography.small, color = EnsuColor.textMuted())+ }+ Text(text = message, style = EnsuTypography.body, color = EnsuColor.textMuted())+ }+ },+ confirmButton = {+ TextButton(+ onClick = onDismiss,+ colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())+ ) {+ Text(text = "Got it")+ }+ },+ containerColor = EnsuColor.backgroundBase()+ )+}++@Composable+internal fun AttachmentDownloadsDialog(+ downloads: List<AttachmentDownloadItem>,+ onCancel: (String) -> Unit,+ onDismiss: () -> Unit+) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(text = "Attachment downloads", style = EnsuTypography.h3Bold) },+ text = {+ if (downloads.isEmpty()) {+ Text(text = "No pending downloads", style = EnsuTypography.body, color = EnsuColor.textMuted())+ } else {+ Column(+ modifier = Modifier+ .heightIn(max = 320.dp)+ .verticalScroll(rememberScrollState())+ ) {+ downloads.forEach { item ->+ Row(+ modifier = Modifier.padding(vertical = EnsuSpacing.xs.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text(text = item.name, style = EnsuTypography.body, color = EnsuColor.textPrimary())+ Text(+ text = "Session ${item.sessionId.take(6)} β’ ${item.sizeBytes.formattedFileSize()}",+ style = EnsuTypography.mini,+ color = EnsuColor.textMuted()+ )+ }+ Text(+ text = statusLabel(item.status),+ style = EnsuTypography.mini,+ color = EnsuColor.textMuted(),+ modifier = Modifier.padding(end = EnsuSpacing.xs.dp)+ )+ if (item.status == AttachmentDownloadStatus.Queued || item.status == AttachmentDownloadStatus.Downloading) {+ TextButton(+ onClick = { onCancel(item.id) },+ colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())+ ) {+ Text(text = "Cancel", style = EnsuTypography.mini)+ }+ }+ }+ }+ }+ }+ },+ confirmButton = {+ TextButton(+ onClick = onDismiss,+ colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())+ ) {+ Text(text = "Close", style = EnsuTypography.small)+ }+ }+ )+}++private fun statusLabel(status: AttachmentDownloadStatus): String {+ return when (status) {+ AttachmentDownloadStatus.Queued -> "Queued"+ AttachmentDownloadStatus.Downloading -> "Downloading"+ AttachmentDownloadStatus.Completed -> "Completed"+ AttachmentDownloadStatus.Failed -> "Failed"+ AttachmentDownloadStatus.Canceled -> "Canceled"+ }+}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.ktnew file mode 100644index 0000000000..bc4dcc34f6--- /dev/null+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt@@ -0,0 +1,231 @@+package io.ente.ensu++import androidx.compose.animation.AnimatedContentTransitionScope+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInHorizontally+import androidx.compose.animation.slideOutHorizontally+import androidx.compose.animation.core.tween+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.DrawerState+import androidx.compose.material3.DrawerValue+import androidx.compose.material3.Scaffold+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.navigation.NavBackStackEntry+import androidx.navigation.NavHostController+import com.google.accompanist.navigation.animation.AnimatedNavHost+import com.google.accompanist.navigation.animation.composable+import io.ente.ensu.chat.ChatView+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.domain.model.Attachment+import io.ente.ensu.domain.model.AttachmentType+import io.ente.ensu.domain.state.AppState+import io.ente.ensu.domain.store.AppStore+import io.ente.ensu.modelsettings.ModelSettingsScreen+import io.ente.ensu.settings.DeveloperSettingsScreen+import io.ente.ensu.settings.LogViewerScreen+import io.ente.ensu.settings.SettingsScreen+import kotlinx.coroutines.flow.Flow++@Composable+internal fun HomeNavigation(+ appState: AppState,+ store: AppStore,+ logRepository: io.ente.ensu.data.logging.FileLogRepository,+ authService: io.ente.ensu.data.auth.EnsuAuthService,+ currentEndpointFlow: Flow<String>,+ navController: NavHostController,+ drawerState: DrawerState,+ currentRoute: String,+ currentSession: io.ente.ensu.domain.model.ChatSession?,+ onSignIn: () -> Unit,+ onSignOut: () -> Unit,+ onOpenDrawer: () -> Unit,+ onAttachmentDownloads: () -> Unit,+ onShowLogShareDialog: () -> Unit,+ onAttachmentSelected: (AttachmentType) -> Unit,+ onOpenAttachment: (Attachment) -> Unit,+ onDeleteAccount: () -> Unit+) {+ Scaffold(+ containerColor = EnsuColor.backgroundBase(),+ contentWindowInsets = WindowInsets(0, 0, 0, 0),+ topBar = {+ when (currentRoute) {+ HomeRoute.Chat -> {+ Column {+ EnsuTopBar(+ sessionTitle = currentSession?.title,+ showBrand = appState.chat.messages.isEmpty(),+ isLoggedIn = appState.auth.isLoggedIn,+ attachmentDownloads = appState.chat.attachmentDownloads,+ attachmentDownloadProgress = appState.chat.attachmentDownloadProgress,+ modelDownloadStatus = appState.chat.downloadStatus,+ modelDownloadPercent = appState.chat.downloadPercent,+ onOpenDrawer = onOpenDrawer,+ onSignIn = onSignIn,+ onAttachmentDownloads = onAttachmentDownloads+ )+ androidx.compose.material3.HorizontalDivider(color = EnsuColor.border())+ }+ }+ HomeRoute.Logs -> {+ LogsTopBar(+ onBack = { navController.popBackStack() },+ onShare = onShowLogShareDialog+ )+ }+ HomeRoute.ModelSettings -> {+ SimpleTopBar(title = "Model Settings") { navController.popBackStack() }+ }+ HomeRoute.DeveloperSettings -> {+ SimpleTopBar(title = "Developer Settings") { navController.popBackStack() }+ }+ HomeRoute.Settings -> {+ SimpleTopBar(title = "Settings") { navController.popBackStack() }+ }+ else -> Unit+ }+ }+ ) { padding ->+ Box(+ modifier = Modifier+ .fillMaxSize()+ .padding(padding)+ ) {+ AnimatedNavHost(+ navController = navController,+ startDestination = HomeRoute.Chat,+ modifier = Modifier.fillMaxSize()+ ) {+ composable(+ route = HomeRoute.Chat,+ enterTransition = { forwardEnter() },+ exitTransition = { forwardExit() },+ popEnterTransition = { backEnter() },+ popExitTransition = { backExit() }+ ) {+ ChatView(+ chatState = appState.chat,+ isDrawerOpen = drawerState.currentValue == DrawerValue.Open,+ onMessageChange = store::updateMessageText,+ onSend = store::sendMessage,+ onStop = store::stopGeneration,+ onCancelDownload = store::cancelDownload,+ onAttachmentSelected = onAttachmentSelected,+ onRemoveAttachment = store::removeAttachment,+ onEditMessage = { message -> store.beginEditing(message.id) },+ onRetryMessage = { message -> store.retryAssistantMessage(message.id) },+ onCancelEdit = store::cancelEditing,+ onBranchChange = store::updateBranchSelection,+ onOpenAttachment = onOpenAttachment,+ onStartDownload = { userInitiated ->+ store.startModelDownload(userInitiated = userInitiated)+ },+ onOverflowTrim = store::confirmOverflowTrim,+ onOverflowIncreaseContext = {+ store.cancelOverflowDialog()+ navController.navigate(HomeRoute.ModelSettings)+ },+ onOverflowCancel = store::cancelOverflowDialog+ )+ }+ composable(+ route = HomeRoute.Settings,+ enterTransition = { forwardEnter() },+ exitTransition = { forwardExit() },+ popEnterTransition = { backEnter() },+ popExitTransition = { backExit() }+ ) {+ val currentEndpoint by currentEndpointFlow.collectAsState(initial = "https://api.ente.io")+ SettingsScreen(+ currentEndpoint = currentEndpoint,+ isLoggedIn = appState.auth.isLoggedIn,+ userEmail = appState.auth.email,+ onOpenLogs = { navController.navigate(HomeRoute.Logs) },+ onSignOut = onSignOut,+ onSignIn = onSignIn,+ onDeleteAccount = onDeleteAccount+ )+ }+ composable(+ route = HomeRoute.Logs,+ enterTransition = { forwardEnter() },+ exitTransition = { forwardExit() },+ popEnterTransition = { backEnter() },+ popExitTransition = { backExit() }+ ) {+ LogViewerScreen(+ logRepository = logRepository+ )+ }+ composable(+ route = HomeRoute.ModelSettings,+ enterTransition = { forwardEnter() },+ exitTransition = { forwardExit() },+ popEnterTransition = { backEnter() },+ popExitTransition = { backExit() }+ ) {+ ModelSettingsScreen(+ state = appState.modelSettings,+ onSave = store::updateModelSettings,+ onReset = store::resetModelSettings+ )+ }+ composable(+ route = HomeRoute.DeveloperSettings,+ enterTransition = { forwardEnter() },+ exitTransition = { forwardExit() },+ popEnterTransition = { backEnter() },+ popExitTransition = { backExit() }+ ) {+ DeveloperSettingsScreen(+ authService = authService,+ currentEndpointFlow = currentEndpointFlow,+ onOpenModelSettings = { navController.navigate(HomeRoute.ModelSettings) },+ onSaved = { navController.popBackStack() }+ )+ }+ }+ }+ }+}++internal object HomeRoute {+ const val Chat = "chat"+ const val Settings = "settings"+ const val Logs = "logs"+ const val ModelSettings = "model-settings"+ const val DeveloperSettings = "developer-settings"+}++internal fun AnimatedContentTransitionScope<NavBackStackEntry>.forwardEnter() =+ slideInHorizontally(+ initialOffsetX = { it },+ animationSpec = tween(220)+ ) + fadeIn(animationSpec = tween(90))++internal fun AnimatedContentTransitionScope<NavBackStackEntry>.forwardExit() =+ slideOutHorizontally(+ targetOffsetX = { -it },+ animationSpec = tween(220)+ ) + fadeOut(animationSpec = tween(90))++internal fun AnimatedContentTransitionScope<NavBackStackEntry>.backEnter() =+ slideInHorizontally(+ initialOffsetX = { -it },+ animationSpec = tween(220)+ ) + fadeIn(animationSpec = tween(90))++internal fun AnimatedContentTransitionScope<NavBackStackEntry>.backExit() =+ slideOutHorizontally(+ targetOffsetX = { it },+ animationSpec = tween(220)+ ) + fadeOut(animationSpec = tween(90))diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeTopBars.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeTopBars.ktnew file mode 100644index 0000000000..20dfb067b4--- /dev/null+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeTopBars.kt@@ -0,0 +1,194 @@+package io.ente.ensu++import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.material3.TopAppBar+import androidx.compose.material3.CenterAlignedTopAppBar+import androidx.compose.material3.TopAppBarDefaults+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.ente.ensu.components.EnsuLogo+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.designsystem.EnsuTypography+import io.ente.ensu.designsystem.HugeIcons+import io.ente.ensu.domain.model.AttachmentDownloadItem+import io.ente.ensu.domain.model.AttachmentDownloadStatus++@Composable+internal fun EnsuTopBar(+ sessionTitle: String?,+ showBrand: Boolean,+ isLoggedIn: Boolean,+ attachmentDownloads: List<AttachmentDownloadItem>,+ attachmentDownloadProgress: Int?,+ modelDownloadStatus: String?,+ modelDownloadPercent: Int?,+ onOpenDrawer: () -> Unit,+ onSignIn: () -> Unit,+ onAttachmentDownloads: () -> Unit+) {+ val titleText = sessionTitle?.takeIf { it.isNotBlank() } ?: "New Chat"++ CenterAlignedTopAppBar(+ title = {+ if (showBrand) {+ EnsuLogo(height = 20.dp)+ } else {+ Text(+ text = titleText,+ style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp),+ color = EnsuColor.textPrimary(),+ maxLines = 1+ )+ }+ },+ navigationIcon = {+ IconButton(onClick = onOpenDrawer) {+ Icon(+ painter = painterResource(HugeIcons.Menu01Icon),+ contentDescription = "Menu"+ )+ }+ },+ actions = {+ val isLoading = modelDownloadStatus?.contains("Loading", ignoreCase = true) == true+ val showModelProgress = isLoading++ if (!isLoggedIn) {+ if (showModelProgress) {+ ModelProgressIndicator(+ isLoading = isLoading,+ progressPercent = modelDownloadPercent+ )+ Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))+ }+ TextButton(onClick = onSignIn) {+ Text(text = "Sign In", style = EnsuTypography.small, color = EnsuColor.accent())+ }+ } else {+ val hasPending = attachmentDownloads.any {+ it.status == AttachmentDownloadStatus.Queued ||+ it.status == AttachmentDownloadStatus.Downloading ||+ it.status == AttachmentDownloadStatus.Failed+ }+ if (hasPending) {+ val active = attachmentDownloads.filter { it.status != AttachmentDownloadStatus.Canceled }+ val completed = active.count { it.status == AttachmentDownloadStatus.Completed }+ val total = active.size+ TextButton(+ onClick = onAttachmentDownloads,+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Icon(+ painter = painterResource(HugeIcons.Upload01Icon),+ contentDescription = "Attachment downloads",+ tint = EnsuColor.textPrimary()+ )+ Text(+ text = "$completed/$total",+ style = EnsuTypography.mini,+ color = EnsuColor.textMuted(),+ maxLines = 1,+ softWrap = false,+ modifier = Modifier.padding(start = 6.dp)+ )+ }+ }+ }+ if (showModelProgress) {+ if (hasPending) {+ Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))+ }+ ModelProgressIndicator(+ isLoading = isLoading,+ progressPercent = modelDownloadPercent,+ modifier = Modifier.padding(end = EnsuSpacing.sm.dp)+ )+ }+ }+ },+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())+ )+}++@Composable+private fun ModelProgressIndicator(+ isLoading: Boolean,+ progressPercent: Int?,+ modifier: Modifier = Modifier+) {+ val indicatorModifier = modifier.size(16.dp)+ val clamped = progressPercent?.coerceIn(0, 100)+ if (!isLoading && clamped != null) {+ CircularProgressIndicator(+ progress = { clamped / 100f },+ modifier = indicatorModifier,+ color = EnsuColor.accent(),+ trackColor = EnsuColor.border(),+ strokeWidth = 2.dp+ )+ } else {+ CircularProgressIndicator(+ modifier = indicatorModifier,+ color = EnsuColor.accent(),+ trackColor = EnsuColor.border(),+ strokeWidth = 2.dp+ )+ }+}++@Composable+internal fun SimpleTopBar(title: String, onBack: () -> Unit) {+ TopAppBar(+ title = { Text(text = title, style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp)) },+ navigationIcon = {+ IconButton(onClick = onBack) {+ Icon(+ painter = painterResource(HugeIcons.ArrowLeft01Icon),+ contentDescription = "Back"+ )+ }+ },+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())+ )+}++@Composable+internal fun LogsTopBar(onBack: () -> Unit, onShare: () -> Unit) {+ TopAppBar(+ title = { Text(text = "Logs", style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp)) },+ navigationIcon = {+ IconButton(onClick = onBack) {+ Icon(+ painter = painterResource(HugeIcons.ArrowLeft01Icon),+ contentDescription = "Back"+ )+ }+ },+ actions = {+ IconButton(onClick = onShare) {+ Icon(+ painter = painterResource(HugeIcons.Upload01Icon),+ contentDescription = "Share",+ modifier = Modifier.size(18.dp)+ )+ }+ },+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())+ )+}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.ktindex 34edb81857..53c379110c 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt@@ -3,100 +3,71 @@package io.ente.ensuimport android.content.Context+import android.content.Intentimport android.net.Uriimport android.provider.OpenableColumns-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.background-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.WindowInsets-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.heightIn-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.layout.width-import android.content.Intentimport android.webkit.MimeTypeMapimport android.widget.Toastimport androidx.activity.compose.BackHandler+import androidx.activity.compose.ManagedActivityResultLauncher+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContract+import androidx.activity.result.contract.ActivityResultContractsimport androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.tweenimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.slideInHorizontallyimport androidx.compose.animation.slideOutHorizontally-import androidx.compose.animation.core.tween-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll-import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.paddingimport androidx.compose.material3.AlertDialog-import androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaults-import androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.DrawerValue-import androidx.compose.material3.Icon-import androidx.compose.material3.IconButtonimport androidx.compose.material3.ModalBottomSheetimport androidx.compose.material3.ModalNavigationDrawer-import androidx.compose.material3.Scaffoldimport androidx.compose.material3.Text-import androidx.compose.material3.CenterAlignedTopAppBarimport androidx.compose.material3.TextButton-import androidx.compose.material3.TopAppBar-import androidx.compose.material3.TopAppBarDefaultsimport androidx.compose.runtime.Composableimport androidx.compose.runtime.DisposableEffect-import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember-import androidx.compose.ui.Alignmentimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.rememberUpdatedState-import androidx.compose.ui.res.painterResourceimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import androidx.compose.ui.unit.spimport androidx.compose.ui.platform.LocalLifecycleOwner+import androidx.compose.ui.unit.dpimport androidx.core.content.FileProviderimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.LifecycleEventObserver-import androidx.navigation.NavBackStackEntryimport androidx.navigation.compose.currentBackStackEntryAsState-import com.google.accompanist.navigation.animation.AnimatedNavHost-import com.google.accompanist.navigation.animation.composableimport com.google.accompanist.navigation.animation.rememberAnimatedNavControllerimport io.ente.ensu.auth.AuthFlowScreen-import io.ente.ensu.chat.ChatViewimport io.ente.ensu.chat.SessionDrawerimport io.ente.ensu.components.NativeChoiceDialog-import io.ente.ensu.components.EnsuLogoimport io.ente.ensu.data.auth.EnsuAuthServiceimport io.ente.ensu.data.logging.FileLogRepositoryimport io.ente.ensu.designsystem.EnsuColor-import io.ente.ensu.designsystem.EnsuCornerRadius-import io.ente.ensu.designsystem.HugeIconsimport io.ente.ensu.designsystem.EnsuSpacingimport io.ente.ensu.designsystem.EnsuTypographyimport io.ente.ensu.domain.model.Attachment-import io.ente.ensu.domain.model.AttachmentDownloadItem-import io.ente.ensu.domain.model.AttachmentDownloadStatusimport io.ente.ensu.domain.model.AttachmentTypeimport io.ente.ensu.domain.model.LogEntryimport io.ente.ensu.domain.state.AppStateimport io.ente.ensu.domain.store.AppStore-import io.ente.ensu.modelsettings.ModelSettingsScreen-import io.ente.ensu.settings.DeveloperSettingsScreen-import io.ente.ensu.settings.LogViewerScreen-import io.ente.ensu.settings.SettingsScreenimport io.ente.ensu.utils.EnsuFeatureFlags+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.launch+import kotlinx.coroutines.withContextimport java.io.Fileimport java.io.FileOutputStreamimport java.util.UUID@@ -157,41 +128,19 @@ fun HomeView(}}- val imagePicker = androidx.activity.compose.rememberLauncherForActivityResult(- contract = androidx.activity.result.contract.ActivityResultContracts.GetContent()- ) { uri ->- if (uri != null) {- store.setAttachmentProcessing(true)- scope.launch {- val attachment = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {- buildAttachmentFromUri(context, uri, io.ente.ensu.domain.model.AttachmentType.Image)- }- if (attachment != null) {- store.addAttachment(attachment)- } else {- store.setAttachmentProcessing(false)- }- }- }- }+ val imagePicker = rememberAttachmentPicker(+ contract = ActivityResultContracts.GetContent(),+ type = AttachmentType.Image,+ store = store,+ context = context+ )- val documentPicker = androidx.activity.compose.rememberLauncherForActivityResult(- contract = androidx.activity.result.contract.ActivityResultContracts.OpenDocument()- ) { uri ->- if (uri != null) {- store.setAttachmentProcessing(true)- scope.launch {- val attachment = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {- buildAttachmentFromUri(context, uri, io.ente.ensu.domain.model.AttachmentType.Document)- }- if (attachment != null) {- store.addAttachment(attachment)- } else {- store.setAttachmentProcessing(false)- }- }- }- }+ val documentPicker = rememberAttachmentPicker(+ contract = ActivityResultContracts.OpenDocument(),+ type = AttachmentType.Document,+ store = store,+ context = context+ )val exportLogsLauncher = androidx.activity.compose.rememberLauncherForActivityResult(contract = androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/zip")@@ -236,7 +185,11 @@ fun HomeView(exportLogsLauncher.launch(name)}- val currentSession = appState.chat.sessions.firstOrNull { it.id == appState.chat.currentSessionId }+ val currentSession by remember(appState.chat.sessions, appState.chat.currentSessionId) {+ derivedStateOf {+ appState.chat.sessions.firstOrNull { it.id == appState.chat.currentSessionId }+ }+ }BackHandler(enabled = isShowingAuth) {isShowingAuth = false@@ -269,158 +222,15 @@ fun HomeView(// Note: Drawer close is handled in navigation callbacks (onOpenSettings, onAccount, etc.)// to avoid race conditions with route changes during navigation transitions.- val scaffoldContent: @Composable () -> Unit = {- Scaffold(- containerColor = EnsuColor.backgroundBase(),- contentWindowInsets = WindowInsets(0, 0, 0, 0),- topBar = {- when (currentRoute) {- HomeRoute.Chat -> {- Column {- EnsuTopBar(- sessionTitle = currentSession?.title,- showBrand = appState.chat.messages.isEmpty(),- isLoggedIn = appState.auth.isLoggedIn,- attachmentDownloads = appState.chat.attachmentDownloads,- attachmentDownloadProgress = appState.chat.attachmentDownloadProgress,- modelDownloadStatus = appState.chat.downloadStatus,- modelDownloadPercent = appState.chat.downloadPercent,- onOpenDrawer = { scope.launch { drawerState.open() } },- onSignIn = handleSignInRequest,- onAttachmentDownloads = { showAttachmentDownloads = true }- )- androidx.compose.material3.HorizontalDivider(color = EnsuColor.border())- }- }- HomeRoute.Logs -> {- LogsTopBar(- onBack = { navController.popBackStack() },- onShare = { showLogShareDialog = true }- )- }- HomeRoute.ModelSettings -> {- SimpleTopBar(title = "Model Settings") { navController.popBackStack() }- }- HomeRoute.DeveloperSettings -> {- SimpleTopBar(title = "Developer Settings") { navController.popBackStack() }- }- HomeRoute.Settings -> {- SimpleTopBar(title = "Settings") { navController.popBackStack() }- }- else -> Unit- }+ val openDrawer: () -> Unit = { scope.launch { drawerState.open() } }++ val handleAttachmentSelected: (AttachmentType) -> Unit = { type ->+ when (type) {+ AttachmentType.Image -> {+ imagePicker.launch("image/*")}- ) { padding ->- Box(- modifier = Modifier- .fillMaxSize()- .padding(padding)- ) {- AnimatedNavHost(- navController = navController,- startDestination = HomeRoute.Chat,- modifier = Modifier.fillMaxSize()- ) {- composable(- route = HomeRoute.Chat,- enterTransition = { forwardEnter() },- exitTransition = { forwardExit() },- popEnterTransition = { backEnter() },- popExitTransition = { backExit() }- ) {- ChatView(- chatState = appState.chat,- isDrawerOpen = drawerState.currentValue == DrawerValue.Open,- onMessageChange = store::updateMessageText,- onSend = store::sendMessage,- onStop = store::stopGeneration,- onCancelDownload = store::cancelDownload,- onAttachmentSelected = { type ->- when (type) {- io.ente.ensu.domain.model.AttachmentType.Image -> {- imagePicker.launch("image/*")- }- io.ente.ensu.domain.model.AttachmentType.Document -> {- documentPicker.launch(arrayOf("*/*"))- }- }- },- onRemoveAttachment = store::removeAttachment,- onEditMessage = { message -> store.beginEditing(message.id) },- onRetryMessage = { message -> store.retryAssistantMessage(message.id) },- onCancelEdit = store::cancelEditing,- onBranchChange = store::updateBranchSelection,- onOpenAttachment = { attachment ->- openAttachment(context, attachment)- },- onStartDownload = { userInitiated ->- store.startModelDownload(userInitiated = userInitiated)- },- onOverflowTrim = store::confirmOverflowTrim,- onOverflowIncreaseContext = {- store.cancelOverflowDialog()- navController.navigate(HomeRoute.ModelSettings)- },- onOverflowCancel = store::cancelOverflowDialog- )- }- composable(- route = HomeRoute.Settings,- enterTransition = { forwardEnter() },- exitTransition = { forwardExit() },- popEnterTransition = { backEnter() },- popExitTransition = { backExit() }- ) {- val currentEndpoint by currentEndpointFlow.collectAsState(initial = "https://api.ente.io")- SettingsScreen(- currentEndpoint = currentEndpoint,- isLoggedIn = appState.auth.isLoggedIn,- userEmail = appState.auth.email,- onOpenLogs = { navController.navigate(HomeRoute.Logs) },- onSignOut = { isShowingSignOutDialog = true },- onSignIn = handleSignInRequest,- onDeleteAccount = { openDeleteAccountEmail(context) }- )- }- composable(- route = HomeRoute.Logs,- enterTransition = { forwardEnter() },- exitTransition = { forwardExit() },- popEnterTransition = { backEnter() },- popExitTransition = { backExit() }- ) {- LogViewerScreen(- logRepository = logRepository- )- }- composable(- route = HomeRoute.ModelSettings,- enterTransition = { forwardEnter() },- exitTransition = { forwardExit() },- popEnterTransition = { backEnter() },- popExitTransition = { backExit() }- ) {- ModelSettingsScreen(- state = appState.modelSettings,- onSave = store::updateModelSettings,- onReset = store::resetModelSettings- )- }- composable(- route = HomeRoute.DeveloperSettings,- enterTransition = { forwardEnter() },- exitTransition = { forwardExit() },- popEnterTransition = { backEnter() },- popExitTransition = { backExit() }- ) {- DeveloperSettingsScreen(- authService = authService,- currentEndpointFlow = currentEndpointFlow,- onOpenModelSettings = { navController.navigate(HomeRoute.ModelSettings) },- onSaved = { navController.popBackStack() }- )- }- }+ AttachmentType.Document -> {+ documentPicker.launch(arrayOf("*/*"))}}}@@ -477,7 +287,25 @@ fun HomeView()}) {- scaffoldContent()+ HomeNavigation(+ appState = appState,+ store = store,+ logRepository = logRepository,+ authService = authService,+ currentEndpointFlow = currentEndpointFlow,+ navController = navController,+ drawerState = drawerState,+ currentRoute = currentRoute,+ currentSession = currentSession,+ onSignIn = handleSignInRequest,+ onSignOut = { isShowingSignOutDialog = true },+ onOpenDrawer = openDrawer,+ onAttachmentDownloads = { showAttachmentDownloads = true },+ onShowLogShareDialog = { showLogShareDialog = true },+ onAttachmentSelected = handleAttachmentSelected,+ onOpenAttachment = { attachment -> openAttachment(context, attachment) },+ onDeleteAccount = { openDeleteAccountEmail(context) }+ )}AnimatedVisibility(@@ -639,313 +467,32 @@ fun HomeView(}@Composable-private fun EnsuTopBar(- sessionTitle: String?,- showBrand: Boolean,- isLoggedIn: Boolean,- attachmentDownloads: List<io.ente.ensu.domain.model.AttachmentDownloadItem>,- attachmentDownloadProgress: Int?,- modelDownloadStatus: String?,- modelDownloadPercent: Int?,- onOpenDrawer: () -> Unit,- onSignIn: () -> Unit,- onAttachmentDownloads: () -> Unit-) {- val titleText = sessionTitle?.takeIf { it.isNotBlank() } ?: "New Chat"-- CenterAlignedTopAppBar(- title = {- if (showBrand) {- EnsuLogo(height = 20.dp)- } else {- Text(- text = titleText,- style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp),- color = EnsuColor.textPrimary(),- maxLines = 1- )- }- },- navigationIcon = {- IconButton(onClick = onOpenDrawer) {- Icon(- painter = painterResource(HugeIcons.Menu01Icon),- contentDescription = "Menu"- )- }- },- actions = {- val isLoading = modelDownloadStatus?.contains("Loading", ignoreCase = true) == true- val showModelProgress = isLoading-- if (!isLoggedIn) {- if (showModelProgress) {- ModelProgressIndicator(- isLoading = isLoading,- progressPercent = modelDownloadPercent- )- Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))- }- TextButton(onClick = onSignIn) {- Text(text = "Sign In", style = EnsuTypography.small, color = EnsuColor.accent())- }- } else {- val hasPending = attachmentDownloads.any {- it.status == AttachmentDownloadStatus.Queued ||- it.status == AttachmentDownloadStatus.Downloading ||- it.status == AttachmentDownloadStatus.Failed- }- if (hasPending) {- val active = attachmentDownloads.filter { it.status != AttachmentDownloadStatus.Canceled }- val completed = active.count { it.status == AttachmentDownloadStatus.Completed }- val total = active.size- TextButton(- onClick = onAttachmentDownloads,- contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)- ) {- Row(verticalAlignment = Alignment.CenterVertically) {- Icon(- painter = painterResource(HugeIcons.Upload01Icon),- contentDescription = "Attachment downloads",- tint = EnsuColor.textPrimary()- )- Text(- text = "$completed/$total",- style = EnsuTypography.mini,- color = EnsuColor.textMuted(),- maxLines = 1,- softWrap = false,- modifier = Modifier.padding(start = 6.dp)- )- }- }- }- if (showModelProgress) {- if (hasPending) {- Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))- }- ModelProgressIndicator(- isLoading = isLoading,- progressPercent = modelDownloadPercent,- modifier = Modifier.padding(end = EnsuSpacing.sm.dp)- )- }- }- },- colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())- )-}--@Composable-private fun ModelProgressIndicator(- isLoading: Boolean,- progressPercent: Int?,- modifier: Modifier = Modifier-) {- val indicatorModifier = modifier.size(16.dp)- val clamped = progressPercent?.coerceIn(0, 100)- if (!isLoading && clamped != null) {- CircularProgressIndicator(- progress = { clamped / 100f },- modifier = indicatorModifier,- color = EnsuColor.accent(),- trackColor = EnsuColor.border(),- strokeWidth = 2.dp- )- } else {- CircularProgressIndicator(- modifier = indicatorModifier,- color = EnsuColor.accent(),- trackColor = EnsuColor.border(),- strokeWidth = 2.dp- )- }-}+private fun <I> rememberAttachmentPicker(+ contract: ActivityResultContract<I, Uri?>,+ type: AttachmentType,+ store: AppStore,+ context: Context+): ManagedActivityResultLauncher<I, Uri?> {+ val scope = rememberCoroutineScope()+ val latestStore by rememberUpdatedState(store)-@Composable-private fun ComingSoonDialog(- title: String,- message: String,- onDismiss: () -> Unit-) {- AlertDialog(- onDismissRequest = onDismiss,- title = {- Text(text = title, style = EnsuTypography.h3Bold)- },- text = {- Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {- Box(- modifier = Modifier- .fillMaxWidth()- .height(140.dp)- .background(- EnsuColor.fillFaint(),- RoundedCornerShape(EnsuCornerRadius.card.dp)- ),- contentAlignment = Alignment.Center- ) {- Text(text = "Illustration", style = EnsuTypography.small, color = EnsuColor.textMuted())+ return rememberLauncherForActivityResult(contract = contract) { uri ->+ if (uri != null) {+ latestStore.setAttachmentProcessing(true)+ scope.launch {+ val attachment = withContext(Dispatchers.IO) {+ buildAttachmentFromUri(context, uri, type)}- Text(text = message, style = EnsuTypography.body, color = EnsuColor.textMuted())- }- },- confirmButton = {- TextButton(- onClick = onDismiss,- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())- ) {- Text(text = "Got it")- }- },- containerColor = EnsuColor.backgroundBase()- )-}--@Composable-private fun AttachmentDownloadsDialog(- downloads: List<AttachmentDownloadItem>,- onCancel: (String) -> Unit,- onDismiss: () -> Unit-) {- AlertDialog(- onDismissRequest = onDismiss,- title = { Text(text = "Attachment downloads", style = EnsuTypography.h3Bold) },- text = {- if (downloads.isEmpty()) {- Text(text = "No pending downloads", style = EnsuTypography.body, color = EnsuColor.textMuted())- } else {- Column(- modifier = Modifier- .heightIn(max = 320.dp)- .verticalScroll(rememberScrollState())- ) {- downloads.forEach { item ->- Row(- modifier = Modifier.padding(vertical = EnsuSpacing.xs.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Column(modifier = Modifier.weight(1f)) {- Text(text = item.name, style = EnsuTypography.body, color = EnsuColor.textPrimary())- Text(- text = "Session ${item.sessionId.take(6)} β’ ${item.sizeBytes / 1024} KB",- style = EnsuTypography.mini,- color = EnsuColor.textMuted()- )- }- Text(- text = statusLabel(item.status),- style = EnsuTypography.mini,- color = EnsuColor.textMuted(),- modifier = Modifier.padding(end = EnsuSpacing.xs.dp)- )- if (item.status == AttachmentDownloadStatus.Queued || item.status == AttachmentDownloadStatus.Downloading) {- TextButton(- onClick = { onCancel(item.id) },- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())- ) {- Text(text = "Cancel", style = EnsuTypography.mini)- }- }- }- }+ if (attachment != null) {+ latestStore.addAttachment(attachment)+ } else {+ latestStore.setAttachmentProcessing(false)}}- },- confirmButton = {- TextButton(- onClick = onDismiss,- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())- ) {- Text(text = "Close", style = EnsuTypography.small)- }}- )-}--private fun statusLabel(status: AttachmentDownloadStatus): String {- return when (status) {- AttachmentDownloadStatus.Queued -> "Queued"- AttachmentDownloadStatus.Downloading -> "Downloading"- AttachmentDownloadStatus.Completed -> "Completed"- AttachmentDownloadStatus.Failed -> "Failed"- AttachmentDownloadStatus.Canceled -> "Canceled"}}-@Composable-private fun SimpleTopBar(title: String, onBack: () -> Unit) {- TopAppBar(- title = { Text(text = title, style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp)) },- navigationIcon = {- IconButton(onClick = onBack) {- Icon(- painter = painterResource(HugeIcons.ArrowLeft01Icon),- contentDescription = "Back"- )- }- },- colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())- )-}--private object HomeRoute {- const val Chat = "chat"- const val Settings = "settings"- const val Logs = "logs"- const val ModelSettings = "model-settings"- const val DeveloperSettings = "developer-settings"-}--@Composable-private fun LogsTopBar(onBack: () -> Unit, onShare: () -> Unit) {- TopAppBar(- title = { Text(text = "Logs", style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp)) },- navigationIcon = {- IconButton(onClick = onBack) {- Icon(- painter = painterResource(HugeIcons.ArrowLeft01Icon),- contentDescription = "Back"- )- }- },- actions = {- IconButton(onClick = onShare) {- Icon(- painter = painterResource(HugeIcons.Upload01Icon),- contentDescription = "Share",- modifier = Modifier.size(18.dp)- )- }- },- colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())- )-}--private fun androidx.compose.animation.AnimatedContentTransitionScope<NavBackStackEntry>.forwardEnter() =- slideInHorizontally(- initialOffsetX = { it },- animationSpec = tween(220)- ) + fadeIn(animationSpec = tween(90))--private fun androidx.compose.animation.AnimatedContentTransitionScope<NavBackStackEntry>.forwardExit() =- slideOutHorizontally(- targetOffsetX = { -it },- animationSpec = tween(220)- ) + fadeOut(animationSpec = tween(90))--private fun androidx.compose.animation.AnimatedContentTransitionScope<NavBackStackEntry>.backEnter() =- slideInHorizontally(- initialOffsetX = { -it },- animationSpec = tween(220)- ) + fadeIn(animationSpec = tween(90))--private fun androidx.compose.animation.AnimatedContentTransitionScope<NavBackStackEntry>.backExit() =- slideOutHorizontally(- targetOffsetX = { it },- animationSpec = tween(220)- ) + fadeOut(animationSpec = tween(90))-private fun buildAttachmentFromUri(context: Context,uri: Uri,diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.ktindex c0af462e86..7412eb230d 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt@@ -2,49 +2,27 @@package io.ente.ensu.auth-import android.content.Intent-import android.net.Uriimport androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.heightimport androidx.compose.material3.CenterAlignedTopAppBarimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.Scaffold-import androidx.compose.material3.Text-import androidx.compose.material3.TextButtonimport androidx.compose.material3.TopAppBarDefaultsimport androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.mutableStateListOf-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember-import androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.painterResource-import androidx.compose.ui.text.input.KeyboardTypeimport androidx.compose.ui.unit.dpimport io.ente.ensu.components.EnsuLogo-import io.ente.ensu.designsystem.HugeIconsimport io.ente.ensu.data.auth.AuthResponsePayloadimport io.ente.ensu.data.auth.EnsuAuthServiceimport io.ente.ensu.data.auth.KeyAttributes-import io.ente.ensu.data.auth.PasskeySessionExpiredException-import io.ente.ensu.data.auth.PasskeySessionNotVerifiedExceptionimport io.ente.ensu.data.auth.SrpAttributes-import io.ente.ensu.data.auth.SrpLoginResultimport io.ente.ensu.designsystem.EnsuColor-import io.ente.ensu.designsystem.EnsuSpacing-import io.ente.ensu.designsystem.EnsuTypography-import kotlinx.coroutines.launch+import io.ente.ensu.designsystem.HugeIconssealed class AuthRoute {data object EmailEntry : AuthRoute()@@ -188,655 +166,3 @@ fun AuthFlowScreen(}}}--@Composable-private fun EmailEntryView(- authService: EnsuAuthService,- onNavigate: (AuthRoute) -> Unit-) {- var email by remember { mutableStateOf("") }- var isLoading by remember { mutableStateOf(false) }- var errorMessage by remember { mutableStateOf<String?>(null) }- val isEmailValid = email.trim().contains("@") && email.trim().contains(".") && email.trim().length >= 5- val scope = rememberCoroutineScope()-- AuthScreen(- content = {- AuthHeader(title = "Welcome back")- Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {- LabeledTextField(- label = "Email",- hint = "Enter your email",- value = email,- onValueChange = { email = it },- keyboardType = KeyboardType.Email- )- if (errorMessage != null) {- Text(- text = errorMessage.orEmpty(),- style = EnsuTypography.small,- color = EnsuColor.error,- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)- )- }- }- },- bottom = {- PrimaryButton(- text = "Log in",- isLoading = isLoading,- isEnabled = isEmailValid && !isLoading- ) {- scope.launch {- if (isLoading) return@launch- isLoading = true- errorMessage = null- try {- val trimmed = email.trim()- val srpAttrs = authService.getSrpAttributes(trimmed)- if (srpAttrs.isEmailMfaEnabled) {- authService.sendOtp(trimmed)- onNavigate(AuthRoute.Otp(trimmed, srpAttrs))- } else {- onNavigate(AuthRoute.Password(trimmed, srpAttrs))- }- } catch (error: Exception) {- errorMessage = "Failed to get account info: ${error.message}"- } finally {- isLoading = false- }- }- }- }- )-}--@Composable-private fun PasswordView(- authService: EnsuAuthService,- email: String,- srpAttributes: SrpAttributes,- onNavigate: (AuthRoute) -> Unit,- onLoggedIn: () -> Unit-) {- var password by remember { mutableStateOf("") }- var showPassword by remember { mutableStateOf(false) }- var isLoading by remember { mutableStateOf(false) }- var errorMessage by remember { mutableStateOf<String?>(null) }- val scope = rememberCoroutineScope()- val hasPassword = password.isNotBlank()-- AuthScreen(- content = {- AuthHeader(title = "Enter password")- AuthSubtitle(text = email)- Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))- PasswordTextField(- label = "Password",- hint = "Enter your password",- value = password,- onValueChange = { password = it },- showPassword = showPassword,- onTogglePassword = { showPassword = !showPassword }- )- if (errorMessage != null) {- Text(- text = errorMessage.orEmpty(),- style = EnsuTypography.small,- color = EnsuColor.error,- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)- )- }- },- bottom = {- PrimaryButton(- text = "Log in",- isLoading = isLoading,- isEnabled = hasPassword && !isLoading- ) {- scope.launch {- if (isLoading) return@launch- isLoading = true- errorMessage = null- try {- val result = authService.loginWithSrp(email, password, srpAttributes)- handleSrpResult(result, email, srpAttributes, password, onNavigate, onLoggedIn)- } catch (error: Exception) {- errorMessage = error.message- } finally {- isLoading = false- }- }- }- }- )-}--@Composable-private fun OtpVerificationView(- authService: EnsuAuthService,- email: String,- srpAttributes: SrpAttributes,- onNavigate: (AuthRoute) -> Unit-) {- var code by remember { mutableStateOf("") }- var isLoading by remember { mutableStateOf(false) }- var errorMessage by remember { mutableStateOf<String?>(null) }- val scope = rememberCoroutineScope()- val hasValidCode = code.trim().length == 6-- fun submitOtp() {- if (!hasValidCode || isLoading) return- scope.launch {- if (isLoading) return@launch- isLoading = true- errorMessage = null- try {- val payload = authService.verifyOtp(email, code)- val keyAttrs = payload.keyAttributes- if (keyAttrs == null) {- errorMessage = "New user signup not implemented. Please use an existing account."- } else if (payload.requiresPasskey) {- onNavigate(- AuthRoute.Passkey(- email = email,- srp = srpAttributes,- sessionId = payload.passkeySessionId.orEmpty(),- accountsUrl = payload.accountsUrl ?: "https://accounts.ente.io",- twoFactorSessionId = payload.twoFactorSessionId,- password = null- )- )- } else if (payload.requiresTwoFactor) {- onNavigate(- AuthRoute.TwoFactor(- email = email,- srp = srpAttributes,- sessionId = payload.twoFactorSessionId.orEmpty(),- password = null- )- )- } else {- onNavigate(- AuthRoute.PasswordAfterMfa(- email = email,- srp = srpAttributes,- userId = payload.userId,- keyAttributes = keyAttrs,- encryptedToken = payload.encryptedToken,- token = payload.token- )- )- }- } catch (error: Exception) {- errorMessage = error.message- } finally {- isLoading = false- }- }- }-- LaunchedEffect(code) {- if (code.trim().length == 6) {- submitOtp()- }- }-- AuthScreen(- content = {- AuthHeader(title = "Verify email", subtitle = email)- Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {- CodeTextField(- value = code,- onValueChange = { code = it },- onComplete = { value -> if (value.length == 6) code = value }- )- TextLink(text = "Resend code") {- scope.launch {- runCatching { authService.sendOtp(email) }- .onFailure { errorMessage = "Failed to resend code: ${it.message}" }- }- }- if (errorMessage != null) {- Text(- text = errorMessage.orEmpty(),- style = EnsuTypography.small,- color = EnsuColor.error,- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)- )- }- }- },- bottom = {- PrimaryButton(- text = "Verify",- isLoading = isLoading,- isEnabled = hasValidCode && !isLoading- ) {- submitOtp()- }- }- )-}--@Composable-private fun TwoFactorView(- authService: EnsuAuthService,- email: String,- srpAttributes: SrpAttributes,- sessionId: String,- password: String?,- onNavigate: (AuthRoute) -> Unit,- onLoggedIn: () -> Unit-) {- var code by remember { mutableStateOf("") }- var isLoading by remember { mutableStateOf(false) }- var errorMessage by remember { mutableStateOf<String?>(null) }- val scope = rememberCoroutineScope()- val hasValidCode = code.trim().length == 6-- fun submitTwoFactor() {- if (!hasValidCode || isLoading) return- scope.launch {- if (isLoading) return@launch- isLoading = true- errorMessage = null- try {- val payload = authService.verifyTwoFactor(sessionId, code)- val keyAttrs = payload.keyAttributes- if (keyAttrs == null) {- errorMessage = "Invalid response"- } else if (!password.isNullOrBlank()) {- authService.loginAfterChallenge(- email = email,- password = password,- srpAttributes = srpAttributes,- userId = payload.userId,- keyAttributes = keyAttrs,- encryptedToken = payload.encryptedToken,- token = payload.token- )- onLoggedIn()- } else {- onNavigate(- AuthRoute.PasswordAfterMfa(- email = email,- srp = srpAttributes,- userId = payload.userId,- keyAttributes = keyAttrs,- encryptedToken = payload.encryptedToken,- token = payload.token- )- )- }- } catch (error: Exception) {- errorMessage = error.message- } finally {- isLoading = false- }- }- }-- LaunchedEffect(code) {- if (code.trim().length == 6) {- submitTwoFactor()- }- }-- AuthScreen(- content = {- AuthHeader(- title = "Two-factor authentication",- subtitle = "Enter the code from your authenticator app"- )- Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {- CodeTextField(- value = code,- onValueChange = { code = it },- onComplete = { value -> if (value.length == 6) code = value }- )- if (errorMessage != null) {- Text(- text = errorMessage.orEmpty(),- style = EnsuTypography.small,- color = EnsuColor.error,- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)- )- }- }- },- bottom = {- PrimaryButton(- text = "Verify",- isLoading = isLoading,- isEnabled = hasValidCode && !isLoading- ) {- submitTwoFactor()- }- }- )-}--@Composable-private fun PasskeyView(- authService: EnsuAuthService,- email: String,- srpAttributes: SrpAttributes,- sessionId: String,- accountsUrl: String,- twoFactorSessionId: String?,- password: String?,- onNavigate: (AuthRoute) -> Unit,- onLoggedIn: () -> Unit-) {- val context = LocalContext.current- var isChecking by remember { mutableStateOf(false) }- var message by remember { mutableStateOf<String?>(null) }- val scope = rememberCoroutineScope()-- LaunchedEffect(sessionId) {- launchPasskey(context, accountsUrl, sessionId)- }-- AuthScreen(- content = {- AuthHeader(- title = "Passkey verification",- subtitle = "Complete passkey verification in browser"- )- Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {- TextLink(text = "Open passkey again") {- launchPasskey(context, accountsUrl, sessionId)- }-- if (!twoFactorSessionId.isNullOrBlank()) {- TextLink(text = "Use authenticator code") {- onNavigate(- AuthRoute.TwoFactor(- email = email,- srp = srpAttributes,- sessionId = twoFactorSessionId,- password = password- )- )- }- }-- if (message != null) {- Text(- text = message.orEmpty(),- style = EnsuTypography.small,- color = EnsuColor.textMuted(),- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)- )- }- }- },- bottom = {- PrimaryButton(- text = "Check status",- isLoading = isChecking,- isEnabled = !isChecking- ) {- scope.launch {- if (isChecking) return@launch- isChecking = true- try {- val payload = authService.getTokenForPasskeySession(sessionId)- handlePasskeyAuthResponse(- authService = authService,- payload = payload,- email = email,- srpAttributes = srpAttributes,- password = password,- onNavigate = onNavigate,- onLoggedIn = onLoggedIn- )- } catch (error: PasskeySessionNotVerifiedException) {- message = "Passkey verification is still pending."- } catch (error: PasskeySessionExpiredException) {- message = "Login session expired."- } catch (error: Exception) {- message = "Failed to check passkey status: ${error.message}"- } finally {- isChecking = false- }- }- }- }- )-}--@Composable-private fun PasswordAfterMfaView(- authService: EnsuAuthService,- email: String,- srpAttributes: SrpAttributes,- userId: Long,- keyAttributes: KeyAttributes,- encryptedToken: String?,- token: String?,- onLoggedIn: () -> Unit-) {- var password by remember { mutableStateOf("") }- var showPassword by remember { mutableStateOf(false) }- var isLoading by remember { mutableStateOf(false) }- var errorMessage by remember { mutableStateOf<String?>(null) }- val scope = rememberCoroutineScope()-- AuthScreen(- content = {- AuthHeader(title = "Enter password")- AuthSubtitle(text = email)- Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))- PasswordTextField(- label = "Password",- hint = "Enter your password",- value = password,- onValueChange = { password = it },- showPassword = showPassword,- onTogglePassword = { showPassword = !showPassword }- )- if (errorMessage != null) {- Text(- text = errorMessage.orEmpty(),- style = EnsuTypography.small,- color = EnsuColor.error,- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)- )- }- },- bottom = {- PrimaryButton(- text = "Continue",- isLoading = isLoading,- isEnabled = password.isNotBlank() && !isLoading- ) {- scope.launch {- if (isLoading) return@launch- isLoading = true- errorMessage = null- try {- authService.loginAfterChallenge(- email = email,- password = password,- srpAttributes = srpAttributes,- userId = userId,- keyAttributes = keyAttributes,- encryptedToken = encryptedToken,- token = token- )- onLoggedIn()- } catch (error: Exception) {- errorMessage = "Incorrect password: ${error.message}"- } finally {- isLoading = false- }- }- }- }- )-}--@Composable-private fun PasskeyPasswordReentryView(- authService: EnsuAuthService,- email: String,- srpAttributes: SrpAttributes,- auth: AuthResponsePayload,- onLoggedIn: () -> Unit-) {- val keyAttributes = auth.keyAttributes- if (keyAttributes == null) {- AuthScreen(- content = {- AuthHeader(title = "Enter password")- AuthSubtitle(text = email)- Text(- text = "Invalid passkey response",- style = EnsuTypography.small,- color = EnsuColor.error,- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)- )- },- bottom = { }- )- return- }-- var password by remember { mutableStateOf("") }- var showPassword by remember { mutableStateOf(false) }- var isLoading by remember { mutableStateOf(false) }- var errorMessage by remember { mutableStateOf<String?>(null) }- val scope = rememberCoroutineScope()-- AuthScreen(- content = {- AuthHeader(title = "Enter password")- AuthSubtitle(text = email)- Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))- PasswordTextField(- label = "Password",- hint = "Enter your password",- value = password,- onValueChange = { password = it },- showPassword = showPassword,- onTogglePassword = { showPassword = !showPassword }- )- if (errorMessage != null) {- Text(- text = errorMessage.orEmpty(),- style = EnsuTypography.small,- color = EnsuColor.error,- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)- )- }- },- bottom = {- PrimaryButton(- text = "Continue",- isLoading = isLoading,- isEnabled = password.isNotBlank() && !isLoading- ) {- scope.launch {- if (isLoading) return@launch- isLoading = true- errorMessage = null- try {- authService.loginAfterChallenge(- email = email,- password = password,- srpAttributes = srpAttributes,- userId = auth.userId,- keyAttributes = keyAttributes,- encryptedToken = auth.encryptedToken,- token = auth.token- )- onLoggedIn()- } catch (error: Exception) {- errorMessage = "Incorrect password: ${error.message}"- } finally {- isLoading = false- }- }- }- }- )-}--private fun handleSrpResult(- result: SrpLoginResult,- email: String,- srpAttributes: SrpAttributes,- password: String,- onNavigate: (AuthRoute) -> Unit,- onLoggedIn: () -> Unit-) {- if (result.requiresPasskey) {- onNavigate(- AuthRoute.Passkey(- email = email,- srp = srpAttributes,- sessionId = result.passkeySessionId.orEmpty(),- accountsUrl = result.accountsUrl ?: "https://accounts.ente.io",- twoFactorSessionId = result.twoFactorSessionId,- password = password- )- )- return- }-- if (result.requiresTwoFactor) {- onNavigate(- AuthRoute.TwoFactor(- email = email,- srp = srpAttributes,- sessionId = result.twoFactorSessionId.orEmpty(),- password = password- )- )- return- }-- onLoggedIn()-}--private suspend fun handlePasskeyAuthResponse(- authService: EnsuAuthService,- payload: AuthResponsePayload,- email: String,- srpAttributes: SrpAttributes,- password: String?,- onNavigate: (AuthRoute) -> Unit,- onLoggedIn: () -> Unit-) {- val keyAttrs = payload.keyAttributes ?: return- if (!password.isNullOrBlank()) {- authService.loginAfterChallenge(- email = email,- password = password,- srpAttributes = srpAttributes,- userId = payload.userId,- keyAttributes = keyAttrs,- encryptedToken = payload.encryptedToken,- token = payload.token- )- onLoggedIn()- } else {- onNavigate(AuthRoute.PasskeyPasswordReentry(email, srpAttributes, payload))- }-}--private fun launchPasskey(context: android.content.Context, accountsUrl: String, sessionId: String) {- val base = accountsUrl.trimEnd('/')- val url = Uri.parse("$base/passkeys/verify")- .buildUpon()- .appendQueryParameter("passkeySessionID", sessionId)- .appendQueryParameter("redirect", "enteensu://passkey")- .appendQueryParameter("clientPackage", context.packageName)- .build()-- val intent = Intent(Intent.ACTION_VIEW, url)- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- context.startActivity(intent)-}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.ktnew file mode 100644index 0000000000..2a5e887f2f--- /dev/null+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthSteps.kt@@ -0,0 +1,648 @@+@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)++package io.ente.ensu.auth++import android.content.Intent+import android.net.Uri+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import io.ente.ensu.data.auth.AuthResponsePayload+import io.ente.ensu.data.auth.EnsuAuthService+import io.ente.ensu.data.auth.KeyAttributes+import io.ente.ensu.data.auth.PasskeySessionExpiredException+import io.ente.ensu.data.auth.PasskeySessionNotVerifiedException+import io.ente.ensu.data.auth.SrpAttributes+import io.ente.ensu.data.auth.SrpLoginResult+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.designsystem.EnsuTypography+import kotlinx.coroutines.launch++@Composable+internal fun EmailEntryView(+ authService: EnsuAuthService,+ onNavigate: (AuthRoute) -> Unit+) {+ var email by remember { mutableStateOf("") }+ val authState = rememberAuthActionState()+ val isEmailValid = email.trim().contains("@") && email.trim().contains(".") && email.trim().length >= 5++ AuthScreen(+ content = {+ AuthHeader(title = "Welcome back")+ Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {+ LabeledTextField(+ label = "Email",+ hint = "Enter your email",+ value = email,+ onValueChange = { email = it },+ keyboardType = KeyboardType.Email+ )+ if (authState.errorMessage != null) {+ Text(+ text = authState.errorMessage.orEmpty(),+ style = EnsuTypography.small,+ color = EnsuColor.error,+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ )+ }+ }+ },+ bottom = {+ PrimaryButton(+ text = "Log in",+ isLoading = authState.isLoading,+ isEnabled = isEmailValid && !authState.isLoading+ ) {+ authState.launch(onError = { "Failed to get account info: ${it.message}" }) {+ val trimmed = email.trim()+ val srpAttrs = authService.getSrpAttributes(trimmed)+ if (srpAttrs.isEmailMfaEnabled) {+ authService.sendOtp(trimmed)+ onNavigate(AuthRoute.Otp(trimmed, srpAttrs))+ } else {+ onNavigate(AuthRoute.Password(trimmed, srpAttrs))+ }+ }+ }+ }+ )+}++@Composable+internal fun PasswordView(+ authService: EnsuAuthService,+ email: String,+ srpAttributes: SrpAttributes,+ onNavigate: (AuthRoute) -> Unit,+ onLoggedIn: () -> Unit+) {+ var password by remember { mutableStateOf("") }+ var showPassword by remember { mutableStateOf(false) }+ val authState = rememberAuthActionState()+ val hasPassword = password.isNotBlank()++ AuthScreen(+ content = {+ AuthHeader(title = "Enter password")+ AuthSubtitle(text = email)+ Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))+ PasswordTextField(+ label = "Password",+ hint = "Enter your password",+ value = password,+ onValueChange = { password = it },+ showPassword = showPassword,+ onTogglePassword = { showPassword = !showPassword }+ )+ if (authState.errorMessage != null) {+ Text(+ text = authState.errorMessage.orEmpty(),+ style = EnsuTypography.small,+ color = EnsuColor.error,+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ )+ }+ },+ bottom = {+ PrimaryButton(+ text = "Log in",+ isLoading = authState.isLoading,+ isEnabled = hasPassword && !authState.isLoading+ ) {+ authState.launch {+ val result = authService.loginWithSrp(email, password, srpAttributes)+ handleSrpResult(result, email, srpAttributes, password, onNavigate, onLoggedIn)+ }+ }+ }+ )+}++@Composable+internal fun OtpVerificationView(+ authService: EnsuAuthService,+ email: String,+ srpAttributes: SrpAttributes,+ onNavigate: (AuthRoute) -> Unit+) {+ var code by remember { mutableStateOf("") }+ val authState = rememberAuthActionState()+ val scope = rememberCoroutineScope()+ val hasValidCode = code.trim().length == 6++ fun submitOtp() {+ if (!hasValidCode || authState.isLoading) return+ authState.launch {+ val payload = authService.verifyOtp(email, code)+ val keyAttrs = payload.keyAttributes+ if (keyAttrs == null) {+ setError("New user signup not implemented. Please use an existing account.")+ } else if (payload.requiresPasskey) {+ onNavigate(+ AuthRoute.Passkey(+ email = email,+ srp = srpAttributes,+ sessionId = payload.passkeySessionId.orEmpty(),+ accountsUrl = payload.accountsUrl ?: "https://accounts.ente.io",+ twoFactorSessionId = payload.twoFactorSessionId,+ password = null+ )+ )+ } else if (payload.requiresTwoFactor) {+ onNavigate(+ AuthRoute.TwoFactor(+ email = email,+ srp = srpAttributes,+ sessionId = payload.twoFactorSessionId.orEmpty(),+ password = null+ )+ )+ } else {+ onNavigate(+ AuthRoute.PasswordAfterMfa(+ email = email,+ srp = srpAttributes,+ userId = payload.userId,+ keyAttributes = keyAttrs,+ encryptedToken = payload.encryptedToken,+ token = payload.token+ )+ )+ }+ }+ }++ LaunchedEffect(code) {+ if (code.trim().length == 6) {+ submitOtp()+ }+ }++ AuthScreen(+ content = {+ AuthHeader(title = "Verify email", subtitle = email)+ Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {+ CodeTextField(+ value = code,+ onValueChange = { code = it },+ onComplete = { value -> if (value.length == 6) code = value }+ )+ TextLink(text = "Resend code") {+ scope.launch {+ runCatching { authService.sendOtp(email) }+ .onFailure { authState.setError("Failed to resend code: ${it.message}") }+ }+ }+ if (authState.errorMessage != null) {+ Text(+ text = authState.errorMessage.orEmpty(),+ style = EnsuTypography.small,+ color = EnsuColor.error,+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ )+ }+ }+ },+ bottom = {+ PrimaryButton(+ text = "Verify",+ isLoading = authState.isLoading,+ isEnabled = hasValidCode && !authState.isLoading+ ) {+ submitOtp()+ }+ }+ )+}++@Composable+internal fun TwoFactorView(+ authService: EnsuAuthService,+ email: String,+ srpAttributes: SrpAttributes,+ sessionId: String,+ password: String?,+ onNavigate: (AuthRoute) -> Unit,+ onLoggedIn: () -> Unit+) {+ var code by remember { mutableStateOf("") }+ val authState = rememberAuthActionState()+ val hasValidCode = code.trim().length == 6++ fun submitTwoFactor() {+ if (!hasValidCode || authState.isLoading) return+ authState.launch {+ val payload = authService.verifyTwoFactor(sessionId, code)+ val keyAttrs = payload.keyAttributes+ if (keyAttrs == null) {+ setError("Invalid response")+ } else if (!password.isNullOrBlank()) {+ authService.loginAfterChallenge(+ email = email,+ password = password,+ srpAttributes = srpAttributes,+ userId = payload.userId,+ keyAttributes = keyAttrs,+ encryptedToken = payload.encryptedToken,+ token = payload.token+ )+ onLoggedIn()+ } else {+ onNavigate(+ AuthRoute.PasswordAfterMfa(+ email = email,+ srp = srpAttributes,+ userId = payload.userId,+ keyAttributes = keyAttrs,+ encryptedToken = payload.encryptedToken,+ token = payload.token+ )+ )+ }+ }+ }++ LaunchedEffect(code) {+ if (code.trim().length == 6) {+ submitTwoFactor()+ }+ }++ AuthScreen(+ content = {+ AuthHeader(+ title = "Two-factor authentication",+ subtitle = "Enter the code from your authenticator app"+ )+ Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {+ CodeTextField(+ value = code,+ onValueChange = { code = it },+ onComplete = { value -> if (value.length == 6) code = value }+ )+ if (authState.errorMessage != null) {+ Text(+ text = authState.errorMessage.orEmpty(),+ style = EnsuTypography.small,+ color = EnsuColor.error,+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ )+ }+ }+ },+ bottom = {+ PrimaryButton(+ text = "Verify",+ isLoading = authState.isLoading,+ isEnabled = hasValidCode && !authState.isLoading+ ) {+ submitTwoFactor()+ }+ }+ )+}++@Composable+internal fun PasskeyView(+ authService: EnsuAuthService,+ email: String,+ srpAttributes: SrpAttributes,+ sessionId: String,+ accountsUrl: String,+ twoFactorSessionId: String?,+ password: String?,+ onNavigate: (AuthRoute) -> Unit,+ onLoggedIn: () -> Unit+) {+ val context = LocalContext.current+ val authState = rememberAuthActionState()++ LaunchedEffect(sessionId) {+ launchPasskey(context, accountsUrl, sessionId)+ }++ AuthScreen(+ content = {+ AuthHeader(+ title = "Passkey verification",+ subtitle = "Complete passkey verification in browser"+ )+ Column(verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(EnsuSpacing.lg.dp)) {+ TextLink(text = "Open passkey again") {+ launchPasskey(context, accountsUrl, sessionId)+ }++ if (!twoFactorSessionId.isNullOrBlank()) {+ TextLink(text = "Use authenticator code") {+ onNavigate(+ AuthRoute.TwoFactor(+ email = email,+ srp = srpAttributes,+ sessionId = twoFactorSessionId,+ password = password+ )+ )+ }+ }++ if (authState.errorMessage != null) {+ Text(+ text = authState.errorMessage.orEmpty(),+ style = EnsuTypography.small,+ color = EnsuColor.textMuted(),+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ )+ }+ }+ },+ bottom = {+ PrimaryButton(+ text = "Check status",+ isLoading = authState.isLoading,+ isEnabled = !authState.isLoading+ ) {+ authState.launch(onError = { "Failed to check passkey status: ${it.message}" }) {+ try {+ val payload = authService.getTokenForPasskeySession(sessionId)+ handlePasskeyAuthResponse(+ authService = authService,+ payload = payload,+ email = email,+ srpAttributes = srpAttributes,+ password = password,+ onNavigate = onNavigate,+ onLoggedIn = onLoggedIn+ )+ } catch (error: PasskeySessionNotVerifiedException) {+ setError("Passkey verification is still pending.")+ } catch (error: PasskeySessionExpiredException) {+ setError("Login session expired.")+ }+ }+ }+ }+ )+}++@Composable+internal fun PasswordAfterMfaView(+ authService: EnsuAuthService,+ email: String,+ srpAttributes: SrpAttributes,+ userId: Long,+ keyAttributes: KeyAttributes,+ encryptedToken: String?,+ token: String?,+ onLoggedIn: () -> Unit+) {+ var password by remember { mutableStateOf("") }+ var showPassword by remember { mutableStateOf(false) }+ val authState = rememberAuthActionState()++ AuthScreen(+ content = {+ AuthHeader(title = "Enter password")+ AuthSubtitle(text = email)+ Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))+ PasswordTextField(+ label = "Password",+ hint = "Enter your password",+ value = password,+ onValueChange = { password = it },+ showPassword = showPassword,+ onTogglePassword = { showPassword = !showPassword }+ )+ if (authState.errorMessage != null) {+ Text(+ text = authState.errorMessage.orEmpty(),+ style = EnsuTypography.small,+ color = EnsuColor.error,+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ )+ }+ },+ bottom = {+ PrimaryButton(+ text = "Continue",+ isLoading = authState.isLoading,+ isEnabled = password.isNotBlank() && !authState.isLoading+ ) {+ authState.launch(onError = { "Incorrect password: ${it.message}" }) {+ authService.loginAfterChallenge(+ email = email,+ password = password,+ srpAttributes = srpAttributes,+ userId = userId,+ keyAttributes = keyAttributes,+ encryptedToken = encryptedToken,+ token = token+ )+ onLoggedIn()+ }+ }+ }+ )+}++@Composable+internal fun PasskeyPasswordReentryView(+ authService: EnsuAuthService,+ email: String,+ srpAttributes: SrpAttributes,+ auth: AuthResponsePayload,+ onLoggedIn: () -> Unit+) {+ val keyAttributes = auth.keyAttributes+ if (keyAttributes == null) {+ AuthScreen(+ content = {+ AuthHeader(title = "Enter password")+ AuthSubtitle(text = email)+ Text(+ text = "Invalid passkey response",+ style = EnsuTypography.small,+ color = EnsuColor.error,+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ )+ },+ bottom = { }+ )+ return+ }++ var password by remember { mutableStateOf("") }+ var showPassword by remember { mutableStateOf(false) }+ val authState = rememberAuthActionState()++ AuthScreen(+ content = {+ AuthHeader(title = "Enter password")+ AuthSubtitle(text = email)+ Spacer(modifier = Modifier.height(EnsuSpacing.xxl.dp))+ PasswordTextField(+ label = "Password",+ hint = "Enter your password",+ value = password,+ onValueChange = { password = it },+ showPassword = showPassword,+ onTogglePassword = { showPassword = !showPassword }+ )+ if (authState.errorMessage != null) {+ Text(+ text = authState.errorMessage.orEmpty(),+ style = EnsuTypography.small,+ color = EnsuColor.error,+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ )+ }+ },+ bottom = {+ PrimaryButton(+ text = "Continue",+ isLoading = authState.isLoading,+ isEnabled = password.isNotBlank() && !authState.isLoading+ ) {+ authState.launch(onError = { "Incorrect password: ${it.message}" }) {+ authService.loginAfterChallenge(+ email = email,+ password = password,+ srpAttributes = srpAttributes,+ userId = auth.userId,+ keyAttributes = keyAttributes,+ encryptedToken = auth.encryptedToken,+ token = auth.token+ )+ onLoggedIn()+ }+ }+ }+ )+}++private class AuthActionState(private val scope: kotlinx.coroutines.CoroutineScope) {+ var isLoading by mutableStateOf(false)+ private set+ var errorMessage by mutableStateOf<String?>(null)+ private set++ fun setError(message: String?) {+ errorMessage = message+ }++ fun launch(+ onError: (Throwable) -> String? = { it.message },+ block: suspend AuthActionState.() -> Unit+ ) {+ if (isLoading) return+ scope.launch {+ if (isLoading) return@launch+ isLoading = true+ errorMessage = null+ try {+ block()+ } catch (error: Throwable) {+ errorMessage = onError(error)+ } finally {+ isLoading = false+ }+ }+ }+}++@Composable+private fun rememberAuthActionState(): AuthActionState {+ val scope = rememberCoroutineScope()+ return remember(scope) { AuthActionState(scope) }+}++private fun handleSrpResult(+ result: SrpLoginResult,+ email: String,+ srpAttributes: SrpAttributes,+ password: String,+ onNavigate: (AuthRoute) -> Unit,+ onLoggedIn: () -> Unit+) {+ if (result.requiresPasskey) {+ onNavigate(+ AuthRoute.Passkey(+ email = email,+ srp = srpAttributes,+ sessionId = result.passkeySessionId.orEmpty(),+ accountsUrl = result.accountsUrl ?: "https://accounts.ente.io",+ twoFactorSessionId = result.twoFactorSessionId,+ password = password+ )+ )+ return+ }++ if (result.requiresTwoFactor) {+ onNavigate(+ AuthRoute.TwoFactor(+ email = email,+ srp = srpAttributes,+ sessionId = result.twoFactorSessionId.orEmpty(),+ password = password+ )+ )+ return+ }++ onLoggedIn()+}++private suspend fun handlePasskeyAuthResponse(+ authService: EnsuAuthService,+ payload: AuthResponsePayload,+ email: String,+ srpAttributes: SrpAttributes,+ password: String?,+ onNavigate: (AuthRoute) -> Unit,+ onLoggedIn: () -> Unit+) {+ val keyAttrs = payload.keyAttributes ?: return+ if (!password.isNullOrBlank()) {+ authService.loginAfterChallenge(+ email = email,+ password = password,+ srpAttributes = srpAttributes,+ userId = payload.userId,+ keyAttributes = keyAttrs,+ encryptedToken = payload.encryptedToken,+ token = payload.token+ )+ onLoggedIn()+ } else {+ onNavigate(AuthRoute.PasskeyPasswordReentry(email, srpAttributes, payload))+ }+}++private fun launchPasskey(context: android.content.Context, accountsUrl: String, sessionId: String) {+ val base = accountsUrl.trimEnd('/')+ val url = Uri.parse("$base/passkeys/verify")+ .buildUpon()+ .appendQueryParameter("passkeySessionID", sessionId)+ .appendQueryParameter("redirect", "enteensu://passkey")+ .appendQueryParameter("clientPackage", context.packageName)+ .build()++ val intent = Intent(Intent.ACTION_VIEW, url)+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ context.startActivity(intent)+}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatInputBar.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatInputBar.ktnew file mode 100644index 0000000000..d256a180ba--- /dev/null+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatInputBar.kt@@ -0,0 +1,314 @@+package io.ente.ensu.chat++import androidx.compose.foundation.ExperimentalLayoutApi+import androidx.compose.foundation.background+import androidx.compose.foundation.focusable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.IntrinsicSize+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.weight+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.rotate+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.unit.dp+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuCornerRadius+import io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.designsystem.EnsuTypography+import io.ente.ensu.designsystem.HugeIcons+import io.ente.ensu.domain.model.Attachment+import io.ente.ensu.domain.model.AttachmentType+import io.ente.ensu.domain.model.ChatMessage+import io.ente.ensu.domain.util.formattedFileSize+import io.ente.ensu.utils.EnsuFeatureFlags+import io.ente.ensu.utils.rememberEnsuHaptics+import kotlinx.coroutines.delay++@OptIn(ExperimentalLayoutApi::class)+@Composable+internal fun MessageInput(+ modifier: Modifier,+ messageText: String,+ attachments: List<Attachment>,+ editingMessage: ChatMessage?,+ isProcessingAttachments: Boolean,+ isGenerating: Boolean,+ isDownloading: Boolean,+ downloadPercent: Int?,+ isAttachmentDownloadBlocked: Boolean,+ attachmentDownloadPercent: Int?,+ onMessageChange: (String) -> Unit,+ onSend: () -> Unit,+ onStop: () -> Unit,+ onAttachmentSelected: (AttachmentType) -> Unit,+ onRemoveAttachment: (Attachment) -> Unit,+ onCancelEdit: () -> Unit,+ focusRequestId: Int+) {+ val haptic = rememberEnsuHaptics()+ val placeholder = when {+ isAttachmentDownloadBlocked -> {+ val percent = attachmentDownloadPercent?.let { " ($it%)" } ?: ""+ "Downloading attachments...$percent"+ }+ else -> "Write a message..."+ }++ val focusRequester = remember { FocusRequester() }+ LaunchedEffect(focusRequestId) {+ if (focusRequestId > 0) {+ // Give the screen a moment to settle so IME shows reliably.+ delay(120)+ focusRequester.requestFocus()+ }+ }++ val hasAttachmentContent = attachments.isNotEmpty() || isProcessingAttachments+ val inputVerticalPadding = if (hasAttachmentContent) EnsuSpacing.xs.dp else 10.dp+ val bottomPadding = if (hasAttachmentContent) EnsuSpacing.sm.dp else EnsuSpacing.md.dp++ Column(+ modifier = modifier+ .background(EnsuColor.backgroundBase()),+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)+ ) {+ if (editingMessage != null) {+ EditBanner(message = editingMessage, onCancelEdit = onCancelEdit)+ }++ if (attachments.isNotEmpty()) {+ val maxAttachmentHeight = 140.dp+ FlowRow(+ modifier = Modifier+ .fillMaxWidth()+ .heightIn(max = maxAttachmentHeight)+ .verticalScroll(rememberScrollState())+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp),+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)+ ) {+ attachments.forEach { attachment ->+ io.ente.ensu.components.AttachmentChip(+ name = attachment.name,+ size = attachment.sizeBytes.formattedFileSize(),+ iconRes = HugeIcons.Attachment01Icon,+ isUploading = attachment.isUploading,+ onDelete = { onRemoveAttachment(attachment) }+ )+ }+ }+ }++ if (isProcessingAttachments) {+ Row(+ modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))+ Text(text = "Reading attachment...", style = EnsuTypography.small)+ }+ }++ Box(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ .padding(bottom = bottomPadding)+ .background(EnsuColor.fillFaint(), RoundedCornerShape((EnsuCornerRadius.input + 4).dp))+ .padding(+ horizontal = EnsuSpacing.inputHorizontal.dp,+ vertical = inputVerticalPadding+ )+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically+ ) {+ BasicTextField(+ value = messageText,+ onValueChange = onMessageChange,+ modifier = Modifier+ .weight(1f)+ .focusRequester(focusRequester)+ .focusable(),+ textStyle = EnsuTypography.message.copy(color = EnsuColor.textPrimary()),+ minLines = 1,+ maxLines = 5,+ keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),+ cursorBrush = SolidColor(EnsuColor.accent())+ ) { innerTextField ->+ Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterStart) {+ if (messageText.isBlank()) {+ Text(+ text = placeholder,+ style = EnsuTypography.message,+ color = EnsuColor.textMuted()+ )+ }+ innerTextField()+ }+ }++ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))++ if (EnsuFeatureFlags.enableImageUploads && editingMessage == null) {+ IconButton(+ onClick = {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ onAttachmentSelected(AttachmentType.Image)+ },+ enabled = !isGenerating && !isDownloading && !isAttachmentDownloadBlocked,+ modifier = Modifier.size(36.dp)+ ) {+ Icon(+ painter = painterResource(HugeIcons.Upload01Icon),+ contentDescription = "Attach",+ modifier = Modifier.size(18.dp)+ )+ }+ }++ val canSend = messageText.isNotBlank() || attachments.isNotEmpty()++ IconButton(+ onClick = {+ if (isGenerating) {+ haptic.perform(HapticFeedbackType.LongPress)+ onStop()+ } else {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ onSend()+ }+ },+ enabled = isGenerating || (!isDownloading && !isAttachmentDownloadBlocked && canSend),+ modifier = Modifier.size(36.dp)+ ) {+ val iconRes = when {+ isGenerating -> HugeIcons.StopIcon+ else -> HugeIcons.Navigation06Icon+ }+ val tint = when {+ isGenerating -> EnsuColor.stopButton+ canSend -> EnsuColor.textPrimary()+ else -> EnsuColor.textMuted()+ }+ val rotation = if (iconRes == HugeIcons.Navigation06Icon) 90f else 0f+ if (iconRes == HugeIcons.StopIcon) {+ Box(+ modifier = Modifier+ .size(22.dp)+ .background(Color.White, CircleShape),+ contentAlignment = Alignment.Center+ ) {+ Icon(+ painter = painterResource(iconRes),+ contentDescription = "Send",+ modifier = Modifier.size(12.dp),+ tint = EnsuColor.stopButton+ )+ }+ } else {+ Icon(+ painter = painterResource(iconRes),+ contentDescription = "Send",+ modifier = Modifier.size(18.dp).rotate(rotation),+ tint = tint+ )+ }+ }+ }+ }+ }+}++@Composable+private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {+ val haptic = rememberEnsuHaptics()+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))+ .height(IntrinsicSize.Min)+ ) {+ Box(+ modifier = Modifier+ .fillMaxHeight()+ .width(3.dp)+ .background(EnsuColor.accent())+ )+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = EnsuSpacing.md.dp, vertical = EnsuSpacing.sm.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Icon(+ painter = painterResource(HugeIcons.Edit01Icon),+ contentDescription = null,+ tint = EnsuColor.accent(),+ modifier = Modifier.size(14.dp)+ )+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))+ Text(+ text = "Editing:",+ style = EnsuTypography.small,+ color = EnsuColor.textMuted()+ )+ Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))+ Text(+ text = message.text,+ style = EnsuTypography.small,+ color = EnsuColor.textPrimary(),+ maxLines = 1,+ overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f)+ )+ IconButton(+ onClick = {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ onCancelEdit()+ },+ modifier = Modifier.size(24.dp)+ ) {+ Icon(+ painter = painterResource(HugeIcons.Cancel01Icon),+ contentDescription = "Cancel edit",+ tint = EnsuColor.textMuted()+ )+ }+ }+ }+}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.ktnew file mode 100644index 0000000000..7dc6a325f9--- /dev/null+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt@@ -0,0 +1,755 @@+package io.ente.ensu.chat++import androidx.compose.animation.animateContentSize+import androidx.compose.animation.core.Spring+import androidx.compose.animation.core.spring+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.gestures.scrollBy+import androidx.compose.foundation.isSystemInDarkTheme+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.IntrinsicSize+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.wrapContentSize+import androidx.compose.foundation.layout.weight+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.material3.Button+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.Icon+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.runtime.snapshotFlow+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalClipboardManager+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Popup+import androidx.compose.ui.window.PopupProperties+import io.ente.ensu.components.BranchSwitcher+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuCornerRadius+import io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.designsystem.EnsuTypography+import io.ente.ensu.designsystem.HugeIcons+import io.ente.ensu.domain.model.Attachment+import io.ente.ensu.domain.model.ChatMessage+import io.ente.ensu.domain.model.MessageAuthor+import io.ente.ensu.domain.util.formatBytes+import io.ente.ensu.domain.util.formattedFileSize+import io.ente.ensu.utils.rememberEnsuHaptics+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.collect+import kotlinx.coroutines.flow.distinctUntilChanged+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale+import kotlin.math.roundToInt+import kotlin.math.roundToLong++@Composable+internal fun MessageList(+ modifier: Modifier,+ messages: List<ChatMessage>,+ streamingResponse: String,+ streamingParentId: String?,+ isGenerating: Boolean,+ isModelDownloaded: Boolean,+ isDownloading: Boolean,+ downloadPercent: Int?,+ downloadStatus: String?,+ modelDownloadSizeBytes: Long?,+ branchSelections: Map<String, Int>,+ onEditMessage: (ChatMessage) -> Unit,+ onRetryMessage: (ChatMessage) -> Unit,+ onBranchChange: (String, Int) -> Unit,+ onOpenAttachment: (Attachment) -> Unit,+ onStartDownload: (Boolean) -> Unit+) {+ if (messages.isEmpty() && !isGenerating) {+ if (!isModelDownloaded) {+ DownloadOnboarding(+ modifier = modifier,+ isDownloading = isDownloading,+ downloadPercent = downloadPercent,+ downloadStatus = downloadStatus,+ modelDownloadSizeBytes = modelDownloadSizeBytes,+ onDownload = { onStartDownload(true) }+ )+ } else {+ EmptyState(+ modifier = modifier,+ title = "Welcome",+ subtitle = "Type a message to start chatting"+ )+ }+ return+ }++ val listState = rememberLazyListState(+ initialFirstVisibleItemIndex = if (messages.isNotEmpty()) messages.size else 0+ )+ val haptic = rememberEnsuHaptics()+ var autoScrollEnabled by remember { mutableStateOf(true) }+ var isAutoScrolling by remember { mutableStateOf(false) }+ var lastHapticLength by remember { mutableStateOf(0) }+ var shouldJumpToBottomOnLoad by remember { mutableStateOf(true) }+ var wasAtBottomBeforeResize by remember { mutableStateOf(true) }+ var lastViewportHeight by remember { mutableStateOf(0) }+ var lastUserMessageId by remember { mutableStateOf<String?>(null) }+ val isAtBottom by remember {+ derivedStateOf {+ !listState.canScrollForward+ }+ }++ val lastMessage = messages.lastOrNull()+ LaunchedEffect(isGenerating, lastMessage?.id) {+ if (isGenerating) {+ autoScrollEnabled = true+ lastHapticLength = 0+ }++ if (lastMessage == null) {+ lastUserMessageId = null+ } else if (lastMessage.author == MessageAuthor.User && lastMessage.id != lastUserMessageId) {+ lastUserMessageId = lastMessage.id+ if (!listState.isScrollInProgress || isAtBottom) {+ autoScrollEnabled = true+ }+ }+ }++ LaunchedEffect(messages.size) {+ if (shouldJumpToBottomOnLoad && messages.isNotEmpty()) {+ if (listState.firstVisibleItemIndex != messages.size) {+ listState.scrollToItem(messages.size)+ }+ shouldJumpToBottomOnLoad = false+ }+ }++ LaunchedEffect(listState.isScrollInProgress, isAtBottom, isAutoScrolling) {+ if (listState.isScrollInProgress && !isAtBottom && !isAutoScrolling) {+ autoScrollEnabled = false+ }+ }++ LaunchedEffect(isAtBottom, isGenerating) {+ if (isGenerating && isAtBottom) {+ autoScrollEnabled = true+ }+ }++ LaunchedEffect(streamingResponse, isGenerating) {+ if (!isGenerating) return@LaunchedEffect+ val length = streamingResponse.length+ if (length > lastHapticLength) {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ lastHapticLength = length+ }+ }++ LaunchedEffect(messages.size, streamingResponse, streamingParentId, isGenerating, autoScrollEnabled) {+ if (!autoScrollEnabled) return@LaunchedEffect+ val targetIndex = messages.size+ if (targetIndex >= 0) {+ isAutoScrolling = true+ try {+ if (isGenerating) {+ listState.animateScrollToItem(targetIndex)+ } else {+ listState.scrollToItem(targetIndex)+ }+ } finally {+ isAutoScrolling = false+ }+ }+ }++ LaunchedEffect(listState) {+ snapshotFlow {+ val layoutInfo = listState.layoutInfo+ val viewportHeight = layoutInfo.viewportEndOffset - layoutInfo.viewportStartOffset+ viewportHeight to isAtBottom+ }+ .distinctUntilChanged()+ .collect { (viewportHeight, atBottom) ->+ if (viewportHeight <= 0) {+ return@collect+ }+ if (lastViewportHeight != 0 && viewportHeight != lastViewportHeight) {+ if (wasAtBottomBeforeResize) {+ val totalItems = listState.layoutInfo.totalItemsCount+ if (totalItems > 0) {+ isAutoScrolling = true+ try {+ listState.scrollToItem(totalItems - 1)+ } finally {+ isAutoScrolling = false+ }+ }+ } else if (viewportHeight < lastViewportHeight) {+ val deltaPx = (lastViewportHeight - viewportHeight).toFloat()+ if (deltaPx > 0f) {+ autoScrollEnabled = false+ isAutoScrolling = true+ try {+ listState.scrollBy(deltaPx)+ } finally {+ isAutoScrolling = false+ }+ }+ }+ }+ lastViewportHeight = viewportHeight+ wasAtBottomBeforeResize = atBottom+ }+ }++ LazyColumn(+ modifier = modifier,+ state = listState,+ contentPadding = PaddingValues(+ top = EnsuSpacing.pageVertical.dp,+ bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp+ ),+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)+ ) {+ items(messages, key = { it.id }) { message ->+ Column(+ modifier = Modifier+ .fillMaxWidth()+ ) {+ when (message.author) {+ MessageAuthor.User -> {+ UserMessageBubble(+ message = message,+ branchSelections = branchSelections,+ onEdit = { onEditMessage(message) },+ onBranchChange = onBranchChange,+ onOpenAttachment = onOpenAttachment+ )+ }+ MessageAuthor.Assistant -> {+ AssistantMessageBubble(+ message = message,+ branchSelections = branchSelections,+ onRetry = { onRetryMessage(message) },+ onBranchChange = onBranchChange+ )+ }+ }++ if (isGenerating && streamingParentId == message.id) {+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ StreamingMessageBubble(text = streamingResponse)+ }+ }+ }++ if (isGenerating && streamingParentId == null) {+ item(key = "streaming") {+ StreamingMessageBubble(text = streamingResponse)+ }+ }++ item(key = "bottom") {+ Spacer(modifier = Modifier.height(1.dp))+ }+ }+}++@Composable+private fun EmptyState(+ modifier: Modifier,+ title: String,+ subtitle: String? = null+) {+ Box(+ modifier = modifier.fillMaxSize(),+ contentAlignment = Alignment.Center+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(+ text = title,+ style = EnsuTypography.h2,+ color = EnsuColor.textPrimary(),+ textAlign = TextAlign.Center+ )+ if (subtitle != null) {+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ Text(+ text = subtitle,+ style = EnsuTypography.body,+ color = EnsuColor.textMuted(),+ textAlign = TextAlign.Center+ )+ }+ }+ }+}++@Composable+private fun DownloadOnboarding(+ modifier: Modifier,+ isDownloading: Boolean,+ downloadPercent: Int?,+ downloadStatus: String?,+ modelDownloadSizeBytes: Long?,+ onDownload: () -> Unit+) {+ val haptic = rememberEnsuHaptics()+ val sizeText = modelDownloadSizeBytes?.let { "Approx. ${formatBytes(it)}" } ?: "Approx. size varies by model"+ Box(+ modifier = modifier.fillMaxSize(),+ contentAlignment = Alignment.Center+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(+ text = "Download to begin using the Chat",+ style = EnsuTypography.large,+ color = EnsuColor.textPrimary(),+ textAlign = TextAlign.Center+ )+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))+ if (isDownloading) {+ val statusText = when {+ downloadStatus?.contains("Loading", ignoreCase = true) == true -> downloadStatus+ modelDownloadSizeBytes != null && downloadPercent != null && downloadPercent >= 0 -> {+ val downloadedBytes = (modelDownloadSizeBytes * (downloadPercent / 100f)).roundToLong()+ "Downloading... ${formatBytes(downloadedBytes)} / ${formatBytes(modelDownloadSizeBytes)}"+ }+ !downloadStatus.isNullOrBlank() -> downloadStatus+ else -> "Downloading..."+ }+ Text(+ text = statusText ?: "Downloading...",+ style = EnsuTypography.body,+ color = EnsuColor.textMuted(),+ textAlign = TextAlign.Center+ )+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ val clamped = downloadPercent?.coerceIn(0, 100)+ if (clamped != null) {+ LinearProgressIndicator(+ progress = { clamped / 100f },+ color = EnsuColor.accent(),+ trackColor = EnsuColor.border(),+ modifier = Modifier+ .fillMaxWidth(0.6f)+ .height(6.dp)+ )+ } else {+ LinearProgressIndicator(+ color = EnsuColor.accent(),+ trackColor = EnsuColor.border(),+ modifier = Modifier+ .fillMaxWidth(0.6f)+ .height(6.dp)+ )+ }+ } else {+ Button(+ onClick = {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ onDownload()+ },+ shape = RoundedCornerShape(EnsuCornerRadius.button.dp),+ colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent())+ ) {+ Text(text = "Download", style = EnsuTypography.body, color = EnsuColor.backgroundBase())+ }+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ Text(+ text = sizeText,+ style = EnsuTypography.small,+ color = EnsuColor.textMuted()+ )+ }+ }+ }+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun UserMessageBubble(+ message: ChatMessage,+ branchSelections: Map<String, Int>,+ onEdit: () -> Unit,+ onBranchChange: (String, Int) -> Unit,+ onOpenAttachment: (Attachment) -> Unit+) {+ val clipboard = LocalClipboardManager.current+ val haptic = rememberEnsuHaptics()+ var showMenu by remember { mutableStateOf(false) }+ var pressOffset by remember { mutableStateOf(Offset.Zero) }+ val bubbleShape = RoundedCornerShape(18.dp)+ val bubbleFill = if (isSystemInDarkTheme()) EnsuColor.fillFaint() else EnsuColor.border().copy(alpha = 0.2f)++ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(start = EnsuSpacing.messageBubbleInset.dp),+ horizontalAlignment = Alignment.End+ ) {+ if (message.attachments.isNotEmpty()) {+ FlowRow(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp, Alignment.End),+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)+ ) {+ message.attachments.forEach { attachment ->+ io.ente.ensu.components.AttachmentChip(+ name = attachment.name,+ size = attachment.sizeBytes.formattedFileSize(),+ iconRes = HugeIcons.Attachment01Icon,+ isUploading = attachment.isUploading,+ onClick = { onOpenAttachment(attachment) }+ )+ }+ }+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ }++ Box {+ Column(+ modifier = Modifier+ .background(bubbleFill, bubbleShape)+ .pointerInput(Unit) {+ detectTapGestures(+ onLongPress = { offset ->+ haptic.perform(HapticFeedbackType.LongPress)+ pressOffset = offset+ showMenu = true+ }+ )+ }+ .padding(EnsuSpacing.md.dp)+ ) {+ Text(+ text = message.text,+ style = EnsuTypography.message,+ color = EnsuColor.userMessageText(),+ textAlign = TextAlign.Right+ )+ }++ MessageActionsMenu(+ showMenu = showMenu,+ pressOffset = pressOffset,+ onDismiss = { showMenu = false },+ actions = listOf(+ MessageAction("Edit", HugeIcons.Edit01Icon) {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ onEdit()+ },+ MessageAction("Copy", HugeIcons.Copy01Icon) {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ clipboard.setText(AnnotatedString(message.text))+ }+ )+ )+ }++ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))++ Row(verticalAlignment = Alignment.CenterVertically) {+ Spacer(modifier = Modifier.weight(1f))+ if (message.branchCount > 1) {+ BranchSwitcher(+ currentIndex = branchSelections[message.id] ?: 1,+ totalCount = message.branchCount,+ onPrevious = {+ val current = branchSelections[message.id] ?: 1+ onBranchChange(message.id, (current - 1).coerceAtLeast(1))+ },+ onNext = {+ val current = branchSelections[message.id] ?: 1+ onBranchChange(message.id, (current + 1).coerceAtMost(message.branchCount))+ }+ )+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))+ }+ TimestampText(message.timestampMillis)+ }+ }+}++@Composable+private fun AssistantMessageBubble(+ message: ChatMessage,+ branchSelections: Map<String, Int>,+ onRetry: () -> Unit,+ onBranchChange: (String, Int) -> Unit+) {+ val clipboard = LocalClipboardManager.current+ val haptic = rememberEnsuHaptics()+ var showMenu by remember { mutableStateOf(false) }+ var pressOffset by remember { mutableStateOf(Offset.Zero) }+ Column(+ modifier = Modifier.fillMaxWidth(),+ horizontalAlignment = Alignment.Start+ ) {+ Box {+ Column(+ modifier = Modifier+ .pointerInput(Unit) {+ detectTapGestures(+ onLongPress = { offset ->+ haptic.perform(HapticFeedbackType.LongPress)+ pressOffset = offset+ showMenu = true+ }+ )+ }+ .padding(horizontal = EnsuSpacing.sm.dp, vertical = EnsuSpacing.md.dp)+ ) {+ MarkdownView(markdown = message.text, enableSelection = false)++ if (message.isInterrupted) {+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))+ Text(+ text = "Interrupted",+ style = EnsuTypography.small,+ color = EnsuColor.textMuted()+ )+ }+ }++ MessageActionsMenu(+ showMenu = showMenu,+ pressOffset = pressOffset,+ onDismiss = { showMenu = false },+ actions = listOf(+ MessageAction("Copy", HugeIcons.Copy01Icon) {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ clipboard.setText(AnnotatedString(message.text))+ },+ MessageAction("Retry", HugeIcons.RepeatIcon) {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ onRetry()+ }+ )+ )+ }++ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))++ Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp), verticalAlignment = Alignment.CenterVertically) {+ TimestampText(message.timestampMillis)+ if (message.branchCount > 1) {+ BranchSwitcher(+ currentIndex = branchSelections[message.id] ?: 1,+ totalCount = message.branchCount,+ onPrevious = {+ val current = branchSelections[message.id] ?: 1+ onBranchChange(message.id, (current - 1).coerceAtLeast(1))+ },+ onNext = {+ val current = branchSelections[message.id] ?: 1+ onBranchChange(message.id, (current + 1).coerceAtMost(message.branchCount))+ }+ )+ }+ }+ }+}++private data class MessageAction(+ val label: String,+ val iconRes: Int,+ val onClick: () -> Unit+)++@Composable+private fun MessageActionsMenu(+ showMenu: Boolean,+ pressOffset: Offset,+ onDismiss: () -> Unit,+ actions: List<MessageAction>+) {+ if (!showMenu) return+ val menuSurface = if (isSystemInDarkTheme()) Color(0xFF1C1C1E) else Color.White+ val offset = IntOffset(pressOffset.x.roundToInt(), pressOffset.y.roundToInt())++ Popup(+ alignment = Alignment.TopStart,+ offset = offset,+ onDismissRequest = onDismiss,+ properties = PopupProperties(focusable = true)+ ) {+ Surface(+ modifier = Modifier.wrapContentSize(),+ color = menuSurface,+ shadowElevation = 4.dp,+ shape = RoundedCornerShape(12.dp)+ ) {+ Column(+ modifier = Modifier+ .width(IntrinsicSize.Min)+ .padding(vertical = EnsuSpacing.xs.dp)+ ) {+ actions.forEach { action ->+ DropdownMenuItem(+ text = {+ Text(+ text = action.label,+ style = EnsuTypography.body,+ color = EnsuColor.textPrimary()+ )+ },+ leadingIcon = {+ Icon(+ painter = androidx.compose.ui.res.painterResource(action.iconRes),+ contentDescription = null,+ modifier = Modifier.size(18.dp),+ tint = EnsuColor.textPrimary()+ )+ },+ onClick = {+ onDismiss()+ action.onClick()+ }+ )+ }+ }+ }+ }+}++@Composable+private fun StreamingMessageBubble(text: String) {+ var showCursor by remember { mutableStateOf(true) }+ val shouldBlink = text.isNotBlank()++ LaunchedEffect(shouldBlink) {+ if (!shouldBlink) {+ showCursor = true+ return@LaunchedEffect+ }+ while (true) {+ delay(520)+ showCursor = !showCursor+ }+ }++ Column(+ modifier = Modifier.fillMaxWidth(),+ horizontalAlignment = Alignment.Start+ ) {+ Column(+ modifier = Modifier+ .animateContentSize(+ animationSpec = spring(+ dampingRatio = 0.9f,+ stiffness = Spring.StiffnessMediumLow+ )+ )+ .padding(horizontal = EnsuSpacing.sm.dp, vertical = EnsuSpacing.md.dp)+ ) {+ if (text.isBlank()) {+ LoadingDotsText()+ } else {+ MarkdownView(markdown = text, enableSelection = false, trailingCursor = showCursor)+ }+ }+ }+}++@Composable+private fun LoadingDotsText() {+ var dotCount by remember { mutableStateOf(1) }+ val phrase = remember { randomLoadingPhrase() }++ LaunchedEffect(Unit) {+ while (true) {+ delay(450)+ dotCount = if (dotCount == 3) 1 else dotCount + 1+ }+ }++ Text(+ text = phrase + ".".repeat(dotCount),+ style = EnsuTypography.message,+ color = EnsuColor.textMuted()+ )+}++private fun randomLoadingPhrase(): String {+ val verb = loadingPhraseVerbs.random()+ val target = loadingPhraseTargets.random()+ return "$verb $target"+}++private val loadingPhraseVerbs = listOf(+ "Generating",+ "Thinking through",+ "Assembling",+ "Drafting",+ "Composing",+ "Crunching",+ "Exploring",+ "Piecing together",+ "Reviewing",+ "Organizing",+ "Synthesizing",+ "Sketching",+ "Refining",+ "Shaping"+)++private val loadingPhraseTargets = listOf(+ "your reply",+ "an answer",+ "ideas",+ "context",+ "details",+ "the response",+ "the next steps",+ "a solution",+ "the summary",+ "insights",+ "the draft",+ "the explanation"+)++@Composable+private fun TimestampText(timestampMillis: Long) {+ Text(+ text = timestampFormatter.format(Date(timestampMillis)),+ style = EnsuTypography.mini,+ color = EnsuColor.textMuted()+ )+}++private val timestampFormatter = SimpleDateFormat("h:mm a", Locale.getDefault())diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatOverlays.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatOverlays.ktnew file mode 100644index 0000000000..84569e6ac6--- /dev/null+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatOverlays.kt@@ -0,0 +1,135 @@+package io.ente.ensu.chat++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.weight+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.hapticfeedback.HapticFeedbackType+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.unit.dp+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuCornerRadius+import io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.designsystem.EnsuTypography+import io.ente.ensu.designsystem.HugeIcons+import io.ente.ensu.domain.state.OverflowDialogState+import io.ente.ensu.utils.rememberEnsuHaptics++@Composable+internal fun OverflowDialog(+ state: OverflowDialogState,+ onTrim: () -> Unit,+ onIncreaseContext: () -> Unit,+ onCancel: () -> Unit+) {+ AlertDialog(+ onDismissRequest = onCancel,+ title = { Text(text = "Context limit reached", style = EnsuTypography.h3) },+ text = {+ Text(+ text = "Input uses ${state.inputTokens} tokens (budget ${state.inputBudget}). Trim history or increase context size?",+ style = EnsuTypography.body,+ color = EnsuColor.textPrimary()+ )+ },+ confirmButton = {+ TextButton(onClick = onTrim) {+ Text(text = "Trim history", color = EnsuColor.textPrimary())+ }+ },+ dismissButton = {+ Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {+ TextButton(onClick = onIncreaseContext) {+ Text(text = "Increase context", color = EnsuColor.textPrimary())+ }+ TextButton(onClick = onCancel) {+ Text(text = "Cancel", color = EnsuColor.textMuted())+ }+ }+ },+ containerColor = EnsuColor.backgroundBase()+ )+}++@Composable+internal fun DownloadToastOverlay(+ status: String,+ percent: Int,+ isLoading: Boolean,+ onCancel: () -> Unit+) {+ val haptic = rememberEnsuHaptics()+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = EnsuSpacing.lg.dp),+ contentAlignment = Alignment.TopCenter+ ) {+ val title = if (isLoading) "Loading model" else "Downloading model"+ val clamped = percent.coerceIn(0, 100)+ Column(+ modifier = Modifier+ .padding(horizontal = EnsuSpacing.lg.dp)+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.toast.dp))+ .padding(EnsuSpacing.lg.dp)+ .fillMaxWidth()+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(text = title, style = EnsuTypography.large, color = EnsuColor.textPrimary())+ Spacer(modifier = Modifier.weight(1f))+ IconButton(+ onClick = {+ haptic.perform(HapticFeedbackType.LongPress)+ onCancel()+ },+ modifier = Modifier.size(28.dp)+ ) {+ Box(+ modifier = Modifier+ .size(22.dp)+ .background(EnsuColor.textPrimary(), CircleShape),+ contentAlignment = Alignment.Center+ ) {+ Icon(+ painter = painterResource(HugeIcons.StopIcon),+ contentDescription = "Cancel download",+ modifier = Modifier.size(12.dp),+ tint = EnsuColor.stopButton+ )+ }+ }+ }+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ LinearProgressIndicator(+ progress = { clamped / 100f },+ color = if (isLoading) EnsuColor.accent() else EnsuColor.accent(),+ trackColor = EnsuColor.border(),+ modifier = Modifier.fillMaxWidth()+ )+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(text = status, style = EnsuTypography.small, color = EnsuColor.textMuted())+ Spacer(modifier = Modifier.weight(1f))+ Text(text = "$clamped%", style = EnsuTypography.mini, color = EnsuColor.textMuted())+ }+ }+ }+}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.ktindex e9ac5dd1c5..2aeab128bf 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt@@ -1,61 +1,22 @@package io.ente.ensu.chatimport androidx.compose.animation.AnimatedContent+import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.tweenimport androidx.compose.animation.fadeInimport androidx.compose.animation.fadeOutimport androidx.compose.animation.slideInVerticallyimport androidx.compose.animation.slideOutVerticallyimport androidx.compose.animation.togetherWith-import androidx.compose.animation.core.FastOutSlowInEasing-import androidx.compose.animation.core.Spring-import androidx.compose.animation.core.spring-import androidx.compose.animation.core.tween-import androidx.compose.animation.animateContentSizeimport androidx.compose.foundation.background-import androidx.compose.foundation.focusable-import androidx.compose.foundation.gestures.detectTapGestures-import androidx.compose.foundation.gestures.scrollBy-import androidx.compose.foundation.isSystemInDarkTheme-import androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.ExperimentalLayoutApi-import androidx.compose.foundation.layout.FlowRow-import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.IntrinsicSize-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.imePaddingimport androidx.compose.foundation.layout.navigationBarsPaddingimport androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.layout.width-import androidx.compose.foundation.layout.wrapContentSize-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.material3.AlertDialog-import androidx.compose.material3.TextButton-import androidx.compose.foundation.lazy.rememberLazyListState-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.shape.CircleShape-import androidx.compose.foundation.shape.RoundedCornerShape-import androidx.compose.foundation.text.BasicTextField-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.CircularProgressIndicator-import androidx.compose.material3.DropdownMenu-import androidx.compose.material3.DropdownMenuItem-import androidx.compose.material3.Icon-import androidx.compose.material3.IconButton-import androidx.compose.material3.LinearProgressIndicator-import androidx.compose.material3.Text+import androidx.compose.foundation.layout.weightimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.derivedStateOf@@ -63,52 +24,14 @@ import androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValue-import androidx.compose.runtime.snapshotFlow-import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier-import androidx.compose.ui.draw.rotate-import androidx.compose.ui.focus.FocusRequester-import androidx.compose.ui.focus.focusRequester-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.SolidColor-import androidx.compose.ui.hapticfeedback.HapticFeedbackType-import androidx.compose.ui.input.pointer.pointerInput-import androidx.compose.ui.platform.LocalClipboardManagerimport androidx.compose.ui.platform.LocalFocusManager-import androidx.compose.ui.res.painterResource-import androidx.compose.material3.Surface-import androidx.compose.ui.text.AnnotatedString-import androidx.compose.ui.text.input.KeyboardCapitalization-import androidx.compose.ui.text.style.TextAlign-import androidx.compose.ui.text.style.TextOverflow-import androidx.compose.ui.unit.IntOffset-import androidx.compose.ui.unit.dp-import androidx.compose.ui.window.Popup-import androidx.compose.ui.window.PopupProperties-import kotlin.math.roundToInt-import io.ente.ensu.components.BranchSwitcherimport io.ente.ensu.designsystem.EnsuColor-import io.ente.ensu.designsystem.EnsuCornerRadius-import io.ente.ensu.designsystem.HugeIconsimport io.ente.ensu.designsystem.EnsuSpacing-import io.ente.ensu.designsystem.EnsuTypographyimport io.ente.ensu.domain.model.Attachment-import io.ente.ensu.utils.EnsuFeatureFlags-import io.ente.ensu.utils.rememberEnsuHapticsimport io.ente.ensu.domain.model.AttachmentTypeimport io.ente.ensu.domain.model.ChatMessage-import io.ente.ensu.domain.model.MessageAuthorimport io.ente.ensu.domain.state.ChatState-import io.ente.ensu.domain.state.OverflowDialogState-import io.ente.ensu.domain.util.formatBytes-import java.text.SimpleDateFormat-import java.util.Date-import java.util.Locale-import kotlin.math.roundToLong-import kotlinx.coroutines.delay-import kotlinx.coroutines.flow.collect-import kotlinx.coroutines.flow.distinctUntilChanged@Composablefun ChatView(@@ -130,9 +53,17 @@ fun ChatView(onOverflowIncreaseContext: () -> Unit,onOverflowCancel: () -> Unit) {- val showDownloadOnboarding = !chatState.isModelDownloaded &&- chatState.messages.isEmpty() &&- !chatState.isGenerating+ val showDownloadOnboarding by remember(+ chatState.isModelDownloaded,+ chatState.messages,+ chatState.isGenerating+ ) {+ derivedStateOf {+ !chatState.isModelDownloaded &&+ chatState.messages.isEmpty() &&+ !chatState.isGenerating+ }+ }val focusManager = LocalFocusManager.currentvar didAutoFocusInput by remember { mutableStateOf(false) }@@ -172,9 +103,17 @@ fun ChatView(}}- val shouldAutoDownload = chatState.hasRequestedModelDownload &&- !chatState.isDownloading &&- !chatState.isGenerating+ val shouldAutoDownload by remember(+ chatState.hasRequestedModelDownload,+ chatState.isDownloading,+ chatState.isGenerating+ ) {+ derivedStateOf {+ chatState.hasRequestedModelDownload &&+ !chatState.isDownloading &&+ !chatState.isGenerating+ }+ }LaunchedEffect(chatState.isModelDownloaded, shouldAutoDownload) {if (!chatState.isModelDownloaded && shouldAutoDownload) {@@ -184,6 +123,14 @@ fun ChatView(val sessionKey = chatState.currentSessionId ?: "new-session"+ val editingMessage by remember(chatState.editingMessageId, chatState.messages) {+ derivedStateOf {+ chatState.editingMessageId?.let { editingId ->+ chatState.messages.firstOrNull { it.id == editingId }+ }+ }+ }+Box(modifier = Modifier.fillMaxSize()) {Column(modifier = Modifier@@ -241,10 +188,6 @@ fun ChatView()}- val editingMessage = chatState.editingMessageId?.let { editingId ->- chatState.messages.firstOrNull { it.id == editingId }- }-if (!showDownloadOnboarding) {MessageInput(modifier = Modifier@@ -276,10 +219,14 @@ fun ChatView(val status = chatState.downloadStatusval isLoading = status?.contains("Loading", ignoreCase = true) == true- val showToast = !showDownloadOnboarding &&- status != null &&- chatState.isDownloading &&- !isLoading+ val showToast by remember(status, chatState.isDownloading, showDownloadOnboarding, isLoading) {+ derivedStateOf {+ !showDownloadOnboarding &&+ status != null &&+ chatState.isDownloading &&+ !isLoading+ }+ }if (showToast) {DownloadToastOverlay(status = status ?: "",@@ -290,1041 +237,3 @@ fun ChatView(}}}--@Composable-private fun MessageList(- modifier: Modifier,- messages: List<ChatMessage>,- streamingResponse: String,- streamingParentId: String?,- isGenerating: Boolean,- isModelDownloaded: Boolean,- isDownloading: Boolean,- downloadPercent: Int?,- downloadStatus: String?,- modelDownloadSizeBytes: Long?,- branchSelections: Map<String, Int>,- onEditMessage: (ChatMessage) -> Unit,- onRetryMessage: (ChatMessage) -> Unit,- onBranchChange: (String, Int) -> Unit,- onOpenAttachment: (Attachment) -> Unit,- onStartDownload: (Boolean) -> Unit-) {- if (messages.isEmpty() && !isGenerating) {- if (!isModelDownloaded) {- DownloadOnboarding(- modifier = modifier,- isDownloading = isDownloading,- downloadPercent = downloadPercent,- downloadStatus = downloadStatus,- modelDownloadSizeBytes = modelDownloadSizeBytes,- onDownload = { onStartDownload(true) }- )- } else {- EmptyState(- modifier = modifier,- title = "Welcome",- subtitle = "Type a message to start chatting"- )- }- return- }-- val listState = rememberLazyListState(- initialFirstVisibleItemIndex = if (messages.isNotEmpty()) messages.size else 0- )- val haptic = rememberEnsuHaptics()- var autoScrollEnabled by remember { mutableStateOf(true) }- var isAutoScrolling by remember { mutableStateOf(false) }- var lastHapticLength by remember { mutableStateOf(0) }- var shouldJumpToBottomOnLoad by remember { mutableStateOf(true) }- var wasAtBottomBeforeResize by remember { mutableStateOf(true) }- var lastViewportHeight by remember { mutableStateOf(0) }- var lastUserMessageId by remember { mutableStateOf<String?>(null) }- val isAtBottom by remember {- derivedStateOf {- !listState.canScrollForward- }- }-- val lastMessage = messages.lastOrNull()- LaunchedEffect(isGenerating, lastMessage?.id) {- if (isGenerating) {- autoScrollEnabled = true- lastHapticLength = 0- }-- if (lastMessage == null) {- lastUserMessageId = null- } else if (lastMessage.author == MessageAuthor.User && lastMessage.id != lastUserMessageId) {- lastUserMessageId = lastMessage.id- if (!listState.isScrollInProgress || isAtBottom) {- autoScrollEnabled = true- }- }- }-- LaunchedEffect(messages.size) {- if (shouldJumpToBottomOnLoad && messages.isNotEmpty()) {- if (listState.firstVisibleItemIndex != messages.size) {- listState.scrollToItem(messages.size)- }- shouldJumpToBottomOnLoad = false- }- }-- LaunchedEffect(listState.isScrollInProgress, isAtBottom, isAutoScrolling) {- if (listState.isScrollInProgress && !isAtBottom && !isAutoScrolling) {- autoScrollEnabled = false- }- }-- LaunchedEffect(isAtBottom, isGenerating) {- if (isGenerating && isAtBottom) {- autoScrollEnabled = true- }- }-- LaunchedEffect(streamingResponse, isGenerating) {- if (!isGenerating) return@LaunchedEffect- val length = streamingResponse.length- if (length > lastHapticLength) {- haptic.perform(HapticFeedbackType.TextHandleMove)- lastHapticLength = length- }- }-- LaunchedEffect(messages.size, streamingResponse, streamingParentId, isGenerating, autoScrollEnabled) {- if (!autoScrollEnabled) return@LaunchedEffect- val targetIndex = messages.size- if (targetIndex >= 0) {- isAutoScrolling = true- try {- if (isGenerating) {- listState.animateScrollToItem(targetIndex)- } else {- listState.scrollToItem(targetIndex)- }- } finally {- isAutoScrolling = false- }- }- }-- LaunchedEffect(listState) {- snapshotFlow {- val layoutInfo = listState.layoutInfo- val viewportHeight = layoutInfo.viewportEndOffset - layoutInfo.viewportStartOffset- viewportHeight to isAtBottom- }- .distinctUntilChanged()- .collect { (viewportHeight, atBottom) ->- if (viewportHeight <= 0) {- return@collect- }- if (lastViewportHeight != 0 && viewportHeight != lastViewportHeight) {- if (wasAtBottomBeforeResize) {- val totalItems = listState.layoutInfo.totalItemsCount- if (totalItems > 0) {- isAutoScrolling = true- try {- listState.scrollToItem(totalItems - 1)- } finally {- isAutoScrolling = false- }- }- } else if (viewportHeight < lastViewportHeight) {- val deltaPx = (lastViewportHeight - viewportHeight).toFloat()- if (deltaPx > 0f) {- autoScrollEnabled = false- isAutoScrolling = true- try {- listState.scrollBy(deltaPx)- } finally {- isAutoScrolling = false- }- }- }- }- lastViewportHeight = viewportHeight- wasAtBottomBeforeResize = atBottom- }- }-- LazyColumn(- modifier = modifier,- state = listState,- contentPadding = PaddingValues(- top = EnsuSpacing.pageVertical.dp,- bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp- ),- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)- ) {- items(messages, key = { it.id }) { message ->- Column(- modifier = Modifier- .fillMaxWidth()- ) {- when (message.author) {- MessageAuthor.User -> {- UserMessageBubble(- message = message,- branchSelections = branchSelections,- onEdit = { onEditMessage(message) },- onBranchChange = onBranchChange,- onOpenAttachment = onOpenAttachment- )- }- MessageAuthor.Assistant -> {- AssistantMessageBubble(- message = message,- branchSelections = branchSelections,- onRetry = { onRetryMessage(message) },- onBranchChange = onBranchChange- )- }- }-- if (isGenerating && streamingParentId == message.id) {- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))- StreamingMessageBubble(text = streamingResponse)- }- }- }-- if (isGenerating && streamingParentId == null) {- item(key = "streaming") {- StreamingMessageBubble(text = streamingResponse)- }- }-- item(key = "bottom") {- Spacer(modifier = Modifier.height(1.dp))- }- }-}--@Composable-private fun EmptyState(- modifier: Modifier,- title: String,- subtitle: String? = null-) {- Box(- modifier = modifier.fillMaxSize(),- contentAlignment = Alignment.Center- ) {- Column(horizontalAlignment = Alignment.CenterHorizontally) {- Text(- text = title,- style = EnsuTypography.h2,- color = EnsuColor.textPrimary(),- textAlign = TextAlign.Center- )- if (subtitle != null) {- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))- Text(- text = subtitle,- style = EnsuTypography.body,- color = EnsuColor.textMuted(),- textAlign = TextAlign.Center- )- }- }- }-}--@Composable-private fun DownloadOnboarding(- modifier: Modifier,- isDownloading: Boolean,- downloadPercent: Int?,- downloadStatus: String?,- modelDownloadSizeBytes: Long?,- onDownload: () -> Unit-) {- val haptic = rememberEnsuHaptics()- val sizeText = modelDownloadSizeBytes?.let { "Approx. ${formatBytes(it)}" } ?: "Approx. size varies by model"- Box(- modifier = modifier.fillMaxSize(),- contentAlignment = Alignment.Center- ) {- Column(horizontalAlignment = Alignment.CenterHorizontally) {- Text(- text = "Download to begin using the Chat",- style = EnsuTypography.large,- color = EnsuColor.textPrimary(),- textAlign = TextAlign.Center- )- Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))- if (isDownloading) {- val statusText = when {- downloadStatus?.contains("Loading", ignoreCase = true) == true -> downloadStatus- modelDownloadSizeBytes != null && downloadPercent != null && downloadPercent >= 0 -> {- val downloadedBytes = (modelDownloadSizeBytes * (downloadPercent / 100f)).roundToLong()- "Downloading... ${formatBytes(downloadedBytes)} / ${formatBytes(modelDownloadSizeBytes)}"- }- !downloadStatus.isNullOrBlank() -> downloadStatus- else -> "Downloading..."- }- Text(- text = statusText ?: "Downloading...",- style = EnsuTypography.body,- color = EnsuColor.textMuted(),- textAlign = TextAlign.Center- )- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))- val clamped = downloadPercent?.coerceIn(0, 100)- if (clamped != null) {- LinearProgressIndicator(- progress = { clamped / 100f },- color = EnsuColor.accent(),- trackColor = EnsuColor.border(),- modifier = Modifier- .fillMaxWidth(0.6f)- .height(6.dp)- )- } else {- LinearProgressIndicator(- color = EnsuColor.accent(),- trackColor = EnsuColor.border(),- modifier = Modifier- .fillMaxWidth(0.6f)- .height(6.dp)- )- }- } else {- Button(- onClick = {- haptic.perform(HapticFeedbackType.TextHandleMove)- onDownload()- },- shape = RoundedCornerShape(EnsuCornerRadius.button.dp),- colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent())- ) {- Text(text = "Download", style = EnsuTypography.body, color = EnsuColor.backgroundBase())- }- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))- Text(- text = sizeText,- style = EnsuTypography.small,- color = EnsuColor.textMuted()- )- }- }- }-}--@Composable-private fun OverflowDialog(- state: OverflowDialogState,- onTrim: () -> Unit,- onIncreaseContext: () -> Unit,- onCancel: () -> Unit-) {- AlertDialog(- onDismissRequest = onCancel,- title = { Text(text = "Context limit reached", style = EnsuTypography.h3) },- text = {- Text(- text = "Input uses ${state.inputTokens} tokens (budget ${state.inputBudget}). Trim history or increase context size?",- style = EnsuTypography.body,- color = EnsuColor.textPrimary()- )- },- confirmButton = {- TextButton(onClick = onTrim) {- Text(text = "Trim history", color = EnsuColor.textPrimary())- }- },- dismissButton = {- Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {- TextButton(onClick = onIncreaseContext) {- Text(text = "Increase context", color = EnsuColor.textPrimary())- }- TextButton(onClick = onCancel) {- Text(text = "Cancel", color = EnsuColor.textMuted())- }- }- },- containerColor = EnsuColor.backgroundBase()- )-}--@OptIn(ExperimentalLayoutApi::class)-@Composable-private fun UserMessageBubble(- message: ChatMessage,- branchSelections: Map<String, Int>,- onEdit: () -> Unit,- onBranchChange: (String, Int) -> Unit,- onOpenAttachment: (Attachment) -> Unit-) {- val clipboard = LocalClipboardManager.current- val haptic = rememberEnsuHaptics()- var showMenu by remember { mutableStateOf(false) }- var pressOffset by remember { mutableStateOf(Offset.Zero) }- val bubbleShape = RoundedCornerShape(18.dp)- val bubbleFill = if (isSystemInDarkTheme()) EnsuColor.fillFaint() else EnsuColor.border().copy(alpha = 0.2f)-- Column(- modifier = Modifier- .fillMaxWidth()- .padding(start = EnsuSpacing.messageBubbleInset.dp),- horizontalAlignment = Alignment.End- ) {- if (message.attachments.isNotEmpty()) {- FlowRow(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp, Alignment.End),- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)- ) {- message.attachments.forEach { attachment ->- io.ente.ensu.components.AttachmentChip(- name = attachment.name,- size = "${attachment.sizeBytes / 1024} KB",- iconRes = HugeIcons.Attachment01Icon,- isUploading = attachment.isUploading,- onClick = { onOpenAttachment(attachment) }- )- }- }- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))- }-- Box {- Column(- modifier = Modifier- .background(bubbleFill, bubbleShape)- .pointerInput(Unit) {- detectTapGestures(- onLongPress = { offset ->- haptic.perform(HapticFeedbackType.LongPress)- pressOffset = offset- showMenu = true- }- )- }- .padding(EnsuSpacing.md.dp)- ) {- Text(- text = message.text,- style = EnsuTypography.message,- color = EnsuColor.userMessageText(),- textAlign = TextAlign.Right- )- }-- MessageActionsMenu(- showMenu = showMenu,- pressOffset = pressOffset,- onDismiss = { showMenu = false },- actions = listOf(- MessageAction("Edit", HugeIcons.Edit01Icon) {- haptic.perform(HapticFeedbackType.TextHandleMove)- onEdit()- },- MessageAction("Copy", HugeIcons.Copy01Icon) {- haptic.perform(HapticFeedbackType.TextHandleMove)- clipboard.setText(AnnotatedString(message.text))- }- )- )- }-- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))-- Row(verticalAlignment = Alignment.CenterVertically) {- Spacer(modifier = Modifier.weight(1f))- if (message.branchCount > 1) {- BranchSwitcher(- currentIndex = branchSelections[message.id] ?: 1,- totalCount = message.branchCount,- onPrevious = {- val current = branchSelections[message.id] ?: 1- onBranchChange(message.id, (current - 1).coerceAtLeast(1))- },- onNext = {- val current = branchSelections[message.id] ?: 1- onBranchChange(message.id, (current + 1).coerceAtMost(message.branchCount))- }- )- Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))- }- TimestampText(message.timestampMillis)- }- }-}--@Composable-private fun AssistantMessageBubble(- message: ChatMessage,- branchSelections: Map<String, Int>,- onRetry: () -> Unit,- onBranchChange: (String, Int) -> Unit-) {- val clipboard = LocalClipboardManager.current- val haptic = rememberEnsuHaptics()- var showMenu by remember { mutableStateOf(false) }- var pressOffset by remember { mutableStateOf(Offset.Zero) }- Column(- modifier = Modifier.fillMaxWidth(),- horizontalAlignment = Alignment.Start- ) {- Box {- Column(- modifier = Modifier- .pointerInput(Unit) {- detectTapGestures(- onLongPress = { offset ->- haptic.perform(HapticFeedbackType.LongPress)- pressOffset = offset- showMenu = true- }- )- }- .padding(horizontal = EnsuSpacing.sm.dp, vertical = EnsuSpacing.md.dp)- ) {- MarkdownView(markdown = message.text, enableSelection = false)-- if (message.isInterrupted) {- Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))- Text(- text = "Interrupted",- style = EnsuTypography.small,- color = EnsuColor.textMuted()- )- }- }-- MessageActionsMenu(- showMenu = showMenu,- pressOffset = pressOffset,- onDismiss = { showMenu = false },- actions = listOf(- MessageAction("Copy", HugeIcons.Copy01Icon) {- haptic.perform(HapticFeedbackType.TextHandleMove)- clipboard.setText(AnnotatedString(message.text))- },- MessageAction("Retry", HugeIcons.RepeatIcon) {- haptic.perform(HapticFeedbackType.TextHandleMove)- onRetry()- }- )- )- }-- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))-- Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp), verticalAlignment = Alignment.CenterVertically) {- TimestampText(message.timestampMillis)- if (message.branchCount > 1) {- BranchSwitcher(- currentIndex = branchSelections[message.id] ?: 1,- totalCount = message.branchCount,- onPrevious = {- val current = branchSelections[message.id] ?: 1- onBranchChange(message.id, (current - 1).coerceAtLeast(1))- },- onNext = {- val current = branchSelections[message.id] ?: 1- onBranchChange(message.id, (current + 1).coerceAtMost(message.branchCount))- }- )- }- }- }-}--private data class MessageAction(- val label: String,- val iconRes: Int,- val onClick: () -> Unit-)--@Composable-private fun MessageActionsMenu(- showMenu: Boolean,- pressOffset: Offset,- onDismiss: () -> Unit,- actions: List<MessageAction>-) {- if (!showMenu) return- val menuSurface = if (isSystemInDarkTheme()) Color(0xFF1C1C1E) else Color.White- val offset = IntOffset(pressOffset.x.roundToInt(), pressOffset.y.roundToInt())-- Popup(- alignment = Alignment.TopStart,- offset = offset,- onDismissRequest = onDismiss,- properties = PopupProperties(focusable = true)- ) {- Surface(- modifier = Modifier.wrapContentSize(),- color = menuSurface,- shadowElevation = 4.dp,- shape = RoundedCornerShape(12.dp)- ) {- Column(- modifier = Modifier- .width(IntrinsicSize.Min)- .padding(vertical = EnsuSpacing.xs.dp)- ) {- actions.forEach { action ->- DropdownMenuItem(- text = {- Text(- text = action.label,- style = EnsuTypography.body,- color = EnsuColor.textPrimary()- )- },- leadingIcon = {- Icon(- painter = painterResource(action.iconRes),- contentDescription = null,- modifier = Modifier.size(18.dp),- tint = EnsuColor.textPrimary()- )- },- onClick = {- onDismiss()- action.onClick()- }- )- }- }- }- }-}--@Composable-private fun StreamingMessageBubble(text: String) {- var showCursor by remember { mutableStateOf(true) }- val shouldBlink = text.isNotBlank()-- LaunchedEffect(shouldBlink) {- if (!shouldBlink) {- showCursor = true- return@LaunchedEffect- }- while (true) {- delay(520)- showCursor = !showCursor- }- }-- Column(- modifier = Modifier.fillMaxWidth(),- horizontalAlignment = Alignment.Start- ) {- Column(- modifier = Modifier- .animateContentSize(- animationSpec = spring(- dampingRatio = 0.9f,- stiffness = Spring.StiffnessMediumLow- )- )- .padding(horizontal = EnsuSpacing.sm.dp, vertical = EnsuSpacing.md.dp)- ) {- if (text.isBlank()) {- LoadingDotsText()- } else {- val displayText = if (showCursor) "$textβ" else text- MarkdownView(markdown = displayText, enableSelection = false)- }- }- }-}--@Composable-private fun LoadingDotsText() {- var dotCount by remember { mutableStateOf(1) }- val phrase = remember { randomLoadingPhrase() }-- LaunchedEffect(Unit) {- while (true) {- delay(450)- dotCount = if (dotCount == 3) 1 else dotCount + 1- }- }-- Text(- text = phrase + ".".repeat(dotCount),- style = EnsuTypography.message,- color = EnsuColor.textMuted()- )-}--private fun randomLoadingPhrase(): String {- val verb = loadingPhraseVerbs.random()- val target = loadingPhraseTargets.random()- return "$verb $target"-}--private val loadingPhraseVerbs = listOf(- "Generating",- "Thinking through",- "Assembling",- "Drafting",- "Composing",- "Crunching",- "Exploring",- "Piecing together",- "Reviewing",- "Organizing",- "Synthesizing",- "Sketching",- "Refining",- "Shaping"-)--private val loadingPhraseTargets = listOf(- "your reply",- "an answer",- "ideas",- "context",- "details",- "the response",- "the next steps",- "a solution",- "the summary",- "insights",- "the draft",- "the explanation"-)--@Composable-private fun DownloadToastOverlay(- status: String,- percent: Int,- isLoading: Boolean,- onCancel: () -> Unit-) {- val haptic = rememberEnsuHaptics()- Box(- modifier = Modifier- .fillMaxWidth()- .padding(top = EnsuSpacing.lg.dp),- contentAlignment = Alignment.TopCenter- ) {- val title = if (isLoading) "Loading model" else "Downloading model"- val clamped = percent.coerceIn(0, 100)- Column(- modifier = Modifier- .padding(horizontal = EnsuSpacing.lg.dp)- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.toast.dp))- .padding(EnsuSpacing.lg.dp)- .fillMaxWidth()- ) {- Row(verticalAlignment = Alignment.CenterVertically) {- Text(text = title, style = EnsuTypography.large, color = EnsuColor.textPrimary())- Spacer(modifier = Modifier.weight(1f))- IconButton(- onClick = {- haptic.perform(HapticFeedbackType.LongPress)- onCancel()- },- modifier = Modifier.size(28.dp)- ) {- Box(- modifier = Modifier- .size(22.dp)- .background(EnsuColor.textPrimary(), CircleShape),- contentAlignment = Alignment.Center- ) {- Icon(- painter = painterResource(HugeIcons.StopIcon),- contentDescription = "Cancel download",- modifier = Modifier.size(12.dp),- tint = EnsuColor.stopButton- )- }- }- }- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))- LinearProgressIndicator(- progress = { clamped / 100f },- color = if (isLoading) EnsuColor.accent() else EnsuColor.accent(),- trackColor = EnsuColor.border(),- modifier = Modifier.fillMaxWidth()- )- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))- Row(verticalAlignment = Alignment.CenterVertically) {- Text(text = status, style = EnsuTypography.small, color = EnsuColor.textMuted())- Spacer(modifier = Modifier.weight(1f))- Text(text = "$clamped%", style = EnsuTypography.mini, color = EnsuColor.textMuted())- }- }- }-}--@Composable-private fun TimestampText(timestampMillis: Long) {- Text(- text = timestampFormatter.format(Date(timestampMillis)),- style = EnsuTypography.mini,- color = EnsuColor.textMuted()- )-}--@Composable-private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {- val haptic = rememberEnsuHaptics()- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = EnsuSpacing.pageHorizontal.dp)- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))- .height(IntrinsicSize.Min)- ) {- Box(- modifier = Modifier- .fillMaxHeight()- .width(3.dp)- .background(EnsuColor.accent())- )- Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = EnsuSpacing.md.dp, vertical = EnsuSpacing.sm.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Icon(- painter = painterResource(HugeIcons.Edit01Icon),- contentDescription = null,- tint = EnsuColor.accent(),- modifier = Modifier.size(14.dp)- )- Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))- Text(- text = "Editing:",- style = EnsuTypography.small,- color = EnsuColor.textMuted()- )- Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))- Text(- text = message.text,- style = EnsuTypography.small,- color = EnsuColor.textPrimary(),- maxLines = 1,- overflow = TextOverflow.Ellipsis,- modifier = Modifier.weight(1f)- )- IconButton(- onClick = {- haptic.perform(HapticFeedbackType.TextHandleMove)- onCancelEdit()- },- modifier = Modifier.size(24.dp)- ) {- Icon(- painter = painterResource(HugeIcons.Cancel01Icon),- contentDescription = "Cancel edit",- tint = EnsuColor.textMuted()- )- }- }- }-}--@OptIn(ExperimentalLayoutApi::class)-@Composable-private fun MessageInput(- modifier: Modifier,- messageText: String,- attachments: List<Attachment>,- editingMessage: ChatMessage?,- isProcessingAttachments: Boolean,- isGenerating: Boolean,- isDownloading: Boolean,- downloadPercent: Int?,- isAttachmentDownloadBlocked: Boolean,- attachmentDownloadPercent: Int?,- onMessageChange: (String) -> Unit,- onSend: () -> Unit,- onStop: () -> Unit,- onAttachmentSelected: (AttachmentType) -> Unit,- onRemoveAttachment: (Attachment) -> Unit,- onCancelEdit: () -> Unit,- focusRequestId: Int-) {- val haptic = rememberEnsuHaptics()- val placeholder = when {- isAttachmentDownloadBlocked -> {- val percent = attachmentDownloadPercent?.let { " ($it%)" } ?: ""- "Downloading attachments...$percent"- }- else -> "Write a message..."- }-- val focusRequester = remember { FocusRequester() }- LaunchedEffect(focusRequestId) {- if (focusRequestId > 0) {- // Give the screen a moment to settle so IME shows reliably.- delay(120)- focusRequester.requestFocus()- }- }-- val hasAttachmentContent = attachments.isNotEmpty() || isProcessingAttachments- val inputVerticalPadding = if (hasAttachmentContent) EnsuSpacing.xs.dp else 10.dp- val bottomPadding = if (hasAttachmentContent) EnsuSpacing.sm.dp else EnsuSpacing.md.dp-- Column(- modifier = modifier- .background(EnsuColor.backgroundBase()),- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)- ) {- if (editingMessage != null) {- EditBanner(message = editingMessage, onCancelEdit = onCancelEdit)- }-- if (attachments.isNotEmpty()) {- val maxAttachmentHeight = 140.dp- FlowRow(- modifier = Modifier- .fillMaxWidth()- .heightIn(max = maxAttachmentHeight)- .verticalScroll(rememberScrollState())- .padding(horizontal = EnsuSpacing.pageHorizontal.dp),- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)- ) {- attachments.forEach { attachment ->- io.ente.ensu.components.AttachmentChip(- name = attachment.name,- size = "${attachment.sizeBytes / 1024} KB",- iconRes = HugeIcons.Attachment01Icon,- isUploading = attachment.isUploading,- onDelete = { onRemoveAttachment(attachment) }- )- }- }- }-- if (isProcessingAttachments) {- Row(- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),- verticalAlignment = Alignment.CenterVertically- ) {- CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)- Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))- Text(text = "Reading attachment...", style = EnsuTypography.small)- }- }-- Box(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = EnsuSpacing.pageHorizontal.dp)- .padding(bottom = bottomPadding)- .background(EnsuColor.fillFaint(), RoundedCornerShape((EnsuCornerRadius.input + 4).dp))- .padding(- horizontal = EnsuSpacing.inputHorizontal.dp,- vertical = inputVerticalPadding- )- ) {- Row(- modifier = Modifier.fillMaxWidth(),- verticalAlignment = Alignment.CenterVertically- ) {- BasicTextField(- value = messageText,- onValueChange = onMessageChange,- modifier = Modifier- .weight(1f)- .focusRequester(focusRequester)- .focusable(),- textStyle = EnsuTypography.message.copy(color = EnsuColor.textPrimary()),- minLines = 1,- maxLines = 5,- keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),- cursorBrush = SolidColor(EnsuColor.accent())- ) { innerTextField ->- Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterStart) {- if (messageText.isBlank()) {- Text(- text = placeholder,- style = EnsuTypography.message,- color = EnsuColor.textMuted()- )- }- innerTextField()- }- }-- Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))-- if (EnsuFeatureFlags.enableImageUploads && editingMessage == null) {- IconButton(- onClick = {- haptic.perform(HapticFeedbackType.TextHandleMove)- onAttachmentSelected(AttachmentType.Image)- },- enabled = !isGenerating && !isDownloading && !isAttachmentDownloadBlocked,- modifier = Modifier.size(36.dp)- ) {- Icon(- painter = painterResource(HugeIcons.Upload01Icon),- contentDescription = "Attach",- modifier = Modifier.size(18.dp)- )- }- }-- val canSend = messageText.isNotBlank() || attachments.isNotEmpty()-- IconButton(- onClick = {- if (isGenerating) {- haptic.perform(HapticFeedbackType.LongPress)- onStop()- } else {- haptic.perform(HapticFeedbackType.TextHandleMove)- onSend()- }- },- enabled = isGenerating || (!isDownloading && !isAttachmentDownloadBlocked && canSend),- modifier = Modifier.size(36.dp)- ) {- val iconRes = when {- isGenerating -> HugeIcons.StopIcon- else -> HugeIcons.Navigation06Icon- }- val tint = when {- isGenerating -> EnsuColor.stopButton- canSend -> EnsuColor.textPrimary()- else -> EnsuColor.textMuted()- }- val rotation = if (iconRes == HugeIcons.Navigation06Icon) 90f else 0f- if (iconRes == HugeIcons.StopIcon) {- Box(- modifier = Modifier- .size(22.dp)- .background(Color.White, CircleShape),- contentAlignment = Alignment.Center- ) {- Icon(- painter = painterResource(iconRes),- contentDescription = "Send",- modifier = Modifier.size(12.dp),- tint = EnsuColor.stopButton- )- }- } else {- Icon(- painter = painterResource(iconRes),- contentDescription = "Send",- modifier = Modifier.size(18.dp).rotate(rotation),- tint = tint- )- }- }- }- }- }-}--private val timestampFormatter = SimpleDateFormat("h:mm a", Locale.getDefault())diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.ktindex 195ab092f1..8158668426 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt@@ -23,6 +23,8 @@ import androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.key+import androidx.compose.runtime.rememberimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalClipboardManager@@ -33,7 +35,6 @@ import androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.buildAnnotatedStringimport androidx.compose.ui.text.font.FontStyleimport androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.text.withStyleimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.sp@@ -44,51 +45,77 @@ import io.ente.ensu.designsystem.EnsuSpacingimport io.ente.ensu.designsystem.EnsuTypography@Composable-fun MarkdownView(markdown: String, enableSelection: Boolean = true) {- val blocks = MarkdownParser.parse(markdown)+fun MarkdownView(+ markdown: String,+ enableSelection: Boolean = true,+ trailingCursor: Boolean = false+) {+ val blocks = remember(markdown) { MarkdownParser.parse(markdown) }val content = @Composable {Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {- blocks.forEach { block ->- when (block) {- is MarkdownBlock.Heading -> {- Text(- text = markdownAnnotatedText(block.text),- style = headingStyle(block.level),- color = EnsuColor.textPrimary()- )- }- is MarkdownBlock.Paragraph -> {- Text(- text = markdownAnnotatedText(block.text),- style = EnsuTypography.message,- color = EnsuColor.textPrimary()- )- }- is MarkdownBlock.BlockQuote -> {- BlockQuoteView(text = block.text)- }- is MarkdownBlock.Code -> {- CodeBlockView(code = block.text)- }- is MarkdownBlock.Math -> {- MathBlockView(text = block.text)- }- is MarkdownBlock.ListItems -> {- Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)) {- block.items.forEach { item ->- Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {- Text(text = "β’", style = EnsuTypography.message, color = EnsuColor.textPrimary())- Text(- text = markdownAnnotatedText(item),- style = EnsuTypography.message,- color = EnsuColor.textPrimary()- )+ blocks.forEachIndexed { index, block ->+ key(index) {+ val appendCursor = trailingCursor && index == blocks.lastIndex+ when (block) {+ is MarkdownBlock.Heading -> {+ Text(+ text = markdownAnnotatedText(block.text, appendCursor),+ style = headingStyle(block.level),+ color = EnsuColor.textPrimary()+ )+ }+ is MarkdownBlock.Paragraph -> {+ Text(+ text = markdownAnnotatedText(block.text, appendCursor),+ style = EnsuTypography.message,+ color = EnsuColor.textPrimary()+ )+ }+ is MarkdownBlock.BlockQuote -> {+ BlockQuoteView(text = block.text, appendCursor = appendCursor)+ }+ is MarkdownBlock.Code -> {+ CodeBlockView(code = block.text)+ if (appendCursor) {+ TrailingCursor()+ }+ }+ is MarkdownBlock.Math -> {+ MathBlockView(text = block.text)+ if (appendCursor) {+ TrailingCursor()+ }+ }+ is MarkdownBlock.ListItems -> {+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)) {+ block.items.forEachIndexed { itemIndex, item ->+ key(itemIndex) {+ val itemCursor = appendCursor && itemIndex == block.items.lastIndex+ Row(+ verticalAlignment = Alignment.Top,+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)+ ) {+ Text(+ text = "β’",+ style = EnsuTypography.message,+ color = EnsuColor.textPrimary()+ )+ Text(+ text = markdownAnnotatedText(item, itemCursor),+ style = EnsuTypography.message,+ color = EnsuColor.textPrimary()+ )+ }+ }}}}- }- MarkdownBlock.Divider -> {- Divider(color = EnsuColor.border())+ MarkdownBlock.Divider -> {+ Divider(color = EnsuColor.border())+ if (appendCursor) {+ TrailingCursor()+ }+ }}}}@@ -105,7 +132,7 @@ fun MarkdownView(markdown: String, enableSelection: Boolean = true) {}@Composable-private fun BlockQuoteView(text: String) {+private fun BlockQuoteView(text: String, appendCursor: Boolean = false) {Row(modifier = Modifier.fillMaxWidth()@@ -121,7 +148,7 @@ private fun BlockQuoteView(text: String) {)Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))Text(- text = markdownAnnotatedText(text),+ text = markdownAnnotatedText(text, appendCursor),style = EnsuTypography.message,color = EnsuColor.textPrimary())@@ -186,6 +213,15 @@ private fun MathBlockView(text: String) {}}+@Composable+private fun TrailingCursor() {+ Text(+ text = "β",+ style = EnsuTypography.message,+ color = EnsuColor.textPrimary()+ )+}+private fun headingStyle(level: Int): TextStyle {val size = when (level) {1 -> 20.sp@@ -195,7 +231,7 @@ private fun headingStyle(level: Int): TextStyle {return EnsuTypography.message.copy(fontSize = size, fontWeight = FontWeight.SemiBold, lineHeight = (size.value + 6).sp)}-private fun markdownAnnotatedText(text: String): AnnotatedString {+private fun markdownAnnotatedText(text: String, appendCursor: Boolean = false): AnnotatedString {val pattern = Regex("(\\*\\*[^*]+\\*\\*|`[^`]+`|\\*[^*]+\\*)")val codeFamily = EnsuTypography.code.fontFamilyreturn buildAnnotatedString {@@ -229,6 +265,9 @@ private fun markdownAnnotatedText(text: String): AnnotatedString {if (currentIndex < text.length) {append(text.substring(currentIndex))}+ if (appendCursor) {+ append("β")+ }}}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.ktindex b05c8573aa..44c0644c25 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt@@ -16,11 +16,12 @@ import androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.systemBarsimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.layout.windowInsetsPadding-import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.ui.graphics.RectangleShape-import androidx.compose.foundation.verticalScrollimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Icon@@ -98,20 +99,13 @@ fun SessionDrawer(HorizontalDivider(color = EnsuColor.border())- Column(- modifier = Modifier- .weight(1f)- .verticalScroll(rememberScrollState())- .padding(vertical = EnsuSpacing.lg.dp),- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)- ) {- SessionGroups(- sessions = filteredSessions,- selectedSessionId = selectedSessionId,- onSelectSession = onSelectSession,- onDeleteSession = onDeleteSession- )- }+ SessionGroups(+ sessions = filteredSessions,+ selectedSessionId = selectedSessionId,+ onSelectSession = onSelectSession,+ onDeleteSession = onDeleteSession,+ modifier = Modifier.weight(1f)+ )HorizontalDivider(color = EnsuColor.border())@@ -296,37 +290,45 @@ private fun SessionGroups(sessions: List<ChatSession>,selectedSessionId: String?,onSelectSession: (ChatSession) -> Unit,- onDeleteSession: (ChatSession) -> Unit+ onDeleteSession: (ChatSession) -> Unit,+ modifier: Modifier = Modifier) {- val grouped = sessions.groupBy { sessionGroupLabel(it.updatedAtMillis) }+ val grouped = remember(sessions) { sessions.groupBy { sessionGroupLabel(it.updatedAtMillis) } }val order = listOf("TODAY", "YESTERDAY", "THIS WEEK", "LAST WEEK", "THIS MONTH", "OLDER")+ val orderedGroups = remember(grouped) {+ order.mapNotNull { label ->+ grouped[label]?.takeIf { it.isNotEmpty() }?.let { label to it }+ }+ }- Column(- modifier = Modifier.fillMaxWidth(),- // iOS uses `VStack(..., spacing: EnsuSpacing.lg)`, but Compose text metrics- // make this look a bit looser, so we tighten slightly.- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)+ LazyColumn(+ modifier = modifier.fillMaxWidth(),+ contentPadding = PaddingValues(vertical = EnsuSpacing.lg.dp),+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {- order.forEach { label ->- val groupSessions = grouped[label] ?: return@forEach-- Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {- Text(- text = label,- style = EnsuTypography.tiny.copy(letterSpacing = 1.sp),- color = EnsuColor.textMuted(),- modifier = Modifier.padding(horizontal = EnsuSpacing.lg.dp)- )-- groupSessions.forEach { session ->- SessionTile(- session = session,- isSelected = session.id == selectedSessionId,- onSelect = { onSelectSession(session) },- onDelete = { onDeleteSession(session) }+ orderedGroups.forEachIndexed { index, (label, groupSessions) ->+ item(key = "header_$label") {+ Column {+ if (index > 0) {+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))+ }+ Text(+ text = label,+ style = EnsuTypography.tiny.copy(letterSpacing = 1.sp),+ color = EnsuColor.textMuted(),+ modifier = Modifier.padding(horizontal = EnsuSpacing.lg.dp))}}++ items(groupSessions, key = { it.id }) { session ->+ SessionTile(+ session = session,+ isSelected = session.id == selectedSessionId,+ onSelect = { onSelectSession(session) },+ onDelete = { onDeleteSession(session) }+ )+ }}}}diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/ChatRecovery.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/ChatRecovery.ktnew file mode 100644index 0000000000..cb1eb05bd4--- /dev/null+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/ChatRecovery.kt@@ -0,0 +1,10 @@+package io.ente.ensu.data.chat++internal object ChatRecovery {+ private val resetSignals = listOf("stream pull failed", "invalid blob", "invalid encrypted")++ fun shouldResetFromMessage(message: String): Boolean {+ val lower = message.lowercase()+ return resetSignals.any { lower.contains(it) }+ }+}diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.ktindex 9cf687b55e..cc173ddb05 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt@@ -159,10 +159,8 @@ class RustChatRepository(val message = when (error) {is DbException.Message -> error.v1else -> error.message.orEmpty()- }.lowercase()- return message.contains("stream pull failed") ||- message.contains("invalid blob") ||- message.contains("invalid encrypted")+ }+ return ChatRecovery.shouldResetFromMessage(message)}private fun resetDb() {diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.ktindex 6eb232a925..b92f60b158 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt@@ -91,10 +91,8 @@ class RustChatSyncRepository(}private fun shouldResetSync(error: Throwable): Boolean {- val message = syncErrorMessage(error).lowercase()- return message.contains("stream pull failed") ||- message.contains("invalid blob") ||- message.contains("invalid encrypted")+ val message = syncErrorMessage(error)+ return ChatRecovery.shouldResetFromMessage(message)}private fun resetSyncState() {diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.ktindex c1931e8209..5cd10efce8 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt@@ -372,20 +372,17 @@ class InferenceRsProvider()private fun modelPathFor(target: LlmModelTarget): File {- val baseDir = File(modelDir, "models")- val filename = target.url.substringAfterLast('/').ifBlank { "model.gguf" }- return if (target.id.startsWith("custom:")) {- val customDir = File(baseDir, "custom")- File(customDir, "${hash(target.url)}_$filename")- } else {- File(baseDir, filename)- }+ return pathForUrl(target, target.url, fallback = "model.gguf")}private fun mmprojPathFor(target: LlmModelTarget): File? {val url = target.mmprojUrl ?: return null+ return pathForUrl(target, url, fallback = "mmproj.gguf")+ }++ private fun pathForUrl(target: LlmModelTarget, url: String, fallback: String): File {val baseDir = File(modelDir, "models")- val filename = url.substringAfterLast('/').ifBlank { "mmproj.gguf" }+ val filename = url.substringAfterLast('/').ifBlank { fallback }return if (target.id.startsWith("custom:")) {val customDir = File(baseDir, "custom")File(customDir, "${hash(url)}_$filename")diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.ktindex d729aa4258..fb29bcfedb 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt@@ -24,7 +24,6 @@ import java.io.FileOutputStreamimport java.text.SimpleDateFormatimport java.util.Dateimport java.util.Locale-import java.util.UUIDimport java.util.zip.ZipEntryimport java.util.zip.ZipOutputStream@@ -52,39 +51,25 @@ class FileLogRepository(override fun log(level: LogLevel, message: String, details: String?, tag: String?, throwable: Throwable?) {val resolvedTag = tag ?: "ensu"- val combinedDetails = buildString {- if (!details.isNullOrBlank()) {- append(details)- }- if (throwable != null) {- if (isNotEmpty()) append("\n")- append(throwable.stackTraceToString())- }- }.ifBlank { null }-- val safeMessage = LogSanitizer.sanitize(message).orEmpty()- val safeDetails = LogSanitizer.sanitize(combinedDetails)-- val entry = LogEntry(- id = UUID.randomUUID().toString(),- timestampMillis = System.currentTimeMillis(),+ val entry = LogEntryBuilder.buildEntry(level = level,+ message = message,+ details = details,tag = resolvedTag,- message = safeMessage,- details = safeDetails+ throwable = throwable)_logs.update { (listOf(entry) + it).take(maxEntriesInMemory) }// Also mirror to Logcat.when (level) {- LogLevel.Info -> Log.i(resolvedTag, safeMessage)- LogLevel.Warning -> Log.w(resolvedTag, safeMessage)+ LogLevel.Info -> Log.i(resolvedTag, entry.message)+ LogLevel.Warning -> Log.w(resolvedTag, entry.message)LogLevel.Error -> {if (throwable != null) {- Log.e(resolvedTag, safeMessage, throwable)+ Log.e(resolvedTag, entry.message, throwable)} else {- Log.e(resolvedTag, safeMessage)+ Log.e(resolvedTag, entry.message)}}}diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.ktindex 15bfc29250..49bdba565c 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt@@ -7,33 +7,18 @@ import kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.update-import java.util.UUIDclass InMemoryLogRepository : LogRepository {private val _logs = MutableStateFlow<List<LogEntry>>(emptyList())override val logs: StateFlow<List<LogEntry>> = _logs.asStateFlow()override fun log(level: LogLevel, message: String, details: String?, tag: String?, throwable: Throwable?) {- val combinedDetails = buildString {- if (!details.isNullOrBlank()) {- append(details)- }- if (throwable != null) {- if (isNotEmpty()) append("\n")- append(throwable.stackTraceToString())- }- }.ifBlank { null }-- val safeMessage = LogSanitizer.sanitize(message).orEmpty()- val safeDetails = LogSanitizer.sanitize(combinedDetails)-- val entry = LogEntry(- id = UUID.randomUUID().toString(),- timestampMillis = System.currentTimeMillis(),+ val entry = LogEntryBuilder.buildEntry(level = level,+ message = message,+ details = details,tag = tag,- message = safeMessage,- details = safeDetails+ throwable = throwable)_logs.update { (listOf(entry) + it).take(500) }}diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/LogEntryBuilder.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/LogEntryBuilder.ktnew file mode 100644index 0000000000..3630a42177--- /dev/null+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/LogEntryBuilder.kt@@ -0,0 +1,39 @@+package io.ente.ensu.data.logging++import io.ente.ensu.domain.model.LogEntry+import io.ente.ensu.domain.model.LogLevel+import java.util.UUID++internal object LogEntryBuilder {+ fun buildEntry(+ level: LogLevel,+ message: String,+ details: String?,+ tag: String?,+ throwable: Throwable?,+ idProvider: () -> String = { UUID.randomUUID().toString() },+ nowProvider: () -> Long = { System.currentTimeMillis() }+ ): LogEntry {+ val combinedDetails = buildString {+ if (!details.isNullOrBlank()) {+ append(details)+ }+ if (throwable != null) {+ if (isNotEmpty()) append("\n")+ append(throwable.stackTraceToString())+ }+ }.ifBlank { null }++ val safeMessage = LogSanitizer.sanitize(message).orEmpty()+ val safeDetails = LogSanitizer.sanitize(combinedDetails)++ return LogEntry(+ id = idProvider(),+ timestampMillis = nowProvider(),+ level = level,+ tag = tag,+ message = safeMessage,+ details = safeDetails+ )+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.ktindex 389be5baac..60ad9ec2b7 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt@@ -1,47 +1,23 @@package io.ente.ensu.domain.store+import io.ente.ensu.domain.chat.ChatRepositoryimport io.ente.ensu.domain.chat.ChatSyncRepository-import io.ente.ensu.domain.llm.LlmMessage-import io.ente.ensu.domain.llm.LlmMessageRole-import io.ente.ensu.domain.llm.LlmModelTargetimport io.ente.ensu.domain.llm.LlmProvider+import io.ente.ensu.domain.logging.LogRepository+import io.ente.ensu.domain.logging.NoOpLogRepositoryimport io.ente.ensu.domain.model.Attachment-import io.ente.ensu.domain.model.AttachmentDownloadItem-import io.ente.ensu.domain.model.AttachmentDownloadStatus-import io.ente.ensu.domain.model.AttachmentType-import io.ente.ensu.domain.model.AuthStateimport io.ente.ensu.domain.model.ChatMessage-import io.ente.ensu.domain.model.ChatSession-import io.ente.ensu.domain.model.LogLevel-import io.ente.ensu.domain.model.MessageAuthor-import io.ente.ensu.domain.model.sanitizeTitleText-import io.ente.ensu.domain.model.sessionTitleFromTextimport io.ente.ensu.domain.preferences.SessionPreferencesimport io.ente.ensu.domain.state.AppStateimport io.ente.ensu.domain.state.ModelSettingsState-import io.ente.ensu.domain.logging.LogRepository-import io.ente.ensu.domain.logging.NoOpLogRepositoryimport kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.flow.collectLatest-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.flow.update-import kotlinx.coroutines.isActive-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import java.io.File-import java.util.concurrent.ConcurrentHashMap-import java.util.concurrent.ConcurrentLinkedDeque-import kotlin.math.abs-import kotlin.math.maxclass AppStore(private val sessionPreferences: SessionPreferences,- private val chatRepository: io.ente.ensu.domain.chat.ChatRepository,+ private val chatRepository: ChatRepository,private val chatSyncRepository: ChatSyncRepository? = null,private val llmProvider: LlmProvider,private val clock: () -> Long = { System.currentTimeMillis() },@@ -51,1567 +27,97 @@ class AppStore(val state: StateFlow<AppState> = _state.asStateFlow()private val messageStore = mutableMapOf<String, MutableList<ChatMessage>>()- private val branchSelections = mutableMapOf<String, MutableMap<String, String>>()- private val sessionSummaries = mutableMapOf<String, String>()- private val sessionAccessTimes = mutableMapOf<String, Long>()- private var scope: CoroutineScope? = null- private var generationJob: Job? = null- private var modelDownloadJob: Job? = null- private var sessionSummaryJob: Job? = null- private var stopRequested = false- private var streamingParentId: String? = null- private var activeGenerationToken = 0L- private var pendingSyncRequested = false- private var pendingSyncErrorHandler: ((String) -> Unit)? = null- private var pendingSyncSuccessHandler: (() -> Unit)? = null- private var pendingOverflow: PendingOverflow? = null- private var overflowBypassMessageId: String? = null-- private val sessionSummarySystemPrompt =- "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no markdown characters, no quotes, no emojis, no trailing punctuation, and output only the title."- private val sessionSummaryMaxWords = 7-- private val attachmentDownloads = ConcurrentHashMap<String, AttachmentDownloadItem>()- private val attachmentDownloadQueue = ConcurrentLinkedDeque<String>()- private val attachmentDownloadActive = ConcurrentHashMap<String, Job>()- private val maxAttachmentDownloadConcurrency = 2-- fun bootstrap(scope: CoroutineScope) {- this.scope = scope-- sessionSummaries.clear()- scope.launch {- val summaries = sessionPreferences.sessionSummaries.first()- sessionSummaries.clear()- sessionSummaries.putAll(summaries.mapKeys { sessionKey(it.key) })- applySessionSummariesToState()- }-- if (_state.value.chat.sessions.isEmpty()) {- loadSessionsFromDb()- }-- refreshModelDownloadInfo()-- scope.launch {- sessionPreferences.sessionSummaries.collectLatest { summaries ->- sessionSummaries.clear()- sessionSummaries.putAll(summaries.mapKeys { sessionKey(it.key) })- applySessionSummariesToState()- }- }- }-- private fun refreshModelDownloadInfo() {- val target = resolveTarget(_state.value.modelSettings)- val isDownloaded = llmProvider.isModelDownloaded(target)- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isModelDownloaded = isDownloaded,- modelDownloadSizeBytes = if (isDownloaded) null else appState.chat.modelDownloadSizeBytes,- hasRequestedModelDownload = appState.chat.hasRequestedModelDownload || isDownloaded- )- )- }-- if (!isDownloaded) {- val scope = scope ?: return- scope.launch {- val size = llmProvider.estimateModelDownloadSize(target)- _state.update { appState ->- appState.copy(chat = appState.chat.copy(modelDownloadSizeBytes = size))- }- }- }- }-- fun createNewSession(): String {- generationJob?.cancel()- llmProvider.stopGeneration()- invalidateGenerationToken()- streamingParentId = null- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isGenerating = false,- isDownloading = false,- streamingResponse = "",- streamingParentId = null,- downloadPercent = null,- downloadStatus = null- )- )- }-- val session = chatRepository.createSession("New Chat")- messageStore[session.id] = mutableListOf()- branchSelections[session.id] = mutableMapOf()-- _state.update { appState ->- val updatedSessions = listOf(session) + appState.chat.sessions- appState.copy(- chat = appState.chat.copy(- sessions = updatedSessions,- currentSessionId = session.id,- messageText = "",- attachments = emptyList(),- editingMessageId = null- )- )- }- markSessionAccess(session.id)- trimSessionCaches()- // Session is empty, no DB load needed.- rebuildChatState(session.id)- updateAttachmentDownloadState()- logRepository.log(LogLevel.Info, "Session created", tag = "Chat")- return session.id- }-- fun startNewSessionDraft() {- generationJob?.cancel()- llmProvider.stopGeneration()- invalidateGenerationToken()- streamingParentId = null- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- currentSessionId = null,- messages = emptyList(),- branchSelections = emptyMap(),- isGenerating = false,- isDownloading = false,- streamingResponse = "",- streamingParentId = null,- downloadPercent = null,- downloadStatus = null,- messageText = "",- attachments = emptyList(),- editingMessageId = null- )- )- }- updateAttachmentDownloadState()+ private val attachmentActions = AttachmentStoreActions(_state, chatSyncRepository, messageStore)+ private val modelSettingsActions = ModelSettingsActions(_state, llmProvider, logRepository)+ private val syncActions = SyncStoreActions(_state, chatSyncRepository, logRepository)+ private val chatActions = ChatStoreActions(+ state = _state,+ sessionPreferences = sessionPreferences,+ chatRepository = chatRepository,+ llmProvider = llmProvider,+ clock = clock,+ logRepository = logRepository,+ messageStore = messageStore,+ attachmentActions = attachmentActions,+ syncActions = syncActions,+ modelSettingsActions = modelSettingsActions+ )+ private val authActions = AuthStoreActions(_state, logRepository) {+ syncActions.syncNow()}- fun selectSession(sessionId: String) {- generationJob?.cancel()- llmProvider.stopGeneration()- invalidateGenerationToken()- streamingParentId = null- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- currentSessionId = sessionId,- isGenerating = false,- isDownloading = false,- streamingResponse = "",- streamingParentId = null,- downloadPercent = null,- downloadStatus = null- )- )- }- loadMessagesFromDb(sessionId)- rebuildChatState(sessionId)- ensureAttachmentsAvailable(sessionId)+ init {+ syncActions.setReloadSessions { chatActions.loadSessionsFromDb() }}- fun deleteSession(sessionId: String) {- val currentState = _state.value- val isCurrent = currentState.chat.currentSessionId == sessionId-- if (isCurrent) {- generationJob?.cancel()- llmProvider.stopGeneration()- invalidateGenerationToken()- streamingParentId = null- }-- chatRepository.deleteSession(sessionId)- removeSessionCaches(sessionId)- purgeAttachmentDownloads(sessionId)- sessionSummaries.remove(sessionKey(sessionId))- scope?.launch { sessionPreferences.setSessionSummary(sessionId, null) }-- val sessions = currentState.chat.sessions.filterNot { it.id == sessionId }-- val newCurrent = if (isCurrent) {- sessions.firstOrNull()?.id- } else {- currentState.chat.currentSessionId?.takeIf { id -> sessions.any { it.id == id } }- ?: sessions.firstOrNull()?.id- }-- _state.update { appState ->- val resetCurrent = isCurrent- appState.copy(- chat = appState.chat.copy(- sessions = sessions,- currentSessionId = newCurrent,- isGenerating = if (resetCurrent) false else appState.chat.isGenerating,- isDownloading = if (resetCurrent) false else appState.chat.isDownloading,- streamingResponse = if (resetCurrent) "" else appState.chat.streamingResponse,- streamingParentId = if (resetCurrent) null else appState.chat.streamingParentId,- downloadPercent = if (resetCurrent) null else appState.chat.downloadPercent,- downloadStatus = if (resetCurrent) null else appState.chat.downloadStatus,- messageText = if (resetCurrent) "" else appState.chat.messageText,- attachments = if (resetCurrent) emptyList() else appState.chat.attachments,- editingMessageId = if (resetCurrent) null else appState.chat.editingMessageId- )- )- }-- if (newCurrent != null) {- loadMessagesFromDb(newCurrent)- rebuildChatState(newCurrent)- ensureAttachmentsAvailable(newCurrent)- } else {- _state.update { appState ->- appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))- }- }- trimSessionCaches(sessions.map { it.id }.toSet())-- scope?.launch { sessionPreferences.setSelectedSessionId(newCurrent) }- syncNow()- logRepository.log(LogLevel.Info, "Session deleted", tag = "Chat")+ fun bootstrap(scope: CoroutineScope) {+ chatActions.setScope(scope)+ attachmentActions.setScope(scope)+ syncActions.setScope(scope)+ modelSettingsActions.setScope(scope)+ chatActions.bootstrap(scope)+ modelSettingsActions.refreshModelDownloadInfo()}- fun persistSelectedSession(scope: CoroutineScope, sessionId: String?) {- scope.launch {- sessionPreferences.setSelectedSessionId(sessionId)- }- }+ fun createNewSession(): String = chatActions.createNewSession()- fun updateMessageText(value: String) {- _state.update { appState ->- appState.copy(chat = appState.chat.copy(messageText = value))- }- }+ fun startNewSessionDraft() = chatActions.startNewSessionDraft()- fun updateBranchSelection(messageId: String, selectedIndex: Int) {- if (_state.value.chat.isGenerating) {- stopGeneration()- }- val sessionId = _state.value.chat.currentSessionId ?: return- val messages = messageStore[sessionId].orEmpty()- val byId = messages.associateBy { it.id }- val message = byId[messageId] ?: return- val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"- val siblings = dedupeSiblings(buildChildrenMap(messages)[parentKey].orEmpty())- if (siblings.isEmpty()) return- val index = (selectedIndex - 1).coerceIn(0, siblings.lastIndex)- val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }- selectionMap[parentKey] = siblings[index].id- rebuildChatState(sessionId)- }+ fun selectSession(sessionId: String) = chatActions.selectSession(sessionId)- fun beginEditing(messageId: String) {- val sessionId = _state.value.chat.currentSessionId ?: return- val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return- if (message.author != MessageAuthor.User) return+ fun deleteSession(sessionId: String) = chatActions.deleteSession(sessionId)- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- editingMessageId = message.id,- messageText = message.text,- attachments = message.attachments- )- )- }- }+ fun persistSelectedSession(scope: CoroutineScope, sessionId: String?) =+ chatActions.persistSelectedSession(scope, sessionId)- fun cancelEditing() {- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- editingMessageId = null,- messageText = "",- attachments = emptyList()- )- )- }- }+ fun updateMessageText(value: String) = chatActions.updateMessageText(value)- fun setAttachmentProcessing(isProcessing: Boolean) {- _state.update { appState ->- appState.copy(chat = appState.chat.copy(isProcessingAttachments = isProcessing))- }- }+ fun updateBranchSelection(messageId: String, selectedIndex: Int) =+ chatActions.updateBranchSelection(messageId, selectedIndex)- fun addAttachment(attachment: Attachment) {- if (_state.value.chat.isGenerating || _state.value.chat.isDownloading || _state.value.chat.isAttachmentDownloadBlocked) return+ fun beginEditing(messageId: String) = chatActions.beginEditing(messageId)- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- attachments = appState.chat.attachments + attachment,- isProcessingAttachments = false- )- )- }- }+ fun cancelEditing() = chatActions.cancelEditing()- fun removeAttachment(attachment: Attachment) {- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- attachments = appState.chat.attachments.filterNot { it.id == attachment.id }- )- )- }- }+ fun setAttachmentProcessing(isProcessing: Boolean) =+ attachmentActions.setAttachmentProcessing(isProcessing)- fun stopGeneration() {- stopRequested = true- llmProvider.stopGeneration()- }+ fun addAttachment(attachment: Attachment) = attachmentActions.addAttachment(attachment)- fun startModelDownload(userInitiated: Boolean = true) {- val scope = scope ?: return- val currentState = _state.value- if (modelDownloadJob?.isActive == true) return- if (currentState.chat.isDownloading || currentState.chat.isGenerating) return- if (!userInitiated && !currentState.chat.hasRequestedModelDownload) return+ fun removeAttachment(attachment: Attachment) = attachmentActions.removeAttachment(attachment)- val target = resolveTarget(currentState.modelSettings)- val isDownloaded = llmProvider.isModelDownloaded(target)- if (isDownloaded) {- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isModelDownloaded = true,- modelDownloadSizeBytes = null,- hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload- )- )- }- }+ fun stopGeneration() = chatActions.stopGeneration()- modelDownloadJob?.cancel()- if (!isDownloaded) {- logRepository.log(- LogLevel.Info,- "Model download started",- details = "model=${target.id}",- tag = "Model"- )- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isDownloading = true,- downloadPercent = 0,- downloadStatus = "Starting download...",- hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload- )- )- }- }-- modelDownloadJob = scope.launch {- var loggedComplete = false- try {- llmProvider.ensureModelReady(target) { progress ->- val downloading = (progress.percent in 0..99) || progress.status.contains("Loading", ignoreCase = true)- val finished = progress.status.contains("Ready", ignoreCase = true)- if (!isDownloaded && finished && !loggedComplete) {- loggedComplete = true- logRepository.log(- LogLevel.Info,- "Model download complete",- details = "model=${target.id}",- tag = "Model"- )- }- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isDownloading = downloading && !finished,- downloadPercent = progress.percent.takeIf { it >= 0 },- downloadStatus = progress.status,- isModelDownloaded = if (finished) true else appState.chat.isModelDownloaded,- modelDownloadSizeBytes = if (finished) null else appState.chat.modelDownloadSizeBytes- )- )- }- }- } catch (err: Throwable) {- val cancelled = err is kotlinx.coroutines.CancellationException ||- err.message?.contains("cancel", ignoreCase = true) == true- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isDownloading = false,- downloadPercent = null,- downloadStatus = if (cancelled) "Download cancelled" else "Download failed",- hasRequestedModelDownload = if (cancelled) false else appState.chat.hasRequestedModelDownload- )- )- }- if (cancelled) {- if (!isDownloaded) {- logRepository.log(LogLevel.Info, "Model download cancelled", tag = "Model")- }- } else {- logRepository.log(- LogLevel.Error,- if (isDownloaded) "Model load failed" else "Model download failed",- details = err.message,- tag = "Model",- throwable = err- )- }- } finally {- modelDownloadJob = null- refreshModelDownloadInfo()- }- }- }+ fun startModelDownload(userInitiated: Boolean = true) =+ modelSettingsActions.startModelDownload(userInitiated)fun cancelDownload() {- generationJob?.cancel()- modelDownloadJob?.cancel()- modelDownloadJob = null- llmProvider.cancelDownload()- invalidateGenerationToken()- streamingParentId = null- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isGenerating = false,- isDownloading = false,- streamingResponse = "",- streamingParentId = null,- downloadPercent = null,- downloadStatus = "Download cancelled",- hasRequestedModelDownload = false- )- )- }- refreshModelDownloadInfo()- }-- fun retryAssistantMessage(messageId: String) {- if (_state.value.chat.isGenerating) {- stopGeneration()- }- val sessionId = _state.value.chat.currentSessionId ?: return- val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return- if (message.author != MessageAuthor.Assistant) return- val parentId = message.parentId ?: return- val parent = messageStore[sessionId]?.firstOrNull { it.id == parentId } ?: return-- if (missingAttachments(sessionId).isNotEmpty()) {- ensureAttachmentsAvailable(sessionId)- return- }- llmProvider.resetContext()- startGeneration(sessionId, parent)- requestSync()+ chatActions.cancelGenerationForDownload()+ modelSettingsActions.cancelModelDownload()}- fun sendMessage() {- val currentState = _state.value- if (currentState.chat.isGenerating || currentState.chat.isDownloading) return- val text = currentState.chat.messageText.trim()- val attachments = currentState.chat.attachments- if (text.isEmpty() && attachments.isEmpty()) return-- val sessionId = currentState.chat.currentSessionId ?: createNewSession()- if (missingAttachments(sessionId).isNotEmpty()) {- ensureAttachmentsAvailable(sessionId)- return- }- val timestamp = clock()+ fun retryAssistantMessage(messageId: String) = chatActions.retryAssistantMessage(messageId)- val editingMessageId = currentState.chat.editingMessageId- val parentId = if (editingMessageId != null) {- val existing = messageStore[sessionId]?.firstOrNull { it.id == editingMessageId }- existing?.parentId- } else {- buildSelectedPath(sessionId).lastOrNull()?.id- }+ fun sendMessage() = chatActions.sendMessage()- val userMessage = chatRepository.insertMessage(- sessionId = sessionId,- parentId = parentId,- author = MessageAuthor.User,- text = text,- attachments = attachments- )-- messageStore.getOrPut(sessionId) { mutableListOf() }.add(userMessage)- updateSelectionForParent(sessionId, parentId, userMessage.id)-- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- messageText = "",- attachments = emptyList(),- editingMessageId = null- )- )- }-- updateCurrentSessionPreview(sessionId, text, timestamp)- rebuildChatState(sessionId)- startGeneration(sessionId, userMessage)- requestSync()- logRepository.log(- LogLevel.Info,- "Message sent",- details = "len=${text.length} attachments=${attachments.size} edited=${editingMessageId != null}",- tag = "Chat"- )- }-- fun confirmOverflowTrim() {- val pending = pendingOverflow ?: return- val message = messageStore[pending.sessionId]?.firstOrNull { it.id == pending.messageId }- if (message == null) {- pendingOverflow = null- overflowBypassMessageId = null- clearOverflowDialog()- return- }- overflowBypassMessageId = pending.messageId- pendingOverflow = null- clearOverflowDialog()- startGeneration(pending.sessionId, message)- }+ fun confirmOverflowTrim() = chatActions.confirmOverflowTrim()- fun cancelOverflowDialog() {- pendingOverflow = null- overflowBypassMessageId = null- clearOverflowDialog()- }+ fun cancelOverflowDialog() = chatActions.cancelOverflowDialog()- fun updateModelSettings(state: ModelSettingsState) {- _state.update { appState ->- appState.copy(modelSettings = state)- }- refreshModelDownloadInfo()- }+ fun updateModelSettings(state: ModelSettingsState) =+ modelSettingsActions.updateModelSettings(state)- fun resetModelSettings() {- _state.update { appState ->- appState.copy(modelSettings = ModelSettingsState())- }- refreshModelDownloadInfo()- }+ fun resetModelSettings() = modelSettingsActions.resetModelSettings()- fun signIn(email: String) {- _state.update { appState ->- appState.copy(auth = AuthState(isLoggedIn = true, email = email))- }- // Do not log PII like user email.- logRepository.log(LogLevel.Info, "Signed in", tag = "Auth")- syncNow()- }+ fun signIn(email: String) = authActions.signIn(email)- fun signOut() {- _state.update { appState ->- appState.copy(auth = AuthState())- }- logRepository.log(LogLevel.Info, "Signed out", tag = "Auth")- }+ fun signOut() = authActions.signOut()fun syncNow(onSuccess: (() -> Unit)? = null,onError: ((String) -> Unit)? = null- ) {- requestSync(onSuccess, onError)- }-- private fun requestSync(- onSuccess: (() -> Unit)? = null,- onError: ((String) -> Unit)? = null- ) {- if (_state.value.chat.isGenerating) {- pendingSyncRequested = true- if (onError != null) {- pendingSyncErrorHandler = onError- }- if (onSuccess != null) {- pendingSyncSuccessHandler = onSuccess- }- return- }-- val handler = pendingSyncErrorHandler ?: onError- val successHandler = pendingSyncSuccessHandler ?: onSuccess- pendingSyncRequested = false- pendingSyncErrorHandler = null- pendingSyncSuccessHandler = null- performSync(handler, successHandler)- }-- private fun syncAfterGeneration() {- val handler = pendingSyncErrorHandler- val successHandler = pendingSyncSuccessHandler- val shouldAutoSync = _state.value.auth.isLoggedIn- if (!pendingSyncRequested && !shouldAutoSync) {- pendingSyncErrorHandler = null- pendingSyncSuccessHandler = null- return- }- if (!shouldAutoSync && handler == null && successHandler == null) {- pendingSyncRequested = false- pendingSyncErrorHandler = null- pendingSyncSuccessHandler = null- return- }- pendingSyncRequested = false- pendingSyncErrorHandler = null- pendingSyncSuccessHandler = null- performSync(handler, successHandler)- }+ ) = syncActions.syncNow(onSuccess, onError)- private fun performSync(- onError: ((String) -> Unit)? = null,- onSuccess: (() -> Unit)? = null- ) {- val scope = scope ?: return- scope.launch {- try {- logRepository.log(LogLevel.Info, "Sync started", tag = "Sync")- withContext(Dispatchers.IO) {- chatSyncRepository?.sync()- }- loadSessionsFromDb()- logRepository.log(LogLevel.Info, "Sync success", tag = "Sync")- if (onSuccess != null) {- withContext(Dispatchers.Main) {- onSuccess()- }- }- } catch (err: Throwable) {- val message = syncErrorMessage(err)- logRepository.log(- LogLevel.Error,- "Sync failed",- details = message,- tag = "Sync",- throwable = err- )- if (onError != null) {- withContext(Dispatchers.Main) {- onError("Sync failed: $message")- }- }- }- }- }-- fun cancelAttachmentDownload(attachmentId: String) {- attachmentDownloadActive[attachmentId]?.cancel()- attachmentDownloadActive.remove(attachmentId)- attachmentDownloadQueue.removeIf { it == attachmentId }- attachmentDownloads[attachmentId]?.let { item ->- attachmentDownloads[attachmentId] = item.copy(status = AttachmentDownloadStatus.Canceled)- }- updateAttachmentDownloadState()- startNextAttachmentDownloads()- }-- private fun syncErrorMessage(error: Throwable): String {- var current: Throwable? = error- while (current != null) {- val message = current.message- if (!message.isNullOrBlank()) {- return message- }- current = current.cause- }- return "Unknown error"- }-- private fun purgeAttachmentDownloads(sessionId: String) {- val ids = attachmentDownloads.values.filter { it.sessionId == sessionId }.map { it.id }- ids.forEach { id ->- attachmentDownloadActive[id]?.cancel()- attachmentDownloadActive.remove(id)- attachmentDownloadQueue.removeIf { it == id }- attachmentDownloads.remove(id)- }- updateAttachmentDownloadState()- }-- private fun ensureAttachmentsAvailable(sessionId: String) {- val missing = missingAttachments(sessionId)- if (missing.isEmpty()) {- updateAttachmentDownloadState()- return- }- queueAttachmentDownloads(missing)- updateAttachmentDownloadState()- }-- private fun missingAttachments(sessionId: String): List<AttachmentDownloadItem> {- val messages = messageStore[sessionId].orEmpty()- if (messages.isEmpty()) return emptyList()- val seen = mutableSetOf<String>()- val missing = mutableListOf<AttachmentDownloadItem>()-- for (message in messages) {- for (attachment in message.attachments) {- if (!seen.add(attachment.id)) continue- val path = attachment.localPath- if (path != null && File(path).exists()) {- attachmentDownloadActive[attachment.id]?.cancel()- attachmentDownloadActive.remove(attachment.id)- attachmentDownloadQueue.removeIf { it == attachment.id }- attachmentDownloads.remove(attachment.id)- continue- }- val existing = attachmentDownloads[attachment.id]- val status = existing?.status ?: AttachmentDownloadStatus.Queued- missing.add(- AttachmentDownloadItem(- id = attachment.id,- sessionId = sessionId,- name = attachment.name,- sizeBytes = attachment.sizeBytes,- status = status- )- )- }- }-- return missing- }-- private fun queueAttachmentDownloads(items: List<AttachmentDownloadItem>) {- items.forEach { item ->- val existing = attachmentDownloads[item.id]- val updated = if (existing == null ||- existing.status == AttachmentDownloadStatus.Failed ||- existing.status == AttachmentDownloadStatus.Canceled- ) {- item- } else {- existing- }- attachmentDownloads[item.id] = updated- if (updated.status != AttachmentDownloadStatus.Completed &&- updated.status != AttachmentDownloadStatus.Canceled &&- attachmentDownloadActive[item.id] == null &&- !attachmentDownloadQueue.contains(item.id)- ) {- attachmentDownloadQueue.addLast(item.id)- }- }- startNextAttachmentDownloads()- }-- private fun startNextAttachmentDownloads() {- val scope = scope ?: return- while (attachmentDownloadActive.size < maxAttachmentDownloadConcurrency && attachmentDownloadQueue.isNotEmpty()) {- val id = attachmentDownloadQueue.pollFirst() ?: continue- if (attachmentDownloadActive.containsKey(id)) {- continue- }- val item = attachmentDownloads[id] ?: continue- if (item.status == AttachmentDownloadStatus.Completed || item.status == AttachmentDownloadStatus.Canceled) {- continue- }- attachmentDownloads[id] = item.copy(status = AttachmentDownloadStatus.Downloading)- updateAttachmentDownloadState()-- val job = scope.launch(Dispatchers.IO) {- val result = runCatching {- chatSyncRepository?.downloadAttachment(id, item.sessionId)- ?: throw IllegalStateException("Sync unavailable")- }- val status = if (result.isSuccess) {- AttachmentDownloadStatus.Completed- } else {- AttachmentDownloadStatus.Failed- }- withContext(Dispatchers.Main) {- attachmentDownloads[id]?.let { current ->- if (current.status != AttachmentDownloadStatus.Canceled) {- attachmentDownloads[id] = current.copy(status = status)- }- }- attachmentDownloadActive.remove(id)- updateAttachmentDownloadState()- startNextAttachmentDownloads()- }- }- attachmentDownloadActive[id] = job- }- }-- private fun updateAttachmentDownloadState() {- val currentSessionId = _state.value.chat.currentSessionId- val missing = currentSessionId?.let { missingAttachments(it) }.orEmpty()- val items = attachmentDownloads.values.sortedBy { it.name }- val active = items.filter { it.status != AttachmentDownloadStatus.Canceled }- val total = active.size- val completed = active.count { it.status == AttachmentDownloadStatus.Completed }- val hasPending = active.any {- it.status == AttachmentDownloadStatus.Queued ||- it.status == AttachmentDownloadStatus.Downloading ||- it.status == AttachmentDownloadStatus.Failed- }- val progress = if (total > 0 && hasPending) (completed * 100 / total) else null- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- attachmentDownloads = items,- attachmentDownloadProgress = progress,- isAttachmentDownloadBlocked = missing.isNotEmpty()- )- )- }- }-- private fun nextGenerationToken(): Long {- activeGenerationToken += 1- return activeGenerationToken- }-- private fun invalidateGenerationToken() {- activeGenerationToken += 1- }-- private fun isGenerationActive(token: Long, sessionId: String): Boolean {- return token == activeGenerationToken && _state.value.chat.currentSessionId == sessionId- }-- private fun startGeneration(sessionId: String, userMessage: ChatMessage) {- val scope = scope ?: return- generationJob?.cancel()- sessionSummaryJob?.cancel()- stopRequested = false-- val settings = _state.value.modelSettings- val target = resolveTarget(settings)- val prompt = buildPrompt(userMessage.text, userMessage.attachments)- val historySelection = buildHistorySelection(- sessionId = sessionId,- promptText = prompt.text,- promptImageCount = prompt.imageFiles.size,- currentMessageId = userMessage.id,- target = target- )-- if (historySelection.wasTrimmed && overflowBypassMessageId != userMessage.id) {- pendingOverflow = PendingOverflow(sessionId, userMessage.id)- showOverflowDialog(historySelection, target)- return- }-- overflowBypassMessageId = null- pendingOverflow = null- clearOverflowDialog()-- val generationToken = nextGenerationToken()- streamingParentId = userMessage.id- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isGenerating = true,- isDownloading = false,- streamingResponse = "",- streamingParentId = userMessage.id,- downloadPercent = null,- downloadStatus = null,- hasRequestedModelDownload = true- )- )- }- rebuildChatState(sessionId)-- generationJob = scope.launch {- val isActive = { isGenerationActive(generationToken, sessionId) }- try {- llmProvider.ensureModelReady(target) { progress ->- if (!isActive()) return@ensureModelReady- val downloading = (progress.percent in 0..99) || progress.status.contains("Loading", ignoreCase = true)- val finished = progress.status.contains("Ready", ignoreCase = true)- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isDownloading = downloading && !finished,- downloadPercent = progress.percent.takeIf { it >= 0 },- downloadStatus = progress.status,- isModelDownloaded = if (finished) true else appState.chat.isModelDownloaded,- modelDownloadSizeBytes = if (finished) null else appState.chat.modelDownloadSizeBytes- )- )- }- }- } catch (err: Throwable) {- val cancelled = err is kotlinx.coroutines.CancellationException ||- err.message?.contains("cancel", ignoreCase = true) == true- if (!isActive()) return@launch- streamingParentId = null- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isGenerating = false,- isDownloading = false,- streamingParentId = null,- downloadPercent = null,- downloadStatus = if (cancelled) "Download cancelled" else null,- hasRequestedModelDownload = if (cancelled) false else appState.chat.hasRequestedModelDownload- )- )- }- if (!cancelled) {- logRepository.log(- LogLevel.Error,- "Model load failed",- details = err.message,- tag = "Model",- throwable = err- )- }- syncAfterGeneration()- return@launch- }-- if (!isActive()) return@launch-- val history = historySelection.messages- val systemMessage = LlmMessage(- text = SYSTEM_PROMPT,- role = LlmMessageRole.System- )- val llmMessages = listOf(systemMessage) + history + LlmMessage(- text = prompt.text,- role = LlmMessageRole.User,- hasAttachments = userMessage.attachments.isNotEmpty()- )-- val buffer = StringBuilder()- var tokenCount = 0-- try {- val summary = llmProvider.generateChat(- target = target,- messages = llmMessages,- imageFiles = prompt.imageFiles,- temperature = resolveTemperature(settings),- maxTokens = target.maxTokens ?: 1024- ) { token ->- buffer.append(token)- tokenCount += estimateTokens(token)- if (isActive()) {- _state.update { appState ->- appState.copy(chat = appState.chat.copy(streamingResponse = buffer.toString()))- }- }- }-- finishGeneration(- sessionId,- userMessage,- buffer,- tokenCount,- summary.totalTimeMs,- interrupted = false,- shouldUpdateUi = isActive()- )- } catch (err: Throwable) {- val interrupted = stopRequested || err.message?.contains("cancel", ignoreCase = true) == true- finishGeneration(- sessionId,- userMessage,- buffer,- tokenCount,- totalTimeMs = null,- interrupted = interrupted,- shouldUpdateUi = isActive()- )- if (!interrupted) {- logRepository.log(- LogLevel.Error,- "Generation failed",- details = err.message,- tag = "LLM",- throwable = err- )- }- }- }- }-- private fun finishGeneration(- sessionId: String,- parentMessage: ChatMessage,- buffer: StringBuilder,- tokenCount: Int,- totalTimeMs: Long?,- interrupted: Boolean,- shouldUpdateUi: Boolean- ) {- val finalText = buffer.toString().trim()- if (finalText.isNotEmpty()) {- val tokensPerSecond = if (totalTimeMs != null && totalTimeMs > 0) {- tokenCount.toDouble() / (totalTimeMs / 1000.0)- } else null-- val inserted = chatRepository.insertMessage(- sessionId = sessionId,- parentId = parentMessage.id,- author = MessageAuthor.Assistant,- text = finalText,- attachments = emptyList()- )-- val assistantMessage = inserted.copy(- isInterrupted = interrupted,- tokensPerSecond = tokensPerSecond- )-- messageStore.getOrPut(sessionId) { mutableListOf() }.add(assistantMessage)- updateSelectionForParent(sessionId, parentMessage.id, assistantMessage.id)- updateCurrentSessionPreview(sessionId, finalText, assistantMessage.timestampMillis)- }-- if (shouldUpdateUi) {- streamingParentId = null- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- isGenerating = false,- isDownloading = false,- streamingResponse = "",- streamingParentId = null,- downloadPercent = null,- downloadStatus = null- )- )- }- rebuildChatState(sessionId)- syncAfterGeneration()- }- scheduleSessionSummary(sessionId)- }-- private fun updateCurrentSessionPreview(sessionId: String, preview: String, timestamp: Long) {- _state.update { appState ->- val updatedSessions = appState.chat.sessions.map { session ->- if (session.id == sessionId) {- val shouldUpdateTitle = session.title.isBlank() || session.title.equals("New Chat", ignoreCase = true)- val updatedTitle = if (shouldUpdateTitle) {- sessionTitleFromText(preview, fallback = session.title)- } else {- session.title- }- if (updatedTitle != session.title) {- chatRepository.updateSessionTitle(sessionId, updatedTitle)- }- session.copy(- title = updatedTitle,- lastMessagePreview = preview,- updatedAtMillis = timestamp- )- } else {- session- }- }- appState.copy(chat = appState.chat.copy(sessions = updatedSessions))- }- }-- private fun applySessionSummariesToState() {- _state.update { appState ->- val updatedSessions = appState.chat.sessions.map { session ->- val summary = sessionSummaries[sessionKey(session.id)]- if (!summary.isNullOrBlank() && summary != session.title) {- session.copy(title = summary)- } else {- session- }- }- appState.copy(chat = appState.chat.copy(sessions = updatedSessions))- }- }-- private fun scheduleSessionSummary(sessionId: String) {- val scope = scope ?: return- sessionSummaryJob?.cancel()- if (sessionSummaries.containsKey(sessionKey(sessionId))) return- val summaryInput = buildSessionSummaryInput(sessionId) ?: return- val target = resolveTarget(_state.value.modelSettings)-- sessionSummaryJob = scope.launch(Dispatchers.Default) {- val summary = generateSessionSummary(- input = summaryInput.text,- fallback = summaryInput.fallback,- target = target- ) ?: return@launch- if (!isActive) return@launch- withContext(Dispatchers.Main) {- applySessionSummary(sessionId, summary)- }- }- }-- private data class SessionSummaryInput(val text: String, val fallback: String)-- private fun buildSessionSummaryInput(sessionId: String): SessionSummaryInput? {- val messages = messageStore[sessionId].orEmpty()- if (messages.isEmpty()) return null- val firstUser = messages.filter { it.author == MessageAuthor.User }- .minByOrNull { it.timestampMillis }- ?: return null- val assistants = messages.filter { it.author == MessageAuthor.Assistant }- if (assistants.size != 1) return null- val firstAssistant = assistants.first()- if (firstAssistant.isInterrupted) return null-- val fallback = summarizeQuestion(firstUser.text)- if (fallback.isBlank()) return null- val input = "User: ${firstUser.text}\nAssistant: ${firstAssistant.text}"- return SessionSummaryInput(text = input, fallback = fallback)- }-- private suspend fun generateSessionSummary(- input: String,- fallback: String,- target: LlmModelTarget- ): String? {- if (!llmProvider.isModelDownloaded(target)) {- return sessionTitleFromText(fallback, fallback = fallback)- }- val cleanedInput = sanitizeTitleText(input)- if (cleanedInput.isBlank()) return sessionTitleFromText(fallback, fallback = fallback)-- val messages = listOf(- LlmMessage(text = sessionSummarySystemPrompt, role = LlmMessageRole.System),- LlmMessage(text = cleanedInput, role = LlmMessageRole.User)- )-- val buffer = StringBuilder()- try {- llmProvider.generateChat(- target = target,- messages = messages,- imageFiles = emptyList(),- temperature = 0.2f,- maxTokens = 64- ) { token ->- buffer.append(token)- }- } catch (err: Throwable) {- val fallbackSummary = summarizeQuestion(fallback)- return if (fallbackSummary.isBlank()) null else sessionTitleFromText(fallbackSummary, fallback = fallback)- }-- val raw = sanitizeTitleText(buffer.toString())- if (raw.isBlank()) return null- val words = raw.split(" ")- .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }- .filter { it.isNotBlank() }- if (words.isEmpty()) return null- val summary = words.take(sessionSummaryMaxWords).joinToString(" ")- return sessionTitleFromText(summary, fallback = fallback)- }-- private fun applySessionSummary(sessionId: String, summary: String) {- val sanitized = sessionTitleFromText(summary, fallback = "New Chat")- if (sanitized.isBlank()) return- val summaryKey = sessionKey(sessionId)- if (sessionSummaries[summaryKey] == sanitized) return- sessionSummaries[summaryKey] = sanitized- scope?.launch { sessionPreferences.setSessionSummary(sessionId, sanitized) }- chatRepository.updateSessionTitle(sessionId, sanitized)- _state.update { appState ->- val updatedSessions = appState.chat.sessions.map { session ->- if (session.id == sessionId) {- session.copy(title = sanitized)- } else {- session- }- }- appState.copy(chat = appState.chat.copy(sessions = updatedSessions))- }- }-- private fun summarizeQuestion(text: String): String {- val cleaned = sanitizeTitleText(text)- if (cleaned.isBlank()) return ""- val words = cleaned.split(" ")- .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }- .filter { it.isNotBlank() }- if (words.isEmpty()) return ""- val summaryWords = words.take(sessionSummaryMaxWords)- return summaryWords.joinToString(" ")- }-- private fun loadMessagesFromDb(sessionId: String) {- val messages = chatRepository.getMessages(sessionId)- messageStore[sessionId] = messages.toMutableList()- // Reset branch selections for this session. (Branch selection is computed in-memory.)- branchSelections.getOrPut(sessionId) { mutableMapOf() }.clear()- markSessionAccess(sessionId)- trimSessionCaches()- }-- private fun markSessionAccess(sessionId: String) {- sessionAccessTimes[sessionId] = clock()- }-- private fun trimSessionCaches(availableSessions: Set<String> = _state.value.chat.sessions.map { it.id }.toSet()) {- val availableKeys = availableSessions.map(::sessionKey).toSet()- sessionSummaries.keys.retainAll(availableKeys)-- val keepIds = LinkedHashSet<String>()- val currentSessionId = _state.value.chat.currentSessionId- if (currentSessionId != null && currentSessionId in availableSessions) {- keepIds.add(currentSessionId)- }- val ordered = sessionAccessTimes.entries- .filter { it.key in availableSessions }- .sortedByDescending { it.value }- .map { it.key }- for (id in ordered) {- if (keepIds.size >= MAX_CACHED_SESSIONS) break- keepIds.add(id)- }- messageStore.keys.retainAll(keepIds)- branchSelections.keys.retainAll(keepIds)- sessionAccessTimes.keys.retainAll(keepIds)- }-- private fun removeSessionCaches(sessionId: String) {- messageStore.remove(sessionId)- branchSelections.remove(sessionId)- sessionAccessTimes.remove(sessionId)- }-- private fun sessionKey(sessionId: String): String {- return sessionId.lowercase()- }-- private fun rebuildChatState(sessionId: String?) {- if (sessionId == null) {- _state.update { appState ->- appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))- }- return- }- val messages = messageStore[sessionId].orEmpty()- val path = buildSelectedPath(sessionId)- val childrenMap = buildChildrenMap(messages)- val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }- val branchSelectionIndices = mutableMapOf<String, Int>()- val byId = messages.associateBy { it.id }-- val displayMessages = path.map { message ->- val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"- val siblings = dedupeSiblings(childrenMap[parentKey].orEmpty())- if (siblings.size > 1) {- val selectedId = selectionMap[parentKey]- val index = siblings.indexOfFirst { it.id == selectedId }- branchSelectionIndices[message.id] = if (index >= 0) index + 1 else siblings.size- }- message.copy(branchCount = max(1, siblings.size))- }-- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- messages = displayMessages,- branchSelections = branchSelectionIndices- )- )- }- }-- private fun buildSelectedPath(sessionId: String): List<ChatMessage> {- val messages = messageStore[sessionId].orEmpty()- if (messages.isEmpty()) return emptyList()-- val byId = messages.associateBy { it.id }- val childrenMap = buildChildrenMap(messages)- val roots = dedupeSiblings(messages.filter { message ->- val parentId = message.parentId- parentId == null || byId[parentId] == null- })- if (roots.isEmpty()) return emptyList()-- val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }- var current = selectChild(selectionMap, "__root__", roots)- val path = mutableListOf<ChatMessage>()- val visited = mutableSetOf<String>()-- while (current != null && visited.add(current.id)) {- path.add(current)- if (current.id == streamingParentId) break- val children = dedupeSiblings(childrenMap[current.id].orEmpty())- if (children.isEmpty()) break- current = selectChild(selectionMap, current.id, children)- }- return path- }-- private fun selectChild(- selectionMap: MutableMap<String, String>,- selectionKey: String,- candidates: List<ChatMessage>- ): ChatMessage? {- if (candidates.isEmpty()) return null- val selectedId = selectionMap[selectionKey]- val selected = candidates.firstOrNull { it.id == selectedId }- return selected ?: candidates.last()- }-- private fun buildChildrenMap(messages: List<ChatMessage>): Map<String, List<ChatMessage>> {- val map = mutableMapOf<String, MutableList<ChatMessage>>()- val byId = messages.associateBy { it.id }- messages.forEach { message ->- val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"- map.getOrPut(parentKey) { mutableListOf() }.add(message)- }- return map- }-- private fun dedupeSiblings(messages: List<ChatMessage>): List<ChatMessage> {- if (messages.size <= 1) return messages.sortedBy { it.timestampMillis }- val sorted = messages.sortedBy { it.timestampMillis }- val result = mutableListOf<ChatMessage>()- for (message in sorted) {- val last = result.lastOrNull()- if (last != null && isDuplicate(last, message)) {- continue- }- result.add(message)- }- return result- }-- private fun isDuplicate(left: ChatMessage, right: ChatMessage): Boolean {- if (left.author != right.author) return false- if (left.text != right.text) return false- if (!attachmentsSignature(left.attachments).contentEquals(attachmentsSignature(right.attachments))) return false- return abs(left.timestampMillis - right.timestampMillis) <= 2_000- }-- private fun attachmentsSignature(attachments: List<Attachment>): Array<String> {- return attachments.map { "${it.type}:${it.name}" }.toTypedArray()- }-- private fun updateSelectionForParent(sessionId: String, parentId: String?, childId: String) {- val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }- val selectionKey = parentId ?: "__root__"- selectionMap[selectionKey] = childId- }-- private data class HistorySelection(- val messages: List<LlmMessage>,- val inputTokens: Int,- val inputBudget: Int,- val wasTrimmed: Boolean- )-- private data class PendingOverflow(- val sessionId: String,- val messageId: String- )-- private fun buildPrompt(text: String, attachments: List<Attachment>): PromptResult {- val builder = StringBuilder(text)- val documents = attachments.filter { it.type == AttachmentType.Document }- val images = attachments.filter { it.type == AttachmentType.Image }-- documents.forEachIndexed { index, attachment ->- builder.append("\n\n----- BEGIN DOCUMENT: Document ${index + 1} -----\n")- builder.append("Attached document: ${attachment.name}\n")- builder.append("----- END DOCUMENT: Document ${index + 1} -----")- }-- val imageFiles = images.mapNotNull { attachment ->- val path = attachment.localPath ?: return@mapNotNull null- java.io.File(path).takeIf { it.exists() }- }-- if (imageFiles.isNotEmpty()) {- builder.append("\n\n[")- builder.append(imageFiles.size)- builder.append(" image attachment")- if (imageFiles.size > 1) builder.append("s")- builder.append(" provided]")- imageFiles.forEach {- builder.append("\n")- builder.append(MEDIA_MARKER)- }- }-- return PromptResult(builder.toString(), imageFiles)- }-- private fun buildHistorySelection(- sessionId: String,- promptText: String,- promptImageCount: Int,- currentMessageId: String,- target: LlmModelTarget- ): HistorySelection {- val path = buildSelectedPath(sessionId)- val historyMessages = path.takeWhile { it.id != currentMessageId }- val contextSize = target.contextLength ?: 4096- val maxOutput = target.maxTokens ?: 1024- val inputBudget = max(0, contextSize - maxOutput - OVERFLOW_SAFETY_TOKENS)- val systemTokens = estimateTokens(SYSTEM_PROMPT)- val promptTokens = estimatePromptTokens(promptText, promptImageCount)- val historyTokens = historyMessages.sumOf { estimateTokens(historyText(it)) }- val inputTokens = systemTokens + promptTokens + historyTokens- var remaining = inputBudget - systemTokens - promptTokens-- if (remaining <= 0 || historyMessages.isEmpty()) {- return HistorySelection(emptyList(), inputTokens, inputBudget, inputTokens > inputBudget)- }-- val selected = mutableListOf<LlmMessage>()- for (message in historyMessages.asReversed()) {- val text = historyText(message)- val cost = estimateTokens(text)- if (cost <= remaining) {- selected.add(- LlmMessage(- text = text,- role = if (message.author == MessageAuthor.User) LlmMessageRole.User else LlmMessageRole.Assistant,- hasAttachments = message.attachments.isNotEmpty()- )- )- remaining -= cost- } else {- break- }- }-- return HistorySelection(selected.reversed(), inputTokens, inputBudget, inputTokens > inputBudget)- }-- private fun showOverflowDialog(selection: HistorySelection, target: LlmModelTarget) {- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- overflowDialog = io.ente.ensu.domain.state.OverflowDialogState(- inputTokens = selection.inputTokens,- inputBudget = selection.inputBudget,- contextLength = target.contextLength ?: 4096,- maxOutput = target.maxTokens ?: 1024- )- )- )- }- }-- private fun clearOverflowDialog() {- _state.update { appState ->- appState.copy(chat = appState.chat.copy(overflowDialog = null))- }- }-- private fun historyText(message: ChatMessage): String {- var text = message.text- if (message.author == MessageAuthor.Assistant) {- text = text.replace(Regex("<think>[\\s\\S]*?</think>"), "")- text = text.replace(Regex("<todo_list>[\\s\\S]*?</todo_list>"), "")- } else if (message.attachments.isNotEmpty()) {- text += "\n\n[${message.attachments.size} attachments attached]"- }- return text.trim()- }-- private fun trimToBudget(text: String, budget: Int): String {- if (budget <= 0) return ""- val maxChars = budget * 4- return if (text.length <= maxChars) text else text.takeLast(maxChars)- }-- private fun estimateTokens(text: String): Int {- return max(1, text.length / 4)- }-- private fun estimateImageTokens(imageCount: Int): Int {- return imageCount * IMAGE_TOKEN_ESTIMATE- }-- private fun estimatePromptTokens(promptText: String, imageCount: Int): Int {- return estimateTokens(promptText) + estimateImageTokens(imageCount)- }-- private fun resolveTemperature(settings: ModelSettingsState): Float {- val temperature = settings.temperature.trim().toFloatOrNull()- val resolved = temperature?.takeIf { it >= 0f } ?: DEFAULT_TEMPERATURE- return resolved.coerceIn(0.35f, 0.7f)- }-- private fun resolveTarget(settings: ModelSettingsState): LlmModelTarget {- val useCustom = settings.useCustomModel && settings.modelUrl.isNotBlank()- val url = if (useCustom) settings.modelUrl else DEFAULT_MODEL_URL- val mmproj = if (useCustom) settings.mmprojUrl.takeIf { it.isNotBlank() } else DEFAULT_MMPROJ_URL- val contextLength = settings.contextLength.toIntOrNull()- val maxTokens = settings.maxTokens.toIntOrNull()- val id = if (useCustom) "custom:${url.hashCode()}" else "default"-- return LlmModelTarget(- id = id,- url = url,- mmprojUrl = mmproj,- contextLength = contextLength,- maxTokens = maxTokens- )- }-- private fun loadSessionsFromDb() {- val sessions = chatRepository.listSessions().map { session ->- val summary = sessionSummaries[sessionKey(session.id)]- if (!summary.isNullOrBlank()) {- session.copy(title = summary)- } else {- session- }- }-- val currentSessionId = _state.value.chat.currentSessionId- val sessionStillExists = currentSessionId != null && sessions.any { it.id == currentSessionId }-- _state.update { appState ->- appState.copy(- chat = appState.chat.copy(- sessions = sessions,- currentSessionId = if (sessionStillExists) currentSessionId else null- )- )- }-- if (sessionStillExists && currentSessionId != null) {- loadMessagesFromDb(currentSessionId)- rebuildChatState(currentSessionId)- } else {- updateAttachmentDownloadState()- }- trimSessionCaches(sessions.map { it.id }.toSet())- }-- private data class PromptResult(- val text: String,- val imageFiles: List<java.io.File>- )-- companion object {- private const val DEFAULT_MODEL_URL =- "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf"- private const val DEFAULT_MMPROJ_URL =- "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"- private const val MEDIA_MARKER = "<__media__>"- private const val OVERFLOW_SAFETY_TOKENS = 128- private const val IMAGE_TOKEN_ESTIMATE = 768- private const val DEFAULT_TEMPERATURE = 0.5f- private const val MAX_CACHED_SESSIONS = 8- private const val SYSTEM_PROMPT =- "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put \$\$ on its own line (never inline). Example:\n\$\$\nx^2 + y^2 = z^2\n\$\$"- }+ fun cancelAttachmentDownload(attachmentId: String) =+ attachmentActions.cancelAttachmentDownload(attachmentId)}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AttachmentStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AttachmentStoreActions.ktnew file mode 100644index 0000000000..314c44f4da--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AttachmentStoreActions.kt@@ -0,0 +1,222 @@+package io.ente.ensu.domain.store++import io.ente.ensu.domain.chat.ChatSyncRepository+import io.ente.ensu.domain.model.Attachment+import io.ente.ensu.domain.model.AttachmentDownloadItem+import io.ente.ensu.domain.model.AttachmentDownloadStatus+import io.ente.ensu.domain.model.ChatMessage+import io.ente.ensu.domain.state.AppState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.ConcurrentLinkedDeque++internal class AttachmentStoreActions(+ private val state: MutableStateFlow<AppState>,+ private val chatSyncRepository: ChatSyncRepository?,+ private val messageStore: MutableMap<String, MutableList<ChatMessage>>+) {+ private val attachmentDownloads = ConcurrentHashMap<String, AttachmentDownloadItem>()+ private val attachmentDownloadQueue = ConcurrentLinkedDeque<String>()+ private val attachmentDownloadActive = ConcurrentHashMap<String, Job>()+ private val maxAttachmentDownloadConcurrency = 2+ private var scope: CoroutineScope? = null++ fun setScope(scope: CoroutineScope) {+ this.scope = scope+ }++ fun setAttachmentProcessing(isProcessing: Boolean) {+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(isProcessingAttachments = isProcessing))+ }+ }++ fun addAttachment(attachment: Attachment) {+ if (state.value.chat.isGenerating ||+ state.value.chat.isDownloading ||+ state.value.chat.isAttachmentDownloadBlocked+ ) return++ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ attachments = appState.chat.attachments + attachment,+ isProcessingAttachments = false+ )+ )+ }+ }++ fun removeAttachment(attachment: Attachment) {+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ attachments = appState.chat.attachments.filterNot { it.id == attachment.id }+ )+ )+ }+ }++ fun cancelAttachmentDownload(attachmentId: String) {+ attachmentDownloadActive[attachmentId]?.cancel()+ attachmentDownloadActive.remove(attachmentId)+ attachmentDownloadQueue.removeIf { it == attachmentId }+ attachmentDownloads[attachmentId]?.let { item ->+ attachmentDownloads[attachmentId] = item.copy(status = AttachmentDownloadStatus.Canceled)+ }+ updateAttachmentDownloadState()+ startNextAttachmentDownloads()+ }++ fun ensureAttachmentsAvailable(sessionId: String) {+ val missing = missingAttachments(sessionId)+ if (missing.isEmpty()) {+ updateAttachmentDownloadState()+ return+ }+ queueAttachmentDownloads(missing)+ updateAttachmentDownloadState()+ }++ fun missingAttachments(sessionId: String): List<AttachmentDownloadItem> {+ val messages = messageStore[sessionId].orEmpty()+ if (messages.isEmpty()) return emptyList()+ val seen = mutableSetOf<String>()+ val missing = mutableListOf<AttachmentDownloadItem>()++ for (message in messages) {+ for (attachment in message.attachments) {+ if (!seen.add(attachment.id)) continue+ val path = attachment.localPath+ if (path != null && File(path).exists()) {+ attachmentDownloadActive[attachment.id]?.cancel()+ attachmentDownloadActive.remove(attachment.id)+ attachmentDownloadQueue.removeIf { it == attachment.id }+ attachmentDownloads.remove(attachment.id)+ continue+ }+ val existing = attachmentDownloads[attachment.id]+ val status = existing?.status ?: AttachmentDownloadStatus.Queued+ missing.add(+ AttachmentDownloadItem(+ id = attachment.id,+ sessionId = sessionId,+ name = attachment.name,+ sizeBytes = attachment.sizeBytes,+ status = status+ )+ )+ }+ }++ return missing+ }++ fun purgeAttachmentDownloads(sessionId: String) {+ val ids = attachmentDownloads.values.filter { it.sessionId == sessionId }.map { it.id }+ ids.forEach { id ->+ attachmentDownloadActive[id]?.cancel()+ attachmentDownloadActive.remove(id)+ attachmentDownloadQueue.removeIf { it == id }+ attachmentDownloads.remove(id)+ }+ updateAttachmentDownloadState()+ }++ fun refreshAttachmentDownloadState() {+ updateAttachmentDownloadState()+ }++ private fun queueAttachmentDownloads(items: List<AttachmentDownloadItem>) {+ items.forEach { item ->+ val existing = attachmentDownloads[item.id]+ val updated = if (existing == null ||+ existing.status == AttachmentDownloadStatus.Failed ||+ existing.status == AttachmentDownloadStatus.Canceled+ ) {+ item+ } else {+ existing+ }+ attachmentDownloads[item.id] = updated+ if (updated.status != AttachmentDownloadStatus.Completed &&+ updated.status != AttachmentDownloadStatus.Canceled &&+ attachmentDownloadActive[item.id] == null &&+ !attachmentDownloadQueue.contains(item.id)+ ) {+ attachmentDownloadQueue.addLast(item.id)+ }+ }+ startNextAttachmentDownloads()+ }++ private fun startNextAttachmentDownloads() {+ val scope = scope ?: return+ while (attachmentDownloadActive.size < maxAttachmentDownloadConcurrency && attachmentDownloadQueue.isNotEmpty()) {+ val id = attachmentDownloadQueue.pollFirst() ?: continue+ if (attachmentDownloadActive.containsKey(id)) {+ continue+ }+ val item = attachmentDownloads[id] ?: continue+ if (item.status == AttachmentDownloadStatus.Completed || item.status == AttachmentDownloadStatus.Canceled) {+ continue+ }+ attachmentDownloads[id] = item.copy(status = AttachmentDownloadStatus.Downloading)+ updateAttachmentDownloadState()++ val job = scope.launch(Dispatchers.IO) {+ val result = runCatching {+ chatSyncRepository?.downloadAttachment(id, item.sessionId)+ ?: throw IllegalStateException("Sync unavailable")+ }+ val status = if (result.isSuccess) {+ AttachmentDownloadStatus.Completed+ } else {+ AttachmentDownloadStatus.Failed+ }+ withContext(Dispatchers.Main) {+ attachmentDownloads[id]?.let { current ->+ if (current.status != AttachmentDownloadStatus.Canceled) {+ attachmentDownloads[id] = current.copy(status = status)+ }+ }+ attachmentDownloadActive.remove(id)+ updateAttachmentDownloadState()+ startNextAttachmentDownloads()+ }+ }+ attachmentDownloadActive[id] = job+ }+ }++ private fun updateAttachmentDownloadState() {+ val currentSessionId = state.value.chat.currentSessionId+ val missing = currentSessionId?.let { missingAttachments(it) }.orEmpty()+ val items = attachmentDownloads.values.sortedBy { it.name }+ val active = items.filter { it.status != AttachmentDownloadStatus.Canceled }+ val total = active.size+ val completed = active.count { it.status == AttachmentDownloadStatus.Completed }+ val hasPending = active.any {+ it.status == AttachmentDownloadStatus.Queued ||+ it.status == AttachmentDownloadStatus.Downloading ||+ it.status == AttachmentDownloadStatus.Failed+ }+ val progress = if (total > 0 && hasPending) (completed * 100 / total) else null+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ attachmentDownloads = items,+ attachmentDownloadProgress = progress,+ isAttachmentDownloadBlocked = missing.isNotEmpty()+ )+ )+ }+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.ktnew file mode 100644index 0000000000..456e05ac61--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AuthStoreActions.kt@@ -0,0 +1,30 @@+package io.ente.ensu.domain.store++import io.ente.ensu.domain.logging.LogRepository+import io.ente.ensu.domain.model.AuthState+import io.ente.ensu.domain.model.LogLevel+import io.ente.ensu.domain.state.AppState+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update++internal class AuthStoreActions(+ private val state: MutableStateFlow<AppState>,+ private val logRepository: LogRepository,+ private val onSync: () -> Unit+) {+ fun signIn(email: String) {+ state.update { appState ->+ appState.copy(auth = AuthState(isLoggedIn = true, email = email))+ }+ // Do not log PII like user email.+ logRepository.log(LogLevel.Info, "Signed in", tag = "Auth")+ onSync()+ }++ fun signOut() {+ state.update { appState ->+ appState.copy(auth = AuthState())+ }+ logRepository.log(LogLevel.Info, "Signed out", tag = "Auth")+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.ktnew file mode 100644index 0000000000..a915b0a165--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt@@ -0,0 +1,1125 @@+package io.ente.ensu.domain.store++import io.ente.ensu.domain.chat.ChatRepository+import io.ente.ensu.domain.logging.LogRepository+import io.ente.ensu.domain.llm.LlmMessage+import io.ente.ensu.domain.llm.LlmMessageRole+import io.ente.ensu.domain.llm.LlmModelTarget+import io.ente.ensu.domain.llm.LlmProvider+import io.ente.ensu.domain.model.Attachment+import io.ente.ensu.domain.model.ChatMessage+import io.ente.ensu.domain.model.ChatSession+import io.ente.ensu.domain.model.LogLevel+import io.ente.ensu.domain.model.MessageAuthor+import io.ente.ensu.domain.model.sanitizeTitleText+import io.ente.ensu.domain.model.sessionTitleFromText+import io.ente.ensu.domain.preferences.SessionPreferences+import io.ente.ensu.domain.state.AppState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlin.math.abs+import kotlin.math.max++internal class ChatStoreActions(+ private val state: MutableStateFlow<AppState>,+ private val sessionPreferences: SessionPreferences,+ private val chatRepository: ChatRepository,+ private val llmProvider: LlmProvider,+ private val clock: () -> Long,+ private val logRepository: LogRepository,+ private val messageStore: MutableMap<String, MutableList<ChatMessage>>,+ private val attachmentActions: AttachmentStoreActions,+ private val syncActions: SyncStoreActions,+ private val modelSettingsActions: ModelSettingsActions+) {+ private val branchSelections = mutableMapOf<String, MutableMap<String, String>>()+ private val sessionSummaries = mutableMapOf<String, String>()+ private val sessionAccessTimes = mutableMapOf<String, Long>()+ private var scope: CoroutineScope? = null+ private var generationJob: Job? = null+ private var sessionSummaryJob: Job? = null+ private var stopRequested = false+ private var streamingParentId: String? = null+ private var activeGenerationToken = 0L+ private var pendingOverflow: PendingOverflow? = null+ private var overflowBypassMessageId: String? = null++ private val sessionSummarySystemPrompt =+ "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no markdown characters, no quotes, no emojis, no trailing punctuation, and output only the title."+ private val sessionSummaryMaxWords = 7++ fun setScope(scope: CoroutineScope) {+ this.scope = scope+ }++ fun bootstrap(scope: CoroutineScope) {+ this.scope = scope++ sessionSummaries.clear()+ scope.launch {+ val summaries = sessionPreferences.sessionSummaries.first()+ sessionSummaries.clear()+ sessionSummaries.putAll(summaries.mapKeys { sessionKey(it.key) })+ applySessionSummariesToState()+ }++ if (state.value.chat.sessions.isEmpty()) {+ loadSessionsFromDb()+ }++ scope.launch {+ sessionPreferences.sessionSummaries.collectLatest { summaries ->+ sessionSummaries.clear()+ sessionSummaries.putAll(summaries.mapKeys { sessionKey(it.key) })+ applySessionSummariesToState()+ }+ }+ }++ fun createNewSession(): String {+ resetGenerationState()++ val session = chatRepository.createSession("New Chat")+ messageStore[session.id] = mutableListOf()+ branchSelections[session.id] = mutableMapOf()++ state.update { appState ->+ val updatedSessions = listOf(session) + appState.chat.sessions+ appState.copy(+ chat = appState.chat.copy(+ sessions = updatedSessions,+ currentSessionId = session.id,+ messageText = "",+ attachments = emptyList(),+ editingMessageId = null+ )+ )+ }+ markSessionAccess(session.id)+ trimSessionCaches()+ rebuildChatState(session.id)+ attachmentActions.refreshAttachmentDownloadState()+ logRepository.log(LogLevel.Info, "Session created", tag = "Chat")+ return session.id+ }++ fun startNewSessionDraft() {+ resetGenerationState()+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ currentSessionId = null,+ messages = emptyList(),+ branchSelections = emptyMap(),+ messageText = "",+ attachments = emptyList(),+ editingMessageId = null+ )+ )+ }+ attachmentActions.refreshAttachmentDownloadState()+ }++ fun selectSession(sessionId: String) {+ resetGenerationState()+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ currentSessionId = sessionId+ )+ )+ }+ val scope = scope ?: return+ scope.launch(Dispatchers.IO) {+ loadMessagesFromDb(sessionId)+ rebuildChatState(sessionId)+ attachmentActions.ensureAttachmentsAvailable(sessionId)+ }+ }++ fun deleteSession(sessionId: String) {+ val currentState = state.value+ val isCurrent = currentState.chat.currentSessionId == sessionId++ if (isCurrent) {+ cancelGeneration()+ }++ chatRepository.deleteSession(sessionId)+ removeSessionCaches(sessionId)+ attachmentActions.purgeAttachmentDownloads(sessionId)+ sessionSummaries.remove(sessionKey(sessionId))+ scope?.launch { sessionPreferences.setSessionSummary(sessionId, null) }++ val sessions = currentState.chat.sessions.filterNot { it.id == sessionId }++ val newCurrent = if (isCurrent) {+ sessions.firstOrNull()?.id+ } else {+ currentState.chat.currentSessionId?.takeIf { id -> sessions.any { it.id == id } }+ ?: sessions.firstOrNull()?.id+ }++ state.update { appState ->+ val resetCurrent = isCurrent+ appState.copy(+ chat = appState.chat.copy(+ sessions = sessions,+ currentSessionId = newCurrent,+ isGenerating = if (resetCurrent) false else appState.chat.isGenerating,+ isDownloading = if (resetCurrent) false else appState.chat.isDownloading,+ streamingResponse = if (resetCurrent) "" else appState.chat.streamingResponse,+ streamingParentId = if (resetCurrent) null else appState.chat.streamingParentId,+ downloadPercent = if (resetCurrent) null else appState.chat.downloadPercent,+ downloadStatus = if (resetCurrent) null else appState.chat.downloadStatus,+ messageText = if (resetCurrent) "" else appState.chat.messageText,+ attachments = if (resetCurrent) emptyList() else appState.chat.attachments,+ editingMessageId = if (resetCurrent) null else appState.chat.editingMessageId+ )+ )+ }++ if (newCurrent != null) {+ val scope = scope+ if (scope != null) {+ scope.launch(Dispatchers.IO) {+ loadMessagesFromDb(newCurrent)+ rebuildChatState(newCurrent)+ attachmentActions.ensureAttachmentsAvailable(newCurrent)+ }+ } else {+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))+ }+ }+ } else {+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))+ }+ }+ trimSessionCaches(sessions.map { it.id }.toSet())++ scope?.launch { sessionPreferences.setSelectedSessionId(newCurrent) }+ syncActions.syncNow()+ logRepository.log(LogLevel.Info, "Session deleted", tag = "Chat")+ }++ fun persistSelectedSession(scope: CoroutineScope, sessionId: String?) {+ scope.launch {+ sessionPreferences.setSelectedSessionId(sessionId)+ }+ }++ fun updateMessageText(value: String) {+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(messageText = value))+ }+ }++ fun updateBranchSelection(messageId: String, selectedIndex: Int) {+ if (state.value.chat.isGenerating) {+ stopGeneration()+ }+ val sessionId = state.value.chat.currentSessionId ?: return+ val messages = messageStore[sessionId].orEmpty()+ val byId = messages.associateBy { it.id }+ val message = byId[messageId] ?: return+ val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"+ val siblings = dedupeSiblings(buildChildrenMap(messages)[parentKey].orEmpty())+ if (siblings.isEmpty()) return+ val index = (selectedIndex - 1).coerceIn(0, siblings.lastIndex)+ val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }+ selectionMap[parentKey] = siblings[index].id+ rebuildChatState(sessionId)+ }++ fun beginEditing(messageId: String) {+ val sessionId = state.value.chat.currentSessionId ?: return+ val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return+ if (message.author != MessageAuthor.User) return++ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ editingMessageId = message.id,+ messageText = message.text,+ attachments = message.attachments+ )+ )+ }+ }++ fun cancelEditing() {+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ editingMessageId = null,+ messageText = "",+ attachments = emptyList()+ )+ )+ }+ }++ fun stopGeneration() {+ stopRequested = true+ llmProvider.stopGeneration()+ }++ fun retryAssistantMessage(messageId: String) {+ if (state.value.chat.isGenerating) {+ stopGeneration()+ }+ val sessionId = state.value.chat.currentSessionId ?: return+ val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return+ if (message.author != MessageAuthor.Assistant) return+ val parentId = message.parentId ?: return+ val parent = messageStore[sessionId]?.firstOrNull { it.id == parentId } ?: return++ if (attachmentActions.missingAttachments(sessionId).isNotEmpty()) {+ attachmentActions.ensureAttachmentsAvailable(sessionId)+ return+ }+ llmProvider.resetContext()+ startGeneration(sessionId, parent)+ syncActions.requestSync()+ }++ fun sendMessage() {+ val currentState = state.value+ if (currentState.chat.isGenerating || currentState.chat.isDownloading) return+ val text = currentState.chat.messageText.trim()+ val attachments = currentState.chat.attachments+ if (text.isEmpty() && attachments.isEmpty()) return++ val sessionId = currentState.chat.currentSessionId ?: createNewSession()+ if (attachmentActions.missingAttachments(sessionId).isNotEmpty()) {+ attachmentActions.ensureAttachmentsAvailable(sessionId)+ return+ }+ val timestamp = clock()++ val editingMessageId = currentState.chat.editingMessageId+ val parentId = if (editingMessageId != null) {+ val existing = messageStore[sessionId]?.firstOrNull { it.id == editingMessageId }+ existing?.parentId+ } else {+ buildSelectedPath(sessionId).lastOrNull()?.id+ }++ val userMessage = chatRepository.insertMessage(+ sessionId = sessionId,+ parentId = parentId,+ author = MessageAuthor.User,+ text = text,+ attachments = attachments+ )++ messageStore.getOrPut(sessionId) { mutableListOf() }.add(userMessage)+ updateSelectionForParent(sessionId, parentId, userMessage.id)++ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ messageText = "",+ attachments = emptyList(),+ editingMessageId = null+ )+ )+ }++ updateCurrentSessionPreview(sessionId, text, timestamp)+ rebuildChatState(sessionId)+ startGeneration(sessionId, userMessage)+ syncActions.requestSync()+ logRepository.log(+ LogLevel.Info,+ "Message sent",+ details = "len=${text.length} attachments=${attachments.size} edited=${editingMessageId != null}",+ tag = "Chat"+ )+ }++ fun confirmOverflowTrim() {+ val pending = pendingOverflow ?: return+ val message = messageStore[pending.sessionId]?.firstOrNull { it.id == pending.messageId }+ if (message == null) {+ pendingOverflow = null+ overflowBypassMessageId = null+ clearOverflowDialog()+ return+ }+ overflowBypassMessageId = pending.messageId+ pendingOverflow = null+ clearOverflowDialog()+ startGeneration(pending.sessionId, message)+ }++ fun cancelOverflowDialog() {+ pendingOverflow = null+ overflowBypassMessageId = null+ clearOverflowDialog()+ }++ fun cancelGenerationForDownload() {+ resetGenerationState()+ }++ fun loadSessionsFromDb() {+ val scope = scope ?: return+ scope.launch(Dispatchers.IO) {+ val sessions = chatRepository.listSessions().map { session ->+ val summary = sessionSummaries[sessionKey(session.id)]+ if (!summary.isNullOrBlank()) {+ session.copy(title = summary)+ } else {+ session+ }+ }++ val currentSessionId = state.value.chat.currentSessionId+ val sessionStillExists = currentSessionId != null && sessions.any { it.id == currentSessionId }++ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ sessions = sessions,+ currentSessionId = if (sessionStillExists) currentSessionId else null+ )+ )+ }++ if (sessionStillExists && currentSessionId != null) {+ loadMessagesFromDb(currentSessionId)+ rebuildChatState(currentSessionId)+ } else {+ attachmentActions.refreshAttachmentDownloadState()+ }+ trimSessionCaches(sessions.map { it.id }.toSet())+ }+ }++ private fun startGeneration(sessionId: String, userMessage: ChatMessage) {+ val scope = scope ?: return+ generationJob?.cancel()+ sessionSummaryJob?.cancel()+ stopRequested = false++ val settings = state.value.modelSettings+ val target = modelSettingsActions.resolveTarget(settings)+ val prompt = buildPrompt(userMessage.text, userMessage.attachments)+ val historySelection = buildHistorySelection(+ sessionId = sessionId,+ promptText = prompt.text,+ promptImageCount = prompt.imageFiles.size,+ currentMessageId = userMessage.id,+ target = target+ )++ if (historySelection.wasTrimmed && overflowBypassMessageId != userMessage.id) {+ pendingOverflow = PendingOverflow(sessionId, userMessage.id)+ showOverflowDialog(historySelection, target)+ return+ }++ overflowBypassMessageId = null+ pendingOverflow = null+ clearOverflowDialog()++ val generationToken = nextGenerationToken()+ streamingParentId = userMessage.id+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = true,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = userMessage.id,+ downloadPercent = null,+ downloadStatus = null,+ hasRequestedModelDownload = true+ )+ )+ }+ rebuildChatState(sessionId)++ generationJob = scope.launch {+ val isActive = { isGenerationActive(generationToken, sessionId) }+ try {+ llmProvider.ensureModelReady(target) { progress ->+ if (!isActive()) return@ensureModelReady+ val downloading = (progress.percent in 0..99) || progress.status.contains("Loading", ignoreCase = true)+ val finished = progress.status.contains("Ready", ignoreCase = true)+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = downloading && !finished,+ downloadPercent = progress.percent.takeIf { it >= 0 },+ downloadStatus = progress.status,+ isModelDownloaded = if (finished) true else appState.chat.isModelDownloaded,+ modelDownloadSizeBytes = if (finished) null else appState.chat.modelDownloadSizeBytes+ )+ )+ }+ }+ } catch (err: Throwable) {+ val cancelled = err is kotlinx.coroutines.CancellationException ||+ err.message?.contains("cancel", ignoreCase = true) == true+ if (!isActive()) return@launch+ streamingParentId = null+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = false,+ isDownloading = false,+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = if (cancelled) "Download cancelled" else null,+ hasRequestedModelDownload = if (cancelled) false else appState.chat.hasRequestedModelDownload+ )+ )+ }+ if (!cancelled) {+ logRepository.log(+ LogLevel.Error,+ "Model load failed",+ details = err.message,+ tag = "Model",+ throwable = err+ )+ }+ syncActions.syncAfterGeneration()+ return@launch+ }++ if (!isActive()) return@launch++ val history = historySelection.messages+ val systemMessage = LlmMessage(+ text = SYSTEM_PROMPT,+ role = LlmMessageRole.System+ )+ val llmMessages = listOf(systemMessage) + history + LlmMessage(+ text = prompt.text,+ role = LlmMessageRole.User,+ hasAttachments = userMessage.attachments.isNotEmpty()+ )++ val buffer = StringBuilder()+ var tokenCount = 0++ try {+ val summary = llmProvider.generateChat(+ target = target,+ messages = llmMessages,+ imageFiles = prompt.imageFiles,+ temperature = modelSettingsActions.resolveTemperature(settings),+ maxTokens = target.maxTokens ?: 1024+ ) { token ->+ buffer.append(token)+ tokenCount += estimateTokens(token)+ if (isActive()) {+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(streamingResponse = buffer.toString()))+ }+ }+ }++ finishGeneration(+ sessionId,+ userMessage,+ buffer,+ tokenCount,+ summary.totalTimeMs,+ interrupted = false,+ shouldUpdateUi = isActive()+ )+ } catch (err: Throwable) {+ val interrupted = stopRequested || err.message?.contains("cancel", ignoreCase = true) == true+ finishGeneration(+ sessionId,+ userMessage,+ buffer,+ tokenCount,+ totalTimeMs = null,+ interrupted = interrupted,+ shouldUpdateUi = isActive()+ )+ if (!interrupted) {+ logRepository.log(+ LogLevel.Error,+ "Generation failed",+ details = err.message,+ tag = "LLM",+ throwable = err+ )+ }+ }+ }+ }++ private fun finishGeneration(+ sessionId: String,+ parentMessage: ChatMessage,+ buffer: StringBuilder,+ tokenCount: Int,+ totalTimeMs: Long?,+ interrupted: Boolean,+ shouldUpdateUi: Boolean+ ) {+ val finalText = buffer.toString().trim()+ if (finalText.isNotEmpty()) {+ val tokensPerSecond = if (totalTimeMs != null && totalTimeMs > 0) {+ tokenCount.toDouble() / (totalTimeMs / 1000.0)+ } else null++ val inserted = chatRepository.insertMessage(+ sessionId = sessionId,+ parentId = parentMessage.id,+ author = MessageAuthor.Assistant,+ text = finalText,+ attachments = emptyList()+ )++ val assistantMessage = inserted.copy(+ isInterrupted = interrupted,+ tokensPerSecond = tokensPerSecond+ )++ messageStore.getOrPut(sessionId) { mutableListOf() }.add(assistantMessage)+ updateSelectionForParent(sessionId, parentMessage.id, assistantMessage.id)+ updateCurrentSessionPreview(sessionId, finalText, assistantMessage.timestampMillis)+ }++ if (shouldUpdateUi) {+ streamingParentId = null+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = false,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = null+ )+ )+ }+ rebuildChatState(sessionId)+ syncActions.syncAfterGeneration()+ }+ scheduleSessionSummary(sessionId)+ }++ private fun updateCurrentSessionPreview(sessionId: String, preview: String, timestamp: Long) {+ state.update { appState ->+ val updatedSessions = appState.chat.sessions.map { session ->+ if (session.id == sessionId) {+ val shouldUpdateTitle = session.title.isBlank() || session.title.equals("New Chat", ignoreCase = true)+ val updatedTitle = if (shouldUpdateTitle) {+ sessionTitleFromText(preview, fallback = session.title)+ } else {+ session.title+ }+ if (updatedTitle != session.title) {+ chatRepository.updateSessionTitle(sessionId, updatedTitle)+ }+ session.copy(+ title = updatedTitle,+ lastMessagePreview = preview,+ updatedAtMillis = timestamp+ )+ } else {+ session+ }+ }+ appState.copy(chat = appState.chat.copy(sessions = updatedSessions))+ }+ }++ private fun applySessionSummariesToState() {+ state.update { appState ->+ val updatedSessions = appState.chat.sessions.map { session ->+ val summary = sessionSummaries[sessionKey(session.id)]+ if (!summary.isNullOrBlank() && summary != session.title) {+ session.copy(title = summary)+ } else {+ session+ }+ }+ appState.copy(chat = appState.chat.copy(sessions = updatedSessions))+ }+ }++ private fun scheduleSessionSummary(sessionId: String) {+ val scope = scope ?: return+ sessionSummaryJob?.cancel()+ if (sessionSummaries.containsKey(sessionKey(sessionId))) return+ val summaryInput = buildSessionSummaryInput(sessionId) ?: return+ val target = modelSettingsActions.resolveTarget(state.value.modelSettings)++ sessionSummaryJob = scope.launch(Dispatchers.Default) {+ val summary = generateSessionSummary(+ input = summaryInput.text,+ fallback = summaryInput.fallback,+ target = target+ ) ?: return@launch+ if (!isActive) return@launch+ withContext(Dispatchers.Main) {+ applySessionSummary(sessionId, summary)+ }+ }+ }++ private data class SessionSummaryInput(val text: String, val fallback: String)++ private fun buildSessionSummaryInput(sessionId: String): SessionSummaryInput? {+ val messages = messageStore[sessionId].orEmpty()+ if (messages.isEmpty()) return null+ val firstUser = messages.filter { it.author == MessageAuthor.User }+ .minByOrNull { it.timestampMillis }+ ?: return null+ val assistants = messages.filter { it.author == MessageAuthor.Assistant }+ if (assistants.size != 1) return null+ val firstAssistant = assistants.first()+ if (firstAssistant.isInterrupted) return null++ val fallback = summarizeQuestion(firstUser.text)+ if (fallback.isBlank()) return null+ val input = "User: ${firstUser.text}\nAssistant: ${firstAssistant.text}"+ return SessionSummaryInput(text = input, fallback = fallback)+ }++ private suspend fun generateSessionSummary(+ input: String,+ fallback: String,+ target: LlmModelTarget+ ): String? {+ if (!llmProvider.isModelDownloaded(target)) {+ return sessionTitleFromText(fallback, fallback = fallback)+ }+ val cleanedInput = sanitizeTitleText(input)+ if (cleanedInput.isBlank()) return sessionTitleFromText(fallback, fallback = fallback)++ val messages = listOf(+ LlmMessage(text = sessionSummarySystemPrompt, role = LlmMessageRole.System),+ LlmMessage(text = cleanedInput, role = LlmMessageRole.User)+ )++ val buffer = StringBuilder()+ try {+ llmProvider.generateChat(+ target = target,+ messages = messages,+ imageFiles = emptyList(),+ temperature = 0.2f,+ maxTokens = 64+ ) { token ->+ buffer.append(token)+ }+ } catch (err: Throwable) {+ val fallbackSummary = summarizeQuestion(fallback)+ return if (fallbackSummary.isBlank()) null else sessionTitleFromText(fallbackSummary, fallback = fallback)+ }++ val raw = sanitizeTitleText(buffer.toString())+ if (raw.isBlank()) return null+ val words = raw.split(" ")+ .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }+ .filter { it.isNotBlank() }+ if (words.isEmpty()) return null+ val summary = words.take(sessionSummaryMaxWords).joinToString(" ")+ return sessionTitleFromText(summary, fallback = fallback)+ }++ private fun applySessionSummary(sessionId: String, summary: String) {+ val sanitized = sessionTitleFromText(summary, fallback = "New Chat")+ if (sanitized.isBlank()) return+ val summaryKey = sessionKey(sessionId)+ if (sessionSummaries[summaryKey] == sanitized) return+ sessionSummaries[summaryKey] = sanitized+ scope?.launch { sessionPreferences.setSessionSummary(sessionId, sanitized) }+ chatRepository.updateSessionTitle(sessionId, sanitized)+ state.update { appState ->+ val updatedSessions = appState.chat.sessions.map { session ->+ if (session.id == sessionId) {+ session.copy(title = sanitized)+ } else {+ session+ }+ }+ appState.copy(chat = appState.chat.copy(sessions = updatedSessions))+ }+ }++ private fun summarizeQuestion(text: String): String {+ val cleaned = sanitizeTitleText(text)+ if (cleaned.isBlank()) return ""+ val words = cleaned.split(" ")+ .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }+ .filter { it.isNotBlank() }+ if (words.isEmpty()) return ""+ val summaryWords = words.take(sessionSummaryMaxWords)+ return summaryWords.joinToString(" ")+ }++ private suspend fun loadMessagesFromDb(sessionId: String) {+ val messages = withContext(Dispatchers.IO) {+ chatRepository.getMessages(sessionId)+ }+ messageStore[sessionId] = messages.toMutableList()+ branchSelections.getOrPut(sessionId) { mutableMapOf() }.clear()+ markSessionAccess(sessionId)+ trimSessionCaches()+ }++ private fun markSessionAccess(sessionId: String) {+ sessionAccessTimes[sessionId] = clock()+ }++ private fun trimSessionCaches(availableSessions: Set<String> = state.value.chat.sessions.map { it.id }.toSet()) {+ val availableKeys = availableSessions.map(::sessionKey).toSet()+ sessionSummaries.keys.retainAll(availableKeys)++ val keepIds = LinkedHashSet<String>()+ val currentSessionId = state.value.chat.currentSessionId+ if (currentSessionId != null && currentSessionId in availableSessions) {+ keepIds.add(currentSessionId)+ }+ val ordered = sessionAccessTimes.entries+ .filter { it.key in availableSessions }+ .sortedByDescending { it.value }+ .map { it.key }+ for (id in ordered) {+ if (keepIds.size >= MAX_CACHED_SESSIONS) break+ keepIds.add(id)+ }+ messageStore.keys.retainAll(keepIds)+ branchSelections.keys.retainAll(keepIds)+ sessionAccessTimes.keys.retainAll(keepIds)+ }++ private fun removeSessionCaches(sessionId: String) {+ messageStore.remove(sessionId)+ branchSelections.remove(sessionId)+ sessionAccessTimes.remove(sessionId)+ }++ private fun sessionKey(sessionId: String): String {+ return sessionId.lowercase()+ }++ private fun rebuildChatState(sessionId: String?) {+ if (sessionId == null) {+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))+ }+ return+ }+ val messages = messageStore[sessionId].orEmpty()+ val path = buildSelectedPath(sessionId)+ val childrenMap = buildChildrenMap(messages)+ val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }+ val branchSelectionIndices = mutableMapOf<String, Int>()+ val byId = messages.associateBy { it.id }++ val displayMessages = path.map { message ->+ val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"+ val siblings = dedupeSiblings(childrenMap[parentKey].orEmpty())+ if (siblings.size > 1) {+ val selectedId = selectionMap[parentKey]+ val index = siblings.indexOfFirst { it.id == selectedId }+ branchSelectionIndices[message.id] = if (index >= 0) index + 1 else siblings.size+ }+ message.copy(branchCount = max(1, siblings.size))+ }++ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ messages = displayMessages,+ branchSelections = branchSelectionIndices+ )+ )+ }+ }++ private fun buildSelectedPath(sessionId: String): List<ChatMessage> {+ val messages = messageStore[sessionId].orEmpty()+ if (messages.isEmpty()) return emptyList()++ val byId = messages.associateBy { it.id }+ val childrenMap = buildChildrenMap(messages)+ val roots = dedupeSiblings(messages.filter { message ->+ val parentId = message.parentId+ parentId == null || byId[parentId] == null+ })+ if (roots.isEmpty()) return emptyList()++ val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }+ var current = selectChild(selectionMap, "__root__", roots)+ val path = mutableListOf<ChatMessage>()+ val visited = mutableSetOf<String>()++ while (current != null && visited.add(current.id)) {+ path.add(current)+ if (current.id == streamingParentId) break+ val children = dedupeSiblings(childrenMap[current.id].orEmpty())+ if (children.isEmpty()) break+ current = selectChild(selectionMap, current.id, children)+ }+ return path+ }++ private fun selectChild(+ selectionMap: MutableMap<String, String>,+ selectionKey: String,+ candidates: List<ChatMessage>+ ): ChatMessage? {+ if (candidates.isEmpty()) return null+ val selectedId = selectionMap[selectionKey]+ val selected = candidates.firstOrNull { it.id == selectedId }+ return selected ?: candidates.last()+ }++ private fun buildChildrenMap(messages: List<ChatMessage>): Map<String, List<ChatMessage>> {+ val map = mutableMapOf<String, MutableList<ChatMessage>>()+ val byId = messages.associateBy { it.id }+ messages.forEach { message ->+ val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"+ map.getOrPut(parentKey) { mutableListOf() }.add(message)+ }+ return map+ }++ private fun dedupeSiblings(messages: List<ChatMessage>): List<ChatMessage> {+ if (messages.size <= 1) return messages.sortedBy { it.timestampMillis }+ val sorted = messages.sortedBy { it.timestampMillis }+ val result = mutableListOf<ChatMessage>()+ for (message in sorted) {+ val last = result.lastOrNull()+ if (last != null && isDuplicate(last, message)) {+ continue+ }+ result.add(message)+ }+ return result+ }++ private fun isDuplicate(left: ChatMessage, right: ChatMessage): Boolean {+ if (left.author != right.author) return false+ if (left.text != right.text) return false+ if (!attachmentsSignature(left.attachments).contentEquals(attachmentsSignature(right.attachments))) return false+ return abs(left.timestampMillis - right.timestampMillis) <= 2_000+ }++ private fun attachmentsSignature(attachments: List<Attachment>): Array<String> {+ return attachments.map { "${it.type}:${it.name}" }.toTypedArray()+ }++ private fun updateSelectionForParent(sessionId: String, parentId: String?, childId: String) {+ val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }+ val selectionKey = parentId ?: "__root__"+ selectionMap[selectionKey] = childId+ }++ private data class HistorySelection(+ val messages: List<LlmMessage>,+ val inputTokens: Int,+ val inputBudget: Int,+ val wasTrimmed: Boolean+ )++ private data class PendingOverflow(+ val sessionId: String,+ val messageId: String+ )++ private fun buildPrompt(text: String, attachments: List<Attachment>): PromptResult {+ val builder = StringBuilder(text)+ val documents = attachments.filter { it.type == io.ente.ensu.domain.model.AttachmentType.Document }+ val images = attachments.filter { it.type == io.ente.ensu.domain.model.AttachmentType.Image }++ documents.forEachIndexed { index, attachment ->+ builder.append("\n\n----- BEGIN DOCUMENT: Document ${index + 1} -----\n")+ builder.append("Attached document: ${attachment.name}\n")+ builder.append("----- END DOCUMENT: Document ${index + 1} -----")+ }++ val imageFiles = images.mapNotNull { attachment ->+ val path = attachment.localPath ?: return@mapNotNull null+ java.io.File(path).takeIf { it.exists() }+ }++ if (imageFiles.isNotEmpty()) {+ builder.append("\n\n[")+ builder.append(imageFiles.size)+ builder.append(" image attachment")+ if (imageFiles.size > 1) builder.append("s")+ builder.append(" provided]")+ imageFiles.forEach {+ builder.append("\n")+ builder.append(MEDIA_MARKER)+ }+ }++ return PromptResult(builder.toString(), imageFiles)+ }++ private fun buildHistorySelection(+ sessionId: String,+ promptText: String,+ promptImageCount: Int,+ currentMessageId: String,+ target: LlmModelTarget+ ): HistorySelection {+ val path = buildSelectedPath(sessionId)+ val historyMessages = path.takeWhile { it.id != currentMessageId }+ val contextSize = target.contextLength ?: 4096+ val maxOutput = target.maxTokens ?: 1024+ val inputBudget = max(0, contextSize - maxOutput - OVERFLOW_SAFETY_TOKENS)+ val systemTokens = estimateTokens(SYSTEM_PROMPT)+ val promptTokens = estimatePromptTokens(promptText, promptImageCount)+ val historyTokens = historyMessages.sumOf { estimateTokens(historyText(it)) }+ val inputTokens = systemTokens + promptTokens + historyTokens+ var remaining = inputBudget - systemTokens - promptTokens++ if (remaining <= 0 || historyMessages.isEmpty()) {+ return HistorySelection(emptyList(), inputTokens, inputBudget, inputTokens > inputBudget)+ }++ val selected = mutableListOf<LlmMessage>()+ for (message in historyMessages.asReversed()) {+ val text = historyText(message)+ val cost = estimateTokens(text)+ if (cost <= remaining) {+ selected.add(+ LlmMessage(+ text = text,+ role = if (message.author == MessageAuthor.User) LlmMessageRole.User else LlmMessageRole.Assistant,+ hasAttachments = message.attachments.isNotEmpty()+ )+ )+ remaining -= cost+ } else {+ break+ }+ }++ return HistorySelection(selected.reversed(), inputTokens, inputBudget, inputTokens > inputBudget)+ }++ private fun showOverflowDialog(selection: HistorySelection, target: LlmModelTarget) {+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ overflowDialog = io.ente.ensu.domain.state.OverflowDialogState(+ inputTokens = selection.inputTokens,+ inputBudget = selection.inputBudget,+ contextLength = target.contextLength ?: 4096,+ maxOutput = target.maxTokens ?: 1024+ )+ )+ )+ }+ }++ private fun clearOverflowDialog() {+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(overflowDialog = null))+ }+ }++ private fun historyText(message: ChatMessage): String {+ var text = message.text+ if (message.author == MessageAuthor.Assistant) {+ text = text.replace(Regex("<think>[\\s\\S]*?</think>"), "")+ text = text.replace(Regex("<todo_list>[\\s\\S]*?</todo_list>"), "")+ } else if (message.attachments.isNotEmpty()) {+ text += "\n\n[${message.attachments.size} attachments attached]"+ }+ return text.trim()+ }++ private fun trimToBudget(text: String, budget: Int): String {+ if (budget <= 0) return ""+ val maxChars = budget * 4+ return if (text.length <= maxChars) text else text.takeLast(maxChars)+ }++ private fun estimateTokens(text: String): Int {+ return max(1, text.length / 4)+ }++ private fun estimateImageTokens(imageCount: Int): Int {+ return imageCount * IMAGE_TOKEN_ESTIMATE+ }++ private fun estimatePromptTokens(promptText: String, imageCount: Int): Int {+ return estimateTokens(promptText) + estimateImageTokens(imageCount)+ }++ private fun cancelGeneration() {+ generationJob?.cancel()+ llmProvider.stopGeneration()+ invalidateGenerationToken()+ streamingParentId = null+ stopRequested = false+ }++ private fun resetGenerationState(+ downloadStatus: String? = null,+ hasRequestedModelDownload: Boolean? = null+ ) {+ cancelGeneration()+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = false,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = downloadStatus,+ hasRequestedModelDownload =+ hasRequestedModelDownload ?: appState.chat.hasRequestedModelDownload+ )+ )+ }+ }++ private fun nextGenerationToken(): Long {+ activeGenerationToken += 1+ return activeGenerationToken+ }++ private fun invalidateGenerationToken() {+ activeGenerationToken += 1+ }++ private fun isGenerationActive(token: Long, sessionId: String): Boolean {+ return token == activeGenerationToken && state.value.chat.currentSessionId == sessionId+ }++ private data class PromptResult(+ val text: String,+ val imageFiles: List<java.io.File>+ )++ companion object {+ private const val MEDIA_MARKER = "<__media__>"+ private const val OVERFLOW_SAFETY_TOKENS = 128+ private const val IMAGE_TOKEN_ESTIMATE = 768+ private const val MAX_CACHED_SESSIONS = 8+ private const val SYSTEM_PROMPT =+ "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put \$\$ on its own line (never inline). Example:\n\$\$\nx^2 + y^2 = z^2\n\$\$"+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.ktnew file mode 100644index 0000000000..16a22e69e6--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt@@ -0,0 +1,213 @@+package io.ente.ensu.domain.store++import io.ente.ensu.domain.llm.LlmModelTarget+import io.ente.ensu.domain.llm.LlmProvider+import io.ente.ensu.domain.logging.LogRepository+import io.ente.ensu.domain.model.LogLevel+import io.ente.ensu.domain.state.AppState+import io.ente.ensu.domain.state.ModelSettingsState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++internal class ModelSettingsActions(+ private val state: MutableStateFlow<AppState>,+ private val llmProvider: LlmProvider,+ private val logRepository: LogRepository+) {+ private var scope: CoroutineScope? = null+ private var modelDownloadJob: Job? = null++ fun setScope(scope: CoroutineScope) {+ this.scope = scope+ }++ fun updateModelSettings(settings: ModelSettingsState) {+ state.update { appState ->+ appState.copy(modelSettings = settings)+ }+ refreshModelDownloadInfo()+ }++ fun resetModelSettings() {+ state.update { appState ->+ appState.copy(modelSettings = ModelSettingsState())+ }+ refreshModelDownloadInfo()+ }++ fun refreshModelDownloadInfo() {+ val target = resolveTarget(state.value.modelSettings)+ val isDownloaded = llmProvider.isModelDownloaded(target)+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isModelDownloaded = isDownloaded,+ modelDownloadSizeBytes = if (isDownloaded) null else appState.chat.modelDownloadSizeBytes,+ hasRequestedModelDownload = appState.chat.hasRequestedModelDownload || isDownloaded+ )+ )+ }++ if (!isDownloaded) {+ val scope = scope ?: return+ scope.launch {+ val size = llmProvider.estimateModelDownloadSize(target)+ state.update { appState ->+ appState.copy(chat = appState.chat.copy(modelDownloadSizeBytes = size))+ }+ }+ }+ }++ fun startModelDownload(userInitiated: Boolean = true) {+ val scope = scope ?: return+ val currentState = state.value+ if (modelDownloadJob?.isActive == true) return+ if (currentState.chat.isDownloading || currentState.chat.isGenerating) return+ if (!userInitiated && !currentState.chat.hasRequestedModelDownload) return++ val target = resolveTarget(currentState.modelSettings)+ val isDownloaded = llmProvider.isModelDownloaded(target)+ if (isDownloaded) {+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isModelDownloaded = true,+ modelDownloadSizeBytes = null,+ hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload+ )+ )+ }+ }++ modelDownloadJob?.cancel()+ if (!isDownloaded) {+ logRepository.log(+ LogLevel.Info,+ "Model download started",+ details = "model=${target.id}",+ tag = "Model"+ )+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = true,+ downloadPercent = 0,+ downloadStatus = "Starting download...",+ hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload+ )+ )+ }+ }++ modelDownloadJob = scope.launch {+ var loggedComplete = false+ try {+ llmProvider.ensureModelReady(target) { progress ->+ val downloading = (progress.percent in 0..99) || progress.status.contains("Loading", ignoreCase = true)+ val finished = progress.status.contains("Ready", ignoreCase = true)+ if (!isDownloaded && finished && !loggedComplete) {+ loggedComplete = true+ logRepository.log(+ LogLevel.Info,+ "Model download complete",+ details = "model=${target.id}",+ tag = "Model"+ )+ }+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = downloading && !finished,+ downloadPercent = progress.percent.takeIf { it >= 0 },+ downloadStatus = progress.status,+ isModelDownloaded = if (finished) true else appState.chat.isModelDownloaded,+ modelDownloadSizeBytes = if (finished) null else appState.chat.modelDownloadSizeBytes+ )+ )+ }+ }+ } catch (err: Throwable) {+ val cancelled = err is kotlinx.coroutines.CancellationException ||+ err.message?.contains("cancel", ignoreCase = true) == true+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = false,+ downloadPercent = null,+ downloadStatus = if (cancelled) "Download cancelled" else "Download failed",+ hasRequestedModelDownload = if (cancelled) false else appState.chat.hasRequestedModelDownload+ )+ )+ }+ if (cancelled) {+ if (!isDownloaded) {+ logRepository.log(LogLevel.Info, "Model download cancelled", tag = "Model")+ }+ } else {+ logRepository.log(+ LogLevel.Error,+ if (isDownloaded) "Model load failed" else "Model download failed",+ details = err.message,+ tag = "Model",+ throwable = err+ )+ }+ } finally {+ modelDownloadJob = null+ refreshModelDownloadInfo()+ }+ }+ }++ fun cancelModelDownload() {+ modelDownloadJob?.cancel()+ modelDownloadJob = null+ llmProvider.cancelDownload()+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = false,+ downloadPercent = null,+ downloadStatus = "Download cancelled",+ hasRequestedModelDownload = false+ )+ )+ }+ refreshModelDownloadInfo()+ }++ fun resolveTarget(settings: ModelSettingsState): LlmModelTarget {+ val useCustom = settings.useCustomModel && settings.modelUrl.isNotBlank()+ val url = if (useCustom) settings.modelUrl else DEFAULT_MODEL_URL+ val mmproj = if (useCustom) settings.mmprojUrl.takeIf { it.isNotBlank() } else DEFAULT_MMPROJ_URL+ val contextLength = settings.contextLength.toIntOrNull()+ val maxTokens = settings.maxTokens.toIntOrNull()+ val id = if (useCustom) "custom:${url.hashCode()}" else "default"++ return LlmModelTarget(+ id = id,+ url = url,+ mmprojUrl = mmproj,+ contextLength = contextLength,+ maxTokens = maxTokens+ )+ }++ fun resolveTemperature(settings: ModelSettingsState): Float {+ val temperature = settings.temperature.trim().toFloatOrNull()+ val resolved = temperature?.takeIf { it >= 0f } ?: DEFAULT_TEMPERATURE+ return resolved.coerceIn(0.35f, 0.7f)+ }++ companion object {+ private const val DEFAULT_MODEL_URL =+ "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf"+ private const val DEFAULT_MMPROJ_URL =+ "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"+ private const val DEFAULT_TEMPERATURE = 0.5f+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/SyncStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/SyncStoreActions.ktnew file mode 100644index 0000000000..b98d6ffe25--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/SyncStoreActions.kt@@ -0,0 +1,130 @@+package io.ente.ensu.domain.store++import io.ente.ensu.domain.chat.ChatSyncRepository+import io.ente.ensu.domain.logging.LogRepository+import io.ente.ensu.domain.model.LogLevel+import io.ente.ensu.domain.state.AppState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++internal class SyncStoreActions(+ private val state: MutableStateFlow<AppState>,+ private val chatSyncRepository: ChatSyncRepository?,+ private val logRepository: LogRepository+) {+ private var scope: CoroutineScope? = null+ private var pendingSyncRequested = false+ private var pendingSyncErrorHandler: ((String) -> Unit)? = null+ private var pendingSyncSuccessHandler: (() -> Unit)? = null+ private var reloadSessions: (() -> Unit)? = null++ fun setScope(scope: CoroutineScope) {+ this.scope = scope+ }++ fun setReloadSessions(loader: () -> Unit) {+ reloadSessions = loader+ }++ fun syncNow(+ onSuccess: (() -> Unit)? = null,+ onError: ((String) -> Unit)? = null+ ) {+ requestSync(onSuccess, onError)+ }++ fun requestSync(+ onSuccess: (() -> Unit)? = null,+ onError: ((String) -> Unit)? = null+ ) {+ if (state.value.chat.isGenerating) {+ pendingSyncRequested = true+ if (onError != null) {+ pendingSyncErrorHandler = onError+ }+ if (onSuccess != null) {+ pendingSyncSuccessHandler = onSuccess+ }+ return+ }++ val handler = pendingSyncErrorHandler ?: onError+ val successHandler = pendingSyncSuccessHandler ?: onSuccess+ pendingSyncRequested = false+ pendingSyncErrorHandler = null+ pendingSyncSuccessHandler = null+ performSync(handler, successHandler)+ }++ fun syncAfterGeneration() {+ val handler = pendingSyncErrorHandler+ val successHandler = pendingSyncSuccessHandler+ val shouldAutoSync = state.value.auth.isLoggedIn+ if (!pendingSyncRequested && !shouldAutoSync) {+ pendingSyncErrorHandler = null+ pendingSyncSuccessHandler = null+ return+ }+ if (!shouldAutoSync && handler == null && successHandler == null) {+ pendingSyncRequested = false+ pendingSyncErrorHandler = null+ pendingSyncSuccessHandler = null+ return+ }+ pendingSyncRequested = false+ pendingSyncErrorHandler = null+ pendingSyncSuccessHandler = null+ performSync(handler, successHandler)+ }++ private fun performSync(+ onError: ((String) -> Unit)? = null,+ onSuccess: (() -> Unit)? = null+ ) {+ val scope = scope ?: return+ scope.launch {+ try {+ logRepository.log(LogLevel.Info, "Sync started", tag = "Sync")+ withContext(Dispatchers.IO) {+ chatSyncRepository?.sync()+ }+ reloadSessions?.invoke()+ logRepository.log(LogLevel.Info, "Sync success", tag = "Sync")+ if (onSuccess != null) {+ withContext(Dispatchers.Main) {+ onSuccess()+ }+ }+ } catch (err: Throwable) {+ val message = syncErrorMessage(err)+ logRepository.log(+ LogLevel.Error,+ "Sync failed",+ details = message,+ tag = "Sync",+ throwable = err+ )+ if (onError != null) {+ withContext(Dispatchers.Main) {+ onError("Sync failed: $message")+ }+ }+ }+ }+ }++ private fun syncErrorMessage(error: Throwable): String {+ var current: Throwable? = error+ while (current != null) {+ val message = current.message+ if (!message.isNullOrBlank()) {+ return message+ }+ current = current.cause+ }+ return "Unknown error"+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/util/ByteFormatter.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/util/ByteFormatter.ktindex f4c93bcdbe..6d76ef5624 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/util/ByteFormatter.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/util/ByteFormatter.kt@@ -12,3 +12,7 @@ fun formatBytes(bytes: Long): String {}return String.format(Locale.US, "%.1f %s", size, units[unitIndex])}++fun Long.formattedFileSize(): String {+ return formatBytes(this)+}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/AuthFlowView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/AuthFlowView.swiftindex 71cbf71948..14f73a7714 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/AuthFlowView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/AuthFlowView.swift@@ -1,5 +1,6 @@import SwiftUI+#if canImport(EnteCore)enum AuthRoute: Hashable {case otp(email: String, srp: SrpAttributes)case password(email: String, srp: SrpAttributes)@@ -230,3 +231,14 @@ struct AuthFlowView: View {#endif}}+#else+enum AuthRoute: Hashable {+ case unavailable+}++struct AuthFlowView: View {+ var body: some View {+ Text("Authentication unavailable")+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/EmailEntryView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/EmailEntryView.swiftindex 4b55722e38..cd2475417a 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/EmailEntryView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/EmailEntryView.swift@@ -1,11 +1,11 @@import SwiftUI+#if canImport(EnteCore)struct EmailEntryView: View {let onNavigate: (AuthRoute) -> Void@State private var email: String = ""- @State private var isLoading = false- @State private var errorMessage: String?+ @StateObject private var actionState = AuthActionState()private var isEmailValid: Bool {let trimmed = email.trimmingCharacters(in: .whitespacesAndNewlines)@@ -29,19 +29,15 @@ struct EmailEntryView: View {Task { await continueTapped() }}- if let errorMessage {- Text(errorMessage)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .frame(maxWidth: .infinity, alignment: .leading)+ if let errorMessage = actionState.errorMessage {+ AuthErrorText(message: errorMessage)}}} bottom: {PrimaryButton(text: "Log in",- isLoading: isLoading,- isEnabled: isEmailValid && !isLoading+ isLoading: actionState.isLoading,+ isEnabled: isEmailValid && !actionState.isLoading) {Task { await continueTapped() }}@@ -50,14 +46,10 @@ struct EmailEntryView: View {@MainActorprivate func continueTapped() async {- guard !isLoading else { return }- errorMessage = nil- isLoading = true- defer { isLoading = false }-- let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)-- do {+ await actionState.run(onError: { error in+ "Failed to get account info: \(error.localizedDescription)"+ }) {+ let trimmedEmail = email.trimmingCharacters(in: .whitespacesAndNewlines)let srpAttrs = try await EnsuAuthService.shared.getSrpAttributes(email: trimmedEmail)if srpAttrs.isEmailMfaEnabled {@@ -66,8 +58,13 @@ struct EmailEntryView: View {} else {onNavigate(.password(email: trimmedEmail, srp: srpAttrs))}- } catch {- errorMessage = "Failed to get account info: \(error.localizedDescription)"}}}+#else+struct EmailEntryView: View {+ var body: some View {+ Text("Authentication unavailable")+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/OtpVerificationView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/OtpVerificationView.swiftindex 3ec3a73e25..27d9d64cab 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/OtpVerificationView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/OtpVerificationView.swift@@ -1,65 +1,38 @@import SwiftUI+#if canImport(EnteCore)struct OtpVerificationView: View {let email: Stringlet srpAttributes: SrpAttributeslet onNavigate: (AuthRoute) -> Void@State private var code: String = ""- @State private var isLoading = false- @State private var errorMessage: String?-- private var hasValidCode: Bool {- code.trimmingCharacters(in: .whitespacesAndNewlines).count == 6- }+ @StateObject private var actionState = AuthActionState()var body: some View {- AuthScreen {- AuthHeader(title: "Verify email", subtitle: email)-- VStack(spacing: EnsuSpacing.lg) {- CodeTextField(code: $code) { value in- if value.count == 6 {- Task { await verifyTapped() }- }- }-- TextLink(text: "Resend code") {- Task { await resendTapped() }- }- .frame(maxWidth: .infinity)-- if let errorMessage {- Text(errorMessage)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .frame(maxWidth: .infinity, alignment: .leading)- }- }- } bottom: {- PrimaryButton(- text: "Verify",- isLoading: isLoading,- isEnabled: hasValidCode && !isLoading- ) {- Task { await verifyTapped() }+ VerificationCodeView(+ title: "Verify email",+ subtitle: email,+ code: $code,+ buttonText: "Verify",+ isLoading: actionState.isLoading,+ errorMessage: actionState.errorMessage,+ onSubmit: verifyTapped+ ) {+ TextLink(text: "Resend code") {+ Task { await resendTapped() }}+ .frame(maxWidth: .infinity)}}@MainActorprivate func verifyTapped() async {- guard !isLoading else { return }- errorMessage = nil- isLoading = true- defer { isLoading = false }-- do {+ await actionState.run {let payload = try await EnsuAuthService.shared.verifyOtp(email: email, otp: code)guard let keyAttrs = payload.keyAttributes else {- errorMessage = "New user signup not implemented. Please use an existing account."+ actionState.setError("New user signup not implemented. Please use an existing account.")return}@@ -99,8 +72,6 @@ struct OtpVerificationView: View {token: payload.token))- } catch {- errorMessage = error.localizedDescription}}@@ -109,7 +80,14 @@ struct OtpVerificationView: View {do {try await EnsuAuthService.shared.sendOtp(email: email)} catch {- errorMessage = "Failed to resend code: \(error.localizedDescription)"+ actionState.setError("Failed to resend code: \(error.localizedDescription)")}}}+#else+struct OtpVerificationView: View {+ var body: some View {+ Text("Authentication unavailable")+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/PasskeyPasswordReentryView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/PasskeyPasswordReentryView.swiftindex ca93c4b035..bd5cd9f2a2 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/PasskeyPasswordReentryView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/PasskeyPasswordReentryView.swift@@ -1,5 +1,6 @@import SwiftUI+#if canImport(EnteCore)struct PasskeyPasswordReentryView: View {let email: Stringlet srpAttributes: SrpAttributes@@ -7,61 +8,32 @@ struct PasskeyPasswordReentryView: View {let onLoggedIn: () -> Void@State private var password: String = ""- @State private var isLoading = false- @State private var errorMessage: String?+ @StateObject private var actionState = AuthActionState()@State private var showPassword = false- private var hasPassword: Bool { !password.isEmpty }-var body: some View {- AuthScreen {- AuthHeader(title: "Enter password")- AuthSubtitle(text: email)-- VStack(spacing: EnsuSpacing.xxl) {- PasswordTextField(- label: "Password",- hint: "Enter your password",- text: $password,- showPassword: $showPassword,- submitLabel: .go- ) {- Task { await continueTapped() }- }-- if let errorMessage {- Text(errorMessage)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .frame(maxWidth: .infinity, alignment: .leading)- }- }- .padding(.top, EnsuSpacing.xxl)- } bottom: {- PrimaryButton(- text: "Continue",- isLoading: isLoading,- isEnabled: hasPassword && !isLoading- ) {- Task { await continueTapped() }- }- }+ PasswordEntryView(+ title: "Enter password",+ subtitle: email,+ buttonText: "Continue",+ password: $password,+ showPassword: $showPassword,+ isLoading: actionState.isLoading,+ errorMessage: actionState.errorMessage,+ onSubmit: continueTapped+ )}@MainActorprivate func continueTapped() async {- guard !isLoading else { return }- errorMessage = nil- isLoading = true- defer { isLoading = false }-- guard let keyAttrs = auth.keyAttributes else {- errorMessage = "Invalid passkey response."- return- }+ await actionState.run(onError: { error in+ "Incorrect password: \(error.localizedDescription)"+ }) {+ guard let keyAttrs = auth.keyAttributes else {+ actionState.setError("Invalid passkey response.")+ return+ }- do {try await EnsuAuthService.shared.loginAfterChallenge(email: email,password: password,@@ -72,8 +44,13 @@ struct PasskeyPasswordReentryView: View {token: auth.token)onLoggedIn()- } catch {- errorMessage = "Incorrect password: \(error.localizedDescription)"}}}+#else+struct PasskeyPasswordReentryView: View {+ var body: some View {+ Text("Authentication unavailable")+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/PasskeyView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/PasskeyView.swiftindex 1127bb079d..2a3f497e0a 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/PasskeyView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/PasskeyView.swift@@ -1,5 +1,6 @@import SwiftUI+#if canImport(EnteCore)struct PasskeyView: View {let email: Stringlet srpAttributes: SrpAttributes@@ -235,3 +236,10 @@ struct PasskeyView: View {)}}+#else+struct PasskeyView: View {+ var body: some View {+ Text("Authentication unavailable")+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/PasswordAfterMfaView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/PasswordAfterMfaView.swiftindex a1ef93533e..217bb2f6af 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/PasswordAfterMfaView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/PasswordAfterMfaView.swift@@ -1,5 +1,6 @@import SwiftUI+#if canImport(EnteCore)struct PasswordAfterMfaView: View {let email: Stringlet srpAttributes: SrpAttributes@@ -10,56 +11,27 @@ struct PasswordAfterMfaView: View {let onLoggedIn: () -> Void@State private var password: String = ""- @State private var isLoading = false- @State private var errorMessage: String?+ @StateObject private var actionState = AuthActionState()@State private var showPassword = false- private var hasPassword: Bool { !password.isEmpty }-var body: some View {- AuthScreen {- AuthHeader(title: "Enter password")- AuthSubtitle(text: email)-- VStack(spacing: EnsuSpacing.xxl) {- PasswordTextField(- label: "Password",- hint: "Enter your password",- text: $password,- showPassword: $showPassword,- submitLabel: .go- ) {- Task { await continueTapped() }- }-- if let errorMessage {- Text(errorMessage)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .frame(maxWidth: .infinity, alignment: .leading)- }- }- .padding(.top, EnsuSpacing.xxl)- } bottom: {- PrimaryButton(- text: "Continue",- isLoading: isLoading,- isEnabled: hasPassword && !isLoading- ) {- Task { await continueTapped() }- }- }+ PasswordEntryView(+ title: "Enter password",+ subtitle: email,+ buttonText: "Continue",+ password: $password,+ showPassword: $showPassword,+ isLoading: actionState.isLoading,+ errorMessage: actionState.errorMessage,+ onSubmit: continueTapped+ )}@MainActorprivate func continueTapped() async {- guard !isLoading else { return }- errorMessage = nil- isLoading = true- defer { isLoading = false }-- do {+ await actionState.run(onError: { error in+ "Incorrect password: \(error.localizedDescription)"+ }) {try await EnsuAuthService.shared.loginAfterChallenge(email: email,password: password,@@ -70,8 +42,13 @@ struct PasswordAfterMfaView: View {token: token)onLoggedIn()- } catch {- errorMessage = "Incorrect password: \(error.localizedDescription)"}}}+#else+struct PasswordAfterMfaView: View {+ var body: some View {+ Text("Authentication unavailable")+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/PasswordView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/PasswordView.swiftindex 0867e7e9f2..3206a60d9f 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/PasswordView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/PasswordView.swift@@ -1,5 +1,6 @@import SwiftUI+#if canImport(EnteCore)struct PasswordView: View {let email: Stringlet srpAttributes: SrpAttributes@@ -7,58 +8,25 @@ struct PasswordView: View {let onLoggedIn: () -> Void@State private var password: String = ""- @State private var isLoading = false- @State private var errorMessage: String?+ @StateObject private var actionState = AuthActionState()@State private var showPassword = false- private var hasPassword: Bool {- !password.isEmpty- }-var body: some View {- AuthScreen {- AuthHeader(title: "Enter password")- AuthSubtitle(text: email)-- VStack(spacing: EnsuSpacing.xxl) {- PasswordTextField(- label: "Password",- hint: "Enter your password",- text: $password,- showPassword: $showPassword,- submitLabel: .go- ) {- Task { await loginTapped() }- }-- if let errorMessage {- Text(errorMessage)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .frame(maxWidth: .infinity, alignment: .leading)- }- }- .padding(.top, EnsuSpacing.xxl)- } bottom: {- PrimaryButton(- text: "Log in",- isLoading: isLoading,- isEnabled: hasPassword && !isLoading- ) {- Task { await loginTapped() }- }- }+ PasswordEntryView(+ title: "Enter password",+ subtitle: email,+ buttonText: "Log in",+ password: $password,+ showPassword: $showPassword,+ isLoading: actionState.isLoading,+ errorMessage: actionState.errorMessage,+ onSubmit: loginTapped+ )}@MainActorprivate func loginTapped() async {- guard !isLoading else { return }- errorMessage = nil- isLoading = true- defer { isLoading = false }-- do {+ await actionState.run {let result = try await EnsuAuthService.shared.loginWithSrp(email: email,password: password,@@ -92,8 +60,13 @@ struct PasswordView: View {}onLoggedIn()- } catch {- errorMessage = error.localizedDescription}}}+#else+struct PasswordView: View {+ var body: some View {+ Text("Authentication unavailable")+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/TwoFactorView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/TwoFactorView.swiftindex 157e1ba318..0705b0d032 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/TwoFactorView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/TwoFactorView.swift@@ -1,5 +1,6 @@import SwiftUI+#if canImport(EnteCore)struct TwoFactorView: View {let email: Stringlet srpAttributes: SrpAttributes@@ -9,57 +10,26 @@ struct TwoFactorView: View {let onLoggedIn: () -> Void@State private var code: String = ""- @State private var isLoading = false- @State private var errorMessage: String?-- private var hasValidCode: Bool {- code.trimmingCharacters(in: .whitespacesAndNewlines).count == 6- }+ @StateObject private var actionState = AuthActionState()var body: some View {- AuthScreen {- AuthHeader(- title: "Two-factor authentication",- subtitle: "Enter the code from your authenticator app"- )-- VStack(spacing: EnsuSpacing.lg) {- CodeTextField(code: $code) { value in- if value.count == 6 {- Task { await verifyTapped() }- }- }-- if let errorMessage {- Text(errorMessage)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .frame(maxWidth: .infinity, alignment: .leading)- }- }- } bottom: {- PrimaryButton(- text: "Verify",- isLoading: isLoading,- isEnabled: hasValidCode && !isLoading- ) {- Task { await verifyTapped() }- }- }+ VerificationCodeView(+ title: "Two-factor authentication",+ subtitle: "Enter the code from your authenticator app",+ code: $code,+ buttonText: "Verify",+ isLoading: actionState.isLoading,+ errorMessage: actionState.errorMessage,+ onSubmit: verifyTapped+ )}@MainActorprivate func verifyTapped() async {- guard !isLoading else { return }- errorMessage = nil- isLoading = true- defer { isLoading = false }-- do {+ await actionState.run {let payload = try await EnsuAuthService.shared.verifyTwoFactor(sessionId: sessionId, code: code)guard let keyAttrs = payload.keyAttributes else {- errorMessage = "Invalid response"+ actionState.setError("Invalid response")return}@@ -87,8 +57,13 @@ struct TwoFactorView: View {token: payload.token))- } catch {- errorMessage = error.localizedDescription}}}+#else+struct TwoFactorView: View {+ var body: some View {+ Text("Authentication unavailable")+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatRecovery.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatRecovery.swiftnew file mode 100644index 0000000000..66c0eda0e8--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatRecovery.swift@@ -0,0 +1,14 @@+import Foundation++enum ChatRecovery {+ private static let resetSignals = [+ "stream pull failed",+ "invalid blob",+ "invalid encrypted"+ ]++ static func shouldResetFromMessage(_ message: String) -> Bool {+ let lowercased = message.lowercased()+ return resetSignals.contains { lowercased.contains($0) }+ }+}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swiftindex 573ffbe6e4..2fc53f62b6 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift@@ -536,341 +536,11 @@ private struct ToastTrigger: Equatable {let generationError: String?}-private struct DownloadOnboardingView: View {- let isDownloading: Bool- let downloadPercent: Int?- let statusText: String?- let totalBytes: Int64?- let sizeText: String- let onDownload: () -> Void-- var body: some View {- VStack(spacing: EnsuSpacing.md) {- Text("Download to begin using the Chat")- .font(EnsuTypography.large)- .foregroundStyle(EnsuColor.textPrimary)- .multilineTextAlignment(.center)-- if isDownloading {- let statusLine: String = {- if let statusText, statusText.localizedCaseInsensitiveContains("loading") {- return statusText- }- if let totalBytes, let percent = downloadPercent, percent >= 0 {- let clamped = min(max(percent, 0), 100)- let downloaded = Int64(Double(totalBytes) * Double(clamped) / 100.0)- return "Downloading... \(downloaded.formattedFileSize) / \(totalBytes.formattedFileSize)"- }- if let statusText, !statusText.isEmpty {- return statusText- }- return "Downloading..."- }()-- Text(statusLine)- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.textMuted)- .multilineTextAlignment(.center)-- progressView- } else {- Button("Download") {- hapticMedium()- onDownload()- }- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.backgroundBase)- .frame(maxWidth: 200)- .padding(.vertical, EnsuSpacing.md)- .background(EnsuColor.accent)- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.button))-- Text(sizeText)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- }- }- .frame(maxWidth: .infinity, maxHeight: .infinity)- .padding(.horizontal, EnsuSpacing.pageHorizontal)- }-- @ViewBuilder- private var progressView: some View {- if let percent = downloadPercent, percent >= 0 {- let clamped = min(max(percent, 0), 100)- ProgressView(value: Double(clamped), total: 100)- .progressViewStyle(.linear)- .tint(EnsuColor.accent)- .frame(maxWidth: 240)- } else {- ProgressView()- .progressViewStyle(.linear)- .tint(EnsuColor.accent)- .frame(maxWidth: 240)- }- }--}-private struct ToastMessage: Identifiable {let id = UUID()let text: String}-private struct ComingSoonSheet: View {- let title: String- let message: String- let onDismiss: () -> Void-- var body: some View {- VStack(spacing: EnsuSpacing.lg) {- RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous)- .fill(EnsuColor.fillFaint)- .frame(height: 180)- .overlay(- Text("Illustration")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- )-- Text(title)- .font(EnsuTypography.large)- .foregroundStyle(EnsuColor.textPrimary)-- Text(message)- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.textMuted)- .multilineTextAlignment(.center)-- Button("Got it") {- onDismiss()- }- .buttonStyle(.borderedProminent)- .tint(EnsuColor.accent)- }- .padding(EnsuSpacing.xl)- .frame(maxWidth: .infinity, maxHeight: .infinity)- .background(EnsuColor.backgroundBase)- }-}--private struct AttachmentDownloadsSheet: View {- let downloads: [AttachmentDownloadItem]- let sessionTitle: (UUID) -> String- let onCancel: (String) -> Void- let onDismiss: () -> Void-- var body: some View {- VStack(spacing: 0) {- HStack {- Text("Attachment downloads")- .font(EnsuTypography.h3Bold)- Spacer()- Button("Close", action: onDismiss)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.accent)- }- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .padding(.vertical, EnsuSpacing.sm)-- Divider()- .background(EnsuColor.border)-- if downloads.isEmpty {- Text("No pending downloads")- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.textMuted)- .padding(.top, EnsuSpacing.lg)- Spacer()- } else {- List(downloads) { item in- HStack(spacing: EnsuSpacing.md) {- VStack(alignment: .leading, spacing: 4) {- Text(item.name)- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.textPrimary)- .lineLimit(1)- Text("\(sessionTitle(item.sessionId)) β’ \(item.formattedSize)")- .font(EnsuTypography.mini)- .foregroundStyle(EnsuColor.textMuted)- if item.status == .failed, let errorMessage = item.errorMessage, !errorMessage.isEmpty {- Text(errorMessage)- .font(EnsuTypography.mini)- .foregroundStyle(EnsuColor.error)- .lineLimit(2)- }- }-- Spacer()-- Text(statusText(for: item.status))- .font(EnsuTypography.mini)- .foregroundStyle(EnsuColor.textMuted)-- if item.status == .queued || item.status == .downloading {- Button(action: {- hapticWarning()- onCancel(item.id)- }) {- Image("Cancel01Icon")- .resizable()- .scaledToFit()- .frame(width: 18, height: 18)- .foregroundStyle(EnsuColor.textMuted)- }- .buttonStyle(.plain)- }- }- .padding(.vertical, 4)- }- .listStyle(.plain)- }- }- .frame(minHeight: 320)- .background(EnsuColor.backgroundBase)- }-- private func statusText(for status: AttachmentDownloadItem.Status) -> String {- switch status {- case .queued:- return "Queued"- case .downloading:- return "Downloading"- case .completed:- return "Completed"- case .failed:- return "Failed"- case .canceled:- return "Canceled"- }- }-}--private struct ChatAppBar: View {- let sessionTitle: String- let showBrand: Bool- let showSignIn: Bool- let showsMenuButton: Bool- let attachmentDownloadSummary: (completed: Int, total: Int)?- let modelDownloadState: DownloadToastState?- let onMenu: () -> Void- let onSignIn: () -> Void- let onAttachmentDownloads: () -> Void-- private let centerInset: CGFloat = 72-- private var modelProgressState: DownloadToastState? {- guard let modelDownloadState else { return nil }- switch modelDownloadState.phase {- case .loading, .downloading:- return modelDownloadState- default:- return nil- }- }-- var body: some View {- ZStack {- HStack(spacing: EnsuSpacing.md) {- if showsMenuButton {- Button(action: {- hapticTap()- onMenu()- }) {- Image("Menu01Icon")- .resizable()- .scaledToFit()- .frame(width: 18, height: 18)- .frame(width: 40, height: 40)- }- .buttonStyle(.plain)- } else {- Color.clear- .frame(width: 40, height: 40)- }-- Spacer()-- HStack(spacing: EnsuSpacing.md) {- if showSignIn {- if let progress = modelProgressState {- ModelProgressIndicator(state: progress)- }- Button(action: {- hapticTap()- onSignIn()- }) {- Text("Sign In")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.accent)- }- .buttonStyle(.plain)- } else {- if let summary = attachmentDownloadSummary {- Button(action: {- hapticTap()- onAttachmentDownloads()- }) {- HStack(spacing: 6) {- Image("Upload01Icon")- .resizable()- .scaledToFit()- .frame(width: 14, height: 14)- .foregroundStyle(EnsuColor.textPrimary)- Text("\(summary.completed)/\(summary.total)")- .font(EnsuTypography.mini)- .foregroundStyle(EnsuColor.textMuted)- }- .padding(.horizontal, 8)- .padding(.vertical, 6)- .background(EnsuColor.fillFaint)- .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))- }- .buttonStyle(.plain)- }- if let progress = modelProgressState {- ModelProgressIndicator(state: progress)- }- }- }- }-- if showBrand {- EnsuLogo(height: 20)- .padding(.horizontal, centerInset)- } else {- Text(sessionTitle)- .font(EnsuTypography.large)- .foregroundStyle(EnsuColor.textPrimary)- .lineLimit(1)- .minimumScaleFactor(0.85)- .padding(.horizontal, centerInset)- }- }- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .padding(.vertical, EnsuSpacing.sm)- .background(EnsuColor.backgroundBase)- }-}--private struct ModelProgressIndicator: View {- let state: DownloadToastState-- var body: some View {- let clamped = min(max(state.percent, 0), 100)- if state.phase == .downloading {- ProgressView(value: Double(clamped), total: 100)- .progressViewStyle(.circular)- .tint(EnsuColor.accent)- .frame(width: 16, height: 16)- } else {- ProgressView()- .progressViewStyle(.circular)- .tint(EnsuColor.accent)- .frame(width: 16, height: 16)- }- }-}#elseimport SwiftUIdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swiftindex 04cf4870ee..0521ef7569 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift@@ -1,4 +1,5 @@import Foundation+import SwiftUI#if canImport(EnteCore)import EnteCore#else@@ -292,140 +293,7 @@ final class LlmChatSync {}#endif-struct ChatAttachment: Identifiable, Equatable {- enum Kind {- case image- case document- }-- let id: UUID- let name: String- let size: Int64- let kind: Kind- let url: URL?- var isUploading: Bool-- init(id: UUID = UUID(), name: String, size: Int64, kind: Kind, url: URL? = nil, isUploading: Bool = false) {- self.id = id- self.name = name- self.size = size- self.kind = kind- self.url = url- self.isUploading = isUploading- }-- var formattedSize: String {- ChatViewModel.fileSizeFormatter.string(fromByteCount: size)- }-- var iconName: String {- switch kind {- case .image:- return "Attachment01Icon"- case .document:- return "Attachment01Icon"- }- }-}--struct AttachmentDownloadItem: Identifiable, Equatable {- enum Status {- case queued- case downloading- case completed- case failed- case canceled- }-- let id: String- let sessionId: UUID- let name: String- let size: Int64- var status: Status- var errorMessage: String? = nil-- var formattedSize: String {- ChatViewModel.fileSizeFormatter.string(fromByteCount: size)- }-}--struct ChatMessage: Identifiable, Equatable {- enum Role: String {- case user- case assistant- }-- let id: UUID- var role: Role- var text: String- var timestamp: Date- var attachments: [ChatAttachment]- var isInterrupted: Bool- var tokensPerSecond: Double?- var branchIndex: Int- var branchCount: Int-- init(- id: UUID = UUID(),- role: Role,- text: String,- timestamp: Date = Date(),- attachments: [ChatAttachment] = [],- isInterrupted: Bool = false,- tokensPerSecond: Double? = nil,- branchIndex: Int = 1,- branchCount: Int = 1- ) {- self.id = id- self.role = role- self.text = text- self.timestamp = timestamp- self.attachments = attachments- self.isInterrupted = isInterrupted- self.tokensPerSecond = tokensPerSecond- self.branchIndex = branchIndex- self.branchCount = branchCount- }-}--struct ChatSession: Identifiable, Equatable {- let id: UUID- var title: String- var lastMessage: String- var updatedAt: Date-- init(id: UUID = UUID(), title: String, lastMessage: String, updatedAt: Date = Date()) {- self.id = id- self.title = title- self.lastMessage = lastMessage- self.updatedAt = updatedAt- }-}--struct DownloadToastState: Identifiable, Equatable {- enum Phase {- case downloading- case loading- case complete- case errorDownload- case errorLoad- }-- let id = UUID()- var phase: Phase- var percent: Int- var status: String- var offerRetryDownload: Bool-}--struct OverflowAlertState: Identifiable, Equatable {- let id = UUID()- let inputTokens: Int- let inputBudget: Int- let contextLength: Int- let maxOutput: Int-}-+#if canImport(EnteCore)@MainActorfinal class ChatViewModel: ObservableObject {private static let defaultTemperature: Float = 0.5@@ -436,11 +304,6 @@ final class ChatViewModel: ObservableObject {private static let sessionSummaryMaxWords = 7private static let sessionSummaryStoreKey = "ensu.session_summaries"private static let sessionSummarySystemPrompt = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no markdown characters, no quotes, no emojis, no trailing punctuation, and output only the title."- fileprivate static let fileSizeFormatter: ByteCountFormatter = {- let formatter = ByteCountFormatter()- formatter.countStyle = .file- return formatter- }()private let logger = EnsuLogging.shared.logger("ChatViewModel")@@ -492,6 +355,7 @@ final class ChatViewModel: ObservableObject {private var messageStore: [UUID: [MessageNode]] = [:]private var branchSelections: [UUID: [String: UUID]] = [:]+ private var childrenByParentCache: [UUID: [UUID: [MessageNode]]] = [:]private var sessionSummaries: [String: String] = [:]private var sessionSummaryTask: Task<Void, Never>?private let rootId = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!@@ -561,24 +425,7 @@ final class ChatViewModel: ObservableObject {// Load sessions/messages.let loaded = (try? chatDb.listSessions()) ?? []- let sessions: [ChatSession] = loaded.compactMap { session in- guard let id = UUID(uuidString: session.uuid) else { return nil }- let messages = (try? chatDb.getMessages(sessionUuid: session.uuid)) ?? []- let sortedMessages = messages.sorted { $0.createdAtUs < $1.createdAtUs }- let firstUserMessage = sortedMessages.first(where: { $0.sender == .selfUser })?.text ?? ""- let lastMessage = sortedMessages.last?.text ?? ""- let summary = summaries[session.uuid.lowercased()]- let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||- session.title.caseInsensitiveCompare("New chat") == .orderedSame- let seedTitle = summary ?? (isPlaceholderTitle ? firstUserMessage : session.title)- let title = Self.sessionTitle(from: seedTitle, fallback: session.title)- return ChatSession(- id: id,- title: title,- lastMessage: lastMessage,- updatedAt: Date(timeIntervalSince1970: Double(session.updatedAtUs) / 1_000_000.0)- )- }+ let sessions = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: summaries)// Stored properties.self.provider = provider@@ -598,8 +445,6 @@ final class ChatViewModel: ObservableObject {if let current = self.currentSessionId {loadMessagesFromDb(for: current)- rebuildMessages(for: current)- queueMissingAttachments(for: current)} else {refreshAttachmentDownloadState()}@@ -617,41 +462,46 @@ final class ChatViewModel: ObservableObject {}var attachmentDownloadProgress: Double? {- let active = attachmentDownloads.filter { $0.status != .canceled }+ let active = attachmentDownloads.filter { $0.status != AttachmentDownloadItem.Status.canceled }let total = active.countguard total > 0 else { return nil }- guard active.contains(where: { $0.status == .queued || $0.status == .downloading || $0.status == .failed }) else {- return nil++ let hasPending = active.contains { item in+ item.status == AttachmentDownloadItem.Status.queued ||+ item.status == AttachmentDownloadItem.Status.downloading ||+ item.status == AttachmentDownloadItem.Status.failed}- let completed = active.filter { $0.status == .completed }.count+ guard hasPending else { return nil }++ let completed = active.filter { $0.status == AttachmentDownloadItem.Status.completed }.countreturn Double(completed) / Double(total)}var attachmentDownloadSummary: (completed: Int, total: Int)? {- let active = attachmentDownloads.filter { $0.status != .canceled }+ let active = attachmentDownloads.filter { $0.status != AttachmentDownloadItem.Status.canceled }let total = active.countguard total > 0 else { return nil }- guard active.contains(where: { $0.status == .queued || $0.status == .downloading || $0.status == .failed }) else {- return nil++ let hasPending = active.contains { item in+ item.status == AttachmentDownloadItem.Status.queued ||+ item.status == AttachmentDownloadItem.Status.downloading ||+ item.status == AttachmentDownloadItem.Status.failed}- let completed = active.filter { $0.status == .completed }.count+ guard hasPending else { return nil }++ let completed = active.filter { $0.status == AttachmentDownloadItem.Status.completed }.countreturn (completed, total)}var modelDownloadSizeText: String {guard let bytes = modelDownloadSizeBytes else { return "Approx. size varies by model" }- return "Approx. \(Self.fileSizeFormatter.string(fromByteCount: bytes))"+ return "Approx. \(bytes.formattedFileSize)"}- func sessionTitle(for sessionId: UUID) -> String {- guard let title = sessions.first(where: { $0.id == sessionId })?.title else { return "Chat" }- return Self.sessionTitle(from: title, fallback: "Chat")- }-- func startNewSession() {+ private func resetGenerationState(stopRequested: Bool = false) {generationTask?.cancel()provider.stopGeneration()- stopRequested = false+ self.stopRequested = stopRequestedactiveGenerationId = nilactiveGenerationSessionId = nilisGenerating = false@@ -659,6 +509,15 @@ final class ChatViewModel: ObservableObject {streamingResponse = ""streamingParentId = nildownloadToast = nil+ }++ func sessionTitle(for sessionId: UUID) -> String {+ guard let title = sessions.first(where: { $0.id == sessionId })?.title else { return "Chat" }+ return Self.sessionTitle(from: title, fallback: "Chat")+ }++ func startNewSession() {+ resetGenerationState()draftText = ""draftAttachments = []editingMessageId = nil@@ -669,34 +528,15 @@ final class ChatViewModel: ObservableObject {}func selectSession(_ session: ChatSession) {- generationTask?.cancel()- provider.stopGeneration()- stopRequested = false- activeGenerationId = nil- activeGenerationSessionId = nil- isGenerating = false- isDownloading = false- streamingResponse = ""- streamingParentId = nil- downloadToast = nil+ resetGenerationState()currentSessionId = session.id+ messages = []loadMessagesFromDb(for: session.id)- rebuildMessages(for: session.id)- queueMissingAttachments(for: session.id)}func deleteSession(_ session: ChatSession) {if currentSessionId == session.id {- generationTask?.cancel()- provider.stopGeneration()- stopRequested = false- activeGenerationId = nil- activeGenerationSessionId = nil- isGenerating = false- isDownloading = false- streamingResponse = ""- streamingParentId = nil- downloadToast = nil+ resetGenerationState()}if let nodes = messageStore[session.id] {@@ -712,13 +552,13 @@ final class ChatViewModel: ObservableObject {sessions.removeAll { $0.id == session.id }messageStore[session.id] = nilbranchSelections[session.id] = nil+ childrenByParentCache[session.id] = nilpurgeAttachmentDownloads(for: session.id)if currentSessionId == session.id {currentSessionId = sessions.first?.idif let next = currentSessionId {+ messages = []loadMessagesFromDb(for: next)- rebuildMessages(for: next)- queueMissingAttachments(for: next)} else {messages = []refreshAttachmentDownloadState()@@ -769,10 +609,14 @@ final class ChatViewModel: ObservableObject {}} catch {let message = syncErrorMessage(from: error)+ let needsReset = ChatRecovery.shouldResetFromMessage(message)+ let userMessage = needsReset+ ? "\(message). Reset chat data to recover."+ : messagelog.error("Sync failed", error, details: message)await MainActor.run {if showErrors {- self.syncErrorMessage = "Sync failed: \(message)"+ self.syncErrorMessage = "Sync failed: \(userMessage)"}}}@@ -858,17 +702,24 @@ final class ChatViewModel: ObservableObject {let sessionId = currentSessionId ?? createSessionForDraft()- if !missingAttachments(for: sessionId).isEmpty {- queueMissingAttachments(for: sessionId)- return+ Task { @MainActor in+ let missing = await self.missingAttachments(for: sessionId)+ if !missing.isEmpty {+ self.queueMissingAttachments(for: sessionId, missing: missing)+ return+ }+ self.sendDraftMessage(trimmed: trimmed, attachments: attachments, sessionId: sessionId)}+ }+ private func sendDraftMessage(trimmed: String, attachments: [ChatAttachment], sessionId: UUID) {let parentId: UUID? = {if let editingId = editingMessageId {let existing = messageStore[sessionId]?.first { $0.id == editingId }return existing?.parentId}- return buildSelectedPath(for: sessionId).last?.id+ let childrenMap = childrenByParent(sessionId: sessionId)+ return buildSelectedPath(for: sessionId, childrenMap: childrenMap).last?.id}()let meta: [AttachmentMeta] = attachments.map { attachment in@@ -910,6 +761,7 @@ final class ChatViewModel: ObservableObject {)messageStore[sessionId, default: []].append(userNode)+ invalidateChildrenCache(for: sessionId)updateSelection(for: sessionId, parentId: parentId, childId: userNode.id)draftText = ""@@ -1047,7 +899,7 @@ final class ChatViewModel: ObservableObject {}func cancelDownload() {- generationTask?.cancel()+ resetGenerationState(stopRequested: true)modelDownloadTask?.cancel()modelDownloadTask = nilprovider.cancelDownload()@@ -1055,15 +907,7 @@ final class ChatViewModel: ObservableObject {logger.info("Model download cancelled")modelDownloadLoggedStart = false}- stopRequested = true- activeGenerationId = nil- activeGenerationSessionId = nil- isGenerating = false- isDownloading = falsehasRequestedModelDownload = false- streamingResponse = ""- streamingParentId = nil- downloadToast = nilrefreshModelDownloadInfo()}@@ -1081,13 +925,16 @@ final class ChatViewModel: ObservableObject {let userNode = messageStore[sessionId]?.first(where: { $0.id == parent }) else {return}- if !missingAttachments(for: sessionId).isEmpty {- queueMissingAttachments(for: sessionId)- return+ Task { @MainActor in+ let missing = await self.missingAttachments(for: sessionId)+ if !missing.isEmpty {+ self.queueMissingAttachments(for: sessionId, missing: missing)+ return+ }+ self.provider.resetContext()+ self.startGeneration(for: userNode)+ self.syncNow(showErrors: false)}- provider.resetContext()- startGeneration(for: userNode)- syncNow(showErrors: false)}func changeBranch(for message: ChatMessage, delta: Int) {@@ -1119,6 +966,7 @@ final class ChatViewModel: ObservableObject {currentSessionId = session.idmessageStore[session.id] = []branchSelections[session.id] = [:]+ invalidateChildrenCache(for: session.id)refreshAttachmentDownloadState()return session.id}@@ -1323,6 +1171,7 @@ final class ChatViewModel: ObservableObject {)messageStore[parent.sessionId, default: []].append(assistant)+ invalidateChildrenCache(for: parent.sessionId)updateSelection(for: parent.sessionId, parentId: parent.id, childId: assistant.id)updateSessionPreview(sessionId: parent.sessionId, preview: trimmed, date: assistant.timestamp)}@@ -1420,56 +1269,67 @@ final class ChatViewModel: ObservableObject {return description}- private func queueMissingAttachments(for sessionId: UUID) {- let missing = missingAttachments(for: sessionId)- guard !missing.isEmpty else {- refreshAttachmentDownloadState()- return- }+ private func queueMissingAttachments(for sessionId: UUID, missing: [AttachmentDownloadItem]? = nil) {+ Task { @MainActor in+ let resolvedMissing: [AttachmentDownloadItem]+ if let missing {+ resolvedMissing = missing+ } else {+ resolvedMissing = await self.missingAttachments(for: sessionId)+ }++ guard !resolvedMissing.isEmpty else {+ self.refreshAttachmentDownloadState(missing: [])+ return+ }- var updated = attachmentDownloads- for item in missing {- if let existingIndex = updated.firstIndex(where: { $0.id == item.id }) {- if updated[existingIndex].status == .failed || updated[existingIndex].status == .canceled {- updated[existingIndex].status = .queued- updated[existingIndex].errorMessage = nil+ var updated = self.attachmentDownloads+ for item in resolvedMissing {+ if let existingIndex = updated.firstIndex(where: { $0.id == item.id }) {+ if updated[existingIndex].status == AttachmentDownloadItem.Status.failed ||+ updated[existingIndex].status == AttachmentDownloadItem.Status.canceled {+ updated[existingIndex].status = AttachmentDownloadItem.Status.queued+ updated[existingIndex].errorMessage = nil+ }+ } else {+ updated.append(item)}- } else {- updated.append(item)}- }- attachmentDownloads = updated- for item in missing {- if !attachmentDownloadQueue.contains(item.id) && attachmentDownloadTasks[item.id] == nil {- attachmentDownloadQueue.append(item.id)+ self.attachmentDownloads = updated+ for item in resolvedMissing {+ if !self.attachmentDownloadQueue.contains(item.id) && self.attachmentDownloadTasks[item.id] == nil {+ self.attachmentDownloadQueue.append(item.id)+ }}- }- refreshAttachmentDownloadState()- startNextAttachmentDownloads()+ self.refreshAttachmentDownloadState(missing: resolvedMissing)+ self.startNextAttachmentDownloads()+ }}- private func missingAttachments(for sessionId: UUID) -> [AttachmentDownloadItem] {+ private func missingAttachments(for sessionId: UUID) async -> [AttachmentDownloadItem] {guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return [] }- var seen = Set<String>()- var missing: [AttachmentDownloadItem] = []+ let attachments = nodes.flatMap { $0.attachments }+ let existingDownloads = attachmentDownloads+ let attachmentsDir = attachmentsDir- for node in nodes {- for attachment in node.attachments {+ let result: (missing: [AttachmentDownloadItem], availableIds: Set<String>) = await Task.detached {+ var seen = Set<String>()+ var missing: [AttachmentDownloadItem] = []+ var availableIds = Set<String>()++ for attachment in attachments {let id = attachment.id.uuidString.lowercased()if seen.contains(id) { continue }seen.insert(id)let path = attachmentsDir.appendingPathComponent(id).pathif FileManager.default.fileExists(atPath: path) {- attachmentDownloadTasks[id]?.cancel()- attachmentDownloadTasks[id] = nil- attachmentDownloadQueue.removeAll { $0 == id }- attachmentDownloads.removeAll { $0.id == id }+ availableIds.insert(id)continue}- let existing = attachmentDownloads.first { $0.id == id }- let status = existing?.status ?? .queued+ let existing = existingDownloads.first { $0.id == id }+ let status = existing?.status ?? AttachmentDownloadItem.Status.queuedmissing.append(AttachmentDownloadItem(id: id,sessionId: sessionId,@@ -1479,9 +1339,20 @@ final class ChatViewModel: ObservableObject {errorMessage: existing?.errorMessage))}++ return (missing, availableIds)+ }.value++ if !result.availableIds.isEmpty {+ for id in result.availableIds {+ attachmentDownloadTasks[id]?.cancel()+ attachmentDownloadTasks[id] = nil+ }+ attachmentDownloadQueue.removeAll { result.availableIds.contains($0) }+ attachmentDownloads.removeAll { result.availableIds.contains($0.id) }}- return missing+ return result.missing}private func startNextAttachmentDownloads() {@@ -1491,11 +1362,12 @@ final class ChatViewModel: ObservableObject {while attachmentDownloadTasks.count < maxAttachmentDownloads, !attachmentDownloadQueue.isEmpty {let id = attachmentDownloadQueue.removeFirst()guard let index = attachmentDownloads.firstIndex(where: { $0.id == id }) else { continue }- if attachmentDownloads[index].status == .canceled || attachmentDownloads[index].status == .completed {+ if attachmentDownloads[index].status == AttachmentDownloadItem.Status.canceled ||+ attachmentDownloads[index].status == AttachmentDownloadItem.Status.completed {continue}let sessionId = attachmentDownloads[index].sessionId- attachmentDownloads[index].status = .downloading+ attachmentDownloads[index].status = AttachmentDownloadItem.Status.downloadinglet task = Task.detached { [weak self] inguard let self else { return }@@ -1506,12 +1378,12 @@ final class ChatViewModel: ObservableObject {auth: auth)await MainActor.run {- self.updateAttachmentDownloadStatus(id: id, status: .completed, errorMessage: nil)+ self.updateAttachmentDownloadStatus(id: id, status: AttachmentDownloadItem.Status.completed, errorMessage: nil)}} catch {let message = self.syncErrorMessage(from: error)await MainActor.run {- self.updateAttachmentDownloadStatus(id: id, status: .failed, errorMessage: message)+ self.updateAttachmentDownloadStatus(id: id, status: AttachmentDownloadItem.Status.failed, errorMessage: message)}}}@@ -1525,9 +1397,9 @@ final class ChatViewModel: ObservableObject {errorMessage: String?) {if let index = attachmentDownloads.firstIndex(where: { $0.id == id }) {- if attachmentDownloads[index].status != .canceled {+ if attachmentDownloads[index].status != AttachmentDownloadItem.Status.canceled {attachmentDownloads[index].status = status- attachmentDownloads[index].errorMessage = status == .failed ? errorMessage : nil+ attachmentDownloads[index].errorMessage = status == AttachmentDownloadItem.Status.failed ? errorMessage : nil}}attachmentDownloadTasks[id] = nil@@ -1535,11 +1407,19 @@ final class ChatViewModel: ObservableObject {startNextAttachmentDownloads()}- private func refreshAttachmentDownloadState() {- if let sessionId = currentSessionId {- currentSessionMissingAttachments = missingAttachments(for: sessionId)- } else {+ private func refreshAttachmentDownloadState(missing: [AttachmentDownloadItem]? = nil) {+ guard let sessionId = currentSessionId else {currentSessionMissingAttachments = []+ return+ }++ if let missing {+ currentSessionMissingAttachments = missing+ return+ }++ Task { @MainActor in+ self.currentSessionMissingAttachments = await self.missingAttachments(for: sessionId)}}@@ -1549,7 +1429,7 @@ final class ChatViewModel: ObservableObject {attachmentDownloadTasks[id] = nil}if let index = attachmentDownloads.firstIndex(where: { $0.id == id }) {- attachmentDownloads[index].status = .canceled+ attachmentDownloads[index].status = AttachmentDownloadItem.Status.canceled}attachmentDownloadQueue.removeAll { $0 == id }refreshAttachmentDownloadState()@@ -1568,15 +1448,18 @@ final class ChatViewModel: ObservableObject {startNextAttachmentDownloads()}- private func reloadFromDb() {- let loaded = (try? chatDb.listSessions()) ?? []- let refreshed: [ChatSession] = loaded.compactMap { session in+ private static func buildSessions(+ from loaded: [LlmChatSession],+ chatDb: LlmChatDb,+ summaries: [String: String]+ ) -> [ChatSession] {+ loaded.compactMap { session inguard let id = UUID(uuidString: session.uuid) else { return nil }let messages = (try? chatDb.getMessages(sessionUuid: session.uuid)) ?? []let sortedMessages = messages.sorted { $0.createdAtUs < $1.createdAtUs }let firstUserMessage = sortedMessages.first(where: { $0.sender == .selfUser })?.text ?? ""let lastMessage = sortedMessages.last?.text ?? ""- let summary = sessionSummaries[sessionSummaryKey(session.uuid)]+ let summary = summaries[session.uuid.lowercased()]let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||session.title.caseInsensitiveCompare("New chat") == .orderedSamelet seedTitle = summary ?? (isPlaceholderTitle ? firstUserMessage : session.title)@@ -1588,6 +1471,11 @@ final class ChatViewModel: ObservableObject {updatedAt: Date(timeIntervalSince1970: Double(session.updatedAtUs) / 1_000_000.0))}+ }++ private func reloadFromDb() {+ let loaded = (try? chatDb.listSessions()) ?? []+ let refreshed = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: sessionSummaries)let selected = currentSessionIdlet resolved = selected.flatMap { id in@@ -1599,6 +1487,7 @@ final class ChatViewModel: ObservableObject {messages = []messageStore = [:]branchSelections = [:]+ childrenByParentCache = [:]for session in refreshed {messageStore[session.id] = []@@ -1607,67 +1496,75 @@ final class ChatViewModel: ObservableObject {if let current = resolved {loadMessagesFromDb(for: current)- rebuildMessages(for: current)- queueMissingAttachments(for: current)} else {refreshAttachmentDownloadState()}}private func loadMessagesFromDb(for sessionId: UUID) {- guard messageStore[sessionId] != nil else {+ if messageStore[sessionId] == nil {messageStore[sessionId] = []branchSelections[sessionId] = [:]- return}- guard let rawMessages = try? chatDb.getMessages(sessionUuid: sessionId.uuidString) else {- messageStore[sessionId] = []- branchSelections[sessionId] = [:]- return- }+ let chatDb = chatDb+ let attachmentsDir = attachmentsDir- let nodes: [MessageNode] = rawMessages.compactMap { msg in- guard let messageId = UUID(uuidString: msg.uuid) else { return nil }- let parentId = msg.parentMessageUuid.flatMap { UUID(uuidString: $0) }- let role: ChatMessage.Role = (msg.sender == .selfUser) ? .user : .assistant- let timestamp = Date(timeIntervalSince1970: Double(msg.createdAtUs) / 1_000_000.0)-- let attachments: [ChatAttachment] = msg.attachments.compactMap { meta in- guard let attachmentId = UUID(uuidString: meta.id) else { return nil }- let kind: ChatAttachment.Kind = (meta.kind == .image) ? .image : .document- let url = attachmentsDir.appendingPathComponent(meta.id)- return ChatAttachment(- id: attachmentId,- name: meta.name,- size: meta.size,- kind: kind,- url: url,- isUploading: false+ Task.detached { [weak self, chatDb, attachmentsDir] in+ guard let self else { return }++ let rawMessages = (try? chatDb.getMessages(sessionUuid: sessionId.uuidString)) ?? []++ let nodes: [MessageNode] = rawMessages.compactMap { msg in+ guard let messageId = UUID(uuidString: msg.uuid) else { return nil }+ let parentId = msg.parentMessageUuid.flatMap { UUID(uuidString: $0) }+ let role: ChatMessage.Role = (msg.sender == .selfUser) ? .user : .assistant+ let timestamp = Date(timeIntervalSince1970: Double(msg.createdAtUs) / 1_000_000.0)++ let attachments: [ChatAttachment] = msg.attachments.compactMap { meta in+ guard let attachmentId = UUID(uuidString: meta.id) else { return nil }+ let kind: ChatAttachment.Kind = (meta.kind == .image) ? .image : .document+ let url = attachmentsDir.appendingPathComponent(meta.id)+ return ChatAttachment(+ id: attachmentId,+ name: meta.name,+ size: meta.size,+ kind: kind,+ url: url,+ isUploading: false+ )+ }++ return MessageNode(+ id: messageId,+ sessionId: sessionId,+ parentId: parentId,+ role: role,+ text: msg.text,+ timestamp: timestamp,+ attachments: attachments,+ isInterrupted: false,+ tokensPerSecond: nil)}- return MessageNode(- id: messageId,- sessionId: sessionId,- parentId: parentId,- role: role,- text: msg.text,- timestamp: timestamp,- attachments: attachments,- isInterrupted: false,- tokensPerSecond: nil- )+ await MainActor.run {+ guard self.messageStore[sessionId] != nil else { return }+ self.messageStore[sessionId] = nodes+ // Branch selection is computed in-memory.+ self.branchSelections[sessionId] = [:]+ self.invalidateChildrenCache(for: sessionId)+ if self.currentSessionId == sessionId {+ self.rebuildMessages(for: sessionId)+ self.queueMissingAttachments(for: sessionId)+ }+ }}-- messageStore[sessionId] = nodes- // Branch selection is computed in-memory.- branchSelections[sessionId] = [:]}private func rebuildMessages(for sessionId: UUID) {- let path = buildSelectedPath(for: sessionId)let childrenMap = childrenByParent(sessionId: sessionId)+ let path = buildSelectedPath(for: sessionId, childrenMap: childrenMap)let selectionMap = branchSelections[sessionId, default: [:]]messages = path.map { node in@@ -1691,10 +1588,9 @@ final class ChatViewModel: ObservableObject {}}- private func buildSelectedPath(for sessionId: UUID) -> [MessageNode] {+ private func buildSelectedPath(for sessionId: UUID, childrenMap: [UUID: [MessageNode]]) -> [MessageNode] {guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return [] }let byId = Dictionary(uniqueKeysWithValues: nodes.map { ($0.id, $0) })- let childrenMap = childrenByParent(sessionId: sessionId)let roots = dedupeSiblings(nodes.filter { node inguard let parentId = node.parentId else { return true }return byId[parentId] == nil@@ -1725,7 +1621,14 @@ final class ChatViewModel: ObservableObject {return candidates.last}+ private func invalidateChildrenCache(for sessionId: UUID) {+ childrenByParentCache[sessionId] = nil+ }+private func childrenByParent(sessionId: UUID) -> [UUID: [MessageNode]] {+ if let cached = childrenByParentCache[sessionId] {+ return cached+ }var map: [UUID: [MessageNode]] = [:]guard let nodes = messageStore[sessionId] else { return map }let byId = Dictionary(uniqueKeysWithValues: nodes.map { ($0.id, $0) })@@ -1733,6 +1636,7 @@ final class ChatViewModel: ObservableObject {let parent = node.parentId.flatMap { byId[$0] != nil ? $0 : nil } ?? rootIdmap[parent, default: []].append(node)}+ childrenByParentCache[sessionId] = mapreturn map}@@ -2021,7 +1925,8 @@ final class ChatViewModel: ObservableObject {currentMessageId: UUID,target: InferenceModelTarget) -> HistorySelection {- let path = buildSelectedPath(for: sessionId)+ let childrenMap = childrenByParent(sessionId: sessionId)+ let path = buildSelectedPath(for: sessionId, childrenMap: childrenMap)let historyMessages = path.prefix { $0.id != currentMessageId }let contextSize: Int = target.contextLength ?? 4096@@ -2057,8 +1962,18 @@ final class ChatViewModel: ObservableObject {private func historyText(_ node: MessageNode) -> String {var text = node.textif node.role == .assistant {- text = text.replacingOccurrences(of: "<think>[\\s\\S]*?</think>", with: "", options: .regularExpression)- text = text.replacingOccurrences(of: "<todo_list>[\\s\\S]*?</todo_list>", with: "", options: .regularExpression)+ if let regex = ChatMessageTagRegex.think {+ let range = NSRange(text.startIndex..., in: text)+ text = regex.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "")+ } else {+ text = text.replacingOccurrences(of: "<think>[\\s\\S]*?</think>", with: "", options: .regularExpression)+ }+ if let regex = ChatMessageTagRegex.todoList {+ let range = NSRange(text.startIndex..., in: text)+ text = regex.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "")+ } else {+ text = text.replacingOccurrences(of: "<todo_list>[\\s\\S]*?</todo_list>", with: "", options: .regularExpression)+ }} else if !node.attachments.isEmpty {text += "\n\n[\(node.attachments.count) attachments attached]"}@@ -2107,3 +2022,9 @@ final class ChatViewModel: ObservableObject {let imageFiles: [URL]}}+#else+@MainActor+final class ChatViewModel: ObservableObject {+ init() {}+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/Components/ChatViewComponents.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/Components/ChatViewComponents.swiftnew file mode 100644index 0000000000..ac0eb842ae--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/Components/ChatViewComponents.swift@@ -0,0 +1,334 @@+#if canImport(EnteCore)+import SwiftUI++struct DownloadOnboardingView: View {+ let isDownloading: Bool+ let downloadPercent: Int?+ let statusText: String?+ let totalBytes: Int64?+ let sizeText: String+ let onDownload: () -> Void++ var body: some View {+ VStack(spacing: EnsuSpacing.md) {+ Text("Download to begin using the Chat")+ .font(EnsuTypography.large)+ .foregroundStyle(EnsuColor.textPrimary)+ .multilineTextAlignment(.center)++ if isDownloading {+ let statusLine: String = {+ if let statusText, statusText.localizedCaseInsensitiveContains("loading") {+ return statusText+ }+ if let totalBytes, let percent = downloadPercent, percent >= 0 {+ let clamped = min(max(percent, 0), 100)+ let downloaded = Int64(Double(totalBytes) * Double(clamped) / 100.0)+ return "Downloading... \(downloaded.formattedFileSize) / \(totalBytes.formattedFileSize)"+ }+ if let statusText, !statusText.isEmpty {+ return statusText+ }+ return "Downloading..."+ }()++ Text(statusLine)+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textMuted)+ .multilineTextAlignment(.center)++ progressView+ } else {+ Button("Download") {+ hapticMedium()+ onDownload()+ }+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.backgroundBase)+ .frame(maxWidth: 200)+ .padding(.vertical, EnsuSpacing.md)+ .background(EnsuColor.accent)+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.button))++ Text(sizeText)+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding(.horizontal, EnsuSpacing.pageHorizontal)+ }++ @ViewBuilder+ private var progressView: some View {+ if let percent = downloadPercent, percent >= 0 {+ let clamped = min(max(percent, 0), 100)+ ProgressView(value: Double(clamped), total: 100)+ .progressViewStyle(.linear)+ .tint(EnsuColor.accent)+ .frame(maxWidth: 240)+ } else {+ ProgressView()+ .progressViewStyle(.linear)+ .tint(EnsuColor.accent)+ .frame(maxWidth: 240)+ }+ }++}++struct ComingSoonSheet: View {+ let title: String+ let message: String+ let onDismiss: () -> Void++ var body: some View {+ VStack(spacing: EnsuSpacing.lg) {+ RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous)+ .fill(EnsuColor.fillFaint)+ .frame(height: 180)+ .overlay(+ Text("Illustration")+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)+ )++ Text(title)+ .font(EnsuTypography.large)+ .foregroundStyle(EnsuColor.textPrimary)++ Text(message)+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textMuted)+ .multilineTextAlignment(.center)++ Button("Got it") {+ onDismiss()+ }+ .buttonStyle(.borderedProminent)+ .tint(EnsuColor.accent)+ }+ .padding(EnsuSpacing.xl)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(EnsuColor.backgroundBase)+ }+}++struct AttachmentDownloadsSheet: View {+ let downloads: [AttachmentDownloadItem]+ let sessionTitle: (UUID) -> String+ let onCancel: (String) -> Void+ let onDismiss: () -> Void++ var body: some View {+ VStack(spacing: 0) {+ HStack {+ Text("Attachment downloads")+ .font(EnsuTypography.h3Bold)+ Spacer()+ Button("Close", action: onDismiss)+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.accent)+ }+ .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.vertical, EnsuSpacing.sm)++ Divider()+ .background(EnsuColor.border)++ if downloads.isEmpty {+ Text("No pending downloads")+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textMuted)+ .padding(.top, EnsuSpacing.lg)+ Spacer()+ } else {+ List(downloads) { item in+ HStack(spacing: EnsuSpacing.md) {+ VStack(alignment: .leading, spacing: 4) {+ Text(item.name)+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textPrimary)+ .lineLimit(1)+ Text("\(sessionTitle(item.sessionId)) β’ \(item.formattedSize)")+ .font(EnsuTypography.mini)+ .foregroundStyle(EnsuColor.textMuted)+ if item.status == .failed, let errorMessage = item.errorMessage, !errorMessage.isEmpty {+ Text(errorMessage)+ .font(EnsuTypography.mini)+ .foregroundStyle(EnsuColor.error)+ .lineLimit(2)+ }+ }++ Spacer()++ Text(statusText(for: item.status))+ .font(EnsuTypography.mini)+ .foregroundStyle(EnsuColor.textMuted)++ if item.status == .queued || item.status == .downloading {+ Button(action: {+ hapticWarning()+ onCancel(item.id)+ }) {+ Image("Cancel01Icon")+ .resizable()+ .scaledToFit()+ .frame(width: 18, height: 18)+ .foregroundStyle(EnsuColor.textMuted)+ }+ .buttonStyle(.plain)+ }+ }+ .padding(.vertical, 4)+ }+ .listStyle(.plain)+ }+ }+ .frame(minHeight: 320)+ .background(EnsuColor.backgroundBase)+ }++ private func statusText(for status: AttachmentDownloadItem.Status) -> String {+ switch status {+ case .queued:+ return "Queued"+ case .downloading:+ return "Downloading"+ case .completed:+ return "Completed"+ case .failed:+ return "Failed"+ case .canceled:+ return "Canceled"+ }+ }+}++struct ChatAppBar: View {+ let sessionTitle: String+ let showBrand: Bool+ let showSignIn: Bool+ let showsMenuButton: Bool+ let attachmentDownloadSummary: (completed: Int, total: Int)?+ let modelDownloadState: DownloadToastState?+ let onMenu: () -> Void+ let onSignIn: () -> Void+ let onAttachmentDownloads: () -> Void++ private let centerInset: CGFloat = 72++ private var modelProgressState: DownloadToastState? {+ guard let modelDownloadState else { return nil }+ switch modelDownloadState.phase {+ case .loading, .downloading:+ return modelDownloadState+ default:+ return nil+ }+ }++ var body: some View {+ ZStack {+ HStack(spacing: EnsuSpacing.md) {+ if showsMenuButton {+ Button(action: {+ hapticTap()+ onMenu()+ }) {+ Image("Menu01Icon")+ .resizable()+ .scaledToFit()+ .frame(width: 18, height: 18)+ .frame(width: 40, height: 40)+ }+ .buttonStyle(.plain)+ } else {+ Color.clear+ .frame(width: 40, height: 40)+ }++ Spacer()++ HStack(spacing: EnsuSpacing.md) {+ if showSignIn {+ if let progress = modelProgressState {+ ModelProgressIndicator(state: progress)+ }+ Button(action: {+ hapticTap()+ onSignIn()+ }) {+ Text("Sign In")+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.accent)+ }+ .buttonStyle(.plain)+ } else {+ if let summary = attachmentDownloadSummary {+ Button(action: {+ hapticTap()+ onAttachmentDownloads()+ }) {+ HStack(spacing: 6) {+ Image("Upload01Icon")+ .resizable()+ .scaledToFit()+ .frame(width: 14, height: 14)+ .foregroundStyle(EnsuColor.textPrimary)+ Text("\(summary.completed)/\(summary.total)")+ .font(EnsuTypography.mini)+ .foregroundStyle(EnsuColor.textMuted)+ }+ .padding(.horizontal, 8)+ .padding(.vertical, 6)+ .background(EnsuColor.fillFaint)+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))+ }+ .buttonStyle(.plain)+ }+ if let progress = modelProgressState {+ ModelProgressIndicator(state: progress)+ }+ }+ }+ }++ if showBrand {+ EnsuLogo(height: 20)+ .padding(.horizontal, centerInset)+ } else {+ Text(sessionTitle)+ .font(EnsuTypography.large)+ .foregroundStyle(EnsuColor.textPrimary)+ .lineLimit(1)+ .minimumScaleFactor(0.85)+ .padding(.horizontal, centerInset)+ }+ }+ .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.vertical, EnsuSpacing.sm)+ .background(EnsuColor.backgroundBase)+ }+}++struct ModelProgressIndicator: View {+ let state: DownloadToastState++ var body: some View {+ let clamped = min(max(state.percent, 0), 100)+ if state.phase == .downloading {+ ProgressView(value: Double(clamped), total: 100)+ .progressViewStyle(.circular)+ .tint(EnsuColor.accent)+ .frame(width: 16, height: 16)+ } else {+ ProgressView()+ .progressViewStyle(.circular)+ .tint(EnsuColor.accent)+ .frame(width: 16, height: 16)+ }+ }+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swiftnew file mode 100644index 0000000000..9322ffe059--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift@@ -0,0 +1,1051 @@+#if canImport(EnteCore)+import SwiftUI+import Markdown+#if os(macOS)+import QuickLookUI+#else+import QuickLook+#endif+#if os(iOS)+import UIKit+#endif++struct BottomOffsetKey: PreferenceKey {+ static var defaultValue: CGFloat = 0++ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {+ value = nextValue()+ }+}++struct ContentHeightKey: PreferenceKey {+ static var defaultValue: CGFloat = 0++ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {+ value = nextValue()+ }+}++struct AttachmentPreviewItem: Identifiable {+ let url: URL+ var id: String { url.path }+}++#if os(iOS)+struct QuickLookPreview: UIViewControllerRepresentable {+ let url: URL++ func makeUIViewController(context: Context) -> QLPreviewController {+ let controller = QLPreviewController()+ controller.dataSource = context.coordinator+ return controller+ }++ func updateUIViewController(_ uiViewController: QLPreviewController, context: Context) {+ context.coordinator.url = url+ uiViewController.reloadData()+ }++ func makeCoordinator() -> Coordinator {+ Coordinator(url: url)+ }++ final class Coordinator: NSObject, QLPreviewControllerDataSource {+ var url: URL++ init(url: URL) {+ self.url = url+ }++ func numberOfPreviewItems(in controller: QLPreviewController) -> Int {+ 1+ }++ func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {+ url as NSURL+ }+ }+}+#elseif os(macOS)+struct QuickLookPreview: NSViewRepresentable {+ let url: URL++ func makeNSView(context: Context) -> QLPreviewView {+ let view = QLPreviewView(frame: .zero, style: .normal)!+ view.autostarts = true+ view.previewItem = url as NSURL+ return view+ }++ func updateNSView(_ nsView: QLPreviewView, context: Context) {+ nsView.previewItem = url as NSURL+ }+}+#endif++struct UserMessageBubbleView: View {+ let message: ChatMessage+ let onEdit: () -> Void+ let onCopy: () -> Void+ let onBranchChange: (Int) -> Void+ let onOpenAttachment: (ChatAttachment) -> Void++ @Environment(\.colorScheme) private var colorScheme++ var body: some View {+ let bubbleShape = RoundedRectangle(cornerRadius: 18, style: .continuous)+ let bubbleFill = colorScheme == .dark ? EnsuColor.fillFaint : EnsuColor.border.opacity(0.2)++ HStack(alignment: .bottom) {+ Spacer(minLength: EnsuSpacing.messageBubbleInset)++ VStack(alignment: .trailing, spacing: EnsuSpacing.sm) {+ if !message.attachments.isEmpty {+ FlowLayout(spacing: EnsuSpacing.sm) {+ ForEach(message.attachments) { attachment in+ AttachmentChip(+ name: attachment.name,+ size: attachment.formattedSize,+ icon: attachment.iconName,+ isUploading: attachment.isUploading+ )+ .onTapGesture {+ hapticTap()+ onOpenAttachment(attachment)+ }+ }+ }+ .frame(maxWidth: .infinity, alignment: .trailing)+ }++ VStack(alignment: .trailing, spacing: EnsuSpacing.sm) {+ Text(message.text)+ .font(EnsuTypography.message)+ .foregroundStyle(EnsuColor.userMessageText)+ .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))+ .multilineTextAlignment(.trailing)+ .textSelection(.enabled)+ }+ .padding(EnsuSpacing.md)+ .background(bubbleFill)+ .clipShape(bubbleShape)+ #if os(iOS)+ .contextMenu {+ Button("Edit") {+ hapticTap()+ onEdit()+ }+ Button("Copy") {+ hapticTap()+ onCopy()+ }+ }+ #endif++ HStack(spacing: EnsuSpacing.sm) {+ Spacer()+ if message.branchCount > 1 {+ BranchSwitcherView(+ currentIndex: message.branchIndex,+ totalCount: message.branchCount,+ onPrevious: { onBranchChange(-1) },+ onNext: { onBranchChange(1) }+ )+ }+ TimestampView(date: message.timestamp)+ }+ }+ }+ }+}++struct AssistantMessageBubbleView: View {+ let message: ChatMessage+ let onCopy: () -> Void+ let onRetry: () -> Void+ let onBranchChange: (Int) -> Void+ let onOpenAttachment: (ChatAttachment) -> Void++ var body: some View {+ HStack(alignment: .bottom) {+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ AssistantMessageRenderer(text: message.text, isStreaming: false, storageId: message.id.uuidString)++ if message.isInterrupted {+ Text("Interrupted")+ .font(EnsuTypography.small)+ .italic()+ .foregroundStyle(EnsuColor.textMuted)+ }+ }+ .padding(.vertical, EnsuSpacing.md)+ .padding(.horizontal, EnsuSpacing.sm)+ #if os(iOS)+ .contextMenu {+ Button("Copy") {+ hapticTap()+ onCopy()+ }+ Button("Retry") {+ hapticMedium()+ onRetry()+ }+ }+ #endif++ HStack(spacing: EnsuSpacing.sm) {+ TimestampView(date: message.timestamp)+ if message.branchCount > 1 {+ BranchSwitcherView(+ currentIndex: message.branchIndex,+ totalCount: message.branchCount,+ onPrevious: { onBranchChange(-1) },+ onNext: { onBranchChange(1) }+ )+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, EnsuSpacing.sm)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ }+}++private enum StreamingCursor {+ static let glyph = "β"+}++struct StreamingBubbleView: View {+ let text: String++ @State private var storageId = UUID().uuidString++ var body: some View {+ HStack(alignment: .bottom) {+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ LoadingDotsView()+ } else {+ TimelineView(.periodic(from: .now, by: 0.55)) { context in+ let phase = Int(context.date.timeIntervalSinceReferenceDate * 2) % 2+ let showCursor = phase == 0+ AssistantMessageRenderer(+ text: text,+ isStreaming: true,+ storageId: storageId,+ showsCursor: showCursor+ )+ }+ }+ }+ .padding(.vertical, EnsuSpacing.md)+ .padding(.horizontal, EnsuSpacing.sm)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .foregroundStyle(EnsuColor.textPrimary)+ }+}++struct LoadingDotsView: View {+ @State private var phrase: String = LoadingDotsView.randomPhrase()++ var body: some View {+ TimelineView(.periodic(from: .now, by: 0.5)) { context in+ let phase = Int(context.date.timeIntervalSinceReferenceDate * 2) % 3+ Text(phrase + dots(for: phase))+ .font(EnsuTypography.message)+ .foregroundStyle(EnsuColor.textMuted)+ }+ }++ private static let loadingPhraseVerbs = [+ "Generating",+ "Thinking through",+ "Assembling",+ "Drafting",+ "Composing",+ "Crunching",+ "Exploring",+ "Piecing together",+ "Reviewing",+ "Organizing",+ "Synthesizing",+ "Sketching",+ "Refining",+ "Shaping"+ ]++ private static let loadingPhraseTargets = [+ "your reply",+ "an answer",+ "ideas",+ "context",+ "details",+ "the response",+ "the next steps",+ "a solution",+ "the summary",+ "insights",+ "the draft",+ "the explanation"+ ]++ private static func randomPhrase() -> String {+ let verb = loadingPhraseVerbs.randomElement() ?? "Generating"+ let target = loadingPhraseTargets.randomElement() ?? "your reply"+ return "\(verb) \(target)"+ }++ private func dots(for phase: Int) -> String {+ switch phase {+ case 0: return "."+ case 1: return ".."+ default: return "..."+ }+ }+}++struct TimestampView: View {+ let date: Date++ var body: some View {+ Text(Self.formatter.string(from: date))+ .font(EnsuTypography.mini)+ .foregroundStyle(EnsuColor.textMuted)+ .monospacedDigit()+ }++ private static let formatter: DateFormatter = {+ let formatter = DateFormatter()+ formatter.dateFormat = "h:mm a"+ return formatter+ }()+}++struct BranchSwitcherView: View {+ let currentIndex: Int+ let totalCount: Int+ let onPrevious: () -> Void+ let onNext: () -> Void++ var body: some View {+ if totalCount > 1 {+ HStack(spacing: EnsuSpacing.sm) {+ TextActionButton(text: "<", action: onPrevious)+ .disabled(currentIndex <= 1)+ Text(String(format: "%2d/%d", currentIndex, totalCount))+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)+ .monospacedDigit()+ TextActionButton(text: ">", action: onNext)+ .disabled(currentIndex >= totalCount)+ }+ }+ }+}++struct AssistantMessageRenderer: View {+ let text: String+ let isStreaming: Bool+ let storageId: String+ var showsCursor: Bool = false++ @State private var parsedMessage: ParsedMessage+ @State private var cachedText: String++ init(text: String, isStreaming: Bool, storageId: String, showsCursor: Bool = false) {+ self.text = text+ self.isStreaming = isStreaming+ self.storageId = storageId+ self.showsCursor = showsCursor+ let parsed = ParsedMessage(text: text)+ _parsedMessage = State(initialValue: parsed)+ _cachedText = State(initialValue: text)+ }++ var body: some View {+ VStack(alignment: .leading, spacing: EnsuSpacing.lg) {+ if let think = parsedMessage.thinkContent {+ ThinkSectionView(content: think, isStreaming: isStreaming, storageId: storageId)+ }++ ForEach(parsedMessage.todoBlocks) { block in+ TodoListCardView(title: block.title, status: block.status, items: block.items)+ }++ if !parsedMessage.markdownBlocks.isEmpty || showsCursor {+ MarkdownView(blocks: parsedMessage.markdownBlocks, showCursor: showsCursor)+ }+ }+ .onChange(of: text) { newValue in+ guard newValue != cachedText else { return }+ cachedText = newValue+ parsedMessage = ParsedMessage(text: newValue)+ }+ }+}++struct ParsedMessage {+ struct TodoBlock: Identifiable {+ let id = UUID()+ let title: String+ let status: String?+ let items: [String]+ }++ let thinkContent: String?+ let todoBlocks: [TodoBlock]+ let markdown: String+ let markdownBlocks: [MarkdownBlock]++ init(text: String) {+ var remaining = text+ var think: String?+ var todos: [TodoBlock] = []++ if let thinkRange = ParsedMessage.extractTag(using: ChatMessageTagRegex.think, from: remaining) {+ think = thinkRange.content.trimmingCharacters(in: .whitespacesAndNewlines)+ remaining = thinkRange.cleaned+ }++ let todoMatches = ParsedMessage.extractTags(using: ChatMessageTagRegex.todoList, from: remaining)+ remaining = todoMatches.cleaned++ for content in todoMatches.contents {+ if let data = content.data(using: .utf8),+ let payload = try? JSONDecoder().decode(TodoPayload.self, from: data) {+ todos.append(TodoBlock(title: payload.title, status: payload.status, items: payload.items))+ }+ }++ self.thinkContent = think+ self.todoBlocks = todos+ self.markdown = remaining+ self.markdownBlocks = MarkdownParser.parse(remaining)+ }++ private static func extractTag(using regex: NSRegularExpression?, from text: String) -> (content: String, cleaned: String)? {+ guard let regex else { return nil }+ guard let match = regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) else { return nil }+ guard let range = Range(match.range(at: 1), in: text) else { return nil }+ let content = String(text[range])+ let cleaned = regex.stringByReplacingMatches(in: text, range: NSRange(text.startIndex..., in: text), withTemplate: "")+ return (content, cleaned)+ }++ private static func extractTags(using regex: NSRegularExpression?, from text: String) -> (contents: [String], cleaned: String) {+ guard let regex else {+ return ([], text)+ }++ let matches = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))+ let contents: [String] = matches.compactMap { match in+ guard let range = Range(match.range(at: 1), in: text) else { return nil }+ return String(text[range])+ }+ let cleaned = regex.stringByReplacingMatches(in: text, range: NSRange(text.startIndex..., in: text), withTemplate: "")+ return (contents, cleaned)+ }++ private struct TodoPayload: Decodable {+ let title: String+ let status: String?+ let items: [String]+ }+}++struct ThinkSectionView: View {+ let content: String+ let isStreaming: Bool+ let storageId: String++ @SceneStorage private var isExpanded: Bool++ init(content: String, isStreaming: Bool, storageId: String) {+ self.content = content+ self.isStreaming = isStreaming+ self.storageId = storageId+ _isExpanded = SceneStorage(wrappedValue: false, "thinkExpanded_\(storageId)")+ }++ var body: some View {+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ Button {+ withAnimation(.easeInOut(duration: 0.16)) {+ isExpanded.toggle()+ }+ } label: {+ HStack {+ Text("THINK")+ .font(EnsuTypography.mini)+ .tracking(0.5)+ .foregroundStyle(EnsuColor.textMuted)+ Spacer()+ Image(systemName: "chevron.down")+ .rotationEffect(.degrees(isExpanded ? 180 : 0))+ .foregroundStyle(EnsuColor.textMuted)+ }+ }+ .buttonStyle(.plain)++ if isExpanded {+ Text(content)+ .font(EnsuFont.code(size: 12.5, weight: .regular))+ .foregroundStyle(EnsuColor.textPrimary)+ .lineSpacing(EnsuLineHeight.spacing(fontSize: 12.5, lineHeight: 1.45))+ .textSelection(.enabled)+ } else if isStreaming {+ Text("β¦" + content)+ .font(EnsuFont.code(size: 12.5, weight: .regular))+ .foregroundStyle(EnsuColor.textMuted)+ .lineLimit(4)+ }+ }+ .padding(EnsuSpacing.cardPadding)+ .background(EnsuColor.fillFaint)+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))+ .onChange(of: isStreaming) { newValue in+ if !newValue {+ isExpanded = false+ }+ }+ }+}++struct TodoListCardView: View {+ let title: String+ let status: String?+ let items: [String]++ var body: some View {+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ HStack {+ Text(title)+ .font(EnsuFont.message(size: 14, weight: .semibold))+ .foregroundStyle(EnsuColor.textPrimary)+ Spacer()+ Text("\(items.count)")+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)+ }++ if let status {+ Text(status)+ .font(EnsuFont.message(size: 12.5, weight: .regular))+ .foregroundStyle(EnsuColor.textMuted)+ }++ VStack(alignment: .leading, spacing: 6) {+ ForEach(items, id: \.self) { item in+ HStack(alignment: .top, spacing: EnsuSpacing.sm) {+ Circle()+ .fill(EnsuColor.accent)+ .frame(width: 6, height: 6)+ .padding(.top, 6)+ Text(item)+ .font(EnsuFont.message(size: 14, weight: .regular))+ .foregroundStyle(EnsuColor.textPrimary)+ .lineSpacing(EnsuLineHeight.spacing(fontSize: 14, lineHeight: 1.5))+ }+ }+ }+ }+ .padding(EnsuSpacing.cardPadding)+ .background(EnsuColor.fillFaint)+ .overlay(+ RoundedRectangle(cornerRadius: EnsuCornerRadius.card)+ .stroke(EnsuColor.border, lineWidth: 1)+ )+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))+ }+}++struct MarkdownView: View {+ let blocks: [MarkdownBlock]+ var showCursor: Bool = false++ var body: some View {+ let lastKind = blocks.last?.kind+ let inlineCursorSupported = lastKind.map { kind in+ switch kind {+ case .heading, .paragraph, .blockquote, .list:+ return true+ case .code, .math, .divider:+ return false+ }+ } ?? false+ let showTrailingCursor = showCursor && (!inlineCursorSupported || blocks.isEmpty)++ VStack(alignment: .leading, spacing: EnsuSpacing.md) {+ ForEach(Array(blocks.enumerated()), id: \.element.id) { index, block in+ let isLast = index == blocks.count - 1+ switch block.kind {+ case .heading(let level, let text):+ let displayText = showCursor && isLast ? text + StreamingCursor.glyph : text+ markdownText(displayText)+ .font(headingFont(for: level))+ .foregroundStyle(EnsuColor.textPrimary)+ case .paragraph(let text):+ let displayText = showCursor && isLast ? text + StreamingCursor.glyph : text+ markdownText(displayText)+ .font(EnsuTypography.message)+ .foregroundStyle(EnsuColor.textPrimary)+ .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))+ case .blockquote(let text):+ let displayText = showCursor && isLast ? text + StreamingCursor.glyph : text+ BlockQuoteView(text: displayText)+ case .code(let code):+ CodeBlockView(code: code)+ case .math(let text):+ MathBlockView(text: text)+ case .list(let items):+ let resolvedItems: [String]+ if showCursor && isLast {+ resolvedItems = items.enumerated().map { offset, item in+ offset == items.count - 1 ? item + StreamingCursor.glyph : item+ }+ } else {+ resolvedItems = items+ }++ VStack(alignment: .leading, spacing: 6) {+ ForEach(resolvedItems, id: \.self) { item in+ HStack(alignment: .top, spacing: EnsuSpacing.sm) {+ Text("β’")+ .font(EnsuTypography.message)+ .foregroundStyle(EnsuColor.textPrimary)+ markdownText(item)+ .font(EnsuTypography.message)+ .foregroundStyle(EnsuColor.textPrimary)+ }+ }+ }+ case .divider:+ Divider()+ .background(EnsuColor.border)+ }+ }++ if showTrailingCursor {+ Text(StreamingCursor.glyph)+ .font(EnsuTypography.message)+ .foregroundStyle(EnsuColor.textPrimary)+ }+ }+ .textSelection(.enabled)+ }++ private func headingFont(for level: Int) -> Font {+ switch level {+ case 1:+ return EnsuFont.message(size: 22, weight: .semibold)+ case 2:+ return EnsuFont.message(size: 20, weight: .semibold)+ default:+ return EnsuFont.message(size: 18, weight: .semibold)+ }+ }+}++func markdownText(_ text: String) -> SwiftUI.Text {+ if let attributed = try? AttributedString(markdown: text) {+ return SwiftUI.Text(attributed)+ }+ return SwiftUI.Text(text)+}++struct MarkdownBlock: Identifiable, Equatable {+ enum Kind: Equatable {+ case heading(level: Int, text: String)+ case paragraph(text: String)+ case blockquote(text: String)+ case code(text: String)+ case math(text: String)+ case list(items: [String])+ case divider+ }++ let id: Int+ let kind: Kind+}++enum MarkdownParser {+ static func parse(_ text: String) -> [MarkdownBlock] {+ var blocks: [MarkdownBlock] = []+ var nextId = 0++ func append(_ kind: MarkdownBlock.Kind) {+ blocks.append(MarkdownBlock(id: nextId, kind: kind))+ nextId += 1+ }++ let segments = text.components(separatedBy: "```")++ for (index, segment) in segments.enumerated() {+ if index % 2 == 1 {+ let code = segment.trimmingCharacters(in: .whitespacesAndNewlines)+ if !code.isEmpty {+ append(.code(text: code))+ }+ continue+ }++ for piece in splitByMathBlocks(segment) {+ switch piece {+ case .math(let latex):+ let trimmed = latex.trimmingCharacters(in: .whitespacesAndNewlines)+ if !trimmed.isEmpty {+ append(.math(text: trimmed))+ }+ case .markdown(let markdown):+ parseMarkdownBlocks(markdown).forEach { append($0) }+ }+ }+ }++ return blocks+ }++ private enum Segment {+ case markdown(String)+ case math(String)+ }++ private static func splitByMathBlocks(_ text: String) -> [Segment] {+ let lines = text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)+ var segments: [Segment] = []+ var markdownLines: [String] = []+ var mathLines: [String] = []+ var mathEndDelimiter: String? = nil++ func flushMarkdown() {+ if !markdownLines.isEmpty {+ segments.append(.markdown(markdownLines.joined(separator: "\n")))+ markdownLines.removeAll()+ }+ }++ func flushMath() {+ if !mathLines.isEmpty {+ segments.append(.math(mathLines.joined(separator: "\n")))+ }+ mathLines.removeAll()+ mathEndDelimiter = nil+ }++ func startMath(endDelimiter: String, initialContent: String? = nil) {+ flushMarkdown()+ mathEndDelimiter = endDelimiter+ mathLines.removeAll()+ if let initial = initialContent?.trimmingCharacters(in: .whitespacesAndNewlines), !initial.isEmpty {+ mathLines.append(initial)+ }+ }++ func isBracketMathLine(_ trimmed: String) -> Bool {+ guard trimmed.hasPrefix("["), trimmed.hasSuffix("]"), trimmed.count > 2 else {+ return false+ }+ if trimmed.contains("](") || trimmed.contains("]:") {+ return false+ }+ return true+ }++ for line in lines {+ let trimmed = line.trimmingCharacters(in: .whitespaces)++ if let endDelimiter = mathEndDelimiter {+ if trimmed == endDelimiter {+ flushMath()+ continue+ }+ if endDelimiter != "]" && trimmed.hasSuffix(endDelimiter) {+ let content = String(trimmed.dropLast(endDelimiter.count)).trimmingCharacters(in: .whitespaces)+ if !content.isEmpty {+ mathLines.append(content)+ }+ flushMath()+ continue+ }+ mathLines.append(line)+ continue+ }++ if trimmed == "\\[" || trimmed == "$$" || trimmed == "[" {+ let endDelimiter = trimmed == "\\[" ? "\\]" : (trimmed == "$$" ? "$$" : "]")+ startMath(endDelimiter: endDelimiter)+ continue+ }++ if trimmed.hasPrefix("\\[") {+ let content = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespaces)+ if content.hasSuffix("\\]") {+ let inner = String(content.dropLast(2)).trimmingCharacters(in: .whitespaces)+ flushMarkdown()+ segments.append(.math(inner))+ } else {+ startMath(endDelimiter: "\\]", initialContent: content)+ }+ continue+ }++ if trimmed.hasPrefix("$$") {+ let content = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespaces)+ if content.hasSuffix("$$") {+ let inner = String(content.dropLast(2)).trimmingCharacters(in: .whitespaces)+ flushMarkdown()+ segments.append(.math(inner))+ } else {+ startMath(endDelimiter: "$$", initialContent: content)+ }+ continue+ }++ if isBracketMathLine(trimmed) {+ let inner = String(trimmed.dropFirst().dropLast()).trimmingCharacters(in: .whitespaces)+ flushMarkdown()+ segments.append(.math(inner))+ continue+ }++ markdownLines.append(line)+ }++ if mathEndDelimiter != nil {+ flushMath()+ } else {+ flushMarkdown()+ }++ return segments+ }++ private static func parseMarkdownBlocks(_ markdown: String) -> [MarkdownBlock.Kind] {+ guard !markdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }+ let document = Document(parsing: markdown)+ var parsedBlocks: [MarkdownBlock.Kind] = []+ for child in document.children {+ parsedBlocks.append(contentsOf: blocks(for: child))+ }+ return parsedBlocks+ }++ private static func blocks(for markup: Markup) -> [MarkdownBlock.Kind] {+ switch markup {+ case let heading as Heading:+ let text = renderInlineChildren(heading)+ guard !text.isEmpty else { return [] }+ let level = max(1, min(heading.level, 3))+ return [.heading(level: level, text: text)]+ case let paragraph as Paragraph:+ let text = renderInlineChildren(paragraph)+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }+ return [.paragraph(text: text)]+ case let blockQuote as BlockQuote:+ let text = renderBlockQuote(blockQuote)+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }+ return [.blockquote(text: text)]+ case let codeBlock as CodeBlock:+ let code = codeBlock.code.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !code.isEmpty else { return [] }+ return [.code(text: code)]+ case _ as ThematicBreak:+ return [.divider]+ case let orderedList as OrderedList:+ let items = orderedList.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ return items.isEmpty ? [] : [.list(items: items)]+ case let unorderedList as UnorderedList:+ let items = unorderedList.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ return items.isEmpty ? [] : [.list(items: items)]+ default:+ var nestedBlocks: [MarkdownBlock.Kind] = []+ for child in markup.children {+ nestedBlocks.append(contentsOf: blocks(for: child))+ }+ return nestedBlocks+ }+ }++ private static func renderBlockQuote(_ quote: BlockQuote) -> String {+ var parts: [String] = []+ for child in quote.children {+ if let paragraph = child as? Paragraph {+ let text = renderInlineChildren(paragraph)+ if !text.isEmpty {+ parts.append(text)+ }+ continue+ }+ if let heading = child as? Heading {+ let text = renderInlineChildren(heading)+ if !text.isEmpty {+ parts.append(text)+ }+ continue+ }+ if let list = child as? OrderedList {+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ if !items.isEmpty {+ parts.append(items.joined(separator: "\n"))+ }+ continue+ }+ if let list = child as? UnorderedList {+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ if !items.isEmpty {+ parts.append(items.joined(separator: "\n"))+ }+ continue+ }+ }+ return parts.joined(separator: "\n")+ }++ private static func renderListItem(_ item: ListItem) -> String {+ var parts: [String] = []+ for child in item.children {+ if let paragraph = child as? Paragraph {+ let text = renderInlineChildren(paragraph)+ if !text.isEmpty {+ parts.append(text)+ }+ continue+ }+ if let list = child as? OrderedList {+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ if !items.isEmpty {+ parts.append(items.joined(separator: "\n"))+ }+ continue+ }+ if let list = child as? UnorderedList {+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ if !items.isEmpty {+ parts.append(items.joined(separator: "\n"))+ }+ continue+ }+ }+ return parts.joined(separator: "\n")+ }++ private static func renderInlineChildren(_ markup: Markup) -> String {+ markup.children.map(renderInline(from:)).joined()+ }++ private static func renderInline(from markup: Markup) -> String {+ switch markup {+ case let text as Markdown.Text:+ return text.string+ case _ as SoftBreak:+ return " "+ case _ as LineBreak:+ return "\n"+ case let emphasis as Emphasis:+ return "*" + renderInlineChildren(emphasis) + "*"+ case let strong as Strong:+ return "**" + renderInlineChildren(strong) + "**"+ case let inlineCode as InlineCode:+ return "`\(inlineCode.code)`"+ case let strikethrough as Strikethrough:+ return "~~" + renderInlineChildren(strikethrough) + "~~"+ case let link as Markdown.Link:+ let label = renderInlineChildren(link)+ let destination = link.destination ?? ""+ return destination.isEmpty ? label : "[\(label)](\(destination))"+ default:+ if !markup.children.contains(where: { _ in true }) {+ return ""+ }+ return renderInlineChildren(markup)+ }+ }+}++struct CodeBlockView: View {+ let code: String++ var body: some View {+ ZStack(alignment: .bottomTrailing) {+ ScrollView(.horizontal, showsIndicators: false) {+ Text(code)+ .font(EnsuTypography.code)+ .foregroundStyle(EnsuColor.textPrimary)+ .lineSpacing(EnsuLineHeight.spacing(fontSize: 13, lineHeight: 1.45))+ .padding(EnsuSpacing.cardPadding)+ .textSelection(.enabled)+ }++ Button {+ hapticTap()+ copyToPasteboard(code)+ } label: {+ Image("Copy01Icon")+ .resizable()+ .scaledToFit()+ .frame(width: 14, height: 14)+ .padding(6)+ .background(EnsuColor.fillFaint.opacity(0.8))+ .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))+ }+ .buttonStyle(.plain)+ .padding(8)+ }+ .background(EnsuColor.fillFaint)+ .overlay(+ RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock)+ .stroke(EnsuColor.border, lineWidth: 1)+ )+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock, style: .continuous))+ }+}++struct MathBlockView: View {+ let text: String++ var body: some View {+ LaTeXView(latex: text)+ .frame(minHeight: 48)+ .background(EnsuColor.fillFaint)+ .overlay(+ RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock)+ .stroke(EnsuColor.border, lineWidth: 1)+ )+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock, style: .continuous))+ }+}++struct BlockQuoteView: View {+ let text: String++ var body: some View {+ markdownText(text)+ .font(EnsuTypography.message)+ .foregroundStyle(EnsuColor.textPrimary)+ .padding(EnsuSpacing.cardPadding)+ .background(EnsuColor.fillFaint)+ .overlay(+ Rectangle()+ .fill(EnsuColor.border)+ .frame(width: 3),+ alignment: .leading+ )+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))+ }+}++struct ScrollChange: Equatable {+ var messagesCount: Int = 0+ var sessionId: UUID?+ var streamingLength: Int = 0+ var keyboardHeight: CGFloat = 0+ var inputBarHeight: CGFloat = 0+ var isGenerating: Bool = false+ var isAtBottom: Bool = true+}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swiftindex 7c982b7cc4..adc3d9f753 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift@@ -1,14 +1,5 @@#if canImport(EnteCore)import SwiftUI-import Markdown-#if os(macOS)-import QuickLookUI-#else-import QuickLook-#endif-#if os(iOS)-import UIKit-#endifstruct MessageListView: View {let messages: [ChatMessage]@@ -319,983 +310,6 @@ struct MessageListView: View {}}-private struct BottomOffsetKey: PreferenceKey {- static var defaultValue: CGFloat = 0-- static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {- value = nextValue()- }-}--private struct ContentHeightKey: PreferenceKey {- static var defaultValue: CGFloat = 0-- static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {- value = nextValue()- }-}--private struct AttachmentPreviewItem: Identifiable {- let url: URL- var id: String { url.path }-}--#if os(iOS)-private struct QuickLookPreview: UIViewControllerRepresentable {- let url: URL-- func makeUIViewController(context: Context) -> QLPreviewController {- let controller = QLPreviewController()- controller.dataSource = context.coordinator- return controller- }-- func updateUIViewController(_ uiViewController: QLPreviewController, context: Context) {- context.coordinator.url = url- uiViewController.reloadData()- }-- func makeCoordinator() -> Coordinator {- Coordinator(url: url)- }-- final class Coordinator: NSObject, QLPreviewControllerDataSource {- var url: URL-- init(url: URL) {- self.url = url- }-- func numberOfPreviewItems(in controller: QLPreviewController) -> Int {- 1- }-- func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {- url as NSURL- }- }-}-#elseif os(macOS)-private struct QuickLookPreview: NSViewRepresentable {- let url: URL-- func makeNSView(context: Context) -> QLPreviewView {- let view = QLPreviewView(frame: .zero, style: .normal)!- view.autostarts = true- view.previewItem = url as NSURL- return view- }-- func updateNSView(_ nsView: QLPreviewView, context: Context) {- nsView.previewItem = url as NSURL- }-}-#endif--private struct UserMessageBubbleView: View {- let message: ChatMessage- let onEdit: () -> Void- let onCopy: () -> Void- let onBranchChange: (Int) -> Void- let onOpenAttachment: (ChatAttachment) -> Void-- @Environment(\.colorScheme) private var colorScheme-- var body: some View {- let bubbleShape = RoundedRectangle(cornerRadius: 18, style: .continuous)- let bubbleFill = colorScheme == .dark ? EnsuColor.fillFaint : EnsuColor.border.opacity(0.2)-- HStack(alignment: .bottom) {- Spacer(minLength: EnsuSpacing.messageBubbleInset)-- VStack(alignment: .trailing, spacing: EnsuSpacing.sm) {- if !message.attachments.isEmpty {- FlowLayout(spacing: EnsuSpacing.sm) {- ForEach(message.attachments) { attachment in- AttachmentChip(- name: attachment.name,- size: attachment.formattedSize,- icon: attachment.iconName,- isUploading: attachment.isUploading- )- .onTapGesture {- hapticTap()- onOpenAttachment(attachment)- }- }- }- .frame(maxWidth: .infinity, alignment: .trailing)- }-- VStack(alignment: .trailing, spacing: EnsuSpacing.sm) {- Text(message.text)- .font(EnsuTypography.message)- .foregroundStyle(EnsuColor.userMessageText)- .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))- .multilineTextAlignment(.trailing)- .textSelection(.enabled)- }- .padding(EnsuSpacing.md)- .background(bubbleFill)- .clipShape(bubbleShape)- #if os(iOS)- .contextMenu {- Button("Edit") {- hapticTap()- onEdit()- }- Button("Copy") {- hapticTap()- onCopy()- }- }- #endif-- HStack(spacing: EnsuSpacing.sm) {- Spacer()- if message.branchCount > 1 {- BranchSwitcherView(- currentIndex: message.branchIndex,- totalCount: message.branchCount,- onPrevious: { onBranchChange(-1) },- onNext: { onBranchChange(1) }- )- }- TimestampView(date: message.timestamp)- }- }- }- }-}--private struct AssistantMessageBubbleView: View {- let message: ChatMessage- let onCopy: () -> Void- let onRetry: () -> Void- let onBranchChange: (Int) -> Void- let onOpenAttachment: (ChatAttachment) -> Void-- var body: some View {- HStack(alignment: .bottom) {- VStack(alignment: .leading, spacing: EnsuSpacing.sm) {- VStack(alignment: .leading, spacing: EnsuSpacing.sm) {- AssistantMessageRenderer(text: message.text, isStreaming: false, storageId: message.id.uuidString)-- if message.isInterrupted {- Text("Interrupted")- .font(EnsuTypography.small)- .italic()- .foregroundStyle(EnsuColor.textMuted)- }- }- .padding(.vertical, EnsuSpacing.md)- .padding(.horizontal, EnsuSpacing.sm)- #if os(iOS)- .contextMenu {- Button("Copy") {- hapticTap()- onCopy()- }- Button("Retry") {- hapticMedium()- onRetry()- }- }- #endif-- HStack(spacing: EnsuSpacing.sm) {- TimestampView(date: message.timestamp)- if message.branchCount > 1 {- BranchSwitcherView(- currentIndex: message.branchIndex,- totalCount: message.branchCount,- onPrevious: { onBranchChange(-1) },- onNext: { onBranchChange(1) }- )- }- }- .frame(maxWidth: .infinity, alignment: .leading)- .padding(.horizontal, EnsuSpacing.sm)- }- .frame(maxWidth: .infinity, alignment: .leading)- }- }-}--private struct StreamingBubbleView: View {- let text: String-- private static let cursorGlyph = "β"-- var body: some View {- HStack(alignment: .bottom) {- VStack(alignment: .leading, spacing: EnsuSpacing.sm) {- VStack(alignment: .leading, spacing: EnsuSpacing.sm) {- if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- LoadingDotsView()- } else {- TimelineView(.periodic(from: .now, by: 0.55)) { context in- let phase = Int(context.date.timeIntervalSinceReferenceDate * 2) % 2- let showCursor = phase == 0- let displayText = showCursor ? text + StreamingBubbleView.cursorGlyph : text- AssistantMessageRenderer(- text: displayText,- isStreaming: true,- storageId: UUID().uuidString- )- }- }- }- .padding(.vertical, EnsuSpacing.md)- .padding(.horizontal, EnsuSpacing.sm)- }- .frame(maxWidth: .infinity, alignment: .leading)- }- .foregroundStyle(EnsuColor.textPrimary)- }-}--private struct LoadingDotsView: View {- @State private var phrase: String = LoadingDotsView.randomPhrase()-- var body: some View {- TimelineView(.periodic(from: .now, by: 0.5)) { context in- let phase = Int(context.date.timeIntervalSinceReferenceDate * 2) % 3- Text(phrase + dots(for: phase))- .font(EnsuTypography.message)- .foregroundStyle(EnsuColor.textMuted)- }- }-- private static let loadingPhraseVerbs = [- "Generating",- "Thinking through",- "Assembling",- "Drafting",- "Composing",- "Crunching",- "Exploring",- "Piecing together",- "Reviewing",- "Organizing",- "Synthesizing",- "Sketching",- "Refining",- "Shaping"- ]-- private static let loadingPhraseTargets = [- "your reply",- "an answer",- "ideas",- "context",- "details",- "the response",- "the next steps",- "a solution",- "the summary",- "insights",- "the draft",- "the explanation"- ]-- private static func randomPhrase() -> String {- let verb = loadingPhraseVerbs.randomElement() ?? "Generating"- let target = loadingPhraseTargets.randomElement() ?? "your reply"- return "\(verb) \(target)"- }-- private func dots(for phase: Int) -> String {- switch phase {- case 0: return "."- case 1: return ".."- default: return "..."- }- }-}--private struct TimestampView: View {- let date: Date-- var body: some View {- Text(Self.formatter.string(from: date))- .font(EnsuTypography.mini)- .foregroundStyle(EnsuColor.textMuted)- .monospacedDigit()- }-- private static let formatter: DateFormatter = {- let formatter = DateFormatter()- formatter.dateFormat = "h:mm a"- return formatter- }()-}--private struct BranchSwitcherView: View {- let currentIndex: Int- let totalCount: Int- let onPrevious: () -> Void- let onNext: () -> Void-- var body: some View {- if totalCount > 1 {- HStack(spacing: EnsuSpacing.sm) {- TextActionButton(text: "<", action: onPrevious)- .disabled(currentIndex <= 1)- Text(String(format: "%2d/%d", currentIndex, totalCount))- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- .monospacedDigit()- TextActionButton(text: ">", action: onNext)- .disabled(currentIndex >= totalCount)- }- }- }-}--struct AssistantMessageRenderer: View {- let text: String- let isStreaming: Bool- let storageId: String-- var body: some View {- let parsed = ParsedMessage(text: text)-- VStack(alignment: .leading, spacing: EnsuSpacing.lg) {- if let think = parsed.thinkContent {- ThinkSectionView(content: think, isStreaming: isStreaming, storageId: storageId)- }-- ForEach(parsed.todoBlocks) { block in- TodoListCardView(title: block.title, status: block.status, items: block.items)- }-- if !parsed.markdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {- MarkdownView(markdown: parsed.markdown)- }- }- }-}--private struct ParsedMessage {- struct TodoBlock: Identifiable {- let id = UUID()- let title: String- let status: String?- let items: [String]- }-- let thinkContent: String?- let todoBlocks: [TodoBlock]- let markdown: String-- init(text: String) {- var remaining = text- var think: String?- var todos: [TodoBlock] = []-- if let thinkRange = ParsedMessage.extractTag(named: "think", from: remaining) {- think = thinkRange.content.trimmingCharacters(in: .whitespacesAndNewlines)- remaining = thinkRange.cleaned- }-- let todoMatches = ParsedMessage.extractTags(named: "todo_list", from: remaining)- remaining = todoMatches.cleaned-- for content in todoMatches.contents {- if let data = content.data(using: .utf8),- let payload = try? JSONDecoder().decode(TodoPayload.self, from: data) {- todos.append(TodoBlock(title: payload.title, status: payload.status, items: payload.items))- }- }-- self.thinkContent = think- self.todoBlocks = todos- self.markdown = remaining- }-- private static func extractTag(named name: String, from text: String) -> (content: String, cleaned: String)? {- let pattern = "<\(name)>([\\s\\S]*?)</\(name)>"- guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return nil }- guard let match = regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) else { return nil }- guard let range = Range(match.range(at: 1), in: text) else { return nil }- let content = String(text[range])- let cleaned = regex.stringByReplacingMatches(in: text, range: NSRange(text.startIndex..., in: text), withTemplate: "")- return (content, cleaned)- }-- private static func extractTags(named name: String, from text: String) -> (contents: [String], cleaned: String) {- let pattern = "<\(name)>([\\s\\S]*?)</\(name)>"- guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {- return ([], text)- }-- let matches = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))- let contents: [String] = matches.compactMap { match in- guard let range = Range(match.range(at: 1), in: text) else { return nil }- return String(text[range])- }- let cleaned = regex.stringByReplacingMatches(in: text, range: NSRange(text.startIndex..., in: text), withTemplate: "")- return (contents, cleaned)- }-- private struct TodoPayload: Decodable {- let title: String- let status: String?- let items: [String]- }-}--private struct ThinkSectionView: View {- let content: String- let isStreaming: Bool- let storageId: String-- @SceneStorage private var isExpanded: Bool-- init(content: String, isStreaming: Bool, storageId: String) {- self.content = content- self.isStreaming = isStreaming- self.storageId = storageId- _isExpanded = SceneStorage(wrappedValue: false, "thinkExpanded_\(storageId)")- }-- var body: some View {- VStack(alignment: .leading, spacing: EnsuSpacing.sm) {- Button {- withAnimation(.easeInOut(duration: 0.16)) {- isExpanded.toggle()- }- } label: {- HStack {- Text("THINK")- .font(EnsuTypography.mini)- .tracking(0.5)- .foregroundStyle(EnsuColor.textMuted)- Spacer()- Image(systemName: "chevron.down")- .rotationEffect(.degrees(isExpanded ? 180 : 0))- .foregroundStyle(EnsuColor.textMuted)- }- }- .buttonStyle(.plain)-- if isExpanded {- Text(content)- .font(EnsuFont.code(size: 12.5, weight: .regular))- .foregroundStyle(EnsuColor.textPrimary)- .lineSpacing(EnsuLineHeight.spacing(fontSize: 12.5, lineHeight: 1.45))- .textSelection(.enabled)- } else if isStreaming {- Text("β¦" + content)- .font(EnsuFont.code(size: 12.5, weight: .regular))- .foregroundStyle(EnsuColor.textMuted)- .lineLimit(4)- }- }- .padding(EnsuSpacing.cardPadding)- .background(EnsuColor.fillFaint)- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))- .onChange(of: isStreaming) { newValue in- if !newValue {- isExpanded = false- }- }- }-}--private struct TodoListCardView: View {- let title: String- let status: String?- let items: [String]-- var body: some View {- VStack(alignment: .leading, spacing: EnsuSpacing.sm) {- HStack {- Text(title)- .font(EnsuFont.message(size: 14, weight: .semibold))- .foregroundStyle(EnsuColor.textPrimary)- Spacer()- Text("\(items.count)")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- }-- if let status {- Text(status)- .font(EnsuFont.message(size: 12.5, weight: .regular))- .foregroundStyle(EnsuColor.textMuted)- }-- VStack(alignment: .leading, spacing: 6) {- ForEach(items, id: \.self) { item in- HStack(alignment: .top, spacing: EnsuSpacing.sm) {- Circle()- .fill(EnsuColor.accent)- .frame(width: 6, height: 6)- .padding(.top, 6)- Text(item)- .font(EnsuFont.message(size: 14, weight: .regular))- .foregroundStyle(EnsuColor.textPrimary)- .lineSpacing(EnsuLineHeight.spacing(fontSize: 14, lineHeight: 1.5))- }- }- }- }- .padding(EnsuSpacing.cardPadding)- .background(EnsuColor.fillFaint)- .overlay(- RoundedRectangle(cornerRadius: EnsuCornerRadius.card)- .stroke(EnsuColor.border, lineWidth: 1)- )- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))- }-}--private struct MarkdownView: View {- let markdown: String-- var body: some View {- VStack(alignment: .leading, spacing: EnsuSpacing.md) {- ForEach(MarkdownParser.parse(markdown)) { block in- switch block {- case .heading(let level, let text):- markdownText(text)- .font(headingFont(for: level))- .foregroundStyle(EnsuColor.textPrimary)- case .paragraph(let text):- markdownText(text)- .font(EnsuTypography.message)- .foregroundStyle(EnsuColor.textPrimary)- .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))- case .blockquote(let text):- BlockQuoteView(text: text)- case .code(let code):- CodeBlockView(code: code)- case .math(let text):- MathBlockView(text: text)- case .list(let items):- VStack(alignment: .leading, spacing: 6) {- ForEach(items, id: \.self) { item in- HStack(alignment: .top, spacing: EnsuSpacing.sm) {- Text("β’")- .font(EnsuTypography.message)- .foregroundStyle(EnsuColor.textPrimary)- markdownText(item)- .font(EnsuTypography.message)- .foregroundStyle(EnsuColor.textPrimary)- }- }- }- case .divider:- Divider()- .background(EnsuColor.border)- }- }- }- .textSelection(.enabled)- }-- private func headingFont(for level: Int) -> Font {- switch level {- case 1:- return EnsuFont.message(size: 22, weight: .semibold)- case 2:- return EnsuFont.message(size: 20, weight: .semibold)- default:- return EnsuFont.message(size: 18, weight: .semibold)- }- }-}--private func markdownText(_ text: String) -> SwiftUI.Text {- if let attributed = try? AttributedString(markdown: text) {- return SwiftUI.Text(attributed)- }- return SwiftUI.Text(text)-}--private enum MarkdownBlock: Identifiable {- case heading(level: Int, text: String)- case paragraph(text: String)- case blockquote(text: String)- case code(text: String)- case math(text: String)- case list(items: [String])- case divider-- var id: UUID { UUID() }-}--private enum MarkdownParser {- static func parse(_ text: String) -> [MarkdownBlock] {- var blocks: [MarkdownBlock] = []- let segments = text.components(separatedBy: "```")-- for (index, segment) in segments.enumerated() {- if index % 2 == 1 {- let code = segment.trimmingCharacters(in: .whitespacesAndNewlines)- if !code.isEmpty {- blocks.append(.code(text: code))- }- continue- }-- for piece in splitByMathBlocks(segment) {- switch piece {- case .math(let latex):- let trimmed = latex.trimmingCharacters(in: .whitespacesAndNewlines)- if !trimmed.isEmpty {- blocks.append(.math(text: trimmed))- }- case .markdown(let markdown):- blocks.append(contentsOf: parseMarkdownBlocks(markdown))- }- }- }-- return blocks- }-- private enum Segment {- case markdown(String)- case math(String)- }-- private static func splitByMathBlocks(_ text: String) -> [Segment] {- let lines = text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)- var segments: [Segment] = []- var markdownLines: [String] = []- var mathLines: [String] = []- var mathEndDelimiter: String? = nil-- func flushMarkdown() {- if !markdownLines.isEmpty {- segments.append(.markdown(markdownLines.joined(separator: "\n")))- markdownLines.removeAll()- }- }-- func flushMath() {- if !mathLines.isEmpty {- segments.append(.math(mathLines.joined(separator: "\n")))- }- mathLines.removeAll()- mathEndDelimiter = nil- }-- func startMath(endDelimiter: String, initialContent: String? = nil) {- flushMarkdown()- mathEndDelimiter = endDelimiter- mathLines.removeAll()- if let initial = initialContent?.trimmingCharacters(in: .whitespacesAndNewlines), !initial.isEmpty {- mathLines.append(initial)- }- }-- func isBracketMathLine(_ trimmed: String) -> Bool {- guard trimmed.hasPrefix("["), trimmed.hasSuffix("]"), trimmed.count > 2 else {- return false- }- if trimmed.contains("](") || trimmed.contains("]:") {- return false- }- return true- }-- for line in lines {- let trimmed = line.trimmingCharacters(in: .whitespaces)-- if let endDelimiter = mathEndDelimiter {- if trimmed == endDelimiter {- flushMath()- continue- }- if endDelimiter != "]" && trimmed.hasSuffix(endDelimiter) {- let content = String(trimmed.dropLast(endDelimiter.count)).trimmingCharacters(in: .whitespaces)- if !content.isEmpty {- mathLines.append(content)- }- flushMath()- continue- }- mathLines.append(line)- continue- }-- if trimmed == "\\[" || trimmed == "$$" || trimmed == "[" {- let endDelimiter = trimmed == "\\[" ? "\\]" : (trimmed == "$$" ? "$$" : "]")- startMath(endDelimiter: endDelimiter)- continue- }-- if trimmed.hasPrefix("\\[") {- let content = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespaces)- if content.hasSuffix("\\]") {- let inner = String(content.dropLast(2)).trimmingCharacters(in: .whitespaces)- flushMarkdown()- segments.append(.math(inner))- } else {- startMath(endDelimiter: "\\]", initialContent: content)- }- continue- }-- if trimmed.hasPrefix("$$") {- let content = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespaces)- if content.hasSuffix("$$") {- let inner = String(content.dropLast(2)).trimmingCharacters(in: .whitespaces)- flushMarkdown()- segments.append(.math(inner))- } else {- startMath(endDelimiter: "$$", initialContent: content)- }- continue- }-- if isBracketMathLine(trimmed) {- let inner = String(trimmed.dropFirst().dropLast()).trimmingCharacters(in: .whitespaces)- flushMarkdown()- segments.append(.math(inner))- continue- }-- markdownLines.append(line)- }-- if mathEndDelimiter != nil {- flushMath()- } else {- flushMarkdown()- }-- return segments- }-- private static func parseMarkdownBlocks(_ markdown: String) -> [MarkdownBlock] {- guard !markdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }- let document = Document(parsing: markdown)- var parsedBlocks: [MarkdownBlock] = []- for child in document.children {- parsedBlocks.append(contentsOf: blocks(for: child))- }- return parsedBlocks- }-- private static func blocks(for markup: Markup) -> [MarkdownBlock] {- switch markup {- case let heading as Heading:- let text = renderInlineChildren(heading)- guard !text.isEmpty else { return [] }- let level = max(1, min(heading.level, 3))- return [.heading(level: level, text: text)]- case let paragraph as Paragraph:- let text = renderInlineChildren(paragraph)- guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }- return [.paragraph(text: text)]- case let blockQuote as BlockQuote:- let text = renderBlockQuote(blockQuote)- guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return [] }- return [.blockquote(text: text)]- case let codeBlock as CodeBlock:- let code = codeBlock.code.trimmingCharacters(in: .whitespacesAndNewlines)- guard !code.isEmpty else { return [] }- return [.code(text: code)]- case _ as ThematicBreak:- return [.divider]- case let orderedList as OrderedList:- let items = orderedList.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }- return items.isEmpty ? [] : [.list(items: items)]- case let unorderedList as UnorderedList:- let items = unorderedList.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }- return items.isEmpty ? [] : [.list(items: items)]- default:- var nestedBlocks: [MarkdownBlock] = []- for child in markup.children {- nestedBlocks.append(contentsOf: blocks(for: child))- }- return nestedBlocks- }- }-- private static func renderBlockQuote(_ quote: BlockQuote) -> String {- var parts: [String] = []- for child in quote.children {- if let paragraph = child as? Paragraph {- let text = renderInlineChildren(paragraph)- if !text.isEmpty {- parts.append(text)- }- continue- }- if let heading = child as? Heading {- let text = renderInlineChildren(heading)- if !text.isEmpty {- parts.append(text)- }- continue- }- if let list = child as? OrderedList {- let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }- if !items.isEmpty {- parts.append(items.joined(separator: "\n"))- }- continue- }- if let list = child as? UnorderedList {- let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }- if !items.isEmpty {- parts.append(items.joined(separator: "\n"))- }- continue- }- }- return parts.joined(separator: "\n")- }-- private static func renderListItem(_ item: ListItem) -> String {- var parts: [String] = []- for child in item.children {- if let paragraph = child as? Paragraph {- let text = renderInlineChildren(paragraph)- if !text.isEmpty {- parts.append(text)- }- continue- }- if let list = child as? OrderedList {- let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }- if !items.isEmpty {- parts.append(items.joined(separator: "\n"))- }- continue- }- if let list = child as? UnorderedList {- let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }- if !items.isEmpty {- parts.append(items.joined(separator: "\n"))- }- continue- }- }- return parts.joined(separator: "\n")- }-- private static func renderInlineChildren(_ markup: Markup) -> String {- markup.children.map(renderInline(from:)).joined()- }-- private static func renderInline(from markup: Markup) -> String {- switch markup {- case let text as Markdown.Text:- return text.string- case _ as SoftBreak:- return " "- case _ as LineBreak:- return "\n"- case let emphasis as Emphasis:- return "*" + renderInlineChildren(emphasis) + "*"- case let strong as Strong:- return "**" + renderInlineChildren(strong) + "**"- case let inlineCode as InlineCode:- return "`\(inlineCode.code)`"- case let strikethrough as Strikethrough:- return "~~" + renderInlineChildren(strikethrough) + "~~"- case let link as Markdown.Link:- let label = renderInlineChildren(link)- let destination = link.destination ?? ""- return destination.isEmpty ? label : "[\(label)](\(destination))"- default:- if !markup.children.contains(where: { _ in true }) {- return ""- }- return renderInlineChildren(markup)- }- }-}--private struct CodeBlockView: View {- let code: String-- var body: some View {- ZStack(alignment: .bottomTrailing) {- ScrollView(.horizontal, showsIndicators: false) {- Text(code)- .font(EnsuTypography.code)- .foregroundStyle(EnsuColor.textPrimary)- .lineSpacing(EnsuLineHeight.spacing(fontSize: 13, lineHeight: 1.45))- .padding(EnsuSpacing.cardPadding)- .textSelection(.enabled)- }-- Button {- hapticTap()- copyToPasteboard(code)- } label: {- Image("Copy01Icon")- .resizable()- .scaledToFit()- .frame(width: 14, height: 14)- .padding(6)- .background(EnsuColor.fillFaint.opacity(0.8))- .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))- }- .buttonStyle(.plain)- .padding(8)- }- .background(EnsuColor.fillFaint)- .overlay(- RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock)- .stroke(EnsuColor.border, lineWidth: 1)- )- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock, style: .continuous))- }-}--private struct MathBlockView: View {- let text: String-- var body: some View {- LaTeXView(latex: text)- .frame(minHeight: 48)- .background(EnsuColor.fillFaint)- .overlay(- RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock)- .stroke(EnsuColor.border, lineWidth: 1)- )- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock, style: .continuous))- }-}--private struct BlockQuoteView: View {- let text: String-- var body: some View {- markdownText(text)- .font(EnsuTypography.message)- .foregroundStyle(EnsuColor.textPrimary)- .padding(EnsuSpacing.cardPadding)- .background(EnsuColor.fillFaint)- .overlay(- Rectangle()- .fill(EnsuColor.border)- .frame(width: 3),- alignment: .leading- )- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))- }-}--private struct ScrollChange: Equatable {- var messagesCount: Int = 0- var sessionId: UUID?- var streamingLength: Int = 0- var keyboardHeight: CGFloat = 0- var inputBarHeight: CGFloat = 0- var isGenerating: Bool = false- var isAtBottom: Bool = true-}-#elseimport SwiftUIdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/Models/ChatModels.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/Models/ChatModels.swiftnew file mode 100644index 0000000000..d1630ae32a--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/Models/ChatModels.swift@@ -0,0 +1,140 @@+import Foundation++enum ChatMessageTagRegex {+ static let think = try? NSRegularExpression(pattern: "<think>([\\s\\S]*?)</think>", options: [])+ static let todoList = try? NSRegularExpression(pattern: "<todo_list>([\\s\\S]*?)</todo_list>", options: [])+}++struct ChatAttachment: Identifiable, Equatable {+ enum Kind {+ case image+ case document+ }++ let id: UUID+ let name: String+ let size: Int64+ let kind: Kind+ let url: URL?+ var isUploading: Bool++ init(id: UUID = UUID(), name: String, size: Int64, kind: Kind, url: URL? = nil, isUploading: Bool = false) {+ self.id = id+ self.name = name+ self.size = size+ self.kind = kind+ self.url = url+ self.isUploading = isUploading+ }++ var formattedSize: String {+ size.formattedFileSize+ }++ var iconName: String {+ switch kind {+ case .image:+ return "Attachment01Icon"+ case .document:+ return "Attachment01Icon"+ }+ }+}++struct AttachmentDownloadItem: Identifiable, Equatable {+ enum Status {+ case queued+ case downloading+ case completed+ case failed+ case canceled+ }++ let id: String+ let sessionId: UUID+ let name: String+ let size: Int64+ var status: Status+ var errorMessage: String? = nil++ var formattedSize: String {+ size.formattedFileSize+ }+}++struct ChatMessage: Identifiable, Equatable {+ enum Role: String {+ case user+ case assistant+ }++ let id: UUID+ var role: Role+ var text: String+ var timestamp: Date+ var attachments: [ChatAttachment]+ var isInterrupted: Bool+ var tokensPerSecond: Double?+ var branchIndex: Int+ var branchCount: Int++ init(+ id: UUID = UUID(),+ role: Role,+ text: String,+ timestamp: Date = Date(),+ attachments: [ChatAttachment] = [],+ isInterrupted: Bool = false,+ tokensPerSecond: Double? = nil,+ branchIndex: Int = 1,+ branchCount: Int = 1+ ) {+ self.id = id+ self.role = role+ self.text = text+ self.timestamp = timestamp+ self.attachments = attachments+ self.isInterrupted = isInterrupted+ self.tokensPerSecond = tokensPerSecond+ self.branchIndex = branchIndex+ self.branchCount = branchCount+ }+}++struct ChatSession: Identifiable, Equatable {+ let id: UUID+ var title: String+ var lastMessage: String+ var updatedAt: Date++ init(id: UUID = UUID(), title: String, lastMessage: String, updatedAt: Date = Date()) {+ self.id = id+ self.title = title+ self.lastMessage = lastMessage+ self.updatedAt = updatedAt+ }+}++struct DownloadToastState: Identifiable, Equatable {+ enum Phase {+ case downloading+ case loading+ case complete+ case errorDownload+ case errorLoad+ }++ let id = UUID()+ var phase: Phase+ var percent: Int+ var status: String+ var offerRetryDownload: Bool+}++struct OverflowAlertState: Identifiable, Equatable {+ let id = UUID()+ let inputTokens: Int+ let inputBudget: Int+ let contextLength: Int+ let maxOutput: Int+}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Components/AuthComponents.swift b/mobile/native/darwin/Apps/ensu/ensu/Components/AuthComponents.swiftindex df51827f5b..c63e9c49f6 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Components/AuthComponents.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Components/AuthComponents.swift@@ -1,5 +1,6 @@import SwiftUI+#if canImport(EnteCore)struct AuthHeader: View {let title: Stringvar subtitle: String? = nil@@ -35,6 +36,80 @@ struct AuthSubtitle: View {}}+struct AuthErrorText: View {+ let message: String++ var body: some View {+ Text(message)+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.error)+ .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+}++@MainActor+final class AuthActionState: ObservableObject {+ @Published var isLoading: Bool = false+ @Published var errorMessage: String?++ func setError(_ message: String?) {+ errorMessage = message+ }++ func run(+ onError: ((Error) -> String)? = nil,+ _ action: @escaping () async throws -> Void+ ) async {+ guard !isLoading else { return }+ errorMessage = nil+ isLoading = true+ defer { isLoading = false }++ do {+ try await action()+ } catch {+ errorMessage = onError?(error) ?? error.localizedDescription+ }+ }+}++struct StyledTextField: View {+ let hint: String+ @Binding var text: String+ var keyboardType: PlatformKeyboardType = .default+ var textContentType: PlatformTextContentType? = nil+ var autocapitalization: PlatformTextInputAutocapitalization = .never+ var isSecure: Bool = false+ var submitLabel: SubmitLabel = .done+ var onSubmit: (() -> Void)? = nil++ var body: some View {+ Group {+ if isSecure {+ SecureField(hint, text: $text)+ } else {+ TextField(hint, text: $text)+ }+ }+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textPrimary)+ .platformTextFieldStyle()+ .platformTextInputAutocapitalization(autocapitalization)+ .autocorrectionDisabled()+ .platformKeyboardType(keyboardType)+ .platformTextContentType(textContentType)+ .submitLabel(submitLabel)+ .onSubmit {+ onSubmit?()+ }+ .padding(.horizontal, EnsuSpacing.inputHorizontal)+ .padding(.vertical, EnsuSpacing.inputVertical)+ .background(EnsuColor.fillFaint)+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))+ }+}+struct LabeledTextField: View {let label: Stringlet hint: String@@ -52,28 +127,16 @@ struct LabeledTextField: View {.font(EnsuTypography.small).foregroundStyle(EnsuColor.textMuted)- Group {- if isSecure {- SecureField(hint, text: $text)- } else {- TextField(hint, text: $text)- }- }- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.textPrimary)- .platformTextFieldStyle()- .platformTextInputAutocapitalization(autocapitalization)- .autocorrectionDisabled()- .platformKeyboardType(keyboardType)- .platformTextContentType(textContentType)- .submitLabel(submitLabel)- .onSubmit {- onSubmit?()- }- .padding(.horizontal, EnsuSpacing.inputHorizontal)- .padding(.vertical, EnsuSpacing.inputVertical)- .background(EnsuColor.fillFaint)- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))+ StyledTextField(+ hint: hint,+ text: $text,+ keyboardType: keyboardType,+ textContentType: textContentType,+ autocapitalization: autocapitalization,+ isSecure: isSecure,+ submitLabel: submitLabel,+ onSubmit: onSubmit+ )}.padding(.horizontal, EnsuSpacing.pageHorizontal)}@@ -162,6 +225,143 @@ struct CodeTextField: View {}}+struct PasswordEntryView: View {+ let title: String+ let subtitle: String+ let buttonText: String+ @Binding var password: String+ @Binding var showPassword: Bool+ let isLoading: Bool+ let errorMessage: String?+ var submitLabel: SubmitLabel = .go+ let onSubmit: () async -> Void++ private var hasPassword: Bool { !password.isEmpty }++ var body: some View {+ AuthScreen {+ AuthHeader(title: title)+ AuthSubtitle(text: subtitle)++ VStack(spacing: EnsuSpacing.xxl) {+ PasswordTextField(+ label: "Password",+ hint: "Enter your password",+ text: $password,+ showPassword: $showPassword,+ submitLabel: submitLabel+ ) {+ Task { await onSubmit() }+ }++ if let errorMessage {+ AuthErrorText(message: errorMessage)+ }+ }+ .padding(.top, EnsuSpacing.xxl)+ } bottom: {+ PrimaryButton(+ text: buttonText,+ isLoading: isLoading,+ isEnabled: hasPassword && !isLoading+ ) {+ Task { await onSubmit() }+ }+ }+ }+}++struct VerificationCodeView<Accessory: View>: View {+ let title: String+ let subtitle: String?+ @Binding var code: String+ let buttonText: String+ let isLoading: Bool+ let errorMessage: String?+ var autoSubmitLength: Int = 6+ let onSubmit: () async -> Void+ @ViewBuilder let accessory: () -> Accessory++ private var hasValidCode: Bool {+ code.trimmingCharacters(in: .whitespacesAndNewlines).count == autoSubmitLength+ }++ init(+ title: String,+ subtitle: String? = nil,+ code: Binding<String>,+ buttonText: String = "Verify",+ isLoading: Bool,+ errorMessage: String?,+ autoSubmitLength: Int = 6,+ onSubmit: @escaping () async -> Void,+ @ViewBuilder accessory: @escaping () -> Accessory+ ) {+ self.title = title+ self.subtitle = subtitle+ self._code = code+ self.buttonText = buttonText+ self.isLoading = isLoading+ self.errorMessage = errorMessage+ self.autoSubmitLength = autoSubmitLength+ self.accessory = accessory+ self.onSubmit = onSubmit+ }++ var body: some View {+ AuthScreen {+ AuthHeader(title: title, subtitle: subtitle)++ VStack(spacing: EnsuSpacing.lg) {+ CodeTextField(code: $code, maxLength: autoSubmitLength) { value in+ if value.count == autoSubmitLength {+ Task { await onSubmit() }+ }+ }++ accessory()++ if let errorMessage {+ AuthErrorText(message: errorMessage)+ }+ }+ } bottom: {+ PrimaryButton(+ text: buttonText,+ isLoading: isLoading,+ isEnabled: hasValidCode && !isLoading+ ) {+ Task { await onSubmit() }+ }+ }+ }+}++extension VerificationCodeView where Accessory == EmptyView {+ init(+ title: String,+ subtitle: String? = nil,+ code: Binding<String>,+ buttonText: String = "Verify",+ isLoading: Bool,+ errorMessage: String?,+ autoSubmitLength: Int = 6,+ onSubmit: @escaping () async -> Void+ ) {+ self.init(+ title: title,+ subtitle: subtitle,+ code: code,+ buttonText: buttonText,+ isLoading: isLoading,+ errorMessage: errorMessage,+ autoSubmitLength: autoSubmitLength,+ onSubmit: onSubmit,+ accessory: { EmptyView() }+ )+ }+}+struct AuthScreen<Content: View, Bottom: View>: View {@ViewBuilder let content: () -> Content@ViewBuilder let bottom: () -> Bottom@@ -182,3 +382,4 @@ struct AuthScreen<Content: View, Bottom: View>: View {.background(EnsuColor.backgroundBase.ignoresSafeArea())}}+#endifdiff --git a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swiftindex 15e1cee26a..9313b7b9ab 100644--- a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift@@ -254,16 +254,11 @@ struct ModelSettingsView: View {.font(EnsuTypography.small).foregroundStyle(EnsuColor.textMuted)- TextField(hint, text: text)- .platformKeyboardType(keyboardType)- .platformTextInputAutocapitalization(.never)- .foregroundStyle(EnsuColor.textPrimary)- .platformTextFieldStyle()- .autocorrectionDisabled()- .padding(.horizontal, EnsuSpacing.inputHorizontal)- .padding(.vertical, EnsuSpacing.inputVertical)- .background(EnsuColor.fillFaint)- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))+ StyledTextField(+ hint: hint,+ text: text,+ keyboardType: keyboardType+ )if let error {Text(error)