Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

[ensu] Add per-chat pack and notes selection

setalp6357b2245300
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.kt
index 521bfe9d7e..155feebc1b 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,6 +7,7 @@ import io.ente.ensu.chat.Attachment
import io.ente.ensu.chat.AttachmentStoreActions
import io.ente.ensu.chat.ChatMessage
import io.ente.ensu.chat.ChatRepository
+import io.ente.ensu.chat.ChatSourceSelectionPreferences
import io.ente.ensu.chat.ChatStoreActions
import io.ente.ensu.device.AndroidDeviceCapabilityProvider
import io.ente.ensu.device.ChatDeviceCapability
@@ -40,6 +41,7 @@ class AppStore(
private val logRepository: FileLogRepository,
clock: () -> Long = { System.currentTimeMillis() },
) {
+ private val sourcePreferences = ChatSourceSelectionPreferences(context)
private val _state = MutableStateFlow(AppState())
val state: StateFlow<AppState> = _state.asStateFlow()
@@ -50,7 +52,6 @@ class AppStore(
private val attachmentActions = AttachmentStoreActions(_state, messageStore)
private val knowledgeStore =
KnowledgeStore(
- context = context,
state = _state,
provider = knowledgeProvider,
datasets = configDefaults.knowledgeDatasets,
@@ -63,11 +64,12 @@ class AppStore(
llmProvider = llmProvider,
logRepository = logRepository,
notesStore = notesStore,
- awaitKnowledgeReady = knowledgeStore::awaitEnabledPacksReady,
+ awaitKnowledgeReady = knowledgeStore::awaitReady,
)
private val chatActions =
ChatStoreActions(
state = _state,
+ sourcePreferences = sourcePreferences,
sessionPreferences = sessionPreferences,
chatRepository = chatRepository,
llmProvider = llmProvider,
@@ -79,7 +81,7 @@ class AppStore(
modelSettingsActions = modelSettingsActions,
configDefaults = configDefaults,
notesStore = notesStore,
- awaitKnowledgeReady = knowledgeStore::awaitEnabledPacksReady,
+ awaitKnowledgeReady = knowledgeStore::awaitReady,
)
fun bootstrap(scope: CoroutineScope) {
@@ -207,8 +209,29 @@ class AppStore(
fun cancelKnowledgePackDownload(stableId: String) = knowledgeStore.cancel(stableId)
+ fun retrySourceInventory() {
+ knowledgeStore.retryInventory()
+ notesStore.retryInventory()
+ chatActions.refreshSourceSelectionInventory()
+ }
+
+ fun sourceSelectionTarget(): String = chatActions.sourceSelectionTarget()
+
+ 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 addNotesFolderForChat(tree: android.net.Uri, target: String) =
+ notesStore.add(tree) { id -> chatActions.selectAddedFolder(target, id) }
+
fun setKnowledgePackEnabled(stableId: String, enabled: Boolean) =
- knowledgeStore.setEnabled(stableId, enabled)
+ chatActions.setPackEnabled(stableId, enabled)
+
+ fun setNotesFolderEnabled(id: String, enabled: Boolean) =
+ chatActions.setFolderEnabled(id, enabled)
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.kt
index cd52089adb..852c8773c9 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
@@ -113,6 +113,8 @@ internal fun HomeNavigation(
ChatView(
onVoiceInputJob = store::trackVoiceInput,
chatState = appState.chat,
+ knowledgeState = appState.knowledge,
+ store = store,
assetStore = store.assetStore,
llmProvider = store.llmProvider,
isDrawerOpen = drawerState.currentValue == DrawerValue.Open,
@@ -180,7 +182,6 @@ internal fun HomeNavigation(
packDownloadsAllowed = appState.chat.deviceCapability.isChatSupported(),
onDownloadOrUpdate = store::downloadOrUpdateKnowledgePack,
onCancel = store::cancelKnowledgePackDownload,
- onSetEnabled = store::setKnowledgePackEnabled,
)
}
composable(
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.kt
index 20eff65036..86d44d43cf 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
@@ -74,6 +74,7 @@ internal fun MessageInput(
onAttachmentSelected: (AttachmentType) -> Unit,
onRemoveAttachment: (Attachment) -> Unit,
onCancelEdit: () -> Unit,
+ onOpenSources: () -> Unit,
voiceInputState: VoiceInputState,
onVoiceInput: () -> Unit,
focusRequestId: Int,
@@ -242,6 +243,41 @@ 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()
+ },
+ modifier = Modifier.size(36.dp),
+ ) {
+ Icon(
+ painter = painterResource(HugeIcons.PackageIcon),
+ contentDescription = "Sources for this chat",
+ modifier = Modifier.size(18.dp),
+ )
+ }
+
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+
BasicTextField(
value = fieldValue,
onValueChange = { newValue ->
@@ -272,27 +308,6 @@ internal fun MessageInput(
}
}
- Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
-
- 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),
- )
- }
- }
-
if (editingMessage == null) {
val isVoiceBusy =
voiceInputState is VoiceInputState.Downloading ||
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.kt
new file mode 100644
index 0000000000..36780dd33b
--- /dev/null
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelection.kt
@@ -0,0 +1,17 @@
+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(),
+) {
+ fun isPackEnabled(id: String): Boolean = id in selectedPackIds
+
+ fun 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.kt
new file mode 100644
index 0000000000..9c025682cc
--- /dev/null
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelectionPreferences.kt
@@ -0,0 +1,45 @@
+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.kt
new file mode 100644
index 0000000000..b6d7b7ff80
--- /dev/null
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourceSelections.kt
@@ -0,0 +1,39 @@
+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.kt
new file mode 100644
index 0000000000..7407064519
--- /dev/null
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatSourcesSheet.kt
@@ -0,0 +1,232 @@
+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.kt
index 5cf8d371ae..fbe7619d72 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,6 +6,8 @@ import io.ente.ensu.llm.DownloadPhase
data class ChatState(
val sessions: List<ChatSession> = emptyList(),
val currentSessionId: String? = null,
+ val sourceSelection: ChatSourceSelection = ChatSourceSelection(),
+ val sourceSelectionReady: Boolean = false,
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.kt
index 05b708fac3..1752242c27 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
@@ -10,6 +10,7 @@ import io.ente.ensu.bindings.ConversationRequest
import io.ente.ensu.bindings.DbException
import io.ente.ensu.bindings.GroundedExcerpt
import io.ente.ensu.bindings.GroundedSource
+import io.ente.ensu.bindings.KnowledgeDatasetConfig
import io.ente.ensu.bindings.LlmException
import io.ente.ensu.bindings.PassageLocator
import io.ente.ensu.bindings.buildGroundedPromptContext
@@ -46,7 +47,10 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
@@ -54,6 +58,7 @@ import kotlinx.coroutines.withContext
internal class ChatStoreActions(
private val state: MutableStateFlow<AppState>,
+ private val sourcePreferences: ChatSourceSelectionPreferences,
private val sessionPreferences: SessionPreferencesDataStore,
private val chatRepository: ChatRepository,
private val llmProvider: LlmProvider,
@@ -67,6 +72,10 @@ internal class ChatStoreActions(
private val notesStore: NotesStore,
private val awaitKnowledgeReady: suspend () -> Unit,
) {
+ private val sourceInventoryReady: Boolean
+ get() = 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>()
@@ -91,6 +100,24 @@ internal class ChatStoreActions(
fun bootstrap(scope: CoroutineScope) {
this.scope = scope
+ refreshSourceSelectionInventory()
+ scope.launch {
+ combine(
+ state.map { it.knowledge.inventoryReady },
+ notesStore.state.map { it.inventoryReady },
+ ) { packsReady, notesReady ->
+ packsReady && notesReady
+ }
+ .distinctUntilChanged()
+ .collectLatest { ready ->
+ if (ready) {
+ refreshSourceSelectionInventory()
+ } else {
+ state.update { it.copy(chat = it.chat.copy(sourceSelectionReady = false)) }
+ }
+ }
+ }
+
sessionSummaries.clear()
scope.launch {
val summaries = sessionPreferences.sessionSummaries.first()
@@ -112,10 +139,83 @@ internal class ChatStoreActions(
}
}
+ fun refreshSourceSelectionInventory() {
+ scope?.launch {
+ awaitKnowledgeReady()
+ notesStore.awaitReady()
+ state.update { appState ->
+ appState.copy(
+ chat =
+ appState.chat.copy(
+ sourceSelection = readSourceSelection(sourceSelectionTarget()),
+ sourceSelectionReady = sourceInventoryReady,
+ )
+ )
+ }
+ }
+ }
+
+ fun sourceSelectionTarget(): String =
+ state.value.chat.currentSessionId ?: sourcePreferences.draftKey
+
+ private fun initialSourceSelection(): ChatSourceSelection =
+ ChatSourceSelection(
+ selectedPackIds =
+ state.value.knowledge.packs.values
+ .filter { it.activeIdentity != null }
+ .map { it.config.stableId }
+ .toSet(),
+ selectedFolderIds = notesStore.state.value.collections.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 {
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()
@@ -126,6 +226,7 @@ internal class ChatStoreActions(
appState.chat.copy(
sessions = updatedSessions,
currentSessionId = session.id,
+ sourceSelection = selection,
messageText = "",
attachments = emptyList(),
editingMessageId = null,
@@ -144,11 +245,13 @@ 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 = "",
@@ -162,7 +265,13 @@ internal class ChatStoreActions(
fun selectSession(sessionId: String) {
resetGenerationState()
state.update { appState ->
- appState.copy(chat = appState.chat.copy(currentSessionId = sessionId))
+ appState.copy(
+ chat =
+ appState.chat.copy(
+ currentSessionId = sessionId,
+ sourceSelection = readSourceSelection(sessionId),
+ )
+ )
}
val scope = scope ?: return
scope.launch(Dispatchers.IO) {
@@ -180,6 +289,7 @@ internal class ChatStoreActions(
}
chatRepository.deleteSession(sessionId)
+ sourcePreferences.remove(sessionId)
if (isCurrent) attachmentActions.discardAttachments(currentState.chat.attachments)
removeSessionCaches(sessionId)
sessionSummaries.remove(sessionKey(sessionId))
@@ -202,6 +312,8 @@ 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,
@@ -489,6 +601,11 @@ internal class ChatStoreActions(
appState.chat.copy(
sessions = sessions,
currentSessionId = if (sessionStillExists) currentSessionId else null,
+ sourceSelection =
+ readSourceSelection(
+ if (sessionStillExists) currentSessionId
+ else sourcePreferences.draftKey
+ ),
)
)
}
@@ -556,6 +673,7 @@ internal class ChatStoreActions(
}
rebuildChatState(sessionId)
+ val requestedSourceSelection = sourcePreferences.read(sessionId)
val notesScope = notesStore.suspendMaintenance()
var followup: ConversationFollowup? = null
val activeJob = scope.launch {
@@ -573,7 +691,27 @@ internal class ChatStoreActions(
if (!isActive()) return@launch
val progressTracker = DownloadProgressTracker()
var embeddingAssetInvalid = false
- val enabledDatasets = state.value.knowledge.enabledReadyDatasets
+ 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)
+ }
+ val enabledFolderIds =
+ notesStore.state.value.collections
+ .filter { it.eligible && sourceSelection.isFolderEnabled(it.id) }
+ .map { it.id }
+ .toSet()
try {
if (prompt.imageFiles.isEmpty()) {
val messages = messageStore[sessionId].orEmpty()
@@ -619,8 +757,7 @@ internal class ChatStoreActions(
val knowledgeHits =
if (
retrievalQuery.isNotBlank() &&
- (enabledDatasets.isNotEmpty() ||
- notesStore.state.value.collections.any { it.eligible })
+ (enabledDatasets.isNotEmpty() || enabledFolderIds.isNotEmpty())
) {
try {
val hits =
@@ -636,7 +773,7 @@ internal class ChatStoreActions(
query = query,
maxHits = configDefaults.knowledgeEmbedding.maxHits,
)
- val notes = notesStore.retrieve(query)
+ val notes = notesStore.retrieve(query, enabledFolderIds)
notesStore.verify(
selectMixedGroundingCandidates(
packs,
@@ -693,7 +830,9 @@ internal class ChatStoreActions(
turn.searchWithHistory(knowledgeHits)
}
if (!isActive() || stopRequested) return@launch
- locators.mapNotNull { reloadPassage(it) }
+ locators.mapNotNull {
+ reloadPassage(it, enabledDatasets, enabledFolderIds)
+ }
}
.orEmpty()
} catch (error: kotlinx.coroutines.CancellationException) {
@@ -1075,12 +1214,18 @@ internal class ChatStoreActions(
return true
}
- private suspend fun reloadPassage(locator: PassageLocator): GroundedExcerpt? =
+ private suspend fun reloadPassage(
+ locator: PassageLocator,
+ enabledDatasets: List<KnowledgeDatasetConfig>,
+ enabledFolderIds: Set<String>,
+ ): GroundedExcerpt? =
try {
when (locator) {
- is PassageLocator.EnsuPack ->
- knowledgeProvider.reload(locator, state.value.knowledge.enabledReadyDatasets)
- is PassageLocator.LocalNote -> notesStore.reload(locator.locator)
+ is PassageLocator.EnsuPack -> knowledgeProvider.reload(locator, enabledDatasets)
+ is PassageLocator.LocalNote ->
+ if (locator.locator.collectionId in enabledFolderIds)
+ notesStore.reload(locator.locator)
+ else null
}
} catch (error: kotlinx.coroutines.CancellationException) {
throw error
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.kt
index 5053620591..2130ed2414 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,16 +46,20 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
+import io.ente.ensu.AppStore
import io.ente.ensu.assets.AssetStore
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.device.ChatDeviceCapability
+import io.ente.ensu.knowledge.KnowledgeState
import io.ente.ensu.llm.LlmProvider
import kotlinx.coroutines.Job
@Composable
fun ChatView(
chatState: ChatState,
+ knowledgeState: KnowledgeState,
+ store: AppStore,
assetStore: AssetStore,
llmProvider: LlmProvider,
isDrawerOpen: Boolean,
@@ -82,6 +86,7 @@ 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) }
val latestSessionKey by rememberUpdatedState(sessionKey)
val unsupportedCapability =
chatState.deviceCapability as? ChatDeviceCapability.UnsupportedLowMemory
@@ -191,6 +196,14 @@ fun ChatView(
voiceController.cancelActiveVoiceInput()
}
+ ChatSourcesSheet(
+ visible = showSources,
+ chatState = chatState,
+ knowledgeState = knowledgeState,
+ store = store,
+ onDismiss = { showSources = false },
+ )
+
Box(modifier = Modifier.fillMaxSize()) {
Column(modifier = Modifier.fillMaxSize().imePadding()) {
AnimatedContent(
@@ -288,6 +301,10 @@ 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/components/ActionButtons.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.kt
index 1b0b6692e9..71bd40aa3c 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
@@ -93,9 +93,10 @@ fun TextActionButton(
}
@Composable
-fun CompactButton(label: String, onClick: () -> Unit) {
+fun CompactButton(label: String, onClick: () -> Unit, enabled: Boolean = true) {
Button(
onClick = onClick,
+ enabled = enabled,
colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent()),
contentPadding =
PaddingValues(
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.kt
index 20a80b6f7c..ec22beffae 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,9 +1,5 @@
package io.ente.ensu.knowledge
-import android.content.Context
-import androidx.datastore.preferences.core.edit
-import androidx.datastore.preferences.core.stringSetPreferencesKey
-import androidx.datastore.preferences.preferencesDataStore
import io.ente.ensu.AppState
import io.ente.ensu.bindings.AssetDownloadException
import io.ente.ensu.bindings.KnowledgeDatasetConfig
@@ -17,20 +13,15 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
-import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
-private val Context.knowledgePreferences by preferencesDataStore("ensu_knowledge_preferences")
-
data class KnowledgePackState(
val config: KnowledgeDatasetConfig,
val status: KnowledgeReconciliationStatus? = null,
val activeIdentity: String? = null,
- val enabled: Boolean = false,
+ val inventoryLoaded: Boolean = false,
val mutationProgress: KnowledgeDownloadProgress? = null,
val errorMessage: String? = null,
) {
@@ -38,31 +29,34 @@ data class KnowledgePackState(
get() = mutationProgress != null
}
-data class KnowledgeState(val packs: Map<String, KnowledgePackState> = emptyMap()) {
- val enabledReadyDatasets: List<KnowledgeDatasetConfig>
+data class KnowledgeState(
+ val packs: Map<String, KnowledgePackState> = emptyMap(),
+ val inventoryLoading: Boolean = true,
+) {
+ val inventoryReady: Boolean
+ get() = !inventoryLoading && packs.values.all { it.inventoryLoaded }
+
+ val readyDatasets: List<KnowledgeDatasetConfig>
get() =
packs.values
.filter { pack ->
- pack.enabled &&
- (pack.status == KnowledgeReconciliationStatus.READY ||
- pack.status == KnowledgeReconciliationStatus.UPDATE_AVAILABLE)
+ pack.status == KnowledgeReconciliationStatus.READY ||
+ pack.status == KnowledgeReconciliationStatus.UPDATE_AVAILABLE
}
.map { it.config }
}
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? = null
private var bootstrapJob: Job? = null
- private val enabledPacksReady = CompletableDeferred<Unit>()
+ private val packsReady = CompletableDeferred<Unit>()
fun bootstrap(scope: CoroutineScope) {
this.scope = scope
@@ -76,30 +70,38 @@ class KnowledgeStore(
)
}
bootstrapJob = scope.launch {
- val requestedEnabled = runCatchingCancellable {
- preferences.enabledDatasetIds.first()
- }
- .getOrDefault(emptySet())
- val (enabled, disabled) = catalog.values.partition { it.stableId in requestedEnabled }
try {
- enabled.forEach { dataset -> reconcileAndUpdate(dataset, enabled = true) }
+ catalog.values.forEach { dataset -> reconcileAndUpdate(dataset) }
} finally {
- enabledPacksReady.complete(Unit)
+ state.update { it.copy(knowledge = it.knowledge.copy(inventoryLoading = false)) }
+ packsReady.complete(Unit)
}
- disabled.forEach { dataset -> reconcileAndUpdate(dataset, enabled = false) }
}
}
- suspend fun awaitEnabledPacksReady() {
- enabledPacksReady.await()
+ suspend fun awaitReady() {
+ packsReady.await()
+ 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 downloadOrUpdate(stableId: String) {
+ fun downloadOrUpdate(stableId: String, onInstalled: (() -> Unit)? = null) {
if (!state.value.chat.deviceCapability.isChatSupported()) return
val dataset = catalog[stableId] ?: return
val ownerScope = scope ?: return
if (jobs[stableId]?.isActive == true) return
- val wasInstalled = state.value.knowledge.packs[stableId]?.activeIdentity != null
updatePack(stableId) {
it.copy(
mutationProgress = KnowledgeDownloadProgress("Starting download...", 0.0),
@@ -114,30 +116,19 @@ class KnowledgeStore(
current.copy(mutationProgress = progress)
}
}
- val shouldEnable =
- !wasInstalled && reconciliation.status == KnowledgeReconciliationStatus.READY
- if (shouldEnable) {
- preferences.setDatasetEnabled(stableId, true)
- }
- val enabled =
- if (wasInstalled) {
- state.value.knowledge.packs[stableId]?.enabled == true
- } else {
- shouldEnable
- }
updatePack(stableId) {
- it.fromReconciliation(reconciliation, enabled).copy(mutationProgress = null)
+ it.fromReconciliation(reconciliation).copy(mutationProgress = null)
}
+ if (reconciliation.activeIdentity != null) onInstalled?.invoke()
} catch (error: CancellationException) {
throw error
} catch (error: Throwable) {
val reconciled = runCatchingCancellable { provider.reconcile(dataset) }.getOrNull()
updatePack(stableId) { current ->
- (reconciled?.let { current.fromReconciliation(it, current.enabled) } ?: current)
- .copy(
- mutationProgress = null,
- errorMessage = userFacingKnowledgeError(error),
- )
+ (reconciled?.let { current.fromReconciliation(it) } ?: current).copy(
+ mutationProgress = null,
+ errorMessage = userFacingKnowledgeError(error),
+ )
}
logRepository.log(
LogLevel.Error,
@@ -160,21 +151,13 @@ class KnowledgeStore(
ownerJob?.join()
if (jobs[stableId]?.isActive == true) return@launch
updatePack(stableId) { current ->
- (result?.let { current.fromReconciliation(it, current.enabled) } ?: current).copy(
+ (result?.let { current.fromReconciliation(it) } ?: current).copy(
mutationProgress = null
)
}
}
}
- fun setEnabled(stableId: String, enabled: Boolean) {
- val pack = state.value.knowledge.packs[stableId] ?: return
- if (pack.activeIdentity == null || pack.isMutating) return
- val ownerScope = scope ?: return
- updatePack(stableId) { it.copy(enabled = enabled) }
- ownerScope.launch { preferences.setDatasetEnabled(stableId, enabled) }
- }
-
private fun updatePack(
stableId: String,
transform: (KnowledgePackState) -> KnowledgePackState,
@@ -190,20 +173,14 @@ class KnowledgeStore(
}
}
- private suspend fun reconcileAndUpdate(
- dataset: KnowledgeDatasetConfig,
- enabled: Boolean,
- ) {
+ private suspend fun reconcileAndUpdate(dataset: KnowledgeDatasetConfig) {
val result = runCatchingCancellable { provider.reconcile(dataset) }
updatePack(dataset.stableId) { current ->
result.fold(
- onSuccess = { reconciliation ->
- current.fromReconciliation(reconciliation, enabled)
- },
+ onSuccess = { reconciliation -> current.fromReconciliation(reconciliation) },
onFailure = { error ->
current.copy(
status = KnowledgeReconciliationStatus.DOWNLOAD,
- enabled = false,
errorMessage = userFacingKnowledgeError(error),
)
},
@@ -212,13 +189,12 @@ class KnowledgeStore(
}
private fun KnowledgePackState.fromReconciliation(
- result: KnowledgeReconciliation,
- enabled: Boolean,
+ result: KnowledgeReconciliation
): KnowledgePackState =
copy(
status = result.status,
activeIdentity = result.activeIdentity,
- enabled = enabled && result.activeIdentity != null,
+ inventoryLoaded = true,
errorMessage = null,
)
@@ -239,21 +215,3 @@ class KnowledgeStore(
}
}
}
-
-private class KnowledgePreferences(context: Context) {
- private val preferences = context.applicationContext.knowledgePreferences
-
- val enabledDatasetIds: Flow<Set<String>> =
- preferences.data.map { values -> values[Keys.enabledDatasetIds].orEmpty() }
-
- suspend fun setDatasetEnabled(stableId: String, enabled: Boolean) {
- preferences.edit { values ->
- val ids = values[Keys.enabledDatasetIds].orEmpty()
- values[Keys.enabledDatasetIds] = if (enabled) ids + stableId else ids - stableId
- }
- }
-
- private object Keys {
- val enabledDatasetIds = stringSetPreferencesKey("enabled_dataset_ids")
- }
-}
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.kt
index 7ff59c8cd1..17e63bd694 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
@@ -41,7 +41,7 @@ fun NotesSettingsScreen(store: NotesStore, onPickerPending: (Boolean) -> Unit) {
val picker =
rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
onPickerPending(false)
- uri?.let(store::add)
+ uri?.let { store.add(it) }
}
LazyColumn(
modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),
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.kt
index f841201d07..a1d8cb4d95 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
@@ -70,6 +70,8 @@ data class NoteCollectionState(
data class NotesState(
val collections: List<NoteCollectionState> = emptyList(),
val error: String? = null,
+ val inventoryReady: Boolean = false,
+ val inventoryLoading: Boolean = true,
)
val LocalNotesStore = staticCompositionLocalOf<NotesStore?> { null }
@@ -141,7 +143,7 @@ class NotesStore(
)
}
}
- _state.value = NotesState(states)
+ _state.value = NotesState(states, inventoryReady = true, inventoryLoading = false)
loaded = true
scans.addAll(registrations.keys)
} catch (e: CancellationException) {
@@ -156,7 +158,8 @@ class NotesStore(
disabled = true
_state.value =
NotesState(
- error = "Could not load Your Notes. Existing indexes have been preserved."
+ error = "Could not load Your Notes. Existing indexes have been preserved.",
+ inventoryLoading = false,
)
}
pump()
@@ -167,6 +170,15 @@ class NotesStore(
bootstrapJob?.join()
}
+ fun retryInventory() {
+ val ownerScope = scope ?: return
+ if (bootstrapJob?.isActive == true || loaded) return
+ disabled = false
+ bootstrapJob = null
+ _state.update { it.copy(inventoryLoading = true, error = null) }
+ bootstrap(ownerScope)
+ }
+
fun setForeground(value: Boolean) {
if (foreground == value) return
foreground = value
@@ -199,7 +211,7 @@ class NotesStore(
active?.job?.join()
}
- fun add(tree: Uri) {
+ fun add(tree: Uri, onAdded: ((String) -> Unit)? = null) {
scope?.launch {
awaitReady()
if (disabled) return@launch
@@ -214,6 +226,7 @@ class NotesStore(
error = null,
)
}
+ onAdded?.invoke(record.id)
enqueue(record.id, immediate = true)
} catch (error: CancellationException) {
throw error
@@ -262,10 +275,12 @@ class NotesStore(
_state.update { it.copy(error = null) }
}
- suspend fun retrieve(query: List<Float>): List<NotesHit> =
+ suspend fun retrieve(query: List<Float>, enabledFolderIds: Set<String>): List<NotesHit> =
withContext(Dispatchers.Main.immediate) {
val records =
- _state.value.collections.filter { it.eligible }.mapNotNull { registrations[it.id] }
+ _state.value.collections
+ .filter { it.eligible && it.id in enabledFolderIds }
+ .mapNotNull { registrations[it.id] }
val hits = mutableListOf<NotesHit>()
for (record in records) {
currentCoroutineContext().ensureActive()
diff --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.kt
index ec831c9c3b..6c9a0539dd 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
@@ -28,6 +28,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import io.ente.ensu.bindings.KnowledgeDatasetConfig
import io.ente.ensu.bindings.KnowledgeReconciliationStatus
@@ -49,7 +51,6 @@ fun KnowledgeSettingsScreen(
packDownloadsAllowed: Boolean,
onDownloadOrUpdate: (String) -> Unit,
onCancel: (String) -> Unit,
- onSetEnabled: (String, Boolean) -> Unit,
) {
var attributionConfig by remember { mutableStateOf<KnowledgeDatasetConfig?>(null) }
@@ -63,7 +64,6 @@ fun KnowledgeSettingsScreen(
packDownloadsAllowed = packDownloadsAllowed,
onDownloadOrUpdate = { onDownloadOrUpdate(pack.config.stableId) },
onCancel = { onCancel(pack.config.stableId) },
- onSetEnabled = { enabled -> onSetEnabled(pack.config.stableId, enabled) },
onOpenAttribution = { attributionConfig = pack.config },
)
}
@@ -78,13 +78,15 @@ fun KnowledgeSettingsScreen(
}
@Composable
-private fun KnowledgePackCard(
+internal fun KnowledgePackCard(
pack: KnowledgePackState,
packDownloadsAllowed: Boolean,
onDownloadOrUpdate: () -> Unit,
onCancel: () -> Unit,
- onSetEnabled: (Boolean) -> Unit,
onOpenAttribution: () -> Unit,
+ selected: Boolean? = null,
+ controlsEnabled: Boolean = true,
+ onSetEnabled: (Boolean) -> Unit = {},
) {
KnowledgeCard {
Row(verticalAlignment = Alignment.CenterVertically) {
@@ -99,14 +101,26 @@ private fun KnowledgePackCard(
)
PackMetadataLine(pack = pack, onOpenAttribution = onOpenAttribution)
}
- if (pack.activeIdentity != null && !pack.isMutating) {
- Switch(checked = pack.enabled, onCheckedChange = onSetEnabled)
+ if (selected != null && pack.activeIdentity != null) {
+ Switch(
+ checked = selected,
+ onCheckedChange = onSetEnabled,
+ enabled = controlsEnabled,
+ modifier =
+ Modifier.semantics {
+ contentDescription = "Use ${pack.config.label} in this chat"
+ },
+ )
} else if (
packDownloadsAllowed &&
pack.status == KnowledgeReconciliationStatus.DOWNLOAD &&
!pack.isMutating
) {
- CompactButton(label = "Download", onClick = onDownloadOrUpdate)
+ CompactButton(
+ label = "Download",
+ onClick = onDownloadOrUpdate,
+ enabled = controlsEnabled,
+ )
}
}
@@ -142,7 +156,7 @@ private fun KnowledgePackCard(
packDownloadsAllowed && pack.status == KnowledgeReconciliationStatus.UPDATE_AVAILABLE
) {
Spacer(Modifier.height(EnsuSpacing.md.dp))
- CompactButton(label = "Update", onClick = onDownloadOrUpdate)
+ CompactButton(label = "Update", onClick = onDownloadOrUpdate, enabled = controlsEnabled)
}
pack.errorMessage?.let { Text(it, style = EnsuTypography.small, color = EnsuColor.error) }
@@ -186,7 +200,7 @@ private fun PackMetadataLine(
}
@Composable
-private fun PackAttributionDialog(
+internal fun PackAttributionDialog(
config: KnowledgeDatasetConfig,
onDismiss: () -> Unit,
) {
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.kt
new file mode 100644
index 0000000000..806f46fab3
--- /dev/null
+++ b/android/apps/ensu/app/src/test/java/io/ente/ensu/chat/ChatSourceSelectionsTest.kt
@@ -0,0 +1,122 @@
+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/apple/apps/ensu/Ensu.xcodeproj/project.pbxproj b/apple/apps/ensu/Ensu.xcodeproj/project.pbxproj
index 968615a1c4..617be0b766 100644
--- a/apple/apps/ensu/Ensu.xcodeproj/project.pbxproj
+++ b/apple/apps/ensu/Ensu.xcodeproj/project.pbxproj
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
+ A50000012F11111100AA0001 = {isa = PBXBuildFile; fileRef = A50000022F11111100AA0001; };
A40000012F11111100AA0001 = {isa = PBXBuildFile; fileRef = A40000022F11111100AA0001; };
A30000012F11111100AA0001 = {isa = PBXBuildFile; fileRef = A30000022F11111100AA0001; };
A20000012F11111100AA0001 = {isa = PBXBuildFile; fileRef = A20000022F11111100AA0001; };
@@ -28,6 +29,7 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
+ A50000022F11111100AA0001 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChatSourceSelectionTests.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>"; };
@@ -84,6 +86,7 @@
children = (
A10000022F11111100AA0001 /* LlmIntegrationTests.swift */,
A40000022F11111100AA0001,
+ A50000022F11111100AA0001,
A20000022F11111100AA0001,
A30000022F11111100AA0001,
);
@@ -254,6 +257,7 @@
files = (
A10000012F11111100AA0001 /* LlmIntegrationTests.swift in Sources */,
A40000012F11111100AA0001,
+ A50000012F11111100AA0001,
A20000012F11111100AA0001,
A30000012F11111100AA0001,
);
diff --git a/apple/apps/ensu/Ensu/Chat/ChatSourcesView.swift b/apple/apps/ensu/Ensu/Chat/ChatSourcesView.swift
new file mode 100644
index 0000000000..477338bc1c
--- /dev/null
+++ b/apple/apps/ensu/Ensu/Chat/ChatSourcesView.swift
@@ -0,0 +1,116 @@
+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.swift
index 48fdb0bcee..b4f69c36dc 100644
--- a/apple/apps/ensu/Ensu/Chat/ChatView.swift
+++ b/apple/apps/ensu/Ensu/Chat/ChatView.swift
@@ -8,6 +8,7 @@ struct ChatView: View {
@StateObject private var viewState = ChatViewState()
@StateObject private var keyboard = KeyboardObserver()
+ @State private var showSources = false
@State private var isInputFocused = false
private var editingMessage: RenderedChatMessage? {
@@ -30,6 +31,7 @@ struct ChatView: View {
&& !viewState.isDrawerOpen
&& !viewState.didDismissKeyboard
&& !viewState.showSettings
+ && !showSources
}
private var overflowDialogPresented: Binding<Bool> {
@@ -176,6 +178,9 @@ struct ChatView: View {
}
)
}
+ .sheet(isPresented: $showSources) {
+ ChatSourcesView(viewModel: viewModel)
+ }
.onChange(of: viewState.showSettings) { isPresented in
viewModel.setChatActive(!isPresented && scenePhase == .active)
if isPresented {
@@ -362,6 +367,7 @@ struct ChatView: View {
onCancelEdit: {
viewModel.cancelEditing()
},
+ onSources: { showSources = true },
onVoiceInput: {
viewState.didDismissKeyboard = true
isInputFocused = false
diff --git a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
index c698e412c5..ef397aaa5e 100644
--- a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
+++ b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift
@@ -41,7 +41,13 @@ final class ChatViewModel: ObservableObject {
private let logger = EnsuLogging.shared.logger("ChatViewModel")
@Published var sessions: [ChatSession]
- @Published var currentSessionId: UUID?
+ @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 messages: [RenderedChatMessage]
@Published var streamingResponse: String = ""
@Published var streamingParentId: UUID? = nil
@@ -230,6 +236,7 @@ final class ChatViewModel: ObservableObject {
}
refreshDeviceCapability()
refreshModelDownloadInfo()
+ loadSourceSelection()
Task {
async let knowledge: Void = knowledgeStore.bootstrap()
async let notes: Void = notesStore.bootstrap()
@@ -388,6 +395,103 @@ 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(
+ 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)
+ }
+
var modelDownloadSizeText: String {
guard let bytes = modelDownloadSizeBytes else { return "Approx. size varies by model" }
return "Approx. \(bytes.formattedFileSize)"
@@ -425,6 +529,7 @@ final class ChatViewModel: ObservableObject {
draftAttachments = []
editingMessageId = nil
+ sourceSelections.remove(nil)
currentSessionId = nil
messages = []
}
@@ -462,6 +567,7 @@ 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 }
@@ -745,6 +851,17 @@ final class ChatViewModel: ObservableObject {
guard !Task.isCancelled, self.pendingSendId == sendId else { return }
self.hasRequestedModelDownload = true
+ await knowledgeStore.bootstrap()
+ await notesStore.bootstrap()
+ guard !Task.isCancelled, self.pendingSendId == sendId,
+ currentSessionId == sessionId
+ else { 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
+
do {
try await self.ensureChatModelReady(
selection, pendingSendId: sendId, loadContext: false)
@@ -1177,6 +1294,7 @@ 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.id
messageStore[session.id] = []
branchSelections[session.id] = [:]
@@ -1222,6 +1340,8 @@ 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] in
defer {
notesScope.close()
@@ -1235,9 +1355,18 @@ 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()
var embeddingAssetInvalid = false
var knowledgeHits: [GroundedExcerpt] = []
- let enabledDatasets = knowledgeStore.enabledReadyDatasets
+ let enabledDatasets = knowledgeStore.readyDatasets.filter {
+ sources.includesPack($0.stableId)
+ }
+ let enabledCollectionIDs = Set(
+ notesStore.collections.filter {
+ $0.eligible && sources.includesCollection($0.id)
+ }.map(\.id))
var followup: ConversationFollowup?
var reloaded: [GroundedExcerpt] = []
defer { followup?.cancel() }
@@ -1275,7 +1404,7 @@ final class ChatViewModel: ObservableObject {
let queryText = userNode.text.trimmingCharacters(in: .whitespacesAndNewlines)
if !queryText.isEmpty,
(!enabledDatasets.isEmpty
- || notesStore.collections.contains(where: { $0.eligible }))
+ || !enabledCollectionIDs.isEmpty)
{
do {
let hits = try await provider.withRetrievalContext(
@@ -1288,7 +1417,8 @@ final class ChatViewModel: ObservableObject {
datasets: enabledDatasets, query: query,
maxHits: knowledgeEmbedding.maxHits
)
- let notes = try await notesStore.retrieve(query: query)
+ let notes = try await notesStore.retrieve(
+ query: query, collectionIDs: enabledCollectionIDs)
let candidates = try selectMixedGroundingCandidates(
packHits: packs.map {
KnowledgePromptHit(datasetId: $0.dataset.stableId, hit: $0.hit)
@@ -1320,7 +1450,10 @@ final class ChatViewModel: ObservableObject {
try Task.checkCancellation()
guard activeGenerationId == generationId else { return }
for locator in locators {
- if let hit = try await reloadPassage(locator) {
+ if let hit = try await reloadPassage(
+ locator, datasets: enabledDatasets,
+ collectionIDs: enabledCollectionIDs)
+ {
reloaded.append(hit)
}
}
@@ -1668,14 +1801,17 @@ final class ChatViewModel: ObservableObject {
}
}
- private func reloadPassage(_ locator: PassageLocator) async throws -> GroundedExcerpt? {
+ private func reloadPassage(
+ _ locator: PassageLocator, datasets: [KnowledgeDatasetConfig],
+ collectionIDs: Set<String>
+ ) async throws -> GroundedExcerpt? {
do {
switch locator {
case .ensuPack:
return try await knowledgeProvider.reload(
- locator, datasets: knowledgeStore.enabledReadyDatasets)
+ locator, datasets: datasets)
case .localNote(let note):
- return try await notesStore.reload(note)
+ return try await notesStore.reload(note, collectionIDs: collectionIDs)
}
} catch {
if isCancellation(error) { throw error }
diff --git a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
index 372e7d286d..47f961c1cc 100644
--- a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
+++ b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift
@@ -17,6 +17,7 @@ struct MessageInputView: View {
let onSend: () -> Void
let onStop: () -> Void
let onCancelEdit: () -> Void
+ let onSources: () -> Void
let onVoiceInput: () -> Void
let onAddImage: (Data, String?) -> Void
let onAddDocument: (URL) -> Void
@@ -121,36 +122,6 @@ struct MessageInputView: View {
}
HStack(alignment: .bottom, spacing: EnsuSpacing.sm) {
- MessageTextView(
- text: $text,
- isFocused: $isFocused,
- moveCursorToEndToken: moveCursorToEndToken,
- onSubmit: {
- if canSend {
- onSend()
- isFocused = false
- hideKeyboard()
- onDismissKeyboard()
- }
- }
- )
- .padding(.vertical, 6)
- .overlay(alignment: .topLeading) {
- if text.isEmpty {
- Text(placeholder)
- .font(EnsuTypography.message)
- .foregroundStyle(Color(uiColor: .placeholderText))
- .padding(.vertical, 6)
- .allowsHitTesting(false)
- .accessibilityHidden(true)
- }
- }
- .onChange(of: isFocused) { focused in
- if focused {
- onUserFocus()
- }
- }
-
if editingMessage == nil && supportsImageAttachments {
let canUseAttachment =
!isGenerating && !isDownloading && !isImageAttachmentLimitReached
@@ -190,6 +161,52 @@ struct MessageInputView: View {
}
}
+ 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,
+ moveCursorToEndToken: moveCursorToEndToken,
+ onSubmit: {
+ if canSend {
+ onSend()
+ isFocused = false
+ hideKeyboard()
+ onDismissKeyboard()
+ }
+ }
+ )
+ .padding(.vertical, 6)
+ .overlay(alignment: .topLeading) {
+ if text.isEmpty {
+ Text(placeholder)
+ .font(EnsuTypography.message)
+ .foregroundStyle(Color(uiColor: .placeholderText))
+ .padding(.vertical, 6)
+ .allowsHitTesting(false)
+ .accessibilityHidden(true)
+ }
+ }
+ .onChange(of: isFocused) { focused in
+ if focused {
+ onUserFocus()
+ }
+ }
+
if editingMessage == nil {
let isVoiceBusy = voiceInputState.isTranscriptionBusy
let canUseVoice =
diff --git a/apple/apps/ensu/Ensu/Services/ChatSourceSelection.swift b/apple/apps/ensu/Ensu/Services/ChatSourceSelection.swift
new file mode 100644
index 0000000000..9934fd9cdf
--- /dev/null
+++ b/apple/apps/ensu/Ensu/Services/ChatSourceSelection.swift
@@ -0,0 +1,86 @@
+import Foundation
+
+/// Explicit stable IDs preserve a chat's choices when sources are added later.
+struct ChatSourceSelection: Codable, Equatable, 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.swift
index f2bce21e69..31d6fd79f4 100644
--- a/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift
+++ b/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift
@@ -5,26 +5,23 @@ import SwiftUI
final class KnowledgeStore: ObservableObject {
@Published private(set) var packs: [KnowledgePackState]
@Published var downloadsAllowed = false
+ private(set) var inventoryReady = false
private let provider: KnowledgeProvider
- private let preferences: KnowledgePreferences
private var bootstrapTask: Task<Void, Never>?
private var mutationTasks: [String: Task<Void, Never>] = [:]
init(
datasets: [KnowledgeDatasetConfig],
- provider: KnowledgeProvider,
- defaults: UserDefaults = .standard
+ provider: KnowledgeProvider
) {
packs = datasets.map { KnowledgePackState(config: $0) }
self.provider = provider
- preferences = KnowledgePreferences(defaults: defaults)
}
- var enabledReadyDatasets: [KnowledgeDatasetConfig] {
+ var readyDatasets: [KnowledgeDatasetConfig] {
packs.compactMap { pack in
- guard pack.enabled,
- pack.status == .ready || pack.status == .updateAvailable
+ guard pack.status == .ready || pack.status == .updateAvailable
else {
return nil
}
@@ -40,48 +37,37 @@ final class KnowledgeStore: ObservableObject {
let task = Task { @MainActor [weak self] in
guard let self else { return }
- await bootstrapEnabledDatasets()
+ await bootstrapDatasets()
}
bootstrapTask = task
await task.value
}
- private func bootstrapEnabledDatasets() async {
- let requestedEnabled = preferences.enabledDatasetIds
- let datasets = packs.map(\.config)
- for dataset in datasets where requestedEnabled.contains(dataset.stableId) {
- await reconcileForBootstrap(dataset, enabled: true)
- }
-
- Task { @MainActor [weak self] in
- guard let self else { return }
- for dataset in datasets where !requestedEnabled.contains(dataset.stableId) {
- await reconcileForBootstrap(dataset, enabled: false)
+ private func bootstrapDatasets() async {
+ var failed = false
+ for dataset in packs.map(\.config) {
+ do {
+ let result = try await provider.reconcile(dataset: dataset)
+ applyReconciliation(result, stableId: dataset.stableId)
+ } catch {
+ failed = true
+ updatePack(dataset.stableId) { pack in
+ pack.status = .download
+ pack.errorMessage = userFacingKnowledgeError(error)
+ }
}
}
+ inventoryReady = !failed
}
- private func reconcileForBootstrap(
- _ dataset: KnowledgeDatasetConfig,
- enabled: Bool
- ) async {
- do {
- let result = try await provider.reconcile(dataset: dataset)
- applyReconciliation(
- result,
- stableId: dataset.stableId,
- enabled: enabled
- )
- } catch {
- updatePack(dataset.stableId) { pack in
- pack.status = .download
- pack.enabled = false
- pack.errorMessage = userFacingKnowledgeError(error)
- }
- }
+ func retryBootstrap() async {
+ await bootstrapTask?.value
+ guard !inventoryReady else { return }
+ bootstrapTask = nil
+ await bootstrap()
}
- func downloadOrUpdate(stableId: String) {
+ func downloadOrUpdate(stableId: String, onInstalled: (() -> Void)? = nil) {
guard downloadsAllowed,
mutationTasks[stableId] == nil,
let index = packs.firstIndex(where: { $0.id == stableId })
@@ -89,7 +75,6 @@ final class KnowledgeStore: ObservableObject {
return
}
let dataset = packs[index].config
- let wasInstalled = packs[index].activeIdentity != nil
updatePack(stableId) { pack in
pack.isMutating = true
pack.progressPercent = 0
@@ -108,28 +93,11 @@ final class KnowledgeStore: ObservableObject {
}
}
}
- let shouldEnable = !wasInstalled && result.status == .ready
- if shouldEnable {
- preferences.setDatasetEnabled(id: stableId, enabled: true)
- }
- let preservedEnablement =
- packs
- .first(where: { $0.id == stableId })?.enabled == true
- applyReconciliation(
- result,
- stableId: stableId,
- enabled: wasInstalled ? preservedEnablement : shouldEnable
- )
+ applyReconciliation(result, stableId: stableId)
+ if result.activeIdentity != nil { onInstalled?() }
} catch {
if let result = try? await provider.reconcile(dataset: dataset) {
- let enabled =
- packs
- .first(where: { $0.id == stableId })?.enabled == true
- applyReconciliation(
- result,
- stableId: stableId,
- enabled: enabled
- )
+ applyReconciliation(result, stableId: stableId)
}
updatePack(stableId) { pack in
pack.errorMessage = userFacingKnowledgeError(error)
@@ -157,10 +125,7 @@ final class KnowledgeStore: ObservableObject {
return
}
if let result {
- let enabled =
- packs
- .first(where: { $0.id == stableId })?.enabled == true
- applyReconciliation(result, stableId: stableId, enabled: enabled)
+ applyReconciliation(result, stableId: stableId)
}
updatePack(stableId) { pack in
pack.isMutating = false
@@ -170,28 +135,13 @@ final class KnowledgeStore: ObservableObject {
}
}
- func setEnabled(stableId: String, enabled: Bool) {
- guard let index = packs.firstIndex(where: { $0.id == stableId }),
- packs[index].activeIdentity != nil,
- !packs[index].isMutating
- else {
- return
- }
- updatePack(stableId) { pack in
- pack.enabled = enabled
- }
- preferences.setDatasetEnabled(id: stableId, enabled: enabled)
- }
-
private func applyReconciliation(
_ result: KnowledgeReconciliation,
- stableId: String,
- enabled: Bool
+ stableId: String
) {
updatePack(stableId) { pack in
pack.status = result.status
pack.activeIdentity = result.activeIdentity
- pack.enabled = enabled && result.activeIdentity != nil
pack.errorMessage = nil
}
}
@@ -234,35 +184,8 @@ struct KnowledgePackState: Identifiable, Sendable {
let config: KnowledgeDatasetConfig
var status: KnowledgeReconciliationStatus?
var activeIdentity: String?
- var enabled = false
var isMutating = false
var progressPercent: Int?
var progressLabel: String?
var errorMessage: String?
}
-
-private final class KnowledgePreferences {
- private enum Keys {
- static let enabledDatasetIds = "ensu.knowledge.enabled_dataset_ids"
- }
-
- private let defaults: UserDefaults
-
- init(defaults: UserDefaults) {
- self.defaults = defaults
- }
-
- var enabledDatasetIds: Set<String> {
- Set(defaults.stringArray(forKey: Keys.enabledDatasetIds) ?? [])
- }
-
- func setDatasetEnabled(id: String, enabled: Bool) {
- var ids = enabledDatasetIds
- if enabled {
- ids.insert(id)
- } else {
- ids.remove(id)
- }
- defaults.set(ids.sorted(), forKey: Keys.enabledDatasetIds)
- }
-}
diff --git a/apple/apps/ensu/Ensu/Services/NotesStore.swift b/apple/apps/ensu/Ensu/Services/NotesStore.swift
index ea3ecdb423..490805dffd 100644
--- a/apple/apps/ensu/Ensu/Services/NotesStore.swift
+++ b/apple/apps/ensu/Ensu/Services/NotesStore.swift
@@ -58,6 +58,17 @@ final class NotesStore: ObservableObject, ModelMaintenance {
self.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 bootstrap() async {
if let bootstrapTask {
await bootstrapTask.value
@@ -126,7 +137,7 @@ final class NotesStore: ObservableObject, ModelMaintenance {
await active?.task.value
}
- func add(_ url: URL) {
+ func add(_ url: URL, onAdded: ((String) -> Void)? = nil) {
Task {
await bootstrap()
guard !disabled else { return }
@@ -136,6 +147,7 @@ final class NotesStore: ObservableObject, ModelMaintenance {
collections.append(NoteCollectionState(id: record.id, label: record.label))
operationError = nil
enqueue(record.id, due: .distantPast)
+ onAdded?(record.id)
}
} catch {
operationError = Self.message(error)
@@ -181,9 +193,10 @@ final class NotesStore: ObservableObject, ModelMaintenance {
pump()
}
- func retrieve(query: [Float]) async throws -> [NotesHit] {
+ func retrieve(query: [Float], collectionIDs: Set<String>) async throws -> [NotesHit] {
var hits: [NotesHit] = []
- for collection in collections where collection.eligible {
+ for collection in collections
+ where collection.eligible && collectionIDs.contains(collection.id) {
try Task.checkCancellation()
do {
hits += try await provider.search(collection.id, query: query)
@@ -198,8 +211,11 @@ final class NotesStore: ObservableObject, ModelMaintenance {
return hits
}
- func reload(_ locator: NotePassageLocator) async throws -> GroundedExcerpt? {
- guard collections.contains(where: { $0.id == locator.collectionId && $0.eligible })
+ func reload(_ locator: NotePassageLocator, collectionIDs: Set<String>) async throws
+ -> GroundedExcerpt?
+ {
+ guard collectionIDs.contains(locator.collectionId),
+ collections.contains(where: { $0.id == locator.collectionId && $0.eligible })
else { return nil }
do {
guard let hit = try await provider.reload(locator) else { return nil }
diff --git a/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift b/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift
index 4780f1a214..79545c16c7 100644
--- a/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift
+++ b/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift
@@ -2,27 +2,34 @@ import SwiftUI
struct KnowledgeSettingsView: View {
@ObservedObject var store: KnowledgeStore
- @State private var attributionPack: KnowledgePackState?
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: EnsuSpacing.md) {
ForEach(store.packs) { pack in
- packCard(pack)
+ KnowledgePackCard(store: store, pack: 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)
- }
}
+}
- @ViewBuilder
- private func packCard(_ pack: KnowledgePackState) -> some View {
+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 {
let attribution = pack.config.attribution
EnsuCard {
HStack {
@@ -38,7 +45,7 @@ struct KnowledgeSettingsView: View {
.font(EnsuTypography.mini)
.foregroundStyle(EnsuColor.textMuted)
Button {
- attributionPack = pack
+ showAttribution = true
} label: {
HStack(spacing: EnsuSpacing.xs) {
Text(attribution.licenseLabel)
@@ -53,21 +60,18 @@ struct KnowledgeSettingsView: View {
}
}
Spacer()
- if pack.activeIdentity != nil && !pack.isMutating {
- Toggle(
- "",
- isOn: Binding(
- get: { pack.enabled },
- set: { store.setEnabled(stableId: pack.id, enabled: $0) }
- )
- )
- .labelsHidden()
- .tint(EnsuColor.accent)
+ if pack.activeIdentity != nil, let selection {
+ Toggle("Use \(pack.config.label) in this chat", isOn: selection)
+ .labelsHidden()
+ .tint(EnsuColor.accent)
+ .disabled(controlsDisabled || pack.isMutating)
} else if store.downloadsAllowed && pack.status == .download && !pack.isMutating {
CompactButton(text: "Download") {
- store.downloadOrUpdate(stableId: pack.id)
+ download()
}
+ .disabled(controlsDisabled)
}
+
}
if pack.isMutating {
@@ -89,9 +93,18 @@ struct KnowledgeSettingsView: View {
.accessibilityLabel("Cancel download")
}
} else if store.downloadsAllowed && pack.status == .updateAvailable {
- CompactButton(text: "Update") {
- store.downloadOrUpdate(stableId: pack.id)
- }
+ CompactButton(text: "Update") { download() }
+ .disabled(controlsDisabled)
+ } else if pack.activeIdentity != nil && selection == nil {
+ Text("Downloaded")
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ }
+
+ if pack.isMutating, let progress = pack.progressLabel {
+ Text(progress)
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
}
if let error = pack.errorMessage {
@@ -100,6 +113,13 @@ struct KnowledgeSettingsView: 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.swift
index 19bee6af5d..e9317e4100 100644
--- a/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swift
+++ b/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swift
@@ -11,53 +11,11 @@ struct NotesSettingsView: View {
ScrollView {
VStack(alignment: .leading, spacing: EnsuSpacing.md) {
ForEach(store.collections) { collection in
- 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()
- 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)
- }
- }
- }
+ NoteCollectionCard(
+ store: store, collection: collection,
+ onRemove: {
+ removing = collection
+ })
}
CompactButton(text: "Add notes folder") {
showPicker = true
@@ -93,6 +51,71 @@ 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.documentCount
let indexing = collection.status == .indexing || collection.status == .updating
@@ -107,7 +130,7 @@ struct NotesSettingsView: View {
}
}
-private struct NotesFolderPicker: UIViewControllerRepresentable {
+struct NotesFolderPicker: UIViewControllerRepresentable {
let selected: (URL) -> Void
func 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.swift
new file mode 100644
index 0000000000..af41e65a75
--- /dev/null
+++ b/apple/apps/ensu/EnsuTests/ChatSourceSelectionTests.swift
@@ -0,0 +1,114 @@
+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/rust/apps/ensu/changes/chat-sources.md b/rust/apps/ensu/changes/chat-sources.md
new file mode 100644
index 0000000000..47c9f5d6d0
--- /dev/null
+++ b/rust/apps/ensu/changes/chat-sources.md
@@ -0,0 +1 @@
+- Choose which Ensu Packs and note folders each chat uses from the composer, with pack downloads and folder setup in the same view.
diff --git a/rust/apps/ensu/src-tauri/src/commands/followup.rs b/rust/apps/ensu/src-tauri/src/commands/followup.rs
index 15b3473521..53b95fc006 100644
--- a/rust/apps/ensu/src-tauri/src/commands/followup.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/followup.rs
@@ -69,6 +69,7 @@ pub struct Request {
path: Vec<Uuid>,
question: String,
enabled_stable_ids: Vec<String>,
+ enabled_note_collection_ids: Vec<String>,
cancellation_epoch: u64,
candidates: Option<core::GroundingCandidates>,
}
@@ -124,6 +125,11 @@ pub async fn conversation_resolve_followup(
},
);
}
+ let sources = Arc::new(super::knowledge::SourceSelection::new(
+ input.enabled_stable_ids,
+ input.enabled_note_collection_ids,
+ ));
+ let searched_sources = Arc::clone(&sources);
let work_db = db.clone();
let check_work = check.clone();
let (snapshot, mut selection, references) = async_runtime::spawn_blocking(move || {
@@ -140,11 +146,12 @@ pub async fn conversation_resolve_followup(
}
check_work()?;
let evidence = snapshot.evidence();
- let (searched, max_utf8_bytes) = input
+ let (mut searched, max_utf8_bytes) = input
.candidates
.map_or((Vec::new(), core::MAX_GROUNDING_BYTES), |fresh| {
(fresh.searched, fresh.max_utf8_bytes)
});
+ searched.retain(|excerpt| searched_sources.allows(&excerpt.locator));
let candidates = core::GroundingCandidates::new(Vec::new(), searched, max_utf8_bytes)
.map_err(|cause| error(cause.to_string()))?;
let references = core::direct_followup_references(
@@ -165,14 +172,7 @@ pub async fn conversation_resolve_followup(
.map_err(|_| error("Source selection task failed"))??;
for reference in references {
check()?;
- match super::knowledge::reload_for_followup(
- &app,
- reference,
- input.enabled_stable_ids.clone(),
- expected,
- )
- .await
- {
+ match super::knowledge::reload_for_followup(&app, reference, &sources, expected).await {
Ok(Some(passage)) => selection.candidates.referenced.push(passage),
Ok(None) => {}
Err(error) if error.name == Some("cancelled") => return Err(error),
diff --git a/rust/apps/ensu/src-tauri/src/commands/knowledge.rs b/rust/apps/ensu/src-tauri/src/commands/knowledge.rs
index e62a7e25b1..842f02ca38 100644
--- a/rust/apps/ensu/src-tauri/src/commands/knowledge.rs
+++ b/rust/apps/ensu/src-tauri/src/commands/knowledge.rs
@@ -25,6 +25,32 @@ 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>,
+}
+
+impl SourceSelection {
+ pub(super) fn new(pack_ids: Vec<String>, note_collection_ids: Vec<String>) -> Self {
+ Self {
+ pack_ids: pack_ids.into_iter().collect(),
+ note_collection_ids: note_collection_ids.into_iter().collect(),
+ }
+ }
+
+ pub(super) fn allows(&self, locator: &retrieval::PassageLocator) -> bool {
+ match locator {
+ retrieval::PassageLocator::EnsuPack { dataset_id, .. } => {
+ self.pack_ids.contains(dataset_id)
+ }
+ retrieval::PassageLocator::LocalNote(locator) => {
+ self.note_collection_ids.contains(&locator.collection_id)
+ }
+ }
+ }
+}
+
impl State {
fn pack_lifecycle(&self, stable_id: &str) -> Arc<async_runtime::Mutex<()>> {
Arc::clone(
@@ -544,34 +570,39 @@ pub async fn knowledge_retrieve(
llm_state: TauriState<'_, crate::commands::llm::State>,
query: String,
enabled_stable_ids: Vec<String>,
+ enabled_note_collection_ids: Vec<String>,
max_context_utf8_bytes: u32,
retrieval_epoch: u64,
) -> Result<Option<GroundedPromptContextDto>, ApiError> {
let knowledge_state = app.state::<State>();
+ let selection = SourceSelection::new(enabled_stable_ids, enabled_note_collection_ids);
let (note_collection_ids, notes) = app
.try_state::<crate::commands::notes::State>()
.map_or_else(
|| (Vec::new(), None),
|state| {
(
- state.available_index_collection_ids(),
+ state
+ .available_index_collection_ids()
+ .into_iter()
+ .filter(|id| selection.note_collection_ids.contains(id))
+ .collect::<Vec<_>>(),
Some(state.retrieval_handle()),
)
},
);
if query.trim().is_empty()
- || (enabled_stable_ids.is_empty() && note_collection_ids.is_empty())
+ || (selection.pack_ids.is_empty() && note_collection_ids.is_empty())
|| max_context_utf8_bytes == 0
{
return Ok(None);
}
let defaults = ente_ensu::config::defaults();
- let enabled = enabled_stable_ids.into_iter().collect::<HashSet<_>>();
let datasets = defaults
.knowledge_datasets
.into_iter()
- .filter(|dataset| enabled.contains(&dataset.stable_id))
+ .filter(|dataset| selection.pack_ids.contains(&dataset.stable_id))
.collect::<Vec<_>>();
let embedding = defaults.knowledge_embedding;
@@ -687,9 +718,12 @@ pub async fn knowledge_retrieve(
pub(crate) async fn reload_for_followup(
app: &AppHandle,
reference: retrieval::IncludedPassage,
- enabled_stable_ids: Vec<String>,
+ selection: &SourceSelection,
retrieval_epoch: u64,
) -> Result<Option<retrieval::ReferencedPassage>, ApiError> {
+ if !selection.allows(&reference.locator) {
+ return Ok(None);
+ }
let app = app.clone();
let indexes = Arc::clone(&app.state::<State>().indexes);
let (collection_ids, notes) = app
@@ -717,9 +751,6 @@ pub(crate) async fn reload_for_followup(
let mut note_hits = Vec::new();
match &reference.locator {
retrieval::PassageLocator::EnsuPack { dataset_id, .. } => {
- if !enabled_stable_ids.contains(dataset_id) {
- return Ok(None);
- }
let indexes = indexes.lock().unwrap_or_else(PoisonError::into_inner);
let Some(open) = indexes.get(dataset_id) else {
return Ok(None);
@@ -802,6 +833,64 @@ 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(&note), 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.json
index 77fc2be4c0..7ebb8299b5 100644
--- a/web/apps/ensu/package.json
+++ b/web/apps/ensu/package.json
@@ -2,6 +2,9 @@
"name": "ensu",
"version": "0.0.0",
"private": true,
+ "scripts": {
+ "test": "node --experimental-transform-types --test tests/*.test.mjs"
+ },
"dependencies": {
"@hugeicons/core-free-icons": "4.3.5",
"@hugeicons/react": "1.1.10",
diff --git a/web/apps/ensu/src/components/chat/ChatComposer.tsx b/web/apps/ensu/src/components/chat/ChatComposer.tsx
index 9768b26c56..284a3f96e9 100644
--- a/web/apps/ensu/src/components/chat/ChatComposer.tsx
+++ b/web/apps/ensu/src/components/chat/ChatComposer.tsx
@@ -67,6 +67,12 @@ export interface ChatComposerProps {
isGenerating: boolean;
handleSend: (input: string) => void | Promise<void>;
handleStopGeneration: () => void;
+ showSourcePicker: boolean;
+ openSources: () => void;
+ sourcesDisabled: boolean;
+ sourcesLoading: boolean;
+ isPreparingMessage: boolean;
+ sourcesStatus?: string;
showAttachmentPicker: boolean;
openAttachmentMenu: (event: React.MouseEvent<HTMLElement>) => void;
attachmentAnchor: HTMLElement | null;
@@ -108,6 +114,12 @@ export const ChatComposer = memo(
isGenerating,
handleSend,
handleStopGeneration,
+ showSourcePicker,
+ openSources,
+ sourcesDisabled,
+ sourcesLoading,
+ isPreparingMessage,
+ sourcesStatus,
showAttachmentPicker,
openAttachmentMenu,
attachmentAnchor,
@@ -146,6 +158,7 @@ export const ChatComposer = memo(
modelGateStatus === "preloading" ||
modelGateStatus === "downloading";
const disableAttachmentButton =
+ isPreparingMessage ||
isGenerating ||
isAttachingImages ||
isModelPreparationActive ||
@@ -540,7 +553,39 @@ export const ChatComposer = memo(
</Box>
)}
+ {sourcesStatus && (
+ <Stack
+ direction="row"
+ sx={{
+ alignItems: "center",
+ px: 1.5,
+ gap: 1,
+ }}
+ role="status"
+ >
+ <Typography
+ variant="small"
+ sx={{
+ flex: 1,
+ color: "text.muted",
+ }}
+ >
+ {sourcesStatus}
+ </Typography>
+ <Button
+ size="small"
+ onClick={openSources}
+ >
+ Sources
+ </Button>
+ </Stack>
+ )}
<ChatInput
+ showSourcePicker={showSourcePicker}
+ openSources={openSources}
+ sourcesDisabled={sourcesDisabled}
+ sourcesLoading={sourcesLoading}
+ isPreparingMessage={isPreparingMessage}
ref={inputRef}
actionIconProps={actionIconProps}
disableAttachmentButton={
diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
index c03fe4ecc9..e0a35ad259 100644
--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx
+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
@@ -97,6 +97,16 @@ 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;
@@ -168,6 +178,13 @@ export interface ChatDialogsProps {
export const ChatDialogs = memo(
({
+ showSources,
+ closeSources,
+ sourceSelectionDisabled,
+ handleDownloadChatKnowledgePack,
+ handleAddChatNotesFolder,
+ enabledNoteCollectionIds,
+ handleSetNotesCollectionEnabled,
showSettingsModal,
openSettingsModal,
closeSettingsModal,
@@ -339,8 +356,462 @@ 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>
<Dialog
open={!!imagePreview}
onClose={closeImagePreview}
@@ -775,197 +1246,7 @@ export const ChatDialogs = memo(
Your Notes
</Box>
</DialogTitle>
- <DialogContent>
- <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 />}
- {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>
- <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>
- )}
- {(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>
+ <DialogContent>{renderNotesContent(false)}</DialogContent>
</Dialog>
<Dialog
@@ -1000,208 +1281,7 @@ export const ChatDialogs = memo(
<Box component="span">Ensu Packs</Box>
</DialogTitle>
<DialogContent>
- <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 ? (
- <Switch
- checked={enabled}
- disabled={
- knowledgeCatalogLoading
- }
- onChange={(_, checked) =>
- handleSetKnowledgePackEnabled(
- pack.stableId,
- checked,
- )
- }
- slotProps={{
- input: {
- "aria-label": `Enable ${pack.label}`,
- },
- }}
- />
- ) : 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>
+ {renderKnowledgeContent(false)}
</DialogContent>
</Dialog>
diff --git a/web/apps/ensu/src/components/chat/ChatInput.tsx b/web/apps/ensu/src/components/chat/ChatInput.tsx
index 4a090535ce..d6bae9148b 100644
--- a/web/apps/ensu/src/components/chat/ChatInput.tsx
+++ b/web/apps/ensu/src/components/chat/ChatInput.tsx
@@ -1,6 +1,10 @@
-import { Navigation06Icon, Upload01Icon } from "@hugeicons/core-free-icons";
+import {
+ Navigation06Icon,
+ PackageIcon,
+ Upload01Icon,
+} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { Box, IconButton, InputBase } from "@mui/material";
+import { Box, IconButton, InputBase, Tooltip } from "@mui/material";
import type { SxProps, Theme } from "@mui/material/styles";
import React, {
forwardRef,
@@ -35,6 +39,11 @@ interface ChatInputProps {
isModelPreparationActive: boolean;
openAttachmentMenu: (event: React.MouseEvent<HTMLElement>) => void;
onTextChange: (text: string) => void;
+ showSourcePicker: boolean;
+ openSources: () => void;
+ sourcesDisabled: boolean;
+ sourcesLoading: boolean;
+ isPreparingMessage: boolean;
showAttachmentPicker: boolean;
stopButtonColor: string;
}
@@ -55,6 +64,11 @@ export const ChatInput = memo(
isModelPreparationActive,
openAttachmentMenu,
onTextChange,
+ showSourcePicker,
+ openSources,
+ sourcesDisabled,
+ sourcesLoading,
+ isPreparingMessage,
showAttachmentPicker,
stopButtonColor,
},
@@ -78,7 +92,9 @@ export const ChatInput = memo(
const send = () => void handleSend(input);
const disableSend =
+ (isPreparingMessage && !isGenerating) ||
isModelPreparationActive ||
+ sourcesLoading ||
isDownloading ||
(!isGenerating &&
(isAttachingImages ||
@@ -97,6 +113,37 @@ export const ChatInput = memo(
"color-mix(in srgb, var(--mui-palette-background-default) 45%, var(--mui-palette-background-paper) 55%)",
}}
>
+ {showAttachmentPicker && (
+ <IconButton
+ aria-label="Add attachment"
+ sx={drawerIconButtonSx}
+ disabled={disableAttachmentButton}
+ onClick={openAttachmentMenu}
+ >
+ <HugeiconsIcon
+ icon={Upload01Icon}
+ {...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>
+ )}
<InputBase
multiline
inputComponent="textarea"
@@ -161,19 +208,6 @@ export const ChatInput = memo(
},
}}
/>
- {showAttachmentPicker && (
- <IconButton
- aria-label="Add attachment"
- sx={drawerIconButtonSx}
- disabled={disableAttachmentButton}
- onClick={openAttachmentMenu}
- >
- <HugeiconsIcon
- icon={Upload01Icon}
- {...actionIconProps}
- />
- </IconButton>
- )}
<IconButton
aria-label={isGenerating ? "Stop" : "Send message"}
onClick={isGenerating ? handleStopGeneration : send}
diff --git a/web/apps/ensu/src/hooks/use-chat-sources.ts b/web/apps/ensu/src/hooks/use-chat-sources.ts
new file mode 100644
index 0000000000..0df6663477
--- /dev/null
+++ b/web/apps/ensu/src/hooks/use-chat-sources.ts
@@ -0,0 +1,68 @@
+import {
+ ChatSourceSelectionStore,
+ type ChatSourceSelection,
+} from "@/services/chat/source-selection";
+import log from "ente-base/log";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+export const useChatSources = (
+ sessionId: string | undefined,
+ defaults: ChatSourceSelection,
+ inventoryReady: boolean,
+) => {
+ const [draftId, setDraftId] = useState("draft:initial");
+ const [revision, setRevision] = useState(0);
+ const storeRef = useRef<ChatSourceSelectionStore | null>(null);
+ if (!storeRef.current) {
+ storeRef.current = new ChatSourceSelectionStore(
+ typeof window === "undefined" ? undefined : window.localStorage,
+ (error) => log.warn("Failed to persist chat sources", error),
+ );
+ }
+ const store = storeRef.current;
+ const targetId = sessionId ?? draftId;
+ const selection = store.get(targetId);
+ useEffect(() => {
+ if (!inventoryReady || store.get(targetId)) return;
+ store.initialize(targetId, defaults);
+ setRevision((value) => value + 1);
+ }, [defaults, inventoryReady, revision, store, targetId]);
+
+ const setEnabled = useCallback(
+ (
+ target: string,
+ kind: keyof ChatSourceSelection,
+ sourceId: string,
+ enabled: boolean,
+ ) => {
+ store.setEnabled(target, kind, sourceId, enabled);
+ setRevision((value) => value + 1);
+ },
+ [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);
+ setRevision((value) => value + 1);
+ },
+ [store],
+ );
+ return {
+ selection,
+ targetId,
+ setEnabled,
+ transferDraft,
+ resetDraft,
+ removeSelection,
+ };
+};
diff --git a/web/apps/ensu/src/hooks/use-notes-collections.ts b/web/apps/ensu/src/hooks/use-notes-collections.ts
index a1a0b09af6..3cc9ac999c 100644
--- a/web/apps/ensu/src/hooks/use-notes-collections.ts
+++ b/web/apps/ensu/src/hooks/use-notes-collections.ts
@@ -43,6 +43,7 @@ export const useNotesCollections = ({
}: UseNotesCollectionsOptions) => {
const [collections, setCollections] = useState<NotesCollection[]>([]);
const [loading, setLoading] = useState(false);
+ const [loaded, setLoaded] = useState(false);
const [operationError, setOperationError] = useState<string | null>(null);
const [listError, setListError] = useState<string | null>(null);
const [subscriptionError, setSubscriptionError] = useState<string | null>(
@@ -82,6 +83,7 @@ export const useNotesCollections = ({
continue;
}
setCollections(next);
+ setLoaded(true);
setListError(null);
return;
} catch (error) {
@@ -351,10 +353,12 @@ export const useNotesCollections = ({
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 removeCollection = useCallback(
@@ -435,6 +439,7 @@ export const useNotesCollections = ({
return {
collections: collectionViews,
loading,
+ loaded,
error: subscriptionError ?? listError ?? operationError,
retry,
addFolder,
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index ffff4c04df..565de8e673 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -6,6 +6,7 @@ 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";
import {
@@ -42,10 +43,8 @@ import {
cancelKnowledgePackDownload,
downloadKnowledgePack,
knowledgeErrorMessage,
- loadEnabledKnowledgePacks,
loadKnowledgeCatalog,
retrieveKnowledge,
- saveEnabledKnowledgePacks,
type GroundedSource,
type KnowledgePack,
} from "@/services/knowledge";
@@ -559,9 +558,10 @@ const Page: React.FC = () => {
const [knowledgeCatalogError, setKnowledgeCatalogError] = useState<
string | null
>(null);
- const [enabledKnowledgePackIds, setEnabledKnowledgePackIds] = useState(
- loadEnabledKnowledgePacks,
- );
+ const [knowledgeCatalogLoaded, setKnowledgeCatalogLoaded] = useState(false);
+ const [showSources, setShowSources] = useState(false);
+ const [isPreparingMessage, setIsPreparingMessage] = useState(false);
+ const pendingSendRef = useRef(false);
const [knowledgeDownloadProgress, setKnowledgeDownloadProgress] = useState<
Record<string, number | undefined>
>({});
@@ -640,9 +640,7 @@ const Page: React.FC = () => {
const knowledgeCatalogPromiseRef = useRef<Promise<KnowledgePack[]> | null>(
null,
);
- const knowledgeBootstrapPromiseRef = useRef<Promise<
- KnowledgePack[]
- > | null>(null);
+
const generationStartingRef = useRef(false);
const generationActiveRef = useRef(false);
const preparedReplyRef = useRef<PreparedReply | undefined>(undefined);
@@ -739,21 +737,13 @@ const Page: React.FC = () => {
return knowledgeCatalogPromiseRef.current;
}, []);
- const loadEnabledKnowledgeCatalogOnce = useCallback(() => {
- if (!knowledgeBootstrapPromiseRef.current) {
- knowledgeBootstrapPromiseRef.current = loadKnowledgeCatalog([
- ...loadEnabledKnowledgePacks(),
- ]);
- }
- return knowledgeBootstrapPromiseRef.current;
- }, []);
-
const refreshKnowledgeCatalog = useCallback(async () => {
if (!isTauriRuntime) return;
setKnowledgeCatalogLoading(true);
setKnowledgeCatalogError(null);
try {
setKnowledgePacks(await loadKnowledgeCatalogOnce());
+ setKnowledgeCatalogLoaded(true);
} catch (error) {
setKnowledgeCatalogError(knowledgeErrorMessage(error));
log.error("Failed to refresh Ensu Packs", error);
@@ -949,46 +939,8 @@ const Page: React.FC = () => {
}, []);
useEffect(() => {
- if (!isTauriRuntime) return;
- setKnowledgeCatalogLoading(true);
- setKnowledgeCatalogError(null);
- void loadEnabledKnowledgeCatalogOnce()
- .then((packs) => {
- setKnowledgePacks(packs);
- const enabled = loadEnabledKnowledgePacks();
- const disabledStableIds = packs
- .filter((pack) => !enabled.has(pack.stableId))
- .map((pack) => pack.stableId);
- if (disabledStableIds.length === 0) return;
- return loadKnowledgeCatalog(disabledStableIds)
- .then((updates) => {
- setKnowledgePacks((current) => {
- const currentById = new Map(
- current.map((pack) => [pack.stableId, pack]),
- );
- return updates.map((pack) =>
- pack.status
- ? pack
- : (currentById.get(pack.stableId) ?? pack),
- );
- });
- })
- .catch((error: unknown) => {
- setKnowledgeCatalogError(knowledgeErrorMessage(error));
- log.error(
- "Failed to refresh disabled Ensu Packs",
- error,
- );
- });
- })
- .catch((error: unknown) => {
- setKnowledgeCatalogError(knowledgeErrorMessage(error));
- log.error("Failed to bootstrap enabled Ensu Packs", error);
- })
- .finally(() => {
- setKnowledgeCatalogLoading(false);
- });
- }, [isTauriRuntime, loadEnabledKnowledgeCatalogOnce]);
+ if (isTauriRuntime) void refreshKnowledgeCatalog();
+ }, [isTauriRuntime, refreshKnowledgeCatalog]);
useEffect(() => {
if (typeof window === "undefined") return;
@@ -1814,7 +1766,10 @@ const Page: React.FC = () => {
}, []);
const isNotesGenerationActive = useCallback(
- () => generationActiveRef.current || sessionSummaryActiveRef.current,
+ () =>
+ pendingSendRef.current ||
+ generationActiveRef.current ||
+ sessionSummaryActiveRef.current,
[],
);
const cancelNotesIndexing = useCallback(() => {
@@ -1842,6 +1797,7 @@ const Page: React.FC = () => {
const {
collections: notesCollections,
loading: notesCollectionsLoading,
+ loaded: notesCollectionsLoaded,
error: notesCollectionsError,
retry: retryNotesCollections,
addFolder: handleAddNotesFolder,
@@ -1849,7 +1805,8 @@ const Page: React.FC = () => {
runIndex: runNotesIndex,
} = useNotesCollections({
isTauriRuntime,
- isGenerating: isGenerating || isSessionSummaryGenerating,
+ isGenerating:
+ isPreparingMessage || isGenerating || isSessionSummaryGenerating,
isGenerationActive: isNotesGenerationActive,
modelReady: modelGateStatus === "ready",
ensureProvider,
@@ -1857,6 +1814,98 @@ const Page: React.FC = () => {
confirmRemoval: confirmNotesRemoval,
});
+ const sourceDefaults = useMemo(
+ () => ({
+ packIds: knowledgePacks
+ .filter(
+ (pack) =>
+ pack.status === "ready" ||
+ pack.status === "updateAvailable",
+ )
+ .map((pack) => pack.stableId),
+ noteCollectionIds: notesCollections.map(
+ (collection) => collection.id,
+ ),
+ }),
+ [knowledgePacks, notesCollections],
+ );
+ const {
+ selection: sourceSelection,
+ targetId: sourceSelectionTarget,
+ setEnabled: setChatSourceEnabled,
+ transferDraft: transferDraftSources,
+ resetDraft: resetDraftSources,
+ removeSelection: removeChatSources,
+ } = useChatSources(
+ currentSessionId,
+ sourceDefaults,
+ isTauriRuntime && knowledgeCatalogLoaded && notesCollectionsLoaded,
+ );
+ const enabledKnowledgePackIds = useMemo(
+ () => new Set(sourceSelection?.packIds ?? []),
+ [sourceSelection],
+ );
+ const enabledNoteCollectionIds = useMemo(
+ () => new Set(sourceSelection?.noteCollectionIds ?? []),
+ [sourceSelection],
+ );
+ const sourcesReady =
+ Boolean(sourceSelection) &&
+ knowledgeCatalogLoaded &&
+ notesCollectionsLoaded;
+ 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 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 {
modelId: selectedModelId || undefined,
@@ -2441,6 +2490,8 @@ const Page: React.FC = () => {
const handleNewChat = useCallback(() => {
cancelActiveGenerationForNavigation();
+ resetDraftSources();
+ setShowSources(false);
setCurrentSessionId(undefined);
currentSessionIdRef.current = undefined;
setAllMessages([]);
@@ -2465,12 +2516,14 @@ const Page: React.FC = () => {
focusInput,
isSmall,
resetPendingImages,
+ resetDraftSources,
updateRouteSession,
]);
const handleSelectSession = useCallback(
(sessionId: string) => {
cancelActiveGenerationForNavigation();
+ setShowSources(false);
setCurrentSessionId(sessionId);
currentSessionIdRef.current = sessionId;
setIsDraftSession(false);
@@ -2490,6 +2543,7 @@ const Page: React.FC = () => {
const removeSessionFromState = useCallback(
(sessionId: string) => {
manuallyRenamedSessionIdsRef.current.delete(sessionId);
+ removeChatSources(sessionId);
setSessions((prev) =>
prev.filter((session) => session.sessionUuid !== sessionId),
);
@@ -2498,6 +2552,8 @@ const Page: React.FC = () => {
);
if (currentSessionIdRef.current === sessionId) {
+ resetDraftSources();
+ setShowSources(false);
setCurrentSessionId(undefined);
currentSessionIdRef.current = undefined;
setIsDraftSession(true);
@@ -2505,7 +2561,7 @@ const Page: React.FC = () => {
updateRouteSession(undefined, true);
}
},
- [updateRouteSession],
+ [removeChatSources, resetDraftSources, updateRouteSession],
);
const handleDeleteSession = useCallback(
@@ -2953,6 +3009,9 @@ const Page: React.FC = () => {
) {
return;
}
+ if (isTauriRuntime && !sourcesReady) return;
+ const selectedPackIds = new Set(sourceSelection?.packIds);
+ const selectedNoteIds = new Set(sourceSelection?.noteCollectionIds);
generationStartingRef.current = true;
generationActiveRef.current = true;
setIsGenerating(true);
@@ -3064,31 +3123,23 @@ const Page: React.FC = () => {
let knowledgeContext: Awaited<
ReturnType<typeof retrieveKnowledge>
> = null;
- let readyPacks = knowledgePacks;
- if (
- isTauriRuntime &&
- enabledKnowledgePackIds.size > 0 &&
- readyPacks.length === 0
- ) {
- try {
- readyPacks = await loadEnabledKnowledgeCatalogOnce();
- if (!isActiveGeneration()) return;
- setKnowledgePacks(readyPacks);
- } catch (error) {
- log.warn(
- "Ensu Pack bootstrap failed; continuing without pack context",
- error,
- );
- }
- }
- const enabledReadyPackIds = readyPacks
+ const enabledReadyPackIds = knowledgePacks
.filter(
(pack) =>
(pack.status === "ready" ||
pack.status === "updateAvailable") &&
- enabledKnowledgePackIds.has(pack.stableId),
+ selectedPackIds.has(pack.stableId),
)
.map((pack) => pack.stableId);
+ const enabledReadyNoteIds = notesCollections
+ .filter(
+ (collection) =>
+ selectedNoteIds.has(collection.id) &&
+ collection.indexedDocumentCount > 0 &&
+ collection.status !== "unavailable" &&
+ collection.status !== "error",
+ )
+ .map((collection) => collection.id);
const knowledgeQuery = parseDocumentBlocks(promptText)
.text.replaceAll(MEDIA_MARKER, "")
.replace(/\[\d+ image attachments? provided\]/gi, "")
@@ -3106,7 +3157,9 @@ const Page: React.FC = () => {
if (
isTauriRuntime &&
knowledgeQuery &&
- remainingKnowledgeBytes > 0
+ remainingKnowledgeBytes > 0 &&
+ (enabledReadyPackIds.length > 0 ||
+ enabledReadyNoteIds.length > 0)
) {
setConversationStatus("Finding sources");
try {
@@ -3116,6 +3169,7 @@ const Page: React.FC = () => {
retrieveKnowledge(
knowledgeQuery,
enabledReadyPackIds,
+ enabledReadyNoteIds,
remainingKnowledgeBytes,
retrievalEpoch,
),
@@ -3156,6 +3210,8 @@ const Page: React.FC = () => {
path: conversationPath,
question: knowledgeQuery,
enabledStableIds: enabledReadyPackIds,
+ enabledNoteCollectionIds:
+ enabledReadyNoteIds,
cancellationEpoch,
candidates: knowledgeContext?.candidates,
}),
@@ -3472,9 +3528,10 @@ const Page: React.FC = () => {
scheduleSessionTitle,
systemPrompt,
isTauriRuntime,
- enabledKnowledgePackIds,
+ sourceSelection,
+ sourcesReady,
knowledgePacks,
- loadEnabledKnowledgeCatalogOnce,
+ notesCollections,
],
);
@@ -3715,16 +3772,10 @@ const Page: React.FC = () => {
[],
);
const handleDownloadKnowledgePack = useCallback(
- (stableId: string) => {
+ (stableId: string, selectForChat?: string) => {
if (activeKnowledgeDownloadsRef.current.has(stableId)) return;
activeKnowledgeDownloadsRef.current.add(stableId);
- const previousPack = knowledgePacks.find(
- (pack) => pack.stableId === stableId,
- );
- const wasInstalled = Boolean(
- previousPack && previousPack.status !== "download",
- );
setKnowledgeErrors((current) => ({
...current,
[stableId]: undefined,
@@ -3745,13 +3796,13 @@ const Page: React.FC = () => {
item.stableId === stableId ? pack : item,
),
);
- if (!wasInstalled) {
- setEnabledKnowledgePackIds((current) => {
- const next = new Set(current).add(stableId);
- saveEnabledKnowledgePacks(next);
- return next;
- });
- }
+ if (selectForChat)
+ setChatSourceEnabled(
+ selectForChat,
+ "packIds",
+ stableId,
+ true,
+ );
})
.catch((error: unknown) => {
const { name } = tauriCommandError(error);
@@ -3771,7 +3822,7 @@ const Page: React.FC = () => {
}));
});
},
- [knowledgePacks, refreshKnowledgeCatalog],
+ [refreshKnowledgeCatalog, setChatSourceEnabled],
);
const handleCancelKnowledgePackDownload = useCallback(
(stableId: string) => {
@@ -3783,17 +3834,20 @@ const Page: React.FC = () => {
},
[],
);
- const handleSetKnowledgePackEnabled = useCallback(
- (stableId: string, enabled: boolean) => {
- setEnabledKnowledgePackIds((current) => {
- const next = new Set(current);
- if (enabled) next.add(stableId);
- else next.delete(stableId);
- saveEnabledKnowledgePacks(next);
- return next;
- });
+ 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(() => {
@@ -4259,7 +4313,7 @@ const Page: React.FC = () => {
}, []);
const handleSend = async (input: string) => {
- if (isAttachingImages) return;
+ if (isAttachingImages || pendingSendRef.current) return;
const trimmed = input.trim();
const hasDocuments = pendingDocuments.length > 0;
const hasImages = pendingImages.length > 0;
@@ -4274,7 +4328,12 @@ const Page: React.FC = () => {
if (!trimmed && !hasDocuments && !hasImages) {
return;
}
- if (showModelGate || isModelPreparationActive) return;
+ if (
+ showModelGate ||
+ isModelPreparationActive ||
+ (isTauriRuntime && !sourcesReady)
+ )
+ return;
if (generationStartingRef.current || generationStoppingRef.current) {
return;
}
@@ -4293,143 +4352,186 @@ const Page: React.FC = () => {
return;
}
- setStickToBottom(true);
+ pendingSendRef.current = true;
+ setIsPreparingMessage(true);
+ try {
+ setStickToBottom(true);
- let activeSessionId = currentSessionId;
- if (!activeSessionId) {
- try {
- activeSessionId = await createSession(chatKey);
- } catch (error) {
- onGenericError(error);
- return;
+ let activeSessionId = currentSessionId;
+ if (!activeSessionId) {
+ try {
+ activeSessionId = await createSession(chatKey);
+ } catch (error) {
+ onGenericError(error);
+ return;
+ }
+ transferDraftSources(activeSessionId);
+ setCurrentSessionId(activeSessionId);
+ currentSessionIdRef.current = activeSessionId;
+ setIsDraftSession(false);
+ isDraftSessionRef.current = false;
+ updateRouteSession(activeSessionId, true);
+ await refreshSessions();
}
- setCurrentSessionId(activeSessionId);
- currentSessionIdRef.current = activeSessionId;
- setIsDraftSession(false);
- isDraftSessionRef.current = false;
- updateRouteSession(activeSessionId, true);
- await refreshSessions();
- }
- const messageText = buildPromptWithDocuments(
- trimmed.replaceAll("\0", ""),
- pendingDocuments,
- );
- const persistedAttachmentIds = new Set(
- (editingMessage?.attachments ?? []).map(({ id }) => id),
- );
- const newAttachmentIds = [
- ...pendingDocuments.map(({ id }) => id),
- ...pendingImages.map(({ id }) => id),
- ].filter((id) => !persistedAttachmentIds.has(id));
- const cleanupUnstoredAttachments = async () => {
- await Promise.all(
- newAttachmentIds.map(async (id) => {
- try {
- await deleteAttachmentBytes(id);
- } catch (error) {
- log.warn(
- `Failed to clean up attachment payload ${id}`,
- error,
- );
- }
- }),
+ const messageText = buildPromptWithDocuments(
+ trimmed.replaceAll("\0", ""),
+ pendingDocuments,
);
- };
- let inferenceImagePaths: string[] = [];
-
- let attachments: ChatAttachment[] = [];
- if (pendingDocuments.length > 0 || pendingImages.length > 0) {
- try {
- const encoder = new TextEncoder();
- const documentAttachments = await Promise.all(
- pendingDocuments.map(async (doc) => {
- const bytes = encoder.encode(doc.text);
- await storeEncryptedAttachmentBytes(
- doc.id,
- bytes,
- chatKey,
- activeSessionId,
- );
- return {
- id: doc.id,
- kind: "document",
- name: doc.name.replace(/\0/g, ""),
- size: bytes.length,
- } satisfies ChatAttachment;
- }),
- );
- const imageAttachments = await Promise.all(
- pendingImages.map(async (img) => {
- const bytes = new Uint8Array(
- await img.file.arrayBuffer(),
- );
- await storeEncryptedAttachmentBytes(
- img.id,
- bytes,
- chatKey,
- activeSessionId,
- );
- const previewUrl = URL.createObjectURL(
- new Blob([toSafeBlobPart(bytes)]),
- );
- attachmentPreviewUrlsRef.current[img.id] = previewUrl;
- setAttachmentPreviews((prev) => ({
- ...prev,
- [img.id]: previewUrl,
- }));
- return {
- id: img.id,
- kind: "image",
- name: img.name.replace(/\0/g, ""),
- size: img.size,
- } satisfies ChatAttachment;
+ const persistedAttachmentIds = new Set(
+ (editingMessage?.attachments ?? []).map(({ id }) => id),
+ );
+ const newAttachmentIds = [
+ ...pendingDocuments.map(({ id }) => id),
+ ...pendingImages.map(({ id }) => id),
+ ].filter((id) => !persistedAttachmentIds.has(id));
+ const cleanupUnstoredAttachments = async () => {
+ await Promise.all(
+ newAttachmentIds.map(async (id) => {
+ try {
+ await deleteAttachmentBytes(id);
+ } catch (error) {
+ log.warn(
+ `Failed to clean up attachment payload ${id}`,
+ error,
+ );
+ }
}),
);
- attachments = [...documentAttachments, ...imageAttachments];
- } catch (error) {
- await cleanupUnstoredAttachments();
- log.error("Failed to store attachments", error);
- showMiniDialog({
- title: "Attachment error",
- message: "We could not attach the files. Please try again.",
- });
- return;
+ };
+ let inferenceImagePaths: string[] = [];
+
+ let attachments: ChatAttachment[] = [];
+ if (pendingDocuments.length > 0 || pendingImages.length > 0) {
+ try {
+ const encoder = new TextEncoder();
+ const documentAttachments = await Promise.all(
+ pendingDocuments.map(async (doc) => {
+ const bytes = encoder.encode(doc.text);
+ await storeEncryptedAttachmentBytes(
+ doc.id,
+ bytes,
+ chatKey,
+ activeSessionId,
+ );
+ return {
+ id: doc.id,
+ kind: "document",
+ name: doc.name.replace(/\0/g, ""),
+ size: bytes.length,
+ } satisfies ChatAttachment;
+ }),
+ );
+ const imageAttachments = await Promise.all(
+ pendingImages.map(async (img) => {
+ const bytes = new Uint8Array(
+ await img.file.arrayBuffer(),
+ );
+ await storeEncryptedAttachmentBytes(
+ img.id,
+ bytes,
+ chatKey,
+ activeSessionId,
+ );
+ const previewUrl = URL.createObjectURL(
+ new Blob([toSafeBlobPart(bytes)]),
+ );
+ attachmentPreviewUrlsRef.current[img.id] =
+ previewUrl;
+ setAttachmentPreviews((prev) => ({
+ ...prev,
+ [img.id]: previewUrl,
+ }));
+ return {
+ id: img.id,
+ kind: "image",
+ name: img.name.replace(/\0/g, ""),
+ size: img.size,
+ } satisfies ChatAttachment;
+ }),
+ );
+ attachments = [...documentAttachments, ...imageAttachments];
+ } catch (error) {
+ await cleanupUnstoredAttachments();
+ log.error("Failed to store attachments", error);
+ showMiniDialog({
+ title: "Attachment error",
+ message:
+ "We could not attach the files. Please try again.",
+ });
+ return;
+ }
}
- }
- if (pendingImages.length > 0) {
- try {
- inferenceImagePaths = await writeInferenceImages(pendingImages);
- } catch (error) {
- await cleanupUnstoredAttachments();
- log.error("Failed to prepare images for inference", error);
- showMiniDialog({
- title: "Attachment error",
- message:
- "We could not prepare the images for inference. Please try again.",
- });
- return;
+ if (pendingImages.length > 0) {
+ try {
+ inferenceImagePaths =
+ await writeInferenceImages(pendingImages);
+ } catch (error) {
+ await cleanupUnstoredAttachments();
+ log.error("Failed to prepare images for inference", error);
+ showMiniDialog({
+ title: "Attachment error",
+ message:
+ "We could not prepare the images for inference. Please try again.",
+ });
+ return;
+ }
}
- }
- const promptText = buildPromptWithImages(
- messageText,
- inferenceImagePaths.length,
- );
+ const promptText = buildPromptWithImages(
+ messageText,
+ inferenceImagePaths.length,
+ );
- composerRef.current?.setText("");
+ composerRef.current?.setText("");
- let messageStored = false;
- try {
- if (editingMessage) {
- const parentUuid = editingMessage.parentMessageUuid;
+ let messageStored = false;
+ try {
+ if (editingMessage) {
+ const parentUuid = editingMessage.parentMessageUuid;
+ const selectionKey = parentUuid ?? ROOT_SELECTION_KEY;
+ const historyPath = parentUuid
+ ? slicePathUntil(messageState.path, parentUuid)
+ : [];
+
+ const newUserMessage = await addMessage(
+ activeSessionId,
+ "self",
+ messageText,
+ chatKey,
+ parentUuid,
+ attachments,
+ );
+ messageStored = true;
+
+ void updateBranchSelectionState(
+ selectionKey,
+ newUserMessage.messageUuid,
+ );
+ appendMessageToState(newUserMessage);
+ updateSessionAfterMessage(newUserMessage);
+ setEditingMessage(null);
+ setPendingDocuments([]);
+ setPendingImages([]);
+
+ await startGeneration({
+ promptText,
+ parentMessage: newUserMessage,
+ historyPath,
+ sessionUuid: activeSessionId,
+ imagePaths: inferenceImagePaths,
+ mediaMarker: MEDIA_MARKER,
+ });
+ return;
+ }
+
+ const basePath = messageState.path;
+ const leaf = basePath[basePath.length - 1];
+ const parentUuid = leaf?.messageUuid;
const selectionKey = parentUuid ?? ROOT_SELECTION_KEY;
- const historyPath = parentUuid
- ? slicePathUntil(messageState.path, parentUuid)
- : [];
- const newUserMessage = await addMessage(
+ const userMessage = await addMessage(
activeSessionId,
"self",
messageText,
@@ -4441,62 +4543,30 @@ const Page: React.FC = () => {
void updateBranchSelectionState(
selectionKey,
- newUserMessage.messageUuid,
+ userMessage.messageUuid,
);
- appendMessageToState(newUserMessage);
- updateSessionAfterMessage(newUserMessage);
- setEditingMessage(null);
+ appendMessageToState(userMessage);
+ updateSessionAfterMessage(userMessage);
setPendingDocuments([]);
setPendingImages([]);
await startGeneration({
promptText,
- parentMessage: newUserMessage,
- historyPath,
+ parentMessage: userMessage,
+ historyPath: basePath,
sessionUuid: activeSessionId,
imagePaths: inferenceImagePaths,
mediaMarker: MEDIA_MARKER,
});
- return;
+ } catch (error) {
+ if (!messageStored) await cleanupUnstoredAttachments();
+ log.error("Failed to store chat message", error);
+ } finally {
+ await cleanupInferenceImages(inferenceImagePaths);
}
-
- const basePath = messageState.path;
- const leaf = basePath[basePath.length - 1];
- const parentUuid = leaf?.messageUuid;
- const selectionKey = parentUuid ?? ROOT_SELECTION_KEY;
-
- const userMessage = await addMessage(
- activeSessionId,
- "self",
- messageText,
- chatKey,
- parentUuid,
- attachments,
- );
- messageStored = true;
-
- void updateBranchSelectionState(
- selectionKey,
- userMessage.messageUuid,
- );
- appendMessageToState(userMessage);
- updateSessionAfterMessage(userMessage);
- setPendingDocuments([]);
- setPendingImages([]);
-
- await startGeneration({
- promptText,
- parentMessage: userMessage,
- historyPath: basePath,
- sessionUuid: activeSessionId,
- imagePaths: inferenceImagePaths,
- mediaMarker: MEDIA_MARKER,
- });
- } catch (error) {
- if (!messageStored) await cleanupUnstoredAttachments();
- log.error("Failed to store chat message", error);
} finally {
- await cleanupInferenceImages(inferenceImagePaths);
+ pendingSendRef.current = false;
+ setIsPreparingMessage(false);
}
};
@@ -4740,6 +4810,18 @@ const Page: React.FC = () => {
isGenerating={isGenerating}
handleSend={handleSend}
handleStopGeneration={handleStopGeneration}
+ showSourcePicker={isTauriRuntime}
+ openSources={openSources}
+ isPreparingMessage={isPreparingMessage}
+ sourcesDisabled={sourceSelectionDisabled}
+ sourcesLoading={isTauriRuntime && !sourcesReady}
+ sourcesStatus={
+ isTauriRuntime && !sourcesReady
+ ? knowledgeCatalogError || notesCollectionsError
+ ? "Couldn’t load sources. Open Sources to retry."
+ : "Loading sources for this chat…"
+ : undefined
+ }
showAttachmentPicker={isTauriRuntime}
openAttachmentMenu={openAttachmentMenu}
attachmentAnchor={attachmentAnchor}
@@ -4806,6 +4888,17 @@ 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}
diff --git a/web/apps/ensu/src/services/chat/source-selection.ts b/web/apps/ensu/src/services/chat/source-selection.ts
new file mode 100644
index 0000000000..dba6329821
--- /dev/null
+++ b/web/apps/ensu/src/services/chat/source-selection.ts
@@ -0,0 +1,109 @@
+/** 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.";
+
+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>();
+
+ 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;
+ 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;
+ } catch (error) {
+ this.onError(error);
+ return;
+ }
+ }
+
+ private save(id: string, selection: ChatSourceSelection) {
+ this.selections.set(id, selection);
+ if (id.startsWith("draft:")) return;
+ try {
+ this.storage?.setItem(
+ storagePrefix + id,
+ JSON.stringify(selection),
+ );
+ } 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],
+ });
+ }
+
+ 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] });
+ }
+
+ 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);
+ }
+
+ remove(id: string) {
+ id = this.destination(id);
+ this.deleted.add(id);
+ this.selections.delete(id);
+ try {
+ this.storage?.removeItem(storagePrefix + id);
+ } catch (error) {
+ this.onError(error);
+ }
+ }
+}
diff --git a/web/apps/ensu/src/services/knowledge.ts b/web/apps/ensu/src/services/knowledge.ts
index 8bf505c7df..de2b5a3606 100644
--- a/web/apps/ensu/src/services/knowledge.ts
+++ b/web/apps/ensu/src/services/knowledge.ts
@@ -1,8 +1,5 @@
import { tauriCommandError } from "@/services/tauri-error";
import { isTauriRuntime } from "@/services/tauri-runtime";
-import log from "ente-base/log";
-
-const ENABLED_PACKS_STORAGE_KEY = "ensu.desktop.enabledKnowledgePacks";
type KnowledgePackStatus = "download" | "ready" | "updateAvailable";
@@ -100,48 +97,18 @@ export const cancelKnowledgePackDownload = (stableId: string) =>
export const retrieveKnowledge = (
query: string,
enabledStableIds: string[],
+ enabledNoteCollectionIds: string[],
maxContextUtf8Bytes: number,
retrievalEpoch: number,
) =>
invokeKnowledge<KnowledgePromptContext | null>("knowledge_retrieve", {
query,
enabledStableIds,
+ enabledNoteCollectionIds,
maxContextUtf8Bytes,
retrievalEpoch,
});
-export const loadEnabledKnowledgePacks = () => {
- if (typeof window === "undefined" || !isTauriRuntime()) {
- return new Set<string>();
- }
- try {
- const raw = window.localStorage.getItem(ENABLED_PACKS_STORAGE_KEY);
- const parsed = raw ? (JSON.parse(raw) as unknown) : [];
- return new Set(
- Array.isArray(parsed)
- ? parsed.filter((value): value is string =>
- Boolean(typeof value === "string" && value),
- )
- : [],
- );
- } catch (error) {
- log.warn("Failed to load enabled Ensu Packs", error);
- return new Set<string>();
- }
-};
-
-export const saveEnabledKnowledgePacks = (stableIds: Set<string>) => {
- if (typeof window === "undefined") return;
- try {
- window.localStorage.setItem(
- ENABLED_PACKS_STORAGE_KEY,
- JSON.stringify([...stableIds].sort()),
- );
- } catch (error) {
- log.warn("Failed to save enabled Ensu Packs", error);
- }
-};
-
export const knowledgeErrorMessage = (error: unknown) => {
const { name } = tauriCommandError(error);
switch (name) {
diff --git a/web/apps/ensu/src/services/llm/conversation.ts b/web/apps/ensu/src/services/llm/conversation.ts
index 567ceb7c5a..132a4e4e0c 100644
--- a/web/apps/ensu/src/services/llm/conversation.ts
+++ b/web/apps/ensu/src/services/llm/conversation.ts
@@ -91,6 +91,7 @@ export const resolveDesktopSourceFollowup = (input: {
path: string[];
question: string;
enabledStableIds: string[];
+ enabledNoteCollectionIds: string[];
cancellationEpoch: number;
candidates?: unknown;
}): Promise<string> =>
diff --git a/web/apps/ensu/tests/source-selection.test.mjs b/web/apps/ensu/tests/source-selection.test.mjs
new file mode 100644
index 0000000000..2fd4934f45
--- /dev/null
+++ b/web/apps/ensu/tests/source-selection.test.mjs
@@ -0,0 +1,110 @@
+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/tsconfig.json b/web/apps/ensu/tsconfig.json
index 2ff1f734c6..79b5ce0b7e 100644
--- a/web/apps/ensu/tsconfig.json
+++ b/web/apps/ensu/tsconfig.json
@@ -3,12 +3,14 @@
"compilerOptions": {
"paths": { "@/*": ["./src/*"] },
"allowJs": true,
+ "allowImportingTsExtensions": true,
"checkJs": true,
"incremental": true,
"exactOptionalPropertyTypes": false
},
"include": [
"src",
+ "tests",
"next-env.d.ts",
"next.config.mjs",
"../../packages/base/global-electron.d.ts",