💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[ensu] Add source onboarding and global source settings
setalp188dd808675f
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.ktindex 155feebc1b..e692e7d94d 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt@@ -7,7 +7,6 @@ import io.ente.ensu.chat.Attachmentimport io.ente.ensu.chat.AttachmentStoreActionsimport io.ente.ensu.chat.ChatMessageimport io.ente.ensu.chat.ChatRepository-import io.ente.ensu.chat.ChatSourceSelectionPreferencesimport io.ente.ensu.chat.ChatStoreActionsimport io.ente.ensu.device.AndroidDeviceCapabilityProviderimport io.ente.ensu.device.ChatDeviceCapability@@ -41,7 +40,8 @@ class AppStore(private val logRepository: FileLogRepository,clock: () -> Long = { System.currentTimeMillis() },) {- private val sourcePreferences = ChatSourceSelectionPreferences(context)+ private val sourcePreferences =+ context.applicationContext.getSharedPreferences("ensu_chat_sources", Context.MODE_PRIVATE)private val _state = MutableStateFlow(AppState())val state: StateFlow<AppState> = _state.asStateFlow()@@ -52,6 +52,7 @@ class AppStore(private val attachmentActions = AttachmentStoreActions(_state, messageStore)private val knowledgeStore =KnowledgeStore(+ context = context,state = _state,provider = knowledgeProvider,datasets = configDefaults.knowledgeDatasets,@@ -69,7 +70,6 @@ class AppStore(private val chatActions =ChatStoreActions(state = _state,- sourcePreferences = sourcePreferences,sessionPreferences = sessionPreferences,chatRepository = chatRepository,llmProvider = llmProvider,@@ -205,33 +205,25 @@ class AppStore(fun refreshModelDownloadInfo() = modelSettingsActions.refreshModelDownloadInfo()- fun downloadOrUpdateKnowledgePack(stableId: String) = knowledgeStore.downloadOrUpdate(stableId)-- fun cancelKnowledgePackDownload(stableId: String) = knowledgeStore.cancel(stableId)-fun retrySourceInventory() {- knowledgeStore.retryInventory()- notesStore.retryInventory()- chatActions.refreshSourceSelectionInventory()+ knowledgeStore.retry()+ notesStore.retryLoad()+ chatActions.refreshSourceInventory()}- fun sourceSelectionTarget(): String = chatActions.sourceSelectionTarget()+ fun downloadOrUpdateKnowledgePack(stableId: String) = knowledgeStore.downloadOrUpdate(stableId)- fun downloadKnowledgePackForChat(stableId: String, target: String) {- val wasInstalled = _state.value.knowledge.packs[stableId]?.activeIdentity != null- knowledgeStore.downloadOrUpdate(stableId) {- if (!wasInstalled) chatActions.selectAddedPack(target, stableId)- }- }+ fun setKnowledgePackEnabled(stableId: String, enabled: Boolean) =+ knowledgeStore.setEnabled(stableId, enabled)- fun addNotesFolderForChat(tree: android.net.Uri, target: String) =- notesStore.add(tree) { id -> chatActions.selectAddedFolder(target, id) }+ fun hasSeenSourceIntroduction() =+ sourcePreferences.getBoolean("sources_introduction_seen", false)- fun setKnowledgePackEnabled(stableId: String, enabled: Boolean) =- chatActions.setPackEnabled(stableId, enabled)+ fun completeSourceIntroduction() {+ sourcePreferences.edit().putBoolean("sources_introduction_seen", true).apply()+ }- fun setNotesFolderEnabled(id: String, enabled: Boolean) =- chatActions.setFolderEnabled(id, enabled)+ fun cancelKnowledgePackDownload(stableId: String) = knowledgeStore.cancel(stableId)fun cancelDownload() {chatActions.cancelGenerationForDownload()diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeNavigation.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeNavigation.ktindex 852c8773c9..a4c47757e0 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeNavigation.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeNavigation.kt@@ -15,7 +15,6 @@ import androidx.compose.material3.DrawerStateimport androidx.compose.material3.DrawerValueimport androidx.compose.material3.Scaffoldimport androidx.compose.runtime.Composable-import androidx.compose.runtime.getValueimport androidx.compose.ui.Modifierimport androidx.navigation.NavBackStackEntryimport androidx.navigation.NavHostController@@ -87,7 +86,8 @@ internal fun HomeNavigation(HomeRoute.Settings -> {SimpleTopBar(title = "Settings") { navController.popBackStack() }}- HomeRoute.Notes -> {+ HomeRoute.Notes,+ HomeRoute.NotesSetup -> {SimpleTopBar(title = "Your Notes") { navController.popBackStack() }}HomeRoute.Knowledge -> {@@ -112,9 +112,12 @@ internal fun HomeNavigation() {ChatView(onVoiceInputJob = store::trackVoiceInput,+ onOpenPacks = { navController.navigate(HomeRoute.Knowledge) },+ onOpenNotes = { navController.navigate(HomeRoute.NotesSetup) },+ hasSeenSourceIntroduction = store.hasSeenSourceIntroduction(),+ onCompleteSourceIntroduction = store::completeSourceIntroduction,+ onRetrySources = store::retrySourceInventory,chatState = appState.chat,- knowledgeState = appState.knowledge,- store = store,assetStore = store.assetStore,llmProvider = store.llmProvider,isDrawerOpen = drawerState.currentValue == DrawerValue.Open,@@ -161,14 +164,20 @@ internal fun HomeNavigation(onSignIn = onSignIn,)}- composable(- route = HomeRoute.Notes,- enterTransition = { forwardEnter() },- exitTransition = { forwardExit() },- popEnterTransition = { backEnter() },- popExitTransition = { backExit() },- ) {- NotesSettingsScreen(store.notesStore, store::setPickerPending)+ listOf(HomeRoute.Notes, HomeRoute.NotesSetup).forEach { route ->+ composable(+ route = route,+ enterTransition = { forwardEnter() },+ exitTransition = { forwardExit() },+ popEnterTransition = { backEnter() },+ popExitTransition = { backExit() },+ ) {+ NotesSettingsScreen(+ store.notesStore,+ store::setPickerPending,+ allowRemoval = route == HomeRoute.Notes,+ )+ }}composable(route = HomeRoute.Knowledge,@@ -182,6 +191,7 @@ internal fun HomeNavigation(packDownloadsAllowed = appState.chat.deviceCapability.isChatSupported(),onDownloadOrUpdate = store::downloadOrUpdateKnowledgePack,onCancel = store::cancelKnowledgePackDownload,+ onSetEnabled = store::setKnowledgePackEnabled,)}composable(@@ -251,6 +261,7 @@ internal object HomeRoute {const val SystemPromptSettings = "system-prompt-settings"const val Knowledge = "knowledge"const val Notes = "notes"+ const val NotesSetup = "notes-setup"}internal fun AnimatedContentTransitionScope<NavBackStackEntry>.forwardEnter() =diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.ktindex 86d44d43cf..9c403e57bb 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt@@ -17,7 +17,6 @@ import androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextFieldimport androidx.compose.foundation.text.KeyboardOptions@@ -28,6 +27,7 @@ import androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.Text+import androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValue@@ -39,7 +39,6 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.draw.rotateimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequester-import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.SolidColorimport androidx.compose.ui.hapticfeedback.HapticFeedbackTypeimport androidx.compose.ui.res.painterResource@@ -68,19 +67,22 @@ internal fun MessageInput(isProcessingAttachments: Boolean,isGenerating: Boolean,isDownloading: Boolean,+ sourcesReady: Boolean,+ sourcesError: String?,+ onRetrySources: () -> Unit,onMessageChange: (String) -> Unit,onSend: () -> Unit,onStop: () -> Unit,onAttachmentSelected: (AttachmentType) -> Unit,onRemoveAttachment: (Attachment) -> Unit,onCancelEdit: () -> Unit,- onOpenSources: () -> Unit,voiceInputState: VoiceInputState,onVoiceInput: () -> Unit,focusRequestId: Int,) {val haptic = rememberHaptics()- val placeholder = "Write a message..."+ val placeholder = "Ask Ensu"+ val composerIconSize = 18.dpval focusRequester = remember { FocusRequester() }var fieldValue by remember {@@ -122,6 +124,20 @@ internal fun MessageInput(modifier = modifier.background(EnsuColor.backgroundBase()),verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),) {+ if (!sourcesReady) {+ Row(+ modifier = Modifier.padding(horizontal = EnsuSpacing.sm.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ sourcesError ?: "Loading sources for this chat…",+ style = EnsuTypography.small,+ color = EnsuColor.textMuted(),+ modifier = Modifier.weight(1f),+ )+ if (sourcesError != null) TextButton(onClick = onRetrySources) { Text("Retry") }+ }+ }if (editingMessage != null) {EditBanner(message = editingMessage, onCancelEdit = onCancelEdit)}@@ -133,7 +149,7 @@ internal fun MessageInput(Modifier.fillMaxWidth().heightIn(max = maxAttachmentHeight).verticalScroll(rememberScrollState())- .padding(horizontal = EnsuSpacing.pageHorizontal.dp),+ .padding(horizontal = EnsuSpacing.sm.dp),horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),) {@@ -165,13 +181,13 @@ internal fun MessageInput(text = "This model doesn't support images. Remove the image attachments to send.",style = EnsuTypography.small,color = EnsuColor.stopButton,- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),+ modifier = Modifier.padding(horizontal = EnsuSpacing.sm.dp),)}if (isProcessingAttachments) {Row(- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),+ modifier = Modifier.padding(horizontal = EnsuSpacing.sm.dp),verticalAlignment = Alignment.CenterVertically,) {CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)@@ -182,7 +198,7 @@ internal fun MessageInput(voiceInputState.statusText()?.let { status ->Row(- modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),+ modifier = Modifier.padding(horizontal = EnsuSpacing.sm.dp),verticalAlignment = Alignment.CenterVertically,) {when (voiceInputState) {@@ -228,7 +244,7 @@ internal fun MessageInput(Box(modifier =Modifier.fillMaxWidth()- .padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ .padding(horizontal = EnsuSpacing.sm.dp).padding(bottom = bottomPadding).background(EnsuColor.fillFaint(),@@ -243,40 +259,27 @@ internal fun MessageInput(modifier = Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically,) {- if (editingMessage == null && supportsImageAttachments) {- val canAddImageAttachment =- !isGenerating && !isDownloading && !isImageAttachmentLimitReached- IconButton(- onClick = {- haptic.perform(HapticFeedbackType.TextHandleMove)- onAttachmentSelected(AttachmentType.Image)- },- enabled = canAddImageAttachment,- modifier = Modifier.size(36.dp),- ) {- Icon(- painter = painterResource(HugeIcons.Upload01Icon),- contentDescription = "Attach",- modifier = Modifier.size(18.dp),- )- }- }-IconButton(onClick = {haptic.perform(HapticFeedbackType.TextHandleMove)- onOpenSources()+ onAttachmentSelected(AttachmentType.Image)},- modifier = Modifier.size(36.dp),+ enabled =+ editingMessage == null &&+ supportsImageAttachments &&+ !isGenerating &&+ !isDownloading &&+ !isImageAttachmentLimitReached,+ modifier = Modifier.size(width = 32.dp, height = 36.dp),) {Icon(- painter = painterResource(HugeIcons.PackageIcon),- contentDescription = "Sources for this chat",- modifier = Modifier.size(18.dp),+ painterResource(HugeIcons.ImagePlusIcon),+ contentDescription = "Add photos",+ modifier = Modifier.size(composerIconSize),)}- Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))+ Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))BasicTextField(value = fieldValue,@@ -339,21 +342,22 @@ internal fun MessageInput(Icon(painter = painterResource(HugeIcons.StopIcon),contentDescription = "Stop dictation",- modifier = Modifier.size(18.dp),- tint = EnsuColor.stopButton,+ modifier = Modifier.size(composerIconSize),+ tint = EnsuColor.sendButton,)} else {Icon(painter = painterResource(HugeIcons.Mic02Icon),contentDescription = "Dictate",- modifier = Modifier.size(18.dp),+ modifier = Modifier.size(composerIconSize),)}}}val canSend =- (messageText.isNotBlank() || attachments.isNotEmpty()) &&+ sourcesReady &&+ (messageText.isNotBlank() || attachments.isNotEmpty()) &&!voiceInputState.blocksSend &&!hasUnsupportedImages@@ -377,31 +381,17 @@ internal fun MessageInput(}val tint =when {- isGenerating -> EnsuColor.stopButton- canSend -> EnsuColor.textPrimary()- else -> EnsuColor.textMuted()+ isGenerating -> EnsuColor.sendButton+ canSend && !isDownloading -> EnsuColor.sendButton+ else -> EnsuColor.sendButtonInactive}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,- )- }+ Icon(+ painter = painterResource(iconRes),+ contentDescription = if (isGenerating) "Stop generation" else "Send",+ modifier = Modifier.size(composerIconSize).rotate(rotation),+ tint = tint,+ )}}}@@ -414,7 +404,7 @@ private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {Row(modifier =Modifier.fillMaxWidth()- .padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ .padding(horizontal = EnsuSpacing.sm.dp).background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp)).height(IntrinsicSize.Min)) {diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatOverlays.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatOverlays.ktindex aa3f6ec563..5439b0aa05 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatOverlays.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatOverlays.kt@@ -9,7 +9,6 @@ import androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.size-import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.Icon@@ -20,7 +19,6 @@ import androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier-import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.hapticfeedback.HapticFeedbackTypeimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.unit.dp@@ -155,17 +153,12 @@ internal fun DownloadToastOverlay(},modifier = Modifier.size(28.dp),) {- Box(- modifier = Modifier.size(22.dp).background(Color.White, CircleShape),- contentAlignment = Alignment.Center,- ) {- Icon(- painter = painterResource(HugeIcons.StopIcon),- contentDescription = "Cancel download",- modifier = Modifier.size(12.dp),- tint = EnsuColor.stopButton,- )- }+ Icon(+ painter = painterResource(HugeIcons.StopIcon),+ contentDescription = "Cancel download",+ modifier = Modifier.size(18.dp),+ tint = EnsuColor.sendButton,+ )}}Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelection.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelection.ktindex 36780dd33b..53849df2b1 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelection.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelection.kt@@ -1,6 +1,5 @@package io.ente.ensu.chat-/** Explicit stable IDs keep later additions from changing an existing chat. */data class ChatSourceSelection(val selectedPackIds: Set<String> = emptySet(),val selectedFolderIds: Set<String> = emptySet(),@@ -8,10 +7,4 @@ data class ChatSourceSelection(fun isPackEnabled(id: String): Boolean = id in selectedPackIdsfun isFolderEnabled(id: String): Boolean = id in selectedFolderIds-- fun withPackEnabled(id: String, enabled: Boolean): ChatSourceSelection =- copy(selectedPackIds = if (enabled) selectedPackIds + id else selectedPackIds - id)-- fun withFolderEnabled(id: String, enabled: Boolean): ChatSourceSelection =- copy(selectedFolderIds = if (enabled) selectedFolderIds + id else selectedFolderIds - id)}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelectionPreferences.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelectionPreferences.ktdeleted file mode 100644index 9c025682cc..0000000000--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelectionPreferences.kt+++ /dev/null@@ -1,45 +0,0 @@-package io.ente.ensu.chat--import android.content.Context-import java.util.UUID--/** Read synchronously to avoid briefly using another chat's choices. */-internal class ChatSourceSelectionPreferences(context: Context) : ChatSourceSelectionStorage {- private val preferences =- context.applicationContext.getSharedPreferences("ensu_chat_sources", Context.MODE_PRIVATE)-- var draftKey: String = preferences.getString("draft_key", null) ?: newDraftKey()- private set-- override fun read(key: String): ChatSourceSelection? {- if (!preferences.contains("$key.packs")) return null- return ChatSourceSelection(- selectedPackIds = preferences.getStringSet("$key.packs", emptySet()).orEmpty().toSet(),- selectedFolderIds =- preferences.getStringSet("$key.folders", emptySet()).orEmpty().toSet(),- )- }-- override fun write(key: String, selection: ChatSourceSelection) {- preferences- .edit()- .putStringSet("$key.packs", selection.selectedPackIds)- .putStringSet("$key.folders", selection.selectedFolderIds)- .apply()- }-- override fun remove(key: String) {- preferences.edit().remove("$key.packs").remove("$key.folders").apply()- }-- fun resetDraft() {- remove(draftKey)- draftKey = newDraftKey()- }-- private fun newDraftKey(): String {- val key = "draft-${UUID.randomUUID()}"- preferences.edit().putString("draft_key", key).apply()- return key- }-}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelections.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelections.ktdeleted file mode 100644index b6d7b7ff80..0000000000--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelections.kt+++ /dev/null@@ -1,39 +0,0 @@-package io.ente.ensu.chat--internal interface ChatSourceSelectionStorage {- fun read(key: String): ChatSourceSelection?-- fun write(key: String, selection: ChatSourceSelection)-- fun remove(key: String)-}--/** Resolves work started in a draft to that draft's eventual chat, even after navigation. */-internal class ChatSourceSelections(private val storage: ChatSourceSelectionStorage) {- private val promotedDrafts = mutableMapOf<String, String>()-- fun initialize(- key: String,- inventoryReady: Boolean = true,- defaults: () -> ChatSourceSelection,- ): ChatSourceSelection =- storage.read(key) ?: defaults().also { if (inventoryReady) storage.write(key, it) }-- fun promote(draftKey: String, sessionId: String) {- storage.read(draftKey)?.let { storage.write(sessionId, it) }- promotedDrafts[draftKey] = sessionId- storage.remove(draftKey)- }-- fun selectAdded(- target: String,- transform: (ChatSourceSelection) -> ChatSourceSelection,- ): Pair<String, ChatSourceSelection>? {- val destination = promotedDrafts[target] ?: target- // Discarded drafts and deleted chats must not be recreated by asynchronous work.- val current = storage.read(destination) ?: return null- val updated = transform(current)- storage.write(destination, updated)- return destination to updated- }-}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourcesSheet.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourcesSheet.ktdeleted file mode 100644index 7407064519..0000000000--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourcesSheet.kt+++ /dev/null@@ -1,232 +0,0 @@-package io.ente.ensu.chat--import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.heightIn-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.material3.ExperimentalMaterial3Api-import androidx.compose.material3.LinearProgressIndicator-import androidx.compose.material3.ModalBottomSheet-import androidx.compose.material3.Switch-import androidx.compose.material3.Text-import androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsState-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.saveable.rememberSaveable-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.semantics.contentDescription-import androidx.compose.ui.semantics.semantics-import androidx.compose.ui.unit.dp-import io.ente.ensu.AppStore-import io.ente.ensu.bindings.KnowledgeDatasetConfig-import io.ente.ensu.components.CompactButton-import io.ente.ensu.components.KnowledgeCard-import io.ente.ensu.designsystem.EnsuColor-import io.ente.ensu.designsystem.EnsuSpacing-import io.ente.ensu.designsystem.EnsuTypography-import io.ente.ensu.device.isChatSupported-import io.ente.ensu.knowledge.KnowledgeState-import io.ente.ensu.notes.NotesStatus-import io.ente.ensu.settings.KnowledgePackCard-import io.ente.ensu.settings.PackAttributionDialog--@OptIn(ExperimentalMaterial3Api::class)-@Composable-internal fun ChatSourcesSheet(- visible: Boolean,- chatState: ChatState,- knowledgeState: KnowledgeState,- store: AppStore,- onDismiss: () -> Unit,-) {- val notesState by store.notesStore.state.collectAsState()- var attribution by remember { mutableStateOf<KnowledgeDatasetConfig?>(null) }- var pendingFolderTarget by rememberSaveable { mutableStateOf<String?>(null) }- // Keep the launcher registered after the sheet closes, until the system picker returns.- val folderPicker =- rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->- store.setPickerPending(false)- val target = pendingFolderTarget- pendingFolderTarget = null- if (uri != null && target != null) store.addNotesFolderForChat(uri, target)- }- if (!visible) return-- val controlsEnabled =- chatState.sourceSelectionReady &&- !chatState.isGenerating &&- chatState.preparationStatus == null &&- !chatState.isDownloading- val supported = chatState.deviceCapability.isChatSupported()-- ModalBottomSheet(- onDismissRequest = onDismiss,- containerColor = EnsuColor.backgroundBase(),- ) {- LazyColumn(- modifier = Modifier.fillMaxWidth().heightIn(max = 640.dp),- contentPadding =- PaddingValues(- horizontal = EnsuSpacing.pageHorizontal.dp,- vertical = EnsuSpacing.md.dp,- ),- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),- ) {- item {- Text("Sources", style = EnsuTypography.h3Bold, color = EnsuColor.textPrimary())- Text(- "Choose what Ensu can use in this chat. Turning a source off does not remove information already in the conversation.",- style = EnsuTypography.small,- color = EnsuColor.textMuted(),- )- }- if (!controlsEnabled) {- item {- val inventoryLoading =- knowledgeState.inventoryLoading || notesState.inventoryLoading- val inventoryFailed =- !inventoryLoading &&- (!knowledgeState.inventoryReady || !notesState.inventoryReady)- Text(- when {- inventoryFailed ->- "Could not load all sources. Your saved choices have been kept."- !chatState.sourceSelectionReady -> "Loading sources…"- else -> "You can change sources after the response finishes."- },- style = EnsuTypography.small,- color = EnsuColor.textMuted(),- )- if (inventoryFailed) {- CompactButton(- label = "Retry loading sources",- onClick = store::retrySourceInventory,- enabled = !chatState.isGenerating,- )- }- }- }- item {- Text("Ensu Packs", style = EnsuTypography.large, color = EnsuColor.textPrimary())- }- if (knowledgeState.packs.isEmpty()) {- item {- Text(- "No Ensu Packs available.",- style = EnsuTypography.small,- color = EnsuColor.textMuted(),- )- }- }- items(knowledgeState.packs.values.toList(), key = { "pack-${it.config.stableId}" }) {- pack ->- KnowledgePackCard(- pack = pack,- packDownloadsAllowed = supported,- selected = chatState.sourceSelection.isPackEnabled(pack.config.stableId),- controlsEnabled = controlsEnabled,- onDownloadOrUpdate = {- store.downloadKnowledgePackForChat(- pack.config.stableId,- store.sourceSelectionTarget(),- )- },- onCancel = { store.cancelKnowledgePackDownload(pack.config.stableId) },- onSetEnabled = { store.setKnowledgePackEnabled(pack.config.stableId, it) },- onOpenAttribution = { attribution = pack.config },- )- }- item {- Text("Your Notes", style = EnsuTypography.large, color = EnsuColor.textPrimary())- }- items(notesState.collections, key = { "folder-${it.id}" }) { folder ->- KnowledgeCard(spacing = EnsuSpacing.sm.dp) {- Row(verticalAlignment = Alignment.CenterVertically) {- Column(modifier = Modifier.weight(1f)) {- Text(- folder.label,- style = EnsuTypography.large,- color = EnsuColor.textPrimary(),- )- Text(- when (folder.status) {- NotesStatus.Pending -> "Preparing notes…"- NotesStatus.Indexing -> "Indexing notes…"- NotesStatus.Updating -> "Updating notes…"- NotesStatus.Unavailable -> "Folder unavailable"- NotesStatus.Error -> "Could not index folder"- NotesStatus.Ready -> "${folder.documentCount} notes indexed"- },- style = EnsuTypography.mini,- color = EnsuColor.textMuted(),- )- }- Switch(- checked = chatState.sourceSelection.isFolderEnabled(folder.id),- onCheckedChange = { store.setNotesFolderEnabled(folder.id, it) },- enabled = controlsEnabled,- modifier =- Modifier.semantics {- contentDescription = "Use ${folder.label} in this chat"- },- )- }- folder.progress?.let { progress ->- LinearProgressIndicator(- progress = { progress.coerceIn(0, 100) / 100f },- modifier = Modifier.fillMaxWidth(),- color = EnsuColor.action(),- trackColor = EnsuColor.border(),- )- }- folder.error?.let { error ->- Text(error, style = EnsuTypography.small, color = EnsuColor.error)- CompactButton(- "Retry",- onClick = { store.notesStore.retry(folder.id) },- enabled = controlsEnabled,- )- }- }- }- item {- CompactButton(- "Add notes folder",- enabled = controlsEnabled && supported,- onClick = {- pendingFolderTarget = store.sourceSelectionTarget()- store.setPickerPending(true)- try {- folderPicker.launch(null)- } catch (error: Exception) {- pendingFolderTarget = null- store.setPickerPending(false)- throw error- }- },- )- }- item {- Text(- "Ensu reads and indexes markdown files in the selected folder. Source files are never modified.",- style = EnsuTypography.small,- color = EnsuColor.textMuted(),- )- }- notesState.error?.let { error ->- item { Text(error, style = EnsuTypography.small, color = EnsuColor.error) }- }- }- }- attribution?.let { config -> PackAttributionDialog(config, onDismiss = { attribution = null }) }-}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.ktindex fbe7619d72..f14fc2a585 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt@@ -6,8 +6,8 @@ import io.ente.ensu.llm.DownloadPhasedata class ChatState(val sessions: List<ChatSession> = emptyList(),val currentSessionId: String? = null,- val sourceSelection: ChatSourceSelection = ChatSourceSelection(),val sourceSelectionReady: Boolean = false,+ val sourceSelectionError: String? = null,val messages: List<ChatMessage> = emptyList(),val streamingResponse: String = "",val streamingParentId: String? = null,diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.ktindex 1752242c27..23d18b4f17 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt@@ -46,6 +46,7 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.collectimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.combineimport kotlinx.coroutines.flow.distinctUntilChanged@@ -58,7 +59,6 @@ import kotlinx.coroutines.withContextinternal class ChatStoreActions(private val state: MutableStateFlow<AppState>,- private val sourcePreferences: ChatSourceSelectionPreferences,private val sessionPreferences: SessionPreferencesDataStore,private val chatRepository: ChatRepository,private val llmProvider: LlmProvider,@@ -75,7 +75,6 @@ internal class ChatStoreActions(private val sourceInventoryReady: Booleanget() = state.value.knowledge.inventoryReady && notesStore.state.value.inventoryReady- private val sourceSelections = ChatSourceSelections(sourcePreferences)private val branchSelections = mutableMapOf<String, MutableMap<String, String>>()private val sessionSummaries = mutableMapOf<String, String>()private val sessionAccessTimes = mutableMapOf<String, Long>()@@ -100,7 +99,7 @@ internal class ChatStoreActions(fun bootstrap(scope: CoroutineScope) {this.scope = scope- refreshSourceSelectionInventory()+ refreshSourceInventory()scope.launch {combine(state.map { it.knowledge.inventoryReady },@@ -109,11 +108,16 @@ internal class ChatStoreActions(packsReady && notesReady}.distinctUntilChanged()- .collectLatest { ready ->- if (ready) {- refreshSourceSelectionInventory()- } else {- state.update { it.copy(chat = it.chat.copy(sourceSelectionReady = false)) }+ .collect { ready ->+ state.update {+ it.copy(+ chat =+ it.chat.copy(+ sourceSelectionReady = ready,+ sourceSelectionError =+ if (ready) null else it.chat.sourceSelectionError,+ )+ )}}}@@ -139,83 +143,47 @@ internal class ChatStoreActions(}}- fun refreshSourceSelectionInventory() {+ fun refreshSourceInventory() {scope?.launch {+ state.update { it.copy(chat = it.chat.copy(sourceSelectionError = null)) }awaitKnowledgeReady()notesStore.awaitReady()state.update { appState ->appState.copy(chat =appState.chat.copy(- sourceSelection = readSourceSelection(sourceSelectionTarget()),sourceSelectionReady = sourceInventoryReady,+ sourceSelectionError =+ if (sourceInventoryReady) null+ else "Couldn’t load sources. Try again.",))}}}- fun sourceSelectionTarget(): String =- state.value.chat.currentSessionId ?: sourcePreferences.draftKey-- private fun initialSourceSelection(): ChatSourceSelection =+ private fun currentSourceSelection(): ChatSourceSelection =ChatSourceSelection(selectedPackIds =state.value.knowledge.packs.values- .filter { it.activeIdentity != null }+ .filter {+ it.activeIdentity != null &&+ it.config.stableId !in state.value.knowledge.disabledIds+ }.map { it.config.stableId }.toSet(),- selectedFolderIds = notesStore.state.value.collections.map { it.id }.toSet(),+ selectedFolderIds =+ notesStore.state.value.collections+ .filter { it.id !in notesStore.state.value.disabledIds }+ .map { it.id }+ .toSet(),)- private fun readSourceSelection(target: String): ChatSourceSelection =- sourceSelections.initialize(target, sourceInventoryReady, ::initialSourceSelection)-- fun selectAddedPack(target: String, id: String) =- selectAddedSource(target) { it.withPackEnabled(id, true) }-- fun selectAddedFolder(target: String, id: String) =- selectAddedSource(target) { it.withFolderEnabled(id, true) }-- private fun selectAddedSource(- target: String,- transform: (ChatSourceSelection) -> ChatSourceSelection,- ) {- val (destination, updated) = sourceSelections.selectAdded(target, transform) ?: return- if (destination == sourceSelectionTarget()) {- state.update { it.copy(chat = it.chat.copy(sourceSelection = updated)) }- }- }-- fun setPackEnabled(id: String, enabled: Boolean) {- updateSourceSelection { it.withPackEnabled(id, enabled) }- }-- fun setFolderEnabled(id: String, enabled: Boolean) {- updateSourceSelection { it.withFolderEnabled(id, enabled) }- }-- private fun updateSourceSelection(transform: (ChatSourceSelection) -> ChatSourceSelection) {- val chat = state.value.chat- if (!sourceInventoryReady || chat.isGenerating || chat.preparationStatus != null) return- val selection = transform(chat.sourceSelection)- sourcePreferences.write(sourceSelectionTarget(), selection)- state.update { it.copy(chat = it.chat.copy(sourceSelection = selection)) }- }-fun createNewSession(): String {+ check(sourceInventoryReady)resetGenerationState()- val selection =- if (state.value.chat.currentSessionId == null)- readSourceSelection(sourcePreferences.draftKey)- else initialSourceSelection()val session = chatRepository.createSession("New Chat")- if (sourceInventoryReady) sourcePreferences.write(session.id, selection)- if (state.value.chat.currentSessionId == null) {- sourceSelections.promote(sourcePreferences.draftKey, session.id)- }- sourcePreferences.resetDraft()messageStore[session.id] = mutableListOf()branchSelections[session.id] = mutableMapOf()@@ -226,7 +194,6 @@ internal class ChatStoreActions(appState.chat.copy(sessions = updatedSessions,currentSessionId = session.id,- sourceSelection = selection,messageText = "",attachments = emptyList(),editingMessageId = null,@@ -245,13 +212,11 @@ internal class ChatStoreActions(resetGenerationState()attachmentActions.discardAttachments(state.value.chat.attachments)- sourcePreferences.resetDraft()state.update { appState ->appState.copy(chat =appState.chat.copy(currentSessionId = null,- sourceSelection = readSourceSelection(sourcePreferences.draftKey),messages = emptyList(),branchSelections = emptyMap(),messageText = "",@@ -265,13 +230,7 @@ internal class ChatStoreActions(fun selectSession(sessionId: String) {resetGenerationState()state.update { appState ->- appState.copy(- chat =- appState.chat.copy(- currentSessionId = sessionId,- sourceSelection = readSourceSelection(sessionId),- )- )+ appState.copy(chat = appState.chat.copy(currentSessionId = sessionId))}val scope = scope ?: returnscope.launch(Dispatchers.IO) {@@ -289,7 +248,6 @@ internal class ChatStoreActions(}chatRepository.deleteSession(sessionId)- sourcePreferences.remove(sessionId)if (isCurrent) attachmentActions.discardAttachments(currentState.chat.attachments)removeSessionCaches(sessionId)sessionSummaries.remove(sessionKey(sessionId))@@ -312,8 +270,6 @@ internal class ChatStoreActions(appState.chat.copy(sessions = sessions,currentSessionId = newCurrent,- sourceSelection =- readSourceSelection(newCurrent ?: sourcePreferences.draftKey),isGenerating = if (resetCurrent) false else appState.chat.isGenerating,preparationStatus =if (resetCurrent) null else appState.chat.preparationStatus,@@ -434,6 +390,10 @@ internal class ChatStoreActions(}fun retryAssistantMessage(messageId: String) {+ if (!sourceInventoryReady) {+ refreshSourceInventory()+ return+ }val priorGeneration = generationJobval priorSummary = sessionSummaryJobif (state.value.chat.isGenerating) {@@ -454,6 +414,7 @@ internal class ChatStoreActions(messageStore[sessionId]?.firstOrNull { it.id == parentId }} ?: return+ val sourceSelection = currentSourceSelection()priorGeneration?.cancel()priorSummary?.cancel()llmProvider.stopGeneration()@@ -469,11 +430,12 @@ internal class ChatStoreActions() {llmProvider.resetContext()}- startGeneration(sessionId, parent)+ startGeneration(sessionId, parent, sourceSelection)}}fun sendMessage() {+ if (!sourceInventoryReady) returnval currentState = state.valueif (currentState.chat.isGenerating || currentState.chat.isDownloading) returnif (!currentState.chat.deviceCapability.isChatSupported()) return@@ -552,7 +514,7 @@ internal class ChatStoreActions(overflowBypassMessageId = pending.messageIdpendingOverflow = nullclearOverflowDialog()- startGeneration(pending.sessionId, message)+ startGeneration(pending.sessionId, message, pending.sourceSelection)}fun cancelOverflowDialog() {@@ -601,11 +563,6 @@ internal class ChatStoreActions(appState.chat.copy(sessions = sessions,currentSessionId = if (sessionStillExists) currentSessionId else null,- sourceSelection =- readSourceSelection(- if (sessionStillExists) currentSessionId- else sourcePreferences.draftKey- ),))}@@ -618,9 +575,17 @@ internal class ChatStoreActions(}}- private fun startGeneration(sessionId: String, userMessage: ChatMessage) {+ private fun startGeneration(+ sessionId: String,+ userMessage: ChatMessage,+ sourceSelection: ChatSourceSelection = currentSourceSelection(),+ ) {val scope = scope ?: returnif (!state.value.chat.deviceCapability.isChatSupported()) return+ if (!sourceInventoryReady) {+ refreshSourceInventory()+ return+ }modelSettingsActions.cancelChatWarmup(releaseLoadedModel = false)val priorGeneration = generationJobval priorSummary = sessionSummaryJob@@ -673,7 +638,6 @@ internal class ChatStoreActions(}rebuildChatState(sessionId)- val requestedSourceSelection = sourcePreferences.read(sessionId)val notesScope = notesStore.suspendMaintenance()var followup: ConversationFollowup? = nullval activeJob = scope.launch {@@ -691,18 +655,6 @@ internal class ChatStoreActions(if (!isActive()) return@launchval progressTracker = DownloadProgressTracker()var embeddingAssetInvalid = false- val sourceSelection = requestedSourceSelection ?: readSourceSelection(sessionId)- if (!state.value.chat.sourceSelectionReady) {- state.update {- it.copy(- chat =- it.chat.copy(- sourceSelection = sourceSelection,- sourceSelectionReady = sourceInventoryReady,- )- )- }- }val enabledDatasets =state.value.knowledge.readyDatasets.filter {sourceSelection.isPackEnabled(it.stableId)@@ -941,6 +893,7 @@ internal class ChatStoreActions(userMessage,prompt,selection,+ sourceSelection,modelSettingsActions.resolveTemperature(settings),knowledgeHits,onModelProgress,@@ -962,6 +915,7 @@ internal class ChatStoreActions(userMessage: ChatMessage,prompt: PromptResult,selection: LlmModelSelection,+ sourceSelection: ChatSourceSelection,temperature: Float,knowledgeHits: List<GroundedExcerpt>,onModelProgress: (DownloadProgress) -> Unit,@@ -998,7 +952,8 @@ internal class ChatStoreActions(overflowBypassMessageId != userMessage.id) {overflowBypassMessageId = null- pendingOverflow = PendingOverflow(sessionId, userMessage.id)+ pendingOverflow =+ PendingOverflow(sessionId, userMessage.id, sourceSelection)streamingParentId = nullstate.update { appState ->appState.copy(@@ -1898,6 +1853,7 @@ internal class ChatStoreActions(private data class PendingOverflow(val sessionId: String,val messageId: String,+ val sourceSelection: ChatSourceSelection,)private fun buildPrompt(text: String, attachments: List<Attachment>): PromptResult {diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.ktindex 2130ed2414..31f9beb63b 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt@@ -46,20 +46,16 @@ import androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.platform.LocalFocusManagerimport androidx.compose.ui.unit.dpimport androidx.core.content.ContextCompat-import io.ente.ensu.AppStoreimport io.ente.ensu.assets.AssetStoreimport io.ente.ensu.designsystem.EnsuColorimport io.ente.ensu.designsystem.EnsuSpacingimport io.ente.ensu.device.ChatDeviceCapability-import io.ente.ensu.knowledge.KnowledgeStateimport io.ente.ensu.llm.LlmProviderimport kotlinx.coroutines.Job@Composablefun ChatView(chatState: ChatState,- knowledgeState: KnowledgeState,- store: AppStore,assetStore: AssetStore,llmProvider: LlmProvider,isDrawerOpen: Boolean,@@ -79,6 +75,11 @@ fun ChatView(onOverflowTrim: () -> Unit,onOverflowCancel: () -> Unit,onVoiceInputJob: (Job) -> Unit,+ onOpenPacks: () -> Unit,+ onOpenNotes: () -> Unit,+ hasSeenSourceIntroduction: Boolean,+ onCompleteSourceIntroduction: () -> Unit,+ onRetrySources: () -> Unit,) {val density = LocalDensity.currentval context = LocalContext.current@@ -86,7 +87,8 @@ fun ChatView(val latestMessageText by rememberUpdatedState(chatState.messageText)val latestOnMessageChange by rememberUpdatedState(onMessageChange)val sessionKey = chatState.currentSessionId ?: "new-session"- var showSources by remember(sessionKey) { mutableStateOf(false) }+ var introductionSeen by+ remember(hasSeenSourceIntroduction) { mutableStateOf(hasSeenSourceIntroduction) }val latestSessionKey by rememberUpdatedState(sessionKey)val unsupportedCapability =chatState.deviceCapability as? ChatDeviceCapability.UnsupportedLowMemory@@ -154,8 +156,17 @@ fun ChatView(var focusRequestId by remember { mutableIntStateOf(0) }var wasDrawerOpen by remember { mutableStateOf(false) }+ val showIntroduction =+ !introductionSeen &&+ chatState.isModelDownloaded &&+ !chatState.isDownloading &&+ !chatState.isGenerating &&+ !isChatUnsupported &&+ !isDrawerOpen+val shouldAutoFocusInput =- chatState.isModelDownloaded &&+ !showIntroduction &&+ chatState.isModelDownloaded &&!showDownloadOnboarding &&!isChatUnsupported &&!chatState.isDownloading &&@@ -196,13 +207,16 @@ fun ChatView(voiceController.cancelActiveVoiceInput()}- ChatSourcesSheet(- visible = showSources,- chatState = chatState,- knowledgeState = knowledgeState,- store = store,- onDismiss = { showSources = false },- )+ if (showIntroduction) {+ SourceIntroductionSheet(+ onDismiss = {+ onCompleteSourceIntroduction()+ introductionSeen = true+ },+ onOpenPacks = onOpenPacks,+ onOpenNotes = onOpenNotes,+ )+ }Box(modifier = Modifier.fillMaxSize()) {Column(modifier = Modifier.fillMaxSize().imePadding()) {@@ -292,6 +306,9 @@ fun ChatView(isProcessingAttachments = chatState.isProcessingAttachments,isGenerating = chatState.isGenerating,isDownloading = chatState.isDownloading,+ sourcesReady = chatState.sourceSelectionReady,+ sourcesError = chatState.sourceSelectionError,+ onRetrySources = onRetrySources,onMessageChange = onMessageChange,onSend = {focusManager.clearFocus()@@ -301,10 +318,6 @@ fun ChatView(onAttachmentSelected = onAttachmentSelected,onRemoveAttachment = onRemoveAttachment,onCancelEdit = onCancelEdit,- onOpenSources = {- focusManager.clearFocus()- showSources = true- },voiceInputState = voiceController.state,onVoiceInput = {if (voiceController.state.isRecording) {diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/SourceIntroductionSheet.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/SourceIntroductionSheet.ktnew file mode 100644index 0000000000..c8f6b79426--- /dev/null+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/SourceIntroductionSheet.kt@@ -0,0 +1,105 @@+package io.ente.ensu.chat++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.Text+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import io.ente.ensu.components.CompactButton+import io.ente.ensu.components.KnowledgeCard+import io.ente.ensu.components.TextActionButton+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.designsystem.EnsuTypography++@OptIn(ExperimentalMaterial3Api::class)+@Composable+internal fun SourceIntroductionSheet(+ onDismiss: () -> Unit,+ onOpenPacks: () -> Unit,+ onOpenNotes: () -> Unit,+) {+ ModalBottomSheet(+ onDismissRequest = onDismiss,+ sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),+ containerColor = EnsuColor.backgroundBase(),+ ) {+ Column(+ Modifier.fillMaxWidth()+ .verticalScroll(rememberScrollState())+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ .padding(bottom = EnsuSpacing.lg.dp),+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp),+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {+ Text(+ "Give Ensu more context",+ style = EnsuTypography.h3,+ color = EnsuColor.textPrimary(),+ )+ Text(+ "Add a knowledge pack or your notes to help Ensu answer accurately.",+ style = EnsuTypography.body,+ color = EnsuColor.textMuted(),+ )+ }+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {+ KnowledgeCard(spacing = EnsuSpacing.sm.dp) {+ Text(+ "Ensu Packs",+ style = EnsuTypography.large,+ color = EnsuColor.textPrimary(),+ )+ Text(+ "Knowledge from Wikipedia to help Ensu get factual questions right.",+ style = EnsuTypography.small,+ color = EnsuColor.textMuted(),+ )+ CompactButton("Set up", onClick = onOpenPacks, prominent = true)+ }+ KnowledgeCard(spacing = EnsuSpacing.sm.dp) {+ Text(+ "Your Notes",+ style = EnsuTypography.large,+ color = EnsuColor.textPrimary(),+ )+ Text(+ "Use a local Markdown notes folder to chat with your own knowledge base.",+ style = EnsuTypography.small,+ color = EnsuColor.textMuted(),+ )+ CompactButton("Set up", onClick = onOpenNotes, prominent = true)+ }+ }+ Column(+ modifier = Modifier.fillMaxWidth(),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp),+ ) {+ TextActionButton(+ text = "Not now",+ onTap = onDismiss,+ underlined = true,+ color = EnsuColor.textPrimary(),+ )+ Text(+ "You can set up Ensu Packs and Your Notes later from Settings.",+ style = EnsuTypography.mini.copy(fontWeight = FontWeight.Normal),+ color = EnsuColor.textMuted(),+ textAlign = TextAlign.Center,+ )+ }+ }+ }+}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.ktindex 71bd40aa3c..f706aba50d 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.kt@@ -2,6 +2,7 @@ package io.ente.ensu.componentsimport androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.Button@@ -20,6 +21,7 @@ import androidx.compose.ui.graphics.vector.ImageVectorimport androidx.compose.ui.hapticfeedback.HapticFeedbackTypeimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextDecorationimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport io.ente.ensu.designsystem.EnsuColor@@ -80,6 +82,8 @@ fun ActionButton(fun TextActionButton(text: String,onTap: () -> Unit,+ underlined: Boolean = false,+ color: Color = EnsuColor.textMuted(),) {val haptic = rememberHaptics()TextButton(@@ -88,23 +92,37 @@ fun TextActionButton(onTap()}) {- Text(text = text, style = EnsuTypography.small, color = EnsuColor.textMuted())+ Text(+ text = text,+ style = EnsuTypography.small,+ color = color,+ textDecoration = if (underlined) TextDecoration.Underline else TextDecoration.None,+ )}}@Composable-fun CompactButton(label: String, onClick: () -> Unit, enabled: Boolean = true) {+fun CompactButton(+ label: String,+ onClick: () -> Unit,+ prominent: Boolean = false,+) {Button(onClick = onClick,- enabled = enabled,+ modifier = Modifier.heightIn(min = if (prominent) 48.dp else 0.dp),colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent()),contentPadding =PaddingValues(- horizontal = EnsuSpacing.md.dp,- vertical = EnsuSpacing.xs.dp,+ horizontal = if (prominent) EnsuSpacing.xxl.dp else EnsuSpacing.md.dp,+ vertical = if (prominent) EnsuSpacing.md.dp else EnsuSpacing.xs.dp,),) {- Text(label, style = EnsuTypography.mini)+ Text(+ label,+ style =+ if (prominent) EnsuTypography.body.copy(fontWeight = FontWeight.SemiBold)+ else EnsuTypography.mini,+ )}}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/HugeIcons.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/HugeIcons.ktindex 2da14081ef..3a446f1616 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/HugeIcons.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/HugeIcons.kt@@ -12,6 +12,7 @@ object HugeIcons {val Folder01Icon = R.drawable.hugeicon_folder01val Delete01Icon = R.drawable.hugeicon_delete01val Edit01Icon = R.drawable.hugeicon_edit01+ val ImagePlusIcon = R.drawable.hugeicon_image_plusval Menu01Icon = R.drawable.hugeicon_menu01val PlusSignIcon = R.drawable.hugeicon_plus_signval PackageIcon = R.drawable.hugeicon_packagediff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.ktindex 00465c69d3..f85414fabd 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt@@ -44,6 +44,8 @@ object EnsuColor {val error = Color(0xFFFF4444)val success = Color(0xFF4CAF50)val stopButton = Color(0xFFFF0000)+ val sendButton = Color(0xFFE66A28)+ val sendButtonInactive = sendButton.copy(alpha = 0.45f)val toastBackgroundLight = Color(0xFF1A1A1A)val toastBackgroundDark = Color(0xFFF8F5F0)diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.ktindex ec22beffae..d3f64e6fce 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt@@ -1,5 +1,8 @@package io.ente.ensu.knowledge+import android.content.Context+import androidx.datastore.preferences.core.stringSetPreferencesKey+import androidx.datastore.preferences.preferencesDataStoreimport io.ente.ensu.AppStateimport io.ente.ensu.bindings.AssetDownloadExceptionimport io.ente.ensu.bindings.KnowledgeDatasetConfig@@ -14,9 +17,12 @@ import kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+private val Context.legacyKnowledgePreferences by preferencesDataStore("ensu_knowledge_preferences")+data class KnowledgePackState(val config: KnowledgeDatasetConfig,val status: KnowledgeReconciliationStatus? = null,@@ -31,10 +37,12 @@ data class KnowledgePackState(data class KnowledgeState(val packs: Map<String, KnowledgePackState> = emptyMap(),+ val disabledIds: Set<String> = emptySet(),val inventoryLoading: Boolean = true,+ val settingsReady: Boolean = false,) {val inventoryReady: Boolean- get() = !inventoryLoading && packs.values.all { it.inventoryLoaded }+ get() = settingsReady && !inventoryLoading && packs.values.all { it.inventoryLoaded }val readyDatasets: List<KnowledgeDatasetConfig>get() =@@ -47,31 +55,58 @@ data class KnowledgeState(}class KnowledgeStore(+ context: Context,private val state: MutableStateFlow<AppState>,private val provider: KnowledgeProvider,datasets: List<KnowledgeDatasetConfig>,private val logRepository: FileLogRepository,) {+ private val preferences = KnowledgePreferences(context)private val catalog = datasets.associateBy { it.stableId }private val jobs = mutableMapOf<String, Job>()private var scope: CoroutineScope? = nullprivate var bootstrapJob: Job? = nullprivate val packsReady = CompletableDeferred<Unit>()- fun bootstrap(scope: CoroutineScope) {+ fun bootstrap(scope: CoroutineScope, retryFailed: Boolean = false) {this.scope = scope- if (bootstrapJob != null) return- state.update { appState ->- appState.copy(- knowledge =- KnowledgeState(- packs = catalog.mapValues { (_, config) -> KnowledgePackState(config) }- )- )- }+ if (bootstrapJob?.isActive == true || (bootstrapJob != null && !retryFailed)) return+ if (state.value.knowledge.inventoryReady) return+ if (bootstrapJob == null)+ state.update { appState ->+ appState.copy(+ knowledge =+ appState.knowledge.copy(+ packs = catalog.mapValues { (_, config) -> KnowledgePackState(config) }+ )+ )+ }+ state.update { it.copy(knowledge = it.knowledge.copy(inventoryLoading = true)) }bootstrapJob = scope.launch {try {- catalog.values.forEach { dataset -> reconcileAndUpdate(dataset) }+ preferences.migratePackSettings(catalog.keys)+ val disabledIds = preferences.disabledPackIds+ state.update {+ it.copy(+ knowledge =+ it.knowledge.copy(+ disabledIds = disabledIds,+ settingsReady = true,+ )+ )+ }+ catalog.values+ .filter { state.value.knowledge.packs[it.stableId]?.inventoryLoaded != true }+ .forEach { dataset -> reconcileAndUpdate(dataset) }+ } catch (error: CancellationException) {+ throw error+ } catch (error: Exception) {+ logRepository.log(+ LogLevel.Error,+ "Could not load source preferences",+ tag = "Knowledge",+ throwable = error,+ )} finally {state.update { it.copy(knowledge = it.knowledge.copy(inventoryLoading = false)) }packsReady.complete(Unit)@@ -84,24 +119,23 @@ class KnowledgeStore(bootstrapJob?.join()}- fun retryInventory() {- val ownerScope = scope ?: return- if (bootstrapJob?.isActive == true || state.value.knowledge.inventoryReady) return- state.update { it.copy(knowledge = it.knowledge.copy(inventoryLoading = true)) }- bootstrapJob = ownerScope.launch {- try {- catalog.values.forEach { dataset -> reconcileAndUpdate(dataset) }- } finally {- state.update { it.copy(knowledge = it.knowledge.copy(inventoryLoading = false)) }- }+ fun retry() {+ scope?.let { bootstrap(it, retryFailed = true) }+ }++ fun setEnabled(stableId: String, enabled: Boolean) {+ preferences.setPackEnabled(stableId, enabled)+ state.update {+ it.copy(knowledge = it.knowledge.copy(disabledIds = preferences.disabledPackIds))}}- fun downloadOrUpdate(stableId: String, onInstalled: (() -> Unit)? = null) {+ fun downloadOrUpdate(stableId: String) {if (!state.value.chat.deviceCapability.isChatSupported()) returnval dataset = catalog[stableId] ?: returnval ownerScope = scope ?: returnif (jobs[stableId]?.isActive == true) return+ val wasInstalled = state.value.knowledge.packs[stableId]?.activeIdentity != nullupdatePack(stableId) {it.copy(mutationProgress = KnowledgeDownloadProgress("Starting download...", 0.0),@@ -119,7 +153,8 @@ class KnowledgeStore(updatePack(stableId) {it.fromReconciliation(reconciliation).copy(mutationProgress = null)}- if (reconciliation.activeIdentity != null) onInstalled?.invoke()+ if (!wasInstalled && reconciliation.activeIdentity != null)+ setEnabled(stableId, true)} catch (error: CancellationException) {throw error} catch (error: Throwable) {@@ -215,3 +250,27 @@ class KnowledgeStore(}}}++private class KnowledgePreferences(context: Context) {+ private val legacyPreferences = context.applicationContext.legacyKnowledgePreferences+ private val preferences =+ context.applicationContext.getSharedPreferences("ensu_chat_sources", Context.MODE_PRIVATE)++ val disabledPackIds: Set<String>+ get() = preferences.getStringSet("disabled_pack_defaults", emptySet()).orEmpty().toSet()++ suspend fun migratePackSettings(packIds: Set<String>) {+ if (preferences.getBoolean("pack_defaults_migrated", false)) return+ val legacy = legacyPreferences.data.first()[stringSetPreferencesKey("enabled_dataset_ids")]+ val editor = preferences.edit()+ if (!preferences.contains("disabled_pack_defaults")) {+ editor.putStringSet("disabled_pack_defaults", legacy?.let { packIds - it }.orEmpty())+ }+ editor.putBoolean("pack_defaults_migrated", true).apply()+ }++ fun setPackEnabled(id: String, enabled: Boolean) {+ val ids = disabledPackIds.let { if (enabled) it - id else it + id }+ preferences.edit().putStringSet("disabled_pack_defaults", ids).apply()+ }+}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.ktindex f5e9add0a4..3da32764c8 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt@@ -290,6 +290,14 @@ class LlmProvider(modelLoadMutex.withLock { if (chatWarmupOwner == owner) unloadModel() }}+ internal suspend fun releaseInactiveChatResources(isPickerPending: () -> Boolean) =+ withContext(ioDispatcher) {+ releaseInactiveChatResources(modelLoadMutex, { chatForeground }, isPickerPending) {+ unloadTranscriptionModelIfLoaded()+ unloadModel()+ }+ }+suspend fun ensureRequiredModelsReady(selection: LlmModelSelection,onProgress: (DownloadProgress) -> Unit,diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelMaintenance.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelMaintenance.ktindex 2d0bfd993d..9fd76f5c07 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelMaintenance.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelMaintenance.kt@@ -1,5 +1,8 @@package io.ente.ensu.llm+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+interface ModelMaintenance {fun suspendMaintenance(): AutoCloseable@@ -17,3 +20,10 @@ internal suspend fun <T> ModelMaintenance?.withMaintenanceSuspended(block: suspetoken?.close()}}++internal suspend fun releaseInactiveChatResources(+ mutex: Mutex,+ isChatForeground: () -> Boolean,+ isPickerPending: () -> Boolean = { false },+ release: () -> Unit,+) = mutex.withLock { if (!isChatForeground() && !isPickerPending()) release() }diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.ktindex 8c263896b4..cbbc9cd64c 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt@@ -37,7 +37,7 @@ internal class ModelSettingsActions(private var modelDownloadJob: Job? = nullprivate var chatActive = falseprivate var appForeground = false- private var pickerPending = false+ @Volatile private var pickerPending = falseprivate var backgroundReleaseJob: Job? = nullprivate val activeVoiceJobs = AtomicInteger()private var warmupSuppressed = false@@ -339,6 +339,9 @@ internal class ModelSettingsActions() {cancelChatWarmup(releaseLoadedModel = false)}+ } else if (!pickerPending) {+ cancelChatWarmup(releaseLoadedModel = false)+ scope?.launch { llmProvider.releaseInactiveChatResources { pickerPending } }}refreshChatWarmup()}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesSettingsScreen.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesSettingsScreen.ktindex 17e63bd694..ecc4c820f3 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesSettingsScreen.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesSettingsScreen.kt@@ -13,6 +13,7 @@ import androidx.compose.material3.AlertDialogimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.Switchimport androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composable@@ -24,6 +25,8 @@ import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.res.painterResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport io.ente.ensu.components.CompactButtonimport io.ente.ensu.components.KnowledgeCard@@ -35,18 +38,29 @@ import java.text.DateFormatimport java.util.Date@Composable-fun NotesSettingsScreen(store: NotesStore, onPickerPending: (Boolean) -> Unit) {+fun NotesSettingsScreen(+ store: NotesStore,+ onPickerPending: (Boolean) -> Unit,+ allowRemoval: Boolean,+) {val state by store.state.collectAsState()var removing by remember { mutableStateOf<NoteCollectionState?>(null) }val picker =rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->onPickerPending(false)- uri?.let { store.add(it) }+ uri?.let(store::add)}LazyColumn(modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),) {+ item {+ Text(+ "Choose notes for future messages in all chats. Changes apply to your next message.",+ style = EnsuTypography.small,+ color = EnsuColor.textMuted(),+ )+ }items(state.collections, key = { it.id }) { collection ->KnowledgeCard(spacing = EnsuSpacing.sm.dp) {Row(verticalAlignment = Alignment.CenterVertically) {@@ -88,17 +102,27 @@ fun NotesSettingsScreen(store: NotesStore, onPickerPending: (Boolean) -> Unit) {color = EnsuColor.textMuted(),)}- IconButton(- onClick = { removing = collection },- modifier = Modifier.size(48.dp),- ) {- Icon(- painter = painterResource(HugeIcons.Delete01Icon),- contentDescription = "Remove ${collection.label}",- modifier = Modifier.size(18.dp),- tint = EnsuColor.textMuted(),- )- }+ Switch(+ checked = collection.id !in state.disabledIds,+ onCheckedChange = { store.setEnabled(collection.id, it) },+ modifier =+ Modifier.semantics {+ contentDescription =+ "Use ${collection.label} for future messages in all chats"+ },+ )+ if (allowRemoval)+ IconButton(+ onClick = { removing = collection },+ modifier = Modifier.size(48.dp),+ ) {+ Icon(+ painter = painterResource(HugeIcons.Delete01Icon),+ contentDescription = "Remove ${collection.label}",+ modifier = Modifier.size(18.dp),+ tint = EnsuColor.textMuted(),+ )+ }}collection.progress?.let { progress ->Row(diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesStore.ktindex a1d8cb4d95..7e7f70ee7b 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesStore.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesStore.kt@@ -71,7 +71,7 @@ data class NotesState(val collections: List<NoteCollectionState> = emptyList(),val error: String? = null,val inventoryReady: Boolean = false,- val inventoryLoading: Boolean = true,+ val disabledIds: Set<String> = emptySet(),)val LocalNotesStore = staticCompositionLocalOf<NotesStore?> { null }@@ -108,9 +108,22 @@ class NotesStore(private var foreground = falseprivate var loaded = falseprivate var disabled = false- private val _state = MutableStateFlow(NotesState())+ private val preferences =+ context.applicationContext.getSharedPreferences("ensu_note_defaults", Context.MODE_PRIVATE)+ private val _state =+ MutableStateFlow(+ NotesState(+ disabledIds = preferences.getStringSet("disabled", emptySet()).orEmpty().toSet()+ )+ )val state: StateFlow<NotesState> = _state.asStateFlow()+ fun setEnabled(id: String, enabled: Boolean) {+ val disabledIds = state.value.disabledIds.let { if (enabled) it - id else it + id }+ preferences.edit().putStringSet("disabled", disabledIds).apply()+ _state.update { it.copy(disabledIds = disabledIds) }+ }+fun bootstrap(owner: CoroutineScope) {if (bootstrapJob != null) returnscope = owner@@ -143,7 +156,7 @@ class NotesStore()}}- _state.value = NotesState(states, inventoryReady = true, inventoryLoading = false)+ _state.update { it.copy(collections = states, inventoryReady = true) }loaded = truescans.addAll(registrations.keys)} catch (e: CancellationException) {@@ -156,11 +169,11 @@ class NotesStore(throwable = e,)disabled = true- _state.value =- NotesState(- error = "Could not load Your Notes. Existing indexes have been preserved.",- inventoryLoading = false,+ _state.update {+ it.copy(+ error = "Could not load Your Notes. Existing indexes have been preserved.")+ }}pump()}@@ -170,13 +183,13 @@ class NotesStore(bootstrapJob?.join()}- fun retryInventory() {- val ownerScope = scope ?: return- if (bootstrapJob?.isActive == true || loaded) return- disabled = false+ fun retryLoad() {+ if (loaded || bootstrapJob?.isActive == true) return+ val owner = scope ?: returnbootstrapJob = null- _state.update { it.copy(inventoryLoading = true, error = null) }- bootstrap(ownerScope)+ disabled = false+ _state.update { it.copy(error = null) }+ bootstrap(owner)}fun setForeground(value: Boolean) {@@ -211,13 +224,14 @@ class NotesStore(active?.job?.join()}- fun add(tree: Uri, onAdded: ((String) -> Unit)? = null) {+ fun add(tree: Uri) {scope?.launch {awaitReady()if (disabled) return@launchwithMaintenanceSuspended {try {val record = provider.add(tree)+ if (record.id !in registrations) setEnabled(record.id, true)registrations[record.id] = record_state.update {it.copy(@@ -226,7 +240,6 @@ class NotesStore(error = null,)}- onAdded?.invoke(record.id)enqueue(record.id, immediate = true)} catch (error: CancellationException) {throw errordiff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/KnowledgeSettingsScreen.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/KnowledgeSettingsScreen.ktindex 6c9a0539dd..839f8889eb 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/KnowledgeSettingsScreen.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/KnowledgeSettingsScreen.kt@@ -51,6 +51,7 @@ fun KnowledgeSettingsScreen(packDownloadsAllowed: Boolean,onDownloadOrUpdate: (String) -> Unit,onCancel: (String) -> Unit,+ onSetEnabled: (String, Boolean) -> Unit,) {var attributionConfig by remember { mutableStateOf<KnowledgeDatasetConfig?>(null) }@@ -58,10 +59,19 @@ fun KnowledgeSettingsScreen(modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),) {+ item {+ Text(+ "Choose packs for future messages in all chats. Changes apply to your next message.",+ style = EnsuTypography.small,+ color = EnsuColor.textMuted(),+ )+ }items(state.packs.values.toList(), key = { it.config.stableId }) { pack ->KnowledgePackCard(pack = pack,packDownloadsAllowed = packDownloadsAllowed,+ selected = pack.config.stableId !in state.disabledIds,+ onSetEnabled = { onSetEnabled(pack.config.stableId, it) },onDownloadOrUpdate = { onDownloadOrUpdate(pack.config.stableId) },onCancel = { onCancel(pack.config.stableId) },onOpenAttribution = { attributionConfig = pack.config },@@ -78,15 +88,14 @@ fun KnowledgeSettingsScreen(}@Composable-internal fun KnowledgePackCard(+private fun KnowledgePackCard(pack: KnowledgePackState,packDownloadsAllowed: Boolean,onDownloadOrUpdate: () -> Unit,onCancel: () -> Unit,onOpenAttribution: () -> Unit,- selected: Boolean? = null,- controlsEnabled: Boolean = true,- onSetEnabled: (Boolean) -> Unit = {},+ selected: Boolean,+ onSetEnabled: (Boolean) -> Unit,) {KnowledgeCard {Row(verticalAlignment = Alignment.CenterVertically) {@@ -101,14 +110,15 @@ internal fun KnowledgePackCard()PackMetadataLine(pack = pack, onOpenAttribution = onOpenAttribution)}- if (selected != null && pack.activeIdentity != null) {+ if (pack.activeIdentity != null) {Switch(checked = selected,onCheckedChange = onSetEnabled,- enabled = controlsEnabled,+ enabled = !pack.isMutating,modifier =Modifier.semantics {- contentDescription = "Use ${pack.config.label} in this chat"+ contentDescription =+ "Use ${pack.config.label} for future messages in all chats"},)} else if (@@ -119,7 +129,6 @@ internal fun KnowledgePackCard(CompactButton(label = "Download",onClick = onDownloadOrUpdate,- enabled = controlsEnabled,)}}@@ -156,7 +165,7 @@ internal fun KnowledgePackCard(packDownloadsAllowed && pack.status == KnowledgeReconciliationStatus.UPDATE_AVAILABLE) {Spacer(Modifier.height(EnsuSpacing.md.dp))- CompactButton(label = "Update", onClick = onDownloadOrUpdate, enabled = controlsEnabled)+ CompactButton(label = "Update", onClick = onDownloadOrUpdate)}pack.errorMessage?.let { Text(it, style = EnsuTypography.small, color = EnsuColor.error) }@@ -200,7 +209,7 @@ private fun PackMetadataLine(}@Composable-internal fun PackAttributionDialog(+private fun PackAttributionDialog(config: KnowledgeDatasetConfig,onDismiss: () -> Unit,) {diff --git a/android/apps/ensu/app/src/main/res/drawable/hugeicon_image_plus.xml b/android/apps/ensu/app/src/main/res/drawable/hugeicon_image_plus.xmlnew file mode 100644index 0000000000..da1e1a3b41--- /dev/null+++ b/android/apps/ensu/app/src/main/res/drawable/hugeicon_image_plus.xml@@ -0,0 +1,6 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">+ <path android:fillColor="#00000000" android:strokeColor="#FF000000" android:strokeWidth="2" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M21.5 18.5H18.5M18.5 18.5H15.5M18.5 18.5V15.5M18.5 18.5V21.5" />+ <path android:fillColor="#00000000" android:strokeColor="#FF000000" android:strokeWidth="2" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M9,7.5A1.5,1.5 0,1 1,6 7.5A1.5,1.5 0,1 1,9 7.5" />+ <path android:fillColor="#00000000" android:strokeColor="#FF000000" android:strokeWidth="2" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M11.5 21.5C7.35301 21.4981 5.22972 21.4473 3.89124 20.1088C2.5 18.7176 2.5 16.4784 2.5 12C2.5 7.52168 2.5 5.2825 3.89124 3.89125C5.28249 2.5 7.52166 2.5 12 2.5C16.4783 2.5 18.7175 2.5 20.1088 3.89125C21.5 5.2825 21.5 7.52168 21.5 12" />+ <path android:fillColor="#00000000" android:strokeColor="#FF000000" android:strokeWidth="2" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M13.0018 13.0616C10.1493 14.6467 7.70477 17.7414 5.41797 20.5" />+</vector>diff --git a/android/apps/ensu/app/src/main/res/drawable/hugeicon_mic02.xml b/android/apps/ensu/app/src/main/res/drawable/hugeicon_mic02.xmlindex 44b4061ccd..472bca1654 100644--- a/android/apps/ensu/app/src/main/res/drawable/hugeicon_mic02.xml+++ b/android/apps/ensu/app/src/main/res/drawable/hugeicon_mic02.xml@@ -6,14 +6,14 @@<pathandroid:fillColor="#00000000"android:strokeColor="#FF000000"- android:strokeWidth="1.5"+ android:strokeWidth="2"android:strokeLineCap="round"android:strokeLineJoin="round"android:pathData="M17 7V11C17 13.7614 14.7614 16 12 16C9.23858 16 7 13.7614 7 11V7C7 4.23858 9.23858 2 12 2C14.7614 2 17 4.23858 17 7Z" /><pathandroid:fillColor="#00000000"android:strokeColor="#FF000000"- android:strokeWidth="1.5"+ android:strokeWidth="2"android:strokeLineCap="round"android:strokeLineJoin="round"android:pathData="M20 11C20 15.4183 16.4183 19 12 19M12 19C7.58172 19 4 15.4183 4 11M12 19V22M12 22H15M12 22H9" />diff --git a/android/apps/ensu/app/src/main/res/drawable/hugeicon_stop.xml b/android/apps/ensu/app/src/main/res/drawable/hugeicon_stop.xmlindex 93cefd4565..70a6ffe3c7 100644--- a/android/apps/ensu/app/src/main/res/drawable/hugeicon_stop.xml+++ b/android/apps/ensu/app/src/main/res/drawable/hugeicon_stop.xml@@ -4,6 +4,9 @@android:viewportWidth="24"android:viewportHeight="24"><path- android:fillColor="#FF000000"+ android:fillColor="#00000000"+ android:strokeColor="#FF000000"+ android:strokeWidth="2"+ android:strokeLineJoin="round"android:pathData="M4 12C4 8.72077 4 7.08116 4.81382 5.91891C5.1149 5.48891 5.48891 5.1149 5.91891 4.81382C7.08116 4 8.72077 4 12 4C15.2792 4 16.9188 4 18.0811 4.81382C18.5111 5.1149 18.8851 5.48891 19.1862 5.91891C20 7.08116 20 8.72077 20 12C20 15.2792 20 16.9188 19.1862 18.0811C18.8851 18.5111 18.5111 18.8851 18.0811 19.1862C16.9188 20 15.2792 20 12 20C8.72077 20 7.08116 20 5.91891 19.1862C5.48891 18.8851 5.1149 18.5111 4.81382 18.0811C4 16.9188 4 15.2792 4 12Z" />-</vector>\ No newline at end of file+</vector>diff --git a/android/apps/ensu/app/src/test/java/io/ente/ensu/chat/ChatSourceSelectionsTest.kt b/android/apps/ensu/app/src/test/java/io/ente/ensu/chat/ChatSourceSelectionsTest.ktdeleted file mode 100644index 806f46fab3..0000000000--- a/android/apps/ensu/app/src/test/java/io/ente/ensu/chat/ChatSourceSelectionsTest.kt+++ /dev/null@@ -1,122 +0,0 @@-package io.ente.ensu.chat--import org.junit.Assert.assertEquals-import org.junit.Assert.assertFalse-import org.junit.Assert.assertNull-import org.junit.Assert.assertTrue-import org.junit.Test--class ChatSourceSelectionsTest {- private class MemoryStorage : ChatSourceSelectionStorage {- private val values = mutableMapOf<String, ChatSourceSelection>()-- override fun read(key: String): ChatSourceSelection? = values[key]-- override fun write(key: String, selection: ChatSourceSelection) {- values[key] = selection- }-- override fun remove(key: String) {- values.remove(key)- }- }-- @Test- fun existingChatKeepsItsSnapshotWhenInventoryChangesAndStoreRestarts() {- val storage = MemoryStorage()- val original = ChatSourceSelection(setOf("pack-a"), setOf("folder-a"))- ChatSourceSelections(storage).initialize("chat") { original }- val restored =- ChatSourceSelections(storage).initialize("chat") {- ChatSourceSelection(setOf("pack-a", "pack-b"), setOf("folder-a", "folder-b"))- }- assertEquals(original, restored)- assertFalse(restored.isPackEnabled("pack-b"))- assertFalse(restored.isFolderEnabled("folder-b"))- }-- @Test- fun emptySelectionStaysEmptyAndNewChatGetsCurrentInventory() {- val storage = MemoryStorage()- val selections = ChatSourceSelections(storage)- selections.initialize("old") { ChatSourceSelection() }- val current = ChatSourceSelection(setOf("pack"), setOf("folder"))- assertEquals(ChatSourceSelection(), selections.initialize("old") { current })- assertEquals(current, selections.initialize("new") { current })- }-- @Test- fun asyncAdditionFollowsPromotedDraftWithoutAffectingAnotherChat() {- val storage = MemoryStorage()- val selections = ChatSourceSelections(storage)- selections.initialize("draft-1") { ChatSourceSelection() }- selections.promote("draft-1", "chat-1")- selections.initialize("draft-2") { ChatSourceSelection() }- val result = selections.selectAdded("draft-1") { it.withFolderEnabled("new-folder", true) }- assertEquals("chat-1", result?.first)- assertTrue(storage.read("chat-1")!!.isFolderEnabled("new-folder"))- assertFalse(storage.read("draft-2")!!.isFolderEnabled("new-folder"))- assertNull(storage.read("draft-1"))- }-- @Test- fun asyncAdditionDoesNotRecreateDiscardedDraftOrDeletedChat() {- val storage = MemoryStorage()- val selections = ChatSourceSelections(storage)- selections.initialize("draft") { ChatSourceSelection() }- storage.remove("draft")- assertNull(selections.selectAdded("draft") { it.withPackEnabled("pack", true) })- selections.initialize("another-draft") { ChatSourceSelection() }- selections.promote("another-draft", "chat")- storage.remove("chat")- assertNull(selections.selectAdded("another-draft") { it.withPackEnabled("pack", true) })- }-- @Test- fun capturedGenerationSelectionIsUnchangedByLaterEditsOrAdditions() {- val storage = MemoryStorage()- val selections = ChatSourceSelections(storage)- val snapshot =- selections.initialize("chat") { ChatSourceSelection(setOf("pack"), setOf("folder")) }- storage.write(- "chat",- snapshot.withPackEnabled("pack", false).withFolderEnabled("folder", false),- )- selections.selectAdded("chat") { it.withPackEnabled("new-pack", true) }- assertTrue(snapshot.isPackEnabled("pack"))- assertTrue(snapshot.isFolderEnabled("folder"))- assertFalse(snapshot.isPackEnabled("new-pack"))- assertFalse(storage.read("chat")!!.isPackEnabled("pack"))- assertFalse(storage.read("chat")!!.isFolderEnabled("folder"))- }-- @Test- fun incompleteInventoryDoesNotPermanentlyDisableUnknownSources() {- val storage = MemoryStorage()- val selections = ChatSourceSelections(storage)- val partial = ChatSourceSelection(setOf("available-pack"), emptySet())- assertEquals(partial, selections.initialize("chat", inventoryReady = false) { partial })- assertNull(storage.read("chat"))-- val complete =- ChatSourceSelection(setOf("available-pack", "recovered-pack"), setOf("folder"))- assertEquals(complete, selections.initialize("chat") { complete })- assertEquals(complete, storage.read("chat"))- }-- @Test- fun inventoryFailurePreservesSavedChoicesIncludingAnEmptySelection() {- val storage = MemoryStorage()- val selections = ChatSourceSelections(storage)- val saved = ChatSourceSelection(setOf("unavailable-pack"), setOf("unavailable-folder"))- selections.initialize("selected") { saved }- selections.initialize("empty") { ChatSourceSelection() }- val available = ChatSourceSelection(setOf("other-pack"), setOf("other-folder"))- assertEquals(saved, selections.initialize("selected", inventoryReady = false) { available })- assertEquals(- ChatSourceSelection(),- selections.initialize("empty", inventoryReady = false) { available },- )- assertEquals(saved, storage.read("selected"))- }-}diff --git a/android/apps/ensu/app/src/test/java/io/ente/ensu/llm/ModelMaintenanceTest.kt b/android/apps/ensu/app/src/test/java/io/ente/ensu/llm/ModelMaintenanceTest.ktnew file mode 100644index 0000000000..3cab87603c--- /dev/null+++ b/android/apps/ensu/app/src/test/java/io/ente/ensu/llm/ModelMaintenanceTest.kt@@ -0,0 +1,61 @@+package io.ente.ensu.llm++import kotlinx.coroutines.CoroutineStart+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.sync.Mutex+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++class ModelMaintenanceTest {+ @Test+ fun leavingChatWaitsForActiveModelWorkBeforeUnloading() = runBlocking {+ val mutex = Mutex(locked = true)+ var resident = true+ val release =+ launch(start = CoroutineStart.UNDISPATCHED) {+ releaseInactiveChatResources(mutex, { false }) { resident = false }+ }++ assertFalse(release.isCompleted)+ assertTrue(resident)+ mutex.unlock()+ release.join()+ assertFalse(resident)+ }++ @Test+ fun returningToChatBeforeQueuedReleaseKeepsTheModelLoaded() = runBlocking {+ val mutex = Mutex(locked = true)+ var chatForeground = false+ var resident = true+ val release =+ launch(start = CoroutineStart.UNDISPATCHED) {+ releaseInactiveChatResources(mutex, { chatForeground }) { resident = false }+ }++ chatForeground = true+ mutex.unlock()+ release.join()+ assertTrue(resident)+ }++ @Test+ fun openingAttachmentPickerBeforeQueuedReleaseKeepsTheModelLoaded() = runBlocking {+ val mutex = Mutex(locked = true)+ var pickerPending = false+ var resident = true+ val release =+ launch(start = CoroutineStart.UNDISPATCHED) {+ releaseInactiveChatResources(mutex, { false }, { pickerPending }) {+ resident = false+ }+ }++ pickerPending = true+ mutex.unlock()+ release.join()+ assertTrue(resident)+ }+}diff --git a/apple/apps/ensu/Ensu.xcodeproj/project.pbxproj b/apple/apps/ensu/Ensu.xcodeproj/project.pbxprojindex 617be0b766..073f70b89d 100644--- a/apple/apps/ensu/Ensu.xcodeproj/project.pbxproj+++ b/apple/apps/ensu/Ensu.xcodeproj/project.pbxproj@@ -29,7 +29,7 @@/* End PBXContainerItemProxy section *//* Begin PBXFileReference section */- A50000022F11111100AA0001 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatSourceSelectionTests.swift; sourceTree = "<group>"; };+ A50000022F11111100AA0001 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KnowledgePreferencesTests.swift; sourceTree = "<group>"; };A40000022F11111100AA0001 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelMemoryCoordinationTests.swift; sourceTree = "<group>"; };A30000022F11111100AA0001 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageMarkdownTests.swift; sourceTree = "<group>"; };A20000022F11111100AA0001 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotesIntegrationTests.swift; sourceTree = "<group>"; };diff --git a/apple/apps/ensu/Ensu/Assets.xcassets/ImagePlusIcon.imageset/Contents.json b/apple/apps/ensu/Ensu/Assets.xcassets/ImagePlusIcon.imageset/Contents.jsonnew file mode 100644index 0000000000..5c9674a1e1--- /dev/null+++ b/apple/apps/ensu/Ensu/Assets.xcassets/ImagePlusIcon.imageset/Contents.json@@ -0,0 +1,16 @@+{+ "images": [+ {+ "filename": "ImagePlusIcon.svg",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ },+ "properties": {+ "preserves-vector-representation": true,+ "template-rendering-intent": "template"+ }+}diff --git a/apple/apps/ensu/Ensu/Assets.xcassets/ImagePlusIcon.imageset/ImagePlusIcon.svg b/apple/apps/ensu/Ensu/Assets.xcassets/ImagePlusIcon.imageset/ImagePlusIcon.svgnew file mode 100644index 0000000000..a57f8b844f--- /dev/null+++ b/apple/apps/ensu/Ensu/Assets.xcassets/ImagePlusIcon.imageset/ImagePlusIcon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"><path d="M21.5 18.5H18.5M18.5 18.5H15.5M18.5 18.5V15.5M18.5 18.5V21.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/><circle cx="7.5" cy="7.5" r="1.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"/><path d="M11.5 21.5C7.35301 21.4981 5.22972 21.4473 3.89124 20.1088C2.5 18.7176 2.5 16.4784 2.5 12C2.5 7.52168 2.5 5.2825 3.89124 3.89125C5.28249 2.5 7.52166 2.5 12 2.5C16.4783 2.5 18.7175 2.5 20.1088 3.89125C21.5 5.2825 21.5 7.52168 21.5 12" stroke="currentColor" stroke-linecap="round" stroke-width="2"/><path d="M13.0018 13.0616C10.1493 14.6467 7.70477 17.7414 5.41797 20.5" stroke="currentColor" stroke-linecap="round" stroke-width="2"/></svg>diff --git a/apple/apps/ensu/Ensu/Assets.xcassets/Mic02Icon.imageset/Mic02Icon.svg b/apple/apps/ensu/Ensu/Assets.xcassets/Mic02Icon.imageset/Mic02Icon.svgindex e8db49563a..5351bf4a5f 100644--- a/apple/apps/ensu/Ensu/Assets.xcassets/Mic02Icon.imageset/Mic02Icon.svg+++ b/apple/apps/ensu/Ensu/Assets.xcassets/Mic02Icon.imageset/Mic02Icon.svg@@ -1,4 +1,4 @@-<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">- <path d="M17 7V11C17 13.7614 14.7614 16 12 16C9.23858 16 7 13.7614 7 11V7C7 4.23858 9.23858 2 12 2C14.7614 2 17 4.23858 17 7Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" />- <path d="M20 11C20 15.4183 16.4183 19 12 19M12 19C7.58172 19 4 15.4183 4 11M12 19V22M12 22H15M12 22H9" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" />+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">+ <path d="M17 7V11C17 13.7614 14.7614 16 12 16C9.23858 16 7 13.7614 7 11V7C7 4.23858 9.23858 2 12 2C14.7614 2 17 4.23858 17 7Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />+ <path d="M20 11C20 15.4183 16.4183 19 12 19M12 19C7.58172 19 4 15.4183 4 11M12 19V22M12 22H15M12 22H9" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" /></svg>diff --git a/apple/apps/ensu/Ensu/Assets.xcassets/StopIcon.imageset/StopIcon.svg b/apple/apps/ensu/Ensu/Assets.xcassets/StopIcon.imageset/StopIcon.svgindex dc2bf00e8c..f1885b03ce 100644--- a/apple/apps/ensu/Ensu/Assets.xcassets/StopIcon.imageset/StopIcon.svg+++ b/apple/apps/ensu/Ensu/Assets.xcassets/StopIcon.imageset/StopIcon.svg@@ -1,3 +1,3 @@-<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M4 12C4 8.72077 4 7.08116 4.81382 5.91891C5.1149 5.48891 5.48891 5.1149 5.91891 4.81382C7.08116 4 8.72077 4 12 4C15.2792 4 16.9188 4 18.0811 4.81382C18.5111 5.1149 18.8851 5.48891 19.1862 5.91891C20 7.08116 20 8.72077 20 12C20 15.2792 20 16.9188 19.1862 18.0811C18.8851 18.5111 18.5111 18.8851 18.0811 19.1862C16.9188 20 15.2792 20 12 20C8.72077 20 7.08116 20 5.91891 19.1862C5.48891 18.8851 5.1149 18.5111 4.81382 18.0811C4 16.9188 4 15.2792 4 12Z" /></svg>diff --git a/apple/apps/ensu/Ensu/Chat/ChatSourcesView.swift b/apple/apps/ensu/Ensu/Chat/ChatSourcesView.swiftdeleted file mode 100644index 477338bc1c..0000000000--- a/apple/apps/ensu/Ensu/Chat/ChatSourcesView.swift+++ /dev/null@@ -1,116 +0,0 @@-import SwiftUI--struct ChatSourcesView: View {- @ObservedObject var viewModel: ChatViewModel- @ObservedObject private var knowledgeStore: KnowledgeStore- @ObservedObject private var notesStore: NotesStore- @Environment(\.dismiss) private var dismiss- @State private var showFolderPicker = false- @State private var folderDestination: ChatSourceDestination?-- init(viewModel: ChatViewModel) {- self.viewModel = viewModel- knowledgeStore = viewModel.knowledgeStore- notesStore = viewModel.notesStore- }-- var body: some View {- NavigationStack {- ScrollView {- VStack(alignment: .leading, spacing: EnsuSpacing.md) {- Text("Choose the sources Ensu can use for new replies in this chat.")- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.textPrimary)- Text(- "Earlier replies and citations stay in the conversation when a source is turned off. Choices are saved on this device."- )- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)-- if let error = viewModel.sourceSelectionError {- Text(error)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- CompactButton(text: "Try again") { viewModel.retryLoadingSources() }- .disabled(viewModel.isGenerating || viewModel.isSendPending)- } else if !viewModel.isSourceSelectionReady {- ProgressView("Loading sources…")- } else if !viewModel.canChangeSources {- Text("Sources can be changed after this response finishes.")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- }-- Text("Ensu Packs")- .font(EnsuTypography.large)- .padding(.top, EnsuSpacing.sm)- ForEach(knowledgeStore.packs) { pack in- KnowledgePackCard(- store: knowledgeStore, pack: pack,- selection: Binding(- get: { viewModel.sourceSelection.includesPack(pack.id) },- set: { viewModel.setPackEnabled(pack.id, enabled: $0) }),- controlsDisabled: !viewModel.canChangeSources,- onDownload: { viewModel.downloadPackForChat(pack.id) })- }- if knowledgeStore.packs.isEmpty {- Text("No packs are available.")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- }-- Text("Your Notes")- .font(EnsuTypography.large)- .padding(.top, EnsuSpacing.sm)- ForEach(notesStore.collections) { collection in- NoteCollectionCard(- store: notesStore, collection: collection,- selection: Binding(- get: {- viewModel.sourceSelection.includesCollection(collection.id)- },- set: { viewModel.setNotesFolderEnabled(collection.id, enabled: $0) }- ),- controlsDisabled: !viewModel.canChangeSources)- }- if notesStore.collections.isEmpty {- Text("Add a folder to use your notes in this chat.")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- }- CompactButton(text: "Add notes folder") {- folderDestination = viewModel.sourceDestination- showFolderPicker = true- }- .disabled(!viewModel.canChangeSources)- Text(- "Ensu reads and indexes markdown files in the selected folder. Source files are never modified."- )- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- if let error = notesStore.operationError {- Text(error)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- }- }- .padding(EnsuSpacing.lg)- }- .background(EnsuColor.backgroundBase)- .navigationTitle("Sources")- .navigationBarTitleDisplayMode(.inline)- .toolbar {- ToolbarItem(placement: .confirmationAction) {- Button("Done") { dismiss() }- }- }- }- .sheet(isPresented: $showFolderPicker) {- NotesFolderPicker { url in- if let destination = folderDestination {- viewModel.addNotesFolderForChat(url, destination: destination)- }- }- }- }-}diff --git a/apple/apps/ensu/Ensu/Chat/ChatView.swift b/apple/apps/ensu/Ensu/Chat/ChatView.swiftindex b4f69c36dc..a916c7b661 100644--- a/apple/apps/ensu/Ensu/Chat/ChatView.swift+++ b/apple/apps/ensu/Ensu/Chat/ChatView.swift@@ -8,7 +8,8 @@ struct ChatView: View {@StateObject private var viewState = ChatViewState()@StateObject private var keyboard = KeyboardObserver()- @State private var showSources = false+ @State private var showSourceIntroduction = false+ @AppStorage("ensu.sources.introductionSeen") private var sourceIntroductionSeen = false@State private var isInputFocused = falseprivate var editingMessage: RenderedChatMessage? {@@ -31,7 +32,19 @@ struct ChatView: View {&& !viewState.isDrawerOpen&& !viewState.didDismissKeyboard&& !viewState.showSettings- && !showSources+ && !showSourceIntroduction+ && sourceIntroductionSeen+ }++ private var canShowSourceIntroduction: Bool {+ !sourceIntroductionSeen && viewModel.isModelDownloaded && !viewModel.isDownloading+ && !viewModel.isGenerating && !viewModel.isChatUnsupported && !viewState.isDrawerOpen+ && !viewState.showSettings && !showSourceIntroduction+ && viewState.pendingWhatsNew == nil+ }++ private var isChatActive: Bool {+ scenePhase == .active && !viewState.showSettings && !showSourceIntroduction}private var overflowDialogPresented: Binding<Bool> {@@ -147,7 +160,6 @@ struct ChatView: View {.onChange(of: scenePhase) { newValue inviewModel.setAppForeground(newValue != .background)viewModel.notesStore.setForeground(newValue == .active)- viewModel.setChatActive(newValue == .active && !viewState.showSettings)if newValue == .active {viewModel.refreshModelDownloadInfo()} else {@@ -159,8 +171,9 @@ struct ChatView: View {.onAppear {viewModel.setAppForeground(scenePhase != .background)viewModel.notesStore.setForeground(scenePhase == .active)- viewModel.setChatActive(scenePhase == .active && !viewState.showSettings)+ viewModel.setChatActive(isChatActive)}+ .onChange(of: isChatActive) { viewModel.setChatActive($0) }.onDisappear { viewModel.setChatActive(false) }.onReceive(NotificationCenter.default.publisher(@@ -178,11 +191,18 @@ struct ChatView: View {})}- .sheet(isPresented: $showSources) {- ChatSourcesView(viewModel: viewModel)+ .sheet(isPresented: $showSourceIntroduction) {+ SourceIntroductionSheet(+ knowledgeStore: viewModel.knowledgeStore, notesStore: viewModel.notesStore)+ }+ .task(id: canShowSourceIntroduction) {+ if canShowSourceIntroduction {+ isInputFocused = false+ showSourceIntroduction = true+ sourceIntroductionSeen = true+ }}.onChange(of: viewState.showSettings) { isPresented in- viewModel.setChatActive(!isPresented && scenePhase == .active)if isPresented {viewState.didDismissKeyboard = trueisInputFocused = false@@ -367,7 +387,6 @@ struct ChatView: View {onCancelEdit: {viewModel.cancelEditing()},- onSources: { showSources = true },onVoiceInput: {viewState.didDismissKeyboard = trueisInputFocused = falsediff --git a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swiftindex ef397aaa5e..d0c5eff0a1 100644--- a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift+++ b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift@@ -41,13 +41,7 @@ final class ChatViewModel: ObservableObject {private let logger = EnsuLogging.shared.logger("ChatViewModel")@Published var sessions: [ChatSession]- @Published var currentSessionId: UUID? {- didSet { loadSourceSelection() }- }- @Published private(set) var sourceSelection = ChatSourceSelection()- @Published private(set) var isSourceSelectionReady = false- @Published private(set) var sourceSelectionError: String?- private let sourceSelections = ChatSourceSelectionStore()+ @Published var currentSessionId: UUID?@Published var messages: [RenderedChatMessage]@Published var streamingResponse: String = ""@Published var streamingParentId: UUID? = nil@@ -236,7 +230,6 @@ final class ChatViewModel: ObservableObject {}refreshDeviceCapability()refreshModelDownloadInfo()- loadSourceSelection()Task {async let knowledge: Void = knowledgeStore.bootstrap()async let notes: Void = notesStore.bootstrap()@@ -247,7 +240,10 @@ final class ChatViewModel: ObservableObject {func setChatActive(_ active: Bool) {guard chatActive != active else { return }chatActive = active- if !active { sessionSummaryTask?.cancel() }+ if !active {+ sessionSummaryTask?.cancel()+ cancelChatWarmup(releaseLoadedModel: false)+ }Task { await provider.setChatForeground(active) }if active {warmupSuppressed = false@@ -395,101 +391,17 @@ final class ChatViewModel: ObservableObject {return sessions.first { $0.id == currentSessionId }}- var canChangeSources: Bool { isSourceSelectionReady && !isGenerating && !isSendPending }-- var sourceDestination: ChatSourceDestination {- sourceSelections.destination(for: currentSessionId)- }-- private func initialSourceSelection() -> ChatSourceSelection {- ChatSourceSelection(+ private func currentSourceSelection() -> ChatSourceSelection? {+ guard knowledgeStore.inventoryReady && notesStore.inventoryReady else { return nil }+ return ChatSourceSelection(selectedPackIDs: Set(- knowledgeStore.packs.filter { $0.activeIdentity != nil }.map(\.id)),- selectedCollectionIDs: Set(notesStore.collections.map(\.id)))- }-- private func initializeSourceSelection(for sessionID: UUID?) -> ChatSourceSelection? {- sourceSelections.initialize(- for: sessionID, available: initialSourceSelection(),- inventoryReady: knowledgeStore.inventoryReady && notesStore.inventoryReady)- }-- private func loadSourceSelection() {- sourceSelectionError = nil- let saved = sourceSelections.selection(for: currentSessionId)- sourceSelection = saved ?? ChatSourceSelection()- isSourceSelectionReady = saved != nil- let destination = sourceDestination- Task { [weak self] in- guard let self else { return }- await knowledgeStore.bootstrap()- await notesStore.bootstrap()- guard sourceDestination == destination else { return }- if let selection = initializeSourceSelection(for: currentSessionId) {- sourceSelection = selection- isSourceSelectionReady = true- }- if !knowledgeStore.inventoryReady || !notesStore.inventoryReady {- sourceSelectionError = "Couldn’t load sources for this chat. Try again."- }- }- }-- func retryLoadingSources() {- guard !isGenerating && !isSendPending else { return }- sourceSelectionError = nil- Task {- await knowledgeStore.retryBootstrap()- await notesStore.retryBootstrap()- loadSourceSelection()- }- }-- func downloadPackForChat(_ id: String) {- guard canChangeSources else { return }- let destination = sourceDestination- let isNew = knowledgeStore.packs.first(where: { $0.id == id })?.activeIdentity == nil- knowledgeStore.downloadOrUpdate(stableId: id) { [weak self] in- guard isNew else { return }- self?.updateAddedSource(destination) { $0.setPack(id, enabled: true) }- }- }-- func addNotesFolderForChat(_ url: URL, destination: ChatSourceDestination) {- notesStore.add(url) { [weak self] id in- self?.updateAddedSource(destination) { $0.setCollection(id, enabled: true) }- }- }-- private func updateAddedSource(- _ destination: ChatSourceDestination, update: (inout ChatSourceSelection) -> Void- ) {- guard let destination = sourceSelections.resolve(destination) else { return }- let sessionID: UUID?- switch destination {- case .session(let id):- guard sessions.contains(where: { $0.id == id }) else { return }- sessionID = id- case .draft:- sessionID = nil- }- // The picker cannot start additions until this destination has a saved selection.- guard var selected = sourceSelections.selection(for: sessionID) else { return }- update(&selected)- sourceSelections.save(selected, for: sessionID)- if currentSessionId == sessionID { sourceSelection = selected }- }-- func setPackEnabled(_ id: String, enabled: Bool) {- guard canChangeSources else { return }- sourceSelection.setPack(id, enabled: enabled)- sourceSelections.save(sourceSelection, for: currentSessionId)- }-- func setNotesFolderEnabled(_ id: String, enabled: Bool) {- guard canChangeSources else { return }- sourceSelection.setCollection(id, enabled: enabled)- sourceSelections.save(sourceSelection, for: currentSessionId)+ knowledgeStore.packs.filter {+ $0.activeIdentity != nil && !knowledgeStore.disabledIDs.contains($0.id)+ }.map(\.id)),+ selectedCollectionIDs: Set(+ notesStore.collections+ .filter { !notesStore.disabledIDs.contains($0.id) }+ .map(\.id)))}var modelDownloadSizeText: String {@@ -529,7 +441,6 @@ final class ChatViewModel: ObservableObject {draftAttachments = []editingMessageId = nil- sourceSelections.remove(nil)currentSessionId = nilmessages = []}@@ -567,7 +478,6 @@ final class ChatViewModel: ObservableObject {try? FileManager.default.removeItem(at: attachmentsDir.appendingPathComponent(id))}sessionSummaries.removeValue(forKey: sessionSummaryKey(session.id))- sourceSelections.remove(session.id)persistSessionSummaries()sessions.removeAll { $0.id == session.id }@@ -839,6 +749,7 @@ final class ChatViewModel: ObservableObject {generationErrorMessage = ModelImagesUnsupported().localizedDescriptionreturn}+ let sourceSnapshot = currentSourceSelection()let sendId = UUID()pendingSendId = sendIdisSendPending = true@@ -856,11 +767,10 @@ final class ChatViewModel: ObservableObject {guard !Task.isCancelled, self.pendingSendId == sendId,currentSessionId == sessionIdelse { return }- // A failed inventory must not become a permanent empty selection.- // Chat can still proceed with the sources currently available.- let selectedSources = initializeSourceSelection(for: sessionId)- sourceSelection = selectedSources ?? initialSourceSelection()- isSourceSelectionReady = selectedSources != nil+ guard let sources = sourceSnapshot ?? currentSourceSelection() else {+ generationErrorMessage = "Couldn’t load sources. Try sending again."+ return+ }do {try await self.ensureChatModelReady(@@ -888,11 +798,15 @@ final class ChatViewModel: ObservableObject {else { return }let destination = sessionId ?? self.createSessionForDraft()self.sendDraftMessage(- trimmed: trimmed, attachments: attachments, sessionId: destination)+ trimmed: trimmed, attachments: attachments, sessionId: destination,+ sources: sources)}}- private func sendDraftMessage(trimmed: String, attachments: [ChatAttachment], sessionId: UUID) {+ private func sendDraftMessage(+ trimmed: String, attachments: [ChatAttachment], sessionId: UUID,+ sources: ChatSourceSelection+ ) {let parentId: UUID? = {if let editingId = editingMessageId {let existing = messageStore[sessionId]?.first { $0.id == editingId }@@ -953,7 +867,7 @@ final class ChatViewModel: ObservableObject {updateSessionPreview(sessionId: sessionId, preview: trimmed, date: timestamp)rebuildMessages(for: sessionId)- startGeneration(for: userNode)+ startGeneration(for: userNode, sources: sources)}func stopGenerating() {@@ -981,7 +895,7 @@ final class ChatViewModel: ObservableObject {overflowBypassMessageId = pendingOverflow.messageIdself.pendingOverflow = niloverflowAlert = nil- startGeneration(for: node)+ startGeneration(for: node, sources: pendingOverflow.sources)}func cancelOverflowDialog() {@@ -1244,6 +1158,7 @@ final class ChatViewModel: ObservableObject {userNode = messageStore[sessionId]?.first(where: { $0.id == parentId })}guard let userNode else { return }+ let sourceSnapshot = currentSourceSelection()cancelPendingSend()priorGeneration?.cancel()priorSummary?.cancel()@@ -1257,7 +1172,7 @@ final class ChatViewModel: ObservableObject {{await provider.resetContext()}- startGeneration(for: userNode)+ startGeneration(for: userNode, sources: sourceSnapshot)}}@@ -1294,7 +1209,6 @@ final class ChatViewModel: ObservableObject {id: sessionId, title: created?.title ?? "New chat", lastMessage: "",updatedAt: updatedAt)sessions.insert(session, at: 0)- sourceSelections.commitDraft(to: session.id)currentSessionId = session.idmessageStore[session.id] = []branchSelections[session.id] = [:]@@ -1302,7 +1216,9 @@ final class ChatViewModel: ObservableObject {return session.id}- private func startGeneration(for userNode: MessageNode) {+ private func startGeneration(+ for userNode: MessageNode, sources sourceSnapshot: ChatSourceSelection?+ ) {guard !isChatUnsupported else {showUnsupportedDeviceDialog = truereturn@@ -1340,8 +1256,6 @@ final class ChatViewModel: ObservableObject {rebuildMessages(for: userNode.sessionId)let notesScope = notesStore.suspendMaintenance()- // Keep this turn's sources stable across async preparation and chat switches.- let sourceSnapshot = sourceSelections.selection(for: userNode.sessionId)generationTask = Task { [self] indefer {notesScope.close()@@ -1355,9 +1269,10 @@ final class ChatViewModel: ObservableObject {await knowledgeStore.bootstrap()await notesStore.bootstrap()guard !Task.isCancelled, activeGenerationId == generationId else { return }- let sources =- sourceSnapshot ?? initializeSourceSelection(for: userNode.sessionId)- ?? initialSourceSelection()+ guard let sources = sourceSnapshot ?? currentSourceSelection() else {+ generationErrorMessage = "Couldn’t load sources. Try again."+ return+ }var embeddingAssetInvalid = falsevar knowledgeHits: [GroundedExcerpt] = []let enabledDatasets = knowledgeStore.readyDatasets.filter {@@ -1636,7 +1551,8 @@ final class ChatViewModel: ObservableObject {case let .overflow(inputTokens, inputBudget, limits):overflowBypassMessageId = nilpendingOverflow = PendingOverflow(- sessionId: userNode.sessionId, messageId: userNode.id)+ sessionId: userNode.sessionId, messageId: userNode.id,+ sources: sources)activeGenerationId = nilactiveGenerationSessionId = nilisGenerating = false@@ -2606,6 +2522,7 @@ final class ChatViewModel: ObservableObject {private struct PendingOverflow {let sessionId: UUIDlet messageId: UUID+ let sources: ChatSourceSelection}private func buildPrompt(text: String, attachments: [ChatAttachment]) -> PromptResult {diff --git a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift b/apple/apps/ensu/Ensu/Chat/MessageInputView.swiftindex 47f961c1cc..e765195ccd 100644--- a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift+++ b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift@@ -17,7 +17,6 @@ struct MessageInputView: View {let onSend: () -> Voidlet onStop: () -> Voidlet onCancelEdit: () -> Void- let onSources: () -> Voidlet onVoiceInput: () -> Voidlet onAddImage: (Data, String?) -> Voidlet onAddDocument: (URL) -> Void@@ -28,8 +27,9 @@ struct MessageInputView: View {@Binding var isFocused: Bool@State private var selectedPhotoItem: PhotosPickerItem?+ @State private var showPhotos = false- private let placeholder = "Write a message..."+ private let placeholder = "Ask Ensu"private var canSend: Bool {!isGenerating && isSendEnabled@@ -77,7 +77,7 @@ struct MessageInputView: View {attachmentFlowLayout}}- .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.horizontal, EnsuSpacing.sm)}if isProcessingAttachments {@@ -89,7 +89,7 @@ struct MessageInputView: View {.foregroundStyle(EnsuColor.textMuted)Spacer()}- .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.horizontal, EnsuSpacing.sm)}if let voiceStatus = voiceInputState.statusText {@@ -118,65 +118,39 @@ struct MessageInputView: View {? EnsuColor.stopButton : EnsuColor.textMuted)Spacer()}- .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.horizontal, EnsuSpacing.sm)}- HStack(alignment: .bottom, spacing: EnsuSpacing.sm) {- if editingMessage == nil && supportsImageAttachments {- let canUseAttachment =- !isGenerating && !isDownloading && !isImageAttachmentLimitReached- PhotosPicker(selection: $selectedPhotoItem, matching: .images) {- Image("Upload01Icon")- .resizable()- .scaledToFit()- .frame(width: attachmentIconSize, height: attachmentIconSize)- .frame(width: 32, height: 32, alignment: .center)+ HStack(alignment: .bottom, spacing: EnsuSpacing.xs) {+ ActionButton(+ icon: "ImagePlusIcon", tooltip: "Add photos",+ color: EnsuColor.textPrimary, size: 32+ ) {+ dismissInput()+ showPhotos = true+ }+ .disabled(+ editingMessage != nil || !supportsImageAttachments+ || isGenerating || isSendPending || isDownloading+ || isImageAttachmentLimitReached+ )+ .photosPicker(+ isPresented: $showPhotos, selection: $selectedPhotoItem,+ matching: .images+ )+ .onChange(of: selectedPhotoItem) { item in+ guard let item, !isImageAttachmentLimitReached else {+ selectedPhotoItem = nil; return}- .disabled(!canUseAttachment)- .foregroundStyle(- canUseAttachment ? EnsuColor.textPrimary : EnsuColor.textMuted- )- .simultaneousGesture(- TapGesture().onEnded {- if canUseAttachment {- hapticTap()- }- }- )- .onChange(of: selectedPhotoItem) { newItem in- guard let newItem else { return }- guard !isImageAttachmentLimitReached else {+ Task {+ let data = try? await item.loadTransferable(type: Data.self)+ await MainActor.run {+ if let data { onAddImage(data, nil) }selectedPhotoItem = nil- return- }- Task {- let data = try? await newItem.loadTransferable(type: Data.self)- await MainActor.run {- if let data {- onAddImage(data, nil)- }- selectedPhotoItem = nil- }}}}- Button {- hapticTap()- isFocused = false- hideKeyboard()- onDismissKeyboard()- onSources()- } label: {- Image("PackageIcon")- .resizable()- .scaledToFit()- .frame(width: attachmentIconSize, height: attachmentIconSize)- .foregroundStyle(EnsuColor.textPrimary)- .frame(width: 32, height: 32)- }- .accessibilityLabel("Sources for this chat")-MessageTextView(text: $text,isFocused: $isFocused,@@ -233,17 +207,15 @@ struct MessageInputView: View {.resizable().scaledToFit().frame(- width: attachmentIconSize, height: attachmentIconSize+ width: composerIconSize, height: composerIconSize)- .foregroundStyle(EnsuColor.stopButton)+ .foregroundStyle(EnsuColor.sendButton).frame(width: 32, height: 32)} else {Image("Mic02Icon").resizable().scaledToFit()- .frame(- width: attachmentIconSize, height: attachmentIconSize- )+ .frame(width: composerIconSize, height: composerIconSize).foregroundStyle(canUseVoice? EnsuColor.textPrimary : EnsuColor.textMuted@@ -252,6 +224,7 @@ struct MessageInputView: View {}}.disabled(!canUseVoice)+ .padding(.leading, EnsuSpacing.xs)}Button {@@ -266,37 +239,19 @@ struct MessageInputView: View {onDismissKeyboard()}} label: {- if sendIcon == "StopIcon" {- ZStack {- Circle()- .fill(Color.white)- .frame(- width: attachmentIconSize + 6,- height: attachmentIconSize + 6)- Image(sendIcon)- .resizable()- .scaledToFit()- .frame(- width: attachmentIconSize - 4,- height: attachmentIconSize - 4- )- .foregroundStyle(EnsuColor.stopButton)- }+ Image(sendIcon)+ .resizable()+ .scaledToFit()+ .frame(width: composerIconSize, height: composerIconSize)+ .rotationEffect(+ sendIcon == "Navigation06Icon" ? .degrees(90) : .zero+ )+ .foregroundStyle(sendColor).frame(width: 32, height: 32)- } else {- Image(sendIcon)- .resizable()- .scaledToFit()- .frame(width: attachmentIconSize, height: attachmentIconSize)- .rotationEffect(- sendIcon == "Navigation06Icon" ? .degrees(90) : .zero- )- .foregroundStyle(sendColor)- .frame(width: 32, height: 32)- }}.accessibilityLabel(isGenerating ? "Stop response" : "Send message").disabled(isDownloading || (!canSend && !isGenerating))+ .padding(.leading, EnsuSpacing.xs)}.padding(.horizontal, EnsuSpacing.inputHorizontal).padding(.vertical, inputVerticalPadding)@@ -326,7 +281,7 @@ struct MessageInputView: View {.offset(y: -(32 + EnsuSpacing.sm))}}- .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.horizontal, EnsuSpacing.sm).padding(.bottom, bottomPadding)}.frame(maxWidth: .infinity, alignment: .leading)@@ -341,7 +296,12 @@ struct MessageInputView: View {.padding(.top, EnsuSpacing.sm)}- private let attachmentIconSize: CGFloat = 16+ private let composerIconSize: CGFloat = 16+ private func dismissInput() {+ isFocused = false+ hideKeyboard()+ onDismissKeyboard()+ }private var keyboardDismissIconName: String {UIImage(systemName: "keyboard.chevron.compact.down") != nil@@ -386,9 +346,9 @@ struct MessageInputView: View {private var sendColor: Color {if isGenerating {- return EnsuColor.stopButton+ return EnsuColor.sendButton}- return isSendEnabled ? EnsuColor.textPrimary : EnsuColor.textMuted+ return isSendEnabled ? EnsuColor.sendButton : EnsuColor.sendButtonInactive}private func editBanner(for message: RenderedChatMessage) -> some View {@@ -434,7 +394,7 @@ struct MessageInputView: View {.frame(width: 3),alignment: .leading)- .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.horizontal, EnsuSpacing.sm)}}diff --git a/apple/apps/ensu/Ensu/Chat/MessageTextView.swift b/apple/apps/ensu/Ensu/Chat/MessageTextView.swiftindex ae1ff39f35..f1e9790a83 100644--- a/apple/apps/ensu/Ensu/Chat/MessageTextView.swift+++ b/apple/apps/ensu/Ensu/Chat/MessageTextView.swift@@ -25,7 +25,7 @@ struct MessageTextView: UIViewRepresentable {view.isScrollEnabled = trueview.alwaysBounceVertical = falseview.autocapitalizationType = .sentences- view.accessibilityLabel = "Write a message..."+ view.accessibilityLabel = "Ask Ensu"view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)return view}diff --git a/apple/apps/ensu/Ensu/Chat/SourceIntroductionSheet.swift b/apple/apps/ensu/Ensu/Chat/SourceIntroductionSheet.swiftnew file mode 100644index 0000000000..62fe9a1c30--- /dev/null+++ b/apple/apps/ensu/Ensu/Chat/SourceIntroductionSheet.swift@@ -0,0 +1,80 @@+import SwiftUI++private enum SourceSetupScreen: Hashable {+ case packs, notes+}++struct SourceIntroductionSheet: View {+ let knowledgeStore: KnowledgeStore+ let notesStore: NotesStore+ @Environment(\.dismiss) private var dismiss+ @State private var setupPath: [SourceSetupScreen] = []++ var body: some View {+ NavigationStack(path: $setupPath) {+ introduction+ .toolbar {+ if !setupPath.isEmpty {+ ToolbarItem(placement: .confirmationAction) {+ Button("Done") { dismiss() }+ }+ }+ }+ .navigationDestination(for: SourceSetupScreen.self) { screen in+ switch screen {+ case .packs:+ KnowledgeSettingsView(store: knowledgeStore)+ case .notes:+ NotesSettingsView(store: notesStore, allowsRemoval: false)+ }+ }+ }+ .presentationDetents([.large])+ .presentationDragIndicator(.visible)+ }++ private var introduction: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: EnsuSpacing.lg) {+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ Text("Give Ensu more context").font(EnsuTypography.h3)+ Text("Add a knowledge pack or your notes to help Ensu answer accurately.")+ .font(EnsuTypography.body).foregroundStyle(EnsuColor.textMuted)+ }+ VStack(spacing: EnsuSpacing.md) {+ EnsuCard {+ Text("Ensu Packs").font(EnsuTypography.large)+ Text("Knowledge from Wikipedia to help Ensu get factual questions right.")+ .font(EnsuTypography.small).foregroundStyle(EnsuColor.textMuted)+ CompactButton(text: "Set up", prominent: true) { setupPath.append(.packs) }+ .accessibilityLabel("Set up Ensu Packs")+ }+ EnsuCard {+ Text("Your Notes").font(EnsuTypography.large)+ Text(+ "Use a local Markdown notes folder to chat with your own knowledge base."+ )+ .font(EnsuTypography.small).foregroundStyle(EnsuColor.textMuted)+ CompactButton(text: "Set up", prominent: true) { setupPath.append(.notes) }+ .accessibilityLabel("Set up Your Notes")+ }+ }+ VStack(spacing: EnsuSpacing.xs) {+ TextActionButton(+ text: "Not now", underlined: true, color: EnsuColor.textPrimary+ ) {+ dismiss()+ }+ Text("You can set up Ensu Packs and Your Notes later from Settings.")+ .font(EnsuTypography.mini.weight(.regular))+ .foregroundStyle(EnsuColor.textMuted)+ .multilineTextAlignment(.center)+ }+ .frame(maxWidth: .infinity)+ }+ .foregroundStyle(EnsuColor.textPrimary)+ .padding(EnsuSpacing.lg)+ }+ .background(EnsuColor.backgroundBase)+ }+}diff --git a/apple/apps/ensu/Ensu/Components/EnsuComponents.swift b/apple/apps/ensu/Ensu/Components/EnsuComponents.swiftindex ed253b45a5..e3feaba9af 100644--- a/apple/apps/ensu/Ensu/Components/EnsuComponents.swift+++ b/apple/apps/ensu/Ensu/Components/EnsuComponents.swift@@ -42,16 +42,19 @@ struct AttributionSheet<Content: View>: View {struct CompactButton: View {let text: String+ var prominent = falselet action: () -> Voidvar body: some View {Button(action: action) {Text(text)- .font(EnsuTypography.small)- .padding(.horizontal, EnsuSpacing.xs)+ .font(prominent ? EnsuTypography.body.weight(.semibold) : EnsuTypography.small)+ .foregroundColor(prominent ? .black : nil)+ .padding(.horizontal, prominent ? EnsuSpacing.sm : EnsuSpacing.xs)+ .frame(minHeight: prominent ? EnsuSpacing.xxl : nil)}.buttonStyle(.borderedProminent)- .controlSize(.small)+ .controlSize(prominent ? .large : .small).tint(EnsuColor.accent)}}@@ -147,6 +150,8 @@ struct ActionButton: View {struct TextActionButton: View {let text: String+ var underlined = false+ var color = EnsuColor.textMutedlet action: () -> Void@Environment(\.isEnabled) private var isEnabled@@ -158,7 +163,8 @@ struct TextActionButton: View {}) {Text(text).font(EnsuTypography.small)- .foregroundStyle(isEnabled ? EnsuColor.textMuted : EnsuColor.textMuted.opacity(0.4))+ .underline(underlined)+ .foregroundStyle(isEnabled ? color : color.opacity(0.4)).padding(.horizontal, 4).frame(height: 36)}diff --git a/apple/apps/ensu/Ensu/DesignSystem/EnsuTheme.swift b/apple/apps/ensu/Ensu/DesignSystem/EnsuTheme.swiftindex c4f647a432..17c7330db3 100644--- a/apple/apps/ensu/Ensu/DesignSystem/EnsuTheme.swift+++ b/apple/apps/ensu/Ensu/DesignSystem/EnsuTheme.swift@@ -15,6 +15,8 @@ enum EnsuColor {static let error = Color(hex: "#FF4444")static let success = Color(hex: "#4CAF50")static let stopButton = Color(hex: "#FF0000")+ static let sendButton = Color(hex: "#E66A28")+ static let sendButtonInactive = sendButton.opacity(0.45)static let toastBackground = Color(PlatformColor.dynamic(light: "#1A1A1A", dark: "#F8F5F0"))static let toastText = Color(PlatformColor.dynamic(light: "#F8F5F0", dark: "#1A1A1A"))diff --git a/apple/apps/ensu/Ensu/Services/ChatSourceSelection.swift b/apple/apps/ensu/Ensu/Services/ChatSourceSelection.swiftindex 9934fd9cdf..a2b49145b9 100644--- a/apple/apps/ensu/Ensu/Services/ChatSourceSelection.swift+++ b/apple/apps/ensu/Ensu/Services/ChatSourceSelection.swift@@ -1,86 +1,9 @@import Foundation-/// Explicit stable IDs preserve a chat's choices when sources are added later.-struct ChatSourceSelection: Codable, Equatable, Sendable {+struct ChatSourceSelection: Sendable {var selectedPackIDs: Set<String> = []var selectedCollectionIDs: Set<String> = []func includesPack(_ id: String) -> Bool { selectedPackIDs.contains(id) }func includesCollection(_ id: String) -> Bool { selectedCollectionIDs.contains(id) }-- mutating func setPack(_ id: String, enabled: Bool) {- if enabled { selectedPackIDs.insert(id) } else { selectedPackIDs.remove(id) }- }-- mutating func setCollection(_ id: String, enabled: Bool) {- if enabled { selectedCollectionIDs.insert(id) } else { selectedCollectionIDs.remove(id) }- }-}--enum ChatSourceDestination: Equatable {- case session(UUID)- case draft(UUID)-}--/// Source choices are local because notes folders and downloaded packs belong to this device.-final class ChatSourceSelectionStore {- private let defaults: UserDefaults- private let prefix = "ensu.chat_sources."- private var draftID = UUID()- private var committedDrafts: [UUID: UUID] = [:]-- init(defaults: UserDefaults = .standard) {- self.defaults = defaults- }-- func selection(for sessionID: UUID?) -> ChatSourceSelection? {- guard let data = defaults.data(forKey: key(sessionID)),- let selection = try? JSONDecoder().decode(ChatSourceSelection.self, from: data)- else { return nil }- return selection- }-- func save(_ selection: ChatSourceSelection, for sessionID: UUID?) {- guard let data = try? JSONEncoder().encode(selection) else { return }- defaults.set(data, forKey: key(sessionID))- }-- func initialize(- for sessionID: UUID?, available: ChatSourceSelection, inventoryReady: Bool = true- ) -> ChatSourceSelection? {- if let saved = selection(for: sessionID) { return saved }- guard inventoryReady else { return nil }- save(available, for: sessionID)- return available- }-- func commitDraft(to sessionID: UUID) {- if let draft = selection(for: nil) { save(draft, for: sessionID) }- committedDrafts[draftID] = sessionID- remove(nil)- }-- func remove(_ sessionID: UUID?) {- defaults.removeObject(forKey: key(sessionID))- if sessionID == nil { draftID = UUID() }- }-- func destination(for sessionID: UUID?) -> ChatSourceDestination {- sessionID.map(ChatSourceDestination.session) ?? .draft(draftID)- }-- /// An async add must follow its original draft into the chat created from it.- func resolve(_ destination: ChatSourceDestination) -> ChatSourceDestination? {- switch destination {- case .session:- return destination- case .draft(let id):- if let committed = committedDrafts[id] { return .session(committed) }- return id == draftID ? destination : nil- }- }-- private func key(_ sessionID: UUID?) -> String {- prefix + (sessionID?.uuidString.lowercased() ?? "draft")- }}diff --git a/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift b/apple/apps/ensu/Ensu/Services/KnowledgeStore.swiftindex 31d6fd79f4..44e7b44f18 100644--- a/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift+++ b/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift@@ -4,19 +4,31 @@ import SwiftUI@MainActorfinal class KnowledgeStore: ObservableObject {@Published private(set) var packs: [KnowledgePackState]+ @Published private(set) var disabledIDs: Set<String>@Published var downloadsAllowed = false++ func setEnabled(_ id: String, enabled: Bool) {+ preferences.setDatasetEnabled(id: id, enabled: enabled)+ disabledIDs = preferences.disabledDatasetIds+ }+private(set) var inventoryReady = falseprivate let provider: KnowledgeProvider+ private let preferences: KnowledgePreferencesprivate var bootstrapTask: Task<Void, Never>?private var mutationTasks: [String: Task<Void, Never>] = [:]init(datasets: [KnowledgeDatasetConfig],- provider: KnowledgeProvider+ provider: KnowledgeProvider,+ defaults: UserDefaults = .standard) {packs = datasets.map { KnowledgePackState(config: $0) }self.provider = provider+ preferences = KnowledgePreferences(defaults: defaults)+ disabledIDs = preferences.migratePackSettings(+ availablePackIDs: Set(datasets.map(\.stableId)))}var readyDatasets: [KnowledgeDatasetConfig] {@@ -41,6 +53,7 @@ final class KnowledgeStore: ObservableObject {}bootstrapTask = taskawait task.value+ if !inventoryReady { bootstrapTask = nil }}private func bootstrapDatasets() async {@@ -60,14 +73,7 @@ final class KnowledgeStore: ObservableObject {inventoryReady = !failed}- func retryBootstrap() async {- await bootstrapTask?.value- guard !inventoryReady else { return }- bootstrapTask = nil- await bootstrap()- }-- func downloadOrUpdate(stableId: String, onInstalled: (() -> Void)? = nil) {+ func downloadOrUpdate(stableId: String) {guard downloadsAllowed,mutationTasks[stableId] == nil,let index = packs.firstIndex(where: { $0.id == stableId })@@ -75,6 +81,7 @@ final class KnowledgeStore: ObservableObject {return}let dataset = packs[index].config+ let wasInstalled = packs[index].activeIdentity != nilupdatePack(stableId) { pack inpack.isMutating = truepack.progressPercent = 0@@ -94,7 +101,9 @@ final class KnowledgeStore: ObservableObject {}}applyReconciliation(result, stableId: stableId)- if result.activeIdentity != nil { onInstalled?() }+ if result.activeIdentity != nil {+ if !wasInstalled { setEnabled(stableId, enabled: true) }+ }} catch {if let result = try? await provider.reconcile(dataset: dataset) {applyReconciliation(result, stableId: stableId)@@ -189,3 +198,40 @@ struct KnowledgePackState: Identifiable, Sendable {var progressLabel: String?var errorMessage: String?}++final class KnowledgePreferences {+ private enum Keys {+ static let enabledDatasetIds = "ensu.knowledge.enabled_dataset_ids"+ static let disabledDatasetIds = "ensu.packs.disabledByDefault"+ }++ private let defaults: UserDefaults++ init(defaults: UserDefaults) {+ self.defaults = defaults+ }++ var disabledDatasetIds: Set<String> {+ Set(defaults.stringArray(forKey: Keys.disabledDatasetIds) ?? [])+ }++ func migratePackSettings(availablePackIDs: Set<String>) -> Set<String> {+ if defaults.stringArray(forKey: Keys.disabledDatasetIds) != nil {+ return disabledDatasetIds+ }+ let legacy = defaults.stringArray(forKey: Keys.enabledDatasetIds).map(Set.init)+ let disabled = legacy.map { availablePackIDs.subtracting($0) } ?? []+ defaults.set(disabled.sorted(), forKey: Keys.disabledDatasetIds)+ return disabled+ }++ func setDatasetEnabled(id: String, enabled: Bool) {+ var ids = disabledDatasetIds+ if enabled {+ ids.remove(id)+ } else {+ ids.insert(id)+ }+ defaults.set(ids.sorted(), forKey: Keys.disabledDatasetIds)+ }+}diff --git a/apple/apps/ensu/Ensu/Services/LlmProvider.swift b/apple/apps/ensu/Ensu/Services/LlmProvider.swiftindex 15f6695506..2c308bd5e7 100644--- a/apple/apps/ensu/Ensu/Services/LlmProvider.swift+++ b/apple/apps/ensu/Ensu/Services/LlmProvider.swift@@ -138,8 +138,14 @@ actor LlmProvider {return llmHasRequiredWorkReserve(availableBytes: headroom)}- func setChatForeground(_ active: Bool) {+ func setChatForeground(_ active: Bool) async {chatForeground = active+ if !active {+ try? await modelLoadGate.withLock {+ guard !chatForeground else { return }+ unloadModel()+ }+ }}func setAppForeground(_ active: Bool) async {diff --git a/apple/apps/ensu/Ensu/Services/NotesStore.swift b/apple/apps/ensu/Ensu/Services/NotesStore.swiftindex 490805dffd..6134c52a58 100644--- a/apple/apps/ensu/Ensu/Services/NotesStore.swift+++ b/apple/apps/ensu/Ensu/Services/NotesStore.swift@@ -25,6 +25,9 @@ final class NotesStore: ObservableObject, ModelMaintenance {@Published private(set) var collections: [NoteCollectionState] = []@Published var operationError: String?@Published var preview: NotesPreview?+ @Published private(set) var disabledIDs: Set<String>+ private let sourceDefaults: UserDefaults+ private static let disabledDefaultsKey = "ensu.notes.disabledByDefault"private struct Pending {let generation: UInt64@@ -53,22 +56,23 @@ final class NotesStore: ObservableObject, ModelMaintenance {private var wake: Task<Void, Never>?private static let emptyNotes = "No supported non-empty UTF-8 notes were found"- init(provider: LlmProvider, notesProvider: NotesProvider = NotesProvider()) {+ init(+ provider: LlmProvider, notesProvider: NotesProvider = NotesProvider(),+ defaults: UserDefaults = .standard+ ) {+ sourceDefaults = defaults+ disabledIDs = Set(defaults.stringArray(forKey: Self.disabledDefaultsKey) ?? [])modelProvider = providerself.provider = notesProvider}- var inventoryReady: Bool { loaded }-- func retryBootstrap() async {- await bootstrapTask?.value- guard !loaded else { return }- disabled = false- operationError = nil- bootstrapTask = nil- await bootstrap()+ func setEnabled(_ id: String, enabled: Bool) {+ if enabled { disabledIDs.remove(id) } else { disabledIDs.insert(id) }+ sourceDefaults.set(Array(disabledIDs), forKey: Self.disabledDefaultsKey)}+ var inventoryReady: Bool { loaded }+func bootstrap() async {if let bootstrapTask {await bootstrapTask.value@@ -95,6 +99,8 @@ final class NotesStore: ObservableObject, ModelMaintenance {}}loaded = true+ disabled = false+ operationError = nilscans.formUnion(records.map(\.id))pump()} catch {@@ -104,6 +110,7 @@ final class NotesStore: ObservableObject, ModelMaintenance {}bootstrapTask = taskawait task.value+ if !loaded { bootstrapTask = nil }}func setForeground(_ value: Bool) {@@ -137,17 +144,19 @@ final class NotesStore: ObservableObject, ModelMaintenance {await active?.task.value}- func add(_ url: URL, onAdded: ((String) -> Void)? = nil) {+ func add(_ url: URL) {Task {await bootstrap()guard !disabled else { return }do {try await withMaintenanceSuspended {let record = try await provider.add(url)- collections.append(NoteCollectionState(id: record.id, label: record.label))+ if !collections.contains(where: { $0.id == record.id }) {+ setEnabled(record.id, enabled: true)+ collections.append(NoteCollectionState(id: record.id, label: record.label))+ }operationError = nilenqueue(record.id, due: .distantPast)- onAdded?(record.id)}} catch {operationError = Self.message(error)diff --git a/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift b/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swiftindex 79545c16c7..f9db0245ed 100644--- a/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift+++ b/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift@@ -2,34 +2,31 @@ import SwiftUIstruct KnowledgeSettingsView: View {@ObservedObject var store: KnowledgeStore+ @State private var attributionPack: KnowledgePackState?var body: some View {ScrollView {VStack(alignment: .leading, spacing: EnsuSpacing.md) {+ Text(+ "Choose packs for future messages in all chats. Existing answers stay unchanged."+ )+ .font(EnsuTypography.small).foregroundStyle(EnsuColor.textMuted)ForEach(store.packs) { pack in- KnowledgePackCard(store: store, pack: pack)+ packCard(pack)}- Text("Choose sources for each chat using Sources in the message composer.")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)}.padding(EnsuSpacing.lg)}.background(EnsuColor.backgroundBase).navigationTitle("Ensu Packs").navigationBarTitleDisplayMode(.inline)+ .sheet(item: $attributionPack) { pack in+ PackAttributionSheet(config: pack.config)+ }}-}--struct KnowledgePackCard: View {- @ObservedObject var store: KnowledgeStore- let pack: KnowledgePackState- var selection: Binding<Bool>? = nil- var controlsDisabled = false- var onDownload: (() -> Void)? = nil- @State private var showAttribution = false- var body: some View {+ @ViewBuilder+ private func packCard(_ pack: KnowledgePackState) -> some View {let attribution = pack.config.attributionEnsuCard {HStack {@@ -45,7 +42,7 @@ struct KnowledgePackCard: View {.font(EnsuTypography.mini).foregroundStyle(EnsuColor.textMuted)Button {- showAttribution = true+ attributionPack = pack} label: {HStack(spacing: EnsuSpacing.xs) {Text(attribution.licenseLabel)@@ -60,18 +57,23 @@ struct KnowledgePackCard: View {}}Spacer()- if pack.activeIdentity != nil, let selection {- Toggle("Use \(pack.config.label) in this chat", isOn: selection)- .labelsHidden()- .tint(EnsuColor.accent)- .disabled(controlsDisabled || pack.isMutating)+ if pack.activeIdentity != nil {+ Toggle(+ "Use \(pack.config.label) for future messages",+ isOn: Binding(+ get: { !store.disabledIDs.contains(pack.id) },+ set: {+ store.setEnabled(pack.id, enabled: $0)+ })+ )+ .labelsHidden()+ .tint(EnsuColor.accent)+ .disabled(pack.isMutating)} else if store.downloadsAllowed && pack.status == .download && !pack.isMutating {CompactButton(text: "Download") {- download()+ store.downloadOrUpdate(stableId: pack.id)}- .disabled(controlsDisabled)}-}if pack.isMutating {@@ -93,12 +95,9 @@ struct KnowledgePackCard: View {.accessibilityLabel("Cancel download")}} else if store.downloadsAllowed && pack.status == .updateAvailable {- CompactButton(text: "Update") { download() }- .disabled(controlsDisabled)- } else if pack.activeIdentity != nil && selection == nil {- Text("Downloaded")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)+ CompactButton(text: "Update") {+ store.downloadOrUpdate(stableId: pack.id)+ }}if pack.isMutating, let progress = pack.progressLabel {@@ -113,13 +112,6 @@ struct KnowledgePackCard: View {.foregroundStyle(EnsuColor.error)}}- .sheet(isPresented: $showAttribution) {- PackAttributionSheet(config: pack.config)- }- }-- private func download() {- if let onDownload { onDownload() } else { store.downloadOrUpdate(stableId: pack.id) }}}diff --git a/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swift b/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swiftindex e9317e4100..91f3d8af72 100644--- a/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swift+++ b/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swift@@ -4,18 +4,78 @@ import QuickLookstruct NotesSettingsView: View {@ObservedObject var store: NotesStore+ var allowsRemoval = true@State private var showPicker = false@State private var removing: NoteCollectionState?var body: some View {ScrollView {VStack(alignment: .leading, spacing: EnsuSpacing.md) {+ Text(+ "Choose notes for future messages in all chats. Existing answers stay unchanged."+ )+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)ForEach(store.collections) { collection in- NoteCollectionCard(- store: store, collection: collection,- onRemove: {- removing = collection- })+ EnsuCard {+ HStack {+ VStack(alignment: .leading, spacing: EnsuSpacing.xs) {+ Text(collection.label)+ .font(EnsuTypography.large)+ .foregroundStyle(EnsuColor.textPrimary)+ .fixedSize(horizontal: false, vertical: true)+ Text(summary(collection))+ .font(EnsuTypography.mini)+ .foregroundStyle(EnsuColor.textMuted)+ .fixedSize(horizontal: false, vertical: true)+ }+ Spacer()+ Toggle(+ "Use \(collection.label) for future messages",+ isOn: Binding(+ get: { !store.disabledIDs.contains(collection.id) },+ set: {+ store.setEnabled(collection.id, enabled: $0)+ })+ )+ .labelsHidden()+ .tint(EnsuColor.accent)+ if allowsRemoval {+ ActionButton(+ icon: "Delete01Icon", tooltip: "Remove \(collection.label)",+ size: 44+ ) {+ removing = collection+ }+ }+ }+ if let progress = collection.progress {+ HStack(spacing: EnsuSpacing.sm) {+ ProgressView(value: Double(progress), total: 100)+ .tint(EnsuColor.action)+ Text("\(progress)%")+ .font(EnsuTypography.mini)+ .foregroundStyle(EnsuColor.textMuted)+ }+ } else if collection.status == .indexing || collection.status == .updating {+ ProgressView().tint(EnsuColor.action)+ }+ if collection.status == .pending {+ Text("Indexing will continue when the app and model are ready.")+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)+ }+ if let error = collection.error {+ Text(error)+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.error)+ }+ if collection.status == .error || collection.status == .unavailable {+ CompactButton(text: "Retry") {+ store.retry(collection.id)+ }+ }+ }}CompactButton(text: "Add notes folder") {showPicker = true@@ -36,13 +96,17 @@ struct NotesSettingsView: View {.background(EnsuColor.backgroundBase).navigationTitle("Your Notes").navigationBarTitleDisplayMode(.inline)- .sheet(isPresented: $showPicker) { NotesFolderPicker { store.add($0) } }+ .sheet(isPresented: $showPicker) {+ NotesFolderPicker { url in+ store.add(url)+ }+ }.alert("Remove folder?",isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } })) {Button("Remove", role: .destructive) {- if let collection = removing { store.remove(collection.id) }+ if allowsRemoval, let collection = removing { store.remove(collection.id) }removing = nil}Button("Cancel", role: .cancel) { removing = nil }@@ -51,71 +115,6 @@ struct NotesSettingsView: View {}}-}--struct NoteCollectionCard: View {- @ObservedObject var store: NotesStore- let collection: NoteCollectionState- var selection: Binding<Bool>? = nil- var controlsDisabled = false- var onRemove: (() -> Void)? = nil-- var body: some View {- EnsuCard {- HStack {- VStack(alignment: .leading, spacing: EnsuSpacing.xs) {- Text(collection.label)- .font(EnsuTypography.large)- .foregroundStyle(EnsuColor.textPrimary)- .fixedSize(horizontal: false, vertical: true)- Text(summary(collection))- .font(EnsuTypography.mini)- .foregroundStyle(EnsuColor.textMuted)- .fixedSize(horizontal: false, vertical: true)- }- Spacer()- if let selection {- Toggle("Use \(collection.label) in this chat", isOn: selection)- .labelsHidden()- .tint(EnsuColor.accent)- .disabled(controlsDisabled)- }- if let onRemove {- ActionButton(- icon: "Delete01Icon", tooltip: "Remove \(collection.label)",- size: 44, action: onRemove)- }- }- if let progress = collection.progress {- HStack(spacing: EnsuSpacing.sm) {- ProgressView(value: Double(progress), total: 100)- .tint(EnsuColor.action)- Text("\(progress)%")- .font(EnsuTypography.mini)- .foregroundStyle(EnsuColor.textMuted)- }- } else if collection.status == .indexing || collection.status == .updating {- ProgressView().tint(EnsuColor.action)- }- if collection.status == .pending {- Text("Indexing will continue when the app and model are ready.")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- }- if let error = collection.error {- Text(error)- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.error)- }- if collection.status == .error || collection.status == .unavailable {- CompactButton(text: "Retry") {- store.retry(collection.id)- }- .disabled(controlsDisabled)- }- }- }-private func summary(_ collection: NoteCollectionState) -> String {let count = collection.documentCountlet indexing = collection.status == .indexing || collection.status == .updating@@ -130,7 +129,7 @@ struct NoteCollectionCard: View {}}-struct NotesFolderPicker: UIViewControllerRepresentable {+private struct NotesFolderPicker: UIViewControllerRepresentable {let selected: (URL) -> Voidfunc makeCoordinator() -> Coordinator { Coordinator(selected: selected) }func makeUIViewController(context: Context) -> UIDocumentPickerViewController {diff --git a/apple/apps/ensu/EnsuTests/ChatSourceSelectionTests.swift b/apple/apps/ensu/EnsuTests/ChatSourceSelectionTests.swiftdeleted file mode 100644index af41e65a75..0000000000--- a/apple/apps/ensu/EnsuTests/ChatSourceSelectionTests.swift+++ /dev/null@@ -1,114 +0,0 @@-import XCTest-@testable import Ensu--final class ChatSourceSelectionTests: XCTestCase {- private var suite: String!- private var defaults: UserDefaults!- private var store: ChatSourceSelectionStore!-- override func setUp() {- super.setUp()- suite = "ChatSourceSelectionTests.\(UUID().uuidString)"- defaults = UserDefaults(suiteName: suite)!- store = ChatSourceSelectionStore(defaults: defaults)- }-- override func tearDown() {- defaults.removePersistentDomain(forName: suite)- store = nil- defaults = nil- super.tearDown()- }-- func testNewChatStartsWithAllCurrentSourcesAndDoesNotPickUpLaterAdditions() {- let chat = UUID()- let original = ChatSourceSelection(- selectedPackIDs: ["pack-a"], selectedCollectionIDs: ["notes-a"])- XCTAssertEqual(store.initialize(for: chat, available: original), original)-- let expanded = ChatSourceSelection(- selectedPackIDs: ["pack-a", "pack-b"], selectedCollectionIDs: ["notes-a", "notes-b"])- XCTAssertEqual(store.initialize(for: chat, available: expanded), original)- XCTAssertEqual(store.initialize(for: UUID(), available: expanded), expanded)- }-- func testAllOffPersistsAcrossRelaunchAndIsIndependentOfOtherChats() throws {- let chat = UUID()- let other = UUID()- store.save(ChatSourceSelection(), for: chat)- let selected = ChatSourceSelection(- selectedPackIDs: ["pack"], selectedCollectionIDs: ["folder"])- store.save(selected, for: other)-- let restored = ChatSourceSelectionStore(defaults: defaults)- XCTAssertEqual(restored.initialize(for: chat, available: selected), ChatSourceSelection())- XCTAssertEqual(try XCTUnwrap(restored.selection(for: other)), selected)- }-- func testFailedInventoryDoesNotPersistIncompleteDefaultsOrReplaceSavedChoices() {- let chat = UUID()- XCTAssertNil(- store.initialize(for: chat, available: ChatSourceSelection(), inventoryReady: false))- XCTAssertNil(store.selection(for: chat))-- let complete = ChatSourceSelection(- selectedPackIDs: ["pack"], selectedCollectionIDs: ["folder"])- XCTAssertEqual(store.initialize(for: chat, available: complete), complete)- XCTAssertEqual(- store.initialize(for: chat, available: ChatSourceSelection(), inventoryReady: false),- complete)- }-- func testDraftChoicesTransferAndAsyncAddFollowsDraftIntoCreatedChat() {- let destination = store.destination(for: nil)- let selected = ChatSourceSelection(selectedCollectionIDs: ["folder"])- store.save(selected, for: nil)- let chat = UUID()- store.commitDraft(to: chat)-- XCTAssertEqual(store.selection(for: chat), selected)- XCTAssertNil(store.selection(for: nil))- XCTAssertEqual(store.resolve(destination), .session(chat))- XCTAssertNotEqual(store.destination(for: nil), destination)- }-- func testAsyncAddForDiscardedDraftDoesNotSelectSourceInNewDraft() {- let destination = store.destination(for: nil)- store.save(ChatSourceSelection(selectedPackIDs: ["pack"]), for: nil)- store.remove(nil)- let fresh = ChatSourceSelection(selectedCollectionIDs: ["new-folder"])- store.save(fresh, for: nil)-- XCTAssertNil(store.resolve(destination))- XCTAssertEqual(store.selection(for: nil), fresh)- }-- func testGenerationSnapshotRemainsStableWhenChatSelectionChanges() {- var selected = ChatSourceSelection(- selectedPackIDs: ["pack"], selectedCollectionIDs: ["notes"])- let snapshot = selected- selected.setPack("pack", enabled: false)- selected.setCollection("notes", enabled: false)- selected.setCollection("later", enabled: true)-- XCTAssertTrue(snapshot.includesPack("pack"))- XCTAssertTrue(snapshot.includesCollection("notes"))- XCTAssertFalse(snapshot.includesCollection("later"))- XCTAssertFalse(selected.includesPack("pack"))- XCTAssertFalse(selected.includesCollection("notes"))- }-- func testRemovingChatDoesNotRemoveAnotherChatOrDraftSelection() {- let chat = UUID()- let other = UUID()- let selected = ChatSourceSelection(selectedPackIDs: ["pack"])- store.save(selected, for: chat)- store.save(selected, for: other)- store.save(selected, for: nil)- store.remove(chat)-- XCTAssertNil(store.selection(for: chat))- XCTAssertEqual(store.selection(for: other), selected)- XCTAssertEqual(store.selection(for: nil), selected)- }-}diff --git a/apple/apps/ensu/EnsuTests/KnowledgePreferencesTests.swift b/apple/apps/ensu/EnsuTests/KnowledgePreferencesTests.swiftnew file mode 100644index 0000000000..ff5d9f865d--- /dev/null+++ b/apple/apps/ensu/EnsuTests/KnowledgePreferencesTests.swift@@ -0,0 +1,30 @@+import XCTest+@testable import Ensu++final class KnowledgePreferencesTests: XCTestCase {+ func testPackSettingsMigrationPreservesLegacyChoicesAndLaterChanges() throws {+ let suite = "KnowledgePreferencesTests.\(UUID().uuidString)"+ let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ let preferences = KnowledgePreferences(defaults: defaults)+ let legacyKey = "ensu.knowledge.enabled_dataset_ids"+ let settingsKey = "ensu.packs.disabledByDefault"+ let available: Set<String> = ["wiki", "books"]+ for enabled in [[], ["wiki"]] {+ defaults.removeObject(forKey: settingsKey)+ defaults.set(enabled, forKey: legacyKey)+ XCTAssertEqual(+ preferences.migratePackSettings(availablePackIDs: available),+ available.subtracting(enabled))+ preferences.setDatasetEnabled(id: "wiki", enabled: false)+ preferences.setDatasetEnabled(id: "books", enabled: true)+ XCTAssertEqual(+ KnowledgePreferences(defaults: defaults)+ .migratePackSettings(availablePackIDs: available.union(["new-pack"])),+ ["wiki"])+ }+ defaults.removeObject(forKey: settingsKey)+ defaults.removeObject(forKey: legacyKey)+ XCTAssertEqual(preferences.migratePackSettings(availablePackIDs: available), [])+ }+}diff --git a/rust/apps/ensu/changes/chat-sources.md b/rust/apps/ensu/changes/chat-sources.mdindex 47c9f5d6d0..26bd704edd 100644--- a/rust/apps/ensu/changes/chat-sources.md+++ b/rust/apps/ensu/changes/chat-sources.md@@ -1 +1 @@-- Choose which Ensu Packs and note folders each chat uses from the composer, with pack downloads and folder setup in the same view.+`Ensu Packs and Notes popup after model downloaddiff --git a/rust/apps/ensu/src-tauri/src/commands/knowledge.rs b/rust/apps/ensu/src-tauri/src/commands/knowledge.rsindex 842f02ca38..396ab344c4 100644--- a/rust/apps/ensu/src-tauri/src/commands/knowledge.rs+++ b/rust/apps/ensu/src-tauri/src/commands/knowledge.rs@@ -25,7 +25,6 @@ pub struct State {pack_lifecycles: Mutex<HashMap<String, Arc<async_runtime::Mutex<()>>>>,}-/// The sources allowed for one response, captured from the chat's selection.pub(crate) struct SourceSelection {pack_ids: HashSet<String>,note_collection_ids: HashSet<String>,@@ -109,7 +108,7 @@ pub struct KnowledgePackDto {stable_id: String,label: String,download_size_bytes: i64,- status: Option<KnowledgePackStatusDto>,+ status: KnowledgePackStatusDto,attribution: AttributionDto,}@@ -380,13 +379,13 @@ fn reconcile_and_open(fn pack_dto(dataset: KnowledgeDatasetConfig,- reconciliation: Option<retrieval::KnowledgeReconciliation>,+ reconciliation: retrieval::KnowledgeReconciliation,) -> KnowledgePackDto {KnowledgePackDto {stable_id: dataset.stable_id,label: dataset.label,download_size_bytes: dataset.download_size_bytes,- status: reconciliation.map(|result| result.status.into()),+ status: reconciliation.status.into(),attribution: dataset.attribution.into(),}}@@ -395,19 +394,10 @@ fn pack_dto(pub async fn knowledge_catalog(model_state: TauriState<'_, ModelDownloadState>,knowledge_state: TauriState<'_, State>,- reconcile_stable_ids: Option<Vec<String>>,) -> Result<Vec<KnowledgePackDto>, ApiError> {let store = model_state.store();- let selected = reconcile_stable_ids.map(|ids| ids.into_iter().collect::<HashSet<_>>());let mut packs = Vec::new();for dataset in ente_ensu::config::defaults().knowledge_datasets {- if selected- .as_ref()- .is_some_and(|ids| !ids.contains(&dataset.stable_id))- {- packs.push(pack_dto(dataset, None));- continue;- }let lifecycle = knowledge_state.pack_lifecycle(&dataset.stable_id);let _lifecycle = lifecycle.lock().await;let indexes = Arc::clone(&knowledge_state.indexes);@@ -416,30 +406,9 @@ pub async fn knowledge_catalog(let reconciliation = async_runtime::spawn_blocking(move || {reconcile_and_open(&reconcile_store, &indexes, &reconcile_dataset)})- .await;- let reconciliation = match reconciliation {- Ok(Ok(result)) => result,- result => {- let error = match result {- Ok(Err(error)) => error.message,- Err(error) => error.to_string(),- Ok(Ok(_)) => unreachable!(),- };- logging::log(- "Knowledge",- format!(- "pack reconciliation failed pack={} error={error}",- dataset.stable_id- ),- );- retrieval::KnowledgeReconciliation {- status: retrieval::KnowledgeReconciliationStatus::Download,- active_identity: None,- active_directory: None,- }- }- };- packs.push(pack_dto(dataset, Some(reconciliation)));+ .await+ .map_err(|error| ApiError::other(error.to_string()))??;+ packs.push(pack_dto(dataset, reconciliation));}Ok(packs)}@@ -548,7 +517,7 @@ pub async fn knowledge_download_pack());}- Ok(pack_dto(dataset, Some(reconciliation)))+ Ok(pack_dto(dataset, reconciliation))}#[tauri::command]@@ -563,17 +532,30 @@ pub fn knowledge_cancel_pack_download(knowledge_state: TauriState<'_, State>, st}}-#[tauri::command]-pub async fn knowledge_retrieve(- app: AppHandle,- model_state: TauriState<'_, ModelDownloadState>,- llm_state: TauriState<'_, crate::commands::llm::State>,+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RetrieveRequest {query: String,enabled_stable_ids: Vec<String>,enabled_note_collection_ids: Vec<String>,max_context_utf8_bytes: u32,retrieval_epoch: u64,+}++#[tauri::command]+pub async fn knowledge_retrieve(+ app: AppHandle,+ model_state: TauriState<'_, ModelDownloadState>,+ llm_state: TauriState<'_, crate::commands::llm::State>,+ input: RetrieveRequest,) -> Result<Option<GroundedPromptContextDto>, ApiError> {+ let RetrieveRequest {+ query,+ enabled_stable_ids,+ enabled_note_collection_ids,+ max_context_utf8_bytes,+ retrieval_epoch,+ } = input;let knowledge_state = app.state::<State>();let selection = SourceSelection::new(enabled_stable_ids, enabled_note_collection_ids);let (note_collection_ids, notes) = app@@ -833,64 +815,6 @@ mod tests {const COLLECTION_ID: &str = "123e4567-e89b-12d3-a456-426614174000";- #[test]- fn response_source_selection_is_explicit_and_independent_for_packs_and_folders() {- let pack = retrieval::PassageLocator::EnsuPack {- dataset_id: "selected-pack".into(),- revision_sha256: "a".repeat(64),- row: 0,- };- let note = retrieval::PassageLocator::LocalNote(note(0).locator);- let new_pack = retrieval::PassageLocator::EnsuPack {- dataset_id: "new-pack".into(),- revision_sha256: "b".repeat(64),- row: 0,- };- let mut new_folder_note = note.clone();- if let retrieval::PassageLocator::LocalNote(locator) = &mut new_folder_note {- locator.collection_id = "another-folder".into();- }-- for (packs_enabled, notes_enabled) in- [(false, false), (true, false), (false, true), (true, true)]- {- let selection = SourceSelection::new(- if packs_enabled {- vec!["selected-pack".into()]- } else {- vec![]- },- if notes_enabled {- vec![COLLECTION_ID.into()]- } else {- vec![]- },- );- assert_eq!(selection.allows(&pack), packs_enabled);- assert_eq!(selection.allows(¬e), notes_enabled);- assert!(!selection.allows(&new_pack));- assert!(!selection.allows(&new_folder_note));- }- }-- #[test]- fn selected_sources_cover_new_content_without_enabling_new_sources() {- let selection = SourceSelection::new(vec!["pack".into()], vec![COLLECTION_ID.into()]);- for revision in ["a", "b"] {- let pack = retrieval::PassageLocator::EnsuPack {- dataset_id: "pack".into(),- revision_sha256: revision.repeat(64),- row: 123,- };- assert!(selection.allows(&pack));- }- for index in 0..3 {- let mut locator = note(index).locator;- locator.indexed_revision = "c".repeat(64);- assert!(selection.allows(&retrieval::PassageLocator::LocalNote(locator)));- }- }-fn note(index: usize) -> NotesSearchHit {NotesSearchHit {locator: ente_ensu::notes::NotePassageLocator {diff --git a/web/apps/ensu/package.json b/web/apps/ensu/package.jsonindex 7ebb8299b5..37acb33831 100644--- a/web/apps/ensu/package.json+++ b/web/apps/ensu/package.json@@ -3,7 +3,7 @@"version": "0.0.0","private": true,"scripts": {- "test": "node --experimental-transform-types --test tests/*.test.mjs"+ "test": "node --experimental-transform-types --test tests/*.test.ts"},"dependencies": {"@hugeicons/core-free-icons": "4.3.5",diff --git a/web/apps/ensu/src/components/chat/ChatComposer.tsx b/web/apps/ensu/src/components/chat/ChatComposer.tsxindex 284a3f96e9..d8011835bc 100644--- a/web/apps/ensu/src/components/chat/ChatComposer.tsx+++ b/web/apps/ensu/src/components/chat/ChatComposer.tsx@@ -12,13 +12,11 @@ import {CircularProgress,IconButton,LinearProgress,- Menu,- MenuItem,Stack,Typography,} from "@mui/material";import type { SxProps, Theme } from "@mui/material/styles";-import React, { forwardRef, memo, useImperativeHandle, useRef } from "react";+import { forwardRef, memo, useImperativeHandle, useRef } from "react";import { ChatInput, type ChatInputHandle } from "./ChatInput";interface IconProps {@@ -66,28 +64,21 @@ export interface ChatComposerProps {formatBytes: (size: number) => string;isGenerating: boolean;handleSend: (input: string) => void | Promise<void>;+ onActivity: () => void;handleStopGeneration: () => void;- showSourcePicker: boolean;- openSources: () => void;- sourcesDisabled: boolean;+ retrySources?: () => void;sourcesLoading: boolean;isPreparingMessage: boolean;sourcesStatus?: string;showAttachmentPicker: boolean;- openAttachmentMenu: (event: React.MouseEvent<HTMLElement>) => void;- attachmentAnchor: HTMLElement | null;- closeAttachmentMenu: () => void;- handleAttachmentChoice: (choice: "image" | "document") => void;+ openPhotoPicker: () => void;showImageAttachment: boolean;isImageAttachmentLimitReached: boolean;- getDocumentInputProps: () => React.InputHTMLAttributes<HTMLInputElement>;- getImageInputProps: () => React.InputHTMLAttributes<HTMLInputElement>;actionButtonSx: SxProps<Theme>;- drawerIconButtonSx: SxProps<Theme>;+ drawerIconButtonSx: Exclude<SxProps<Theme>, readonly unknown[]>;smallIconProps: IconProps;compactIconProps: IconProps;actionIconProps: IconProps;- stopButtonColor: string;}export const ChatComposer = memo(@@ -113,28 +104,21 @@ export const ChatComposer = memo(formatBytes,isGenerating,handleSend,+ onActivity,handleStopGeneration,- showSourcePicker,- openSources,- sourcesDisabled,+ retrySources,sourcesLoading,isPreparingMessage,sourcesStatus,showAttachmentPicker,- openAttachmentMenu,- attachmentAnchor,- closeAttachmentMenu,- handleAttachmentChoice,+ openPhotoPicker,showImageAttachment,isImageAttachmentLimitReached,- getDocumentInputProps,- getImageInputProps,actionButtonSx,drawerIconButtonSx,smallIconProps,compactIconProps,actionIconProps,- stopButtonColor,},ref,) {@@ -261,398 +245,358 @@ export const ChatComposer = memo() : null;return (- <>+ <Box+ sx={{+ px: 1,+ position: "absolute",+ left: 0,+ right: 0,+ bottom: 16,+ zIndex: 5,+ pointerEvents: "none",+ width: "100%",+ boxSizing: "border-box",+ }}+ ><Boxsx={{- px: { xs: 2, md: 4 },- position: "absolute",- left: 0,- right: 0,- bottom: 16,- zIndex: 5,- pointerEvents: "none",+ maxWidth: 900,width: "100%",+ mx: "auto",+ pointerEvents: "auto",boxSizing: "border-box",}}>- <Box- sx={{- maxWidth: 900,- width: "100%",- mx: "auto",- pointerEvents: "auto",- boxSizing: "border-box",- }}- >- {showModelGate ? (- <>- {showDownloadProgress &&- downloadStatus?.totalBytes && (- <Box+ {showModelGate ? (+ <>+ {showDownloadProgress &&+ downloadStatus?.totalBytes && (+ <Box+ sx={{+ display: "flex",+ justifyContent: "flex-end",+ mb: 1,+ px: 1,+ }}+ >+ <Typography+ variant="mini"sx={{- display: "flex",- justifyContent: "flex-end",- mb: 1,- px: 1,+ color: "text.muted",+ fontVariantNumeric:+ "tabular-nums",}}>- <Typography- variant="mini"- sx={{- color: "text.muted",- fontVariantNumeric:- "tabular-nums",- }}- >- {formatBytes(- downloadStatus.bytesDownloaded ??- 0,- )}{" "}- /{" "}- {formatBytes(- downloadStatus.totalBytes,- )}- </Typography>- </Box>- )}- <Stack- sx={{- px: 0,- py: 0,- gap: 0.5,- borderRadius: 2,- bgcolor: "background.paper",- border: "1px solid",- borderColor: "divider",- boxShadow:- "0px 12px 32px rgba(0, 0, 0, 0.12)",- position: "relative",- overflow: "hidden",- }}- >- {showDownloadProgress && (- <LinearProgress- variant={- downloadStatus?.totalBytes- ? "determinate"- : "indeterminate"- }- value={- downloadStatus?.totalBytes- ? downloadStatus.percent- : undefined- }- sx={{- position: "absolute",- top: 0,- left: 0,- right: 0,- height: 3,- borderRadius: "8px 8px 0 0",- pointerEvents: "none",- }}- />- )}- <Stack sx={{ px: 2, py: 2, gap: 1.5 }}>- <Typography variant="h3">- Download to begin using the Chat+ {formatBytes(+ downloadStatus.bytesDownloaded ??+ 0,+ )}{" "}+ /{" "}+ {formatBytes(+ downloadStatus.totalBytes,+ )}</Typography>+ </Box>+ )}+ <Stack+ sx={{+ px: 0,+ py: 0,+ gap: 0.5,+ borderRadius: 2,+ bgcolor: "background.paper",+ border: "1px solid",+ borderColor: "divider",+ boxShadow:+ "0px 12px 32px rgba(0, 0, 0, 0.12)",+ position: "relative",+ overflow: "hidden",+ }}+ >+ {showDownloadProgress && (+ <LinearProgress+ variant={+ downloadStatus?.totalBytes+ ? "determinate"+ : "indeterminate"+ }+ value={+ downloadStatus?.totalBytes+ ? downloadStatus.percent+ : undefined+ }+ sx={{+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ height: 3,+ borderRadius: "8px 8px 0 0",+ pointerEvents: "none",+ }}+ />+ )}+ <Stack sx={{ px: 2, py: 2, gap: 1.5 }}>+ <Typography variant="h3">+ Download to begin using the Chat+ </Typography>+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ {downloadStatusLabel ??+ (modelGateStatus === "error"+ ? "We couldn't load the model. Try downloading again."+ : downloadSizeLabel)}+ </Typography>+ {modelGateError && (<Typography- variant="small"- sx={{ color: "text.muted" }}+ variant="mini"+ sx={{ color: "critical.main" }}>- {downloadStatusLabel ??- (modelGateStatus === "error"- ? "We couldn't load the model. Try downloading again."- : downloadSizeLabel)}+ {modelGateError}</Typography>- {modelGateError && (- <Typography- variant="mini"- sx={{ color: "critical.main" }}- >- {modelGateError}- </Typography>- )}- <Button- variant="contained"- color="accent"- disabled={- modelGateStatus !== "missing" &&- modelGateStatus !== "error"- }- onClick={() =>- void handleDownloadModel()- }- >- {modelGateStatus === "checking"- ? "Checking..."- : modelGateStatus ===- "preloading" ||- modelGateStatus ===- "downloading"- ? "Loading..."- : modelGateStatus === "error"- ? "Retry"- : "Download"}- </Button>- </Stack>+ )}+ <Button+ variant="contained"+ color="accent"+ disabled={+ modelGateStatus !== "missing" &&+ modelGateStatus !== "error"+ }+ onClick={() =>+ void handleDownloadModel()+ }+ >+ {modelGateStatus === "checking"+ ? "Checking..."+ : modelGateStatus ===+ "preloading" ||+ modelGateStatus ===+ "downloading"+ ? "Loading..."+ : modelGateStatus === "error"+ ? "Retry"+ : "Download"}+ </Button></Stack>- </>- ) : (- <>- {pendingImagePreviewRow}- <Stack- sx={{- px: 0,- py: 0,- gap: 0.5,- borderRadius: 2,- bgcolor: "background.paper",- border: "1px solid",- borderColor: "divider",- boxShadow:- "0px 12px 32px rgba(0, 0, 0, 0.12)",- position: "relative",- overflow: "hidden",- }}- >- {showDownloadProgress && (- <LinearProgress- variant={- downloadStatus?.totalBytes- ? "determinate"- : "indeterminate"- }- value={- downloadStatus?.totalBytes- ? downloadStatus.percent- : undefined- }- sx={{- position: "absolute",- top: 0,- left: 0,- right: 0,- height: 3,- borderRadius: "8px 8px 0 0",- pointerEvents: "none",- }}+ </Stack>+ </>+ ) : (+ <>+ {pendingImagePreviewRow}+ <Stack+ sx={{+ px: 0,+ py: 0,+ gap: 0.5,+ borderRadius: 2,+ bgcolor: "background.paper",+ border: "1px solid",+ borderColor: "divider",+ boxShadow:+ "0px 12px 32px rgba(0, 0, 0, 0.12)",+ position: "relative",+ overflow: "hidden",+ }}+ >+ {showDownloadProgress && (+ <LinearProgress+ variant={+ downloadStatus?.totalBytes+ ? "determinate"+ : "indeterminate"+ }+ value={+ downloadStatus?.totalBytes+ ? downloadStatus.percent+ : undefined+ }+ sx={{+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ height: 3,+ borderRadius: "8px 8px 0 0",+ pointerEvents: "none",+ }}+ />+ )}+ {editingMessage && (+ <Box+ sx={{+ display: "flex",+ alignItems: "center",+ gap: 1,+ px: 1.5,+ py: 0.5,+ borderRadius: 2,+ bgcolor: "fill.faint",+ borderLeft: "3px solid",+ borderLeftColor: "accent.main",+ }}+ >+ <HugeiconsIcon+ icon={Edit01Icon}+ {...compactIconProps}/>- )}- {editingMessage && (- <Box+ <Typography+ variant="mini"+ sx={{ color: "text.muted" }}+ >+ Editing:+ </Typography>+ <Typography+ variant="mini"sx={{- display: "flex",- alignItems: "center",- gap: 1,- px: 1.5,- py: 0.5,- borderRadius: 2,- bgcolor: "fill.faint",- borderLeft: "3px solid",- borderLeftColor: "accent.main",+ color: "text.base",+ flex: 1,+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",}}+ >+ {editingMessage.text}+ </Typography>+ <IconButton+ aria-label="Cancel edit"+ sx={actionButtonSx}+ onClick={handleCancelEdit}><HugeiconsIcon- icon={Edit01Icon}- {...compactIconProps}+ icon={Cancel01Icon}+ {...smallIconProps}/>- <Typography- variant="mini"- sx={{ color: "text.muted" }}- >- Editing:- </Typography>- <Typography- variant="mini"+ </IconButton>+ </Box>+ )}++ {pendingDocuments.length > 0 && (+ <Box+ sx={{+ display: "grid",+ gridTemplateColumns:+ "repeat(2, minmax(0, 1fr))",+ gap: 0.5,+ }}+ >+ {pendingDocuments.map((doc) => (+ <Box+ key={doc.id}sx={{- color: "text.base",- flex: 1,- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",+ display: "flex",+ alignItems: "center",+ gap: 1,+ px: 1.5,+ py: 0.75,+ borderRadius: 1.5,+ bgcolor: "fill.faint",+ minWidth: 0,}}>- {editingMessage.text}- </Typography>- <IconButton- aria-label="Cancel edit"- sx={actionButtonSx}- onClick={handleCancelEdit}- >- <HugeiconsIcon- icon={Cancel01Icon}- {...smallIconProps}- />- </IconButton>- </Box>- )}-- {pendingDocuments.length > 0 && (- <Box- sx={{- display: "grid",- gridTemplateColumns:- "repeat(2, minmax(0, 1fr))",- gap: 0.5,- }}- >- {pendingDocuments.map((doc) => (- <Box- key={doc.id}+ <Typography+ variant="mini"sx={{- display: "flex",- alignItems: "center",- gap: 1,- px: 1.5,- py: 0.75,- borderRadius: 1.5,- bgcolor: "fill.faint",- minWidth: 0,+ flex: 1,+ color: "text.base",+ overflow: "hidden",+ textOverflow:+ "ellipsis",+ whiteSpace: "nowrap",}}>- <Typography- variant="mini"- sx={{- flex: 1,- color: "text.base",- overflow: "hidden",- textOverflow:- "ellipsis",- whiteSpace:- "nowrap",- }}- >- {doc.name}- </Typography>- <Typography- variant="mini"- sx={{- color: "text.muted",- }}- >- {formatBytes(doc.size)}- </Typography>- <IconButton- aria-label="Remove document"- sx={actionButtonSx}- onClick={() =>- removePendingDocument(- doc.id,- )- }- >- <HugeiconsIcon- icon={Cancel01Icon}- {...smallIconProps}- />- </IconButton>- </Box>- ))}- </Box>- )}+ {doc.name}+ </Typography>+ <Typography+ variant="mini"+ sx={{ color: "text.muted" }}+ >+ {formatBytes(doc.size)}+ </Typography>+ <IconButton+ aria-label="Remove document"+ sx={actionButtonSx}+ onClick={() =>+ removePendingDocument(+ doc.id,+ )+ }+ >+ <HugeiconsIcon+ icon={Cancel01Icon}+ {...smallIconProps}+ />+ </IconButton>+ </Box>+ ))}+ </Box>+ )}- {sourcesStatus && (- <Stack- direction="row"+ {sourcesStatus && (+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ px: 1.5,+ gap: 1,+ }}+ role="status"+ >+ <Typography+ variant="small"sx={{- alignItems: "center",- px: 1.5,- gap: 1,+ flex: 1,+ color: "text.muted",}}- role="status">- <Typography- variant="small"- sx={{- flex: 1,- color: "text.muted",- }}- >- {sourcesStatus}- </Typography>+ {sourcesStatus}+ </Typography>+ {retrySources && (<Buttonsize="small"- onClick={openSources}+ onClick={retrySources}>- Sources+ Retry</Button>- </Stack>- )}- <ChatInput- showSourcePicker={showSourcePicker}- openSources={openSources}- sourcesDisabled={sourcesDisabled}- sourcesLoading={sourcesLoading}- isPreparingMessage={isPreparingMessage}- ref={inputRef}- actionIconProps={actionIconProps}- disableAttachmentButton={- disableAttachmentButton- }- drawerIconButtonSx={drawerIconButtonSx}- handleSend={handleSend}- handleStopGeneration={- handleStopGeneration- }- hasPendingAttachments={- pendingDocuments.length > 0 ||- pendingImages.length > 0- }- isDownloading={isDownloading}- isAttachingImages={isAttachingImages}- isGenerating={isGenerating}- isModelPreparationActive={- isModelPreparationActive- }- initialText={draftRef.current}- onTextChange={(text) => {- draftRef.current = text;- }}- openAttachmentMenu={openAttachmentMenu}- showAttachmentPicker={- showAttachmentPicker- }- stopButtonColor={stopButtonColor}- />- </Stack>- </>- )}- </Box>- </Box>-- {showAttachmentPicker && (- <>- <input {...getDocumentInputProps()} />- <input {...getImageInputProps()} />- <Menu- anchorEl={attachmentAnchor}- open={Boolean(attachmentAnchor)}- onClose={closeAttachmentMenu}- anchorOrigin={{- vertical: "top",- horizontal: "right",- }}- transformOrigin={{- vertical: "bottom",- horizontal: "right",- }}- >- {showImageAttachment && (- <MenuItem- disabled={isImageAttachmentLimitReached}- onClick={() =>- handleAttachmentChoice("image")+ )}+ </Stack>+ )}+ <ChatInput+ ref={inputRef}+ actionIconProps={actionIconProps}+ disableAttachmentButton={+ disableAttachmentButton ||+ !showImageAttachment}- >- Image- </MenuItem>- )}- </Menu>- </>- )}- </>+ sourcesLoading={sourcesLoading}+ isPreparingMessage={isPreparingMessage}+ drawerIconButtonSx={drawerIconButtonSx}+ handleSend={handleSend}+ handleStopGeneration={handleStopGeneration}+ hasPendingAttachments={+ pendingDocuments.length > 0 ||+ pendingImages.length > 0+ }+ isDownloading={isDownloading}+ isAttachingImages={isAttachingImages}+ isGenerating={isGenerating}+ isModelPreparationActive={+ isModelPreparationActive+ }+ initialText={draftRef.current}+ onTextChange={(text) => {+ draftRef.current = text;+ onActivity();+ }}+ openPhotoPicker={openPhotoPicker}+ showAttachmentPicker={showAttachmentPicker}+ />+ </Stack>+ </>+ )}+ </Box>+ </Box>);}),);diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsxindex e0a35ad259..70ed108e67 100644--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx@@ -1,3 +1,4 @@+import { SourceIntroductionDialog } from "@/components/chat/SourceIntroductionDialog";import type { KnowledgePack } from "@/services/knowledge";import {DEFAULT_TAURI_CONTEXT_SIZE,@@ -97,16 +98,6 @@ interface ModelSettingsDraft {}export interface ChatDialogsProps {- showSources: boolean;- closeSources: () => void;- sourceSelectionDisabled: boolean;- handleDownloadChatKnowledgePack: (stableId: string) => void;- handleAddChatNotesFolder: () => void;- enabledNoteCollectionIds: Set<string>;- handleSetNotesCollectionEnabled: (- collectionId: string,- enabled: boolean,- ) => void;showSettingsModal: boolean;openSettingsModal: () => void;closeSettingsModal: () => void;@@ -155,18 +146,21 @@ export interface ChatDialogsProps {knowledgeCatalogLoading: boolean;knowledgeCatalogError: string | null;retryKnowledgeCatalog: () => void;- enabledKnowledgePackIds: Set<string>;knowledgeDownloadProgress: Record<string, number | undefined>;knowledgeErrors: Record<string, string | undefined>;handleDownloadKnowledgePack: (stableId: string) => void;handleCancelKnowledgePackDownload: (stableId: string) => void;- handleSetKnowledgePackEnabled: (stableId: string, enabled: boolean) => void;notesCollections: NotesCollectionView[];notesCollectionsLoading: boolean;notesCollectionsError: string | null;retryNotesCollections: () => void;handleAddNotesFolder: () => void;handleRemoveNotesCollection: (collectionId: string, label: string) => void;+ onSettingsFlowVisibilityChange: (open: boolean) => void;+ disabledNoteIds: string[];+ disabledPackIds: string[];+ handleSetPackEnabled: (id: string, enabled: boolean) => void;+ handleSetNotesEnabled: (collectionId: string, enabled: boolean) => void;handleIndexNotesCollection: (collectionId: string, force?: boolean) => void;chatNotificationOpen: boolean;setChatNotificationOpen: React.Dispatch<React.SetStateAction<boolean>>;@@ -178,13 +172,6 @@ export interface ChatDialogsProps {export const ChatDialogs = memo(({- showSources,- closeSources,- sourceSelectionDisabled,- handleDownloadChatKnowledgePack,- handleAddChatNotesFolder,- enabledNoteCollectionIds,- handleSetNotesCollectionEnabled,showSettingsModal,openSettingsModal,closeSettingsModal,@@ -233,18 +220,21 @@ export const ChatDialogs = memo(knowledgeCatalogLoading,knowledgeCatalogError,retryKnowledgeCatalog,- enabledKnowledgePackIds,knowledgeDownloadProgress,knowledgeErrors,handleDownloadKnowledgePack,handleCancelKnowledgePackDownload,- handleSetKnowledgePackEnabled,notesCollections,notesCollectionsLoading,notesCollectionsError,retryNotesCollections,handleAddNotesFolder,handleRemoveNotesCollection,+ onSettingsFlowVisibilityChange,+ disabledNoteIds,+ disabledPackIds,+ handleSetPackEnabled,+ handleSetNotesEnabled,handleIndexNotesCollection,chatNotificationOpen,setChatNotificationOpen,@@ -289,13 +279,57 @@ export const ChatDialogs = memo(const [showKnowledgeSettings, setShowKnowledgeSettings] =React.useState(false);const [showNotesSettings, setShowNotesSettings] = React.useState(false);+ const [showIntroduction, setShowIntroduction] = React.useState(false);+ const [returnToIntroduction, setReturnToIntroduction] =+ React.useState(false);+ const settingsFlowVisible =+ showSettingsModal ||+ showNotesSettings ||+ showKnowledgeSettings ||+ showIntroduction ||+ showModelSettings ||+ showSystemPromptSettings ||+ showBackupComingSoon;+ React.useEffect(() => {+ onSettingsFlowVisibilityChange(settingsFlowVisible);+ }, [onSettingsFlowVisibilityChange, settingsFlowVisible]);+ const checkedIntroduction = React.useRef(false);+ React.useEffect(() => {+ if (+ !isTauriRuntime ||+ modelGateStatus !== "ready" ||+ showSettingsModal ||+ checkedIntroduction.current+ )+ return;+ checkedIntroduction.current = true;+ try {+ if (+ localStorage.getItem(+ "ensu.desktop.sources.introductionSeen",+ ) === "true"+ )+ return;+ localStorage.setItem(+ "ensu.desktop.sources.introductionSeen",+ "true",+ );+ } catch {+ setShowIntroduction(true);+ return;+ }+ setShowIntroduction(true);+ }, [isTauriRuntime, modelGateStatus, showSettingsModal]);const [attributionPack, setAttributionPack] =React.useState<KnowledgePack | null>(null);const returnToSettings = () => {setShowKnowledgeSettings(false);setShowNotesSettings(false);- openSettingsModal();+ if (returnToIntroduction) {+ setReturnToIntroduction(false);+ setShowIntroduction(true);+ } else openSettingsModal();};const [draftSystemPrompt, setDraftSystemPrompt] = React.useState("");@@ -356,462 +390,22 @@ export const ChatDialogs = memo(return !contextErrorValue;}, [draftContextLength, isTauriRuntime]);- const renderNotesContent = (inChat: boolean) => (- <Stack sx={{ gap: 2 }}>- {notesCollectionsError && (- <Stack- direction="row"- sx={{ alignItems: "center", gap: 1 }}- >- <Typography- variant="small"- sx={{ flex: 1, color: "critical.main" }}- >- {notesCollectionsError}- </Typography>- <Button size="small" onClick={retryNotesCollections}>- Retry- </Button>- </Stack>- )}- {notesCollectionsLoading && <LinearProgress />}- {!notesCollectionsLoading && notesCollections.length === 0 && (- <Typography variant="small" sx={{ color: "text.muted" }}>- Add a folder to use your notes in this chat.- </Typography>- )}- {notesCollections.map((collection) => {- const indexing =- collection.status === "indexing" ||- collection.status === "updating";- const starting = collection.activity === "starting";- const progress = collection.indexingProgress;- const canRetry =- collection.status === "error" ||- collection.status === "unavailable" ||- collection.activity === "failed";- const waitingMessage =- collection.activity === "waitingForGeneration"- ? "Indexing will resume after the current response."- : collection.activity === "waitingForModel"- ? "Indexing will start when the model is ready."- : null;- return (- <Stack- key={collection.id}- sx={{- gap: 1.25,- p: 2,- borderRadius: 2,- bgcolor: "fill.faint",- }}- >- <Stack- direction="row"- sx={{ alignItems: "center", gap: 1 }}- >- <Stack sx={{ flex: 1, minWidth: 0 }}>- <Typography variant="h6" noWrap>- {collection.label}- </Typography>- <Typography- variant="mini"- noWrap- sx={{ color: "text.muted" }}- >- {starting &&- collection.indexedDocumentCount === 0- ? "Preparing notes…"- : `${collection.indexedDocumentCount} ${collection.indexedDocumentCount === 1 ? "note indexed" : "notes indexed"}`}- {collection.lastUpdatedAtMs != null && (- <>- {" · Updated at "}- {formatNotesUpdatedAt(- collection.lastUpdatedAtMs,- )}- </>- )}- </Typography>- </Stack>- {inChat && (- <Switch- checked={enabledNoteCollectionIds.has(- collection.id,- )}- disabled={sourceSelectionDisabled}- onChange={(_, checked) =>- handleSetNotesCollectionEnabled(- collection.id,- checked,- )- }- slotProps={{- input: {- "aria-label": `Use ${collection.label} in this chat`,- },- }}- />- )}- {!inChat && (- <IconButton- aria-label={`Remove ${collection.label}`}- disabled={indexing || starting}- onClick={() =>- handleRemoveNotesCollection(- collection.id,- collection.label,- )- }- sx={actionButtonSx}- >- <HugeiconsIcon- icon={Delete01Icon}- {...compactIconProps}- />- </IconButton>- )}- </Stack>- {indexing && (- <Stack- direction="row"- sx={{ alignItems: "center", gap: 1 }}- >- <LinearProgress- variant="determinate"- value={progress ?? 0}- sx={{ flex: 1 }}- />- <Typography- variant="mini"- sx={{ color: "text.muted" }}- >- {progress ?? 0}%- </Typography>- </Stack>- )}- {starting && <LinearProgress />}- {waitingMessage && (- <Typography- variant="small"- sx={{ color: "text.muted" }}- >- {waitingMessage}- </Typography>- )}- {collection.lastError && (- <Typography- variant="small"- sx={{ color: "critical.main" }}- >- {collection.lastError}- </Typography>- )}- {collection.watcherError && (- <Typography- variant="small"- sx={{ color: "text.muted" }}- >- {collection.watcherError}- </Typography>- )}- {collection.status === "unavailable" &&- !collection.lastError && (- <Typography- variant="small"- sx={{ color: "text.muted" }}- >- Folder unavailable- </Typography>- )}- {(canRetry || collection.watcherError) && (- <Button- size="small"- onClick={() =>- handleIndexNotesCollection(- collection.id,- true,- )- }- sx={{ alignSelf: "flex-start" }}- >- {canRetry ? "Try again" : "Refresh"}- </Button>- )}- </Stack>- );- })}- <ListItemButton- disabled={- notesCollectionsLoading ||- (inChat && sourceSelectionDisabled)- }- onClick={- inChat ? handleAddChatNotesFolder : handleAddNotesFolder- }- sx={settingsItemSx}- >- <HugeiconsIcon icon={Folder01Icon} {...compactIconProps} />- <Typography variant="small" sx={{ flex: 1 }}>- Add notes folder- </Typography>- </ListItemButton>- <Typography variant="small" sx={{ px: 2, color: "text.muted" }}>- Ensu reads and indexes markdown files in the selected- folder. Source files are never modified.- </Typography>- </Stack>- );- const renderKnowledgeContent = (inChat: boolean) => (- <Stack sx={{ gap: 2 }}>- {knowledgeCatalogError && (- <Stack- direction="row"- sx={{ alignItems: "center", gap: 1 }}- >- <Typography- variant="small"- sx={{ flex: 1, color: "critical.main" }}- >- {knowledgeCatalogError}- </Typography>- <Button size="small" onClick={retryKnowledgeCatalog}>- Retry- </Button>- </Stack>- )}- {knowledgeCatalogLoading && <LinearProgress />}- {knowledgePacks.map((pack) => {- const progress = knowledgeDownloadProgress[pack.stableId];- const installed =- pack.status === "ready" ||- pack.status === "updateAvailable";- const isMutating = progress !== undefined;- const enabled =- enabledKnowledgePackIds.has(pack.stableId) && installed;- return (- <Stack- key={pack.stableId}- sx={{- gap: 1.5,- p: 2,- borderRadius: 2,- bgcolor: "fill.faint",- }}- >- <Stack- direction="row"- sx={{ alignItems: "center", gap: 1.5 }}- >- <Stack sx={{ flex: 1, gap: 0.5 }}>- <Typography variant="h6">- {pack.label}- </Typography>- <Stack- direction="row"- sx={{ alignItems: "center", gap: 0.75 }}- >- <Typography- variant="mini"- sx={{ color: "text.muted" }}- >- {formatBytes(- pack.downloadSizeBytes,- )}- </Typography>- <Typography- variant="mini"- sx={{ color: "text.muted" }}- >- ·- </Typography>- <Link- component="button"- type="button"- underline="hover"- onClick={() =>- setAttributionPack(pack)- }- sx={compactInlineLinkSx}- >- {pack.attribution.licenseLabel}- </Link>- </Stack>- </Stack>- {installed && !isMutating && inChat ? (- <Switch- checked={enabled}- disabled={- knowledgeCatalogLoading ||- sourceSelectionDisabled- }- onChange={(_, checked) =>- handleSetKnowledgePackEnabled(- pack.stableId,- checked,- )- }- slotProps={{- input: {- "aria-label": `Use ${pack.label} in this chat`,- },- }}- />- ) : pack.status === "download" &&- !isMutating ? (- <Button- variant="contained"- color="accent"- size="small"- disabled={- knowledgeCatalogLoading ||- (inChat && sourceSelectionDisabled)- }- onClick={() =>- (inChat- ? handleDownloadChatKnowledgePack- : handleDownloadKnowledgePack)(- pack.stableId,- )- }- >- Download- </Button>- ) : !inChat && installed && !isMutating ? (- <Typography- variant="small"- sx={{ color: "text.muted" }}- >- Downloaded- </Typography>- ) : pack.status == null && !isMutating ? (- <Typography- variant="small"- sx={{ color: "text.muted" }}- >- Checking availability…- </Typography>- ) : null}- </Stack>-- {isMutating && (- <Stack- direction="row"- sx={{ alignItems: "center", gap: 1 }}- >- <LinearProgress- variant="determinate"- value={Math.max(- 0,- Math.min(100, progress),- )}- sx={{ flex: 1 }}- />- <IconButton- aria-label={`Cancel ${pack.label} download`}- onClick={() =>- handleCancelKnowledgePackDownload(- pack.stableId,- )- }- sx={actionButtonSx}- >- <HugeiconsIcon- icon={Cancel01Icon}- {...compactIconProps}- />- </IconButton>- </Stack>- )}-- {!isMutating &&- pack.status === "updateAvailable" && (- <Button- variant="contained"- color="accent"- size="small"- disabled={- knowledgeCatalogLoading ||- (inChat && sourceSelectionDisabled)- }- sx={{ alignSelf: "flex-start" }}- onClick={() =>- (inChat- ? handleDownloadChatKnowledgePack- : handleDownloadKnowledgePack)(- pack.stableId,- )- }- >- Update- </Button>- )}-- {knowledgeErrors[pack.stableId] && (- <Typography- variant="small"- sx={{ color: "critical.main" }}- >- {knowledgeErrors[pack.stableId]}- </Typography>- )}- </Stack>- );- })}- </Stack>- );-return (<>- <Dialog- open={showSources}- onClose={closeSources}- fullScreen={isSmall}- maxWidth="sm"- fullWidth- aria-labelledby="chat-sources-title"- slotProps={{ paper: { sx: dialogPaperSx } }}- >- <DialogTitle- sx={[- dialogTitleSx,- {- display: "flex",- alignItems: "center",- justifyContent: "space-between",- },- ]}- >- <span id="chat-sources-title">Sources</span>- <IconButton- aria-label="Close sources"- onClick={closeSources}- sx={drawerIconButtonSx}- >- <HugeiconsIcon- icon={Cancel01Icon}- {...tinyIconProps}- />- </IconButton>- </DialogTitle>- <DialogContent>- <Stack sx={{ gap: 2 }}>- <Typography- variant="small"- sx={{ color: "text.muted" }}- >- Choose the packs and notes Ensu can use in this- chat. Changes apply to the next response.- Information already in the conversation remains- available.- </Typography>- <Typography variant="h6">Ensu Packs</Typography>- {renderKnowledgeContent(true)}- <Divider />- <Typography variant="h6">Your Notes</Typography>- {renderNotesContent(true)}- </Stack>- </DialogContent>- </Dialog>+ <SourceIntroductionDialog+ open={showIntroduction}+ onClose={() => setShowIntroduction(false)}+ onSetUpPacks={() => {+ setShowIntroduction(false);+ setReturnToIntroduction(true);+ setShowKnowledgeSettings(true);+ }}+ onSetUpNotes={() => {+ setShowIntroduction(false);+ setReturnToIntroduction(true);+ setShowNotesSettings(true);+ }}+ /><Dialogopen={!!imagePreview}onClose={closeImagePreview}@@ -962,6 +556,7 @@ export const ChatDialogs = memo(<ListItemButtononClick={() => {closeSettingsModal();+ setReturnToIntroduction(false);setShowNotesSettings(true);}}sx={settingsItemSx}@@ -987,6 +582,7 @@ export const ChatDialogs = memo(<ListItemButtononClick={() => {closeSettingsModal();+ setReturnToIntroduction(false);setShowKnowledgeSettings(true);}}sx={settingsItemSx}@@ -1233,7 +829,11 @@ export const ChatDialogs = memo(]}><IconButton- aria-label="Back to settings"+ aria-label={+ returnToIntroduction+ ? "Back to setup"+ : "Back to settings"+ }onClick={returnToSettings}sx={drawerIconButtonSx}>@@ -1246,7 +846,245 @@ export const ChatDialogs = memo(Your Notes</Box></DialogTitle>- <DialogContent>{renderNotesContent(false)}</DialogContent>+ <DialogContent>+ <Stack sx={{ gap: 2 }}>+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ Choose notes to use for your next messages in+ any chat.+ </Typography>+ {notesCollectionsError && (+ <Stack+ direction="row"+ sx={{ alignItems: "center", gap: 1 }}+ >+ <Typography+ variant="small"+ sx={{ flex: 1, color: "critical.main" }}+ >+ {notesCollectionsError}+ </Typography>+ <Button+ size="small"+ onClick={retryNotesCollections}+ >+ Retry+ </Button>+ </Stack>+ )}+ {notesCollectionsLoading && <LinearProgress />}+ {notesCollections.map((collection) => {+ const indexing =+ collection.status === "indexing" ||+ collection.status === "updating";+ const starting =+ collection.activity === "starting";+ const progress = collection.indexingProgress;+ const canRetry =+ collection.status === "error" ||+ collection.status === "unavailable" ||+ collection.activity === "failed";+ const waitingMessage =+ collection.activity ===+ "waitingForGeneration"+ ? "Indexing will resume after the current response."+ : collection.activity ===+ "waitingForModel"+ ? "Indexing will start when the model is ready."+ : collection.activity ===+ "waitingForChat"+ ? "Indexing will resume when chat is idle."+ : null;+ return (+ <Stack+ key={collection.id}+ sx={{+ gap: 1.25,+ p: 2,+ borderRadius: 2,+ bgcolor: "fill.faint",+ }}+ >+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ gap: 1,+ }}+ >+ <Stack+ sx={{ flex: 1, minWidth: 0 }}+ >+ <Typography variant="h6" noWrap>+ {collection.label}+ </Typography>+ <Typography+ variant="mini"+ noWrap+ sx={{ color: "text.muted" }}+ >+ {starting &&+ collection.indexedDocumentCount ===+ 0+ ? "Preparing notes…"+ : `${collection.indexedDocumentCount} ${collection.indexedDocumentCount === 1 ? "note indexed" : "notes indexed"}`}+ {collection.lastUpdatedAtMs !=+ null && (+ <>+ {" · Updated at "}+ {formatNotesUpdatedAt(+ collection.lastUpdatedAtMs,+ )}+ </>+ )}+ </Typography>+ </Stack>+ <Switch+ checked={+ !disabledNoteIds.includes(+ collection.id,+ )+ }+ disabled={+ notesCollectionsLoading+ }+ onChange={(_, checked) =>+ handleSetNotesEnabled(+ collection.id,+ checked,+ )+ }+ slotProps={{+ input: {+ "aria-label": `Use ${collection.label} for new messages`,+ },+ }}+ />+ {!returnToIntroduction && (+ <IconButton+ aria-label={`Remove ${collection.label}`}+ title="Remove notes folder"+ disabled={+ indexing || starting+ }+ onClick={() =>+ handleRemoveNotesCollection(+ collection.id,+ collection.label,+ )+ }+ sx={[+ actionButtonSx,+ { color: "text.muted" },+ ]}+ >+ <HugeiconsIcon+ icon={Delete01Icon}+ {...smallIconProps}+ />+ </IconButton>+ )}+ </Stack>+ {indexing && (+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ gap: 1,+ }}+ >+ <LinearProgress+ variant="determinate"+ value={progress ?? 0}+ sx={{ flex: 1 }}+ />+ <Typography+ variant="mini"+ sx={{ color: "text.muted" }}+ >+ {progress ?? 0}%+ </Typography>+ </Stack>+ )}+ {starting && <LinearProgress />}+ {waitingMessage && (+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ {waitingMessage}+ </Typography>+ )}+ {collection.lastError && (+ <Typography+ variant="small"+ sx={{ color: "critical.main" }}+ >+ {collection.lastError}+ </Typography>+ )}+ {collection.watcherError && (+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ {collection.watcherError}+ </Typography>+ )}+ {collection.status === "unavailable" &&+ !collection.lastError && (+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ Folder unavailable+ </Typography>+ )}+ {(canRetry ||+ collection.watcherError) && (+ <Button+ size="small"+ onClick={() =>+ handleIndexNotesCollection(+ collection.id,+ true,+ )+ }+ sx={{ alignSelf: "flex-start" }}+ >+ {canRetry+ ? "Try again"+ : "Refresh"}+ </Button>+ )}+ </Stack>+ );+ })}+ <ListItemButton+ disabled={notesCollectionsLoading}+ onClick={handleAddNotesFolder}+ sx={settingsItemSx}+ >+ <HugeiconsIcon+ icon={Folder01Icon}+ {...compactIconProps}+ />+ <Typography variant="small" sx={{ flex: 1 }}>+ Add notes folder+ </Typography>+ </ListItemButton>+ <Typography+ variant="small"+ sx={{ px: 2, color: "text.muted" }}+ >+ Ensu reads and indexes markdown files in the+ selected folder. Source files are never+ modified.+ </Typography>+ </Stack>+ </DialogContent></Dialog><Dialog@@ -1269,7 +1107,11 @@ export const ChatDialogs = memo(]}><IconButton- aria-label="Back to settings"+ aria-label={+ returnToIntroduction+ ? "Back to setup"+ : "Back to settings"+ }onClick={returnToSettings}sx={drawerIconButtonSx}>@@ -1281,7 +1123,214 @@ export const ChatDialogs = memo(<Box component="span">Ensu Packs</Box></DialogTitle><DialogContent>- {renderKnowledgeContent(false)}+ <Stack sx={{ gap: 2 }}>+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ Choose packs to use for your next messages in+ any chat.+ </Typography>+ {knowledgeCatalogError && (+ <Stack+ direction="row"+ sx={{ alignItems: "center", gap: 1 }}+ >+ <Typography+ variant="small"+ sx={{ flex: 1, color: "critical.main" }}+ >+ {knowledgeCatalogError}+ </Typography>+ <Button+ size="small"+ onClick={retryKnowledgeCatalog}+ >+ Retry+ </Button>+ </Stack>+ )}+ {knowledgeCatalogLoading && <LinearProgress />}+ {knowledgePacks.map((pack) => {+ const progress =+ knowledgeDownloadProgress[pack.stableId];+ const installed =+ pack.status === "ready" ||+ pack.status === "updateAvailable";+ const isMutating = progress !== undefined;+ const enabled =+ !disabledPackIds.includes(pack.stableId) &&+ installed;+ return (+ <Stack+ key={pack.stableId}+ sx={{+ gap: 1.5,+ p: 2,+ borderRadius: 2,+ bgcolor: "fill.faint",+ }}+ >+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ gap: 1.5,+ }}+ >+ <Stack sx={{ flex: 1, gap: 0.5 }}>+ <Typography variant="h6">+ {pack.label}+ </Typography>+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ gap: 0.75,+ }}+ >+ <Typography+ variant="mini"+ sx={{+ color: "text.muted",+ }}+ >+ {formatBytes(+ pack.downloadSizeBytes,+ )}+ </Typography>+ <Typography+ variant="mini"+ sx={{+ color: "text.muted",+ }}+ >+ ·+ </Typography>+ <Link+ component="button"+ type="button"+ underline="hover"+ onClick={() =>+ setAttributionPack(+ pack,+ )+ }+ sx={compactInlineLinkSx}+ >+ {+ pack.attribution+ .licenseLabel+ }+ </Link>+ </Stack>+ </Stack>+ {installed && !isMutating ? (+ <Switch+ checked={enabled}+ disabled={+ knowledgeCatalogLoading+ }+ onChange={(_, checked) =>+ handleSetPackEnabled(+ pack.stableId,+ checked,+ )+ }+ slotProps={{+ input: {+ "aria-label": `Use ${pack.label} for new messages`,+ },+ }}+ />+ ) : pack.status === "download" &&+ !isMutating ? (+ <Button+ variant="contained"+ color="accent"+ size="small"+ disabled={+ knowledgeCatalogLoading+ }+ onClick={() =>+ handleDownloadKnowledgePack(+ pack.stableId,+ )+ }+ >+ Download+ </Button>+ ) : null}+ </Stack>++ {isMutating && (+ <Stack+ direction="row"+ sx={{+ alignItems: "center",+ gap: 1,+ }}+ >+ <LinearProgress+ variant="determinate"+ value={Math.max(+ 0,+ Math.min(100, progress),+ )}+ sx={{ flex: 1 }}+ />+ <IconButton+ aria-label={`Cancel ${pack.label} download`}+ onClick={() =>+ handleCancelKnowledgePackDownload(+ pack.stableId,+ )+ }+ sx={actionButtonSx}+ >+ <HugeiconsIcon+ icon={Cancel01Icon}+ {...compactIconProps}+ />+ </IconButton>+ </Stack>+ )}++ {!isMutating &&+ pack.status ===+ "updateAvailable" && (+ <Button+ variant="contained"+ color="accent"+ size="small"+ disabled={+ knowledgeCatalogLoading+ }+ sx={{+ alignSelf: "flex-start",+ }}+ onClick={() =>+ handleDownloadKnowledgePack(+ pack.stableId,+ )+ }+ >+ Update+ </Button>+ )}++ {knowledgeErrors[pack.stableId] && (+ <Typography+ variant="small"+ sx={{ color: "critical.main" }}+ >+ {knowledgeErrors[pack.stableId]}+ </Typography>+ )}+ </Stack>+ );+ })}+ </Stack></DialogContent></Dialog>diff --git a/web/apps/ensu/src/components/chat/ChatInput.tsx b/web/apps/ensu/src/components/chat/ChatInput.tsxindex d6bae9148b..1e21a58f47 100644--- a/web/apps/ensu/src/components/chat/ChatInput.tsx+++ b/web/apps/ensu/src/components/chat/ChatInput.tsx@@ -1,12 +1,12 @@import {+ ImagePlusIcon,Navigation06Icon,- PackageIcon,- Upload01Icon,+ StopIcon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { Box, IconButton, InputBase, Tooltip } from "@mui/material";-import type { SxProps, Theme } from "@mui/material/styles";-import React, {+import { Box, IconButton, InputBase } from "@mui/material";+import { alpha, type SxProps, type Theme } from "@mui/material/styles";+import {forwardRef,memo,useImperativeHandle,@@ -15,6 +15,8 @@ import React, {useState,} from "react";+const sendButtonColor = "#E66A28";+interface IconProps {size: number;strokeWidth: number;@@ -28,7 +30,7 @@ export interface ChatInputHandle {interface ChatInputProps {actionIconProps: IconProps;disableAttachmentButton: boolean;- drawerIconButtonSx: SxProps<Theme>;+ drawerIconButtonSx: Exclude<SxProps<Theme>, readonly unknown[]>;handleSend: (input: string) => void | Promise<void>;handleStopGeneration: () => void;hasPendingAttachments: boolean;@@ -37,15 +39,11 @@ interface ChatInputProps {isDownloading: boolean;isGenerating: boolean;isModelPreparationActive: boolean;- openAttachmentMenu: (event: React.MouseEvent<HTMLElement>) => void;+ openPhotoPicker: () => void;onTextChange: (text: string) => void;- showSourcePicker: boolean;- openSources: () => void;- sourcesDisabled: boolean;sourcesLoading: boolean;isPreparingMessage: boolean;showAttachmentPicker: boolean;- stopButtonColor: string;}export const ChatInput = memo(@@ -62,15 +60,11 @@ export const ChatInput = memo(isDownloading,isGenerating,isModelPreparationActive,- openAttachmentMenu,+ openPhotoPicker,onTextChange,- showSourcePicker,- openSources,- sourcesDisabled,sourcesLoading,isPreparingMessage,showAttachmentPicker,- stopButtonColor,},ref,) {@@ -105,7 +99,7 @@ export const ChatInput = memo(sx={{display: "flex",alignItems: "center",- gap: 1,+ gap: 0.5,px: 1,py: 0.75,borderRadius: 2,@@ -115,44 +109,27 @@ export const ChatInput = memo(>{showAttachmentPicker && (<IconButton- aria-label="Add attachment"- sx={drawerIconButtonSx}+ aria-label="Add photos"disabled={disableAttachmentButton}- onClick={openAttachmentMenu}+ sx={[+ drawerIconButtonSx,+ { width: 32, p: 0, flexShrink: 0 },+ ]}+ onClick={openPhotoPicker}><HugeiconsIcon- icon={Upload01Icon}+ icon={ImagePlusIcon}{...actionIconProps}/></IconButton>)}- {showSourcePicker && (- <Tooltip title="Sources for this chat">- <span>- <IconButton- aria-label="Sources for this chat"- aria-haspopup="dialog"- sx={drawerIconButtonSx}- disabled={sourcesDisabled && !sourcesLoading}- onClick={openSources}- >- <HugeiconsIcon- icon={PackageIcon}- {...actionIconProps}- />- </IconButton>- </span>- </Tooltip>- )}<InputBasemultilineinputComponent="textarea"inputProps={{ rows: 1, type: undefined, wrap: "soft" }}inputRef={inputRef}placeholder={- isDownloading- ? "Downloading model..."- : "Write a message..."+ isDownloading ? "Downloading model..." : "Ask Ensu"}value={input}onPasteCapture={(event) => {@@ -185,7 +162,8 @@ export const ChatInput = memo(minWidth: 0,bgcolor: "transparent",borderRadius: 2,- px: 1.5,+ pl: 0,+ pr: 1.5,py: 1.5,minHeight: 48,display: "flex",@@ -215,48 +193,29 @@ export const ChatInput = memo(sx={{width: 44,height: 44,+ ml: 0.5,borderRadius: 2,bgcolor: "transparent",- color: isGenerating ? "critical.main" : "text.muted",+ color: sendButtonColor,"&:hover": { bgcolor: "fill.faint" },- "&.Mui-disabled": { color: "text.faint" },+ "&.Mui-disabled": {+ color: alpha(sendButtonColor, 0.45),+ },}}>- {isGenerating ? (- <Box- sx={{- width: 22,- height: 22,- minWidth: 22,- minHeight: 22,- borderRadius: "999px",- bgcolor: "#ffffff",- display: "inline-flex",- alignItems: "center",- justifyContent: "center",- }}- >- <Box- component="svg"- viewBox="0 0 24 24"- sx={{ width: 12, height: 12, display: "block" }}- >- <path- d="M4 12C4 8.72077 4 7.08116 4.81382 5.91891C5.1149 5.48891 5.48891 5.1149 5.91891 4.81382C7.08116 4 8.72077 4 12 4C15.2792 4 16.9188 4 18.0811 4.81382C18.5111 5.1149 18.8851 5.48891 19.1862 5.91891C20 7.08116 20 8.72077 20 12C20 15.2792 20 16.9188 19.1862 18.0811C18.8851 18.5111 18.5111 18.8851 18.0811 19.1862C16.9188 20 15.2792 20 12 20C8.72077 20 7.08116 20 5.91891 19.1862C5.48891 18.8851 5.1149 18.5111 4.81382 18.0811C4 16.9188 4 15.2792 4 12Z"- fill={stopButtonColor}- />- </Box>- </Box>- ) : (- <Box- sx={{ transform: "rotate(90deg)", display: "flex" }}- >- <HugeiconsIcon- icon={Navigation06Icon}- {...actionIconProps}- />- </Box>- )}+ <Box+ sx={{+ transform: isGenerating+ ? undefined+ : "rotate(90deg)",+ display: "flex",+ }}+ >+ <HugeiconsIcon+ icon={isGenerating ? StopIcon : Navigation06Icon}+ {...actionIconProps}+ />+ </Box></IconButton></Box>);diff --git a/web/apps/ensu/src/components/chat/SourceIntroductionDialog.tsx b/web/apps/ensu/src/components/chat/SourceIntroductionDialog.tsxnew file mode 100644index 0000000000..6c2f83bdc6--- /dev/null+++ b/web/apps/ensu/src/components/chat/SourceIntroductionDialog.tsx@@ -0,0 +1,112 @@+import { Button, Dialog, Stack, Typography } from "@mui/material";+import React from "react";++interface SourceIntroductionDialogProps {+ open: boolean;+ onClose: () => void;+ onSetUpPacks: () => void;+ onSetUpNotes: () => void;+}++export const SourceIntroductionDialog: React.FC<+ SourceIntroductionDialogProps+> = ({ open, onClose, onSetUpPacks, onSetUpNotes }) => (+ <Dialog+ open={open}+ onClose={onClose}+ maxWidth="sm"+ fullWidth+ aria-labelledby="source-introduction-title"+ slotProps={{+ paper: { sx: { borderRadius: 3, bgcolor: "background.default" } },+ }}+ >+ <Stack sx={{ p: 3, gap: 2 }}>+ <Stack sx={{ gap: 1 }}>+ <Typography id="source-introduction-title" variant="h3">+ Give Ensu more context+ </Typography>+ <Typography variant="small" sx={{ color: "text.muted" }}>+ Add a knowledge pack or your notes to help Ensu answer+ accurately.+ </Typography>+ </Stack>+ <Stack sx={{ gap: 1.5 }}>+ {[+ {+ title: "Ensu Packs",+ description:+ "Knowledge from Wikipedia to help Ensu get factual questions right.",+ onSetUp: onSetUpPacks,+ },+ {+ title: "Your Notes",+ description:+ "Use a local Markdown notes folder to chat with your own knowledge base.",+ onSetUp: onSetUpNotes,+ },+ ].map(({ title, description, onSetUp }) => (+ <Stack+ key={title}+ sx={{+ p: 2,+ gap: 1,+ borderRadius: 2,+ bgcolor: "fill.faint",+ }}+ >+ <Typography variant="h6">{title}</Typography>+ <Typography+ variant="small"+ sx={{ color: "text.muted" }}+ >+ {description}+ </Typography>+ <Button+ variant="contained"+ color="accent"+ size="large"+ aria-label={`Set up ${title}`}+ sx={{+ alignSelf: "flex-start",+ minHeight: 48,+ px: 3,+ typography: "body",+ fontWeight: 600,+ }}+ onClick={onSetUp}+ >+ Set up+ </Button>+ </Stack>+ ))}+ </Stack>+ <Stack sx={{ gap: 0.5, alignItems: "center" }}>+ <Button+ variant="text"+ size="small"+ sx={{+ color: "text.primary",+ textDecoration: "underline",+ textUnderlineOffset: "3px",+ "&:hover": { textDecoration: "underline" },+ }}+ onClick={onClose}+ >+ Not now+ </Button>+ <Typography+ variant="mini"+ sx={{+ color: "text.muted",+ fontWeight: 400,+ textAlign: "center",+ }}+ >+ You can set up Ensu Packs and Your Notes later from+ Settings.+ </Typography>+ </Stack>+ </Stack>+ </Dialog>+);diff --git a/web/apps/ensu/src/components/utils/use-file-input.ts b/web/apps/ensu/src/components/utils/use-file-input.tsdeleted file mode 100644index 1731833b05..0000000000--- a/web/apps/ensu/src/components/utils/use-file-input.ts+++ /dev/null@@ -1,75 +0,0 @@-import { useCallback, useRef } from "react";--interface UseFileInputParams {- directory?: boolean;- accept?: string;- onSelect: (selectedFiles: File[]) => void;- onCancel: () => void;-}--interface UseFileInputResult {- getInputProps: () => React.HTMLAttributes<HTMLInputElement>;- openSelector: () => void;-}--export const useFileInput = ({- directory,- accept,- onSelect,- onCancel,-}: UseFileInputParams): UseFileInputResult => {- const inputRef = useRef<HTMLInputElement | null>(null);-- const handleInputRef = useCallback(- (node: HTMLInputElement | null) => {- if (inputRef.current) {- inputRef.current.removeEventListener("cancel", onCancel);- }-- inputRef.current = node;-- if (inputRef.current) {- inputRef.current.addEventListener("cancel", onCancel);- }- },- [onCancel],- );-- const openSelector = useCallback(() => {- const input = inputRef.current;- if (!input) return;-- input.value = "";- input.click();- }, []);-- const handleChange: React.ChangeEventHandler<HTMLInputElement> = (- event,- ) => {- const files = event.target.files;- if (files?.length) {- onSelect([...files]);- } else {- onCancel();- }- };-- const directoryOpts = directory- ? { directory: "", webkitdirectory: "" }- : {};-- const getInputProps = useCallback(- () => ({- type: "file",- multiple: true,- style: { display: "none" },- ...directoryOpts,- ref: handleInputRef,- onChange: handleChange,- ...(accept && { accept }),- }),- [directoryOpts, accept, handleChange, handleInputRef],- );-- return { getInputProps, openSelector };-};diff --git a/web/apps/ensu/src/hooks/use-chat-sources.ts b/web/apps/ensu/src/hooks/use-chat-sources.tsindex 0df6663477..67fbed7428 100644--- a/web/apps/ensu/src/hooks/use-chat-sources.ts+++ b/web/apps/ensu/src/hooks/use-chat-sources.ts@@ -6,12 +6,12 @@ import log from "ente-base/log";import { useCallback, useEffect, useRef, useState } from "react";export const useChatSources = (- sessionId: string | undefined,- defaults: ChatSourceSelection,- inventoryReady: boolean,+ available: ChatSourceSelection,+ packInventoryReady: boolean,+ notesInventoryReady: boolean,) => {- const [draftId, setDraftId] = useState("draft:initial");- const [revision, setRevision] = useState(0);+ const [, setRevision] = useState(0);+ const [packSettingsReady, setPackSettingsReady] = useState(false);const storeRef = useRef<ChatSourceSelectionStore | null>(null);if (!storeRef.current) {storeRef.current = new ChatSourceSelectionStore(@@ -20,49 +20,37 @@ export const useChatSources = ();}const store = storeRef.current;- const targetId = sessionId ?? draftId;- const selection = store.get(targetId);+ const inventoryReady =+ packInventoryReady && packSettingsReady && notesInventoryReady;+ const selection = inventoryReady ? store.selection(available) : undefined;useEffect(() => {- if (!inventoryReady || store.get(targetId)) return;- store.initialize(targetId, defaults);- setRevision((value) => value + 1);- }, [defaults, inventoryReady, revision, store, targetId]);+ if (!packInventoryReady) return;+ store.migratePackSettings(available.packIds);+ setPackSettingsReady(true);+ }, [available.packIds, packInventoryReady, store]);- const setEnabled = useCallback(- (- target: string,- kind: keyof ChatSourceSelection,- sourceId: string,- enabled: boolean,- ) => {- store.setEnabled(target, kind, sourceId, enabled);+ const setPackEnabled = useCallback(+ (id: string, enabled: boolean) => {+ if (!packInventoryReady) return;+ store.setPackEnabled(id, enabled, available.packIds);setRevision((value) => value + 1);},- [store],+ [available.packIds, packInventoryReady, store],);- const transferDraft = useCallback(- (session: string) => {- store.transferDraft(draftId, session);- setRevision((value) => value + 1);- },- [draftId, store],- );- const resetDraft = useCallback(() => {- setDraftId(`draft:${crypto.randomUUID()}`);- }, []);- const removeSelection = useCallback(- (session: string) => {- store.remove(session);+ const setNoteEnabled = useCallback(+ (id: string, enabled: boolean) => {+ store.setNoteEnabled(id, enabled);setRevision((value) => value + 1);},[store],);+return {selection,- targetId,- setEnabled,- transferDraft,- resetDraft,- removeSelection,+ packSettingsReady: packInventoryReady && packSettingsReady,+ disabledNoteIds: store.disabledNoteIds(),+ disabledPackIds: store.disabledPackIds(),+ setPackEnabled,+ setNoteEnabled,};};diff --git a/web/apps/ensu/src/hooks/use-notes-collections.ts b/web/apps/ensu/src/hooks/use-notes-collections.tsindex 3cc9ac999c..373b821ee1 100644--- a/web/apps/ensu/src/hooks/use-notes-collections.ts+++ b/web/apps/ensu/src/hooks/use-notes-collections.ts@@ -25,7 +25,8 @@ const NOTES_REMOVE_WAIT_ERROR =interface UseNotesCollectionsOptions {isTauriRuntime: boolean;isGenerating: boolean;- isGenerationActive: () => boolean;+ isIndexingPaused: boolean;+ isIndexingBlocked: () => boolean;modelReady: boolean;ensureProvider: () => Promise<LlmProvider>;cancelIndexing: () => void;@@ -35,7 +36,8 @@ interface UseNotesCollectionsOptions {export const useNotesCollections = ({isTauriRuntime,isGenerating,- isGenerationActive,+ isIndexingPaused,+ isIndexingBlocked,modelReady,ensureProvider,cancelIndexing,@@ -70,7 +72,7 @@ export const useNotesCollections = ({}, [cancelIndexing, controller]);const refresh = useCallback(async () => {- if (!isTauriRuntime) return;+ if (!isTauriRuntime) return false;const request = controller.beginRefresh();setLoading(true);try {@@ -78,27 +80,28 @@ export const useNotesCollections = ({const mutation = controller.refreshMutationSnapshot();try {const next = await listNotesCollections();- if (!controller.isRefreshCurrent(request)) return;+ if (!controller.isRefreshCurrent(request)) return false;if (!controller.canApplyRefresh(request, mutation)) {continue;}setCollections(next);setLoaded(true);setListError(null);- return;+ return true;} catch (error) {- if (!controller.isRefreshCurrent(request)) return;+ if (!controller.isRefreshCurrent(request)) return false;if (!controller.canApplyRefresh(request, mutation)) {continue;}setListError(notesErrorMessage(error));log.error("Failed to refresh Your Notes", error);- return;+ return false;}}} finally {if (controller.isRefreshCurrent(request)) setLoading(false);}+ return false;}, [controller, isTauriRuntime]);const replaceCollection = useCallback(@@ -137,7 +140,7 @@ export const useNotesCollections = ({automatic = false,automaticRequestKey?: number,) => {- const blocked = !modelReady || isGenerationActive();+ const blocked = !modelReady || isIndexingBlocked();const request = automatic? controller.ensureIndex(collectionId,@@ -159,14 +162,14 @@ export const useNotesCollections = ({});const ownsIndex = () => controller.canContinueIndex(collectionId);- const canStartIndex = () => ownsIndex() && !isGenerationActive();+ const canStartIndex = () => ownsIndex() && !isIndexingBlocked();void ensureProvider().then((provider) =>provider.withKnowledgeRetrieval(async (retrievalEpoch) => {let needsRerun = true;let bypassQuietPeriod = force;while (needsRerun && ownsIndex()) {- if (isGenerationActive()) {+ if (isIndexingBlocked()) {controller.queueIndex(collectionId,bypassQuietPeriod,@@ -227,7 +230,7 @@ export const useNotesCollections = ({[controller,ensureProvider,- isGenerationActive,+ isIndexingBlocked,lifecycleChanged,modelReady,refresh,@@ -242,7 +245,7 @@ export const useNotesCollections = ({);useEffect(() => {- const blocked = !modelReady || isGenerationActive();+ const blocked = !modelReady || isIndexingBlocked();const queued = controller.drainQueued(blocked);if (queued.length > 0) {lifecycleChanged();@@ -253,7 +256,8 @@ export const useNotesCollections = ({}, [controller,isGenerating,- isGenerationActive,+ isIndexingPaused,+ isIndexingBlocked,lifecycleChanged,lifecycleRevision,modelReady,@@ -345,21 +349,24 @@ export const useNotesCollections = ({setSyncAttempt((attempt) => attempt + 1);}, []);- const addFolder = useCallback(async () => {- setOperationError(null);- try {- const sourceRoot = await selectNotesFolder();- if (!sourceRoot) return;- const collection = await addNotesCollection(sourceRoot);- replaceCollection(collection);- runIndex(collection.id);- return collection;- } catch (error) {- setOperationError(notesErrorMessage(error));- log.error("Failed to add Notes folder", error);- }- return undefined;- }, [replaceCollection, runIndex]);+ const addFolder = useCallback(+ async (onAdded?: (collection: NotesCollection) => void) => {+ setOperationError(null);+ try {+ if (!loaded && !(await refresh())) return;+ const sourceRoot = await selectNotesFolder();+ if (!sourceRoot) return;+ const collection = await addNotesCollection(sourceRoot);+ onAdded?.(collection);+ replaceCollection(collection);+ runIndex(collection.id);+ } catch (error) {+ setOperationError(notesErrorMessage(error));+ log.error("Failed to add Notes folder", error);+ }+ },+ [loaded, refresh, replaceCollection, runIndex],+ );const removeCollection = useCallback((collectionId: string, label: string) => {@@ -410,16 +417,20 @@ export const useNotesCollections = ({} else if (lifecycleActivity === "queued") {activity = !modelReady? "waitingForModel"- : isGenerating || isGenerationActive()- ? "waitingForGeneration"- : "starting";+ : isIndexingPaused+ ? "waitingForChat"+ : isGenerating || isIndexingBlocked()+ ? "waitingForGeneration"+ : "starting";} else if (collection.updateDueAtMs != null) {activity = null;} else if (collection.status !== "pending") {activity = null;} else if (!modelReady) {activity = "waitingForModel";- } else if (isGenerating || isGenerationActive()) {+ } else if (isIndexingPaused) {+ activity = "waitingForChat";+ } else if (isGenerating || isIndexingBlocked()) {activity = "waitingForGeneration";} else {activity = "starting";@@ -430,7 +441,8 @@ export const useNotesCollections = ({collections,controller,isGenerating,- isGenerationActive,+ isIndexingPaused,+ isIndexingBlocked,lifecycleRevision,modelReady,],diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex 565de8e673..e507ed2863 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -5,7 +5,6 @@ import {import { ChatDialogs } from "@/components/chat/ChatDialogs";import { ChatMessageList } from "@/components/chat/ChatMessageList";import { ChatSidebar } from "@/components/chat/ChatSidebar";-import { useFileInput } from "@/components/utils/use-file-input";import { useChatSources } from "@/hooks/use-chat-sources";import { useNotesCollections } from "@/hooks/use-notes-collections";import { handleManualAppUpdateCheck } from "@/services/app-update";@@ -22,6 +21,7 @@ import {initChatKeyStore,} from "@/services/chat/chat-key";import { initializeChatStorePersistence } from "@/services/chat/persistence";+import type { ChatSourceSelection } from "@/services/chat/source-selection";import {addMessage,createSession,@@ -69,6 +69,7 @@ import type {ModelInfo,ModelSettings,} from "@/services/llm/types";+import { NotesIndexingIdleScheduler } from "@/services/notes-indexing-idle";import { tauriCommandError } from "@/services/tauri-error";import { isTauriRuntime as detectTauriAppRuntime } from "@/services/tauri-runtime";import { Menu01Icon } from "@hugeicons/core-free-icons";@@ -217,9 +218,6 @@ const IMAGE_SELECTOR_EXTENSIONS = ["heif","avif",] as const;-const IMAGE_SELECTOR_ACCEPT = IMAGE_SELECTOR_EXTENSIONS.map(- (ext) => `.${ext}`,-).join(",");const MAX_IMAGE_ATTACHMENTS_PER_MESSAGE = 2;const buildPromptWithImages = (text: string, imageCount: number) => {@@ -559,9 +557,12 @@ const Page: React.FC = () => {string | null>(null);const [knowledgeCatalogLoaded, setKnowledgeCatalogLoaded] = useState(false);- const [showSources, setShowSources] = useState(false);const [isPreparingMessage, setIsPreparingMessage] = useState(false);const pendingSendRef = useRef(false);+ const settingsFlowOpenRef = useRef(false);+ const notesWarmupEpochRef = useRef(0);+ const notesIndexingPausedRef = useRef(false);+ const [notesIndexingPaused, setNotesIndexingPaused] = useState(false);const [knowledgeDownloadProgress, setKnowledgeDownloadProgress] = useState<Record<string, number | undefined>>({});@@ -587,8 +588,6 @@ const Page: React.FC = () => {DocumentAttachment[]>([]);const [pendingImages, setPendingImages] = useState<ImageAttachment[]>([]);- const [attachmentAnchor, setAttachmentAnchor] =- useState<HTMLElement | null>(null);const [chatNotification, setChatNotification] = useState<NotificationAttributes | undefined>(undefined);@@ -1765,13 +1764,55 @@ const Page: React.FC = () => {return providerRef.current;}, []);- const isNotesGenerationActive = useCallback(+ const isChatBusy = useCallback(() =>pendingSendRef.current ||generationActiveRef.current ||sessionSummaryActiveRef.current,[],);+ const notesIdleSchedulerRef = useRef<NotesIndexingIdleScheduler | null>(+ null,+ );+ if (!notesIdleSchedulerRef.current) {+ notesIdleSchedulerRef.current = new NotesIndexingIdleScheduler(+ () => {+ notesIndexingPausedRef.current = false;+ setNotesIndexingPaused(false);+ },+ isChatBusy,+ {+ schedule: (callback, delayMs) =>+ window.setTimeout(callback, delayMs),+ cancel: (handle) => window.clearTimeout(handle),+ },+ );+ }+ const notesIdleScheduler = notesIdleSchedulerRef.current;+ useEffect(+ () => () => {+ notesWarmupEpochRef.current += 1;+ notesIdleScheduler.cancel();+ },+ [notesIdleScheduler],+ );+ const handleChatActivity = useCallback(+ () => notesIdleScheduler.activity(),+ [notesIdleScheduler],+ );+ useEffect(() => {+ handleChatActivity();+ }, [+ handleChatActivity,+ isPreparingMessage,+ isGenerating,+ isSessionSummaryGenerating,+ ]);++ const isIndexingBlocked = useCallback(+ () => notesIndexingPausedRef.current || isChatBusy(),+ [isChatBusy],+ );const cancelNotesIndexing = useCallback(() => {const provider = providerRef.current;if (provider?.getBackendKind() === "tauri") {@@ -1800,21 +1841,22 @@ const Page: React.FC = () => {loaded: notesCollectionsLoaded,error: notesCollectionsError,retry: retryNotesCollections,- addFolder: handleAddNotesFolder,+ addFolder: addNotesFolder,removeCollection: handleRemoveNotesCollection,runIndex: runNotesIndex,} = useNotesCollections({isTauriRuntime,isGenerating:isPreparingMessage || isGenerating || isSessionSummaryGenerating,- isGenerationActive: isNotesGenerationActive,+ isIndexingPaused: notesIndexingPaused,+ isIndexingBlocked,modelReady: modelGateStatus === "ready",ensureProvider,cancelIndexing: cancelNotesIndexing,confirmRemoval: confirmNotesRemoval,});- const sourceDefaults = useMemo(+ const availableSources = useMemo(() => ({packIds: knowledgePacks.filter(@@ -1831,80 +1873,28 @@ const Page: React.FC = () => {);const {selection: sourceSelection,- targetId: sourceSelectionTarget,- setEnabled: setChatSourceEnabled,- transferDraft: transferDraftSources,- resetDraft: resetDraftSources,- removeSelection: removeChatSources,+ packSettingsReady,+ disabledNoteIds,+ disabledPackIds,+ setPackEnabled: handleSetPackEnabled,+ setNoteEnabled: handleSetNotesEnabled,} = useChatSources(- currentSessionId,- sourceDefaults,- isTauriRuntime && knowledgeCatalogLoaded && notesCollectionsLoaded,- );- const enabledKnowledgePackIds = useMemo(- () => new Set(sourceSelection?.packIds ?? []),- [sourceSelection],- );- const enabledNoteCollectionIds = useMemo(- () => new Set(sourceSelection?.noteCollectionIds ?? []),- [sourceSelection],+ availableSources,+ isTauriRuntime && knowledgeCatalogLoaded,+ notesCollectionsLoaded,);const sourcesReady =Boolean(sourceSelection) &&knowledgeCatalogLoaded &¬esCollectionsLoaded;- const sourceSelectionDisabled =- isPreparingMessage ||- isGenerating ||- isSessionSummaryGenerating ||- !sourcesReady;- const openSources = useCallback(() => setShowSources(true), []);- const closeSources = useCallback(() => setShowSources(false), []);- const handleSetKnowledgePackEnabled = useCallback(- (stableId: string, enabled: boolean) => {- if (isNotesGenerationActive() || !sourceSelection) return;- setChatSourceEnabled(- sourceSelectionTarget,- "packIds",- stableId,- enabled,- );- },- [- isNotesGenerationActive,- setChatSourceEnabled,- sourceSelection,- sourceSelectionTarget,- ],- );- const handleSetNotesCollectionEnabled = useCallback(- (collectionId: string, enabled: boolean) => {- if (isNotesGenerationActive() || !sourceSelection) return;- setChatSourceEnabled(- sourceSelectionTarget,- "noteCollectionIds",- collectionId,- enabled,- );- },- [- isNotesGenerationActive,- setChatSourceEnabled,- sourceSelection,- sourceSelectionTarget,- ],+ const handleAddNotesFolder = useCallback(+ () =>+ addNotesFolder((collection) => {+ if (!notesCollections.some((item) => item.id === collection.id))+ handleSetNotesEnabled(collection.id, true);+ }),+ [addNotesFolder, handleSetNotesEnabled, notesCollections],);- const handleAddChatNotesFolder = useCallback(async () => {- const target = sourceSelectionTarget;- const collection = await handleAddNotesFolder();- if (collection)- setChatSourceEnabled(- target,- "noteCollectionIds",- collection.id,- true,- );- }, [handleAddNotesFolder, setChatSourceEnabled, sourceSelectionTarget]);const getModelSettings = useCallback((): ModelSettings => {return {@@ -2266,6 +2256,55 @@ const Page: React.FC = () => {}}, [ensureProvider, formatErrorMessage, getModelSettings, showMiniDialog]);+ const handleSettingsFlowVisibilityChange = useCallback(+ (open: boolean) => {+ if (!isTauriRuntime) return;+ if (settingsFlowOpenRef.current === open) return;+ settingsFlowOpenRef.current = open;+ const epoch = ++notesWarmupEpochRef.current;+ if (open) {+ notesIdleScheduler.resumeNow();+ return;+ }+ notesIdleScheduler.cancel();+ notesIndexingPausedRef.current = true;+ setNotesIndexingPaused(true);+ void (async () => {+ try {+ const canRestoreChat = () =>+ notesWarmupEpochRef.current === epoch &&+ !settingsFlowOpenRef.current &&+ !isChatBusy();+ if (!canRestoreChat()) return;+ const provider = await ensureProvider();+ if (!canRestoreChat()) return;+ await provider.cancelGeneration(-1);+ if (!canRestoreChat()) return;+ await provider.ensureModelReady(getModelSettings());+ if (!canRestoreChat()) return;+ setLoadedModelName(+ provider.getCurrentModel()?.name ?? null,+ );+ } catch (error) {+ log.warn("Failed to restore chat model after Notes", error);+ } finally {+ if (+ notesWarmupEpochRef.current === epoch &&+ !settingsFlowOpenRef.current+ )+ notesIdleScheduler.defer();+ }+ })();+ },+ [+ ensureProvider,+ getModelSettings,+ isChatBusy,+ isTauriRuntime,+ notesIdleScheduler,+ ],+ );+const prewarmSelectedImageInference = useCallback(() => {if (!isTauriRuntime) return;void (async () => {@@ -2490,8 +2529,6 @@ const Page: React.FC = () => {const handleNewChat = useCallback(() => {cancelActiveGenerationForNavigation();- resetDraftSources();- setShowSources(false);setCurrentSessionId(undefined);currentSessionIdRef.current = undefined;setAllMessages([]);@@ -2516,14 +2553,12 @@ const Page: React.FC = () => {focusInput,isSmall,resetPendingImages,- resetDraftSources,updateRouteSession,]);const handleSelectSession = useCallback((sessionId: string) => {cancelActiveGenerationForNavigation();- setShowSources(false);setCurrentSessionId(sessionId);currentSessionIdRef.current = sessionId;setIsDraftSession(false);@@ -2543,7 +2578,6 @@ const Page: React.FC = () => {const removeSessionFromState = useCallback((sessionId: string) => {manuallyRenamedSessionIdsRef.current.delete(sessionId);- removeChatSources(sessionId);setSessions((prev) =>prev.filter((session) => session.sessionUuid !== sessionId),);@@ -2552,8 +2586,6 @@ const Page: React.FC = () => {);if (currentSessionIdRef.current === sessionId) {- resetDraftSources();- setShowSources(false);setCurrentSessionId(undefined);currentSessionIdRef.current = undefined;setIsDraftSession(true);@@ -2561,7 +2593,7 @@ const Page: React.FC = () => {updateRouteSession(undefined, true);}},- [removeChatSources, resetDraftSources, updateRouteSession],+ [updateRouteSession],);const handleDeleteSession = useCallback(@@ -2989,6 +3021,7 @@ const Page: React.FC = () => {sessionUuid,imagePaths,mediaMarker,+ sources = sourceSelection,}: {promptText: string;parentMessage: ChatMessage;@@ -2998,6 +3031,7 @@ const Page: React.FC = () => {sessionUuid?: string;imagePaths?: string[];mediaMarker?: string;+ sources?: ChatSourceSelection;}): Promise<void> => {const parentMessageUuid = parentMessage.messageUuid;const activeSessionId =@@ -3009,9 +3043,9 @@ const Page: React.FC = () => {) {return;}- if (isTauriRuntime && !sourcesReady) return;- const selectedPackIds = new Set(sourceSelection?.packIds);- const selectedNoteIds = new Set(sourceSelection?.noteCollectionIds);+ if (isTauriRuntime && !sources) return;+ const selectedPackIds = new Set(sources?.packIds);+ const selectedNoteIds = new Set(sources?.noteCollectionIds);generationStartingRef.current = true;generationActiveRef.current = true;setIsGenerating(true);@@ -3529,7 +3563,6 @@ const Page: React.FC = () => {systemPrompt,isTauriRuntime,sourceSelection,- sourcesReady,knowledgePacks,notesCollections,],@@ -3572,6 +3605,7 @@ const Page: React.FC = () => {return;}const historyPath = slicePathUntil(messageState.path, parentUuid);+ handleChatActivity();await startGeneration({promptText: parentMessage.text,parentMessage,@@ -3583,6 +3617,7 @@ const Page: React.FC = () => {},[allMessages,+ handleChatActivity,chatKey,currentSessionId,isDownloading,@@ -3772,9 +3807,15 @@ const Page: React.FC = () => {[],);const handleDownloadKnowledgePack = useCallback(- (stableId: string, selectForChat?: string) => {+ (stableId: string) => {if (activeKnowledgeDownloadsRef.current.has(stableId)) return;activeKnowledgeDownloadsRef.current.add(stableId);+ const isNew = !knowledgePacks.some(+ (pack) =>+ pack.stableId === stableId &&+ (pack.status === "ready" ||+ pack.status === "updateAvailable"),+ );setKnowledgeErrors((current) => ({...current,@@ -3791,18 +3832,12 @@ const Page: React.FC = () => {}));}).then((pack) => {+ if (isNew) handleSetPackEnabled(stableId, true);setKnowledgePacks((current) =>current.map((item) =>item.stableId === stableId ? pack : item,),);- if (selectForChat)- setChatSourceEnabled(- selectForChat,- "packIds",- stableId,- true,- );}).catch((error: unknown) => {const { name } = tauriCommandError(error);@@ -3822,7 +3857,7 @@ const Page: React.FC = () => {}));});},- [refreshKnowledgeCatalog, setChatSourceEnabled],+ [refreshKnowledgeCatalog, knowledgePacks, handleSetPackEnabled],);const handleCancelKnowledgePackDownload = useCallback((stableId: string) => {@@ -3834,22 +3869,6 @@ const Page: React.FC = () => {},[],);- const handleDownloadChatKnowledgePack = useCallback(- (stableId: string) => {- const installed = knowledgePacks.some(- (pack) =>- pack.stableId === stableId &&- (pack.status === "ready" ||- pack.status === "updateAvailable"),- );- handleDownloadKnowledgePack(- stableId,- installed ? undefined : sourceSelectionTarget,- );- },- [handleDownloadKnowledgePack, knowledgePacks, sourceSelectionTarget],- );-const handleBuildVersionTap = useCallback(() => {if (advancedUnlocked || typeof window === "undefined") return;if (buildVersionTapTimeoutRef.current) {@@ -3951,61 +3970,6 @@ const Page: React.FC = () => {setShowSystemPromptSettings(false);}, []);- const closeAttachmentMenu = useCallback(() => {- setAttachmentAnchor(null);- }, []);-- const handleDocumentSelect = useCallback(- (files: File[]) => {- closeAttachmentMenu();- void (async () => {- const results = await Promise.allSettled(- files.map(async (file) => ({- id: createDocumentId(),- name: file.name,- text: await file.text(),- size: file.size,- })),- );-- const successful = results- .filter(- (- result,- ): result is PromiseFulfilledResult<DocumentAttachment> =>- result.status === "fulfilled",- )- .map((result) => result.value);-- if (successful.length) {- setPendingDocuments((prev) => [...prev, ...successful]);- }-- const failed = results.length - successful.length;- if (failed > 0) {- showMiniDialog({- title: "Some documents failed",- message:- "We could not read some documents. Please try again.",- });- }- })();- },- [closeAttachmentMenu, showMiniDialog],- );-- const handleDocumentCancel = useCallback(() => {- closeAttachmentMenu();- }, [closeAttachmentMenu]);-- const {- getInputProps: getDocumentInputProps,- openSelector: openDocumentSelector,- } = useFileInput({- directory: false,- onSelect: handleDocumentSelect,- onCancel: handleDocumentCancel,- });const imageAttachmentSlotsRemaining = Math.max(0,MAX_IMAGE_ATTACHMENTS_PER_MESSAGE - pendingImages.length,@@ -4033,7 +3997,6 @@ const Page: React.FC = () => {const handleImageSelect = useCallback((files: File[]) => {- closeAttachmentMenu();if (imageAttachmentSlotsRemaining <= 0) return;const images = files.map((file) => ({id: createAttachmentId(),@@ -4052,23 +4015,9 @@ const Page: React.FC = () => {});}},- [closeAttachmentMenu, imageAttachmentSlotsRemaining],+ [imageAttachmentSlotsRemaining],);- const handleImageCancel = useCallback(() => {- closeAttachmentMenu();- }, [closeAttachmentMenu]);-- const {- getInputProps: getImageInputProps,- openSelector: openImageSelector,- } = useFileInput({- directory: false,- accept: IMAGE_SELECTOR_ACCEPT,- onSelect: handleImageSelect,- onCancel: handleImageCancel,- });-const processTauriImagePaths = useCallback(async (selectedPaths: string[], source: "picker" | "drop") => {if (imageAttachmentSlotsRemaining <= 0) return;@@ -4077,7 +4026,6 @@ const Page: React.FC = () => {imageAttachmentSlotsRemaining,);if (pathsToProcess.length === 0) {- handleImageCancel();return;}@@ -4121,8 +4069,6 @@ const Page: React.FC = () => {if (files.length > 0) {handleImageSelect(files);prewarmSelectedImageInference();- } else {- handleImageCancel();}} catch (error) {if (epoch !== imageAttachmentEpochRef.current) return;@@ -4140,7 +4086,6 @@ const Page: React.FC = () => {}},[- handleImageCancel,handleImageSelect,imageAttachmentSlotsRemaining,prewarmSelectedImageInference,@@ -4149,7 +4094,6 @@ const Page: React.FC = () => {);const openTauriImageSelector = useCallback(async () => {- closeAttachmentMenu();if (imageAttachmentSlotsRemaining <= 0) return;try {const { open: openFileDialog } =@@ -4165,14 +4109,12 @@ const Page: React.FC = () => {],});if (!selection) {- handleImageCancel();return;}const selectedPaths = Array.isArray(selection)? selection: [selection];if (selectedPaths.length === 0) {- handleImageCancel();return;}await processTauriImagePaths(selectedPaths, "picker");@@ -4183,13 +4125,7 @@ const Page: React.FC = () => {message: "Could not open the image picker. Please try again.",});}- }, [- closeAttachmentMenu,- handleImageCancel,- imageAttachmentSlotsRemaining,- processTauriImagePaths,- showMiniDialog,- ]);+ }, [imageAttachmentSlotsRemaining, processTauriImagePaths, showMiniDialog]);useEffect(() => {if (!isTauriRuntime || !showImageAttachment) return;@@ -4270,40 +4206,15 @@ const Page: React.FC = () => {showMiniDialog,]);- const openAttachmentMenu = useCallback(() => {- closeAttachmentMenu();- if (showImageAttachment) {- if (isImageAttachmentLimitReached) return;- void openTauriImageSelector();- return;- }- openDocumentSelector();+ const openPhotoPicker = useCallback(() => {+ if (!showImageAttachment || isImageAttachmentLimitReached) return;+ void openTauriImageSelector();}, [- closeAttachmentMenu,+ showImageAttachment,isImageAttachmentLimitReached,- openDocumentSelector,openTauriImageSelector,- showImageAttachment,]);- const handleAttachmentChoice = useCallback(- (choice: "image" | "document") => {- closeAttachmentMenu();- if (choice === "image") {- if (isImageAttachmentLimitReached) return;- openImageSelector();- } else {- openDocumentSelector();- }- },- [- closeAttachmentMenu,- isImageAttachmentLimitReached,- openDocumentSelector,- openImageSelector,- ],- );-const removePendingDocument = useCallback((id: string) => {setPendingDocuments((prev) => prev.filter((doc) => doc.id !== id));}, []);@@ -4353,7 +4264,9 @@ const Page: React.FC = () => {}pendingSendRef.current = true;+ handleChatActivity();setIsPreparingMessage(true);+ const messageSources = sourceSelection;try {setStickToBottom(true);@@ -4365,7 +4278,6 @@ const Page: React.FC = () => {onGenericError(error);return;}- transferDraftSources(activeSessionId);setCurrentSessionId(activeSessionId);currentSessionIdRef.current = activeSessionId;setIsDraftSession(false);@@ -4522,6 +4434,7 @@ const Page: React.FC = () => {sessionUuid: activeSessionId,imagePaths: inferenceImagePaths,mediaMarker: MEDIA_MARKER,+ sources: messageSources,});return;}@@ -4557,6 +4470,7 @@ const Page: React.FC = () => {sessionUuid: activeSessionId,imagePaths: inferenceImagePaths,mediaMarker: MEDIA_MARKER,+ sources: messageSources,});} catch (error) {if (!messageStored) await cleanupUnstoredAttachments();@@ -4809,36 +4723,36 @@ const Page: React.FC = () => {formatBytes={formatBytes}isGenerating={isGenerating}handleSend={handleSend}+ onActivity={handleChatActivity}handleStopGeneration={handleStopGeneration}- showSourcePicker={isTauriRuntime}- openSources={openSources}+ retrySources={+ knowledgeCatalogError || notesCollectionsError+ ? () => {+ void refreshKnowledgeCatalog();+ retryNotesCollections();+ }+ : undefined+ }isPreparingMessage={isPreparingMessage}- sourcesDisabled={sourceSelectionDisabled}sourcesLoading={isTauriRuntime && !sourcesReady}sourcesStatus={isTauriRuntime && !sourcesReady? knowledgeCatalogError || notesCollectionsError- ? "Couldn’t load sources. Open Sources to retry."+ ? "Couldn’t load sources. Try again.": "Loading sources for this chat…": undefined}showAttachmentPicker={isTauriRuntime}- openAttachmentMenu={openAttachmentMenu}- attachmentAnchor={attachmentAnchor}- closeAttachmentMenu={closeAttachmentMenu}- handleAttachmentChoice={handleAttachmentChoice}+ openPhotoPicker={openPhotoPicker}showImageAttachment={showImageAttachment}isImageAttachmentLimitReached={isImageAttachmentLimitReached}- getDocumentInputProps={getDocumentInputProps}- getImageInputProps={getImageInputProps}actionButtonSx={actionButtonSx}drawerIconButtonSx={drawerIconButtonSx}smallIconProps={smallIconProps}compactIconProps={compactIconProps}actionIconProps={actionIconProps}- stopButtonColor={theme.palette.error.main}/>{showImageDropOverlay && (<Box@@ -4888,17 +4802,6 @@ const Page: React.FC = () => {</Box><ChatDialogs- showSources={showSources}- closeSources={closeSources}- sourceSelectionDisabled={sourceSelectionDisabled}- handleDownloadChatKnowledgePack={- handleDownloadChatKnowledgePack- }- handleAddChatNotesFolder={handleAddChatNotesFolder}- enabledNoteCollectionIds={enabledNoteCollectionIds}- handleSetNotesCollectionEnabled={- handleSetNotesCollectionEnabled- }showSettingsModal={showSettingsModal}openSettingsModal={openSettingsModal}closeSettingsModal={closeSettingsModal}@@ -4944,23 +4847,30 @@ const Page: React.FC = () => {handleSaveSystemPrompt={handleSaveSystemPrompt}handleUseDefaultSystemPrompt={handleUseDefaultSystemPrompt}knowledgePacks={knowledgePacks}- knowledgeCatalogLoading={knowledgeCatalogLoading}+ knowledgeCatalogLoading={+ knowledgeCatalogLoading || !packSettingsReady+ }knowledgeCatalogError={knowledgeCatalogError}retryKnowledgeCatalog={refreshKnowledgeCatalog}- enabledKnowledgePackIds={enabledKnowledgePackIds}knowledgeDownloadProgress={knowledgeDownloadProgress}knowledgeErrors={knowledgeErrors}handleDownloadKnowledgePack={handleDownloadKnowledgePack}handleCancelKnowledgePackDownload={handleCancelKnowledgePackDownload}- handleSetKnowledgePackEnabled={handleSetKnowledgePackEnabled}notesCollections={notesCollections}notesCollectionsLoading={notesCollectionsLoading}notesCollectionsError={notesCollectionsError}retryNotesCollections={retryNotesCollections}handleAddNotesFolder={handleAddNotesFolder}handleRemoveNotesCollection={handleRemoveNotesCollection}+ onSettingsFlowVisibilityChange={+ handleSettingsFlowVisibilityChange+ }+ disabledNoteIds={disabledNoteIds}+ disabledPackIds={disabledPackIds}+ handleSetPackEnabled={handleSetPackEnabled}+ handleSetNotesEnabled={handleSetNotesEnabled}handleIndexNotesCollection={runNotesIndex}chatNotificationOpen={chatNotificationOpen}setChatNotificationOpen={setChatNotificationOpen}diff --git a/web/apps/ensu/src/services/chat/source-selection.ts b/web/apps/ensu/src/services/chat/source-selection.tsindex dba6329821..399011d3d4 100644--- a/web/apps/ensu/src/services/chat/source-selection.ts+++ b/web/apps/ensu/src/services/chat/source-selection.ts@@ -1,107 +1,123 @@-/** Device-local choices for one chat. Stable IDs survive pack updates. */export interface ChatSourceSelection {packIds: string[];noteCollectionIds: string[];}-type SourceKind = keyof ChatSourceSelection;-type SelectionStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;-const storagePrefix = "ensu.desktop.chatSources.";+type SelectionStorage = Pick<Storage, "getItem" | "setItem">;+const packsSettingsKey = "ensu.desktop.packs.disabledByDefault";+const notesSettingsKey = "ensu.desktop.notes.disabledByDefault";+const legacyPacksKey = "ensu.desktop.enabledKnowledgePacks";const stringIds = (value: unknown): string[] | undefined =>Array.isArray(value) && value.every((id) => typeof id === "string")? [...new Set(value)]: undefined;-/** Keeps draft identities stable across an asynchronous download or folder add. */export class ChatSourceSelectionStore {- private selections = new Map<string, ChatSourceSelection>();- private destinations = new Map<string, string>();- private deleted = new Set<string>();+ private cachedDisabledNoteIds?: string[];+ private cachedDisabledPackIds?: string[];+ private packSettingsMigrated = false;constructor(private storage?: SelectionStorage,private onError: (error: unknown) => void = () => undefined,) {}- private destination(id: string): string {- return this.destinations.get(id) ?? id;- }-- get(id: string): ChatSourceSelection | undefined {- id = this.destination(id);- if (this.deleted.has(id)) return;- const cached = this.selections.get(id);- if (cached) return cached;+ private legacyPackIds(): string[] | undefined {try {- const raw = this.storage?.getItem(storagePrefix + id);- if (!raw) return;- const parsed = JSON.parse(- raw,- ) as Partial<ChatSourceSelection> | null;- const packIds = stringIds(parsed?.packIds);- const noteCollectionIds = stringIds(parsed?.noteCollectionIds);- if (!packIds || !noteCollectionIds) return;- const selection = { packIds, noteCollectionIds };- this.selections.set(id, selection);- return selection;+ const raw = this.storage?.getItem(legacyPacksKey);+ return raw ? stringIds(JSON.parse(raw)) : undefined;} catch (error) {this.onError(error);- return;+ return undefined;}}- private save(id: string, selection: ChatSourceSelection) {- this.selections.set(id, selection);- if (id.startsWith("draft:")) return;+ migratePackSettings(packIds: string[]) {try {+ if (this.storage?.getItem(packsSettingsKey) != null) return;+ if (!this.packSettingsMigrated) {+ const legacy = this.legacyPackIds();+ if (!legacy) return;+ this.cachedDisabledPackIds = packIds.filter(+ (id) => !legacy.includes(id),+ );+ this.packSettingsMigrated = true;+ }this.storage?.setItem(- storagePrefix + id,- JSON.stringify(selection),+ packsSettingsKey,+ JSON.stringify(this.cachedDisabledPackIds),);} catch (error) {this.onError(error);}}- initialize(id: string, defaults: ChatSourceSelection) {- id = this.destination(id);- if (this.deleted.has(id) || this.get(id)) return;- this.save(id, {- packIds: [...defaults.packIds],- noteCollectionIds: [...defaults.noteCollectionIds],- });+ disabledPackIds(): string[] {+ if (this.cachedDisabledPackIds) return this.cachedDisabledPackIds;+ try {+ const raw = this.storage?.getItem(packsSettingsKey);+ this.cachedDisabledPackIds = raw+ ? (stringIds(JSON.parse(raw)) ?? [])+ : [];+ } catch (error) {+ this.onError(error);+ this.cachedDisabledPackIds = [];+ }+ return this.cachedDisabledPackIds;+ }++ setPackEnabled(id: string, enabled: boolean, availablePackIds: string[]) {+ this.migratePackSettings(availablePackIds);+ const ids = new Set(this.disabledPackIds());+ if (enabled) ids.delete(id);+ else ids.add(id);+ this.cachedDisabledPackIds = [...ids];+ try {+ this.storage?.setItem(+ packsSettingsKey,+ JSON.stringify(this.cachedDisabledPackIds),+ );+ } catch (error) {+ this.onError(error);+ }}- setEnabled(- id: string,- kind: SourceKind,- sourceId: string,- enabled: boolean,- ) {- id = this.destination(id);- const current = this.get(id);- if (!current) return;- const ids = new Set(current[kind]);- if (enabled) ids.add(sourceId);- else ids.delete(sourceId);- this.save(id, { ...current, [kind]: [...ids] });+ selection(available: ChatSourceSelection): ChatSourceSelection {+ return {+ packIds: available.packIds.filter(+ (id) => !this.disabledPackIds().includes(id),+ ),+ noteCollectionIds: available.noteCollectionIds.filter(+ (id) => !this.disabledNoteIds().includes(id),+ ),+ };}- transferDraft(draftId: string, sessionId: string) {- const selection = this.get(draftId);- if (!selection) return;- this.save(sessionId, selection);- this.destinations.set(draftId, sessionId);- this.selections.delete(draftId);+ disabledNoteIds(): string[] {+ if (this.cachedDisabledNoteIds) return this.cachedDisabledNoteIds;+ try {+ const raw = this.storage?.getItem(notesSettingsKey);+ this.cachedDisabledNoteIds = raw+ ? (stringIds(JSON.parse(raw)) ?? [])+ : [];+ } catch (error) {+ this.onError(error);+ this.cachedDisabledNoteIds = [];+ }+ return this.cachedDisabledNoteIds;}- remove(id: string) {- id = this.destination(id);- this.deleted.add(id);- this.selections.delete(id);+ setNoteEnabled(id: string, enabled: boolean) {+ const ids = new Set(this.disabledNoteIds());+ if (enabled) ids.delete(id);+ else ids.add(id);+ this.cachedDisabledNoteIds = [...ids];try {- this.storage?.removeItem(storagePrefix + id);+ this.storage?.setItem(+ notesSettingsKey,+ JSON.stringify(this.cachedDisabledNoteIds),+ );} catch (error) {this.onError(error);}diff --git a/web/apps/ensu/src/services/knowledge.ts b/web/apps/ensu/src/services/knowledge.tsindex de2b5a3606..0a82b83021 100644--- a/web/apps/ensu/src/services/knowledge.ts+++ b/web/apps/ensu/src/services/knowledge.ts@@ -15,7 +15,7 @@ export interface KnowledgePack {stableId: string;label: string;downloadSizeBytes: number;- status: KnowledgePackStatus | null;+ status: KnowledgePackStatus;attribution: KnowledgeAttribution;}@@ -64,10 +64,8 @@ const invokeKnowledge = async <T>(return invoke<T>(command, args);};-export const loadKnowledgeCatalog = (reconcileStableIds?: string[]) =>- invokeKnowledge<KnowledgePack[]>("knowledge_catalog", {- reconcileStableIds,- });+export const loadKnowledgeCatalog = () =>+ invokeKnowledge<KnowledgePack[]>("knowledge_catalog");export const downloadKnowledgePack = async (stableId: string,@@ -102,11 +100,13 @@ export const retrieveKnowledge = (retrievalEpoch: number,) =>invokeKnowledge<KnowledgePromptContext | null>("knowledge_retrieve", {- query,- enabledStableIds,- enabledNoteCollectionIds,- maxContextUtf8Bytes,- retrievalEpoch,+ input: {+ query,+ enabledStableIds,+ enabledNoteCollectionIds,+ maxContextUtf8Bytes,+ retrievalEpoch,+ },});export const knowledgeErrorMessage = (error: unknown) => {diff --git a/web/apps/ensu/src/services/notes-indexing-idle.ts b/web/apps/ensu/src/services/notes-indexing-idle.tsnew file mode 100644index 0000000000..c0c34c5089--- /dev/null+++ b/web/apps/ensu/src/services/notes-indexing-idle.ts@@ -0,0 +1,53 @@+interface IdleTimers {+ schedule: (callback: () => void, delayMs: number) => number;+ cancel: (handle: number) => void;+}++export class NotesIndexingIdleScheduler {+ private timer?: number;+ private waiting = false;+ private revision = 0;++ constructor(+ private resume: () => void,+ private isChatBusy: () => boolean,+ private timers: IdleTimers,+ private quietPeriodMs = 30_000,+ ) {}++ defer() {+ this.waiting = true;+ this.schedule();+ }++ activity() {+ if (this.waiting) this.schedule();+ }++ resumeNow() {+ this.cancel();+ this.resume();+ }++ cancel() {+ this.revision += 1;+ this.waiting = false;+ if (this.timer !== undefined) this.timers.cancel(this.timer);+ this.timer = undefined;+ }++ private schedule() {+ if (this.timer !== undefined) this.timers.cancel(this.timer);+ const revision = ++this.revision;+ this.timer = this.timers.schedule(() => {+ if (!this.waiting || revision !== this.revision) return;+ this.timer = undefined;+ if (this.isChatBusy()) {+ this.schedule();+ return;+ }+ this.waiting = false;+ this.resume();+ }, this.quietPeriodMs);+ }+}diff --git a/web/apps/ensu/src/services/notes-lifecycle.ts b/web/apps/ensu/src/services/notes-lifecycle.tsindex fd0b53f0d7..0e1f208e0b 100644--- a/web/apps/ensu/src/services/notes-lifecycle.ts+++ b/web/apps/ensu/src/services/notes-lifecycle.ts@@ -9,7 +9,12 @@ interface NotesIndexCompletion {type NotesIndexActivity = "starting" | "queued" | "failed" | null;export type NotesCollectionActivity =- "starting" | "waitingForGeneration" | "waitingForModel" | "failed" | null;+ | "starting"+ | "waitingForGeneration"+ | "waitingForModel"+ | "waitingForChat"+ | "failed"+ | null;export interface NotesCollectionView extends NotesCollection {activity: NotesCollectionActivity;diff --git a/web/apps/ensu/tests/notes-indexing-idle.test.ts b/web/apps/ensu/tests/notes-indexing-idle.test.tsnew file mode 100644index 0000000000..fca78cd581--- /dev/null+++ b/web/apps/ensu/tests/notes-indexing-idle.test.ts@@ -0,0 +1,124 @@+import assert from "node:assert/strict";+import test from "node:test";+import { NotesIndexingIdleScheduler } from "../src/services/notes-indexing-idle.ts";++const makeClock = () => {+ let now = 0;+ let nextId = 0;+ const pending = new Map<number, { at: number; run: () => void }>();+ const callbacks: (() => void)[] = [];+ return {+ timers: {+ schedule: (run: () => void, delayMs: number) => {+ const id = ++nextId;+ pending.set(id, { at: now + delayMs, run });+ callbacks.push(run);+ return id;+ },+ cancel: (id: number) => {+ pending.delete(id);+ },+ },+ callbacks,+ advance: (elapsedMs: number) => {+ const end = now + elapsedMs;+ while (true) {+ const next = [...pending].sort(+ ([, a], [, b]) => a.at - b.at,+ )[0];+ if (!next || next[1].at > end) break;+ const [id, task] = next;+ pending.delete(id);+ now = task.at;+ task.run();+ }+ now = end;+ },+ };+};++void test("indexing resumes once after the restored chat has 30 quiet seconds", () => {+ const clock = makeClock();+ let resumed = 0;+ const scheduler = new NotesIndexingIdleScheduler(+ () => resumed++,+ () => false,+ clock.timers,+ );+ scheduler.defer();+ clock.advance(29_999);+ assert.equal(resumed, 0);+ clock.advance(1);+ assert.equal(resumed, 1);+ clock.advance(60_000);+ assert.equal(resumed, 1);+});++void test("typing or sending restarts the pending quiet period", () => {+ const clock = makeClock();+ let resumed = 0;+ const scheduler = new NotesIndexingIdleScheduler(+ () => resumed++,+ () => false,+ clock.timers,+ );+ scheduler.defer();+ clock.advance(20_000);+ scheduler.activity();+ clock.advance(29_999);+ assert.equal(resumed, 0);+ clock.advance(1);+ assert.equal(resumed, 1);+});++void test("a busy chat defers indexing until a later idle check", () => {+ const clock = makeClock();+ let busy = true;+ let resumed = 0;+ const scheduler = new NotesIndexingIdleScheduler(+ () => resumed++,+ () => busy,+ clock.timers,+ );+ scheduler.defer();+ clock.advance(90_000);+ assert.equal(resumed, 0);+ busy = false;+ clock.advance(30_000);+ assert.equal(resumed, 1);+});++void test("reopening Notes resumes immediately and invalidates stale callbacks", () => {+ const clock = makeClock();+ let resumed = 0;+ const scheduler = new NotesIndexingIdleScheduler(+ () => resumed++,+ () => false,+ clock.timers,+ );+ scheduler.defer();+ const staleCallback = clock.callbacks[0];+ assert.ok(staleCallback);+ scheduler.resumeNow();+ assert.equal(resumed, 1);+ staleCallback();+ clock.advance(60_000);+ assert.equal(resumed, 1);+});++void test("unmount or another warmup cancels the previous pending resumption", () => {+ const clock = makeClock();+ let resumed = 0;+ const scheduler = new NotesIndexingIdleScheduler(+ () => resumed++,+ () => false,+ clock.timers,+ );+ scheduler.defer();+ scheduler.cancel();+ clock.advance(60_000);+ assert.equal(resumed, 0);+ scheduler.defer();+ clock.advance(30_000);+ assert.equal(resumed, 1);+});diff --git a/web/apps/ensu/tests/source-selection.test.mjs b/web/apps/ensu/tests/source-selection.test.mjsdeleted file mode 100644index 2fd4934f45..0000000000--- a/web/apps/ensu/tests/source-selection.test.mjs+++ /dev/null@@ -1,110 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";-import { ChatSourceSelectionStore } from "../src/services/chat/source-selection.ts";--const defaults = { packIds: ["wiki"], noteCollectionIds: ["journal"] };-const makeStorage = () => {- /** @type {Map<string, string>} */- const entries = new Map();- /** @type {Pick<Storage, "getItem" | "setItem" | "removeItem">} */- const storage = {- getItem: (key) => entries.get(key) ?? null,- setItem: (key, value) => entries.set(key, value),- removeItem: (key) => entries.delete(key),- };- return storage;-};--void test("new chats select current sources once and do not inherit later additions", () => {- const store = new ChatSourceSelectionStore();- store.initialize("first", defaults);- const later = {- packIds: ["wiki", "books"],- noteCollectionIds: ["journal", "work"],- };- store.initialize("first", later);- store.initialize("second", later);- assert.deepEqual(store.get("first"), defaults);- assert.deepEqual(store.get("second"), later);-});--void test("empty selections survive restart and subsequent inventory changes", () => {- const storage = makeStorage();- const store = new ChatSourceSelectionStore(storage);- store.initialize("chat", defaults);- store.setEnabled("chat", "packIds", "wiki", false);- store.setEnabled("chat", "noteCollectionIds", "journal", false);- const reopened = new ChatSourceSelectionStore(storage);- reopened.initialize("chat", defaults);- assert.deepEqual(reopened.get("chat"), {- packIds: [],- noteCollectionIds: [],- });-});--void test("switching chats preserves each explicit selection", () => {- const store = new ChatSourceSelectionStore();- store.initialize("one", defaults);- store.initialize("two", defaults);- store.setEnabled("one", "packIds", "wiki", false);- store.setEnabled("two", "noteCollectionIds", "journal", false);- assert.deepEqual(store.get("one"), {- packIds: [],- noteCollectionIds: ["journal"],- });- assert.deepEqual(store.get("two"), {- packIds: ["wiki"],- noteCollectionIds: [],- });-});--void test("downloads started in a draft follow it into its newly created chat", () => {- const storage = makeStorage();- const store = new ChatSourceSelectionStore(storage);- store.initialize("draft:one", defaults);- store.transferDraft("draft:one", "chat-one");- store.initialize("draft:two", defaults);- store.setEnabled("draft:one", "packIds", "books", true);- assert.deepEqual(store.get("chat-one")?.packIds, ["wiki", "books"]);- assert.deepEqual(store.get("draft:two"), defaults);- assert.deepEqual(- new ChatSourceSelectionStore(storage).get("chat-one")?.packIds,- ["wiki", "books"],- );-});--void test("folder adds completed in an abandoned draft do not alter the next draft", () => {- const store = new ChatSourceSelectionStore();- store.initialize("draft:old", defaults);- store.initialize("draft:new", defaults);- store.setEnabled("draft:old", "noteCollectionIds", "work", true);- assert.deepEqual(store.get("draft:new"), defaults);-});--void test("an in-flight generation snapshot is unchanged by later selections", () => {- const store = new ChatSourceSelectionStore();- store.initialize("chat", defaults);- const snapshot = store.get("chat");- store.setEnabled("chat", "packIds", "wiki", false);- store.setEnabled("chat", "noteCollectionIds", "work", true);- assert.deepEqual(snapshot, defaults);-});--void test("late download completion cannot resurrect a deleted chat's selection", () => {- const storage = makeStorage();- const store = new ChatSourceSelectionStore(storage);- store.initialize("draft:one", defaults);- store.transferDraft("draft:one", "chat");- store.remove("chat");- store.setEnabled("draft:one", "packIds", "books", true);- assert.equal(store.get("chat"), undefined);- assert.equal(new ChatSourceSelectionStore(storage).get("chat"), undefined);-});--void test("malformed persisted choices safely initialize from current inventory", () => {- const storage = makeStorage();- storage.setItem("ensu.desktop.chatSources.chat", '{"packIds":null}');- const store = new ChatSourceSelectionStore(storage);- store.initialize("chat", defaults);- assert.deepEqual(store.get("chat"), defaults);-});diff --git a/web/apps/ensu/tests/source-selection.test.ts b/web/apps/ensu/tests/source-selection.test.tsnew file mode 100644index 0000000000..8c4a069d85--- /dev/null+++ b/web/apps/ensu/tests/source-selection.test.ts@@ -0,0 +1,95 @@+import assert from "node:assert/strict";+import test from "node:test";+import { ChatSourceSelectionStore } from "../src/services/chat/source-selection.ts";++const available = {+ packIds: ["wiki", "books"],+ noteCollectionIds: ["journal"],+};+const makeStorage = () => {+ const entries = new Map<string, string>();+ const storage: Pick<Storage, "getItem" | "setItem"> = {+ getItem: (key) => entries.get(key) ?? null,+ setItem: (key, value) => entries.set(key, value),+ };+ return storage;+};++void test("legacy migration replaces an already-read default cache", () => {+ const storage = makeStorage();+ storage.setItem("ensu.desktop.enabledKnowledgePacks", '["wiki"]');+ const store = new ChatSourceSelectionStore(storage);+ assert.deepEqual(store.disabledPackIds(), []);+ store.migratePackSettings(available.packIds);+ assert.deepEqual(store.selection(available), {+ packIds: ["wiki"],+ noteCollectionIds: ["journal"],+ });+});++void test("explicit empty legacy choices remain disabled", () => {+ const storage = makeStorage();+ storage.setItem("ensu.desktop.enabledKnowledgePacks", "[]");+ const store = new ChatSourceSelectionStore(storage);+ store.migratePackSettings(available.packIds);+ assert.deepEqual(store.selection(available).packIds, []);+});++void test("empty choices survive restart without repeating legacy migration", () => {+ const storage = makeStorage();+ storage.setItem("ensu.desktop.enabledKnowledgePacks", '["wiki"]');+ const store = new ChatSourceSelectionStore(storage);+ store.migratePackSettings(available.packIds);+ store.setPackEnabled("wiki", false, available.packIds);+ store.setNoteEnabled("journal", false);+ const reopened = new ChatSourceSelectionStore(storage);+ reopened.migratePackSettings(available.packIds);+ assert.deepEqual(reopened.selection(available), {+ packIds: [],+ noteCollectionIds: [],+ });+});++void test("failed migration writes preserve current choices until storage recovers", () => {+ const storage = makeStorage();+ storage.setItem("ensu.desktop.enabledKnowledgePacks", '["wiki"]');+ let writable = false;+ const writeError = new Error("Storage full");+ const errors: unknown[] = [];+ const store = new ChatSourceSelectionStore(+ {+ getItem: storage.getItem,+ setItem: (key, value) => {+ if (!writable) throw writeError;+ storage.setItem(key, value);+ },+ },+ (error) => errors.push(error),+ );+ store.migratePackSettings(available.packIds);+ store.setPackEnabled("wiki", false, available.packIds);+ assert.deepEqual(store.selection(available).packIds, []);+ store.migratePackSettings([...available.packIds]);+ assert.deepEqual(store.selection(available).packIds, []);+ store.setPackEnabled("books", true, available.packIds);+ assert.deepEqual(store.selection(available).packIds, ["books"]);+ assert.ok(errors.includes(writeError));++ writable = true;+ store.migratePackSettings(available.packIds);+ const reopened = new ChatSourceSelectionStore(storage);+ reopened.migratePackSettings(available.packIds);+ assert.deepEqual(reopened.selection(available).packIds, ["books"]);+});++void test("an in-flight send snapshot is unchanged by later settings changes", () => {+ const store = new ChatSourceSelectionStore(makeStorage());+ const snapshot = store.selection(available);+ store.setPackEnabled("wiki", false, available.packIds);+ store.setNoteEnabled("journal", false);+ assert.deepEqual(snapshot, available);+ assert.deepEqual(store.selection(available), {+ packIds: ["books"],+ noteCollectionIds: [],+ });+});